Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

Cut explainer page weight by two thirds and add sequence phases

tt-a1i9029c734a548
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 337b6bf5..553849af 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -6163,7 +6163,7 @@ async function commandDoctor(args) {
});
}
- const explainerRuntime = ['parse.mjs', 'validate.mjs', 'inline.mjs', 'sources.mjs', 'writing.mjs', 'diagrams.mjs', 'prepare.mjs', 'patch.mjs', 'diff.mjs', 'revision.mjs', 'layout.mjs', 'render.mjs', 'check.mjs', 'browser-check.mjs', 'charts.mjs', 'vendor/pele/core.js', 'reader.css', 'reader.js'];
+ const explainerRuntime = ['parse.mjs', 'validate.mjs', 'inline.mjs', 'sources.mjs', 'writing.mjs', 'diagrams.mjs', 'prepare.mjs', 'patch.mjs', 'diff.mjs', 'revision.mjs', 'layout.mjs', 'render.mjs', 'check.mjs', 'browser-check.mjs', 'charts.mjs', 'page-bundle.mjs', 'vendor/pele/core.js', 'reader.css', 'reader.js'];
const missingExplainerRuntime = explainerRuntime.filter(file => !fs.existsSync(path.join(skillRoot, 'explainer', file))).length;
checks.push({label:'Explainer runtime and reader assets',ok:missingExplainerRuntime===0,missing:missingExplainerRuntime});
diff --git a/archify/explainer/check.mjs b/archify/explainer/check.mjs
index fbcec760..e4e45cd2 100644
--- a/archify/explainer/check.mjs
+++ b/archify/explainer/check.mjs
@@ -6,6 +6,7 @@ import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { parseExplainer } from './parse.mjs';
import { computeExplainerRevision } from './revision.mjs';
+import { unpackPageBundle } from './page-bundle.mjs';
export const isExplainerHtml = html => /<html\b[^>]*\bdata-archify-artifact\s*=\s*["']explainer["']/i.test(html) || (html.includes('archify-explainer-prepared') && scanHtml(html).scripts.some(s=>s.attrs.id==='archify-explainer-prepared'));
const hash = value => createHash('sha256').update(value).digest('hex');
@@ -90,7 +91,8 @@ export function checkExplainerHtml(html, { file = '<html>', checkNative = true }
try { return JSON.parse(found[0].text); } catch { issue('payload-json',`Invalid JSON payload: ${id}.`,'Re-render the validated source instead of editing embedded payloads.',found[0]); return null; }
}
before=diagnostics.length;
- const bundle=payload('archify-explainer-prepared');
+ let bundle=payload('archify-explainer-prepared');
+ try { bundle=unpackPageBundle(bundle); } catch { issue('native-hash','A compressed native diagram payload cannot be inflated.','Re-render the native diagram and freeze its original HTML bytes.'); bundle=null; }
const document=bundle?.document;
const source=bundle ? {text:bundle.sourceText} : null;
const manifest=payload('explainer-manifest');
diff --git a/archify/explainer/diagrams.mjs b/archify/explainer/diagrams.mjs
index 54c9cb20..a9658684 100644
--- a/archify/explainer/diagrams.mjs
+++ b/archify/explainer/diagrams.mjs
@@ -140,13 +140,21 @@ export function compileExplainerDiagram(diagramType, rows, { title, id, line = 1
spec.participants.push(actor); byId.set(actor.id, actor); aliases.set(label, actor.id);
return actor.id;
};
+ // "phase | label" rows open a labelled band over the messages that follow, up to the next phase.
+ const phases = [];
for (const entry of entries.filter(entry => !entry.parts[0].startsWith('actor '))) {
+ if (entry.parts[0] === 'phase') { expect(entry, 2, 2, 'phase | TCP handshake'); phases.push({ label: entry.parts[1], first: spec.messages.length, context: entry.context }); continue; }
expect(entry, 3, 4, 'Client | API | 请求记录 | return');
const [fromLabel, toLabel, label, variant] = entry.parts;
const from = actorId(fromLabel, entry.context), to = actorId(toLabel, entry.context);
context.rowMap[`/messages/${spec.messages.length}`] = entry.context.line;
spec.messages.push({ id: edgeId(from, to), from, to, label, y: 160 + spec.messages.length * 48, ...(variant ? { variant } : {}) });
}
+ phases.forEach((phase, index) => {
+ const last = (phases[index + 1]?.first ?? spec.messages.length) - 1;
+ if (last < phase.first) fail(phase.context, 'diagram-row', 'A phase needs at least one message after it.', 'phase | TCP handshake\n| browser | server | SYN |');
+ (spec.segments ||= []).push({ from: spec.messages[phase.first].y - 22, to: spec.messages[last].y + 16, label: phase.label });
+ });
duplicateCheck(spec.participants, context, 'actor');
if (!spec.messages.length) fail(context, 'diagram-rows', 'Sequence shorthand needs a message.', 'client | api | 请求记录');
} else if (diagramType === 'architecture' || diagramType === 'workflow') {
@@ -436,8 +444,8 @@ export async function prepareExplainerDiagrams(document, { repoRoot, baseDir, qu
if (!svgMatch) fail(context, 'diagram-svg', 'The native renderer produced no primary semantic SVG.', 'Use a supported native diagram renderer.');
const canonicalSvg = svgMatch[0], semantic = semanticOf(canonicalSvg);
const svg = changesPreview(canonicalSvg, block.changes, semantic, context);
- const styles = [...html.matchAll(/<style\b[^>]*>[\s\S]*?<\/style>/g)].map(match => match[0]).join('\n');
- diagrams[block.id] = { diagramType: block.diagramType, spec: original, html, svg, canonicalSvg, styles, sha256: hash(bytes), bytes: bytes.length,
+ // Preview styles are derived from html at render time; storing them again would double the page.
+ diagrams[block.id] = { diagramType: block.diagramType, spec: original, html, svg, sha256: hash(bytes), bytes: bytes.length,
specification: freezeBytes(originalBytes), checks: { validate: { ok: true }, render: { ok: true }, check }, semantic,
...(block.changes ? { changes: block.changes.map(change => ({ ...change })) } : {}) };
} finally { await temporary.cleanup(); }
diff --git a/archify/explainer/page-bundle.mjs b/archify/explainer/page-bundle.mjs
new file mode 100644
index 00000000..32bb7c7b
--- /dev/null
+++ b/archify/explainer/page-bundle.mjs
@@ -0,0 +1,16 @@
+import { gzipSync, gunzipSync } from 'node:zlib';
+
+// The native Viewer HTML is needed only when a reader opens "Explore", so the page stores it
+// gzip-compressed and the reader inflates it on demand. Keys keep their order, so the prepared
+// bundle digest is computed and verified over the same unpacked JSON.
+const swap = (bundle, from, to, convert) => {
+ const diagrams = bundle?.preparedDiagrams?.diagrams;
+ if (!diagrams || typeof diagrams !== 'object') return bundle;
+ return { ...bundle, preparedDiagrams: { ...bundle.preparedDiagrams, diagrams: Object.fromEntries(Object.entries(diagrams).map(([id, child]) =>
+ [id, child && typeof child[from] === 'string' ? Object.fromEntries(Object.entries(child).map(([key, value]) => key === from ? [to, convert(value)] : [key, value])) : child])) } };
+};
+
+export const packPageBundle = bundle => swap(bundle, 'html', 'htmlGzip', html => gzipSync(html, { level: 9 }).toString('base64'));
+
+/** Accepts packed and older unpacked pages alike. */
+export const unpackPageBundle = bundle => swap(bundle, 'htmlGzip', 'html', data => gunzipSync(Buffer.from(data, 'base64')).toString('utf8'));
diff --git a/archify/explainer/patch.mjs b/archify/explainer/patch.mjs
index 019149f4..dbfd9952 100644
--- a/archify/explainer/patch.mjs
+++ b/archify/explainer/patch.mjs
@@ -5,6 +5,7 @@ import { parseValidatedExplainer, rebindPreparedBundle, validatePreparedTargets
import { resolveExplainerSources } from './sources.mjs';
import { prepareExplainerDiagrams } from './diagrams.mjs';
import { computeExplainerRevision } from './revision.mjs';
+import { unpackPageBundle } from './page-bundle.mjs';
import { throwDiagnosticError } from '../renderers/shared/diagnostics.mjs';
function fail(reason, message, input, panelId, example) {
@@ -21,7 +22,8 @@ export async function preparePanelPatch({artifactPath,panelId,replacementPath,re
const artifactBytes=fs.readFileSync(artifactPath);
if(expectedArtifact && (artifactBytes.length!==expectedArtifact.bytes || createHash('sha256').update(artifactBytes).digest('hex')!==expectedArtifact.sha256)) fail('artifact-changed','The original artifact changed after validation.',artifactPath,panelId,'Finish other writes to the artifact and retry the panel patch.');
const html = artifactBytes.toString('utf8');
- const previous = embedded(html,'archify-explainer-prepared',artifactPath);
+ let previous;
+ try { previous = unpackPageBundle(embedded(html,'archify-explainer-prepared',artifactPath)); } catch (error) { if (error.diagnostics) throw error; fail('payload','Embedded native diagram payload cannot be inflated.',artifactPath,panelId,'Rebuild the original artifact before patching.'); }
const draft = previous;
if(typeof draft.sourceText !== 'string' || draft.sourceText !== previous.sourceText
|| createHash('sha256').update(draft.sourceText).digest('hex') !== previous.source?.sha256
diff --git a/archify/explainer/reader.js b/archify/explainer/reader.js
index 0d52c63e..cf56b800 100644
--- a/archify/explainer/reader.js
+++ b/archify/explainer/reader.js
@@ -255,11 +255,20 @@
const ready=()=>requestAnimationFrame(()=>requestAnimationFrame(()=>parent.postMessage({kind:'archify-explainer-ready',token},'*')));
if(document.readyState==='complete')ready();else addEventListener('load',ready,{once:true});
})();<\/script>`;
- const end = diagram.html.toLowerCase().lastIndexOf('</body>');
- frame.srcdoc = end < 0 ? diagram.html + script : diagram.html.slice(0,end) + script + diagram.html.slice(end);
viewer = {id,frame,token,hash,nodes:requestedNodes,edges:requestedEdges,ready:false};
viewerDialog.querySelector('.dialog-loading').hidden = false;
viewerDialog.append(frame);
+ nativeHtml(diagram).then(html=>{
+ if (viewer?.frame !== frame) return;
+ const end = html.toLowerCase().lastIndexOf('</body>');
+ frame.srcdoc = end < 0 ? html + script : html.slice(0,end) + script + html.slice(end);
+ },()=>notify(say('This diagram could not be opened.','无法打开此交互图。')));
+ }
+ // The page stores each native Viewer gzip-compressed; inflate it once, on first open.
+ function nativeHtml(diagram) {
+ if (typeof diagram.html === 'string') return Promise.resolve(diagram.html);
+ const bytes = Uint8Array.from(atob(diagram.htmlGzip),character=>character.charCodeAt(0));
+ return diagram.inflating ||= new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).text();
}
function closeViewer() { if(viewerDialog.open) viewerDialog.close(); }
document.querySelector('[data-close-diagram]').addEventListener('click',closeViewer);
diff --git a/archify/explainer/render.mjs b/archify/explainer/render.mjs
index 7a7acb04..6acbcf32 100644
--- a/archify/explainer/render.mjs
+++ b/archify/explainer/render.mjs
@@ -5,6 +5,7 @@ import { parseExplainerDiff } from './diff.mjs';
import { computeExplainerRevision } from './revision.mjs';
import { layoutExplainerPanels } from './layout.mjs';
import { compileExplainerChart } from './charts.mjs';
+import { packPageBundle } from './page-bundle.mjs';
const css = fs.readFileSync(new URL('./reader.css', import.meta.url), 'utf8');
const js = fs.readFileSync(new URL('./reader.js', import.meta.url), 'utf8');
@@ -55,7 +56,7 @@ export function renderExplainer(document, options = {}) {
break;
}
case 'steps': body = `<ol class="steps">${block.items.map(item => `<li id="${escape(item.id)}"><b>${item.target ? nativeLink(item.target,i(item.text)) : i(item.text)}</b>${item.detail ? `<p>${i(item.detail)}</p>` : ''}</li>`).join('')}</ol>`; break;
- case 'diagram': { const diagram = diagrams[block.id]; if (!diagram?.svg || !diagram?.html) unavailable(block,`Missing prepared native diagram: ${block.id}`); const title = diagram.spec?.meta?.title || block.id; const svg = staticSvg(diagram.svg, block.id); const previewClass = previewPrefix(block.id); const nativeStyle = scopeNativeCss(diagram.styles || '', '.' + previewClass, previewClass + '-'); const nativeWidth = Number(diagram.svg.match(/viewBox=["'][^"']*?[\d.-]+[ ,]+[\d.-]+[ ,]+([\d.]+)/)?.[1]); const singleLane = diagram.spec?.lanes?.length === 1 ? ' single-lane' : ''; body = `<figure class="diagram"><div class="diagram-preview ${previewClass}${singleLane}" role="img" aria-label="${escape(title)}"${nativeWidth > 0 ? ` style="--native-width:${Math.round(nativeWidth)}px"` : ''}><style>${nativeStyle}</style>${svg}</div><figcaption><span>${escape(title)}</span><button class="text-button interactive" type="button" data-open-diagram="${escape(block.id)}">${words.explore} ↗</button></figcaption></figure><p class="diagram-fit-status fine" role="status" hidden></p><details class="diagram-semantics" open><summary>${words.graph}</summary><ul>${(diagram.semantic?.nodes || []).map(node => `<li>${escape(node.label || node.id)} <code>${escape(node.id)}</code></li>`).join('')}${(diagram.semantic?.edges || []).map(edge => `<li><code>${escape(edge.from)}</code> → <code>${escape(edge.to)}</code>${edge.label ? ` · ${escape(edge.label)}` : ''}</li>`).join('')}</ul></details>${block.changes?.length ? `<dl class="changes"><dt>${words.changes}</dt>${block.changes.map(change => `<dd><span class="chip ${escape(change.change)}">${words[change.change]}</span> <code>${escape(change.target)}</code></dd>`).join('')}</dl>` : ''}`; break; }
+ case 'diagram': { const diagram = diagrams[block.id]; if (!diagram?.svg || !diagram?.html) unavailable(block,`Missing prepared native diagram: ${block.id}`); const title = diagram.spec?.meta?.title || block.id; const svg = staticSvg(diagram.svg, block.id); const previewClass = previewPrefix(block.id); const nativeStyle = scopeNativeCss(diagram.styles ?? nativeStyles(diagram.html), '.' + previewClass, previewClass + '-', diagram.svg); const nativeWidth = Number(diagram.svg.match(/viewBox=["'][^"']*?[\d.-]+[ ,]+[\d.-]+[ ,]+([\d.]+)/)?.[1]); const singleLane = diagram.spec?.lanes?.length === 1 ? ' single-lane' : ''; body = `<figure class="diagram"><div class="diagram-preview ${previewClass}${singleLane}" role="img" aria-label="${escape(title)}"${nativeWidth > 0 ? ` style="--native-width:${Math.round(nativeWidth)}px"` : ''}><style>${nativeStyle}</style>${svg}</div><figcaption><span>${escape(title)}</span><button class="text-button interactive" type="button" data-open-diagram="${escape(block.id)}">${words.explore} ↗</button></figcaption></figure><p class="diagram-fit-status fine" role="status" hidden></p><details class="diagram-semantics" open><summary>${words.graph}</summary><ul>${(diagram.semantic?.nodes || []).map(node => `<li>${escape(node.label || node.id)} <code>${escape(node.id)}</code></li>`).join('')}${(diagram.semantic?.edges || []).map(edge => `<li><code>${escape(edge.from)}</code> → <code>${escape(edge.to)}</code>${edge.label ? ` · ${escape(edge.label)}` : ''}</li>`).join('')}</ul></details>${block.changes?.length ? `<dl class="changes"><dt>${words.changes}</dt>${block.changes.map(change => `<dd><span class="chip ${escape(change.change)}">${words[change.change]}</span> <code>${escape(change.target)}</code></dd>`).join('')}</dl>` : ''}`; break; }
case 'chart': { const chart = compileExplainerChart(block.text); if (chart.error) unavailable(block, chart.error); body = `<figure class="chart" style="--native-width:${Math.round(chart.width)}px">${chart.svg.replace(/^<svg\b[^>]*>/, tag => tag.replace(/\s(?:width|height)="[^"]*"/g, ''))}${block.title ? `<figcaption>${i(block.title)}</figcaption>` : ''}</figure>`; break; }
case 'snippet': body = `<figure class="snippet"><figcaption><span class="snippet-label">${block.title ? i(block.title) : ''}${block.language ? `<code class="snippet-language">${escape(block.language)}</code>` : ''}</span><button class="text-button interactive" type="button" data-copy>${words.copy}</button></figcaption><pre><code${block.language ? ` class="language-${escape(block.language)}"` : ''}>${escape(block.text)}</code></pre></figure>`; break;
case 'code': { const source = sources[block.source]; if (!source?.path || typeof source.text !== 'string') unavailable(block,`Code requires a Git excerpt: ${block.source}`); body = `<figure class="code"><figcaption>${i(`[](source:${block.source})`)}<span>${escape(source.path)}:${escape(source.lines?.join('–'))}</span></figcaption><pre><code${block.language ? ` class="language-${escape(block.language)}"` : ''}>${escape(source.text)}</code></pre></figure>`; break; }
@@ -96,7 +97,7 @@ export function renderExplainer(document, options = {}) {
manifest.dependencies = (bundle.dependencies || []).map(({contentBase64,...entry})=>entry);
if (!preparedBundle) bundle.digest = hash(JSON.stringify(bundle));
if (bundle.sourceText !== sourceText || JSON.stringify(bundle.document) !== JSON.stringify(document)) throw new Error('Prepared bundle differs from rendered source or canonical document.');
- return `<!doctype html>\n<html lang="${escape(locale)}" data-archify-artifact="explainer" data-artifact="${escape(document.meta.id)}" data-revision="${revision}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><meta name="description" content="${escape(document.answer.summary)}"><title>${escape(document.meta.title)} · Archify</title><style>${css}</style></head><body><a class="skip-link" href="#board">${locale.startsWith('en')?'Skip to content':'跳至正文'}</a><div class="shell"><header class="masthead"><h1>${escape(document.meta.title)}</h1><div class="tools interactive"><div class="theme-controls" role="group" aria-label="${locale.startsWith('en')?'Theme':'主题'}">${['auto','light','dark'].map(theme=>`<button type="button" data-theme-choice="${theme}" aria-pressed="${theme === 'auto'}">${words[theme]}</button>`).join('')}</div><button type="button" data-print>${words.print}</button></div></header><main id="board"><div class="board">${panels}</div></main><footer>${footnotesHtml}<section class="sources"><h2>${words.sources}</h2><ol>${sourceList}</ol></section><p class="colophon">Archify</p></footer></div><dialog class="viewer-dialog" id="diagram-dialog" aria-labelledby="diagram-dialog-title"><header><h2 id="diagram-dialog-title"></h2><button type="button" data-close-diagram>${words.close} ×</button></header><p class="dialog-loading" role="status">${words.loading}</p></dialog><div id="toast" role="status" aria-live="polite"></div><script type="application/json" id="archify-explainer-prepared">${json(bundle)}</script><script type="application/json" id="explainer-manifest">${json(manifest)}</script><script type="application/json" id="explainer-reader-words">${json(words)}</script><script>${js}</script></body></html>`;
+ return `<!doctype html>\n<html lang="${escape(locale)}" data-archify-artifact="explainer" data-artifact="${escape(document.meta.id)}" data-revision="${revision}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><meta name="description" content="${escape(document.answer.summary)}"><title>${escape(document.meta.title)} · Archify</title><style>${css}</style></head><body><a class="skip-link" href="#board">${locale.startsWith('en')?'Skip to content':'跳至正文'}</a><div class="shell"><header class="masthead"><h1>${escape(document.meta.title)}</h1><div class="tools interactive"><div class="theme-controls" role="group" aria-label="${locale.startsWith('en')?'Theme':'主题'}">${['auto','light','dark'].map(theme=>`<button type="button" data-theme-choice="${theme}" aria-pressed="${theme === 'auto'}">${words[theme]}</button>`).join('')}</div><button type="button" data-print>${words.print}</button></div></header><main id="board"><div class="board">${panels}</div></main><footer>${footnotesHtml}<section class="sources"><h2>${words.sources}</h2><ol>${sourceList}</ol></section><p class="colophon">Archify</p></footer></div><dialog class="viewer-dialog" id="diagram-dialog" aria-labelledby="diagram-dialog-title"><header><h2 id="diagram-dialog-title"></h2><button type="button" data-close-diagram>${words.close} ×</button></header><p class="dialog-loading" role="status">${words.loading}</p></dialog><div id="toast" role="status" aria-live="polite"></div><script type="application/json" id="archify-explainer-prepared">${json(packPageBundle(bundle))}</script><script type="application/json" id="explainer-manifest">${json(manifest)}</script><script type="application/json" id="explainer-reader-words">${json(words)}</script><script>${js}</script></body></html>`;
}
// Prefix native SVG identifiers in the preview only. Original native HTML is frozen above.
@@ -114,11 +115,29 @@ function staticSvg(svg, id) {
// A scope written as "a · b · c" reads as separate conditions; anything else stays a sentence.
function scopeParts(scope) { return scope.split(/\s+·\s+/).map(part=>part.trim()).filter(Boolean); }
+// Split a selector list on its top-level commas; commas inside :is(), :not() or attribute values stay.
+function selectorList(selector) {
+ const parts = []; let depth = 0, quote = '', start = 0;
+ for (let i = 0; i < selector.length; i++) {
+ const c = selector[i];
+ if (quote) { if (c === quote && selector[i-1] !== '\\') quote = ''; }
+ else if (c === '"' || c === "'") quote = c;
+ else if (c === '(' || c === '[') depth++;
+ else if (c === ')' || c === ']') depth--;
+ else if (c === ',' && !depth) { parts.push(selector.slice(start,i)); start = i + 1; }
+ }
+ return [...parts, selector.slice(start)];
+}
+const nativeStyles = html => [...String(html).matchAll(/<style\b[^>]*>[\s\S]*?<\/style>/g)].map(match => match[0]).join('\n');
function previewPrefix(id) { return `preview-${id.replace(/[^A-Za-z0-9_-]/g,'-')}`; }
// Native CSS is scoped to its static preview. No native body/chrome layout enters the reader.
-function scopeNativeCss(styles, scope, prefix) {
+// The preview sets text in page fonts and shows only the SVG, so font faces and rules that name a
+// class absent from the SVG (Viewer chrome, toolbars, cards) are dropped.
+function scopeNativeCss(styles, scope, prefix, svg = '') {
const css = styles.replace(/<style[^>]*>/gi,'').replace(/<\/style>/gi,'').replace(/\/\*[\s\S]*?\*\//g,'');
+ const present = new Set(svg ? [...svg.matchAll(/\bclass="([^"]*)"/g)].flatMap(match => match[1].split(/\s+/)) : []);
+ const applies = value => !svg || [...value.replace(/:not\([^)]*\)/g,'').matchAll(/\.([A-Za-z_][\w-]*)/g)].every(match => present.has(match[1]));
const defaults = []; const systemDark = []; const systemLight = [];
function rules(input, collectThemes = true) {
let result = ''; let cursor = 0;
@@ -128,15 +147,14 @@ function scopeNativeCss(styles, scope, prefix) {
for(; end < input.length && depth; end++) { const c = input[end]; if(quote) {if(c === quote && input[end-1] !== '\\') quote = '';} else if(c === '\"' || c === "'") quote = c; else if(c === '{') depth++; else if(c === '}') depth--; }
const body = input.slice(opening + 1,end-1).replace(/url\(#([^\)]+)\)/g,(_,id)=>`url(#${prefix}${id})`); cursor = end;
if(selector.startsWith('@media') || selector.startsWith('@supports') || selector.startsWith('@layer')) { result += `${selector}{${rules(body,false)}}`; continue; }
- if(selector.startsWith('@font-face')) { result += `${selector}{${body}}`; continue; }
if(selector.startsWith('@')) continue;
- const selectors = selector.split(',').filter(value=>!/(^|[\s>+~])body(?:\b|$)/.test(value)).map(value=>{
+ const selectors = selectorList(selector).filter(value=>!/(^|[\s>+~])body(?:\b|$)/.test(value) && applies(value)).map(value=>{
let next = value.trim().replace(/#([A-Za-z][\w-]*)/g,(_,id)=>'#' + prefix + id);
next = next.replace(/^:root|^html\b/,scope);
if (next.startsWith('[data-theme=') || next.startsWith('[data-preset=')) next = scope + next;
return next.startsWith(scope) ? next : `${scope} ${next}`;
});
- const rootSelectors = selector.split(',').map(value=>value.trim());
+ const rootSelectors = selectorList(selector).map(value=>value.trim());
if (collectThemes && rootSelectors.includes(':root')) defaults.push(body);
if (collectThemes && rootSelectors.some(value=>/^(?:\:root)?\[data-theme=[\"']?dark[\"']?\]$/.test(value))) systemDark.push(body);
if (collectThemes && rootSelectors.some(value=>/^(?:\:root)?\[data-theme=[\"']?light[\"']?\]$/.test(value))) systemLight.push(body);
diff --git a/archify/references/explainer-authoring.md b/archify/references/explainer-authoring.md
index 0adf5421..802b2812 100644
--- a/archify/references/explainer-authoring.md
+++ b/archify/references/explainer-authoring.md
@@ -116,7 +116,7 @@ Node and participant types: `frontend`, `backend`, `database`, `cloud`, `securit
| redis | api | nil | return |
```
-Actor rows: `actor <id> | label | type`. Message rows: `from | to | label | variant?`, where `from` and `to` are actor IDs or labels.
+Actor rows: `actor <id> | label | type`. Message rows: `from | to | label | variant?`, where `from` and `to` are actor IDs or labels. A `phase | label` row opens a labelled band over the messages after it, up to the next phase: `phase | TCP handshake (1 RTT)`.
**`@workflow`** and **`@architecture`**: nodes, then edges. Placement follows the edges from left to right, starting with nodes that have no incoming edge.
diff --git a/test/explainer-browser.test.mjs b/test/explainer-browser.test.mjs
index 59840ee8..af533f55 100644
--- a/test/explainer-browser.test.mjs
+++ b/test/explainer-browser.test.mjs
@@ -5,6 +5,7 @@ import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {ChromeVisualBrowser,findChrome,runBrowserCheck} from '../archify/bin/visual-check.mjs';
+import {unpackPageBundle} from '../archify/explainer/page-bundle.mjs';
import {inspectPublicHtml,inspectExplainerBrowser,inspectNativePreviewLayout,inspectNativeViewer,explainerObservation,explainerObservationDiagnostics} from '../archify/explainer/browser-check.mjs';
// Explicit developer diagnostics only; ordinary explainer tests never launch Chrome.
const chrome=process.env.ARCHIFY_EXPLAINER_BROWSER_TESTS==='1' ? findChrome() : null;
@@ -77,7 +78,7 @@ test('wide frozen native previews keep every node visible at 1280 and reclaim th
const oversizedPrepared=await prepareExplainerDiagrams(oversized,{baseDir:dir,sourcePath:path.join(dir,'oversized.json'),quality:'showcase'}),hugeFile=artifact('oversized-native',renderExplainer(oversized,{sourceText:JSON.stringify(oversized),preparedDiagrams:oversizedPrepared,preparedSources:{sources:{example:{title:'Example'}}}}));
const huge=await inspectExplainerBrowser(browser,{artifactPath:hugeFile,width:1440,height:900,theme:'light'});assert.equal(huge.nativeText[0].fit,'insufficient');assert.equal(parseFloat(huge.nativeText[0].minWidth),0);assert.ok(huge.nativeText[0].scrollWidth<=huge.nativeText[0].clientWidth+1);assert.ok(huge.interactionFailures.some(e=>e.name==='diagram-fit'&&e.measurement.requiredWidth>e.measurement.clientWidth),'An actually overwide graph must fail with measured fit evidence');assert.ok(huge.interactionFailures.some(e=>e.name==='diagram-text'));
const corrupted=artifact('responsive-retained-floor',html.replace('</style>','\n.diagram-preview>svg{min-width:1321px!important}\n</style>'));await browser.resetPage();await inspectPublicHtml(browser,{artifactPath:corrupted,width:1280,theme:'light',keyboard:false});assert.ok((await inspectNativePreviewLayout(browser)).some(e=>e.outsidePreview.length>0),'A retained desktop floor must be detected through actual clipped node bounds');
- const embedded=await pageValue(browser,"Object.fromEntries(Object.entries(JSON.parse(document.querySelector('#archify-explainer-prepared').textContent).preparedDiagrams.diagrams).map(([id,c])=>[id,{html:c.html,sha256:c.sha256,bytes:c.bytes}]))");
+ const embedded=Object.fromEntries(Object.entries(unpackPageBundle(await pageValue(browser,"JSON.parse(document.querySelector('#archify-explainer-prepared').textContent)")).preparedDiagrams.diagrams).map(([id,c])=>[id,{html:c.html,sha256:c.sha256,bytes:c.bytes}]));
for(const [id,c]of Object.entries(embedded)){assert.equal(hash(c.html),frozen[id].sha256);assert.equal(Buffer.byteLength(c.html),frozen[id].bytes);assert.equal(c.sha256,frozen[id].sha256);assert.equal(c.bytes,frozen[id].bytes);}
}finally{await browser.close();}
});
diff --git a/test/explainer-diagrams.test.mjs b/test/explainer-diagrams.test.mjs
index 4dfa249d..7b22c2df 100644
--- a/test/explainer-diagrams.test.mjs
+++ b/test/explainer-diagrams.test.mjs
@@ -38,11 +38,11 @@ test('explainer diagrams: compact shapes produce real native showcase HTML and s
assert.equal(entry.checks.check.artifact.sha256, entry.sha256, 'native receipt binds original canonical bytes');
assert.equal(fs.existsSync(path.dirname(entry.checks.check.file)), false, 'renderer-owned temporary directory is cleaned');
assert.ok(entry.semantic.nodes.length >= 2);
- assert.match(entry.styles, /--frontend-fill/);
- assert.match(entry.styles, /data-theme="light"/);
+ assert.match(entry.html, /--frontend-fill/);
+ assert.match(entry.html, /data-theme="light"/);
assert.match(entry.svg, /data-quality-profile="showcase"/);
assert.match(entry.html, /Archify/);
- assert.equal(entry.canonicalSvg, entry.svg);
+ assert.ok(entry.html.includes(entry.svg), "the preview SVG is the canonical native SVG");
assert.equal(Buffer.from(entry.specification.contentBase64, 'base64').toString(), JSON.stringify(specs[type]));
}
assert.deepEqual(diagrams.sequence.semantic.edges.map(edge => [edge.from, edge.to]), [['client', 'api'], ['api', 'redis'], ['redis', 'api']]);
@@ -97,11 +97,11 @@ test('explainer diagrams: inline native locale inherits its parent while explici
]), meta: { locale: 'zh-CN' } };
const originalDocument = JSON.stringify(document);
const { diagrams, dependencies } = await prepareExplainerDiagrams(document, { baseDir: directory });
- assert.match(diagrams.inherited.canonicalSvg, /lang="zh-CN"/);
- assert.match(diagrams.inherited.canonicalSvg, />图例<\/text>/);
+ assert.match(diagrams.inherited.html, /lang="zh-CN"/);
+ assert.match(diagrams.inherited.html, />图例<\/text>/);
for (const id of ['english', 'standalone']) {
- assert.match(diagrams[id].canonicalSvg, /lang="en"/);
- assert.match(diagrams[id].canonicalSvg, />Legend<\/text>/);
+ assert.match(diagrams[id].html, /lang="en"/);
+ assert.match(diagrams[id].html, />Legend<\/text>/);
}
assert.equal(JSON.stringify(document), originalDocument, 'locale inheritance never rewrites authored specs');
assert.equal(diagrams.inherited.spec.meta.locale, undefined);
@@ -128,7 +128,6 @@ test('explainer diagrams: structural changes decorate only explicit preview targ
xml.on('error', error => { throw error; });
assert.doesNotThrow(() => xml.write(entry.svg).close(), 'preview annotations preserve valid native SVG markup');
assert.doesNotMatch(entry.html, /data-explainer-change/);
- assert.doesNotMatch(entry.canonicalSvg, /data-explainer-change/);
assert.equal(hash(entry.html), entry.sha256);
await assert.rejects(prepareExplainerDiagrams(documentOf([blockOf('sequence', spec,
{ changes: [{ target: 'nonexistent', change: 'removed' }] })])), error => error.archifyDiagnostics[0].code === 'explainer/diagram-change-target');
@@ -203,3 +202,11 @@ test('explainer diagrams: short phased workflows form one row with phase labels;
assert.throws(() => compileExplainerDiagram('workflow', ['lane confirm | Confirm', 'alert | Alert | external | missing'], { id: 'phases' }),
error => (error.archifyDiagnostics || error.diagnostics || []).some(item => /undeclared lane/.test(item.message)));
});
+
+test('explainer diagrams: sequence phase rows become native segments over the following messages', () => {
+ const spec = compileExplainerDiagram('sequence', ['actor b | Browser | frontend', 'actor s | Server | backend', 'phase | TCP', 'b | s | SYN', 's | b | SYN-ACK | return', 'phase | TLS', 'b | s | ClientHello'], { id: 'phased' });
+ assert.deepEqual(spec.segments.map(segment => segment.label), ['TCP', 'TLS']);
+ assert.ok(spec.segments[0].from < spec.messages[0].y && spec.segments[0].to > spec.messages[1].y && spec.segments[0].to < spec.segments[1].from);
+ assert.ok(spec.segments[1].from < spec.messages[2].y && spec.segments[1].to > spec.messages[2].y);
+ assert.throws(() => compileExplainerDiagram('sequence', ['b | s | SYN', 'phase | Empty'], { id: 'empty' }), error => (error.archifyDiagnostics || error.diagnostics || []).some(item => /phase needs/.test(item.message)));
+});
diff --git a/test/explainer-patch.test.mjs b/test/explainer-patch.test.mjs
index 8803d848..52cac9a8 100644
--- a/test/explainer-patch.test.mjs
+++ b/test/explainer-patch.test.mjs
@@ -5,10 +5,11 @@ import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { scanHtml } from '../archify/explainer/check.mjs';
+import { unpackPageBundle } from '../archify/explainer/page-bundle.mjs';
import { compileExplainerDiagram } from '../archify/explainer/diagrams.mjs';
const cli=path.resolve('archify/bin/archify.mjs');
const run=args=>spawnSync(process.execPath,[cli,...args],{encoding:'utf8',maxBuffer:64*1024*1024,env:{...process.env,ARCHIFY_UPDATE_CHECK_DISABLED:'1'}});
-const read=file=>JSON.parse(scanHtml(fs.readFileSync(file,'utf8')).scripts.find(s=>s.attrs.id==='archify-explainer-prepared').text);
+const read=file=>unpackPageBundle(JSON.parse(scanHtml(fs.readFileSync(file,'utf8')).scripts.find(s=>s.attrs.id==='archify-explainer-prepared').text));
const manifest=file=>JSON.parse(scanHtml(fs.readFileSync(file,'utf8')).scripts.find(s=>s.attrs.id==='explainer-manifest').text);
function temp(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'archify-explainer-patch-test-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));return dir;}
function fixture(){return {schema_version:1,diagram_type:'explainer',meta:{id:'patch-document',title:'What can change?',locale:'en'},answer:{summary:'One stable panel can be replaced.'},panels:[{id:'first',title:'What changes?',blocks:[{id:'first-text',type:'prose',text:'This text may change.'}]},{id:'second',title:'What stays?',blocks:[{id:'second-text',type:'prose',text:'This text remains exactly the same.'}]}],sources:[]};}
diff --git a/test/explainer-renderer.test.mjs b/test/explainer-renderer.test.mjs
index 1a0ce17c..f4dc9840 100644
--- a/test/explainer-renderer.test.mjs
+++ b/test/explainer-renderer.test.mjs
@@ -4,13 +4,14 @@ import { createHash } from 'node:crypto';
import { parse } from 'parse5';
import { renderExplainer } from '../archify/explainer/render.mjs';
import { computeExplainerRevision } from '../archify/explainer/revision.mjs';
+import { unpackPageBundle } from '../archify/explainer/page-bundle.mjs';
const sha = value => createHash('sha256').update(value).digest('hex');
const all = (node, test) => [ ...(test(node) ? [node] : []), ...(node.childNodes || []).flatMap(child=>all(child,test)) ];
const attr = (node,key) => node.attrs?.find(attribute=>attribute.name === key)?.value;
const text = node => node.nodeName === '#text' ? node.value : (node.childNodes || []).map(text).join('');
const find = (tree,id) => all(tree,node=>attr(node,'id') === id)[0];
-const payload = (tree,id) => JSON.parse(text(find(tree,id)));
+const payload = (tree,id) => unpackPageBundle(JSON.parse(text(find(tree,id))));
const source = {id:'code-source',title:'Real excerpt',path:'src/example.mjs',lines:[2,3]};
const nativeHtml = '<!doctype html><html><body><svg id="diagram-svg"></svg><script>const sample = "native";</script></body></html>';
const diagram = {diagramType:'architecture',spec:{meta:{title:'Actual relationships'}},html:nativeHtml,svg:'<svg id="diagram-svg" viewBox="0 0 200 80"><defs><marker id="arrow"></marker></defs><g data-node-id="api"><text x="10" y="30">API</text></g><path data-edge-id="write" data-edge-from="api" data-edge-to="redis" marker-end="url(#arrow)"/><g data-node-id="redis"><text x="90" y="30">Redis</text></g></svg>',styles:'<style>:root,[data-theme="dark"]{--native-ink:#eee}[data-theme="light"]{--native-ink:#123}body{height:100vh}text{fill:var(--native-ink)}</style>',sha256:sha(nativeHtml),bytes:Buffer.byteLength(nativeHtml),semantic:{nodes:[{id:'api',label:'API'},{id:'redis',label:'Redis'}],edges:[{id:'write',from:'api',to:'redis',label:'writes'}]}};