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(website): preserve Guide keyboard focus and selected filter state
tt-a1i7f13d25fb8e1
diff --git a/website/package.json b/website/package.jsonindex 12ceb738..a8d3c7b0 100644--- a/website/package.json+++ b/website/package.json@@ -12,7 +12,7 @@"preview": "astro preview","check": "astro check","test": "node --test test/*.test.mjs ../test/cloudflare-output.test.mjs",- "test:browser": "node --test --test-name-pattern=\"real Chrome\" ../test/site-language-continuity.test.mjs test/community-browser.test.mjs test/homepage-browser.test.mjs test/agent-diagrams-browser.test.mjs test/mco-source-case-browser.test.mjs test/gallery-browser.test.mjs test/clipboard-browser.test.mjs"+ "test:browser": "node --test --test-name-pattern=\"real Chrome\" ../test/site-language-continuity.test.mjs test/community-browser.test.mjs test/homepage-browser.test.mjs test/agent-diagrams-browser.test.mjs test/mco-source-case-browser.test.mjs test/gallery-browser.test.mjs test/clipboard-browser.test.mjs test/guide-keyboard-browser.test.mjs"},"dependencies": {"@astrojs/react": "^6.0.6",diff --git a/website/src/scripts/guide.js b/website/src/scripts/guide.jsindex f3c79f0a..a92da1c1 100644--- a/website/src/scripts/guide.js+++ b/website/src/scripts/guide.js@@ -62,7 +62,14 @@}function renderFilters() {var labels = {"en":{"architecture":"Architecture","workflow":"Workflow","sequence":"Sequence","dataflow":"Data flow","lifecycle":"Lifecycle","erd":"Entity-relationship"},"zh":{"architecture":"架构图","workflow":"工作流","sequence":"时序图","dataflow":"数据流","lifecycle":"生命周期","erd":"实体关系图"}};- document.getElementById('filters').innerHTML = ['all'].concat(types).map(function (type) { return '<button class="filter '+(activeType === type ? 'active':'')+'" type="button" data-filter="'+type+'">'+escapeHtml(type === 'all' ? t('all') : labels[language][type])+'</button>'; }).join('');+ document.getElementById('filters').innerHTML = ['all'].concat(types).map(function (type) { return '<button class="filter '+(activeType === type ? 'active':'')+'" type="button" aria-pressed="'+(activeType === type)+'" data-filter="'+type+'">'+escapeHtml(type === 'all' ? t('all') : labels[language][type])+'</button>'; }).join('');+ }+ function updateFilters() {+ document.querySelectorAll('[data-filter]').forEach(function (filter) {+ var selected = filter.dataset.filter === activeType;+ filter.classList.toggle('active', selected);+ filter.setAttribute('aria-pressed', String(selected));+ });}function renderCards() {var visible = recipes.filter(function (recipe) { return activeType === 'all' || recipe.type === activeType; });@@ -75,7 +82,7 @@var recipe = local(rawRecipe);lastRecipe = rawRecipe;var alt = alternatives || [];- var html = '<div class="result-main"><div><span class="result-kicker">'+escapeHtml(t('recommended'))+' · '+escapeHtml(confidence)+' '+escapeHtml(t('confidence'))+'</span><h3>'+escapeHtml(recipe.title)+'</h3><p class="result-question">'+escapeHtml(recipe.question)+'</p><p class="result-summary">'+escapeHtml(recipe.summary)+'</p>'+(recipe.proof ? '<a class="proof-link" href="'+ArchifySiteLanguage.page('gallery', '#proof-'+encodeURIComponent(recipe.proof))+'">'+escapeHtml(t('proofLink'))+'</a>' : '')+'</div><div class="boundary"><div class="boundary-item"><small>'+escapeHtml(t('use'))+'</small><p>'+escapeHtml(recipe.useWhen)+'</p></div><div class="boundary-item avoid"><small>'+escapeHtml(t('avoid'))+'</small><p>'+escapeHtml(recipe.avoidWhen)+'</p></div></div></div>';+ var html = '<div class="result-main"><div><span class="result-kicker">'+escapeHtml(t('recommended'))+' · '+escapeHtml(confidence)+' '+escapeHtml(t('confidence'))+'</span><h3 id="result-title" tabindex="-1">'+escapeHtml(recipe.title)+'</h3><p class="result-question">'+escapeHtml(recipe.question)+'</p><p class="result-summary">'+escapeHtml(recipe.summary)+'</p>'+(recipe.proof ? '<a class="proof-link" href="'+ArchifySiteLanguage.page('gallery', '#proof-'+encodeURIComponent(recipe.proof))+'">'+escapeHtml(t('proofLink'))+'</a>' : '')+'</div><div class="boundary"><div class="boundary-item"><small>'+escapeHtml(t('use'))+'</small><p>'+escapeHtml(recipe.useWhen)+'</p></div><div class="boundary-item avoid"><small>'+escapeHtml(t('avoid'))+'</small><p>'+escapeHtml(recipe.avoidWhen)+'</p></div></div></div>';html += '<div class="result-grid"><div class="checklist"><div class="mini-heading">'+escapeHtml(t('must'))+'</div><ul>'+recipe.include.map(function (item) { return '<li>'+escapeHtml(item)+'</li>'; }).join('')+'</ul><div class="presentation"><span class="tag">'+escapeHtml(recipe.type)+'</span><span class="tag">'+escapeHtml(recipe.presentation.preset)+'</span><span class="tag">'+escapeHtml(recipe.presentation.motion)+'</span></div></div>';html += '<div class="prompt-box"><div class="prompt-bar"><div class="mini-heading" style="margin:0">'+escapeHtml(t('prompt'))+'</div><button class="copy" id="copy-prompt" aria-describedby="prompt-copy-status" type="button">'+escapeHtml(t('copyPrompt'))+'</button></div><p id="prompt-copy-status" class="copy-status" role="status" aria-live="polite"></p><p class="prompt-text">'+escapeHtml(recipe.prompt)+'</p></div></div>';if (alt.length) html += '<div class="alternatives">'+escapeHtml(t('alternatives'))+alt.map(function (entry) { var item=local(entry.recipe); return '<button type="button" data-alt="'+item.id+'">'+escapeHtml(item.title)+' ['+item.type+']</button>'; }).join('')+'</div>';@@ -117,9 +124,14 @@document.getElementById('clear').addEventListener('click',function () { document.getElementById('scenario').value=''; document.getElementById('result').classList.remove('visible'); lastRecipe=null; });document.getElementById('scenario').addEventListener('keydown',function (event) { if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') runRecommendation(); });document.getElementById('samples').addEventListener('click',function (event) { var chip=event.target.closest('[data-query]'); if (!chip) return; document.getElementById('scenario').value=chip.dataset.query; runRecommendation(); });- document.getElementById('filters').addEventListener('click',function (event) { var filter=event.target.closest('[data-filter]'); if (!filter) return; activeType=filter.dataset.filter; renderFilters(); renderCards(); });+ document.getElementById('filters').addEventListener('click',function (event) { var filter=event.target.closest('[data-filter]'); if (!filter) return; activeType=filter.dataset.filter; updateFilters(); renderCards(); });document.getElementById('cards').addEventListener('click',function (event) { var card=event.target.closest('[data-recipe]'); if (!card) return; var recipe=recipes.find(function (item) { return item.id === card.dataset.recipe; }); renderResult(recipe,'selected',[]); document.getElementById('result').scrollIntoView({behavior:'smooth',block:'center'}); });- document.getElementById('result').addEventListener('click',function (event) { if (event.target.id === 'copy-prompt') copyPrompt(); var alt=event.target.closest('[data-alt]'); if (alt) renderResult(recipes.find(function (item) { return item.id === alt.dataset.alt; }),'selected',[]); });+ document.getElementById('result').addEventListener('click',function (event) { if (event.target.id === 'copy-prompt') copyPrompt(); var alt=event.target.closest('[data-alt]'); if (alt) {+ // Only recover focus when this activation removes the focused control.+ var restoreFocus = document.activeElement === alt;+ renderResult(recipes.find(function (item) { return item.id === alt.dataset.alt; }),'selected',[]);+ if (restoreFocus) document.getElementById('result-title').focus();+ } });document.getElementById('language').addEventListener('click', saveLanguageState);restoreLanguageState();applyLanguage(language);diff --git a/website/src/styles/guide.css b/website/src/styles/guide.cssindex 860db73a..49ea3db0 100644--- a/website/src/styles/guide.css+++ b/website/src/styles/guide.css@@ -153,3 +153,5 @@.copy-status { color:var(--text-2); font-size:.85rem; overflow-wrap:anywhere; }.copy-status:empty { margin:0; }++ .filter:focus-visible, .alternatives button:focus-visible, #result-title:focus-visible { outline:2px solid var(--accent); outline-offset:4px; }diff --git a/website/test/guide-keyboard-browser.test.mjs b/website/test/guide-keyboard-browser.test.mjsnew file mode 100644index 00000000..4dae06e6--- /dev/null+++ b/website/test/guide-keyboard-browser.test.mjs@@ -0,0 +1,155 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import http from 'node:http';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { ChromeVisualBrowser, findChrome } from '../../archify/bin/visual-check.mjs';++const website = fileURLToPath(new URL('../', import.meta.url));+const enabled = process.env.ARCHIFY_SITE_INTEGRATION === '1';+const root = path.resolve(process.env.ARCHIFY_SITE_ROOT || path.join(website, 'dist'));+const mount = process.env.ARCHIFY_SITE_BASE ?? '/archify';+const target = mount ? 'github' : 'cloudflare';+const output = path.join(website, '.browser-evidence', target, 'guide-keyboard');++test('real Chrome: Guide native keyboard activation retains focus and exposes selected filters', {+ skip: enabled ? false : 'Set ARCHIFY_SITE_INTEGRATION=1 and ARCHIFY_CHROME to run Guide keyboard evidence.',+ timeout: 120000,+}, async () => {+ const chrome = findChrome();+ assert.ok(chrome, 'The requested Guide keyboard gate requires usable Chrome.');+ const server = http.createServer((request, response) => {+ const url = new URL(request.url, 'http://127.0.0.1');+ if (mount && !url.pathname.startsWith(`${mount}/`)) return response.writeHead(404).end();+ let relative = url.pathname.slice(mount.length).replace(/^\/+/, '') || 'index.html';+ if (!path.extname(relative)) relative += '.html';+ const file = path.resolve(root, relative);+ if (!file.startsWith(`${root}${path.sep}`)) return response.writeHead(404).end();+ try {+ const types = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2' };+ response.setHeader('Content-Type', types[path.extname(file)] || 'application/octet-stream');+ response.end(fs.readFileSync(file));+ } catch { response.writeHead(404).end(); }+ });+ let browser;+ const manifest = { target, capturedAt: new Date().toISOString(),+ checkoutSha: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: website, encoding: 'utf8' }).trim(),+ runId: process.env.GITHUB_RUN_ID || null, receipts: [], screenshots: [] };+ fs.mkdirSync(output, { recursive: true });+ try {+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ browser = new ChromeVisualBrowser(chrome);+ const session = await browser.sessionPromise;+ const evaluate = async expression => {+ const result = await browser.cdp.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);+ assert.ok(!result.exceptionDetails, JSON.stringify(result.exceptionDetails));+ return result.result.value;+ };++ const settle = () => evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');+ const press = async (key, shift = false) => {+ const code = { Enter: 'Enter', ' ': 'Space', Tab: 'Tab' }[key];+ const keyCode = { Enter: 13, ' ': 32, Tab: 9 }[key];+ const data = { key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode, modifiers: shift ? 8 : 0 };+ await browser.cdp.send('Input.dispatchKeyEvent', { type: 'keyDown', ...data, ...(key === ' ' ? { text: ' ' } : key === 'Enter' ? { text: '\r' } : {}) }, session);+ await browser.cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', ...data }, session);+ await settle();+ };+ const click = async selector => {+ const point = await evaluate(`(() => {+ const e = document.querySelector(${JSON.stringify(selector)});+ e.scrollIntoView({block:'center', behavior:'instant'});+ const r = e.getBoundingClientRect(); return { x:r.x + r.width/2, y:r.y + r.height/2 };+ })()`);+ for (const type of ['mousePressed', 'mouseReleased']) await browser.cdp.send('Input.dispatchMouseEvent', { type, ...point, button:'left', clickCount:1 }, session);+ await settle();+ };+ const focus = selector => evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`);+ const active = () => evaluate(`(() => { const e = document.activeElement; return e.dataset.filter || e.id || e.className || e.tagName; })()`);+ const capture = async (lang, width, theme, region) => {+ await evaluate(`document.activeElement.scrollIntoView({block:'center', behavior:'instant'})`);+ await settle();+ const receipt = await evaluate(`(() => {+ const e = document.activeElement, r = e.getBoundingClientRect(), s = getComputedStyle(e);+ return { text:e.textContent, focusVisible:e.matches(':focus-visible'), outline:s.outlineStyle, outlineWidth:s.outlineWidth,+ fits:r.left >= 0 && r.right <= innerWidth && r.top >= document.querySelector('.site-nav').getBoundingClientRect().bottom && r.bottom <= innerHeight,+ pageWidth:document.documentElement.scrollWidth, lang:document.documentElement.lang };+ })()`);+ const file = `${lang}-${width}-${theme}-${region}.png`;+ const image = await browser.cdp.send('Page.captureScreenshot', { format: 'png' }, session);+ fs.writeFileSync(path.join(output, file), Buffer.from(image.data, 'base64'));+ manifest.screenshots.push({ file, receipt });+ assert.ok(receipt.focusVisible && receipt.outline !== 'none' && parseFloat(receipt.outlineWidth) >= 2, `${file}: visible focus`);+ assert.ok(receipt.fits && receipt.pageWidth <= width + 1, `${file}: focus remains visible without overflow`);+ };+ await browser.cdp.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] }, session);+ for (const lang of ['en', 'zh']) for (const width of [320, 1440]) for (const theme of ['light', 'dark']) {+ await browser.cdp.send('Emulation.setDeviceMetricsOverride', { width, height: 1000, deviceScaleFactor: 1, mobile: width === 320 }, session);+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session); loaded.catch(() => {});+ await browser.cdp.send('Page.navigate', { url: `http://127.0.0.1:${server.address().port}${mount}/${lang === 'zh' ? 'zh/' : ''}guide.html` }, session);+ await loaded;+ await evaluate(`document.fonts.ready`);+ await evaluate(`document.documentElement.dataset.theme = ${JSON.stringify(theme)}`);+ // Let existing theme transitions settle before taking visual evidence.+ await evaluate('new Promise(resolve => setTimeout(resolve, 300))');+ // Pointer smoke is separate from the native keyboard regressions below.+ await click('[data-filter="workflow"]');+ assert.equal(await active(), 'workflow');+ await click('[data-recipe]');+ assert.equal(await evaluate(`document.activeElement.matches('[data-recipe]')`), true, 'card activation preserves its focused control');+ await evaluate(`document.getElementById('scenario').value = 'api request cache miss event stream'`);+ await click('#recommend'); assert.equal(await active(), 'recommend');+ await click('[data-alt]'); assert.equal(await active(), 'result-title', 'focused pointer alternative receives a sensible replacement target');+ await click('#recommend');+ await focus('#scenario');+ await evaluate(`document.querySelector('[data-alt]').click()`);+ assert.equal(await active(), 'scenario', 'unfocused programmatic activation does not steal another control’s focus');+ manifest.receipts.push({ lang, width, theme, pointer: 'card, recommendation and alternative focus verified', unfocusedAlternative: 'scenario focus preserved' });+ for (const key of ['Enter', ' ']) {+ await focus('[data-filter="workflow"]');+ await press(key);+ assert.equal(await active(), 'workflow', 'activation does not discard the focused filter');+ const filters = await evaluate(`(() => ({+ selected:[...document.querySelectorAll('[data-filter][aria-pressed="true"]')].map(e => e.dataset.filter),+ unselected:[...document.querySelectorAll('[data-filter]:not([data-filter="workflow"])')].every(e => e.getAttribute('aria-pressed') === 'false'),+ cards:[...document.querySelectorAll('#cards .card-type')].map(e => e.textContent),+ expected:JSON.parse(document.getElementById('guide-data').textContent).filter(r => r.type === 'workflow').length+ }))()`);+ assert.deepEqual(filters.selected, ['workflow']); assert.equal(filters.unselected, true);+ assert.equal(filters.cards.length, filters.expected); assert.ok(filters.cards.every(type => type === 'workflow'));+ if (key === 'Enter') await capture(lang, width, theme, 'filter');+ await press('Tab'); assert.equal(await active(), 'sequence');+ await press('Tab', true); assert.equal(await active(), 'workflow');+ await press('Tab', true); assert.equal(await active(), 'architecture');+ // Switch selection as well as reactivating an already selected filter.+ await press(key); assert.equal(await active(), 'architecture');+ assert.equal(await evaluate(`document.querySelector('[data-filter="architecture"]').getAttribute('aria-pressed')`), 'true');+ assert.equal(await evaluate(`document.querySelector('[data-filter="workflow"]').getAttribute('aria-pressed')`), 'false');++ await evaluate(`document.getElementById('scenario').value = 'api request cache miss event stream'`);+ await focus('#recommend'); await press(key);+ assert.equal(await active(), 'recommend', 'recommendation does not gratuitously move focus');+ const expected = await evaluate(`(() => {+ const e = document.querySelector('[data-alt]');+ const r = JSON.parse(document.getElementById('guide-data').textContent).find(r => r.id === e.dataset.alt);+ return { title:r[${JSON.stringify(lang)}].title, prompt:r[${JSON.stringify(lang)}].prompt, next:r.proof ? 'proof-link' : 'copy-prompt' };+ })()`);+ await focus('[data-alt]'); await press(key);+ assert.equal(await active(), 'result-title', 'replaced alternative transfers focus to its new result heading');+ assert.equal(await evaluate(`document.querySelector('#result-title').textContent`), expected.title);+ assert.equal(await evaluate(`document.querySelector('.prompt-text').textContent`), expected.prompt);+ assert.equal(await evaluate(`document.querySelectorAll('[data-alt]').length`), 0);+ if (key === 'Enter') await capture(lang, width, theme, 'result');+ await press('Tab'); assert.equal(await active(), expected.next, 'Tab continues into the selected result');+ await focus('#result-title'); await press('Tab', true); assert.equal(await active(), 'clear', 'Shift+Tab returns to preceding controls');+ manifest.receipts.push({ lang, width, theme, key, filters, result: expected });+ fs.writeFileSync(path.join(output, 'manifest.json'), JSON.stringify(manifest, null, 2));+ }+ }+ } finally {+ if (browser) await browser.close();+ await new Promise(resolve => server.close(resolve));+ }+});diff --git a/website/test/guide-language-state.test.mjs b/website/test/guide-language-state.test.mjsindex 45b1936e..868541c3 100644--- a/website/test/guide-language-state.test.mjs+++ b/website/test/guide-language-state.test.mjs@@ -55,13 +55,13 @@ test('guide language navigation preserves a draft, filter and selected recipe onconst translated = page({ language: 'zh', href: 'https://archify.si/zh/guide', target: 'https://archify.si/guide', storage: original.storage });assert.equal(translated.element('scenario').value, draft);assert.match(translated.element('filters').innerHTML, /class="filter active"[^>]*data-filter="workflow"/);- assert.match(translated.element('result').innerHTML, /<h3>workflow 配方<\/h3>/);+ assert.match(translated.element('result').innerHTML, /<h3[^>]*>workflow 配方<\/h3>/);assert.equal(translated.element('result').classList.contains('visible'), true);assert.equal(original.storage.has(key), false, 'restore consumes the record');translated.element('language').dispatch('click', click);const back = page({ storage: original.storage });assert.equal(back.element('scenario').value, draft);- assert.match(back.element('result').innerHTML, /<h3>workflow recipe<\/h3>/);+ assert.match(back.element('result').innerHTML, /<h3[^>]*>workflow recipe<\/h3>/);assert.equal(original.storage.has(key), false);});