Skip to content

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

Polish explainer walk-throughs, source cards, export and the Viewer preset

tt-a1i3b08e7e6f2f7
diff --git a/archify/explainer/reader.css b/archify/explainer/reader.css
index 85adf891..5e9e2a1e 100644
--- a/archify/explainer/reader.css
+++ b/archify/explainer/reader.css
@@ -42,24 +42,27 @@ h1{font:700 26px/1.35 var(--sans);color:var(--ink);letter-spacing:-.015em;max-wi
.theme-controls button{height:24px;border:0;border-radius:6px;padding:0 10px;background:none;color:var(--muted)}
.theme-controls button:hover{color:var(--ink);background:var(--sunk)}
.theme-controls button[aria-pressed=true]{background:var(--sunk);color:var(--ink);font-weight:600;box-shadow:inset 0 0 0 1px var(--rule)}
-.style-menu{position:relative}
+.tool-menu{position:relative}
/* The same control shape for the walk-through bar, its start buttons and the question dialog */
.walk-bar button,.walk-start:not(.text-button),.ask-dialog footer button{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 11px;border:1px solid var(--control-border,var(--rule-strong));border-radius:8px;font-size:12.5px;line-height:1}
.ask-dialog footer button{height:32px;padding:0 14px}
-.style-menu [data-style-toggle] .tool-icon{width:13px;height:13px;margin-left:1px;transition:transform .15s}
-.style-menu [aria-expanded=true] .tool-icon{transform:rotate(180deg)}
+.tool-menu [aria-haspopup] .tool-icon:last-child{width:13px;height:13px;margin-left:1px;transition:transform .15s}
+.tool-menu [aria-expanded=true] .tool-icon:last-child{transform:rotate(180deg)}
.style-swatch{width:14px;height:14px;flex-shrink:0;border-radius:50%;box-shadow:inset 0 0 0 1px rgb(0 0 0/.12)}
.style-swatch[data-swatch=clean]{background:linear-gradient(135deg,#f4f5f7 50%,#2457d6 50%)}
.style-swatch[data-swatch=editorial]{background:linear-gradient(135deg,#f6f2ea 50%,#9c2f1f 50%)}
.style-swatch[data-swatch=product]{background:linear-gradient(135deg,#f1efff 50%,#5b4bf5 50%)}
.style-swatch[data-swatch=swiss]{background:linear-gradient(135deg,#fff 50%,#ff4f00 50%)}
-.style-options{position:absolute;right:0;top:calc(100% + 6px);z-index:40;min-width:148px;padding:4px;background:var(--panel);border:1px solid var(--control-border,var(--rule-strong));border-radius:10px;box-shadow:0 12px 32px rgb(16 24 40/.14)}
-.style-options button{display:flex;align-items:center;gap:9px;width:100%;height:32px;padding:0 10px;border:0;border-radius:6px;background:none;text-align:left}
-.style-options button span:not(.style-swatch){flex:1}
-.style-options button:hover,.style-options button:focus-visible{background:var(--sunk);outline:none;color:var(--ink)}
+.menu-options{position:absolute;right:0;top:calc(100% + 6px);z-index:40;min-width:148px;padding:4px;background:var(--panel);border:1px solid var(--control-border,var(--rule-strong));border-radius:10px;box-shadow:0 12px 32px rgb(16 24 40/.14)}
+.menu-options button{display:flex;align-items:center;gap:9px;width:100%;height:32px;padding:0 10px;border:0;border-radius:6px;background:none;text-align:left}
+.menu-options button span:not(.style-swatch){flex:1}
+.menu-options button:hover,.menu-options button:focus-visible{background:var(--sunk);outline:none;color:var(--ink)}
.style-options .tool-icon{width:14px;height:14px;color:var(--accent);visibility:hidden}
.style-options [aria-checked=true]{color:var(--ink);font-weight:600}
.style-options [aria-checked=true] .tool-icon{visibility:visible}
+.export-menu .menu-options{min-width:176px}
+.export-menu .menu-options .tool-icon{width:15px;height:15px;color:var(--muted)}
+.export-menu .menu-options small{font-size:11px;color:var(--faint)}
/* Board */
.board{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:16px;align-items:stretch}
@@ -172,6 +175,7 @@ meter{width:100%;height:8px;accent-color:var(--accent)}
.term:hover,.term.term-lit{background:var(--accent-soft);color:var(--accent-ink);text-decoration-color:var(--accent)}
.walk-start{margin-bottom:10px;font-size:12px;color:var(--accent);border-color:color-mix(in srgb,var(--accent) 35%,var(--rule))}
.walk-start[aria-pressed=true]{background:var(--accent-soft)}
+.js .walk-start[hidden]{display:none!important}
.walk-bar{position:sticky;top:8px;z-index:2;display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:0 0 12px;padding:6px 8px;border:1px solid var(--rule);border-radius:10px;background:color-mix(in srgb,var(--panel) 92%,transparent);backdrop-filter:blur(6px);box-shadow:var(--shadow);font-size:12px}
.walk-text{flex:1 1 220px;min-width:0;color:var(--ink);font-size:13px}
.walk-text:empty{display:none}
@@ -201,7 +205,7 @@ meter{width:100%;height:8px;accent-color:var(--accent)}
/* Phase labels then sit just above the nodes instead of above the hidden lane header. */
.single-lane .phase-rule,.single-lane .phase-chip,.single-lane .phase-chip+text{transform:translateY(30px)}
.diagram-preview text{font-family:var(--sans)!important}
-.board .diagram-preview.diagram-preview[class]{--bg:transparent;--grid:transparent;--canvas-dot:transparent;--mask:var(--surface);--panel:var(--surface);--text:var(--ink);--text-muted:var(--muted);--text-dim:var(--muted);--text-faint:var(--faint);--arrow:var(--faint);--arrow-emphasis:var(--accent);--frontend-fill:var(--surface);--frontend-stroke:var(--rule-strong);--backend-fill:var(--accent-soft);--backend-stroke:color-mix(in srgb,var(--accent) 50%,var(--rule));--database-fill:var(--sunk);--database-stroke:var(--rule-strong);--cloud-fill:var(--surface);--cloud-stroke:var(--rule-strong);--external-fill:var(--surface);--external-stroke:var(--rule-strong);--messagebus-fill:var(--surface);--messagebus-stroke:var(--rule-strong);--security-fill:var(--surface);--security-stroke:var(--rule-strong)}
+.board .diagram-preview.diagram-preview[class]{--bg:transparent;--lane-fill:color-mix(in srgb,var(--sunk) 55%,transparent);--lane-stroke:var(--control-border,var(--rule-strong));--grid:transparent;--canvas-dot:transparent;--mask:var(--surface);--panel:var(--surface);--text:var(--ink);--text-muted:var(--muted);--text-dim:var(--muted);--text-faint:var(--faint);--arrow:var(--faint);--arrow-emphasis:var(--accent);--frontend-fill:var(--surface);--frontend-stroke:var(--rule-strong);--backend-fill:var(--accent-soft);--backend-stroke:color-mix(in srgb,var(--accent) 50%,var(--rule));--database-fill:var(--sunk);--database-stroke:var(--rule-strong);--cloud-fill:var(--surface);--cloud-stroke:var(--rule-strong);--external-fill:var(--surface);--external-stroke:var(--rule-strong);--messagebus-fill:var(--surface);--messagebus-stroke:var(--rule-strong);--security-fill:var(--surface);--security-stroke:var(--rule-strong)}
.diagram-preview .semantic-sigil{color:var(--muted);stroke:var(--muted)}
.diagram-preview text.t-edge-default{fill:var(--accent-ink)}
.diagram-preview [data-node-id],.diagram-preview [data-edge-id]{transition:opacity .18s}
@@ -296,13 +300,23 @@ footer{padding:28px 0 32px}
/* Source cards */
.diagram-preview .has-source{cursor:help}
.diagram-preview .has-source:hover rect:not(.c-mask){stroke:var(--accent);stroke-width:2}
-.source-card{position:absolute;z-index:30;display:flex;flex-direction:column;gap:6px;padding:12px 14px;background:var(--panel);border:1px solid var(--rule-strong);border-radius:10px;box-shadow:0 12px 36px rgb(16 24 40/.16);font-size:12.5px;color:var(--secondary)}
-.source-card b{color:var(--ink);font-size:13px}
-.source-where{align-self:flex-start;font-size:11.5px;color:var(--muted)}
-.source-card pre{margin:2px 0 0;max-height:280px;font-size:11.5px;line-height:1.6;padding:8px 0}
+/* Source card: what kind of source, where it is, the evidence itself, then how to open it. */
+.source-card{position:absolute;z-index:30;display:flex;flex-direction:column;gap:10px;padding:12px 14px;background:var(--panel);border:1px solid var(--control-border,var(--rule-strong));border-radius:12px;box-shadow:0 16px 40px rgb(16 24 40/.16);font-size:12.5px;color:var(--secondary)}
+.source-card header{display:flex;align-items:flex-start;gap:10px}
+.source-icon{display:grid;place-items:center;flex-shrink:0;width:28px;height:28px;border-radius:8px;background:var(--accent-soft);color:var(--accent-ink)}
+.source-icon svg{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.3;stroke-linecap:round;stroke-linejoin:round}
+.source-head{display:grid;gap:2px;flex:1;min-width:0}
+.source-card b{color:var(--ink);font-size:13px;line-height:1.4}
+.source-where{font:11.5px/1.4 var(--mono);color:var(--muted);overflow-wrap:anywhere}
+.source-number{flex-shrink:0;min-width:20px;height:20px;padding:0 6px;border-radius:999px;display:grid;place-items:center;background:var(--sunk);font-size:11px;font-weight:600;color:var(--muted)}
+.source-card pre{margin:0;max-height:280px;font-size:11.5px;line-height:1.6;padding:8px 0;border-radius:8px}
.source-card .line{display:block;padding:0 12px 0 0;white-space:pre}
.source-card .line i{display:inline-block;width:3.2em;padding-right:10px;text-align:right;color:var(--faint);font-style:normal;user-select:none}
-.source-card a{align-self:flex-start;font-size:12px}
+.source-note{margin:0;padding:8px 12px;border-radius:8px;background:var(--sunk);box-shadow:inset 3px 0 0 var(--rule-strong);line-height:1.6}
+.source-note span{display:block;margin-top:2px;font-size:11.5px;color:var(--muted)}
+.source-card footer{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 0 0;border-top:1px solid var(--rule);font-size:11.5px;color:var(--muted)}
+.source-pin code{font-size:11px}
+.source-card a{font-size:12px;font-weight:500}
@media print{.source-card{display:none!important}}
/* Follow-up questions */
diff --git a/archify/explainer/reader.js b/archify/explainer/reader.js
index 8e47f5b7..97217675 100644
--- a/archify/explainer/reader.js
+++ b/archify/explainer/reader.js
@@ -220,9 +220,21 @@
}
all('[data-theme-choice]').forEach(button=>button.addEventListener('click',()=>{theme = button.dataset.themeChoice; applyTheme();}));
preference.addEventListener?.('change',applyTheme);
- document.querySelector('[data-print]').addEventListener('click',()=>window.print());
+ // Toolbar menus, not native selects, so they match the toolbar: arrow keys move, Escape or Tab
+ // closes, and a click elsewhere closes.
+ function toolMenu(container, pick, current = () => null) {
+ const toggle = container.querySelector('[aria-haspopup]'), panel = container.querySelector('[role=menu]'), items = all('[role^=menuitem]',panel);
+ const set = open => { panel.hidden = !open; toggle.setAttribute('aria-expanded',String(open)); if (open) (current() || items[0]).focus(); };
+ toggle.addEventListener('click',()=>set(panel.hidden));
+ items.forEach(item=>item.addEventListener('click',()=>{ set(false); toggle.focus(); pick(item); }));
+ panel.addEventListener('keydown',event=>{
+ const index = items.indexOf(document.activeElement);
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); items[(index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length].focus(); }
+ else if (event.key === 'Escape' || event.key === 'Tab') { set(false); if (event.key === 'Escape') toggle.focus(); }
+ });
+ document.addEventListener('click',event=>{ if (!panel.hidden && !container.contains(event.target)) set(false); });
+ }
// The author picks a default style; a reader's own choice is kept for every explainer page.
- // A small menu, not a native select, so it matches the toolbar; arrow keys move, Escape closes.
const styleToggle = document.querySelector('[data-style-toggle]'), styleMenu = document.querySelector('.style-options');
const styleItems = all('[data-style-choice]',styleMenu || document);
const setStyle = (style, remember) => {
@@ -233,16 +245,9 @@
styleToggle.querySelector('.style-swatch').dataset.swatch = style;
if (remember) { try { localStorage.setItem('archify-explainer-style',style); } catch {} requestAnimationFrame(()=>{ layoutBoard(); ensureDiagramReadability(); }); }
};
- const toggleMenu = open => { styleMenu.hidden = !open; styleToggle.setAttribute('aria-expanded',String(open)); if (open) (styleItems.find(item=>item.getAttribute('aria-checked') === 'true') || styleItems[0]).focus(); };
try { const saved = localStorage.getItem('archify-explainer-style'); if (saved) setStyle(saved,false); } catch {}
- styleToggle?.addEventListener('click',()=>toggleMenu(styleMenu.hidden));
- styleItems.forEach(item=>item.addEventListener('click',()=>{ setStyle(item.dataset.styleChoice,true); toggleMenu(false); styleToggle.focus(); }));
- styleMenu?.addEventListener('keydown',event=>{
- const index = styleItems.indexOf(document.activeElement);
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); styleItems[(index + (event.key === 'ArrowDown' ? 1 : -1) + styleItems.length) % styleItems.length].focus(); }
- else if (event.key === 'Escape' || event.key === 'Tab') { toggleMenu(false); if (event.key === 'Escape') styleToggle.focus(); }
- });
- document.addEventListener('click',event=>{ if (styleMenu && !styleMenu.hidden && !event.target.closest('.style-menu')) toggleMenu(false); });
+ toolMenu(document.querySelector('.style-menu'),item=>setStyle(item.dataset.styleChoice,true),()=>styleItems.find(item=>item.getAttribute('aria-checked') === 'true'));
+ toolMenu(document.querySelector('.export-menu'),item=>item.matches('[data-print]') ? window.print() : exportImage());
// Long image: the page as laid out now, drawn through an SVG foreignObject at twice the pixel
// density. Controls, dialogs and walk-through bars are left out. Browsers that refuse to export a
// foreignObject canvas (Safari) get a notice pointing to Print / PDF.
@@ -265,16 +270,16 @@
context.drawImage(image,0,0,canvas.width,canvas.height);
return new Promise((resolve,reject)=>canvas.toBlob(blob=>blob ? resolve(blob) : reject(new Error('empty')),'image/png'));
}
- const imageButton = document.querySelector('[data-export-image]');
- imageButton?.addEventListener('click',async()=>{
- imageButton.disabled = true;
+ const exportToggle = document.querySelector('[data-export-toggle]');
+ async function exportImage() {
+ exportToggle.disabled = true;
try {
const blob = await pageImage(), link = document.createElement('a');
link.href = URL.createObjectURL(blob); link.download = `${(document.querySelector('h1')?.textContent || 'explainer').trim().replace(/[\\/:*?"<>|]+/g,' ').slice(0,80)}.png`;
document.body.append(link); link.click(); link.remove(); setTimeout(()=>URL.revokeObjectURL(link.href),4000);
} catch { notify(say('This browser cannot export the page as an image. Use Print / PDF instead.','当前浏览器无法导出长图,请用"打印 / PDF"。')); }
- finally { imageButton.disabled = false; }
- });
+ finally { exportToggle.disabled = false; }
+ }
window.ArchifyExplainer = {pageImage};
// Only the isolated srcdoc copy receives this bridge. The payload remains byte-for-byte native.
const viewerDialog = byId('diagram-dialog');
@@ -289,7 +294,8 @@
} catch {}
return false;
}
- function sendViewer() { if(!viewer?.ready) return; viewer.frame.contentWindow.postMessage({kind:'archify-explainer-host',token:viewer.token,theme:root.dataset.theme,hash:viewer.hash,nodes:viewer.nodes,edges:viewer.edges},'*'); }
+ // The Viewer follows the page's theme, and its editorial preset matches the editorial style.
+ function sendViewer() { if(!viewer?.ready) return; viewer.frame.contentWindow.postMessage({kind:'archify-explainer-host',token:viewer.token,theme:root.dataset.theme,preset:root.dataset.style === 'editorial' ? 'editorial' : 'classic',hash:viewer.hash,nodes:viewer.nodes,edges:viewer.edges},'*'); }
function openViewer(id,hash,opener) {
const diagram = diagrams[id];
if(!diagram || !validHash(diagram,hash)) { notify(say('Diagram target unavailable.','图中目标不可用。')); return; }
@@ -330,6 +336,7 @@
const data=event.data;
if(event.source!==parent||data?.kind!=='archify-explainer-host'||data.token!==token)return;
if(['light','dark'].includes(data.theme))document.documentElement.dataset.theme=data.theme;
+ if(['classic','editorial'].includes(data.preset))window.Archify?.preset?.apply?.(data.preset);
if(typeof data.hash!=='string'||!/^(?:|focus=[^&]+|route=[^&]+~[^&]+)$/.test(data.hash))return;
pending=data;
if(location.hash.slice(1)===data.hash)dispatchEvent(new HashChangeEvent('hashchange'));
@@ -436,7 +443,10 @@
bar.innerHTML = `<button type="button" data-walk="prev">← ${words.prev}</button><span class="walk-count"></span><button type="button" data-walk="next">${words.next} →</button><span class="walk-text" aria-live="polite"></span><button type="button" data-walk="end">${words.end}</button>`;
// A diagram's bar sits above the diagram, so it stays in view while a tall diagram scrolls past.
const figure = control.closest('figcaption')?.closest('figure'); if (figure) figure.before(bar); else control.after(bar);
- control.setAttribute('aria-pressed','true');
+ // The bar takes the start button's place while the walk runs, so one set of controls shows.
+ const hadFocus = document.activeElement === control;
+ control.setAttribute('aria-pressed','true'); control.hidden = true;
+ if (hadFocus) bar.querySelector('[data-walk=next]').focus();
// The bar changes the panel height the board was planned with.
const replan = () => requestAnimationFrame(()=>{ layoutBoard(); ensureDiagramReadability(); });
replan();
@@ -445,7 +455,7 @@
bar.addEventListener('click',event=>{ const action = event.target.closest('[data-walk]')?.dataset.walk; if (action === 'end') stop(); else if (action) move(action === 'next' ? 1 : -1); });
const keys = event => { if (event.target.closest('input,textarea') || viewerDialog.open) return; if (event.key === 'ArrowRight') { event.preventDefault(); move(1); } else if (event.key === 'ArrowLeft') { event.preventDefault(); move(-1); } else if (event.key === 'Escape') stop(); };
document.addEventListener('keydown',keys);
- walking = {control,end:()=>{ document.removeEventListener('keydown',keys); bar.remove(); control.setAttribute('aria-pressed','false'); show(-1); walking = null; replan(); }};
+ walking = {control,end:()=>{ const refocus = bar.contains(document.activeElement); document.removeEventListener('keydown',keys); bar.remove(); control.hidden = false; control.setAttribute('aria-pressed','false'); if (refocus) control.focus(); show(-1); walking = null; replan(); }};
render();
}
function setupWalks() {
@@ -464,6 +474,24 @@
if (box && (box.bottom < 0 || box.top > innerHeight)) preview.scrollIntoView({block:'nearest',behavior:'smooth'});
}));
});
+ // A workflow no step list walks through can be walked node by node, in the order it was written,
+ // each node lit with the edges that lead into it.
+ const walked = new Set(all('ol.steps [data-diagram-link]').map(link=>link.dataset.diagramLink));
+ all('.block-diagram').forEach(block=>{
+ const diagram = diagrams[block.id], nodes = diagram?.semantic?.nodes || [], edges = diagram?.semantic?.edges || [];
+ if (diagram?.diagramType !== 'workflow' || walked.has(block.id) || nodes.length < 3) return;
+ const preview = block.querySelector('.diagram-preview');
+ const button = document.createElement('button'); button.type = 'button'; button.className = 'walk-start'; button.textContent = `▶ ${words.walkFlow}`; button.setAttribute('aria-pressed','false');
+ block.querySelector('.diagram-title')?.after(button);
+ button.addEventListener('click',()=>walk(button,nodes,index=>{
+ if (index < 0) { spotlight(preview); return; }
+ const node = nodes[index], into = edges.filter(edge=>edge.to === node.id && (index === 0 || nodes.slice(0,index).some(seen=>seen.id === edge.from)));
+ spotlight(preview,[node.id,...into.map(edge=>edge.from)],into.map(edge=>edge.id));
+ const target = preview.querySelector(`[data-node-id="${CSS.escape(node.id)}"]`), box = target?.getBoundingClientRect();
+ if (box && (box.top < 0 || box.bottom > innerHeight - 80)) target.scrollIntoView({block:'center',behavior:'smooth'});
+ return node.label || node.id;
+ }));
+ });
all('.block-diagram').forEach(block=>{
if (diagrams[block.id]?.diagramType !== 'sequence') return;
const preview = block.querySelector('.diagram-preview'), messages = all('[data-edge-id]',preview);
@@ -550,6 +578,12 @@
}
// Source cards: hovering or focusing a citation shows where the claim comes from, with the pinned
// code excerpt for a repository source, so a reader can check it without leaving the page.
+ const glyph = path => `<svg viewBox="0 0 16 16"><path d="${path}"/></svg>`;
+ const sourceIcons = {
+ code:glyph('M5.5 5 2.5 8l3 3M10.5 5l3 3-3 3M9 3.5 7 12.5'),
+ web:glyph('M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2zM2 8h12M8 2c1.7 1.6 2.5 3.6 2.5 6S9.7 12.4 8 14C6.3 12.4 5.5 10.4 5.5 8S6.3 3.6 8 2z'),
+ note:glyph('M4 2.5h5.5l2.5 2.5v8.5H4zM9.5 2.5V5H12M6 8h4M6 10.5h4'),
+ };
function setupSourceCards() {
const sources = prepared.preparedSources?.sources || {};
const card = document.createElement('div'); card.className = 'source-card'; card.hidden = true; card.setAttribute('role','tooltip');
@@ -562,11 +596,16 @@
if (!source) return;
clearTimeout(hideTimer);
const escapeText = value => String(value ?? '').replace(/[&<>"]/g,character=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[character]));
- const location = source.path ? `${source.path}${source.lines ? `:${source.lines.join('–')}` : ''}${source.revision ? ` @ ${String(source.revision).slice(0,10)}` : ''}` : (()=>{ try { return new URL(source.url).host; } catch { return ''; } })();
- const lines = typeof source.text === 'string' ? source.text.split('\n') : [];
+ // A repository source shows its pinned excerpt; a web page its host; any other note its text.
+ const host = (()=>{ try { return new URL(source.url).host.replace(/^www\./,''); } catch { return ''; } })();
+ const where = source.path ? `${source.path}${source.lines ? `:${source.lines.join('–')}` : ''}` : host;
+ const kind = source.path ? 'code' : source.url ? 'web' : 'note';
+ const lines = source.path && typeof source.text === 'string' ? source.text.split('\n') : [];
const first = source.lines?.[0] || 1;
const excerpt = lines.length ? `<pre><code>${lines.slice(0,14).map((line,index)=>`<span class="line"><i>${first + index}</i>${escapeText(line) || ' '}</span>`).join('')}${lines.length > 14 ? `<span class="line more"><i></i>…</span>` : ''}</code></pre>` : '';
- card.innerHTML = `<b>${escapeText(source.title || source.path || id)}</b>${location ? `<code class="source-where">${escapeText(location)}</code>` : ''}${excerpt}${source.url ? `<a href="${escapeText(source.url)}" target="_blank" rel="noopener noreferrer">${say('Open source','打开原文')} ↗</a>` : ''}`;
+ const note = !source.path && (source.text || source.method) ? `<p class="source-note">${escapeText(source.text || '')}${source.method ? `<span>${escapeText(source.method)}</span>` : ''}</p>` : '';
+ const number = /^\d+$/.test(link.textContent.trim()) ? link.textContent.trim() : '';
+ card.innerHTML = `<header><span class="source-icon" data-kind="${kind}" aria-hidden="true">${sourceIcons[kind]}</span><span class="source-head"><b>${escapeText(source.title || source.path || id)}</b>${where ? `<span class="source-where">${escapeText(where)}</span>` : ''}</span>${number ? `<span class="source-number">${number}</span>` : ''}</header>${excerpt}${note}${source.revision || source.url ? `<footer>${source.revision ? `<span class="source-pin">${say('Pinned at','固定在')} <code>${escapeText(String(source.revision).slice(0,7))}</code></span>` : '<span></span>'}${source.url ? `<a href="${escapeText(source.url)}" target="_blank" rel="noopener noreferrer">${say('Open source','打开原文')} ↗</a>` : ''}</footer>` : ''}`;
card.hidden = false;
const box = link.getBoundingClientRect(), width = Math.min(520,innerWidth - 24);
card.style.width = `${width}px`;
diff --git a/archify/explainer/render.mjs b/archify/explainer/render.mjs
index c0ce4113..d7d79e40 100644
--- a/archify/explainer/render.mjs
+++ b/archify/explainer/render.mjs
@@ -21,13 +21,14 @@ const icons = {
print: icon('M4.5 6V2.5h7V6M4.5 11.5h-2v-5h11v5h-2M4.5 9.5h7v4h-7z'),
expand: icon('M9.5 2.5h4v4M13.5 2.5 9.5 6.5M6.5 13.5h-4v-4M2.5 13.5l4-4'),
close: icon('M4 4l8 8M12 4l-8 8'),
+ export: icon('M8 2.5v7M5 6.5l3 3 3-3M3 11v2.5h10V11'),
};
// The Archify symbol (docs/assets/archify-mark.svg), for the favicon and the colophon.
const mark = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 360" fill="none"><path d="M151 94 81 164C67 178 60 191 60 212V248H97V212C97 204 100 199 106 193L179 120Z" fill="#0856F5"/><path d="M238 135C252 132 261 126 270 116L321 167C334 180 339 194 339 213V248H303V213C303 204 300 199 294 193Z" fill="#1DBBB7"/><rect x="146" y="16" width="110" height="104" rx="30" fill="#0856F5"/><rect x="18" y="238" width="110" height="104" rx="28" fill="#0856F5"/><rect x="274" y="238" width="108" height="104" rx="28" fill="#1DBBB7"/></svg>';
const favicon = `data:image/svg+xml,${encodeURIComponent(mark)}`;
const dictionaries = {
- en:{answer:'Answer',answerMark:'A',scope:'Applies to',sources:'Sources',print:'Print / PDF',image:'Image',style:'Style',styles:{clean:'Clean',editorial:'Editorial',product:'Product',swiss:'Swiss'},auto:'System',light:'Light',dark:'Dark',typical:'Typical value',explore:'Open interactive view',exploreHint:'Click a node to trace its links',exploreTitle:'Zoom, find nodes, trace paths, upstream and downstream, export images or motion',close:'Close',loading:'Opening diagram…',graph:'Diagram structure',changes:'Structure changes',added:'Added',removed:'Removed',modified:'Modified',copy:'Copy',copied:'Copied',walk:'Step through',walkMessages:'Play messages',prev:'Back',next:'Next',end:'Done',ask:'Ask',askQuote:'Ask about this',askPlaceholder:'What is unclear, or what should this part cover?',askCopy:'Copy question',askCopied:'Copied. Paste it to your agent.',askCancel:'Cancel',askChips:['I do not follow this part','Go deeper','Give an example','What is this based on?'],askPage:'Page',askFile:'File',askWhere:'Where',askQuoteLabel:'Quote',askQuestion:'Question',askNote:'Copies the page, the panel and its ID, so your agent can revise just this part.',askPatch:'Revise only this panel with Archify panel replacement (patch explainer), keeping its ID.',tagline:'Turn anything you want to understand, plan, or share into an interactive visual.',facts:{panels:n=>`${n} ${n === 1 ? 'panel' : 'panels'}`,diagrams:n=>`${n} ${n === 1 ? 'diagram' : 'diagrams'} validated`,sources:n=>`${n} ${n === 1 ? 'source' : 'sources'}`,pinned:rev=>`code pinned to ${rev}`}},
- zh:{answer:'结论',answerMark:'答',scope:'适用于',sources:'来源',print:'打印 / PDF',image:'长图',style:'样式',styles:{clean:'简洁',editorial:'杂志',product:'产品',swiss:'网格'},auto:'系统',light:'浅色',dark:'深色',typical:'典型值',explore:'打开交互图',exploreHint:'点节点看上下游',exploreTitle:'缩放、搜索节点、追踪路径和上下游,导出图片或动画',close:'关闭',loading:'正在打开交互图…',graph:'图的结构',changes:'结构改动',added:'新增',removed:'删除',modified:'修改',copy:'复制',copied:'已复制',walk:'逐步看',walkMessages:'逐条看消息',prev:'上一步',next:'下一步',end:'结束',ask:'追问',askQuote:'追问这段',askPlaceholder:'哪里没看懂,或者希望这块补充什么?',askCopy:'复制追问',askCopied:'已复制,粘贴给 agent 即可',askCancel:'取消',askChips:['没看懂这块','展开讲讲','举个例子','依据是什么?'],askPage:'页面',askFile:'文件',askWhere:'位置',askQuoteLabel:'引用',askQuestion:'问题',askNote:'会一并复制页面、面板位置和 ID,agent 可以只改这一块。',askPatch:'请用 Archify 的面板替换(patch explainer)只更新这个面板,保留它的 ID。',tagline:'把你想理解、规划或分享的事,变成可以互动的可视化作品。',facts:{panels:n=>`${n} 个面板`,diagrams:n=>`${n} 张图已通过结构校验`,sources:n=>`${n} 个来源`,pinned:rev=>`代码固定在提交 ${rev}`}}
+ en:{answer:'Answer',answerMark:'A',scope:'Applies to',sources:'Sources',print:'Print / PDF',image:'Long image',export:'Export',style:'Style',styles:{clean:'Clean',editorial:'Editorial',product:'Product',swiss:'Swiss'},auto:'System',light:'Light',dark:'Dark',typical:'Typical value',explore:'Open interactive view',exploreHint:'Click a node to trace its links',exploreTitle:'Zoom, find nodes, trace paths, upstream and downstream, export images or motion',close:'Close',loading:'Opening diagram…',graph:'Diagram structure',changes:'Structure changes',added:'Added',removed:'Removed',modified:'Modified',copy:'Copy',copied:'Copied',walk:'Step through',walkMessages:'Play messages',walkFlow:'Walk the flow',prev:'Back',next:'Next',end:'Done',ask:'Ask',askQuote:'Ask about this',askPlaceholder:'What is unclear, or what should this part cover?',askCopy:'Copy question',askCopied:'Copied. Paste it to your agent.',askCancel:'Cancel',askChips:['I do not follow this part','Go deeper','Give an example','What is this based on?'],askPage:'Page',askFile:'File',askWhere:'Where',askQuoteLabel:'Quote',askQuestion:'Question',askNote:'Copies the page, the panel and its ID, so your agent can revise just this part.',askPatch:'Revise only this panel with Archify panel replacement (patch explainer), keeping its ID.',tagline:'Turn anything you want to understand, plan, or share into an interactive visual.',facts:{panels:n=>`${n} ${n === 1 ? 'panel' : 'panels'}`,diagrams:n=>`${n} ${n === 1 ? 'diagram' : 'diagrams'} validated`,sources:n=>`${n} ${n === 1 ? 'source' : 'sources'}`,pinned:rev=>`code pinned to ${rev}`}},
+ zh:{answer:'结论',answerMark:'答',scope:'适用于',sources:'来源',print:'打印 / PDF',image:'长图',export:'导出',style:'样式',styles:{clean:'简洁',editorial:'杂志',product:'产品',swiss:'网格'},auto:'系统',light:'浅色',dark:'深色',typical:'典型值',explore:'打开交互图',exploreHint:'点节点看上下游',exploreTitle:'缩放、搜索节点、追踪路径和上下游,导出图片或动画',close:'关闭',loading:'正在打开交互图…',graph:'图的结构',changes:'结构改动',added:'新增',removed:'删除',modified:'修改',copy:'复制',copied:'已复制',walk:'逐步看',walkMessages:'逐条看消息',walkFlow:'沿流程看',prev:'上一步',next:'下一步',end:'结束',ask:'追问',askQuote:'追问这段',askPlaceholder:'哪里没看懂,或者希望这块补充什么?',askCopy:'复制追问',askCopied:'已复制,粘贴给 agent 即可',askCancel:'取消',askChips:['没看懂这块','展开讲讲','举个例子','依据是什么?'],askPage:'页面',askFile:'文件',askWhere:'位置',askQuoteLabel:'引用',askQuestion:'问题',askNote:'会一并复制页面、面板位置和 ID,agent 可以只改这一块。',askPatch:'请用 Archify 的面板替换(patch explainer)只更新这个面板,保留它的 ID。',tagline:'把你想理解、规划或分享的事,变成可以互动的可视化作品。',facts:{panels:n=>`${n} 个面板`,diagrams:n=>`${n} 张图已通过结构校验`,sources:n=>`${n} 个来源`,pinned:rev=>`代码固定在提交 ${rev}`}}
};
/** Render a validated canonical explainer with separately prepared, immutable resources. */
@@ -120,7 +121,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-style="${escape(document.meta.style || 'clean')}" 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><link rel="icon" type="image/svg+xml" href="${favicon}"><style>${css}</style></head><body><a class="skip-link" href="#board">${english?'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="${english?'Theme':'主题'}">${['auto','light','dark'].map(theme=>`<button type="button" data-theme-choice="${theme}" aria-pressed="${theme === 'auto'}">${words[theme]}</button>`).join('')}</div><div class="style-menu"><button type="button" class="tool-button" data-style-toggle aria-haspopup="menu" aria-expanded="false" aria-label="${words.style}"><span class="style-swatch" data-swatch="${escape(document.meta.style || 'clean')}"></span><span data-style-label>${words.styles[document.meta.style || 'clean']}</span>${icons.chevron}</button><div class="style-options" role="menu" aria-label="${words.style}" hidden>${['clean','editorial','product','swiss'].map(style=>`<button type="button" role="menuitemradio" aria-checked="${style === (document.meta.style || 'clean')}" data-style-choice="${style}" tabindex="-1"><span class="style-swatch" data-swatch="${style}"></span><span>${words.styles[style]}</span>${icons.check}</button>`).join('')}</div></div><button type="button" class="tool-button" data-export-image>${icons.image}<span>${words.image}</span></button><button type="button" class="tool-button" data-print>${icons.print}<span>${words.print}</span></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>${colophon}</footer></div><dialog class="viewer-dialog" id="diagram-dialog" aria-labelledby="diagram-dialog-title"><header><h2 id="diagram-dialog-title"></h2><button type="button" class="viewer-close" data-close-diagram>${icons.close}<span>${words.close}</span><kbd>Esc</kbd></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>`;
+ return `<!doctype html>\n<html lang="${escape(locale)}" data-style="${escape(document.meta.style || 'clean')}" 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><link rel="icon" type="image/svg+xml" href="${favicon}"><style>${css}</style></head><body><a class="skip-link" href="#board">${english?'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="${english?'Theme':'主题'}">${['auto','light','dark'].map(theme=>`<button type="button" data-theme-choice="${theme}" aria-pressed="${theme === 'auto'}">${words[theme]}</button>`).join('')}</div><div class="tool-menu style-menu"><button type="button" class="tool-button" data-style-toggle aria-haspopup="menu" aria-expanded="false" aria-label="${words.style}"><span class="style-swatch" data-swatch="${escape(document.meta.style || 'clean')}"></span><span data-style-label>${words.styles[document.meta.style || 'clean']}</span>${icons.chevron}</button><div class="menu-options style-options" role="menu" aria-label="${words.style}" hidden>${['clean','editorial','product','swiss'].map(style=>`<button type="button" role="menuitemradio" aria-checked="${style === (document.meta.style || 'clean')}" data-style-choice="${style}" tabindex="-1"><span class="style-swatch" data-swatch="${style}"></span><span>${words.styles[style]}</span>${icons.check}</button>`).join('')}</div></div><div class="tool-menu export-menu"><button type="button" class="tool-button" data-export-toggle aria-haspopup="menu" aria-expanded="false">${icons.export}<span>${words.export}</span>${icons.chevron}</button><div class="menu-options" role="menu" aria-label="${words.export}" hidden><button type="button" role="menuitem" tabindex="-1" data-export-image>${icons.image}<span>${words.image}</span><small>PNG</small></button><button type="button" role="menuitem" tabindex="-1" data-print>${icons.print}<span>${words.print}</span></button></div></div></div></header><main id="board"><div class="board">${panels}</div></main><footer>${footnotesHtml}<section class="sources"><h2>${words.sources}</h2><ol>${sourceList}</ol></section>${colophon}</footer></div><dialog class="viewer-dialog" id="diagram-dialog" aria-labelledby="diagram-dialog-title"><header><h2 id="diagram-dialog-title"></h2><button type="button" class="viewer-close" data-close-diagram>${icons.close}<span>${words.close}</span><kbd>Esc</kbd></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.
diff --git a/test/explainer-browser.test.mjs b/test/explainer-browser.test.mjs
index c114d2e8..af9d8dac 100644
--- a/test/explainer-browser.test.mjs
+++ b/test/explainer-browser.test.mjs
@@ -108,7 +108,9 @@ test('public system-theme mode starts with fresh storage and stable DOM identiti
test('text names light their diagram nodes and walk-throughs step through steps and messages',{skip:!chrome},async()=>{
const {renderExplainer}=await import('../archify/explainer/render.mjs');const {compileExplainerDiagram,prepareExplainerDiagrams}=await import('../archify/explainer/diagrams.mjs');
const spec=compileExplainerDiagram('sequence',['actor api | API | backend','actor redis | Redis | database','api | redis | Read cache','redis | api | Return cache'],{title:'Cache lookup',id:'native',quality:'showcase'});
+ const flow=compileExplainerDiagram('workflow',['alert | Alert','check | Check signal','fix | Fix','alert > check','check > fix'],{title:'Triage',id:'flow',quality:'showcase'});
const doc=formalDocument();doc.meta.id='walk-browser';doc.meta.quality_profile='showcase';doc.panels.push({id:'how',title:'Where does the request go?',blocks:[{id:'native',type:'diagram',diagramType:'sequence',spec},{id:'why',type:'prose',text:'The API asks Redis first, and Redis answers from memory.'},{id:'step',type:'steps',items:[{id:'read-step',text:'Read cache',target:{diagram:'native',node:'api',edges:['api-to-redis-1']}},{id:'return-step',text:'Return cache',target:{diagram:'native',node:'redis',edges:['redis-to-api-1']}}]}]});
+ doc.panels.push({id:'triage',title:'How is it handled?',blocks:[{id:'flow',type:'diagram',diagramType:'workflow',spec:flow}]});
const preparedDiagrams=await prepareExplainerDiagrams(doc,{baseDir:dir,sourcePath:path.join(dir,'walk.json'),quality:'showcase'});
const file=artifact('walk',renderExplainer(doc,{sourceText:JSON.stringify(doc),preparedDiagrams,preparedSources:{sources:{example:{title:'Example'}}}}));
const browser=new ChromeVisualBrowser(chrome);try {
@@ -128,6 +130,11 @@ test('text names light their diagram nodes and walk-throughs step through steps
return new Promise(resolve=>setTimeout(()=>resolve({terms,lit,stepHover,cleared,current,stepLit,ended,text,copied,open:document.querySelector('.ask-dialog').open}),50));})()`);
assert.deepEqual(result.terms,['API','Redis'],'each name is linked once per panel');
assert.deepEqual(result.lit,['redis']);
+ const flowWalk=await pageValue(browser,`(function(){const start=document.querySelector('#flow figcaption .walk-start');start.click();const hidden=start.hidden;document.querySelector('.walk-bar [data-walk=next]').click();const lit=[...document.querySelectorAll('#flow .reader-highlight')].map(e=>e.dataset.nodeId||e.dataset.edgeId);const text=document.querySelector('.walk-text').textContent;document.querySelector('.walk-bar [data-walk=end]').click();return {hidden,lit,text,restored:!start.hidden&&!document.querySelector('.walk-bar')};})()`);
+ assert.equal(flowWalk.hidden,true,'the walk bar replaces the start button');
+ assert.equal(flowWalk.text,'Check signal');
+ assert.ok(flowWalk.lit.includes('check')&&flowWalk.lit.includes('alert')&&flowWalk.lit.length>=3,JSON.stringify(flowWalk.lit));
+ assert.equal(flowWalk.restored,true);
assert.deepEqual(result.stepHover.sort(),['redis','redis-to-api-1'],'hovering anywhere in a step lights its node and edge');
assert.equal(result.cleared,true);
assert.equal(result.current,'return-step');