@liqweed/motion-kit 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  "name": "motion-kit",
8
8
  "source": "./",
9
9
  "description": "animated-diagram, motion-render and project-logo skills and the motion-kit runtime/CLI",
10
- "version": "0.6.0"
10
+ "version": "0.7.0"
11
11
  }
12
12
  ]
13
13
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "motion-kit",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Deterministic animated diagrams: scenes as pure functions of time for live pages, Slidev, slide frames, baked SVG and video; plus project logos/icons.",
5
5
  "author": { "name": "Ophir Radnitz" },
6
6
  "repository": "https://github.com/liqweed/motion-kit",
package/README.md CHANGED
@@ -102,7 +102,8 @@ node cli/motion-kit.mjs vendor <repo>/components/motion-kit --adapter slidev #
102
102
 
103
103
  Copies `runtime/`, the adapter, the gate (`lib/check.mjs`, `lib/gate.mjs`,
104
104
  `lib/load.mjs`) and `LICENSE`; writes `check.mjs` and `MOTION_KIT_VERSION`.
105
- Don't edit vendored files; change motion-kit and re-vendor. Vendoring keeps
105
+ Don't edit vendored files; change motion-kit and re-vendor.
106
+ `motion-kit outdated <dir>` tells you when a newer release exists. Vendoring keeps
106
107
  consumer CI self-contained (no install step, no network): the vendored gate
107
108
  runs the same checks as `motion-kit check`.
108
109
 
@@ -195,8 +196,10 @@ Pull requests here are reviewed with the help of
195
196
  free. Thank you, CodeRabbit, for the support.
196
197
 
197
198
  See the [Astro consumer guide](docs/guides/astro.md) for dictionaries, server
198
- rendering, styles, page helpers, CI and upgrades. The six built-in scene types
199
- include [state-machine and request-journey](skills/animated-diagram/references/scene-types.md).
199
+ rendering, styles, page helpers, CI and upgrades. The seven built-in scene types
200
+ include [state-machine, request-journey and flowchart](skills/animated-diagram/references/scene-types.md);
201
+ `motion-kit import flow.mmd --out flow.json` turns a Mermaid flowchart into a
202
+ spec, laid out once at build time.
200
203
  The [spec playground](https://motion-kit.dev/playground/) checks, plays and
201
204
  shares a JSON spec directly in the browser.
202
205
 
@@ -8,7 +8,9 @@
8
8
  * motion-kit bake <scene> --out x.svg [--fps 15] [--theme ...] [--style S]
9
9
  * motion-kit video <scene> --out x.mp4|.gif|.webm [--fps 30] [--scale 2] [--hold 1.5] [--sheet sheet.png]
10
10
  * motion-kit icon <scene> --out <repo> [--size 512] [--style S] [--no-png] project icon set (assets/, .idea/)
11
+ * motion-kit import <flow.mmd|-> [--out spec.json] [--id ID] [--title T] [--description D] Mermaid flowchart → spec
11
12
  * motion-kit vendor <dir> [--adapter page|slidev|astro|element]
13
+ * motion-kit outdated <dir> is a vendored copy behind npm's latest? (exit 1 when it is)
12
14
  * motion-kit formats | types
13
15
  * motion-kit --version print the version
14
16
  *
@@ -16,9 +18,14 @@
16
18
  * --options O passes scene options to a custom module's factory, unchanged:
17
19
  * inline JSON ('{"view":"short"}'), a .json file, or an .mjs module whose
18
20
  * default export is the options or ({ format, locale }) => options.
21
+ *
22
+ * import: a chain becomes a `sequence` spec; a chart with branches, joins,
23
+ * link labels or dotted links becomes a `flowchart` spec, laid out here once.
24
+ * Without --out the spec goes to stdout; with it, the spec is also checked in
25
+ * every format (or only the --format ones). Unsupported Mermaid syntax fails with its line.
19
26
  */
20
- import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
21
- import { dirname, join, resolve } from "node:path";
27
+ import { closeSync, cpSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
28
+ import { basename, dirname, join, resolve } from "node:path";
22
29
  import { fileURLToPath } from "node:url";
23
30
  import { parseArgs } from "node:util";
24
31
  import { bake, bakeStats } from "../runtime/bake.mjs";
@@ -26,6 +33,8 @@ import { FORMATS } from "../runtime/scene.mjs";
26
33
  import { SCENE_TYPES } from "../runtime/types/index.mjs";
27
34
  import { checkScene } from "../lib/check.mjs";
28
35
  import { checkFiles } from "../lib/gate.mjs";
36
+ import { mermaidToSpec } from "../lib/mermaid.mjs";
37
+ import { compareVersions, isAdapterName, latestVersion, PACKAGE, shellQuote, vendoredVersion } from "../lib/outdated.mjs";
29
38
  import { buildHtml } from "../lib/build.mjs";
30
39
  import { writeIconSet } from "../lib/icon.mjs";
31
40
  import { exportSteps } from "../lib/export.mjs";
@@ -53,6 +62,9 @@ const { values: a, positionals } = parseArgs({
53
62
  hold: { type: "string", default: "1.5" },
54
63
  sheet: { type: "string" },
55
64
  adapter: { type: "string", default: "page" },
65
+ id: { type: "string" },
66
+ title: { type: "string" },
67
+ description: { type: "string" },
56
68
  size: { type: "string", default: "512" },
57
69
  "no-png": { type: "boolean", default: false },
58
70
  "no-scrubber": { type: "boolean", default: false },
@@ -188,12 +200,63 @@ async function main() {
188
200
  if (files.includes(".idea/icon.svg")) console.log("note: if .idea/ is git-ignored, add !.idea/icon*.svg after it to commit the IDE icon");
189
201
  return;
190
202
  }
203
+ case "import": {
204
+ const file = need(args[0], "<flow.mmd> (or - for stdin)");
205
+ const source = readFileSync(file === "-" ? 0 : file, "utf8");
206
+ const id = a.id ?? (file === "-" ? "flowchart" : basename(file).replace(/\.[^.]*$/, "").replace(/[^\w-]+/g, "-").replace(/^[^A-Za-z]+/, "") || "flowchart");
207
+ let result;
208
+ try {
209
+ result = mermaidToSpec(source, { id, title: a.title, description: a.description });
210
+ } catch (e) {
211
+ fail(`import ${file}: ${e instanceof Error ? e.message : e}`);
212
+ }
213
+ for (const w of result.warnings) console.error(`motion-kit: import ${file}: ${w}`);
214
+ const json = `${JSON.stringify(result.spec, null, "\t")}\n`;
215
+ if (!a.out) {
216
+ process.stdout.write(json);
217
+ return;
218
+ }
219
+ const dest = resolve(a.out);
220
+ if (isModule(dest)) fail(`import: --out ${a.out} is a scene module path, so check and build would not load it as a spec; use a .json path`);
221
+ mkdirSync(dirname(dest), { recursive: true });
222
+ // Gate a candidate beside the destination; an existing spec is replaced only once it passes.
223
+ // Created exclusively (a planted symlink cannot redirect the write) and never more readable than the file it replaces.
224
+ // The name is short and fixed-length so a long destination basename cannot push it past the filesystem's limit.
225
+ const candidate = join(dirname(dest), `.import-${process.pid}-${Date.now().toString(36)}.json`);
226
+ let mode = 0o666;
227
+ try {
228
+ mode = statSync(dest).mode & 0o777;
229
+ } catch {}
230
+ let created = false;
231
+ let bad;
232
+ try {
233
+ const fd = openSync(candidate, "wx", mode);
234
+ created = true;
235
+ try {
236
+ writeFileSync(fd, json);
237
+ } finally {
238
+ closeSync(fd);
239
+ }
240
+ bad = await checkFiles([candidate], { formats: a.format, locales: a.locale, style });
241
+ if (!bad) renameSync(candidate, dest);
242
+ } finally {
243
+ if (created) rmSync(candidate, { force: true });
244
+ }
245
+ if (bad) {
246
+ console.error(`motion-kit: the import does not pass the gate (every format, or only those named by --format), so ${a.out} was not written; shorten labels, split the chart, or ship only the formats that pass (--format)`);
247
+ process.exit(1);
248
+ }
249
+ const { spec } = result;
250
+ console.log(`wrote ${a.out}: ${spec.type} "${spec.id}", ${spec.nodes.length} nodes${spec.edges ? `, ${spec.edges.length} links` : ""}`);
251
+ return;
252
+ }
191
253
  case "vendor": {
192
254
  const dir = resolve(need(args[0], "<dir>"));
255
+ if (!isAdapterName(a.adapter) || !existsSync(join(ROOT, "adapters", a.adapter))) fail(`unknown adapter "${a.adapter}" (page, slidev, astro or element)`);
256
+ const adapter = join(ROOT, "adapters", a.adapter);
193
257
  mkdirSync(dir, { recursive: true });
194
258
  cpSync(join(ROOT, "LICENSE"), join(dir, "LICENSE"));
195
259
  cpSync(join(ROOT, "runtime"), join(dir, "runtime"), { recursive: true });
196
- const adapter = join(ROOT, "adapters", a.adapter);
197
260
  cpSync(adapter, join(dir, "adapter"), { recursive: true });
198
261
  mkdirSync(join(dir, "lib"), { recursive: true });
199
262
  for (const f of ["check.mjs", "gate.mjs", "load.mjs"]) cpSync(join(ROOT, "lib", f), join(dir, "lib", f));
@@ -202,6 +265,26 @@ async function main() {
202
265
  console.log(`vendored runtime + ${a.adapter} adapter (motion-kit ${VERSION}) into ${dir}`);
203
266
  return;
204
267
  }
268
+ case "outdated": {
269
+ const dir = resolve(need(args[0], "<dir>"));
270
+ let vendored;
271
+ let latest;
272
+ try {
273
+ vendored = vendoredVersion(dir);
274
+ latest = await latestVersion();
275
+ } catch (e) {
276
+ console.error(`motion-kit: outdated: ${e instanceof Error ? e.message : e}`);
277
+ process.exit(2);
278
+ }
279
+ if (compareVersions(vendored.version, latest) < 0) {
280
+ console.log(`${dir}: motion-kit ${vendored.version} is vendored; ${latest} is the latest release.`);
281
+ console.log(`re-vendor: npx ${PACKAGE}@${latest} vendor ${shellQuote(dir)} --adapter ${vendored.adapter}`);
282
+ console.log(`changes: https://github.com/liqweed/motion-kit/blob/main/CHANGELOG.md`);
283
+ process.exit(1);
284
+ }
285
+ console.log(`${dir}: motion-kit ${vendored.version} is up to date (latest ${latest}).`);
286
+ return;
287
+ }
205
288
  default:
206
289
  fail(`unknown command "${cmd}" (try --help)`);
207
290
  }
@@ -316,7 +316,8 @@ move ends at `start + lag + duration`, which is what step timing MUST budget.
316
316
 
317
317
  Registered types: `sequence` (2–12 nodes), `hub-spoke` (2–10 spokes),
318
318
  `timeline` (2–8 events), `stack` (2–8 layers), `state-machine` and
319
- `request-journey` (2–8 nodes; graph bounds in §11.1). Fields and storyboards:
319
+ `request-journey` (2–8 nodes; graph bounds in §11.1), and `flowchart` (2–12
320
+ nodes, 1–20 edges, layout stored in the spec). Fields and storyboards:
320
321
  [`scene-types.md`](../../skills/animated-diagram/references/scene-types.md).
321
322
  Normative points:
322
323
 
@@ -572,6 +573,14 @@ Registered graph walks are `state-machine` and `request-journey` (2–8 nodes,
572
573
  1–12 edges, 1–10 explicit path edges). Their fields, narrative steps, region
573
574
  boundaries and limits are in the [scene type reference](../../skills/animated-diagram/references/scene-types.md).
574
575
 
576
+ A `flowchart` spec carries its layout: integer `rank` and `pos` ≥ 0 per node,
577
+ one `via` waypoint per rank an edge crosses. The type MUST NOT lay a graph out;
578
+ it scales the stored layout per format and MUST throw on overlapping nodes,
579
+ waypoints through a node, self-loops, edges that skip ranks, and labels or
580
+ connectors that collide in a format (`runtime/types/flowchart.mjs`). The
581
+ layout is computed at build time by `motion-kit import` (`lib/mermaid.mjs`,
582
+ `lib/layout.mjs`), deterministically: the same chart gives the same spec.
583
+
575
584
  Export manifests include `runtimeHash` (SHA-256 of sorted runtime module paths
576
585
  and contents); `inputHash` includes it, source, style, scene options, format,
577
586
  locale and rendering settings. Custom modules' arbitrary imported dependencies
@@ -0,0 +1,93 @@
1
+ {
2
+ "type": "flowchart",
3
+ "id": "pull-request",
4
+ "title": "How a pull request lands",
5
+ "description": "A pull request runs CI and review; a failed build or requested changes loop back until it merges and is released.",
6
+ "direction": "down",
7
+ "nodes": [
8
+ {
9
+ "id": "open",
10
+ "label": "Open a PR",
11
+ "shape": "pill",
12
+ "rank": 0,
13
+ "pos": 0.25
14
+ },
15
+ {
16
+ "id": "ci",
17
+ "label": "CI passes?",
18
+ "shape": "decision",
19
+ "rank": 1,
20
+ "pos": 0.25
21
+ },
22
+ {
23
+ "id": "fix",
24
+ "label": "Fix the build",
25
+ "rank": 2,
26
+ "pos": 0
27
+ },
28
+ {
29
+ "id": "review",
30
+ "label": "Approved?",
31
+ "shape": "decision",
32
+ "rank": 2,
33
+ "pos": 1
34
+ },
35
+ {
36
+ "id": "revise",
37
+ "label": "Revise",
38
+ "rank": 3,
39
+ "pos": 0.75
40
+ },
41
+ {
42
+ "id": "merge",
43
+ "label": "Merge",
44
+ "rank": 3,
45
+ "pos": 1.75
46
+ },
47
+ {
48
+ "id": "release",
49
+ "label": "Release",
50
+ "shape": "pill",
51
+ "rank": 4,
52
+ "pos": 1.75
53
+ }
54
+ ],
55
+ "edges": [
56
+ {
57
+ "from": "open",
58
+ "to": "ci"
59
+ },
60
+ {
61
+ "from": "ci",
62
+ "to": "fix",
63
+ "label": "No"
64
+ },
65
+ {
66
+ "from": "fix",
67
+ "to": "ci"
68
+ },
69
+ {
70
+ "from": "ci",
71
+ "to": "review",
72
+ "label": "Yes"
73
+ },
74
+ {
75
+ "from": "review",
76
+ "to": "revise",
77
+ "label": "Changes"
78
+ },
79
+ {
80
+ "from": "revise",
81
+ "to": "review"
82
+ },
83
+ {
84
+ "from": "review",
85
+ "to": "merge",
86
+ "label": "Yes"
87
+ },
88
+ {
89
+ "from": "merge",
90
+ "to": "release"
91
+ }
92
+ ]
93
+ }
@@ -0,0 +1,15 @@
1
+ ---
2
+ title: How a pull request lands
3
+ ---
4
+ %% Source of examples/pull-request.json:
5
+ %% node cli/motion-kit.mjs import examples/pull-request.mmd --out examples/pull-request.json
6
+ flowchart TD
7
+ accDescr: A pull request runs CI and review; a failed build or requested changes loop back until it merges and is released.
8
+ open([Open a PR]) --> ci{CI passes?}
9
+ ci -- No --> fix[Fix the build]
10
+ fix --> ci
11
+ ci -- Yes --> review{Approved?}
12
+ review -->|Changes| revise[Revise]
13
+ revise --> review
14
+ review -->|Yes| merge[Merge]
15
+ merge --> release([Release])
package/lib/layout.mjs ADDED
@@ -0,0 +1,236 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Ophir Radnitz
3
+ /**
4
+ * motion-kit · layered graph layout, run once at build time (Node).
5
+ *
6
+ * layered(nodeIds, edges) → { ranks: Map<id, number>, pos: Map<id, number>, via: [rank, pos][][] }
7
+ *
8
+ * A small Sugiyama layout with no dependencies and no randomness, so the same
9
+ * graph always gets the same coordinates:
10
+ *
11
+ * 1. Cycles are broken by reversing the edges a depth-first search (in
12
+ * declaration order) finds going back to a node still on its stack.
13
+ * 2. Ranks: longest path from the sources, then every node that is not a
14
+ * source moves as close to its successors as its predecessors allow.
15
+ * 3. Edges spanning more than one rank get a waypoint on every rank between.
16
+ * 4. Order within a rank: barycenter sweeps down and up, keeping the order with
17
+ * the fewest crossings; ties keep declaration order.
18
+ * 5. Positions: each rank is placed as close as possible to the mean position
19
+ * of its neighbours, with a minimum gap (1 between nodes, less next to and
20
+ * between waypoints), by isotonic regression. Positions start at 0.
21
+ *
22
+ * The scene type maps ranks and positions to pixels per format; it never lays
23
+ * the graph out itself. Positions are in node pitches; ranks are integers.
24
+ */
25
+
26
+ const GAP_NODE = 1;
27
+ const GAP_MIXED = 0.75;
28
+ const GAP_VIA = 0.4;
29
+ const SWEEPS = 12;
30
+ const PLACE_ROUNDS = 8;
31
+
32
+ /**
33
+ * @typedef {{ from: string, to: string }} LayoutEdge
34
+ * @typedef {{ ranks: Map<string, number>, pos: Map<string, number>, via: [number, number][][] }} Layout
35
+ */
36
+
37
+ /**
38
+ * @param {string[]} nodeIds in declaration order
39
+ * @param {LayoutEdge[]} edges no self-loops
40
+ * @returns {Layout}
41
+ */
42
+ export function layered(nodeIds, edges) {
43
+ const index = new Map(nodeIds.map((id, i) => [id, i]));
44
+ const n = nodeIds.length;
45
+ for (const e of edges) {
46
+ if (!index.has(e.from) || !index.has(e.to)) throw new Error(`layout: edge ${e.from} → ${e.to} names an unknown node`);
47
+ if (e.from === e.to) throw new Error(`layout: self-loop on ${e.from}`);
48
+ }
49
+
50
+ // 1. Break cycles: reverse back edges found by a DFS in declaration order.
51
+ const out = nodeIds.map(() => /** @type {number[]} */ ([]));
52
+ edges.forEach((e, i) => out[/** @type {number} */ (index.get(e.from))].push(i));
53
+ const state = new Array(n).fill(0); // 0 new, 1 on stack, 2 done
54
+ const reversed = new Set();
55
+ /** @param {number} v */
56
+ const visit = (v) => {
57
+ state[v] = 1;
58
+ for (const ei of out[v]) {
59
+ const w = /** @type {number} */ (index.get(edges[ei].to));
60
+ if (state[w] === 1) reversed.add(ei);
61
+ else if (state[w] === 0) visit(w);
62
+ }
63
+ state[v] = 2;
64
+ };
65
+ for (let v = 0; v < n; v++) if (state[v] === 0) visit(v);
66
+ // Directed, acyclic edges as [tail, head] node indices.
67
+ const dag = edges.map((e, i) => {
68
+ const a = /** @type {number} */ (index.get(e.from));
69
+ const b = /** @type {number} */ (index.get(e.to));
70
+ return reversed.has(i) ? [b, a] : [a, b];
71
+ });
72
+
73
+ // 2. Ranks: longest path, then pull nodes down toward their successors.
74
+ const preds = nodeIds.map(() => /** @type {number[]} */ ([]));
75
+ const succs = nodeIds.map(() => /** @type {number[]} */ ([]));
76
+ for (const [a, b] of dag) {
77
+ preds[b].push(a);
78
+ succs[a].push(b);
79
+ }
80
+ const rank = new Array(n).fill(-1);
81
+ /** @param {number} v @returns {number} */
82
+ const rankOf = (v) => {
83
+ if (rank[v] < 0) rank[v] = preds[v].length ? Math.max(...preds[v].map(rankOf)) + 1 : 0;
84
+ return rank[v];
85
+ };
86
+ for (let v = 0; v < n; v++) rankOf(v);
87
+ for (let changed = true; changed;) {
88
+ changed = false;
89
+ for (let v = n - 1; v >= 0; v--) {
90
+ if (!preds[v].length || !succs[v].length) continue;
91
+ const best = Math.min(...succs[v].map((w) => rank[w])) - 1;
92
+ if (best > rank[v]) {
93
+ rank[v] = best;
94
+ changed = true;
95
+ }
96
+ }
97
+ }
98
+
99
+ // 3. Chains of waypoints for edges that span ranks. Items: real nodes are
100
+ // 0..n-1; waypoints follow. Each item has a rank.
101
+ /** @type {{ rank: number, node: boolean }[]} */
102
+ const items = rank.map((r) => ({ rank: r, node: true }));
103
+ /** @type {[number, number][]} */
104
+ const links = [];
105
+ /** @type {number[][]} */
106
+ const chains = dag.map(([a, b]) => {
107
+ const chain = [];
108
+ let prev = a;
109
+ for (let r = rank[a] + 1; r < rank[b]; r++) {
110
+ const id = items.length;
111
+ items.push({ rank: r, node: false });
112
+ links.push([prev, id]);
113
+ chain.push(id);
114
+ prev = id;
115
+ }
116
+ links.push([prev, b]);
117
+ return chain;
118
+ });
119
+ const R = Math.max(...rank) + 1;
120
+ const up = items.map(() => /** @type {number[]} */ ([]));
121
+ const down = items.map(() => /** @type {number[]} */ ([]));
122
+ for (const [a, b] of links) {
123
+ down[a].push(b);
124
+ up[b].push(a);
125
+ }
126
+
127
+ // 4. Order within ranks: barycenter sweeps, keep the fewest crossings.
128
+ /** @type {number[][]} */
129
+ let layers = Array.from({ length: R }, () => []);
130
+ items.forEach((it, i) => layers[it.rank].push(i));
131
+ const crossings = (/** @type {number[][]} */ ls) => {
132
+ const at = new Map();
133
+ ls.forEach((l) => l.forEach((v, i) => at.set(v, i)));
134
+ let c = 0;
135
+ for (let r = 0; r + 1 < ls.length; r++) {
136
+ const es = [];
137
+ for (const v of ls[r]) for (const w of down[v]) es.push([at.get(v), at.get(w)]);
138
+ for (let i = 0; i < es.length; i++) for (let j = i + 1; j < es.length; j++) {
139
+ if ((es[i][0] - es[j][0]) * (es[i][1] - es[j][1]) < 0) c++;
140
+ }
141
+ }
142
+ return c;
143
+ };
144
+ let best = layers.map((l) => [...l]);
145
+ let bestC = crossings(best);
146
+ for (let s = 0; s < SWEEPS && bestC > 0; s++) {
147
+ const downward = s % 2 === 0;
148
+ const at = new Map();
149
+ layers.forEach((l) => l.forEach((v, i) => at.set(v, i)));
150
+ const order = downward ? [...layers.keys()].slice(1) : [...layers.keys()].reverse().slice(1);
151
+ for (const r of order) {
152
+ const bary = new Map();
153
+ for (const v of layers[r]) {
154
+ const ns = downward ? up[v] : down[v];
155
+ bary.set(v, ns.length ? ns.reduce((sum, w) => sum + at.get(w), 0) / ns.length : at.get(v));
156
+ }
157
+ layers[r] = [...layers[r]].sort((a, b) => bary.get(a) - bary.get(b) || at.get(a) - at.get(b));
158
+ layers[r].forEach((v, i) => at.set(v, i));
159
+ }
160
+ const c = crossings(layers);
161
+ if (c < bestC) {
162
+ best = layers.map((l) => [...l]);
163
+ bestC = c;
164
+ }
165
+ }
166
+ layers = best;
167
+
168
+ // 5. Positions: pull toward neighbours' mean, keep minimum gaps.
169
+ const gap = (/** @type {number} */ a, /** @type {number} */ b) => (items[a].node && items[b].node ? GAP_NODE : items[a].node || items[b].node ? GAP_MIXED : GAP_VIA);
170
+ const x = new Array(items.length).fill(0);
171
+ for (const l of layers) l.forEach((v, i) => (x[v] = i === 0 ? 0 : x[l[i - 1]] + gap(l[i - 1], v)));
172
+ const centre = (/** @type {number[]} */ l) => (x[l[0]] + x[l[l.length - 1]]) / 2;
173
+ const widest = Math.max(...layers.map((l) => x[l[l.length - 1]] - x[l[0]]));
174
+ for (const l of layers) {
175
+ const shift = widest / 2 - centre(l);
176
+ for (const v of l) x[v] += shift;
177
+ }
178
+ for (let round = 0; round < PLACE_ROUNDS; round++) {
179
+ const downward = round % 2 === 0;
180
+ const order = downward ? [...layers.keys()] : [...layers.keys()].reverse();
181
+ for (const r of order) {
182
+ const l = layers[r];
183
+ const want = l.map((v) => {
184
+ const ns = [...up[v], ...down[v]];
185
+ return ns.length ? ns.reduce((sum, w) => sum + x[w], 0) / ns.length : x[v];
186
+ });
187
+ const placed = placeInOrder(want, l.slice(1).map((v, i) => gap(l[i], v)));
188
+ l.forEach((v, i) => (x[v] = placed[i]));
189
+ }
190
+ }
191
+ // Snap to a quarter-pitch grid, so a chain whose ends sit a hair apart
192
+ // draws straight, then restore the gaps left to right.
193
+ for (const l of layers) {
194
+ l.forEach((v, i) => {
195
+ x[v] = Math.round(x[v] * 4) / 4;
196
+ if (i > 0) x[v] = Math.max(x[v], x[l[i - 1]] + Math.ceil(gap(l[i - 1], v) * 4) / 4);
197
+ });
198
+ }
199
+ const min = Math.min(...x);
200
+ const round2 = (/** @type {number} */ v) => Math.round((v - min) * 100) / 100;
201
+
202
+ const ranks = new Map(nodeIds.map((id, i) => [id, rank[i]]));
203
+ const pos = new Map(nodeIds.map((id, i) => [id, round2(x[i])]));
204
+ const via = chains.map((chain, i) => {
205
+ /** @type {[number, number][]} */
206
+ const pts = chain.map((v) => [items[v].rank, round2(x[v])]);
207
+ return reversed.has(i) ? pts.reverse() : pts;
208
+ });
209
+ return { ranks, pos, via };
210
+ }
211
+
212
+ /**
213
+ * Positions closest (least squares) to `want`, in the same order, with
214
+ * position[i + 1] − position[i] ≥ gaps[i]: pool-adjacent-violators on the
215
+ * gap-shifted targets.
216
+ * @param {number[]} want
217
+ * @param {number[]} gaps
218
+ * @returns {number[]}
219
+ */
220
+ export function placeInOrder(want, gaps) {
221
+ const offset = [0];
222
+ for (const g of gaps) offset.push(offset[offset.length - 1] + g);
223
+ /** @type {{ sum: number, count: number }[]} */
224
+ const blocks = [];
225
+ want.forEach((w, i) => {
226
+ blocks.push({ sum: w - offset[i], count: 1 });
227
+ while (blocks.length > 1 && blocks[blocks.length - 2].sum / blocks[blocks.length - 2].count > blocks[blocks.length - 1].sum / blocks[blocks.length - 1].count) {
228
+ const b = /** @type {{ sum: number, count: number }} */ (blocks.pop());
229
+ blocks[blocks.length - 1].sum += b.sum;
230
+ blocks[blocks.length - 1].count += b.count;
231
+ }
232
+ });
233
+ const out = [];
234
+ for (const b of blocks) for (let k = 0; k < b.count; k++) out.push(b.sum / b.count + offset[out.length]);
235
+ return out;
236
+ }