Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions packages/cli/src/commands.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -72,10 +71,9 @@ export async function buildHtml(
): Promise<ValidationResult & { html?: string }> {
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)) };
}
Expand Down
58 changes: 39 additions & 19 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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;
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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<string | null> {
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<string | null> {
function launch(cmd: string, args: string[], wait: number, blind = false): Promise<string | null> {
return new Promise((done) => {
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' });
const timer = setTimeout(() => done(null), wait);
Expand All @@ -121,7 +141,7 @@ function launch(cmd: string, args: string[], wait: number): Promise<string | nul
done(why);
};
child.once('error', (e) => 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();
});
}
24 changes: 22 additions & 2 deletions packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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']);
}
});

Expand All @@ -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', () => {
Expand Down Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/diagram-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export const TYPE_LABELS: Record<NodeType, string> = {
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<NodeType, number>();
for (const n of nodes) counts.set(n.type, (counts.get(n.type) ?? 0) + 1);
Expand Down
80 changes: 60 additions & 20 deletions packages/layout/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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:';
Expand Down Expand Up @@ -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<string, string> = {
'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<string>): number {
const size = new Map(draft.nodes.map((n) => [n.id, along(direction, cardSize(n.card, variant))]));
const out = new Map<string, string[]>(draft.nodes.map((n) => [n.id, []]));
const waiting = new Map<string, number>(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<string, number>(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
Expand Down Expand Up @@ -325,17 +361,21 @@ export async function layoutDiagram(draft: DiagramDraft): Promise<LaidOutDiagram
widen(graph);
}
const opts = graph.layoutOptions!;
// A large diagram is laid out once: ELK's own wrap decision (by aspect ratio alone) stands in for the width gate,
// which needs a first run to measure, and the flow order isn't needed (no flips).
if (large && !stages) {
return { laid: collect(draft, await elk.layout({ ...structuredClone(graph), layoutOptions: { ...opts, ...wrapOptions } }), direction, false, reversed), flat: null };
const wrapped = () => 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;
Expand Down
4 changes: 3 additions & 1 deletion packages/layout/src/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading