diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 25ef5b9..4576aa0 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -1,7 +1,6 @@ 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'; @@ -72,10 +71,9 @@ export async function buildHtml( ): Promise { const result = validateFile(path); if (!result.ok || !result.diagram) return result; - const { kind, nodes, edges } = result.diagram; + const { nodes, edges } = result.diagram; // The result only prints once the layout is done; without this a big diagram looks hung for minutes. - // Lane and sequence kinds have their own layouts, which take a second at their largest. - if (progress && !isLaneKind(kind) && kind !== 'sequence' && isLarge(result.diagram)) + if (progress && 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 8663e1b..324f830 100644 --- a/packages/cli/src/open.ts +++ b/packages/cli/src/open.ts @@ -1,13 +1,22 @@ import { execFileSync, spawn } from 'node:child_process'; -import { readFileSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { resolve } from 'node:path'; /** * 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. + * start (WSL): its Windows path goes on the end of `args`, as an encoded command; `windowsFile` is one whose Windows + * path goes there as it is. `wait` is how long, in ms, the opener gets to exit before it counts as having handed the + * file off. `blind` marks an opener whose exit code says nothing, so that having started is all it can report. */ -export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number }; +export type Opener = { + cmd: string; + args: string[]; + orAt?: () => string; + startFile?: string; + windowsFile?: string; + wait?: number; + blind?: true; +}; 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. @@ -17,19 +26,26 @@ const HANDED_OFF = 3000; const WINDOWS_START = 15000; // WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt. -function powershell(): string { +const inWindows = (path: string) => (): string => { try { - return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'); + return wslpath('-u', `C:\\Windows\\${path}`); } catch { - return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'; + return `/mnt/c/Windows/${path.replaceAll('\\', '/')}`; } -} +}; + +const INTEROP = ['/proc/sys/fs/binfmt_misc/WSLInterop', '/proc/sys/fs/binfmt_misc/WSLInterop-late']; /** 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 { +export function isWsl( + env: NodeJS.ProcessEnv = process.env, + read: (path: string) => string = (path) => readFileSync(path, 'utf8'), + has: (path: string) => boolean = existsSync, +): boolean { if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true; try { - return /microsoft/i.test(readFileSync('/proc/version', 'utf8')); + // A Docker Desktop container runs on the WSL kernel too, but only WSL itself registers the Windows interop. + return /microsoft/i.test(read('/proc/version')) && INTEROP.some(has); } catch { return false; } @@ -53,14 +69,16 @@ export function browserCommands( // nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file. const start: Opener = { cmd: 'powershell.exe', - orAt: powershell, + orAt: inWindows('System32\\WindowsPowerShell\\v1.0\\powershell.exe'), 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] }]; + // Where policy blocks PowerShell, explorer.exe still opens the file; it exits 1 either way. + const explorer: Opener = { cmd: 'explorer.exe', orAt: inWindows('explorer.exe'), args: [], windowsFile: file, wait: WINDOWS_START, blind: true }; + return [...viaWslview, start, explorer, { cmd: 'xdg-open', args: [file] }]; } export function startCommand(windowsPath: string): string { @@ -96,23 +114,25 @@ export async function openWith( } async function run( - { cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener, + { cmd, args, orAt, startFile, windowsFile, wait = HANDED_OFF, blind }: Opener, windowsPath: (file: string) => string, ): Promise { - if (startFile !== undefined) { + const file = startFile ?? windowsFile; + if (file !== undefined) { try { - args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')]; + const path = windowsPath(resolve(file)); + args = [...args, startFile === undefined ? path : Buffer.from(startCommand(path), 'utf16le').toString('base64')]; } catch (e) { return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path"; } } - let why = await launch(cmd, args, wait); - if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait); + let why = await launch(cmd, args, wait, blind); + if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait, blind); return why === null ? null : `${cmd} ${why}`; } /** 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 { +function launch(cmd: string, args: string[], wait: number, blind = false): Promise { return new Promise((done) => { const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' }); const timer = setTimeout(() => done(null), wait); @@ -121,7 +141,7 @@ function launch(cmd: string, args: string[], wait: number): Promise finish((e as NodeJS.ErrnoException).code === 'ENOENT' ? NOT_FOUND : `failed (${e.message})`)); - child.once('exit', (code, signal) => finish(code ? `exited with ${code}` : signal ? `was killed by ${signal}` : null)); + child.once('exit', (code, signal) => finish(blind ? null : code ? `exited with ${code}` : signal ? `was killed by ${signal}` : null)); child.unref(); }); } diff --git a/packages/cli/test/open.test.ts b/packages/cli/test/open.test.ts index 43e1681..ccc49cc 100644 --- a/packages/cli/test/open.test.ts +++ b/packages/cli/test/open.test.ts @@ -15,7 +15,8 @@ describe('browserCommands', () => { it('tries the Windows side first on WSL, and xdg-open last', () => { const commands = browserCommands('/tmp/a.html', 'linux', true) as Opener[]; - expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']); + expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'explorer.exe', 'xdg-open']); + expect(commands[2]).toMatchObject({ windowsFile: '/tmp/a.html', blind: true, args: [] }); // 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'); @@ -24,7 +25,7 @@ describe('browserCommands', () => { 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']); + expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'explorer.exe', 'xdg-open']); } }); @@ -50,6 +51,15 @@ describe('isWsl', () => { expect(isWsl({ WSL_DISTRO_NAME: 'Ubuntu' })).toBe(true); expect(isWsl({ WSL_INTEROP: '/run/WSL/1_interop' })).toBe(true); }); + + it('takes a WSL kernel for WSL only where the Windows interop is registered', () => { + const kernel = () => 'Linux version 5.15.167.4-microsoft-standard-WSL2'; + expect(isWsl({}, kernel, (path) => path.endsWith('/WSLInterop'))).toBe(true); + expect(isWsl({}, kernel, (path) => path.endsWith('/WSLInterop-late'))).toBe(true); + // A Docker Desktop container. + expect(isWsl({}, kernel, () => false)).toBe(false); + expect(isWsl({}, () => 'Linux version 6.8.0-generic', () => true)).toBe(false); + }); }); describe('startCommand', () => { @@ -78,6 +88,16 @@ describe('openWith', () => { expect(await openWith([{ cmd: MISSING, orAt: () => `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`); }); + it('takes a blind opener as having opened once it has run, whatever it exits with', async () => { + expect(await openWith([{ ...exits(1), blind: true }])).toBeNull(); + expect(await openWith([{ cmd: MISSING, args: [], blind: true }])).toBe(`${MISSING} not found`); + }); + + posix('hands a windowsFile opener the Windows path itself', async () => { + const check = `process.exit(process.argv[1] === 'W:\\\\a.html' ? 0 : 7)`; + expect(await openWith([{ cmd: NODE, args: ['-e', check], windowsFile: '/home/u/a.html' }], () => 'W:\\a.html')).toBeNull(); + }); + 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(); diff --git a/packages/core/src/diagram-stats.ts b/packages/core/src/diagram-stats.ts index 048fad7..e99a4fb 100644 --- a/packages/core/src/diagram-stats.ts +++ b/packages/core/src/diagram-stats.ts @@ -27,6 +27,9 @@ export const TYPE_LABELS: Record = { neutral: 'Neutral', }; +/** Past this many nodes validation warns to split the diagram, and the layout takes its cheaper settings. */ +export const LARGE_DIAGRAM = 60; + export function countByType(nodes: DiagramNode[]): [NodeType, number][] { const counts = new Map(); for (const n of nodes) counts.set(n.type, (counts.get(n.type) ?? 0) + 1); diff --git a/packages/layout/src/index.ts b/packages/layout/src/index.ts index 60ff555..367ae24 100644 --- a/packages/layout/src/index.ts +++ b/packages/layout/src/index.ts @@ -5,7 +5,7 @@ import { Worker as Thread } from 'node:worker_threads'; import ElkApi from 'elkjs/lib/elk-api.js'; import ElkBundled from 'elkjs/lib/elk.bundled.js'; import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk-api'; -import { cardSize, isLaneKind, measureText, round, usesCompactCards, type DiagramDraft, type DiagramGroup, type Direction, type LaidOutDiagram, type Point, type Rect } from '@stackmap/core'; +import { cardSize, isLaneKind, LARGE_DIAGRAM, 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 { boundsWithLabels, placeLabels } from './labels'; import { layoutLanes } from './lanes'; @@ -24,13 +24,16 @@ const COMPACT_GAP = { right: 72, max: 168 } as const; /** Widest layer gap a full-card layout grows to so its labels fit. */ const FULL_GAP_MAX = 280; const GROUP_LAYER_GAP = 80; -/** Past this many nodes (where validation warns to split), or edges, a layout takes ELK's cheaper settings and isn't - * redone, to fix an edge against the flow or make room for labels: each ELK run grows roughly with the square of the - * graph, and a diagram that size is read zoomed in anyway. */ -const RETRY_LIMIT = 60; -const RETRY_EDGE_LIMIT = 3 * RETRY_LIMIT; -/** A diagram the layout treats as large: the CLI says so before laying one out, since it can still take a while. */ -export const isLarge = (draft: DiagramDraft) => draft.nodes.length > RETRY_LIMIT || draft.edges.length > RETRY_EDGE_LIMIT; +/** Past LARGE_DIAGRAM nodes, or this many edges, a layout takes ELK's cheaper settings and isn't redone, to fix an edge + * against the flow or make room for labels: each ELK run grows roughly with the square of the graph, and a diagram + * that size is read zoomed in anyway. */ +const LARGE_EDGES = 3 * LARGE_DIAGRAM; +/** + * A diagram the layout treats as large: the CLI says so before laying one out, since it can still take a while. + * Never a lane or sequence kind: those have their own layouts, which take a second at their largest. + */ +export const isLarge = (draft: DiagramDraft) => + !isLaneKind(draft.kind) && draft.kind !== 'sequence' && (draft.nodes.length > LARGE_DIAGRAM || draft.edges.length > LARGE_EDGES); const LAYER_GAP = 'elk.layered.spacing.nodeNodeBetweenLayers'; const EDGE_RUN = 'elk.layered.spacing.edgeNodeBetweenLayers'; const GROUP_PREFIX = 'group:'; @@ -149,19 +152,52 @@ const rootOptions = (direction: Direction, compact: boolean, large: boolean): Re 'org.eclipse.elk.json.edgeCoords': 'ROOT', }); +const CANVAS = { width: 1060, aspect: 1.4 } as const; /** - * Layout width (padding included) past which a ~1060px canvas fits the diagram below ~60% zoom, so the - * layout is redone with wrapping. ELK's own wrap decision is scale-free (aspect ratio only) and would - * also fold a short two-node chain, hence the width gate. + * Layout length along the flow (padding included) past which the canvas fits the diagram below ~65% zoom, so the + * layout is redone with wrapping, which folds that axis: the width left to right, the height top-down. ELK's own wrap + * decision is scale-free (aspect ratio only) and would also fold a short two-node chain, hence the gate. */ -const MAX_UNWRAPPED_WIDTH = 1600; +const maxUnwrapped = (direction: Direction) => (direction === 'RIGHT' ? 1600 : Math.round(1600 / CANVAS.aspect)); +const along = (direction: Direction, size: { width?: number; height?: number }) => (direction === 'RIGHT' ? size.width : size.height) ?? 0; +const FOLD_GAIN = 1.15; +/** The zoom at which a layout fits the canvas. */ +const fit = (size: { width?: number; height?: number }) => Math.min(CANVAS.width / (size.width || 1), CANVAS.width / CANVAS.aspect / (size.height || 1)); const wrapOptions: Record = { 'elk.layered.wrapping.strategy': 'SINGLE_EDGE', - 'elk.aspectRatio': '1.4', + 'elk.aspectRatio': String(CANVAS.aspect), 'elk.layered.wrapping.additionalEdgeSpacing': '40', }; +/** + * The least a layout can measure along the flow: its longest chain of cards, each a layer gap past the one before. + * Lets a large diagram be known too long without the ELK run that would measure it. + */ +function leastAlong(draft: DiagramDraft, direction: Direction, variant: 'compact' | 'full', gap: number, reversed: Set): number { + const size = new Map(draft.nodes.map((n) => [n.id, along(direction, cardSize(n.card, variant))])); + const out = new Map(draft.nodes.map((n) => [n.id, []])); + const waiting = new Map(draft.nodes.map((n) => [n.id, 0])); + for (const e of draft.edges) { + if (e.from === e.to) continue; + const [a, b] = reversed.has(e.id) ? [e.to, e.from] : [e.from, e.to]; + out.get(a)!.push(b); + waiting.set(b, waiting.get(b)! + 1); + } + const reach = new Map(draft.nodes.map((n) => [n.id, size.get(n.id)!])); + const ready = draft.nodes.filter((n) => waiting.get(n.id) === 0).map((n) => n.id); + let longest = 0; + for (let id = ready.pop(); id !== undefined; id = ready.pop()) { + longest = Math.max(longest, reach.get(id)!); + for (const next of out.get(id)!) { + reach.set(next, Math.max(reach.get(next)!, reach.get(id)! + gap + size.get(next)!)); + waiting.set(next, waiting.get(next)! - 1); + if (waiting.get(next) === 0) ready.push(next); + } + } + return longest + 80; +} + /** * Edges laid out against their drawn direction: every reply (`return`), then whatever still closes a cycle, found by * a depth-first walk from the entry points in draft order. ELK would otherwise break cycles itself and may pick the @@ -325,17 +361,21 @@ export async function layoutDiagram(draft: DiagramDraft): Promise elk.layout({ ...structuredClone(graph), layoutOptions: { ...opts, ...wrapOptions } }); + const limit = maxUnwrapped(direction); + // A large diagram already known too long is laid out once, wrapped: the run that would measure it costs as much + // again, and the flow order isn't needed (no flips). + if (large && !stages && leastAlong(draft, direction, variant, Number(opts[LAYER_GAP]), reversed) > limit) { + return { laid: collect(draft, await wrapped(), direction, false, reversed), flat: null }; } const flat = await elk.layout(structuredClone(graph)); // Wrapping would fold stages back onto each other. - const wrap = (flat.width ?? 0) > MAX_UNWRAPPED_WIDTH && !stages; - const result = wrap ? await elk.layout({ ...structuredClone(graph), layoutOptions: { ...opts, ...wrapOptions } }) : flat; + const folded = along(direction, flat) > limit && !stages ? await wrapped() : null; + // Folding trades one axis for the other and sends edges back across the diagram: kept only when the diagram + // then reads clearly larger on the canvas. + const wrap = folded !== null && fit(folded) > FOLD_GAIN * fit(flat); // `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 }; + return { laid: collect(draft, wrap ? folded : flat, direction, stages !== null, reversed), flat: wrap ? flat : null }; }; const first = await run(); let laid = first.laid; diff --git a/packages/layout/src/labels.ts b/packages/layout/src/labels.ts index b958b9e..736a5ab 100644 --- a/packages/layout/src/labels.ts +++ b/packages/layout/src/labels.ts @@ -214,8 +214,10 @@ function findLabelSpot( // (a pause/resume pair on parallel runs gets one pill above and one below). const beside = horizontal ? LABEL_H / 2 + 3 : w / 2 + 4; const offsets: [number, number][] = horizontal ? [[0, 0], [0, -beside], [0, beside]] : [[0, 0], [beside, 0], [-beside, 0]]; + // The middle of the run first; a biased label, the end of the run nearer its far card. + const stops = bias === 'end' ? [0.8, 0.65, 0.5, 0.35, 0.2] : bias === 'start' ? [0.2, 0.35, 0.5, 0.65, 0.8] : [0.5, 0.35, 0.65, 0.2, 0.8]; search: for (const [dx, dy] of offsets) { - for (const t of [0.5, 0.35, 0.65, 0.2, 0.8]) { + for (const t of stops) { 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); diff --git a/packages/layout/src/route.ts b/packages/layout/src/route.ts index 95c97c4..a03a749 100644 --- a/packages/layout/src/route.ts +++ b/packages/layout/src/route.ts @@ -343,6 +343,19 @@ export function routeEdges( 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)]; + // The whole straight run at each end stays on its port (a nudge never moves it), so it keeps its line as the + // port itself does. + for (const [node, role, pts] of [ + [req.from, 'out', out[req.id]!], + [req.to, 'in', [...out[req.id]!].reverse()], + ] as const) { + const vertical = pts[0]!.x === pts[1]!.x; + let end = 1; + while (end + 1 < pts.length && (vertical ? pts[end + 1]!.x === pts[0]!.x : pts[end + 1]!.y === pts[0]!.y)) end++; + const [a, b] = vertical ? [pts[0]!.y, pts[end]!.y] : [pts[0]!.x, pts[end]!.x]; + const line = lineKey(vertical, vertical ? pts[0]!.x : pts[0]!.y); + portLines.set(line, [...(portLines.get(line) ?? []), { lo: Math.min(a, b), hi: Math.max(a, b), node, role }]); + } } return out; } diff --git a/packages/layout/test/fuzz.test.ts b/packages/layout/test/fuzz.test.ts index fd8c452..63724ed 100644 --- a/packages/layout/test/fuzz.test.ts +++ b/packages/layout/test/fuzz.test.ts @@ -121,13 +121,14 @@ 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) => { + it.each(cases.map((d, i) => [i, d] as const))('random diagram %i keeps every route off the cards and the port runs apart', (_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); + expect(overlappingPortRuns(d, out)).toEqual([]); }, 30_000); }); @@ -185,13 +186,15 @@ describe('ELK layout properties', () => { 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); } - // A target wholly before or after its source along the flow is entered by the side facing it (same row only: - // a wrapped layout carries forward edges back to the start of the next row). + // A target wholly before or after its source along the flow is entered by the side facing it (same row or + // column only: a wrapped layout carries forward edges back to the start of the next one). const [s, t] = [out.nodes[e.from]!, out.nodes[e.to]!]; const end = pts.at(-1)!; if (d.direction === 'DOWN') { - if (t.y + t.height <= s.y) expect(Math.abs(end.y - t.y - t.height) < 0.5, `${e.id} enters the bottom`).toBe(true); - if (t.y >= s.y + s.height) expect(Math.abs(end.y - t.y) < 0.5, `${e.id} enters the top`).toBe(true); + if (s.x < t.x + t.width && t.x < s.x + s.width) { + if (t.y + t.height <= s.y) expect(Math.abs(end.y - t.y - t.height) < 0.5, `${e.id} enters the bottom`).toBe(true); + if (t.y >= s.y + s.height) expect(Math.abs(end.y - t.y) < 0.5, `${e.id} enters the top`).toBe(true); + } } else if (s.y < t.y + t.height && t.y < s.y + s.height) { if (t.x + t.width <= s.x) expect(Math.abs(end.x - t.x - t.width) < 0.5, `${e.id} enters the right`).toBe(true); if (t.x >= s.x + s.width) expect(Math.abs(end.x - t.x) < 0.5, `${e.id} enters the left`).toBe(true); diff --git a/packages/layout/test/labels.test.ts b/packages/layout/test/labels.test.ts index 1671293..8778549 100644 --- a/packages/layout/test/labels.test.ts +++ b/packages/layout/test/labels.test.ts @@ -138,6 +138,17 @@ describe('labels by a group frame', () => { }); }); +describe('a label on a fan-out or fan-in', () => { + const fan = (role: 'from' | 'to') => ['a', 'b', 'c'].map((id) => ({ id, label: 'calls', [role]: 'hub', [role === 'from' ? 'to' : 'from']: id })); + // One long clear run: the middle fits, and so does either end. + const routes = { a: [{ x: 0, y: 0 }, { x: 400, y: 0 }], b: [{ x: 0, y: 200 }, { x: 400, y: 200 }], c: [{ x: 0, y: 400 }, { x: 400, y: 400 }] }; + + it('takes the end of its run nearest the far card, not the middle', () => { + expect(placeLabels(fan('from'), routes, []).labels.a!.x).toBeGreaterThan(250); + expect(placeLabels(fan('to'), routes, []).labels.a!.x).toBeLessThan(150); + }); +}); + 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 ee3ee51..aa1626f 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, squared, STAGE_LABEL_BAND } from '../src/index'; +import { GROUP_LABEL_BAND, isLarge, layoutDiagram, squared, STAGE_LABEL_BAND } from '../src/index'; import { STRESS } from './stress'; const node = (id: string, extra: Partial = {}): DiagramNode => ({ @@ -28,6 +28,15 @@ describe('squared', () => { }); }); +describe('isLarge', () => { + it('holds past the node limit only for the kinds ELK lays out', () => { + const nodes = Array.from({ length: 61 }, (_, i) => node(`n${i}`)); + expect(isLarge(draft({ nodes }))).toBe(true); + expect(isLarge(draft({ nodes: nodes.slice(1) }))).toBe(false); + for (const kind of ['workflow', 'lifecycle', 'sequence'] as const) expect(isLarge(draft({ kind, nodes })), kind).toBe(false); + }); +}); + describe('layoutDiagram', () => { it('places the target to the right and routes port to port', async () => { const out = await layoutDiagram( @@ -110,6 +119,34 @@ describe('layoutDiagram', () => { expect(width / height).toBeLessThanOrEqual(2.6); }); + const chain = (n: number): Pick => ({ + nodes: Array.from({ length: n }, (_, i) => node(`c${i}`)), + edges: Array.from({ length: n - 1 }, (_, i) => ({ id: `e${i}`, from: `c${i}`, to: `c${i + 1}` })), + }); + + it('wraps a tall top-down diagram on its height, the axis a fold shortens', async () => { + const { width, height } = (await layoutDiagram(draft({ direction: 'DOWN', ...chain(16) }))).bounds; + // One column is 360 by 2184. + expect(height).toBeLessThan(1200); + expect(width).toBeGreaterThan(360); + }); + + it('wraps a top-down chain alike on either side of the large-diagram limit', async () => { + const [under, over] = await Promise.all([60, 61].map(async (n) => (await layoutDiagram(draft({ direction: 'DOWN', ...chain(n) }))).bounds)); + expect(under!.width).toBe(over!.width); + expect(Math.abs(under!.height - over!.height)).toBeLessThan(200); + }); + + it('leaves a large diagram that is short along the flow unwrapped', async () => { + // Large by its edges alone; ELK's own wrap decision goes by aspect ratio and would fold this strip. + const edges = Array.from({ length: 184 }, (_, i) => ({ id: `e${i}`, from: `c${i % 3}`, to: `c${(i % 3) + 1}` })); + const out = await layoutDiagram(draft({ density: 'compact', nodes: chain(4).nodes, edges })); + expect(out.bounds.width).toBeLessThanOrEqual(1600); + const tops = out.draft.nodes.map((n) => out.nodes[n.id]!.x); + expect(tops).toEqual([...tops].sort((a, b) => a - b)); + expect(new Set(tops).size).toBe(4); + }); + it('keeps a short chain on one row', async () => { const out = await layoutDiagram( draft({ nodes: [node('a'), node('b'), node('c')], edges: [{ id: 'ab', from: 'a', to: 'b' }, { id: 'bc', from: 'b', to: 'c' }] }), diff --git a/packages/layout/test/quality.test.ts b/packages/layout/test/quality.test.ts index 164d3f7..d4f0f57 100644 --- a/packages/layout/test/quality.test.ts +++ b/packages/layout/test/quality.test.ts @@ -42,8 +42,10 @@ describe.each(laid)('layout quality of %s', (_name, draft, out) => { if (sameRow && t.x + t.width <= s.x) expect(near(end.x, t.x + t.width), `${e.id} enters its right side`).toBe(true); if (sameRow && t.x >= s.x + s.width) expect(near(end.x, t.x), `${e.id} enters its left side`).toBe(true); } else { - if (t.y + t.height <= s.y) expect(near(end.y, t.y + t.height), `${e.id} enters its bottom`).toBe(true); - if (t.y >= s.y + s.height) expect(near(end.y, t.y), `${e.id} enters its top`).toBe(true); + // Same column only, for the same reason. + const sameColumn = s.x < t.x + t.width && t.x < s.x + s.width; + if (sameColumn && t.y + t.height <= s.y) expect(near(end.y, t.y + t.height), `${e.id} enters its bottom`).toBe(true); + if (sameColumn && t.y >= s.y + s.height) expect(near(end.y, t.y), `${e.id} enters its top`).toBe(true); } } }); diff --git a/packages/schema/src/rules/kinds.ts b/packages/schema/src/rules/kinds.ts index dc3f2c0..da31e5e 100644 --- a/packages/schema/src/rules/kinds.ts +++ b/packages/schema/src/rules/kinds.ts @@ -206,6 +206,17 @@ function phaseDiagnostics(d: DiagramDraft): Diagnostic[] { else if (!owner.has(n.id) && n.group === undefined) out.push({ ...error('semantics/unphased-node', `/nodes/${i}`, `Node "${n.id}" is in no phase; it is placed in its first predecessor's`, { id: n.id }, ['add it to a phase\'s "nodes"']), severity: 'warning' }); }); + // The layout can't hold a group to a stage, so its frame lands wherever its cards do: across the bands. + d.groups?.forEach((g, i) => { + if (d.nodes.some((n) => n.group === g.id && !owner.has(n.id))) + out.push({ + ...error('semantics/group-outside-phases', `/groups/${i}`, `Group "${g.id}" belongs to no phase; its frame can lie across the phase bands`, { id: g.id }, [ + 'ungroup its nodes and add them to a phase', + 'remove "phases" and show the stages as groups', + ]), + severity: 'warning', + }); + }); } if (byNodes) { diff --git a/packages/schema/src/rules/semantics.ts b/packages/schema/src/rules/semantics.ts index e60be4b..0599c56 100644 --- a/packages/schema/src/rules/semantics.ts +++ b/packages/schema/src/rules/semantics.ts @@ -1,4 +1,4 @@ -import { usesCompactCards, type DiagramDraft } from '@stackmap/core'; +import { LARGE_DIAGRAM, usesCompactCards, type DiagramDraft } from '@stackmap/core'; import type { Diagnostic } from '../diagnostics'; function duplicates(items: { id: string }[] | undefined, collection: string): Diagnostic[] { @@ -62,8 +62,6 @@ function cycles(nodes: string[], edges: [string, string][]): string[][] { return out; } -const LARGE_DIAGRAM = 60; - /** Size, duplicate ids and row labels, orphans, self-loops, parallel edges, dataflow cycles, empty views and groups. */ export function semanticsDiagnostics(d: DiagramDraft): Diagnostic[] { const out: Diagnostic[] = [ diff --git a/packages/schema/test/kinds.test.ts b/packages/schema/test/kinds.test.ts index 079e934..69ec963 100644 --- a/packages/schema/test/kinds.test.ts +++ b/packages/schema/test/kinds.test.ts @@ -175,6 +175,26 @@ describe('kind rules', () => { ]); }); + it('warns that a group beside phases can lie across their bands', () => { + const staged = { + kind: 'architecture', + title: 't', + groups: [{ id: 'g', label: 'G' }], + phases: [{ id: 'in', label: 'In', nodes: ['a'] }, { id: 'out', label: 'Out', nodes: ['c'] }], + nodes: [ + { id: 'a', type: 'client', card: { title: 'A' } }, + { id: 'b', type: 'service', group: 'g', card: { title: 'B' } }, + { id: 'c', type: 'database', card: { title: 'C' } }, + ], + edges: [ + { id: 'e1', from: 'a', to: 'b' }, + { id: 'e2', from: 'b', to: 'c' }, + ], + }; + expect(codes(staged)).toEqual(['warning:semantics/group-outside-phases@/groups/0']); + expect(codes({ ...staged, phases: undefined })).toEqual([]); + }); + it('sequence: replies must answer a call, and time bands follow each other', () => { const seq = (edges: unknown[], phases?: unknown[]) => ({ kind: 'sequence', diff --git a/packages/viewer/e2e/present.spec.ts b/packages/viewer/e2e/present.spec.ts index 4ddd40e..d6c4f05 100644 --- a/packages/viewer/e2e/present.spec.ts +++ b/packages/viewer/e2e/present.spec.ts @@ -62,6 +62,18 @@ test('F presents: chrome hidden, one step per view, arrows step, Esc ends', asyn await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); }); +test('a presentation leaves ⌘/Ctrl/Alt key combinations to the browser', async ({ page }) => { + await page.goto('/?page=release-delivery'); + await expect(page.locator('.sm-card').first()).toBeVisible(); + await page.keyboard.press('f'); + const bar = page.getByRole('group', { name: 'Presentation' }); + await expect(bar).toContainText('1 / 3'); + for (const combo of ['Alt+ArrowRight', 'Control+End', 'Meta+ArrowRight']) await page.keyboard.press(combo); + await expect(bar).toContainText('1 / 3'); + await page.keyboard.press('ArrowRight'); + await expect(bar).toContainText('2 / 3'); +}); + test('Esc cancels route picking even with focus on the Route button', async ({ page }) => { await page.goto('/?page=release-delivery'); await page.getByRole('button', { name: 'Route between two nodes (R)' }).click(); diff --git a/packages/viewer/src/chrome/Presentation.tsx b/packages/viewer/src/chrome/Presentation.tsx index 8810ac5..babe451 100644 --- a/packages/viewer/src/chrome/Presentation.tsx +++ b/packages/viewer/src/chrome/Presentation.tsx @@ -22,6 +22,8 @@ export function PresentBar({ onExit }: { onExit: () => void }) { const step = steps[at]!; useEffect(() => { const onKey = (e: KeyboardEvent) => { + // ⌘/Ctrl/Alt with an arrow is the browser's own (back, forward, end of page). + if (e.metaKey || e.ctrlKey || e.altKey) return; // Space and Enter on a focused button press that button. if ((e.key === ' ' || e.key === 'Enter') && e.target instanceof HTMLButtonElement) return; const to = { ArrowRight: at + 1, PageDown: at + 1, ' ': at + 1, ArrowLeft: at - 1, PageUp: at - 1, Home: 0, End: steps.length - 1 }[e.key]; diff --git a/packages/viewer/src/samples/gallery.layout.ts b/packages/viewer/src/samples/gallery.layout.ts index 5d02718..05385cf 100644 --- a/packages/viewer/src/samples/gallery.layout.ts +++ b/packages/viewer/src/samples/gallery.layout.ts @@ -1768,7 +1768,7 @@ export const galleryLayouts: Record = { "labels": { "e2": { "x": 580, - "y": 241 + "y": 197.2 }, "e4": { "x": 1084, @@ -1784,7 +1784,7 @@ export const galleryLayouts: Record = { }, "e8": { "x": 1476, - "y": 446.2 + "y": 462.4 }, "e10": { "x": 1388, @@ -1796,7 +1796,7 @@ export const galleryLayouts: Record = { }, "e13": { "x": 720, - "y": 515 + "y": 610.4 } }, "bounds": { @@ -2238,11 +2238,11 @@ export const galleryLayouts: Record = { "labels": { "needs-approval": { "x": 813, - "y": 152 + "y": 171.2 }, "approved": { "x": 715, - "y": 152 + "y": 171.2 }, "review-blocked": { "x": 1020, @@ -2250,11 +2250,11 @@ export const galleryLayouts: Record = { }, "execution-failed": { "x": 912, - "y": 278.8 + "y": 319.6 }, "retry": { "x": 888, - "y": 312.4 + "y": 163.6 }, "approval-cancelled": { "x": 780, @@ -3755,15 +3755,15 @@ export const galleryLayouts: Record = { "y": 353 }, "e6": { - "x": 1378.15, + "x": 1394.8, "y": 305 }, "e7": { - "x": 1455, + "x": 1483.8, "y": 130 }, "e8": { - "x": 1404.5, + "x": 1463.6, "y": 326 } } diff --git a/packages/viewer/src/samples/grouped-platform.layout.ts b/packages/viewer/src/samples/grouped-platform.layout.ts index ce0f9fc..9af5c6d 100644 --- a/packages/viewer/src/samples/grouped-platform.layout.ts +++ b/packages/viewer/src/samples/grouped-platform.layout.ts @@ -441,7 +441,7 @@ export const groupedPlatformLayout: LaidOutDiagram = { }, "e5": { "x": 457, - "y": 695 + "y": 719 } } }; diff --git a/site/e2e/smoke.spec.ts b/site/e2e/smoke.spec.ts index 518e162..0ab3681 100644 --- a/site/e2e/smoke.spec.ts +++ b/site/e2e/smoke.spec.ts @@ -328,11 +328,14 @@ test('the docs search loads its index again after a failed fetch', async ({ page await page.route('**/search.json', (r) => (fail ? r.abort() : r.continue())); await page.goto('/docs'); const box = page.getByRole('combobox', { name: 'Search the docs' }); + const failed = page.waitForEvent('requestfailed', (r) => r.url().endsWith('/search.json')); await expect(async () => { await page.keyboard.press('ControlOrMeta+k'); await expect(box).toBeFocused({ timeout: 500 }); }).toPass(); await box.fill('serve'); + // An open while the failing fetch is still pending shares it, so the retry is only due once it has failed. + await failed; await expect(page.getByRole('option')).toHaveCount(0); await page.keyboard.press('Escape'); await expect(box).toHaveCount(0);