diff --git a/packages/cli/e2e/offline.spec.ts b/packages/cli/e2e/offline.spec.ts index 0fa99cd..177005d 100644 --- a/packages/cli/e2e/offline.spec.ts +++ b/packages/cli/e2e/offline.spec.ts @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { pathToFileURL } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { expect, test } from '@playwright/test'; import { groupedPlatform } from '@stackmap/core/samples'; @@ -10,7 +10,7 @@ test('a delivered file renders from file:// with no network', async ({ page }) = const dir = mkdtempSync(join(tmpdir(), 'stackmap-e2e-')); const input = join(dir, 'platform.json'); writeFileSync(input, JSON.stringify(groupedPlatform)); - execFileSync('node', [new URL('../dist/cli.js', import.meta.url).pathname, 'deliver', input]); + execFileSync('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'deliver', input]); const requests: string[] = []; await page.route('**/*', (route) => { @@ -29,6 +29,6 @@ test('a delivered file renders from file:// with no network', async ({ page }) = }); test('the bare template says no diagram is embedded', async ({ page }) => { - await page.goto(pathToFileURL(new URL('../dist/viewer.html', import.meta.url).pathname).href); + await page.goto(new URL('../dist/viewer.html', import.meta.url).href); await expect(page.getByRole('status')).toHaveText(/No diagram embedded/); }); diff --git a/packages/cli/e2e/serve.spec.ts b/packages/cli/e2e/serve.spec.ts index e138214..8612f60 100644 --- a/packages/cli/e2e/serve.spec.ts +++ b/packages/cli/e2e/serve.spec.ts @@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { expect, test } from '@playwright/test'; import { commerceApi } from '@stackmap/core/samples'; @@ -15,7 +16,7 @@ async function start(initial: unknown, port = '0') { file = join(mkdtempSync(join(tmpdir(), 'stackmap-live-')), 'd.json'); write(initial); } - proc = spawn('node', [new URL('../dist/cli.js', import.meta.url).pathname, 'serve', file, '--port', port]); + proc = spawn('node', [fileURLToPath(new URL('../dist/cli.js', import.meta.url)), 'serve', file, '--port', port]); url = await new Promise((resolve, reject) => { proc.stdout!.on('data', (b: Buffer) => { const m = /serving (http:\/\/127\.0\.0\.1:\d+)/.exec(b.toString()); diff --git a/packages/cli/scripts/smoke.mjs b/packages/cli/scripts/smoke.mjs index d1a26e5..717d30e 100644 --- a/packages/cli/scripts/smoke.mjs +++ b/packages/cli/scripts/smoke.mjs @@ -4,10 +4,12 @@ import { createHash } from 'node:crypto'; import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { GALLERY } from '../../core/src/samples/gallery.ts'; import { commerceApi, groupedPlatform } from '../../core/src/samples/index.ts'; -const cli = new URL('../dist/cli.js', import.meta.url).pathname; +// Not `.pathname`: it keeps percent-escapes, so a checkout path with a space would not resolve. +const cli = fileURLToPath(new URL('../dist/cli.js', import.meta.url)); const dir = mkdtempSync(join(tmpdir(), 'stackmap-smoke-')); const run = (...args) => execFileSync('node', [cli, ...args], { encoding: 'utf8' }); const check = (ok, msg) => { diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 3783a65..33f9302 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'; @@ -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)); @@ -90,9 +91,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 d35cd95..25ef5b9 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'; @@ -36,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`, @@ -44,7 +45,8 @@ 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); } @@ -70,9 +72,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/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/src/serve.ts b/packages/cli/src/serve.ts index effbb96..b78adff 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'; @@ -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) => { @@ -93,9 +100,19 @@ 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); + const result = await buildHtml(path, template, log); publish({ ok: result.ok, diagnostics: result.diagnostics }, result.html); } catch (e) { const unreadable = e instanceof CliError; @@ -110,21 +127,54 @@ 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; + if (fingerprint() !== source) 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; + 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)] }), + ); + + running = rebuild(); + await running; 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'); } - 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)); @@ -136,23 +186,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/commands.test.ts b/packages/cli/test/commands.test.ts index 084d7da..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'; @@ -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) }); @@ -147,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); 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)`; diff --git a/packages/cli/test/serve-queue.test.ts b/packages/cli/test/serve-queue.test.ts new file mode 100644 index 0000000..a2d9e2d --- /dev/null +++ b/packages/cli/test/serve-queue.test.ts @@ -0,0 +1,51 @@ +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 }); + 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); +}); + +it('does not rebuild for a save that leaves the content as it was built', async () => { + const file = join(mkdtempSync(join(tmpdir(), 'stackmap-queue-')), 'd.json'); + writeFileSync(file, '1'); + build.mockResolvedValue(built('first')); + server = await serve(file, { template: '', port: 0 }); + build.mockClear(); + writeFileSync(file, '1'); + await pause(400); + expect(build).not.toHaveBeenCalled(); + writeFileSync(file, '2'); + await expect.poll(() => build.mock.calls.length, { timeout: 4000 }).toBe(1); +}); diff --git a/packages/cli/test/serve.test.ts b/packages/cli/test/serve.test.ts index af7d7b5..8a59380 100644 --- a/packages/cli/test/serve.test.ts +++ b/packages/cli/test/serve.test.ts @@ -6,7 +6,8 @@ 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 { CliError } from '../src/io'; +import { isLocalHost, LIVE_BLOCK_ID, serve, type ServeHandle } from '../src/serve'; const TEMPLATE = `stackmap
${EMPTY_DATA_BLOCK}`; let dir: string; @@ -96,6 +97,23 @@ 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 }); + 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 }); @@ -159,6 +177,32 @@ 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('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('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 }); 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/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/core/src/lane-columns.ts b/packages/core/src/lane-columns.ts index 2dc73a8..62862a2 100644 --- a/packages/core/src/lane-columns.ts +++ b/packages/core/src/lane-columns.ts @@ -5,12 +5,13 @@ import type { DiagramDraft, DiagramEdge } from './types'; /** * Edges that run from a later phase into an earlier one, directly or through unphased nodes: laid out as back - * edges (a phase can't start before the one it feeds), and reported by validation. + * edges (a phase can't start before the one it feeds), and reported by validation. Keyed by edge id; the value + * is the index of the phase the edge leads back into. */ -export function phaseViolations(draft: DiagramDraft): Set { +export function phaseViolations(draft: DiagramDraft): Map { const phaseOf = new Map(); draft.phases?.forEach((p, i) => p.nodes?.forEach((n) => phaseOf.has(n) || phaseOf.set(n, i))); - const out = new Set(); + const out = new Map(); if (!phaseOf.size) return out; // The latest phase that reaches each node along forward edges; monotone and bounded by the phase count. const reach = new Map(draft.nodes.map((n) => [n.id, phaseOf.get(n.id) ?? -1])); @@ -22,7 +23,7 @@ export function phaseViolations(draft: DiagramDraft): Set { const r = reach.get(e.from)!; const target = phaseOf.get(e.to); if (target !== undefined && r > target) { - out.add(e.id); + out.set(e.id, target); changed = true; } else if (r > reach.get(e.to)!) { reach.set(e.to, r); @@ -36,7 +37,7 @@ export function phaseViolations(draft: DiagramDraft): Set { /** Edges that don't push their target to a later column: replies, phase-order breaks, and what closes a cycle. */ export function backEdges(draft: DiagramDraft): Set { const back = new Set(draft.edges.filter((e) => e.kind === 'return' || e.from === e.to).map((e) => e.id)); - for (const id of phaseViolations(draft)) back.add(id); + for (const id of phaseViolations(draft).keys()) back.add(id); // DFS in draft order; an edge into a node still on the stack closes a cycle. const out = new Map(draft.nodes.map((n) => [n.id, [] as DiagramEdge[]])); for (const e of draft.edges) if (!back.has(e.id)) out.get(e.from)?.push(e); 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/layout/src/index.ts b/packages/layout/src/index.ts index 7d9d352..60ff555 100644 --- a/packages/layout/src/index.ts +++ b/packages/layout/src/index.ts @@ -5,10 +5,11 @@ 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, 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 { boundsWithLabels, placeLabels } from './labels'; import { layoutLanes } from './lanes'; +import { simplify } from './route'; import { layoutSequence } from './sequence'; export { layoutLanes } from './lanes'; @@ -33,6 +34,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; @@ -209,7 +212,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); @@ -268,6 +270,12 @@ export async function layoutDiagram(draft: DiagramDraft): Promise MAX_UNWRAPPED_WIDTH && !stages; const result = wrap ? await elk.layout({ ...structuredClone(graph), layoutOptions: { ...opts, ...wrapOptions } }) : flat; - // Flow order is read before wrapping, which moves later layers back to the start of a new row. - return { laid: collect(draft, result, direction, stages !== null, reversed), flow: collect(draft, flat, direction, false, reversed).nodes }; + // `flat` only when it isn't what was collected: the layout before wrapping. + return { laid: collect(draft, result, direction, stages !== null, reversed), flat: wrap ? flat : null }; }; - let { laid, flow } = await run(); + const first = await run(); + let laid = first.laid; // A group that both feeds and is fed by another can only sit on one side of it, so some edge between them runs // against the flow: entering its target from the far side, it wraps round the diagram. Lay such an edge out // from its target (it then leaves and enters by the facing sides) and redo the layout once. - const flips = large ? [] : againstFlow(draft, flow, direction, reversed); + // Flow order is read before wrapping, which moves later layers back to the start of a new row. + const flips = large ? [] : againstFlow(draft, first.flat ? collect(draft, first.flat, direction, false, reversed).nodes : laid.nodes, direction, reversed); if (flips.length) { reversed = new Set(reversed); for (const id of flips) reversed.has(id) ? reversed.delete(id) : reversed.add(id); wire(reversed); ({ laid } = await run()); } - const place = (l: LaidOutDiagram) => 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, @@ -349,12 +360,14 @@ export async function layoutDiagram(draft: DiagramDraft): Promise 0 && !large) { const cap = compact ? COMPACT_GAP.max : FULL_GAP_MAX; const defaultRun = Number(root.layoutOptions![EDGE_RUN]); - const gap = Math.min(cap, Math.max(Number(root.layoutOptions![LAYER_GAP]), spots.misfit + (compact ? 24 : 48))); + const current = Number(root.layoutOptions![LAYER_GAP]); + const gap = Math.min(cap, Math.max(current, spots.misfit + (compact ? 24 : 48))); const longRun = Math.min(direction === 'RIGHT' ? spots.misfit + 16 : 40, Math.floor((cap - 24) / 2)); const tries = [ { gap, run: defaultRun }, { gap: Math.max(gap, 2 * longRun + 24), run: longRun }, - ]; + // Room the first layout already had (groups aside: they take the gap only on a retry) gives that layout again. + ].filter((room) => draft.groups?.length || room.gap !== current || room.run !== defaultRun); const worse = (a: typeof spots, b: typeof spots) => a.forced - b.forced || a.unseated - b.unseated || a.misfit - b.misfit; for (const room of tries) { const wider = (await run(room)).laid; @@ -363,7 +376,7 @@ export async function layoutDiagram(draft: DiagramDraft): Promise 0 && dx < 1 && dy >= 1) a.x = b.x = i > 1 && pts[i - 2]!.x === a.x ? a.x : Math.round((a.x + b.x) / 2); else if (dy > 0 && dy < 1 && dx >= 1) a.y = b.y = i > 1 && pts[i - 2]!.y === a.y ? a.y : Math.round((a.y + b.y) / 2); } - return pts.filter((p, i) => { - const [prev, next] = [pts[i - 1], pts[i + 1]]; - if (!prev || !next) return true; - return !((prev.x === p.x && p.x === next.x) || (prev.y === p.y && p.y === next.y)); - }); + // Repeated points first: tested against its twin, a doubled corner would count as straight both ways and vanish. + return simplify(pts); } const STEP_MAX = 16; @@ -500,32 +510,52 @@ function stagePartitions(draft: DiagramDraft): Map { } if (!changed) break; } - // Partitions only order the top level; grouped nodes are left to the group's own layout. + // Partitions only order the top level; grouped nodes are left to the group's own layout. (ELK ignores a partition + // set on a group or inside one, so a group can't be held to a stage.) const grouped = new Set(draft.nodes.filter((n) => n.group !== undefined).map((n) => n.id)); for (const n of draft.nodes) if (!part.has(n.id)) part.set(n.id, 0); for (const id of grouped) part.delete(id); return part; } -/** One band per stage: its nodes' extent along the flow, the whole diagram across it, plus the label band. */ -function stageBands(draft: DiagramDraft, nodes: Record, direction: Direction): Record { +/** Each group's cards, those of the groups nested in it included. */ +function groupMembers(draft: DiagramDraft): Map { + const parent = new Map((draft.groups ?? []).map((g) => [g.id, g.parent])); + const out = new Map((draft.groups ?? []).map((g) => [g.id, []])); + for (const n of draft.nodes) { + // The step count guards against a draft whose groups name each other as parent. + for (let g = n.group, steps = 0; g !== undefined && out.has(g) && steps <= parent.size; g = parent.get(g), steps++) out.get(g)!.push(n.id); + } + return out; +} + +/** + * One band per stage: its nodes' extent along the flow, the whole diagram across it, plus the label band. Group + * frames count: across the flow all of them (a frame's title would otherwise sit under the stage labels), and along + * it the frames of groups whose cards are all in the stage. + */ +function stageBands(draft: DiagramDraft, nodes: Record, groups: Record, direction: Direction): Record { const out: Record = {}; - const all = Object.values(nodes); - if (!all.length) return out; + if (!Object.keys(nodes).length) return out; + const all = [...Object.values(nodes), ...Object.values(groups)]; + const members = [...groupMembers(draft)]; const top = Math.min(...all.map((r) => r.y)); const bottom = Math.max(...all.map((r) => r.y + r.height)); const left = Math.min(...all.map((r) => r.x)); const right = Math.max(...all.map((r) => r.x + r.width)); for (const p of draft.phases ?? []) { - const members = (p.nodes ?? []).flatMap((id) => nodes[id] ?? []); - if (!members.length) continue; + const cards = (p.nodes ?? []).flatMap((id) => nodes[id] ?? []); + if (!cards.length) continue; + const own = new Set(p.nodes); + const frames = members.flatMap(([id, ns]) => (ns.length && ns.every((n) => own.has(n)) && groups[id] ? [groups[id]] : [])); + const inside = [...cards, ...frames]; if (direction === 'RIGHT') { - const x = Math.min(...members.map((r) => r.x)) - STAGE_PAD; - const x2 = Math.max(...members.map((r) => r.x + r.width)) + STAGE_PAD; + const x = Math.min(...inside.map((r) => r.x)) - STAGE_PAD; + const x2 = Math.max(...inside.map((r) => r.x + r.width)) + STAGE_PAD; out[p.id] = { x: round(x), y: round(top - STAGE_PAD - STAGE_LABEL_BAND), width: round(x2 - x), height: round(bottom - top + 2 * STAGE_PAD + STAGE_LABEL_BAND) }; } else { - const y = Math.min(...members.map((r) => r.y)) - STAGE_PAD; - const y2 = Math.max(...members.map((r) => r.y + r.height)) + STAGE_PAD; + const y = Math.min(...inside.map((r) => r.y)) - STAGE_PAD; + const y2 = Math.max(...inside.map((r) => r.y + r.height)) + STAGE_PAD; out[p.id] = { x: round(left - STAGE_PAD - 160), y: round(y), width: round(right - left + 2 * STAGE_PAD + 160), height: round(y2 - y) }; } } diff --git a/packages/layout/src/labels.ts b/packages/layout/src/labels.ts index 9331e4f..b958b9e 100644 --- a/packages/layout/src/labels.ts +++ b/packages/layout/src/labels.ts @@ -1,21 +1,47 @@ -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. */ -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; @@ -28,16 +54,35 @@ function distance(p: Point, pts: Point[]): number { return best; } const pillAt = (p: Point, w: number): Rect => ({ x: p.x - w / 2, y: p.y - LABEL_H / 2, width: w, height: LABEL_H }); +/** Room kept between a label and the edge of the diagram. */ +const EDGE_ROOM = 16; + +/** + * The diagram's bounds, grown to hold any label that hangs past the right or bottom edge: a pill beside an outer + * run can reach past what the cards and routes need. (Nothing is placed past the left or top edge.) + */ +export function boundsWithLabels(bounds: B, edges: { id: string; label?: string }[], labels: Record): B { + let { width, height } = bounds; + for (const e of edges) { + const p = labels[e.id]; + if (!p || !e.label) continue; + width = Math.max(width, round(p.x + labelWidth(e.label) / 2 + EDGE_ROOM)); + height = Math.max(height, round(p.y + LABEL_H / 2 + EDGE_ROOM)); + } + return { ...bounds, width, height }; +} /** A group frame: labels keep off its border and its title. */ 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. */ @@ -50,7 +95,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) })), }; } @@ -95,8 +140,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) { @@ -104,7 +149,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) }; @@ -113,14 +158,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!)); @@ -138,17 +183,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; @@ -172,8 +219,11 @@ 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; + // Off the left or top edge there is no diagram to grow into. + if (pill.x < 0 || pill.y < 0) 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; diff --git a/packages/layout/src/lanes.ts b/packages/layout/src/lanes.ts index 8b97147..4bf76c6 100644 --- a/packages/layout/src/lanes.ts +++ b/packages/layout/src/lanes.ts @@ -1,5 +1,5 @@ -import { assignColumns, backEdges, cardSize, COMPACT, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; -import { labelWidth, placeLabels } from './labels'; +import { assignColumns, backEdges, cardSize, COMPACT, round, type DiagramDraft, type DiagramEdge, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; +import { boundsWithLabels, labelWidth, placeLabels } from './labels'; export { assignColumns, backEdges } from '@stackmap/core'; import { nudge, routeEdges, STUB, type PortChoice, type RouteRequest } from './route'; @@ -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[] } { @@ -133,7 +131,12 @@ export function layoutLanes(draft: DiagramDraft): LaidOutDiagram { const xs = [x0 - (hasStart ? START_MARK : 0) - LANE_PAD_X / 2, bandX + bandW - LANE_PAD_X / 2]; for (let c = 0; c < cols - 1; c++) xs.push(colX(c) + cardW + gutter / 2); const ys: number[] = []; - for (const r of Object.values(laneRects)) ys.push(r.y + r.height - LANE_PAD_BOTTOM / 2, r.y - LANE_GAP / 2, r.y + r.height + LANE_GAP / 2); + // Above the first lane the channel runs mid-way to the phase header, whose lower edge is where it would else be. + const above = (r: Rect) => r.y - (r.y === top && draft.phases?.length ? PHASE_GAP : LANE_GAP) / 2; + for (const r of Object.values(laneRects)) ys.push(r.y + r.height - LANE_PAD_BOTTOM / 2, above(r), r.y + r.height + LANE_GAP / 2); + // The lines the diagram rules itself. A first-row card's top stub ends on its lane's upper edge (LANE_PAD_TOP is + // one STUB), so a route bending there would run along it: routes pay to, and nudged tracks never land on one. + const ruled = [...Object.values(laneRects).flatMap((r) => [r.y, r.y + r.height]), ...(draft.phases?.length ? [PAD + PHASE_BAND] : [])]; // Lane rails, group labels and start markers are text and marks that edges must not run over. const obstacles: Rect[] = []; for (const lane of lanes) { @@ -175,14 +178,15 @@ export function layoutLanes(draft: DiagramDraft): LaidOutDiagram { }) .sort((a, b) => a.order - b.order); const ends = Object.fromEntries(draft.edges.map((e) => [e.id, { from: e.from, to: e.to }])); - const routed = nudge(routeEdges(rects, requests, { xs, ys }, obstacles), ends); + const routed = nudge(routeEdges(rects, requests, { xs, ys, ruled }, obstacles), ends, Object.values(rects), ruled); const edges: Record = {}; for (const e of draft.edges) { 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 { @@ -193,6 +197,6 @@ export function layoutLanes(draft: DiagramDraft): LaidOutDiagram { lanes: laneRects, phases: phaseRects, labels, - bounds: { width: round(bandX + bandW + PAD), height: round(height) }, + bounds: boundsWithLabels({ width: round(bandX + bandW + PAD), height: round(height) }, draft.edges, labels), }; } diff --git a/packages/layout/src/route.ts b/packages/layout/src/route.ts index 85f466d..95c97c4 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 @@ -27,6 +27,8 @@ const MARGIN = 12; const BEND = 48; /** Extra cost per px for running along a channel another, unrelated edge already uses. */ const SHARED = 1.5; +/** Extra cost per px for running along a line the diagram rules itself (a lane's edge): the edge would read as part of it. */ +const RULED = 1.5; const TRACK = 8; /** Cost of a side the request didn't ask for: a last resort, so every edge gets an orthogonal route. */ const ANY_SIDE = 400; @@ -37,14 +39,21 @@ const SIDES: Side[] = ['right', 'bottom', 'left', 'top']; const MIXED_TONE = 300; /** Shortest straight run a nudge may leave at a port (arrowhead + gap). */ const MIN_RUN = 12; +/** + * Cost of running along the line of a port some other card's edge uses, or of taking a port on a line another edge + * already runs along: end to end, the two would draw as one line between cards that share no edge. + */ +const FACING = 600; +/** How far past its stub a port keeps other edges off its line. */ +const PORT_CLEAR = 12; +/** Closest a nudged run comes to a card, or a stretched port run to another edge on its line. */ +const NUDGE_CLEAR = 4; type Dir = 0 | 1 | 2 | 3; // right, down, left, up 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 +82,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); @@ -188,6 +196,11 @@ interface Used { from: string; to: string; } +/** A stretch of a line, along it. */ +interface Span { + lo: number; + hi: number; +} /** Numeric key of an undirected grid step (point indexes stay far below 2^26). */ const stepKey = (a: number, b: number) => (a < b ? a * 67108864 + b : b * 67108864 + a); /** Cost of touching a point another, unrelated edge already runs through (a crossing or a merge). */ @@ -203,12 +216,13 @@ interface Port { /** * Routes every request around `nodes` (and extra `obstacles`, e.g. labels), using `xs`/`ys` as channel lines. + * `ruled` are the horizontal lines the diagram draws itself, which routes keep off where another way is as short. * Returns each edge's polyline from port to port, first point on the source card, last on the target card. */ export function routeEdges( nodes: Record, requests: RouteRequest[], - channels: { xs: number[]; ys: number[] }, + channels: { xs: number[]; ys: number[]; ruled?: number[] }, obstacles: Rect[] = [], ): Record { const xs = [...channels.xs]; @@ -225,11 +239,25 @@ export function routeEdges( } const blocked = [...Object.values(nodes).map((r) => inflate(r, MARGIN)), ...obstacles]; const grid = buildGrid(xs, ys, blocked); + const ruled = new Set((channels.ruled ?? []).map(round)); const at = new Map(grid.pts.map((p, i) => [`${p.x},${p.y}`, i])); const find = (p: Point) => at.get(`${round(p.x)},${round(p.y)}`); const usedSteps = new Map(); const usedPoints = new Map(); const out: Record = {}; + // Per line (`x…` for a vertical one, `y…` for a horizontal one): the stretch each claimed port keeps clear, and the + // stretches routes run along. + const portLines = new Map(); + const runLines = new Map(); + const lineKey = (vertical: boolean, at: number) => `${vertical ? 'x' : 'y'}${round(at)}`; + /** A port's run, and PORT_CLEAR past its stub, as a stretch of its line. */ + const portSpan = (r: Rect, side: Side, slot: Slot) => { + const [p, q] = [portPoint(r, side, slot), stubPoint(r, side, slot)]; + const d = SIDE_DIR[side]; + const vertical = side === 'top' || side === 'bottom'; + const [a, b] = vertical ? [p.y, q.y + DY[d]! * PORT_CLEAR] : [p.x, q.x + DX[d]! * PORT_CLEAR]; + return { key: lineKey(vertical, vertical ? p.x : p.y), lo: Math.min(a, b), hi: Math.max(a, b) }; + }; // Who uses each port slot: edges may share one only in the same direction and tone (a trunk). // Two edges between the same two cards never share one (they would draw as one line with two labels). @@ -240,7 +268,9 @@ export function routeEdges( SLOTS.map((slot) => { const use = slotUse.get(`${node}:${side}:${slot}`); const clash = !use ? 0 : use.role !== role ? OPPOSED : use.pairs.has(pair) || !use.tones.has(tone) ? MIXED_TONE : 0; - return { side, slot, cost: (listed.get(side) ?? ANY_SIDE) + Math.abs(slot) * SLOT_COST + clash }; + const span = portSpan(nodes[node]!, side, slot); + const facing = runLines.get(span.key)?.some((u) => (role === 'out' ? u.from : u.to) !== node && span.lo < u.hi && u.lo < span.hi) ? FACING : 0; + return { side, slot, cost: (listed.get(side) ?? ANY_SIDE) + Math.abs(slot) * SLOT_COST + clash + facing }; }), ); }; @@ -250,6 +280,8 @@ export function routeEdges( use.tones.add(tone); use.pairs.add(pair); slotUse.set(key, use); + const { key: line, lo, hi } = portSpan(nodes[node]!, port.side, port.slot); + portLines.set(line, [...(portLines.get(line) ?? []), { lo, hi, node, role }]); }; for (const req of requests) { @@ -273,7 +305,18 @@ export function routeEdges( } // Fan-out from one card and fan-in to one card share a trunk on purpose; only unrelated edges pay. const unrelated = (list: Used[] | undefined) => !!list?.some((u) => u.from !== req.from && u.to !== req.to); - const extra = (a: number, b: number, len: number) => (unrelated(usedSteps.get(stepKey(a, b))) ? SHARED * len : 0) + (unrelated(usedPoints.get(b)) ? CROSS : 0); + // Edges that may use a port themselves (out of the same card, or into it) run along its line freely. + const facing = (a: number, b: number) => { + const [p, q] = [grid.pts[a]!, grid.pts[b]!]; + const vertical = p.x === q.x; + const spans = portLines.get(lineKey(vertical, vertical ? p.x : p.y)); + if (!spans) return 0; + const [lo, hi] = vertical ? [Math.min(p.y, q.y), Math.max(p.y, q.y)] : [Math.min(p.x, q.x), Math.max(p.x, q.x)]; + return spans.some((u) => (u.role === 'out' ? req.from : req.to) !== u.node && lo < u.hi && u.lo < hi) ? FACING : 0; + }; + const onRule = (a: number, b: number) => grid.pts[a]!.y === grid.pts[b]!.y && ruled.has(grid.pts[a]!.y); + const extra = (a: number, b: number, len: number) => + (unrelated(usedSteps.get(stepKey(a, b))) ? SHARED * len : 0) + (unrelated(usedPoints.get(b)) ? CROSS : 0) + facing(a, b) + (onRule(a, b) ? RULED * len : 0); // Search near the two cards first (most routes stay local); only a route that needs more room gets the grid. const box = { x0: Math.min(src.x, dst.x) - REGION, y0: Math.min(src.y, dst.y) - REGION, x1: Math.max(src.x + src.width, dst.x + dst.width) + REGION, y1: Math.max(src.y + src.height, dst.y + dst.height) + REGION }; const path = search(grid, starts, goals, extra, box) ?? search(grid, starts, goals, extra); @@ -291,7 +334,13 @@ export function routeEdges( const me = { from: req.from, to: req.to }; gridPath.forEach((k, i) => { usedPoints.set(k, [...(usedPoints.get(k) ?? []), me]); - if (i) usedSteps.set(stepKey(gridPath[i - 1]!, k), [...(usedSteps.get(stepKey(gridPath[i - 1]!, k)) ?? []), me]); + if (!i) return; + usedSteps.set(stepKey(gridPath[i - 1]!, k), [...(usedSteps.get(stepKey(gridPath[i - 1]!, k)) ?? []), me]); + const [p, q] = [grid.pts[gridPath[i - 1]!]!, grid.pts[k]!]; + const vertical = p.x === q.x; + const line = lineKey(vertical, vertical ? p.x : p.y); + const [lo, hi] = vertical ? [Math.min(p.y, q.y), Math.max(p.y, q.y)] : [Math.min(p.x, q.x), Math.max(p.x, q.x)]; + runLines.set(line, [...(runLines.get(line) ?? []), { lo, hi, ...me }]); }); out[req.id] = [portPoint(src, from.side, from.slot), ...gridPath.map((k) => grid.pts[k]!), portPoint(dst, to.side, to.slot)]; } @@ -399,9 +448,11 @@ interface Seg { /** * Spreads unrelated edges that run along the same line over parallel tracks, TRACK px apart. Segments of * edges that share a source or a target stay merged (a trunk). Segments on a port never move, and a move - * never shortens a port's straight run below MIN_RUN, so edges still meet their cards square. + * never shortens a port's straight run below MIN_RUN, so edges still meet their cards square. A segment takes the + * nearest track that keeps it and the runs it stretches off the `cards`, its port runs off other edges' lines, and + * a horizontal run off the `ruled` lines the diagram draws itself; with none, it stays where it was routed. */ -export function nudge(routes: Record, ends: Record): Record { +export function nudge(routes: Record, ends: Record, cards: Rect[] = [], ruled: number[] = []): Record { const out: Record = Object.fromEntries(Object.entries(routes).map(([k, v]) => [k, simplify(v).map((p) => ({ ...p }))])); for (const vertical of [true, false]) { const lines = new Map(); @@ -423,17 +474,26 @@ export function nudge(routes: Record, ends: Record Math.min(a.hi, b.hi) - Math.max(a.lo, b.lo) > 0.5; const mayShare = (a: Seg, b: Seg) => a.edge === b.edge || ((a.src === b.src) !== (a.dst === b.dst)); const track = new Map(); + const axis = vertical ? 'x' : 'y'; + const free = (seg: Seg, t: number) => !segs.some((o) => track.get(o) === t && overlap(o, seg) && !mayShare(o, seg)); + const offset = (t: number) => (t % 2 ? 1 : -1) * Math.ceil(t / 2) * TRACK; + // Each segment moves as soon as it has its track, so the next one is checked against where things now are. for (const seg of segs) { let t = 0; - while (segs.some((o) => track.get(o) === t && overlap(o, seg) && !mayShare(o, seg))) t++; - track.set(seg, t); - } - for (const seg of segs) { - const t = track.get(seg)!; + const onRule = (off: number) => !vertical && ruled.some((y) => Math.abs(seg.at + off - y) < 0.5); + while (!free(seg, t) || (t > 0 && (onRule(offset(t)) || !fits(out, ends, cards, seg, axis, offset(t))))) { + if (++t <= 2 * segs.length + 8) continue; + // No track fits: it holds the first free one, as a segment kept back by its port run does, and stays put. + t = 0; + while (!free(seg, t)) t++; + track.set(seg, t); + t = 0; + break; + } + if (!track.has(seg)) track.set(seg, t); if (!t) continue; - const off = (t % 2 ? 1 : -1) * Math.ceil(t / 2) * TRACK; + const off = offset(t); const pts = out[seg.edge]!; - const axis = vertical ? 'x' : 'y'; // Moving a point next to a port stretches or shrinks that port's run; keep room for the arrowhead. const run = (j: number, port: number) => Math.abs(pts[j]![axis] + off - pts[port]![axis]); if ((seg.i === 1 && run(1, 0) < MIN_RUN) || (seg.i + 1 === pts.length - 2 && run(seg.i + 1, pts.length - 1) < MIN_RUN)) continue; @@ -443,3 +503,37 @@ export function nudge(routes: Record, ends: Record [k, simplify(v)])); } + +/** + * Whether a segment can move `off` along `axis`: the moved run keeps NUDGE_CLEAR off every card, the runs either side + * of it (which stretch or shrink with it) cross none, and a port run neither turns back into its card nor stretches + * onto a line some other card's edge runs along. + */ +function fits(routes: Record, ends: Record, cards: Rect[], seg: Seg, axis: 'x' | 'y', off: number): boolean { + const pts = routes[seg.edge]!; + const [i, j] = [seg.i, seg.i + 1]; + const [a, b] = [i, j].map((k) => ({ ...pts[k]!, [axis]: round(seg.at + off) })) as [Point, Point]; + if (cards.some((r) => crosses(a, b, inflate(r, NUDGE_CLEAR)))) return false; + for (const [port, moved, at, role] of [ + [pts[i - 1]!, a, i === 1, 'out'], + [pts[j + 1]!, b, j === pts.length - 2, 'in'], + ] as const) { + if (cards.some((r) => crosses(port, moved, r))) return false; + if (!at) continue; + const [was, now] = [seg.at - port[axis], moved[axis] - port[axis]]; + if (Math.sign(now) !== Math.sign(was)) return false; + if (Math.abs(now) <= Math.abs(was)) continue; + // Stretched: nothing else on its line within reach, unless that edge may use this port too. + const other = axis === 'x' ? 'y' : 'x'; + const [lo, hi] = [Math.min(port[axis], moved[axis]) - NUDGE_CLEAR, Math.max(port[axis], moved[axis]) + NUDGE_CLEAR]; + const card = ends[seg.edge]![role === 'out' ? 'from' : 'to']; + for (const [id, q] of Object.entries(routes)) { + if (id === seg.edge || ends[id]![role === 'out' ? 'from' : 'to'] === card) continue; + for (let k = 1; k < q.length; k++) { + const [u, v] = [q[k - 1]!, q[k]!]; + if (Math.abs(u[other] - port[other]) < 0.5 && Math.abs(v[other] - port[other]) < 0.5 && Math.min(u[axis], v[axis]) < hi && lo < Math.max(u[axis], v[axis])) return false; + } + } + } + return true; +} diff --git a/packages/layout/src/sequence.ts b/packages/layout/src/sequence.ts index c6348c2..0e7fe18 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 */ @@ -42,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. @@ -64,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); @@ -92,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); @@ -177,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 = {}; @@ -189,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) }, @@ -202,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/fuzz.test.ts b/packages/layout/test/fuzz.test.ts index b0912f9..fd8c452 100644 --- a/packages/layout/test/fuzz.test.ts +++ b/packages/layout/test/fuzz.test.ts @@ -1,21 +1,23 @@ import { describe, expect, it } from 'vitest'; -import type { DiagramDraft, Point, Rect } from '@stackmap/core'; +import type { DiagramDraft, LaidOutDiagram, Point, Rect } from '@stackmap/core'; import { layoutDiagram } from '../src/index'; +import { labelWidth } from '../src/labels'; import { layoutLanes } from '../src/lanes'; // Property test: random workflows and lifecycles (tones, returns, async, labels, tags, phases, groups, self-loops, // parallel edges) must always lay out into geometry the viewer can draw honestly. -function generator(seed: number) { +/** `dense`: a fixed node count with several edges a node, where channels fill up and nudging runs out of tracks. */ +function generator(seed: number, dense?: { nodes: number; edges: number }) { const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff), seed / 0x7fffffff); const pick = (a: readonly T[]) => a[Math.floor(rnd() * a.length)]!; return (): DiagramDraft => { const lanes = Array.from({ length: 2 + Math.floor(rnd() * 4) }, (_, i) => ({ id: `l${i}`, label: `Lane ${i}` })); - const n = 3 + Math.floor(rnd() * 14); + const n = dense?.nodes ?? 3 + Math.floor(rnd() * 14); const lifecycle = rnd() < 0.3; const types = lifecycle ? (['start', 'active', 'waiting', 'decision', 'success', 'failure'] as const) : (['service', 'client', 'queue', 'security'] as const); const nodes = Array.from({ length: n }, (_, i) => ({ id: `n${i}`, type: pick(types), lane: pick(lanes).id, card: { title: `N${i}`, ...(rnd() < 0.3 ? { tag: 'tag' } : {}) } })); - const edges = Array.from({ length: Math.floor(rnd() * n * 2) }, (_, i) => { + const edges = Array.from({ length: dense?.edges ?? Math.floor(rnd() * n * 2) }, (_, i) => { const r = rnd(); return { id: `e${i}`, @@ -39,6 +41,51 @@ const inside = (p: Point, r: Rect) => p.x > r.x + 0.5 && p.x < r.x + r.width - 0 const crosses = (a: Point, b: Point, r: Rect) => Math.max(a.x, b.x) > r.x + 0.5 && Math.min(a.x, b.x) < r.x + r.width - 0.5 && Math.max(a.y, b.y) > r.y + 0.5 && Math.min(a.y, b.y) < r.y + r.height - 0.5; +/** Every label's pill lies inside the bounds the viewer sizes and fits the diagram by. */ +function expectLabelsInside(d: DiagramDraft, out: LaidOutDiagram) { + for (const e of d.edges) { + const p = out.labels?.[e.id]; + if (!p || !e.label) continue; + const half = labelWidth(e.label) / 2; + expect(p.x - half >= 0 && p.y - 10 >= 0 && p.x + half <= out.bounds.width && p.y + 10 <= out.bounds.height, `label ${e.id} inside the diagram`).toBe(true); + } +} + +/** No segment of a route runs through a card, its own two aside where it leaves and arrives. */ +function expectOffCards(d: DiagramDraft, out: LaidOutDiagram) { + for (const e of d.edges) { + const pts = out.edges[e.id]!; + for (const [id, r] of Object.entries(out.nodes)) + for (let i = 1; i < pts.length; i++) { + const own = (i === 1 && id === e.from) || (i === pts.length - 1 && id === e.to); + if (!own) expect(crosses(pts[i - 1]!, pts[i]!, r), `${e.id} segment ${i} crosses ${id}`).toBe(false); + } + } +} + +/** Port runs (card to first bend) of edges that share no card never lie over each other: that draws as one edge. */ +function overlappingPortRuns(d: DiagramDraft, out: LaidOutDiagram): string[] { + const runs = d.edges.flatMap((e) => { + const pts = out.edges[e.id]!; + return [ + { e, card: e.from, a: pts[0]!, b: pts[1]! }, + { e, card: e.to, a: pts.at(-1)!, b: pts.at(-2)! }, + ]; + }); + const hits: string[] = []; + runs.forEach((p, i) => { + for (const q of runs.slice(i + 1)) { + if (p.card === q.card || p.e.from === q.e.from || p.e.to === q.e.to) continue; + for (const [fixed, along] of [['x', 'y'], ['y', 'x']] as const) { + if (p.a[fixed] !== p.b[fixed] || q.a[fixed] !== q.b[fixed] || Math.abs(p.a[fixed] - q.a[fixed]) >= 0.5) continue; + const shared = Math.min(Math.max(p.a[along], p.b[along]), Math.max(q.a[along], q.b[along])) - Math.max(Math.min(p.a[along], p.b[along]), Math.min(q.a[along], q.b[along])); + if (shared > 0.5) hits.push(`${p.e.id} × ${q.e.id}`); + } + } + }); + return hits; +} + describe('lane layout properties', () => { const next = generator(20260930); const cases = Array.from({ length: 150 }, next); @@ -49,14 +96,14 @@ describe('lane layout properties', () => { // Columns stay dense: the diagram is never wider than one column per node. expect(out.bounds.width).toBeLessThan(144 + d.nodes.length * (176 + 176) + 200); const ports = new Map>(); + expectOffCards(d, out); + expect(overlappingPortRuns(d, out)).toEqual([]); + // A first-row card's top stub ends on its lane's upper edge: no route turns there and runs along the edge. + const tops = Object.values(out.lanes ?? {}).map((r) => r.y); for (const e of d.edges) { const pts = out.edges[e.id]!; for (let i = 1; i < pts.length; i++) expect(pts[i]!.x === pts[i - 1]!.x || pts[i]!.y === pts[i - 1]!.y, `${e.id} is orthogonal`).toBe(true); - for (const [id, r] of Object.entries(out.nodes)) - for (let i = 1; i < pts.length; i++) { - const own = (i === 1 && id === e.from) || (i === pts.length - 1 && id === e.to); - if (!own) expect(crosses(pts[i - 1]!, pts[i]!, r), `${e.id} segment ${i} crosses ${id}`).toBe(false); - } + for (let i = 1; i < pts.length; i++) expect(pts[i]!.x !== pts[i - 1]!.x && tops.some((y) => Math.abs(y - pts[i]!.y) < 0.5), `${e.id} runs along a lane's edge`).toBe(false); for (const [role, p] of [['out', pts[0]!], ['in', pts.at(-1)!]] as const) { const key = `${p.x},${p.y}`; ports.set(key, (ports.get(key) ?? new Set()).add(role)); @@ -65,9 +112,25 @@ describe('lane layout properties', () => { // No point is both where an arrow arrives and where another edge leaves: that would read as two-way. expect([...ports].filter(([, roles]) => roles.size > 1).map(([k]) => k)).toEqual([]); for (const [id, p] of Object.entries(out.labels ?? {})) for (const [n, r] of Object.entries(out.nodes)) expect(inside(p, r), `label ${id} on ${n}`).toBe(false); + expectLabelsInside(d, out); }); }); +// Crowded diagrams: thirty cards with eight edges each fill the channels, so edges spread over many tracks beside them. +describe('crowded lane layouts', () => { + const next = generator(4, { nodes: 30, edges: 240 }); + const cases = Array.from({ length: 3 }, next); + + it.each(cases.map((d, i) => [i, d] as const))('random diagram %i keeps every route off the cards', (_i, d) => { + const out = layoutLanes(d); + for (const e of d.edges) { + const pts = out.edges[e.id]!; + for (let i = 1; i < pts.length; i++) expect(pts[i]!.x === pts[i - 1]!.x || pts[i]!.y === pts[i - 1]!.y, `${e.id} is orthogonal`).toBe(true); + } + expectOffCards(d, out); + }, 30_000); +}); + // The same for architecture and dataflow (ELK): random groups (nested too), directions, compact cards, stages, tones, // replies, async edges, labels, self-loops and parallel edges. function elkGenerator(seed: number) { @@ -148,5 +211,6 @@ describe('ELK layout properties', () => { // One look per port, and never an arrival where another edge leaves. expect([...ports].filter(([, styles]) => styles.size > 1).map(([k]) => k)).toEqual([]); for (const [id, p] of Object.entries(out.labels ?? {})) for (const [n, r] of Object.entries(out.nodes)) expect(inside(p, r), `label ${id} on ${n}`).toBe(false); + expectLabelsInside(d, out); }); }); 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) { diff --git a/packages/layout/test/layout.test.ts b/packages/layout/test/layout.test.ts index ae1b839..ee3ee51 100644 --- a/packages/layout/test/layout.test.ts +++ b/packages/layout/test/layout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; import { cardSize, type DiagramDraft, type DiagramNode, type Point, type Rect } from '@stackmap/core'; import { commerceApi, groupedPlatform } from '@stackmap/core/samples'; -import { GROUP_LABEL_BAND, layoutDiagram } from '../src/index'; +import { GROUP_LABEL_BAND, layoutDiagram, squared, STAGE_LABEL_BAND } from '../src/index'; import { STRESS } from './stress'; const node = (id: string, extra: Partial = {}): DiagramNode => ({ @@ -18,6 +18,16 @@ const near = (a: Point, b: Point) => { expect(a.y).toBeCloseTo(b.y, 0); }; +describe('squared', () => { + it('snaps a near-straight run and drops the bend that no longer turns', () => { + expect(squared([{ x: 0, y: 10.33 }, { x: 50, y: 10 }, { x: 90, y: 10 }])).toEqual([{ x: 0, y: 10 }, { x: 90, y: 10 }]); + }); + + it('keeps a corner that comes as two points in the same place', () => { + expect(squared([{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }])).toEqual([{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }]); + }); +}); + describe('layoutDiagram', () => { it('places the target to the right and routes port to port', async () => { const out = await layoutDiagram( @@ -202,6 +212,35 @@ describe('layoutDiagram', () => { } }); + 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.each(['RIGHT', 'DOWN'] as const)('draws a stage band round the frame of a group that belongs to it, clear of the stage labels (%s)', async (direction) => { + const out = await layoutDiagram( + draft({ + direction, + groups: [{ id: 'g', label: 'Workers' }], + nodes: [node('a'), node('b', { group: 'g' }), node('c', { group: 'g' }), node('d')], + edges: [{ id: '1', from: 'a', to: 'b' }, { id: '2', from: 'a', to: 'c' }, { id: '3', from: 'b', to: 'd' }], + phases: [{ id: 'in', label: 'In', nodes: ['a'] }, { id: 'work', label: 'Work', nodes: ['b', 'c'] }, { id: 'out', label: 'Out', nodes: ['d'] }], + }), + ); + const [g, band] = [out.groups.g!, out.phases!.work!]; + expect(g.x).toBeGreaterThanOrEqual(band.x); + expect(g.y).toBeGreaterThanOrEqual(band.y); + expect(g.x + g.width).toBeLessThanOrEqual(band.x + band.width); + expect(g.y + g.height).toBeLessThanOrEqual(band.y + band.height); + // The stage's label strip (above the bands left to right, down their left side top-down) stays off the frame. + if (direction === 'RIGHT') expect(g.y).toBeGreaterThanOrEqual(band.y + STAGE_LABEL_BAND); + else expect(g.x).toBeGreaterThanOrEqual(band.x + 160); + }); + 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']!); diff --git a/packages/layout/test/route.test.ts b/packages/layout/test/route.test.ts new file mode 100644 index 0000000..b65e5c2 --- /dev/null +++ b/packages/layout/test/route.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest'; +import type { Point, Rect } from '@stackmap/core'; +import { nudge } from '../src/route'; + +const crosses = (a: Point, b: Point, r: Rect) => + 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; +const hits = (routes: Record, card: Rect) => + Object.entries(routes).flatMap(([id, pts]) => (pts.slice(1).some((b, i) => crosses(pts[i]!, b, card)) ? [id] : [])); +/** Edges that share no card: every one takes a track of its own. */ +const apart = (ids: string[]) => Object.fromEntries(ids.map((id) => [id, { from: `${id}-from`, to: `${id}-to` }])); + +describe('nudge', () => { + it('keeps the tracks it hands out off a card beside the channel', () => { + // Six edges along y=100, 20px above a card: the sixth track (+24) would run 4px inside it. + const card = { x: 100, y: 120, width: 176, height: 60 }; + const routes = Object.fromEntries( + Array.from({ length: 6 }, (_, k) => [`e${k}`, [{ x: k * 10, y: 0 }, { x: k * 10, y: 100 }, { x: 300 + k * 10, y: 100 }, { x: 300 + k * 10, y: 300 }]]), + ); + expect(hits(nudge(routes, apart(Object.keys(routes))), card)).toEqual(['e5']); + const out = nudge(routes, apart(Object.keys(routes)), [card]); + expect(hits(out, card)).toEqual([]); + const lines = Object.values(out).map((pts) => pts[1]!.y); + expect(new Set(lines).size).toBe(6); + for (const y of lines) expect(y).toBeLessThanOrEqual(card.y - 4); + }); + + it('hands out no track on a line the diagram rules itself', () => { + const routes = Object.fromEntries( + Array.from({ length: 2 }, (_, k) => [`e${k}`, [{ x: k * 10, y: 0 }, { x: k * 10, y: 100 }, { x: 300 + k * 10, y: 100 }, { x: 300 + k * 10, y: 300 }]]), + ); + expect(nudge(routes, apart(['e0', 'e1'])).e1![1]!.y).toBe(108); + expect(nudge(routes, apart(['e0', 'e1']), [], [108]).e1![1]!.y).toBe(92); + }); + + it("never turns a port run back into the edge's own card", () => { + // The ninth track is 32px up: past the 20px run out of the card's bottom, and still MIN_RUN away from the port. + const card = { x: -88, y: -60, width: 176, height: 60 }; + const others = Object.fromEntries( + Array.from({ length: 8 }, (_, k) => [`o${k}`, [{ x: -100 - k * 10, y: -300 }, { x: -100 - k * 10, y: 20 }, { x: 400 + k * 10, y: 20 }, { x: 400 + k * 10, y: 300 }]]), + ); + const routes = { ...others, own: [{ x: 0, y: 0 }, { x: 0, y: 20 }, { x: 200, y: 20 }, { x: 200, y: 100 }] }; + const out = nudge(routes, apart(Object.keys(routes)), [card]); + expect(out.own![1]!.y).toBeGreaterThanOrEqual(12); + expect(hits(out, card)).toEqual([]); + }); + + it("does not stretch a port run onto the port facing it on another card's edge", () => { + // Two cards 44px apart: `down` leaves the upper one by x=88, `up` the lower one. The first track for `down` (+8) + // would bring its run to y=88, over the run `up` comes in by (84..104). + const cards = [{ x: 0, y: 0, width: 176, height: 60 }, { x: 0, y: 104, width: 176, height: 60 }]; + const routes = { + first: [{ x: 200, y: -50 }, { x: 200, y: 80 }, { x: 400, y: 80 }, { x: 400, y: 300 }], + down: [{ x: 88, y: 60 }, { x: 88, y: 80 }, { x: 300, y: 80 }, { x: 300, y: 300 }], + up: [{ x: 88, y: 104 }, { x: 88, y: 84 }, { x: -100, y: 84 }, { x: -100, y: 300 }], + }; + const out = nudge(routes, apart(Object.keys(routes)), cards); + expect(out.down![1]!.y).toBeLessThan(out.up![1]!.y); + expect(out.down![1]!.y).not.toBe(out.first![1]!.y); + }); +}); diff --git a/packages/layout/test/sequence.test.ts b/packages/layout/test/sequence.test.ts index 6dcbc0e..1ea7737 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')]); @@ -126,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']); 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]; diff --git a/packages/schema/src/rules/kinds.ts b/packages/schema/src/rules/kinds.ts index 4f91570..dc3f2c0 100644 --- a/packages/schema/src/rules/kinds.ts +++ b/packages/schema/src/rules/kinds.ts @@ -213,13 +213,14 @@ function phaseDiagnostics(d: DiagramDraft): Diagnostic[] { // edge; say so, it's usually a mistake. const back = phaseViolations(d); d.edges.forEach((e, i) => { - if (!back.has(e.id)) return; - const into = d.phases![owner.get(e.to)!]!.id; + const phase = back.get(e.id); + if (phase === undefined) return; + const into = d.phases![phase]!.id; out.push({ ...error('semantics/phase-order', `/edges/${i}`, `Edge "${e.id}" leads back into phase "${into}" from a later phase`, { id: e.id, phase: into }, [ 'mark it "kind": "return" if it loops back on purpose', 'reorder the phases', - `put "${e.from}" in a phase`, + ...(owner.has(e.from) ? [] : [`put "${e.from}" in a phase`]), ]), severity: 'warning', }); diff --git a/packages/schema/src/rules/schema.ts b/packages/schema/src/rules/schema.ts index 5099a52..293f700 100644 --- a/packages/schema/src/rules/schema.ts +++ b/packages/schema/src/rules/schema.ts @@ -29,7 +29,7 @@ const keysAt = (path: readonly PropertyKey[]) => Object.keys(schemaAt(path)?.pro */ function childAccepting(path: readonly PropertyKey[], key: string): string | undefined { const props = schemaAt(path)?.properties ?? {}; - return Object.keys(props).find((k) => props[k]!.type === 'object' && key in (props[k]!.properties ?? {})); + return Object.keys(props).find((k) => props[k]!.type === 'object' && Object.hasOwn(props[k]!.properties ?? {}, key)); } /** Whether the object enclosing `path` accepts `key` (card `evidence` belongs on the node). */ @@ -39,7 +39,7 @@ function parentAccepts(path: readonly PropertyKey[], key: string): boolean { const up = path.slice(0, -1); const parent = schemaAt(up); const obj = parent?.properties ? parent : schemaAt(up.slice(0, -1)); - return key in (obj?.properties ?? {}); + return Object.hasOwn(obj?.properties ?? {}, key); } // Names authors reach for that mean an existing field. @@ -54,6 +54,8 @@ function name(path: readonly PropertyKey[]): string { return typeof last === 'number' ? `item ${last} of "${String(path.at(-2))}"` : `"${String(last)}"`; } +const NUMERIC: ReadonlySet = new Set(['number', 'int', 'bigint']); + function fixes(issue: z.core.$ZodIssue, received: unknown): string[] { const key = String(issue.path.at(-1) ?? 'value'); switch (issue.code) { @@ -64,9 +66,13 @@ function fixes(issue: z.core.$ZodIssue, received: unknown): string[] { case 'invalid_value': return [`use one of: ${issue.values.map(String).join(', ')}`]; case 'too_big': - return issue.origin === 'array' ? [`keep at most ${issue.maximum} items`] : [`shorten "${key}" to at most ${issue.maximum} characters`]; + if (issue.origin === 'array') return [`keep at most ${issue.maximum} items`]; + if (NUMERIC.has(issue.origin)) return [`make "${key}" ${issue.inclusive ? 'at most' : 'less than'} ${issue.maximum}`]; + return [`shorten "${key}" to at most ${issue.maximum} characters`]; case 'too_small': - return issue.origin === 'array' ? [`add at least ${issue.minimum} item(s)`] : [`give "${key}" a non-empty value`]; + if (issue.origin === 'array') return [`add at least ${issue.minimum} item(s)`]; + if (NUMERIC.has(issue.origin)) return [`make "${key}" ${issue.inclusive ? 'at least' : 'greater than'} ${issue.minimum}`]; + return [`give "${key}" a non-empty value`]; case 'invalid_format': if (issue.format === 'regex' && issue.pattern === String(ID_PATTERN)) return [`use a lowercase id such as "${toId(String(received ?? ''))}"`]; @@ -80,7 +86,8 @@ function fixes(issue: z.core.$ZodIssue, received: unknown): string[] { case 'unrecognized_keys': { const allowed = keysAt(issue.path); return issue.keys.flatMap((k) => { - const alias = ALIASES[k]; + // Own keys only: an agent's stray `constructor` or `toString` is on every object's prototype. + const alias = Object.hasOwn(ALIASES, k) ? ALIASES[k] : undefined; if (alias && allowed.includes(alias)) return [`rename "${k}" to "${alias}"`]; // A node's `label` means its card title, not the similarly spelt `lane`. const aliasHome = alias && childAccepting(issue.path, alias); diff --git a/packages/schema/src/rules/semantics.ts b/packages/schema/src/rules/semantics.ts index 5940425..e60be4b 100644 --- a/packages/schema/src/rules/semantics.ts +++ b/packages/schema/src/rules/semantics.ts @@ -1,4 +1,4 @@ -import type { DiagramDraft } from '@stackmap/core'; +import { usesCompactCards, type DiagramDraft } from '@stackmap/core'; import type { Diagnostic } from '../diagnostics'; function duplicates(items: { id: string }[] | undefined, collection: string): Diagnostic[] { @@ -103,6 +103,16 @@ export function semanticsDiagnostics(d: DiagramDraft): Diagnostic[] { evidence: { id: n.id }, allowedFixes: ['add "stats"', 'remove "statsNote"', 'move the note into a card row'], }); + // The card reserves the footer band whether or not anything is in it. + if (n.card.footer && !n.card.footer.left && !n.card.footer.right && !usesCompactCards(d)) + out.push({ + code: 'semantics/empty-footer', + severity: 'warning', + subject: `/nodes/${i}/card/footer`, + message: `The footer on "${n.id}" is empty: it draws a blank band`, + evidence: { id: n.id }, + allowedFixes: ['add "left" or "right"', 'remove "footer"'], + }); }); // The authoring contract aims for ~10–40 nodes; well past that cards are unreadable at fit, and a grouped @@ -141,7 +151,8 @@ export function semanticsDiagnostics(d: DiagramDraft): Diagnostic[] { subject: `/edges/${i}`, message: `Edge "${e.id}" connects "${e.from}" to itself`, evidence: { id: e.id, node: e.from }, - allowedFixes: ['remove the edge', 'describe the loop in a card row instead'], + // Compact cards have no rows: that fix would trade this warning for an error. + allowedFixes: ['remove the edge', `describe the loop in ${usesCompactCards(d) ? 'an evidence note' : 'a card row'} instead`], }); }); diff --git a/packages/schema/test/kinds.test.ts b/packages/schema/test/kinds.test.ts index 4943e57..079e934 100644 --- a/packages/schema/test/kinds.test.ts +++ b/packages/schema/test/kinds.test.ts @@ -73,6 +73,15 @@ describe('kind rules', () => { expect(codes(d)).toEqual(['error:semantics/card-section-for-kind@/nodes/0/card/rows', 'error:semantics/card-section-for-kind@/nodes/0/card/cta']); }); + it('a self-loop on a compact card is not sent to a card row, which compact cards reject', () => { + const fixesFor = (d: unknown) => validateDiagram(d).diagnostics.find((x) => x.code === 'semantics/self-loop')!.allowedFixes; + const loop = { id: 'retry', from: 'build', to: 'build' }; + expect(fixesFor(workflow({ edges: [{ id: 'e1', from: 'commit', to: 'build' }, loop] }))).toEqual(['remove the edge', 'describe the loop in an evidence note instead']); + const full = { kind: 'architecture', title: 'T', nodes: [{ id: 'build', type: 'service', card: { title: 'B' } }], edges: [loop] }; + expect(fixesFor(full)).toEqual(['remove the edge', 'describe the loop in a card row instead']); + expect(fixesFor({ ...full, density: 'compact' })).toEqual(['remove the edge', 'describe the loop in an evidence note instead']); + }); + it('checks phase members, overlaps and order', () => { expect(codes(workflow({ phases: [{ id: 'p', label: 'P', edges: ['e1'] }] }))).toEqual(['error:semantics/phase-members@/phases/0/edges', 'error:semantics/phase-members@/phases/0']); expect(codes(workflow({ phases: [{ id: 'p', label: 'P', nodes: ['commit'] }, { id: 'q', label: 'Q', nodes: ['commit', 'build'] }] }))).toEqual([ @@ -105,6 +114,13 @@ describe('kind rules', () => { ], }; expect(codes(d)).toEqual(['warning:semantics/phase-order@/edges/1']); + // "trace" is in no phase, so placing it is a way out. + expect(validateDiagram(d).diagnostics[0]!.allowedFixes).toContain('put "trace" in a phase'); + }); + + it('does not suggest phasing the source of a phase-order edge that already has a phase', () => { + const d = workflow({ phases: [{ id: 'p', label: 'P', nodes: ['build'] }, { id: 'q', label: 'Q', nodes: ['commit'] }] }); + expect(validateDiagram(d).diagnostics[0]!.allowedFixes).toEqual(['mark it "kind": "return" if it loops back on purpose', 'reorder the phases']); }); it('warns when a lane group would frame a step that is not in it', () => { diff --git a/packages/schema/test/validate.test.ts b/packages/schema/test/validate.test.ts index bcddece..2a1ce60 100644 --- a/packages/schema/test/validate.test.ts +++ b/packages/schema/test/validate.test.ts @@ -124,6 +124,18 @@ describe('validateDiagram', () => { }); }); + it('a number out of range gets a number fix, not a text one', () => { + const withLine = (line: number) => base({ nodes: [node('a', { evidence: [{ file: 'a.ts', line }] }), node('b')] }); + expect(diags(withLine(0))[0]).toMatchObject({ code: 'schema/too_small', subject: '/nodes/0/evidence/0/line', allowedFixes: ['make "line" greater than 0'] }); + }); + + it('an unknown key named like an Object.prototype member is just removed', () => { + for (const key of ['constructor', 'toString', 'hasOwnProperty']) { + const [d] = diags(base({ nodes: [node('a', { [key]: 1 } as never), node('b')] })); + expect(d).toMatchObject({ code: 'schema/unrecognized_keys', subject: '/nodes/0', allowedFixes: [expect.stringMatching(new RegExp(`^remove "${key}" \\(not valid here`))] }); + } + }); + it('limits say how far to cut', () => { const stats = Array.from({ length: 4 }, (_, i) => ({ value: String(i), label: 'x' })); expect(diags(base({ nodes: [node('a', { card: { title: 'a', stats } })] }))[0]).toMatchObject({ @@ -236,6 +248,15 @@ describe('validateDiagram', () => { ]); }); + it('an empty footer is a warning (it draws a blank band)', () => { + expect(only(base({ nodes: [node('a', { card: { title: 'a', footer: {} } }), node('b')] }), 'semantics/empty-footer')).toMatchObject([ + { severity: 'warning', subject: '/nodes/0/card/footer', allowedFixes: ['add "left" or "right"', 'remove "footer"'] }, + ]); + expect(only(base({ nodes: [node('a', { card: { title: 'a', footer: { right: { text: 'eu' } } } }), node('b')] }), 'semantics/empty-footer')).toEqual([]); + // Compact cards already reject the footer outright. + expect(only(base({ density: 'compact', nodes: [node('a', { card: { title: 'a', footer: {} } }), node('b')] }), 'semantics/empty-footer')).toEqual([]); + }); + it('a duplicate id rename suggestion is itself unused', () => { const d = base({ nodes: [node('a'), node('a-2'), node('a')], edges: [] }); expect(only(d, 'semantics/duplicate-id')[0]!.allowedFixes[0]).toBe('rename to a unique id, e.g. "a-3"'); 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/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/e2e/motion.spec.ts b/packages/viewer/e2e/motion.spec.ts index 9164da7..5e38b4a 100644 --- a/packages/viewer/e2e/motion.spec.ts +++ b/packages/viewer/e2e/motion.spec.ts @@ -91,3 +91,40 @@ 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); +}); + +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/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/canvas/DiagramCanvas.test.tsx b/packages/viewer/src/canvas/DiagramCanvas.test.tsx index 3352e73..7cf63bb 100644 --- a/packages/viewer/src/canvas/DiagramCanvas.test.tsx +++ b/packages/viewer/src/canvas/DiagramCanvas.test.tsx @@ -1,8 +1,11 @@ import { fireEvent, render } from '@testing-library/react'; +import { useRef } from 'react'; import { describe, expect, it, vi } from 'vitest'; import { commerceApiLayout } from '../samples/commerce-api.layout'; import { ExploreProvider } from '../explore/ExploreContext'; +import { ViewerScope } from '../explore/scope'; import { DiagramCanvas } from './DiagramCanvas'; +import { StaticScene } from './StaticScene'; const { nodeCardRenders } = vi.hoisted(() => ({ nodeCardRenders: vi.fn() })); @@ -47,4 +50,54 @@ describe('DiagramCanvas', () => { expect([emphasis('orders'), emphasis('sessions')]).toEqual(['focus', 'dim']); expect(nodeCardRenders).not.toHaveBeenCalled(); }); + + it('shares nothing document-wide with another drawing of the same diagram on the page', () => { + function Embedded() { + const root = useRef(null); + return ( + +
+ + + +
+
+ ); + } + const { getAllByTestId } = render( + <> + + + + , + ); + const [first, second] = getAllByTestId('embedded') as [HTMLElement, HTMLElement]; + // Arrow keys move focus to a card of the viewer they were pressed in, not the first copy in the document. + const from = second.querySelector('.sm-card[data-card-id="orders"]')!; + from.focus(); + fireEvent.keyDown(from, { key: 'ArrowDown' }); + expect(second.contains(document.activeElement)).toBe(true); + expect(document.activeElement).not.toBe(from); + // Each canvas paints its dot grid from its own pattern. + const fill = (el: HTMLElement) => el.querySelector('rect[fill^="url(#"]')!.getAttribute('fill')!.slice(5, -1); + expect(fill(first)).not.toBe(fill(second)); + expect(first.querySelector('pattern')!.id).toBe(fill(first)); + }); + + 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..9b913d4 100644 --- a/packages/viewer/src/canvas/DiagramCanvas.tsx +++ b/packages/viewer/src/canvas/DiagramCanvas.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; import type { LaidOutDiagram, Rect } from '@stackmap/core'; import { ZoomBar } from '../chrome/ZoomBar'; import { motionAllowed } from '../motion/motion'; @@ -77,10 +77,12 @@ const DOT = 1.2; function DotGrid({ x, y, k }: Transform) { const gap = GRID * k; const r = (DOT * k) / 2; + // Pattern ids are document-wide, and a page may embed several viewers. + const id = `sm-grid${useId().replace(/[^\w-]/g, '')}`; return ( ); } @@ -148,8 +150,9 @@ export function DiagramCanvas({ // M toggles the radar from anywhere but a text field or menu; not while presenting (it's hidden then). const chromeRef = useRef(chrome); chromeRef.current = chrome; - const playableRef = useRef(false); - playableRef.current = state.playing || hasFlow(state, emphasis); + // Read when P is pressed: this renders on every pan and zoom frame, and hasFlow walks every edge. + const shown = useRef({ state, emphasis }); + shown.current = { state, emphasis }; // P plays or stops the flow, presenting too; with reduced motion, or nothing shown to play, it does nothing. useEffect(() => { const onKey = (e: globalThis.KeyboardEvent) => { @@ -158,7 +161,7 @@ export function DiagramCanvas({ const t = e.target as HTMLElement | null; if (e.metaKey || e.ctrlKey || e.altKey || e.repeat || inMenu(t) || (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))) return; if (key === 'm' && (!chromeRef.current || !withMinimap)) return; - if (key === 'p' && (!motionAllowed() || !playableRef.current)) return; + if (key === 'p' && (!motionAllowed() || !(shown.current.state.playing || hasFlow(shown.current.state, shown.current.emphasis)))) return; e.preventDefault(); if (key === 'm') setMinimap((v) => !v); else dispatch({ type: 'togglePlay' }); @@ -166,12 +169,14 @@ export function DiagramCanvas({ addEventListener('keydown', onKey); return () => removeEventListener('keydown', onKey); }, [dispatch, inScope, withMinimap]); - const flow = useFlow(scene); const playing = state.playing && motionAllowed(); + const flow = useFlow(scene, playing); useSceneReveal(sceneRef, scene, viewport.restored); // 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/FlowLayer.test.tsx b/packages/viewer/src/canvas/FlowLayer.test.tsx index 3895645..9b669fa 100644 --- a/packages/viewer/src/canvas/FlowLayer.test.tsx +++ b/packages/viewer/src/canvas/FlowLayer.test.tsx @@ -1,6 +1,9 @@ -import { render } from '@testing-library/react'; +import { act, render } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ExploreProvider } from '../explore/ExploreContext'; import type { Flow } from '../motion/flow'; +import { useInFlight } from '../motion/inFlight'; +import { commerceApiLayout } from '../samples/commerce-api.layout'; import { FlowLayer, playingClock, type FlowClock } from './FlowLayer'; const flow: Flow = { @@ -42,6 +45,38 @@ describe('FlowLayer', () => { }); }); +describe('FlowLayer, in flight', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('tells its own explorer which edges a pulse is on, and no other diagram on the page', () => { + const frames: FrameRequestCallback[] = []; + vi.stubGlobal('requestAnimationFrame', (f: FrameRequestCallback) => frames.push(f)); + vi.stubGlobal('cancelAnimationFrame', () => {}); + const seen: Record = {}; + const Probe = ({ name }: { name: string }) => { + seen[name] = [...useInFlight()]; + return null; + }; + const { draft } = commerceApiLayout; + render( + <> + + + + + + + + , + ); + act(() => { + frames.shift()!(1000); + frames.shift()!(1100); + }); + expect(seen).toEqual({ playing: ['ab'], still: [] }); + }); +}); + describe('playingClock', () => { afterEach(() => vi.unstubAllGlobals()); diff --git a/packages/viewer/src/canvas/FlowLayer.tsx b/packages/viewer/src/canvas/FlowLayer.tsx index b456179..480f555 100644 --- a/packages/viewer/src/canvas/FlowLayer.tsx +++ b/packages/viewer/src/canvas/FlowLayer.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef } from 'react'; import type { Point } from '@stackmap/core'; import { glowAt, pointAt, PULSE, pulseFrame, ringAt, sliceAt, type Flow, type FlowPulse } from '../motion/flow'; -import { setInFlight } from '../motion/inFlight'; +import { useInFlightStore } from '../motion/inFlight'; const accent = (p: FlowPulse) => `var(--sm-${p.tint}-accent)`; const polyline = (path: Point[]) => `M${path.map((q) => `${q.x} ${q.y}`).join('L')}`; @@ -38,6 +38,7 @@ export function FlowLayer({ flow, width, height, speed = 1, clock }: { flow: Flo const root = useRef(null); const rate = useRef(speed); rate.current = speed; + const inFlight = useInFlightStore(); useEffect(() => { const groups = [...(root.current?.children ?? [])] as SVGGElement[]; if (!groups.length) return; @@ -55,7 +56,7 @@ export function FlowLayer({ flow, width, height, speed = 1, clock }: { flow: Flo return on; }; // Only the viewer's own playback says which edges are in flight; a borrowed clock is someone else's. - const tracked = !clock; + const tracked = clock ? null : inFlight; const draw = (ms: number | null) => { const flying: string[] = []; flow.pulses.forEach((p, i) => { @@ -96,14 +97,14 @@ export function FlowLayer({ flow, width, height, speed = 1, clock }: { flow: Flo h.setAttribute('transform', `translate(${at.x} ${at.y})`); }); }); - if (tracked) setInFlight(flying); + tracked?.set(flying); }; const stop = (clock ?? playingClock(() => rate.current))(draw); return () => { stop(); - if (tracked) setInFlight([]); + tracked?.set([]); }; - }, [flow, clock]); + }, [flow, clock, inFlight]); return (
@@ -178,7 +181,7 @@ function NodeDetail({ node, toggle }: { node: DiagramNode; toggle: ReactNode }) label="Clear selection (Esc)" onClick={() => { dispatch({ type: 'clear' }); - focusCard(node.id); // back where the keyboard user came from + focusCard(node.id, root()); // back where the keyboard user came from }} > @@ -198,26 +201,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/SearchPanel.tsx b/packages/viewer/src/chrome/SearchPanel.tsx index 0ebda34..2b3b3cb 100644 --- a/packages/viewer/src/chrome/SearchPanel.tsx +++ b/packages/viewer/src/chrome/SearchPanel.tsx @@ -3,6 +3,7 @@ import { TYPE_LABELS } from '@stackmap/core'; import { searchMatches } from '../explore/emphasis'; import { focusCard } from '../canvas/SceneLayers'; import { useExplore } from '../explore/ExploreContext'; +import { useViewerRoot } from '../explore/scope'; import { popIn } from '../motion/motion'; import { useEnter } from '../motion/useEnter'; import { PANEL_CLASS, PANEL_STYLE } from './ui'; @@ -12,6 +13,7 @@ const MAX_RESULTS = 8; /** `origin`: the trigger's centre, so the panel grows out of it; omitted, the panel just appears (keyboard `/`). */ export function SearchPanel({ onClose, origin }: { onClose: () => void; origin?: string }) { const { draft, state, dispatch } = useExplore(); + const root = useViewerRoot(); const input = useRef(null); const panel = useRef(null); useEnter(panel, (el) => popIn(el, origin!), !!origin); @@ -25,7 +27,7 @@ export function SearchPanel({ onClose, origin }: { onClose: () => void; origin?: const choose = (id: string) => { dispatch({ type: 'select', id, reveal: true }); dispatch({ type: 'search', query: null }); - requestAnimationFrame(() => focusCard(id)); + requestAnimationFrame(() => focusCard(id, root())); }; return (
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(); 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 ? (
diff --git a/packages/viewer/src/explore/ExploreContext.tsx b/packages/viewer/src/explore/ExploreContext.tsx index 32fd7e7..502e57f 100644 --- a/packages/viewer/src/explore/ExploreContext.tsx +++ b/packages/viewer/src/explore/ExploreContext.tsx @@ -1,7 +1,8 @@ -import { createContext, useContext, useEffect, useMemo, useReducer, useRef, type Dispatch, type ReactNode } from 'react'; +import { createContext, useContext, useEffect, useMemo, useReducer, useRef, useState, type Dispatch, type ReactNode } from 'react'; import type { DiagramDraft } from '@stackmap/core'; import { emphasis, type Emphasis } from './emphasis'; import { buildGraph, type Graph } from './graph'; +import { createInFlight, InFlightProvider } from '../motion/inFlight'; import { explore, formatHash, INITIAL, parseHash, type ExploreAction, type ExploreState, type Known } from './state'; export interface Explore { @@ -77,9 +78,12 @@ export function ExploreProvider({ }, [known, syncHash]); const value = useMemo(() => ({ draft, state, dispatch, graph, emphasis: em }), [draft, state, graph, em]); + const [inFlight] = useState(createInFlight); return ( - {children} + + {children} + ); } 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), diff --git a/packages/viewer/src/explore/scope.ts b/packages/viewer/src/explore/scope.ts index 23f616b..3d76640 100644 --- a/packages/viewer/src/explore/scope.ts +++ b/packages/viewer/src/explore/scope.ts @@ -6,6 +6,12 @@ const ScopeContext = createContext | null>(null); export const ViewerScope = ScopeContext.Provider; +/** Where this viewer's own elements are looked up: its scope, or the page when a delivered file is all of it. */ +export function useViewerRoot(): () => ParentNode { + const root = useContext(ScopeContext); + return useCallback(() => root?.current ?? document, [root]); +} + /** Whether a window key event is the viewer's to handle: always without a scope, else only from inside it. */ export function useInScope(): (e: Event) => boolean { const root = useContext(ScopeContext); diff --git a/packages/viewer/src/motion/flowOf.ts b/packages/viewer/src/motion/flowOf.ts index 3b86263..8dd6796 100644 --- a/packages/viewer/src/motion/flowOf.ts +++ b/packages/viewer/src/motion/flowOf.ts @@ -5,8 +5,17 @@ import type { ExploreState } from '../explore/state'; import { EDGE_RADIUS, type Scene } from '../canvas/scene'; import { hopFlow, hopRanks, NO_FLOW, roundedPolyline, waveFlow, type Flow, type FlowEdge } from './flow'; +// Read from the scene alone, while a flow is rebuilt for every change of emphasis (a selection, a search keystroke). +const built = new WeakMap>(); + /** What a pulse needs from the scene: its drawn route, its tint, and what lights up when it lands. */ function flowEdges(scene: Scene): Map { + let edges = built.get(scene); + if (!edges) built.set(scene, (edges = buildFlowEdges(scene))); + return edges; +} + +function buildFlowEdges(scene: Scene): Map { const cards = new Map(scene.cards.map((c) => [c.node.id, c])); const radius = scene.compact ? COMPACT.radius : CARD.radius; return new Map( diff --git a/packages/viewer/src/motion/inFlight.ts b/packages/viewer/src/motion/inFlight.ts index cc16b0f..cf8f32b 100644 --- a/packages/viewer/src/motion/inFlight.ts +++ b/packages/viewer/src/motion/inFlight.ts @@ -1,23 +1,46 @@ -import { useSyncExternalStore } from 'react'; +import { createContext, useContext, useSyncExternalStore } from 'react'; -// The edges a pulse is travelling right now, for chrome that follows playback (the route's step list). -// Published by the flow layer only when the set changes, so subscribers re-render per hop, not per frame. const EMPTY: ReadonlySet = new Set(); -let current = EMPTY; -let key = ''; -const listeners = new Set<() => void>(); -export function setInFlight(ids: string[]): void { - const next = ids.join('\n'); - if (next === key) return; - key = next; - current = ids.length ? new Set(ids) : EMPTY; - listeners.forEach((l) => l()); +/** + * The edges a pulse is travelling right now, for chrome that follows playback (the route's step list). + * Published by the flow layer only when the set changes, so subscribers re-render per hop, not per frame. + */ +export interface InFlight { + set(ids: string[]): void; + get(): ReadonlySet; + subscribe(listener: () => void): () => void; } -const subscribe = (l: () => void) => { - listeners.add(l); - return () => listeners.delete(l); -}; +export function createInFlight(): InFlight { + let current = EMPTY; + let key = ''; + const listeners = new Set<() => void>(); + return { + set(ids) { + const next = ids.join('\n'); + if (next === key) return; + key = next; + current = ids.length ? new Set(ids) : EMPTY; + listeners.forEach((l) => l()); + }, + get: () => current, + subscribe(l) { + listeners.add(l); + return () => listeners.delete(l); + }, + }; +} + +// One per explorer, not per page: several diagrams can play on one page, each with its own chrome. +const InFlightContext = createContext(null); +export const InFlightProvider = InFlightContext.Provider; +export const useInFlightStore = (): InFlight | null => useContext(InFlightContext); -export const useInFlight = (): ReadonlySet => useSyncExternalStore(subscribe, () => current, () => EMPTY); +const none = () => () => {}; +const empty = () => EMPTY; + +export function useInFlight(): ReadonlySet { + const store = useContext(InFlightContext); + return useSyncExternalStore(store?.subscribe ?? none, store?.get ?? empty, empty); +} diff --git a/packages/viewer/src/motion/useFlow.test.ts b/packages/viewer/src/motion/useFlow.test.ts index adfa28c..4b7d925 100644 --- a/packages/viewer/src/motion/useFlow.test.ts +++ b/packages/viewer/src/motion/useFlow.test.ts @@ -66,6 +66,13 @@ describe('which flow plays', () => { }); }); +describe('what a flow costs', () => { + it('builds the edge geometry once per scene, not once per change of emphasis', () => { + const path = (s: Partial) => flow(s).pulses.find((p) => p.id === 'bc')!.path; + expect(path({ selected: 'c' })).toBe(path({})); + }); +}); + describe('whether there is a flow to play', () => { const playable = (s: Partial) => { const state = { ...INITIAL, ...s }; diff --git a/packages/viewer/src/motion/useFlow.ts b/packages/viewer/src/motion/useFlow.ts index 06df042..378e3e2 100644 --- a/packages/viewer/src/motion/useFlow.ts +++ b/packages/viewer/src/motion/useFlow.ts @@ -1,13 +1,14 @@ import { useMemo } from 'react'; import { useExplore } from '../explore/ExploreContext'; import type { Scene } from '../canvas/scene'; -import type { Flow } from './flow'; +import { NO_FLOW, type Flow } from './flow'; import { flowOf } from './flowOf'; export { flowOf }; -export function useFlow(scene: Scene): Flow { +/** `on` false (nothing is playing): no flow is built, so a change of emphasis costs nothing here. */ +export function useFlow(scene: Scene, on = true): Flow { const { graph, state, emphasis } = useExplore(); const { route, selected } = state; - return useMemo(() => flowOf(scene, graph, { route, selected }, emphasis), [scene, graph, route, selected, emphasis]); + return useMemo(() => (on ? flowOf(scene, graph, { route, selected }, emphasis) : NO_FLOW), [on, scene, graph, route, selected, emphasis]); } diff --git a/packages/viewer/src/samples/gallery.layout.ts b/packages/viewer/src/samples/gallery.layout.ts index 1980985..5d02718 100644 --- a/packages/viewer/src/samples/gallery.layout.ts +++ b/packages/viewer/src/samples/gallery.layout.ts @@ -464,11 +464,11 @@ export const galleryLayouts: Record = { }, { "x": 1528, - "y": 708 + "y": 700 }, { "x": 1576, - "y": 708 + "y": 700 }, { "x": 1576, @@ -571,7 +571,7 @@ export const galleryLayouts: Record = { }, "e9": { "x": 1576, - "y": 814.6 + "y": 811.8 }, "e10": { "x": 1288, @@ -1059,19 +1059,19 @@ export const galleryLayouts: Record = { }, { "x": 1048, - "y": 684 + "y": 676 }, { "x": 1096, - "y": 684 + "y": 676 }, { "x": 1096, - "y": 808 + "y": 800 }, { "x": 1048, - "y": 808 + "y": 800 }, { "x": 1048, @@ -1148,7 +1148,7 @@ export const galleryLayouts: Record = { }, "e10": { "x": 1096, - "y": 783.2 + "y": 775.2 } }, "bounds": { @@ -2691,11 +2691,11 @@ export const galleryLayouts: Record = { }, { "x": 1316, - "y": 484 + "y": 476 }, { "x": 1364, - "y": 484 + "y": 476 }, { "x": 1364, @@ -2765,11 +2765,11 @@ export const galleryLayouts: Record = { }, "restored": { "x": 1398, - "y": 536 + "y": 532 } }, "bounds": { - "width": 1420, + "width": 1444, "height": 736 } }, diff --git a/site/app/docs/cli/page.tsx b/site/app/docs/cli/page.tsx index cb61962..0c75d85 100644 --- a/site/app/docs/cli/page.tsx +++ b/site/app/docs/cli/page.tsx @@ -4,6 +4,7 @@ import { C, DocHead, H2, H3, P, Table } from '@/components/docs/prose'; import { Tabs } from '@/components/docs/Tabs'; import { Cmd } from '@/components/ui/Cmd'; import { JsonCode, Terminal } from '@/components/ui/Code'; +import { PACKAGE } from '@/lib/package'; import { CLI_COMMANDS, CLI_OPTIONS, EXIT_CODES, FAMILIES, type Family } from '@/lib/reference'; import { OPEN_GRAPH } from '@/lib/seo'; import { SITE } from '@/lib/site-data'; @@ -16,7 +17,7 @@ export const metadata: Metadata = { }; const DEMO = '.stackmap/commerce-api/diagram.json'; -const npx = `npx @omsimos/stackmap@${SITE.version}`; +const npx = `npx ${PACKAGE}@${SITE.version}`; function Synopsis({ name }: { name: (typeof CLI_COMMANDS)[number]['name'] }) { const c = CLI_COMMANDS.find((x) => x.name === name)!; diff --git a/site/app/docs/page.tsx b/site/app/docs/page.tsx index 55dce03..25e7242 100644 --- a/site/app/docs/page.tsx +++ b/site/app/docs/page.tsx @@ -12,6 +12,8 @@ import { EXAMPLES } from '@/lib/catalog'; import { SOURCES, stillOf } from '@/lib/diagrams'; import { kindHref } from '@/lib/docs-nav'; import { jsonOwners } from '@/lib/json-lines'; +import { KIND_PAGES } from '@/lib/kinds'; +import { schemaUrl } from '@/lib/package'; import { OPEN_GRAPH } from '@/lib/seo'; import { SITE } from '@/lib/site-data'; import { spell } from '@/lib/words'; @@ -23,9 +25,9 @@ export const metadata: Metadata = { openGraph: { ...OPEN_GRAPH, url: '/docs' }, }; -const ASK = 'Make an architecture diagram of this repository, backed by evidence from the code.'; +const ASK = KIND_PAGES.architecture.ask; // The agent's file pins the schema to the installed CLI, so the example does too. -const JSON_TEXT = SOURCES.quickStart.replace('{\n', `{\n "$schema": "https://unpkg.com/@omsimos/stackmap@${SITE.version}/dist/stackmap.schema.json",\n`); +const JSON_TEXT = SOURCES.quickStart.replace('{\n', `{\n "$schema": "${schemaUrl(SITE.version)}",\n`); const FILE = '.stackmap/commerce-api/diagram.json'; function Step({ n, id, title, children }: { n: number; id: string; title: string; children: React.ReactNode }) { diff --git a/site/app/docs/schema/page.tsx b/site/app/docs/schema/page.tsx index 258a58f..ef1aef4 100644 --- a/site/app/docs/schema/page.tsx +++ b/site/app/docs/schema/page.tsx @@ -11,6 +11,7 @@ import { JsonCode } from '@/components/ui/Code'; import { formatJson } from '@/lib/data/json-format'; import type { SchemaField, SchemaSection } from '@/lib/data/schema-ref'; import { diagramOf } from '@/lib/diagrams'; +import { schemaUrl } from '@/lib/package'; import { INTROS, SAMPLE_CARD, SAMPLES, diagramOutline } from '@/lib/schema-docs'; import { blocks, notePieces, type Placement } from '@/lib/schema-page'; import { OPEN_GRAPH } from '@/lib/seo'; @@ -115,7 +116,7 @@ export default function SchemaPage() {

diff --git a/site/app/examples/[key]/page.tsx b/site/app/examples/[key]/page.tsx index 98c8790..056cecf 100644 --- a/site/app/examples/[key]/page.tsx +++ b/site/app/examples/[key]/page.tsx @@ -12,6 +12,7 @@ import { diagramOf, SOURCES, stillOf } from '@/lib/diagrams'; import { kindHref } from '@/lib/docs-nav'; import { KIND_PAGES } from '@/lib/kinds'; import { OPEN_GRAPH } from '@/lib/seo'; +import { article } from '@/lib/words'; export const dynamicParams = false; @@ -27,9 +28,10 @@ export async function generateMetadata({ params }: PageProps<'/examples/[key]'>) if (!e) return {}; const { draft } = diagramOf(e); const href = exampleHref(e); + const kind = KIND_LABELS[e.kind].toLowerCase(); return { title: `${draft.title} · Examples`, - description: `${draft.subtitle ? `${draft.subtitle}. ` : ''}A ${KIND_LABELS[e.kind].toLowerCase()} diagram laid out by stackmap, open in the viewer.`, + description: `${draft.subtitle ? `${draft.subtitle}. ` : ''}${article(kind, true)} ${kind} diagram laid out by stackmap, open in the viewer.`, alternates: { canonical: href }, openGraph: { ...OPEN_GRAPH, url: href }, }; diff --git a/site/app/layout.tsx b/site/app/layout.tsx index a104e9b..1df29d7 100644 --- a/site/app/layout.tsx +++ b/site/app/layout.tsx @@ -7,7 +7,7 @@ import { DocsFooter, Footer } from '@/components/site/Footer'; import { FooterFor } from '@/components/site/FooterFor'; import { Nav } from '@/components/site/Nav'; import { DESCRIPTION, OPEN_GRAPH, SITE_NAME, siteUrl } from '@/lib/seo'; -import { THEME_SCRIPT, themeCss } from '@/lib/theme'; +import { SETTLED_SCRIPT, THEME_SCRIPT, themeCss } from '@/lib/theme'; import './globals.css'; import './site.css'; @@ -30,10 +30,11 @@ export const viewport: Viewport = { export default function RootLayout({ children }: { children: ReactNode }) { return ( - // The head script sets data-theme from the reader's stored choice before React hydrates. - + // The head script sets data-theme from the reader's stored choice before React hydrates. data-scroll-behavior + // has the router land on a new page at once instead of gliding there (the CSS glide is for moves within a page). + -