From a13b8245de3f86a37be62f6ecea44d7cb9b15fdf Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 12:46:00 +0800 Subject: [PATCH 01/65] fix(cli): on WSL, wait for a Windows opener's exit code, keep paths PowerShell would expand from wslview, and find PowerShell under any automount root --- packages/cli/src/open.ts | 64 +++++++++++++++++++++++----------- packages/cli/test/open.test.ts | 32 +++++++++++++---- 2 files changed, 68 insertions(+), 28 deletions(-) diff --git a/packages/cli/src/open.ts b/packages/cli/src/open.ts index 495346a..8663e1b 100644 --- a/packages/cli/src/open.ts +++ b/packages/cli/src/open.ts @@ -3,14 +3,27 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; /** - * One way to open a file. `orAt` is where `cmd` lives when it isn't on the PATH. `startFile` is a file for - * PowerShell to start (WSL): its Windows path goes on the end of `args`, as an encoded command. + * One way to open a file. `orAt` finds `cmd` when it isn't on the PATH. `startFile` is a file for PowerShell to + * start (WSL): its Windows path goes on the end of `args`, as an encoded command. `wait` is how long, in ms, the + * opener gets to exit before it counts as having handed the file off. */ -export type Opener = { cmd: string; args: string[]; orAt?: string; startFile?: string }; +export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number }; -// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`; this is the default mount. -const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'; const NOT_FOUND = 'not found'; +// xdg-open can turn into the browser itself and never exit, so a short wait has to count as a hand-off. +const HANDED_OFF = 3000; +// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only +// sign that nothing opened. +const WINDOWS_START = 15000; + +// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt. +function powershell(): string { + try { + return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'); + } catch { + return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'; + } +} /** Whether this Linux is WSL, where a stock distro has no xdg-open but Windows has a browser. */ export function isWsl(env: NodeJS.ProcessEnv = process.env): boolean { @@ -38,22 +51,26 @@ export function browserCommands( if (!wsl) return [{ cmd: 'xdg-open', args: [file] }]; // The browser is on the Windows side. xdg-open comes last: with no Linux browser it can exit 0 having opened // nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file. - return [ - { cmd: 'wslview', args: [file] }, - { cmd: 'powershell.exe', orAt: POWERSHELL, args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], startFile: file }, - { cmd: 'xdg-open', args: [file] }, - ]; + const start: Opener = { + cmd: 'powershell.exe', + orAt: powershell, + args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], + startFile: file, + wait: WINDOWS_START, + }; + // wslview hands the path to PowerShell with quoting of its own, so it only gets paths PowerShell reads literally. + const viaWslview: Opener[] = /[$`'"‘’‚‛“”„]/.test(file) ? [] : [{ cmd: 'wslview', args: [file], wait: WINDOWS_START }]; + return [...viaWslview, start, { cmd: 'xdg-open', args: [file] }]; } -/** The PowerShell command that opens `windowsPath` with its default app. */ export function startCommand(windowsPath: string): string { // PowerShell ends a single-quoted string on the curly quotes too; a doubled one is the only escape. return `Start-Process -FilePath '${windowsPath.replace(/['‘’‚‛]/g, '$&$&')}'`; } -function wslpath(file: string): string { +function wslpath(to: '-w' | '-u', path: string): string { // stderr is dropped so that wslpath's own message doesn't land ahead of the warning. - return execFileSync('wslpath', ['-w', file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); + return execFileSync('wslpath', [to, path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } /** @@ -65,8 +82,10 @@ export async function openInBrowser(file: string): Promise { return 'refused' in commands ? commands.refused : openWith(commands); } -/** Tries each opener until one hands the file off; resolves null then, or why every one of them failed. */ -export async function openWith(openers: Opener[], windowsPath: (file: string) => string = wslpath): Promise { +export async function openWith( + openers: Opener[], + windowsPath: (file: string) => string = (file) => wslpath('-w', file), +): Promise { const failures: string[] = []; for (const opener of openers) { const why = await run(opener, windowsPath); @@ -76,7 +95,10 @@ export async function openWith(openers: Opener[], windowsPath: (file: string) => return failures.join('; '); } -async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: string) => string): Promise { +async function run( + { cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener, + windowsPath: (file: string) => string, +): Promise { if (startFile !== undefined) { try { args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')]; @@ -84,16 +106,16 @@ async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: s return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path"; } } - let why = await launch(cmd, args); - if (why === NOT_FOUND && orAt) why = await launch(orAt, args); + let why = await launch(cmd, args, wait); + if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait); return why === null ? null : `${cmd} ${why}`; } -/** Resolves null once the command exits cleanly or is still running after a moment, else what went wrong. */ -function launch(cmd: string, args: string[]): Promise { +/** Resolves null once the command exits cleanly or is still running after `wait` ms, else what went wrong. */ +function launch(cmd: string, args: string[], wait: number): Promise { return new Promise((done) => { const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' }); - const timer = setTimeout(() => done(null), 3000); + const timer = setTimeout(() => done(null), wait); const finish = (why: string | null) => { clearTimeout(timer); done(why); diff --git a/packages/cli/test/open.test.ts b/packages/cli/test/open.test.ts index 31e26de..43e1681 100644 --- a/packages/cli/test/open.test.ts +++ b/packages/cli/test/open.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { browserCommands, isWsl, openWith, startCommand } from '../src/open'; +import { browserCommands, isWsl, openWith, startCommand, type Opener } from '../src/open'; const NODE = process.execPath; const MISSING = 'stackmap-no-such-opener'; const exits = (code: number) => ({ cmd: NODE, args: ['-e', `process.exit(${code})`] }); +// A Windows host has no signal exit status, and its path.resolve puts a drive on a POSIX path. +const posix = it.skipIf(process.platform === 'win32'); describe('browserCommands', () => { it('uses the native opener on darwin and linux', () => { @@ -12,8 +14,18 @@ describe('browserCommands', () => { }); it('tries the Windows side first on WSL, and xdg-open last', () => { - const commands = browserCommands('/tmp/a.html', 'linux', true); - expect(Array.isArray(commands) && commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']); + const commands = browserCommands('/tmp/a.html', 'linux', true) as Opener[]; + expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']); + // run() puts the encoded command straight after the last argument. + expect(commands[1]).toMatchObject({ startFile: '/tmp/a.html', orAt: expect.any(Function) }); + expect(commands[1]!.args.at(-1)).toBe('-EncodedCommand'); + }); + + it('keeps a path PowerShell would expand or unquote away from wslview', () => { + for (const file of ['/home/u/$(x)/a.html', '/home/u/a`b.html', "/home/u/it's.html", '/home/u/a"b.html']) { + const commands = browserCommands(file, 'linux', true) as Opener[]; + expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'xdg-open']); + } }); it('quotes the path for cmd on win32', () => { @@ -56,17 +68,23 @@ describe('openWith', () => { expect(await openWith([{ cmd: MISSING, args: [] }, exits(1)])).toBe(`${MISSING} not found; ${NODE} exited with 1`); }); - it('takes an opener killed by a signal as failed', async () => { + posix('takes an opener killed by a signal as failed', async () => { const killed = { cmd: NODE, args: ['-e', "process.kill(process.pid, 'SIGKILL')"] }; expect(await openWith([killed])).toBe(`${NODE} was killed by SIGKILL`); }); it('finds an opener that is off the PATH at its known location', async () => { - expect(await openWith([{ cmd: MISSING, orAt: NODE, args: ['-e', ''] }])).toBeNull(); - expect(await openWith([{ cmd: MISSING, orAt: `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`); + expect(await openWith([{ cmd: MISSING, orAt: () => NODE, args: ['-e', ''] }])).toBeNull(); + expect(await openWith([{ cmd: MISSING, orAt: () => `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`); + }); + + it('waits as long as the opener asks before taking it as handed off', async () => { + const slow = { cmd: NODE, args: ['-e', 'setTimeout(() => process.exit(1), 1000)'] }; + expect(await openWith([{ ...slow, wait: 100 }])).toBeNull(); + expect(await openWith([{ ...slow, wait: 30000 }])).toBe(`${NODE} exited with 1`); }); - it('hands PowerShell the Windows path of the file as an encoded command', async () => { + posix('hands PowerShell the Windows path of the file as an encoded command', async () => { const want = "Start-Process -FilePath '\\\\wsl.localhost\\Ubuntu\\home\\u\\it''s.html'"; // The child exits 0 only when the argument after its own decodes to the command. const check = `process.exit(Buffer.from(process.argv[1], 'base64').toString('utf16le') === ${JSON.stringify(want)} ? 0 : 7)`; From e68e3e7e3707e89ef043e61cc106e7de0da41e23 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:08:08 +0800 Subject: [PATCH 02/65] refactor(layout): share one coordinate rounding helper with core --- packages/core/src/geometry.ts | 3 ++- packages/layout/src/index.ts | 3 +-- packages/layout/src/labels.ts | 3 +-- packages/layout/src/lanes.ts | 4 +--- packages/layout/src/route.ts | 5 +---- packages/layout/src/sequence.ts | 4 +--- 6 files changed, 7 insertions(+), 15 deletions(-) diff --git a/packages/core/src/geometry.ts b/packages/core/src/geometry.ts index 8c45cda..681d5d9 100644 --- a/packages/core/src/geometry.ts +++ b/packages/core/src/geometry.ts @@ -1,6 +1,7 @@ import type { Point } from './types'; -const round = (n: number) => Math.round(n * 100) / 100; +/** Coordinates to two decimals: every layout rounds alike, so points on one line compare equal. */ +export const round = (n: number) => Math.round(n * 100) / 100; const dist = (a: Point, b: Point) => Math.hypot(b.x - a.x, b.y - a.y); const towards = (from: Point, to: Point, d: number): Point => { const len = dist(from, to); diff --git a/packages/layout/src/index.ts b/packages/layout/src/index.ts index 7d9d352..062f997 100644 --- a/packages/layout/src/index.ts +++ b/packages/layout/src/index.ts @@ -5,7 +5,7 @@ import { Worker as Thread } from 'node:worker_threads'; import ElkApi from 'elkjs/lib/elk-api.js'; import ElkBundled from 'elkjs/lib/elk.bundled.js'; import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk-api'; -import { cardSize, isLaneKind, usesCompactCards, type DiagramDraft, type Direction, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; +import { cardSize, isLaneKind, round, usesCompactCards, type DiagramDraft, type Direction, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; import { runChild, threadPort } from './elk-io'; import { placeLabels } from './labels'; import { layoutLanes } from './lanes'; @@ -209,7 +209,6 @@ function portKey(e: DiagramDraft['edges'][number], node: string, role: 'out' | ' return `${node}:${role}:${flipped ? 'flipped' : 'flow'}:${e.tone ?? ''}:${e.kind ?? 'sync'}`; } -const round = (n: number) => Math.round(n * 100) / 100; export async function layoutDiagram(draft: DiagramDraft): Promise { if (isLaneKind(draft.kind)) return layoutLanes(draft); diff --git a/packages/layout/src/labels.ts b/packages/layout/src/labels.ts index 9331e4f..b01cd0f 100644 --- a/packages/layout/src/labels.ts +++ b/packages/layout/src/labels.ts @@ -1,11 +1,10 @@ -import { measureText, polylineMidpoint, type Point, type Rect } from '@stackmap/core'; +import { measureText, polylineMidpoint, round, type Point, type Rect } from '@stackmap/core'; // Edge label placement shared by the lane and ELK layouts: the viewer's pill (11px Geist, 8px padding each side, // 20px tall) on a run of the route, clear of cards, other labels and other edges' lines. const LABEL_H = 20; export const labelWidth = (text: string) => Math.ceil(measureText(text, 'sans400', 11)) + 16; -const round = (n: number) => Math.round(n * 100) / 100; const overlaps = (a: Rect, b: Rect) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; /** Whether any axis-aligned segment of a route runs through the rectangle. */ diff --git a/packages/layout/src/lanes.ts b/packages/layout/src/lanes.ts index 8b97147..58a6b8f 100644 --- a/packages/layout/src/lanes.ts +++ b/packages/layout/src/lanes.ts @@ -1,4 +1,4 @@ -import { assignColumns, backEdges, cardSize, COMPACT, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; +import { assignColumns, backEdges, cardSize, COMPACT, round, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; import { labelWidth, placeLabels } from './labels'; export { assignColumns, backEdges } from '@stackmap/core'; @@ -28,8 +28,6 @@ export const GROUP_LABEL = 28; /** Room left of a lifecycle start state for its initial marker. */ export const START_MARK = 28; - -const round = (n: number) => Math.round(n * 100) / 100; const roundRect = (r: Rect): Rect => ({ x: round(r.x), y: round(r.y), width: round(r.width), height: round(r.height) }); function portChoices(sameLane: boolean, dCol: number, dLane: number, isBack: boolean): { sources: PortChoice[]; targets: PortChoice[] } { diff --git a/packages/layout/src/route.ts b/packages/layout/src/route.ts index 85f466d..faa7e9d 100644 --- a/packages/layout/src/route.ts +++ b/packages/layout/src/route.ts @@ -1,4 +1,4 @@ -import type { Point, Rect } from '@stackmap/core'; +import { round, type Point, type Rect } from '@stackmap/core'; // Orthogonal connector routing for the lane layouts, where ELK doesn't place the nodes. A sparse visibility // grid (the caller's channel lines plus every node's centre and port stubs), A* over (point, heading) with a @@ -43,8 +43,6 @@ const DX = [1, 0, -1, 0]; const DY = [0, 1, 0, -1]; const SIDE_DIR: Record = { right: 0, bottom: 1, left: 2, top: 3 }; -const round = (n: number) => Math.round(n * 100) / 100; - /** Port slots per side: the midpoint, then one either side, so edges of different tones leave separately. */ const SLOTS = [0, -1, 1, -2, 2] as const; type Slot = (typeof SLOTS)[number]; @@ -73,7 +71,6 @@ const stubPoint = (r: Rect, side: Side, slot: Slot = 0): Point => { }; const inflate = (r: Rect, m: number): Rect => ({ x: r.x - m, y: r.y - m, width: r.width + 2 * m, height: r.height + 2 * m }); -const inside = (p: Point, r: Rect) => p.x > r.x && p.x < r.x + r.width && p.y > r.y && p.y < r.y + r.height; /** Whether an axis-aligned segment passes through the rectangle's interior. */ function crosses(a: Point, b: Point, r: Rect): boolean { const x0 = Math.min(a.x, b.x); diff --git a/packages/layout/src/sequence.ts b/packages/layout/src/sequence.ts index c6348c2..b6ea3e3 100644 --- a/packages/layout/src/sequence.ts +++ b/packages/layout/src/sequence.ts @@ -1,4 +1,4 @@ -import { cardSize, measureText, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect, type SequenceLayout } from '@stackmap/core'; +import { cardSize, measureText, round, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect, type SequenceLayout } from '@stackmap/core'; // Sequence layout: participants across the top in draft order, messages top to bottom in edge order. The agent // gives only order; stackmap derives column spacing from the labels, rows from the messages and phases, and @@ -24,8 +24,6 @@ const MIN_BAR = 24; const LABEL = { face: 'sans400', size: 11.5, height: 16, gap: 6 } as const; const labelWidth = (text: string) => Math.ceil(measureText(text, LABEL.face, LABEL.size)) + 12; -const round = (n: number) => Math.round(n * 100) / 100; - export interface Bar { participant: string; /** 0 = on the lifeline; a self-call nests one step right of what is open */ From 7003475dae47addaf733bbc76a94578e401d59d5 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:08:45 +0800 Subject: [PATCH 03/65] fix(cli): keep serve running when a request path is not a valid URL --- packages/cli/src/serve.ts | 7 ++++--- packages/cli/test/serve.test.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index effbb96..d229c71 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -119,12 +119,13 @@ export async function serve(path: string, { template, port = 4400, log = () => { res.writeHead(403, { 'content-type': 'text/plain' }); return void res.end('forbidden host'); } - const url = new URL(req.url ?? '/', 'http://localhost'); + // Not `new URL`: it throws on a path like `//`, and any page in the user's browser can send one. + const pathname = (req.url ?? '/').split('?', 1)[0]; const read = req.method === 'GET' || req.method === 'HEAD'; - if (read && url.pathname === '/') { + if (read && pathname === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); res.end(req.method === 'HEAD' ? undefined : page); - } else if (req.method === 'GET' && url.pathname === '/events') { + } else if (req.method === 'GET' && pathname === '/events') { res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' }); res.write('retry: 1000\n\n'); send(res, 'diagnostics', JSON.stringify(state)); diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index af7d7b5..57beb2a 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -96,6 +96,14 @@ describe('serve', () => { expect(await raw(server.url, 'HEAD')).toBe(200); }); + it('answers a path that is not a valid URL instead of crashing', async () => { + write(commerceApi); + server = await serve(file, { template: TEMPLATE, port: 0 }); + expect(await raw(`${server.url}//`, 'GET')).toBe(404); + expect(await raw(`${server.url}/?x=1`, 'GET')).toBe(200); + expect(await raw(server.url, 'GET')).toBe(200); + }); + it('stamps the page and every diagnostics event with the build id, so a stale page can tell', async () => { write(commerceApi); server = await serve(file, { template: TEMPLATE, port: 0 }); From 7d3904dc0f89fd34e9cd36eebc43d077103bfb5d Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:09:04 +0800 Subject: [PATCH 04/65] fix(cli): accept the port-less Host header that clients send when serve runs on port 80 --- packages/cli/src/serve.ts | 10 ++++++++-- packages/cli/test/serve.test.ts | 11 ++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index d229c71..5b7325f 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -41,6 +41,13 @@ const diagnostic = (code: string, message: string, fix: string, path: string): D allowedFixes: [fix], }); +/** DNS rebinding: a foreign page resolving its own name to 127.0.0.1 would send its own Host. */ +export function isLocalHost(host: string | undefined, port: number): boolean { + // Clients leave the port out of Host when it is http's default. + const suffixes = port === 80 ? [':80', ''] : [`:${port}`]; + return suffixes.some((s) => host === `127.0.0.1${s}` || host === `localhost${s}`); +} + function listen(server: ReturnType, port: number): Promise { return new Promise((resolve, reject) => { const tryPort = (p: number, left: number) => { @@ -114,8 +121,7 @@ export async function serve(path: string, { template, port = 4400, log = () => { let bound = 0; const server = createServer((req, res) => { - // DNS rebinding: a foreign page resolving its own name to 127.0.0.1 would send its own Host. - if (req.headers.host !== `127.0.0.1:${bound}` && req.headers.host !== `localhost:${bound}`) { + if (!isLocalHost(req.headers.host, bound)) { res.writeHead(403, { 'content-type': 'text/plain' }); return void res.end('forbidden host'); } diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index 57beb2a..c9a9a32 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -6,7 +6,7 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { commerceApi } from '@stackmap/core/samples'; import { EMPTY_DATA_BLOCK } from '../src/embed'; -import { LIVE_BLOCK_ID, serve, type ServeHandle } from '../src/serve'; +import { isLocalHost, LIVE_BLOCK_ID, serve, type ServeHandle } from '../src/serve'; const TEMPLATE = `stackmap
${EMPTY_DATA_BLOCK}`; let dir: string; @@ -96,6 +96,15 @@ describe('serve', () => { expect(await raw(server.url, 'HEAD')).toBe(200); }); + it('accepts a Host without a port only on port 80, where clients leave it out', () => { + expect(isLocalHost('127.0.0.1', 80)).toBe(true); + expect(isLocalHost('localhost', 80)).toBe(true); + expect(isLocalHost('localhost:80', 80)).toBe(true); + expect(isLocalHost('localhost', 4400)).toBe(false); + expect(isLocalHost('evil.example', 80)).toBe(false); + expect(isLocalHost(undefined, 80)).toBe(false); + }); + it('answers a path that is not a valid URL instead of crashing', async () => { write(commerceApi); server = await serve(file, { template: TEMPLATE, port: 0 }); From 5d6e2b04b30d79a135682e9a8169e6cc73ccb906 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:09:05 +0800 Subject: [PATCH 05/65] fix(viewer): keep the export menu open when an item is pressed in Safari --- packages/viewer/e2e/export.spec.ts | 18 ++++++++++++++++-- packages/viewer/src/chrome/ExportMenu.tsx | 2 ++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/viewer/e2e/export.spec.ts b/packages/viewer/e2e/export.spec.ts index 7d051f4..18fdb91 100644 --- a/packages/viewer/e2e/export.spec.ts +++ b/packages/viewer/e2e/export.spec.ts @@ -1,5 +1,5 @@ -import { readFileSync } from 'node:fs'; -import { expect, test } from '@playwright/test'; +import { existsSync, readFileSync } from 'node:fs'; +import { expect, test, webkit } from '@playwright/test'; import { commerceApiLayout } from '../src/samples/commerce-api.layout'; // PNG IHDR: width and height are big-endian u32 at bytes 16..24. @@ -129,6 +129,20 @@ test('the export menu is keyboard operable and closes on Escape', async ({ page await expect(page.getByRole('button', { name: 'Export' })).toBeFocused(); }); +// Safari doesn't focus a button on click: pressing an item blurred the focused one, and that blur closed the menu. +test('the export menu takes a mouse click in WebKit', async ({ baseURL }) => { + test.skip(!existsSync(webkit.executablePath()), 'WebKit is not installed'); + const browser = await webkit.launch(); + try { + const page = await browser.newPage({ baseURL }); + await page.goto('/?page=sample'); + await expect(page.locator('.sm-card')).toHaveCount(6); + expect((await exportAs(page, /^SVG/)).name).toBe('commerce-api.svg'); + } finally { + await browser.close(); + } +}); + test('edge routes that swing outside the cards are inside the export', async ({ page }) => { const { groupedPlatformLayout } = await import('../src/samples/grouped-platform.layout'); await page.goto('/?page=grouped'); diff --git a/packages/viewer/src/chrome/ExportMenu.tsx b/packages/viewer/src/chrome/ExportMenu.tsx index 7da35bb..7a50987 100644 --- a/packages/viewer/src/chrome/ExportMenu.tsx +++ b/packages/viewer/src/chrome/ExportMenu.tsx @@ -152,6 +152,8 @@ export function ExportMenu() { onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOpen(false); }} + // Safari doesn't focus a button on click, so a press would blur the focused item to nothing and close the menu. + onMouseDown={(e) => e.preventDefault()} className={`${PANEL_CLASS} absolute top-full right-0 z-20 mt-2 w-[200px] p-1.5`} style={PANEL_STYLE} onKeyDown={(e) => { From 34f8215425607c23103f111dedb53a4e9e4ed8f1 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:10:24 +0800 Subject: [PATCH 06/65] fix(viewer): forget a pan's target when another camera move cuts it short --- packages/viewer/e2e/motion.spec.ts | 20 ++++++++++++++++++++ packages/viewer/src/canvas/useZoom.ts | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/viewer/e2e/motion.spec.ts b/packages/viewer/e2e/motion.spec.ts index 9164da7..7863a98 100644 --- a/packages/viewer/e2e/motion.spec.ts +++ b/packages/viewer/e2e/motion.spec.ts @@ -91,3 +91,23 @@ test('exporting mid-intro settles everything first', async ({ page }) => { await expect(page.locator('.sm-edge-path[data-drawing]')).toHaveCount(0); expect(await page.evaluate(() => [...document.querySelectorAll('.sm-card')].filter((c) => c.style.opacity).length)).toBe(0); }); + +test('a pan cut short by a zoom is forgotten: the next arrow press keeps the zoom', async ({ page }) => { + await page.goto('/?page=sample'); + await settled(page); + const camera = () => + page.evaluate(() => { + const m = new DOMMatrix(getComputedStyle(document.querySelector('.sm-viewport')!).transform); + return { x: m.e, k: m.a }; + }); + await page.locator('.sm-stage').focus(); + await page.keyboard.press('ArrowRight'); + await page.keyboard.press('+'); + await page.waitForTimeout(400); + const zoomed = await camera(); + await page.keyboard.press('ArrowRight'); + await page.waitForTimeout(400); + const panned = await camera(); + expect(panned.k).toBeCloseTo(zoomed.k, 5); + expect(panned.x).toBeCloseTo(zoomed.x - 80, 0); +}); diff --git a/packages/viewer/src/canvas/useZoom.ts b/packages/viewer/src/canvas/useZoom.ts index 71e31d8..580e4bd 100644 --- a/packages/viewer/src/canvas/useZoom.ts +++ b/packages/viewer/src/canvas/useZoom.ts @@ -180,7 +180,8 @@ export function useZoom(stageRef: RefObject, content: Rec .transition() .duration(duration()) .call(z.transform, toZoom(next)) - .on('end', () => { + // Cut short by another move (a zoom, a fit) it is no longer where the camera is heading. + .on('end interrupt cancel', () => { if (pending.current === next) pending.current = null; }); }), From 458a7f665039bf426fb53c8bb3e54678cb57134f Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:10:45 +0800 Subject: [PATCH 07/65] fix(cli): pick up saves made during serve's first layout, and rebuild once for a burst of them --- packages/cli/src/serve.ts | 45 ++++++++++++++++++--------- packages/cli/test/serve-queue.test.ts | 40 ++++++++++++++++++++++++ packages/cli/test/serve.test.ts | 9 ++++++ 3 files changed, 79 insertions(+), 15 deletions(-) create mode 100644 packages/cli/test/serve-queue.test.ts diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index 5b7325f..991cb6a 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -117,7 +117,35 @@ export async function serve(path: string, { template, port = 4400, log = () => { } }; - await rebuild(); + // One rebuild waits behind the running one however many saves arrive: only the latest content matters. + let queued = false; + let running = Promise.resolve(); + const schedule = () => { + if (queued) return; + queued = true; + running = running + .then(() => { + queued = false; + return rebuild(); + }) + .catch((e: unknown) => log(`✗ rebuild failed: ${(e as Error).message}`)); + }; + + // Editors save by writing a temp file and renaming it over the original, so watch the directory. + // Watching starts before the first build, so a save during that layout is not lost. + let timer: NodeJS.Timeout | undefined; + const watcher: FSWatcher = watch(dirname(path), (_event, name) => { + if (name !== null && name !== basename(path)) return; + clearTimeout(timer); + timer = setTimeout(schedule, DEBOUNCE_MS); + }); + // e.g. the directory was deleted (EPERM on Windows): report it instead of crashing the server. + watcher.on('error', (e) => + publish({ ok: false, diagnostics: [diagnostic('io/watch-failed', `stopped watching: ${e.message}`, 'restart stackmap serve', path)] }), + ); + + running = rebuild(); + await running; let bound = 0; const server = createServer((req, res) => { @@ -143,23 +171,10 @@ export async function serve(path: string, { template, port = 4400, log = () => { } }); - // Editors save by writing a temp file and renaming it over the original, so watch the directory. - let timer: NodeJS.Timeout | undefined; - let running = Promise.resolve(); - const watcher: FSWatcher = watch(dirname(path), (_event, name) => { - if (name !== null && name !== basename(path)) return; - clearTimeout(timer); - timer = setTimeout(() => { - running = running.then(rebuild).catch((e: unknown) => log(`✗ rebuild failed: ${(e as Error).message}`)); - }, DEBOUNCE_MS); - }); - // e.g. the directory was deleted (EPERM on Windows): report it instead of crashing the server. - watcher.on('error', (e) => - publish({ ok: false, diagnostics: [diagnostic('io/watch-failed', `stopped watching: ${e.message}`, 'restart stackmap serve', path)] }), - ); const keepAlive = setInterval(() => clients.forEach((res) => res.write(': ping\n\n')), 15_000); bound = await listen(server, port).catch((e) => { + clearTimeout(timer); watcher.close(); clearInterval(keepAlive); throw e; diff --git a/packages/cli/test/serve-queue.test.ts b/packages/cli/test/serve-queue.test.ts new file mode 100644 index 0000000..17b1d12 --- /dev/null +++ b/packages/cli/test/serve-queue.test.ts @@ -0,0 +1,40 @@ +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, expect, it, vi } from 'vitest'; +import { buildHtml } from '../src/commands'; +import { serve, type ServeHandle } from '../src/serve'; + +vi.mock('../src/commands', () => ({ buildHtml: vi.fn() })); +const build = vi.mocked(buildHtml); +const built = (title: string) => ({ ok: true, diagnostics: [], html: `${title}` }); +const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +let server: ServeHandle | undefined; +afterEach(async () => { + await server?.close(); + server = undefined; +}); + +it('runs one rebuild for all the saves that arrive during a slow one', async () => { + const file = join(mkdtempSync(join(tmpdir(), 'stackmap-queue-')), 'd.json'); + writeFileSync(file, '1'); + build.mockResolvedValueOnce(built('first')); + server = await serve(file, { template: '', port: 0 }); + // FSEvents can still report the write above; let that settle so it isn't counted below. + await pause(400); + build.mockClear(); + + let release!: () => void; + build.mockImplementationOnce(() => new Promise((resolve) => (release = () => resolve(built('slow'))))); + build.mockResolvedValue(built('latest')); + // Each save lands after the previous one's debounce, while the slow build is still running. + for (const content of ['2', '3', '4']) { + writeFileSync(file, content); + await pause(300); + } + release(); + await expect.poll(async () => (await fetch(server!.url)).text(), { timeout: 4000 }).toContain('latest'); + await pause(300); + expect(build).toHaveBeenCalledTimes(2); +}); diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index c9a9a32..d7f6900 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -176,6 +176,15 @@ describe('serve', () => { await sse.close(); }); + it('picks up an edit saved while the first layout is still running', async () => { + write(commerceApi); + const starting = serve(file, { template: TEMPLATE, port: 0 }); + // serve has read the file and is awaiting its layout. + write(withTitle('Edited early')); + server = await starting; + await expect.poll(async () => titleOf(await page(server!.url)), { timeout: 8000 }).toBe('Edited early · stackmap'); + }); + it('starts on an invalid file with the bare live template', async () => { write({ kind: 'architecture' }); server = await serve(file, { template: TEMPLATE, port: 0 }); From 330a410acf2d063a1e0a926406054b63fde8c466 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:11:18 +0800 Subject: [PATCH 08/65] fix(cli): stop warning of a slow layout for workflow, lifecycle and sequence diagrams --- packages/cli/src/commands.ts | 6 ++++-- packages/cli/test/commands.test.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index d35cd95..fbfd87b 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -1,6 +1,7 @@ import { createHash } from 'node:crypto'; import { realpathSync } from 'node:fs'; import { extname, resolve } from 'node:path'; +import { isLaneKind } from '@stackmap/core'; import { isLarge, layoutDiagram } from '@stackmap/layout'; import { validateDiagram, type Diagnostic, type ValidationResult } from '@stackmap/schema'; import { embedDiagram } from './embed'; @@ -70,9 +71,10 @@ export async function buildHtml( ): Promise { const result = validateFile(path); if (!result.ok || !result.diagram) return result; - const { nodes, edges } = result.diagram; + const { kind, nodes, edges } = result.diagram; // The result only prints once the layout is done; without this a big diagram looks hung for minutes. - if (progress && isLarge(result.diagram)) + // Lane and sequence kinds have their own layouts, which take a second at their largest. + if (progress && !isLaneKind(kind) && kind !== 'sequence' && isLarge(result.diagram)) progress(`laying out ${nodes.length} nodes and ${edges.length} connections; a diagram this size can take a while`); return { ...result, html: embedDiagram(template, await layoutDiagram(result.diagram)) }; } diff --git a/packages/cli/test/commands.test.ts b/packages/cli/test/commands.test.ts index 084d7da..9cde541 100644 --- a/packages/cli/test/commands.test.ts +++ b/packages/cli/test/commands.test.ts @@ -89,6 +89,19 @@ describe('deliver', () => { expect(lines).toEqual(['laying out 61 nodes and 60 connections; a diagram this size can take a while']); }, 30_000); + it('gives no slow-layout notice for kinds that never reach the slow layout', async () => { + const lines: string[] = []; + const nodes = Array.from({ length: 61 }, (_, i) => ({ id: `n${i}`, type: 'service', lane: 'a', card: { title: `n${i}` } })); + const edges = nodes.slice(1).map((n, i) => ({ id: `e${i}`, from: `n${i}`, to: n.id })); + const workflow = { kind: 'workflow', title: 'Steps', lanes: [{ id: 'a', label: 'A' }], nodes, edges }; + const sequence = { kind: 'sequence', title: 'Calls', nodes: nodes.map(({ lane: _lane, ...n }) => n), edges }; + for (const [name, d] of Object.entries({ workflow, sequence })) { + const r = await deliverCommand(file(`${name}.json`, d), { template: TEMPLATE, progress: (l) => lines.push(l) }); + expect(r.code).toBe(0); + } + expect(lines).toEqual([]); + }); + it('opens nothing when validation fails', async () => { let opened = false; const r = await deliverCommand(file('broken.json', broken), { template: TEMPLATE, open: async () => ((opened = true), null) }); From 27be047cae5fa5b8fd9d46090c0f5acad7057ec0 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:11:44 +0800 Subject: [PATCH 09/65] fix(cli): have serve say when a large diagram is being laid out --- packages/cli/src/serve.ts | 2 +- packages/cli/test/serve.test.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index 991cb6a..6d28b87 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -102,7 +102,7 @@ export async function serve(path: string, { template, port = 4400, log = () => { let built = false; const rebuild = async () => { try { - const result = await buildHtml(path, template); + const result = await buildHtml(path, template, log); publish({ ok: result.ok, diagnostics: result.diagnostics }, result.html); } catch (e) { const unreadable = e instanceof CliError; diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index d7f6900..7fcaa0f 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -185,6 +185,15 @@ describe('serve', () => { await expect.poll(async () => titleOf(await page(server!.url)), { timeout: 8000 }).toBe('Edited early · stackmap'); }); + it('says a large layout is under way before it finishes', async () => { + const nodes = Array.from({ length: 61 }, (_, i) => ({ id: `n${i}`, type: 'service', card: { title: `n${i}` } })); + const edges = nodes.slice(1).map((n, i) => ({ id: `e${i}`, from: `n${i}`, to: n.id })); + write({ kind: 'architecture', title: 'Big', nodes, edges }); + const lines: string[] = []; + server = await serve(file, { template: TEMPLATE, port: 0, log: (l) => lines.push(l) }); + expect(lines).toEqual(['laying out 61 nodes and 60 connections; a diagram this size can take a while', '✓ d.json ready']); + }); + it('starts on an invalid file with the bare live template', async () => { write({ kind: 'architecture' }); server = await serve(file, { template: TEMPLATE, port: 0 }); From db0ba3b41b3b9e7cd7728504c0db16fd05f091e3 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:12:39 +0800 Subject: [PATCH 10/65] perf(layout): skip routes nowhere near a label when placing it --- packages/layout/src/labels.ts | 64 +++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/packages/layout/src/labels.ts b/packages/layout/src/labels.ts index b01cd0f..9325122 100644 --- a/packages/layout/src/labels.ts +++ b/packages/layout/src/labels.ts @@ -7,14 +7,41 @@ const LABEL_H = 20; export const labelWidth = (text: string) => Math.ceil(measureText(text, 'sans400', 11)) + 16; const overlaps = (a: Rect, b: Rect) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; -/** Whether any axis-aligned segment of a route runs through the rectangle. */ -const crossed = (r: Rect, lines: Point[][]) => - lines.some((pts) => - pts.slice(1).some((b, i) => { - const a = pts[i]!; - return Math.max(a.x, b.x) > r.x && Math.min(a.x, b.x) < r.x + r.width && Math.max(a.y, b.y) > r.y && Math.min(a.y, b.y) < r.y + r.height; - }), +/** A route with its bounding box: most routes are nowhere near a given spot, and the box says so at once. */ +interface Line { + id?: string; + pts: Point[]; + x0: number; + y0: number; + x1: number; + y1: number; +} +function line(pts: Point[], id?: string): Line { + const l: Line = { id, pts, x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity }; + for (const p of pts) { + l.x0 = Math.min(l.x0, p.x); + l.y0 = Math.min(l.y0, p.y); + l.x1 = Math.max(l.x1, p.x); + l.y1 = Math.max(l.y1, p.y); + } + return l; +} +/** Whether any axis-aligned segment of a route (the edge's own aside) runs through the rectangle. */ +const crossed = (r: Rect, lines: Line[], own?: string) => + lines.some( + (l) => + (own === undefined || l.id !== own) && + l.x1 > r.x && + l.x0 < r.x + r.width && + l.y1 > r.y && + l.y0 < r.y + r.height && + l.pts.some((b, i) => { + const a = l.pts[i - 1]; + return !!a && Math.max(a.x, b.x) > r.x && Math.min(a.x, b.x) < r.x + r.width && Math.max(a.y, b.y) > r.y && Math.min(a.y, b.y) < r.y + r.height; + }), ); +/** Whether the route comes within `d` of the point. */ +const within = (p: Point, l: Line, d: number) => Math.hypot(Math.max(l.x0 - p.x, 0, p.x - l.x1), Math.max(l.y0 - p.y, 0, p.y - l.y1)) < d && distance(p, l.pts) < d; /** Distance from a point to the nearest segment of a polyline. */ function distance(p: Point, pts: Point[]): number { let best = Infinity; @@ -94,8 +121,8 @@ export function placeLabels( const { lines: borders, titles } = frameObstacles(frames); const cards = [...cardRects, ...titles]; const bias = biases(edges); - const rivals = (id: string) => Object.entries(routes).flatMap(([k, pts]) => (k === id ? [] : [pts])); - const others = (id: string) => [...rivals(id), ...borders]; + const rivals = Object.entries(routes).map(([id, pts]) => line(pts, id)); + const lines = [...rivals, ...borders.map((pts) => line(pts))]; const taken: Rect[] = []; const labels: Record = {}; if (keepMidpoints) { @@ -103,7 +130,7 @@ export function placeLabels( if (bias.get(e.id) !== 'mid') continue; const p = polylineMidpoint(routes[e.id]!); const pill = pillAt(p, labelWidth(e.label!)); - if (cards.some((r) => overlaps(pill, r)) || taken.some((r) => overlaps(pill, r)) || crossed(pill, others(e.id))) continue; + if (cards.some((r) => overlaps(pill, r)) || taken.some((r) => overlaps(pill, r)) || crossed(pill, lines, e.id)) continue; // Claimed now, so a later label whose midpoint lands here is the one that moves. taken.push(pill); labels[e.id] = { x: round(p.x), y: round(p.y) }; @@ -112,14 +139,14 @@ export function placeLabels( // Runs an edge has to itself first, for every label, before any label settles beside a trunk it shares. for (const e of labelled) { if (labels[e.id]) continue; - const spot = findLabelSpot(routes[e.id]!, e.label!, cards, taken, others(e.id), bias.get(e.id), rivals(e.id)); + const spot = findLabelSpot(routes[e.id]!, e.label!, cards, taken, lines, bias.get(e.id), rivals, false, e.id); if (spot) labels[e.id] = spot; } let misfit = 0; let unseated = 0; for (const e of labelled) { if (labels[e.id]) continue; - const spot = findLabelSpot(routes[e.id]!, e.label!, cards, taken, others(e.id), bias.get(e.id), rivals(e.id), true); + const spot = findLabelSpot(routes[e.id]!, e.label!, cards, taken, lines, bias.get(e.id), rivals, true, e.id); if (spot) labels[e.id] = spot; else { misfit = Math.max(misfit, labelWidth(e.label!)); @@ -137,17 +164,19 @@ export function placeLabels( } /** A spot that fits, claimed in `taken`; null when none does. */ -export function findLabelSpot( +function findLabelSpot( points: Point[], text: string, cards: Rect[], taken: Rect[], - lines: Point[][] = [], + lines: Line[] = [], bias: Bias = 'mid', /** other edges' routes: a spot nearer one of them than its own would read as naming that edge */ - rivals: Point[][] = [], + rivals: Line[] = [], /** whether the label may hang off a run a rival also takes: a trunk the edge shares */ shared = false, + /** the edge's id, whose own route in `lines` and `rivals` doesn't count */ + own?: string, ): Point | null { const w = labelWidth(text); let best: { p: Point; score: number } | null = null; @@ -171,8 +200,9 @@ export function findLabelSpot( const at = { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; const p = { x: round(at.x + dx), y: round(at.y + dy) }; const pill = pillAt(p, w); - if (cards.some((r) => overlaps(pill, r)) || taken.some((r) => overlaps(pill, r)) || crossed(pill, lines)) continue; - if (rivals.some((r) => distance(p, r) < distance(p, points) || (!shared && distance(at, r) < 0.5))) continue; + if (cards.some((r) => overlaps(pill, r)) || taken.some((r) => overlaps(pill, r)) || crossed(pill, lines, own)) continue; + const mine = distance(p, points); + if (rivals.some((r) => r.id !== own && (within(p, r, mine) || (!shared && within(at, r, 0.5))))) continue; // Longer and horizontal runs first; off-centre and off-line spots lose a little. A biased label goes as near // its far end as it fits instead. const reach = bias === 'end' ? total - (from + t * len) : bias === 'start' ? from + t * len : null; From f1899f55c75e9d256287f8be3f3ab314831a78a1 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:12:41 +0800 Subject: [PATCH 11/65] fix(cli): skip serve rebuilds when the watched file's content has not changed --- packages/cli/src/serve.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index 6d28b87..4255a2f 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto'; -import { watch, type FSWatcher } from 'node:fs'; +import { readFileSync, watch, type FSWatcher } from 'node:fs'; import { createServer, type ServerResponse } from 'node:http'; import type { AddressInfo } from 'node:net'; import { basename, dirname } from 'node:path'; @@ -100,7 +100,17 @@ export async function serve(path: string, { template, port = 4400, log = () => { }; let built = false; + // What the last build read: the watcher also reports saves that change nothing, and a write from just before it started. + let source = ''; + const fingerprint = () => { + try { + return createHash('sha256').update(readFileSync(path)).digest('hex'); + } catch { + return ''; + } + }; const rebuild = async () => { + source = fingerprint(); try { const result = await buildHtml(path, template, log); publish({ ok: result.ok, diagnostics: result.diagnostics }, result.html); @@ -126,7 +136,7 @@ export async function serve(path: string, { template, port = 4400, log = () => { running = running .then(() => { queued = false; - return rebuild(); + if (fingerprint() !== source) return rebuild(); }) .catch((e: unknown) => log(`✗ rebuild failed: ${(e as Error).message}`)); }; From c0d5e37c8b3ec3db136aa4861716a9c9d886727e Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:13:13 +0800 Subject: [PATCH 12/65] fix(viewer): centre a search result that was off screen instead of panning past it --- packages/viewer/e2e/explore.spec.ts | 16 +++++++ packages/viewer/e2e/motion.spec.ts | 17 ++++++++ packages/viewer/src/canvas/useZoom.ts | 61 +++++++++++++++------------ 3 files changed, 66 insertions(+), 28 deletions(-) diff --git a/packages/viewer/e2e/explore.spec.ts b/packages/viewer/e2e/explore.spec.ts index 1e2ec60..a0599ac 100644 --- a/packages/viewer/e2e/explore.spec.ts +++ b/packages/viewer/e2e/explore.spec.ts @@ -92,6 +92,22 @@ test('"/" opens search; Enter selects the first match and centres it', async ({ expect(Math.abs(c.y + c.height / 2 - (stage.y + (stage.height + 80 - 76) / 2))).toBeLessThan(2); }); +test('a search result that was off screen ends up centred, not panned past', async ({ page }) => { + for (let i = 0; i < 4; i++) await page.getByRole('button', { name: 'Zoom in' }).click(); + await page.locator('.sm-stage').focus(); + for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowLeft'); + await settle(page); + await page.keyboard.press('/'); + await page.getByRole('combobox', { name: 'Search nodes' }).fill('sess'); + await page.getByRole('combobox', { name: 'Search nodes' }).press('Enter'); + await expect(card(page, 'sessions')).toBeFocused(); + await settle(page); + const stage = (await page.locator('.sm-stage').boundingBox())!; + const c = (await card(page, 'sessions').boundingBox())!; + expect(Math.abs(c.x + c.width / 2 - (stage.x + stage.width / 2))).toBeLessThan(2); + expect(Math.abs(c.y + c.height / 2 - (stage.y + (stage.height + 80 - 76) / 2))).toBeLessThan(2); +}); + test('search tolerates regex characters and whitespace', async ({ page }) => { await page.getByRole('button', { name: /Search nodes/ }).click(); const box = page.getByRole('combobox', { name: 'Search nodes' }); diff --git a/packages/viewer/e2e/motion.spec.ts b/packages/viewer/e2e/motion.spec.ts index 7863a98..5e38b4a 100644 --- a/packages/viewer/e2e/motion.spec.ts +++ b/packages/viewer/e2e/motion.spec.ts @@ -111,3 +111,20 @@ test('a pan cut short by a zoom is forgotten: the next arrow press keeps the zoo expect(panned.k).toBeCloseTo(zoomed.k, 5); expect(panned.x).toBeCloseTo(zoomed.x - 80, 0); }); + +test('a search result that was off screen glides to the centre and stays there', async ({ page }) => { + await page.goto('/?page=sample'); + await settled(page); + for (let i = 0; i < 4; i++) await page.getByRole('button', { name: 'Zoom in' }).click(); + await page.locator('.sm-stage').focus(); + for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowLeft'); + await page.waitForTimeout(400); + await page.keyboard.press('/'); + await page.getByRole('combobox', { name: 'Search nodes' }).fill('sess'); + await page.getByRole('combobox', { name: 'Search nodes' }).press('Enter'); + await page.waitForTimeout(500); + const stage = (await page.locator('.sm-stage').boundingBox())!; + const c = (await page.locator('.sm-card[data-card-id="sessions"]').boundingBox())!; + expect(Math.abs(c.x + c.width / 2 - (stage.x + stage.width / 2))).toBeLessThan(2); + expect(Math.abs(c.y + c.height / 2 - (stage.y + (stage.height + 80 - 76) / 2))).toBeLessThan(2); +}); diff --git a/packages/viewer/src/canvas/useZoom.ts b/packages/viewer/src/canvas/useZoom.ts index 580e4bd..f526fda 100644 --- a/packages/viewer/src/canvas/useZoom.ts +++ b/packages/viewer/src/canvas/useZoom.ts @@ -54,7 +54,7 @@ export function useZoom(stageRef: RefObject, content: Rec const [transform, setTransform] = useState({ x: 0, y: 0, k: 1 }); const current = useRef(transform); current.current = transform; - // Where an animated pan is heading, so a press during the animation adds to it instead of losing the rest. + // Where an animated move is heading, so a move made on the way builds on it, not on the camera mid-flight. const pending = useRef(null); const [stage, setStage] = useState({ width: 0, height: 0 }); const behavior = useRef | null>(null); @@ -119,6 +119,18 @@ export function useZoom(stageRef: RefObject, content: Rec [stageRef], ); + const head = useCallback((z: ZoomBehavior, el: HTMLDivElement, next: Transform) => { + pending.current = next; + select(el) + .transition() + .duration(duration()) + .call(z.transform, toZoom(next)) + // Cut short by another move (a zoom, a drag) it is no longer where the camera is heading. + .on('end interrupt cancel', () => { + if (pending.current === next) pending.current = null; + }); + }, []); + const zoomIn = useCallback( () => animate((z, el) => select(el).transition().duration(duration()).call(z.scaleBy, ZOOM_STEP)), [animate], @@ -129,25 +141,24 @@ export function useZoom(stageRef: RefObject, content: Rec ); const fit = useCallback( () => - animate((z, el) => - select(el) - .transition() - .duration(duration()) - .call(z.transform, toZoom(fitTransform(content, { width: el.clientWidth, height: el.clientHeight }, { inset: CHROME_INSET }))), - ), - [animate, content], + animate((z, el) => head(z, el, fitTransform(content, { width: el.clientWidth, height: el.clientHeight }, { inset: CHROME_INSET }))), + [animate, head, content], ); // Centre between the chrome bands, not on the raw stage, so the node doesn't sit under the toolbar. const centerOn = useCallback( (p: Point, opts?: MoveOptions) => animate((z, el) => { const anchor: [number, number] = [el.clientWidth / 2, (el.clientHeight + CHROME_INSET.top - CHROME_INSET.bottom) / 2]; - pending.current = null; // A 0ms transition still lands a frame later, so rapid instant moves would cancel each other. - if (opts?.instant) select(el).interrupt().call(z.translateTo, p.x, p.y, anchor); - else select(el).transition().duration(duration()).call(z.translateTo, p.x, p.y, anchor); + if (opts?.instant) { + pending.current = null; + select(el).interrupt().call(z.translateTo, p.x, p.y, anchor); + return; + } + const { k } = pending.current ?? current.current; + head(z, el, { x: anchor[0] - p.x * k, y: anchor[1] - p.y * k, k }); }), - [animate], + [animate, head], ); const fitRect = useCallback( @@ -161,9 +172,9 @@ export function useZoom(stageRef: RefObject, content: Rec t.k <= 1 ? t : { x: (size.width - r.width) / 2 - r.x, y: CHROME_INSET.top + (band - r.height) / 2 - r.y, k: 1 }; - select(el).transition().duration(duration()).call(z.transform, toZoom(next)); + head(z, el, next); }), - [animate], + [animate, head], ); const panBy = useCallback( (dx: number, dy: number, opts?: MoveOptions) => @@ -175,33 +186,27 @@ export function useZoom(stageRef: RefObject, content: Rec select(el).interrupt().call(z.transform, toZoom(next)); return; } - pending.current = next; - select(el) - .transition() - .duration(duration()) - .call(z.transform, toZoom(next)) - // Cut short by another move (a zoom, a fit) it is no longer where the camera is heading. - .on('end interrupt cancel', () => { - if (pending.current === next) pending.current = null; - }); + head(z, el, next); }), - [animate], + [animate, head], ); const ensureVisible = useCallback( (r: Rect) => animate((z, el) => { - const { k } = current.current; + // Against where the camera will be: a reveal centring this card may have only just set off. + const base = pending.current ?? current.current; + const { k } = base; const margin = 24 / k; - const full = viewportRect(current.current, { width: el.clientWidth, height: el.clientHeight }); + const full = viewportRect(base, { width: el.clientWidth, height: el.clientHeight }); // Treat the overlay bands as off-screen so a focused card never ends up under the chrome. const v = { ...full, y: full.y + CHROME_INSET.top / k, height: full.height - (CHROME_INSET.top + CHROME_INSET.bottom) / k }; const shift = (lo: number, size: number, vlo: number, vsize: number) => lo - margin < vlo ? lo - margin - vlo : lo + size + margin > vlo + vsize ? lo + size + margin - (vlo + vsize) : 0; const dx = shift(r.x, r.width, v.x, v.width); const dy = shift(r.y, r.height, v.y, v.height); - if (dx || dy) select(el).transition().duration(duration()).call(z.translateBy, -dx, -dy); + if (dx || dy) head(z, el, { x: base.x - dx * k, y: base.y - dy * k, k }); }), - [animate], + [animate, head], ); const camera = useMemo( From 296271b7cfb9c55c05caaead5bcd255336807372 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:13:46 +0800 Subject: [PATCH 13/65] fix(layout): keep a repeated unanswered call in the activation bar it opened --- packages/layout/src/sequence.ts | 21 +++++++++++++++++---- packages/layout/test/sequence.test.ts | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/packages/layout/src/sequence.ts b/packages/layout/src/sequence.ts index b6ea3e3..5313cf2 100644 --- a/packages/layout/src/sequence.ts +++ b/packages/layout/src/sequence.ts @@ -40,9 +40,10 @@ export interface Bar { /** * Activation bars by simulation over the messages in order, per participant a stack of open bars: - * - a call to an idle participant opens a bar; a call to one that is waiting on its own call (a callback) - * nests a bar inside; a call from someone new to a participant that is busy but waiting on nobody first ends - * the old bar where it was last busy; + * - a call to an idle participant opens a bar; a call to one that is waiting on its own call nests a bar inside, + * when it is a callback or comes from a new caller (a caller repeating its request with no reply drawn stays in + * the bar it opened); a call from someone new to a participant that is busy but waiting on nobody first ends the + * old bar where it was last busy; * - a reply closes the replier's bar opened by the one it answers (else its innermost), with any nested inside; * - a self-call nests a short bar; sending or receiving keeps a bar busy; * - a bar still open at the end runs to its participant's last message. @@ -62,6 +63,17 @@ export function activations(edges: DiagramEdge[]): Bar[] { const top = stacks.get(p)?.at(-1); if (top) top.busy = row; }; + /** Whether `p` is waiting on `q`, directly or down its chain of calls: a call from `q` is then a callback. */ + const awaits = (p: string, q: string) => { + const seen = new Set([p]); + for (const x of seen) { + for (const w of waiting.get(x) ?? []) { + if (w === q) return true; + seen.add(w); + } + } + return false; + }; edges.forEach((e, row) => { last.set(e.from, row); last.set(e.to, row); @@ -90,7 +102,8 @@ export function activations(edges: DiagramEdge[]): Bar[] { } // Receiving counts as busy, but only for work this message belongs to (checked above). touch(e.to, row); - if (!st.length || (pending && e.kind !== 'async')) { + // Without the caller check, every repeat of an unanswered request would nest one bar deeper. + if (!st.length || (pending && e.kind !== 'async' && (awaits(e.to, e.from) || !st.some((b) => b.caller === e.from)))) { const bar: Bar = { participant: e.to, depth: st.length, from: row, to: row, caller: e.from, busy: row }; st.push(bar); bars.push(bar); diff --git a/packages/layout/test/sequence.test.ts b/packages/layout/test/sequence.test.ts index 6dcbc0e..a8fdf6c 100644 --- a/packages/layout/test/sequence.test.ts +++ b/packages/layout/test/sequence.test.ts @@ -96,6 +96,24 @@ describe('activations', () => { ]); }); + it('a repeated call from the same caller, with no replies drawn, stays in the bar it opened', () => { + // a→b, b→c three times over and never a reply: b is waiting on c throughout, but a's next request is no callback. + const calls = [0, 1, 2].flatMap((i) => [m(`r${i}`, 'a', 'b'), m(`q${i}`, 'b', 'c')]); + expect(activations(calls)).toEqual([ + { participant: 'b', depth: 0, from: 0, to: 5 }, + { participant: 'c', depth: 0, from: 1, to: 5 }, + ]); + }); + + it('a call back into a participant waiting down the chain still nests', () => { + // a→b, b→c, c→a: a's own call is still out, so c's call nests on a. + const bars = activations([m('0', 'x', 'a'), m('1', 'a', 'b'), m('2', 'b', 'c'), m('3', 'c', 'a')]); + expect(bars.filter((b) => b.participant === 'a')).toEqual([ + { participant: 'a', depth: 0, from: 0, to: 3 }, + { participant: 'a', depth: 1, from: 3, to: 3 }, + ]); + }); + it('receiving a reply keeps a bar busy', () => { // a→b; b→c; c→b (reply at row 2); d→b: b's first bar runs to row 2, then d's opens. const bars = activations([m('0', 'a', 'b'), m('1', 'b', 'c'), m('2', 'c', 'b', { kind: 'return' }), m('3', 'd', 'b')]); From 4a639f38af3185e623089d85e998ad90b1bd4d64 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:14:20 +0800 Subject: [PATCH 14/65] fix(viewer): keep a route to what lies between its ends, not loops back through them --- packages/viewer/src/explore/graph.test.ts | 28 +++++++++++++++++++---- packages/viewer/src/explore/graph.ts | 9 +++++--- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/packages/viewer/src/explore/graph.test.ts b/packages/viewer/src/explore/graph.test.ts index 5a2bc4e..a1465a5 100644 --- a/packages/viewer/src/explore/graph.test.ts +++ b/packages/viewer/src/explore/graph.test.ts @@ -62,15 +62,35 @@ describe('routeBetween', () => { // a → b → c → y, x → b, c → a (a cycle), plus a detour b → d → y const r = buildGraph(['a', 'b', 'c', 'd', 'x', 'y', 'lone'], [...edges, { id: 'bd', from: 'b', to: 'd' }, { id: 'dy', from: 'd', to: 'y' }]); - it('collects every node and edge on a directed walk (loops included), and one shortest path', () => { + it('collects every node and edge on a directed walk, and one shortest path', () => { const route = routeBetween(r, 'b', 'y')!; expect(route.reversed).toBe(false); - // a is on the loop b → c → a → b, so a walk from b to y can pass it; the edge back into b isn't lit. - expect([...route.nodes].sort()).toEqual(['a', 'b', 'c', 'd', 'y']); - expect([...route.edges].sort()).toEqual(['bc', 'bd', 'ca', 'cy', 'dy']); + // a is only on the loop b → c → a → b: it leads nowhere but back to the start, so it isn't on the way to y. + expect([...route.nodes].sort()).toEqual(['b', 'c', 'd', 'y']); + expect([...route.edges].sort()).toEqual(['bc', 'bd', 'cy', 'dy']); expect(route.steps).toHaveLength(2); }); + it('leaves out what only a loop back through an end reaches, and keeps loops along the way', () => { + // draft → review, with a retry loop review → changes → draft. + const retry = buildGraph(['draft', 'review', 'changes'], [ + { id: 'submit', from: 'draft', to: 'review' }, + { id: 'reject', from: 'review', to: 'changes' }, + { id: 'redo', from: 'changes', to: 'draft' }, + ]); + const route = routeBetween(retry, 'draft', 'review')!; + expect([...route.nodes].sort()).toEqual(['draft', 'review']); + expect([...route.edges]).toEqual(['submit']); + // a → m → b with m ⇄ n: the loop at m is on a walk from a to b. + const detour = buildGraph(['a', 'm', 'n', 'b'], [ + { id: 'am', from: 'a', to: 'm' }, + { id: 'mn', from: 'm', to: 'n' }, + { id: 'nm', from: 'n', to: 'm' }, + { id: 'mb', from: 'm', to: 'b' }, + ]); + expect([...routeBetween(detour, 'a', 'b')!.edges].sort()).toEqual(['am', 'mb', 'mn', 'nm']); + }); + it('runs the other way when only that direction has a path', () => { const route = routeBetween(r, 'y', 'x')!; expect(route.reversed).toBe(true); diff --git a/packages/viewer/src/explore/graph.ts b/packages/viewer/src/explore/graph.ts index 5af6735..06f7cb6 100644 --- a/packages/viewer/src/explore/graph.ts +++ b/packages/viewer/src/explore/graph.ts @@ -64,11 +64,13 @@ export interface Route { reversed: boolean; } -function walk(g: Graph, start: string, dir: 'out' | 'in', use: (e: string) => boolean): Set { +/** Everything reached from `start`; `stop` is reached but never walked through. */ +function walk(g: Graph, start: string, dir: 'out' | 'in', use: (e: string) => boolean, stop: string): Set { const seen = new Set([start]); const queue = [start]; while (queue.length) { const id = queue.shift()!; + if (id === stop) continue; for (const e of g[dir].get(id) ?? []) { if (!use(e)) continue; const next = dir === 'out' ? g.ends.get(e)!.to : g.ends.get(e)!.from; @@ -86,9 +88,10 @@ type Found = Omit; /** On a directed path a → b over the edges `use` allows; edges into a or out of b never count. */ function directed(g: Graph, a: string, b: string, use: (e: string) => boolean): Found | null { if (!g.out.has(a) || !g.out.has(b) || a === b) return null; - const ahead = walk(g, a, 'out', use); + // Neither walk passes through the other end: what only a loop back through a or b reaches isn't on the way. + const ahead = walk(g, a, 'out', use, b); if (!ahead.has(b)) return null; - const behind = walk(g, b, 'in', use); + const behind = walk(g, b, 'in', use, a); const nodes = new Set([...ahead].filter((n) => behind.has(n))); const edges = new Set( [...g.ends].filter(([id, e]) => use(id) && nodes.has(e.from) && nodes.has(e.to) && e.to !== a && e.from !== b).map(([id]) => id), From 48851520ace3b1e4be2dd0e3629758e3754ae7dc Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:14:42 +0800 Subject: [PATCH 15/65] fix(layout): end a sequence message on the bar it meets left of a nested activation --- packages/layout/src/sequence.ts | 15 ++++++++------- packages/layout/test/sequence.test.ts | 11 +++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/layout/src/sequence.ts b/packages/layout/src/sequence.ts index 5313cf2..0e7fe18 100644 --- a/packages/layout/src/sequence.ts +++ b/packages/layout/src/sequence.ts @@ -188,10 +188,11 @@ export function layoutSequence(draft: DiagramDraft): LaidOutDiagram { const y1 = Math.max(b.self ? y0 : rowY[b.to]! + 6, y0 + (b.self ? 18 : MIN_BAR)); return { x: round(x), y: round(y0), width: ACTIVATION.width, height: round(y1 - y0) }; }; - // A message leaves and arrives at the edge of the innermost bar open on its row. - const reach = (participant: string, row: number) => { - const open = bars.filter((b) => !b.self && b.participant === participant && b.from <= row && b.to >= row); - return open.length ? ACTIVATION.width / 2 + Math.max(...open.map((b) => b.depth)) * ACTIVATION.nest : 0; + // A message leaves and arrives at the face of the bars open on its row: nested bars step right, so the right + // face is the innermost bar's and the left face the outermost's. `side` is 1 for the right, -1 for the left. + const reach = (participant: string, row: number, side: number) => { + const depths = bars.filter((b) => !b.self && b.participant === participant && b.from <= row && b.to >= row).map((b) => b.depth); + return depths.length ? (side * ACTIVATION.width) / 2 + (side > 0 ? Math.max(...depths) : Math.min(...depths)) * ACTIVATION.nest : 0; }; const out: Record = {}; @@ -200,7 +201,7 @@ export function layoutSequence(draft: DiagramDraft): LaidOutDiagram { const y = rowY[i]!; const x = xOf(e.from); if (e.from === e.to) { - const x0 = x + reach(e.from, i); + const x0 = x + reach(e.from, i, 1); const bar = bars.find((b) => b.self === e.id)!; out[e.id] = [ { x: round(x0), y: round(y) }, @@ -213,8 +214,8 @@ export function layoutSequence(draft: DiagramDraft): LaidOutDiagram { } const tx = xOf(e.to); const dir = tx > x ? 1 : -1; - const a = x + dir * reach(e.from, i); - const b = tx - dir * reach(e.to, i); + const a = x + reach(e.from, i, dir); + const b = tx + reach(e.to, i, -dir); out[e.id] = [ { x: round(a), y: round(y) }, { x: round(b), y: round(y) }, diff --git a/packages/layout/test/sequence.test.ts b/packages/layout/test/sequence.test.ts index a8fdf6c..1ea7737 100644 --- a/packages/layout/test/sequence.test.ts +++ b/packages/layout/test/sequence.test.ts @@ -144,6 +144,17 @@ describe('layoutSequence', () => { expect(loop.at(-1)!.y).toBeGreaterThan(loop[0]!.y); }); + it('ends a message on the face of the bars it meets, on either side of nested ones', () => { + // b→c, c→b (a callback: nests on b), then b→a and a→b on b's left (async: neither opens a bar). + const out = layoutSequence(seq([m('0', 'a', 'b'), m('1', 'b', 'c'), m('2', 'c', 'b'), m('3', 'b', 'a', { kind: 'async' }), m('4', 'a', 'b', { kind: 'async' })])); + const bars = out.sequence!.activations.filter((x) => x.participant === 'b').map((x) => x.rect); + expect(bars).toHaveLength(2); + const [left, right] = [Math.min(...bars.map((r) => r.x)), Math.max(...bars.map((r) => r.x + r.width))]; + expect(out.edges['2']!.at(-1)!.x).toBe(right); + expect(out.edges['3']![0]!.x).toBe(left); + expect(out.edges['4']!.at(-1)!.x).toBe(left); + }); + it('lays out a sequence with no messages', () => { const out = layoutSequence(seq([])); expect(Object.keys(out.nodes)).toEqual(['a', 'b', 'c']); From fc61ac4b205ed3925efe92947735ac20ecebe781 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:15:17 +0800 Subject: [PATCH 16/65] fix(cli): report serve's port and folder failures as plain errors, not internal ones --- packages/cli/src/cli.ts | 6 ++---- packages/cli/src/commands.ts | 2 +- packages/cli/src/serve.ts | 15 ++++++++++----- packages/cli/test/serve.test.ts | 9 +++++++++ 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 3783a65..c371a67 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs'; import { parseArgs } from 'node:util'; -import { deliverCommand, validateCommand, type CommandResult } from './commands'; +import { deliverCommand, failure, validateCommand, type CommandResult } from './commands'; import { openInBrowser } from './open'; import { serve } from './serve'; import { styleFor } from './style'; @@ -90,9 +90,7 @@ async function run(argv: string[]): Promise { return { code: 0, stdout: '', stderr: '' }; } -const result = await run(process.argv.slice(2)).catch( - (e: unknown): CommandResult => ({ code: 2, stdout: '', stderr: `stackmap: internal error: ${(e as Error).message}\n` }), -); +const result = await run(process.argv.slice(2)).catch(failure); process.stdout.write(result.stdout); process.stderr.write(result.stderr); process.exitCode = result.code; diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index fbfd87b..acc9450 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -37,7 +37,7 @@ export function validateFile(path: string): ValidationResult { } // Exit 1 means "the diagram has errors" to the agent loop, so every other failure must be exit 2. -const failure = (e: unknown): CommandResult => ({ +export const failure = (e: unknown): CommandResult => ({ code: 2, stdout: '', stderr: `stackmap: ${e instanceof CliError ? '' : 'internal error: '}${(e as Error).message}\n`, diff --git a/packages/cli/src/serve.ts b/packages/cli/src/serve.ts index 4255a2f..b78adff 100644 --- a/packages/cli/src/serve.ts +++ b/packages/cli/src/serve.ts @@ -144,11 +144,16 @@ export async function serve(path: string, { template, port = 4400, log = () => { // Editors save by writing a temp file and renaming it over the original, so watch the directory. // Watching starts before the first build, so a save during that layout is not lost. let timer: NodeJS.Timeout | undefined; - const watcher: FSWatcher = watch(dirname(path), (_event, name) => { - if (name !== null && name !== basename(path)) return; - clearTimeout(timer); - timer = setTimeout(schedule, DEBOUNCE_MS); - }); + let watcher: FSWatcher; + try { + watcher = watch(dirname(path), (_event, name) => { + if (name !== null && name !== basename(path)) return; + clearTimeout(timer); + timer = setTimeout(schedule, DEBOUNCE_MS); + }); + } catch (e) { + throw new CliError(`cannot watch ${dirname(path)}: ${(e as NodeJS.ErrnoException).code ?? (e as Error).message}`); + } // e.g. the directory was deleted (EPERM on Windows): report it instead of crashing the server. watcher.on('error', (e) => publish({ ok: false, diagnostics: [diagnostic('io/watch-failed', `stopped watching: ${e.message}`, 'restart stackmap serve', path)] }), diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index 7fcaa0f..8a59380 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -6,6 +6,7 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { commerceApi } from '@stackmap/core/samples'; import { EMPTY_DATA_BLOCK } from '../src/embed'; +import { CliError } from '../src/io'; import { isLocalHost, LIVE_BLOCK_ID, serve, type ServeHandle } from '../src/serve'; const TEMPLATE = `stackmap
${EMPTY_DATA_BLOCK}`; @@ -194,6 +195,14 @@ describe('serve', () => { expect(lines).toEqual(['laying out 61 nodes and 60 connections; a diagram this size can take a while', '✓ d.json ready']); }); + it('fails with a plain message, and builds nothing, when the folder to watch is missing', async () => { + const lines: string[] = []; + const starting = serve(join(dir, 'nope', 'x.json'), { template: TEMPLATE, port: 0, log: (l) => lines.push(l) }); + await expect(starting).rejects.toThrow(CliError); + await expect(starting).rejects.toThrow(/^cannot watch .+nope: ENOENT$/); + expect(lines).toEqual([]); + }); + it('starts on an invalid file with the bare live template', async () => { write({ kind: 'architecture' }); server = await serve(file, { template: TEMPLATE, port: 0 }); From 541716040814d2c68521cd386ffe9eca642ca379 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:15:34 +0800 Subject: [PATCH 17/65] fix(viewer): refit the presentation once full screen has resized the stage --- packages/viewer/e2e/present.spec.ts | 43 ++++++++++++++++++++++ packages/viewer/src/chrome/ViewerShell.tsx | 5 ++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/viewer/e2e/present.spec.ts b/packages/viewer/e2e/present.spec.ts index aaf024d..4ddd40e 100644 --- a/packages/viewer/e2e/present.spec.ts +++ b/packages/viewer/e2e/present.spec.ts @@ -94,3 +94,46 @@ test('in a presentation, Space presses the focused button and M leaves the radar await expect(bar).toBeHidden(); await expect(page.getByRole('img', { name: 'Minimap' })).toBeHidden(); }); + +test('the presentation refits once full screen has resized the stage, entering and leaving', async ({ page }) => { + // Headless Chromium never resizes for full screen: stand in for it, with the resize landing after the request. + await page.addInitScript(() => { + let current: Element | null = null; + const land = (el: Element | null) => { + current = el; + document.dispatchEvent(new Event('fullscreenchange')); + }; + Object.defineProperty(document, 'fullscreenElement', { get: () => current }); + Element.prototype.requestFullscreen = function () { + (window as unknown as { landFullscreen: () => void }).landFullscreen = () => land(this); + return Promise.resolve(); + }; + document.exitFullscreen = () => { + (window as unknown as { landFullscreen: () => void }).landFullscreen = () => land(null); + return Promise.resolve(); + }; + }); + const offCentre = async () => { + await page.waitForTimeout(250); + return page.evaluate(() => { + const stage = document.querySelector('.sm-stage')!.getBoundingClientRect(); + const cards = [...document.querySelectorAll('.sm-card')].map((c) => c.getBoundingClientRect()); + const left = Math.min(...cards.map((c) => c.left)); + const right = Math.max(...cards.map((c) => c.right)); + return Math.abs((left + right) / 2 - (stage.left + stage.width / 2)); + }); + }; + const land = () => page.evaluate(() => (window as unknown as { landFullscreen: () => void }).landFullscreen()); + await page.goto('/?page=sample'); + await expect(page.locator('.sm-card')).toHaveCount(6); + await page.keyboard.press('f'); + await page.waitForTimeout(250); + await page.setViewportSize({ width: 1900, height: 1100 }); + await land(); + expect(await offCentre()).toBeLessThan(2); + await page.keyboard.press('Escape'); + await page.waitForTimeout(250); + await page.setViewportSize({ width: 1440, height: 960 }); + await land(); + expect(await offCentre()).toBeLessThan(2); +}); diff --git a/packages/viewer/src/chrome/ViewerShell.tsx b/packages/viewer/src/chrome/ViewerShell.tsx index 680f55d..b1a0d9a 100644 --- a/packages/viewer/src/chrome/ViewerShell.tsx +++ b/packages/viewer/src/chrome/ViewerShell.tsx @@ -45,6 +45,8 @@ export function ViewerShell({ const [presenting, setPresenting] = useState(false); const presentingRef = useRef(false); presentingRef.current = presenting; + // Full screen lands frames after the presentation toggles, and resizes the stage a second time. + const [fullscreen, setFullscreen] = useState(false); const present = useCallback((on: boolean) => { presentingRef.current = on; setPresenting(on); @@ -72,6 +74,7 @@ export function ViewerShell({ }; // Leaving full screen (Esc in the browser's own handling) ends the presentation too. const onFullscreen = () => { + setFullscreen(!!document.fullscreenElement); if (!document.fullscreenElement) setPresenting(false); // A request that resolved after the presentation already ended (a quick F, F): leave full screen again. else if (!presentingRef.current) void document.exitFullscreen().catch(() => {}); @@ -124,7 +127,7 @@ export function ViewerShell({ className={`@container/stage relative min-w-0 flex-1 overflow-hidden bg-stage ${presenting ? '' : 'rounded-[20px]'}`} style={presenting ? undefined : { boxShadow: 'inset 0 0 0 1px var(--sm-panel-border)' }} > - + {toolbarHidden ? (
From 9fcf8e1f8164bf1321b95af2391bcdd7bc07e477 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:15:42 +0800 Subject: [PATCH 18/65] docs(site): reserve the walkthrough's runway in CSS so a hash or a restored scroll lands where it stays --- site/components/landing/How.tsx | 12 +++--------- site/components/landing/landing.css | 8 ++++++++ site/e2e/smoke.spec.ts | 24 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/site/components/landing/How.tsx b/site/components/landing/How.tsx index e2ed4d7..919e1ce 100644 --- a/site/components/landing/How.tsx +++ b/site/components/landing/How.tsx @@ -98,7 +98,6 @@ export function How({ demo, receipt, repair }: { demo: LaidOutDiagram; receipt: const [shown, setShown] = useState(0); const runway = useRef(0); const stickTop = useRef(0); - const arrived = useRef(false); useEffect(() => { const mm = gsap.matchMedia(); @@ -106,18 +105,14 @@ export function How({ demo, receipt, repair }: { demo: LaidOutDiagram; receipt: const p = pin.current!; const s = stick.current!; const layout = () => { - runway.current = Math.round(innerHeight * 1.6); + // The runway is CSS (.how-pin::after), so the page is its final height before this runs and a hash or a + // restored scroll position lands where it stays. + runway.current = p.offsetHeight - s.offsetHeight; stickTop.current = Math.max(88, Math.round((innerHeight - s.offsetHeight) / 2 + 24)); - p.style.height = `${s.offsetHeight + runway.current}px`; s.style.position = 'sticky'; s.style.top = `${stickTop.current}px`; }; layout(); - // The runway arrives after the browser (or Next, from another page) has scrolled to the hash, pushing a - // target below it a runway further down: go there again. - const target = !arrived.current && location.hash && document.getElementById(decodeURIComponent(location.hash.slice(1))); - arrived.current = true; - if (target && p.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING) target.scrollIntoView(); setPinned(true); const draw = (progress: number) => { if (fill.current) fill.current.style.transform = `scaleX(${progress})`; @@ -136,7 +131,6 @@ export function How({ demo, receipt, repair }: { demo: LaidOutDiagram; receipt: draw(st.progress); return () => { st.kill(); - p.style.height = ''; s.style.position = ''; s.style.top = ''; if (fill.current) fill.current.style.transform = ''; diff --git a/site/components/landing/landing.css b/site/components/landing/landing.css index 1abae8b..675892d 100644 --- a/site/components/landing/landing.css +++ b/site/components/landing/landing.css @@ -179,6 +179,14 @@ .how-stick { position: relative; } +/* The pinned walkthrough's runway (How.tsx), reserved before script runs so nothing below it moves on hydration. */ +@media (prefers-reduced-motion: no-preference) and (min-width: 1024px) { + .js .how-pin::after { + content: ''; + display: block; + height: 160vh; + } +} .how-frame { display: flex; flex-direction: column; diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index df1a341..ec50ffc 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -257,3 +257,27 @@ test('on a phone the nav menu opens the site links and closes on Escape', async await expect(page.getByRole('button', { name: 'Menu' })).toHaveAttribute('aria-expanded', 'false'); await page.close(); }); + +test('with the walkthrough pinned, a hash lands on its section, a reload keeps its place and a broken hash is harmless', async ({ browser }) => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, reducedMotion: 'no-preference' }); + const errors = collectErrors(page); + const top = (id: string) => page.evaluate((id) => Math.abs(document.getElementById(id)!.getBoundingClientRect().top), id); + await page.goto('/#50%'); + await expect(page.locator('.how-pin')).toHaveAttribute('data-live', 'true'); + expect(errors).toEqual([]); + // From another page, loaded and then through the router: both end below the runway, on the section. + await page.goto('/docs'); + await page.goto('/#install'); + await expect.poll(() => top('install')).toBeLessThan(140); + await page.goto('/docs'); + await page.getByRole('link', { name: 'Install', exact: true }).first().click(); + await expect(page).toHaveURL(/\/#install$/); + await expect.poll(() => top('install')).toBeLessThan(140); + // The address still names #install, but the reader has moved on: a reload restores where they were. + await page.evaluate(() => scrollTo({ top: 300, behavior: 'instant' })); + await page.waitForTimeout(300); + await page.reload(); + await expect(page.locator('.how-pin')).toHaveAttribute('data-live', 'true'); + expect(Math.abs((await page.evaluate(() => scrollY)) - 300)).toBeLessThan(60); + await page.close(); +}); From 09684ec7caf3654dd994f901b92329e7fa4cb37d Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:15:58 +0800 Subject: [PATCH 19/65] fix(layout): size an empty group's frame to hold its title --- packages/layout/src/index.ts | 10 +++++++++- packages/layout/test/layout.test.ts | 9 +++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/layout/src/index.ts b/packages/layout/src/index.ts index 062f997..7dec0da 100644 --- a/packages/layout/src/index.ts +++ b/packages/layout/src/index.ts @@ -5,7 +5,7 @@ import { Worker as Thread } from 'node:worker_threads'; import ElkApi from 'elkjs/lib/elk-api.js'; import ElkBundled from 'elkjs/lib/elk.bundled.js'; import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk-api'; -import { cardSize, isLaneKind, round, usesCompactCards, type DiagramDraft, type Direction, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; +import { cardSize, isLaneKind, measureText, round, usesCompactCards, type DiagramDraft, type DiagramGroup, type Direction, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; import { runChild, threadPort } from './elk-io'; import { placeLabels } from './labels'; import { layoutLanes } from './lanes'; @@ -33,6 +33,8 @@ export const isLarge = (draft: DiagramDraft) => draft.nodes.length > RETRY_LIMIT const LAYER_GAP = 'elk.layered.spacing.nodeNodeBetweenLayers'; const EDGE_RUN = 'elk.layered.spacing.edgeNodeBetweenLayers'; const GROUP_PREFIX = 'group:'; +/** A group title's width from its frame's left edge, as the viewer draws it: 12.5px medium, 20px in, a shield on a trust boundary. */ +const titleWidth = (g: DiagramGroup) => 20 + (g.tone === 'security' ? 19 : 0) + Math.ceil(measureText(g.label, 'sans500', 12.5)) + 8; /** ELK recurses along each connected run of the graph: a few hundred connected nodes overflow Node's ~1 MB stack. */ const ELK_STACK_MB = 256; @@ -267,6 +269,12 @@ export async function layoutDiagram(draft: DiagramDraft): Promise { } }); + it('draws a group with nothing in it as a frame that holds its title', async () => { + const out = await layoutDiagram(draft({ groups: [{ id: 'g', label: 'Empty' }, { id: 'h', label: 'Full' }], nodes: [node('a', { group: 'h' }), node('b')] })); + const g = out.groups.g!; + expect(g.width).toBeGreaterThan(60); + expect(g.height).toBeGreaterThanOrEqual(GROUP_LABEL_BAND); + const overlap = (a: Rect, b: Rect) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height; + for (const r of [out.groups.h!, out.nodes.b!]) expect(overlap(g, r)).toBe(false); + }); + it('top-aligns the cards of a row, whatever their heights', async () => { // In the hub, feed (a reply's target) and finisher are shorter than their row-mates and used to be centred on them. const out = await layoutDiagram(STRESS['hub-down']!); From ddac338d35256303a2f06f33e64e36156cdf1719 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:16:11 +0800 Subject: [PATCH 20/65] fix(cli): reject an empty or non-numeric --port instead of serving on a random one --- packages/cli/src/cli.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index c371a67..33f9302 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -81,8 +81,9 @@ async function run(argv: string[]): Promise { return signed(command, await deliverCommand(file, { template, out: values.out, style, open, progress })); } - const port = values.port === undefined ? 4400 : Number(values.port); - if (!Number.isInteger(port) || port < 0 || port > 65535) return usage(`--port must be 0-65535, got "${values.port}"`); + // Digits only: Number('') and Number(' ') are 0, which would silently mean "any free port". + const port = values.port === undefined ? 4400 : /^\d+$/.test(values.port) ? Number(values.port) : NaN; + if (!(port >= 0 && port <= 65535)) return usage(`--port must be 0-65535, got "${values.port}"`); const server = await serve(file, { template, port, log: (line) => process.stderr.write(`${line}\n`) }); process.stdout.write(sign(command, `serving ${style.path(server.url)} · watching ${file} · Ctrl-C to stop\n`)); await new Promise((resolve) => process.once('SIGINT', resolve)); From d540987da9ece257128aaa380fd6f5312ccd7aef Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:16:29 +0800 Subject: [PATCH 21/65] fix(cli): refuse to overwrite the input when -o names it in a different case --- packages/cli/src/commands.ts | 3 ++- packages/cli/test/commands.test.ts | 12 +++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index acc9450..25ef5b9 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -45,7 +45,8 @@ export const failure = (e: unknown): CommandResult => ({ const real = (p: string) => { try { - return realpathSync(p); + // .native also resolves the name to its case on disk: on macOS and Windows `D.JSON` can be `d.json`. + return realpathSync.native(p); } catch { return resolve(p); } diff --git a/packages/cli/test/commands.test.ts b/packages/cli/test/commands.test.ts index 9cde541..a00721e 100644 --- a/packages/cli/test/commands.test.ts +++ b/packages/cli/test/commands.test.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto'; -import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { beforeEach, describe, expect, it } from 'vitest'; @@ -160,6 +160,16 @@ describe('deliver', () => { expect(JSON.parse(readFileSync(json, 'utf8'))).toEqual(commerceApi); }); + it('refuses an output that names its input in another case, where the filesystem ignores case', async () => { + const json = file('case.json', commerceApi); + const upper = join(dir, 'CASE.JSON'); + if (!existsSync(upper)) return; // a case-sensitive filesystem: that is a different file + const r = await deliverCommand(json, { template: TEMPLATE, out: upper }); + expect(r.code).toBe(2); + expect(r.stderr).toMatch(/^stackmap: refusing to overwrite the input/); + expect(JSON.parse(readFileSync(json, 'utf8'))).toEqual(commerceApi); + }); + it('reports an unexpected failure as an internal error with exit 2, never a stack trace', async () => { const r = await deliverCommand(file('d.json', commerceApi), { template: 'no data block' }); expect(r.code).toBe(2); From 0d588903298db0fbb7efa7578e7b6f3012e25cba Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:16:37 +0800 Subject: [PATCH 22/65] =?UTF-8?q?fix(viewer):=20leave=20=E2=8C=98/Ctrl/Alt?= =?UTF-8?q?=20key=20combinations=20on=20the=20canvas=20to=20the=20browser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../viewer/src/canvas/DiagramCanvas.test.tsx | 17 +++++++++++++++++ packages/viewer/src/canvas/DiagramCanvas.tsx | 2 ++ packages/viewer/src/canvas/SceneLayers.tsx | 2 +- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/viewer/src/canvas/DiagramCanvas.test.tsx b/packages/viewer/src/canvas/DiagramCanvas.test.tsx index 3352e73..b7080c5 100644 --- a/packages/viewer/src/canvas/DiagramCanvas.test.tsx +++ b/packages/viewer/src/canvas/DiagramCanvas.test.tsx @@ -47,4 +47,21 @@ describe('DiagramCanvas', () => { expect([emphasis('orders'), emphasis('sessions')]).toEqual(['focus', 'dim']); expect(nodeCardRenders).not.toHaveBeenCalled(); }); + + it('leaves modified keys to the browser: ⌘/Ctrl + and 0 zoom the page, Alt+← goes back', () => { + const { container } = render( + + + , + ); + // fireEvent returns false when the handler prevented the default. + for (const target of [container.querySelector('.sm-stage')!, container.querySelector('.sm-card[data-card-id="orders"]')!]) { + expect(fireEvent.keyDown(target, { key: 'ArrowLeft' })).toBe(false); + expect(fireEvent.keyDown(target, { key: '=', metaKey: true })).toBe(true); + expect(fireEvent.keyDown(target, { key: '-', ctrlKey: true })).toBe(true); + expect(fireEvent.keyDown(target, { key: '0', ctrlKey: true })).toBe(true); + expect(fireEvent.keyDown(target, { key: 'ArrowLeft', altKey: true })).toBe(true); + expect(fireEvent.keyDown(target, { key: 'ArrowLeft', metaKey: true })).toBe(true); + } + }); }); diff --git a/packages/viewer/src/canvas/DiagramCanvas.tsx b/packages/viewer/src/canvas/DiagramCanvas.tsx index fdca39d..3ab13a8 100644 --- a/packages/viewer/src/canvas/DiagramCanvas.tsx +++ b/packages/viewer/src/canvas/DiagramCanvas.tsx @@ -172,6 +172,8 @@ export function DiagramCanvas({ // Keys when the stage itself has focus (cards handle their own and stop propagation). const onKeyDown = (e: KeyboardEvent) => { + // ⌘/Ctrl with + - 0 is the browser's own zoom, Alt/⌘ with an arrow its history. + if (e.metaKey || e.ctrlKey || e.altKey) return; const pan: Record = { ArrowUp: [0, PAN_STEP], ArrowDown: [0, -PAN_STEP], diff --git a/packages/viewer/src/canvas/SceneLayers.tsx b/packages/viewer/src/canvas/SceneLayers.tsx index d190f4d..8daea32 100644 --- a/packages/viewer/src/canvas/SceneLayers.tsx +++ b/packages/viewer/src/canvas/SceneLayers.tsx @@ -165,7 +165,7 @@ const Card = memo(function Card({ const camera = useCamera(); const accent = { '--sm-handle': `var(--sm-${node.type}-accent)` } as CSSProperties; const onKeyDown = (e: KeyboardEvent) => { - if (e.target !== e.currentTarget) return; + if (e.target !== e.currentTarget || e.metaKey || e.ctrlKey || e.altKey) return; const dir = ARROWS[e.key]; if (dir) { const next = neighbourInDirection(rects, node.id, dir); From fdddbf745edbfd9f6379117708334a59bea24a2f Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:16:55 +0800 Subject: [PATCH 23/65] fix(layout): keep edge labels off a group title wider than 160px --- packages/layout/src/index.ts | 3 ++- packages/layout/src/labels.ts | 6 ++++-- packages/layout/src/lanes.ts | 3 ++- packages/layout/test/labels.test.ts | 11 +++++++++++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/layout/src/index.ts b/packages/layout/src/index.ts index 7dec0da..2cb5ac0 100644 --- a/packages/layout/src/index.ts +++ b/packages/layout/src/index.ts @@ -347,7 +347,8 @@ export async function layoutDiagram(draft: DiagramDraft): Promise placeLabels(draft.edges, l.edges, Object.values(l.nodes), !compact, Object.values(l.groups).map((rect) => ({ rect, band: GROUP_LABEL_BAND }))); + const frames = (l: LaidOutDiagram) => (draft.groups ?? []).map((g) => ({ rect: l.groups[g.id]!, band: GROUP_LABEL_BAND, title: titleWidth(g) })); + const place = (l: LaidOutDiagram) => placeLabels(draft.edges, l.edges, Object.values(l.nodes), !compact, frames(l)); let spots = place(laid); // A label that found no room to sit widens the layer gaps: compact layouts start tight on purpose, and a full // layout's gap can still be narrower than a label beside a branch. Two ways to make room are tried: wider gaps, diff --git a/packages/layout/src/labels.ts b/packages/layout/src/labels.ts index 9325122..bdecbdd 100644 --- a/packages/layout/src/labels.ts +++ b/packages/layout/src/labels.ts @@ -60,10 +60,12 @@ export interface LabelFrame { rect: Rect; /** height of the title band along the frame's top */ band: number; + /** the title's width from the frame's left edge, when it is longer than the usual strip */ + title?: number; } /** Where along its route a label should sit: by the target on a fan-out, by the source on a fan-in. */ type Bias = 'start' | 'mid' | 'end'; -// The frame title's box: the viewer's title is short, so a fixed strip from the corner covers it. +// The frame title's box: most titles are short, so a strip from the corner covers them; a longer one says so. const TITLE = { width: 160, height: 28 }; /** Frame borders as closed polylines, and the strips their titles take. */ @@ -76,7 +78,7 @@ function frameObstacles(frames: LabelFrame[]): { lines: Point[][]; titles: Rect[ { x: r.x, y: r.y + r.height }, { x: r.x, y: r.y }, ]), - titles: frames.map(({ rect: r, band }) => ({ x: r.x, y: r.y, width: Math.min(r.width, TITLE.width), height: Math.max(band, TITLE.height) })), + titles: frames.map(({ rect: r, band, title = 0 }) => ({ x: r.x, y: r.y, width: Math.min(r.width, Math.max(title, TITLE.width)), height: Math.max(band, TITLE.height) })), }; } diff --git a/packages/layout/src/lanes.ts b/packages/layout/src/lanes.ts index 58a6b8f..3b5ba23 100644 --- a/packages/layout/src/lanes.ts +++ b/packages/layout/src/lanes.ts @@ -180,7 +180,8 @@ export function layoutLanes(draft: DiagramDraft): LaidOutDiagram { if (routed[e.id]) edges[e.id] = routed[e.id]!.map((p) => ({ x: round(p.x), y: round(p.y) })); } - const { labels } = placeLabels(draft.edges, edges, Object.values(rects), false, Object.values(groupRects).map((rect) => ({ rect, band: GROUP_LABEL }))); + const frames = (draft.groups ?? []).flatMap((g) => (groupRects[g.id] ? [{ rect: groupRects[g.id]!, band: GROUP_LABEL, title: labelWidth(g.label) + 24 }] : [])); + const { labels } = placeLabels(draft.edges, edges, Object.values(rects), false, frames); const height = y - LANE_GAP + PAD; return { diff --git a/packages/layout/test/labels.test.ts b/packages/layout/test/labels.test.ts index 08aab8c..1671293 100644 --- a/packages/layout/test/labels.test.ts +++ b/packages/layout/test/labels.test.ts @@ -127,6 +127,17 @@ describe('labels beside a trunk', () => { }); }); +describe('labels by a group frame', () => { + it("stay off a title longer than the frame's default strip", () => { + // The run crosses the title band; the route midpoint sits past 160px but still under a 300px title. + const a = [{ x: 100, y: 24 }, { x: 440, y: 24 }]; + const frame = { rect: { x: -40, y: -40, width: 700, height: 300 }, band: 100 }; + const pill = (labels: Record) => labels.a!.x - labelWidth('ok') / 2; + expect(pill(placeLabels([{ id: 'a', label: 'ok' }], { a }, [], false, [frame]).labels)).toBeLessThan(300); + expect(pill(placeLabels([{ id: 'a', label: 'ok' }], { a }, [], false, [{ ...frame, title: 340 }]).labels)).toBeGreaterThanOrEqual(300); + }); +}); + describe('labels on a fan-out', () => { it('sit on the far half of each edge, by the card they name, not by the shared source', async () => { for (const name of ['hub-down', 'hub-right'] as const) { From 4a7f218264f3c79b52715fe6ce3727614ed751f6 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:16:56 +0800 Subject: [PATCH 24/65] fix(core): budget a row label against its value as rendered, so padded values raise no false card-fit error --- packages/core/src/card-text.ts | 5 ++++- packages/core/test/card-text.test.ts | 6 ++++++ packages/schema/src/rules/card-fit.ts | 5 ++--- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/core/src/card-text.ts b/packages/core/src/card-text.ts index a6fc2a2..c74f7ba 100644 --- a/packages/core/src/card-text.ts +++ b/packages/core/src/card-text.ts @@ -27,6 +27,9 @@ const C_TILE = 28; const C_GAP = 10; const C_TEXT = COMPACT.width - 2 * C_PAD - C_TILE - C_GAP; // 114 +/** Text as a card shows it: white-space: nowrap collapses runs of whitespace and trims the ends. */ +export const shownText = (text: string) => text.replace(/\s+/g, ' ').trim(); + export function cardTextSlots(card: CardData, variant: CardVariant = 'full'): TextSlot[] { const slots: TextSlot[] = []; const add = (path: string, text: string | undefined, face: FontFace, size: number, maxWidth: number) => { @@ -48,7 +51,7 @@ export function cardTextSlots(card: CardData, variant: CardVariant = 'full'): Te const face: FontFace = row.mono ? 'mono400' : 'sans400'; const valueMax = INNER * ROW_VALUE_MAX; // The value is shrink-0 up to its cap, so the label gets whatever the rendered value leaves. - const valueWidth = Math.min(measureText(row.value, face, 12), valueMax); + const valueWidth = Math.min(measureText(shownText(row.value), face, 12), valueMax); add(`/rows/${i}/label`, row.label, 'sans400', 12, INNER - GAP - valueWidth); add(`/rows/${i}/value`, row.value, face, 12, valueMax); }); diff --git a/packages/core/test/card-text.test.ts b/packages/core/test/card-text.test.ts index 868f763..e8195a4 100644 --- a/packages/core/test/card-text.test.ts +++ b/packages/core/test/card-text.test.ts @@ -20,6 +20,12 @@ describe('cardTextSlots', () => { expect(slot(card, '/rows/0/label')!.maxWidth).toBeCloseTo(248 - 12 - measureText(value, 'mono400', 12), 6); }); + it('budgets a row label against the value as rendered: whitespace collapsed and trimmed', () => { + const card = { title: 't', rows: [{ label: 'Port', value: ' x ' }, { label: 'Port', value: 'a b' }] }; + expect(slot(card, '/rows/0/label')!.maxWidth).toBeCloseTo(248 - 12 - measureText('x', 'sans400', 12), 6); + expect(slot(card, '/rows/1/label')!.maxWidth).toBeCloseTo(248 - 12 - measureText('a b', 'sans400', 12), 6); + }); + it('a long row value leaves the label its floor, not less', () => { const card = { title: 't', rows: [{ label: 'Connection', value: 'x'.repeat(200) }] }; expect(slot(card, '/rows/0/label')!.maxWidth).toBeCloseTo(248 - 12 - 248 * 0.55, 6); diff --git a/packages/schema/src/rules/card-fit.ts b/packages/schema/src/rules/card-fit.ts index 59f9f9f..24af124 100644 --- a/packages/schema/src/rules/card-fit.ts +++ b/packages/schema/src/rules/card-fit.ts @@ -1,4 +1,4 @@ -import { cardTextSlots, measureText, usesCompactCards, type DiagramDraft } from '@stackmap/core'; +import { cardTextSlots, measureText, shownText, usesCompactCards, type DiagramDraft } from '@stackmap/core'; import type { Diagnostic } from '../diagnostics'; const round = (n: number) => Math.round(n * 10) / 10; @@ -9,8 +9,7 @@ export function cardFitDiagnostics(d: DiagramDraft): Diagnostic[] { const variant = usesCompactCards(d) ? 'compact' : 'full'; d.nodes.forEach((n, i) => { for (const slot of cardTextSlots(n.card, variant)) { - // Cards render with white-space: nowrap, which collapses runs of whitespace and trims the ends. - const shown = slot.text.replace(/\s+/g, ' ').trim(); + const shown = shownText(slot.text); const width = measureText(shown, slot.face, slot.size); if (width <= slot.maxWidth) continue; const chars = [...shown]; From e107004f96e4c555c7b6fb7058153b8610aad4a6 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:25 +0800 Subject: [PATCH 25/65] fix(viewer): show a card's link in the inspector when the card has nothing else --- packages/viewer/src/chrome/Inspector.tsx | 39 ++++++++++--------- .../viewer/src/chrome/ViewerShell.test.tsx | 13 +++++++ 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/packages/viewer/src/chrome/Inspector.tsx b/packages/viewer/src/chrome/Inspector.tsx index 5c174e7..4d627d5 100644 --- a/packages/viewer/src/chrome/Inspector.tsx +++ b/packages/viewer/src/chrome/Inspector.tsx @@ -166,6 +166,7 @@ function NodeDetail({ node, toggle }: { node: DiagramNode; toggle: ReactNode }) const { card } = node; const lane = node.lane ? draft.lanes?.find((l) => l.id === node.lane)?.label : undefined; const H = useHeading(0); + const details = !!(card.rows?.length || card.stats?.length || card.footer); return ( <>
@@ -198,26 +199,28 @@ function NodeDetail({ node, toggle }: { node: DiagramNode; toggle: ReactNode }) {lane && {lane}}

)} - {(card.rows?.length || card.stats?.length || card.footer) && ( + {(details || card.cta?.href) && (
-
- {card.rows?.map((r, i) => ( -
-
{r.label}
-
{r.value}
-
- ))} - {card.stats?.map((s, i) => ( -
-
{s.label}
-
{s.value}
-
- ))} - {card.stats?.length && card.statsNote ?

{card.statsNote}

: null} - {[card.footer?.left, card.footer?.right].map((f, i) => (f ?

{f.text}

: null))} -
+ {details && ( +
+ {card.rows?.map((r, i) => ( +
+
{r.label}
+
{r.value}
+
+ ))} + {card.stats?.map((s, i) => ( +
+
{s.label}
+
{s.value}
+
+ ))} + {card.stats?.length && card.statsNote ?

{card.statsNote}

: null} + {[card.footer?.left, card.footer?.right].map((f, i) => (f ?

{f.text}

: null))} +
+ )} {card.cta?.href && ( - + {card.cta.label} diff --git a/packages/viewer/src/chrome/ViewerShell.test.tsx b/packages/viewer/src/chrome/ViewerShell.test.tsx index 11d05a1..31eb9bd 100644 --- a/packages/viewer/src/chrome/ViewerShell.test.tsx +++ b/packages/viewer/src/chrome/ViewerShell.test.tsx @@ -85,6 +85,19 @@ describe('ViewerShell', () => { expect(screen.queryByRole('button', { name: 'Search nodes (/)' })).toBeNull(); }); + it('a card with nothing but a link still has it in the inspector, where the keyboard reaches it', () => { + const draft = { + ...commerceApiLayout.draft, + nodes: commerceApiLayout.draft.nodes.map((n) => + n.id === 'orders' ? { ...n, card: { title: n.card.title, cta: { label: 'Open runbook', href: 'https://example.com/runbook' } } } : n, + ), + }; + render( {}} />); + fireEvent.click(screen.getByRole('button', { name: 'Orders, Database' })); + const link = within(screen.getByRole('complementary', { name: 'Inspector' })).getByRole('link', { name: 'Open runbook' }); + expect(link).toHaveAttribute('href', 'https://example.com/runbook'); + }); + it('has no editor controls', () => { render( {}} />); for (const name of [/add/i, /undo/i, /redo/i, /lock/i]) expect(screen.queryByRole('button', { name })).toBeNull(); From 98ec4d4afd8113f792eae071e29a70df3c1a4e66 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:30 +0800 Subject: [PATCH 26/65] docs(site): leave what is already on screen alone when the reveals take over --- site/app/site.css | 2 +- site/components/landing/Reveals.tsx | 3 ++- site/e2e/smoke.spec.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/site/app/site.css b/site/app/site.css index a327a4b..661ef6c 100644 --- a/site/app/site.css +++ b/site/app/site.css @@ -286,7 +286,7 @@ body { } } -/* Reveals: [data-reveal] is hidden only once GSAP has taken it (lib/reveal.ts); the server markup is the resting frame. */ +/* Reveals: [data-reveal] is hidden only once GSAP has taken it (components/landing/Reveals.tsx); the server markup is the resting frame. */ /* Nav */ .nav { diff --git a/site/components/landing/Reveals.tsx b/site/components/landing/Reveals.tsx index 12e26dc..1261e9b 100644 --- a/site/components/landing/Reveals.tsx +++ b/site/components/landing/Reveals.tsx @@ -11,7 +11,8 @@ export function Reveals() { useEffect(() => { const mm = gsap.matchMedia(); mm.add('(prefers-reduced-motion: no-preference)', () => { - const els = gsap.utils.toArray('[data-reveal]'); + // Only what is still below the fold: hiding what the server already painted on screen would blank it. + const els = gsap.utils.toArray('[data-reveal]').filter((el) => el.getBoundingClientRect().top > innerHeight * 0.92); gsap.set(els, { autoAlpha: 0, y: 12 }); ScrollTrigger.batch(els, { start: 'top 92%', diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index ec50ffc..30499f9 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -281,3 +281,31 @@ test('with the walkthrough pinned, a hash lands on its section, a reload keeps i expect(Math.abs((await page.evaluate(() => scrollY)) - 300)).toBeLessThan(60); await page.close(); }); + +test('a reload part-way down the landing never blanks what is already on screen', async ({ browser }) => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, reducedMotion: 'no-preference' }); + // The lowest opacity any reveal on screen ever has, sampled every frame from before the page's own script. + await page.addInitScript(() => { + const w = window as unknown as { lowest: number }; + w.lowest = 1; + const tick = () => { + for (const el of document.querySelectorAll('[data-reveal]')) { + const r = el.getBoundingClientRect(); + const s = getComputedStyle(el); + if (r.bottom > 0 && r.top < innerHeight * 0.9) w.lowest = Math.min(w.lowest, s.visibility === 'hidden' ? 0 : Number(s.opacity)); + } + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + await page.goto('/'); + await expect(page.locator('.how-pin')).toHaveAttribute('data-live', 'true'); + await page.evaluate(() => scrollTo({ top: document.getElementById('how')!.getBoundingClientRect().top + scrollY - 100, behavior: 'instant' })); + await page.waitForTimeout(1200); + await page.reload(); + await expect(page.locator('.how-pin')).toHaveAttribute('data-live', 'true'); + await page.waitForTimeout(800); + expect(await page.evaluate(() => scrollY)).toBeGreaterThan(500); + expect(await page.evaluate(() => (window as unknown as { lowest: number }).lowest)).toBe(1); + await page.close(); +}); From 22af1d30575ddd87cd236f1e622674f5bede5939 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:30 +0800 Subject: [PATCH 27/65] docs(site): light the edge when its JSON lines are pointed at in a linked figure --- site/components/docs/docs.css | 4 ++-- site/e2e/smoke.spec.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/site/components/docs/docs.css b/site/components/docs/docs.css index 6f6cb35..535b0f8 100644 --- a/site/components/docs/docs.css +++ b/site/components/docs/docs.css @@ -984,8 +984,8 @@ .lf [data-frame-id][data-lk] { border-color: var(--sm-text) !important; } -.lf [data-edge-id][data-lk] path { - stroke: var(--sm-text); +.lf path[data-edge-id][data-lk] { + stroke: var(--sm-text) !important; } @media (max-width: 1023px) { .lf.split { diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index 30499f9..ffecb6c 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -309,3 +309,14 @@ test('a reload part-way down the landing never blanks what is already on screen' expect(await page.evaluate(() => (window as unknown as { lowest: number }).lowest)).toBe(1); await page.close(); }); + +test('pointing at an edge in a linked figure’s JSON lights its line', async ({ page }) => { + await page.goto('/docs'); + const line = page.locator('.lf .cl[data-o^="edge:"]').first(); + const id = (await line.getAttribute('data-o'))!.slice('edge:'.length); + const path = page.locator(`.lf path[data-edge-id="${id}"]`); + const before = await path.evaluate((p) => getComputedStyle(p).stroke); + await line.hover(); + await expect(page.locator('.lf[data-linking]')).toHaveCount(1); + await expect.poll(() => path.evaluate((p) => getComputedStyle(p).stroke)).not.toBe(before); +}); From 31ee23f9febe12a2383c827c3644a48a7d6a4ec6 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:30 +0800 Subject: [PATCH 28/65] docs(site): fetch the search index again after a failed load --- site/components/docs/Search.tsx | 10 ++++++++-- site/e2e/smoke.spec.ts | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/site/components/docs/Search.tsx b/site/components/docs/Search.tsx index 7b92875..c925329 100644 --- a/site/components/docs/Search.tsx +++ b/site/components/docs/Search.tsx @@ -16,8 +16,14 @@ const ICONS: Record = { }; let cached: Promise | undefined; -// Fetched once, on the first open: every docs page shares the one file. -const loadIndex = () => (cached ??= fetch('/search.json').then((r) => (r.ok ? r.json() : Promise.reject(new Error(`search index: ${r.status}`))))); +// Fetched once, on the first open: every docs page shares the one file. A failed fetch is not kept, so the next open tries again. +const loadIndex = () => + (cached ??= fetch('/search.json') + .then((r): Promise => (r.ok ? r.json() : Promise.reject(new Error(`search index: ${r.status}`)))) + .catch((e: unknown) => { + cached = undefined; + throw e; + })); const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches; diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index ffecb6c..c24a47e 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -320,3 +320,22 @@ test('pointing at an edge in a linked figure’s JSON lights its line', async ({ await expect(page.locator('.lf[data-linking]')).toHaveCount(1); await expect.poll(() => path.evaluate((p) => getComputedStyle(p).stroke)).not.toBe(before); }); + +test('the docs search loads its index again after a failed fetch', async ({ page }) => { + let fail = true; + await page.route('**/search.json', (r) => (fail ? r.abort() : r.continue())); + await page.goto('/docs'); + const box = page.getByRole('combobox', { name: 'Search the docs' }); + await expect(async () => { + await page.keyboard.press('ControlOrMeta+k'); + await expect(box).toBeFocused({ timeout: 500 }); + }).toPass(); + await box.fill('serve'); + await expect(page.getByRole('option')).toHaveCount(0); + await page.keyboard.press('Escape'); + await expect(box).toHaveCount(0); + fail = false; + await page.keyboard.press('ControlOrMeta+k'); + await box.fill('serve'); + await expect(page.getByRole('option').first()).toBeVisible(); +}); From 1c406f5ae7bef41f684a080182845e31d18ec6de Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:31 +0800 Subject: [PATCH 29/65] docs(site): start the embedded viewer's flow only once it is on screen --- site/components/viewer/EmbeddedViewer.tsx | 9 ++++++++- site/e2e/smoke.spec.ts | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/site/components/viewer/EmbeddedViewer.tsx b/site/components/viewer/EmbeddedViewer.tsx index 19f02a4..3f1147a 100644 --- a/site/components/viewer/EmbeddedViewer.tsx +++ b/site/components/viewer/EmbeddedViewer.tsx @@ -27,9 +27,15 @@ function useAutoplay(frame: RefObject, live: boolean, delay: const playing = useRef(state.playing); playing.current = state.playing; const paused = useRef(false); + const onScreen = useRef(false); useEffect(() => { if (!live || !motionAllowed()) return; - const t = setTimeout(() => playing.current || dispatch({ type: 'togglePlay' }), delay); + const t = setTimeout(() => { + if (playing.current) return; + // Off screen the start is left to the observer, as if it had paused a running flow. + if (onScreen.current) dispatch({ type: 'togglePlay' }); + else paused.current = true; + }, delay); return () => clearTimeout(t); }, [live, delay, dispatch]); useEffect(() => { @@ -37,6 +43,7 @@ function useAutoplay(frame: RefObject, live: boolean, delay: if (!live || !el) return; const io = new IntersectionObserver(([e]) => { if (!e) return; + onScreen.current = e.isIntersecting; if (!e.isIntersecting && playing.current) { paused.current = true; dispatch({ type: 'togglePlay' }); diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index c24a47e..fafd594 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -339,3 +339,16 @@ test('the docs search loads its index again after a failed fetch', async ({ page await box.fill('serve'); await expect(page.getByRole('option').first()).toBeVisible(); }); + +test('the hero viewer starts its flow only once it is on screen', async ({ browser }) => { + const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, reducedMotion: 'no-preference' }); + await page.goto('/#install'); + const play = page.getByRole('group', { name: 'Try the viewer' }).getByRole('button', { name: /Play/ }); + // Past the 1.1 s the flow waits for the intro. + await page.waitForTimeout(2200); + expect(await page.evaluate(() => scrollY)).toBeGreaterThan(900); + await expect(play).toHaveAttribute('aria-pressed', 'false'); + await page.evaluate(() => scrollTo({ top: 0, behavior: 'instant' })); + await expect(play).toHaveAttribute('aria-pressed', 'true'); + await page.close(); +}); From ef4a068865288ecb0ffae8348bbeef00ab4bd457 Mon Sep 17 00:00:00 2001 From: Joseph Dale Banares Date: Sat, 14 Nov 2026 01:17:31 +0800 Subject: [PATCH 30/65] docs(site): keep the gallery's kind filter in step with the address --- site/components/examples/ExampleGrid.tsx | 19 +++++++++++++------ site/e2e/smoke.spec.ts | 10 ++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/site/components/examples/ExampleGrid.tsx b/site/components/examples/ExampleGrid.tsx index c0ac33d..823cb1b 100644 --- a/site/components/examples/ExampleGrid.tsx +++ b/site/components/examples/ExampleGrid.tsx @@ -1,7 +1,8 @@ 'use client'; import Link from 'next/link'; -import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; +import { useSearchParams } from 'next/navigation'; +import { Suspense, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'; import { ArrowRight, Bot } from 'lucide-react'; import { DIAGRAM_KINDS, KIND_LABELS, type DiagramKind } from '@stackmap/core'; @@ -14,6 +15,14 @@ export interface GridItem { type Kind = DiagramKind | 'all'; +// On a static page useSearchParams needs a Suspense boundary, and whatever is inside one renders in the browser +// only: this reads the address on its own so the cards stay server markup. +function KindParam({ onKind }: { onKind: (k: Kind) => void }) { + const k = useSearchParams().get('kind'); + useEffect(() => onKind(k && (DIAGRAM_KINDS as readonly string[]).includes(k) ? (k as DiagramKind) : 'all'), [k, onKind]); + return null; +} + /** * The gallery's kind filter, agent toggle and cards. The cards are server markup; this only hides the ones that * don't match. `?kind=` picks the kind, so the docs can link straight to theirs. @@ -24,11 +33,6 @@ export function ExampleGrid({ items, ledes }: { items: GridItem[]; ledes: Record const bar = useRef(null); const ind = useRef(null); - useEffect(() => { - const k = new URLSearchParams(location.search).get('kind'); - if (k && (DIAGRAM_KINDS as readonly string[]).includes(k)) setKind(k as DiagramKind); - }, []); - const pick = (k: Kind) => { setKind(k); const url = new URL(location.href); @@ -60,6 +64,9 @@ export function ExampleGrid({ items, ledes }: { items: GridItem[]; ledes: Record return ( <> + + +