@teurons/vds-diagrams 0.0.0-stage → 0.3.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.
Files changed (51) hide show
  1. package/README.md +170 -2
  2. package/dist/cli.js +2244 -0
  3. package/dist/diagrams.css +991 -0
  4. package/dist/grid.d.ts +1 -0
  5. package/dist/grid.js +283 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +2044 -0
  8. package/dist/skills/vds-aggregates/SKILL.md +115 -0
  9. package/dist/skills/vds-ask-or-park/SKILL.md +101 -0
  10. package/dist/skills/vds-book-to-spec/SKILL.md +136 -0
  11. package/dist/skills/vds-build-from-published/SKILL.md +89 -0
  12. package/dist/skills/vds-change/SKILL.md +113 -0
  13. package/dist/skills/vds-context-map/SKILL.md +125 -0
  14. package/dist/skills/vds-contexts/SKILL.md +134 -0
  15. package/dist/skills/vds-diagrams/SKILL.md +88 -0
  16. package/dist/skills/vds-entities-and-values/SKILL.md +108 -0
  17. package/dist/skills/vds-language/SKILL.md +106 -0
  18. package/dist/skills/vds-model-review/SKILL.md +123 -0
  19. package/dist/skills/vds-ports-and-adapters/SKILL.md +119 -0
  20. package/dist/skills/vds-publish/SKILL.md +123 -0
  21. package/dist/skills/vds-reframe/SKILL.md +122 -0
  22. package/dist/skills/vds-requirements/SKILL.md +128 -0
  23. package/dist/skills/vds-requirements-review/SKILL.md +121 -0
  24. package/dist/skills/vds-scenarios/SKILL.md +142 -0
  25. package/dist/skills/vds-slice-blocks/SKILL.md +127 -0
  26. package/dist/skills/vds-story-walk/SKILL.md +128 -0
  27. package/dist/skills/vds-strip-invented/SKILL.md +130 -0
  28. package/dist/skills/vds-subdomains/SKILL.md +127 -0
  29. package/dist/skills/vds-which-skill/FILE-SHAPES.md +312 -0
  30. package/dist/skills/vds-which-skill/SKILL.md +125 -0
  31. package/dist/types/diagrams/src/grid/camera.d.ts +32 -0
  32. package/dist/types/diagrams/src/grid/capability.d.ts +11 -0
  33. package/dist/types/diagrams/src/grid/fold-uj.d.ts +2 -0
  34. package/dist/types/diagrams/src/grid/grid-canvas.d.ts +95 -0
  35. package/dist/types/diagrams/src/grid/index.d.ts +5 -0
  36. package/dist/types/diagrams/src/grid/input.d.ts +93 -0
  37. package/dist/types/diagrams/src/grid/route.d.ts +21 -0
  38. package/dist/types/engine/js/bridge.d.ts +12 -0
  39. package/dist/types/engine/js/index.d.ts +73 -0
  40. package/dist/types/vds-diagrams/src/canvas.d.ts +43 -0
  41. package/dist/types/vds-diagrams/src/from-scenarios.d.ts +4 -0
  42. package/dist/types/vds-diagrams/src/grid-folds.d.ts +1 -0
  43. package/dist/types/vds-diagrams/src/grid.d.ts +2 -0
  44. package/dist/types/vds-diagrams/src/index.d.ts +6 -0
  45. package/dist/types/vds-diagrams/src/types.d.ts +39 -0
  46. package/dist/types/vds-diagrams/src/user-journey.d.ts +54 -0
  47. package/dist/types/vds-diagrams/src/workspace.d.ts +25 -0
  48. package/dist/vds_engine.wasm +0 -0
  49. package/dist/workspace.d.ts +1 -0
  50. package/dist/workspace.js +113 -0
  51. package/package.json +68 -3
package/dist/index.js ADDED
@@ -0,0 +1,2044 @@
1
+ 'use client';
2
+ "use client";
3
+
4
+ // src/canvas.tsx
5
+ import { Button } from "@teurons/ui/button";
6
+ import { CopyButton } from "@teurons/ui/copy-button";
7
+ import {
8
+ Drawer,
9
+ DrawerBody,
10
+ DrawerContent,
11
+ DrawerDescription,
12
+ DrawerHeader,
13
+ DrawerTitle
14
+ } from "@teurons/ui/drawer";
15
+ import { Popover, PopoverContent, PopoverTrigger } from "@teurons/ui/popover";
16
+ import {
17
+ SegmentedControl,
18
+ SegmentedControlList,
19
+ SegmentedControlTrigger
20
+ } from "@teurons/ui/segmented-control";
21
+ import { Tooltip, TooltipContent, TooltipTrigger } from "@teurons/ui/tooltip";
22
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
23
+
24
+ // ../diagrams/src/grid/camera.ts
25
+ var MAX = 2.5;
26
+ var GLIDE_MS = 380;
27
+ var easeOut = (k) => 1 - (1 - k) ** 3;
28
+ var pen = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : null;
29
+ function labelWidth(pill) {
30
+ const nm = pill.querySelector(".nm");
31
+ if (!nm || !pen) return pill.offsetWidth;
32
+ pen.font = getComputedStyle(nm).font;
33
+ const text = nm.textContent ?? "";
34
+ const words = text.split(" ");
35
+ const one = pen.measureText(text).width;
36
+ let two = one;
37
+ for (let k = 1; k < words.length; k++)
38
+ two = Math.min(
39
+ two,
40
+ Math.max(
41
+ pen.measureText(words.slice(0, k).join(" ")).width,
42
+ pen.measureText(words.slice(k).join(" ")).width
43
+ )
44
+ );
45
+ return pill.scrollWidth - nm.scrollWidth + Math.ceil(two) + 2;
46
+ }
47
+ function floorOf({ w, h, W, H }, pills, cols) {
48
+ const labelled = Math.max(
49
+ 0,
50
+ ...pills.map((p, i) => {
51
+ const col = cols[i];
52
+ return col ? (labelWidth(p) + 12) / col.w : 0;
53
+ })
54
+ );
55
+ return Math.min(MAX, Math.max(labelled, Math.min(1, Math.max(0.15, Math.min(w / W, h / H)))));
56
+ }
57
+ function keep({ w, h, W, H }, floor, v) {
58
+ const s = Math.min(MAX, Math.max(floor, v.s));
59
+ const x = Math.min(0, Math.max(Math.min(0, w - W * s), v.x));
60
+ const y = Math.min(0, Math.max(Math.min(0, h - H * s), v.y));
61
+ return { s, x: W * s < w ? 0 : x, y: H * s < h ? 0 : y };
62
+ }
63
+ function zoomAt(v, f, px, py, floor) {
64
+ const s = Math.min(MAX, Math.max(floor, v.s * f));
65
+ return { s, x: px - (px - v.x) * (s / v.s), y: py - (py - v.y) * (s / v.s) };
66
+ }
67
+ function frame(self, group, { w, h }, floor) {
68
+ const bounds = (rs) => {
69
+ const x0 = Math.min(...rs.map((r) => r.x)), x1 = Math.max(...rs.map((r) => r.x + r.w));
70
+ const y0 = Math.min(...rs.map((r) => r.y)), y1 = Math.max(...rs.map((r) => r.y + r.h));
71
+ return { x0, x1, y0, y1, s: Math.min(1.1, w * 0.82 / (x1 - x0), h * 0.82 / (y1 - y0)) };
72
+ };
73
+ const all = bounds(group);
74
+ const alone = bounds([self]);
75
+ const f = all.s >= 0.5 ? all : { ...alone, s: Math.max(0.5, Math.min(1.1, alone.s)) };
76
+ const s = Math.min(MAX, Math.max(floor, f.s));
77
+ return { s, x: w / 2 - (f.x0 + f.x1) / 2 * s, y: h / 2 - (f.y0 + f.y1) / 2 * s };
78
+ }
79
+
80
+ // ../diagrams/src/grid/input.ts
81
+ var GRID_INPUTS = [1];
82
+ var ids = (list) => (list ?? []).map((x) => x.id);
83
+ function twice(list) {
84
+ const seen = /* @__PURE__ */ new Set();
85
+ const out = [];
86
+ for (const id of list) {
87
+ if (seen.has(id)) out.push(id);
88
+ seen.add(id);
89
+ }
90
+ return [...new Set(out)];
91
+ }
92
+ var wrongKind = (input) => input?.kind !== "grid" || input?.input === void 0 || !GRID_INPUTS.includes(input.input) ? `not a grid input this canvas reads: kind ${input?.kind ?? "(none)"}, input ${input?.input ?? "(none)"}; it reads grid ${GRID_INPUTS.join(", ")}` : null;
93
+ function shapeProblems(input) {
94
+ const out = [];
95
+ if (!input.columns?.length) out.push("no columns");
96
+ if (!input.rows?.length) out.push("no rows");
97
+ for (const [what, list] of [
98
+ ["column", ids(input.columns)],
99
+ ["row", ids(input.rows)],
100
+ ["box", ids(input.boxes)]
101
+ ])
102
+ for (const id of twice(list)) out.push(`${what} ${id} appears twice`);
103
+ return out;
104
+ }
105
+ var spanOf = (b) => {
106
+ const span = b.span ?? 1;
107
+ return Number.isInteger(span) && span >= 1 ? span : null;
108
+ };
109
+ function spanProblem(b, at, cols) {
110
+ const span = spanOf(b);
111
+ if (span === null) return `box ${b.id}: span must be a whole number from 1`;
112
+ return at + span > cols ? `box ${b.id}: spans past the last column` : null;
113
+ }
114
+ function placeProblems(b, row, at, cols) {
115
+ if (!row || at < 0)
116
+ return [
117
+ !row && `box ${b.id}: unknown row ${b.row}`,
118
+ at < 0 && `box ${b.id}: unknown column ${b.column}`
119
+ ].filter((m) => Boolean(m));
120
+ return [
121
+ row.kind === "divider" && `box ${b.id}: a divider row holds no box`,
122
+ spanProblem(b, at, cols)
123
+ ].filter((m) => Boolean(m));
124
+ }
125
+ function cellsOf(b, rows, cols) {
126
+ const at = cols.indexOf(b.column);
127
+ const span = spanOf(b);
128
+ if (!rows.has(b.row) || at < 0 || span === null) return [];
129
+ const end = Math.min(at + span, cols.length);
130
+ return Array.from({ length: end - at }, (_, k) => `${b.row}|${at + k}`);
131
+ }
132
+ function overlapProblems(boxes, rows, cols) {
133
+ const out = [];
134
+ const covered = /* @__PURE__ */ new Map();
135
+ for (const b of boxes) {
136
+ const span = spanOf(b) ?? 0;
137
+ for (const key of cellsOf(b, rows, cols)) {
138
+ const other = covered.get(key);
139
+ if (other && (other.span > 1 || span > 1))
140
+ out.push(`box ${b.id}: overlaps box ${other.id} in row ${b.row}`);
141
+ covered.set(key, { id: b.id, span });
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ function arrowProblems(arrows, boxes) {
147
+ const known = new Set(ids(boxes));
148
+ return (arrows ?? []).flatMap(
149
+ (a) => [a.from, a.to].filter((end) => !known.has(String(end).split("#")[0] ?? "")).map((end) => `arrow ${a.from} \u2192 ${a.to}: unknown box ${end}`)
150
+ );
151
+ }
152
+ function problemsOf(input) {
153
+ const kind = wrongKind(input);
154
+ if (kind) return [kind];
155
+ if (!input)
156
+ return [
157
+ `not a grid input this canvas reads: kind (none), input (none); it reads grid ${GRID_INPUTS.join(", ")}`
158
+ ];
159
+ const cols = ids(input.columns);
160
+ const rows = new Map((input.rows ?? []).map((r) => [r.id, r]));
161
+ const boxes = input.boxes ?? [];
162
+ return [
163
+ ...shapeProblems(input),
164
+ ...boxes.flatMap((b) => placeProblems(b, rows.get(b.row), cols.indexOf(b.column), cols.length)),
165
+ ...overlapProblems(boxes, rows, cols),
166
+ ...arrowProblems(input.arrows, boxes)
167
+ ];
168
+ }
169
+ function layoutOf(input) {
170
+ const problems = problemsOf(input);
171
+ if (problems.length) throw new Error(`cannot draw this grid:
172
+ - ${problems.join("\n- ")}`);
173
+ const columns = (input.columns ?? []).map((c, i) => ({
174
+ ...c,
175
+ number: c.number ?? String(i + 1)
176
+ }));
177
+ const rows = (input.rows ?? []).map((r) => ({ ...r, kind: r.kind ?? "lane" }));
178
+ const colAt = new Map(columns.map((c, i) => [c.id, i]));
179
+ const cells = /* @__PURE__ */ new Map();
180
+ const order = {};
181
+ const reading = [];
182
+ const sorted = [...input.boxes ?? []].sort(
183
+ (a, b) => (colAt.get(a.column) ?? 0) - (colAt.get(b.column) ?? 0) || rows.findIndex((r) => r.id === a.row) - rows.findIndex((r) => r.id === b.row)
184
+ );
185
+ const count = /* @__PURE__ */ new Map();
186
+ for (const b of sorted) {
187
+ const c = colAt.get(b.column);
188
+ if (c === void 0) continue;
189
+ const n = (count.get(c) ?? 0) + 1;
190
+ count.set(c, n);
191
+ const key = `${b.row}|${c}`;
192
+ const cell = cells.get(key) ?? { span: b.span ?? 1, boxes: [] };
193
+ cell.boxes.push({ ...b, n, c });
194
+ cells.set(key, cell);
195
+ order[b.id] = c;
196
+ reading.push(b.id);
197
+ }
198
+ const covered = /* @__PURE__ */ new Set();
199
+ for (const [key, cell] of cells) {
200
+ const [row, ci] = key.split("|");
201
+ for (let k = 1; k < cell.span; k++) covered.add(`${row}|${Number(ci) + k}`);
202
+ }
203
+ const cellAt = (row, ci) => {
204
+ if (row.kind === "divider") return ci === 0 ? { span: columns.length, boxes: [] } : null;
205
+ const key = `${row.id}|${ci}`;
206
+ if (covered.has(key)) return null;
207
+ return cells.get(key) ?? { span: 1, boxes: [] };
208
+ };
209
+ const num = /* @__PURE__ */ new Map();
210
+ for (const cell of cells.values()) for (const b of cell.boxes) num.set(b.id, `${b.c + 1}.${b.n}`);
211
+ const edges = (input.arrows ?? []).map((a) => {
212
+ const n = a.numbered === "from" ? num.get(a.from) : void 0;
213
+ return n && a.label ? { ...a, label: `${n} ${a.label}` } : { ...a };
214
+ });
215
+ return { columns, rows, cellAt, order, reading, edges, corner: input.corner };
216
+ }
217
+
218
+ // ../diagrams/src/grid/fold-uj.ts
219
+ var ACTOR = "actor";
220
+ var INBOX = "inbox";
221
+ function actionsOf(input) {
222
+ const title = new Map((input.boxes ?? []).map((b) => [b.id, b]));
223
+ const out = /* @__PURE__ */ new Map();
224
+ for (const a of input.arrows ?? []) {
225
+ const to = title.get(a.to);
226
+ if (to?.kind === "cmd" && !out.has(a.from)) out.set(a.from, to.title);
227
+ }
228
+ return out;
229
+ }
230
+ function screenAtStep(columns, screens) {
231
+ const at = /* @__PURE__ */ new Map();
232
+ let open;
233
+ for (const c of columns) {
234
+ open = screens.find((s) => s.column === c.id) ?? open;
235
+ if (open) at.set(c.id, open);
236
+ }
237
+ return at;
238
+ }
239
+ function foldScenarioToUserJourney(input) {
240
+ const rows = (input.rows ?? []).filter((r) => r.kind === ACTOR || r.kind === INBOX);
241
+ const order = new Map((input.columns ?? []).map((c, i) => [c.id, i]));
242
+ const byOrder = (a, b) => (order.get(a.column) ?? 0) - (order.get(b.column) ?? 0);
243
+ const all = input.boxes ?? [];
244
+ const persona = new Set(rows.filter((r) => r.kind === ACTOR).map((r) => r.id));
245
+ const screens = all.filter((b) => persona.has(b.row)).sort(byOrder);
246
+ const used = new Set(screens.map((b) => b.column));
247
+ const openAt = screenAtStep(input.columns ?? [], screens);
248
+ const messages = all.filter((b) => rows.some((r) => r.kind === INBOX && r.id === b.row)).map((b) => ({ ...b, column: openAt.get(b.column)?.column ?? b.column })).filter((b) => used.has(b.column));
249
+ const boxes = screens;
250
+ const keptAt = (input.columns ?? []).map((c) => used.has(c.id));
251
+ const folded = [
252
+ ...boxes.map((b) => {
253
+ if (!b.span || b.span < 2) return b;
254
+ const at = order.get(b.column) ?? 0;
255
+ const span = keptAt.slice(at, at + b.span).filter(Boolean).length;
256
+ const { span: _, ...rest } = b;
257
+ return span > 1 ? { ...rest, span } : rest;
258
+ }),
259
+ ...messages
260
+ ];
261
+ const columns = (input.columns ?? []).filter((c) => used.has(c.id)).map((c, i) => ({
262
+ ...c,
263
+ number: String(i + 1),
264
+ label: boxes.find((b) => b.column === c.id)?.title ?? c.label
265
+ }));
266
+ const actions = actionsOf(input);
267
+ const arrows = [];
268
+ for (let i = 1; i < boxes.length; i++) {
269
+ const from = boxes[i - 1];
270
+ const to = boxes[i];
271
+ if (!from || !to || from.column === to.column) continue;
272
+ const label = actions.get(from.id);
273
+ arrows.push({
274
+ from: from.id,
275
+ to: to.id,
276
+ tone: "journey",
277
+ ends: "dots",
278
+ ...label ? { label } : {}
279
+ });
280
+ }
281
+ return { ...input, corner: ["Screen \u2192", "Persona \u2193"], columns, rows, boxes: folded, arrows };
282
+ }
283
+
284
+ // ../diagrams/src/grid/route.ts
285
+ function wrap(text, max) {
286
+ const lines = [""];
287
+ for (const w of String(text).split(" ")) {
288
+ const cur = lines.at(-1);
289
+ if (!cur) lines[lines.length - 1] = w;
290
+ else if (`${cur} ${w}`.length <= max) lines[lines.length - 1] = `${cur} ${w}`;
291
+ else lines.push(w);
292
+ }
293
+ if (lines.length > 2) {
294
+ const rest = lines.slice(1).join(" ");
295
+ lines.length = 1;
296
+ lines.push(rest.length > max ? `${rest.slice(0, max - 1)}\u2026` : rest);
297
+ }
298
+ return lines;
299
+ }
300
+ var NORMAL = {
301
+ right: [1, 0],
302
+ left: [-1, 0],
303
+ bottom: [0, 1],
304
+ top: [0, -1]
305
+ };
306
+ var HEAD = 8;
307
+ var TUCK = 4;
308
+ function port(b, side, i, n, at) {
309
+ const t = at ?? (i + 1) / (n + 1);
310
+ if (side === "right") return [b.x + b.w, b.y + b.h * t];
311
+ if (side === "left") return [b.x, b.y + b.h * t];
312
+ if (side === "bottom") return [b.x + b.w * t, b.y + b.h];
313
+ return [b.x + b.w * t, b.y];
314
+ }
315
+ var GAP = 14;
316
+ var inside = (a, b) => a.x >= b.x - 0.5 && a.y >= b.y - 0.5 && a.x + a.w <= b.x + b.w + 0.5 && a.y + a.h <= b.y + b.h + 0.5;
317
+ var hits = (p, q, r) => {
318
+ const x0 = Math.min(p[0], q[0]), x1 = Math.max(p[0], q[0]), y0 = Math.min(p[1], q[1]), y1 = Math.max(p[1], q[1]);
319
+ return x1 > r.x + 2 && x0 < r.x + r.w - 2 && y1 > r.y + 2 && y0 < r.y + r.h - 2;
320
+ };
321
+ var clear = (pts, obstacles) => pts.every((p, i) => i === 0 || obstacles.every((r) => !hits(pts[i - 1] ?? p, p, r)));
322
+ var lerp = (a, b, t) => a + (b - a) * t;
323
+ function viaBelow(A, B, i2, obstacles, lane) {
324
+ const sx = A.x + A.w, sy = A.y + A.h / 2;
325
+ const gx = sx + Math.max(GAP, 12) + lane * 10;
326
+ const bx = B.x + 8 + i2 * 12, by = B.y + B.h;
327
+ const straight = [
328
+ [sx, sy],
329
+ [bx, sy],
330
+ [bx, by]
331
+ ];
332
+ if (clear(straight, obstacles)) return straight;
333
+ const below = A.y + A.h + GAP + lane * 8;
334
+ const runs = [];
335
+ for (let ry = below; ry < below + 2400; ry += 8) runs.push(ry);
336
+ for (let ry = by + GAP + lane * 8; ry < below; ry += 8) runs.push(ry);
337
+ for (const ry of runs) {
338
+ const p = [
339
+ [sx, sy],
340
+ [gx, sy],
341
+ [gx, ry],
342
+ [bx, ry],
343
+ [bx, by]
344
+ ];
345
+ if (clear(p, obstacles)) return p;
346
+ }
347
+ return void 0;
348
+ }
349
+ var gapsInOrder = (nearA, nearB, late) => late ? [...nearB, ...nearA] : [...nearA, ...nearB];
350
+ function candidates(A, B, t1, t2, hint, obstacles = [], lane = 0, lanes = 1) {
351
+ const out = [];
352
+ const below = B.y >= A.y + A.h, above = B.y + B.h <= A.y;
353
+ const right = B.x >= A.x + A.w, left = B.x + B.w <= A.x;
354
+ const ox0 = Math.max(A.x, B.x) + 8, ox1 = Math.min(A.x + A.w, B.x + B.w) - 8;
355
+ const oy0 = Math.max(A.y, B.y) + 6, oy1 = Math.min(A.y + A.h, B.y + B.h) - 6;
356
+ const ax = lerp(A.x + 8, A.x + A.w - 8, t1), bx = lerp(B.x + 8, B.x + B.w - 8, t2);
357
+ const ay = lerp(A.y + 6, A.y + A.h - 6, t1), by = lerp(B.y + 6, B.y + B.h - 6, t2);
358
+ const fromSide = hint.from, toSide = hint.to;
359
+ const ok = (side, want) => !want || side === want;
360
+ if ((below || above) && ox0 <= ox1 && ok(below ? "bottom" : "top", fromSide) && ok(below ? "top" : "bottom", toSide)) {
361
+ const x = lerp(ox0, ox1, t1);
362
+ out.push(
363
+ below ? [
364
+ [x, A.y + A.h],
365
+ [x, B.y]
366
+ ] : [
367
+ [x, A.y],
368
+ [x, B.y + B.h]
369
+ ]
370
+ );
371
+ }
372
+ if ((right || left) && oy0 <= oy1 && ok(right ? "right" : "left", fromSide) && ok(right ? "left" : "right", toSide)) {
373
+ const y = lerp(oy0, oy1, t1);
374
+ out.push(
375
+ right ? [
376
+ [A.x + A.w, y],
377
+ [B.x, y]
378
+ ] : [
379
+ [A.x, y],
380
+ [B.x + B.w, y]
381
+ ]
382
+ );
383
+ }
384
+ for (const side of ["right", "left"]) {
385
+ if (!ok(side, fromSide) || !(below || above) || !ok(below ? "top" : "bottom", toSide)) continue;
386
+ const sx = side === "right" ? A.x + A.w : A.x;
387
+ if (side === "right" && bx <= sx + GAP || side === "left" && bx >= sx - GAP) continue;
388
+ out.push([
389
+ [sx, ay],
390
+ [bx, ay],
391
+ [bx, below ? B.y : B.y + B.h]
392
+ ]);
393
+ }
394
+ for (const side of ["left", "right"]) {
395
+ if (!ok(side, toSide) || !(below || above) || !ok(below ? "bottom" : "top", fromSide)) continue;
396
+ const ex = side === "left" ? B.x : B.x + B.w;
397
+ const beside = side === "left" ? ex - GAP : ex + GAP;
398
+ for (const x of [ax, beside]) {
399
+ if (x < A.x + 4 || x > A.x + A.w - 4) continue;
400
+ if (side === "left" && x > ex - GAP || side === "right" && x < ex + GAP) continue;
401
+ out.push([
402
+ [x, below ? A.y + A.h : A.y],
403
+ [x, by],
404
+ [ex, by]
405
+ ]);
406
+ }
407
+ }
408
+ if ((below || above) && ok(below ? "bottom" : "top", fromSide) && ok(below ? "top" : "bottom", toSide))
409
+ for (const ym of below ? [B.y - GAP, A.y + A.h + GAP] : [B.y + B.h + GAP, A.y - GAP])
410
+ out.push([
411
+ [ax, below ? A.y + A.h : A.y],
412
+ [ax, ym],
413
+ [bx, ym],
414
+ [bx, below ? B.y : B.y + B.h]
415
+ ]);
416
+ for (const side of ["right", "left"]) {
417
+ if (!ok(side, fromSide) || !(below || above) || !ok(below ? "top" : "bottom", toSide)) continue;
418
+ const sx = side === "right" ? A.x + A.w : A.x;
419
+ const roomy = obstacles.map((r) => ({ x: r.x - 10, y: r.y, w: r.w + 20, h: r.h }));
420
+ const turn = (lanes - 1 - lane) * 7;
421
+ const ym = below ? B.y - GAP - turn : B.y + B.h + GAP + turn;
422
+ for (let k = 1; k <= 60; k++) {
423
+ const dir = side === "right" ? 1 : -1;
424
+ const base = sx + dir * (GAP + (k - 1) * 10);
425
+ const band = Array.from({ length: lanes }, (_, j) => base + dir * j * 12);
426
+ if (!band.every(
427
+ (x) => clear(
428
+ [
429
+ [x, ay],
430
+ [x, ym]
431
+ ],
432
+ roomy
433
+ )
434
+ ))
435
+ continue;
436
+ const gx = band[lane] ?? base;
437
+ out.push([
438
+ [sx, ay],
439
+ [gx, ay],
440
+ [gx, ym],
441
+ [bx, ym],
442
+ [bx, below ? B.y : B.y + B.h]
443
+ ]);
444
+ break;
445
+ }
446
+ }
447
+ for (const [fs, ts, dir] of [
448
+ ["right", "left", 1],
449
+ ["left", "right", -1]
450
+ ]) {
451
+ if (!ok(fs, fromSide) || !ok(ts, toSide)) continue;
452
+ if (dir === 1 ? B.x < A.x + A.w + 2 * GAP : B.x + B.w > A.x - 2 * GAP) continue;
453
+ const sx = dir === 1 ? A.x + A.w : A.x, ex = dir === 1 ? B.x : B.x + B.w;
454
+ const sy = lerp(A.y + 8, A.y + A.h - 8, t1), ey = lerp(B.y + 8, B.y + B.h - 8, t2);
455
+ const xs = (from, to) => {
456
+ const list = [];
457
+ const d = Math.sign(to - from);
458
+ for (let x = from; d * (to - x) > 0; x += d * 8) list.push(x);
459
+ return list;
460
+ };
461
+ const nearA = xs(sx + dir * (GAP + lane * 8), ex - dir * GAP);
462
+ const nearB = xs(ex - dir * (GAP + lane * 8), sx + dir * GAP);
463
+ const z = gapsInOrder(nearA, nearB, hint.late).map((x) => [
464
+ [sx, sy],
465
+ [x, sy],
466
+ [x, ey],
467
+ [ex, ey]
468
+ ]).find((p) => clear(p, obstacles));
469
+ if (z) {
470
+ out.push(z);
471
+ continue;
472
+ }
473
+ const rails = [
474
+ B.y - GAP - lane * 8,
475
+ B.y + B.h + GAP + lane * 8,
476
+ A.y - GAP - lane * 8,
477
+ A.y + A.h + GAP + lane * 8
478
+ ];
479
+ found: for (const ry of rails)
480
+ for (const g1 of nearA.slice(0, 12))
481
+ for (const g2 of nearB.slice(0, 12)) {
482
+ if (dir === 1 ? g2 <= g1 : g2 >= g1) continue;
483
+ const p = [
484
+ [sx, sy],
485
+ [g1, sy],
486
+ [g1, ry],
487
+ [g2, ry],
488
+ [g2, ey],
489
+ [ex, ey]
490
+ ];
491
+ if (clear(p, obstacles)) {
492
+ out.push(p);
493
+ break found;
494
+ }
495
+ }
496
+ }
497
+ if (below || above)
498
+ for (const side of ["left", "right"]) {
499
+ if (!ok(side, fromSide) || !ok(side, toSide)) continue;
500
+ const d = side === "right" ? 1 : -1;
501
+ const edge = side === "right" ? Math.max(A.x + A.w, B.x + B.w) : Math.min(A.x, B.x);
502
+ const sx = side === "right" ? A.x + A.w : A.x, ex = side === "right" ? B.x + B.w : B.x;
503
+ const sy = lerp(A.y + 8, A.y + A.h - 8, t1), ey = lerp(B.y + 8, B.y + B.h - 8, t2);
504
+ for (let k = 0; k < 8; k++) {
505
+ const gx = edge + d * (GAP + (lane + k) * 8);
506
+ const p = [
507
+ [sx, sy],
508
+ [gx, sy],
509
+ [gx, ey],
510
+ [ex, ey]
511
+ ];
512
+ if (clear(p, obstacles)) {
513
+ out.push(p);
514
+ break;
515
+ }
516
+ }
517
+ }
518
+ return out;
519
+ }
520
+ function roundPath(pts, r = 14) {
521
+ const first = pts[0] ?? [0, 0];
522
+ let d = `M${first[0]},${first[1]}`;
523
+ for (let i = 1; i < pts.length - 1; i++) {
524
+ const [px = 0, py = 0] = pts[i - 1] ?? [0, 0];
525
+ const [x = 0, y = 0] = pts[i] ?? [0, 0];
526
+ const [nx = 0, ny = 0] = pts[i + 1] ?? [0, 0];
527
+ const k1 = Math.min(r, Math.hypot(x - px, y - py) / 2), k2 = Math.min(r, Math.hypot(nx - x, ny - y) / 2);
528
+ const ux = Math.sign(x - px), uy = Math.sign(y - py), vx = Math.sign(nx - x), vy = Math.sign(ny - y);
529
+ d += ` L${x - ux * k1},${y - uy * k1} Q${x},${y} ${x + vx * k2},${y + vy * k2}`;
530
+ }
531
+ const [lx = 0, ly = 0] = pts.at(-1) ?? [0, 0];
532
+ return `${d} L${lx},${ly}`;
533
+ }
534
+ var RING = 3;
535
+ function outward(pts) {
536
+ const [ax = 0, ay = 0] = pts[0] ?? [0, 0];
537
+ const [bx = 0, by = 0] = pts[1] ?? [0, 0];
538
+ const len = Math.hypot(bx - ax, by - ay) || 1;
539
+ return [ax + (bx - ax) / len * RING, ay + (by - ay) / len * RING];
540
+ }
541
+ function nearStart(pts) {
542
+ const [ax = 0, ay = 0] = pts[0] ?? [0, 0];
543
+ const [bx = 0, by = 0] = pts[1] ?? [0, 0];
544
+ const level = Math.abs(bx - ax) >= Math.abs(by - ay);
545
+ const dx = Math.sign(bx - ax), dy = Math.sign(by - ay);
546
+ return level ? [ax + dx * 22, ay - 9] : [ax + 16, ay + dy * 22];
547
+ }
548
+ function routeAll(edges, order, boxes) {
549
+ const col = (key) => order[key.split("#")[0] ?? ""] ?? order[key] ?? 0;
550
+ const drawn = edges.filter((e) => boxes[e.from] && boxes[e.to]).map((e) => {
551
+ const a = col(e.from), b = col(e.to);
552
+ const back = b < a;
553
+ const fromSide = e.fromSide ?? (back ? "bottom" : a === b ? "right" : "right");
554
+ const toSide = e.toSide ?? (back ? "bottom" : a === b ? "right" : "left");
555
+ return { ...e, fromSide, toSide, back, hint: { from: e.fromSide, to: e.toSide } };
556
+ });
557
+ const centre = (k) => {
558
+ const box = boxes[k];
559
+ return box && { x: box.x + box.w / 2, y: box.y + box.h / 2 };
560
+ };
561
+ const ends = /* @__PURE__ */ new Map();
562
+ const into = (key, e) => {
563
+ const list = ends.get(key);
564
+ if (list) list.push(e);
565
+ else ends.set(key, [e]);
566
+ };
567
+ const outKey = (e) => `${e.from}|out${e.hint.from ? `|${e.hint.from}` : ""}`;
568
+ const inKey = (e) => `${e.to}|in${e.hint.to ? `|${e.hint.to}` : ""}`;
569
+ for (const e of drawn) {
570
+ into(outKey(e), e);
571
+ into(inKey(e), e);
572
+ }
573
+ for (const [key, list] of ends) {
574
+ const out = key.includes("|out");
575
+ list.sort(
576
+ (a, b) => (centre(out ? a.to : a.from)?.x ?? 0) - (centre(out ? b.to : b.from)?.x ?? 0) || (centre(out ? a.to : a.from)?.y ?? 0) - (centre(out ? b.to : b.from)?.y ?? 0)
577
+ );
578
+ }
579
+ const pos = (key, e) => {
580
+ const list = ends.get(key) ?? [];
581
+ return [list.indexOf(e), list.length];
582
+ };
583
+ const rects = Object.values(boxes);
584
+ const below = drawn.filter((e) => e.hint.from === "right" && e.hint.to === "bottom");
585
+ const belowLane = /* @__PURE__ */ new Map();
586
+ for (const e of below) {
587
+ const A = boxes[e.from];
588
+ const mates = below.map((m) => boxes[m.from]).filter((r) => Boolean(r && A && Math.abs(r.x - A.x) < 1));
589
+ belowLane.set(e, mates.filter((r) => A && r.y < A.y).length);
590
+ }
591
+ return drawn.map((e) => {
592
+ const A = boxes[e.from] ?? { x: 0, y: 0, w: 0, h: 0 };
593
+ const B = boxes[e.to] ?? { x: 0, y: 0, w: 0, h: 0 };
594
+ const [i1, n1] = pos(outKey(e), e);
595
+ const [i2, n2] = pos(inKey(e), e);
596
+ const t1 = (i1 + 1) / (n1 + 1), t2 = (i2 + 1) / (n2 + 1);
597
+ const hint = e.hint;
598
+ const obstacles = rects.filter(
599
+ (r) => !inside(A, r) && !inside(B, r) && !inside(r, A) && !inside(r, B)
600
+ );
601
+ const named = Boolean(hint.from || hint.to);
602
+ const late = e.bend === "late";
603
+ const tryWith = (h) => candidates(A, B, t1, t2, { ...h, late }, obstacles, e.lane ?? i1, e.lanes ?? n1).find(
604
+ (p) => clear(p, obstacles)
605
+ );
606
+ const pts = (hint.from === "right" && hint.to === "bottom" ? viaBelow(A, B, i2, obstacles, belowLane.get(e) ?? 0) : void 0) ?? (e.strict || named ? tryWith(hint) : tryWith({})) ?? (named && hint.to ? tryWith({ from: hint.from }) : void 0) ?? (e.strict ? null : tryWith({}));
607
+ let d;
608
+ let mx;
609
+ let my;
610
+ let p1;
611
+ let pEnd;
612
+ if (pts) {
613
+ const q = pts.at(-2) ?? [0, 0];
614
+ const endPoint = pts.at(-1) ?? [0, 0];
615
+ const [qx, qy] = q;
616
+ const [ex, ey] = endPoint;
617
+ const len = Math.hypot(ex - qx, ey - qy) || 1;
618
+ const ux = (ex - qx) / len, uy = (ey - qy) / len;
619
+ const gap = e.ends === "dots" ? RING * 2 : 0;
620
+ const end = [ex - ux * (TUCK + gap), ey - uy * (TUCK + gap)];
621
+ const start = e.ends === "dots" ? outward(pts) : pts[0] ?? [0, 0];
622
+ d = roundPath([start, ...pts.slice(1, -1), end], e.ends === "dots" ? 6 : 14);
623
+ p1 = start;
624
+ pEnd = e.ends === "dots" ? [ex - ux * RING, ey - uy * RING] : endPoint;
625
+ const spots = [];
626
+ for (let i = pts.length - 1; i >= 1; i--) {
627
+ const [px = 0, py = 0] = pts[i - 1] ?? [0, 0];
628
+ const [nx = 0, ny = 0] = pts[i] ?? [0, 0];
629
+ for (const t of [0.5, 0.3, 0.7, 0.15, 0.85]) spots.push([lerp(px, nx, t), lerp(py, ny, t)]);
630
+ }
631
+ const free = ([x, y]) => rects.every(
632
+ (r) => !(x > r.x - 30 && x < r.x + r.w + 30 && y > r.y - 8 && y < r.y + r.h + 8)
633
+ );
634
+ [mx, my] = e.labelAt === "start" ? nearStart(pts) : spots.find(free) ?? spots[0] ?? [0, 0];
635
+ } else {
636
+ const p0 = port(A, e.fromSide ?? "bottom", i1, n1);
637
+ p1 = p0;
638
+ const p2 = port(B, e.toSide ?? "top", i2, n2);
639
+ pEnd = p2;
640
+ const [n1x, n1y] = NORMAL[e.fromSide ?? "bottom"];
641
+ const [n2x, n2y] = NORMAL[e.toSide ?? "top"];
642
+ const k = Math.min(140, Math.max(24, Math.hypot(p2[0] - p0[0], p2[1] - p0[1]) * 0.4));
643
+ const c1 = [p0[0] + n1x * k, p0[1] + n1y * k], c2 = [p2[0] + n2x * k, p2[1] + n2y * k];
644
+ const end = [p2[0] + n2x * TUCK, p2[1] + n2y * TUCK];
645
+ d = `M${p0[0]},${p0[1]} C${c1[0]},${c1[1]} ${c2[0]},${c2[1]} ${end[0]},${end[1]}`;
646
+ mx = 0.125 * p0[0] + 0.375 * c1[0] + 0.375 * c2[0] + 0.125 * end[0];
647
+ my = 0.125 * p0[1] + 0.375 * c1[1] + 0.375 * c2[1] + 0.125 * end[1];
648
+ }
649
+ return {
650
+ ...e,
651
+ id: `${e.from}>${e.to}>${e.label ?? ""}`,
652
+ d,
653
+ mx,
654
+ my,
655
+ p1,
656
+ p2: pEnd,
657
+ lines: e.label ? wrap(e.label, 14) : []
658
+ };
659
+ });
660
+ }
661
+
662
+ // ../diagrams/src/grid/grid-canvas.tsx
663
+ import {
664
+ Handle,
665
+ Position,
666
+ ReactFlow,
667
+ ReactFlowProvider,
668
+ useReactFlow,
669
+ useStoreApi
670
+ } from "@xyflow/react";
671
+ import {
672
+ Fragment,
673
+ createContext,
674
+ useContext,
675
+ useEffect,
676
+ useLayoutEffect,
677
+ useMemo,
678
+ useRef,
679
+ useState
680
+ } from "react";
681
+ import { Fragment as Fragment2, jsx, jsxs } from "react/jsx-runtime";
682
+ var Ctx = createContext(null);
683
+ var useGrid = () => {
684
+ const shared = useContext(Ctx);
685
+ if (!shared) throw new Error("the grid canvas parts must sit inside <Root>");
686
+ return shared;
687
+ };
688
+ var cx = (...names) => names.filter(Boolean).join(" ");
689
+ var toView = (v) => ({ s: v.zoom, x: v.x, y: v.y });
690
+ var toFlow = (v) => ({ zoom: v.s, x: v.x, y: v.y });
691
+ function measure(sheet, zoom) {
692
+ const base = sheet.getBoundingClientRect();
693
+ const at = (r) => ({
694
+ x: (r.left - base.left) / zoom,
695
+ y: (r.top - base.top) / zoom,
696
+ w: r.width / zoom,
697
+ h: r.height / zoom
698
+ });
699
+ const table = sheet.querySelector("table");
700
+ if (!table) throw new Error("the grid sheet holds no table to measure");
701
+ const [spacer, ...trs] = [...table.querySelectorAll("tr")];
702
+ const geo = {
703
+ cols: [...spacer?.children ?? []].map((td) => ({
704
+ x: table.offsetLeft + td.offsetLeft,
705
+ w: td.offsetWidth
706
+ })),
707
+ rows: trs.map((tr) => ({ y: table.offsetTop + tr.offsetTop, h: tr.offsetHeight }))
708
+ };
709
+ const boxes = {};
710
+ const cellOf = {};
711
+ const cells = [];
712
+ for (const td of table.querySelectorAll("td[data-cell]")) {
713
+ const anchors = [...td.querySelectorAll("[data-anchor]")];
714
+ if (!anchors.length) continue;
715
+ const z = anchors.some((a) => getComputedStyle(a).zIndex === "2") ? 2 : 0;
716
+ cells.push({
717
+ id: td.dataset.cell ?? "",
718
+ r: Number(td.dataset.r),
719
+ c: Number(td.dataset.c),
720
+ span: td.colSpan,
721
+ z,
722
+ ...at(td.getBoundingClientRect())
723
+ });
724
+ for (const a of anchors) {
725
+ boxes[a.dataset.anchor ?? ""] = at(a.getBoundingClientRect());
726
+ cellOf[a.dataset.anchor ?? ""] = td.dataset.cell ?? "";
727
+ }
728
+ }
729
+ return { geo, boxes, cellOf, cells, W: sheet.offsetWidth, H: sheet.offsetHeight };
730
+ }
731
+ function Rows() {
732
+ const { grid } = useGrid();
733
+ return /* @__PURE__ */ jsxs("tbody", { children: [
734
+ /* @__PURE__ */ jsx("tr", { "data-slot": "grid-spacer", className: "gd-spacer", children: grid.columns.map((c) => /* @__PURE__ */ jsx("td", {}, c.key)) }),
735
+ grid.rows.map((r, ri) => /* @__PURE__ */ jsx("tr", { className: `gd-${r.kind}`, children: grid.columns.map((c, ci) => {
736
+ const cell = grid.cell(r, c, ci);
737
+ if (!cell) return null;
738
+ return /* @__PURE__ */ jsx(
739
+ "td",
740
+ {
741
+ colSpan: cell.span ?? 1,
742
+ "data-cell": `${r.key}|${c.key}`,
743
+ "data-r": ri,
744
+ "data-c": ci,
745
+ children: cell.content
746
+ },
747
+ c.key
748
+ );
749
+ }) }, r.key))
750
+ ] });
751
+ }
752
+ function Backdrop() {
753
+ const { setM, m } = useGrid();
754
+ const sheet = useRef(null);
755
+ const store = useStoreApi();
756
+ useLayoutEffect(() => {
757
+ const again = () => {
758
+ if (!sheet.current) return;
759
+ const next = measure(sheet.current, store.getState().transform[2] || 1);
760
+ setM((prev) => prev && JSON.stringify(prev) === JSON.stringify(next) ? prev : next);
761
+ };
762
+ again();
763
+ const ro = new ResizeObserver(again);
764
+ if (sheet.current) ro.observe(sheet.current);
765
+ document.fonts?.ready.then(again);
766
+ return () => ro.disconnect();
767
+ }, [setM, store]);
768
+ return /* @__PURE__ */ jsxs("div", { "data-slot": "grid-backdrop", className: "gd-sheet", ref: sheet, children: [
769
+ /* @__PURE__ */ jsx("table", { className: "gd-table", children: /* @__PURE__ */ jsx(Rows, {}) }),
770
+ m?.geo.cols.slice(0, -1).map((c, i) => {
771
+ const rows = m.geo.rows;
772
+ const first = rows[0];
773
+ const last = rows[rows.length - 1];
774
+ const top = first?.y ?? 0;
775
+ const end = last ? last.y + last.h : 0;
776
+ return /* @__PURE__ */ jsx(
777
+ "i",
778
+ {
779
+ "data-slot": "grid-slice",
780
+ className: "gd-slice",
781
+ style: { left: c.x + c.w, top, height: end - top }
782
+ },
783
+ `${c.x}-${c.w}`
784
+ );
785
+ })
786
+ ] });
787
+ }
788
+ function CellNode({ data }) {
789
+ const { grid } = useGrid();
790
+ const r = grid.rows[data.r];
791
+ const c = grid.columns[data.c];
792
+ if (!r || !c) return null;
793
+ return /* @__PURE__ */ jsxs(Fragment2, { children: [
794
+ /* @__PURE__ */ jsx(Handle, { type: "target", position: Position.Left, isConnectable: false, className: "gd-handle" }),
795
+ /* @__PURE__ */ jsx(
796
+ "table",
797
+ {
798
+ "data-slot": "grid-cell",
799
+ className: "gd-table",
800
+ style: { width: data.w, height: data.h, tableLayout: "fixed" },
801
+ children: /* @__PURE__ */ jsx("tbody", { children: /* @__PURE__ */ jsx("tr", { className: `gd-${r.kind}`, children: /* @__PURE__ */ jsx("td", { children: grid.cell(r, c, data.c)?.content }) }) })
802
+ }
803
+ ),
804
+ /* @__PURE__ */ jsx(Handle, { type: "source", position: Position.Right, isConnectable: false, className: "gd-handle" })
805
+ ] });
806
+ }
807
+ var touchesOf = (mark) => (k) => !!mark && (k === mark || k.startsWith(`${mark}#`));
808
+ function ArrowLabel({ e }) {
809
+ if (!e.lines.length) return null;
810
+ return /* @__PURE__ */ jsx("g", { transform: `translate(${e.mx},${e.my})`, children: e.lines.map((l, j) => {
811
+ const [, n, word] = /^(\d+\.\d+) (.*)$/.exec(l) ?? [];
812
+ return /* @__PURE__ */ jsx("text", { y: (j - (e.lines.length - 1) / 2) * 14 + 4, textAnchor: "middle", children: n ? /* @__PURE__ */ jsxs(Fragment2, { children: [
813
+ /* @__PURE__ */ jsx("tspan", { className: "gd-label-n", children: n }),
814
+ " ",
815
+ word
816
+ ] }) : l }, l);
817
+ }) });
818
+ }
819
+ function ArrowEdge({ data: e }) {
820
+ const { picked } = useGrid();
821
+ if (!e) return null;
822
+ const touches = touchesOf(picked?.anchor);
823
+ const on = touches(e.from) || touches(e.to);
824
+ const state = on ? "on" : picked ? "dim" : "";
825
+ return /* @__PURE__ */ jsxs(
826
+ "g",
827
+ {
828
+ "data-tone": e.tone,
829
+ "data-from": e.from.split("#")[0],
830
+ "data-to": e.to.split("#")[0],
831
+ className: cx("gd-arrow", state),
832
+ children: [
833
+ /* @__PURE__ */ jsx("path", { className: "gd-under", d: e.d }),
834
+ /* @__PURE__ */ jsx("path", { className: "gd-hit", d: e.d }),
835
+ /* @__PURE__ */ jsx("path", { d: e.d, markerEnd: `url(#gd-${on ? "on" : "off"})` }),
836
+ /* @__PURE__ */ jsx("circle", { className: "gd-out", cx: e.p1[0], cy: e.p1[1], r: 3 }),
837
+ /* @__PURE__ */ jsx("circle", { className: "gd-in", cx: e.p2[0], cy: e.p2[1], r: 3 }),
838
+ /* @__PURE__ */ jsx(ArrowLabel, { e })
839
+ ]
840
+ }
841
+ );
842
+ }
843
+ var nodeTypes = { backdrop: Backdrop, cell: CellNode };
844
+ var edgeTypes = { arrow: ArrowEdge };
845
+ function litOf(routed, mark) {
846
+ const touches = touchesOf(mark);
847
+ const lit = new Set(mark ? [mark] : []);
848
+ for (const e of routed)
849
+ if (touches(e.from) || touches(e.to))
850
+ for (const k of [e.from, e.to]) {
851
+ lit.add(k);
852
+ lit.add(k.split("#")[0] ?? "");
853
+ }
854
+ return lit;
855
+ }
856
+ function markStyleOf(mark, lit) {
857
+ if (!mark) return null;
858
+ const q = JSON.stringify;
859
+ const bright = [...lit].map((k) => `.gd.picking .react-flow__node-cell [data-anchor=${q(k)}]`);
860
+ return `.gd [data-anchor=${q(mark)}] { outline: 3px solid var(--ws-st); outline-offset: 3px; --gd-picked: 1; } ${bright.join(", ")} { opacity: 1; }`;
861
+ }
862
+ function hoverStyleOf(hover) {
863
+ if (!hover) return null;
864
+ const q = JSON.stringify(hover);
865
+ return `.gd .gd-arrow:is([data-from=${q}], [data-to=${q}]) { --gd-hover: 1; }`;
866
+ }
867
+ function anchorAt(target) {
868
+ const el = target?.closest("[data-anchor]");
869
+ return el?.dataset.anchor?.split("#")[0] ?? null;
870
+ }
871
+ function nodesOf(m) {
872
+ const fixed = { draggable: false, selectable: false };
873
+ const back = {
874
+ id: "backdrop",
875
+ type: "backdrop",
876
+ position: { x: 0, y: 0 },
877
+ data: {},
878
+ zIndex: -1,
879
+ ...fixed
880
+ };
881
+ if (!m) return [back];
882
+ const cells = m.cells.map(
883
+ (c) => ({
884
+ id: c.id,
885
+ type: "cell",
886
+ position: { x: c.x, y: c.y },
887
+ data: { ...c },
888
+ zIndex: c.z,
889
+ ...fixed
890
+ })
891
+ );
892
+ return [back, ...cells];
893
+ }
894
+ var edgesOf = (routed, m) => m ? routed.map((e) => ({
895
+ id: e.id,
896
+ source: m.cellOf[e.from] ?? "",
897
+ target: m.cellOf[e.to] ?? "",
898
+ type: "arrow",
899
+ data: e,
900
+ zIndex: 1,
901
+ selectable: false,
902
+ focusable: false
903
+ })) : [];
904
+ function usePaintAxes(store, root) {
905
+ useEffect(() => {
906
+ const paint = () => {
907
+ const [x, y, s] = store.getState().transform;
908
+ const axes = root.current?.querySelectorAll(
909
+ "[data-slot=grid-x-axis], [data-slot=grid-y-axis]"
910
+ ) ?? [];
911
+ for (const el of axes) {
912
+ el.style.setProperty("--x", `${x}px`);
913
+ el.style.setProperty("--y", `${y}px`);
914
+ el.style.setProperty("--s", String(s));
915
+ }
916
+ const pct = root.current?.querySelector("[data-slot=grid-zoom-level]");
917
+ if (pct) pct.textContent = `${Math.round(s * 100)}%`;
918
+ };
919
+ paint();
920
+ return store.subscribe(paint);
921
+ }, [store, root]);
922
+ }
923
+ function wheelPan(e, v) {
924
+ const unit = e.deltaMode === 1 ? 32 : 1;
925
+ const shift = e.shiftKey && !e.deltaX;
926
+ const dx = shift ? e.deltaY : e.deltaX;
927
+ const dy = shift ? 0 : e.deltaY;
928
+ return { ...v, x: v.x - dx * unit, y: v.y - dy * unit };
929
+ }
930
+ function useWheel(root, pane, m, cam) {
931
+ useEffect(() => {
932
+ const el = root.current;
933
+ const target = pane.current;
934
+ if (!el || !target) return;
935
+ const onWheel = (e) => {
936
+ const zoom = e.ctrlKey || e.metaKey;
937
+ const sideways = e.shiftKey && !e.deltaX;
938
+ if (target.contains(e.target) && !zoom && !sideways) return;
939
+ e.preventDefault();
940
+ e.stopPropagation();
941
+ const r = target.getBoundingClientRect();
942
+ if (zoom) cam.zoomAt(Math.exp(-e.deltaY * 0.01), e.clientX - r.left, e.clientY - r.top);
943
+ else cam.go(wheelPan(e, cam.view()));
944
+ };
945
+ el.addEventListener("wheel", onWheel, { capture: true, passive: false });
946
+ return () => el.removeEventListener("wheel", onWheel, { capture: true });
947
+ }, [m]);
948
+ }
949
+ function useFloor(m, pane, cam, setFloor) {
950
+ useLayoutEffect(() => {
951
+ if (!m) return;
952
+ const target = pane.current;
953
+ if (!target) return;
954
+ const again = () => {
955
+ const f = cam.smallest();
956
+ cam.floorRef.current = f;
957
+ setFloor(f);
958
+ const v = cam.view();
959
+ const k = cam.keep(v);
960
+ if (Math.abs(k.x - v.x) + Math.abs(k.y - v.y) + Math.abs(k.s - v.s) > 0.01) cam.go(k);
961
+ };
962
+ again();
963
+ const ro = new ResizeObserver(again);
964
+ ro.observe(target);
965
+ return () => ro.disconnect();
966
+ }, [m]);
967
+ }
968
+ function useCamera(root, pane, m, floorRef) {
969
+ const rf = useReactFlow();
970
+ const size = () => ({
971
+ w: pane.current?.clientWidth ?? 1,
972
+ h: pane.current?.clientHeight ?? 1,
973
+ W: m?.W ?? 1,
974
+ H: m?.H ?? 1
975
+ });
976
+ const pills = () => [
977
+ ...root.current?.querySelectorAll("[data-slot=grid-x-cell] .gd-pill") ?? []
978
+ ];
979
+ const smallest = () => floorOf(size(), pills(), m?.geo.cols ?? []);
980
+ const keep2 = (v) => keep(size(), floorRef.current, v);
981
+ const go = (v, options) => void rf.setViewport(toFlow(keep2(v)), options);
982
+ const view = () => toView(rf.getViewport());
983
+ const zoomAt2 = (f, px, py) => go(zoomAt(view(), f, px, py, floorRef.current));
984
+ return { size, smallest, keep: keep2, go, view, zoomAt: zoomAt2, floorRef };
985
+ }
986
+ function useGlide(mark, m, routed, cam) {
987
+ useEffect(() => {
988
+ if (!mark || !m?.boxes[mark]) return;
989
+ const touches = touchesOf(mark);
990
+ const leads = routed.filter((e) => touches(e.from)).map((e) => e.to);
991
+ const group = [mark, ...leads].map((k) => m.boxes[k]).filter((b) => Boolean(b));
992
+ cam.go(
993
+ frame(m.boxes[mark] ?? { x: 0, y: 0, w: 0, h: 0 }, group, cam.size(), cam.floorRef.current),
994
+ {
995
+ duration: GLIDE_MS,
996
+ ease: easeOut,
997
+ interpolate: "linear"
998
+ }
999
+ );
1000
+ }, [mark, m]);
1001
+ }
1002
+ function ArrowHeads() {
1003
+ return /* @__PURE__ */ jsx("svg", { width: "0", height: "0", style: { position: "absolute" }, "aria-hidden": "true", children: /* @__PURE__ */ jsx("defs", { children: ["off", "on"].map((t) => /* @__PURE__ */ jsx(
1004
+ "marker",
1005
+ {
1006
+ id: `gd-${t}`,
1007
+ viewBox: "0 0 10 10",
1008
+ refX: 10 - TUCK * 10 / HEAD,
1009
+ refY: "5",
1010
+ markerWidth: HEAD,
1011
+ markerHeight: HEAD,
1012
+ markerUnits: "userSpaceOnUse",
1013
+ orient: "auto",
1014
+ children: /* @__PURE__ */ jsx("path", { d: "M0,1 L10,5 L0,9 z", className: `gd-head ${t}` })
1015
+ },
1016
+ t
1017
+ )) }) });
1018
+ }
1019
+ function pickFrom(e, mark, onPick) {
1020
+ const el = e.target?.closest("[data-station]");
1021
+ if (!el) return;
1022
+ const anchor = el.dataset.anchor ?? el.dataset.station ?? "";
1023
+ onPick(anchor === mark ? null : { anchor, station: el.dataset.station ?? "" });
1024
+ }
1025
+ function useGridState(grid, picked, root) {
1026
+ const store = useStoreApi();
1027
+ const pane = useRef(null);
1028
+ const [m, setM] = useState(null);
1029
+ const [floor, setFloor] = useState(0.15);
1030
+ const floorRef = useRef(floor);
1031
+ floorRef.current = floor;
1032
+ const mark = picked?.anchor ?? null;
1033
+ const routed = useMemo(() => m ? routeAll(grid.edges, grid.order, m.boxes) : [], [grid, m]);
1034
+ const cam = useCamera(root, pane, m, floorRef);
1035
+ usePaintAxes(store, root);
1036
+ useFloor(m, pane, cam, setFloor);
1037
+ useWheel(root, pane, m, cam);
1038
+ useGlide(mark, m, routed, cam);
1039
+ const nodes = useMemo(() => nodesOf(m), [m]);
1040
+ const edges = useMemo(() => edgesOf(routed, m), [routed, m]);
1041
+ const { zoomAt: zoomAt2, size, go, smallest } = cam;
1042
+ return {
1043
+ shared: { grid, picked, m, setM, pane, nodes, edges, floor, zoomAt: zoomAt2, size, go, smallest },
1044
+ markStyle: markStyleOf(mark, litOf(routed, mark))
1045
+ };
1046
+ }
1047
+ function RootInner({
1048
+ grid,
1049
+ picked = null,
1050
+ onPick = () => {
1051
+ },
1052
+ className,
1053
+ children,
1054
+ ...props
1055
+ }) {
1056
+ const root = useRef(null);
1057
+ const { shared, markStyle } = useGridState(grid, picked, root);
1058
+ const mark = picked?.anchor ?? null;
1059
+ const [hover, setHover] = useState(null);
1060
+ const hoverStyle = hoverStyleOf(hover);
1061
+ return /* @__PURE__ */ jsx(Ctx.Provider, { value: shared, children: /* @__PURE__ */ jsxs(
1062
+ "div",
1063
+ {
1064
+ "data-slot": "grid",
1065
+ className: cx("gd", mark && "picking", className),
1066
+ ref: root,
1067
+ onClickCapture: (e) => pickFrom(e, mark, onPick),
1068
+ onPointerOver: (e) => setHover(anchorAt(e.target)),
1069
+ onPointerLeave: () => setHover(null),
1070
+ ...props,
1071
+ children: [
1072
+ markStyle && /* @__PURE__ */ jsx("style", { children: markStyle }),
1073
+ hoverStyle && /* @__PURE__ */ jsx("style", { children: hoverStyle }),
1074
+ /* @__PURE__ */ jsx(ArrowHeads, {}),
1075
+ children
1076
+ ]
1077
+ }
1078
+ ) });
1079
+ }
1080
+ function Root(props) {
1081
+ return /* @__PURE__ */ jsx(ReactFlowProvider, { children: /* @__PURE__ */ jsx(RootInner, { ...props }) });
1082
+ }
1083
+ var along = (g, at) => !g ? { display: "none" } : at === "left" ? {
1084
+ left: `calc(var(--x) + ${g.x ?? 0}px * var(--s))`,
1085
+ width: `calc(${g.w ?? 0}px * var(--s))`
1086
+ } : {
1087
+ top: `calc(var(--y) + ${g.y ?? 0}px * var(--s))`,
1088
+ height: `calc(${g.h ?? 0}px * var(--s))`
1089
+ };
1090
+ function Axes({
1091
+ corner = ["Step \u2192", "Lane \u2193"],
1092
+ renderColumn: renderColumn2 = (_c, header) => header
1093
+ }) {
1094
+ const { grid, m, picked } = useGrid();
1095
+ return /* @__PURE__ */ jsxs(Fragment2, { children: [
1096
+ /* @__PURE__ */ jsxs("div", { "data-slot": "grid-corner", className: "gd-corner", children: [
1097
+ /* @__PURE__ */ jsx("span", { children: corner[0] }),
1098
+ /* @__PURE__ */ jsx("span", { children: corner[1] })
1099
+ ] }),
1100
+ /* @__PURE__ */ jsx("div", { "data-slot": "grid-x-axis", className: "gd-x", children: /* @__PURE__ */ jsx("div", { className: "gd-x-track", children: grid.columns.map((c, i) => /* @__PURE__ */ jsx(
1101
+ "div",
1102
+ {
1103
+ "data-slot": "grid-x-cell",
1104
+ className: "gd-col",
1105
+ style: along(m?.geo.cols[i], "left"),
1106
+ children: renderColumn2(
1107
+ c,
1108
+ /* @__PURE__ */ jsxs(
1109
+ "button",
1110
+ {
1111
+ type: "button",
1112
+ "data-station": c.key,
1113
+ className: cx("gd-pill", picked?.station === c.key && "on"),
1114
+ children: [
1115
+ /* @__PURE__ */ jsx("span", { className: "n", children: c.number }),
1116
+ /* @__PURE__ */ jsx("span", { className: "nm", children: c.label })
1117
+ ]
1118
+ }
1119
+ )
1120
+ )
1121
+ },
1122
+ c.key
1123
+ )) }) }),
1124
+ /* @__PURE__ */ jsx("div", { "data-slot": "grid-y-axis", className: "gd-y", children: grid.rows.map((r, i) => /* @__PURE__ */ jsx(
1125
+ "div",
1126
+ {
1127
+ "data-slot": "grid-y-cell",
1128
+ className: cx("gd-row", `gd-${r.kind}`),
1129
+ style: along(m?.geo.rows[i], "top"),
1130
+ children: /* @__PURE__ */ jsxs("span", { className: "gd-row-label", children: [
1131
+ /* @__PURE__ */ jsx("b", { children: r.label }),
1132
+ r.sub && /* @__PURE__ */ jsx("small", { children: r.sub })
1133
+ ] })
1134
+ },
1135
+ r.key
1136
+ )) })
1137
+ ] });
1138
+ }
1139
+ function Viewport({ className, ...props }) {
1140
+ const { pane, nodes, edges, floor, m } = useGrid();
1141
+ return /* @__PURE__ */ jsx("div", { "data-slot": "grid-viewport", className: cx("gd-viewport", className), ref: pane, ...props, children: /* @__PURE__ */ jsx(
1142
+ ReactFlow,
1143
+ {
1144
+ nodes,
1145
+ edges,
1146
+ nodeTypes,
1147
+ edgeTypes,
1148
+ defaultViewport: { x: 0, y: 0, zoom: 1 },
1149
+ minZoom: floor,
1150
+ maxZoom: MAX,
1151
+ translateExtent: m ? [
1152
+ [0, 0],
1153
+ [m.W, m.H]
1154
+ ] : void 0,
1155
+ panOnScroll: true,
1156
+ panOnScrollSpeed: 1,
1157
+ zoomOnScroll: false,
1158
+ zoomOnDoubleClick: false,
1159
+ zoomActivationKeyCode: null,
1160
+ nodesDraggable: false,
1161
+ nodesConnectable: false,
1162
+ nodesFocusable: false,
1163
+ edgesFocusable: false,
1164
+ elementsSelectable: false,
1165
+ paneClickDistance: 4,
1166
+ proOptions: { hideAttribution: true }
1167
+ }
1168
+ ) });
1169
+ }
1170
+ var PlainButton = ({ variant: _v, mode: _m, size: _s, ...props }) => /* @__PURE__ */ jsx("button", { type: "button", className: "gd-zoom-button", ...props });
1171
+ function Zoom({ className, Button: Button2 = PlainButton, ...props }) {
1172
+ const { zoomAt: zoomAt2, size, go, smallest } = useGrid();
1173
+ const at = (f) => () => zoomAt2(f, size().w / 2, size().h / 2);
1174
+ const ghost = { variant: "neutral", mode: "ghost", size: "xs" };
1175
+ return /* @__PURE__ */ jsxs("div", { "data-slot": "grid-zoom", className: cx("gd-zoom", className), ...props, children: [
1176
+ /* @__PURE__ */ jsx(Button2, { ...ghost, "aria-label": "Zoom out", onClick: at(0.8), children: "\u2212" }),
1177
+ /* @__PURE__ */ jsx(Button2, { ...ghost, "aria-label": "Zoom to 100%", onClick: () => go({ s: 1, x: 0, y: 0 }), children: /* @__PURE__ */ jsx("span", { "data-slot": "grid-zoom-level", className: "type-meta tabular-nums", children: "100%" }) }),
1178
+ /* @__PURE__ */ jsx(Button2, { ...ghost, "aria-label": "Zoom in", onClick: at(1.25), children: "+" }),
1179
+ /* @__PURE__ */ jsx(Button2, { ...ghost, onClick: () => go({ s: smallest(), x: 0, y: 0 }), children: "Fit" })
1180
+ ] });
1181
+ }
1182
+ var boxProps = (box, columnId) => ({
1183
+ "data-anchor": box.id,
1184
+ "data-station": columnId,
1185
+ "data-kind": box.kind
1186
+ });
1187
+ function Box({ box, columnId }) {
1188
+ return /* @__PURE__ */ jsxs("button", { type: "button", className: "gd-box", "aria-label": box.title, ...boxProps(box, columnId), children: [
1189
+ box.label && /* @__PURE__ */ jsx("small", { children: box.label }),
1190
+ /* @__PURE__ */ jsx("b", { children: box.title })
1191
+ ] });
1192
+ }
1193
+ function gridFrom(layout, renderBox) {
1194
+ const draw = renderBox ?? ((box, columnId) => /* @__PURE__ */ jsx(Box, { box, columnId }, box.id));
1195
+ return {
1196
+ columns: layout.columns.map((c) => ({ ...c, key: c.id })),
1197
+ rows: layout.rows.map((r) => ({ ...r, key: r.id })),
1198
+ cell: (r, _c, ci) => {
1199
+ const cell = layout.cellAt(r, ci);
1200
+ if (!cell) return null;
1201
+ const column = layout.columns[ci];
1202
+ if (!column) return null;
1203
+ const boxes = cell.boxes.map((b) => /* @__PURE__ */ jsx(Fragment, { children: draw(b, column.id) }, b.id));
1204
+ return {
1205
+ span: cell.span,
1206
+ content: boxes.length ? /* @__PURE__ */ jsx("div", { className: "gd-stack", children: boxes }) : null
1207
+ };
1208
+ },
1209
+ order: layout.order,
1210
+ edges: layout.edges
1211
+ };
1212
+ }
1213
+ function GridCanvas({
1214
+ input,
1215
+ picked = null,
1216
+ onPick = () => {
1217
+ },
1218
+ renderBox,
1219
+ renderColumn: renderColumn2,
1220
+ Button: Button2,
1221
+ className,
1222
+ ...props
1223
+ }) {
1224
+ const layout = useMemo(() => layoutOf(input), [input]);
1225
+ const grid = useMemo(() => gridFrom(layout, renderBox), [layout, renderBox]);
1226
+ return /* @__PURE__ */ jsxs(Root, { grid, picked, onPick, className, ...props, children: [
1227
+ /* @__PURE__ */ jsx(Axes, { corner: layout.corner, renderColumn: renderColumn2 }),
1228
+ /* @__PURE__ */ jsx(Viewport, {}),
1229
+ /* @__PURE__ */ jsx(Zoom, { Button: Button2 })
1230
+ ] });
1231
+ }
1232
+ function Flow({ grid, view = "full", ...props }) {
1233
+ const input = useMemo(
1234
+ () => view === "uj" ? foldScenarioToUserJourney(grid) : grid,
1235
+ [grid, view]
1236
+ );
1237
+ return /* @__PURE__ */ jsx(GridCanvas, { input, ...props }, view);
1238
+ }
1239
+
1240
+ // ../diagrams/src/grid/capability.ts
1241
+ var SCREEN = "scr";
1242
+ var PERSONA = "actor";
1243
+ var INBOX2 = "inbox";
1244
+ var SUMMED = /* @__PURE__ */ new Set(["auto", "call", "ext", "tr"]);
1245
+ function screenKey(flow, box) {
1246
+ const d = flow.details?.[box.id];
1247
+ return d?.rows?.find((r) => r.label === "Screen")?.value ?? box.title;
1248
+ }
1249
+ function screenColumns(flow) {
1250
+ const cols = flow.columns ?? [];
1251
+ const at = /* @__PURE__ */ new Map();
1252
+ for (const b of (flow.boxes ?? []).filter((x) => x.kind === SCREEN)) {
1253
+ const i = cols.findIndex((c) => c.id === b.column);
1254
+ for (const c of cols.slice(i, i + (b.span ?? 1))) at.set(c.id, screenKey(flow, b));
1255
+ }
1256
+ return at;
1257
+ }
1258
+ function screenAtStep2(flow) {
1259
+ const cols = flow.columns ?? [];
1260
+ const at = screenColumns(flow);
1261
+ let last = cols.map((c) => at.get(c.id)).find(Boolean);
1262
+ for (const c of cols) {
1263
+ last = at.get(c.id) ?? last;
1264
+ if (last) at.set(c.id, last);
1265
+ }
1266
+ return at;
1267
+ }
1268
+ function screensInOrder(flows) {
1269
+ const rank = /* @__PURE__ */ new Map();
1270
+ for (const f of flows) {
1271
+ (f.boxes ?? []).filter((b) => b.kind === SCREEN).forEach((b, i) => {
1272
+ const k = screenKey(f, b);
1273
+ const was = rank.get(k);
1274
+ if (!was || i < was.at) rank.set(k, { at: i, title: was?.title ?? b.title });
1275
+ });
1276
+ }
1277
+ return [...rank.entries()].sort((a, b) => a[1].at - b[1].at).map(([key, v]) => ({ key, title: v.title }));
1278
+ }
1279
+ function mergedPlace(f, b, step, colOf) {
1280
+ const screen = b.kind === SCREEN ? screenKey(f, b) : step.get(b.column);
1281
+ const column = colOf.get(screen ?? "") ?? "c0";
1282
+ return {
1283
+ id: b.kind === SCREEN ? `scr:${screen}` : `${b.kind}:${column}:${b.row}:${b.title}`,
1284
+ column
1285
+ };
1286
+ }
1287
+ function addBox(into, b, place, d) {
1288
+ if (into.boxes.has(place.id)) return;
1289
+ const { span: _, ...rest } = b;
1290
+ into.boxes.set(place.id, { ...rest, ...place });
1291
+ if (d !== void 0) into.details[place.id] = d;
1292
+ }
1293
+ function mergeBoxes(f, colOf, into) {
1294
+ const step = screenAtStep2(f);
1295
+ const idOf = /* @__PURE__ */ new Map();
1296
+ for (const b of f.boxes ?? []) {
1297
+ const place = mergedPlace(f, b, step, colOf);
1298
+ idOf.set(b.id, place.id);
1299
+ addBox(into, b, place, f.details?.[b.id]);
1300
+ }
1301
+ return idOf;
1302
+ }
1303
+ function addArrow(into, a, from = "", to = "") {
1304
+ const key = `${from}>${to}>${a.label}`;
1305
+ if (from && to && from !== to && !into.arrows.has(key)) into.arrows.set(key, { ...a, from, to });
1306
+ }
1307
+ function mergeOne(f, colOf, into) {
1308
+ const idOf = mergeBoxes(f, colOf, into);
1309
+ for (const a of f.arrows ?? []) addArrow(into, a, idOf.get(a.from), idOf.get(a.to));
1310
+ }
1311
+ function mergeScenarioGrids(flows) {
1312
+ const screens = screensInOrder(flows);
1313
+ const colOf = new Map(screens.map((s, i) => [s.key, `c${i}`]));
1314
+ const columns = screens.map((s, i) => ({
1315
+ id: `c${i}`,
1316
+ number: String(i + 1),
1317
+ label: s.title
1318
+ }));
1319
+ const rows = [];
1320
+ for (const r of flows.flatMap((f) => f.rows ?? []))
1321
+ if (!rows.some((x) => x.id === r.id)) rows.push(r);
1322
+ const merged = { boxes: /* @__PURE__ */ new Map(), arrows: /* @__PURE__ */ new Map(), details: {} };
1323
+ for (const f of flows) mergeOne(f, colOf, merged);
1324
+ return {
1325
+ ...flows[0] ?? { kind: "grid", input: 1 },
1326
+ corner: ["Screen \u2192", "Lane \u2193"],
1327
+ columns,
1328
+ rows,
1329
+ boxes: [...merged.boxes.values()],
1330
+ arrows: [...merged.arrows.values()],
1331
+ details: merged.details
1332
+ };
1333
+ }
1334
+ function waysOut(s, arrows, byId) {
1335
+ const ways = [];
1336
+ for (const a of arrows) {
1337
+ const to = byId.get(a.to);
1338
+ if (a.from !== s.id || to?.kind !== SCREEN || to.id === s.id) continue;
1339
+ const label = a.label ?? "Next";
1340
+ if (!ways.some((w) => w.label === label && w.to.id === to.id)) ways.push({ label, to });
1341
+ }
1342
+ return ways;
1343
+ }
1344
+ function checksOf(s, ways, out) {
1345
+ let at = s.id;
1346
+ ways.forEach((w, i) => {
1347
+ const id = `chk:${s.id}:${i}`;
1348
+ const title = `${w.label}?`;
1349
+ out.boxes.push({ id, row: "decision", column: s.column, kind: "chk", title });
1350
+ out.details[id] = {
1351
+ kind: "Check",
1352
+ title,
1353
+ rows: [
1354
+ { label: "Asked after", value: s.title },
1355
+ { label: "Yes leads to", value: w.to.title }
1356
+ ],
1357
+ steps: []
1358
+ };
1359
+ const no = at === s.id ? {} : { label: "No", labelAt: "start", numbered: "from" };
1360
+ out.arrows.push({
1361
+ from: at,
1362
+ to: id,
1363
+ tone: at === s.id ? "journey" : "no",
1364
+ fromSide: "bottom",
1365
+ toSide: "top",
1366
+ ends: "dots",
1367
+ ...no
1368
+ });
1369
+ const up = w.to.column !== s.column ? { toSide: "bottom" } : {};
1370
+ out.arrows.push({
1371
+ from: id,
1372
+ to: w.to.id,
1373
+ tone: "yes",
1374
+ label: "Yes",
1375
+ labelAt: "start",
1376
+ numbered: "from",
1377
+ fromSide: "right",
1378
+ ends: "dots",
1379
+ ...up
1380
+ });
1381
+ at = id;
1382
+ });
1383
+ }
1384
+ function backendOf(c, all, kept) {
1385
+ const work = all.filter((b) => b.column === c.id && SUMMED.has(b.kind ?? ""));
1386
+ const names = [...new Set(work.map((b) => b.title))];
1387
+ if (!names.length) return null;
1388
+ const title = names.length > 1 ? `${names[0]} +${names.length - 1} more` : names[0] ?? "";
1389
+ const box = { id: `be:${c.id}`, row: "backend", column: c.id, kind: "auto", title };
1390
+ const panel = {
1391
+ kind: "Backend",
1392
+ title: c.label ?? c.id,
1393
+ rows: all.filter((b) => b.column === c.id && !kept.has(b.row)).map((b) => ({ label: b.kind ?? "box", value: b.title })),
1394
+ steps: []
1395
+ };
1396
+ return { box, panel };
1397
+ }
1398
+ function foldCapabilityToUserJourney(full) {
1399
+ const all = full.boxes ?? [];
1400
+ const persona = (full.rows ?? []).filter((r) => r.kind === PERSONA);
1401
+ const inboxes = (full.rows ?? []).filter((r) => r.kind === INBOX2);
1402
+ const rows = [
1403
+ ...persona,
1404
+ { id: "decision", kind: "mid", label: "Decision", sub: "routes to a screen" },
1405
+ ...inboxes,
1406
+ { id: "backend", kind: "auto", label: "Backend", sub: "system work" }
1407
+ ];
1408
+ const kept = new Set([...persona, ...inboxes].map((r) => r.id));
1409
+ const out = {
1410
+ boxes: all.filter((b) => kept.has(b.row)),
1411
+ arrows: [],
1412
+ details: { ...full.details }
1413
+ };
1414
+ const byId = new Map(all.map((b) => [b.id, b]));
1415
+ for (const s of all.filter((b) => b.kind === SCREEN))
1416
+ checksOf(s, waysOut(s, full.arrows ?? [], byId), out);
1417
+ for (const c of full.columns ?? []) {
1418
+ const be = backendOf(c, all, kept);
1419
+ if (!be) continue;
1420
+ out.boxes.push(be.box);
1421
+ out.details[be.box.id] = be.panel;
1422
+ }
1423
+ return { ...full, corner: ["Screen \u2192", "Lane \u2193"], rows, ...out };
1424
+ }
1425
+
1426
+ // src/user-journey.ts
1427
+ var CHANNEL = { sms: "SMS", email: "Email" };
1428
+ function screenProblems(screens, out) {
1429
+ const ids2 = /* @__PURE__ */ new Set();
1430
+ for (const s of screens) {
1431
+ if (!s.id || !s.title) out.push("a screen needs an id and a title");
1432
+ if (ids2.has(s.id)) out.push(`screen ${s.id}: id given twice`);
1433
+ ids2.add(s.id);
1434
+ }
1435
+ if (!ids2.size) out.push("a user journey needs at least one screen");
1436
+ return ids2;
1437
+ }
1438
+ function decisionProblems(decisions, known) {
1439
+ for (const d of decisions) {
1440
+ known("decision", d.after);
1441
+ for (const w of d.ways ?? []) known(`decision after ${d.after}, way "${w.when}"`, w.to);
1442
+ }
1443
+ }
1444
+ function messageProblems(messages, known, out) {
1445
+ for (const m of messages) {
1446
+ known(`message ${m.id}`, m.after);
1447
+ if (!(m.channel in CHANNEL)) out.push(`message ${m.id}: channel must be sms or email`);
1448
+ }
1449
+ }
1450
+ function referenceProblems(j, ids2, out) {
1451
+ const known = (where, id) => {
1452
+ if (!ids2.has(id)) out.push(`${where}: no screen ${id}`);
1453
+ };
1454
+ decisionProblems(j.decisions ?? [], known);
1455
+ messageProblems(j.messages ?? [], known, out);
1456
+ for (const w of j.backend ?? []) known(`backend "${w.title}"`, w.under);
1457
+ }
1458
+ function validateUserJourney(json) {
1459
+ const j = json;
1460
+ if (!j || typeof j !== "object") return ["not a user journey: expected a JSON object"];
1461
+ if (j.kind !== "journey" || j.input !== 1)
1462
+ return ['not a user journey: kind must be "journey" and input 1'];
1463
+ const out = [];
1464
+ referenceProblems(j, screenProblems(j.screens ?? [], out), out);
1465
+ return out;
1466
+ }
1467
+ function validateScenarioUserJourney(json) {
1468
+ const out = validateUserJourney(json);
1469
+ if (out.length) return out;
1470
+ const ways = /* @__PURE__ */ new Map();
1471
+ for (const d of json.decisions ?? [])
1472
+ ways.set(d.after, (ways.get(d.after) ?? 0) + (d.ways?.length ?? 0));
1473
+ for (const [screen, n] of ways)
1474
+ if (n > 1) out.push(`screen ${screen}: ${n} ways out; a scenario diagram follows one path`);
1475
+ return out;
1476
+ }
1477
+ var PERSONA2 = "persona";
1478
+ function screenBox(s, col) {
1479
+ const chips = [
1480
+ ...(s.errors ?? []).map((text) => ({ text, tone: "err" })),
1481
+ ...(s.states ?? []).map((text) => ({ text, tone: "state" }))
1482
+ ];
1483
+ const detail = {
1484
+ kind: "Screen",
1485
+ title: s.title,
1486
+ rows: [{ label: "Screen", value: s.id }],
1487
+ steps: [],
1488
+ ...chips.length ? { chips } : {},
1489
+ ...s.render === void 0 ? {} : { render: s.render }
1490
+ };
1491
+ return [{ id: `scr:${s.id}`, row: PERSONA2, column: col, kind: "scr", title: s.title }, detail];
1492
+ }
1493
+ function userJourneyToGrid(j) {
1494
+ const col = new Map(j.screens.map((s, i) => [s.id, `c${i}`]));
1495
+ const at = (id) => col.get(id) ?? "c0";
1496
+ const rows = [
1497
+ { id: PERSONA2, kind: "actor", label: j.persona ?? "Person", sub: "person" }
1498
+ ];
1499
+ for (const ch of ["sms", "email"])
1500
+ if ((j.messages ?? []).some((m) => m.channel === ch))
1501
+ rows.push({ id: ch, kind: "inbox", label: CHANNEL[ch], sub: "message" });
1502
+ if (j.backend?.length) rows.push({ id: "automation", kind: "auto", label: "Automation" });
1503
+ const boxes = [];
1504
+ const details = {};
1505
+ for (const s of j.screens) {
1506
+ const [box, detail] = screenBox(s, at(s.id));
1507
+ boxes.push(box);
1508
+ details[box.id] = detail;
1509
+ }
1510
+ for (const m of j.messages ?? []) {
1511
+ const id = `msg:${m.id}`;
1512
+ boxes.push({ id, row: m.channel, column: at(m.after), kind: "msg", title: m.title });
1513
+ details[id] = {
1514
+ kind: "Message",
1515
+ title: m.title,
1516
+ rows: [{ label: "Channel", value: CHANNEL[m.channel] }],
1517
+ steps: [],
1518
+ ...m.render === void 0 ? {} : { render: m.render }
1519
+ };
1520
+ }
1521
+ (j.backend ?? []).forEach(
1522
+ (w, i) => boxes.push({
1523
+ id: `auto:${i}`,
1524
+ row: "automation",
1525
+ column: at(w.under),
1526
+ kind: "auto",
1527
+ title: w.title
1528
+ })
1529
+ );
1530
+ const arrows = (j.decisions ?? []).flatMap(
1531
+ (d) => d.ways.map((w) => ({
1532
+ from: `scr:${d.after}`,
1533
+ to: `scr:${w.to}`,
1534
+ tone: "screen_move",
1535
+ label: w.when
1536
+ }))
1537
+ );
1538
+ const full = {
1539
+ kind: "grid",
1540
+ input: 1,
1541
+ columns: j.screens.map((s, i) => ({ id: `c${i}`, number: String(i + 1), label: s.title })),
1542
+ rows,
1543
+ boxes,
1544
+ arrows,
1545
+ details
1546
+ };
1547
+ return foldCapabilityToUserJourney(full);
1548
+ }
1549
+
1550
+ // src/canvas.tsx
1551
+ import { Fragment as Fragment3, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1552
+ function Lines({ id, chips }) {
1553
+ if (!chips) return null;
1554
+ return /* @__PURE__ */ jsx2("ul", { className: "fl-lines", children: chips.map((c) => /* @__PURE__ */ jsxs2("li", { "data-tone": c.tone, "data-anchor": c.port ? `${id}#${c.port}` : void 0, children: [
1555
+ c.port && /* @__PURE__ */ jsx2("i", { className: "fl-way", children: c.port }),
1556
+ c.text
1557
+ ] }, c.text)) });
1558
+ }
1559
+ function CardTitle({ box, kind }) {
1560
+ const num = /* @__PURE__ */ jsx2("i", { className: "fl-num", children: `${box.c + 1}.${box.n}` });
1561
+ if (box.kind !== "scr" && box.kind !== "msg")
1562
+ return /* @__PURE__ */ jsxs2("b", { children: [
1563
+ num,
1564
+ " ",
1565
+ box.title
1566
+ ] });
1567
+ return /* @__PURE__ */ jsxs2(Fragment3, { children: [
1568
+ /* @__PURE__ */ jsxs2("small", { className: "fl-kind", children: [
1569
+ num,
1570
+ " ",
1571
+ kind
1572
+ ] }),
1573
+ /* @__PURE__ */ jsx2("b", { children: box.title })
1574
+ ] });
1575
+ }
1576
+ function ScreenPreview({
1577
+ box,
1578
+ spec,
1579
+ renderScreen
1580
+ }) {
1581
+ if (!renderScreen || spec === void 0) return null;
1582
+ return /* @__PURE__ */ jsx2("span", { className: "fl-screen", "aria-hidden": "true", inert: true, children: /* @__PURE__ */ jsx2("span", { className: "fl-screen-frame", children: renderScreen(spec, box) }) });
1583
+ }
1584
+ function Card({
1585
+ box,
1586
+ detail,
1587
+ renderScreen
1588
+ }) {
1589
+ const kind = box.kind ?? "";
1590
+ return (
1591
+ // A div acting as the button: a screen drawn inside may hold buttons of its own, and a
1592
+ // button may not hold another.
1593
+ // biome-ignore lint/a11y/useSemanticElements: the card holds a whole screen, buttons included
1594
+ /* @__PURE__ */ jsxs2(
1595
+ "div",
1596
+ {
1597
+ role: "button",
1598
+ tabIndex: 0,
1599
+ className: `fl-card fl-${kind}`,
1600
+ "data-anchor": box.id,
1601
+ "data-station": `s${box.c}`,
1602
+ "aria-label": `${detail?.kind ?? kind}: ${box.title}`,
1603
+ onKeyDown: (e) => {
1604
+ if (e.key === "Enter" || e.key === " ") {
1605
+ e.preventDefault();
1606
+ e.currentTarget.click();
1607
+ }
1608
+ },
1609
+ children: [
1610
+ /* @__PURE__ */ jsx2(CardTitle, { box, kind: detail?.kind }),
1611
+ /* @__PURE__ */ jsx2(Lines, { id: box.id, chips: detail?.chips }),
1612
+ /* @__PURE__ */ jsx2(ScreenPreview, { box, spec: detail?.render, renderScreen })
1613
+ ]
1614
+ }
1615
+ )
1616
+ );
1617
+ }
1618
+ var endText = (e) => `${e.kind}: ${e.title}${e.label ? ` (${e.label})` : ""}`;
1619
+ function linksOf(arrows, details, id) {
1620
+ const end = (other, a) => {
1621
+ const d = details.get(other);
1622
+ return d && { id: other, kind: d.kind, title: d.title, label: a.label, carries: a.carries };
1623
+ };
1624
+ return {
1625
+ from: arrows.filter((a) => a.to === id).map((a) => end(a.from, a)).filter((e) => e !== void 0),
1626
+ to: arrows.filter((a) => a.from === id).map((a) => end(a.to, a)).filter((e) => e !== void 0)
1627
+ };
1628
+ }
1629
+ var carriesLines = (e) => {
1630
+ const all = e.carries ?? [];
1631
+ const plain = all.filter((c) => !c.includes(":"));
1632
+ const ruled = all.filter((c) => c.includes(":"));
1633
+ return [...plain.length ? [plain.join(", ")] : [], ...ruled].map((c) => `carries ${c}`);
1634
+ };
1635
+ var carriesText = (e) => carriesLines(e).map((c) => ` ${c}`);
1636
+ var toGroups = (to) => [
1637
+ { heading: "Records", ends: to.filter((e) => e.kind === "Event") },
1638
+ { heading: "Tracks", ends: to.filter((e) => e.kind === "Analytics") },
1639
+ { heading: "Leads to", ends: to.filter((e) => e.kind !== "Event" && e.kind !== "Analytics") }
1640
+ ].filter((g) => g.ends.length > 0);
1641
+ var asText = (d, links) => [
1642
+ `${d.kind}: ${d.title}`,
1643
+ ...d.rows.map((r) => `${r.label}: ${r.value}`),
1644
+ ...d.steps.map((s) => `${s.req.id} ${s.req.title} / ${s.scn.id} ${s.scn.title}`),
1645
+ ...links.from.flatMap((e) => [`Comes from: ${endText(e)}`, ...carriesText(e)]),
1646
+ ...toGroups(links.to).flatMap(
1647
+ (g) => g.ends.flatMap((e) => [`${g.heading}: ${endText(e)}`, ...carriesText(e)])
1648
+ )
1649
+ ].join("\n");
1650
+ function LinkList({ heading, ends }) {
1651
+ if (!ends.length) return null;
1652
+ return /* @__PURE__ */ jsxs2("div", { children: [
1653
+ /* @__PURE__ */ jsx2("dt", { className: "type-meta text-muted-foreground", children: heading }),
1654
+ ends.map((e) => /* @__PURE__ */ jsxs2("dd", { className: "type-body", children: [
1655
+ endText(e),
1656
+ e.carries?.length ? /* @__PURE__ */ jsx2("ul", { className: "type-meta text-muted-foreground", children: carriesLines(e).map((c) => /* @__PURE__ */ jsx2("li", { children: c }, c)) }) : null
1657
+ ] }, e.id))
1658
+ ] });
1659
+ }
1660
+ function DetailPanel({
1661
+ detail,
1662
+ links,
1663
+ onStep
1664
+ }) {
1665
+ return /* @__PURE__ */ jsxs2(Fragment3, { children: [
1666
+ /* @__PURE__ */ jsx2(DrawerHeader, { children: /* @__PURE__ */ jsxs2("div", { className: "flex min-w-0 flex-1 flex-col gap-1", children: [
1667
+ /* @__PURE__ */ jsx2(DrawerDescription, { children: detail.kind }),
1668
+ /* @__PURE__ */ jsx2(DrawerTitle, { children: detail.title })
1669
+ ] }) }),
1670
+ /* @__PURE__ */ jsx2(DrawerBody, { children: /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-4 px-5 pb-5", children: [
1671
+ /* @__PURE__ */ jsxs2("div", { className: "flex gap-2", children: [
1672
+ /* @__PURE__ */ jsx2(
1673
+ Button,
1674
+ {
1675
+ variant: "neutral",
1676
+ mode: "stroke",
1677
+ size: "xs",
1678
+ onClick: () => onStep(-1),
1679
+ "aria-label": "Previous box",
1680
+ children: "\u2039 Previous"
1681
+ }
1682
+ ),
1683
+ /* @__PURE__ */ jsx2(
1684
+ Button,
1685
+ {
1686
+ variant: "neutral",
1687
+ mode: "stroke",
1688
+ size: "xs",
1689
+ onClick: () => onStep(1),
1690
+ "aria-label": "Next box",
1691
+ children: "Next \u203A"
1692
+ }
1693
+ ),
1694
+ /* @__PURE__ */ jsx2(
1695
+ CopyButton,
1696
+ {
1697
+ value: asText(detail, links),
1698
+ copyLabel: "Copy these details",
1699
+ className: "ms-auto"
1700
+ }
1701
+ )
1702
+ ] }),
1703
+ /* @__PURE__ */ jsxs2("dl", { className: "flex flex-col gap-2", children: [
1704
+ detail.rows.map((r) => /* @__PURE__ */ jsxs2("div", { children: [
1705
+ /* @__PURE__ */ jsx2("dt", { className: "type-meta text-muted-foreground", children: r.label }),
1706
+ /* @__PURE__ */ jsx2("dd", { className: "type-body whitespace-pre-line", children: r.value })
1707
+ ] }, r.label)),
1708
+ /* @__PURE__ */ jsx2(LinkList, { heading: "Comes from", ends: links.from }),
1709
+ toGroups(links.to).map((g) => /* @__PURE__ */ jsx2(LinkList, { heading: g.heading, ends: g.ends }, g.heading))
1710
+ ] }),
1711
+ detail.steps.map((s) => /* @__PURE__ */ jsxs2("section", { className: "type-body border-t border-border pt-2", children: [
1712
+ /* @__PURE__ */ jsx2("code", { className: "font-mono", children: s.req.id }),
1713
+ " ",
1714
+ s.req.title,
1715
+ /* @__PURE__ */ jsxs2("p", { className: "text-muted-foreground", children: [
1716
+ /* @__PURE__ */ jsx2("code", { className: "font-mono", children: s.scn.id }),
1717
+ " ",
1718
+ s.scn.title
1719
+ ] })
1720
+ ] }, s.scn.id + s.req.id))
1721
+ ] }) })
1722
+ ] });
1723
+ }
1724
+ var ZoomHost = ({ variant: _v, mode: _m, size: _s, ...props }) => /* @__PURE__ */ jsx2(Button, { variant: "neutral", mode: "ghost", size: "xs", ...props });
1725
+ var renderColumn = (c, header) => c.hint?.length ? /* @__PURE__ */ jsxs2(Tooltip, { children: [
1726
+ /* @__PURE__ */ jsx2(TooltipTrigger, { render: header }),
1727
+ /* @__PURE__ */ jsx2(TooltipContent, { side: "bottom", size: "small", children: /* @__PURE__ */ jsx2("span", { className: "fc-tip", children: c.hint.map((h, i) => {
1728
+ if (i === 0) return /* @__PURE__ */ jsx2("b", { children: h }, h);
1729
+ const [id = "", ...rest] = h.split(" ");
1730
+ return /* @__PURE__ */ jsxs2("span", { children: [
1731
+ /* @__PURE__ */ jsx2("i", { children: id }),
1732
+ " ",
1733
+ rest.join(" ")
1734
+ ] }, h);
1735
+ }) }) })
1736
+ ] }) : header;
1737
+ function UserJourneyKey() {
1738
+ const marks = [
1739
+ ["Arrow leaves here", /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "6", r: "3", className: "k-out" }, "d")],
1740
+ ["Arrow lands here", /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "6", r: "3", className: "k-in" }, "r")],
1741
+ ["Yes, the way on", /* @__PURE__ */ jsx2("path", { d: "M2 6 H22", className: "k-yes" }, "y")],
1742
+ ["No, the next check", /* @__PURE__ */ jsx2("path", { d: "M2 6 H22", className: "k-no" }, "n")],
1743
+ [
1744
+ "Automation, runs by itself",
1745
+ /* @__PURE__ */ jsx2("rect", { x: "3", y: "1", width: "18", height: "10", rx: "2", className: "k-auto" }, "a")
1746
+ ],
1747
+ ["Error the screen shows", /* @__PURE__ */ jsx2("path", { d: "M12 2 L16 6 L12 10 L8 6 Z", className: "k-err" }, "e")],
1748
+ ["Other outcome on the screen", /* @__PURE__ */ jsx2("circle", { cx: "12", cy: "6", r: "2.5", className: "k-other" }, "o")]
1749
+ ];
1750
+ return /* @__PURE__ */ jsxs2(Popover, { children: [
1751
+ /* @__PURE__ */ jsx2(PopoverTrigger, { render: /* @__PURE__ */ jsx2("button", { type: "button", className: "fc-key" }), children: "Key" }),
1752
+ /* @__PURE__ */ jsx2(PopoverContent, { side: "top", align: "start", children: /* @__PURE__ */ jsx2("span", { className: "fc-key-list", children: marks.map(([label, mark]) => /* @__PURE__ */ jsxs2("span", { children: [
1753
+ /* @__PURE__ */ jsx2("svg", { width: "24", height: "12", "aria-hidden": "true", children: mark }),
1754
+ label
1755
+ ] }, label)) }) })
1756
+ ] });
1757
+ }
1758
+ function arrowAt(root, x, y) {
1759
+ for (const hit of root.querySelectorAll(".gd-arrow .gd-hit")) {
1760
+ const m = hit.getScreenCTM();
1761
+ if (!m) continue;
1762
+ const p = new DOMPoint(x, y).matrixTransform(m.inverse());
1763
+ if (hit.isPointInStroke(p)) return hit.parentNode;
1764
+ }
1765
+ return null;
1766
+ }
1767
+ function useArrowTip(details, on) {
1768
+ const [tip, setTip] = useState2(null);
1769
+ const timer = useRef2(0);
1770
+ const shown = useRef2(null);
1771
+ const hidAt = useRef2(0);
1772
+ const clear2 = () => {
1773
+ clearTimeout(timer.current);
1774
+ if (shown.current?.hasAttribute("data-tip")) hidAt.current = Date.now();
1775
+ shown.current?.removeAttribute("data-tip");
1776
+ shown.current = null;
1777
+ setTip(null);
1778
+ };
1779
+ const move = (e) => {
1780
+ if (!on) return;
1781
+ const { clientX: x, clientY: y, currentTarget } = e;
1782
+ const over = e.target.closest("[data-anchor]") ? null : arrowAt(currentTarget, x, y);
1783
+ if (over === shown.current) {
1784
+ if (over) setTip((t) => t && { ...t, x, y });
1785
+ return;
1786
+ }
1787
+ clear2();
1788
+ shown.current = over;
1789
+ if (!over) return;
1790
+ const wait = Date.now() - hidAt.current < 300 ? 0 : 350;
1791
+ timer.current = window.setTimeout(() => {
1792
+ over.setAttribute("data-tip", "");
1793
+ const name = (k) => {
1794
+ const n = k && currentTarget.querySelector(`[data-anchor="${k}"] .fl-num`)?.textContent;
1795
+ const title = k && details.get(k)?.title || k || "";
1796
+ return n ? `${n} ${title}` : title;
1797
+ };
1798
+ setTip({
1799
+ x,
1800
+ y,
1801
+ from: name(over.dataset.from),
1802
+ to: name(over.dataset.to),
1803
+ answer: over.querySelector("text")?.textContent ?? ""
1804
+ });
1805
+ }, wait);
1806
+ };
1807
+ useEffect2(() => () => clearTimeout(timer.current), []);
1808
+ return [tip, move, clear2];
1809
+ }
1810
+ function Named({ text }) {
1811
+ const [, n, rest] = /^(\d+\.\d+) (.*)$/.exec(text) ?? [];
1812
+ return n ? /* @__PURE__ */ jsxs2(Fragment3, { children: [
1813
+ /* @__PURE__ */ jsx2("i", { children: n }),
1814
+ " ",
1815
+ rest
1816
+ ] }) : /* @__PURE__ */ jsx2(Fragment3, { children: text });
1817
+ }
1818
+ function ArrowTip({ tip }) {
1819
+ const word = tip.answer.replace(/^\d+\.\d+ /, "");
1820
+ const left = tip.x + 300 > innerWidth ? tip.x - 14 : tip.x + 14;
1821
+ const top = tip.y + 80 > innerHeight ? tip.y - 16 : tip.y + 16;
1822
+ const flip = `translate(${left < tip.x ? "-100%" : "0"}, ${top < tip.y ? "-100%" : "0"})`;
1823
+ return /* @__PURE__ */ jsxs2("div", { className: "fc-arrow-tip", style: { left, top, transform: flip }, role: "tooltip", children: [
1824
+ /* @__PURE__ */ jsx2("span", { className: "from", children: /* @__PURE__ */ jsx2(Named, { text: tip.from }) }),
1825
+ /* @__PURE__ */ jsxs2("span", { children: [
1826
+ word && /* @__PURE__ */ jsx2("b", { children: word }),
1827
+ " \u2192 ",
1828
+ /* @__PURE__ */ jsx2(Named, { text: tip.to })
1829
+ ] })
1830
+ ] });
1831
+ }
1832
+ function useStepKeys(picked, unpick, step) {
1833
+ useEffect2(() => {
1834
+ const onKey = (e) => {
1835
+ const target = e.target;
1836
+ if (target instanceof Element && target.closest("input, select, textarea")) return;
1837
+ if (e.key === "Escape") unpick();
1838
+ if (picked && e.key === "ArrowRight") step(1);
1839
+ if (picked && e.key === "ArrowLeft") step(-1);
1840
+ };
1841
+ addEventListener("keydown", onKey);
1842
+ return () => removeEventListener("keydown", onKey);
1843
+ });
1844
+ }
1845
+ function drawnGrid(source, view) {
1846
+ if ("userJourney" in source) {
1847
+ const g = userJourneyToGrid(source.userJourney);
1848
+ return { ...g, reading: g.boxes?.map((b) => b.id) ?? [] };
1849
+ }
1850
+ const cap = "scenarioGrids" in source;
1851
+ const base = cap ? mergeScenarioGrids(source.scenarioGrids) : source.scenarioGrid;
1852
+ const fold = cap ? foldCapabilityToUserJourney : foldScenarioToUserJourney;
1853
+ const drawn = view === "full" ? base : fold(base);
1854
+ return {
1855
+ ...drawn,
1856
+ details: drawn.details ?? base.details,
1857
+ reading: drawn.boxes?.map((b) => b.id) ?? []
1858
+ };
1859
+ }
1860
+ function usePick(key, grid, details) {
1861
+ const reading = grid?.reading ?? [];
1862
+ const [picked, setPicked] = useState2(null);
1863
+ useEffect2(() => setPicked(null), [key]);
1864
+ const detail = picked ? details.get(picked.anchor) ?? details.get(picked.station) ?? null : null;
1865
+ const links = picked ? linksOf(grid.arrows ?? [], details, picked.anchor) : null;
1866
+ const step = (dir) => {
1867
+ const i = picked ? reading.indexOf(picked.anchor) : -1;
1868
+ const id = reading[Math.min(reading.length - 1, Math.max(0, i + dir))];
1869
+ if (!id) return;
1870
+ const column = grid.boxes?.find((b) => b.id === id)?.column ?? "s0";
1871
+ setPicked({ anchor: id, station: column });
1872
+ };
1873
+ useStepKeys(picked, () => setPicked(null), step);
1874
+ return { picked, setPicked, detail, links, step };
1875
+ }
1876
+ function ViewSwitch({ view, onView }) {
1877
+ return /* @__PURE__ */ jsx2(SegmentedControl, { value: view, onValueChange: (v) => onView(v), children: /* @__PURE__ */ jsxs2(SegmentedControlList, { size: "sm", "aria-label": "Diagram view", className: "fc-views", children: [
1878
+ /* @__PURE__ */ jsx2(SegmentedControlTrigger, { value: "full", children: "Full" }),
1879
+ /* @__PURE__ */ jsx2(SegmentedControlTrigger, { value: "userJourney", children: "UJ" })
1880
+ ] }) });
1881
+ }
1882
+ function Canvas({ id, source, defaultView, renderScreen }) {
1883
+ const [view, setView] = useState2(defaultView);
1884
+ useEffect2(() => setView(defaultView), [id]);
1885
+ const grid = useMemo2(() => drawnGrid(source, view), [id, view]);
1886
+ const details = useMemo2(
1887
+ () => new Map(Object.entries(grid.details ?? {})),
1888
+ [grid]
1889
+ );
1890
+ const { picked, setPicked, detail, links, step } = usePick(id, grid, details);
1891
+ const journey = view === "userJourney";
1892
+ const [tip, onMove, onLeave] = useArrowTip(details, journey);
1893
+ return /* @__PURE__ */ jsxs2(
1894
+ "div",
1895
+ {
1896
+ className: detail ? "vds-diagrams fc-body open" : "vds-diagrams fc-body",
1897
+ "data-drawing": journey ? "journey" : "flow",
1898
+ onMouseMove: onMove,
1899
+ onMouseLeave: onLeave,
1900
+ onWheel: onLeave,
1901
+ onPointerDown: onLeave,
1902
+ children: [
1903
+ /* @__PURE__ */ jsx2(
1904
+ Flow,
1905
+ {
1906
+ grid,
1907
+ picked,
1908
+ onPick: setPicked,
1909
+ renderBox: (box, _columnId) => /* @__PURE__ */ jsx2(Card, { box, detail: details.get(box.id), renderScreen }),
1910
+ renderColumn,
1911
+ Button: ZoomHost
1912
+ },
1913
+ `${id}:${view}`
1914
+ ),
1915
+ journey && /* @__PURE__ */ jsx2(UserJourneyKey, {}),
1916
+ !("userJourney" in source) && /* @__PURE__ */ jsx2(ViewSwitch, { view, onView: setView }),
1917
+ tip && /* @__PURE__ */ jsx2(ArrowTip, { tip }),
1918
+ /* @__PURE__ */ jsx2(
1919
+ Drawer,
1920
+ {
1921
+ modal: false,
1922
+ open: Boolean(detail),
1923
+ onOpenChange: (open) => !open && setPicked(null),
1924
+ children: /* @__PURE__ */ jsx2(DrawerContent, { overlay: false, variant: "floating", side: "right", "aria-label": "Box details", children: detail && /* @__PURE__ */ jsx2(DetailPanel, { detail, links: links ?? { from: [], to: [] }, onStep: step }) })
1925
+ }
1926
+ )
1927
+ ]
1928
+ }
1929
+ );
1930
+ }
1931
+ function Problems({ problems }) {
1932
+ return /* @__PURE__ */ jsx2("div", { className: "vds-diagrams fc-body", role: "alert", children: /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-2 p-5", children: [
1933
+ /* @__PURE__ */ jsx2("p", { className: "type-body", children: "This user journey cannot be drawn:" }),
1934
+ /* @__PURE__ */ jsx2("ul", { className: "type-meta text-muted-foreground flex list-disc flex-col gap-1 ps-5", children: problems.map((p) => /* @__PURE__ */ jsx2("li", { children: p }, p)) })
1935
+ ] }) });
1936
+ }
1937
+ function JourneyCanvas({
1938
+ id,
1939
+ journey,
1940
+ problems,
1941
+ renderScreen
1942
+ }) {
1943
+ if (problems.length) return /* @__PURE__ */ jsx2(Problems, { problems });
1944
+ return /* @__PURE__ */ jsx2(
1945
+ Canvas,
1946
+ {
1947
+ id,
1948
+ source: { userJourney: journey },
1949
+ defaultView: "userJourney",
1950
+ renderScreen
1951
+ }
1952
+ );
1953
+ }
1954
+ function ScenarioDiagram(props) {
1955
+ const { id = "scenario", view = "full", renderScreen } = props;
1956
+ if (props.userJourney) {
1957
+ const problems = validateScenarioUserJourney(props.userJourney);
1958
+ return /* @__PURE__ */ jsx2(
1959
+ JourneyCanvas,
1960
+ {
1961
+ id,
1962
+ journey: props.userJourney,
1963
+ problems,
1964
+ renderScreen
1965
+ }
1966
+ );
1967
+ }
1968
+ const source = { scenarioGrid: props.scenarioGrid };
1969
+ return /* @__PURE__ */ jsx2(Canvas, { id, source, defaultView: view, renderScreen });
1970
+ }
1971
+ function CapabilityDiagram(props) {
1972
+ const { id = "capability", view = "userJourney", renderScreen } = props;
1973
+ if (props.userJourney) {
1974
+ const problems = validateUserJourney(props.userJourney);
1975
+ return /* @__PURE__ */ jsx2(
1976
+ JourneyCanvas,
1977
+ {
1978
+ id,
1979
+ journey: props.userJourney,
1980
+ problems,
1981
+ renderScreen
1982
+ }
1983
+ );
1984
+ }
1985
+ const source = { scenarioGrids: props.scenarioGrids };
1986
+ return /* @__PURE__ */ jsx2(Canvas, { id, source, defaultView: view, renderScreen });
1987
+ }
1988
+
1989
+ // src/grid.ts
1990
+ function validateScenarioGrid(json) {
1991
+ if (!json || typeof json !== "object") return ["not a grid: expected a JSON object"];
1992
+ return problemsOf(json);
1993
+ }
1994
+
1995
+ // src/from-scenarios.ts
1996
+ var SUMMED2 = /* @__PURE__ */ new Set(["auto", "call", "ext", "tr"]);
1997
+ var screenId = (boxId) => boxId.replace(/^scr:/, "");
1998
+ function decisionsOf(g) {
1999
+ const byScreen = /* @__PURE__ */ new Map();
2000
+ for (const a of g.arrows ?? []) {
2001
+ if (!a.from.startsWith("scr:") || !a.to.startsWith("scr:") || a.from === a.to) continue;
2002
+ const d = byScreen.get(a.from) ?? { after: screenId(a.from), ways: [] };
2003
+ const way = { when: a.label ?? "Next", to: screenId(a.to) };
2004
+ if (!d.ways.some((w) => w.when === way.when && w.to === way.to)) d.ways.push(way);
2005
+ byScreen.set(a.from, d);
2006
+ }
2007
+ return [...byScreen.values()];
2008
+ }
2009
+ function capabilityUserJourney(scenarioGrids, title) {
2010
+ const g = mergeScenarioGrids(scenarioGrids);
2011
+ const boxes = g.boxes ?? [];
2012
+ const screenAt = new Map(
2013
+ boxes.filter((b) => b.kind === "scr").map((b) => [b.column, screenId(b.id)])
2014
+ );
2015
+ const persona = (g.rows ?? []).find((r) => r.kind === "actor")?.label;
2016
+ const under = (column) => screenAt.get(column) ?? "";
2017
+ return {
2018
+ kind: "journey",
2019
+ input: 1,
2020
+ title,
2021
+ ...persona ? { persona } : {},
2022
+ screens: boxes.filter((b) => b.kind === "scr").map((b) => ({ id: screenId(b.id), title: b.title })),
2023
+ decisions: decisionsOf(g),
2024
+ messages: boxes.filter((b) => b.kind === "msg").map((b, i) => ({
2025
+ id: `msg-${i + 1}`,
2026
+ channel: b.row === "email" ? "email" : "sms",
2027
+ title: b.title,
2028
+ after: under(b.column)
2029
+ })),
2030
+ backend: boxes.filter((b) => SUMMED2.has(b.kind ?? "")).map((b) => ({ under: under(b.column), title: b.title }))
2031
+ };
2032
+ }
2033
+ export {
2034
+ CapabilityDiagram,
2035
+ ScenarioDiagram,
2036
+ capabilityUserJourney,
2037
+ foldCapabilityToUserJourney,
2038
+ foldScenarioToUserJourney,
2039
+ mergeScenarioGrids,
2040
+ userJourneyToGrid,
2041
+ validateScenarioGrid,
2042
+ validateScenarioUserJourney,
2043
+ validateUserJourney
2044
+ };