Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
Refine Viewer reading scale, zoom and source presentation
tt-a1i4bd30135dea4
diff --git a/archify/assets/template.html b/archify/assets/template.htmlindex 07a511d4..21477664 100644--- a/archify/assets/template.html+++ b/archify/assets/template.html@@ -599,15 +599,29 @@ OTHER DEALINGS IN THE FONT SOFTWARE.color: var(--frontend-stroke);}- /* The reader owns only the outer scale. Wide diagrams and measured tall workflows keep one authored- SVG/viewBox while the runtime chooses a desktop width from the actual- vertical budget. This avoids device-specific files and breakpoint- jumps between a laptop and a tall monitor. */+ /* The reader owns only the outer scale. Long sequences and waterfall rows+ favor reading width and page scroll; other diagrams keep height fitting.+ Small automatic canvases retain a modest scale inside a usable shell.+ Every strategy preserves the authored SVG/viewBox and semantic geometry. */.container {width: 100%;max-width: var(--archify-reader-width, 1440px);margin: 0 auto;}+ html[data-reader-area="true"] .diagram-container {+ min-height: var(--archify-diagram-min-height);+ display: flex;+ align-items: center;+ }+ html[data-reader-area="true"] .diagram-container > svg { flex-shrink: 0; }+ /* The original SVG legend can use the spare outer reader canvas while the+ capped diagram stays centered. The container still clips all outer paint. */+ .diagram-container:has([data-reader-legend-corner]) > svg { overflow: visible; }+ .diagram-container [data-reader-legend-corner] {+ transform-origin: 0 0;+ transform-box: view-box;+ transform: var(--archify-reader-legend-transform);+ }html[data-reader-narrow="true"]:not([data-present="true"]) .diagram-container > svg {min-width: 0;max-width: var(--archify-diagram-max-width);@@ -4178,41 +4192,6 @@ OTHER DEALINGS IN THE FONT SOFTWARE.filter: drop-shadow(0 0 7px var(--frontend-stroke));outline: none;}- /* Verified Source Beacons are installed at runtime only for nodes whose- repository evidence passed the local revision/blob/line checks. They- live inside the owning node so every focus, route, story, and guided- view keeps one coherent opacity state. Export serialization removes- them before producing the canonical SVG or any derived visual. */- .source-evidence-beacon {- pointer-events: none;- opacity: 1;- transition: filter 160ms ease;- }- .source-evidence-beacon rect {- fill: color-mix(in srgb, var(--mask) 92%, var(--backend-stroke));- stroke: color-mix(in srgb, var(--backend-stroke) 82%, var(--panel-border));- stroke-width: 1;- vector-effect: non-scaling-stroke;- }- .source-evidence-beacon text {- fill: var(--backend-stroke);- font-size: 7px;- font-weight: 700;- letter-spacing: 0.06em;- text-anchor: middle;- text-transform: uppercase;- }- svg [data-node-id]:hover .source-evidence-beacon,- svg [data-node-id]:focus-visible .source-evidence-beacon,- svg [data-node-id][data-focus-selected] .source-evidence-beacon {- opacity: 1;- filter: drop-shadow(0 0 4px color-mix(in srgb, var(--backend-stroke) 72%, transparent));- }- svg[data-preset="signal-flow"] .source-evidence-beacon { opacity: 0.9; }- svg[data-preset="blueprint"] .source-evidence-beacon rect {- rx: 0.8px;- filter: none;- }svg [data-legend-kind][role="button"] { cursor: pointer; }svg [data-legend-kind]:focus { outline: none; }svg [data-legend-hit] {@@ -4871,7 +4850,6 @@ OTHER DEALINGS IN THE FONT SOFTWARE.filter: none;}.relationship-pulse-overlay { display: none !important; }- .source-evidence-beacon,svg [data-node-id], svg [data-edge-from], svg [data-detail], svg [data-detail-anchor], svg [data-legend-hit], svg { transition: none !important; }}</style>@@ -5673,6 +5651,10 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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();});@@ -5810,7 +5792,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.!clone.hasAttribute('data-tree-any-collapsed') &&!clone.style.getPropertyValue('transform') &&!clone.style.getPropertyValue('clip-path') &&- clone.querySelectorAll('[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;+ clone.querySelectorAll('[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;}@@ -7411,83 +7393,23 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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') ? 22 : 0;- var title = document.createElementNS(svgNamespace, 'title');- title.textContent = label;- var plate = document.createElementNS(svgNamespace, 'rect');- plate.setAttribute('height', '13');- plate.setAttribute('rx', '6.5');- var text = document.createElementNS(svgNamespace, 'text');- text.setAttribute('y', '9.4');- text.textContent = viewerText('viewer.passport.sourceMarker') + ' ' + count;- beacon.appendChild(title);- beacon.appendChild(plate);- beacon.appendChild(text);- node.appendChild(beacon);-- // Measure the real glyph advance, then clamp the plate between 24- // and 36px; a still-wider label is squeezed with textLength so the- // badge never overlaps the neighbouring brand mark or sigil.- var textWidth = 16;- try {- var measured = text.getComputedTextLength();- if (Number.isFinite(measured) && measured > 0) textWidth = measured;- } catch (_) {}- var plateWidth = Math.min(36, Math.max(24, textWidth + 8));- if (textWidth > plateWidth - 8) {- text.setAttribute('textLength', String(plateWidth - 8));- text.setAttribute('lengthAdjust', 'spacingAndGlyphs');- }- plate.setAttribute('width', String(plateWidth));- text.setAttribute('x', String(plateWidth / 2));- beacon.setAttribute('transform', 'translate(' + (box.x + box.width - 6 - brandOffset - plateWidth) + ' ' + (box.y + 4.5) + ')');-- 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;- }return {available: function () { return Boolean(payload); },repository: function () { return payload ? payload.repository : null; },+ // Compatibility only: sources are shown in the Focus card.+ installBeacons: function () { return 0; },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@@ -9172,6 +9094,13 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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();});@@ -9512,14 +9441,18 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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 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 measuredHeightFit = svg && svg.getAttribute('data-reader-fit') === 'intrinsic-height';+ var widthFirstReading = measuredHeightFit && svg &&+ (svg.hasAttribute('data-sequence-column-fit') || svg.hasAttribute('data-waterfall-ui'));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@@ -9529,6 +9462,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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)@@ -9640,12 +9574,60 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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. Only ordinary capped+ // reading at 25–100% borrows the spare outer canvas for its legend.+ function syncLegend() {+ var cameraScale = Number(svg && svg.getAttribute('data-view-scale')) || 1;+ if (!legend || !eligible() || html.getAttribute('data-reader-area') !== 'true' || 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);+ 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@@ -9707,22 +9689,36 @@ OTHER DEALINGS IN THE FONT SOFTWARE.// 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));- if (Math.abs(rounded - lastWidth) < 1) return false;+ var changed = Math.abs(rounded - lastWidth) >= 1;lastWidth = rounded;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');- if (rounded < shellFloor) {- // `rounded` already includes a docked rail and its gap; the SVG cap- // is only the diagram's share, not the space beside it.- var railShare = html.getAttribute('data-reader-rail') === 'true' ? RAIL_WIDTH + RAIL_GAP : 0;- html.style.setProperty('--archify-diagram-max-width', Math.max(1, rounded - railShare - chromeMetrics().diagramX) + '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);@@ -9734,7 +9730,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.document.documentElement.scrollHeight,document.body.scrollHeight) - window.innerHeight - belowFold();- if (overflow > 1 && lastWidth > Math.ceil(minWidth)) {+ if (overflow > 1 && !widthFirstReading && lastWidth > Math.ceil(minWidth)) {applyWidth(Math.max(minWidth, lastWidth - overflow * ratio - 4), minWidth);settledCap = lastWidth;html.setAttribute('data-reader-overflow', 'reduced');@@ -9785,10 +9781,9 @@ OTHER DEALINGS IN THE FONT SOFTWARE.if (collapsedPreference === '1' || (collapsedPreference !== '0' && !comfortable)) mode = 'collapsed';else mode = fitsReadable ? 'true' : 'overlay';}- // With notes below the fold, the first screen belongs to the whole- // diagram and its controls: it may shrink past the comfortable primary- // size down to the renderer's readable text floor, and zoom restores- // detail. Only a graph taller than that floor allows still scrolls.+ // 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';@@ -9800,6 +9795,13 @@ OTHER DEALINGS IN THE FONT SOFTWARE.outerHeight(header) + stackedBelow;var availableSvgHeight = Math.max(1, window.innerHeight - fixedHeight);var desiredWidth = availableSvgHeight * ratio + chrome.diagramX + (docked ? railExtra : 0);+ // Long sequences and waterfall rows use the available horizontal room;+ // ordinary page scrolling keeps their text and row spacing readable.+ // Other diagram families retain the existing height-fit strategy.+ if (widthFirstReading) 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);@@ -9828,7 +9830,8 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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); }@@ -9847,6 +9850,8 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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);@@ -9889,6 +9894,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.measure: measure,schedule: schedule,whenStable: whenStable,+ syncLegend: syncLegend,active: function () { return html.getAttribute('data-reader-layout') === 'adaptive'; },receipt: function () { return { ratio: ratio, width: lastWidth }; }};@@ -10294,6 +10300,8 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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;@@ -10308,6 +10316,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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));}@@ -10334,15 +10352,15 @@ OTHER DEALINGS IN THE FONT SOFTWARE.var y;var width;var height;- if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram')) {+ if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram') && state.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;+ x = viewBox.x + (((container.scrollLeft - 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);+ width = Math.min(viewBox.width, Math.min(metrics.width, container.clientWidth) / state.scale / metrics.scale);height = Math.min(viewBox.height, metrics.height / state.scale / metrics.scale);}width = Math.max(1, Math.min(viewBox.width, width));@@ -10414,6 +10432,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.clipFrame = 0;var rendered = sampleRenderedState();clipToViewport(rendered);+ if (Archify.readerLayout && typeof Archify.readerLayout.syncLegend === 'function') Archify.readerLayout.syncLegend();if (!cameraSettled(rendered)) clipFrame = requestAnimationFrame(sample);}sample();@@ -10421,12 +10440,12 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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();@@ -10520,8 +10539,14 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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;@@ -10530,6 +10555,12 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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 || {};diff --git a/test/architecture-reading-size-browser.test.mjs b/test/architecture-reading-size-browser.test.mjsindex 1e156c55..1edf6e54 100644--- a/test/architecture-reading-size-browser.test.mjs+++ b/test/architecture-reading-size-browser.test.mjs@@ -30,6 +30,7 @@ test('automatic architectures preserve primary reading size when fitting the fulreturn result.result?.value;};let geometry;+ let compactRailCases = 0;for (const [width, height] of [[1440, 900], [1600, 900], [2048, 1320]]) {await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });const loaded = browser.cdp.waitFor('Page.loadEventFired', session);@@ -43,15 +44,30 @@ test('automatic architectures preserve primary reading size when fitting the fulconst toolbar = document.querySelector('.toolbar').getBoundingClientRect();const guide = document.querySelector('.diagram-container').getBoundingClientRect();const svg = document.querySelector('.diagram-container > svg');+ const stage = svg.getBoundingClientRect();+ const nav = document.querySelector('.diagram-nav').getBoundingClientRect();+ const overlapWidth = Math.max(0, Math.min(stage.right, nav.right) - Math.max(stage.left, nav.left));+ const overlapHeight = Math.max(0, Math.min(stage.bottom, nav.bottom) - Math.max(stage.top, nav.top));return { rail: document.documentElement.dataset.navStageRail, summaryRail: document.documentElement.dataset.readerRail || null,toolbarBottom: toolbar.bottom, guideTop: guide.top, guideWidth: guide.width,+ navWidth: nav.width, navHeight: nav.height,+ navStageOverlap: overlapWidth * overlapHeight,+ navStageGap: Math.max(nav.top - stage.bottom, stage.top - nav.bottom, nav.left - stage.right, stage.left - nav.right),primaryFont: Math.min(...Array.from(svg.querySelectorAll('text[data-node-label]')).map(text => parseFloat(text.getAttribute('font-size')) * svg.getBoundingClientRect().width / svg.viewBox.baseVal.width)),scrollWidth: document.documentElement.scrollWidth,geometry: [svg.getAttribute('viewBox'), ...Array.from(svg.querySelectorAll('[data-node-id]')).map(node =>[node.getAttribute('transform'), ...Array.from(node.querySelectorAll('text')).map(text => text.getAttribute('font-size'))])] };})()`);const label = `${width}x${height}/${theme}`;- assert.equal(observed.rail, 'true', label + ': fixture must exercise the compact rail');+ // Compact viewports still exercise the real stage rail. On a taller+ // screen the independently capped SVG can leave enough normal canvas+ // space for in-canvas navigation; either placement must clear the stage.+ if (width <= 1600) assert.equal(observed.rail, 'true', label + ': compact fixture must exercise the stage rail');+ else assert.ok(observed.rail === undefined || observed.rail === 'true', label + ': unexpected navigation placement');+ if (observed.rail === 'true') compactRailCases += 1;+ assert.ok(observed.navWidth > 0 && observed.navHeight > 0, label + ': navigation must be visible');+ assert.equal(observed.navStageOverlap, 0, label + ': navigation overlaps graph stage ' + JSON.stringify(observed));+ assert.ok(observed.navStageGap >= 9.99, label + ': navigation lacks its 10px stage clearance ' + JSON.stringify(observed));assert.ok(observed.guideWidth > 0, label + ': diagram must be visible');assert.ok(observed.guideTop >= observed.toolbarBottom + 4, label + ': toolbar overlaps diagram ' + JSON.stringify(observed));assert.ok(observed.scrollWidth <= width, label + ': horizontal overflow');@@ -63,6 +79,7 @@ test('automatic architectures preserve primary reading size when fitting the fulelse geometry = observed.geometry;}}+ assert.ok(compactRailCases >= 4, 'both themes at 1440 and 1600 must exercise real compact-stage clearance');} finally {await browser.close();fs.rmSync(dir, { recursive: true, force: true });diff --git a/test/brand-marks.test.mjs b/test/brand-marks.test.mjsindex 41b08dc8..d208853e 100644--- a/test/brand-marks.test.mjs+++ b/test/brand-marks.test.mjs@@ -788,11 +788,11 @@ test('unknown preset names fail with a repairable public CLI diagnostic', () =>assert.ok(receipt.diagnostics.some((entry) => entry.supportedFixes.some((fix) => fix.includes('archify brands'))));});-test('viewer exposes brand identity to Passport and Finder while keeping source beacons clear', () => {+test('viewer exposes brand identity to Passport and Finder with sources in the Focus card', () => {const template = fs.readFileSync(path.join(skillRoot, 'assets', 'template.html'), 'utf8');assert.match(template, /id="focus-brand" data-passport="brand" hidden/);assert.match(template, /node\.getAttribute\('data-node-brand'\)/);- assert.match(template, /brandOffset = node\.hasAttribute\('data-node-brand'\) \? 22 : 0/);+ assert.doesNotMatch(template, /Archify\.sourceEvidence\.installBeacons\(\)|classList\.add\('source-evidence-beacon'\)/);assert.match(template, /sourceSearch \+ ' ' \+ text\)\.toLowerCase\(\) \+ ' ' \+ brand\.toLowerCase\(\)/);});diff --git a/test/compact-header-clearance.test.mjs b/test/compact-header-clearance.test.mjsindex c8173164..485b74e2 100644--- a/test/compact-header-clearance.test.mjs+++ b/test/compact-header-clearance.test.mjs@@ -8,7 +8,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');-test('compact stage rail keeps the diagram below the toolbar', async (t) => {+test('compact stage rail and in-canvas navigation keep the diagram clear of toolbar and controls', async (t) => {if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');const chrome = findChrome();assert.ok(chrome);@@ -30,6 +30,7 @@ test('compact stage rail keeps the diagram below the toolbar', async (t) => {return result.result?.value;};let geometry;+ let compactRailCases = 0;for (const [width, height] of [[1440, 900], [1600, 900], [2048, 1320]]) {await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });const loaded = browser.cdp.waitFor('Page.loadEventFired', session);@@ -43,14 +44,29 @@ test('compact stage rail keeps the diagram below the toolbar', async (t) => {const toolbar = document.querySelector('.toolbar').getBoundingClientRect();const guide = document.querySelector('.diagram-container').getBoundingClientRect();const svg = document.querySelector('.diagram-container > svg');+ const stage = svg.getBoundingClientRect();+ const nav = document.querySelector('.diagram-nav').getBoundingClientRect();+ const overlapWidth = Math.max(0, Math.min(stage.right, nav.right) - Math.max(stage.left, nav.left));+ const overlapHeight = Math.max(0, Math.min(stage.bottom, nav.bottom) - Math.max(stage.top, nav.top));return { rail: document.documentElement.dataset.navStageRail,toolbarBottom: toolbar.bottom, guideTop: guide.top, guideWidth: guide.width,+ navWidth: nav.width, navHeight: nav.height,+ navStageOverlap: overlapWidth * overlapHeight,+ navStageGap: Math.max(nav.top - stage.bottom, stage.top - nav.bottom, nav.left - stage.right, stage.left - nav.right),scrollWidth: document.documentElement.scrollWidth,geometry: [svg.getAttribute('viewBox'), ...Array.from(svg.querySelectorAll('[data-node-id]')).map(node =>[node.getAttribute('transform'), ...Array.from(node.querySelectorAll('text')).map(text => text.getAttribute('font-size'))])] };})()`);const label = `${width}x${height}/${theme}`;- assert.equal(observed.rail, 'true', label + ': fixture must exercise the compact rail');+ // Compact viewports still exercise the real stage rail. On a taller+ // screen the independently capped SVG can leave enough normal canvas+ // space for in-canvas navigation; either placement must clear the stage.+ if (width <= 1600) assert.equal(observed.rail, 'true', label + ': compact fixture must exercise the stage rail');+ else assert.ok(observed.rail === undefined || observed.rail === 'true', label + ': unexpected navigation placement');+ if (observed.rail === 'true') compactRailCases += 1;+ assert.ok(observed.navWidth > 0 && observed.navHeight > 0, label + ': navigation must be visible');+ assert.equal(observed.navStageOverlap, 0, label + ': navigation overlaps graph stage ' + JSON.stringify(observed));+ assert.ok(observed.navStageGap >= 9.99, label + ': navigation lacks its 10px stage clearance ' + JSON.stringify(observed));assert.ok(observed.guideWidth > 0, label + ': diagram must be visible');assert.ok(observed.guideTop >= observed.toolbarBottom + 4, label + ': toolbar overlaps diagram ' + JSON.stringify(observed));assert.ok(observed.scrollWidth <= width, label + ': horizontal overflow');@@ -58,6 +74,7 @@ test('compact stage rail keeps the diagram below the toolbar', async (t) => {else geometry = observed.geometry;}}+ assert.ok(compactRailCases >= 4, 'both themes at 1440 and 1600 must exercise real compact-stage clearance');} finally {await browser.close();fs.rmSync(dir, { recursive: true, force: true });diff --git a/test/fixtures/reader-readability/compact-table.erd.json b/test/fixtures/reader-readability/compact-table.erd.jsonnew file mode 100644index 00000000..b72bc1bd--- /dev/null+++ b/test/fixtures/reader-readability/compact-table.erd.json@@ -0,0 +1,37 @@+{+ "schema_version": 1,+ "diagram_type": "erd",+ "meta": {+ "locale": "en",+ "quality_profile": "showcase",+ "output": "diagram.html",+ "title": "Anonymous compact table"+ },+ "entities": [+ {+ "id": "record",+ "label": "record",+ "row": 0,+ "col": 0,+ "attributes": [+ {+ "name": "id",+ "type": "bigint",+ "key": "pk"+ },+ {+ "name": "status",+ "type": "text"+ },+ {+ "name": "created_at",+ "type": "timestamp"+ }+ ]+ }+ ],+ "relationships": [],+ "layout": {+ "mode": "grid"+ }+}diff --git a/test/joint-layout-browser.test.mjs b/test/joint-layout-browser.test.mjsindex 57bbcf3f..8b29b45b 100644--- a/test/joint-layout-browser.test.mjs+++ b/test/joint-layout-browser.test.mjs@@ -223,12 +223,15 @@ test('one joint wait preserves real Reader/Chrome convergence at the CLI boundarreturn __jointCompare(immediate);})()`, true), label);}- function clearStage(raw, label) {- assert.ok(raw.reserve > 0, `${label}: reserve`);- assert.ok(raw.gap >= 9, `${label}: stage gap ${raw.gap}`);+ function clearStage(raw, label, { requireRail = true } = {}) {+ const dock = raw.boxes.find(([selector]) => selector === '.diagram-nav')[1];+ assert.ok(dock[4] > 0 && dock[5] > 0, `${label}: navigation must be visible`);+ assert.ok(raw.gap >= 9.99, `${label}: stage gap ${raw.gap}`);assert.equal(raw.overlap, 0, `${label}: dock/stage overlap`);- assert.equal(raw.rail, 'true', label);- assert.equal(raw.rootRail, 'true', label);+ if (requireRail) assert.ok(raw.reserve > 0, `${label}: reserve`);+ const expectedRail = raw.reserve > 0 ? 'true' : null;+ assert.equal(raw.rail, expectedRail, label);+ assert.equal(raw.rootRail, expectedRail, label);assert.ok(raw.dimensions[2] <= raw.dimensions[0], `${label}: horizontal containment`);}function unchanged(before, after, label) {@@ -288,13 +291,18 @@ test('one joint wait preserves real Reader/Chrome convergence at the CLI boundarArchify.viewerChromeLayout.whenStable = function() { __jointCalls.chrome++; return chrome(); };` });const states = [];+ let reservedCliStates = 0;const result = await runVisualCheck({ artifactPath: instrumented, chromePath: chrome,browserFactory: async () => ({inspect: async options => {const metrics = await browser.inspect(options);assert.deepEqual(await evaluate('__jointCalls'), { joint: 1, chrome: 0 }, 'one CLI joint call; no legacy Chrome call');const raw = compare(await evaluate('__jointCompare(__jointAtResolution)', true), `cli-${options.width}-${options.height}-${options.theme}`);- clearStage(raw, 'CLI');+ // The capped SVG may leave space for navigation inside the normal+ // canvas on large screens. Both 1440px theme states still exercise+ // an actual reserved rail; every state retains strict clearance.+ clearStage(raw, 'CLI', { requireRail: options.width === 1440 });+ if (raw.reserve > 0) reservedCliStates += 1;assert.deepEqual(raw.dimensions.slice(0, 2), [options.width, options.height], 'actual raw viewport');assert.deepEqual([metrics.innerWidth, metrics.innerHeight], [options.width, options.height], 'actual CLI metrics viewport');assert.equal(raw.theme, options.theme);@@ -308,6 +316,7 @@ test('one joint wait preserves real Reader/Chrome convergence at the CLI boundar}),});assert.equal(result.exitCode, 0, JSON.stringify(result.receipt));+ assert.ok(reservedCliStates >= 2, 'both 1440px CLI theme states must exercise an actual reserved rail');assert.deepEqual(states, [[1440, 900, 'light'], [1600, 1000, 'light'], [1920, 1080, 'light'],[2048, 1320, 'light'], [1440, 900, 'dark'], [2048, 1320, 'dark']]);assert.deepEqual(result.receipt.containment.viewports.map(value => [value.width, value.height]), states.slice(0, 4).map(value => value.slice(0, 2)));diff --git a/test/reader-layout-browser.test.mjs b/test/reader-layout-browser.test.mjsindex d11b5f79..e2accba8 100644--- a/test/reader-layout-browser.test.mjs+++ b/test/reader-layout-browser.test.mjs@@ -40,6 +40,9 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound}artifacts[mode] = output;}+ const compactErd = path.join(scratch, 'compact-table.html');+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/erd/render-erd.mjs'),+ path.resolve(skillRoot, '../test/fixtures/reader-readability/compact-table.erd.json'), compactErd]);const browser = new ChromeVisualBrowser(chromePath);const records = [];try {@@ -84,6 +87,10 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundlayout: html.getAttribute('data-reader-layout'), overflow: html.getAttribute('data-reader-overflow'),wide: diagram.getAttribute('data-wide-diagram'), shape: html.getAttribute('data-diagram-shape'),readerFit: svg.getAttribute('data-reader-fit'),+ readerArea: html.getAttribute('data-reader-area'),+ minimumAreaHeight: html.style.getPropertyValue('--archify-diagram-min-height'),+ legendCorner: Boolean(svg.querySelector('[data-reader-legend-corner]')),+ legendTransformRuntime: svg.querySelector('[data-legend]')?.style.getPropertyValue('--archify-reader-legend-transform') || '',geometry: ['viewBox', 'width', 'height'].map(function (name) { return svg.getAttribute(name); }),shellWidth: document.querySelector('.container').getBoundingClientRect().width,scrollHeight: Math.max(html.scrollHeight, document.body.scrollHeight),@@ -129,6 +136,10 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundassert.equal(state.layout, null);assert.equal(state.overflow, null);assert.equal(state.receipt.width, 0);+ assert.equal(state.readerArea, null);+ assert.equal(state.minimumAreaHeight, '');+ assert.equal(state.legendCorner, false);+ assert.equal(state.legendTransformRuntime, '');assert.equal(state.wide, wide ? 'true' : null);assert.equal(state.shape, wide ? 'wide' : null);}@@ -201,6 +212,368 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound});const wide = variant('wide', { ratio: 3, undeclaredFit: true });+ await t.test('capped canvas keeps its original legend in the outer corner through camera, input and canonical export', async () => {+ async function corner(label) {+ const state = await evaluate(`(function () {+ var diagram = document.querySelector('.diagram-container');+ var svg = diagram.querySelector(':scope > svg');+ var legend = svg.querySelector('[data-legend]');+ var rect = diagram.getBoundingClientRect();+ var style = getComputedStyle(diagram);+ var legendRect = legend.getBoundingClientRect();+ var nodeRect = svg.querySelector('[data-node-id]').getBoundingClientRect();+ var navRect = diagram.querySelector('.diagram-nav').getBoundingClientRect();+ var left = rect.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft);+ var bottom = rect.bottom - parseFloat(style.borderBottomWidth) - parseFloat(style.paddingBottom);+ return { corner: legend.hasAttribute('data-reader-legend-corner'),+ scale: Archify.view.state().scale, svgCount: diagram.querySelectorAll(':scope > svg').length,+ originalSvg: legend.ownerSVGElement === svg,+ left: legendRect.left, bottom: legendRect.bottom, width: legendRect.width, height: legendRect.height,+ leftGap: legendRect.left - left, bottomGap: bottom - legendRect.bottom,+ nodeWidth: nodeRect.width, nodeHeight: nodeRect.height,+ navOverlap: Math.max(0, Math.min(navRect.right, legendRect.right) - Math.max(navRect.left, legendRect.left)) *+ Math.max(0, Math.min(navRect.bottom, legendRect.bottom) - Math.max(navRect.top, legendRect.top)) };+ })()`);+ records.push({ label, ...state });+ assert.equal(state.corner, true, JSON.stringify(state));+ assert.equal(state.svgCount, 1, 'Legend stays in the original root SVG');+ assert.equal(state.originalSvg, true);+ assert.ok(Math.abs(state.leftGap) <= 1 && Math.abs(state.bottomGap) <= 1, JSON.stringify(state));+ assert.equal(state.navOverlap, 0, JSON.stringify(state));+ if (evidence) {+ const capture = await send('Page.captureScreenshot', { format: 'png' });+ fs.writeFileSync(path.join(evidence, `${label}.png`), Buffer.from(capture.data, 'base64'));+ }+ return state;+ }+ async function exportLegend(label) {+ const value = await evaluate(`(async function () {+ var svg = document.querySelector('.diagram-container > svg');+ var before = svg.outerHTML;+ var original = URL.createObjectURL;+ var captured;+ URL.createObjectURL = function (blob) {+ if (blob.type.indexOf('image/svg+xml') === 0) captured = blob;+ return original.call(URL, blob);+ };+ try {+ await Archify.exportMenu.run('svg');+ var text = await captured.text();+ var clone = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;+ var legend = clone.querySelector('[data-legend]');+ return { text: text, liveUnchanged: before === svg.outerHTML,+ legendMarkup: legend.outerHTML, legendCount: clone.querySelectorAll('[data-legend]').length,+ runtime: clone.hasAttribute('data-view-scale') || Boolean(clone.querySelector('[data-reader-legend-corner]')) ||+ text.includes('--archify-reader-legend-transform'),+ viewBox: clone.getAttribute('viewBox') };+ } finally { URL.createObjectURL = original; }+ })()`, true);+ assert.equal(value.liveUnchanged, true);+ assert.equal(value.legendCount, 1);+ assert.equal(value.runtime, false, 'Export restores canonical legend placement without runtime CSS');+ if (evidence) fs.writeFileSync(path.join(evidence, `${label}.svg`), value.text);+ return value;+ }+ // Capture canonical placement in the ordinary uncapped reading mode,+ // then compare the exact exported group at every capped camera size.+ await load(compactErd, { width: 1440, height: 360 });+ const canonical = await exportLegend('compact-legend-canonical');+ for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) {+ await load(compactErd, { width, height });+ const baseline = await corner(`compact-legend-${width}-100`);+ for (const [scale, steps] of [[0.75, 1], [0.25, 2]]) {+ await evaluate(`for (var i = 0; i < ${steps}; i += 1) Archify.view.zoomOut();`);+ await stable();+ const zoomed = await corner(`compact-legend-${width}-${Math.round(scale * 100)}`);+ assert.equal(zoomed.scale, scale);+ assert.ok(Math.abs(zoomed.width - baseline.width) <= 1 && Math.abs(zoomed.height - baseline.height) <= 1);+ assert.ok(Math.abs(zoomed.nodeWidth - baseline.nodeWidth * scale) <= 1);+ assert.ok(Math.abs(zoomed.nodeHeight - baseline.nodeHeight * scale) <= 1);+ const exported = await exportLegend(`compact-legend-export-${width}-${Math.round(scale * 100)}`);+ assert.equal(exported.legendMarkup.replace(' style=""', ''), canonical.legendMarkup);+ assert.equal(exported.viewBox, canonical.viewBox);+ }+ await evaluate('Archify.view.reset()');+ await stable();+ const reset = await corner(`compact-legend-${width}-reset`);+ assert.ok(Math.abs(reset.nodeWidth - baseline.nodeWidth) <= 1);+ await evaluate('Archify.view.zoomIn()');+ await stable();+ assert.equal((await snapshot(`compact-legend-${width}-125`)).legendCorner, false,+ 'Camera enlargement restores existing in-SVG positioning and clipping');+ await evaluate('Archify.view.reset()');+ await stable();+ await corner(`compact-legend-${width}-after-enlarge`);+ }+ await load(compactErd);+ const hit = await evaluate(`(function () {+ var rect = document.querySelector('[data-legend] .er-legend-hit').getBoundingClientRect();+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };+ })()`);+ async function keyHighlighted(highlighted = true) {+ return evaluate(`(async function () {+ var row = document.querySelector('[data-er-row]:not(:has([data-er-badge="pk"]))');+ // Input changes the existing opacity transition; observe its result+ // after animation frames rather than expecting an immediate repaint.+ for (var i = 0; i < 30; i += 1) {+ var opacity = Number(getComputedStyle(row).opacity);+ if (${highlighted ? 'opacity < 0.3' : 'opacity >= 0.99'}) return true;+ await new Promise(function (resolve) { requestAnimationFrame(resolve); });+ }+ return false;+ })()`, true);+ }+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...hit });+ assert.ok(await keyHighlighted(),+ 'Hovering the relocated real ERD legend highlights matching key rows');+ await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 0, y: 0 });+ assert.ok(await keyHighlighted(false), 'Moving away restores ordinary row paint');+ await evaluate("document.querySelector('[data-legend] .er-legend-hit').focus({ preventScroll: true })");+ assert.ok(await keyHighlighted(),+ 'Keyboard focus retains same-SVG ERD key highlighting');+ await evaluate('document.activeElement.blur()');+ await evaluate(`document.querySelector('[data-legend]').setAttribute('transform', 'translate(3 4)');+ Archify.view.zoomOut(); Archify.view.zoomOut(); Archify.view.zoomOut();`);+ await stable();+ await corner('compact-legend-authored-transform');+ assert.match((await exportLegend('compact-legend-export-authored-transform')).legendMarkup,+ /transform="translate\(3 4\)"/, 'Canonical export preserves an authored group transform');+ const marker = '<g data-legend="">';+ const original = fs.readFileSync(compactErd, 'utf8');+ assert.ok(original.includes(marker));+ const longLegend = path.join(scratch, 'compact-long-legend.html');+ // A wider, multi-row legend must use its existing position when the+ // available bottom corner would overlap the navigation dock.+ fs.writeFileSync(longLegend, original.replace(marker,+ marker + '<rect x="30" y="220" width="600" height="50" fill="none" stroke="none"/>'));+ await load(longLegend);+ const constrained = await snapshot('compact-long-legend-fallback');+ assert.equal(constrained.readerArea, 'true');+ assert.equal(constrained.legendCorner, false);+ assert.equal(constrained.legendTransformRuntime, '');+ });+ await t.test('compact real ERD keeps the normal canvas while SVG enlargement remains capped', async () => {+ const original = fs.readFileSync(compactErd, 'utf8');+ const uncapped = path.join(scratch, 'compact-table-uncapped-control.html');+ // Keep identical automatic eligibility and authored geometry; only remove+ // the SVG enlargement cap to establish the normal outer reader area.+ assert.ok(original.includes('var MAX_AUTOMATIC_SCALE = 1.5;'));+ fs.writeFileSync(uncapped, original.replace('var MAX_AUTOMATIC_SCALE = 1.5;',+ 'var MAX_AUTOMATIC_SCALE = Infinity;'));+ async function area() {+ return evaluate(`(function () {+ var budget = Archify.readerLayout.measure();+ var diagram = document.querySelector('.diagram-container');+ var svg = diagram.querySelector(':scope > svg');+ var rect = diagram.getBoundingClientRect();+ var svgRect = svg.getBoundingClientRect();+ var style = getComputedStyle(diagram);+ var left = rect.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft);+ var right = rect.right - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight);+ var top = rect.top + parseFloat(style.borderTopWidth) + parseFloat(style.paddingTop);+ var bottom = rect.bottom - parseFloat(style.borderBottomWidth) - parseFloat(style.paddingBottom);+ var bodyStyle = getComputedStyle(document.body);+ return { width: rect.width, height: rect.height, svgWidth: svg.clientWidth,+ intrinsicWidth: svg.viewBox.baseVal.width, budget,+ chromeX: rect.width - (right - left),+ chromeY: rect.height - (bottom - top),+ viewportWidth: innerWidth,+ bodyX: parseFloat(bodyStyle.paddingLeft) + parseFloat(bodyStyle.paddingRight),+ readerArea: document.documentElement.getAttribute('data-reader-area'),+ minimumAreaHeight: document.documentElement.style.getPropertyValue('--archify-diagram-min-height'),+ stageRail: document.documentElement.getAttribute('data-nav-stage-rail'),+ navReserve: style.getPropertyValue('--archify-nav-reserve'),+ centerX: (svgRect.left + svgRect.right - left - right) / 2,+ centerY: (svgRect.top + svgRect.bottom - top - bottom) / 2 };+ })()`);+ }+ for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) {+ await load(uncapped, { width, height });+ const normal = await area();+ await load(compactErd, { width, height });+ const fitted = await area();+ records.push({ label: `compact-table-${width}-canvas`, normal, fitted });+ assert.equal(normal.readerArea, null, 'uncapped automatic canvas retains ordinary document flow');+ assert.equal(normal.minimumAreaHeight, '');+ assert.equal(fitted.readerArea, 'true', 'a binding cap keeps its normal outer reader area');+ // Navigation may switch between an external rail and in-canvas controls+ // when the SVG shrinks. Both regions must keep their own normal viewport+ // budget; the enlargement cap must affect only the SVG.+ for (const region of [normal, fitted]) {+ const desiredWidth = region.budget.availableSvgHeight * region.budget.ratio + region.chromeX;+ const expectedWidth = Math.max(960, Math.min(1920, region.viewportWidth - region.bodyX, desiredWidth));+ assert.ok(Math.abs(region.width - Math.round(expectedWidth)) <= 1, JSON.stringify(region));+ assert.ok(Math.abs(region.height - region.budget.availableSvgHeight - region.chromeY) <= 1, JSON.stringify(region));+ }+ assert.ok(fitted.width > 960 && fitted.height > height * 0.75, JSON.stringify(fitted));+ assert.ok(fitted.svgWidth <= fitted.intrinsicWidth * 1.5 + 1, JSON.stringify(fitted));+ assert.ok(Math.abs(fitted.centerX) <= 1 && Math.abs(fitted.centerY) <= 1, JSON.stringify(fitted));+ const geometry = (await snapshot(`compact-table-${width}`)).geometry;+ await evaluate('Archify.view.zoomOut()');+ await stable();+ const zoomed = await area();+ records.push({ label: `compact-table-${width}-zoomed-canvas`, zoomed });+ assert.ok(Math.abs(zoomed.centerX) <= 1 && Math.abs(zoomed.centerY) <= 1, JSON.stringify(zoomed));+ assert.ok(Math.abs(zoomed.height - fitted.height) <= 1 && Math.abs(zoomed.width - fitted.width) <= 1);+ await evaluate('Archify.view.reset()');+ await stable();+ assert.deepEqual((await snapshot(`compact-table-${width}-reset`)).geometry, geometry);+ }+ });++ await t.test('automatic compact ERD clears its reader area in specialized modes and restores it on return', async () => {+ await load(compactErd);+ async function restored(label) {+ const state = await snapshot(label);+ assert.equal(state.active, true);+ assert.equal(state.readerArea, 'true');+ assert.match(state.minimumAreaHeight, /^[\d.]+px$/);+ }+ await restored('compact-area-initial');+ await evaluate("document.documentElement.setAttribute('data-embed', 'true')");+ await stable();+ inactive(await snapshot('compact-area-embed'), false);+ await evaluate("document.documentElement.removeAttribute('data-embed')");+ await stable();+ await restored('compact-area-after-embed');+ await evaluate('Archify.presentation.enter()');+ await stable();+ inactive(await snapshot('compact-area-presentation'), false);+ await evaluate('Archify.presentation.exit()');+ await stable();+ await restored('compact-area-after-presentation');+ await media('dark', false, true);+ await stable();+ inactive(await snapshot('compact-area-print'), false);+ await media('dark');+ await stable();+ await restored('compact-area-after-print');+ });++ await t.test('compact ERD resize clears and restores its area across desktop eligibility and binding cap boundaries', async () => {+ await load(compactErd);+ const initial = await snapshot('compact-resize-initial');+ assert.equal(initial.readerArea, 'true');+ await viewport(1023, 900);+ await stable();+ const narrow = await snapshot('compact-resize-ineligible');+ inactive(narrow, false);+ assert.deepEqual(narrow.geometry, initial.geometry);+ await viewport(1440, 900);+ await stable();+ const desktop = await snapshot('compact-resize-eligible');+ assert.equal(desktop.readerArea, 'true');+ assert.deepEqual(desktop.geometry, initial.geometry);+ // The same desktop width at a short viewport height already fits this+ // graph below its enlargement cap; that ordinary flow needs no area floor.+ await viewport(1440, 360);+ await stable();+ const uncapped = await snapshot('compact-resize-nonbinding');+ assert.equal(uncapped.active, true);+ assert.equal(uncapped.readerArea, null);+ assert.equal(uncapped.minimumAreaHeight, '');+ assert.deepEqual(uncapped.geometry, initial.geometry);+ await viewport(1440, 900);+ await stable();+ const capped = await snapshot('compact-resize-binding');+ assert.equal(capped.readerArea, 'true');+ assert.match(capped.minimumAreaHeight, /^[\d.]+px$/);+ assert.deepEqual(capped.geometry, initial.geometry);+ });++ await t.test('long automatic sequences and waterfalls favor reading width while small canvases cap enlargement', async () => {+ function readerFixture(name, width, height, attributes) {+ const original = fs.readFileSync(artifacts.architecture, 'utf8');+ const svgStart = original.indexOf('<svg');+ const svgEnd = original.indexOf('</svg>', svgStart) + '</svg>'.length;+ assert.ok(svgStart >= 0 && svgEnd > svgStart);+ const rows = height > 1000 ? 48 : 4;+ const rowMarkup = Array.from({ length: rows }, (_, index) => {+ const y = 20 + index * (height - 60) / rows;+ return `<g data-node-id="reader-row-${index}">+ <rect x="20" y="${y}" width="${width - 40}" height="36" fill="var(--backend-fill)" stroke="var(--backend-stroke)"/>+ <text data-node-label="" x="30" y="${y + 24}" class="t-primary" font-size="14">Reader row ${index + 1}</text>+ </g>`;+ }).join('\n');+ const svg = `<svg viewBox="0 0 ${width} ${height}" ${attributes}>${rowMarkup}</svg>`;+ const file = path.join(scratch, `${name}.html`);+ fs.writeFileSync(file, original.slice(0, svgStart) + svg + original.slice(svgEnd));+ return file;+ }+ const samples = [+ ['sequence', 1100, 2400, 'data-sequence-column-fit="fixed"'],+ ['waterfall', 1100, 2400, 'data-waterfall-ui=""'],+ ['small-erd', 456, 270, ''],+ ];+ for (const [name, width, height, marker] of samples) {+ const file = readerFixture(name, width, height,+ `data-reader-fit="intrinsic-height" data-reader-min-text="7.5" ${marker}`);+ for (const [viewportWidth, viewportHeight] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) {+ await load(file, { width: viewportWidth, height: viewportHeight });+ const before = await snapshot(`${name}-${viewportWidth}`);+ const dimensions = await evaluate(`(function () {+ var svg = document.querySelector('.diagram-container > svg');+ var diagram = svg.parentElement;+ var style = getComputedStyle(diagram);+ var startY = diagram.getBoundingClientRect().top + parseFloat(style.paddingTop) + parseFloat(style.borderTopWidth);+ return { width: svg.clientWidth, height: svg.clientHeight,+ startOffsetY: svg.getBoundingClientRect().top - startY,+ readerArea: document.documentElement.getAttribute('data-reader-area'),+ minimumAreaHeight: document.documentElement.style.getPropertyValue('--archify-diagram-min-height'),+ primaryPx: 14 * svg.clientWidth / svg.viewBox.baseVal.width,+ overflowX: Math.max(document.documentElement.scrollWidth, document.body.scrollWidth) > innerWidth + 1 };+ })()`);+ assert.equal(before.active, true);+ if (evidence && (viewportWidth === 1440 || viewportWidth === 2048)) {+ const capture = await send('Page.captureScreenshot', { format: 'png' });+ fs.writeFileSync(path.join(evidence, `${name}-${viewportWidth}-reading.png`), Buffer.from(capture.data, 'base64'));+ }+ assert.equal(dimensions.overflowX, false, JSON.stringify(dimensions));+ assert.ok(dimensions.width <= width * 1.5 + 1, JSON.stringify(dimensions));+ if (dimensions.width < width * 1.5 - 1) {+ assert.equal(dimensions.readerArea, null, 'nonbinding automatic cap preserves natural document flow');+ assert.equal(dimensions.minimumAreaHeight, '');+ }+ if (name === 'small-erd') {+ assert.ok(dimensions.width >= 456, JSON.stringify(dimensions));+ assert.ok(before.shellWidth >= 960, JSON.stringify(before));+ } else {+ assert.ok(dimensions.width >= 1250, JSON.stringify(dimensions));+ assert.ok(dimensions.primaryPx >= 14, JSON.stringify(dimensions));+ assert.ok(before.scrollHeight > before.innerHeight);+ assert.ok(Math.abs(dimensions.startOffsetY) <= 1, 'long content begins at the normal canvas top: ' + JSON.stringify(dimensions));+ assert.equal(before.overflow, 'authored');+ }+ await evaluate('Archify.view.zoomIn(); Archify.view.reset()');+ await stable();+ assert.deepEqual((await snapshot(`${name}-${viewportWidth}-reset`)).geometry, before.geometry);+ await evaluate('Archify.presentation.enter()');+ await stable();+ const presentation = await snapshot(`${name}-${viewportWidth}-presentation`);+ inactive(presentation, width / height >= 1.55);+ const stage = await evaluate(`(function () {+ var rect = document.querySelector('.diagram-container > svg').getBoundingClientRect();+ return { top: rect.top, bottom: rect.bottom, height: innerHeight };+ })()`);+ assert.ok(stage.top >= 0 && stage.bottom <= stage.height + 1, JSON.stringify(stage));+ if (evidence && viewportWidth === 1440) {+ const capture = await send('Page.captureScreenshot', { format: 'png' });+ fs.writeFileSync(path.join(evidence, `${name}-${viewportWidth}-presentation.png`), Buffer.from(capture.data, 'base64'));+ }+ await evaluate('Archify.presentation.exit()');+ await stable();+ assert.deepEqual((await snapshot(`${name}-${viewportWidth}-return`)).geometry, before.geometry);+ }+ }+ // A sequence marker alone must not override an authored canvas's fit.+ const authored = readerFixture('authored-sequence', 1100, 2400, 'data-sequence-column-fit="fixed"');+ await load(authored);+ inactive(await snapshot('authored-sequence'), false);+ const authoredSmall = readerFixture('authored-small', 456, 270, '');+ await load(authoredSmall, { width: 2048, height: 1320 });+ assert.ok(await evaluate("document.querySelector('.diagram-container > svg').clientWidth > 456 * 1.5"),+ 'an authored canvas retains its previous enlargement behavior');+ });await t.test('desktop budgets, extreme content and limited horizontal space preserve geometry', async () => {for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) {await load(wide, { width, height });diff --git a/test/real-repository-proof.test.mjs b/test/real-repository-proof.test.mjsindex b8e82694..2bc219cd 100644--- a/test/real-repository-proof.test.mjs+++ b/test/real-repository-proof.test.mjs@@ -162,7 +162,7 @@ test('MCO public proof is source-backed, valid, and linked from every README', (assert.equal(evidence.repository.revision, source.meta.repository.revision);assert.equal(evidence.repository.shortRevision, source.meta.repository.revision.slice(0, 7));assert.equal(evidence.referenceCount, references);- assert.match(checkedInHtml, /Archify\.sourceEvidence\.installBeacons\(\)/);+ assert.doesNotMatch(checkedInHtml, /Archify\.sourceEvidence\.installBeacons\(\)|classList\.add\('source-evidence-beacon'\)/);execFileSync(process.execPath, [cli, 'check', artifactPath], { encoding: 'utf8' });const noRootTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-mco-proof-no-root-'));diff --git a/test/repository-evidence-types-browser.test.mjs b/test/repository-evidence-types-browser.test.mjsindex ce32a45a..94e13085 100644--- a/test/repository-evidence-types-browser.test.mjs+++ b/test/repository-evidence-types-browser.test.mjs@@ -10,9 +10,9 @@ import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjsconst root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');const chrome = Object.hasOwn(process.env, 'ARCHIFY_CHROME') ? findChrome() : null;-test('non-architecture sources reach real Viewer beacons, Focus and Finder', {+test('verified sources remain in Focus and Finder without node badges or label mutations', {skip: !chrome,- timeout: 60000,+ timeout: 120000,}, async (t) => {const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-typed-evidence-browser-'));t.after(() => fs.rmSync(repo, { recursive: true, force: true }));@@ -28,6 +28,10 @@ test('non-architecture sources reach real Viewer beacons, Focus and Finder', {const browser = new ChromeVisualBrowser(chrome);t.after(() => browser.close());const cases = [+ ['architecture', 'components', 'web-app.architecture.json', false, 'light'],+ ['architecture', 'components', 'web-app.architecture.json', 'gitlab', 'dark'],+ ['timeline', 'events', 'payment-incident.timeline.json', false, 'light'],+ ['waterfall', 'spans', 'checkout-request.waterfall.json', false, 'dark'],['workflow', 'nodes', 'agent-tool-call.workflow.json', false, 'light'],['sequence', 'participants', 'cache-miss-request.sequence.json', false, 'dark'],['dataflow', 'nodes', 'product-analytics.dataflow.json', true, 'light'],@@ -52,29 +56,33 @@ test('non-architecture sources reach real Viewer beacons, Focus and Finder', {['class', 'types', 'payments.class.json', false, 'dark'],];for (const [type, collection, example, local, theme, extra = {}, nodeId] of cases) {- const url = local ? 'http://git.internal/Team/repo' : 'https://github.com/example/evidence-repo';+ const url = local === 'gitlab' ? 'https://gitlab.com/example/platform/evidence-repo'+ : local ? 'http://git.internal/Team/repo' : 'https://github.com/example/evidence-repo';+ const localOnly = local === true;git('remote', 'set-url', 'origin', url);const diagram = JSON.parse(fs.readFileSync(path.join(root, 'examples', example), 'utf8'));const node = Object.assign(nodeId ? diagram[collection].find(node => node.id === nodeId) : diagram[collection][0], extra);node.sources = [{ path: 'source.js', line: 1, end_line: 3 }];- diagram.meta.repository = { url, revision, ...(local ? { link_mode: 'local-only' } : {}) };+ diagram.meta.repository = { url, revision, ...(localOnly ? { link_mode: 'local-only' } : {}) };const input = path.join(repo, `${type}.json`), artifactPath = path.join(repo, `${type}.html`);fs.writeFileSync(input, JSON.stringify(diagram));execFileSync(process.execPath, [path.join(root, 'bin/archify.mjs'), 'deliver', type, input, artifactPath, '--repo-root', repo, '--json'], { encoding: 'utf8' });+ const svg = fs.readFileSync(artifactPath, 'utf8').match(/<svg\b[\s\S]*?<\/svg>/)[0];await browser.inspect({ artifactPath, width: 1440, height: 900, theme });const session = await browser.sessionPromise;const response = await browser.cdp.send('Runtime.evaluate', {expression: `(() => {const node = [...document.querySelectorAll('[data-node-id]')].find(n => n.dataset.nodeId === ${JSON.stringify(node.id)});const box = el => el && el.getBoundingClientRect();- const beaconBox = box(node.querySelector('[data-source-evidence-beacon]'));- const collisions = [['sigil', '[data-semantic-sigil]'], ['brand', '.brand-mark'], ['label', '[data-node-label]']]- .filter(([, selector]) => {- const other = box(node.querySelector(selector));- return other && beaconBox && beaconBox.left < other.right && other.left < beaconBox.right- && beaconBox.top < other.bottom && other.top < beaconBox.bottom;- }).map(([name]) => name);- const texts = [...node.querySelectorAll('text:not(.source-evidence-beacon text)')];+ const compatibilityResult = Archify.sourceEvidence.installBeacons();+ const badgeCount = document.querySelectorAll('[data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label]').length;+ const originalSvg = new DOMParser().parseFromString(${JSON.stringify(svg)}, 'image/svg+xml');+ const ariaChanges = [...document.querySelectorAll('.diagram-container svg [data-node-id]')].filter(actual => {+ const original = [...originalSvg.querySelectorAll('[data-node-id]')].find(n => n.getAttribute('data-node-id') === actual.getAttribute('data-node-id'));+ return !original || original.getAttribute('aria-label') !== actual.getAttribute('aria-label');+ }).map(n => n.dataset.nodeId);+ const evidence = Archify.sourceEvidence.node(${JSON.stringify(node.id)});+ const texts = [...node.querySelectorAll('text')];// Fine-detail tags/steps must also fit when zoom reveals them.texts.forEach(text => {text.style.setProperty('display', 'inline', 'important');@@ -96,7 +104,7 @@ test('non-architecture sources reach real Viewer beacons, Focus and Finder', {const finder = document.getElementById('node-finder-input');finder.value = 'source.js';finder.dispatchEvent(new Event('input', {bubbles:true}));- return { visible: !panel.hidden, beacon: !!node.querySelector('[data-source-evidence-beacon]'), collisions, textCollisions, overflowingText,+ return { visible: !panel.hidden, badgeCount, ariaChanges, evidence, compatibilityResult, textCollisions, overflowingText,nodeSize: ['width', 'height'].map(key => Number(node.querySelector('rect').getAttribute(key))),labelFont: Number(node.querySelector('text[data-node-label]').getAttribute('font-size')),hasBrand: !!node.querySelector('.brand-mark'),@@ -107,9 +115,12 @@ test('non-architecture sources reach real Viewer beacons, Focus and Finder', {}, session);assert.equal(response.exceptionDetails, undefined, type);const result = response.result.value;+ assert.equal(result.badgeCount, 0, type);+ assert.deepEqual(result.ariaChanges, [], `${type}: preserve authored node accessibility labels`);+ assert.equal(result.compatibilityResult, 0, `${type}: legacy method remains inert`);+ assert.equal(result.evidence.length, 1, `${type}: verified evidence lookup`);+ assert.equal(result.evidence[0].path, 'source.js', type);assert.equal(result.visible, true, type);- assert.equal(result.beacon, true, type);- assert.deepEqual(result.collisions, [], `${type} ${example}: the source badge must not cover the node's sigil, brand, or label`);if (Object.keys(extra).length > 1) {assert.deepEqual(result.textCollisions, [], `${type} ${node.label}: compact rows must remain separate`);assert.deepEqual(result.overflowingText, [], `${type} ${node.label}: compact rows must remain inside the authored box`);@@ -118,7 +129,7 @@ test('non-architecture sources reach real Viewer beacons, Focus and Finder', {}assert.equal(result.hasBrand, Boolean(extra.brand), `${type} ${example}: brand fixture`);assert.deepEqual(result.paths, ['source.js'], type);- assert.deepEqual(result.links, local ? [] : [`${url}/blob/${revision}/source.js#L1-L3`], type);- assert.ok(result.search.includes(node.label), `${type}: Finder must match the source-backed node`);+ assert.deepEqual(result.links, localOnly ? [] : [`${url}/${local === 'gitlab' ? '-/' : ''}blob/${revision}/source.js#L1${local === 'gitlab' ? '-3' : '-L3'}`], type);+ assert.ok(result.search.includes(node.label || node.title || node.name), `${type}: Finder must match the source-backed node`);}});diff --git a/test/repository-evidence-types.test.mjs b/test/repository-evidence-types.test.mjsindex 766375d9..e4196428 100644--- a/test/repository-evidence-types.test.mjs+++ b/test/repository-evidence-types.test.mjs@@ -99,10 +99,9 @@ for (const shape of TYPES) {);assert.equal(evidence.nodes[first][0].label, 'Request router');- // The verified node must exist in the artifact under the same id, or the- // viewer's beacon pass has nothing to attach the SRC affordance to.+ // Evidence stays keyed to the rendered subject for Focus/Finder lookup.assert.match(html, new RegExp(`data-node-id="${first}"`));- assert.match(html, /Archify\.sourceEvidence\.installBeacons\(\)/);+ assert.doesNotMatch(html, /Archify\.sourceEvidence\.installBeacons\(\)|classList\.add\('source-evidence-beacon'\)/);const svg = html.match(/<svg\b[\s\S]*?<\/svg>/)?.[0] || '';assert.doesNotMatch(svg, /src\/router\.js|github\.com\/example\/evidence-repo|source-evidence/);diff --git a/test/repository-evidence.test.mjs b/test/repository-evidence.test.mjsindex 65f5480f..86277d12 100644--- a/test/repository-evidence.test.mjs+++ b/test/repository-evidence.test.mjs@@ -533,7 +533,7 @@ test('browser renders local-only sources as searchable text and web sources as llocations: rows.map(row => row.querySelector('code').textContent),repositoryHref: document.getElementById('focus-repository').getAttribute('href'),scope: panel.title,- beacon: !!document.querySelector('[data-node-id="users"] [data-source-evidence-beacon]'),+ badges: document.querySelectorAll('[data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label]').length,invalidLinks: [...panel.querySelectorAll('a[href]')].some(a => /undefined|javascript:/.test(a.getAttribute('href'))),search: document.getElementById('node-finder-results').textContent};@@ -542,7 +542,7 @@ test('browser renders local-only sources as searchable text and web sources as lassert.equal(response.exceptionDetails, undefined);const observed = response.result.value;assert.equal(observed.visible, true);- assert.equal(observed.beacon, true);+ assert.equal(observed.badges, 0);assert.equal(observed.invalidLinks, false);assert.deepEqual(observed.paths, ['src/router.js', 'src/store.js']);assert.match(observed.scope, /local Git/);@@ -607,9 +607,7 @@ test('repository evidence is revision-verified, receipt-backed, searchable, andassert.match(html, /var sourceSearch = sources\.map/);assert.match(html, /renderSourceEvidence\(id\)/);assert.match(html, /referrerPolicy = 'no-referrer'/);- assert.match(html, /classList\.add\('source-evidence-beacon'\)/);- assert.match(html, /text\.textContent = viewerText\('viewer\.passport\.sourceMarker'\) \+ ' ' \+ count/);- assert.match(html, /Archify\.sourceEvidence\.installBeacons\(\)/);+ assert.doesNotMatch(html, /Archify\.sourceEvidence\.installBeacons\(\)|classList\.add\('source-evidence-beacon'\)/);assert.match(html, /querySelectorAll\('\[data-source-evidence-beacon\]'\)/);assert.match(html, /data-source-evidence-original-label/);diff --git a/test/semantic-passport-move-browser.test.mjs b/test/semantic-passport-move-browser.test.mjsindex d456886c..835ab4a2 100644--- a/test/semantic-passport-move-browser.test.mjs+++ b/test/semantic-passport-move-browser.test.mjs@@ -342,6 +342,55 @@ test('Semantic Passport pointer movement honors threshold, capture, four-edge cl}});+test('compact ERD Passport reclamps to the settled container when the reader cap stops binding', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser regression.',+}, async () => {+ const artifact = path.join(tmp, 'compact-erd-passport.html');+ execFileSync(process.execPath, [+ path.join(skillRoot, 'renderers/erd/render-erd.mjs'),+ path.join(skillRoot, '../test/fixtures/reader-readability/compact-table.erd.json'), artifact,+ ]);+ const browser = desktopBrowser(chromePath);+ try {+ const sessionId = await loadArtifact(browser, artifact);+ await focusNode(browser, sessionId, 'record');+ const geometry = await evaluate(browser, sessionId, `(() => {+ const svg = document.querySelector('.diagram-container > svg');+ return [svg.getAttribute('viewBox'), ...Array.from(svg.querySelectorAll('[data-node-id]')).map(node =>+ [node.getAttribute('data-node-id'), node.getAttribute('transform')])];+ })()`);+ async function resize(width, height, area) {+ await browser.cdp.send('Emulation.setDeviceMetricsOverride', {+ width, height, deviceScaleFactor: 1, mobile: false,+ }, sessionId);+ await evaluate(browser, sessionId, `Archify.layoutStability.whenStable()`, true);+ await settle(browser, sessionId, 300);+ await evaluate(browser, sessionId, `Archify.layoutStability.whenStable()`, true);+ const state = await passportState(browser, sessionId);+ assert.equal(state.manual, 'true', JSON.stringify(state));+ assert.ok(state.container.height >= state.chip.height + 32, 'panel fits inside the normal container');+ assertBounded(state, 16);+ assert.equal(await evaluate(browser, sessionId,+ `document.documentElement.getAttribute('data-reader-area')`), area);+ assert.deepEqual(await evaluate(browser, sessionId, `(() => {+ const svg = document.querySelector('.diagram-container > svg');+ return [svg.getAttribute('viewBox'), ...Array.from(svg.querySelectorAll('[data-node-id]')).map(node =>+ [node.getAttribute('data-node-id'), node.getAttribute('transform')])];+ })()`), geometry);+ }+ await dragHandleTo(browser, sessionId, { x: 1435, y: 895 });+ await resize(1440, 360, null);+ await resize(1440, 900, 'true');+ await dragHandleTo(browser, sessionId, { x: 1435, y: 895 });+ await resize(940, 640, null);+ await resize(1440, 900, 'true');+ await dragHandleTo(browser, sessionId, { x: 1435, y: 895 });+ await resize(1440, 400, null);+ } finally {+ await browser.close();+ }+});+test('Semantic Passport keyboard movement uses coarse/fine steps, Home reset, and resize reclamping', {skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser regression.',}, async () => {diff --git a/test/semantic-radar.test.mjs b/test/semantic-radar.test.mjsindex cc703195..4dd88f7e 100644--- a/test/semantic-radar.test.mjs+++ b/test/semantic-radar.test.mjs@@ -183,7 +183,7 @@ test('Semantic Radar tracks desktop camera and mobile contained scroll', () => {const html = render('sequence', CASES.sequence);assert.match(html, /function logicalViewport\(\)/);assert.match(html, /x = viewBox\.x \+ container\.scrollLeft \/ metrics\.scale/);- assert.match(html, /x = viewBox\.x \+ \(\(-state\.x \/ state\.scale\) - metrics\.offsetX\) \/ metrics\.scale/);+ assert.match(html, /var visible = Archify\.view\.logicalViewport\(\)/);assert.match(html, /viewport\.setAttribute\('width', String\(visible\.width\)\)/);assert.match(html, /viewerText\('viewer\.radar\.viewport\.width'/);assert.match(html, /function centerAt\(logicalX, logicalY, options\)/);diff --git a/test/tree-branches-browser.test.mjs b/test/tree-branches-browser.test.mjsindex 3cdaa104..770cec8d 100644--- a/test/tree-branches-browser.test.mjs+++ b/test/tree-branches-browser.test.mjs@@ -19,8 +19,8 @@ test('Tree branches collapse in place, follow the keyboard, reveal selections, a}, async (t) => {const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-tree-browser-'));t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));- // Verified evidence on a root, branch and leaf exercises the shared beacon- // installer against both hidden stack decorations and actual node cards.+ // Verified evidence on root, branch and leaf stays available without adding+ // source badges or mutating node accessibility labels.const git = (...args) => execFileSync('git', ['-C', scratch, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();fs.writeFileSync(path.join(scratch, 'source.js'), 'export const source = true;\n');git('init');@@ -75,26 +75,11 @@ test('Tree branches collapse in place, follow the keyboard, reveal selections, aawait load(small);assert.equal(await run('Archify.treeBranches.active'), true);- async function checkBeacons() {- assert.deepEqual(await run(`(() => ['platform', 'payments', 'card_payment'].map(id => {- const node = document.querySelector('[data-node-id="' + id + '"]');- const beacon = node.querySelector('[data-source-evidence-beacon]');- const card = node.querySelector('rect.c-mask').getBoundingClientRect();- const box = beacon && beacon.getBoundingClientRect();- const texts = [...node.querySelectorAll('text:not(.source-evidence-beacon text)')];- texts.forEach(text => {- text.style.setProperty('display', 'inline', 'important');- text.style.setProperty('opacity', '1', 'important');- });- const textCollisions = texts.filter(text => {- const other = text.getBoundingClientRect();- return box && box.left < other.right && other.left < box.right && box.top < other.bottom && other.top < box.bottom;- }).map(text => text.textContent);- return { id, exists: !!beacon, onCard: !!box && box.x >= card.x && box.x + box.width <= card.x + card.width- && box.y >= card.y && box.y + box.height <= card.y + card.height, textCollisions };- }))()`), ['platform', 'payments', 'card_payment'].map(id => ({ id, exists: true, onCard: true, textCollisions: [] })));+ async function checkSources() {+ assert.equal(await run(`document.querySelectorAll('[data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label]').length`), 0);+ assert.deepEqual(await run(`['platform', 'payments', 'card_payment'].map(id => Archify.sourceEvidence.node(id).map(source => source.path))`), [['source.js'], ['source.js'], ['source.js']]);}- await checkBeacons();+ await checkSources();const before = await run(box('operations'));const started = await run('performance.now()');await run(`document.querySelector('[data-tree-toggle="payments"]').dispatchEvent(new MouseEvent('click', { bubbles: true }))`);@@ -174,5 +159,5 @@ test('Tree branches collapse in place, follow the keyboard, reveal selections, aassert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);await load(small, '', 'dark');- await checkBeacons();+ await checkSources();});diff --git a/test/viewer-camera-browser.test.mjs b/test/viewer-camera-browser.test.mjsindex 41ea803f..2da0d748 100644--- a/test/viewer-camera-browser.test.mjs+++ b/test/viewer-camera-browser.test.mjs@@ -38,6 +38,23 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {files.trace = path.join(scratch, 'trace.html');execFileSync(process.execPath, [path.join(skillRoot, 'renderers/architecture/render-architecture.mjs'),path.join(scratch, 'trace.json'), files.trace]);+ const longSequence = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', cases.sequence), 'utf8'));+ longSequence.meta.viewBox = [1080, 3400];+ longSequence.segments = [];+ longSequence.activations = [];+ longSequence.messages = Array.from({ length: 60 }, (_, i) => ({+ id: `long-${i}`, from: 'web', to: 'api', y: 160 + i * 50, label: `Request ${i + 1}`,+ }));+ fs.writeFileSync(path.join(scratch, 'long-sequence.json'), JSON.stringify(longSequence));+ files.longSequence = path.join(scratch, 'long-sequence.html');+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/sequence/render-sequence.mjs'),+ path.join(scratch, 'long-sequence.json'), files.longSequence]);+ const mobileWide = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', cases.architecture), 'utf8'));+ mobileWide.meta.viewBox = [1600, 700];+ fs.writeFileSync(path.join(scratch, 'mobile-wide.json'), JSON.stringify(mobileWide));+ files.mobileWide = path.join(scratch, 'mobile-wide.html');+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/architecture/render-architecture.mjs'),+ path.join(scratch, 'mobile-wide.json'), files.mobileWide]);const browser = new ChromeVisualBrowser(chrome);t.after(() => browser.close());const session = await browser.sessionPromise;@@ -131,12 +148,154 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {for (let i = 0; i < 12; i++) Archify.view.zoomOut();return { independent, max, min: Archify.view.state().scale };})()`);- assert.deepEqual(limits, { independent: true, max: 3, min: 1 });+ assert.deepEqual(limits, { independent: true, max: 3, min: 0.25 });await stable();assert.equal((await snapshot(`${mode}-limits`)).viewBox, initial.viewBox);}});+ await t.test('manual overview zoom centers below 100%, restores reset and survives viewport changes', async () => {+ for (const width of [1440, 720]) {+ await load('architecture', { width, reduced: true });+ const initial = await snapshot(`underscale-${width}-initial`);+ await run(`document.querySelector('[data-view="out"]').click()`);+ await stable();+ const inspect = `(() => {+ const c = document.querySelector('.diagram-container'), s = c.querySelector(':scope > svg');+ const state = Archify.view.state();+ return { state, width: s.clientWidth, height: s.clientHeight, visibleWidth: Math.min(s.clientWidth, c.clientWidth), scrollLeft: c.scrollLeft,+ percent: c.querySelector('[data-view-percent]').textContent,+ out: c.querySelector('[data-view="out"]').disabled,+ incoming: c.querySelector('[data-view="in"]').disabled,+ pannable: c.classList.contains('is-pannable'), clip: s.style.clipPath,+ viewport: Archify.view.logicalViewport(), viewBox: s.getAttribute('viewBox') };+ })()`;+ let value = await run(inspect);+ assert.equal(value.state.scale, 0.75);+ assert.equal(value.percent, '75%');+ assert.equal(value.out, false);+ assert.equal(value.pannable, false);+ assert.equal(value.clip, '');+ assert.ok(Math.abs(value.state.x - value.scrollLeft - (value.visibleWidth - value.width * 0.75) / 2) < 0.1);+ assert.ok(Math.abs(value.state.y - value.height * 0.125) < 0.1);+ assert.equal(value.viewport.scale, 0.75);+ await snapshot(`underscale-${width}-75`);+ await screenshot(`underscale-${width}-75`);+ await run(`for (let i = 0; i < 8; i++) Archify.view.zoomOut()`);+ await stable();+ value = await run(inspect);+ assert.equal(value.state.scale, 0.25);+ assert.equal(value.percent, '25%');+ assert.equal(value.out, true);+ assert.equal(value.incoming, false);+ assert.equal(value.viewBox, initial.viewBox);+ await viewport(width === 1440 ? 1280 : 600, 800);+ await stable();+ value = await run(inspect);+ assert.equal(value.state.scale, 0.25);+ assert.ok(Math.abs(value.state.x - value.scrollLeft - (value.visibleWidth - value.width * 0.25) / 2) < 0.1);+ assert.ok(Math.abs(value.state.y - value.height * 0.375) < 0.1);+ await snapshot(`underscale-${width}-25-resized`);+ await screenshot(`underscale-${width}-25-resized`);+ await run(`document.querySelector('[data-view="reset"]').click()`);+ await stable();+ value = await run(inspect);+ assert.deepEqual(value.state, { scale: 1, x: 0, y: 0, mode: 'overview' });+ assert.equal(value.percent, '100%');+ assert.equal(value.out, false);+ await run(`Archify.view.zoomOut(); Archify.finder.select('api')`);+ await stable();+ assert.equal(await run(`Archify.focus.active()`), 'api');+ assert.ok((await run(inspect)).state.scale >= 1);+ await snapshot(`underscale-${width}-finder`);+ }+ await load();+ await run(`document.getElementById('btn-present').click()`);+ await stable();+ await run(`Archify.view.zoomOut()`);+ await stable();+ assert.equal(await run(`document.documentElement.getAttribute('data-present')`), 'true');+ assert.equal((await snapshot('underscale-present-75')).state.scale, 0.75);+ await screenshot('underscale-present-75');+ });++ await t.test('long sequences keep the first row visible below 100% and the final row reachable', async () => {+ await load('longSequence', { width: 1280, height: 800, reduced: true });+ await run(`Archify.view.zoomOut(); Archify.view.zoomOut(); Archify.view.zoomOut()`);+ await stable();+ const value = await run(`(() => {+ const s = document.querySelector('.diagram-container > svg');+ const rows = [...s.querySelectorAll('[data-edge-from]')];+ const first = rows[0].getBoundingClientRect(), last = rows[rows.length - 1].getBoundingClientRect();+ return { height: s.clientHeight, state: Archify.view.state(), first: first.y, last: last.y,+ scrollHeight: document.documentElement.scrollHeight, windowHeight: innerHeight };+ })()`);+ assert.ok(value.height > value.windowHeight);+ assert.equal(value.state.scale, 0.25);+ assert.equal(value.state.y, 0);+ assert.ok(value.first >= 0 && value.first < value.windowHeight, 'the first row remains on screen');+ assert.ok(value.last <= value.scrollHeight, 'the final row remains reachable by page scroll');+ await snapshot('long-sequence-25-top');+ await screenshot('long-sequence-25-top');+ await run(`window.scrollTo(0, ${Math.max(0, value.last - value.windowHeight / 2)})`);+ await stable();+ await snapshot('long-sequence-25-final');+ await screenshot('long-sequence-25-final');+ });++ await t.test('long-diagram zoom preserves visible content from middle and bottom scroll positions', async () => {+ for (const position of [0.5, 0.85, 'page-bottom']) {+ await load('longSequence', { width: 1280, height: 800, reduced: true });+ const scrollTarget = position === 'page-bottom' ? 'document.documentElement.scrollHeight'+ : `document.querySelector('.diagram-container > svg').clientHeight * ${position}`;+ await run(`window.scrollTo(0, ${scrollTarget})`);+ await stable();+ for (const scale of [0.75, 0.5, 0.25, 0.5, 0.75, 1]) {+ const currentScale = await run('Archify.view.state().scale');+ await run(`Archify.view.${scale < currentScale ? 'zoomOut' : 'zoomIn'}()`);+ await stable();+ const value = await run(`(() => {+ const s = document.querySelector('.diagram-container > svg'), c = s.parentElement;+ const r = s.getBoundingClientRect(), nav = c.querySelector('.diagram-nav').getBoundingClientRect();+ return { state: Archify.view.state(), top: r.top, bottom: r.bottom,+ scrollY, navTop: nav.top, navBottom: nav.bottom, windowHeight: innerHeight };+ })()`);+ assert.equal(value.state.scale, scale);+ assert.ok(value.bottom > 0 && value.top < value.windowHeight, 'shrunk content stays on screen');+ assert.ok(value.navTop >= 0 && value.navBottom <= value.windowHeight, 'existing dock lift keeps controls usable');+ await snapshot(`long-scrolled-${position}-${scale}`);+ await screenshot(`long-scrolled-${position}-${scale}`);+ }+ }+ });++ await t.test('a true narrow wide canvas centers a fitting overview inside its visible scroll viewport', async () => {+ for (const scrolled of [false, true]) {+ await load('mobileWide', { width: 360, height: 800, reduced: true });+ if (scrolled) {+ await run(`document.querySelector('.diagram-container').scrollTo({ left: 240, behavior: 'instant' })`);+ await stable();+ }+ await run(`Archify.view.zoomOut(); Archify.view.zoomOut(); Archify.view.zoomOut()`);+ await stable();+ const value = await run(`(() => {+ const c = document.querySelector('.diagram-container'), s = c.querySelector(':scope > svg');+ const box = c.getBoundingClientRect(), r = s.getBoundingClientRect();+ return { scale: Archify.view.state().scale, wide: c.hasAttribute('data-wide-diagram'),+ svgWidth: s.clientWidth, clientWidth: c.clientWidth, scrollLeft: c.scrollLeft,+ left: r.left, right: r.right, containerLeft: box.left + c.clientLeft,+ containerRight: box.left + c.clientLeft + c.clientWidth };+ })()`);+ assert.equal(value.wide, true);+ assert.ok(value.svgWidth > value.clientWidth);+ assert.equal(value.scale, 0.25);+ if (scrolled) assert.ok(value.scrollLeft > 0);+ assert.ok(value.left >= value.containerLeft - 1 && value.right <= value.containerRight + 1);+ await snapshot(`mobile-wide-360-25-${scrolled ? 'scrolled' : 'initial'}`);+ await screenshot(`mobile-wide-360-25-${scrolled ? 'scrolled' : 'initial'}`);+ }+ });+await t.test('pointer cancellation ends dragging and controls do not begin a pan', async () => {await load();await run('Archify.view.zoomIn()');@@ -352,26 +511,40 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {});await t.test('export removes camera transforms without mutating the live camera', async () => {- await load();- await run(`Archify.view.reveal(['api'], { instant: true })`);- await stable();- const exported = await run(`(async () => {- const svg = document.querySelector('.diagram-container > svg'), before = svg.outerHTML;- const state = JSON.stringify(Archify.view.state()), original = URL.createObjectURL;- let blob;- URL.createObjectURL = value => { if (value.type.startsWith('image/svg+xml')) blob = value; return original.call(URL, value); };- let after;- try { const pending = Archify.exportMenu.run('svg'); after = svg.outerHTML; await pending; }- finally { URL.createObjectURL = original; }- const text = await blob.text();- const root = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;- return { text, unchanged: before === after && state === JSON.stringify(Archify.view.state()),- clean: !root.hasAttribute('data-view-scale') && !root.style.transform && !root.style.clipPath,- geometry: root.getAttribute('viewBox') === svg.getAttribute('viewBox'),- ids: [...root.querySelectorAll('[data-node-id]')].map(n => n.getAttribute('data-node-id')).join() === [...svg.querySelectorAll('[data-node-id]')].map(n => n.getAttribute('data-node-id')).join() };- })()`, true);- assert.equal(exported.unchanged, true); assert.equal(exported.clean, true); assert.equal(exported.geometry, true); assert.equal(exported.ids, true);- if (evidence) fs.writeFileSync(path.join(evidence, 'camera-export.svg'), exported.text);- await snapshot('export');+ for (const [mode, setup] of [+ ['semantic', `Archify.view.reveal(['api'], { instant: true })`],+ ['75-percent', `Archify.view.zoomOut()`],+ ]) {+ await load();+ await run(setup);+ await stable();+ const live = await run(`(() => ({ scale: Archify.view.state().scale,+ clip: document.querySelector('.diagram-container > svg').style.clipPath }))()`);+ if (mode === 'semantic') {+ assert.ok(live.scale > 1, 'semantic export exercises zoomed camera clipping');+ assert.notEqual(live.clip, '');+ } else {+ assert.equal(live.scale, 0.75);+ assert.equal(live.clip, '');+ }+ const exported = await run(`(async () => {+ const svg = document.querySelector('.diagram-container > svg'), before = svg.outerHTML;+ const state = JSON.stringify(Archify.view.state()), original = URL.createObjectURL;+ let blob;+ URL.createObjectURL = value => { if (value.type.startsWith('image/svg+xml')) blob = value; return original.call(URL, value); };+ let after;+ try { const pending = Archify.exportMenu.run('svg'); after = svg.outerHTML; await pending; }+ finally { URL.createObjectURL = original; }+ const text = await blob.text();+ const root = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;+ return { text, unchanged: before === after && state === JSON.stringify(Archify.view.state()),+ clean: !root.hasAttribute('data-view-scale') && !root.style.transform && !root.style.clipPath,+ geometry: root.getAttribute('viewBox') === svg.getAttribute('viewBox'),+ ids: [...root.querySelectorAll('[data-node-id]')].map(n => n.getAttribute('data-node-id')).join() === [...svg.querySelectorAll('[data-node-id]')].map(n => n.getAttribute('data-node-id')).join() };+ })()`, true);+ assert.equal(exported.unchanged, true); assert.equal(exported.clean, true); assert.equal(exported.geometry, true); assert.equal(exported.ids, true);+ if (evidence) fs.writeFileSync(path.join(evidence, `camera-export-${mode}.svg`), exported.text);+ await snapshot(`export-${mode}`);+ }});});diff --git a/viewer/README.md b/viewer/README.mdindex 68804352..e997c95d 100644--- a/viewer/README.md+++ b/viewer/README.md@@ -144,7 +144,7 @@ and candidate; encoding bytes/timing are not a deterministic oracle for video.## Focus / Semantic Explorer contract-The complete IIFE initializes once after Source Evidence and installBeacons(),+The complete IIFE initializes once after Source Evidence,before Intent Trace. Reader/Chrome Layout, Camera, Finder, Routeand Lens keep their later positions. Required diagram SVG, Passport controls andrelationship list remain required DOM. Shared viewerText/viewerCount/viewerKindLabel@@ -175,10 +175,13 @@ provider is part of Focus ownership, not a second initialization step.record or null; reachability returns copied node/edge arrays. Snapshot resultsare constructed from current authored nodes, edges and validated Reach state.- Passport uses existing label/kind/detail/context/tag/brand/source metadata. The- Source Evidence provider owns repository/node lookup and beacon installation;+ Source Evidence provider owns repository/node lookup; Finder searches source paths.Focus owns displaying or hiding evidence and building the existing safe links.Relationship rows are grouped out/in/loop, retaining authored order within eachgroup and deduplicating keys. Up/Down/Home/End clamp within the resulting rows.+ A diagram-container ResizeObserver requests the existing placement frame while+ Passport is visible, so manual positions are reclamped after Reader layout+ settles. Active dragging retains its existing placement guard.- Relationship intent priority is pin, then focus, then hover. Clearing one intentmay restore another. Pointer transitions within the same row/hit target do notreset intent; touch and non-fine-pointer hover retain their filters. Direct hover@@ -561,13 +564,36 @@ The source split narrows maintenance scope while preserving runtime dependenciesIt captures `.container`, `.diagram-container` and its direct child SVG,optional header/card elements, and the initial viewBox ratio.- The public Interface remains `measure`, `schedule`, `whenStable`, `active`,- and `receipt`. Viewer Chrome Layout calls `schedule` after changing the+ `receipt`, and `syncLegend`. Camera calls `syncLegend` while sampling its+ rendered transform so a corner legend stays fixed through zoom transitions.+ Viewer Chrome Layout calls `schedule` after changing thenavigation reserve and `whenStable` while probing layout. The browservisual checker also uses `window.Archify.readerLayout.whenStable`.- Reader owns the outer width (`html`'s `--archify-reader-width`) and temporary- `data-reader-layout` / `data-reader-overflow` attributes. Ineligible measures- clear them and reset the recorded width. CSS consumes the width on `.container`.+ `data-reader-layout` / `data-reader-overflow` attributes. Automatic canvases+ whose enlargement cap binds also use `data-reader-area` and+ `--archify-diagram-min-height` to keep a normal viewport-sized reading area.+ Uncapped and ineligible measures clear these values+ and reset the recorded width. CSS consumes the width on `.container`.Reader never writes canonical SVG geometry, viewBox or semantic IDs.+- Automatic (`intrinsic-height`) Sequence and Waterfall canvases use the+ available desktop reading width and retain authored vertical page scroll;+ overflow settling must not shrink them back to fit the viewport height.+ Other diagram families retain height fitting. All automatic canvases cap+ enlargement at 1.5 times the authored SVG width without reducing the outer+ reading area. Capped SVGs are centered inside that area; uncapped diagrams+ retain their existing natural flow. In a capped reader area, the original+ SVG legend uses a temporary CSS transform to sit at the outer canvas's+ bottom-left content corner, at its normal reading size through 25–100%+ camera zoom. The group stays in the same SVG for hover/focus and export.+ A legend that cannot fit clear of the navigation dock keeps its original+ position. Camera zoom above 100%, a nonbinding cap, small screens, Embed,+ Present and print restore ordinary in-SVG legend placement; canonical+ exports remove the corner marker and transform without changing authored+ coordinates or transforms. The 960px shell floor still serves the header and+ controls. An explicit viewBox retains+ its existing fixed-canvas fit. Present still provides the full overview;+ camera 100% is relative to the fitted reading size, not intrinsic SVG pixels.- Initial wide-diagram classification sets `data-wide-diagram` on the diagramcontainer and `data-diagram-shape` on `html`. These survive eligibility changes;CSS and camera/radar behavior still depend on the wide-diagram flag on narrow@@ -577,8 +603,8 @@ The source split narrows maintenance scope while preserving runtime dependenciesthe page lifetime. `schedule` coalesces requests; deferred overflow settlingrechecks eligibility. Leaving adaptive layout clears its state withoutunmounting the module or clearing another module's state.-- Width eligibility, overflow fallback and optional-observer behavior are- unchanged. Shared `waitForStableLayout` waits for fonts, pending work and+- Desktop eligibility and optional-observer behavior are unchanged. Shared+ `waitForStableLayout` waits for fonts, pending work andconsecutive stable dimensions; its default 240-frame sampling limit startsafter font readiness. It is not a wall-clock timeout for stalled fonts orbackground pages. Keep this helper shared with Viewer Chrome Layout.@@ -643,6 +669,16 @@ the modes are overview, manual and semantic. Zoom and Reset return undefined;delegates to `reveal` or returns false. Manual Reset interrupts callers, whereas`reset({ automatic: true })` stops camera motion without the manual takeover path.+Manual zoom uses 25 percentage point steps from 25% through 300%, relative to+the Reader's fitted size. Below 100%, the diagram centers within the visible+horizontal scroll viewport; diagrams taller than the viewport stay top-aligned.+Manual zoom adjusts page scrolling for those long diagrams to preserve the+visible reading region, or reveal the whole diagram when it fits onscreen.+Map detail and no camera dragging apply; wide mobile layouts retain+their contained horizontal scroll. Reset restores 100% overview. Semantic reveal+and Radar centering retain their existing minimum of 100%. Canonical exports+retain the original geometry regardless of the manual zoom.+`reveal` returns a transaction or false, with branch-specific side effects.Desktop empty/unknown targets can return before changing the camera. At widthsup to 720px it first stops motion and applies a semantic scale-1 state; a widediff --git a/viewer/export-cleanup.js b/viewer/export-cleanup.jsindex 4e1d5b4e..f0272d17 100644--- a/viewer/export-cleanup.js+++ b/viewer/export-cleanup.js@@ -19,6 +19,10 @@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();});@@ -156,5 +160,5 @@!clone.hasAttribute('data-tree-any-collapsed') &&!clone.style.getPropertyValue('transform') &&!clone.style.getPropertyValue('clip-path') &&- clone.querySelectorAll('[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;+ clone.querySelectorAll('[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;}diff --git a/viewer/focus.js b/viewer/focus.jsindex 91aaccd4..a2b03ac6 100644--- a/viewer/focus.js+++ b/viewer/focus.js@@ -1550,6 +1550,13 @@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();});diff --git a/viewer/reader-layout.js b/viewer/reader-layout.jsindex beada7c3..76fba0c0 100644--- a/viewer/reader-layout.js+++ b/viewer/reader-layout.js@@ -4,14 +4,18 @@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 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 measuredHeightFit = svg && svg.getAttribute('data-reader-fit') === 'intrinsic-height';+ var widthFirstReading = measuredHeightFit && svg &&+ (svg.hasAttribute('data-sequence-column-fit') || svg.hasAttribute('data-waterfall-ui'));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@@ -21,6 +25,7 @@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)@@ -132,12 +137,60 @@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. Only ordinary capped+ // reading at 25–100% borrows the spare outer canvas for its legend.+ function syncLegend() {+ var cameraScale = Number(svg && svg.getAttribute('data-view-scale')) || 1;+ if (!legend || !eligible() || html.getAttribute('data-reader-area') !== 'true' || 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);+ 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@@ -199,22 +252,36 @@// 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));- if (Math.abs(rounded - lastWidth) < 1) return false;+ var changed = Math.abs(rounded - lastWidth) >= 1;lastWidth = rounded;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');- if (rounded < shellFloor) {- // `rounded` already includes a docked rail and its gap; the SVG cap- // is only the diagram's share, not the space beside it.- var railShare = html.getAttribute('data-reader-rail') === 'true' ? RAIL_WIDTH + RAIL_GAP : 0;- html.style.setProperty('--archify-diagram-max-width', Math.max(1, rounded - railShare - chromeMetrics().diagramX) + '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);@@ -226,7 +293,7 @@document.documentElement.scrollHeight,document.body.scrollHeight) - window.innerHeight - belowFold();- if (overflow > 1 && lastWidth > Math.ceil(minWidth)) {+ if (overflow > 1 && !widthFirstReading && lastWidth > Math.ceil(minWidth)) {applyWidth(Math.max(minWidth, lastWidth - overflow * ratio - 4), minWidth);settledCap = lastWidth;html.setAttribute('data-reader-overflow', 'reduced');@@ -277,10 +344,9 @@if (collapsedPreference === '1' || (collapsedPreference !== '0' && !comfortable)) mode = 'collapsed';else mode = fitsReadable ? 'true' : 'overlay';}- // With notes below the fold, the first screen belongs to the whole- // diagram and its controls: it may shrink past the comfortable primary- // size down to the renderer's readable text floor, and zoom restores- // detail. Only a graph taller than that floor allows still scrolls.+ // 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';@@ -292,6 +358,13 @@outerHeight(header) + stackedBelow;var availableSvgHeight = Math.max(1, window.innerHeight - fixedHeight);var desiredWidth = availableSvgHeight * ratio + chrome.diagramX + (docked ? railExtra : 0);+ // Long sequences and waterfall rows use the available horizontal room;+ // ordinary page scrolling keeps their text and row spacing readable.+ // Other diagram families retain the existing height-fit strategy.+ if (widthFirstReading) 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);@@ -320,7 +393,8 @@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); }@@ -339,6 +413,8 @@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);@@ -381,6 +457,7 @@measure: measure,schedule: schedule,whenStable: whenStable,+ syncLegend: syncLegend,active: function () { return html.getAttribute('data-reader-layout') === 'adaptive'; },receipt: function () { return { ratio: ratio, width: lastWidth }; }};diff --git a/viewer/template.source.html b/viewer/template.source.htmlindex c2031e4a..2e01bc91 100644--- a/viewer/template.source.html+++ b/viewer/template.source.html@@ -910,83 +910,23 @@ OTHER DEALINGS IN THE FONT SOFTWARE.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') ? 22 : 0;- var title = document.createElementNS(svgNamespace, 'title');- title.textContent = label;- var plate = document.createElementNS(svgNamespace, 'rect');- plate.setAttribute('height', '13');- plate.setAttribute('rx', '6.5');- var text = document.createElementNS(svgNamespace, 'text');- text.setAttribute('y', '9.4');- text.textContent = viewerText('viewer.passport.sourceMarker') + ' ' + count;- beacon.appendChild(title);- beacon.appendChild(plate);- beacon.appendChild(text);- node.appendChild(beacon);-- // Measure the real glyph advance, then clamp the plate between 24- // and 36px; a still-wider label is squeezed with textLength so the- // badge never overlaps the neighbouring brand mark or sigil.- var textWidth = 16;- try {- var measured = text.getComputedTextLength();- if (Number.isFinite(measured) && measured > 0) textWidth = measured;- } catch (_) {}- var plateWidth = Math.min(36, Math.max(24, textWidth + 8));- if (textWidth > plateWidth - 8) {- text.setAttribute('textLength', String(plateWidth - 8));- text.setAttribute('lengthAdjust', 'spacingAndGlyphs');- }- plate.setAttribute('width', String(plateWidth));- text.setAttribute('x', String(plateWidth / 2));- beacon.setAttribute('transform', 'translate(' + (box.x + box.width - 6 - brandOffset - plateWidth) + ' ' + (box.y + 4.5) + ')');-- 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;- }return {available: function () { return Boolean(payload); },repository: function () { return payload ? payload.repository : null; },+ // Compatibility only: sources are shown in the Focus card.+ installBeacons: function () { return 0; },node: function (id) {var sources = payload && payload.nodes ? payload.nodes[id] : null;return Array.isArray(sources) ? sources.slice() : [];- },- installBeacons: installBeacons+ }};})();- Archify.sourceEvidence.installBeacons();/* ARCHIFY:TREE_BRANCHES */diff --git a/viewer/viewer-camera.js b/viewer/viewer-camera.jsindex e8f912d0..ac26c80f 100644--- a/viewer/viewer-camera.js+++ b/viewer/viewer-camera.js@@ -7,6 +7,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;@@ -21,6 +23,16 @@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));}@@ -47,15 +59,15 @@var y;var width;var height;- if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram')) {+ if (window.innerWidth <= 720 && container.hasAttribute('data-wide-diagram') && state.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;+ x = viewBox.x + (((container.scrollLeft - 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);+ width = Math.min(viewBox.width, Math.min(metrics.width, container.clientWidth) / state.scale / metrics.scale);height = Math.min(viewBox.height, metrics.height / state.scale / metrics.scale);}width = Math.max(1, Math.min(viewBox.width, width));@@ -127,6 +139,7 @@clipFrame = 0;var rendered = sampleRenderedState();clipToViewport(rendered);+ if (Archify.readerLayout && typeof Archify.readerLayout.syncLegend === 'function') Archify.readerLayout.syncLegend();if (!cameraSettled(rendered)) clipFrame = requestAnimationFrame(sample);}sample();@@ -134,12 +147,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();@@ -233,8 +246,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;@@ -243,6 +262,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 || {};diff --git a/viewer/viewer.css b/viewer/viewer.cssindex 00ab3f0e..6bc99e80 100644--- a/viewer/viewer.css+++ b/viewer/viewer.css@@ -430,15 +430,29 @@ html[data-present="true"]:not([data-embed="true"]) #btn-present {color: var(--frontend-stroke);}-/* The reader owns only the outer scale. Wide diagrams and measured tall workflows keep one authored- SVG/viewBox while the runtime chooses a desktop width from the actual- vertical budget. This avoids device-specific files and breakpoint- jumps between a laptop and a tall monitor. */+/* The reader owns only the outer scale. Long sequences and waterfall rows+ favor reading width and page scroll; other diagrams keep height fitting.+ Small automatic canvases retain a modest scale inside a usable shell.+ Every strategy preserves the authored SVG/viewBox and semantic geometry. */.container {width: 100%;max-width: var(--archify-reader-width, 1440px);margin: 0 auto;}+html[data-reader-area="true"] .diagram-container {+ min-height: var(--archify-diagram-min-height);+ display: flex;+ align-items: center;+}+html[data-reader-area="true"] .diagram-container > svg { flex-shrink: 0; }+/* The original SVG legend can use the spare outer reader canvas while the+ capped diagram stays centered. The container still clips all outer paint. */+.diagram-container:has([data-reader-legend-corner]) > svg { overflow: visible; }+.diagram-container [data-reader-legend-corner] {+ transform-origin: 0 0;+ transform-box: view-box;+ transform: var(--archify-reader-legend-transform);+}html[data-reader-narrow="true"]:not([data-present="true"]) .diagram-container > svg {min-width: 0;max-width: var(--archify-diagram-max-width);@@ -4009,41 +4023,6 @@ svg [data-node-id]:focus-visible {filter: drop-shadow(0 0 7px var(--frontend-stroke));outline: none;}-/* Verified Source Beacons are installed at runtime only for nodes whose- repository evidence passed the local revision/blob/line checks. They- live inside the owning node so every focus, route, story, and guided- view keeps one coherent opacity state. Export serialization removes- them before producing the canonical SVG or any derived visual. */-.source-evidence-beacon {- pointer-events: none;- opacity: 1;- transition: filter 160ms ease;-}-.source-evidence-beacon rect {- fill: color-mix(in srgb, var(--mask) 92%, var(--backend-stroke));- stroke: color-mix(in srgb, var(--backend-stroke) 82%, var(--panel-border));- stroke-width: 1;- vector-effect: non-scaling-stroke;-}-.source-evidence-beacon text {- fill: var(--backend-stroke);- font-size: 7px;- font-weight: 700;- letter-spacing: 0.06em;- text-anchor: middle;- text-transform: uppercase;-}-svg [data-node-id]:hover .source-evidence-beacon,-svg [data-node-id]:focus-visible .source-evidence-beacon,-svg [data-node-id][data-focus-selected] .source-evidence-beacon {- opacity: 1;- filter: drop-shadow(0 0 4px color-mix(in srgb, var(--backend-stroke) 72%, transparent));-}-svg[data-preset="signal-flow"] .source-evidence-beacon { opacity: 0.9; }-svg[data-preset="blueprint"] .source-evidence-beacon rect {- rx: 0.8px;- filter: none;-}svg [data-legend-kind][role="button"] { cursor: pointer; }svg [data-legend-kind]:focus { outline: none; }svg [data-legend-hit] {@@ -4702,6 +4681,5 @@ html[data-share-playback="true"] svg[data-animation="trace"] [data-graph-role="afilter: none;}.relationship-pulse-overlay { display: none !important; }- .source-evidence-beacon,svg [data-node-id], svg [data-edge-from], svg [data-detail], svg [data-detail-anchor], svg [data-legend-hit], svg { transition: none !important; }}