Semantic passport
@@ -5413,8 +5621,8 @@
- Route probe
- Choose a start node
+ Path
+ Click where the path starts
Find start
@@ -5422,8 +5630,8 @@
Clear
-
-
Pick two semantic nodes on the diagram
+
+ Click two nodes on the diagram
←
@@ -5434,7 +5642,7 @@
→
Overview
-
Choose the source, then the destination. Direction matters.
+
Click a start, then an end. Paths follow the arrows.
@@ -5466,8 +5674,9 @@
Click node Drag to pan
Semantic radar needs more MAP space.
+
Notes & index
- PATH
+ ROUTE
MAP
LENS
@@ -5478,41 +5687,67 @@
+
+
+
+
+
- • The browser sends questions and reviewer decisions over REST; the backend returns text, information, and widget descriptors over SSE.
- • One Pi RPC process drives each active session and delegates deterministic phase operations to tht / Harness.
+ Il backend avvia un processo Pi per sessione e invia /nuova-domanda o /riprendi-sessione
+ tht-gate.js guida le fasi F1–F8 e chiama il CLI tht per ogni passo deterministico
+ I gate reviewer arrivano al browser come ui_request via SSE; la risposta torna con POST /sessions/:id/response
- • Harness owns the eight-phase workflow and persists session_manifest.yaml, phase artifacts, and review_decisions.jsonl.
- • Backend owns the separate installation-local metadata catalog; the live frontend transcript is not persisted.
+ Lo stato è nei documenti di fase e nel ledger review_decisions.jsonl, non nella chat
+ La fase corrente si calcola ripiegando il ledger (phase.py), non viene salvata
+ Repository sessioni su filesystem oppure PostgreSQL, secondo la configurazione
+
+
+
+
+
+
+ Il backend gestisce il Metadata Catalog PostgreSQL
+ Le descrizioni AI campionano il DWH in sola lettura e usano un helper Python LiteLLM, senza Pi
- • Catalog DB, Qdrant, and Ollama stay inside Compose; workspace state is operator controlled and mounted into core.
- • The DWH and AI provider remain external endpoints; DWH access is constrained to introspection, tests, bounded samples, and read-only SQL.
+ Login OIDC o identità upstream dal portale (Omics embedded)
+ Qdrant ed Embedding sono servizi interni della rete Compose; DWH e LLM sono endpoint esterni
+
+
+ Node index
+
+
+
+
+
@@ -5550,12 +5785,47 @@
.replace(/\b\w/g, function (letter) { return letter.toUpperCase(); });
}
+ function readerLink(state) {
+ var template = document.documentElement.getAttribute('data-reading-link-template');
+ if (template === null) return location.href.replace(/#.*$/, '') + '#' + state;
+ if (!template || template.length > 4096 || template.split('{state}').length !== 2) return null;
+ try {
+ var url = new URL(template.replace('{state}', encodeURIComponent(state)));
+ if (['http:', 'https:', 'file:'].indexOf(url.protocol) === -1 || url.username || url.password) return null;
+ return url.href;
+ } catch (_) { return null; }
+ }
+
+ function copyReaderText(value) {
+ function fallbackCopy() {
+ var field = document.createElement('textarea');
+ field.value = value;
+ field.setAttribute('readonly', '');
+ field.style.position = 'fixed';
+ field.style.opacity = '0';
+ document.body.appendChild(field);
+ field.select();
+ var copied = false;
+ try { copied = document.execCommand('copy'); } catch (_) {}
+ field.remove();
+ return copied;
+ }
+ var policy = document.permissionsPolicy || document.featurePolicy;
+ var allowed = !policy || typeof policy.allowsFeature !== 'function' || policy.allowsFeature('clipboard-write');
+ if (allowed && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
+ try { return Promise.resolve(navigator.clipboard.writeText(value)).then(function () { return true; }).catch(fallbackCopy); }
+ catch (_) {}
+ }
+ return Promise.resolve(fallbackCopy());
+ }
+
function hasDrawableGeometry(element) {
- if (!element) return false;
+ if (!element || element.hasAttribute('data-ambient-flow-overlay')) return false;
var geometries = /^(path|line|polyline)$/i.test(element.tagName)
? [element]
: Array.prototype.slice.call(element.querySelectorAll('path, line, polyline'));
return geometries.some(function (geometry) {
+ if (geometry.hasAttribute('data-ambient-flow-overlay')) return false;
var source = geometry.tagName.toLowerCase() === 'path'
? geometry.getAttribute('d')
: geometry.tagName.toLowerCase() === 'polyline'
@@ -5770,8 +6040,8 @@
var MOTION_FPS = 30;
var SHARE_CARD_WIDTH = 1200;
var SHARE_CARD_HEIGHT = 630;
- var SHARE_CARD_PADDING = 36;
- var SHARE_CARD_HEADER = 112;
+ var SHARE_CARD_PADDING = 40;
+ var SHARE_CARD_HEADER = 124;
function exportError(key, values) {
var error = new Error(viewerText(key, values));
@@ -5799,6 +6069,182 @@
return getComputedStyle(document.body).backgroundColor || '#ffffff';
}
+ function cleanExportClone(clone) {
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-ambient-flow-overlay]'), function (el) {
+ el.remove();
+ });
+ // Route interaction rewrites CSS declarations through CSSOM. Normalize
+ // authored motion delays on the clone so exported bytes do not depend
+ // on whether the reader traced a route before downloading.
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-animate]'), function (el) {
+ var step = el.style.getPropertyValue('--step');
+ if (step) el.setAttribute('style', el.style.cssText);
+ });
+ // View transforms and neighborhood focus are HTML exploration state,
+ // never part of a downloaded full-diagram artifact.
+ clone.style.removeProperty('transform');
+ clone.style.removeProperty('clip-path');
+ clone.removeAttribute('data-view-scale');
+ clone.removeAttribute('data-focus-active');
+ clone.removeAttribute('data-reach-active');
+ clone.removeAttribute('data-lens-active');
+ clone.removeAttribute('data-lens-flow-count');
+ clone.removeAttribute('data-lens-flow-density');
+ clone.removeAttribute('data-legend-preview-active');
+ clone.removeAttribute('data-relationship-preview-active');
+ clone.removeAttribute('data-relationship-direct-active');
+ clone.removeAttribute('data-relationship-pin-active');
+ clone.removeAttribute('data-intent-trace-active');
+ clone.removeAttribute('data-route-picking');
+ clone.removeAttribute('data-route-active');
+ clone.removeAttribute('data-route-journey');
+ clone.removeAttribute('data-share-route');
+ clone.removeAttribute('data-share-reach');
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-reader-legend-corner]'), function (el) {
+ el.removeAttribute('data-reader-legend-corner');
+ el.style.removeProperty('--archify-reader-legend-transform');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-intent-trace-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-route-probe-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-route-journey-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-semantic-lens-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-bridge-runtime]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-kind]'), function (el) {
+ el.removeAttribute('data-legend-kind');
+ el.removeAttribute('data-legend-label');
+ el.removeAttribute('data-legend-count');
+ el.removeAttribute('data-legend-zero');
+ el.removeAttribute('data-legend-selected');
+ el.removeAttribute('role');
+ el.removeAttribute('tabindex');
+ el.removeAttribute('aria-label');
+ el.removeAttribute('aria-pressed');
+ el.removeAttribute('aria-haspopup');
+ el.removeAttribute('aria-controls');
+ el.removeAttribute('aria-expanded');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-bridge]'), function (el) {
+ el.removeAttribute('data-legend-bridge');
+ el.removeAttribute('role');
+ el.removeAttribute('aria-label');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-pulse-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-hit-overlay]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-source-evidence-beacon]'), function (el) {
+ el.remove();
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-source-evidence-count]'), function (el) {
+ var originalLabel = el.getAttribute('data-source-evidence-original-label');
+ if (originalLabel == null) el.removeAttribute('aria-label');
+ else el.setAttribute('aria-label', originalLabel);
+ el.removeAttribute('data-source-evidence-count');
+ el.removeAttribute('data-source-evidence-original-label');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-focus-match], [data-focus-selected]'), function (el) {
+ el.removeAttribute('data-focus-match');
+ el.removeAttribute('data-focus-selected');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-reach-match], [data-reach-origin], [data-reach-depth]'), function (el) {
+ el.removeAttribute('data-reach-match');
+ el.removeAttribute('data-reach-origin');
+ el.removeAttribute('data-reach-depth');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-lens-match], [data-lens-selected], [data-lens-peer]'), function (el) {
+ el.removeAttribute('data-lens-match');
+ el.removeAttribute('data-lens-selected');
+ el.removeAttribute('data-lens-peer');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-preview-match], [data-legend-preview-selected], [data-legend-preview-peer]'), function (el) {
+ el.removeAttribute('data-legend-preview-match');
+ el.removeAttribute('data-legend-preview-selected');
+ el.removeAttribute('data-legend-preview-peer');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-preview], [data-relationship-preview-node], [data-relationship-preview-source], [data-relationship-preview-target]'), function (el) {
+ el.removeAttribute('data-relationship-preview');
+ el.removeAttribute('data-relationship-preview-node');
+ el.removeAttribute('data-relationship-preview-source');
+ el.removeAttribute('data-relationship-preview-target');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-intent-trace-match], [data-intent-trace-selected]'), function (el) {
+ el.removeAttribute('data-intent-trace-match');
+ el.removeAttribute('data-intent-trace-selected');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-route-match], [data-route-start], [data-route-end], [data-route-step], [data-route-candidate], [data-route-journey-state], [data-route-journey-current]'), function (el) {
+ el.removeAttribute('data-route-match');
+ el.removeAttribute('data-route-start');
+ el.removeAttribute('data-route-end');
+ el.removeAttribute('data-route-step');
+ el.removeAttribute('data-route-candidate');
+ el.removeAttribute('data-route-journey-state');
+ el.removeAttribute('data-route-journey-current');
+ el.style.removeProperty('--route-step');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-share-route-match], [data-share-route-step], [data-share-route-start], [data-share-route-end], [data-share-route-middle]'), function (el) {
+ el.removeAttribute('data-share-route-match');
+ el.removeAttribute('data-share-route-step');
+ el.removeAttribute('data-share-route-start');
+ el.removeAttribute('data-share-route-end');
+ el.removeAttribute('data-share-route-middle');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-share-reach-match], [data-share-reach-origin], [data-share-reach-depth]'), function (el) {
+ el.removeAttribute('data-share-reach-match');
+ el.removeAttribute('data-share-reach-origin');
+ el.removeAttribute('data-share-reach-depth');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-detail], [data-detail-anchor]'), function (el) {
+ el.removeAttribute('data-detail');
+ el.removeAttribute('data-detail-anchor');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-node-id][aria-pressed]'), function (el) {
+ el.setAttribute('aria-pressed', 'false');
+ });
+ // A downloaded tree is always the complete hierarchy: collapsing is a
+ // reading aid, never a silent change to what the artifact contains.
+ clone.removeAttribute('data-tree-any-collapsed');
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-tree-hidden], [data-tree-collapsed]'), function (el) {
+ el.removeAttribute('data-tree-hidden');
+ el.removeAttribute('data-tree-collapsed');
+ });
+ Array.prototype.forEach.call(clone.querySelectorAll('[data-tree-toggle]'), function (el) {
+ el.setAttribute('aria-expanded', 'true');
+ el.setAttribute('aria-label', el.getAttribute('data-tree-label-collapse') || '');
+ });
+ return !clone.hasAttribute('data-view-scale') &&
+ !clone.hasAttribute('data-focus-active') &&
+ !clone.hasAttribute('data-reach-active') &&
+ !clone.hasAttribute('data-lens-active') &&
+ !clone.hasAttribute('data-lens-flow-count') &&
+ !clone.hasAttribute('data-lens-flow-density') &&
+ !clone.hasAttribute('data-legend-preview-active') &&
+ !clone.hasAttribute('data-relationship-preview-active') &&
+ !clone.hasAttribute('data-relationship-direct-active') &&
+ !clone.hasAttribute('data-intent-trace-active') &&
+ !clone.hasAttribute('data-route-picking') &&
+ !clone.hasAttribute('data-route-active') &&
+ !clone.hasAttribute('data-route-journey') &&
+ !clone.hasAttribute('data-share-route') &&
+ !clone.hasAttribute('data-share-reach') &&
+ !clone.hasAttribute('data-tree-any-collapsed') &&
+ !clone.style.getPropertyValue('transform') &&
+ !clone.style.getPropertyValue('clip-path') &&
+ clone.querySelectorAll('[data-ambient-flow-overlay], [data-reader-legend-corner], [data-focus-match], [data-focus-selected], [data-reach-match], [data-reach-origin], [data-reach-depth], [data-semantic-lens-overlay], [data-lens-match], [data-lens-selected], [data-lens-peer], [data-legend-bridge], [data-legend-kind], [data-legend-bridge-runtime], [data-legend-count], [data-legend-zero], [data-legend-selected], [data-legend-preview-match], [data-legend-preview-selected], [data-legend-preview-peer], [data-relationship-hit-overlay], [data-relationship-pulse-overlay], [data-relationship-preview], [data-relationship-preview-node], [data-relationship-preview-source], [data-relationship-preview-target], [data-intent-trace-overlay], [data-intent-trace-match], [data-intent-trace-selected], [data-route-probe-overlay], [data-route-journey-overlay], [data-route-match], [data-route-start], [data-route-end], [data-route-step], [data-route-candidate], [data-route-journey-state], [data-route-journey-current], [data-share-route-match], [data-share-route-step], [data-share-route-start], [data-share-route-end], [data-share-route-middle], [data-share-reach-match], [data-share-reach-origin], [data-share-reach-depth], [data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label], [data-detail], [data-detail-anchor], [data-tree-hidden], [data-tree-collapsed]').length === 0;
+ }
+
+
/**
* Serialize the main SVG into a standalone document.
*
@@ -5808,10 +6254,12 @@
* (PNG/JPEG/WebP/clipboard) because canvas rasterization needs
* deterministic colors; a raster cannot react to
* prefers-color-scheme after encoding.
- * - autoTheme=true — emits BOTH dark and light variable sets plus a
+ * - theme=auto — emits BOTH dark and light variable sets plus a
* `@media (prefers-color-scheme)` rule so the resulting SVG
* self-themes when embedded in GitHub READMEs or other hosts that
- * expose a color scheme. Used for "Download SVG".
+ * expose a color scheme. Used for the default "Download SVG".
+ * - theme=light|dark — locks the standalone SVG to the requested
+ * theme, independently of its source Viewer and host OS themes.
*/
function applyRouteSnapshot(clone, snapshot) {
if (!snapshot || !Array.isArray(snapshot.nodeIds) || !Array.isArray(snapshot.edges) ||
@@ -5976,194 +6424,19 @@
}
function serializeSvg(scale, opts) {
- // scale: integer multiplier for intrinsic SVG pixel dimensions used by
+ // scale: multiplier (integer unless the figure is oversized) for intrinsic SVG pixel dimensions used by
// the raster path. Defaults to 1 (natural size) for SVG download.
scale = scale || 1;
opts = opts || {};
- var autoTheme = opts.autoTheme === true;
+ var requestedTheme = opts.theme || (opts.autoTheme === true ? 'auto' : null);
+ if (requestedTheme && requestedTheme !== 'auto' && requestedTheme !== 'light' && requestedTheme !== 'dark') {
+ throw new Error('Unsupported SVG theme: ' + requestedTheme);
+ }
+ var autoTheme = requestedTheme === 'auto';
var svg = document.querySelector('.diagram-container svg');
var clone = svg.cloneNode(true);
- // View transforms and neighborhood focus are HTML exploration state,
- // never part of a downloaded full-diagram artifact.
- clone.style.removeProperty('transform');
- clone.style.removeProperty('clip-path');
- clone.removeAttribute('data-view-scale');
- clone.removeAttribute('data-focus-active');
- clone.removeAttribute('data-reach-active');
- clone.removeAttribute('data-lens-active');
- clone.removeAttribute('data-lens-flow-count');
- clone.removeAttribute('data-lens-flow-density');
- clone.removeAttribute('data-legend-preview-active');
- clone.removeAttribute('data-relationship-preview-active');
- clone.removeAttribute('data-relationship-direct-active');
- clone.removeAttribute('data-relationship-pin-active');
- clone.removeAttribute('data-intent-trace-active');
- clone.removeAttribute('data-route-picking');
- clone.removeAttribute('data-route-active');
- clone.removeAttribute('data-route-journey');
- clone.removeAttribute('data-share-route');
- clone.removeAttribute('data-share-reach');
- clone.removeAttribute('data-story-active');
- clone.removeAttribute('data-story-playing');
- clone.removeAttribute('data-story-beat');
- clone.removeAttribute('data-story-next');
- clone.removeAttribute('data-story-follow');
- clone.removeAttribute('data-chapter-handoff');
- clone.removeAttribute('data-chapter-anchor');
- clone.removeAttribute('data-chapter-preview');
- Array.prototype.forEach.call(clone.querySelectorAll('[data-chapter-handoff-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-chapter-role]'), function (el) {
- el.removeAttribute('data-chapter-role');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-chapter-preview-role]'), function (el) {
- el.removeAttribute('data-chapter-preview-role');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-story-overlay], [data-story-carrier-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-intent-trace-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-route-probe-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-route-journey-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-semantic-lens-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-bridge-runtime]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-kind]'), function (el) {
- el.removeAttribute('data-legend-kind');
- el.removeAttribute('data-legend-label');
- el.removeAttribute('data-legend-count');
- el.removeAttribute('data-legend-zero');
- el.removeAttribute('data-legend-selected');
- el.removeAttribute('role');
- el.removeAttribute('tabindex');
- el.removeAttribute('aria-label');
- el.removeAttribute('aria-pressed');
- el.removeAttribute('aria-haspopup');
- el.removeAttribute('aria-controls');
- el.removeAttribute('aria-expanded');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-bridge]'), function (el) {
- el.removeAttribute('data-legend-bridge');
- el.removeAttribute('role');
- el.removeAttribute('aria-label');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-pulse-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-hit-overlay]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-source-evidence-beacon]'), function (el) {
- el.remove();
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-source-evidence-count]'), function (el) {
- var originalLabel = el.getAttribute('data-source-evidence-original-label');
- if (originalLabel == null || originalLabel === '') el.removeAttribute('aria-label');
- else el.setAttribute('aria-label', originalLabel);
- el.removeAttribute('data-source-evidence-count');
- el.removeAttribute('data-source-evidence-original-label');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-story-step], [data-story-beat-state], [data-story-beat-step]'), function (el) {
- el.removeAttribute('data-story-step');
- el.removeAttribute('data-story-beat-state');
- el.removeAttribute('data-story-beat-step');
- el.style.removeProperty('--story-step');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-focus-match], [data-focus-selected]'), function (el) {
- el.removeAttribute('data-focus-match');
- el.removeAttribute('data-focus-selected');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-reach-match], [data-reach-origin], [data-reach-depth]'), function (el) {
- el.removeAttribute('data-reach-match');
- el.removeAttribute('data-reach-origin');
- el.removeAttribute('data-reach-depth');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-lens-match], [data-lens-selected], [data-lens-peer]'), function (el) {
- el.removeAttribute('data-lens-match');
- el.removeAttribute('data-lens-selected');
- el.removeAttribute('data-lens-peer');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-legend-preview-match], [data-legend-preview-selected], [data-legend-preview-peer]'), function (el) {
- el.removeAttribute('data-legend-preview-match');
- el.removeAttribute('data-legend-preview-selected');
- el.removeAttribute('data-legend-preview-peer');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-relationship-preview], [data-relationship-preview-node], [data-relationship-preview-source], [data-relationship-preview-target]'), function (el) {
- el.removeAttribute('data-relationship-preview');
- el.removeAttribute('data-relationship-preview-node');
- el.removeAttribute('data-relationship-preview-source');
- el.removeAttribute('data-relationship-preview-target');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-intent-trace-match], [data-intent-trace-selected]'), function (el) {
- el.removeAttribute('data-intent-trace-match');
- el.removeAttribute('data-intent-trace-selected');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-route-match], [data-route-start], [data-route-end], [data-route-step], [data-route-candidate], [data-route-journey-state], [data-route-journey-current]'), function (el) {
- el.removeAttribute('data-route-match');
- el.removeAttribute('data-route-start');
- el.removeAttribute('data-route-end');
- el.removeAttribute('data-route-step');
- el.removeAttribute('data-route-candidate');
- el.removeAttribute('data-route-journey-state');
- el.removeAttribute('data-route-journey-current');
- el.style.removeProperty('--route-step');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-share-route-match], [data-share-route-step], [data-share-route-start], [data-share-route-end], [data-share-route-middle]'), function (el) {
- el.removeAttribute('data-share-route-match');
- el.removeAttribute('data-share-route-step');
- el.removeAttribute('data-share-route-start');
- el.removeAttribute('data-share-route-end');
- el.removeAttribute('data-share-route-middle');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-share-reach-match], [data-share-reach-origin], [data-share-reach-depth]'), function (el) {
- el.removeAttribute('data-share-reach-match');
- el.removeAttribute('data-share-reach-origin');
- el.removeAttribute('data-share-reach-depth');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-detail], [data-detail-anchor]'), function (el) {
- el.removeAttribute('data-detail');
- el.removeAttribute('data-detail-anchor');
- });
- Array.prototype.forEach.call(clone.querySelectorAll('[data-node-id][aria-pressed]'), function (el) {
- el.setAttribute('aria-pressed', 'false');
- });
- var canonicalStateClean = !clone.hasAttribute('data-view-scale') &&
- !clone.hasAttribute('data-focus-active') &&
- !clone.hasAttribute('data-reach-active') &&
- !clone.hasAttribute('data-lens-active') &&
- !clone.hasAttribute('data-lens-flow-count') &&
- !clone.hasAttribute('data-lens-flow-density') &&
- !clone.hasAttribute('data-legend-preview-active') &&
- !clone.hasAttribute('data-relationship-preview-active') &&
- !clone.hasAttribute('data-relationship-direct-active') &&
- !clone.hasAttribute('data-intent-trace-active') &&
- !clone.hasAttribute('data-route-picking') &&
- !clone.hasAttribute('data-route-active') &&
- !clone.hasAttribute('data-route-journey') &&
- !clone.hasAttribute('data-share-route') &&
- !clone.hasAttribute('data-share-reach') &&
- !clone.hasAttribute('data-story-active') &&
- !clone.hasAttribute('data-story-playing') &&
- !clone.hasAttribute('data-story-beat') &&
- !clone.hasAttribute('data-story-next') &&
- !clone.hasAttribute('data-story-follow') &&
- !clone.hasAttribute('data-chapter-handoff') &&
- !clone.hasAttribute('data-chapter-anchor') &&
- !clone.hasAttribute('data-chapter-preview') &&
- !clone.style.getPropertyValue('transform') &&
- !clone.style.getPropertyValue('clip-path') &&
- clone.querySelectorAll('[data-story-overlay], [data-story-carrier-overlay], [data-story-carrier-token], [data-story-step], [data-story-beat-state], [data-story-beat-step], [data-chapter-handoff-overlay], [data-chapter-role], [data-chapter-preview-role], [data-focus-match], [data-focus-selected], [data-reach-match], [data-reach-origin], [data-reach-depth], [data-semantic-lens-overlay], [data-lens-match], [data-lens-selected], [data-lens-peer], [data-legend-bridge], [data-legend-kind], [data-legend-bridge-runtime], [data-legend-count], [data-legend-zero], [data-legend-selected], [data-legend-preview-match], [data-legend-preview-selected], [data-legend-preview-peer], [data-relationship-hit-overlay], [data-relationship-pulse-overlay], [data-relationship-preview], [data-relationship-preview-node], [data-relationship-preview-source], [data-relationship-preview-target], [data-intent-trace-overlay], [data-intent-trace-match], [data-intent-trace-selected], [data-route-probe-overlay], [data-route-journey-overlay], [data-route-match], [data-route-start], [data-route-end], [data-route-step], [data-route-candidate], [data-route-journey-state], [data-route-journey-current], [data-share-route-match], [data-share-route-step], [data-share-route-start], [data-share-route-end], [data-share-route-middle], [data-share-reach-match], [data-share-reach-origin], [data-share-reach-depth], [data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label], [data-detail], [data-detail-anchor]').length === 0;
+ var canonicalStateClean = cleanExportClone(clone);
var vb = svg.viewBox.baseVal;
var finiteSvgDimensions = Number.isFinite(vb.x) && Number.isFinite(vb.y) &&
@@ -6180,6 +6453,10 @@
// canvas upscaling.
clone.setAttribute('width', vb.width * scale);
clone.setAttribute('height', vb.height * scale);
+ // Keep copied Viewer layout rules from overriding the export's size.
+ clone.style.width = vb.width * scale + 'px';
+ clone.style.height = vb.height * scale + 'px';
+ clone.style.minWidth = '0';
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
// Only the SVG-relevant rules: semantic classes, markers, and the
@@ -6200,6 +6477,17 @@
var sel = rule.selectorText || '';
if (/(^|,)\s*(svg|:root|\[data-theme|\[data-preset|\.c-|\.t-|\.a-|\.m-)/.test(sel)) {
out.push(rule.cssText);
+ } else if (opts.figure && sel.indexOf('.diagram-container > svg') !== -1) {
+ // Figures look like the Viewer canvas: keep its preset/theme paint
+ // (quiet grid, lifted nodes) by rescoping matching rules to svg.
+ var scoped = sel.split(',').map(function (part) {
+ var at = part.indexOf('.diagram-container > svg');
+ if (at === -1) return null;
+ var prefix = part.slice(0, at).trim();
+ try { if (prefix && !document.documentElement.matches(prefix)) return null; } catch (_) { return null; }
+ return 'svg' + part.slice(at + '.diagram-container > svg'.length);
+ }).filter(Boolean);
+ if (scoped.length) out.push(scoped.join(', ') + ' { ' + rule.style.cssText + ' }');
}
});
});
@@ -6228,46 +6516,46 @@
document.body.appendChild(probe);
try {
var c = getComputedStyle(probe);
- return varNames.map(function (n) {
- return n + ': ' + c.getPropertyValue(n).trim() + ';';
- }).join(' ');
+ return {
+ background: c.getPropertyValue('--bg').trim(),
+ vars: varNames.map(function (n) {
+ return n + ': ' + c.getPropertyValue(n).trim() + ';';
+ }).join(' ')
+ };
} finally {
document.body.removeChild(probe);
}
}
- // Prepend a local()-only @font-face block for each weight so that the
- // sandboxed image-rendering context used during PNG/JPEG/WebP export
- // can find JetBrains Mono if the user has it installed locally, and
- // falls through cleanly to the monospace stack otherwise. The usual
- // Google-Fonts
in the host document is unreachable from the
- // serialized SVG, so url()-sourced faces would just hang.
- var fontFallback = [400, 500, 600, 700].map(function (w) {
- return "@font-face { font-family: 'JetBrains Mono'; font-weight: " + w +
- "; src: local('JetBrains Mono'), local('JetBrainsMono-Regular'); }";
- }).join('\n');
+ // Keep the same font bytes, character coverage, and attribution in
+ // standalone SVGs and the SVG images used by every raster export.
+ var fontCss = document.getElementById('archify-fonts').textContent;
var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');
var bgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
- bgRect.setAttribute('width', '100%');
- bgRect.setAttribute('height', '100%');
+ // Cover the real viewBox: auto-cropped canvases start below y=0, and a
+ // 100% rect anchored at the origin left an unpainted band at the bottom.
+ bgRect.setAttribute('x', vb.x);
+ bgRect.setAttribute('y', vb.y);
+ bgRect.setAttribute('width', vb.width);
+ bgRect.setAttribute('height', vb.height);
if (autoTheme) {
// Dual-theme SVG. Dark is the default (so hosts without
// prefers-color-scheme still render), light swaps in via media
// query, and svg[data-theme="..."] still lets downstream
// consumers force a specific theme.
- var darkVars = resolveVars('dark');
- var lightVars = resolveVars('light');
+ var darkTheme = resolveVars('dark');
+ var lightTheme = resolveVars('light');
style.textContent =
- fontFallback + "\n" +
+ fontCss + "\n" +
"svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" +
hostStyle + "\n" +
- ":root, svg { " + darkVars + " }\n" +
- "@media (prefers-color-scheme: light) { :root, svg { " + lightVars + " } }\n" +
- "svg[data-theme=\"light\"] { " + lightVars + " }\n" +
- "svg[data-theme=\"dark\"] { " + darkVars + " }\n" +
+ ":root, svg { " + darkTheme.vars + " }\n" +
+ "@media (prefers-color-scheme: light) { :root, svg { " + lightTheme.vars + " } }\n" +
+ "svg[data-theme=\"light\"] { " + lightTheme.vars + " }\n" +
+ "svg[data-theme=\"dark\"] { " + darkTheme.vars + " }\n" +
"rect.c-bg-rect { fill: var(--bg); }\n";
// Don't lock the serialized SVG to the viewer's current theme.
@@ -6276,11 +6564,12 @@
// swaps with the media query.
bgRect.setAttribute('class', 'c-bg-rect');
} else {
- // Raster path: lock to the viewer's current theme.
- var theme = document.documentElement.getAttribute('data-theme') || 'dark';
- var themeHost = document.querySelector('[data-theme="' + theme + '"]') || document.documentElement;
- var computed = getComputedStyle(themeHost);
- var vars = varNames.map(function (n) {
+ // Raster exports keep the viewer's current theme. Explicit SVG
+ // exports instead select their own stable light/dark source.
+ var lockedTheme = requestedTheme || document.documentElement.getAttribute('data-theme') || 'dark';
+ var resolvedTheme = requestedTheme && resolveVars(lockedTheme);
+ var computed = getComputedStyle(document.documentElement);
+ var vars = resolvedTheme ? resolvedTheme.vars : varNames.map(function (n) {
return n + ': ' + computed.getPropertyValue(n).trim() + ';';
}).join(' ');
@@ -6289,35 +6578,42 @@
// overrides our chosen theme via later-in-cascade equal-specificity.
// Keep this order.
style.textContent =
- fontFallback + "\n" +
+ fontCss + "\n" +
"svg { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, 'DejaVu Sans Mono', 'Liberation Mono', 'Noto Sans Mono CJK SC', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', monospace; }\n" +
hostStyle + "\n" +
":root, svg { " + vars + " }\n";
- bgRect.setAttribute('fill', computed.getPropertyValue('--bg').trim() || '#ffffff');
+ if (requestedTheme) clone.setAttribute('data-theme', lockedTheme);
+ bgRect.setAttribute('fill', (resolvedTheme ? resolvedTheme.background : computed.getPropertyValue('--bg').trim()) || '#ffffff');
}
if (opts.routeSnapshot) {
- style.textContent += "\nsvg[data-share-route] [data-node-id], svg[data-share-route] [data-edge-from] { opacity: 0.18; }\n" +
- "svg[data-share-route] [data-share-route-match] { opacity: 1; }\n" +
+ style.textContent += "\nsvg[data-share-route] [data-node-id], svg[data-share-route] [data-edge-from], svg[data-share-route] [data-graph-role=\"automatic-crossover-underlay\"] { opacity: 0.18; }\n" +
+ "svg[data-share-route] [data-share-route-match], svg[data-share-route] [data-graph-role=\"automatic-crossover\"]:has(> [data-share-route-match]) > [data-graph-role=\"automatic-crossover-underlay\"] { opacity: 1; }\n" +
"svg[data-share-route] [data-share-route-start] > :is(rect, circle, polygon):not(.c-mask) { stroke-width: 3; stroke-dasharray: 5 3; }\n" +
"svg[data-share-route] [data-share-route-middle] > :is(rect, circle, polygon):not(.c-mask) { stroke-width: 2.2; }\n" +
"svg[data-share-route] [data-share-route-end] > :is(rect, circle, polygon):not(.c-mask) { stroke-width: 3.4; stroke-dasharray: 1 0; }\n";
}
if (opts.reachSnapshot) {
- style.textContent += "\nsvg[data-share-reach] [data-node-id], svg[data-share-reach] [data-edge-from] { opacity: 0.14; }\n" +
- "svg[data-share-reach] [data-share-reach-match] { opacity: 1; }\n" +
+ style.textContent += "\nsvg[data-share-reach] [data-node-id], svg[data-share-reach] [data-edge-from], svg[data-share-reach] [data-graph-role=\"automatic-crossover-underlay\"] { opacity: 0.14; }\n" +
+ "svg[data-share-reach] [data-share-reach-match], svg[data-share-reach] [data-graph-role=\"automatic-crossover\"]:has(> [data-share-reach-match]) > [data-graph-role=\"automatic-crossover-underlay\"] { opacity: 1; }\n" +
"svg[data-share-reach] [data-edge-from][data-share-reach-match] { stroke-width: 1.55; }\n" +
"svg[data-share-reach=\"upstream\"] [data-share-reach-origin] > :is(rect, circle, polygon):not(.c-mask) { stroke: var(--database-stroke); stroke-width: 3.4; stroke-dasharray: 5 3; }\n" +
"svg[data-share-reach=\"downstream\"] [data-share-reach-origin] > :is(rect, circle, polygon):not(.c-mask) { stroke: var(--backend-stroke); stroke-width: 3.4; stroke-dasharray: 1 0; }\n" +
"svg[data-preset=\"blueprint\"][data-share-reach] [data-share-reach-origin], svg[data-preset=\"blueprint\"][data-share-reach] [data-edge-from][data-share-reach-match] { filter: none; }\n";
}
+ // Figures draw the diagram on a painted canvas card, like the Viewer.
+ if (opts.figure) bgRect.setAttribute('fill', 'none');
+
clone.insertBefore(style, clone.firstChild);
clone.insertBefore(bgRect, style.nextSibling);
+ // The XML declaration pins UTF-8: without it, consumers that guess an
+ // encoding instead of defaulting to UTF-8 mangle non-ASCII text.
return {
- svgString: new XMLSerializer().serializeToString(clone),
+ svgString: '\n' +
+ new XMLSerializer().serializeToString(clone),
width: vb.width * scale,
height: vb.height * scale,
canonicalStateClean: canonicalStateClean,
@@ -6331,7 +6627,9 @@
var a = document.createElement('a');
a.href = url;
a.download = filename;
- document.body.appendChild(a);
+ // Keep the export-owned activation inside its existing control boundary.
+ // The synthetic download click must not dismiss the reader selection.
+ menu.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
@@ -6341,14 +6639,114 @@
// silently produces a blank canvas above ~16 Mpx; Chrome / Firefox /
// desktop Safari are far higher but start failing on memory-constrained
// devices. We pick the largest integer scale in {4,3,2,1} whose target
- // pixel count fits under this cap.
+ // pixel count fits under this cap; a figure too large even at 1x is
+ // downscaled to fit rather than allocating an oversized canvas.
var MAX_CANVAS_PIXELS = 16 * 1024 * 1024;
function pickSafeScale(vbW, vbH) {
for (var s = RASTER_SCALE; s >= 1; s--) {
if (vbW * s * vbH * s <= MAX_CANVAS_PIXELS) return s;
}
- return 1;
+ return Math.sqrt(MAX_CANVAS_PIXELS / (vbW * vbH)) * 0.999;
+ }
+
+ // Raster exports reproduce the Viewer page without its controls: the
+ // title row with its accent dot, then the diagram on the same rounded
+ // canvas card (fill, hairline, shadow, dot field). CSS pixels.
+ var FIGURE_MARGIN = 28;
+ var FIGURE_CARD_PADDING = 24;
+ var FIGURE_TITLE_SIZE = 24;
+ var FIGURE_SUBTITLE_SIZE = 14;
+
+ function figureLayout(vb) {
+ var titleNode = document.querySelector('.header h1');
+ var subtitleNode = document.querySelector('.header .subtitle');
+ var container = document.querySelector('.diagram-container');
+ var root = getComputedStyle(document.documentElement);
+ var card = container ? getComputedStyle(container) : null;
+ var title = titleNode ? titleNode.textContent.trim() : '';
+ var subtitle = subtitleNode ? subtitleNode.textContent.trim() : '';
+ var header = title ? 32 + (subtitle ? 24 : 0) + 18 : 0;
+ var cardWidth = vb.width + FIGURE_CARD_PADDING * 2;
+ var cardHeight = vb.height + FIGURE_CARD_PADDING * 2;
+ var cardFill = card && card.backgroundColor && !/rgba\(0, 0, 0, 0\)|transparent/.test(card.backgroundColor)
+ ? card.backgroundColor : (root.getPropertyValue('--panel').trim() || 'transparent');
+ return {
+ title: title,
+ subtitle: subtitle,
+ family: titleNode ? getComputedStyle(titleNode).fontFamily : 'sans-serif',
+ text: root.getPropertyValue('--text').trim() || '#111827',
+ muted: root.getPropertyValue('--text-muted').trim() || '#64748b',
+ accent: root.getPropertyValue('--frontend-stroke').trim() || '#0891b2',
+ bg: root.getPropertyValue('--bg').trim() || currentBg(),
+ cardFill: cardFill,
+ cardBorder: root.getPropertyValue('--panel-border').trim() || 'transparent',
+ dot: card && /radial-gradient/.test(card.backgroundImage) ? (root.getPropertyValue('--canvas-dot').trim() || '') : '',
+ light: (document.documentElement.getAttribute('data-theme') || 'dark') === 'light',
+ header: header,
+ cardWidth: cardWidth,
+ cardHeight: cardHeight,
+ width: cardWidth + FIGURE_MARGIN * 2,
+ height: cardHeight + FIGURE_MARGIN * 2 + header
+ };
+ }
+
+ function paintFigure(ctx, layout) {
+ var m = FIGURE_MARGIN;
+ ctx.fillStyle = layout.bg;
+ ctx.fillRect(0, 0, layout.width, layout.height);
+ if (layout.title) {
+ var titleMid = m + 16;
+ ctx.fillStyle = layout.accent;
+ ctx.globalAlpha = 0.16;
+ ctx.beginPath(); ctx.arc(m + 5, titleMid, 9, 0, Math.PI * 2); ctx.fill();
+ ctx.globalAlpha = 1;
+ ctx.beginPath(); ctx.arc(m + 5, titleMid, 5, 0, Math.PI * 2); ctx.fill();
+ ctx.textBaseline = 'middle';
+ ctx.fillStyle = layout.text;
+ ctx.fillText(fitCanvasText(ctx, layout.title, layout.width - m * 2 - 22, FIGURE_TITLE_SIZE, 14, '650', layout.family), m + 22, titleMid + 1);
+ if (layout.subtitle) {
+ ctx.fillStyle = layout.muted;
+ ctx.fillText(fitCanvasText(ctx, layout.subtitle, layout.width - m * 2, FIGURE_SUBTITLE_SIZE, 11, '400', layout.family), m, titleMid + 30);
+ }
+ ctx.textBaseline = 'alphabetic';
+ }
+ var x = m, y = m + layout.header, w = layout.cardWidth, h = layout.cardHeight, r = 16;
+ function cardPath() {
+ ctx.beginPath();
+ if (typeof ctx.roundRect === 'function') ctx.roundRect(x, y, w, h, r);
+ else ctx.rect(x, y, w, h);
+ }
+ ctx.save();
+ if (layout.light) {
+ ctx.shadowColor = 'rgba(15, 23, 42, 0.08)';
+ ctx.shadowBlur = 28;
+ ctx.shadowOffsetY = 10;
+ }
+ cardPath();
+ ctx.fillStyle = layout.bg;
+ ctx.fill();
+ ctx.restore();
+ cardPath();
+ ctx.fillStyle = layout.cardFill;
+ ctx.fill();
+ if (layout.dot) {
+ ctx.save();
+ cardPath();
+ ctx.clip();
+ ctx.fillStyle = layout.dot;
+ for (var dy = y + 1; dy < y + h; dy += 20) {
+ for (var dx = x + 1; dx < x + w; dx += 20) {
+ ctx.beginPath(); ctx.arc(dx, dy, 1, 0, Math.PI * 2); ctx.fill();
+ }
+ }
+ ctx.restore();
+ }
+ cardPath();
+ ctx.strokeStyle = layout.cardBorder;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ return { x: x + FIGURE_CARD_PADDING, y: y + FIGURE_CARD_PADDING };
}
function rasterize(format) {
@@ -6358,8 +6756,9 @@
// size — no upsampling blur.
var svg = document.querySelector('.diagram-container svg');
var vb = svg.viewBox.baseVal;
- var scale = pickSafeScale(vb.width, vb.height);
- var data = serializeSvg(scale);
+ var layout = figureLayout(vb);
+ var scale = pickSafeScale(layout.width, layout.height);
+ var data = serializeSvg(scale, { figure: true });
var svgBlob = new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' });
var svgUrl = URL.createObjectURL(svgBlob);
@@ -6368,15 +6767,15 @@
img.onload = function () {
try {
var canvas = document.createElement('canvas');
- canvas.width = data.width;
- canvas.height = data.height;
+ canvas.width = Math.round(layout.width * scale);
+ canvas.height = Math.round(layout.height * scale);
var ctx = canvas2dOrThrow(canvas, format);
- if (format === 'jpeg') {
- ctx.fillStyle = currentBg();
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- }
- // Draw at natural size — SVG was already rasterized at target res.
- ctx.drawImage(img, 0, 0);
+ // Paint in CSS pixels; the SVG image is already rendered at scale,
+ // so drawing it at CSS size under this transform stays 1:1.
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
+ var origin = paintFigure(ctx, layout);
+ ctx.drawImage(img, origin.x, origin.y, vb.width, vb.height);
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
URL.revokeObjectURL(svgUrl);
var mime = format === 'jpeg' ? 'image/jpeg' :
format === 'webp' ? 'image/webp' : 'image/png';
@@ -6398,10 +6797,10 @@
});
}
- function fitCanvasText(ctx, text, maxWidth, startSize, minSize, weight) {
+ function fitCanvasText(ctx, text, maxWidth, startSize, minSize, weight, fontFamily) {
var value = String(text || '').trim();
var size = startSize;
- var family = "'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
+ var family = fontFamily || "'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
while (size > minSize) {
ctx.font = (weight || '600') + ' ' + size + 'px ' + family;
if (ctx.measureText(value).width <= maxWidth) return value;
@@ -6427,14 +6826,13 @@
}
function renderShareCard(options) {
- options = options || {};
var routeSnapshot = options.routeSnapshot || null;
var reachSnapshot = options.reachSnapshot || null;
if (routeSnapshot && reachSnapshot) return Promise.reject(exportError('viewer.export.error.variantsCombined'));
var svg = document.querySelector('.diagram-container svg');
var vb = svg.viewBox.baseVal;
var sourceScale = Math.min(2, pickSafeScale(vb.width, vb.height));
- var data = serializeSvg(sourceScale, { routeSnapshot: routeSnapshot, reachSnapshot: reachSnapshot });
+ var data = serializeSvg(sourceScale, { routeSnapshot: routeSnapshot, reachSnapshot: reachSnapshot, figure: true });
if (!data.canonicalStateClean) return Promise.reject(exportError('viewer.export.error.viewerState'));
if (routeSnapshot && !data.routeStateClean) return Promise.reject(exportError('viewer.export.error.routeState'));
if (reachSnapshot && !data.reachStateClean) return Promise.reject(exportError('viewer.export.error.reachState'));
@@ -6459,7 +6857,6 @@
: '--frontend-stroke';
var accent = computed.getPropertyValue(accentProperty).trim() || '#22d3ee';
var titleNode = document.querySelector('.header h1');
- var subtitleNode = document.querySelector('.header .subtitle');
var title = titleNode ? titleNode.textContent : document.title;
var directionLabel = reachSnapshot
? viewerText('viewer.export.direction.' + reachSnapshot.direction)
@@ -6469,62 +6866,65 @@
source: routeSnapshot.source.label,
target: routeSnapshot.target.label
})
- : reachSnapshot
- ? viewerText('viewer.export.card.reachSummary', {
- direction: directionLabel,
- origin: reachSnapshot.origin.label,
- nodes: viewerCount('viewer.export.card.node', reachSnapshot.nodeIds.length - 1),
- links: viewerCount('viewer.export.card.link', reachSnapshot.edges.length),
- hops: viewerCount('viewer.export.card.hop', reachSnapshot.maxDepth)
- })
- : subtitleNode ? subtitleNode.textContent : '';
- var preset = document.documentElement.getAttribute('data-preset') || 'classic';
- var theme = document.documentElement.getAttribute('data-theme') || 'dark';
- var presetKey = preset === 'signal-flow'
- ? 'viewer.preset.flow.short'
- : 'viewer.preset.' + preset;
- var presetLabel = viewerText(presetKey).toUpperCase();
- var themeLabel = viewerText('viewer.theme.' + theme).toUpperCase();
+ : viewerText('viewer.export.card.reachSummary', {
+ direction: directionLabel,
+ origin: reachSnapshot.origin.label,
+ nodes: viewerCount('viewer.export.card.node', reachSnapshot.nodeIds.length - 1),
+ links: viewerCount('viewer.export.card.link', reachSnapshot.edges.length),
+ hops: viewerCount('viewer.export.card.hop', reachSnapshot.maxDepth)
+ });
var cardLabel = routeSnapshot
? viewerText('viewer.export.card.routeBadge', {
hops: viewerCount('viewer.export.card.hop', routeSnapshot.hops).toUpperCase()
})
- : reachSnapshot
- ? viewerText('viewer.export.card.reachBadge', { direction: directionLabel.toUpperCase() })
- : viewerText('viewer.export.card.defaultBadge', { preset: presetLabel, theme: themeLabel });
+ : viewerText('viewer.export.card.reachBadge', { direction: directionLabel.toUpperCase() });
+
+ var family = titleNode ? getComputedStyle(titleNode).fontFamily : 'sans-serif';
+ var panelFill = bg;
ctx.fillStyle = bg;
ctx.fillRect(0, 0, SHARE_CARD_WIDTH, SHARE_CARD_HEIGHT);
+ // Header: a short accent rule and badge over the title and summary.
ctx.fillStyle = accent;
- ctx.fillRect(SHARE_CARD_PADDING, 27, 42, 3);
-
+ ctx.fillRect(SHARE_CARD_PADDING, 34, 28, 3);
ctx.textBaseline = 'alphabetic';
- ctx.fillStyle = text;
- var fittedTitle = fitCanvasText(ctx, title, SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2 - 330, 29, 18, '700');
- ctx.fillText(fittedTitle, SHARE_CARD_PADDING, 62);
-
- ctx.fillStyle = muted;
- var fittedSubtitle = fitCanvasText(ctx, subtitle, SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2 - 280, 13, 11, '500');
- ctx.fillText(fittedSubtitle, SHARE_CARD_PADDING, 87);
-
- ctx.font = "600 12px 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
+ ctx.font = '600 12px ' + family;
ctx.textAlign = 'right';
- ctx.fillStyle = accent;
- ctx.fillText(cardLabel, SHARE_CARD_WIDTH - SHARE_CARD_PADDING, 50);
+ ctx.fillStyle = muted;
+ ctx.fillText(cardLabel, SHARE_CARD_WIDTH - SHARE_CARD_PADDING, 40);
ctx.textAlign = 'left';
- var availableWidth = SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2;
- var availableHeight = SHARE_CARD_HEIGHT - SHARE_CARD_HEADER - SHARE_CARD_PADDING;
+ ctx.fillStyle = text;
+ var fittedTitle = fitCanvasText(ctx, title, SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2 - 260, 30, 18, '650', family);
+ ctx.fillText(fittedTitle, SHARE_CARD_PADDING, 74);
+
+ ctx.fillStyle = muted;
+ var fittedSubtitle = fitCanvasText(ctx, subtitle, SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2, 15, 12, '400', family);
+ ctx.fillText(fittedSubtitle, SHARE_CARD_PADDING, 99);
+
+ // The diagram sits on one soft rounded panel with an even inset.
+ var panelX = SHARE_CARD_PADDING;
+ var panelY = SHARE_CARD_HEADER;
+ var panelWidth = SHARE_CARD_WIDTH - SHARE_CARD_PADDING * 2;
+ var panelHeight = SHARE_CARD_HEIGHT - SHARE_CARD_HEADER - SHARE_CARD_PADDING;
+ var inset = 18;
+ ctx.beginPath();
+ if (typeof ctx.roundRect === 'function') ctx.roundRect(panelX, panelY, panelWidth, panelHeight, 14);
+ else ctx.rect(panelX, panelY, panelWidth, panelHeight);
+ ctx.fillStyle = panelFill;
+ ctx.fill();
+ ctx.strokeStyle = border;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+
+ var availableWidth = panelWidth - inset * 2;
+ var availableHeight = panelHeight - inset * 2;
var fit = Math.min(availableWidth / data.width, availableHeight / data.height);
var drawWidth = data.width * fit;
var drawHeight = data.height * fit;
- var drawX = SHARE_CARD_PADDING + (availableWidth - drawWidth) / 2;
- var drawY = SHARE_CARD_HEADER + (availableHeight - drawHeight) / 2;
-
- ctx.strokeStyle = border;
- ctx.lineWidth = 1;
- ctx.strokeRect(drawX - 0.5, drawY - 0.5, drawWidth + 1, drawHeight + 1);
+ var drawX = panelX + inset + (availableWidth - drawWidth) / 2;
+ var drawY = panelY + inset + (availableHeight - drawHeight) / 2;
ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
URL.revokeObjectURL(svgUrl);
@@ -6547,7 +6947,6 @@
function rasterizeShareCard(options) {
options = options || {};
- if (!options.variant) return renderShareCard();
if (options.variant !== 'route' && options.variant !== 'reach') {
return Promise.reject(exportError('viewer.export.unknownVariant', { variant: options.variant }));
}
@@ -6601,7 +7000,6 @@
var vb = svg.viewBox.baseVal;
var scale = Math.min(1, 1280 / vb.width);
var data = serializeSvg(scale);
- var sourceUrl = URL.createObjectURL(new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' }));
function createMotionScene(root) {
var rootMatrix = root.getCTM ? root.getCTM() : null;
@@ -6620,13 +7018,18 @@
function samplesFor(element) {
if (typeof element.getTotalLength !== 'function' || typeof element.getPointAtLength !== 'function') return [];
+ var geometry = element;
+ if (element.getAttribute('data-motion-path')) {
+ geometry = element.cloneNode(false);
+ geometry.setAttribute('d', element.getAttribute('data-motion-path'));
+ }
var length;
- try { length = element.getTotalLength(); } catch (_) { return []; }
+ try { length = geometry.getTotalLength(); } catch (_) { return []; }
if (!Number.isFinite(length) || length <= 0) return [];
var count = Math.max(12, Math.min(72, Math.ceil(length / 12)));
var points = [];
for (var i = 0; i <= count; i++) {
- points.push(pointInRoot(element, element.getPointAtLength(length * i / count)));
+ points.push(pointInRoot(element, geometry.getPointAtLength(length * i / count)));
}
return points;
}
@@ -6753,73 +7156,99 @@
var motionScene = createMotionScene(svg);
return new Promise(function (resolve, reject) {
- var backgroundImage = new Image();
- backgroundImage.onload = function () {
- var canvas = document.createElement('canvas');
- canvas.width = Math.max(2, Math.round(data.width / 2) * 2);
- canvas.height = Math.max(2, Math.round(data.height / 2) * 2);
- var ctx = canvas.getContext('2d');
- var stream = canvas.captureStream(fps);
- var mime = motionMimeType();
- var recorder;
- try {
- recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 6000000 });
- } catch (err) {
- URL.revokeObjectURL(sourceUrl);
- stream.getTracks().forEach(function (track) { track.stop(); });
- reject(err);
- return;
+ var sourceUrl = null;
+ var backgroundImage = null;
+ var stream = null;
+ var recorder = null;
+ var raf = 0;
+ var durationTimer = 0;
+ var flushTimer = 0;
+ var settled = false;
+
+ function finish(error, blob) {
+ if (settled) return;
+ // 先锁定终态:停止录制和释放流可能产生晚到的编码事件。
+ settled = true;
+ cancelAnimationFrame(raf);
+ clearTimeout(durationTimer);
+ clearTimeout(flushTimer);
+ if (backgroundImage) {
+ backgroundImage.onload = null;
+ backgroundImage.onerror = null;
}
- var chunks = [];
- var raf = 0;
- var stopped = false;
- var startedAt = performance.now();
- function cleanup() {
- if (stopped) return;
- stopped = true;
- cancelAnimationFrame(raf);
- URL.revokeObjectURL(sourceUrl);
- stream.getTracks().forEach(function (track) { track.stop(); });
+ if (recorder) {
+ recorder.ondataavailable = null;
+ recorder.onerror = null;
+ recorder.onstop = null;
+ try { if (recorder.state !== 'inactive') recorder.stop(); } catch (_) {}
}
- function draw(now) {
- var elapsed = Math.max(0, ((Number(now) || performance.now()) - startedAt) / 1000);
- drawMotionFrame(ctx, backgroundImage, motionScene, elapsed);
- raf = requestAnimationFrame(draw);
- }
- recorder.ondataavailable = function (event) {
- if (event.data && event.data.size) chunks.push(event.data);
+ if (stream) stream.getTracks().forEach(function (track) { track.stop(); });
+ if (sourceUrl) URL.revokeObjectURL(sourceUrl);
+ if (blob) resolve(blob);
+ else reject(error);
+ }
+
+ try {
+ sourceUrl = URL.createObjectURL(new Blob([data.svgString], { type: 'image/svg+xml;charset=utf-8' }));
+ backgroundImage = new Image();
+ backgroundImage.onload = function () {
+ if (settled) return;
+ try {
+ var canvas = document.createElement('canvas');
+ canvas.width = Math.max(2, Math.round(data.width / 2) * 2);
+ canvas.height = Math.max(2, Math.round(data.height / 2) * 2);
+ var ctx = canvas.getContext('2d');
+ if (!ctx) throw exportError('viewer.export.error.contextUnavailable', { label: 'WebM' });
+ stream = canvas.captureStream(fps);
+ var mime = motionMimeType();
+ recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 6000000 });
+ var chunks = [];
+ var startedAt = performance.now();
+ function draw(now) {
+ if (settled) return;
+ try {
+ var elapsed = Math.max(0, ((Number(now) || performance.now()) - startedAt) / 1000);
+ drawMotionFrame(ctx, backgroundImage, motionScene, elapsed);
+ raf = requestAnimationFrame(draw);
+ } catch (error) { finish(error); }
+ }
+ recorder.ondataavailable = function (event) {
+ if (!settled && event.data && event.data.size) chunks.push(event.data);
+ };
+ recorder.onerror = function (event) {
+ finish(event.error || exportError('viewer.export.error.mediaRecorder'));
+ };
+ recorder.onstop = function () {
+ if (settled) return;
+ try {
+ var blob = new Blob(chunks, { type: recorder.mimeType || mime });
+ if (!blob.size) throw exportError('viewer.export.error.emptyWebm');
+ finish(null, blob);
+ } catch (error) { finish(error); }
+ };
+ drawMotionFrame(ctx, backgroundImage, motionScene, 0);
+ recorder.start(250);
+ if (settled) return;
+ startedAt = performance.now();
+ raf = requestAnimationFrame(draw);
+ durationTimer = setTimeout(function () {
+ if (settled || recorder.state === 'inactive') return;
+ // 保留最佳努力的编码器 flush;失败后仍通过 stop 收集最后的片段。
+ try { recorder.requestData(); } catch (_) {}
+ if (settled) return;
+ flushTimer = setTimeout(function () {
+ if (settled) return;
+ try { if (recorder.state !== 'inactive') recorder.stop(); }
+ catch (error) { finish(error); }
+ }, 120);
+ }, duration);
+ } catch (error) { finish(error); }
};
- recorder.onerror = function (event) {
- cleanup();
- reject(event.error || exportError('viewer.export.error.mediaRecorder'));
+ backgroundImage.onerror = function () {
+ finish(exportError('viewer.export.error.webmBackground'));
};
- recorder.onstop = function () {
- cleanup();
- var blob = new Blob(chunks, { type: recorder.mimeType || mime });
- if (!blob.size) reject(exportError('viewer.export.error.emptyWebm'));
- else resolve(blob);
- };
- drawMotionFrame(ctx, backgroundImage, motionScene, 0);
- recorder.start(250);
- startedAt = performance.now();
- raf = requestAnimationFrame(draw);
- setTimeout(function () {
- if (recorder.state === 'inactive') return;
- // Chromium normally emits the final chunk during stop(), but
- // some embedded browser shells need an explicit encoder flush
- // first. Keep the short grace window bounded and harmless for
- // browsers that already delivered timeslice chunks.
- try { recorder.requestData(); } catch (_) {}
- setTimeout(function () {
- if (recorder.state !== 'inactive') recorder.stop();
- }, 120);
- }, duration);
- };
- backgroundImage.onerror = function () {
- URL.revokeObjectURL(sourceUrl);
- reject(exportError('viewer.export.error.webmBackground'));
- };
- backgroundImage.src = sourceUrl;
+ backgroundImage.src = sourceUrl;
+ } catch (error) { finish(error); }
});
}
@@ -6860,8 +7289,7 @@
// canvas.toBlob('image/webp') silently returns a PNG on browsers without
// WebP encoding (older Safari), so detect explicitly.
function supports(format) {
- if (format === 'share-card') return true;
- if (format === 'svg' || format === 'png') return true;
+ if (format === 'svg' || format === 'svg-light' || format === 'svg-dark' || format === 'png') return true;
if (format === 'webm') return canRecordMotion();
var mime = format === 'jpeg' ? 'image/jpeg' : 'image/webp';
try {
@@ -6877,7 +7305,7 @@
it.disabled = true;
it.title = viewerText('viewer.export.unsupported');
}
- if ((it.dataset.action === 'copy' || it.dataset.action === 'copy-share-card') && !canCopyImage()) {
+ if (it.dataset.action === 'copy' && !canCopyImage()) {
it.disabled = true;
it.title = viewerText('viewer.export.clipboardUnsupported');
}
@@ -6967,21 +7395,21 @@
});
function runExport(format) {
+ if (['svg', 'svg-light', 'svg-dark', 'png', 'jpeg', 'webp', 'webm'].indexOf(format) === -1) {
+ return Promise.reject(exportError('viewer.export.unsupported'));
+ }
var base = diagramFilename();
+ var svgTheme = format === 'svg' ? 'auto' :
+ format === 'svg-light' ? 'light' :
+ format === 'svg-dark' ? 'dark' : null;
close(true);
clearExportReceipt();
if (format === 'webm') toast(viewerText('viewer.export.recording'));
- return (format === 'share-card'
- ? rasterizeShareCard().then(function (blob) {
- recordExportReceipt('share-card', blob, true, { width: SHARE_CARD_WIDTH, height: SHARE_CARD_HEIGHT });
- download(blob, base + '-share-card.png');
- toast(viewerText('viewer.export.downloadedShare'));
- })
- : format === 'svg'
- ? Promise.resolve(serializeSvg(1, { autoTheme: true })).then(function (d) {
+ return (svgTheme
+ ? Promise.resolve(serializeSvg(1, { theme: svgTheme })).then(function (d) {
var blob = new Blob([d.svgString], { type: 'image/svg+xml;charset=utf-8' });
recordExportReceipt('svg', blob, d.canonicalStateClean);
- download(blob, base + '.svg');
+ download(blob, base + (svgTheme === 'auto' ? '' : '-' + svgTheme) + '.svg');
})
: format === 'webm'
? recordWebm().then(function (blob) {
@@ -7117,29 +7545,6 @@
}
}
- function runCopyShareCard() {
- close(true);
- clearExportReceipt();
- if (!canCopyImage()) {
- alert(viewerText('viewer.export.clipboardUnsupported.period'));
- return;
- }
- var blobPromise = rasterizeShareCard();
- return writePngToClipboard(blobPromise).then(function () {
- return blobPromise.then(function (blob) {
- recordExportReceipt('share-card', blob, true, { width: SHARE_CARD_WIDTH, height: SHARE_CARD_HEIGHT });
- toast(viewerText('viewer.export.copiedShare'));
- });
- }).catch(function (err) {
- console.error(err);
- var technicalMessage = err && err.message ? err.message : 'share-card';
- var message = exportMessage(err);
- document.documentElement.setAttribute('data-last-export-error-format', 'share-card');
- document.documentElement.setAttribute('data-last-export-error', technicalMessage);
- alert(viewerText('viewer.export.copyFailed', { message: message }));
- });
- }
-
function runCopy() {
close(true);
clearExportReceipt();
@@ -7165,9 +7570,6 @@
var reachShareCardBtn = e.target.closest('button[data-action="reach-share-card"]');
if (reachShareCardBtn && !reachShareCardBtn.disabled && !reachShareCardBtn.hidden) { runReachShareCard(); return; }
- var copyShareCardBtn = e.target.closest('button[data-action="copy-share-card"]');
- if (copyShareCardBtn && !copyShareCardBtn.disabled) { runCopyShareCard(); return; }
-
var copyBtn = e.target.closest('button[data-action="copy"]');
if (copyBtn && !copyBtn.disabled) { runCopy(); return; }
@@ -7185,8 +7587,7 @@
downloadRouteShareCard: runRouteShareCard,
downloadReachShareCard: runReachShareCard,
syncRouteShare: syncRouteShareItem,
- syncReachShare: syncReachShareItem,
- copyShareCard: runCopyShareCard
+ syncReachShare: syncReachShareItem
};
// Auto-open on page load for demo/screenshot purposes: ?openExport=1
@@ -7207,6 +7608,7 @@
} catch (_) {}
})();
+
/* ============================================================
Motion Governor — one reader switch and one motion budget. Ambient
trace yields to the strongest semantic owner; Still also parks bounded
@@ -7227,38 +7629,498 @@
var ownerToken = 0;
var ownerCleanup = null;
var lastEffectivePaused = null;
- var ambientStarted = false;
- var ambientPending = new Set();
+ var entryStarted = false;
+ var entryPending = new Set();
+ var flowCount = 0;
- function detachAmbientBoundary() {
- if (!svg) return;
- svg.removeEventListener('animationend', onAmbientBoundary, true);
- svg.removeEventListener('animationcancel', onAmbientBoundary, true);
+ // Runtime decoration carries geometry and tree visibility only. Keep each
+ // flow beside its authored edge so transforms, clipping and crossover
+ // paint order apply.
+ // Each renderer may declare a choreography that matches what its diagram
+ // means. Relay (the default) sends a comet from each source when the
+ // signal reaches it; stream adds a packet train for continuous data; walk
+ // moves one token along the main state path; sequence plays messages in
+ // authored order; sweep runs a playhead along a timeline; replay fills
+ // waterfall spans in proportion to their measured time. Motion Governor
+ // plans the timeline and per-element keyframes; viewer.css owns looks.
+ var SVG_NS = 'http://www.w3.org/2000/svg';
+ var choreography = svg ? (svg.getAttribute('data-motion-choreography') || 'relay') : 'relay';
+ var RELAY = {
+ speed: 280,
+ minTravel: 0.42,
+ maxTravel: 1.5,
+ handoff: 0.1,
+ dwell: 0.55,
+ maxSpan: 9,
+ land: 0.9,
+ rest: 1.4,
+ minCycle: 3.6
+ };
+ function stepOf(element, fallback) {
+ var step = parseFloat(element && element.style ? element.style.getPropertyValue('--step') : '');
+ return Number.isFinite(step) ? step : fallback;
}
- function settleAmbient(reason) {
- if (!capable) return false;
- ambientStarted = true;
- ambientPending.clear();
- detachAmbientBoundary();
- html.setAttribute('data-ambient-motion', 'settled');
- html.setAttribute('data-ambient-settle-reason', reason || 'complete');
- return true;
+ function byStep(a, b) { return a.step - b.step || a.index - b.index; }
+ function addWindow(windows, id, start, end, strong) {
+ if (!id) return;
+ (windows[id] = windows[id] || []).push({ start: start, end: end, strong: !!strong });
}
- function onAmbientBoundary(event) {
- if (!ambientPending.has(event.target)) return;
- ambientPending.delete(event.target);
- if (!ambientPending.size) settleAmbient('complete');
+ function planRelay(records, windows) {
+ var arrive = Object.create(null);
+ var seeded = Object.create(null);
+ var targets = Object.create(null);
+ records.forEach(function (record) { if (record.from !== record.to) targets[record.to] = true; });
+ function seed(id) {
+ if (arrive[id] !== undefined) return;
+ arrive[id] = 0;
+ seeded[id] = true;
+ }
+ function relax() {
+ // Earliest arrival over a few dozen edges; a scan per settle keeps
+ // cycles and fan-in deterministic without a priority queue.
+ var settled = Object.create(null);
+ for (;;) {
+ var next = null;
+ Object.keys(arrive).forEach(function (id) {
+ if (!settled[id] && (next === null || arrive[id] < arrive[next])) next = id;
+ });
+ if (next === null) return;
+ settled[next] = true;
+ var depart = arrive[next] + (seeded[next] ? 0 : RELAY.handoff);
+ records.forEach(function (record) {
+ if (record.from !== next) return;
+ var at = depart + record.travel;
+ if (arrive[record.to] === undefined || at < arrive[record.to]) arrive[record.to] = at;
+ });
+ }
+ }
+ records.forEach(function (record) { if (!targets[record.from]) seed(record.from); });
+ relax();
+ for (;;) {
+ // A closed cycle has no entry; start it at its earliest authored edge.
+ var orphan = records.filter(function (record) { return arrive[record.from] === undefined; }).sort(byStep)[0];
+ if (!orphan) break;
+ seed(orphan.from);
+ relax();
+ }
+ records.forEach(function (record) {
+ record.depart = arrive[record.from] + (seeded[record.from] ? 0 : RELAY.handoff);
+ record.active = true;
+ });
+ Object.keys(arrive).forEach(function (id) { addWindow(windows, id, arrive[id], arrive[id]); });
}
- function startAmbient() {
- if (ambientStarted || !capable) return false;
- ambientStarted = true;
- ambientPending = new Set(Array.prototype.slice.call(svg.querySelectorAll('[data-animate="edge"], [data-animate="node"]')));
- if (!ambientPending.size) return settleAmbient('empty');
- svg.addEventListener('animationend', onAmbientBoundary, true);
- svg.addEventListener('animationcancel', onAmbientBoundary, true);
- html.setAttribute('data-ambient-motion', 'running');
- html.removeAttribute('data-ambient-settle-reason');
- return true;
+ function planWalk(records, windows) {
+ // A state machine is in one state at a time: follow the first authored
+ // transition to an unvisited state and let the current state stay lit.
+ var targets = Object.create(null);
+ records.forEach(function (record) { if (record.from !== record.to) targets[record.to] = true; });
+ var ordered = records.slice().sort(byStep);
+ var start = (ordered.find(function (record) { return !targets[record.from]; }) || ordered[0]).from;
+ var visited = Object.create(null);
+ var current = start;
+ var clock = 0;
+ var enteredAt = 0;
+ visited[start] = true;
+ for (var hops = 0; hops < 16; hops += 1) {
+ var next = ordered.find(function (record) { return record.from === current && !visited[record.to]; });
+ if (!next) break;
+ next.active = true;
+ next.depart = clock + RELAY.dwell;
+ addWindow(windows, current, enteredAt, next.depart, true);
+ clock = next.depart + next.travel;
+ enteredAt = clock;
+ current = next.to;
+ visited[current] = true;
+ }
+ addWindow(windows, current, enteredAt, enteredAt + 1.2, true);
+ }
+ function planSequence(records, windows) {
+ var clock = 0;
+ records.slice().sort(byStep).forEach(function (record) {
+ record.active = true;
+ record.depart = clock;
+ clock += record.travel + RELAY.handoff;
+ addWindow(windows, record.from, record.depart, record.depart);
+ addWindow(windows, record.to, record.depart + record.travel, record.depart + record.travel);
+ });
+ }
+ function scalePlan(records, windows, span) {
+ var scale = span > RELAY.maxSpan ? RELAY.maxSpan / span : 1;
+ if (scale === 1) return span;
+ records.forEach(function (record) {
+ if (!record.active) return;
+ record.depart *= scale;
+ record.travel *= scale;
+ });
+ Object.keys(windows).forEach(function (id) {
+ windows[id].forEach(function (window) { window.start *= scale; window.end *= scale; });
+ });
+ return span * scale;
+ }
+ function nodeShapes() {
+ var shapes = Object.create(null);
+ Array.prototype.forEach.call(svg.querySelectorAll('[data-animate="node"]'), function (shape) {
+ var wrapper = shape.closest('[data-node-id]');
+ var id = wrapper ? wrapper.getAttribute('data-node-id') : '';
+ if (id) (shapes[id] = shapes[id] || []).push(shape);
+ });
+ return shapes;
+ }
+ function sceneBounds(elements) {
+ var box = null;
+ elements.forEach(function (element) {
+ var b = null;
+ try { b = element.getBBox(); } catch (_) {}
+ if (!b || !(b.width || b.height)) return;
+ if (!box) box = { x: b.x, y: b.y, right: b.x + b.width, bottom: b.y + b.height };
+ else {
+ box.x = Math.min(box.x, b.x); box.y = Math.min(box.y, b.y);
+ box.right = Math.max(box.right, b.x + b.width); box.bottom = Math.max(box.bottom, b.y + b.height);
+ }
+ });
+ return box;
+ }
+ function overlay(tag, cls, attrs, parent, before) {
+ var element = document.createElementNS(SVG_NS, tag);
+ Object.keys(attrs).forEach(function (name) { element.setAttribute(name, attrs[name]); });
+ element.setAttribute('class', 'ambient-edge-flow ' + cls);
+ element.setAttribute('data-ambient-flow-overlay', 'true');
+ element.setAttribute('aria-hidden', 'true');
+ parent.insertBefore(element, before || null);
+ return element;
+ }
+ // Timeline and waterfall share a playhead: a lit vertical rule and its
+ // bloom travel the time axis linearly, because time is the subject.
+ function addPlayhead(box, x0, x1, lead, sweep, extras) {
+ var anchor = svg.querySelector('[data-node-id]');
+ var parent = anchor ? anchor.parentNode : svg;
+ var attrs = { x1: x0.toFixed(1), x2: x0.toFixed(1), y1: (box.y - 10).toFixed(1), y2: (box.bottom + 10).toFixed(1) };
+ ['playhead-glow', 'playhead'].forEach(function (kind) {
+ var line = overlay('line', 'ambient-flow-' + kind, attrs, parent, anchor);
+ line.style.setProperty('--flow-name', 'archify-motion-playhead');
+ extras.push(line);
+ });
+ extras.playhead = { distance: x1 - x0, lead: lead, sweep: sweep };
+ }
+ function planSweep(windows, extras) {
+ var events = Array.prototype.filter.call(svg.querySelectorAll('[data-node-id][data-timeline-x]'), function (node) {
+ return Number.isFinite(parseFloat(node.getAttribute('data-timeline-x')));
+ });
+ if (!events.length) return 0;
+ var xs = events.map(function (node) { return parseFloat(node.getAttribute('data-timeline-x')); });
+ var x0 = Math.min.apply(null, xs), x1 = Math.max.apply(null, xs);
+ var lead = 0.35;
+ var sweep = Math.min(7, Math.max(3.2, events.length * 0.6));
+ events.forEach(function (node, index) {
+ var at = lead + (x1 > x0 ? (xs[index] - x0) / (x1 - x0) : 0) * sweep;
+ addWindow(windows, node.getAttribute('data-node-id'), at, at + 0.35, true);
+ });
+ var box = sceneBounds(Array.prototype.slice.call(svg.querySelectorAll('[data-timeline-lane]')));
+ if (box && x1 > x0) addPlayhead(box, x0, x1, lead, sweep, extras);
+ return lead + sweep + 0.6;
+ }
+ function planReplay(windows, extras) {
+ var spans = [];
+ Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id][data-waterfall-start]'), function (node) {
+ var start = parseFloat(node.getAttribute('data-waterfall-start'));
+ var end = parseFloat(node.getAttribute('data-waterfall-end'));
+ var bar = node.querySelector('[data-animate="node"]');
+ if (!bar || !Number.isFinite(start) || !(end >= start)) return;
+ var width = parseFloat(bar.getAttribute('width'));
+ var x = parseFloat(bar.getAttribute('x'));
+ if (!(width > 0) || !Number.isFinite(x)) return;
+ spans.push({ node: node, bar: bar, start: start, end: end, x: x, width: width });
+ });
+ if (!spans.length) return 0;
+ var t0 = Math.min.apply(null, spans.map(function (span) { return span.start; }));
+ var t1 = Math.max.apply(null, spans.map(function (span) { return span.end; }));
+ if (!(t1 > t0)) return 0;
+ var ruler = spans.reduce(function (best, span) { return span.end - span.start > best.end - best.start ? span : best; });
+ var pxPerUnit = ruler.width / Math.max(ruler.end - ruler.start, 1e-9);
+ var x0 = ruler.x - (ruler.start - t0) * pxPerUnit;
+ var lead = 0.35;
+ var replay = Math.min(6, Math.max(3.4, spans.length * 0.45));
+ var at = function (t) { return lead + (t - t0) / (t1 - t0) * replay; };
+ var settle = lead + replay + 0.9;
+ spans.forEach(function (span) {
+ var fill = overlay('rect', 'ambient-flow-fill', {
+ x: span.bar.getAttribute('x'), y: span.bar.getAttribute('y'),
+ width: span.bar.getAttribute('width'), height: span.bar.getAttribute('height'),
+ rx: span.bar.getAttribute('rx') || '0'
+ }, span.bar.parentNode, span.bar.nextSibling);
+ var tone = /(?:^|\s)c-([a-z]+)(?:\s|$)/.exec(span.bar.getAttribute('class') || '');
+ if (tone) fill.style.setProperty('--flow-fill', 'var(--' + tone[1] + '-stroke)');
+ if (span.node.getAttribute('data-waterfall-status') && span.node.getAttribute('data-waterfall-status') !== 'ok') {
+ fill.classList.add('ambient-flow-fill-failed');
+ }
+ fill.timing = { start: at(span.start), end: Math.max(at(span.end), at(span.start) + 0.08), settle: settle };
+ extras.push(fill);
+ addWindow(windows, span.node.getAttribute('data-node-id'), fill.timing.end, fill.timing.end);
+ });
+ var box = sceneBounds(spans.map(function (span) { return span.bar; }));
+ if (box) addPlayhead(box, x0, x0 + (t1 - t0) * pxPerUnit, lead, replay, extras);
+ return settle;
+ }
+ function writeKeyframes(records, windows, extras, cycle) {
+ function at(seconds) {
+ return (Math.min(100, Math.max(0, seconds / cycle * 100))).toFixed(3) + '%';
+ }
+ var ease = 'animation-timing-function: cubic-bezier(0.45, 0.05, 0.35, 1);';
+ var rules = [
+ '@keyframes archify-relay-ripple {',
+ ' 0% { r: 2px; opacity: var(--flow-peak, 0.6); }',
+ ' ' + at(0.75) + ', 100% { r: 20px; opacity: 0; }',
+ '}'
+ ];
+ records.forEach(function (record) {
+ if (!record.active) return;
+ var travel = record.travel;
+ rules.push(
+ '@keyframes archify-relay-comet-' + record.index + ' {',
+ ' 0% { stroke-dashoffset: calc(var(--flow-len, 0px) + var(--flow-shift, 0px)); opacity: 0; ' + ease + ' }',
+ ' ' + at(Math.min(0.12, travel * 0.2)) + ' { opacity: var(--flow-peak, 0.9); }',
+ ' ' + at(travel) + ' { stroke-dashoffset: var(--flow-shift, 0px); opacity: var(--flow-peak, 0.9); }',
+ ' ' + at(travel + 0.16) + ', 100% { stroke-dashoffset: var(--flow-shift, 0px); opacity: 0; }',
+ '}',
+ // A solid wake draws the travelled path behind the head on the same
+ // easing; a dashed wake only brightens its authored segments.
+ '@keyframes archify-relay-wake-' + record.index + ' {',
+ record.dashed
+ ? ' 0%, ' + at(travel * 0.3) + ' { opacity: 0; }'
+ : ' 0% { stroke-dashoffset: var(--flow-len, 0px); opacity: var(--flow-peak, 0.3); ' + ease + ' }',
+ record.dashed
+ ? ' ' + at(travel) + ' { opacity: var(--flow-peak, 0.3); }'
+ : ' ' + at(travel) + ' { stroke-dashoffset: 0px; opacity: var(--flow-peak, 0.3); }',
+ ' ' + at(travel + 0.9) + ', 100% { stroke-dashoffset: 0px; opacity: 0; }',
+ '}'
+ );
+ });
+ var glow = function (strong) {
+ return 'filter: var(--ambient-node-base-filter,) drop-shadow(0 0 ' + (strong ? 14 : 10) + 'px var(--arrow-emphasis));';
+ };
+ var base = 'filter: var(--ambient-node-base-filter, none);';
+ Object.keys(windows).forEach(function (id, index) {
+ var merged = [];
+ windows[id].slice().sort(function (a, b) { return a.start - b.start; }).forEach(function (window) {
+ var peakEnd = Math.max(window.end, window.start + 0.42);
+ var last = merged[merged.length - 1];
+ if (last && window.start <= last.peakEnd + 0.78) {
+ last.peakEnd = Math.max(last.peakEnd, peakEnd);
+ last.strong = last.strong || window.strong;
+ } else merged.push({ start: window.start, peakEnd: peakEnd, strong: window.strong });
+ });
+ var frames = [' 0%, 100% { ' + base + ' }'];
+ merged.forEach(function (window) {
+ frames.push(
+ ' ' + at(window.start) + ' { ' + base + ' }',
+ ' ' + at(window.start + 0.12) + ', ' + at(window.peakEnd) + ' { ' + glow(window.strong) + ' }',
+ ' ' + at(window.peakEnd + 0.78) + ' { ' + base + ' }'
+ );
+ });
+ rules.push('@keyframes archify-relay-node-' + index + ' {', frames.join('\n'), '}');
+ windows[id].keyframes = 'archify-relay-node-' + index;
+ });
+ if (extras.playhead) {
+ var p = extras.playhead;
+ rules.push(
+ '@keyframes archify-motion-playhead {',
+ ' 0% { transform: translateX(0px); opacity: 0; }',
+ ' ' + at(Math.max(0.05, p.lead - 0.2)) + ' { transform: translateX(0px); opacity: 0; }',
+ ' ' + at(p.lead) + ' { transform: translateX(0px); opacity: var(--flow-peak, 0.9); }',
+ ' ' + at(p.lead + p.sweep) + ' { transform: translateX(' + p.distance.toFixed(1) + 'px); opacity: var(--flow-peak, 0.9); }',
+ ' ' + at(p.lead + p.sweep + 0.45) + ', 100% { transform: translateX(' + p.distance.toFixed(1) + 'px); opacity: 0; }',
+ '}'
+ );
+ }
+ extras.forEach(function (element, index) {
+ if (!element.timing) return;
+ var t = element.timing;
+ rules.push(
+ '@keyframes archify-replay-fill-' + index + ' {',
+ ' 0%, ' + at(t.start) + ' { transform: scaleX(0); opacity: var(--flow-peak, 0.4); }',
+ ' ' + at(t.end) + ', ' + at(t.settle) + ' { transform: scaleX(1); opacity: var(--flow-peak, 0.4); }',
+ ' ' + at(t.settle + 0.7) + ', 100% { transform: scaleX(1); opacity: 0; }',
+ '}'
+ );
+ element.style.setProperty('--flow-name', 'archify-replay-fill-' + index);
+ });
+ var style = document.createElement('style');
+ style.setAttribute('data-ambient-flow-keyframes', 'true');
+ style.textContent = rules.join('\n');
+ document.head.appendChild(style);
+ }
+ function createFlows() {
+ var records = [];
+ Array.prototype.forEach.call(svg.querySelectorAll('path[data-animate="edge"]'), function (shape, index) {
+ var d = shape.getAttribute('data-motion-path') || shape.getAttribute('d');
+ if (!d) return;
+ var anchor = shape;
+ // Tree Branches initializes after these overlays and includes their
+ // inherited ancestors in its existing collapse/expand lifecycle.
+ function tagOverlay(flow) {
+ flow.setAttribute('data-ambient-flow-overlay', 'true');
+ flow.setAttribute('aria-hidden', 'true');
+ if (shape.hasAttribute('data-tree-ancestors')) {
+ flow.setAttribute('data-tree-ancestors', shape.getAttribute('data-tree-ancestors'));
+ }
+ }
+ function addPath(cls) {
+ var flow = document.createElementNS(SVG_NS, 'path');
+ flow.setAttribute('d', d);
+ ['transform', 'mask', 'clip-path', 'vector-effect'].forEach(function (name) {
+ if (shape.hasAttribute(name)) flow.setAttribute(name, shape.getAttribute(name));
+ });
+ flow.setAttribute('class', 'ambient-edge-flow ambient-flow-' + cls);
+ tagOverlay(flow);
+ shape.parentNode.insertBefore(flow, anchor.nextSibling);
+ anchor = flow;
+ return flow;
+ }
+ var wake = addPath('wake');
+ var len = 0;
+ try { len = wake.getTotalLength(); } catch (_) {}
+ if (!(len > 0)) {
+ wake.remove();
+ return;
+ }
+ var record = {
+ index: records.length,
+ len: len,
+ from: shape.getAttribute('data-edge-from') || shape.getAttribute('data-composition-edge-from') || '',
+ to: shape.getAttribute('data-edge-to') || shape.getAttribute('data-composition-edge-to') || '',
+ step: stepOf(shape, index),
+ travel: Math.min(RELAY.maxTravel, Math.max(RELAY.minTravel, len / RELAY.speed)),
+ depart: 0,
+ active: false,
+ layers: []
+ };
+ records.push(record);
+ // Dashed authored lines keep their dash language through the relay:
+ // the wake brightens only the authored segments and never fills the
+ // gaps back into a solid line.
+ var authoredDash = '';
+ try { authoredDash = window.getComputedStyle(shape).strokeDasharray; } catch (_) {}
+ record.dashed = !!(authoredDash && authoredDash !== 'none');
+ wake.style.setProperty('--flow-dasharray', record.dashed ? authoredDash : len.toFixed(1) + ' ' + len.toFixed(1));
+ // Absolute caps keep the comet a slim streak on long edges instead
+ // of growing into a bright slab; the tail disintegrates into a
+ // sparkle of fragments behind the head, and --flow-shift trails
+ // each layer behind the head tip by its own length.
+ var headLen = Math.min(14, Math.max(7, len * 0.03));
+ var haloLen = Math.min(22, Math.max(12, len * 0.07));
+ var trail = len >= 120
+ ? { pattern: '2.5 2 4 3 5.5 4.5 8 ' + (len - 30).toFixed(1), length: 30 }
+ : (len >= 60
+ ? { pattern: '3 3 7 ' + (len - 13).toFixed(1), length: 13 }
+ : { pattern: '5 ' + Math.max(4, len - 5).toFixed(1), length: 5 });
+ record.layers.push(
+ { flow: wake, kind: 'wake', dash: len, shift: 0 },
+ { flow: addPath('glow'), kind: 'comet', dash: haloLen, shift: (haloLen - headLen) / 2 },
+ { flow: addPath('halo'), kind: 'comet', dash: haloLen, shift: (haloLen - headLen) / 2 },
+ { flow: addPath('tail'), kind: 'comet', dash: trail.length, shift: trail.length - headLen, dasharray: trail.pattern },
+ { flow: addPath('head'), kind: 'comet', dash: headLen, shift: 0 }
+ );
+ if (choreography === 'stream') {
+ // A packet train behind the comet reads as a continuous stream.
+ [1, 2, 3].forEach(function (order) {
+ record.layers.push({ flow: addPath('head packet'), kind: 'comet', dash: Math.max(4, headLen * 0.55), shift: 0, packet: order });
+ });
+ }
+ // The ripple lands where the comet does; keep it out of the edge's
+ // mask so it can bloom over the node boundary.
+ var end = null;
+ try { end = wake.getPointAtLength(len); } catch (_) {}
+ if (end) {
+ var ripple = document.createElementNS(SVG_NS, 'circle');
+ ripple.setAttribute('cx', end.x.toFixed(1));
+ ripple.setAttribute('cy', end.y.toFixed(1));
+ ripple.setAttribute('r', '2');
+ if (shape.hasAttribute('transform')) ripple.setAttribute('transform', shape.getAttribute('transform'));
+ ripple.setAttribute('class', 'ambient-edge-flow ambient-flow-ripple');
+ tagOverlay(ripple);
+ shape.parentNode.insertBefore(ripple, anchor.nextSibling);
+ record.ripple = ripple;
+ }
+ });
+ var windows = Object.create(null);
+ var extras = [];
+ var span = 0;
+ if (choreography === 'sweep') span = planSweep(windows, extras);
+ else if (choreography === 'replay') span = planReplay(windows, extras);
+ else if (records.length) {
+ var linked = records.filter(function (record) { return record.from && record.to; });
+ if (choreography === 'sequence' || linked.length < records.length) planSequence(records, windows);
+ else if (choreography === 'walk') planWalk(records, windows);
+ else planRelay(records, windows);
+ span = records.reduce(function (max, record) {
+ return record.active ? Math.max(max, record.depart + record.travel) : max;
+ }, 0);
+ span = scalePlan(records, windows, span);
+ }
+ records.forEach(function (record) {
+ if (record.active) return;
+ record.layers.forEach(function (layer) { layer.flow.remove(); });
+ if (record.ripple) record.ripple.remove();
+ });
+ var active = records.filter(function (record) { return record.active; });
+ if (!active.length && !extras.length) return;
+ var cycle = Math.max(RELAY.minCycle, span + RELAY.land + RELAY.rest);
+ writeKeyframes(active, windows, extras, cycle);
+ svg.style.setProperty('--flow-cycle', cycle.toFixed(3) + 's');
+ html.style.setProperty('--flow-cycle-chrome', cycle.toFixed(3) + 's');
+ active.forEach(function (record) {
+ var gap = Math.min(0.22, record.travel * 0.28);
+ record.layers.forEach(function (layer) {
+ var flow = layer.flow;
+ flow.style.setProperty('--flow-len', record.len.toFixed(1) + 'px');
+ flow.style.setProperty('--flow-delay', (record.depart + (layer.packet || 0) * gap).toFixed(3) + 's');
+ flow.style.setProperty('--flow-dash', layer.dash.toFixed(1) + 'px');
+ flow.style.setProperty('--flow-shift', layer.shift.toFixed(1) + 'px');
+ flow.style.setProperty('--flow-name', 'archify-relay-' + layer.kind + '-' + record.index);
+ if (layer.dasharray) flow.style.setProperty('--flow-dasharray', layer.dasharray);
+ });
+ if (record.ripple) {
+ record.ripple.style.setProperty('--flow-delay', (record.depart + record.travel).toFixed(3) + 's');
+ record.ripple.style.setProperty('--flow-name', 'archify-relay-ripple');
+ }
+ });
+ var shapes = nodeShapes();
+ Object.keys(windows).forEach(function (id) {
+ (shapes[id] || []).forEach(function (shape) {
+ shape.style.setProperty('--flow-node-name', windows[id].keyframes);
+ });
+ });
+ flowCount = active.length + extras.length;
+ }
+ function settleEntry() {
+ entryPending.clear();
+ svg.removeEventListener('animationend', onEntryBoundary, true);
+ svg.removeEventListener('animationcancel', onEntryBoundary, true);
+ html.setAttribute('data-ambient-entry', 'settled');
+ }
+ function onEntryBoundary(event) {
+ if (!entryPending.has(event.target)) return;
+ // The entrance settles only when each node's pulse finishes; the
+ // shorter fade-rise enter animation may end first without ending it.
+ if (event.animationName && !/node-pulse/.test(event.animationName)) return;
+ entryPending.delete(event.target);
+ if (!entryPending.size) settleEntry();
+ }
+ function renderAmbient(suppressed) {
+ html.setAttribute('data-ambient-motion', flowCount ? (suppressed ? 'paused' : 'running') : 'empty');
+ if (suppressed) {
+ entryStarted = true;
+ settleEntry();
+ } else if (!entryStarted) {
+ entryStarted = true;
+ entryPending = new Set(Array.prototype.slice.call(svg.querySelectorAll('[data-animate="node"]')));
+ if (!entryPending.size) settleEntry();
+ else {
+ svg.addEventListener('animationend', onEntryBoundary, true);
+ svg.addEventListener('animationcancel', onEntryBoundary, true);
+ html.setAttribute('data-ambient-entry', 'running');
+ }
+ }
}
function readStored() {
@@ -7266,8 +8128,8 @@
}
function writeStored() {
try {
- if (readerPaused) localStorage.setItem(STORAGE_KEY, 'still');
- else localStorage.removeItem(STORAGE_KEY);
+ if (readerPaused) localStorage.removeItem(STORAGE_KEY);
+ else localStorage.setItem(STORAGE_KEY, 'live');
} catch (_) {}
}
function reducedMotion() {
@@ -7280,10 +8142,6 @@
return readerPaused || reducedMotion() || hasSuspension();
}
function ownerLabel(value) {
- if (value === 'story') return viewerText('viewer.owner.story');
- if (value === 'chapter') return viewerText('viewer.owner.chapter');
- if (value === 'chapter-preview') return viewerText('viewer.owner.chapterPreview');
- if (value === 'handoff') return viewerText('viewer.owner.handoff');
if (value === 'route') return viewerText('viewer.owner.route');
if (value === 'lens') return viewerText('viewer.owner.lens');
if (value === 'relationship') return viewerText('viewer.owner.relationship');
@@ -7297,20 +8155,10 @@
var systemPaused = reducedMotion();
var paused = effectivePaused();
html.setAttribute('data-motion', paused ? 'still' : 'live');
- if (paused || owner || html.hasAttribute('data-embed') || html.hasAttribute('data-share-playback') || html.hasAttribute('data-document-hidden')) {
- settleAmbient('suppressed');
- } else if (!ambientStarted) {
- startAmbient();
- }
+ renderAmbient(paused || owner || html.hasAttribute('data-embed') || html.hasAttribute('data-share-playback') || html.hasAttribute('data-document-hidden'));
btn.setAttribute('aria-pressed', paused ? 'false' : 'true');
btn.disabled = systemPaused;
label.textContent = viewerText(paused ? 'viewer.motion.still' : 'viewer.motion.live');
- if (paused && lastEffectivePaused !== true && Archify.guidedViews && Archify.guidedViews.isPlaying()) {
- Archify.guidedViews.pause();
- }
- if (paused && lastEffectivePaused !== true && Archify.guidedViews && Archify.guidedViews.settleHandoff) {
- Archify.guidedViews.settleHandoff(systemPaused ? 'reduced-motion' : (hasSuspension() ? 'hidden' : 'still'));
- }
if (paused && lastEffectivePaused !== true && Archify.routeProbe && Archify.routeProbe.isJourneyPlaying && Archify.routeProbe.isJourneyPlaying()) {
Archify.routeProbe.pauseJourney({ preserveElapsed: true, reason: systemPaused ? 'reduced-motion' : (hasSuspension() ? 'hidden' : 'still') });
}
@@ -7349,8 +8197,6 @@
}
function deriveOwner() {
if (!svg) return '';
- if (svg.hasAttribute('data-story-playing') || svg.hasAttribute('data-story-follow')) return 'story';
- if (svg.hasAttribute('data-story-active')) return 'chapter';
if (svg.hasAttribute('data-route-picking') || svg.hasAttribute('data-route-active')) return 'route';
if (svg.hasAttribute('data-lens-active')) return 'lens';
if (svg.hasAttribute('data-relationship-preview-active')) return 'relationship';
@@ -7414,7 +8260,7 @@
html.removeAttribute('data-motion');
html.removeAttribute('data-motion-owner');
html.removeAttribute('data-ambient-motion');
- html.removeAttribute('data-ambient-settle-reason');
+ html.removeAttribute('data-ambient-entry');
return {
capable: false,
pause: function () { return false; },
@@ -7430,21 +8276,26 @@
};
}
+ createFlows();
html.setAttribute('data-motion-capable', 'true');
btn.hidden = false;
- readerPaused = readStored() === 'still';
+ readerPaused = readStored() !== 'live';
btn.addEventListener('click', function () { setPaused(!readerPaused); });
if (motionQuery) {
if (typeof motionQuery.addEventListener === 'function') motionQuery.addEventListener('change', render);
else if (typeof motionQuery.addListener === 'function') motionQuery.addListener(render);
}
document.addEventListener('visibilitychange', syncVisibility);
+ if (typeof MutationObserver !== 'undefined') {
+ var contextObserver = new MutationObserver(render);
+ contextObserver.observe(html, { attributes: true, attributeFilter: ['data-embed', 'data-share-playback'] });
+ }
if (document.documentElement.getAttribute('data-embed') !== 'true' && typeof MutationObserver !== 'undefined' && typeof Node !== 'undefined' && svg instanceof Node) {
var ownerObserver = new MutationObserver(function () { publishOwner(); });
ownerObserver.observe(svg, {
attributes: true,
attributeFilter: [
- 'data-story-playing', 'data-story-follow', 'data-story-active', 'data-route-picking', 'data-route-active',
+ 'data-route-picking', 'data-route-active',
'data-lens-active', 'data-relationship-preview-active', 'data-intent-trace-active',
'data-focus-active', 'data-legend-preview-active'
]
@@ -7479,69 +8330,172 @@
Archify.sourceEvidence = (function () {
var element = document.getElementById('archify-source-evidence-data');
var payload = null;
- var svgNamespace = 'http://www.w3.org/2000/svg';
if (element) {
try {
var parsed = JSON.parse(element.textContent || 'null');
if (parsed && parsed.verified === true && parsed.repository && parsed.nodes) payload = parsed;
} catch (_) {}
}
- function installBeacons() {
- if (!payload) return 0;
- var svg = document.querySelector('.diagram-container svg');
- if (!svg) return 0;
- var installed = 0;
- Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {
- var id = node.getAttribute('data-node-id');
- var sources = payload.nodes[id];
- if (!Array.isArray(sources) || !sources.length || node.querySelector('[data-source-evidence-beacon]')) return;
- var shape = node.querySelector('[data-animate="node"]') || node.querySelector('[class*="c-"]');
- var box;
- try { box = (shape || node).getBBox(); } catch (_) { return; }
- if (!box || !Number.isFinite(box.x) || !Number.isFinite(box.y) || !Number.isFinite(box.width) || box.width < 36) return;
-
- var count = sources.length;
- var label = viewerCount('viewer.passport.beacon', count);
- var beacon = document.createElementNS(svgNamespace, 'g');
- beacon.classList.add('source-evidence-beacon');
- beacon.setAttribute('data-source-evidence-beacon', '');
- beacon.setAttribute('aria-hidden', 'true');
- var brandOffset = node.hasAttribute('data-node-brand') ? 24 : 0;
- beacon.setAttribute('transform', 'translate(' + (box.x + box.width - 35 - brandOffset) + ' ' + (box.y + 5) + ')');
- var title = document.createElementNS(svgNamespace, 'title');
- title.textContent = label;
- var plate = document.createElementNS(svgNamespace, 'rect');
- plate.setAttribute('width', '30');
- plate.setAttribute('height', '12');
- plate.setAttribute('rx', '6');
- var text = document.createElementNS(svgNamespace, 'text');
- text.setAttribute('x', '15');
- text.setAttribute('y', '8.25');
- text.textContent = viewerText('viewer.passport.sourceMarker') + ' ' + count;
- beacon.appendChild(title);
- beacon.appendChild(plate);
- beacon.appendChild(text);
- node.appendChild(beacon);
-
- var originalLabel = node.getAttribute('aria-label') || '';
- node.setAttribute('data-source-evidence-count', String(count));
- node.setAttribute('data-source-evidence-original-label', originalLabel);
- node.setAttribute('aria-label', (originalLabel ? originalLabel + ', ' : '') + viewerCount('viewer.passport.sourceCount', count));
- installed += 1;
- });
- return installed;
- }
+ // Keep verified evidence discoverable to screen readers without adding
+ // visual marks. Restore first so repeated initialization never appends
+ // another count or retains one after evidence becomes unavailable.
+ var svg = document.querySelector('.diagram-container svg');
+ if (svg) Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {
+ if (node.hasAttribute('data-source-evidence-count')) {
+ var savedLabel = node.getAttribute('data-source-evidence-original-label');
+ if (savedLabel == null) node.removeAttribute('aria-label');
+ else node.setAttribute('aria-label', savedLabel);
+ node.removeAttribute('data-source-evidence-count');
+ node.removeAttribute('data-source-evidence-original-label');
+ }
+ var sources = payload && payload.nodes[node.getAttribute('data-node-id')];
+ if (!Array.isArray(sources) || !sources.length) return;
+ var originalLabel = node.getAttribute('aria-label');
+ node.setAttribute('data-source-evidence-count', String(sources.length));
+ if (originalLabel != null) node.setAttribute('data-source-evidence-original-label', originalLabel);
+ node.setAttribute('aria-label', (originalLabel ? originalLabel + ', ' : '') +
+ viewerCount('viewer.passport.sourceCount', sources.length));
+ });
return {
available: function () { return Boolean(payload); },
repository: function () { return payload ? payload.repository : null; },
node: function (id) {
var sources = payload && payload.nodes ? payload.nodes[id] : null;
return Array.isArray(sources) ? sources.slice() : [];
- },
- installBeacons: installBeacons
+ }
};
})();
- Archify.sourceEvidence.installBeacons();
+
+ /* ============================================================
+ Tree Branches — expand/collapse for hierarchy diagrams. The renderer
+ lays out the complete tree once and tags every node, link, and toggle
+ with its ancestors; collapsing only hides descendants, so visible nodes
+ never move and the reader keeps their place. Selecting a hidden node
+ through Finder, Outline, or a shared link expands its ancestors. Export
+ always writes the complete tree (see Export Cleanup).
+ ============================================================ */
+ Archify.treeBranches = (function () {
+ var svg = document.querySelector('.diagram-container > svg[data-tree-ui]');
+ if (!svg) return { active: false };
+ var collapsed = Object.create(null);
+ var toggles = Object.create(null);
+ Array.prototype.forEach.call(svg.querySelectorAll('[data-tree-toggle]'), function (toggle) {
+ toggles[toggle.getAttribute('data-tree-toggle')] = toggle;
+ });
+ var tagged = svg.querySelectorAll('[data-tree-ancestors]');
+ var expandAll = svg.querySelector('[data-tree-expand-all]');
+
+ function ancestors(el) {
+ return (el.getAttribute('data-tree-ancestors') || '').split(' ').filter(Boolean);
+ }
+
+ function apply() {
+ Array.prototype.forEach.call(tagged, function (el) {
+ var hidden = ancestors(el).some(function (id) { return collapsed[id]; });
+ if (hidden) el.setAttribute('data-tree-hidden', '');
+ else el.removeAttribute('data-tree-hidden');
+ });
+ var any = false;
+ Object.keys(toggles).forEach(function (id) {
+ var toggle = toggles[id];
+ var isCollapsed = Boolean(collapsed[id]);
+ any = any || isCollapsed;
+ toggle.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true');
+ toggle.setAttribute('aria-label', toggle.getAttribute(isCollapsed ? 'data-tree-label-expand' : 'data-tree-label-collapse') || '');
+ var node = svg.querySelector('[data-node-id="' + id + '"]');
+ if (node) {
+ if (isCollapsed) node.setAttribute('data-tree-collapsed', '');
+ else node.removeAttribute('data-tree-collapsed');
+ }
+ });
+ if (any) svg.setAttribute('data-tree-any-collapsed', '');
+ else svg.removeAttribute('data-tree-any-collapsed');
+ }
+
+ function setCollapsed(id, value) {
+ if (!toggles[id]) return false;
+ if (value) collapsed[id] = true;
+ else delete collapsed[id];
+ apply();
+ return true;
+ }
+
+ function toggle(id) { return setCollapsed(id, !collapsed[id]); }
+
+ // Reveal a node by expanding every collapsed ancestor; nothing else moves.
+ function reveal(id) {
+ var node = svg.querySelector('[data-node-id="' + id + '"]');
+ if (!node) return false;
+ var changed = false;
+ ancestors(node).forEach(function (ancestor) {
+ if (collapsed[ancestor]) { delete collapsed[ancestor]; changed = true; }
+ });
+ if (changed) apply();
+ return changed;
+ }
+
+ function restoreAll() {
+ collapsed = Object.create(null);
+ apply();
+ }
+
+ function activate(event) {
+ var target = event.target.closest('[data-tree-toggle], [data-tree-expand-all]');
+ if (!target || !svg.contains(target)) return false;
+ event.preventDefault();
+ event.stopPropagation();
+ if (target.hasAttribute('data-tree-expand-all')) {
+ restoreAll();
+ var root = svg.querySelector('[data-tree-toggle]:not([data-tree-ancestors])');
+ if (root) root.focus();
+ } else {
+ toggle(target.getAttribute('data-tree-toggle'));
+ target.focus();
+ }
+ return true;
+ }
+
+ // Capture phase so the canvas focus handler never treats a toggle press
+ // as a background click that clears the current focus.
+ svg.addEventListener('click', activate, true);
+ svg.addEventListener('keydown', function (event) {
+ if (event.key === 'Enter' || event.key === ' ') { activate(event); return; }
+ var node = event.target.closest('[data-node-id]');
+ if (!node || !svg.contains(node)) return;
+ var id = node.getAttribute('data-node-id');
+ // Arrow keys follow the tree convention: left collapses, right expands.
+ if (event.key === 'ArrowLeft' && toggles[id] && !collapsed[id]) { event.preventDefault(); setCollapsed(id, true); }
+ else if (event.key === 'ArrowRight' && collapsed[id]) { event.preventDefault(); setCollapsed(id, false); }
+ }, true);
+
+ // Focus reveals ancestors synchronously before positioning its lens.
+ // The observer also covers paths that change pressed state directly.
+ new MutationObserver(function (records) {
+ records.forEach(function (record) {
+ var el = record.target;
+ if (el.hasAttribute && el.hasAttribute('data-tree-hidden') && el.getAttribute('aria-pressed') === 'true') {
+ reveal(el.getAttribute('data-node-id'));
+ }
+ });
+ }).observe(svg, { subtree: true, attributes: true, attributeFilter: ['aria-pressed'] });
+
+ Object.keys(toggles).forEach(function (id) {
+ if (toggles[id].hasAttribute('data-tree-initially-collapsed')) collapsed[id] = true;
+ });
+ apply();
+
+ return {
+ active: true,
+ toggle: toggle,
+ collapse: function (id) { return setCollapsed(id, true); },
+ expand: function (id) { return setCollapsed(id, false); },
+ reveal: reveal,
+ restoreAll: restoreAll,
+ collapsedIds: function () { return Object.keys(collapsed); },
+ expandAllControl: expandAll
+ };
+ })();
+
/* ============================================================
Explore — stable-ID neighborhood focus + dependency-free pan/zoom.
@@ -7573,6 +8527,7 @@
var copyBtn = document.getElementById('btn-focus-copy');
var relationsBtn = document.getElementById('btn-focus-relations');
var clearBtn = document.getElementById('btn-focus-clear');
+ var moveBtn = document.getElementById('btn-focus-move');
var activeIds = [];
var hoveredRelationship = null;
var focusedRelationship = null;
@@ -7582,6 +8537,9 @@
var relationshipHitOverlay = null;
var relationshipHitTargets = [];
var directPreviewTimer = null;
+ var lensDrag = null;
+ var lensDragClickPointer = null;
+ var manualLensPosition = null;
var reachabilityMode = null;
var activeReachability = null;
var svgNamespace = 'http://www.w3.org/2000/svg';
@@ -7720,9 +8678,6 @@
}
var result = reachabilityFor(activeIds[0], direction);
if (!result || result.nodeIds.length <= 1) return false;
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false, resetView: false });
- }
clearRelationshipPreview({ clearPin: true });
clearReachability({ updateUrl: false });
reachabilityMode = direction;
@@ -7776,7 +8731,7 @@
if (options.reveal !== false && Archify.view && typeof Archify.view.reveal === 'function') {
Archify.view.reveal(result.nodeIds, { includeNeighbors: false, reason: 'reachability' });
}
- requestLensPlacement();
+ placeRelationshipLens();
return true;
}
function reachabilitySnapshot() {
@@ -7879,6 +8834,7 @@
function renderSourceEvidence(id) {
evidenceLinks.textContent = '';
repositoryLink.removeAttribute('href');
+ repositoryLink.removeAttribute('aria-label');
repositoryLink.textContent = '';
var sources = Archify.sourceEvidence.node(id);
var repository = Archify.sourceEvidence.repository();
@@ -7886,24 +8842,28 @@
evidence.hidden = true;
return;
}
- var slug = repository.url.replace(/^https:\/\/github\.com\//, '').replace(/\/$/, '');
- repositoryLink.href = repository.url + '/tree/' + repository.revision;
- repositoryLink.textContent = slug + ' @ ' + repository.shortRevision;
- repositoryLink.setAttribute('aria-label', viewerText('viewer.passport.repository.open', { revision: repository.revision }));
+ repositoryLink.textContent = repository.label + ' @ ' + repository.shortRevision;
+ if (repository.href) {
+ repositoryLink.href = repository.href;
+ repositoryLink.setAttribute('aria-label', viewerText('viewer.passport.repository.open', { revision: repository.revision }));
+ }
+ evidence.title = viewerText('viewer.passport.verificationScope');
sources.forEach(function (source) {
- var link = document.createElement('a');
+ var link = document.createElement(source.href ? 'a' : 'div');
link.className = 'semantic-passport-source';
- link.href = source.href;
- link.target = '_blank';
- link.rel = 'noopener noreferrer';
- link.referrerPolicy = 'no-referrer';
- link.setAttribute('aria-label', viewerText('viewer.passport.source.open', { path: source.path, revision: repository.shortRevision }));
+ if (source.href) {
+ link.href = source.href;
+ link.target = '_blank';
+ link.rel = 'noopener noreferrer';
+ link.referrerPolicy = 'no-referrer';
+ link.setAttribute('aria-label', viewerText('viewer.passport.source.open', { path: source.path, revision: repository.shortRevision }));
+ }
var name = document.createElement('strong');
name.textContent = source.label || source.path.split('/').pop() || source.path;
var location = document.createElement('code');
location.textContent = source.line
- ? 'L' + source.line + (source.endLine && source.endLine !== source.line ? '–' + source.endLine : '') + ' ↗'
- : viewerText('viewer.passport.source.openLink');
+ ? 'L' + source.line + (source.endLine && source.endLine !== source.line ? '–' + source.endLine : '') + (source.href ? ' ↗' : '')
+ : source.href ? viewerText('viewer.passport.source.openLink') : '';
var sourcePath = document.createElement('small');
sourcePath.textContent = source.path;
link.appendChild(name);
@@ -7958,12 +8918,12 @@
function relationshipEdgeShapes(edge) {
if (!edge) return [];
if (/^(path|line|polyline)$/i.test(edge.tagName || '')) return [edge];
- return Array.prototype.slice.call(edge.querySelectorAll('path, line, polyline'));
+ return Array.prototype.slice.call(edge.querySelectorAll('path:not([data-ambient-flow-overlay]), line, polyline'));
}
function relationshipHitRecords() {
var recordsByKey = {};
- var recordsById = {};
- var byId = {};
+ var recordsById = Object.create(null);
+ var byId = Object.create(null);
nodes().forEach(function (node) { byId[node.getAttribute('data-node-id')] = node; });
var records = [];
edges().forEach(function (edge) {
@@ -8062,6 +9022,8 @@
}
function relationshipPulseGeometry(shape) {
var clone = shape.cloneNode(false);
+ if (shape.getAttribute('data-motion-path')) clone.setAttribute('d', relationshipTokenPath(shape));
+ clone.removeAttribute('data-motion-path');
clone.removeAttribute('id');
clone.removeAttribute('class');
clone.removeAttribute('style');
@@ -8106,7 +9068,7 @@
function relationshipTokenPath(shape) {
if (!shape) return '';
var tagName = String(shape.tagName || '').toLowerCase();
- if (tagName === 'path') return shape.getAttribute('d') || '';
+ if (tagName === 'path') return shape.getAttribute('data-motion-path') || shape.getAttribute('d') || '';
if (tagName === 'line') {
return 'M ' + shape.getAttribute('x1') + ' ' + shape.getAttribute('y1') +
' L ' + shape.getAttribute('x2') + ' ' + shape.getAttribute('y2');
@@ -8251,7 +9213,7 @@
target.removeAttribute('data-preview-active');
});
renderRelationshipCopyAction();
- requestLensPlacement();
+ placeRelationshipLens();
}
function previewRelationship(button, options) {
options = options || {};
@@ -8278,7 +9240,7 @@
if (!chip.hidden && options.direct !== true) chip.setAttribute('data-relationship-previewing', 'true');
activeRelationshipPreview = button;
renderRelationshipPulse(key);
- requestLensPlacement();
+ placeRelationshipLens();
}
function syncRelationshipPreview() {
var next = pinnedRelationship || focusedRelationship || hoveredRelationship;
@@ -8290,11 +9252,9 @@
html.getAttribute('data-guide-open') === 'true' ||
container.classList.contains('is-panning') ||
(activeIds.length > 0 && !pinnedRelationshipKey) ||
- svg.hasAttribute('data-story-active') ||
svg.hasAttribute('data-route-picking') ||
svg.hasAttribute('data-route-active') ||
- svg.hasAttribute('data-lens-active') ||
- svg.hasAttribute('data-chapter-preview');
+ svg.hasAttribute('data-lens-active');
}
function scheduleDirectRelationshipPreview(target) {
if (directPreviewTimer) window.clearTimeout(directPreviewTimer);
@@ -8333,9 +9293,6 @@
}
var record = relationshipRecordForKey(key);
if (!record) return false;
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
set(record.from, { toggle: false, updateUrl: false });
var row = Array.prototype.slice.call(relationshipList.querySelectorAll('[data-relationship-key]')).find(function (candidate) {
return candidate.getAttribute('data-relationship-key') === key;
@@ -8557,9 +9514,148 @@
relationshipList.appendChild(section);
});
}
+ function lensPlacementBounds() {
+ var containerRect = container.getBoundingClientRect();
+ if (containerRect.width <= 0 || containerRect.height <= 0 || chip.offsetWidth <= 0 || chip.offsetHeight <= 0) return null;
+ var padding = window.innerWidth <= 720 ? 8 : 16;
+ var visibleLeft = Math.max(padding, -containerRect.left + padding);
+ var visibleRight = Math.min(
+ container.clientWidth - padding,
+ window.innerWidth - containerRect.left - padding
+ );
+ var visibleTop = Math.max(padding, -containerRect.top + padding);
+ var visibleBottom = Math.min(
+ container.clientHeight - padding,
+ window.innerHeight - containerRect.top - padding
+ );
+ var minLeft = visibleLeft;
+ var minTop = Math.min(visibleTop, Math.max(padding, visibleBottom - chip.offsetHeight));
+ return {
+ containerRect: containerRect,
+ minLeft: minLeft,
+ maxLeft: Math.max(minLeft, visibleRight - chip.offsetWidth),
+ minTop: minTop,
+ maxTop: Math.max(minTop, visibleBottom - chip.offsetHeight)
+ };
+ }
+ function manualLensPlacementAvailable() {
+ return window.innerWidth > 720 && (!finePointerQuery || finePointerQuery.matches);
+ }
+ function clampLensPosition(position, bounds) {
+ if (!position || !bounds) return null;
+ return {
+ left: Math.max(bounds.minLeft, Math.min(bounds.maxLeft, position.left)),
+ top: Math.max(bounds.minTop, Math.min(bounds.maxTop, position.top))
+ };
+ }
+ function currentLensPosition() {
+ var bounds = lensPlacementBounds();
+ if (!bounds) return null;
+ var rect = chip.getBoundingClientRect();
+ return clampLensPosition({
+ left: rect.left - bounds.containerRect.left,
+ top: rect.top - bounds.containerRect.top
+ }, bounds);
+ }
+ function applyManualLensPosition(position) {
+ if (!manualLensPlacementAvailable()) return false;
+ var bounds = lensPlacementBounds();
+ var clamped = clampLensPosition(position, bounds);
+ if (!clamped) return false;
+ manualLensPosition = clamped;
+ chip.setAttribute('data-manual-placement', 'true');
+ chip.style.left = Math.round(clamped.left) + 'px';
+ chip.style.top = Math.round(clamped.top) + 'px';
+ if (Archify.radar && typeof Archify.radar.sync === 'function') Archify.radar.sync();
+ return true;
+ }
+ function resetLensPlacement(options) {
+ options = options || {};
+ manualLensPosition = null;
+ chip.removeAttribute('data-manual-placement');
+ chip.style.removeProperty('left');
+ chip.style.removeProperty('top');
+ if (options.reposition !== false && !chip.hidden) requestLensPlacement();
+ }
+ function beginLensDrag(event) {
+ if (!manualLensPlacementAvailable() || event.button !== 0 || lensDrag) return;
+ var start = currentLensPosition();
+ if (!start) return;
+ event.preventDefault();
+ event.stopPropagation();
+ lensDrag = {
+ pointerId: event.pointerId,
+ originX: event.clientX,
+ originY: event.clientY,
+ start: start,
+ previousManual: manualLensPosition ? { left: manualLensPosition.left, top: manualLensPosition.top } : null,
+ moved: false
+ };
+ chip.setAttribute('data-panel-dragging', 'true');
+ try { moveBtn.setPointerCapture(event.pointerId); } catch (_) {}
+ }
+ function moveLensDrag(event) {
+ if (!lensDrag || lensDrag.pointerId !== event.pointerId) return;
+ var dx = event.clientX - lensDrag.originX;
+ var dy = event.clientY - lensDrag.originY;
+ if (!lensDrag.moved && Math.hypot(dx, dy) <= 3) return;
+ lensDrag.moved = true;
+ event.preventDefault();
+ event.stopPropagation();
+ applyManualLensPosition({ left: lensDrag.start.left + dx, top: lensDrag.start.top + dy });
+ }
+ function finishLensDrag(event, cancel) {
+ if (!lensDrag || lensDrag.pointerId !== event.pointerId) return;
+ event.preventDefault();
+ event.stopPropagation();
+ var activeDrag = lensDrag;
+ lensDrag = null;
+ if (activeDrag.moved) lensDragClickPointer = activeDrag.pointerId;
+ chip.removeAttribute('data-panel-dragging');
+ try { moveBtn.releasePointerCapture(event.pointerId); } catch (_) {}
+ if (!cancel) return;
+ manualLensPosition = activeDrag.previousManual
+ ? { left: activeDrag.previousManual.left, top: activeDrag.previousManual.top }
+ : null;
+ if (manualLensPosition && manualLensPlacementAvailable()) {
+ applyManualLensPosition(manualLensPosition);
+ } else {
+ chip.removeAttribute('data-manual-placement');
+ chip.style.removeProperty('left');
+ chip.style.removeProperty('top');
+ if (!chip.hidden) requestLensPlacement();
+ }
+ }
+ function moveLensWithKeyboard(event) {
+ if (event.key === 'Home') {
+ event.preventDefault();
+ resetLensPlacement();
+ return;
+ }
+ if (event.metaKey || event.ctrlKey || event.altKey || !manualLensPlacementAvailable()) return;
+ var directions = {
+ ArrowLeft: [-1, 0],
+ ArrowRight: [1, 0],
+ ArrowUp: [0, -1],
+ ArrowDown: [0, 1]
+ };
+ var direction = directions[event.key];
+ if (!direction) return;
+ event.preventDefault();
+ var current = manualLensPosition || currentLensPosition();
+ if (!current) return;
+ var distance = event.shiftKey ? 4 : 16;
+ applyManualLensPosition({
+ left: current.left + direction[0] * distance,
+ top: current.top + direction[1] * distance
+ });
+ }
var lensFrame = 0;
function placeRelationshipLens() {
- lensFrame = 0;
+ if (lensFrame) {
+ cancelAnimationFrame(lensFrame);
+ lensFrame = 0;
+ }
if (chip.hidden || activeIds.length !== 1) return;
var node = svg.querySelector('[data-node-id="' + activeIds[0] + '"]');
if (!node) return;
@@ -8571,8 +9667,15 @@
var visibleBottom = Math.min(containerRect.height - padding, window.innerHeight - containerRect.top - padding);
var maxTop = Math.max(padding, visibleBottom - chip.offsetHeight);
var minTop = Math.min(visibleTop, maxTop);
- var nodeCenter = nodeRect.top - containerRect.top + nodeRect.height / 2;
var mobile = window.innerWidth <= 720;
+ if (!manualLensPlacementAvailable()) {
+ chip.removeAttribute('data-manual-placement');
+ chip.style.removeProperty('left');
+ } else if (manualLensPosition) {
+ applyManualLensPosition(manualLensPosition);
+ return;
+ }
+ var nodeCenter = nodeRect.top - containerRect.top + nodeRect.height / 2;
var previewingOnMobile = mobile && chip.getAttribute('data-relationship-previewing') === 'true';
var compactOnMobile = mobile && chip.getAttribute('data-relations-expanded') !== 'true';
var preferred;
@@ -8643,6 +9746,12 @@
}
function clear(options) {
options = options || {};
+ if (lensDrag) {
+ var dragPointerId = lensDrag.pointerId;
+ lensDrag = null;
+ chip.removeAttribute('data-panel-dragging');
+ try { moveBtn.releasePointerCapture(dragPointerId); } catch (_) {}
+ }
var restoreNode = options.restoreFocus === true && activeIds.length === 1
? svg.querySelector('[data-node-id="' + activeIds[0] + '"]')
: null;
@@ -8690,7 +9799,7 @@
relationsBtn.setAttribute('aria-label', viewerText('viewer.passport.relations.show'));
relationsBtn.setAttribute('aria-expanded', 'false');
chip.removeAttribute('data-relations-expanded');
- chip.style.removeProperty('top');
+ if (options.preserveLensPlacement !== true) resetLensPlacement({ reposition: false });
if (options.preserveView !== true && Archify.view && typeof Archify.view.reset === 'function') {
Archify.view.reset({ automatic: true });
}
@@ -8713,22 +9822,28 @@
Archify.routeProbe.clear({ updateUrl: false, restoreFocus: false });
}
var nodeList = nodes();
- var byId = {};
+ var byId = Object.create(null);
nodeList.forEach(function (node) { byId[node.getAttribute('data-node-id')] = node; });
var normalized = [];
(ids || []).forEach(function (id) {
if (byId[id] && normalized.indexOf(id) === -1) normalized.push(id);
});
if (!normalized.length) return false;
+ // Hash restoration and internal selections use this path too. Reveal
+ // tree ancestors before measuring the selected node for its lens.
+ if (Archify.treeBranches && Archify.treeBranches.active) {
+ normalized.forEach(function (id) { Archify.treeBranches.reveal(id); });
+ }
if (normalized.length === activeIds.length && normalized.every(function (id, index) { return activeIds[index] === id; }) && options.toggle !== false) {
clear();
return true;
}
- clear({ updateUrl: false, preserveView: true });
+ var preserveLensPlacement = activeIds.length === 1 && normalized.length === 1 && !chip.hidden;
+ clear({ updateUrl: false, preserveView: true, preserveLensPlacement: preserveLensPlacement });
activeIds = normalized;
- var selected = {};
- var related = {};
+ var selected = Object.create(null);
+ var related = Object.create(null);
var seenEdges = {};
var matchedEdges = 0;
normalized.forEach(function (id) { selected[id] = true; related[id] = true; });
@@ -8755,12 +9870,12 @@
svg.setAttribute('data-focus-active', normalized.join(' '));
var defaultLabel = normalized.length === 1
? nodeLabel(byId[normalized[0]], normalized[0])
- : viewerText('viewer.guided.chapter.selectedNodes', { count: normalized.length });
+ : viewerText('viewer.focus.selectedNodes', { count: normalized.length });
label.textContent = options.label || defaultLabel;
chip.hidden = options.hideChip === true || normalized.length !== 1 || selectionMode;
if (!chip.hidden) {
renderRelationshipLens(normalized[0], byId);
- requestLensPlacement();
+ placeRelationshipLens();
}
if (options.updateUrl !== false) {
var key = options.urlKey || 'focus';
@@ -8776,31 +9891,14 @@
return setMany([id], options);
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
-
function copyFocusLink() {
if (activeIds.length !== 1) return Promise.resolve(false);
var record = pinnedRelationshipRecord();
var relationId = record && record.id;
- var value = location.href.replace(/#.*$/, '') + (relationId
- ? '#relation=' + encodeURIComponent(relationId)
- : '#focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink(relationId
+ ? 'relation=' + encodeURIComponent(relationId)
+ : 'focus=' + encodeURIComponent(activeIds[0]) + (reachabilityMode ? '&reach=' + reachabilityMode : ''));
+ return (value === null ? Promise.resolve(false) : copyReaderText(value)).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', copied
? viewerText(relationId ? 'viewer.passport.copy.pinned.success' : 'viewer.passport.copy.focused.success')
@@ -8834,6 +9932,17 @@
Archify.view.reveal([id], { includeNeighbors: true, reason: 'focus' });
}
});
+ moveBtn.addEventListener('pointerdown', beginLensDrag);
+ moveBtn.addEventListener('pointermove', moveLensDrag);
+ moveBtn.addEventListener('pointerup', function (event) { finishLensDrag(event, false); });
+ moveBtn.addEventListener('pointercancel', function (event) { finishLensDrag(event, true); });
+ moveBtn.addEventListener('lostpointercapture', function (event) { finishLensDrag(event, true); });
+ moveBtn.addEventListener('dblclick', function (event) {
+ event.preventDefault();
+ event.stopPropagation();
+ resetLensPlacement();
+ });
+ moveBtn.addEventListener('keydown', moveLensWithKeyboard);
clearBtn.addEventListener('click', function () { clear({ restoreFocus: true }); });
copyBtn.addEventListener('click', copyFocusLink);
upstreamBtn.addEventListener('click', function () { applyReachability('upstream'); });
@@ -8846,15 +9955,12 @@
relationsBtn.setAttribute('aria-label', viewerText(expanded
? 'viewer.passport.relations.show'
: 'viewer.passport.relations.hide'));
- requestLensPlacement();
+ placeRelationshipLens();
});
relationshipList.addEventListener('click', function (event) {
var button = event.target.closest('[data-relationship-target]');
if (!button) return;
var id = button.getAttribute('data-relationship-target');
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
set(id, { toggle: false });
if (Archify.view && typeof Archify.view.reveal === 'function') {
Archify.view.reveal([id], { includeNeighbors: true, reason: 'relationship' });
@@ -8903,16 +10009,38 @@
event.preventDefault();
buttons[index].focus();
});
+ document.addEventListener('pointerdown', function () {
+ lensDragClickPointer = null;
+ }, true);
document.addEventListener('click', function (event) {
+ // Losing capture (for example when a resize hides the handle) can
+ // retarget this drag's final click to the page. It is not dismissal.
+ // A new pointerdown releases the guard; keyboard clicks remain live.
+ if (lensDragClickPointer != null && event.detail > 0 &&
+ (event.pointerId == null || event.pointerId === lensDragClickPointer)) {
+ lensDragClickPointer = null;
+ event.preventDefault();
+ event.stopPropagation();
+ return;
+ }
var target = event.target;
if (chip.hidden || !target || typeof target.closest !== 'function' || chip.contains(target)) return;
if (container.getAttribute('data-just-panned') === 'true') return;
- if (target.closest('[data-node-id], [data-relationship-hit-key], .overview-map')) return;
+ // Export consumes the active semantic snapshot; its controls are not
+ // an outside selection. Genuine outside activation still clears it.
+ if (target.closest('[data-node-id], [data-relationship-hit-key], .overview-map, #btn-export, #export-menu')) return;
clear();
}, true);
window.addEventListener('scroll', requestLensPlacement, { passive: true });
window.addEventListener('resize', requestLensPlacement);
container.addEventListener('scroll', requestLensPlacement, { passive: true });
+ // Reader and Chrome may finish resizing the stage after window resize.
+ // The absolute Passport does not resize its container when reclamped.
+ if (typeof ResizeObserver === 'function') {
+ new ResizeObserver(function () {
+ if (!chip.hidden) requestLensPlacement();
+ }).observe(container);
+ }
document.addEventListener('visibilitychange', function () {
if (document.hidden) removeRelationshipPulse();
});
@@ -8945,7 +10073,7 @@
applyReachability(reach, { updateUrl: false, toggle: false, reveal: false });
}
}
- else if (!params.get('view')) clear({ updateUrl: false });
+ else clear({ updateUrl: false });
} catch (_) {}
}
@@ -8962,7 +10090,7 @@
reachabilitySnapshot: reachabilitySnapshot,
inspectRelationship: inspectRelationship,
inspectRelationshipById: inspectRelationshipById,
- reposition: requestLensPlacement,
+ reposition: placeRelationshipLens,
relationship: function () {
var record = pinnedRelationshipRecord();
return record ? { id: record.id || null, key: record.key, from: record.from, to: record.to, label: record.label } : null;
@@ -8980,6 +10108,7 @@
};
})();
+
/* ============================================================
Intent Trace — temporary one-hop topology before durable focus.
Fine-pointer hover and keyboard focus share the same stable-ID preview;
@@ -9017,14 +10146,13 @@
html.getAttribute('data-guide-open') === 'true' ||
container.classList.contains('is-panning') ||
svg.hasAttribute('data-lens-active') ||
- svg.hasAttribute('data-story-active') ||
svg.hasAttribute('data-relationship-preview-active') ||
!!(Archify.routeProbe && typeof Archify.routeProbe.active === 'function' && Archify.routeProbe.active()) ||
!!(Archify.focus && typeof Archify.focus.active === 'function' && Archify.focus.active());
}
function edgeShapes(edge) {
if (/^(path|line|polyline)$/i.test(edge.tagName)) return [edge];
- return Array.prototype.slice.call(edge.querySelectorAll('path, line, polyline'));
+ return Array.prototype.slice.call(edge.querySelectorAll('path:not([data-ambient-flow-overlay]), line, polyline'));
}
function removeOverlay() {
Array.prototype.forEach.call(svg.querySelectorAll('[data-intent-trace-overlay]'), function (overlay) {
@@ -9047,6 +10175,8 @@
}
function traceGeometry(shape, direction) {
var clone = shape.cloneNode(false);
+ if (shape.getAttribute('data-motion-path')) clone.setAttribute('d', shape.getAttribute('data-motion-path'));
+ clone.removeAttribute('data-motion-path');
clone.removeAttribute('id');
clone.removeAttribute('class');
clone.removeAttribute('style');
@@ -9079,7 +10209,7 @@
clear({ announce: false });
var nodeList = nodes();
var edgeList = edges();
- var byId = {};
+ var byId = Object.create(null);
nodeList.forEach(function (node) { byId[node.getAttribute('data-node-id')] = node; });
var selected = byId[id];
if (!selected) return false;
@@ -9088,7 +10218,7 @@
overlay.setAttribute('class', 'intent-trace-overlay');
overlay.setAttribute('data-intent-trace-overlay', '');
overlay.setAttribute('aria-hidden', 'true');
- var related = {};
+ var related = Object.create(null);
var seen = {};
var counts = { out: 0, in: 0, loop: 0 };
related[id] = true;
@@ -9194,1727 +10324,17 @@
};
})();
- Archify.guidedViews = (function () {
- var data = document.getElementById('archify-guided-views-data');
- var panel = document.getElementById('guided-views');
- var prev = document.getElementById('guided-view-prev');
- var next = document.getElementById('guided-view-next');
- var all = document.getElementById('guided-view-all');
- var play = document.getElementById('guided-view-play');
- var playIcon = document.getElementById('guided-view-play-icon');
- var playLabel = document.getElementById('guided-view-play-label');
- var beatLink = document.getElementById('guided-view-beat-link');
- var beatLinkLabel = document.getElementById('guided-view-beat-link-label');
- var progressBar = document.getElementById('guided-view-progress-bar');
- var count = document.getElementById('guided-view-count');
- var handoffReceipt = document.getElementById('guided-view-handoff');
- var label = document.getElementById('guided-view-label');
- var note = document.getElementById('guided-view-note');
- var trail = document.getElementById('guided-view-trail');
- var storyCaption = document.getElementById('guided-story-caption');
- var storyCaptionIndex = document.getElementById('guided-story-caption-index');
- var storyCaptionRoute = document.getElementById('guided-story-caption-route');
- var storyCaptionDetail = document.getElementById('guided-story-caption-detail');
- var storyCaptionNext = document.getElementById('guided-story-caption-next');
- var storyCaptionNextLabel = document.getElementById('guided-story-caption-next-label');
- var chapterIndex = document.getElementById('guided-view-index');
- var chapterList = document.getElementById('guided-view-chapters');
- var shareCue = document.getElementById('share-chapter-cue');
- var shareCueState = document.getElementById('share-chapter-state');
- var shareCueCount = document.getElementById('share-chapter-count');
- var shareCueLabel = document.getElementById('share-chapter-label');
- var shareCueNote = document.getElementById('share-chapter-note');
- var shareCueRoute = document.getElementById('share-chapter-route');
- var shareCueProgress = document.getElementById('share-chapter-progress-bar');
- var svg = document.querySelector('.diagram-container svg');
- var views = [];
- var activeIndex = -1;
- var playing = false;
- var storyBeatTimer = null;
- var storyBeatIndex = -1;
- var storyBeatStartedAt = 0;
- var storyBeatElapsedMs = 0;
- var storyBeatDwellMs = 0;
- var storyPlaybackGeneration = 0;
- var storyFollowGeneration = 0;
- var storyPlaybackScope = 'story';
- var storyPlaybackComplete = false;
- var beatLinkFeedbackTimer = null;
- var momentRestoreGeneration = 0;
- var storySteps = [];
- var storyPulseOwnerToken = 0;
- var storyPulseGeneration = 0;
- var autoplayPending = false;
- var VIEW_INTERVAL_MS = 3200;
- var STORY_FOLLOW_MIN_DWELL_MS = 1100;
- var STORY_FOLLOW_DURATION_MS = 320;
- var chapterButtons = [];
- var handoffGeneration = 0;
- var currentHandoff = null;
- var previewGeneration = 0;
- var pointerPreviewIntent = null;
- var focusPreviewIntent = null;
- var activePreviewIndex = -1;
- var previewOwnerToken = 0;
-
- try { views = JSON.parse(data.textContent || '[]'); } catch (_) { views = []; }
- if (!views.length) return { count: 0, active: function () { return null; } };
- var canonicalNodeIds = {};
- Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {
- canonicalNodeIds[node.getAttribute('data-node-id')] = true;
- });
- views.forEach(function (view) {
- var seen = {};
- view.focus = (view.focus || []).filter(function (id) {
- if (!canonicalNodeIds[id] || seen[id]) return false;
- seen[id] = true;
- return true;
- });
- });
- // Establish the compact cold state before exposing the panel so the
- // full Director cannot flash during first paint. Hash restoration runs
- // in the same task and replaces this state before paint when valid.
- panel.setAttribute('data-active-view', 'all');
- panel.hidden = false;
- panel.setAttribute('data-view-interval-ms', String(VIEW_INTERVAL_MS));
- panel.setAttribute('data-story-follow-min-dwell-ms', String(STORY_FOLLOW_MIN_DWELL_MS));
- buildChapterIndex();
-
- function reducedMotion() {
- return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
- }
-
- function findNode(id) {
- return Array.prototype.find.call(svg.querySelectorAll('[data-node-id]'), function (node) {
- return node.getAttribute('data-node-id') === id;
- }) || null;
- }
-
- function chapterDelta(previous, destination) {
- var previousFocus = previous ? previous.focus : [];
- var destinationFocus = destination ? destination.focus : [];
- var previousIds = {};
- var destinationIds = {};
- previousFocus.forEach(function (id) { previousIds[id] = true; });
- destinationFocus.forEach(function (id) { destinationIds[id] = true; });
- return {
- stay: previousFocus.filter(function (id) { return destinationIds[id]; }),
- enter: destinationFocus.filter(function (id) { return !previousIds[id]; }),
- leave: previousFocus.filter(function (id) { return !destinationIds[id]; })
- };
- }
-
- function chapterAnchor(previous, destination, outgoingBeatIndex, delta) {
- if (!previous || !destination) return '';
- var stayIds = {};
- delta.stay.forEach(function (id) { stayIds[id] = true; });
- var activeBeat = outgoingBeatIndex >= 0 ? previous.focus[outgoingBeatIndex] : '';
- if (activeBeat && stayIds[activeBeat]) return activeBeat;
- for (var index = previous.focus.length - 1; index >= 0; index -= 1) {
- if (stayIds[previous.focus[index]]) return previous.focus[index];
- }
- return '';
- }
-
- function handoffMotionAllowed() {
- if (document.hidden || reducedMotion()) return false;
- if (document.documentElement.getAttribute('data-embed') === 'true') return false;
- if (window.matchMedia && window.matchMedia('print').matches) return false;
- return !(Archify.motionGovernor && Archify.motionGovernor.capable && Archify.motionGovernor.isPaused());
- }
-
- function classifyHandoff(delta, anchor) {
- var roles = {};
- delta.stay.forEach(function (id) { roles[id] = 'stay'; });
- delta.enter.forEach(function (id) { roles[id] = 'enter'; });
- delta.leave.forEach(function (id) { roles[id] = 'leave'; });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {
- var id = node.getAttribute('data-node-id');
- var role = roles[id] || '';
- if (role) node.setAttribute('data-chapter-role', role);
- else node.removeAttribute('data-chapter-role');
- });
- svg.setAttribute('data-chapter-handoff', anchor ? 'anchor' : 'no-anchor');
- if (anchor) svg.setAttribute('data-chapter-anchor', anchor);
- else svg.removeAttribute('data-chapter-anchor');
- }
-
- function drawHandoffAnchor(id) {
- var node = findNode(id);
- if (!node) return null;
- var box;
- try { box = node.getBBox(); } catch (_) { return null; }
- var overlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- var ring = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
- overlay.setAttribute('class', 'chapter-handoff-overlay');
- overlay.setAttribute('data-chapter-handoff-overlay', '');
- overlay.setAttribute('aria-hidden', 'true');
- ring.setAttribute('class', 'chapter-handoff-anchor');
- ring.setAttribute('x', String(box.x - 8));
- ring.setAttribute('y', String(box.y - 8));
- ring.setAttribute('width', String(box.width + 16));
- ring.setAttribute('height', String(box.height + 16));
- ring.setAttribute('rx', '10');
- overlay.appendChild(ring);
- svg.appendChild(overlay);
- return overlay;
- }
-
- function clearHandoffPresentation() {
- svg.removeAttribute('data-chapter-handoff');
- svg.removeAttribute('data-chapter-anchor');
- Array.prototype.forEach.call(svg.querySelectorAll('[data-chapter-handoff-overlay]'), function (overlay) { overlay.remove(); });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-chapter-role]'), function (node) { node.removeAttribute('data-chapter-role'); });
- if (handoffReceipt) {
- handoffReceipt.hidden = true;
- handoffReceipt.textContent = '';
- }
- }
-
- function completeHandoff(handoff, outcome) {
- if (!handoff || currentHandoff !== handoff) return false;
- if (handoff.holdTimer) clearTimeout(handoff.holdTimer);
- handoff.holdTimer = null;
- currentHandoff = null;
- clearHandoffPresentation();
- if (handoff.ownerToken && Archify.motionGovernor) Archify.motionGovernor.release(handoff.ownerToken);
- handoff.resolve({ id: handoff.id, state: outcome || 'complete', anchor: handoff.anchor || null });
- syncStoryControlsDisabled();
- syncChapterPreview();
- return true;
- }
-
- function settleHandoff(reason) {
- var handoff = currentHandoff;
- if (!handoff) return false;
- if (handoff.holdTimer) clearTimeout(handoff.holdTimer);
- handoff.holdTimer = null;
- if (handoff.camera && handoff.camera.cancel) handoff.camera.cancel(reason || 'settled', true);
- else if (Archify.view && Archify.view.reveal) Archify.view.reveal(handoff.focus, { instant: true, reason: reason || 'settled' });
- completeHandoff(handoff, reason || 'settled');
- return true;
- }
-
- function cancelHandoff(reason) {
- var handoff = currentHandoff;
- if (!handoff) return false;
- if (handoff.holdTimer) clearTimeout(handoff.holdTimer);
- handoff.holdTimer = null;
- if (handoff.camera && handoff.camera.cancel) handoff.camera.cancel(reason || 'manual', false);
- completeHandoff(handoff, reason || 'manual');
- return true;
- }
-
- function afterHandoff(callback) {
- if (!currentHandoff) { callback(); return; }
- currentHandoff.finished.then(callback);
- }
-
- function beginHandoff(previousIndex, nextIndex, previous, destination, outgoingBeatIndex, reason) {
- if (!Archify.view || !Archify.view.reveal) return null;
- if (!previous || previousIndex === nextIndex) {
- Archify.view.reveal(destination.focus, { reason: reason });
- return null;
- }
- var delta = chapterDelta(previous, destination);
- var anchor = chapterAnchor(previous, destination, outgoingBeatIndex, delta);
- if (!handoffMotionAllowed()) {
- Archify.view.reveal(destination.focus, { instant: true, reason: reason });
- return null;
- }
- var resolver;
- var handoff = {
- id: ++handoffGeneration,
- mode: anchor ? 'holding' : 'no-anchor',
- anchor: anchor,
- focus: destination.focus.slice(),
- holdTimer: null,
- camera: null,
- ownerToken: 0,
- finished: new Promise(function (resolve) { resolver = resolve; }),
- resolve: resolver
- };
- currentHandoff = handoff;
- classifyHandoff(delta, anchor);
- if (anchor) {
- drawHandoffAnchor(anchor);
- var node = findNode(anchor);
- var nodeLabel = node ? (node.getAttribute('data-node-label') || anchor) : anchor;
- handoffReceipt.textContent = viewerText('viewer.guided.handoff', {
- from: (previousIndex + 1 < 10 ? '0' : '') + (previousIndex + 1),
- to: (nextIndex + 1 < 10 ? '0' : '') + (nextIndex + 1),
- label: nodeLabel
- });
- handoffReceipt.hidden = false;
- }
- if (Archify.motionGovernor) {
- handoff.ownerToken = Archify.motionGovernor.claim('handoff', function () {
- if (currentHandoff === handoff) settleHandoff('preempted');
- });
- }
- var startCamera = function () {
- if (currentHandoff !== handoff) return;
- handoff.holdTimer = null;
- handoff.mode = 'settling';
- svg.setAttribute('data-chapter-handoff', anchor ? 'settling' : 'no-anchor');
- handoff.camera = Archify.view.reveal(destination.focus, { reason: reason, duration: 420 });
- if (handoff.camera && handoff.camera.finished) {
- handoff.camera.finished.then(function (outcome) {
- if (currentHandoff === handoff) completeHandoff(handoff, outcome && outcome.state || 'complete');
- });
- } else {
- completeHandoff(handoff, 'complete');
- }
- };
- if (anchor) handoff.holdTimer = setTimeout(startCamera, 110);
- else startCamera();
- return handoff;
- }
-
- function centerChapterButton(button) {
- if (!button || !chapterList) return false;
- var target = Math.max(0, button.offsetLeft - (chapterList.clientWidth - button.offsetWidth) / 2);
- if (typeof chapterList.scrollTo === 'function') chapterList.scrollTo({ left: target, behavior: 'auto' });
- else chapterList.scrollLeft = target;
- return true;
- }
-
- function focusChapterButton(index) {
- if (!chapterButtons.length) return false;
- index = Math.max(0, Math.min(chapterButtons.length - 1, index));
- chapterButtons.forEach(function (button, buttonIndex) {
- button.setAttribute('tabindex', buttonIndex === index ? '0' : '-1');
- });
- chapterButtons[index].focus();
- centerChapterButton(chapterButtons[index]);
- return true;
- }
-
- function buildChapterIndex() {
- chapterButtons = [];
- chapterList.textContent = '';
- views.forEach(function (view, index) {
- var item = document.createElement('li');
- var button = document.createElement('button');
- button.type = 'button';
- button.className = 'guided-view-chapter';
- button.setAttribute('data-guided-view-id', view.id);
- button.setAttribute('aria-pressed', 'false');
- button.setAttribute('tabindex', index === 0 ? '0' : '-1');
- button.setAttribute('aria-label', viewerText('viewer.guided.chapter.open', {
- index: index + 1,
- total: views.length,
- label: view.label,
- count: view.focus.length
- }));
- button.title = view.label + ' — ' + (view.note || viewerText('viewer.guided.chapter.selectedNodes', { count: view.focus.length }));
- var position = document.createElement('span');
- position.className = 'guided-view-chapter-index';
- position.setAttribute('aria-hidden', 'true');
- position.textContent = (index + 1 < 10 ? '0' : '') + (index + 1);
- var title = document.createElement('span');
- title.className = 'guided-view-chapter-title';
- title.textContent = view.label;
- var stops = document.createElement('em');
- stops.className = 'guided-view-chapter-count';
- stops.textContent = viewerCount('viewer.guided.chapter.stop', view.focus.length);
- var delta = document.createElement('span');
- delta.className = 'guided-view-chapter-delta';
- delta.hidden = true;
- delta.setAttribute('aria-hidden', 'true');
- ['stay', 'enter', 'leave'].forEach(function (kind) {
- var value = document.createElement('span');
- value.setAttribute('data-delta-kind', kind);
- delta.appendChild(value);
- });
- button.appendChild(position);
- button.appendChild(title);
- button.appendChild(stops);
- button.appendChild(delta);
- item.appendChild(button);
- chapterList.appendChild(item);
- chapterButtons.push(button);
- });
- }
-
- function syncChapterIndex() {
- chapterButtons.forEach(function (button, index) {
- var current = index === activeIndex;
- var stops = button.querySelector('.guided-view-chapter-count');
- var deltaLabel = button.querySelector('.guided-view-chapter-delta');
- var position = activeIndex < 0 ? 'available' : (current ? 'current' : (index < activeIndex ? 'before' : 'after'));
- button.setAttribute('data-chapter-position', position);
- button.setAttribute('aria-pressed', current ? 'true' : 'false');
- button.setAttribute('tabindex', current || (activeIndex < 0 && index === 0) ? '0' : '-1');
- if (current) {
- stops.hidden = false;
- deltaLabel.hidden = true;
- button.removeAttribute('data-chapter-delta');
- button.setAttribute('aria-label', viewerText('viewer.guided.chapter.current', {
- index: index + 1,
- total: views.length,
- label: views[index].label,
- count: views[index].focus.length
- }));
- button.title = viewerText('viewer.guided.chapter.current.title', {
- label: views[index].label,
- count: views[index].focus.length
- });
- } else {
- var delta = chapterDelta(activeIndex >= 0 ? views[activeIndex] : null, views[index]);
- var compact = '=' + delta.stay.length + ' +' + delta.enter.length + ' \u2212' + delta.leave.length;
- var expanded = viewerText('viewer.guided.chapter.delta.expanded', {
- stay: delta.stay.length,
- enter: delta.enter.length,
- leave: delta.leave.length
- });
- stops.hidden = true;
- deltaLabel.hidden = false;
- deltaLabel.querySelector('[data-delta-kind="stay"]').textContent = '=' + delta.stay.length;
- deltaLabel.querySelector('[data-delta-kind="enter"]').textContent = '+' + delta.enter.length;
- deltaLabel.querySelector('[data-delta-kind="leave"]').textContent = '\u2212' + delta.leave.length;
- button.setAttribute('data-chapter-delta', compact);
- button.setAttribute('aria-label', viewerText('viewer.guided.chapter.delta.aria', {
- index: index + 1,
- total: views.length,
- label: views[index].label,
- delta: expanded
- }));
- button.title = viewerText('viewer.guided.chapter.delta.title', {
- label: views[index].label,
- delta: compact
- });
- }
- if (current) button.setAttribute('aria-current', 'step');
- else button.removeAttribute('aria-current');
- if (button.parentElement) button.parentElement.setAttribute('data-chapter-position', position);
- });
- if (activeIndex >= 0) centerChapterButton(chapterButtons[activeIndex]);
- }
-
- function chapterPreviewBlocked() {
- if (document.hidden || playing || currentHandoff) return true;
- if (document.documentElement.getAttribute('data-embed') === 'true') return true;
- if (window.matchMedia && window.matchMedia('print').matches) return true;
- if (svg.hasAttribute('data-route-picking') || svg.hasAttribute('data-route-active')) return true;
- if (svg.hasAttribute('data-lens-active') || svg.hasAttribute('data-legend-preview-active')) return true;
- if (svg.hasAttribute('data-relationship-preview-active') || svg.hasAttribute('data-intent-trace-active')) return true;
- return activeIndex < 0 && svg.hasAttribute('data-focus-active');
- }
-
- function clearChapterPreviewPresentation() {
- svg.removeAttribute('data-chapter-preview');
- Array.prototype.forEach.call(svg.querySelectorAll('[data-chapter-preview-role]'), function (node) {
- node.removeAttribute('data-chapter-preview-role');
- });
- chapterButtons.forEach(function (button) { button.removeAttribute('data-preview-active'); });
- activePreviewIndex = -1;
- if (previewOwnerToken && Archify.motionGovernor) {
- var token = previewOwnerToken;
- previewOwnerToken = 0;
- Archify.motionGovernor.release(token);
- }
- }
-
- function clearChapterPreview(options) {
- options = options || {};
- previewGeneration += 1;
- if (options.clearIntents !== false) {
- pointerPreviewIntent = null;
- focusPreviewIntent = null;
- }
- clearChapterPreviewPresentation();
- return true;
- }
-
- function winningChapterPreviewIntent() {
- return [pointerPreviewIntent, focusPreviewIntent].filter(function (intent) {
- return intent && intent.index >= 0 && intent.index < views.length && intent.index !== activeIndex;
- }).sort(function (left, right) { return right.generation - left.generation; })[0] || null;
- }
-
- function showChapterPreview(index) {
- if (index < 0 || index >= views.length || index === activeIndex || chapterPreviewBlocked()) {
- clearChapterPreviewPresentation();
- return false;
- }
- if (activePreviewIndex === index && svg.getAttribute('data-chapter-preview') === views[index].id) return true;
- clearChapterPreviewPresentation();
- var delta = chapterDelta(activeIndex >= 0 ? views[activeIndex] : null, views[index]);
- var roles = {};
- delta.stay.forEach(function (id) { roles[id] = 'stay'; });
- delta.enter.forEach(function (id) { roles[id] = 'enter'; });
- delta.leave.forEach(function (id) { roles[id] = 'leave'; });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {
- var role = roles[node.getAttribute('data-node-id')];
- if (role) node.setAttribute('data-chapter-preview-role', role);
- });
- svg.setAttribute('data-chapter-preview', views[index].id);
- chapterButtons[index].setAttribute('data-preview-active', 'true');
- activePreviewIndex = index;
- if (Archify.motionGovernor && Archify.motionGovernor.capable) {
- previewOwnerToken = Archify.motionGovernor.claim('chapter-preview', function () {
- previewOwnerToken = 0;
- clearChapterPreviewPresentation();
- });
- }
- return true;
- }
-
- function syncChapterPreview() {
- var intent = winningChapterPreviewIntent();
- if (!intent || chapterPreviewBlocked()) {
- clearChapterPreviewPresentation();
- return false;
- }
- return showChapterPreview(intent.index);
- }
-
- function setChapterPreviewIntent(source, index) {
- var intent = { index: index, generation: ++previewGeneration };
- if (source === 'pointer') pointerPreviewIntent = intent;
- else focusPreviewIntent = intent;
- if (playing) pausePlayback();
- return syncChapterPreview();
- }
-
- function clearChapterPreviewIntent(source, index) {
- var intent = source === 'pointer' ? pointerPreviewIntent : focusPreviewIntent;
- if (intent && (typeof index !== 'number' || intent.index === index)) {
- if (source === 'pointer') pointerPreviewIntent = null;
- else focusPreviewIntent = null;
- previewGeneration += 1;
- }
- return syncChapterPreview();
- }
-
- function hoverCapable() {
- return !!(window.matchMedia && window.matchMedia('(hover: hover)').matches);
- }
-
- function sharePlaybackRequested() {
- try { return new URLSearchParams(location.search).get('play') === '1'; }
- catch (_) { return false; }
- }
-
- autoplayPending = sharePlaybackRequested();
- if (autoplayPending) {
- document.documentElement.setAttribute('data-share-playback', 'true');
- setAutoplayState('pending');
- }
-
- function setAutoplayState(state) {
- if (state) panel.setAttribute('data-autoplay', state);
- else panel.removeAttribute('data-autoplay');
- renderShareCue();
- }
-
- function shareCueStatus(state) {
- return {
- pending: viewerText('viewer.guided.state.ready'),
- playing: viewerText('viewer.guided.state.playing'),
- complete: viewerText('viewer.guided.state.settled'),
- interrupted: viewerText('viewer.guided.state.paused'),
- pinned: viewerText('viewer.guided.state.pinned'),
- 'reduced-motion': viewerText('viewer.guided.state.still')
- }[state] || viewerText('viewer.guided.state.ready');
- }
-
- function shareCueBeatCopy(state, view, stops) {
- var total = stops.length;
- var activeStop = storyBeatIndex >= 0 ? stops[storyBeatIndex] : null;
- if ((state === 'playing' || state === 'interrupted') && activeStop) {
- return viewerText('viewer.guided.share.step', {
- index: (storyBeatIndex + 1 < 10 ? '0' : '') + (storyBeatIndex + 1),
- total: (total < 10 ? '0' : '') + total,
- label: activeStop.textContent
- });
- }
- if (state === 'pinned' && activeStop) {
- return storyBeatCopy(storySteps[storyBeatIndex], total);
- }
- if (state === 'reduced-motion' && activeStop && hashBeatMatchesCurrent()) {
- return viewerText('viewer.guided.share.staticMoment', {
- step: viewerText('viewer.guided.share.step', {
- index: (storyBeatIndex + 1 < 10 ? '0' : '') + (storyBeatIndex + 1),
- total: (total < 10 ? '0' : '') + total,
- label: activeStop.textContent
- })
- });
- }
- if (state === 'complete') return viewerText('viewer.guided.share.complete', {
- count: total,
- note: view.note || viewerText('viewer.guided.share.settled')
- });
- if (state === 'reduced-motion') return viewerText('viewer.guided.share.staticPath', { count: total });
- if (state === 'pending') return viewerText('viewer.guided.share.ready', { count: total });
- return view.note || viewerText('viewer.guided.chapter.selectedNodes', { count: view.focus.length });
- }
-
- function renderShareCue() {
- if (!shareCue) return;
- var view = activeIndex >= 0 ? views[activeIndex] : null;
- var shareMode = document.documentElement.getAttribute('data-share-playback') === 'true';
- var embedMode = document.documentElement.getAttribute('data-embed') === 'true';
- var pinnedMode = !shareMode && embedMode && hashBeatMatchesCurrent();
- if (pinnedMode) document.documentElement.setAttribute('data-share-moment', 'true');
- else document.documentElement.removeAttribute('data-share-moment');
- shareCue.hidden = !(embedMode && view && (shareMode || pinnedMode));
- if (shareCue.hidden) return;
- var state = pinnedMode ? 'pinned' : (panel.getAttribute('data-autoplay') || 'pending');
- var stops = Array.prototype.slice.call(trail.querySelectorAll('[data-story-node]'));
- var route = stops.map(function (stop, index) {
- if (index === 0) return stop.textContent;
- var kind = stop.getAttribute('data-story-link');
- var separator = kind === 'forward' ? '\u2192' : (kind === 'reverse' ? '\u2190' : (kind === 'multiple' ? '\u21c4' : '\u00b7'));
- return separator + ' ' + stop.textContent;
- }).join(' ');
- var beatCopy = shareCueBeatCopy(state, view, stops);
- shareCue.setAttribute('data-state', state);
- shareCue.setAttribute('aria-live', state === 'playing' ? 'off' : 'polite');
- shareCueState.textContent = shareCueStatus(state);
- shareCueCount.textContent = viewerText('viewer.guided.share.chapter', {
- index: (activeIndex + 1 < 10 ? '0' : '') + (activeIndex + 1),
- total: (views.length < 10 ? '0' : '') + views.length
- });
- shareCueLabel.textContent = view.label;
- shareCueNote.textContent = beatCopy;
- shareCueRoute.textContent = route;
- shareCue.setAttribute('aria-label', viewerText('viewer.guided.share.aria', {
- state: shareCueStatus(state),
- index: activeIndex + 1,
- total: views.length,
- label: view.label,
- beat: beatCopy,
- route: route
- }));
- }
-
- function setShareCueProgress(fraction) {
- if (!shareCueProgress) return;
- shareCueProgress.style.animation = 'none';
- shareCueProgress.style.setProperty('--guided-progress-start', String(Math.max(0, Math.min(1, fraction))));
- shareCueProgress.style.transform = 'scaleX(' + Math.max(0, Math.min(1, fraction)) + ')';
- }
-
- function startShareCueProgress(fraction, duration) {
- if (!shareCueProgress) return;
- setShareCueProgress(fraction || 0);
- void shareCueProgress.offsetWidth;
- shareCueProgress.style.animation = 'archify-guided-progress ' + Math.max(1, duration || VIEW_INTERVAL_MS) + 'ms linear forwards';
- }
-
- function storyNodeLabel(node, fallback) {
- if (!node) return fallback;
- return node.getAttribute('data-node-label') ||
- (node.getAttribute('aria-label') || fallback).replace(/^Focus\s+/, '');
- }
-
- function storyEdgeKey(edge) {
- return edge.getAttribute('data-edge-key') || (
- edge.getAttribute('data-edge-from') + '\u0000' +
- edge.getAttribute('data-edge-to') + '\u0000' +
- (edge.getAttribute('data-edge-label') || '')
- );
- }
-
- function uniqueStoryEdges(edgeList) {
- var positions = {};
- var unique = [];
- edgeList.forEach(function (edge) {
- var key = storyEdgeKey(edge);
- if (!Object.prototype.hasOwnProperty.call(positions, key)) {
- positions[key] = unique.length;
- unique.push(edge);
- return;
- }
- var index = positions[key];
- if (!storyGeometry(unique[index]).length && storyGeometry(edge).length) unique[index] = edge;
- });
- return unique;
- }
-
- function storyStep(view, index, edgeList, byId) {
- var id = view.focus[index];
- var node = byId[id];
- var previousId = index > 0 ? view.focus[index - 1] : '';
- var forward = [];
- var reverse = [];
- if (previousId) {
- edgeList.forEach(function (edge) {
- var from = edge.getAttribute('data-edge-from');
- var to = edge.getAttribute('data-edge-to');
- if (from === previousId && to === id) forward.push(edge);
- else if (from === id && to === previousId) reverse.push(edge);
- });
- }
- forward = uniqueStoryEdges(forward);
- reverse = uniqueStoryEdges(reverse);
- var edges = forward.concat(reverse).sort(function (left, right) {
- return edgeList.indexOf(left) - edgeList.indexOf(right);
- });
- var relation = index === 0 ? 'start' : (!edges.length ? 'group' : (
- edges.length === 1 && forward.length === 1 ? 'forward' :
- (edges.length === 1 && reverse.length === 1 ? 'reverse' : 'multiple')
- ));
- return {
- index: index,
- nodeId: id,
- nodeLabel: storyNodeLabel(byId[id], id),
- previousId: previousId,
- previousLabel: previousId ? storyNodeLabel(byId[previousId], previousId) : '',
- relation: relation,
- edges: edges,
- edgeKeys: edges.map(storyEdgeKey),
- edgeLabels: edges.map(function (edge) { return edge.getAttribute('data-edge-label') || ''; }).filter(function (value, edgeIndex, values) {
- return value && values.indexOf(value) === edgeIndex;
- }),
- responsibility: node ? (node.getAttribute('data-node-sublabel') || '') : '',
- context: node ? (node.getAttribute('data-node-context') || '') : ''
- };
- }
-
- function storyBeatCopy(step, total) {
- if (!step) return '';
- var position = (step.index + 1 < 10 ? '0' : '') + (step.index + 1);
- var countValue = (total < 10 ? '0' : '') + total;
- if (step.relation === 'start') return viewerText('viewer.guided.beat.start', { index: position, total: countValue, label: step.nodeLabel });
- if (step.relation === 'forward') return viewerText('viewer.guided.beat.forward', { index: position, total: countValue, from: step.previousLabel, to: step.nodeLabel });
- if (step.relation === 'reverse') return viewerText('viewer.guided.beat.reverse', { index: position, total: countValue, from: step.nodeLabel, to: step.previousLabel });
- if (step.relation === 'multiple') return viewerText('viewer.guided.beat.multiple', { index: position, total: countValue, from: step.previousLabel, to: step.nodeLabel, count: step.edges.length });
- return viewerText('viewer.guided.beat.group', { index: position, total: countValue, from: step.previousLabel, to: step.nodeLabel });
- }
-
- function storyBeatAria(step, total) {
- var prefix = viewerText('viewer.guided.beat.aria.prefix', { index: step.index + 1, total: total, label: step.nodeLabel });
- if (step.relation === 'start') return prefix + viewerText('viewer.guided.beat.aria.start');
- if (step.relation === 'forward') return prefix + viewerText('viewer.guided.beat.aria.forward', { from: step.previousLabel });
- if (step.relation === 'reverse') return prefix + viewerText('viewer.guided.beat.aria.reverse', { from: step.previousLabel, to: step.nodeLabel });
- if (step.relation === 'multiple') return prefix + viewerText('viewer.guided.beat.aria.multiple', { from: step.previousLabel, count: step.edges.length });
- return prefix + viewerText('viewer.guided.beat.aria.group', { from: step.previousLabel });
- }
-
- function storyCaptionRouteCopy(step) {
- if (step.relation === 'start') return step.nodeLabel + ' · ' + viewerText('viewer.guided.caption.start');
- if (step.relation === 'reverse') return step.previousLabel + ' ← ' + step.nodeLabel;
- if (step.relation === 'multiple') return step.previousLabel + ' ⇄ ' + step.nodeLabel;
- if (step.relation === 'group') return step.previousLabel + ' · ' + step.nodeLabel;
- return step.previousLabel + ' → ' + step.nodeLabel;
- }
-
- function storyCaptionDetailCopy(step) {
- var facts = [];
- if (step.relation === 'group') facts.push(viewerText('viewer.guided.caption.grouped'));
- else if (step.edgeLabels.length) facts.push(step.edgeLabels.slice(0, 3).join(' + ') + (step.edgeLabels.length > 3 ? viewerText('viewer.guided.caption.more', { count: step.edgeLabels.length - 3 }) : ''));
- else if (step.relation === 'reverse') facts.push(viewerText('viewer.guided.caption.reverse'));
- else if (step.relation === 'multiple') facts.push(viewerText('viewer.guided.caption.relationships', { count: step.edges.length }));
- else if (step.relation !== 'start') facts.push(viewerText('viewer.guided.caption.relationship'));
- if (step.relation === 'reverse') facts.push(viewerText('viewer.guided.caption.direction', { from: step.nodeLabel, to: step.previousLabel }));
- if (step.responsibility) facts.push(step.responsibility);
- if (step.context) facts.push(step.context);
- if (!facts.length) facts.push(viewerText('viewer.guided.caption.starting'));
- return facts.join(' · ');
- }
-
- function renderStoryCaption(step, total, nextStep) {
- if (!storyCaption) return;
- if (!step) {
- storyCaption.hidden = true;
- storyCaption.removeAttribute('data-story-caption');
- storyCaptionNext.hidden = true;
- storyCaptionNextLabel.textContent = '';
- return;
- }
- storyCaption.hidden = false;
- storyCaption.setAttribute('data-story-caption', step.relation);
- storyCaption.setAttribute('aria-live', playing ? 'off' : 'polite');
- storyCaptionIndex.textContent = (step.index + 1 < 10 ? '0' : '') + (step.index + 1) + ' / ' + (total < 10 ? '0' : '') + total;
- storyCaptionRoute.textContent = storyCaptionRouteCopy(step);
- storyCaptionDetail.textContent = storyCaptionDetailCopy(step);
- storyCaptionNext.hidden = !nextStep;
- storyCaptionNextLabel.textContent = nextStep
- ? ((nextStep.index + 1 < 10 ? '0' : '') + (nextStep.index + 1) + ' · ' + nextStep.nodeLabel)
- : '';
- storyCaption.style.animation = 'none';
- void storyCaption.offsetWidth;
- storyCaption.style.removeProperty('animation');
- }
-
- function storyMomentLink() {
- var view = activeIndex >= 0 ? views[activeIndex] : null;
- var step = storyBeatIndex >= 0 ? storySteps[storyBeatIndex] : null;
- if (!view || !step) return '';
- var url = new URL(location.href);
- url.searchParams.delete('play');
- url.hash = 'view=' + encodeURIComponent(view.id) + '&beat=' + encodeURIComponent(step.nodeId);
- return url.href;
- }
-
- function fallbackCopyStoryMoment(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
-
- function resetBeatLinkFeedback() {
- if (beatLinkFeedbackTimer) clearTimeout(beatLinkFeedbackTimer);
- beatLinkFeedbackTimer = null;
- beatLink.removeAttribute('data-copy-state');
- beatLinkLabel.textContent = viewerText('viewer.guided.copyMoment');
- }
-
- function syncBeatLink() {
- var step = storyBeatIndex >= 0 ? storySteps[storyBeatIndex] : null;
- var available = !!(activeIndex >= 0 && step && !currentHandoff);
- beatLink.disabled = !available;
- if (!beatLink.hasAttribute('data-copy-state')) beatLinkLabel.textContent = viewerText('viewer.guided.copyMoment');
- var description = available
- ? viewerText('viewer.guided.beatLink', { index: step.index + 1, total: storySteps.length, label: step.nodeLabel })
- : viewerText('viewer.guided.selectBeatLink');
- beatLink.setAttribute('aria-label', description);
- beatLink.title = description;
- }
-
- function setBeatLinkFeedback(copied) {
- resetBeatLinkFeedback();
- beatLink.setAttribute('data-copy-state', copied ? 'copied' : 'failed');
- beatLinkLabel.textContent = viewerText(copied ? 'viewer.guided.copied' : 'viewer.guided.copyFailed');
- beatLink.setAttribute('aria-label', viewerText(copied ? 'viewer.guided.momentCopied' : 'viewer.guided.momentCopyFailed'));
- beatLinkFeedbackTimer = setTimeout(function () {
- resetBeatLinkFeedback();
- syncBeatLink();
- }, 1600);
- }
-
- function copyStoryMomentLink() {
- if (playing) pausePlayback();
- var value = storyMomentLink();
- if (!value) return Promise.resolve(false);
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopyStoryMoment(value); })
- : Promise.resolve(fallbackCopyStoryMoment(value));
- return copy.then(function (copied) {
- setBeatLinkFeedback(copied);
- return copied;
- });
- }
-
- function hashBeatMatchesCurrent() {
- var view = activeIndex >= 0 ? views[activeIndex] : null;
- var step = storyBeatIndex >= 0 ? storySteps[storyBeatIndex] : null;
- if (!view || !step) return false;
- try {
- var params = new URLSearchParams(location.hash.replace(/^#/, ''));
- return params.get('view') === view.id && params.get('beat') === step.nodeId;
- } catch (_) { return false; }
- }
-
- function storyMotionAllowed() {
- if (document.hidden || reducedMotion()) return false;
- if (document.documentElement.getAttribute('data-motion') !== 'live') return false;
- if (document.documentElement.getAttribute('data-embed') === 'true' &&
- document.documentElement.getAttribute('data-share-playback') !== 'true') return false;
- if (window.matchMedia && window.matchMedia('print').matches) return false;
- return !(Archify.motionGovernor && Archify.motionGovernor.isPaused());
- }
-
- function storyAutomaticPlaybackAllowed() {
- if (document.hidden || reducedMotion()) return false;
- if (window.matchMedia && window.matchMedia('print').matches) return false;
- if (Archify.motionGovernor && Archify.motionGovernor.capable) return !Archify.motionGovernor.isPaused();
- return true;
- }
-
- function clearStoryPulse(options) {
- options = options || {};
- storyPulseGeneration += 1;
- Array.prototype.forEach.call(svg.querySelectorAll('.story-trail-flow[data-story-pulse]'), function (flow) {
- flow.removeAttribute('data-story-pulse');
- });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-carrier-overlay]'), function (overlay) {
- overlay.remove();
- });
- if (storyPulseOwnerToken && options.release !== false && Archify.motionGovernor) {
- var token = storyPulseOwnerToken;
- storyPulseOwnerToken = 0;
- Archify.motionGovernor.release(token);
- } else if (options.release === false) storyPulseOwnerToken = 0;
- }
-
- function pulseStoryStep(step) {
- clearStoryPulse();
- if (!step || (step.relation !== 'forward' && step.relation !== 'reverse') || step.edges.length !== 1 || !storyMotionAllowed()) return false;
- var flows = Array.prototype.slice.call(svg.querySelectorAll('.story-trail-flow[data-story-beat-step="' + step.index + '"]'));
- if (!flows.length) return false;
- var pulseGeneration = storyPulseGeneration;
- if (Archify.motionGovernor && Archify.motionGovernor.capable) {
- storyPulseOwnerToken = Archify.motionGovernor.claim('story', function () {
- clearStoryPulse({ release: false });
- });
- }
- flows.forEach(function (flow) { flow.setAttribute('data-story-pulse', 'true'); });
- if (Archify.flowTokens && typeof Archify.flowTokens.create === 'function') {
- var edge = step.edges[0];
- var shapes = storyGeometry(edge);
- var carrier = shapes.length ? Archify.flowTokens.create(edge, shapes[0], {
- className: 'story-flow-token',
- duration: '0.78s'
- }) : null;
- if (carrier) {
- var carrierOverlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- var carrierWrapper = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- carrierOverlay.setAttribute('class', 'story-carrier-overlay');
- carrierOverlay.setAttribute('data-story-carrier-overlay', '');
- carrierOverlay.setAttribute('aria-hidden', 'true');
- if (edge.hasAttribute('transform')) carrierWrapper.setAttribute('transform', edge.getAttribute('transform'));
- carrier.setAttribute('data-story-carrier-token', '');
- carrier.setAttribute('data-story-beat-step', String(step.index));
- carrierWrapper.appendChild(carrier);
- carrierOverlay.appendChild(carrierWrapper);
- var firstNode = svg.querySelector('[data-node-id]');
- while (firstNode && firstNode.parentNode !== svg) firstNode = firstNode.parentNode;
- if (firstNode) svg.insertBefore(carrierOverlay, firstNode);
- else svg.appendChild(carrierOverlay);
- }
- }
- void flows[0].getBoundingClientRect();
- flows[0].addEventListener('animationend', function () {
- if (pulseGeneration === storyPulseGeneration) clearStoryPulse();
- }, { once: true });
- return true;
- }
-
- function stopStoryBeatTimer(options) {
- options = options || {};
- storyPlaybackGeneration += 1;
- if (storyBeatTimer && options.preserveElapsed === true && storyBeatStartedAt) {
- storyBeatElapsedMs = Math.min(storyBeatDwellMs, storyBeatElapsedMs + Math.max(0, Date.now() - storyBeatStartedAt));
- }
- if (storyBeatTimer) clearTimeout(storyBeatTimer);
- storyBeatTimer = null;
- storyBeatStartedAt = 0;
- }
-
- function centerStoryStop(stop) {
- if (!stop || !trail) return false;
- var target = Math.max(0, stop.offsetLeft - (trail.clientWidth - stop.offsetWidth) / 2);
- trail.scrollLeft = target;
- return true;
- }
-
- function storyBeatDwell(total) {
- return Math.max(STORY_FOLLOW_MIN_DWELL_MS, VIEW_INTERVAL_MS / Math.max(1, total));
- }
-
- function clearStoryFollow() {
- storyFollowGeneration += 1;
- svg.removeAttribute('data-story-follow');
- panel.removeAttribute('data-story-follow');
- panel.removeAttribute('data-story-follow-node');
- }
-
- function storyFrameIds(step) {
- if (!step) return [];
- var ids = [];
- if (step.index > 0 && storySteps[step.index - 1]) ids.push(storySteps[step.index - 1].nodeId);
- ids.push(step.nodeId);
- if (step.index + 1 < storySteps.length) ids.push(storySteps[step.index + 1].nodeId);
- return ids;
- }
-
- function followStoryStep(step, options) {
- options = options || {};
- if (!step || document.hidden) return false;
- if (!Archify.view || typeof Archify.view.reveal !== 'function') {
- var deferredIndex = step.index;
- var deferredGeneration = ++storyFollowGeneration;
- requestAnimationFrame(function () {
- if (deferredGeneration !== storyFollowGeneration || storyBeatIndex !== deferredIndex) return;
- if (Archify.view && typeof Archify.view.reveal === 'function') followStoryStep(step, options);
- });
- return true;
- }
- if (window.matchMedia && window.matchMedia('print').matches) return false;
- var embed = document.documentElement.getAttribute('data-embed') === 'true';
- var explicitEmbedPlayback = document.documentElement.getAttribute('data-share-playback') === 'true';
- if (embed && !explicitEmbedPlayback && options.linked !== true) return false;
- var ids = storyFrameIds(step);
- var generation = ++storyFollowGeneration;
- svg.setAttribute('data-story-follow', step.nodeId);
- panel.setAttribute('data-story-follow', 'moving');
- panel.setAttribute('data-story-follow-node', step.nodeId);
- var receipt = Archify.view.reveal(ids, {
- reason: options.manual === true ? 'story-beat' : 'story-follow',
- padding: 64,
- maxScale: 1.65,
- duration: STORY_FOLLOW_DURATION_MS,
- instant: options.instant === true || reducedMotion() || document.documentElement.getAttribute('data-motion') !== 'live'
- });
- if (receipt && receipt.finished && typeof receipt.finished.then === 'function') {
- receipt.finished.then(function (result) {
- if (generation !== storyFollowGeneration || storyBeatIndex !== step.index) return;
- svg.removeAttribute('data-story-follow');
- panel.setAttribute('data-story-follow', result && result.state === 'complete' ? 'settled' : 'interrupted');
- });
- } else if (generation === storyFollowGeneration) {
- panel.setAttribute('data-story-follow', 'settled');
- }
- return receipt;
- }
-
- function setStoryBeat(index, options) {
- options = options || {};
- var stops = Array.prototype.slice.call(trail.querySelectorAll('[data-story-node]'));
- if (!stops.length) return false;
- resetBeatLinkFeedback();
- storyBeatIndex = Math.max(0, Math.min(stops.length - 1, index));
- var nextStep = storyBeatIndex + 1 < storySteps.length ? storySteps[storyBeatIndex + 1] : null;
- svg.setAttribute('data-story-beat', (storyBeatIndex + 1) + '/' + stops.length);
- panel.setAttribute('data-story-beat', (storyBeatIndex + 1) + '/' + stops.length);
- if (nextStep) {
- svg.setAttribute('data-story-next', nextStep.nodeId);
- panel.setAttribute('data-story-next', nextStep.nodeId);
- } else {
- svg.removeAttribute('data-story-next');
- panel.removeAttribute('data-story-next');
- }
- function storyBeatState(step) {
- if (step < storyBeatIndex) return 'past';
- if (step === storyBeatIndex) return 'active';
- if (step === storyBeatIndex + 1) return 'next';
- return 'pending';
- }
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-step]'), function (node) {
- var step = Number(node.getAttribute('data-story-step'));
- node.setAttribute('data-story-beat-state', storyBeatState(step));
- });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-beat-step]'), function (edge) {
- var step = Number(edge.getAttribute('data-story-beat-step'));
- edge.setAttribute('data-story-beat-state', storyBeatState(step));
- });
- stops.forEach(function (stop, step) {
- stop.setAttribute('data-story-beat-state', storyBeatState(step));
- if (step === storyBeatIndex) stop.setAttribute('aria-current', 'step');
- else stop.removeAttribute('aria-current');
- });
- note.setAttribute('aria-live', 'off');
- note.textContent = storyBeatCopy(storySteps[storyBeatIndex], stops.length);
- renderStoryCaption(storySteps[storyBeatIndex], stops.length, nextStep);
- if (options.center === true) centerStoryStop(stops[storyBeatIndex]);
- if (options.pulse === true) pulseStoryStep(storySteps[storyBeatIndex]);
- else clearStoryPulse();
- if (options.follow === true) followStoryStep(storySteps[storyBeatIndex], {
- manual: options.manual === true,
- linked: options.linked === true,
- instant: options.followInstant === true
- });
- renderShareCue();
- syncBeatLink();
- return true;
- }
-
- function settleStoryBeats() {
- stopStoryBeatTimer();
- clearStoryPulse();
- clearStoryFollow();
- resetBeatLinkFeedback();
- storyBeatIndex = -1;
- storyBeatElapsedMs = 0;
- storyBeatDwellMs = 0;
- svg.removeAttribute('data-story-beat');
- svg.removeAttribute('data-story-next');
- panel.removeAttribute('data-story-beat');
- panel.removeAttribute('data-story-next');
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-beat-state]'), function (el) {
- el.removeAttribute('data-story-beat-state');
- });
- Array.prototype.forEach.call(trail.querySelectorAll('[data-story-beat-state]'), function (stop) {
- stop.removeAttribute('data-story-beat-state');
- stop.removeAttribute('aria-current');
- });
- note.setAttribute('aria-live', 'polite');
- if (activeIndex >= 0) note.textContent = views[activeIndex].note || viewerText('viewer.guided.chapter.selectedNodes', { count: views[activeIndex].focus.length });
- renderStoryCaption(null, 0);
- renderShareCue();
- syncBeatLink();
- }
-
- function clearStoryTrail() {
- stopStoryBeatTimer();
- clearStoryPulse();
- clearStoryFollow();
- resetBeatLinkFeedback();
- storyBeatIndex = -1;
- storyBeatElapsedMs = 0;
- storyBeatDwellMs = 0;
- storySteps = [];
- svg.removeAttribute('data-story-active');
- svg.removeAttribute('data-story-playing');
- svg.removeAttribute('data-story-beat');
- svg.removeAttribute('data-story-next');
- panel.removeAttribute('data-story-beat');
- panel.removeAttribute('data-story-next');
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-overlay]'), function (overlay) {
- overlay.remove();
- });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-story-step], [data-story-beat-state]'), function (node) {
- node.removeAttribute('data-story-step');
- node.removeAttribute('data-story-beat-state');
- node.style.removeProperty('--story-step');
- });
- Array.prototype.forEach.call(svg.querySelectorAll('[data-edge-from][data-story-beat-step]'), function (edge) {
- edge.removeAttribute('data-story-beat-step');
- edge.removeAttribute('data-story-beat-state');
- });
- trail.textContent = '';
- trail.hidden = true;
- trail.removeAttribute('aria-label');
- renderStoryCaption(null, 0);
- syncBeatLink();
- }
-
- function storyGeometry(edge) {
- if (/^(path|line|polyline)$/i.test(edge.tagName)) return [edge];
- return Array.prototype.slice.call(edge.querySelectorAll('path, line, polyline'));
- }
-
- function renderStoryTrail(view) {
- if (Archify.semanticLens && typeof Archify.semanticLens.clearPreview === 'function') Archify.semanticLens.clearPreview();
- clearStoryTrail();
- if (!view) return;
-
- var nodeList = Array.prototype.slice.call(svg.querySelectorAll('[data-node-id]'));
- var edgeList = Array.prototype.slice.call(svg.querySelectorAll('[data-edge-from][data-edge-to]'));
- var byId = {};
- nodeList.forEach(function (node) { byId[node.getAttribute('data-node-id')] = node; });
- storySteps = view.focus.map(function (_, index) { return storyStep(view, index, edgeList, byId); });
- var labels = [];
- storySteps.forEach(function (step, index) {
- var id = step.nodeId;
- var node = byId[id];
- if (!node) return;
- node.setAttribute('data-story-step', String(index));
- node.style.setProperty('--story-step', String(index));
- var nodeLabel = step.nodeLabel;
- labels.push(nodeLabel);
- var stop = document.createElement('button');
- stop.type = 'button';
- stop.className = 'guided-view-stop';
- stop.setAttribute('data-story-node', id);
- stop.setAttribute('data-story-index', String(index));
- stop.setAttribute('data-story-relation', step.relation);
- stop.setAttribute('data-story-number', (index + 1 < 10 ? '0' : '') + (index + 1));
- if (index > 0) stop.setAttribute('data-story-link', step.relation);
- stop.style.setProperty('--story-step', String(index));
- stop.setAttribute('aria-label', storyBeatAria(step, storySteps.length));
- stop.title = storyBeatCopy(step, storySteps.length);
- stop.textContent = nodeLabel;
- trail.appendChild(stop);
- });
- trail.hidden = labels.length === 0;
- trail.setAttribute('aria-label', viewerText('viewer.guided.storyTrail', { label: view.label, count: labels.length }));
- trail.scrollLeft = 0;
- svg.setAttribute('data-story-active', view.id);
-
- var overlay = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- overlay.setAttribute('class', 'story-trail-overlay');
- overlay.setAttribute('data-story-overlay', '');
- overlay.setAttribute('aria-hidden', 'true');
- var copied = 0;
- storySteps.forEach(function (step) {
- step.edges.forEach(function (edge) {
- var edgeBeat = step.index;
- edge.setAttribute('data-story-beat-step', String(edgeBeat));
- var wrapper = document.createElementNS('http://www.w3.org/2000/svg', 'g');
- if (edge.hasAttribute('transform')) wrapper.setAttribute('transform', edge.getAttribute('transform'));
- storyGeometry(edge).forEach(function (shape) {
- var clone = shape.cloneNode(false);
- clone.removeAttribute('id');
- clone.removeAttribute('marker-start');
- clone.removeAttribute('marker-mid');
- clone.removeAttribute('marker-end');
- clone.removeAttribute('aria-label');
- clone.removeAttribute('role');
- clone.removeAttribute('data-animate');
- clone.removeAttribute('data-edge-from');
- clone.removeAttribute('data-edge-to');
- clone.removeAttribute('data-edge-key');
- clone.removeAttribute('data-edge-id');
- clone.removeAttribute('data-edge-label');
- clone.setAttribute('class', 'story-trail-flow');
- clone.setAttribute('data-story-beat-step', String(edgeBeat));
- clone.style.setProperty('--story-step', String(edgeBeat));
- wrapper.appendChild(clone);
- copied += 1;
- });
- if (wrapper.childNodes.length) overlay.appendChild(wrapper);
- });
- });
- if (copied) {
- var firstEdge = edgeList[0];
- if (firstEdge && firstEdge.parentNode) firstEdge.parentNode.insertBefore(overlay, firstEdge);
- else svg.insertBefore(overlay, svg.firstChild);
- }
- }
-
- function syncStoryPlayback() {
- var shouldPlay = playing && activeIndex >= 0;
- if (shouldPlay && svg.getAttribute('data-story-playing') !== 'true') svg.setAttribute('data-story-playing', 'true');
- else if (!shouldPlay && svg.hasAttribute('data-story-playing')) svg.removeAttribute('data-story-playing');
- }
-
- function resetProgress(fraction) {
- fraction = Math.max(0, Math.min(1, Number(fraction) || 0));
- progressBar.style.animation = 'none';
- progressBar.style.setProperty('--guided-progress-start', String(fraction));
- progressBar.style.transform = 'scaleX(' + fraction + ')';
- }
-
- function startProgress(fraction, duration) {
- resetProgress(fraction);
- void progressBar.offsetWidth;
- progressBar.style.animation = 'archify-guided-progress ' + Math.max(1, duration || VIEW_INTERVAL_MS) + 'ms linear forwards';
- }
-
- function currentStoryProgress() {
- var total = storySteps.length;
- if (!total || storyBeatIndex < 0) return 0;
- var elapsed = storyBeatElapsedMs;
- if (playing && storyBeatTimer && storyBeatStartedAt) elapsed += Math.max(0, Date.now() - storyBeatStartedAt);
- var dwell = storyBeatDwellMs || storyBeatDwell(total);
- return Math.max(0, Math.min(1, (storyBeatIndex + Math.min(1, elapsed / dwell)) / total));
- }
-
- function renderPlayback() {
- var automaticPlaybackAllowed = storyAutomaticPlaybackAllowed();
- panel.setAttribute('data-playing', playing ? 'true' : 'false');
- syncStoryPlayback();
- play.disabled = !playing && !automaticPlaybackAllowed;
- play.setAttribute('aria-pressed', playing ? 'true' : 'false');
- play.setAttribute('aria-label', viewerText(playing
- ? 'viewer.guided.pause'
- : !automaticPlaybackAllowed
- ? 'viewer.guided.motionUnavailable'
- : storyPlaybackComplete
- ? 'viewer.guided.replay'
- : 'viewer.guided.play'));
- play.title = viewerText(playing
- ? 'viewer.guided.pause.title'
- : !automaticPlaybackAllowed
- ? 'viewer.guided.enableMotion'
- : storyPlaybackComplete
- ? 'viewer.guided.replay.title'
- : 'viewer.guided.play.title');
- playIcon.textContent = playing ? '\u2016' : '\u25b6';
- playLabel.textContent = viewerText(playing
- ? 'viewer.guided.pauseStory'
- : storyPlaybackComplete
- ? 'viewer.guided.replayStory'
- : 'viewer.guided.playStory');
- if (storyCaption && !storyCaption.hidden) storyCaption.setAttribute('aria-live', playing ? 'off' : 'polite');
- }
-
- function render() {
- var view = views[activeIndex];
- count.textContent = activeIndex < 0 ? '0 / ' + views.length : (activeIndex + 1) + ' / ' + views.length;
- label.textContent = view ? view.label : viewerText('viewer.guided.explore');
- note.setAttribute('aria-live', storyBeatIndex >= 0 ? 'off' : 'polite');
- note.textContent = storyBeatIndex >= 0
- ? storyBeatCopy(storySteps[storyBeatIndex], storySteps.length)
- : (view
- ? (view.note || viewerText('viewer.guided.chapter.selectedNodes', { count: view.focus.length }))
- : viewerText('viewer.guided.intro'));
- prev.disabled = activeIndex < 0;
- next.disabled = activeIndex >= views.length - 1;
- all.disabled = activeIndex < 0;
- panel.setAttribute('data-active-view', view ? view.id : 'all');
- syncChapterIndex();
- renderShareCue();
- renderPlayback();
- syncBeatLink();
- }
-
- function pausePlayback(options) {
- options = options || {};
- var progress = options.complete === true ? 1 : currentStoryProgress();
- if (panel.getAttribute('data-autoplay') === 'playing') {
- setShareCueProgress(progress);
- setAutoplayState(options.complete === true ? 'complete' : 'interrupted');
- }
- stopStoryBeatTimer({ preserveElapsed: options.complete !== true });
- clearStoryPulse();
- clearStoryFollow();
- playing = false;
- storyPlaybackComplete = options.complete === true;
- resetProgress(progress);
- renderPlayback();
- renderShareCue();
- }
-
- function finishStoryChapter() {
- if (!playing) return false;
- if (storyPlaybackScope === 'chapter') {
- pausePlayback({ complete: true });
- return true;
- }
- if (activeIndex < views.length - 1) {
- var destinationIndex = activeIndex + 1;
- activate(destinationIndex, { playback: true });
- afterHandoff(function () {
- if (!playing || activeIndex !== destinationIndex) return;
- storyBeatElapsedMs = 0;
- setStoryBeat(0, { pulse: true, follow: true });
- scheduleStoryPlayback();
- });
- return true;
- }
- pausePlayback({ complete: true });
- return true;
- }
-
- function scheduleStoryPlayback() {
- var total = storySteps.length;
- if (!playing || !total || reducedMotion()) {
- if (playing) pausePlayback();
- return false;
- }
- storyBeatDwellMs = storyBeatDwell(total);
- if (storyBeatIndex < 0) {
- storyBeatElapsedMs = 0;
- setStoryBeat(0, { pulse: true, follow: true });
- }
- storyBeatElapsedMs = Math.max(0, Math.min(storyBeatDwellMs, storyBeatElapsedMs));
- var remainingDwell = Math.max(1, storyBeatDwellMs - storyBeatElapsedMs);
- var progress = (storyBeatIndex + storyBeatElapsedMs / storyBeatDwellMs) / total;
- var remainingChapter = remainingDwell + Math.max(0, total - storyBeatIndex - 1) * storyBeatDwellMs;
- startProgress(progress, remainingChapter);
- if (panel.getAttribute('data-autoplay') === 'playing') startShareCueProgress(progress, remainingChapter);
- var generation = ++storyPlaybackGeneration;
- storyBeatStartedAt = Date.now();
- storyBeatTimer = setTimeout(function () {
- if (!playing || generation !== storyPlaybackGeneration) return;
- storyBeatTimer = null;
- storyBeatStartedAt = 0;
- storyBeatElapsedMs = 0;
- if (storyBeatIndex < total - 1) {
- setStoryBeat(storyBeatIndex + 1, { pulse: true, follow: true });
- scheduleStoryPlayback();
- } else finishStoryChapter();
- }, remainingDwell);
- return true;
- }
-
- function startPlayback() {
- if (!storyAutomaticPlaybackAllowed()) {
- renderPlayback();
- return false;
- }
- autoplayPending = false;
- setAutoplayState(null);
- setShareCueProgress(0);
- document.documentElement.removeAttribute('data-share-playback');
- storyPlaybackScope = 'story';
- if (storyPlaybackComplete) showAll({ updateUrl: false });
- storyPlaybackComplete = false;
- if (activeIndex < 0) activate(0, { playback: true });
- playing = true;
- renderPlayback();
- afterHandoff(function () {
- if (!playing) return;
- if (storyBeatIndex >= 0) followStoryStep(storySteps[storyBeatIndex]);
- scheduleStoryPlayback();
- });
- return true;
- }
-
- function startCurrentViewPlayback() {
- if (document.hidden) return false;
- autoplayPending = false;
- document.documentElement.setAttribute('data-share-playback', 'true');
- storyPlaybackScope = 'chapter';
- storyPlaybackComplete = false;
- if (activeIndex < 0) activate(0, { playback: true, updateUrl: false });
- if (!storyAutomaticPlaybackAllowed()) {
- var preserveMoment = hashBeatMatchesCurrent();
- setShareCueProgress(preserveMoment && storySteps.length ? (storyBeatIndex + 1) / storySteps.length : 1);
- setAutoplayState('reduced-motion');
- playing = false;
- if (preserveMoment) {
- clearStoryPulse();
- renderShareCue();
- } else settleStoryBeats();
- renderPlayback();
- return false;
- }
- playing = true;
- setAutoplayState('playing');
- renderPlayback();
- afterHandoff(function () {
- if (!playing) return;
- if (storyBeatIndex >= 0) followStoryStep(storySteps[storyBeatIndex]);
- scheduleStoryPlayback();
- });
- return true;
- }
-
- function maybeStartSharePlayback() {
- if (!autoplayPending || document.hidden) return false;
- return startCurrentViewPlayback();
- }
-
- function togglePlayback() {
- return playing ? (pausePlayback(), false) : startPlayback();
- }
-
- function syncStoryControlsDisabled() {
- Array.prototype.forEach.call(trail.querySelectorAll('[data-story-node]'), function (stop) {
- stop.disabled = !!currentHandoff;
- });
- syncBeatLink();
- }
-
- function selectStoryBeat(index) {
- if (currentHandoff || activeIndex < 0 || index < 0 || index >= storySteps.length) return false;
- momentRestoreGeneration += 1;
- clearChapterPreview({ clearIntents: true });
- if (playing) pausePlayback();
- else {
- stopStoryBeatTimer();
- clearStoryPulse();
- }
- storyPlaybackComplete = false;
- storyPlaybackScope = 'story';
- storyBeatElapsedMs = 0;
- storyBeatDwellMs = storyBeatDwell(storySteps.length);
- var view = views[activeIndex];
- Archify.focus.setMany(view.focus, {
- toggle: false,
- updateUrl: false,
- mode: 'selection',
- label: view.label,
- hideChip: true
- });
- setStoryBeat(index, { manual: true, center: true, pulse: true, follow: true });
- resetProgress(index / storySteps.length);
- renderPlayback();
- return true;
- }
-
- function selectStoryBeatById(id, options) {
- options = options || {};
- var index = storySteps.findIndex(function (step) { return step.nodeId === id; });
- if (index < 0) return false;
- if (playing) pausePlayback();
- else {
- stopStoryBeatTimer();
- clearStoryPulse();
- }
- storyPlaybackComplete = false;
- storyPlaybackScope = 'story';
- storyBeatElapsedMs = 0;
- storyBeatDwellMs = storyBeatDwell(storySteps.length);
- setStoryBeat(index, {
- manual: false,
- center: true,
- pulse: false,
- follow: options.follow === true,
- linked: options.linked === true,
- followInstant: options.followInstant === true
- });
- resetProgress(index / storySteps.length);
- renderPlayback();
- return true;
- }
-
- function updateUrl(view) {
- try {
- history.replaceState(null, '', location.pathname + location.search + (view ? '#view=' + encodeURIComponent(view.id) : ''));
- } catch (_) {}
- }
-
- function showAll(options) {
- options = options || {};
- if (options.restore !== true) momentRestoreGeneration += 1;
- clearChapterPreview({ clearIntents: true });
- if (playing && options.playback !== true) pausePlayback();
- if (options.playback !== true) storyPlaybackComplete = false;
- cancelHandoff('overview');
- activeIndex = -1;
- renderStoryTrail(null);
- if (options.clearFocus !== false) Archify.focus.clear({ updateUrl: false });
- if (options.resetView !== false && Archify.view && typeof Archify.view.reset === 'function') {
- Archify.view.reset({ automatic: true });
- }
- render();
- if (options.updateUrl !== false) updateUrl(null);
- }
-
- function activate(index, options) {
- options = options || {};
- if (options.restore !== true) momentRestoreGeneration += 1;
- if (playing && options.playback !== true) pausePlayback();
- if (options.playback !== true) storyPlaybackComplete = false;
- if (index < 0) { showAll(options); return true; }
- if (index >= views.length) return false;
- clearChapterPreview({ clearIntents: true });
- var previousIndex = activeIndex;
- var previous = previousIndex >= 0 ? views[previousIndex] : null;
- var outgoingBeatIndex = storyBeatIndex;
- cancelHandoff('replaced');
- activeIndex = index;
- var view = views[index];
- Archify.focus.setMany(view.focus, {
- toggle: false,
- updateUrl: false,
- mode: 'selection',
- label: view.label,
- hideChip: true
- });
- renderStoryTrail(view);
- beginHandoff(previousIndex, index, previous, view, outgoingBeatIndex, options.playback === true ? 'playback' : 'guided');
- syncStoryControlsDisabled();
- render();
- if (options.updateUrl !== false) updateUrl(view);
- return true;
- }
-
- function activateById(id, options) {
- var index = views.findIndex(function (view) { return view.id === id; });
- return index >= 0 && activate(index, options);
- }
-
- prev.addEventListener('click', function () { activate(activeIndex - 1); });
- next.addEventListener('click', function () { activate(activeIndex + 1); });
- all.addEventListener('click', function () { showAll(); });
- play.addEventListener('click', togglePlayback);
- beatLink.addEventListener('click', copyStoryMomentLink);
- trail.addEventListener('focusin', function (event) {
- if (!event.target.closest('[data-story-node]')) return;
- if (playing) pausePlayback();
- });
- trail.addEventListener('click', function (event) {
- var stop = event.target.closest('[data-story-node]');
- if (!stop || stop.disabled) return;
- selectStoryBeat(Number(stop.getAttribute('data-story-index')));
- });
- trail.addEventListener('keydown', function (event) {
- if (event.key !== 'Enter' && event.key !== ' ') return;
- var stop = event.target.closest('[data-story-node]');
- if (!stop || stop.disabled) return;
- event.preventDefault();
- selectStoryBeat(Number(stop.getAttribute('data-story-index')));
- });
- chapterList.addEventListener('click', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- if (!button) return;
- activateById(button.getAttribute('data-guided-view-id'));
- });
- chapterList.addEventListener('pointerover', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- if (!button || !hoverCapable() || event.pointerType === 'touch') return;
- if (event.relatedTarget && button.contains(event.relatedTarget)) return;
- setChapterPreviewIntent('pointer', chapterButtons.indexOf(button));
- });
- chapterList.addEventListener('pointerout', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- if (!button || (event.relatedTarget && button.contains(event.relatedTarget))) return;
- clearChapterPreviewIntent('pointer', chapterButtons.indexOf(button));
- });
- chapterIndex.addEventListener('focusin', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- if (!button) return;
- setChapterPreviewIntent('focus', chapterButtons.indexOf(button));
- });
- chapterIndex.addEventListener('focusout', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- if (!button || (event.relatedTarget && button.contains(event.relatedTarget))) return;
- clearChapterPreviewIntent('focus', chapterButtons.indexOf(button));
- });
- chapterList.addEventListener('keydown', function (event) {
- var button = event.target.closest('[data-guided-view-id]');
- var index = chapterButtons.indexOf(button);
- if (index < 0) return;
- var target = null;
- if (event.key === 'ArrowRight') target = Math.min(chapterButtons.length - 1, index + 1);
- else if (event.key === 'ArrowLeft') target = Math.max(0, index - 1);
- else if (event.key === 'Home') target = 0;
- else if (event.key === 'End') target = chapterButtons.length - 1;
- if (target === null) return;
- event.preventDefault();
- focusChapterButton(target);
- });
-
- // A direct node exploration supersedes the curated view. Capture phase
- // releases the view before the focus explorer writes its own deep link.
- function releaseForNode(event) {
- if (activeIndex >= 0 && event.target.closest('[data-node-id]')) {
- pausePlayback();
- showAll({ clearFocus: false, updateUrl: false });
- }
- }
- svg.addEventListener('click', releaseForNode, true);
- svg.addEventListener('keydown', function (event) {
- if (event.key === 'Enter' || event.key === ' ') releaseForNode(event);
- }, true);
-
- document.addEventListener('keydown', function (event) {
- if (event.metaKey || event.ctrlKey || event.altKey) return;
- if (document.documentElement.getAttribute('data-guide-open') === 'true') return;
- var target = event.target;
- if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return;
- if (event.key === ']') {
- event.preventDefault();
- if (activeIndex < views.length - 1) activate(activeIndex + 1);
- } else if (event.key === '[') {
- event.preventDefault();
- if (activeIndex >= 0) activate(activeIndex - 1);
- } else if (event.key.toLowerCase() === 'p') {
- event.preventDefault();
- togglePlayback();
- } else if (event.key === 'Escape' && activePreviewIndex >= 0) {
- event.preventDefault();
- event.stopImmediatePropagation();
- clearChapterPreview({ clearIntents: true });
- } else if (event.key === 'Escape' && activeIndex >= 0) {
- event.preventDefault();
- showAll();
- }
- }, true);
-
- function syncViewFromHash() {
- try {
- var params = new URLSearchParams(location.hash.replace(/^#/, ''));
- var initial = params.get('view');
- var requestedBeat = params.get('beat');
- var restoreGeneration = ++momentRestoreGeneration;
- if (initial) {
- var activated = activateById(initial, { updateUrl: false, restore: true });
- if (!activated) {
- showAll({ updateUrl: false, restore: true });
- return;
- }
- if (requestedBeat) afterHandoff(function () {
- if (restoreGeneration !== momentRestoreGeneration) return;
- var latest = new URLSearchParams(location.hash.replace(/^#/, ''));
- if (latest.get('view') !== initial || latest.get('beat') !== requestedBeat) return;
- if (activeIndex < 0 || views[activeIndex].id !== initial) return;
- selectStoryBeatById(requestedBeat, { linked: true, follow: true, followInstant: true });
- });
- } else if (params.get('focus') || params.get('relation')) {
- activeIndex = -1;
- render();
- } else {
- showAll({ updateUrl: false, restore: true });
- }
- } catch (_) { showAll({ updateUrl: false, restore: true }); }
- }
-
- window.addEventListener('hashchange', syncViewFromHash);
- document.addEventListener('visibilitychange', function () {
- if (document.hidden) {
- clearChapterPreview({ clearIntents: true });
- if (playing) pausePlayback();
- else clearStoryPulse();
- settleHandoff('hidden');
- }
- else if (!document.hidden) maybeStartSharePlayback();
- });
- if (window.matchMedia) {
- var guidedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
- var onGuidedMotionChange = function () {
- if (guidedMotionQuery.matches) {
- if (playing) pausePlayback();
- else clearStoryPulse();
- settleHandoff('reduced-motion');
- }
- };
- if (typeof guidedMotionQuery.addEventListener === 'function') guidedMotionQuery.addEventListener('change', onGuidedMotionChange);
- else if (typeof guidedMotionQuery.addListener === 'function') guidedMotionQuery.addListener(onGuidedMotionChange);
- }
- if (document.documentElement.getAttribute('data-embed') !== 'true' && typeof MutationObserver !== 'undefined' && typeof Node !== 'undefined' && svg instanceof Node && document.documentElement instanceof Node) {
- var chapterPreviewOwnerObserver = new MutationObserver(syncChapterPreview);
- chapterPreviewOwnerObserver.observe(svg, {
- attributes: true,
- attributeFilter: [
- 'data-route-picking', 'data-route-active', 'data-lens-active',
- 'data-legend-preview-active', 'data-relationship-preview-active',
- 'data-intent-trace-active', 'data-focus-active'
- ]
- });
- var storyMotionObserver = new MutationObserver(function () {
- if (document.documentElement.getAttribute('data-motion') !== 'live') clearStoryPulse();
- renderPlayback();
- });
- storyMotionObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-motion'] });
- }
- window.addEventListener('beforeprint', function () {
- clearChapterPreview({ clearIntents: true });
- if (playing) pausePlayback();
- else clearStoryPulse();
- settleHandoff('print');
- });
- syncViewFromHash();
- if (autoplayPending) {
- requestAnimationFrame(function () {
- requestAnimationFrame(maybeStartSharePlayback);
- });
- }
-
- return {
- count: views.length,
- activate: activateById,
- showAll: showAll,
- play: startPlayback,
- playCurrent: startCurrentViewPlayback,
- pause: pausePlayback,
- beatLink: storyMomentLink,
- copyBeatLink: copyStoryMomentLink,
- cancelHandoff: cancelHandoff,
- settleHandoff: settleHandoff,
- clearPreview: function () { return clearChapterPreview({ clearIntents: true }); },
- isPlaying: function () { return playing; },
- handoff: function () {
- return currentHandoff ? { id: currentHandoff.id, mode: currentHandoff.mode, anchor: currentHandoff.anchor || null } : null;
- },
- active: function () { return activeIndex < 0 ? null : views[activeIndex].id; },
- preview: function () { return activePreviewIndex < 0 ? null : views[activePreviewIndex].id; },
- delta: function (id) {
- var index = views.findIndex(function (view) { return view.id === id; });
- if (index < 0) return null;
- var value = chapterDelta(activeIndex >= 0 ? views[activeIndex] : null, views[index]);
- return { stay: value.stay.slice(), enter: value.enter.slice(), leave: value.leave.slice() };
- },
- beat: function () {
- var step = storyBeatIndex >= 0 ? storySteps[storyBeatIndex] : null;
- return step ? {
- index: step.index,
- position: step.index + 1,
- total: storySteps.length,
- nodeId: step.nodeId,
- relation: step.relation,
- edgeKeys: step.edgeKeys.slice()
- } : null;
- },
- focus: function () { return activeIndex < 0 ? [] : views[activeIndex].focus.slice(); }
- };
- })();
/* ============================================================
Adaptive Reader Shell — one diagram across laptop and monitor.
The canonical SVG and viewBox never change. On ordinary desktop pages,
- wide diagrams receive only enough outer width to use the available
+ wide diagrams and measured intrinsic tall workflows receive enough outer width to use the available
height without pushing summary cards below the viewport. Mobile,
- embed, presentation, print, and non-wide diagrams retain their own
+ embed, presentation, print, and unmarked non-wide diagrams retain their own
established layout contracts.
============================================================ */
+ // Fixed script-private participants; the CLI sees only the joint wait below.
+ const archifyLayoutOwners = { reader: null, viewerChrome: null };
Archify.waitForStableLayout = function (options) {
options = options || {};
var maximumFrames = Math.max(1, Number(options.maximumFrames) || 240);
@@ -10961,19 +10381,62 @@
var shell = document.querySelector('.container');
var diagram = document.querySelector('.diagram-container');
var svg = diagram && diagram.querySelector(':scope > svg');
+ var legend = svg && svg.querySelector('[data-legend]');
var header = shell && shell.querySelector('.header');
- var guided = shell && shell.querySelector('.guided-views');
var cards = shell && shell.querySelector('.cards');
var viewBox = svg && svg.viewBox && svg.viewBox.baseVal;
var ratio = viewBox && viewBox.height > 0 ? viewBox.width / viewBox.height : 0;
+ var readerFit = svg && svg.getAttribute('data-reader-fit');
+ var widthFirstReading = readerFit === 'width-first';
+ var automaticSequence = widthFirstReading && svg.hasAttribute('data-sequence-column-fit');
+ var readingScroll = widthFirstReading;
+ var measuredHeightFit = readerFit === 'intrinsic-height' || widthFirstReading;
var frame = 0;
var settleFrame = 0;
var lastWidth = 0;
+ var automaticAreaHeight = 0;
+ // Widest reader the overflow settle has accepted for this viewport (0 =
+ // uncapped). Card copy rewraps as the reader narrows, so recomputing
+ // from fixed heights alone would widen again and oscillate; only a
+ // resize lifts the cap.
+ var settledCap = 0;
var WIDE_RATIO = 1.55;
var MIN_DESKTOP_WIDTH = 1024;
var MIN_READER_WIDTH = 960;
var MAX_READER_WIDTH = 1920;
+ var MAX_AUTOMATIC_SCALE = 1.5;
+ var MIN_PROJECTED_NODE_TEXT_PX = 6;
+ var declaredMinimumText = svg ? parseFloat(svg.getAttribute('data-reader-min-text') || '') : null;
+ var requestedMinimumText = Number.isFinite(declaredMinimumText)
+ ? Math.max(MIN_PROJECTED_NODE_TEXT_PX, declaredMinimumText)
+ : MIN_PROJECTED_NODE_TEXT_PX;
+ var declaredPrimaryText = svg ? parseFloat(svg.getAttribute('data-reader-primary-text') || '') : null;
var SAFE_BOTTOM_GAP = 12;
+ // Wide viewports move summary cards beside the diagram, so the height
+ // budget belongs to the diagram and spare width holds the notes.
+ var RAIL_MIN_VIEWPORT = 1280;
+ var RAIL_WIDTH = 288;
+ var RAIL_GAP = 20;
+ // A default rail must leave primary node labels comfortably readable;
+ // otherwise it starts collapsed and the reader can still open it.
+ var RAIL_COMFORT_PRIMARY_PX = 12;
+ var railPanel = shell && shell.querySelector('.reader-rail');
+ var railReveal = document.getElementById('rail-reveal');
+ var railCollapse = document.getElementById('rail-collapse');
+ var railPlacement = document.getElementById('rail-placement');
+ var RAIL_COLLAPSED_KEY = 'archify-rail-collapsed';
+ var RAIL_PLACEMENT_KEY = 'archify-rail-placement';
+ // Memory is the page's source of truth; storage only carries the choice
+ // to later artifacts, so a blocked or full localStorage cannot freeze it.
+ var preferences = Object.create(null);
+ function readPreference(key) {
+ if (key in preferences) return preferences[key];
+ try { return localStorage.getItem(key); } catch (_) { return null; }
+ }
+ function writePreference(key, value) {
+ preferences[key] = value;
+ try { localStorage.setItem(key, value); } catch (_) {}
+ }
if (diagram && ratio >= WIDE_RATIO) {
diagram.setAttribute('data-wide-diagram', 'true');
@@ -10992,9 +10455,58 @@
var style = window.getComputedStyle(element);
return element.getBoundingClientRect().height + number(style.marginTop) + number(style.marginBottom);
}
+ // Smallest scale that keeps node text at the requested floor and
+ // context relationship labels readable. A declared wide reader holds
+ // relationship labels to the requested floor too; every other reader
+ // still keeps them at the 6px hard floor the browser gate enforces, so
+ // a first-screen fit can never push them below it.
+ function minimumReadableScale() {
+ var nodeMinimum = null;
+ var edgeMinimum = null;
+ var selectors = 'text[data-node-label], text[data-boundary-label], text[data-detail="context"], g[data-detail="context"] text';
+ Array.from(svg.querySelectorAll(selectors)).forEach(function (text) {
+ if (text.getAttribute('data-detail') === 'fine' || text.closest('[data-detail="fine"]')) return;
+ var sourceFontPx = parseFloat(text.getAttribute('font-size') || '');
+ if (!Number.isFinite(sourceFontPx)) return;
+ var primary = text.hasAttribute('data-node-label') || text.hasAttribute('data-boundary-label');
+ var context = text.getAttribute('data-detail') === 'context' || Boolean(text.closest('g[data-detail="context"]'));
+ if (!primary && context && text.closest('[data-edge-from][data-edge-to]')) {
+ edgeMinimum = edgeMinimum == null ? sourceFontPx : Math.min(edgeMinimum, sourceFontPx);
+ } else if (primary || text.closest('[data-node-id]')) {
+ nodeMinimum = nodeMinimum == null ? sourceFontPx : Math.min(nodeMinimum, sourceFontPx);
+ }
+ });
+ var edgeTarget = measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)
+ ? requestedMinimumText
+ : MIN_PROJECTED_NODE_TEXT_PX;
+ var scale = 0;
+ if (nodeMinimum != null) scale = Math.max(scale, requestedMinimumText / nodeMinimum);
+ if (edgeMinimum != null) scale = Math.max(scale, edgeTarget / edgeMinimum);
+ return scale > 0 ? Math.min(1, scale) : 1;
+ }
+ var sourcePrimary = null;
+ if (svg) Array.from(svg.querySelectorAll('text[data-node-label]')).forEach(function (text) {
+ var size = parseFloat(text.getAttribute('font-size') || '');
+ if (Number.isFinite(size) && size > 0) sourcePrimary = sourcePrimary == null ? size : Math.max(sourcePrimary, size);
+ });
+ // SVG width at which the largest node label renders at targetPx. Every
+ // renderer writes label font sizes, so the rail comfort check works for
+ // all diagram types; only the renderer-declared floor needs metadata.
+ function labelWidth(targetPx) {
+ return sourcePrimary == null || !viewBox ? 0 : viewBox.width * targetPx / sourcePrimary;
+ }
+ function primaryReadingWidth() {
+ if (!measuredHeightFit || !Number.isFinite(declaredPrimaryText) || declaredPrimaryText <= 0) return 0;
+ // Primary labels should remain comfortable to read when cards or
+ // auxiliary rows make a one-screen fit too small. Ordinary page
+ // scroll preserves that reading size; viewport width still caps it.
+ // A long title may already use a smaller fitted font. Preserve that
+ // hierarchy rather than enlarging every other node to compensate.
+ return labelWidth(declaredPrimaryText);
+ }
function eligible() {
return Boolean(
- shell && diagram && svg && ratio >= WIDE_RATIO &&
+ shell && diagram && svg && (ratio >= WIDE_RATIO || measuredHeightFit) &&
window.innerWidth >= MIN_DESKTOP_WIDTH &&
html.getAttribute('data-embed') !== 'true' &&
html.getAttribute('data-present') !== 'true' &&
@@ -11003,9 +10515,109 @@
}
function clear() {
html.style.removeProperty('--archify-reader-width');
+ html.style.removeProperty('--archify-diagram-max-width');
+ html.style.removeProperty('--archify-diagram-min-height');
+ html.removeAttribute('data-reader-area');
+ html.removeAttribute('data-reader-narrow');
html.removeAttribute('data-reader-layout');
html.removeAttribute('data-reader-overflow');
+ setRail(false);
lastWidth = 0;
+ automaticAreaHeight = 0;
+ settledCap = 0;
+ clearLegend();
+ }
+ function clearLegend() {
+ if (!legend || !legend.hasAttribute('data-reader-legend-corner')) return;
+ legend.removeAttribute('data-reader-legend-corner');
+ legend.style.removeProperty('--archify-reader-legend-transform');
+ }
+ // Keep the original legend in its SVG: renderer hover/focus selectors and
+ // canonical export still own that same group. Ordinary capped reading
+ // and fitted automatic sequences borrow the outer corner at 25–100%.
+ function syncLegend() {
+ var cameraScale = Number(svg && svg.getAttribute('data-view-scale')) || 1;
+ var cornerReading = html.getAttribute('data-reader-area') === 'true' || automaticSequence && !readingScroll;
+ if (!legend || !eligible() || !cornerReading || cameraScale > 1.001) {
+ clearLegend();
+ return;
+ }
+ var box = legend.getBBox();
+ var parentMatrix = legend.parentNode.getScreenCTM();
+ if (!parentMatrix || !box.width || !box.height) {
+ clearLegend();
+ return;
+ }
+ var rect = diagram.getBoundingClientRect();
+ var style = window.getComputedStyle(diagram);
+ var scale = Math.min(svg.clientWidth / viewBox.width, svg.clientHeight / viewBox.height);
+ if (!Number.isFinite(scale) || scale <= 0) {
+ clearLegend();
+ return;
+ }
+ var left = rect.left + number(style.borderLeftWidth) + number(style.paddingLeft);
+ var right = rect.right - number(style.borderRightWidth) - number(style.paddingRight);
+ var bottom = rect.bottom - number(style.borderBottomWidth) - number(style.paddingBottom);
+ var top = bottom - box.height * scale;
+ var nav = diagram.querySelector('.diagram-nav');
+ var navRect = visible(nav) ? nav.getBoundingClientRect() : null;
+ // Long or multi-row legends retain their canonical position if the
+ // spare corner cannot hold them clear of the dock and content area.
+ if (left + box.width * scale > right || top < rect.top + number(style.paddingTop) + number(style.borderTopWidth) ||
+ (navRect && left < navRect.right + 10 && left + box.width * scale > navRect.left - 10 &&
+ top < navRect.bottom + 10 && bottom > navRect.top - 10)) {
+ clearLegend();
+ return;
+ }
+ var matrix = parentMatrix.inverse().translate(left, top).scale(scale).translate(-box.x, -box.y);
+ var value = 'matrix(' + [matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f].join(',') + ')';
+ if (legend.style.getPropertyValue('--archify-reader-legend-transform') !== value) {
+ legend.style.setProperty('--archify-reader-legend-transform', value);
+ }
+ if (!legend.hasAttribute('data-reader-legend-corner')) legend.setAttribute('data-reader-legend-corner', '');
+ }
+ // Rail modes: "true" docks beside the diagram, "collapsed" leaves only the
+ // reveal control, "overlay" opens a drawer when docking would break the
+ // readable floor, and "bottom" stacks notes and index below the diagram.
+ function setRail(mode) {
+ if (mode) {
+ html.setAttribute('data-reader-rail', mode);
+ html.style.setProperty('--archify-rail-width', RAIL_WIDTH + 'px');
+ html.style.setProperty('--archify-rail-gap', RAIL_GAP + 'px');
+ } else {
+ html.removeAttribute('data-reader-rail');
+ html.style.removeProperty('--archify-rail-width');
+ html.style.removeProperty('--archify-rail-gap');
+ }
+ if (railReveal) railReveal.hidden = mode !== 'collapsed';
+ if (railCollapse) {
+ railCollapse.hidden = mode !== 'true' && mode !== 'overlay';
+ railCollapse.setAttribute('aria-expanded', String(mode === 'true' || mode === 'overlay'));
+ }
+ if (railPlacement) {
+ railPlacement.hidden = !mode || mode === 'collapsed' || (mode === 'bottom' && window.innerWidth < RAIL_MIN_VIEWPORT);
+ railPlacement.setAttribute('data-placement', mode === 'bottom' ? 'bottom' : 'right');
+ railPlacement.setAttribute('aria-label', viewerText(mode === 'bottom' ? 'viewer.rail.right' : 'viewer.rail.bottom'));
+ railPlacement.title = railPlacement.getAttribute('aria-label');
+ }
+ }
+ var outline = document.getElementById('node-outline');
+ function hasCards() {
+ return Boolean((cards && cards.children.length && !cards.hidden) || (outline && !outline.hidden));
+ }
+ // Bottom notes and index are reading material below the fold: the first
+ // screen belongs to the interactive diagram and its controls.
+ function belowFold() {
+ return html.getAttribute('data-reader-rail') === 'bottom' ? outerHeight(railPanel) : 0;
+ }
+ // A docked rail may run past a short diagram down to the viewport floor,
+ // so the index uses that space instead of scrolling inside the diagram's
+ // height; it never pushes the page into overflow.
+ function fitDockedRail() {
+ if (html.getAttribute('data-reader-rail') !== 'true' || !railPanel) return;
+ var top = railPanel.getBoundingClientRect().top + window.scrollY;
+ var floor = window.innerHeight - number(window.getComputedStyle(body).paddingBottom) - top;
+ html.style.setProperty('--archify-rail-max', Math.max(diagram.getBoundingClientRect().height, floor) + 'px');
}
function chromeMetrics() {
var bodyStyle = window.getComputedStyle(body);
@@ -11019,27 +10631,59 @@
number(diagramStyle.borderTopWidth) + number(diagramStyle.borderBottomWidth)
};
}
- function applyWidth(width) {
- var rounded = Math.round(width);
- if (Math.abs(rounded - lastWidth) < 1) return false;
+ // `width` is the diagram's reading width. The page shell never narrows
+ // below the desktop reader floor, so a narrow, tall diagram keeps a
+ // usable header, toolbar, and controls; its SVG is centred instead.
+ function applyWidth(width, minWidth) {
+ var rounded = Math.max(Math.ceil(minWidth || 0), Math.round(width));
+ var changed = Math.abs(rounded - lastWidth) >= 1;
lastWidth = rounded;
- html.style.setProperty('--archify-reader-width', rounded + 'px');
+ var shellFloor = Math.min(MIN_READER_WIDTH, Math.max(0, window.innerWidth - chromeMetrics().bodyX));
+ html.style.setProperty('--archify-reader-width', Math.max(rounded, shellFloor) + 'px');
+ var railShare = html.getAttribute('data-reader-rail') === 'true' ? RAIL_WIDTH + RAIL_GAP : 0;
+ var diagramWidth = Math.max(1, rounded - railShare - chromeMetrics().diagramX);
+ // Content fitting and automatic enlargement never reduce the outer
+ // reader region. The SVG alone takes the narrower reading width.
+ var automaticWidthCap = measuredHeightFit && viewBox && viewBox.width > 0
+ ? viewBox.width * MAX_AUTOMATIC_SCALE : 0;
+ if (automaticWidthCap && diagramWidth > automaticWidthCap) {
+ diagramWidth = automaticWidthCap;
+ html.style.setProperty('--archify-diagram-min-height', automaticAreaHeight + 'px');
+ html.setAttribute('data-reader-area', 'true');
+ } else {
+ // Ordinary automatic diagrams retain their existing document flow.
+ // Settling can also stop binding the cap without a new measure.
+ html.style.removeProperty('--archify-diagram-min-height');
+ html.removeAttribute('data-reader-area');
+ }
+ if (diagramWidth < Math.max(rounded, shellFloor) - railShare - chromeMetrics().diagramX) {
+ html.style.setProperty('--archify-diagram-max-width', diagramWidth + 'px');
+ html.setAttribute('data-reader-narrow', 'true');
+ } else {
+ html.style.removeProperty('--archify-diagram-max-width');
+ html.removeAttribute('data-reader-narrow');
+ }
html.setAttribute('data-reader-layout', 'adaptive');
- return true;
+ syncLegend();
+ return changed;
}
function settleOverflow(minWidth) {
if (settleFrame) cancelAnimationFrame(settleFrame);
settleFrame = requestAnimationFrame(function () {
settleFrame = 0;
if (!eligible() || !lastWidth) return;
+ fitDockedRail();
var overflow = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
- ) - window.innerHeight;
- if (overflow > 1 && lastWidth > minWidth) {
- applyWidth(Math.max(minWidth, lastWidth - overflow * ratio - 4));
+ ) - window.innerHeight - belowFold();
+ // visual-check fails any page whose rounded-up height exceeds the
+ // viewport, so even a 1px remainder must be reduced or declared.
+ if (overflow > 0 && !readingScroll && lastWidth > Math.ceil(minWidth)) {
+ applyWidth(Math.max(minWidth, lastWidth - overflow * ratio - 4), minWidth);
+ settledCap = lastWidth;
html.setAttribute('data-reader-overflow', 'reduced');
- } else if (overflow > 1) {
+ } else if (overflow > 0) {
html.setAttribute('data-reader-overflow', 'authored');
} else {
html.removeAttribute('data-reader-overflow');
@@ -11054,18 +10698,72 @@
}
var chrome = chromeMetrics();
var viewportCap = Math.max(0, window.innerWidth - chrome.bodyX);
- var minWidth = Math.min(MIN_READER_WIDTH, viewportCap);
+ // Sequence first-screen fitting preserves source text sizes instead
+ // of shrinking to the shared hard readability floor.
+ var readableWidth = viewBox && viewBox.width > 0
+ ? viewBox.width * (automaticSequence ? 1 : minimumReadableScale()) + chrome.diagramX
+ : MIN_READER_WIDTH;
var maxWidth = Math.min(MAX_READER_WIDTH, viewportCap);
+ var readableMinimumWidth = automaticSequence || measuredHeightFit && ratio < WIDE_RATIO
+ ? readableWidth
+ : measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)
+ ? Math.max(MIN_READER_WIDTH, readableWidth)
+ : MIN_READER_WIDTH;
+ var minWidth;
+ if (automaticSequence) {
+ minWidth = Math.min(readableMinimumWidth, maxWidth);
+ } else if (measuredHeightFit && ratio < WIDE_RATIO) {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ } else if (measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)) {
+ minWidth = Math.min(readableMinimumWidth, maxWidth);
+ } else {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ }
+ var primaryWidth = primaryReadingWidth();
+ var railExtra = RAIL_WIDTH + RAIL_GAP;
+ var mode = null;
+ // Notes default below the diagram; the right rail is the reader's
+ // opt-in and needs a wide viewport.
+ if (hasCards() && (readPreference(RAIL_PLACEMENT_KEY) !== 'right' || window.innerWidth < RAIL_MIN_VIEWPORT)) {
+ mode = 'bottom';
+ } else if (hasCards()) {
+ var fitsReadable = readableMinimumWidth + railExtra <= maxWidth;
+ var comfortWidth = labelWidth(RAIL_COMFORT_PRIMARY_PX);
+ var comfortable = fitsReadable && (!comfortWidth || comfortWidth + chrome.diagramX + railExtra <= maxWidth);
+ var collapsedPreference = readPreference(RAIL_COLLAPSED_KEY);
+ if (collapsedPreference === '1' || (collapsedPreference !== '0' && !comfortable)) mode = 'collapsed';
+ else mode = fitsReadable ? 'true' : 'overlay';
+ }
+ // Height-fit families with notes below the fold may shrink to their
+ // readable floor. Width-first families choose their reading width
+ // below and retain page scrolling instead.
+ if (mode === 'bottom') primaryWidth = 0;
+ if (primaryWidth > 0) minWidth = Math.max(minWidth, Math.min(maxWidth, primaryWidth + chrome.diagramX));
+ var docked = mode === 'true';
+ setRail(mode);
+ chrome = chromeMetrics();
+ if (docked) minWidth = Math.min(maxWidth, minWidth + railExtra);
+ var stackedBelow = mode === 'bottom' ? 0 : docked ? 0 : outerHeight(cards);
var fixedHeight = chrome.bodyY + chrome.diagramY + SAFE_BOTTOM_GAP +
- outerHeight(header) + outerHeight(guided) + outerHeight(cards);
+ outerHeight(header) + stackedBelow;
var availableSvgHeight = Math.max(1, window.innerHeight - fixedHeight);
- var desiredWidth = availableSvgHeight * ratio + chrome.diagramX;
- var width = Math.max(minWidth, Math.min(maxWidth, desiredWidth));
- applyWidth(width);
+ var desiredWidth = availableSvgHeight * ratio + chrome.diagramX + (docked ? railExtra : 0);
+ // Compact automatic sequences fit the first screen without shrinking
+ // their authored text. Longer sequences retain reading width and page
+ // scroll; other width-first families keep their existing strategy.
+ var sequenceFits = automaticSequence && Math.min(desiredWidth, maxWidth) >=
+ readableWidth + (docked ? railExtra : 0);
+ readingScroll = widthFirstReading && !sequenceFits;
+ if (readingScroll) desiredWidth = maxWidth;
+ // Only a binding enlargement cap needs a separate normal reader area.
+ // Uncapped diagrams keep their existing natural height and Chrome fit.
+ automaticAreaHeight = availableSvgHeight + chrome.diagramY;
+ var width = Math.max(minWidth, Math.min(maxWidth, desiredWidth, settledCap || desiredWidth));
+ applyWidth(width, minWidth);
settleOverflow(minWidth);
return {
ratio: ratio,
- width: Math.round(width),
+ width: lastWidth,
availableSvgHeight: Math.round(availableSvgHeight),
fixedHeight: Math.round(fixedHeight)
};
@@ -11088,37 +10786,71 @@
Math.round(shellRect.width * 100) / 100,
Math.round(shellRect.height * 100) / 100,
Math.round(diagramRect.width * 100) / 100,
- Math.round(diagramRect.height * 100) / 100
+ Math.round(diagramRect.height * 100) / 100,
+ legend && legend.hasAttribute('data-reader-legend-corner') ? legend.style.getPropertyValue('--archify-reader-legend-transform') : ''
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Adaptive reader layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.reader = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
- window.addEventListener('resize', schedule, { passive: true });
+ window.addEventListener('resize', function () {
+ settledCap = 0;
+ schedule();
+ }, { passive: true });
window.addEventListener('load', schedule, { once: true });
+ window.addEventListener('beforeprint', clearLegend);
+ window.addEventListener('afterprint', schedule);
if (document.fonts && document.fonts.ready) document.fonts.ready.then(schedule).catch(function () {});
if (typeof ResizeObserver === 'function') {
var resizeObserver = new ResizeObserver(schedule);
- [header, guided, cards].forEach(function (element) { if (element) resizeObserver.observe(element); });
+ [header, cards].forEach(function (element) { if (element) resizeObserver.observe(element); });
}
if (typeof MutationObserver === 'function') {
var contentObserver = new MutationObserver(schedule);
- if (guided) contentObserver.observe(guided, { attributes: true, childList: true, subtree: true });
if (cards) contentObserver.observe(cards, { attributes: true, childList: true, subtree: true });
contentObserver.observe(html, { attributes: true, attributeFilter: ['data-embed', 'data-present'] });
}
+ // Reader choices persist across artifacts; a resize-style remeasure
+ // applies them without reloading.
+ function chooseRail(key, value) {
+ writePreference(key, value);
+ settledCap = 0;
+ schedule();
+ }
+ function collapseRail() {
+ chooseRail(RAIL_COLLAPSED_KEY, '1');
+ if (railReveal) requestAnimationFrame(function () { try { railReveal.focus({ preventScroll: true }); } catch (_) {} });
+ }
+ if (railReveal) railReveal.addEventListener('click', function () { chooseRail(RAIL_COLLAPSED_KEY, '0'); });
+ if (railCollapse) railCollapse.addEventListener('click', collapseRail);
+ if (railPlacement) railPlacement.addEventListener('click', function () {
+ var toBottom = html.getAttribute('data-reader-rail') !== 'bottom';
+ if (!toBottom) writePreference(RAIL_COLLAPSED_KEY, '0');
+ chooseRail(RAIL_PLACEMENT_KEY, toBottom ? 'bottom' : 'right');
+ });
+ document.addEventListener('keydown', function (event) {
+ if (event.key === 'Escape' && html.getAttribute('data-reader-rail') === 'overlay') collapseRail();
+ });
+ document.addEventListener('pointerdown', function (event) {
+ if (html.getAttribute('data-reader-rail') !== 'overlay' || !railPanel) return;
+ if (!railPanel.contains(event.target) && !(railReveal && railReveal.contains(event.target))) chooseRail(RAIL_COLLAPSED_KEY, '1');
+ });
+ if (typeof ResizeObserver === 'function' && railPanel) new ResizeObserver(schedule).observe(railPanel);
schedule();
return {
measure: measure,
schedule: schedule,
whenStable: whenStable,
+ syncLegend: syncLegend,
active: function () { return html.getAttribute('data-reader-layout') === 'adaptive'; },
receipt: function () { return { ratio: ratio, width: lastWidth }; }
};
@@ -11267,8 +10999,36 @@
};
return lastReceipt;
}
+ /* When the stage runs below the viewport, the dock lifts to the viewport
+ floor so its controls stay reachable while reading. Stage-rail
+ decisions and receipts use its resting position, so the lift never
+ feeds back into layout. */
+ var lift = 0;
+ var liftFrame = 0;
+ function restingNavRect() {
+ var rect = nav.getBoundingClientRect();
+ if (!lift) return rect;
+ return { x: rect.x, y: rect.y + lift, left: rect.left, right: rect.right, top: rect.top + lift, bottom: rect.bottom + lift, width: rect.width, height: rect.height };
+ }
+ function updateLift() {
+ liftFrame = 0;
+ var next = 0;
+ if (eligible()) {
+ var rest = restingNavRect();
+ var box = container.getBoundingClientRect();
+ next = Math.round(Math.max(0, Math.min(rest.bottom - (window.innerHeight - 16), rest.top - box.top - 16)));
+ }
+ if (next === lift) return;
+ lift = next;
+ if (lift) container.style.setProperty('--archify-dock-lift', lift + 'px');
+ else container.style.removeProperty('--archify-dock-lift');
+ }
+ function scheduleLift() {
+ if (!liftFrame) liftFrame = requestAnimationFrame(updateLift);
+ }
function measure() {
frame = 0;
+ scheduleLift();
if (probingBaseline) return null;
if (!eligible()) return clear({ preserveBaseline: !cameraAtBaseline() });
@@ -11282,7 +11042,7 @@
if (reserve === 0 && restorableReserve > 0) {
if (writeReserve(restorableReserve)) return null;
}
- var cameraNavRect = nav.getBoundingClientRect();
+ var cameraNavRect = restingNavRect();
var cameraLegendRect = visible(legend) ? legend.getBoundingClientRect() : null;
var cameraStageRect = protectedStageRect();
var cameraIntersectionArea = usable(cameraLegendRect) && intersectionArea(cameraNavRect, cameraStageRect) > 0
@@ -11302,7 +11062,7 @@
return lastReceipt;
}
- var navRect = nav.getBoundingClientRect();
+ var navRect = restingNavRect();
var legendRect = visible(legend) ? legend.getBoundingClientRect() : null;
var stageRect = protectedStageRect();
if (!usable(navRect) || !usable(stageRect)) return clear();
@@ -11324,7 +11084,7 @@
if (writeReserve(reserve + remaining)) return null;
}
- navRect = nav.getBoundingClientRect();
+ navRect = restingNavRect();
legendRect = visible(legend) ? legend.getBoundingClientRect() : null;
stageRect = protectedStageRect();
stageGap = navRect.top - stageRect.bottom;
@@ -11379,10 +11139,11 @@
}
function stableSnapshot() {
var containerRect = container ? container.getBoundingClientRect() : { width: 0, height: 0 };
- var navRect = nav ? nav.getBoundingClientRect() : { top: 0, left: 0 };
+ var navRect = nav ? restingNavRect() : { top: 0, left: 0 };
var legendRect = legend ? legend.getBoundingClientRect() : { top: 0, left: 0 };
return [
reserve,
+ lift,
Math.round(containerRect.width * 100) / 100,
Math.round(containerRect.height * 100) / 100,
Math.round(navRect.left * 100) / 100,
@@ -11393,16 +11154,19 @@
lastReceipt ? lastReceipt.stageGap : ''
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame || liftFrame || probingBaseline); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame || probingBaseline); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Viewer chrome layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.viewerChrome = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
window.addEventListener('resize', reprobe, { passive: true });
+ window.addEventListener('scroll', scheduleLift, { passive: true });
window.addEventListener('load', schedule, { once: true });
window.addEventListener('beforeprint', schedule);
window.addEventListener('afterprint', reprobe);
@@ -11410,10 +11174,18 @@
if (typeof ResizeObserver === 'function') {
var resizeObserver = new ResizeObserver(schedule);
[nav, svg, legend].forEach(function (element) { if (element) resizeObserver.observe(element); });
+ // Camera zoom changes outer page flow without changing intrinsic SVG
+ // size. Follow that box for dock placement, independently of scrolling
+ // and the baseline stage-rail measurement.
+ new ResizeObserver(scheduleLift).observe(container);
}
if (typeof MutationObserver === 'function') {
var contentObserver = new MutationObserver(function (records) {
- var viewerModeChanged = records.some(function (record) { return record.target === html; });
+ // A theme switch changes paint, not the stage geometry. Reprobing
+ // drops the bottom rail for several frames and makes the diagram jump.
+ var viewerModeChanged = records.some(function (record) {
+ return record.target === html && record.attributeName !== 'data-theme';
+ });
if (viewerModeChanged) reprobe();
else schedule();
});
@@ -11431,11 +11203,55 @@
reprobe: reprobe,
whenStable: whenStable,
stageRect: protectedStageRect,
+ dockRect: function () { return nav ? restingNavRect() : null; },
active: function () { return reserve > 0; },
receipt: function () { return lastReceipt || measure(); }
};
})();
+ Archify.layoutStability = {
+ whenStable: function () {
+ var reader = archifyLayoutOwners.reader;
+ var chrome = archifyLayoutOwners.viewerChrome;
+ if (!reader || !chrome) {
+ return Promise.reject(new Error('Joint layout owners are unavailable.'));
+ }
+ var observedFontsReady = document.fonts && document.fonts.ready;
+ var fontCyclePending = false;
+ var fontGeneration = 0;
+ function scheduleOwners() { reader.schedule(); chrome.schedule(); }
+ function fontsPending() {
+ var fonts = document.fonts;
+ var ready = fonts && fonts.ready;
+ if (ready && (ready !== observedFontsReady || (fonts.status === 'loading' && !fontCyclePending))) {
+ observedFontsReady = ready;
+ fontCyclePending = true;
+ var generation = ++fontGeneration;
+ ready.catch(function () {}).then(function () {
+ if (generation !== fontGeneration) return;
+ fontCyclePending = false;
+ scheduleOwners();
+ });
+ }
+ return fontCyclePending || Boolean(fonts && fonts.status === 'loading');
+ }
+ return Archify.waitForStableLayout({
+ maximumFrames: 960,
+ schedule: scheduleOwners,
+ pending: function () {
+ // Recapture readiness for font cycles that begin during sampling.
+ return fontsPending() || reader.pending() || chrome.pending();
+ },
+ snapshot: function () {
+ return JSON.stringify([
+ ['reader', reader.snapshot()],
+ ['viewerChrome', chrome.snapshot()]
+ ]);
+ },
+ timeoutMessage: 'Joint reader and viewer chrome layout did not reach stable dimensions.'
+ });
+ }
+ };
Archify.view = (function () {
var container = document.querySelector('.diagram-container');
var svg = container.querySelector('svg');
@@ -11445,6 +11261,8 @@
var resetPercentLabel = resetBtn.querySelector('[data-view-percent]');
var inBtn = container.querySelector('[data-view="in"]');
var state = { scale: 1, x: 0, y: 0, mode: 'overview' };
+ var minimumZoom = 0.25;
+ var maximumZoom = 3;
var drag = null;
var cameraTimer = null;
var cameraFrame = null;
@@ -11453,12 +11271,25 @@
var clipFrame = 0;
var resizeFrame = 0;
var autoScrollUntil = 0;
+ var originalFlowHeight = container.style.getPropertyValue('height');
+ var originalFlowHeightPriority = container.style.getPropertyPriority('height');
+ var compactPageFlow = false;
var viewBox = svg.viewBox && svg.viewBox.baseVal;
function clamp() {
var width = svg.clientWidth || 1;
var height = svg.clientHeight || 1;
+ if (state.scale < 1) {
+ var visibleWidth = Math.min(width, container.clientWidth);
+ var availableX = visibleWidth - width * state.scale;
+ state.x = availableX >= 0 ? container.scrollLeft + availableX / 2
+ : Math.max(container.scrollLeft + availableX, Math.min(container.scrollLeft, state.x));
+ // Long sequences keep their first rows in view instead of centering
+ // inside a layout box that can be several screens tall.
+ state.y = height > window.innerHeight ? 0 : height * (1 - state.scale) / 2;
+ return;
+ }
state.x = Math.min(0, Math.max(width - width * state.scale, state.x));
state.y = Math.min(0, Math.max(height - height * state.scale, state.y));
}
@@ -11481,26 +11312,35 @@
function logicalViewport() {
var metrics = contentMetrics();
if (!metrics) return null;
+ var camera = sampleRenderedState();
var x;
var y;
var width;
var height;
- if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram')) {
+ if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram') && camera.scale >= 1) {
x = viewBox.x + container.scrollLeft / metrics.scale;
y = viewBox.y;
width = Math.min(viewBox.width, Math.max(1, container.clientWidth / metrics.scale));
height = viewBox.height;
} else {
- x = viewBox.x + ((-state.x / state.scale) - metrics.offsetX) / metrics.scale;
- y = viewBox.y + ((-state.y / state.scale) - metrics.offsetY) / metrics.scale;
- width = Math.min(viewBox.width, metrics.width / state.scale / metrics.scale);
- height = Math.min(viewBox.height, metrics.height / state.scale / metrics.scale);
+ x = viewBox.x + (((container.scrollLeft - camera.x) / camera.scale) - metrics.offsetX) / metrics.scale;
+ y = viewBox.y + ((-camera.y / camera.scale) - metrics.offsetY) / metrics.scale;
+ width = Math.min(viewBox.width, Math.min(metrics.width, container.clientWidth) / camera.scale / metrics.scale);
+ height = Math.min(viewBox.height, metrics.height / camera.scale / metrics.scale);
}
width = Math.max(1, Math.min(viewBox.width, width));
height = Math.max(1, Math.min(viewBox.height, height));
x = Math.max(viewBox.x, Math.min(viewBox.x + viewBox.width - width, x));
y = Math.max(viewBox.y, Math.min(viewBox.y + viewBox.height - height, y));
- return { x: x, y: y, width: width, height: height, scale: state.scale };
+ // The camera's layout box can span several browser screens. Intersect
+ // its logical bounds with the actual window, including page scrolling.
+ var matrix = svg.getScreenCTM();
+ if (matrix && matrix.d > 0) {
+ var end = y + height;
+ y = Math.max(y, Math.min(end - 1, -matrix.f / matrix.d));
+ height = Math.max(1, Math.min(end, (window.innerHeight - matrix.f) / matrix.d) - y);
+ }
+ return { x: x, y: y, width: width, height: height, scale: camera.scale };
}
function detailLevel() {
if (state.mode === 'semantic') return 'full';
@@ -11530,7 +11370,8 @@
semantic: semantic ? viewerText('viewer.nav.camera.semantic') : '',
hint: detailHint
});
- resetBtn.setAttribute('aria-label', viewerText('viewer.nav.camera', { hint: detailHint }));
+ var readout = (showDetailLevel ? resolvedLevel + ' ' : '') + percent;
+ resetBtn.setAttribute('aria-label', readout + ' · ' + viewerText('viewer.nav.camera', { hint: detailHint }));
resetBtn.setAttribute('data-detail-level', detail);
container.setAttribute('data-detail-level', detail);
container.setAttribute('data-camera-mode', state.mode);
@@ -11558,13 +11399,45 @@
Math.abs(rendered.x - state.x) < 0.05 &&
Math.abs(rendered.y - state.y) < 0.05;
}
+ // CSS transforms keep the SVG's intrinsic layout size. Shrink only its
+ // outer page-flow box for long ordinary diagrams, never the SVG itself:
+ // changing its height would feed the smaller size back into camera math.
+ function ordinaryPage() {
+ var html = document.documentElement;
+ return html.getAttribute('data-embed') !== 'true' &&
+ html.getAttribute('data-present') !== 'true' &&
+ (!window.matchMedia || !window.matchMedia('print').matches);
+ }
+ function syncPageFlow(camera) {
+ camera = camera || state;
+ var height = svg.clientHeight;
+ var ordinary = ordinaryPage();
+ // Restore ordinary flow as soon as the target reaches 100%. Chrome
+ // uses that target to resume baseline rail measurement; retaining a
+ // partially shrunk box during the CSS transition would inflate reserve.
+ if (ordinary && state.scale < 1 && camera.scale < 1 && height > window.innerHeight) {
+ var style = getComputedStyle(container);
+ var chrome = ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']
+ .reduce(function (total, key) { return total + (parseFloat(style[key]) || 0); }, 0);
+ var flowHeight = Math.ceil(height * camera.scale + Math.max(0, camera.y) + chrome) + 'px';
+ if (container.style.getPropertyValue('height') !== flowHeight) container.style.setProperty('height', flowHeight);
+ compactPageFlow = true;
+ } else if (compactPageFlow) {
+ if (originalFlowHeight) container.style.setProperty('height', originalFlowHeight, originalFlowHeightPriority);
+ else container.style.removeProperty('height');
+ compactPageFlow = false;
+ }
+ }
function syncViewportClip() {
if (clipFrame) cancelAnimationFrame(clipFrame);
clipFrame = 0;
function sample() {
clipFrame = 0;
var rendered = sampleRenderedState();
+ syncPageFlow(rendered);
clipToViewport(rendered);
+ if (Archify.radar && Archify.radar.isOpen()) Archify.radar.sync();
+ if (Archify.readerLayout && typeof Archify.readerLayout.syncLegend === 'function') Archify.readerLayout.syncLegend();
if (!cameraSettled(rendered)) clipFrame = requestAnimationFrame(sample);
}
sample();
@@ -11572,12 +11445,12 @@
function apply() {
clamp();
svg.style.transform = 'translate(' + state.x + 'px,' + state.y + 'px) scale(' + state.scale + ')';
+ svg.setAttribute('data-view-scale', String(state.scale));
syncViewportClip();
renderControls();
- outBtn.disabled = state.scale <= 1;
- inBtn.disabled = state.scale >= 3;
+ outBtn.disabled = state.scale <= minimumZoom;
+ inBtn.disabled = state.scale >= maximumZoom;
container.classList.toggle('is-pannable', state.scale > 1);
- svg.setAttribute('data-view-scale', String(state.scale));
if (Archify.radar && typeof Archify.radar.sync === 'function') Archify.radar.sync();
if (Archify.viewerChromeLayout && typeof Archify.viewerChromeLayout.schedule === 'function') {
Archify.viewerChromeLayout.schedule();
@@ -11657,18 +11530,12 @@
container.removeAttribute('data-camera-transaction');
}
function interruptCamera(reason) {
- if (Archify.guidedViews && Archify.guidedViews.cancelHandoff) {
- Archify.guidedViews.cancelHandoff(reason || 'manual');
- }
var rendered = sampleRenderedState();
stopCameraMotion(reason || 'manual', false);
state = rendered;
state.mode = 'manual';
apply();
renderControls();
- if (Archify.guidedViews && Archify.guidedViews.isPlaying && Archify.guidedViews.isPlaying()) {
- Archify.guidedViews.pause();
- }
if (Archify.routeProbe && Archify.routeProbe.isJourneyPlaying && Archify.routeProbe.isJourneyPlaying()) {
Archify.routeProbe.pauseJourney({ preserveElapsed: true, reason: reason || 'manual' });
}
@@ -11677,8 +11544,14 @@
options = options || {};
if (options.manual !== false) interruptCamera();
var previous = state.scale;
- next = Math.max(1, Math.min(3, Math.round(next * 4) / 4));
+ next = Math.max(minimumZoom, Math.min(maximumZoom, Math.round(next * 4) / 4));
if (next === previous) return;
+ var longDiagram = svg.clientHeight > window.innerHeight && Math.min(previous, next) < 1;
+ var before = longDiagram ? svg.getBoundingClientRect() : null;
+ var anchorY = before ? Math.max(0, Math.min(window.innerHeight, before.bottom) + Math.max(0, before.top)) / 2 : 0;
+ if (before && (before.bottom <= 0 || before.top >= window.innerHeight)) anchorY = window.innerHeight / 2;
+ var logicalY = before ? Math.max(0, Math.min(svg.clientHeight, (anchorY - before.top) / previous)) : 0;
+ var documentTop = before ? window.scrollY + before.top - state.y : 0;
var centerX = (svg.clientWidth || 1) / 2;
var centerY = (svg.clientHeight || 1) / 2;
var contentX = (centerX - state.x) / previous;
@@ -11687,6 +11560,12 @@
state.x = centerX - contentX * next;
state.y = centerY - contentY * next;
apply();
+ if (longDiagram) {
+ var scaledHeight = svg.clientHeight * next;
+ var pageY = scaledHeight <= window.innerHeight ? documentTop + state.y
+ : documentTop + state.y + logicalY * next - anchorY;
+ window.scrollTo({ left: window.scrollX, top: Math.max(0, pageY), behavior: 'instant' });
+ }
}
function reset(options) {
options = options || {};
@@ -11695,6 +11574,17 @@
state = { scale: 1, x: 0, y: 0, mode: 'overview' };
apply();
}
+ function scrollLongDiagramTo(contentY, metrics, options) {
+ if (!ordinaryPage() || metrics.height <= window.innerHeight) return;
+ // apply() may still be animating its CSS transform. Recover the layout
+ // origin from the painted transform, then use the final camera target.
+ var painted = sampleRenderedState();
+ var rect = svg.getBoundingClientRect();
+ var pixelScale = rect.height / metrics.height / painted.scale;
+ var documentTop = window.scrollY + rect.top - painted.y * pixelScale;
+ var target = documentTop + (state.y + contentY * state.scale) * pixelScale - window.innerHeight / 2;
+ window.scrollTo({ left: window.scrollX, top: Math.max(0, target), behavior: options.instant ? 'instant' : 'smooth' });
+ }
function centerAt(logicalX, logicalY, options) {
options = options || {};
logicalX = Number(logicalX);
@@ -11713,6 +11603,7 @@
autoScrollUntil = Date.now() + 80;
try { container.scrollTo({ left: mobileTarget, behavior: options.instant ? 'auto' : 'smooth' }); }
catch (_) { container.scrollLeft = mobileTarget; }
+ scrollLongDiagramTo(metrics.offsetY + (logicalY - viewBox.y) * metrics.scale, metrics, options);
return true;
}
var minimumScale = Math.max(1, Math.min(3, Number(options.minimumScale) || 1));
@@ -11724,12 +11615,13 @@
state.y = metrics.height / 2 - contentY * state.scale;
state.mode = 'manual';
apply();
+ scrollLongDiagramTo(contentY, metrics, options);
if (Archify.focus && Archify.focus.reposition) Archify.focus.reposition();
return true;
}
function semanticIds(ids, includeNeighbors) {
- var seeds = {};
- var wanted = {};
+ var seeds = Object.create(null);
+ var wanted = Object.create(null);
(ids || []).forEach(function (id) { seeds[id] = true; wanted[id] = true; });
if (includeNeighbors) {
Array.prototype.forEach.call(svg.querySelectorAll('[data-edge-from][data-edge-to]'), function (edge) {
@@ -11763,8 +11655,8 @@
var maxX = Math.max.apply(Math, boxes.map(function (box) { return box.x + box.width; }));
var maxY = Math.max.apply(Math, boxes.map(function (box) { return box.y + box.height; }));
var bounds = {
- x: contentOffsetX + minX * contentScale,
- y: contentOffsetY + minY * contentScale,
+ x: contentOffsetX + (minX - viewBox.x) * contentScale,
+ y: contentOffsetY + (minY - viewBox.y) * contentScale,
width: Math.max(1, (maxX - minX) * contentScale),
height: Math.max(1, (maxY - minY) * contentScale)
};
@@ -11868,7 +11760,7 @@
if (!boxes.length || !viewBox || viewBox.width <= 0) return false;
var minX = Math.min.apply(Math, boxes.map(function (box) { return box.x; }));
var maxX = Math.max.apply(Math, boxes.map(function (box) { return box.x + box.width; }));
- var center = ((minX + maxX) / 2 / viewBox.width) * (svg.clientWidth || 1);
+ var center = (((minX + maxX) / 2 - viewBox.x) / viewBox.width) * (svg.clientWidth || 1);
var target = Math.max(0, Math.min(svg.clientWidth - container.clientWidth, center - container.clientWidth / 2));
var transaction = cameraReceipt({ scrollLeft: target }, options);
cameraTransaction = transaction;
@@ -11886,9 +11778,6 @@
return transaction;
}
function syncSemantic() {
- var guided = Archify.guidedViews && typeof Archify.guidedViews.focus === 'function'
- ? Archify.guidedViews.focus() : [];
- if (guided && guided.length) return reveal(guided, { reason: 'guided-sync' });
var active = Archify.focus && typeof Archify.focus.active === 'function' ? Archify.focus.active() : null;
if (typeof active === 'string') return reveal([active], { includeNeighbors: true, reason: 'focus-sync' });
if (Array.isArray(active) && active.length) return reveal(active, { reason: 'selection-sync' });
@@ -11946,6 +11835,20 @@
else apply();
});
});
+ // Reader width and Chrome reserve can change without a window resize.
+ // Observe their resulting sizes; the SVG remains intrinsically sized, so
+ // the outer flow height cannot feed back into its camera base.
+ if (typeof ResizeObserver === 'function') {
+ var flowObserver = new ResizeObserver(function () { syncPageFlow(sampleRenderedState()); });
+ flowObserver.observe(svg);
+ flowObserver.observe(container);
+ }
+ if (typeof MutationObserver === 'function') {
+ new MutationObserver(function () { syncPageFlow(sampleRenderedState()); })
+ .observe(document.documentElement, { attributes: true, attributeFilter: ['data-embed', 'data-present'] });
+ }
+ var printMedia = window.matchMedia && window.matchMedia('print');
+ if (printMedia && printMedia.addEventListener) printMedia.addEventListener('change', function () { syncPageFlow(sampleRenderedState()); });
window.addEventListener('hashchange', function () { requestAnimationFrame(syncSemantic); });
apply();
pinControls();
@@ -12345,8 +12248,7 @@
: viewerText('viewer.radar.viewport.scale', { percent: Math.round(visible.scale * 100) }));
status.textContent = viewerText('viewer.radar.status', { count: nodes.length, viewport: viewportCopy });
nodes.forEach(function (item) {
- var active = item.node.hasAttribute('data-focus-selected') ||
- item.node.getAttribute('data-story-beat-state') === 'active';
+ var active = item.node.hasAttribute('data-focus-selected');
if (active) item.rect.setAttribute('data-radar-active', 'true');
else item.rect.removeAttribute('data-radar-active');
});
@@ -12370,6 +12272,7 @@
if (next) {
clearSpaceRetry();
spaceRetryCount = 0;
+ trigger.setAttribute('data-radar-requested', 'true');
build();
attemptRequestedOpen(options);
} else {
@@ -12382,11 +12285,13 @@
resetDockingStyles();
restorePassport();
feedback.hidden = true;
+ // Focus before collapsing: the dock hides this trigger at 100% unless it holds focus.
+ if (options.restoreFocus === true) trigger.focus();
trigger.setAttribute('aria-expanded', 'false');
+ trigger.removeAttribute('data-radar-requested');
trigger.removeAttribute('data-radar-space-limited');
trigger.setAttribute('aria-label', viewerText('viewer.nav.radar'));
trigger.title = viewerText('viewer.nav.radar.title');
- if (options.restoreFocus === true) trigger.focus();
}
return next;
}
@@ -12407,9 +12312,6 @@
function focusNode(id) {
var main = diagram.querySelector('[data-node-id="' + id + '"]');
if (!main) return false;
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
if (Archify.focus && typeof Archify.focus.set === 'function') {
Archify.focus.set(id, { toggle: false });
}
@@ -12594,8 +12496,8 @@
/* ============================================================
Presentation Stage — a shareable, viewport-filling live view.
It changes only HTML layout and URL state; SVG semantics and export
- serialization remain untouched. Escape first clears an active guided
- view/focus, then exits the stage.
+ serialization remain untouched. Escape first clears an active
+ focus, then exits the stage.
============================================================ */
Archify.presentation = (function () {
var html = document.documentElement;
@@ -12668,7 +12570,7 @@
/* ============================================================
Node Finder — stable-ID search over the existing semantic SVG.
Search never changes the IR or SVG geometry: selecting a result resets
- the viewport, releases a guided view, and delegates to semantic focus.
+ the viewport and delegates to semantic focus.
============================================================ */
Archify.finder = (function () {
var html = document.documentElement;
@@ -12790,9 +12692,6 @@
try { item.node.focus({ preventScroll: true }); } catch (_) { try { item.node.focus(); } catch (_) {} }
return true;
}
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
if (Archify.view && typeof Archify.view.reset === 'function') Archify.view.reset({ automatic: true });
Archify.focus.set(id, { toggle: false });
if (Archify.view && typeof Archify.view.reveal === 'function') {
@@ -12830,6 +12729,7 @@
var links = document.createElement('em');
links.textContent = badge;
links.title = context.kind === 'focus' ? badge : action;
+ if (item.links === 0) links.setAttribute('data-zero', 'true');
var meta = document.createElement('small');
meta.textContent = [viewerKindLabel(item.type), item.id, item.sublabel, item.tag].filter(Boolean).join(' \u00b7 ');
meta.title = [viewerKindLabel(item.type), item.id, item.context, item.sublabel, item.tag].filter(Boolean).join(' \u00b7 ');
@@ -12931,6 +12831,146 @@
};
})();
+ /* ============================================================
+ Node Outline — a rail index of the semantic nodes, grouped by their
+ authored context. Hover previews neighbors through Intent Trace;
+ selection delegates to the Finder's focus-and-reveal path. It reads
+ the canonical SVG and never changes geometry or export state.
+ ============================================================ */
+ Archify.outline = (function () {
+ var panel = document.getElementById('node-outline');
+ var list = document.getElementById('node-outline-list');
+ var count = document.getElementById('node-outline-count');
+ var svg = document.querySelector('.diagram-container > svg');
+ if (!panel || !list || !svg) return { count: 0 };
+ var TONES = ['frontend', 'backend', 'database', 'cloud', 'security', 'messagebus', 'external'];
+ var nodes = Array.from(svg.querySelectorAll('[data-node-id]')).filter(function (node) {
+ return !node.closest('[data-legend-hit], .legend') && node.getAttribute('data-node-label');
+ });
+ var buttons = Object.create(null);
+
+ function tone(node) {
+ var shape = node.querySelector('[class*="c-"]:not(.c-mask)');
+ var match = shape && /(?:^|\s)c-([a-z]+)/.exec(shape.getAttribute('class') || '');
+ return match && TONES.indexOf(match[1]) !== -1 ? match[1] : 'external';
+ }
+ function preview(id) {
+ if (Archify.intentTrace && typeof Archify.intentTrace.show === 'function') Archify.intentTrace.show(id);
+ }
+ function clearPreview() {
+ if (Archify.intentTrace && typeof Archify.intentTrace.clear === 'function') Archify.intentTrace.clear({ announce: false });
+ }
+ function select(id) {
+ clearPreview();
+ var finder = Archify.finder;
+ if (finder && typeof finder.select === 'function') {
+ if (finder.select(id)) return;
+ var routeMode = Archify.routeProbe && typeof Archify.routeProbe.active === 'function' ? Archify.routeProbe.active() : 'idle';
+ // Only an active endpoint picker owns a refused selection.
+ if (routeMode === 'source' || routeMode === 'target') return;
+ }
+ if (Archify.focus && typeof Archify.focus.set === 'function') Archify.focus.set(id, { toggle: false });
+ }
+
+ var groups = [];
+ var byContext = Object.create(null);
+ nodes.forEach(function (node) {
+ // Group by the outermost context (lane or stage); deeper segments
+ // such as workflow groups and columns would split the index into
+ // one-node sections.
+ var context = (node.getAttribute('data-node-context') || '').split(' \u203a ')[0];
+ if (!byContext[context]) {
+ byContext[context] = { label: context, nodes: [] };
+ groups.push(byContext[context]);
+ }
+ byContext[context].nodes.push(node);
+ });
+
+ groups.forEach(function (group) {
+ var section = document.createElement('li');
+ section.className = 'node-outline-group';
+ if (groups.length > 1 && group.label) {
+ var heading = document.createElement('span');
+ heading.className = 'node-outline-heading';
+ var headingLabel = document.createElement('span');
+ headingLabel.textContent = group.label;
+ var headingCount = document.createElement('small');
+ headingCount.textContent = String(group.nodes.length);
+ heading.appendChild(headingLabel);
+ heading.appendChild(headingCount);
+ section.appendChild(heading);
+ }
+ var items = document.createElement('ul');
+ group.nodes.forEach(function (node) {
+ var id = node.getAttribute('data-node-id');
+ var item = document.createElement('li');
+ var button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'node-outline-item';
+ button.setAttribute('data-outline-node', id);
+ button.style.setProperty('--outline-tone', 'var(--' + tone(node) + '-stroke)');
+ var dot = document.createElement('span');
+ dot.className = 'node-outline-dot';
+ dot.setAttribute('aria-hidden', 'true');
+ var label = document.createElement('strong');
+ label.textContent = node.getAttribute('data-node-label');
+ button.appendChild(dot);
+ button.appendChild(label);
+ var sublabel = node.getAttribute('data-node-sublabel');
+ if (sublabel) {
+ var detail = document.createElement('small');
+ detail.textContent = sublabel;
+ button.appendChild(detail);
+ }
+ button.addEventListener('pointerenter', function () { preview(id); });
+ button.addEventListener('focus', function () { preview(id); });
+ button.addEventListener('pointerleave', clearPreview);
+ button.addEventListener('blur', clearPreview);
+ button.addEventListener('click', function () { select(id); });
+ buttons[id] = button;
+ item.appendChild(button);
+ items.appendChild(item);
+ });
+ section.appendChild(items);
+ list.appendChild(section);
+ });
+
+ var previewing = null;
+ function syncCurrent() {
+ nodes.forEach(function (node) {
+ var button = buttons[node.getAttribute('data-node-id')];
+ if (!button) return;
+ if (node.getAttribute('aria-pressed') === 'true') button.setAttribute('aria-current', 'true');
+ else button.removeAttribute('aria-current');
+ });
+ // Mirror a diagram-side hover so the index answers "where is this?".
+ var active = buttons[svg.getAttribute('data-intent-trace-active') || ''] || null;
+ if (active === previewing) return;
+ if (previewing) previewing.removeAttribute('data-previewing');
+ previewing = active;
+ if (!active) return;
+ active.setAttribute('data-previewing', '');
+ if (!active.matches(':hover') && panel.offsetParent) {
+ var box = list.getBoundingClientRect();
+ var item = active.getBoundingClientRect();
+ if (item.top < box.top || item.bottom > box.bottom - 24) {
+ list.scrollTop += item.top - box.top - box.height / 2 + item.height / 2;
+ }
+ }
+ }
+ if (typeof MutationObserver === 'function') {
+ new MutationObserver(syncCurrent).observe(svg, { attributes: true, subtree: true, attributeFilter: ['aria-pressed', 'data-intent-trace-active'] });
+ }
+ if (count) count.textContent = String(nodes.length);
+ panel.hidden = nodes.length < 2;
+ syncCurrent();
+ if (Archify.readerLayout && typeof Archify.readerLayout.schedule === 'function') Archify.readerLayout.schedule();
+
+ return { count: nodes.length, select: select };
+ })();
+
+
+
/* ============================================================
Route Probe — shortest directed path over compiled semantics.
The graph is read from renderer-owned stable IDs and relationship
@@ -13037,7 +13077,7 @@
}
function edgeShapes(edge) {
if (/^(path|line|polyline)$/i.test(edge.tagName)) return [edge];
- return Array.prototype.slice.call(edge.querySelectorAll('path, line, polyline'));
+ return Array.prototype.slice.call(edge.querySelectorAll('path:not([data-ambient-flow-overlay]), line, polyline'));
}
function removeOverlay() {
Array.prototype.forEach.call(svg.querySelectorAll('[data-route-probe-overlay]'), function (overlay) {
@@ -13197,7 +13237,7 @@
}
function outgoingByNode() {
var byId = nodesById();
- var outgoing = {};
+ var outgoing = Object.create(null);
edges().forEach(function (edge) {
var from = edge.getAttribute('data-edge-from');
var to = edge.getAttribute('data-edge-to');
@@ -13209,7 +13249,7 @@
}
function reachableFrom(source) {
var outgoing = outgoingByNode();
- var reached = {};
+ var reached = Object.create(null);
var queue = [source];
reached[source] = true;
for (var cursor = 0; cursor < queue.length; cursor += 1) {
@@ -13224,7 +13264,7 @@
}
function hopDistancesFrom(source) {
var outgoing = outgoingByNode();
- var distances = {};
+ var distances = Object.create(null);
var queue = [source];
distances[source] = 0;
for (var cursor = 0; cursor < queue.length; cursor += 1) {
@@ -13240,7 +13280,7 @@
function shortestDirectedPath(source, target) {
if (source === target) return null;
var outgoing = outgoingByNode();
- var previous = {};
+ var previous = Object.create(null);
var queue = [source];
previous[source] = null;
for (var cursor = 0; cursor < queue.length && !Object.prototype.hasOwnProperty.call(previous, target); cursor += 1) {
@@ -13267,6 +13307,8 @@
}
function traceGeometry(shape, step) {
var clone = shape.cloneNode(false);
+ if (shape.getAttribute('data-motion-path')) clone.setAttribute('d', shape.getAttribute('data-motion-path'));
+ clone.removeAttribute('data-motion-path');
clone.removeAttribute('id');
clone.removeAttribute('class');
clone.removeAttribute('style');
@@ -13367,6 +13409,8 @@
}
function journeyGeometry(shape) {
var clone = shape.cloneNode(false);
+ if (shape.getAttribute('data-motion-path')) clone.setAttribute('d', shape.getAttribute('data-motion-path'));
+ clone.removeAttribute('data-motion-path');
clone.removeAttribute('id');
clone.removeAttribute('class');
clone.removeAttribute('style');
@@ -13727,9 +13771,6 @@
if (Array.isArray(focused)) focused = null;
clear({ updateUrl: false, preserveView: true, restoreFocus: false });
if (Archify.intentTrace && typeof Archify.intentTrace.clear === 'function') Archify.intentTrace.clear({ announce: false });
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
if (Archify.focus && typeof Archify.focus.clear === 'function') {
Archify.focus.clear({ updateUrl: false, preserveView: true });
}
@@ -13770,7 +13811,7 @@
var sourceIds = nodes().map(function (node) { return node.getAttribute('data-node-id'); }).filter(function (id) {
return outgoing[id] && outgoing[id].length;
});
- var sourceBadges = {};
+ var sourceBadges = Object.create(null);
sourceIds.forEach(function (id) { sourceBadges[id] = viewerText('viewer.route.finder.source.badge'); });
return {
kind: 'route-source',
@@ -13786,7 +13827,7 @@
if (mode === 'target' && startId && byId[startId]) {
var distances = hopDistancesFrom(startId);
var targetIds = Object.keys(distances).filter(function (id) { return id !== startId && byId[id]; });
- var targetBadges = {};
+ var targetBadges = Object.create(null);
targetIds.forEach(function (id) {
targetBadges[id] = viewerCount('viewer.route.hop', distances[id]);
});
@@ -13817,26 +13858,10 @@
if (!context || !Archify.finder) return false;
return Archify.finder.open({ context: context });
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (mode !== 'result') return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId);
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('route=' + encodeURIComponent(startId) + '~' + encodeURIComponent(endId));
+ return (value === null ? Promise.resolve(false) : copyReaderText(value)).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
copyBtn.setAttribute('aria-label', viewerText(copied ? 'viewer.route.copy.success' : 'viewer.route.copy.failed'));
window.setTimeout(function () {
@@ -13966,6 +13991,7 @@
};
})();
+
/* ============================================================
Semantic Lens — a counted, viewer-only legend over data-node-kind.
One selected kind reveals every authored relationship touching it.
@@ -13995,7 +14021,7 @@
var MAX_LENS_FLOW_EDGES = 24;
function nodesById() {
- var byId = {};
+ var byId = Object.create(null);
Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id][data-node-kind]'), function (node) {
var id = node.getAttribute('data-node-id');
if (id && !byId[id]) byId[id] = node;
@@ -14029,7 +14055,7 @@
function edgeShapes(edge) {
if (!edge) return [];
if (/^(path|line|polyline)$/i.test(edge.tagName || '')) return [edge];
- return Array.prototype.slice.call(edge.querySelectorAll('path, line, polyline'));
+ return Array.prototype.slice.call(edge.querySelectorAll('path:not([data-ambient-flow-overlay]), line, polyline'));
}
function legendSourceBounds(entry) {
var bounds = null;
@@ -14151,7 +14177,7 @@
return selectedKinds.length > 0 || !panel.hidden || html.getAttribute('data-present') === 'true' ||
svg.hasAttribute('data-focus-active') || svg.hasAttribute('data-intent-trace-active') ||
svg.hasAttribute('data-route-picking') || svg.hasAttribute('data-route-active') ||
- svg.hasAttribute('data-story-active') || svg.hasAttribute('data-relationship-preview-active');
+ svg.hasAttribute('data-relationship-preview-active');
}
function previewLegendKind(entry) {
clearLegendPreview();
@@ -14162,7 +14188,7 @@
return (byId[id].getAttribute('data-node-kind') || 'neutral') === kind;
});
if (!matches.length) return false;
- var chosen = {};
+ var chosen = Object.create(null);
matches.forEach(function (id) {
chosen[id] = true;
byId[id].setAttribute('data-legend-preview-match', '');
@@ -14202,6 +14228,8 @@
}
function flowGeometry(shape, direction, step) {
var clone = shape.cloneNode(false);
+ if (shape.getAttribute('data-motion-path')) clone.setAttribute('d', shape.getAttribute('data-motion-path'));
+ clone.removeAttribute('data-motion-path');
clone.removeAttribute('id');
clone.removeAttribute('class');
clone.removeAttribute('style');
@@ -14338,7 +14366,7 @@
options = options || {};
cleanSvgState();
var byId = nodesById();
- var nodeKind = {};
+ var nodeKind = Object.create(null);
Object.keys(byId).forEach(function (id) { nodeKind[id] = byId[id].getAttribute('data-node-kind') || 'neutral'; });
if (!selectedKinds.length) {
status.textContent = viewerText('viewer.lens.choose');
@@ -14423,9 +14451,6 @@
if (Archify.routeProbe && typeof Archify.routeProbe.clear === 'function') {
Archify.routeProbe.clear({ updateUrl: false, restoreFocus: false });
}
- if (Archify.guidedViews && typeof Archify.guidedViews.showAll === 'function') {
- Archify.guidedViews.showAll({ clearFocus: false, updateUrl: false });
- }
if (Archify.intentTrace && typeof Archify.intentTrace.clear === 'function') {
Archify.intentTrace.clear({ announce: false });
}
@@ -14488,28 +14513,16 @@
if (options.closePanel === true) close({ restoreFocus: false });
return false;
}
- function fallbackCopy(value) {
- var field = document.createElement('textarea');
- field.value = value;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.appendChild(field);
- field.select();
- var copied = false;
- try { copied = document.execCommand('copy'); } catch (_) {}
- field.remove();
- return copied;
- }
function copyLink() {
if (!selectedKinds.length) return Promise.resolve(false);
- var value = location.href.replace(/#.*$/, '') + '#lens=' + selectedKinds.map(encodeURIComponent).join('~');
- var copy = navigator.clipboard && typeof navigator.clipboard.writeText === 'function'
- ? navigator.clipboard.writeText(value).then(function () { return true; }).catch(function () { return fallbackCopy(value); })
- : Promise.resolve(fallbackCopy(value));
- return copy.then(function (copied) {
+ var value = readerLink('lens=' + selectedKinds.map(encodeURIComponent).join('~'));
+ return (value === null ? Promise.resolve(false) : copyReaderText(value)).then(function (copied) {
copyBtn.textContent = viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed');
- window.setTimeout(function () { copyBtn.textContent = viewerText('viewer.common.copyLink'); }, 1600);
+ copyBtn.setAttribute('aria-label', viewerText(copied ? 'viewer.common.copied' : 'viewer.common.copyFailed'));
+ window.setTimeout(function () {
+ copyBtn.textContent = viewerText('viewer.common.copyLink');
+ copyBtn.setAttribute('aria-label', viewerText('viewer.lens.copy'));
+ }, 1600);
return copied;
});
}
@@ -14642,10 +14655,11 @@
};
})();
+
/* ============================================================
Diagram Guide — a factual command deck over existing interactions.
Counts come from compiled semantics; actions delegate to Finder, Route
- Probe, Semantic Radar, Semantic Lens, Story Trail, Presentation, theme, export, and
+ Probe, Semantic Radar, Semantic Lens, Presentation, theme, export, and
camera without adding a second command implementation or SVG state.
============================================================ */
Archify.guide = (function () {
@@ -14658,13 +14672,9 @@
var stats = document.getElementById('diagram-guide-stats');
var actions = document.getElementById('diagram-guide-actions');
var feedback = document.getElementById('diagram-guide-feedback');
- var storyBtn = actions.querySelector('[data-guide-action="story"]');
- var storyCopy = document.getElementById('diagram-guide-story-copy');
var routePanel = document.getElementById('route-probe');
+ var returnFocus = null;
- function viewCount() {
- return Archify.guidedViews && Number(Archify.guidedViews.count) || 0;
- }
function relationshipCount() {
var seen = {};
Array.prototype.forEach.call(svg.querySelectorAll('[data-edge-from][data-edge-to]'), function (edge) {
@@ -14680,17 +14690,10 @@
function renderFacts() {
var nodes = svg.querySelectorAll('[data-node-id]').length;
var relationships = relationshipCount();
- var views = viewCount();
stats.textContent = viewerText('viewer.guide.facts', {
nodes: viewerCount('viewer.guide.fact.node', nodes),
- relationships: viewerCount('viewer.guide.fact.relationship', relationships),
- views: viewerCount('viewer.guide.fact.view', views)
+ relationships: viewerCount('viewer.guide.fact.relationship', relationships)
});
- storyBtn.disabled = views === 0;
- storyBtn.setAttribute('aria-disabled', views === 0 ? 'true' : 'false');
- storyCopy.textContent = views
- ? viewerCount('viewer.guide.story.available', views)
- : viewerText('viewer.guide.story.unavailable');
}
function actionButtons() {
return Array.prototype.slice.call(actions.querySelectorAll('.diagram-guide-action:not(:disabled)'));
@@ -14703,7 +14706,12 @@
trigger.setAttribute('aria-expanded', 'false');
trigger.setAttribute('aria-label', viewerText('viewer.guide.open'));
feedback.textContent = '';
- if (options.restoreFocus !== false) trigger.focus();
+ if (options.restoreFocus !== false) {
+ // Return focus where the reader was when the guide opened; the
+ // trigger itself is only the fallback when that element is gone.
+ var target = returnFocus && returnFocus.isConnected ? returnFocus : trigger;
+ if (target && typeof target.focus === 'function') target.focus();
+ }
return false;
}
function open() {
@@ -14713,12 +14721,10 @@
if (Archify.finder && Archify.finder.isOpen()) Archify.finder.close({ restoreFocus: false });
if (Archify.radar && Archify.radar.isOpen()) Archify.radar.close({ restoreFocus: false });
if (Archify.semanticLens && Archify.semanticLens.isOpen()) Archify.semanticLens.close({ restoreFocus: false });
- if (Archify.guidedViews && Archify.guidedViews.isPlaying && Archify.guidedViews.isPlaying()) {
- Archify.guidedViews.pause();
- }
if (Archify.routeProbe && Archify.routeProbe.isJourneyPlaying && Archify.routeProbe.isJourneyPlaying()) {
Archify.routeProbe.pauseJourney({ preserveElapsed: true, reason: 'guide' });
}
+ returnFocus = document.activeElement;
renderFacts();
panel.hidden = false;
html.setAttribute('data-guide-open', 'true');
@@ -14735,16 +14741,11 @@
function toggle() { return panel.hidden ? open() : close(); }
function execute(action) {
feedback.textContent = '';
- if (action === 'story' && !viewCount()) {
- feedback.textContent = viewerText('viewer.guide.noStory');
- return false;
- }
close({ restoreFocus: false });
if (action === 'find') return Archify.finder.open();
if (action === 'route') return Archify.routeProbe.begin({ focusNode: true });
if (action === 'map') return Archify.radar.open();
if (action === 'lens') return Archify.semanticLens.open();
- if (action === 'story') return Archify.guidedViews.play();
if (action === 'present') return Archify.presentation.enter();
if (action === 'export') return Archify.exportMenu.open();
if (action === 'theme') return Archify.theme.toggle();
@@ -14760,7 +14761,6 @@
r: 'route',
m: 'map',
l: 'lens',
- p: 'story',
f: 'present',
e: 'export',
t: 'theme',
@@ -14809,7 +14809,9 @@
execute(action);
});
document.addEventListener('click', function (event) {
- if (!panel.hidden && !panel.contains(event.target) && event.target !== trigger) close({ restoreFocus: false });
+ // Clicks anywhere on the trigger (including its icon span) are the
+ // toggle itself, never an outside dismissal.
+ if (!panel.hidden && !panel.contains(event.target) && !trigger.contains(event.target)) close({ restoreFocus: false });
});
renderFacts();
@@ -14822,8 +14824,7 @@
facts: function () {
return {
nodes: svg.querySelectorAll('[data-node-id]').length,
- relationships: relationshipCount(),
- views: viewCount()
+ relationships: relationshipCount()
};
}
};