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
fix(viewer): preserve source accessibility and compact zoomed page flow
tt-a1i0942c7f6cd04
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsindex 05ec34ad..a3b2502e 100644--- a/archify/bin/visual-check.mjs+++ b/archify/bin/visual-check.mjs@@ -1890,7 +1890,7 @@ function observation({ width, height, theme, metrics }) {&& !overflowX&& readabilityOk&& Number.isFinite(minimumProjectedNodeTextPx)- && ((readerLayout === 'adaptive' && readerOverflow === 'authored' && readerFit === 'intrinsic-height')+ && ((readerLayout === 'adaptive' && readerOverflow === 'authored' && (readerFit === 'intrinsic-height' || readerFit === 'width-first'))|| (readerFit === 'authored-height' && metrics.diagramType === 'architecture'&& metrics.documentScrollUnclipped === true)));@@ -2081,7 +2081,7 @@ export function verticalBudgetFixes(entry) {? `the page is ${excess}px too tall (${stacked}); the Reader already narrowed the stage to its ${entry.diagramWidth}px minimum, so the SVG height only follows meta.viewBox: keep every node and relationship and reduce the viewBox height to at most ${targetViewBoxHeight} (from ${page.viewBoxHeight}) by tightening vertical gaps and empty rows`: `the page is ${excess}px too tall (${stacked}) and the SVG alone exceeds the viewport at the minimum reader width; split the diagram into two`);} else {- fixes.push(`the page is ${excess}px too tall (${stacked}); the SVG spans the full ${entry.diagramWidth}px reader width because its viewBox ratio is below 1.55 and it declares no intrinsic-height fit, so the Reader can neither narrow it nor accept readable vertical scroll: either remove meta.viewBox so the renderer sizes the canvas and declares the fit, or make the viewBox at least 1.55x wider than tall`);+ fixes.push(`the page is ${excess}px too tall (${stacked}); the SVG spans the full ${entry.diagramWidth}px reader width because its viewBox ratio is below 1.55 and it declares no automatic Reader fit, so the Reader can neither narrow it nor accept readable vertical scroll: either remove meta.viewBox so the renderer sizes the canvas and declares the fit, or make the viewBox at least 1.55x wider than tall`);}}if (page.cardsPx >= excess) {diff --git a/archify/examples/locales/de.json b/archify/examples/locales/de.jsonindex 568cf380..7fdebf22 100644--- a/archify/examples/locales/de.json+++ b/archify/examples/locales/de.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "SCHLEIFE","viewer.passport.sourceCount.one": "{count} verifizierte Quellenreferenz","viewer.passport.sourceCount.other": "{count} verifizierte Quellenreferenzen",- "viewer.passport.sourceMarker": "QUELLE",- "viewer.passport.beacon.one": "{count} verifizierte Quelle; diesen Knoten fokussieren, um sie zu prüfen",- "viewer.passport.beacon.other": "{count} verifizierte Quellen; diesen Knoten fokussieren, um sie zu prüfen","viewer.passport.repository.open": "Verifizierte Repository-Revision {revision} öffnen","viewer.passport.source.open": "Verifizierte Quelle {path} bei Revision {revision} öffnen","viewer.passport.source.openLink": "Öffnen ↗",diff --git a/archify/examples/locales/fr.json b/archify/examples/locales/fr.jsonindex af7f539c..af7ac101 100644--- a/archify/examples/locales/fr.json+++ b/archify/examples/locales/fr.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "BOUCLE","viewer.passport.sourceCount.one": "{count} référence de source vérifiée","viewer.passport.sourceCount.other": "{count} références de source vérifiées",- "viewer.passport.sourceMarker": "SOURCE",- "viewer.passport.beacon.one": "{count} source vérifiée ; centrez ce nœud pour l'inspecter",- "viewer.passport.beacon.other": "{count} sources vérifiées ; centrez ce nœud pour l'inspecter","viewer.passport.repository.open": "Ouvrir la révision {revision} du dépôt vérifié","viewer.passport.source.open": "Ouvrir la source vérifiée {path} à la révision {revision}","viewer.passport.source.openLink": "Ouvrir ↗",diff --git a/archify/examples/locales/it.json b/archify/examples/locales/it.jsonindex 362a061c..57df42ad 100644--- a/archify/examples/locales/it.json+++ b/archify/examples/locales/it.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "ANELLO","viewer.passport.sourceCount.one": "{count} riferimento a fonte verificata","viewer.passport.sourceCount.other": "{count} riferimenti a fonti verificate",- "viewer.passport.sourceMarker": "FONTE",- "viewer.passport.beacon.one": "{count} fonte verificata; metti a fuoco questo nodo per analizzarla",- "viewer.passport.beacon.other": "{count} fonti verificate; metti a fuoco questo nodo per analizzarle","viewer.passport.repository.open": "Apri la revisione {revision} del repository verificato","viewer.passport.source.open": "Apri la fonte verificata {path} alla revisione {revision}","viewer.passport.source.openLink": "Apri ↗",diff --git a/archify/examples/locales/ja.json b/archify/examples/locales/ja.jsonindex 83309b4d..d49ce3a2 100644--- a/archify/examples/locales/ja.json+++ b/archify/examples/locales/ja.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "ループ","viewer.passport.sourceCount.one": "検証済みソース参照 {count} 件","viewer.passport.sourceCount.other": "検証済みソース参照 {count} 件",- "viewer.passport.sourceMarker": "出典",- "viewer.passport.beacon.one": "検証済みソース {count} 件。このノードにフォーカスして確認",- "viewer.passport.beacon.other": "検証済みソース {count} 件。このノードにフォーカスして確認","viewer.passport.repository.open": "検証済みリポジトリのリビジョン {revision} を開く","viewer.passport.source.open": "リビジョン {revision} の検証済みソース {path} を開く","viewer.passport.source.openLink": "開く ↗",diff --git a/archify/examples/locales/pt.json b/archify/examples/locales/pt.jsonindex c99fe4d2..166c3089 100644--- a/archify/examples/locales/pt.json+++ b/archify/examples/locales/pt.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "LAÇO","viewer.passport.sourceCount.one": "{count} referência de origem verificada","viewer.passport.sourceCount.other": "{count} referências de origem verificadas",- "viewer.passport.sourceMarker": "ORIG",- "viewer.passport.beacon.one": "{count} origem verificada; foque este nó para inspecionar",- "viewer.passport.beacon.other": "{count} origens verificadas; foque este nó para inspecionar","viewer.passport.repository.open": "Abrir revisão verificada do repositório {revision}","viewer.passport.source.open": "Abrir origem verificada {path} na revisão {revision}","viewer.passport.source.openLink": "Abrir ↗",diff --git a/archify/examples/locales/ru.json b/archify/examples/locales/ru.jsonindex 3c93c434..8fab5fff 100644--- a/archify/examples/locales/ru.json+++ b/archify/examples/locales/ru.json@@ -268,9 +268,6 @@"viewer.passport.relationship.direction.loop": "ПЕТЛЯ","viewer.passport.sourceCount.one": "{count} проверенная ссылка на источник","viewer.passport.sourceCount.other": "{count} проверенных ссылок на источники",- "viewer.passport.sourceMarker": "ИСТ",- "viewer.passport.beacon.one": "{count} проверенный источник; выделите узел для просмотра",- "viewer.passport.beacon.other": "{count} проверенных источников; выделите узел для просмотра","viewer.passport.repository.open": "Открыть проверенную ревизию репозитория {revision}","viewer.passport.source.open": "Открыть проверенный источник {path} на ревизии {revision}","viewer.passport.source.openLink": "Открыть ↗",diff --git a/archify/locales/en.json b/archify/locales/en.jsonindex 410c2a40..b28176c2 100644--- a/archify/locales/en.json+++ b/archify/locales/en.json@@ -277,9 +277,6 @@"viewer.passport.relationship.direction.loop": "LOOP","viewer.passport.sourceCount.one": "{count} verified source reference","viewer.passport.sourceCount.other": "{count} verified source references",- "viewer.passport.sourceMarker": "SRC",- "viewer.passport.beacon.one": "{count} verified source; focus this node to inspect",- "viewer.passport.beacon.other": "{count} verified sources; focus this node to inspect","viewer.passport.repository.open": "Open verified repository revision {revision}","viewer.passport.source.open": "Open verified source {path} at revision {revision}","viewer.passport.source.openLink": "Open ↗",diff --git a/archify/locales/es.json b/archify/locales/es.jsonindex 5bbfe8ba..25c43f8d 100644--- a/archify/locales/es.json+++ b/archify/locales/es.json@@ -285,9 +285,6 @@"viewer.passport.relationship.direction.loop": "BUCLE","viewer.passport.sourceCount.one": "{count} referencia de fuente verificada","viewer.passport.sourceCount.other": "{count} referencias de fuente verificadas",- "viewer.passport.sourceMarker": "SRC",- "viewer.passport.beacon.one": "{count} fuente verificada; enfoca este nodo para inspeccionar",- "viewer.passport.beacon.other": "{count} fuentes verificadas; enfoca este nodo para inspeccionar","viewer.passport.repository.open": "Abrir la revisión verificada del repositorio {revision}","viewer.passport.source.open": "Abrir la fuente verificada {path} en la revisión {revision}","viewer.passport.source.openLink": "Abrir ↗",diff --git a/archify/locales/ko.json b/archify/locales/ko.jsonindex 4d193dda..211a2948 100644--- a/archify/locales/ko.json+++ b/archify/locales/ko.json@@ -276,9 +276,6 @@"viewer.passport.relationship.direction.loop": "순환","viewer.passport.sourceCount.one": "검증된 소스 참조 {count}개","viewer.passport.sourceCount.other": "검증된 소스 참조 {count}개",- "viewer.passport.sourceMarker": "출처",- "viewer.passport.beacon.one": "검증된 소스 {count}개; 이 노드를 포커스하여 확인",- "viewer.passport.beacon.other": "검증된 소스 {count}개; 이 노드를 포커스하여 확인","viewer.passport.repository.open": "검증된 저장소 리비전 {revision} 열기","viewer.passport.source.open": "리비전 {revision}의 검증된 소스 {path} 열기","viewer.passport.source.openLink": "열기 ↗",diff --git a/archify/locales/zh-CN.json b/archify/locales/zh-CN.jsonindex dc59cc66..8ff6ca24 100644--- a/archify/locales/zh-CN.json+++ b/archify/locales/zh-CN.json@@ -277,9 +277,6 @@"viewer.passport.relationship.direction.loop": "自环","viewer.passport.sourceCount.one": "{count} 个已验证来源引用","viewer.passport.sourceCount.other": "{count} 个已验证来源引用",- "viewer.passport.sourceMarker": "来源",- "viewer.passport.beacon.one": "{count} 个已验证来源;聚焦此节点以检查",- "viewer.passport.beacon.other": "{count} 个已验证来源;聚焦此节点以检查","viewer.passport.repository.open": "打开已验证的仓库修订版本 {revision}","viewer.passport.source.open": "打开修订版本 {revision} 中已验证的来源 {path}","viewer.passport.source.openLink": "打开 ↗",diff --git a/archify/locales/zh-TW.json b/archify/locales/zh-TW.jsonindex b28a6e85..15dd4451 100644--- a/archify/locales/zh-TW.json+++ b/archify/locales/zh-TW.json@@ -277,9 +277,6 @@"viewer.passport.relationship.direction.loop": "自環","viewer.passport.sourceCount.one": "{count} 個已驗證來源引用","viewer.passport.sourceCount.other": "{count} 個已驗證來源引用",- "viewer.passport.sourceMarker": "來源",- "viewer.passport.beacon.one": "{count} 個已驗證來源;聚焦此節點以檢查",- "viewer.passport.beacon.other": "{count} 個已驗證來源;聚焦此節點以檢查","viewer.passport.repository.open": "開啟已驗證的儲存庫版本 {revision}","viewer.passport.source.open": "開啟版本 {revision} 中已驗證的來源 {path}","viewer.passport.source.openLink": "開啟 ↗",diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex ea770f23..0768987f 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -431,7 +431,8 @@ The receipt binds the artifact SHA-256 and byte count, identifiesHorizontal overflow always fails. Normal document-level vertical scrolling isaccepted only with a renderer-declared contract and measured readable text.-Automatic canvases declare `data-reader-fit="intrinsic-height"`; their adaptive+Automatic canvases declare `data-reader-fit="intrinsic-height"` (height fitting)+or `data-reader-fit="width-first"` (Sequence and Waterfall reading width); their adaptiveReader must reach its readable width and expose `data-reader-overflow="authored"`.Architecture with an explicit `meta.viewBox` instead declares`data-diagram-type="architecture"` and `data-reader-fit="authored-height"`:diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjsindex 808db62f..e45b73b9 100644--- a/archify/renderers/sequence/render-sequence.mjs+++ b/archify/renderers/sequence/render-sequence.mjs@@ -483,7 +483,7 @@ function renderSvg() {// Same default-canvas contract as lifecycle: 920x760 is below the 1.55 wide// ratio, so without intrinsic-height the desktop Reader can neither narrow// nor scroll it and every default sequence fails the browser gate.- const readerFit = sequence.meta?.viewBox ? '' : ' data-reader-fit="intrinsic-height"';+ const readerFit = sequence.meta?.viewBox ? '' : ' data-reader-fit="width-first"';return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" data-sequence-column-fit="${columnFit}"${readerFit} ${svgRootAttrs(sequence.meta)}>${svgAccessibleText(sequence.meta, 'sequence')}${renderDefinitions()}diff --git a/archify/renderers/shared/desktop-readability.mjs b/archify/renderers/shared/desktop-readability.mjsindex c3292c69..c9c59ad8 100644--- a/archify/renderers/shared/desktop-readability.mjs+++ b/archify/renderers/shared/desktop-readability.mjs@@ -88,7 +88,7 @@ export function declaredWideReadabilityBudget({export const DESKTOP_FIXED_VERTICAL_CHROME_PX = Object.freeze({ body: 12, header: 39, diagram: 75 });// A canvas the Reader can neither narrow (viewBox ratio below the wide-// threshold) nor scroll readably (no intrinsic-height fit) renders at the full+// threshold) nor scroll readably (no automatic Reader fit) renders at the full// reader width, so its page height is a function of the viewBox alone. Returns// null when the Reader has a way to fit the page; otherwise the certain// overflow at 1440x900 before any cards are counted.@@ -104,7 +104,7 @@ export function predictedFixedWidthOverflow({} = {}) {if (![viewBoxWidth, viewBoxHeight].every(Number.isFinite) || viewBoxWidth <= 0 || viewBoxHeight <= 0) return null;const ratio = viewBoxWidth / viewBoxHeight;- if (readerFit === 'intrinsic-height'+ if (readerFit === 'intrinsic-height' || readerFit === 'width-first'|| (readerFit === 'authored-height' && diagramType === 'architecture')|| ratio >= DECLARED_WIDE_READER_RATIO) return null;const svgWidthPx = viewport.width - bodyHorizontalPx - diagramHorizontalPx;diff --git a/archify/renderers/waterfall/render-waterfall.mjs b/archify/renderers/waterfall/render-waterfall.mjsindex 2d10b10c..e6db3728 100644--- a/archify/renderers/waterfall/render-waterfall.mjs+++ b/archify/renderers/waterfall/render-waterfall.mjs@@ -278,7 +278,7 @@ function legendSwatch(entry) {const SOLID_TONES = ['frontend', 'backend', 'database', 'cloud', 'messagebus', 'security', 'external'];function renderSvg() {- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(wf.meta)} data-waterfall-ui="" data-waterfall-unit="${esc(unit)}" data-reader-fit="intrinsic-height" data-reader-min-text="7.5">+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(wf.meta)} data-waterfall-ui="" data-waterfall-unit="${esc(unit)}" data-reader-fit="width-first" data-reader-min-text="7.5">${svgAccessibleText(wf.meta, 'waterfall')}${renderDefinitions()}<style>diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjsindex 5e392c8e..dbd96e70 100644--- a/archify/scripts/check-render-output.mjs+++ b/archify/scripts/check-render-output.mjs@@ -1169,7 +1169,7 @@ function collectDesktopReadability(svgAttrs, fragment, contract) {}const minimumSourceTextPx = entries.length ? Math.min(...entries.map((entry) => entry.sourceFontPx)) : Number.NaN;const eligible = contract === DECLARED_WIDE_READER_CONTRACT- && svgAttrs['data-reader-fit'] === 'intrinsic-height'+ && ['intrinsic-height', 'width-first'].includes(svgAttrs['data-reader-fit'])&& Number.isFinite(requestedMinimumTextPx) && requestedMinimumTextPx > 0&& !invalidSemanticText && entries.length > 0;const declared = eligible ? declaredWideReadabilityBudget({diff --git a/test/adaptive-reader-layout.test.mjs b/test/adaptive-reader-layout.test.mjsindex c782e20b..86e4a342 100644--- a/test/adaptive-reader-layout.test.mjs+++ b/test/adaptive-reader-layout.test.mjs@@ -40,7 +40,10 @@ test('wide desktop diagrams use one height-budgeted reader shell instead of brea});test('compiler-measured intrinsic tall workflows reuse the height budget without widening eligibility', () => {- assert.match(reader, /svg\.getAttribute\('data-reader-fit'\) === 'intrinsic-height'/);+ assert.match(reader, /var readerFit = svg && svg\.getAttribute\('data-reader-fit'\)/);+ assert.match(reader, /var widthFirstReading = readerFit === 'width-first'/);+ assert.match(reader, /var measuredHeightFit = readerFit === 'intrinsic-height' \|\| widthFirstReading/);+ assert.doesNotMatch(reader, /data-sequence-column-fit|data-waterfall-ui/);assert.match(reader, /ratio >= WIDE_RATIO \|\| measuredHeightFit/);assert.match(reader, /var MIN_PROJECTED_NODE_TEXT_PX = 6/);assert.match(reader, /viewBox\.width \* minimumReadableScale\(\) \+ chrome\.diagramX/);diff --git a/test/export-cleanup-browser.test.mjs b/test/export-cleanup-browser.test.mjsindex 3381ad20..392a597f 100644--- a/test/export-cleanup-browser.test.mjs+++ b/test/export-cleanup-browser.test.mjs@@ -297,7 +297,7 @@ test('Export cleanup preserves canonical artifacts and live interaction state',emptyClean, emptyUnchanged: emptyBefore === empty.outerHTML };})()`);assert.deepEqual(result, { clean: true, twiceClean: true, unchanged: true, idempotent: true,- authored: true, labels: ['original', null, null], restorationRecords: 0, shares: false,+ authored: true, labels: ['original', '', null], restorationRecords: 0, shares: false,emptyClean: true, emptyUnchanged: true });records.push({ label: 'restoration', ...result });});diff --git a/test/fixtures/japanese-locale.architecture.json b/test/fixtures/japanese-locale.architecture.jsonindex 920b6dac..87b4bd71 100644--- a/test/fixtures/japanese-locale.architecture.json+++ b/test/fixtures/japanese-locale.architecture.json@@ -274,9 +274,6 @@"viewer.passport.relationship.direction.loop": "ループ","viewer.passport.sourceCount.one": "検証済みソース参照 {count} 件","viewer.passport.sourceCount.other": "検証済みソース参照 {count} 件",- "viewer.passport.sourceMarker": "出典",- "viewer.passport.beacon.one": "検証済みソース {count} 件。このノードにフォーカスして確認",- "viewer.passport.beacon.other": "検証済みソース {count} 件。このノードにフォーカスして確認","viewer.passport.repository.open": "検証済みリポジトリのリビジョン {revision} を開く","viewer.passport.source.open": "リビジョン {revision} の検証済みソース {path} を開く","viewer.passport.source.openLink": "開く ↗",diff --git a/test/fixtures/korean-locale.architecture.json b/test/fixtures/korean-locale.architecture.jsonindex d87205c8..73130f3f 100644--- a/test/fixtures/korean-locale.architecture.json+++ b/test/fixtures/korean-locale.architecture.json@@ -274,9 +274,6 @@"viewer.passport.relationship.direction.loop": "순환","viewer.passport.sourceCount.one": "검증된 소스 참조 {count}개","viewer.passport.sourceCount.other": "검증된 소스 참조 {count}개",- "viewer.passport.sourceMarker": "출처",- "viewer.passport.beacon.one": "검증된 소스 {count}개; 이 노드를 포커스하여 확인",- "viewer.passport.beacon.other": "검증된 소스 {count}개; 이 노드를 포커스하여 확인","viewer.passport.repository.open": "검증된 저장소 리비전 {revision} 열기","viewer.passport.source.open": "리비전 {revision}의 검증된 소스 {path} 열기","viewer.passport.source.openLink": "열기 ↗",diff --git a/test/layout-rules.test.mjs b/test/layout-rules.test.mjsindex be2643f2..2a51ca11 100644--- a/test/layout-rules.test.mjs+++ b/test/layout-rules.test.mjs@@ -1376,9 +1376,8 @@ test('architecture: measured auto canvases opt into height-aware reader fitting'assert.doesNotMatch(authoredSvg, /data-reader-min-text=/);});-// Sequence and dataflow share the lifecycle/architecture contract: the default-// canvas is below the wide ratio, so omitting meta.viewBox must declare the-// intrinsic-height fit or every default canvas certainly overflows 1440x900.+// Automatic Sequence declares width-first; Dataflow declares intrinsic-height.+// Both default canvases need an explicit automatic Reader fit below the wide ratio.for (const [mode, doc, authoredViewBox] of [['sequence', {schema_version: 1, diagram_type: 'sequence',@@ -1397,12 +1396,12 @@ for (const [mode, doc, authoredViewBox] of [flows: [{ from: 'a', to: 'b', label: 'write' }],}, [1080, 520]],]) {- test(`${mode}: default canvas declares intrinsic-height fit, authored viewBox does not`, () => {+ test(`${mode}: default canvas declares automatic Reader fit, authored viewBox does not`, () => {const automatic = render(mode, doc);assert.equal(automatic.code, 0, automatic.stderr);const automaticSvg = fs.readFileSync(automatic.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];assert.ok(automaticSvg, `expected an SVG root for the default ${mode} canvas`);- assert.match(automaticSvg, /data-reader-fit="intrinsic-height"/);+ assert.match(automaticSvg, new RegExp(`data-reader-fit="${mode === 'sequence' ? 'width-first' : 'intrinsic-height'}"`));const authored = structuredClone(doc);authored.meta.viewBox = authoredViewBox;diff --git a/test/reader-layout-browser.test.mjs b/test/reader-layout-browser.test.mjsindex e2accba8..d1e147dd 100644--- a/test/reader-layout-browser.test.mjs+++ b/test/reader-layout-browser.test.mjs@@ -352,6 +352,29 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundassert.equal(constrained.legendCorner, false);assert.equal(constrained.legendTransformRuntime, '');});+ await t.test('zero-size SVG clears corner legend placement and recovers without nonfinite transforms', async () => {+ await load(compactErd, { width: 1440, height: 900 });+ assert.equal((await snapshot('legend-size-initial')).legendCorner, true);+ for (const collapse of ["svg.style.height = '0px'", "svg.style.width = '0px'; svg.style.minWidth = '0px'"]) {+ const collapsed = await evaluate(`(() => {+ const svg = document.querySelector('.diagram-container > svg');+ ${collapse};+ Archify.readerLayout.syncLegend();+ const legend = svg.querySelector('[data-legend]');+ return { width: svg.clientWidth, height: svg.clientHeight, corner: legend.hasAttribute('data-reader-legend-corner'),+ transform: legend.style.getPropertyValue('--archify-reader-legend-transform') };+ })()`);+ assert.ok(collapsed.width === 0 || collapsed.height === 0);+ assert.equal(collapsed.corner, false);+ assert.equal(collapsed.transform, '');+ records.push({ label: 'legend-size-collapsed', ...collapsed });+ await evaluate(`(() => { const svg = document.querySelector('.diagram-container > svg');+ svg.style.removeProperty('height'); svg.style.removeProperty('width'); svg.style.removeProperty('min-width');+ Archify.readerLayout.syncLegend(); })()`);+ await stable();+ assert.equal((await snapshot('legend-size-restored')).legendCorner, true);+ }+ });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');@@ -501,13 +524,13 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundreturn file;}const samples = [- ['sequence', 1100, 2400, 'data-sequence-column-fit="fixed"'],- ['waterfall', 1100, 2400, 'data-waterfall-ui=""'],- ['small-erd', 456, 270, ''],+ ['sequence', 1100, 2400, 'width-first'],+ ['waterfall', 1100, 2400, 'width-first'],+ ['small-erd', 456, 270, 'intrinsic-height'],];- for (const [name, width, height, marker] of samples) {+ for (const [name, width, height, fit] of samples) {const file = readerFixture(name, width, height,- `data-reader-fit="intrinsic-height" data-reader-min-text="7.5" ${marker}`);+ `data-reader-fit="${fit}" data-reader-min-text="7.5"`);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}`);@@ -565,15 +588,51 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundassert.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);+ // UI and column metadata alone never declare automatic Reader fitting.+ for (const marker of ['data-sequence-column-fit="fixed"', 'data-waterfall-ui=""', '']) {+ const authored = readerFixture('undeclared-reader', 1100, 2400, marker);+ await load(authored);+ inactive(await snapshot('undeclared-reader'), false);+ const heightFit = readerFixture('height-fit-reader', 1100, 2400, `data-reader-fit="intrinsic-height" ${marker}`);+ await load(heightFit);+ const state = await snapshot('height-fit-reader');+ assert.equal(state.active, true);+ assert.ok(state.receipt.width < 1200, 'intrinsic fitting stays independent of family markers');+ }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('public renderers declare automatic reading width while undeclared canvases retain their fit', async () => {+ const sequence = { schema_version: 1, diagram_type: 'sequence', meta: { title: 'Reader sequence', output: 'reader-sequence.html' },+ participants: [{ id: 'a', type: 'external', label: 'Client' }, { id: 'b', type: 'backend', label: 'Server' }],+ messages: [{ from: 'a', to: 'b', y: 160, label: 'ping' }] };+ const waterfall = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/checkout-request.waterfall.json'), 'utf8'));+ for (const [mode, doc] of [['sequence', sequence], ['waterfall', waterfall]]) {+ const input = path.join(scratch, `${mode}-automatic.json`);+ const output = path.join(scratch, `${mode}-automatic.html`);+ fs.writeFileSync(input, JSON.stringify(doc));+ execFileSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'render', mode, input, output]);+ const html = fs.readFileSync(output, 'utf8');+ assert.match(html.match(/<svg\b[^>]*>/)[0], /data-reader-fit="width-first"/);+ await load(output);+ const declared = await snapshot(`${mode}-automatic`);+ assert.equal(declared.active, true);+ assert.equal(declared.readerFit, 'width-first');+ const undeclared = path.join(scratch, `${mode}-undeclared.html`);+ fs.writeFileSync(undeclared, html.replace(' data-reader-fit="width-first"', ''));+ await load(undeclared);+ const fallback = await snapshot(`${mode}-undeclared`);+ assert.deepEqual(fallback.geometry, declared.geometry);+ if (declared.receipt.ratio < 1.55) inactive(fallback, false);+ else assert.ok(fallback.receipt.width <= declared.receipt.width);+ for (const query of ['&embed=1', '&present=1']) {+ await load(output, { query });+ inactive(await snapshot(`${mode}-${query}`), declared.receipt.ratio >= 1.55);+ }+ }+ });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/render-output-checks.test.mjs b/test/render-output-checks.test.mjsindex 1463b232..17308df4 100644--- a/test/render-output-checks.test.mjs+++ b/test/render-output-checks.test.mjs@@ -84,6 +84,19 @@ test('render output check: predicts the certain 1440x900 overflow of a fixed-widconst declaredFit = checkHtml('viewport-height-fit', node, 'showcase', '0 0 1080 780', '', ' data-reader-fit="intrinsic-height"');assert.equal(declaredFit.result.composition.issues.some((item) => item.code === 'composition/viewport-height'), false, 'a Reader-declared fit can scroll readably');+ // Long automatic rows already have readable document scrolling; declaration+ // changes must not invent fixed-canvas warnings for the same geometry.+ for (const fit of ['intrinsic-height', 'width-first']) {+ const tallAutomatic = checkHtml(`viewport-tall-${fit}`, node, 'showcase', '0 0 920 2400', '', ` data-reader-fit="${fit}"`);+ assert.equal(tallAutomatic.result.composition.issues.some(item => item.code === 'composition/viewport-height'), false);+ }+ for (const attributes of ['', ' data-reader-fit="unknown"', ' data-sequence-column-fit="fixed"', ' data-waterfall-ui=""']) {+ const tallUndeclared = checkHtml('viewport-tall-undeclared', node, 'showcase', '0 0 920 2400', '', attributes);+ const warning = tallUndeclared.result.composition.issues.find(item => item.code === 'composition/viewport-height');+ assert.equal(warning?.severity, 'warning');+ assert.ok(warning?.pageHeightPx > 3000);+ }+for (const type of ['architecture', 'workflow', '']) {const fixed = checkHtml(`viewport-authored-${type}`, node, 'showcase', '0 0 1080 780', '',` data-reader-fit="authored-height" data-diagram-type="${type}"`);@@ -170,6 +183,19 @@ test('render output check: recognized declared-wide Reader admits the hard floorassert.ok(result.composition.desktopReadability.minimumProjectedTextPx < 7.5);});+test('render output check: width-first preserves the intrinsic declared-wide readability budget', () => {+ const body = '<g data-node-id="node"><text data-node-label x="160" y="126" class="t-primary" font-size="8">Node</text></g>';+ const head = '<meta name="archify-reader-contract" content="declared-wide-v1">';+ const intrinsic = checkHtml('intrinsic-budget', body, 'showcase', '0 0 1438 800', head, ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"');+ const widthFirst = checkHtml('width-first-budget', body, 'showcase', '0 0 1438 800', head, ' data-reader-fit="width-first" data-reader-min-text="7.5"');+ assert.equal(widthFirst.code, intrinsic.code);+ assert.deepEqual(widthFirst.result.composition.desktopReadability, intrinsic.result.composition.desktopReadability);+ for (const marker of ['data-sequence-column-fit="fixed"', 'data-waterfall-ui=""', 'data-reader-fit="unknown"']) {+ const undeclared = checkHtml('undeclared-budget', body, 'showcase', '0 0 1438 800', head, ` ${marker} data-reader-min-text="7.5"`);+ assert.equal(undeclared.result.composition.desktopReadability.budgetBasis, 'legacy-930');+ }+});+test('render output check: ordinary metadata preserves legacy readability and bare semantic markers', () => {const { code, result } = checkHtml('ordinary-meta-legacy-primary', `<g data-node-id="compact-node">diff --git a/test/repository-evidence-types-browser.test.mjs b/test/repository-evidence-types-browser.test.mjsindex 94e13085..bcb5523f 100644--- a/test/repository-evidence-types-browser.test.mjs+++ b/test/repository-evidence-types-browser.test.mjs@@ -10,7 +10,7 @@ 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('verified sources remain in Focus and Finder without node badges or label mutations', {+test('verified sources remain in Focus and Finder with accessible counts and no node badges', {skip: !chrome,timeout: 120000,}, async (t) => {@@ -74,8 +74,8 @@ test('verified sources remain in Focus and Finder without node badges or label mexpression: `(() => {const node = [...document.querySelectorAll('[data-node-id]')].find(n => n.dataset.nodeId === ${JSON.stringify(node.id)});const box = el => el && el.getBoundingClientRect();- const compatibilityResult = Archify.sourceEvidence.installBeacons();- const badgeCount = document.querySelectorAll('[data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label]').length;+ const legacyMethodPresent = Object.hasOwn(Archify.sourceEvidence, 'installBeacons');+ const badgeCount = document.querySelectorAll('[data-source-evidence-beacon]').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'));@@ -104,7 +104,7 @@ test('verified sources remain in Focus and Finder without node badges or label mconst finder = document.getElementById('node-finder-input');finder.value = 'source.js';finder.dispatchEvent(new Event('input', {bubbles:true}));- return { visible: !panel.hidden, badgeCount, ariaChanges, evidence, compatibilityResult, textCollisions, overflowingText,+ return { visible: !panel.hidden, badgeCount, ariaChanges, evidence, legacyMethodPresent, sourceAria: node.getAttribute('aria-label'), 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'),@@ -116,8 +116,9 @@ test('verified sources remain in Focus and Finder without node badges or label massert.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.deepEqual(result.ariaChanges, [node.id], `${type}: only source-backed nodes gain an accessibility hint`);+ assert.match(result.sourceAria, /1 verified source reference/, type);+ assert.equal(result.legacyMethodPresent, false, `${type}: obsolete beacon interface removed`);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);diff --git a/test/repository-evidence.test.mjs b/test/repository-evidence.test.mjsindex 86277d12..1e7511e0 100644--- a/test/repository-evidence.test.mjs+++ b/test/repository-evidence.test.mjs@@ -533,7 +533,9 @@ 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,- badges: document.querySelectorAll('[data-source-evidence-beacon], [data-source-evidence-count], [data-source-evidence-original-label]').length,+ badges: document.querySelectorAll('[data-source-evidence-beacon]').length,+ sourceCount: document.querySelector('[data-node-id="users"]').getAttribute('data-source-evidence-count'),+ sourceAria: document.querySelector('[data-node-id="users"]').getAttribute('aria-label'),invalidLinks: [...panel.querySelectorAll('a[href]')].some(a => /undefined|javascript:/.test(a.getAttribute('href'))),search: document.getElementById('node-finder-results').textContent};@@ -543,6 +545,8 @@ test('browser renders local-only sources as searchable text and web sources as lconst observed = response.result.value;assert.equal(observed.visible, true);assert.equal(observed.badges, 0);+ assert.equal(observed.sourceCount, '2');+ assert.match(observed.sourceAria, /2 verified source references/);assert.equal(observed.invalidLinks, false);assert.deepEqual(observed.paths, ['src/router.js', 'src/store.js']);assert.match(observed.scope, /local Git/);@@ -555,6 +559,146 @@ test('browser renders local-only sources as searchable text and web sources as l} finally { await browser.close(); }});+test('browser announces verified source counts without visual marks and restores canonical export labels', {+ skip: process.env.ARCHIFY_CHROME ? false : 'Set ARCHIFY_CHROME to run evidence browser checks.',+ timeout: 30000,+}, async (t) => {+ const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));+ data.diagram.meta.locale = 'zh-CN';+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));+ const artifactPath = path.join(data.root, 'source-aria.html');+ const delivered = run(['deliver', 'architecture', data.input, artifactPath, '--repo-root', data.root, '--json']);+ assert.equal(delivered.status, 0, delivered.stderr || delivered.stdout);+ const html = fs.readFileSync(artifactPath, 'utf8');+ const initialization = html.match(/Archify\.sourceEvidence = \(function \(\) \{[\s\S]*?\}\)\(\);/)?.[0];+ assert.ok(initialization);+ const browser = new ChromeVisualBrowser(findChrome());+ try {+ await browser.inspect({ artifactPath, width: 1440, height: 900, theme: 'light' });+ const sessionId = await browser.sessionPromise;+ async function accessibleNodeName() {+ const remote = await browser.cdp.send('Runtime.evaluate', {+ expression: `document.querySelector('[data-node-id="users"]')`,+ }, sessionId);+ const tree = await browser.cdp.send('Accessibility.getPartialAXTree', {+ objectId: remote.result.objectId, fetchRelatives: false,+ }, sessionId);+ const name = tree.nodes.find(node => !node.ignored)?.name?.value;+ assert.equal(typeof name, 'string', JSON.stringify(tree));+ return name;+ }+ assert.match(await accessibleNodeName(), /2 个已验证来源引用/);+ const response = await browser.cdp.send('Runtime.evaluate', {+ expression: `(async () => {+ const reinitialize = () => { ${initialization} };+ const svg = document.querySelector('.diagram-container > svg');+ const node = svg.querySelector('[data-node-id="users"]');+ const element = document.getElementById('archify-source-evidence-data');+ const payload = JSON.parse(element.textContent);+ const originalSources = payload.nodes.users.slice();+ const authoredLabel = node.getAttribute('data-source-evidence-original-label');+ const geometry = [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');+ const initial = node.getAttribute('aria-label');+ reinitialize();+ const repeated = node.getAttribute('aria-label');+ const noVisualMarks = !svg.querySelector('[data-source-evidence-beacon], .source-evidence-beacon');+ const geometryPreserved = geometry === [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');+ Archify.focus.set('users', { toggle: false });+ const passportLinks = document.querySelectorAll('#focus-evidence a[href]').length;+ const before = svg.outerHTML;+ const originalCreate = URL.createObjectURL;+ let exportedBlob;+ URL.createObjectURL = function(blob) {+ if (blob.type.startsWith('image/svg+xml')) exportedBlob = blob;+ return originalCreate.call(URL, blob);+ };+ let exportPreservesLive;+ try {+ const pending = Archify.exportMenu.run('svg');+ exportPreservesLive = before === svg.outerHTML;+ await pending;+ } finally { URL.createObjectURL = originalCreate; }+ const exported = new DOMParser().parseFromString(await exportedBlob.text(), 'image/svg+xml');+ const exportedLabel = exported.querySelector('[data-node-id="users"]').getAttribute('aria-label');+ const exportClean = !exported.querySelector('[data-source-evidence-count], [data-source-evidence-original-label], [data-reader-legend-corner], [data-source-evidence-beacon]');+ // The download anchor can clear Focus through its existing outside-click+ // behavior. Reopen via the public interface to verify sources survive.+ Archify.focus.set('users', { toggle: false });+ const passportLinksAfter = document.querySelectorAll('#focus-evidence a[href]').length;+ payload.nodes.users = [];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const zeroRestored = node.getAttribute('aria-label') === authoredLabel && !node.hasAttribute('data-source-evidence-count');+ const results = [];+ for (const label of [null, '', 'Authored focus label']) {+ node.removeAttribute('data-source-evidence-count');+ node.removeAttribute('data-source-evidence-original-label');+ if (label === null) node.removeAttribute('aria-label'); else node.setAttribute('aria-label', label);+ payload.nodes.users = [originalSources[0]];+ payload.verified = true;+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const once = node.getAttribute('aria-label');+ reinitialize();+ const twice = node.getAttribute('aria-label');+ let labelBlob;+ URL.createObjectURL = function(blob) {+ if (blob.type.startsWith('image/svg+xml')) labelBlob = blob;+ return originalCreate.call(URL, blob);+ };+ try { await Archify.exportMenu.run('svg'); }+ finally { URL.createObjectURL = originalCreate; }+ const exportedNode = new DOMParser().parseFromString(await labelBlob.text(), 'image/svg+xml').querySelector('[data-node-id="users"]');+ payload.nodes.users = [];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const zeroRestored = node.getAttribute('aria-label');+ payload.nodes.users = [originalSources[0]];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ payload.verified = false;+ element.textContent = JSON.stringify(payload);+ reinitialize();+ results.push({ once, twice, zeroRestored, exportedLabel: exportedNode.getAttribute('aria-label'), restored: node.getAttribute('aria-label'), count: node.getAttribute('data-source-evidence-count') });+ }+ return { initial, repeated, noVisualMarks, geometryPreserved, authoredLabel, exportedLabel,+ exportClean, exportPreservesLive, passportLinks, passportLinksAfter,+ zeroRestored, results };+ })()`, returnByValue: true, awaitPromise: true,+ }, sessionId);+ assert.equal(response.exceptionDetails, undefined);+ const observed = response.result.value;+ assert.match(observed.initial, /2 个已验证来源引用/);+ assert.equal(observed.repeated, observed.initial);+ for (const key of ['noVisualMarks', 'geometryPreserved', 'exportClean', 'exportPreservesLive', 'zeroRestored']) assert.equal(observed[key], true, key);+ assert.equal(observed.exportedLabel, observed.authoredLabel);+ assert.equal(observed.passportLinks, 3);+ assert.equal(observed.passportLinksAfter, 3);+ for (const [index, result] of observed.results.entries()) {+ assert.match(result.once, /1 个已验证来源引用/);+ assert.equal(result.twice, result.once);+ assert.equal(result.restored, [null, '', 'Authored focus label'][index]);+ assert.equal(result.zeroRestored, [null, '', 'Authored focus label'][index]);+ assert.equal(result.exportedLabel, [null, '', 'Authored focus label'][index]);+ assert.equal(result.count, null);+ }+ const restored = await browser.cdp.send('Runtime.evaluate', {+ expression: `(() => {+ const element = document.getElementById('archify-source-evidence-data');+ const payload = JSON.parse(element.textContent);+ payload.verified = true;+ element.textContent = JSON.stringify(payload);+ ${initialization}+ return document.querySelector('[data-node-id="users"]').getAttribute('aria-labelledby');+ })()`, returnByValue: true,+ }, sessionId);+ assert.equal(restored.exceptionDetails, undefined);+ assert.equal(restored.result.value, null, 'node has no competing aria-labelledby');+ assert.equal(await accessibleNodeName(), 'Authored focus label, 1 个已验证来源引用');+ } finally { await browser.close(); }+});+test('repository evidence accepts canonical HTTPS and common SSH remotes', () => {const data = fixture();const output = path.join(data.root, 'remote-form.html');diff --git a/test/sequence-column-fit.test.mjs b/test/sequence-column-fit.test.mjsindex bd7f9df1..617cc069 100644--- a/test/sequence-column-fit.test.mjs+++ b/test/sequence-column-fit.test.mjs@@ -166,3 +166,16 @@ test('standard retains acceptance for parallel schema-v1 labels with legacy spacassert.equal(Number(plate[2]), 16);assert.equal(Number(plate[3]), 9);});++// The Viewer fit declaration is independent of fixed/spread column geometry.+test('automatic sequence declares width-first fit; authored viewBox does not', () => {+ for (const columnFit of [undefined, 'fixed', 'spread']) {+ const doc = wideSequence(columnFit);+ delete doc.meta.viewBox;+ const root = render(doc).match(/<svg\b[^>]*>/)?.[0];+ assert.match(root, /data-reader-fit="width-first"/);+ assert.match(root, new RegExp(`data-sequence-column-fit="${columnFit || 'fixed'}"`));+ const authoredRoot = render(wideSequence(columnFit)).match(/<svg\b[^>]*>/)?.[0];+ assert.doesNotMatch(authoredRoot, /data-reader-fit=/);+ }+});diff --git a/test/tree-branches-browser.test.mjs b/test/tree-branches-browser.test.mjsindex 770cec8d..2e0c7526 100644--- a/test/tree-branches-browser.test.mjs+++ b/test/tree-branches-browser.test.mjs@@ -76,8 +76,9 @@ test('Tree branches collapse in place, follow the keyboard, reveal selections, aawait load(small);assert.equal(await run('Archify.treeBranches.active'), true);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.equal(await run(`document.querySelectorAll('[data-source-evidence-beacon]').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']]);+ assert.deepEqual(await run(`['platform', 'payments', 'card_payment'].map(id => document.querySelector('[data-node-id="' + id + '"]').getAttribute('data-source-evidence-count'))`), ['1', '1', '1']);}await checkSources();const before = await run(box('operations'));diff --git a/test/viewer-camera-browser.test.mjs b/test/viewer-camera-browser.test.mjsindex 2da0d748..9d9b1eee 100644--- a/test/viewer-camera-browser.test.mjs+++ b/test/viewer-camera-browser.test.mjs@@ -167,7 +167,7 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {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,+ pannable: c.classList.contains('is-pannable'), clip: s.style.clipPath, flowHeight: c.style.height,viewport: Archify.view.logicalViewport(), viewBox: s.getAttribute('viewBox') };})()`;let value = await run(inspect);@@ -176,6 +176,7 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {assert.equal(value.out, false);assert.equal(value.pannable, false);assert.equal(value.clip, '');+ assert.equal(value.flowHeight, '', 'short diagrams retain their original flow box');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);@@ -221,31 +222,83 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {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 });+ const initial = await run(`(() => {+ const s = document.querySelector('.diagram-container > svg');+ return { height: s.clientHeight, pageHeight: document.documentElement.scrollHeight,+ viewBox: s.getAttribute('viewBox'), markup: s.innerHTML };+ })()`);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();+ const c = s.parentNode, box = c.getBoundingClientRect(), svgBox = s.getBoundingClientRect(), style = getComputedStyle(c);return { height: s.clientHeight, state: Archify.view.state(), first: first.y, last: last.y,- scrollHeight: document.documentElement.scrollHeight, windowHeight: innerHeight };+ scrollHeight: document.documentElement.scrollHeight, windowHeight: innerHeight,+ blankTail: box.bottom - svgBox.bottom, bottomChrome: parseFloat(style.paddingBottom) + parseFloat(style.borderBottomWidth),+ viewBox: s.getAttribute('viewBox'), markup: s.innerHTML };})()`);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');+ assert.equal(value.height, initial.height, 'zoom never feeds a reduced layout size back into the SVG');+ assert.equal(value.viewBox, initial.viewBox);+ assert.equal(value.markup, initial.markup, 'authored rows and geometry are unchanged');+ assert.ok(value.blankTail <= value.bottomChrome + 2, JSON.stringify(value));+ assert.ok(Math.abs(initial.pageHeight - value.scrollHeight - initial.height * 0.75) <= 3, 'page flow shrinks with the rendered rows');+ records.push({ label: 'long-sequence-flow', initialHeight: initial.height, initialPageHeight: initial.pageHeight,+ ...value, markup: undefined });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');+ // Reader/Chrome may alter stage width or reserve without window resize.+ await run(`(() => { const c = document.querySelector('.diagram-container'); c.style.width = '75%'; })()`);+ await stable();+ const reflow = await run(`(() => {+ const s = document.querySelector('.diagram-container > svg'), c = s.parentNode, style = getComputedStyle(c);+ return { base: s.clientHeight, paint: s.getBoundingClientRect().height,+ gap: c.getBoundingClientRect().bottom - s.getBoundingClientRect().bottom,+ bottom: parseFloat(style.paddingBottom) + parseFloat(style.borderBottomWidth) };+ })()`);+ assert.ok(reflow.base < initial.height);+ assert.ok(Math.abs(reflow.paint - reflow.base * 0.25) < 1);+ assert.ok(reflow.gap <= reflow.bottom + 2, 'stage reflow refreshes flow height without a window resize');+ await run(`document.querySelector('.diagram-container').style.removeProperty('width')`);+ await stable();+ await viewport(1440, 900);+ await stable();+ assert.equal(await run('Archify.view.state().scale'), 0.25);+ const resized = await run(`(() => { const s = document.querySelector('.diagram-container > svg');+ return { base: s.clientHeight, paint: s.getBoundingClientRect().height }; })()`);+ assert.ok(Math.abs(resized.paint - resized.base * 0.25) < 1, 'resize must not shrink the base twice');+ await viewport(1280, 800);+ await stable();+ for (const mode of ['embed', 'present', 'print']) {+ if (mode === 'print') await send('Emulation.setEmulatedMedia', { media: 'print' });+ else await run(`document.documentElement.setAttribute('data-${mode}', 'true')`);+ await stable();+ assert.equal(await run(`document.querySelector('.diagram-container').style.height`), '', mode + ' restores ordinary mode-owned height');+ if (mode === 'print') await send('Emulation.setEmulatedMedia', { media: '' });+ else await run(`document.documentElement.removeAttribute('data-${mode}')`);+ await stable();+ assert.notEqual(await run(`document.querySelector('.diagram-container').style.height`), '', 'ordinary long overview restores compact flow');+ }+ await run('Archify.view.reset()');+ await stable();+ assert.equal(await run(`document.querySelector('.diagram-container').style.height`), '');+ assert.equal(await run(`document.querySelector('.diagram-container > svg').clientHeight`), initial.height);+ assert.equal(await run(`document.documentElement.scrollHeight`), initial.pageHeight);});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 });+ await load('longSequence', { width: 1280, height: 800, reduced: position !== 'page-bottom' });const scrollTarget = position === 'page-bottom' ? 'document.documentElement.scrollHeight': `document.querySelector('.diagram-container > svg').clientHeight * ${position}`;await run(`window.scrollTo(0, ${scrollTarget})`);@@ -511,11 +564,12 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {});await t.test('export removes camera transforms without mutating the live camera', async () => {- for (const [mode, setup] of [- ['semantic', `Archify.view.reveal(['api'], { instant: true })`],- ['75-percent', `Archify.view.zoomOut()`],+ for (const [mode, diagram, setup] of [+ ['semantic', 'architecture', `Archify.view.reveal(['api'], { instant: true })`],+ ['75-percent', 'architecture', `Archify.view.zoomOut()`],+ ['long-25-percent', 'longSequence', `Archify.view.zoomOut(); Archify.view.zoomOut(); Archify.view.zoomOut()`],]) {- await load();+ await load(diagram, { reduced: true });await run(setup);await stable();const live = await run(`(() => ({ scale: Archify.view.state().scale,@@ -524,7 +578,7 @@ test('Camera preserves transactions, rendered state and real caller handoffs', {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.scale, mode === 'long-25-percent' ? 0.25 : 0.75);assert.equal(live.clip, '');}const exported = await run(`(async () => {diff --git a/test/visual-check.test.mjs b/test/visual-check.test.mjsindex b4493be9..1292d8a1 100644--- a/test/visual-check.test.mjs+++ b/test/visual-check.test.mjs@@ -80,6 +80,7 @@ function fakeBrowser({overflowAt,tallAt,readableScrollAt,+ automaticReaderFit = 'intrinsic-height',authoredScrollAt,authoredDiagramType = 'architecture',authoredUnclipped = true,@@ -125,7 +126,7 @@ function fakeBrowser({} : {}),readerLayout: readableScroll ? 'adaptive' : null,readerOverflow: readableScroll ? 'authored' : null,- readerFit: readableScroll ? 'intrinsic-height' : authoredScroll ? 'authored-height' : null,+ readerFit: readableScroll ? automaticReaderFit : authoredScroll ? 'authored-height' : null,diagramType: authoredScroll ? authoredDiagramType : null,documentScrollUnclipped: authoredScroll && authoredUnclipped,readerWidth: 960,@@ -2677,24 +2678,32 @@ test('visual-check reports the page composition when a viewport overflows vertictest('visual-check accepts only Reader-declared readable vertical page scrolling', async () => {const input = artifact('readable-scroll.html');const target = ({ width, theme }) => width === 1440 && theme === 'light';- const result = await runVisualCheck({- artifactPath: input,- chromePath: '/fake/chrome',- browserFactory: async () => fakeBrowser({ readableScrollAt: target }),- });+ for (const automaticReaderFit of ['intrinsic-height', 'width-first']) {+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => fakeBrowser({ readableScrollAt: target, automaticReaderFit }),+ });- assert.equal(result.exitCode, 0);- assert.equal(result.receipt.status, 'pass');- assert.equal(result.receipt.containment.status, 'pass');- assert.equal(result.receipt.containment.policy, 'fit-or-reader-declared-readable-vertical-scroll');- const viewport = result.receipt.containment.viewports.find(({ width }) => width === 1440);- assert.equal(viewport.overflowY, true);- assert.equal(viewport.verticalScrollAccepted, true);- assert.equal(viewport.overflowDisposition, 'readable-vertical-scroll');- assert.equal(viewport.readerLayout, 'adaptive');- assert.equal(viewport.readerOverflow, 'authored');- assert.equal(viewport.readerFit, 'intrinsic-height');- assert.equal(result.receipt.diagnostics.some(({ code }) => code === 'viewer/viewport-overflow'), false);+ assert.equal(result.exitCode, 0);+ assert.equal(result.receipt.status, 'pass');+ assert.equal(result.receipt.containment.status, 'pass');+ assert.equal(result.receipt.containment.policy, 'fit-or-reader-declared-readable-vertical-scroll');+ const viewport = result.receipt.containment.viewports.find(({ width }) => width === 1440);+ assert.equal(viewport.overflowY, true);+ assert.equal(viewport.verticalScrollAccepted, true);+ assert.equal(viewport.overflowDisposition, 'readable-vertical-scroll');+ assert.equal(viewport.readerLayout, 'adaptive');+ assert.equal(viewport.readerOverflow, 'authored');+ assert.equal(viewport.readerFit, automaticReaderFit);+ assert.equal(result.receipt.diagnostics.some(({ code }) => code === 'viewer/viewport-overflow'), false);+ }+ for (const automaticReaderFit of [null, 'unknown']) {+ const result = await runVisualCheck({ artifactPath: input, chromePath: '/fake/chrome',+ browserFactory: async () => fakeBrowser({ readableScrollAt: target, automaticReaderFit }) });+ assert.equal(result.exitCode, 1);+ assert.equal(result.receipt.containment.viewports.find(({ width }) => width === 1440).verticalScrollAccepted, false);+ }});test('visual-check still rejects horizontal overflow and unreadable text in Reader scroll state', async () => {diff --git a/test/waterfall-rendering.test.mjs b/test/waterfall-rendering.test.mjsindex e70fe438..efe988e0 100644--- a/test/waterfall-rendering.test.mjs+++ b/test/waterfall-rendering.test.mjs@@ -31,6 +31,9 @@ test('waterfall: both examples render and pass the showcase artifact checks', ()for (const diagram of [small, large]) {const result = run(diagram);assert.equal(result.status, 0, result.stderr);+ const root = fs.readFileSync(result.output, 'utf8').match(/<svg\b[^>]*>/)?.[0];+ assert.match(root, /data-reader-fit="width-first"/);+ assert.match(root, /data-reader-min-text="7\.5"/);const receipt = JSON.parse(spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' }).stdout);assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));assert.equal(receipt.composition.summary.errors, 0);diff --git a/viewer/README.md b/viewer/README.mdindex e997c95d..0f3bee5b 100644--- a/viewer/README.md+++ b/viewer/README.md@@ -177,6 +177,12 @@ provider is part of Focus ownership, not a second initialization step.- Passport uses existing label/kind/detail/context/tag/brand/source metadata. TheSource Evidence provider owns repository/node lookup; Finder searches source paths.Focus owns displaying or hiding evidence and building the existing safe links.+ Source Evidence appends the localized verified source count to node ARIA+ labels at initialization, preserving the original label for canonical export.+ Only revision-verified payload sources contribute; zero counts add no hint.+ Repeated initialization restores the original label first, so hints never+ accumulate and disappeared evidence removes the old hint. This adds no SVG+ badge, shape, or geometry and exposes no beacon installation interface.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@@ -576,10 +582,16 @@ The source split narrows maintenance scope while preserving runtime dependenciesUncapped and ineligible measures clear these valuesand 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;+- Renderers declare fitting independently of their UI or column metadata:+ `data-reader-fit="width-first"` selects available desktop reading width;+ `data-reader-fit="intrinsic-height"` selects height fitting. Both declare+ automatic canvases and share the existing readability and enlargement limits.+ Automatic Sequence and Waterfall canvases declare `width-first` and retain+ 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+ Undeclared SVGs retain the ordinary ratio-based eligibility and fit; UI or+ column attributes alone do not opt into either automatic fit. Other diagram+ families retain height fitting. All automatic canvases capenlargement at 1.5 times the authored SVG width without reducing the outerreading area. Capped SVGs are centered inside that area; uncapped diagramsretain their existing natural flow. In a capped reader area, the original@@ -679,6 +691,14 @@ their contained horizontal scroll. Reset restores 100% overview. Semantic revealand Radar centering retain their existing minimum of 100%. Canonical exportsretain the original geometry regardless of the manual zoom.+For long ordinary diagrams below 100%, Camera also reduces the container's+page-flow height to the painted SVG height plus its existing padding/borders.+The SVG retains its intrinsic client size, so zoom and layout cannot repeatedly+shrink the camera base. Size observation follows Reader width and Chrome reserve+changes without requiring a window resize. Reset, short diagrams, Embed, Present+and print restore the original inline container height and priority. This outer+layout state is absent from canonical SVG exports.+`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 wide@@ -861,7 +881,7 @@ Viewer capability or changes the live DOM. No new `Archify` interface is exposed| Focus, relationship preview, reachability, Intent Trace | Remove selection/preview markers and runtime overlays; reset node `aria-pressed` using the existing rule. || Route Probe | Remove picking, result and journey markers/overlays and route step styles. || Semantic Lens and legend preview | Remove filtering/preview decorations and runtime legend accessibility attributes. |-| Source Evidence | Remove beacons/counts; restore recorded original labels. Missing or empty original labels remove `aria-label`, as before. |+| Source Evidence | Remove beacons/counts; restore recorded original labels. Missing original labels remove `aria-label`; an authored empty label remains an empty attribute. || Previous Route/Reach share decoration | Remove before applying the current export's explicit snapshot. |Original content, node/edge identity, geometry and authored animation metadatadiff --git a/viewer/export-cleanup.js b/viewer/export-cleanup.jsindex f0272d17..79d06f2b 100644--- a/viewer/export-cleanup.js+++ b/viewer/export-cleanup.js@@ -68,7 +68,7 @@});Array.prototype.forEach.call(clone.querySelectorAll('[data-source-evidence-count]'), function (el) {var originalLabel = el.getAttribute('data-source-evidence-original-label');- if (originalLabel == null || originalLabel === '') el.removeAttribute('aria-label');+ if (originalLabel == null) el.removeAttribute('aria-label');else el.setAttribute('aria-label', originalLabel);el.removeAttribute('data-source-evidence-count');el.removeAttribute('data-source-evidence-original-label');diff --git a/viewer/reader-layout.js b/viewer/reader-layout.jsindex 76fba0c0..f0eaa922 100644--- a/viewer/reader-layout.js+++ b/viewer/reader-layout.js@@ -9,9 +9,9 @@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 readerFit = svg && svg.getAttribute('data-reader-fit');+ var widthFirstReading = readerFit === 'width-first';+ var measuredHeightFit = readerFit === 'intrinsic-height' || widthFirstReading;var frame = 0;var settleFrame = 0;var lastWidth = 0;@@ -171,6 +171,10 @@var rect = diagram.getBoundingClientRect();var style = window.getComputedStyle(diagram);var scale = Math.min(svg.clientWidth / viewBox.width, svg.clientHeight / viewBox.height);+ if (!Number.isFinite(scale) || scale <= 0) {+ clearLegend();+ return;+ }var left = rect.left + number(style.borderLeftWidth) + number(style.paddingLeft);var right = rect.right - number(style.borderRightWidth) - number(style.paddingRight);var bottom = rect.bottom - number(style.borderBottomWidth) - number(style.paddingBottom);diff --git a/viewer/template.source.html b/viewer/template.source.htmlindex 2e01bc91..a7d984e8 100644--- a/viewer/template.source.html+++ b/viewer/template.source.html@@ -916,11 +916,29 @@ OTHER DEALINGS IN THE FONT SOFTWARE.if (parsed && parsed.verified === true && parsed.repository && parsed.nodes) payload = parsed;} catch (_) {}}+ // Keep verified evidence discoverable to screen readers without adding+ // visual marks. Restore first so repeated initialization never appends+ // another count or retains one after evidence becomes unavailable.+ var svg = document.querySelector('.diagram-container svg');+ if (svg) Array.prototype.forEach.call(svg.querySelectorAll('[data-node-id]'), function (node) {+ if (node.hasAttribute('data-source-evidence-count')) {+ var savedLabel = node.getAttribute('data-source-evidence-original-label');+ if (savedLabel == null) node.removeAttribute('aria-label');+ else node.setAttribute('aria-label', savedLabel);+ node.removeAttribute('data-source-evidence-count');+ node.removeAttribute('data-source-evidence-original-label');+ }+ var sources = payload && payload.nodes[node.getAttribute('data-node-id')];+ if (!Array.isArray(sources) || !sources.length) return;+ var originalLabel = node.getAttribute('aria-label');+ node.setAttribute('data-source-evidence-count', String(sources.length));+ if (originalLabel != null) node.setAttribute('data-source-evidence-original-label', originalLabel);+ node.setAttribute('aria-label', (originalLabel ? originalLabel + ', ' : '') ++ viewerCount('viewer.passport.sourceCount', sources.length));+ });return {available: function () { return Boolean(payload); },repository: function () { return payload ? payload.repository : null; },- // 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() : [];diff --git a/viewer/viewer-camera.js b/viewer/viewer-camera.jsindex ac26c80f..95acead3 100644--- a/viewer/viewer-camera.js+++ b/viewer/viewer-camera.js@@ -17,6 +17,9 @@var clipFrame = 0;var resizeFrame = 0;var autoScrollUntil = 0;+ var originalFlowHeight = container.style.getPropertyValue('height');+ var originalFlowHeightPriority = container.style.getPropertyPriority('height');+ var compactPageFlow = false;var viewBox = svg.viewBox && svg.viewBox.baseVal;@@ -132,12 +135,36 @@Math.abs(rendered.x - state.x) < 0.05 &&Math.abs(rendered.y - state.y) < 0.05;}+ // CSS transforms keep the SVG's intrinsic layout size. Shrink only its+ // outer page-flow box for long ordinary diagrams, never the SVG itself:+ // changing its height would feed the smaller size back into camera math.+ function syncPageFlow(camera) {+ camera = camera || state;+ var html = document.documentElement;+ var height = svg.clientHeight;+ var ordinary = html.getAttribute('data-embed') !== 'true' &&+ html.getAttribute('data-present') !== 'true' &&+ (!window.matchMedia || !window.matchMedia('print').matches);+ if (ordinary && camera.scale < 1 && height > window.innerHeight) {+ var style = getComputedStyle(container);+ var chrome = ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']+ .reduce(function (total, key) { return total + (parseFloat(style[key]) || 0); }, 0);+ var flowHeight = Math.ceil(height * camera.scale + Math.max(0, camera.y) + chrome) + 'px';+ if (container.style.getPropertyValue('height') !== flowHeight) container.style.setProperty('height', flowHeight);+ compactPageFlow = true;+ } else if (compactPageFlow) {+ if (originalFlowHeight) container.style.setProperty('height', originalFlowHeight, originalFlowHeightPriority);+ else container.style.removeProperty('height');+ compactPageFlow = false;+ }+ }function syncViewportClip() {if (clipFrame) cancelAnimationFrame(clipFrame);clipFrame = 0;function sample() {clipFrame = 0;var rendered = sampleRenderedState();+ syncPageFlow(rendered);clipToViewport(rendered);if (Archify.readerLayout && typeof Archify.readerLayout.syncLegend === 'function') Archify.readerLayout.syncLegend();if (!cameraSettled(rendered)) clipFrame = requestAnimationFrame(sample);@@ -524,6 +551,20 @@else apply();});});+ // Reader width and Chrome reserve can change without a window resize.+ // Observe their resulting sizes; the SVG remains intrinsically sized, so+ // the outer flow height cannot feed back into its camera base.+ if (typeof ResizeObserver === 'function') {+ var flowObserver = new ResizeObserver(function () { syncPageFlow(sampleRenderedState()); });+ flowObserver.observe(svg);+ flowObserver.observe(container);+ }+ if (typeof MutationObserver === 'function') {+ new MutationObserver(function () { syncPageFlow(sampleRenderedState()); })+ .observe(document.documentElement, { attributes: true, attributeFilter: ['data-embed', 'data-present'] });+ }+ var printMedia = window.matchMedia && window.matchMedia('print');+ if (printMedia && printMedia.addEventListener) printMedia.addEventListener('change', function () { syncPageFlow(sampleRenderedState()); });window.addEventListener('hashchange', function () { requestAnimationFrame(syncSemantic); });apply();pinControls();