@zyro-sec/merman 1.0.2 → 1.0.3

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 (91) hide show
  1. package/package.json +2 -2
  2. package/script/layout-audit.ts +98 -98
  3. package/src/core/canvas.ts +228 -228
  4. package/src/core/color/style.ts +56 -56
  5. package/src/core/drawing.ts +301 -301
  6. package/src/core/geometry.ts +347 -347
  7. package/src/core/mermaid.ts +38 -38
  8. package/src/core/render-grid.ts +51 -51
  9. package/src/core/spatial.ts +243 -243
  10. package/src/core/text-lines.ts +32 -32
  11. package/src/core/text.ts +44 -44
  12. package/src/detect.ts +17 -17
  13. package/src/diagnostics.ts +16 -16
  14. package/src/flowchart/drawing.ts +340 -340
  15. package/src/flowchart/labels.ts +144 -144
  16. package/src/flowchart/layout.ts +1427 -1427
  17. package/src/flowchart/options.ts +12 -12
  18. package/src/flowchart/parser.ts +467 -467
  19. package/src/flowchart/render.ts +10 -10
  20. package/src/flowchart/routing.ts +1542 -1542
  21. package/src/flowchart/style.ts +79 -79
  22. package/src/flowchart/types.ts +65 -65
  23. package/src/gantt/diagram.ts +8 -8
  24. package/src/gantt/drawing.ts +191 -191
  25. package/src/gantt/parser.ts +161 -161
  26. package/src/gantt/render-grid.ts +17 -17
  27. package/src/gantt/style.ts +36 -36
  28. package/src/gantt/types.ts +44 -44
  29. package/src/gitgraph/diagram.ts +8 -8
  30. package/src/gitgraph/drawing.ts +234 -234
  31. package/src/gitgraph/parser.ts +219 -219
  32. package/src/gitgraph/render-grid.ts +17 -17
  33. package/src/gitgraph/style.ts +37 -37
  34. package/src/gitgraph/types.ts +36 -36
  35. package/src/markdown.ts +336 -336
  36. package/src/palette.ts +75 -75
  37. package/src/plugin.ts +15 -15
  38. package/src/sequence/diagram.ts +8 -8
  39. package/src/sequence/drawing.ts +287 -287
  40. package/src/sequence/options.ts +8 -8
  41. package/src/sequence/parser.ts +282 -282
  42. package/src/sequence/placement.ts +684 -684
  43. package/src/sequence/render-grid.ts +22 -22
  44. package/src/sequence/style.ts +81 -81
  45. package/src/sequence/types.ts +74 -74
  46. package/src/state/diagram.ts +8 -8
  47. package/src/state/drawing.ts +360 -360
  48. package/src/state/endpoint.ts +15 -15
  49. package/src/state/layout.ts +1134 -1134
  50. package/src/state/note.ts +59 -59
  51. package/src/state/options.ts +11 -11
  52. package/src/state/parser.ts +224 -224
  53. package/src/state/render-grid.ts +22 -22
  54. package/src/state/routing.ts +1522 -1522
  55. package/src/state/search.ts +103 -103
  56. package/src/state/style.ts +52 -52
  57. package/src/state/types.ts +63 -63
  58. package/src/state/visible-model.ts +77 -77
  59. package/src/test/diagram.ts +32 -32
  60. package/src/test/layout-audit/fixtures.ts +538 -538
  61. package/src/test/layout-audit/harness.ts +522 -522
  62. package/src/timeline/diagram.ts +8 -8
  63. package/src/timeline/drawing.ts +109 -109
  64. package/src/timeline/parser.ts +119 -119
  65. package/src/timeline/render-grid.ts +17 -17
  66. package/src/timeline/style.ts +36 -36
  67. package/src/timeline/types.ts +31 -31
  68. package/tsconfig.json +10 -10
  69. package/src/core/canvas.test.ts +0 -203
  70. package/src/core/color/style.test.ts +0 -24
  71. package/src/core/drawing.test.ts +0 -116
  72. package/src/core/geometry.test.ts +0 -112
  73. package/src/core/spatial.test.ts +0 -87
  74. package/src/core/text.test.ts +0 -33
  75. package/src/flowchart/flowchart.test.ts +0 -2800
  76. package/src/flowchart/labels.test.ts +0 -127
  77. package/src/flowchart/routing.test.ts +0 -368
  78. package/src/gantt/diagram.test.ts +0 -124
  79. package/src/gitgraph/diagram.test.ts +0 -183
  80. package/src/layout-audit.test.ts +0 -92
  81. package/src/palette.test.ts +0 -103
  82. package/src/sequence/diagram.test.ts +0 -757
  83. package/src/sequence/placement.test.ts +0 -219
  84. package/src/state/diagram.test.ts +0 -1386
  85. package/src/state/layout.test.ts +0 -314
  86. package/src/state/routing.test.ts +0 -693
  87. package/src/state/style.test.ts +0 -113
  88. package/src/state/visible-model.test.ts +0 -84
  89. package/src/test/diagnostics.test.ts +0 -129
  90. package/src/test/markdown.test.ts +0 -474
  91. package/src/timeline/diagram.test.ts +0 -188
@@ -1,1386 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import stringWidth from "string-width"
3
- import { spatialPathClaim } from "../core/spatial.js"
4
- import { expectDiagram } from "../test/diagram.js"
5
- import { renderStateDiagram } from "./diagram.js"
6
- import { createStateDiagramDrawing, drawStateDiagramGrid } from "./drawing.js"
7
- import { createStateDiagramLayout } from "./layout.js"
8
- import { parseMermaidStateDiagram } from "./parser.js"
9
- import { prepareVisibleStateDiagram } from "./visible-model.js"
10
-
11
- function expectCompleteStateDiagram(source: string, output = renderStateDiagram(source)): void {
12
- const diagram = prepareVisibleStateDiagram(parseMermaidStateDiagram(source))
13
- const layout = createStateDiagramLayout(diagram, { minStateGap: 5 })
14
- const states = diagram.states.filter((state) => state.kind === "state")
15
- const stateBounds = states.map((state) => layout.bounds.get(state.id)!)
16
-
17
- for (const text of [
18
- ...states.map((state) => state.label),
19
- ...diagram.transitions.map((transition) => transition.label),
20
- ...diagram.notes.flatMap((note) => note.lines),
21
- ].filter(Boolean)) {
22
- expect(output).toContain(text)
23
- }
24
- for (const [index, bound] of stateBounds.entries()) {
25
- for (const other of stateBounds.slice(index + 1)) {
26
- expect(
27
- bound.left < other.left + other.width &&
28
- bound.left + bound.width > other.left &&
29
- bound.top < other.top + other.height &&
30
- bound.top + bound.height > other.top,
31
- `${bound.id} overlaps ${other.id}`,
32
- ).toBe(false)
33
- }
34
- }
35
- const occupiedByNote = layout.noteBounds.map((note) => {
36
- const connector = spatialPathClaim(`connector:${note.id}`, note.id, "boundary", note.connector!.points)
37
- return new Set([
38
- ...Array.from({ length: note.height }, (_, dy) =>
39
- Array.from({ length: note.width }, (_, dx) => `${note.left + dx}:${note.top + dy}`),
40
- ).flat(),
41
- ...connector.spans.flatMap((span) =>
42
- Array.from({ length: span.toX - span.fromX + 1 }, (_, dx) => `${span.fromX + dx}:${span.y}`),
43
- ),
44
- ])
45
- })
46
- for (const [index, occupied] of occupiedByNote.entries()) {
47
- for (const bound of stateBounds) {
48
- expect(
49
- Array.from({ length: bound.height }, (_, dy) =>
50
- Array.from({ length: bound.width }, (_, dx) => occupied.has(`${bound.left + dx}:${bound.top + dy}`)),
51
- )
52
- .flat()
53
- .some(Boolean),
54
- `${layout.noteBounds[index]!.id} overlaps ${bound.id}`,
55
- ).toBe(false)
56
- }
57
- for (const other of occupiedByNote.slice(index + 1)) {
58
- expect([...occupied].some((cell) => other.has(cell))).toBe(false)
59
- }
60
- }
61
- }
62
-
63
- type ResponsiveStateLabelProfile = "short" | "long" | "unicode"
64
-
65
- function responsiveStateChain(direction: "LR" | "RL", profile: ResponsiveStateLabelProfile): string {
66
- const stateLabel = (id: string) => {
67
- if (profile === "long") return `${id} deliberate state with a long descriptive label`
68
- if (profile === "unicode") return `${id} 東京<br/>résumé 🚀`
69
- return `${id} node`
70
- }
71
- const transitionLabel = (id: string) => {
72
- if (profile === "long") return `${id} transition carrying detailed context`
73
- if (profile === "unicode") return `${id} 東京<br/>✓ prêt`
74
- return `${id} edge`
75
- }
76
- const ids = ["A", "B", "C", "D", "E"]
77
- return [
78
- "stateDiagram-v2",
79
- `direction ${direction}`,
80
- ...ids.map((id) => `state "${stateLabel(id)}" as ${id}`),
81
- "[*] --> A",
82
- ...ids.slice(0, -1).map((id, index) => `${id} --> ${ids[index + 1]}: ${transitionLabel(`E0${index + 1}`)}`),
83
- "E --> [*]",
84
- ].join("\n")
85
- }
86
-
87
- function renderedStateDimensions(output: string) {
88
- const lines = output.split("\n")
89
- return { width: Math.max(...lines.map((line) => stringWidth(line))), height: lines.length }
90
- }
91
-
92
- describe("StateDiagram", () => {
93
- test("detects and parses Mermaid state diagrams", () => {
94
- const diagram = parseMermaidStateDiagram(`
95
- stateDiagram-v2
96
- %% request lifecycle
97
- direction LR
98
- [*] --> Idle
99
- Idle --> Loading: submit
100
- Loading --> Success: done
101
- Success --> [*]
102
- `)
103
-
104
- expect(diagram.direction).toBe("LR")
105
- expect(diagram.states).toEqual([
106
- { id: "__start", label: "●", kind: "start" },
107
- { id: "Idle", label: "Idle", kind: "state" },
108
- { id: "Loading", label: "Loading", kind: "state" },
109
- { id: "Success", label: "Success", kind: "state" },
110
- { id: "__end", label: "◎", kind: "end" },
111
- ])
112
- expect(diagram.transitions).toEqual([
113
- { from: "__start", to: "Idle", label: "" },
114
- { from: "Idle", to: "Loading", label: "submit" },
115
- { from: "Loading", to: "Success", label: "done" },
116
- { from: "Success", to: "__end", label: "" },
117
- ])
118
- })
119
-
120
- test("parses quoted state aliases", () => {
121
- const diagram = parseMermaidStateDiagram(`
122
- stateDiagram-v2
123
- state "Waiting<br/>for Payment" as WaitingPayment
124
- [*] --> WaitingPayment
125
- `)
126
-
127
- expect(diagram.states).toContainEqual({
128
- id: "WaitingPayment",
129
- label: "Waiting<br/>for Payment",
130
- kind: "state",
131
- })
132
- })
133
-
134
- test("decodes HTML entities in state, transition, and note labels", () => {
135
- const diagram = parseMermaidStateDiagram(`stateDiagram-v2
136
- state "Ready &amp; waiting" as Ready
137
- Ready --> Done: elapsed &lt;3s
138
- note right of Done: result &#x2265; 1`)
139
-
140
- expect(diagram.states.find((state) => state.id === "Ready")?.label).toBe("Ready & waiting")
141
- expect(diagram.transitions[0]?.label).toBe("elapsed <3s")
142
- expect(diagram.notes[0]?.lines).toEqual(["result ≥ 1"])
143
- })
144
-
145
- test("parses choice pseudo-states", () => {
146
- const diagram = parseMermaidStateDiagram(`
147
- stateDiagram-v2
148
- [*] --> Decision
149
- state Decision <<choice>>
150
- Decision --> Accepted: yes
151
- `)
152
-
153
- expect(diagram.states).toContainEqual({ id: "Decision", label: "", kind: "choice" })
154
- })
155
-
156
- test("parses composite states and notes", () => {
157
- const diagram = parseMermaidStateDiagram(`
158
- stateDiagram-v2
159
- state Authenticated {
160
- [*] --> Idle
161
- Idle --> Editing: open
162
- }
163
- note right of Editing
164
- Draft changes
165
- end note
166
- `)
167
-
168
- expect(diagram.composites).toContainEqual({ id: "Authenticated", label: "Authenticated" })
169
- expect(diagram.states).toContainEqual({
170
- id: "Idle",
171
- label: "Idle",
172
- kind: "state",
173
- parentId: "Authenticated",
174
- })
175
- expect(diagram.states).toContainEqual({
176
- id: "Authenticated.__start",
177
- label: "●",
178
- kind: "start",
179
- parentId: "Authenticated",
180
- })
181
- expect(diagram.notes).toEqual([{ target: "Editing", position: "right", lines: ["Draft changes"] }])
182
- })
183
-
184
- test("renders a horizontal state diagram", () => {
185
- const output = renderStateDiagram(`
186
- stateDiagram-v2
187
- direction LR
188
- [*] --> Idle
189
- Idle --> Loading: submit
190
- Loading --> Success: done
191
- Success --> [*]
192
- `)
193
-
194
- expectDiagram(output).toEqualDiagram(`
195
- ╭──────╮ submit ╭─────────╮ done ╭─────────╮
196
- ●────────────▶│ Idle ├────────────▶│ Loading ├────────────▶│ Success ├────────────▶◎
197
- ╰──────╯ ╰─────────╯ ╰─────────╯
198
- `)
199
- })
200
-
201
- test("renders reverse horizontal direction from right to left", () => {
202
- const output = renderStateDiagram(`stateDiagram-v2
203
- direction RL
204
- A --> B`)
205
- const labelRow = output.split("\n").find((line) => line.includes(" A ") && line.includes(" B "))!
206
-
207
- expect(labelRow.indexOf("B")).toBeLessThan(labelRow.indexOf("A"))
208
- expect(output).toContain("◀")
209
- })
210
-
211
- test("renders reverse vertical direction from bottom to top", () => {
212
- const source = `stateDiagram-v2
213
- direction BT
214
- A --> B`
215
- const drawing = createStateDiagramDrawing(parseMermaidStateDiagram(source))
216
-
217
- expect(drawing.layout.bounds.get("A")!.top).toBeGreaterThan(drawing.layout.bounds.get("B")!.top)
218
- expect(drawing.grid.toString({ trimTop: true, trimBottom: true })).toContain("▲")
219
- })
220
-
221
- test.each(
222
- (["LR", "RL"] as const).flatMap((direction) =>
223
- (["short", "long", "unicode"] as const).flatMap((profile) =>
224
- ([60, 80, 120] as const).map((layoutMaxWidth) => [direction, profile, layoutMaxWidth] as const),
225
- ),
226
- ),
227
- )("folds responsive %s %s chains at %d columns", (direction, profile, layoutMaxWidth) => {
228
- const source = responsiveStateChain(direction, profile)
229
- const horizontal = renderStateDiagram(source)
230
- const responsive = renderStateDiagram(source, { layoutMaxWidth })
231
- const vertical = renderStateDiagram(source, { direction: direction === "RL" ? "BT" : "TB" })
232
-
233
- expect(renderedStateDimensions(horizontal).width).toBeGreaterThan(layoutMaxWidth)
234
- expect(responsive).toBe(vertical)
235
- expect(renderedStateDimensions(responsive).width).toBeLessThan(renderedStateDimensions(horizontal).width)
236
- for (const content of ["A", "B", "C", "D", "E", "E01", "E02", "E03", "E04"]) {
237
- expect(responsive).toContain(content)
238
- }
239
- })
240
-
241
- test.each(["LR", "RL"] as const)("keeps the narrower %s orientation for broad ranks", (direction) => {
242
- const source = `stateDiagram-v2
243
- direction ${direction}
244
- ${Array.from({ length: 8 }, (_, index) => ` A --> B${index}`).join("\n")}`
245
- const horizontal = renderStateDiagram(source)
246
- const vertical = renderStateDiagram(source, { direction: direction === "RL" ? "BT" : "TB" })
247
- const responsive = renderStateDiagram(source, { layoutMaxWidth: 60 })
248
-
249
- expect(renderedStateDimensions(horizontal).width).toBeLessThan(renderedStateDimensions(vertical).width)
250
- expect(responsive).toBe(horizontal)
251
- })
252
-
253
- test("falls back before allocating an oversized horizontal canvas", () => {
254
- const ids = Array.from({ length: 301 }, (_, index) => `S${index}`)
255
- const label = "transition label carrying enough context to make the horizontal canvas too large"
256
- const source = `stateDiagram-v2
257
- direction LR
258
- ${ids
259
- .slice(0, -1)
260
- .map((id, index) => ` ${id} --> ${ids[index + 1]}: ${label}`)
261
- .join("\n")}`
262
- const output = renderStateDiagram(source, { layoutMaxWidth: 80 })
263
-
264
- expect(output).toContain("S0")
265
- expect(output).toContain("S300")
266
- expect(renderedStateDimensions(output).width).toBeLessThanOrEqual(stringWidth(label) + 8)
267
- })
268
-
269
- test.each(["TB", "TD", "BT"] as const)("preserves explicit %s layouts under a narrow width target", (direction) => {
270
- const source = `stateDiagram-v2
271
- direction ${direction}
272
- A --> B: next`
273
-
274
- expect(renderStateDiagram(source, { layoutMaxWidth: 1 })).toBe(renderStateDiagram(source))
275
- })
276
-
277
- test("preserves horizontal layouts that fit or have no finite width target", () => {
278
- const source = `stateDiagram-v2
279
- direction LR
280
- A --> B`
281
- const output = renderStateDiagram(source)
282
-
283
- expect(renderStateDiagram(source, { layoutMaxWidth: 120 })).toBe(output)
284
- expect(renderStateDiagram(source, { layoutMaxWidth: Number.POSITIVE_INFINITY })).toBe(output)
285
- })
286
-
287
- test("treats a single irreducibly wide state as soft overflow", () => {
288
- const label = "界".repeat(40)
289
- const output = renderStateDiagram(
290
- `stateDiagram-v2
291
- direction LR
292
- state "${label}" as Wide`,
293
- { layoutMaxWidth: 60 },
294
- )
295
-
296
- expect(renderedStateDimensions(output).width).toBeGreaterThan(60)
297
- expect(output).toContain(label)
298
- })
299
-
300
- test("does not mutate a parsed diagram when rendering with a direction override", () => {
301
- const diagram = parseMermaidStateDiagram(`stateDiagram-v2
302
- direction LR
303
- A --> B`)
304
-
305
- drawStateDiagramGrid(diagram, { direction: "RL" })
306
-
307
- expect(diagram.direction).toBe("LR")
308
- })
309
-
310
- test("places right-to-left transition labels between intact frames", () => {
311
- const output = renderStateDiagram(`stateDiagram-v2
312
- direction RL
313
- A --> B: reopen after a very detailed reviewer comment`)
314
-
315
- expect(output).toContain("╭───╮")
316
- expect(output.match(/╭───╮/g)?.length).toBe(2)
317
- expect(output).toContain("reopen after a very detailed reviewer comment")
318
- })
319
-
320
- test("keeps Unicode state labels inside their measured frame", () => {
321
- const output = renderStateDiagram(`stateDiagram-v2
322
- direction LR
323
- state "界" as Wide`)
324
- const widths = output.split("\n").map((line) => stringWidth(line))
325
-
326
- expect(new Set(widths).size).toBe(1)
327
- expect(output).toContain("界")
328
- })
329
-
330
- test("reserves horizontal room for long transition labels", () => {
331
- const label = "this transition label is much wider than the route"
332
- const output = renderStateDiagram(`stateDiagram-v2
333
- direction LR
334
- A --> B: ${label}`)
335
- const labelRow = output.split("\n").find((line) => line.includes(label))!
336
-
337
- expect(labelRow.match(/╭───╮/g)?.length).toBe(2)
338
- })
339
-
340
- test("renders every line of multiline transition labels", () => {
341
- const output = renderStateDiagram(`stateDiagram-v2
342
- direction LR
343
- A --> B: first<br/>second`)
344
-
345
- expect(output).toContain("first")
346
- expect(output).toContain("second")
347
- })
348
-
349
- test("keeps reciprocal multiline transition labels clear of routes", () => {
350
- const output = renderStateDiagram(`stateDiagram-v2
351
- [*] --> Running: create from base image
352
- Running --> Dormant: 📸 suspend hook fires<br/>(WE must call it on idle)
353
- Dormant --> Running: wake from snapshot image<br/>(apt installs restored!)
354
- Running --> Lost: 💥 sandbox dies BEFORE hook fires<br/>(crash, our bug, race)
355
- Lost --> Running: wake from LAST snapshot<br/>⚠ files since then GONE`)
356
- const labelLines = [
357
- "create from base image",
358
- "📸 suspend hook fires",
359
- "(WE must call it on idle)",
360
- "wake from snapshot image",
361
- "(apt installs restored!)",
362
- "💥 sandbox dies BEFORE hook fires",
363
- "(crash, our bug, race)",
364
- "wake from LAST snapshot",
365
- "⚠ files since then GONE",
366
- ]
367
-
368
- for (const line of labelLines) expect(output.split(line)).toHaveLength(2)
369
- expect(output).toMatchInlineSnapshot(`
370
- " create from base image ╭─────────╮
371
- ●───────────────────────▶│ Running │
372
- ╰──┬──────╯
373
- ▲ │ ▲ 💥 sandbox dies BEFORE hook fires
374
- ╭────────┼─┴───┼───────╮(crash, our bug, race)
375
- ▼ ╭────┼─────╯ ▼
376
- ╭──────┴──╮ │ ╭──────╮
377
- │ Dormant │ │ │ Lost │
378
- ╰─────────╯ │ ╰───┬──╯
379
- │ │
380
- 📸 suspend hook fires │ │ wake from LAST snapshot
381
- (WE must call it on idle)│ │ ⚠ files since then GONE
382
- ╰───────────────╯
383
- wake from snapshot image
384
- (apt installs restored!)"
385
- `)
386
- })
387
-
388
- test("renders a vertical state diagram", () => {
389
- const output = renderStateDiagram(`
390
- stateDiagram-v2
391
- direction TB
392
- [*] --> Cart
393
- Cart --> Payment: checkout
394
- Payment --> Complete
395
- `)
396
-
397
- expect(output).toMatchInlineSnapshot(`
398
- " ●
399
- │
400
- │
401
- │
402
- ▼
403
- ╭──────╮
404
- │ Cart │
405
- ╰───┬──╯
406
- │
407
- │ checkout
408
- │
409
- ▼
410
- ╭─────────╮
411
- │ Payment │
412
- ╰────┬────╯
413
- │
414
- │
415
- │
416
- ▼
417
- ╭──────────╮
418
- │ Complete │
419
- ╰──────────╯"
420
- `)
421
- })
422
-
423
- test("renders branched and backward transitions visibly", () => {
424
- const output = renderStateDiagram(`
425
- stateDiagram-v2
426
- direction LR
427
- [*] --> Idle
428
- Idle --> Loading: submit
429
- Loading --> Success: 200 OK
430
- Loading --> Error: timeout
431
- Error --> Loading: retry
432
- Success --> [*]
433
- `)
434
-
435
- expect(output).toMatchInlineSnapshot(`
436
- " ╭──────╮ submit ╭─────────╮ 200 OK ╭─────────╮
437
- ●────────────▶│ Idle ├────────────▶│ Loading ├────────────▶│ Success ├────────────▶◎
438
- ╰──────╯ ╰──┬──────╯ ╰─────────╯
439
- │ ▲
440
- timeout │ │
441
- ▼ │ retry
442
- ╭─────┴─╮
443
- │ Error │
444
- ╰───────╯"
445
- `)
446
- })
447
-
448
- test("captures converging labeled branches with long state names", () => {
449
- const output = renderStateDiagram(`stateDiagram-v2
450
- [*] --> Waiting
451
- state "Waiting for surface and workspace" as Waiting
452
- state "Surface bound only" as Surface
453
- state "Workspace bound only" as Workspace
454
- state "Ready with queued input" as Ready
455
- state "Agent activity requested" as Active
456
- Waiting --> Surface: InteractionSurfaceBound
457
- Waiting --> Workspace: WorkspaceBound
458
- Surface --> Ready: WorkspaceBound
459
- Workspace --> Ready: InteractionSurfaceBound
460
- Ready --> Active: AgentActivityRequested`)
461
-
462
- expect(output).toMatchInlineSnapshot(`
463
- " ╭───────────────────────────────────╮ InteractionSurfaceBound ╭────────────────────╮ WorkspaceBound ╭─────────────────────────╮ AgentActivityRequested ╭──────────────────────────╮
464
- ●────────────▶│ Waiting for surface and workspace ├────────────────────────▶│ Surface bound only ├───────────────▶│ Ready with queued input ├───────────────────────▶│ Agent activity requested │
465
- ╰───────────────┬───────────────────╯ ╰────────────────────╯ ╰─────────────────────────╯ ╰──────────────────────────╯
466
- │ WorkspaceBound ▲
467
- ╰──────────────────────────────────────────────────────╮ │
468
- │ InteractionSurfaceBound │
469
- ▼ ╭───────────────────────────────────────╯
470
- ╭─────────────┴────────╮
471
- │ Workspace bound only │
472
- ╰──────────────────────╯"
473
- `)
474
- })
475
-
476
- test("keeps raised note connectors off outgoing transitions", () => {
477
- const output = renderStateDiagram(`
478
- stateDiagram-v2
479
- direction LR
480
- [*] --> Idle
481
- Idle --> Loading: submit
482
- Loading --> Success: 200 OK
483
- Loading --> Error: timeout
484
- note right of Loading : waiting for response
485
- Error --> Loading: retry
486
- Success --> [*]
487
- `)
488
-
489
- expect(output).toMatchInlineSnapshot(`
490
- " ╔══════════════════════╗
491
- ╔═══╣ waiting for response ║
492
- ║ ╚══════════════════════╝
493
- ║
494
- ║
495
- ╭──────╮ submit ╭─────────╮ 200 OK ╭─────────╮
496
- ●────────────▶│ Idle ├────────────▶│ Loading ├────────────▶│ Success ├────────────▶◎
497
- ╰──────╯ ╰──┬──────╯ ╰─────────╯
498
- │ ▲
499
- timeout │ │
500
- ▼ │ retry
501
- ╭─────┴─╮
502
- │ Error │
503
- ╰───────╯"
504
- `)
505
- })
506
-
507
- test("places a composite note above an occupied right side", () => {
508
- const output = renderStateDiagram(`stateDiagram-v2
509
- [*] --> Processing
510
-
511
- state Processing {
512
- [*] --> Validate
513
- Validate --> Decision
514
- state Decision <<choice>>
515
- Decision --> Accepted: valid
516
- Decision --> Rejected: invalid
517
- Accepted --> [*]
518
- Rejected --> [*]
519
- }
520
-
521
- note right of Processing
522
- Validation and routing happen
523
- inside this composite state.
524
- end note
525
-
526
- Processing --> Complete
527
- Complete --> [*]`)
528
- const lines = output.split("\n")
529
- const noteBottom = lines.findIndex((line) => line.includes("╚═══════════════════════════════╝"))
530
- const completeRow = lines.findIndex((line) => line.includes(" Complete "))
531
-
532
- expect(noteBottom).toBeGreaterThanOrEqual(0)
533
- expect(noteBottom).toBeLessThan(completeRow)
534
- expect(lines.slice(noteBottom + 1, completeRow).every((line) => !line.includes("Complete"))).toBe(true)
535
- expect(lines).toHaveLength(20)
536
- })
537
-
538
- test("renders configurable line arrowheads", () => {
539
- const output = renderStateDiagram(
540
- `
541
- stateDiagram-v2
542
- direction LR
543
- [*] --> Idle
544
- Idle --> Loading: submit
545
- `,
546
- { arrowHeadStyle: "line" },
547
- )
548
-
549
- expect(output).toContain("→")
550
- expect(output).not.toContain("▶")
551
- })
552
-
553
- test("renders self transitions and choice branches", () => {
554
- const output = renderStateDiagram(`
555
- stateDiagram-v2
556
- direction LR
557
- state Decision <<choice>>
558
- [*] --> Editing
559
- Editing --> Editing: type
560
- Editing --> Decision: submit
561
- Decision --> Saved: ok
562
- Decision --> Error: fail
563
- Error --> Editing: retry
564
- `)
565
-
566
- expect(output).toMatchInlineSnapshot(`
567
- " ╭─────────╮ submit ok ╭───────╮
568
- ●────────────▶│ Editing ├────────────▶◆────────────▶│ Saved │
569
- ╰──┬──────╯ │ ╰───────╯
570
- ▲ │ ▲ type │ fail
571
- │ ╰────╯ │
572
- │ ▼
573
- │ ╭───────╮
574
- │ │ Error │
575
- │ ╰───┬───╯
576
- │ │
577
- │ │
578
- │ retry │
579
- ╰──────────────────────╯"
580
- `)
581
- })
582
-
583
- test("connects lower routed branches into choice junctions", () => {
584
- const output = renderStateDiagram(`stateDiagram-v2
585
- direction LR
586
- state Decision <<choice>>
587
- [*] --> Fork
588
- Fork --> Upper
589
- Fork --> Lower
590
- Upper --> Decision
591
- Lower --> Decision
592
- Decision --> Done
593
- Done --> [*]`)
594
-
595
- expect(output).toContain("Upper ├────────────▶◆────────────▶│ Done")
596
- })
597
-
598
- test("renders self transitions as loops in vertical diagrams", () => {
599
- const output = renderStateDiagram(`stateDiagram-v2
600
- direction TB
601
- Working --> Working: retry`)
602
-
603
- expectDiagram(output).toEqualDiagram(`
604
- ╭─────────╮
605
- │ Working │
606
- ╰──┬──────╯
607
- │ ▲ retry
608
- ╰────╯
609
- `)
610
- })
611
-
612
- test("renders self transitions from choice pseudo-states", () => {
613
- const output = renderStateDiagram(`stateDiagram-v2
614
- direction LR
615
- state Decision <<choice>>
616
- Decision --> Decision: reconsider`)
617
-
618
- expect(output).toContain("◆")
619
- expect(output).toContain("reconsider")
620
- expect(output.split("\n").filter((line) => line.trim())).toHaveLength(3)
621
- })
622
-
623
- test.each(["LR", "RL"] as const)("trims leading rows from standalone %s choices", (direction) => {
624
- const output = renderStateDiagram(`stateDiagram-v2
625
- direction ${direction}
626
- state Decision <<choice>>`)
627
-
628
- expect(output).toBe("◆")
629
- })
630
-
631
- test("renders parallel transitions without losing labels", () => {
632
- const horizontal = renderStateDiagram(`stateDiagram-v2
633
- direction LR
634
- A --> B: first
635
- A --> B: second`)
636
- const vertical = renderStateDiagram(`stateDiagram-v2
637
- direction TB
638
- A --> B: first
639
- A --> B: second`)
640
-
641
- expect(horizontal).toContain("first")
642
- expect(horizontal).toContain("second")
643
- expect(vertical).toContain("first")
644
- expect(vertical).toContain("second")
645
- })
646
-
647
- test("renders cyclic same-rank vertical parallels with a note", () => {
648
- const output = renderStateDiagram(`stateDiagram-v2
649
- direction TD
650
- state "Node S13_0" as S13_0
651
- state "Node S13_1" as S13_1
652
- state "Node S13_2" as S13_2
653
- state "Node S13_3" as S13_3
654
- state "Node S13_4" as S13_4
655
- S13_0 --> S13_1: state_edge_13_0
656
- S13_1 --> S13_2: state_edge_13_1
657
- S13_2 --> S13_3: state_edge_13_2
658
- S13_3 --> S13_4: state_edge_13_3
659
- S13_0 --> S13_2: state_edge_13_4
660
- S13_4 --> S13_1: state_edge_13_5
661
- S13_2 --> S13_0: state_edge_13_6
662
- S13_1 --> S13_2: state_edge_13_7
663
- S13_3 --> S13_2: state_edge_13_8
664
- S13_3 --> S13_0: state_edge_13_9
665
- S13_0 --> S13_0: state_edge_13_10
666
- note left of S13_0: state_note_13_0`)
667
-
668
- for (const index of [0, 1, 2, 3, 4]) expect(output).toContain(`Node S13_${index}`)
669
- for (const index of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) expect(output).toContain(`state_edge_13_${index}`)
670
- expect(output).toContain("state_note_13_0")
671
- })
672
-
673
- test("preserves every state in a routed multi-note vertical graph", () => {
674
- const source = `stateDiagram-v2
675
- direction TD
676
- state "Node S21_0" as S21_0
677
- state "Node S21_1" as S21_1
678
- state "Node S21_2" as S21_2
679
- state "Node S21_3" as S21_3
680
- state "Node S21_4" as S21_4
681
- state "Node S21_5" as S21_5
682
- S21_0 --> S21_1: state_edge_21_0
683
- S21_1 --> S21_2: state_edge_21_1
684
- S21_2 --> S21_3: state_edge_21_2
685
- S21_3 --> S21_4: state_edge_21_3
686
- S21_4 --> S21_5: state_edge_21_4
687
- S21_4 --> S21_5: state_edge_21_5
688
- S21_2 --> S21_4: state_edge_21_6
689
- S21_3 --> S21_1: state_edge_21_7
690
- note right of S21_1: state_note_21_0
691
- note left of S21_0: state_note_21_1
692
- note left of S21_4: state_note_21_2`
693
- const output = renderStateDiagram(source)
694
-
695
- for (const index of [0, 1, 2, 3, 4, 5]) expect(output).toContain(`Node S21_${index}`)
696
- for (const index of [0, 1, 2, 3, 4, 5, 6, 7]) expect(output).toContain(`state_edge_21_${index}`)
697
- for (const index of [0, 1, 2]) expect(output).toContain(`state_note_21_${index}`)
698
- expectCompleteStateDiagram(source, output)
699
- })
700
-
701
- test("renders every note in a cyclic vertical graph", () => {
702
- const source = `stateDiagram-v2
703
- direction TB
704
- state "Node S27_0" as S27_0
705
- state "Node S27_1" as S27_1
706
- state "Node S27_2" as S27_2
707
- state "Node S27_3" as S27_3
708
- state "Node S27_4" as S27_4
709
- state "Node S27_5" as S27_5
710
- S27_0 --> S27_1: state_edge_27_0
711
- S27_1 --> S27_2: state_edge_27_1
712
- S27_2 --> S27_3: state_edge_27_2
713
- S27_3 --> S27_4: state_edge_27_3
714
- S27_4 --> S27_5: state_edge_27_4
715
- S27_1 --> S27_0: state_edge_27_5
716
- S27_5 --> S27_1: state_edge_27_6
717
- S27_2 --> S27_1: state_edge_27_7
718
- S27_1 --> S27_5: state_edge_27_8
719
- note left of S27_5: state_note_27_0
720
- note right of S27_0: state_note_27_1
721
- note left of S27_3: state_note_27_2`
722
- const output = renderStateDiagram(source)
723
-
724
- for (const index of [0, 1, 2, 3, 4, 5]) expect(output).toContain(`Node S27_${index}`)
725
- for (const index of [0, 1, 2, 3, 4, 5, 6, 7, 8]) expect(output).toContain(`state_edge_27_${index}`)
726
- for (const index of [0, 1, 2]) expect(output).toContain(`state_note_27_${index}`)
727
- expectCompleteStateDiagram(source, output)
728
- })
729
-
730
- test("places exhausted notes on deterministic exterior lanes", () => {
731
- const source = `stateDiagram-v2
732
- direction TD
733
- state "Node S33_0" as S33_0
734
- state "Node S33_1" as S33_1
735
- state "Node S33_2" as S33_2
736
- state "Node S33_3" as S33_3
737
- state "Node S33_4" as S33_4
738
- state "Node S33_5" as S33_5
739
- state "Node S33_6" as S33_6
740
- S33_0 --> S33_1: state_edge_33_0
741
- S33_1 --> S33_2: state_edge_33_1
742
- S33_2 --> S33_3: state_edge_33_2
743
- S33_3 --> S33_4: state_edge_33_3
744
- S33_4 --> S33_5: state_edge_33_4
745
- S33_5 --> S33_6: state_edge_33_5
746
- S33_6 --> S33_4: state_edge_33_6
747
- S33_2 --> S33_4: state_edge_33_7
748
- S33_3 --> S33_3: state_edge_33_8
749
- note left of S33_2: state_note_33_0
750
- note left of S33_6: state_note_33_1`
751
- const output = renderStateDiagram(source)
752
- const exhaustedBudget = { remaining: 0 }
753
- const layout = createStateDiagramLayout(prepareVisibleStateDiagram(parseMermaidStateDiagram(source)), {
754
- minStateGap: 5,
755
- searchBudget: exhaustedBudget,
756
- })
757
-
758
- for (const index of [0, 1, 2, 3, 4, 5, 6]) expect(output).toContain(`Node S33_${index}`)
759
- for (const index of [0, 1, 2, 3, 4, 5, 6, 7, 8]) expect(output).toContain(`state_edge_33_${index}`)
760
- for (const index of [0, 1]) expect(output).toContain(`state_note_33_${index}`)
761
- expect(layout.noteBounds).toHaveLength(2)
762
- expect(exhaustedBudget.remaining).toBe(0)
763
- expectCompleteStateDiagram(source, output)
764
- })
765
-
766
- test("separates reciprocal RL branches sharing a parallel lane", () => {
767
- const source = `stateDiagram-v2
768
- direction RL
769
- state "Node S237_0" as S237_0
770
- state "Node S237_1" as S237_1
771
- state "Node S237_2" as S237_2
772
- state "Node S237_3" as S237_3
773
- state "Node S237_4" as S237_4
774
- state "Node S237_5" as S237_5
775
- S237_0 --> S237_1: state_edge_237_0
776
- S237_1 --> S237_2: state_edge_237_1
777
- S237_2 --> S237_3: state_edge_237_2
778
- S237_3 --> S237_4: state_edge_237_3
779
- S237_4 --> S237_5: state_edge_237_4
780
- S237_1 --> S237_5: state_edge_237_5
781
- S237_4 --> S237_5: state_edge_237_6
782
- S237_4 --> S237_0: state_edge_237_7
783
- S237_0 --> S237_4: state_edge_237_8
784
- note right of S237_1: state_note_237_0
785
- note left of S237_5: state_note_237_1
786
- note right of S237_2: state_note_237_2`
787
- const output = renderStateDiagram(source)
788
-
789
- for (const index of [0, 1, 2, 3, 4, 5]) expect(output).toContain(`Node S237_${index}`)
790
- for (const index of [0, 1, 2, 3, 4, 5, 6, 7, 8]) expect(output).toContain(`state_edge_237_${index}`)
791
- for (const index of [0, 1, 2]) expect(output).toContain(`state_note_237_${index}`)
792
- expectCompleteStateDiagram(source, output)
793
- })
794
-
795
- test("separates labels on four parallel vertical transitions", () => {
796
- const output = renderStateDiagram(`stateDiagram-v2
797
- direction TB
798
- A --> B: one
799
- A --> B: two
800
- A --> B: three
801
- A --> B: four`)
802
-
803
- expect(output).not.toContain("twothree")
804
- for (const label of ["one", "two", "three", "four"]) {
805
- expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
806
- }
807
- })
808
-
809
- test("grows parallel vertical diagrams by the maximum label width rather than their sum", () => {
810
- const render = (labels: readonly string[]) =>
811
- renderStateDiagram(`stateDiagram-v2
812
- direction TB
813
- ${labels.map((label) => ` A --> B: ${label}`).join("\n")}`)
814
- const shortLabels = ["one", "two", "three"]
815
- const longLabels = [
816
- "alpha route label that is deliberately long",
817
- "beta route label that is deliberately long",
818
- "gamma route label that is deliberately long",
819
- ]
820
- const width = (output: string) => Math.max(...output.split("\n").map((line) => stringWidth(line)))
821
- const labelGrowth =
822
- Math.max(...longLabels.map((label) => stringWidth(label))) -
823
- Math.max(...shortLabels.map((label) => stringWidth(label)))
824
-
825
- expect(width(render(longLabels)) - width(render(shortLabels))).toBeLessThanOrEqual(labelGrowth + 2)
826
- })
827
-
828
- test("keeps audited parallel labels clear of frames and rails", () => {
829
- const output = renderStateDiagram(`stateDiagram-v2
830
- direction TB
831
- A --> B: alpha route label that is deliberately long
832
- A --> B: beta route label that is deliberately long
833
- A --> B: gamma route label that is deliberately long`)
834
-
835
- expect(output).toMatchInlineSnapshot(`
836
- "╭───╮ alpha route label that is deliberately long
837
- │ A ├───┬──╮
838
- ╰─┬─╯ │ │ gamma route label that is deliberately long
839
- │ │ │
840
- │ │ │ beta route label that is deliberately long
841
- │ │ │
842
- ▼ │ │
843
- ╭───╮ │ │
844
- │ B │◀──┴──╯
845
- ╰───╯"
846
- `)
847
- })
848
-
849
- test("keeps audited repeated self-transition lanes distinct and readable", () => {
850
- const output = renderStateDiagram(`stateDiagram-v2
851
- direction LR
852
- A --> A: one
853
- A --> A: two
854
- A --> A: three`)
855
-
856
- expect(output).toMatchInlineSnapshot(`
857
- "╭───╮
858
- │ A │
859
- ╰─┬─╯
860
- │ ▲ ▲ ▲
861
- ├──╯ │ │
862
- │ │ │
863
- │ one │ │
864
- ├──────╯ │
865
- │ │
866
- │ two │ three
867
- ╰──────────╯"
868
- `)
869
- })
870
-
871
- test("expands composites around self-transition labels without engulfing external states", () => {
872
- const source = `stateDiagram-v2
873
- direction LR
874
- state Outer {
875
- A --> A: loop-0
876
- A --> A: loop-1
877
- A --> A: loop-2
878
- }
879
- A --> C`
880
- const drawing = createStateDiagramDrawing(parseMermaidStateDiagram(source))
881
- const outer = drawing.layout.compositeBounds.get("Outer")!
882
- const external = drawing.layout.bounds.get("C")!
883
- const output = drawing.grid.toString({ trimTop: true, trimBottom: true })
884
-
885
- expect(
886
- external.left < outer.left + outer.width &&
887
- external.left + external.width > outer.left &&
888
- external.top < outer.top + outer.height &&
889
- external.top + external.height > outer.top,
890
- ).toBe(false)
891
- for (const plan of drawing.transitionPlans.filter(
892
- (plan) => plan.route.transition.from === plan.route.transition.to,
893
- )) {
894
- expect(plan.label).toBeDefined()
895
- expect(plan.label!.x).toBeGreaterThan(outer.left)
896
- expect(plan.label!.y).toBeGreaterThan(outer.top)
897
- expect(plan.label!.x + Math.max(...plan.label!.lines.map((line) => stringWidth(line)))).toBeLessThan(
898
- outer.left + outer.width,
899
- )
900
- expect(plan.label!.y + plan.label!.lines.length).toBeLessThan(outer.top + outer.height)
901
- }
902
- for (const label of ["loop-0", "loop-1", "loop-2"]) expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
903
- })
904
-
905
- test("keeps audited nested note connectors direct and inside every frame", () => {
906
- const output = renderStateDiagram(`stateDiagram-v2
907
- direction TB
908
- state Outer {
909
- state Inner {
910
- A --> B: down
911
- B --> A: up
912
- note right of B: note
913
- }
914
- }`)
915
-
916
- expect(output).toMatchInlineSnapshot(`
917
- "╭─ Outer ───────────────╮
918
- │ │
919
- │ ╭─ Inner ───────────╮ │
920
- │ │ │ │
921
- │ │ ╭───╮ │ │
922
- │ │▶│ A │ │ │
923
- │ ││╰─┬─╯ │ │
924
- │ ││ │ │ │
925
- │ ││ │ down │ │
926
- │ ││ │ │ │
927
- │ ││ ▼ │ │
928
- │ ││╭───╮ ╔══════╗ │ │
929
- │ │╰┤ B │════╣ note ║ │ │
930
- │ │ ╰───╯ ╚══════╝ │ │
931
- │ │up │ │
932
- │ ╰───────────────────╯ │
933
- │ │
934
- ╰───────────────────────╯"
935
- `)
936
- })
937
-
938
- test("leaves frame gaps where external transitions cross nested composite boundaries", () => {
939
- const drawing = createStateDiagramDrawing(
940
- parseMermaidStateDiagram(`stateDiagram-v2
941
- direction LR
942
- state Session {
943
- [*] --> Open
944
- state Open {
945
- [*] --> Clean
946
- }
947
- }
948
- [*] --> Session: hydrate`),
949
- )
950
- const hydrate = drawing.transitionPlans.find((plan) => plan.route.transition.label === "hydrate")!
951
- const crossings = hydrate.cells.filter((cell) =>
952
- [...drawing.layout.compositeBounds.values()].some((bounds) => {
953
- const right = bounds.left + bounds.width - 1
954
- const bottom = bounds.top + bounds.height - 1
955
- return (
956
- ((cell.x === bounds.left || cell.x === right) && cell.y >= bounds.top && cell.y <= bottom) ||
957
- ((cell.y === bounds.top || cell.y === bottom) && cell.x >= bounds.left && cell.x <= right)
958
- )
959
- }),
960
- )
961
-
962
- expect(crossings).toHaveLength(2)
963
- for (const cell of crossings) expect(drawing.grid.getCell(cell.x, cell.y)?.char).toBe("─")
964
- })
965
-
966
- test("keeps explicit choices visible in choice-only cycles", () => {
967
- const output = renderStateDiagram(`stateDiagram-v2
968
- direction TB
969
- state One <<choice>>
970
- state Two <<choice>>
971
- state Three <<choice>>
972
- One --> Two: clockwise
973
- Two --> Three: clockwise
974
- Three --> One: clockwise`)
975
-
976
- expect(output.match(/◆/g)).toHaveLength(3)
977
- })
978
-
979
- test("routes dense horizontal transitions around unrelated states", () => {
980
- const output = renderStateDiagram(`stateDiagram-v2
981
- direction LR
982
- A --> B: ab
983
- A --> C: ac
984
- A --> D: ad
985
- B --> A: ba
986
- B --> C: bc
987
- B --> D: bd
988
- C --> A: ca
989
- C --> B: cb
990
- C --> D: cd
991
- D --> A: da
992
- D --> B: db
993
- D --> C: dc`)
994
-
995
- for (const state of ["A", "B", "C", "D"]) expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
996
- })
997
-
998
- test("keeps dense vertical fan routes out of sibling states", () => {
999
- const output = renderStateDiagram(`stateDiagram-v2
1000
- direction TB
1001
- state "Alpha" as A
1002
- state "Beta" as B
1003
- state "Gamma store" as C
1004
- state "Delta notifier" as D
1005
- A --> B
1006
- A --> C
1007
- A --> D
1008
- B --> A: back
1009
- B --> D: across`)
1010
-
1011
- for (const text of ["Alpha", "Beta", "Gamma store", "Delta notifier", "back", "across"]) {
1012
- expect(output).toContain(text)
1013
- }
1014
- })
1015
-
1016
- test("routes parallel transitions around vertically offset states", () => {
1017
- const output = renderStateDiagram(`stateDiagram-v2
1018
- A --> B: first<br/>line two
1019
- A --> B: second<br/>another line
1020
- B --> A: return<br/>with details`)
1021
-
1022
- expect(output).toContain(" A ")
1023
- expect(output).toContain("│ B │")
1024
- expect(output).toContain("first")
1025
- expect(output).toContain("second")
1026
- expect(output).toContain("return")
1027
- })
1028
-
1029
- test("keeps independent overlapping feedback labels and paths distinct", () => {
1030
- const content = (direction: "LR" | "RL") => `stateDiagram-v2
1031
- direction ${direction}
1032
- A --> B: advance
1033
- B --> C: continue
1034
- C --> D: finish
1035
- C --> A: reset A
1036
- D --> B: reset B`
1037
-
1038
- for (const direction of ["LR", "RL"] as const) {
1039
- const output = renderStateDiagram(content(direction))
1040
- expect(output).toContain("reset A")
1041
- expect(output).toContain("reset B")
1042
- expect(output).not.toContain("res│t")
1043
- }
1044
- })
1045
-
1046
- test("keeps independent internal feedback paths inside their composite frame", () => {
1047
- const output = renderStateDiagram(`stateDiagram-v2
1048
- direction LR
1049
- state Runtime {
1050
- A --> B: advance
1051
- B --> C: continue
1052
- C --> D: finish
1053
- C --> A: reset A
1054
- D --> B: reset B
1055
- }`)
1056
- const lines = output.split("\n")
1057
- const frameTop = lines.findIndex((line) => line.includes("Runtime"))
1058
- const upperFeedback = lines.findIndex((line) => line.includes("reset B"))
1059
-
1060
- expect(upperFeedback).toBeGreaterThan(frameTop)
1061
- expect(output).toContain("reset A")
1062
- expect(output).not.toContain("res│t")
1063
- })
1064
-
1065
- test("places notes away from independent feedback corridors", () => {
1066
- const output = renderStateDiagram(`stateDiagram-v2
1067
- direction LR
1068
- A --> B: advance
1069
- B --> C: continue
1070
- C --> D: finish
1071
- C --> A: reset A
1072
- D --> B: reset B
1073
- note right of B : note beside B`)
1074
-
1075
- expect(output).toContain("note beside B")
1076
- expect(output).toContain("reset B")
1077
- expect(output).not.toContain("╭─║")
1078
- expect(output).not.toContain("║──")
1079
- })
1080
-
1081
- test("places notes away from transition routes and labels", () => {
1082
- const output = renderStateDiagram(`stateDiagram-v2
1083
- direction LR
1084
- A --> B: proceed only after validation
1085
- note left of B: blocking note`)
1086
-
1087
- expect(output).toContain("proceed only after validation")
1088
- expect(output).toContain("blocking note")
1089
- expect(output.match(/ A | B /g)).toHaveLength(2)
1090
- expect(output).toMatch(/[╠╣]═/)
1091
- })
1092
-
1093
- test("keeps adjacent note connectors out of other notes", () => {
1094
- const output = renderStateDiagram(`stateDiagram-v2
1095
- direction LR
1096
- A --> B: advance
1097
- B --> C: continue
1098
- note right of B: first note
1099
- note right of B: second note
1100
- note left of C: left note`)
1101
-
1102
- for (const text of ["advance", "continue", "first note", "second note", "left note"]) {
1103
- expect(output).toContain(text)
1104
- }
1105
- expect(output).not.toContain("╝═════╗")
1106
- })
1107
-
1108
- test("keeps note connectors out of vertical loop and transition labels", () => {
1109
- const output = renderStateDiagram(`stateDiagram-v2
1110
- direction TB
1111
- state "Processing Ω<br/>phase two" as Processing
1112
- state "Result ≥ threshold" as Result
1113
- Ready --> Processing: first
1114
- Ready --> Processing: duplicate
1115
- Processing --> Ready: restore
1116
- Processing --> Processing: heartbeat
1117
- Processing --> Result: result ≥ 1
1118
- Result --> Ready: reopen
1119
- note right of Processing: Unicode note 界`)
1120
-
1121
- for (const text of ["heartbeat", "result ≥ 1", "Unicode note 界"]) {
1122
- expect(output).toContain(text)
1123
- }
1124
- expect(output).not.toContain("hea║tbeat")
1125
- expect(output).not.toContain("result║≥ 1")
1126
- })
1127
-
1128
- test("keeps nested state labels clear of note connectors", () => {
1129
- const output = renderStateDiagram(`stateDiagram-v2
1130
- direction LR
1131
- state "Open document" as Open {
1132
- [*] --> Clean: load
1133
- Clean --> Dirty: edit
1134
- Dirty --> Clean: save
1135
- }
1136
- note right of Dirty: unsaved changes`)
1137
-
1138
- for (const text of ["Open document", "Clean", "Dirty", "load", "edit", "save", "unsaved changes"]) {
1139
- expect(output).toContain(text)
1140
- }
1141
- })
1142
-
1143
- test("keeps duplicate feedback labels away from an independent return path", () => {
1144
- const output = renderStateDiagram(`stateDiagram-v2
1145
- direction LR
1146
- A --> B
1147
- B --> C
1148
- C --> D
1149
- C --> A: ca
1150
- D --> B: db1
1151
- D --> B: db2`)
1152
-
1153
- expect(output).toContain("ca")
1154
- expect(output).toContain("db1")
1155
- expect(output).toContain("db2")
1156
- expect(output).not.toContain("c│")
1157
- })
1158
-
1159
- test("renders composite state containers", () => {
1160
- const output = renderStateDiagram(`
1161
- stateDiagram-v2
1162
- direction LR
1163
- state Authenticated {
1164
- [*] --> Idle
1165
- Idle --> Editing: open
1166
- Editing --> [*]: save
1167
- }
1168
- `)
1169
-
1170
- expect(output).toMatchInlineSnapshot(`
1171
- "╭─ Authenticated ──────────────────────────────────────────────╮
1172
- │ │
1173
- │ ╭──────╮ open ╭─────────╮ save │
1174
- │ ─────────────▶│ Idle ├────────────▶│ Editing ├────────────── │
1175
- │ ╰──────╯ ╰─────────╯ │
1176
- │ │
1177
- ╰──────────────────────────────────────────────────────────────╯"
1178
- `)
1179
- })
1180
-
1181
- test("routes transitions entering and leaving composite states through scoped markers", () => {
1182
- const content = `
1183
- stateDiagram-v2
1184
- direction LR
1185
- [*] --> Authenticated: login
1186
- state Authenticated {
1187
- [*] --> Idle
1188
- Idle --> Editing: open
1189
- Editing --> [*]: save
1190
- }
1191
- Authenticated --> [*]: logout
1192
- `
1193
- const diagram = parseMermaidStateDiagram(content)
1194
- const output = renderStateDiagram(content)
1195
-
1196
- expect(diagram.transitions).toContainEqual({
1197
- from: "__start",
1198
- to: "Authenticated.__start",
1199
- label: "login",
1200
- })
1201
- expect(diagram.transitions).toContainEqual({
1202
- from: "Authenticated.__end",
1203
- to: "__end",
1204
- label: "logout",
1205
- })
1206
- expect(output).toMatchInlineSnapshot(`
1207
- " ╭─ Authenticated ──────────────────╮
1208
- │ │ save
1209
- login │ ╭──────╮ open ╭─────────╮ │ logout
1210
- ●────────────▶│ Idle ├────────────▶│ Editing ├────────────▶◎
1211
- │ ╰──────╯ ╰─────────╯ │
1212
- │ │
1213
- ╰──────────────────────────────────╯"
1214
- `)
1215
- })
1216
-
1217
- test("keeps nested composite entry and exit routes within the outer frame height", () => {
1218
- const output = renderStateDiagram(`stateDiagram-v2
1219
- state Session {
1220
- [*] --> Open
1221
- state Open {
1222
- [*] --> Clean
1223
- Clean --> Dirty: edit
1224
- Dirty --> Clean: save
1225
- }
1226
- note right of Open: document lifecycle
1227
- Open --> [*]: close
1228
- }
1229
- [*] --> Session
1230
- Session --> [*]`)
1231
- const lines = output.split("\n")
1232
- const outerFrameTop = lines.find((line) => line.includes("Session"))!
1233
- const frameLeft = outerFrameTop.indexOf("╭")
1234
- const frameRight = outerFrameTop.lastIndexOf("╮")
1235
- const outerFrameBottom = lines.findIndex((line) => line[frameLeft] === "╰" && line[frameRight] === "╯")
1236
- const startColumn = lines.find((line) => line.includes("●"))!.indexOf("●")
1237
- const endColumn = lines.find((line) => line.includes("◎"))!.indexOf("◎")
1238
-
1239
- expect(outerFrameBottom).toBeGreaterThan(0)
1240
- expect(startColumn).toBeLessThan(frameLeft)
1241
- expect(endColumn).toBeGreaterThan(frameRight)
1242
- expect(lines.slice(outerFrameBottom + 1).every((line) => line.trim() === "")).toBe(true)
1243
- expect(output).toContain("Open")
1244
- expect(output).toContain("document lifecycle")
1245
- expect(output).toContain("close")
1246
- })
1247
-
1248
- test("renders notes attached to states", () => {
1249
- const output = renderStateDiagram(`
1250
- stateDiagram-v2
1251
- direction LR
1252
- [*] --> Idle
1253
- Idle --> Loading: submit
1254
- note right of Loading : waits for response
1255
- `)
1256
-
1257
- expect(output).toMatchInlineSnapshot(`
1258
- " ╭──────╮ submit ╭─────────╮ ╔════════════════════╗
1259
- ●────────────▶│ Idle ├────────────▶│ Loading │════╣ waits for response ║
1260
- ╰──────╯ ╰─────────╯ ╚════════════════════╝"
1261
- `)
1262
- })
1263
-
1264
- test("keeps composite-to-choice elbows connected", () => {
1265
- const output = renderStateDiagram(`stateDiagram-v2
1266
- [*] --> Authenticated
1267
- state Authenticated {
1268
- [*] --> Editing
1269
- Editing --> Ready
1270
- }
1271
- note right of Editing
1272
- Draft changes
1273
- end note
1274
- Authenticated --> Decision
1275
- state Decision <<choice>>
1276
- Decision --> [*]`)
1277
-
1278
- expect(output).toContain("╰─────────────▼")
1279
- expect(output).toContain("◆────────────▶◎")
1280
- })
1281
-
1282
- test("keeps vertical branch labels from overwriting state labels", () => {
1283
- const output = renderStateDiagram(`stateDiagram-v2
1284
- direction TB
1285
- state "Branch root" as Root
1286
- state "Upper branch" as Upper
1287
- state "Lower branch" as Lower
1288
- state "Merged branch" as Merge
1289
- Root --> Upper: branch-up
1290
- Root --> Lower: branch-down
1291
- Upper --> Merge: merge-up
1292
- Lower --> Merge: merge-down
1293
- Merge --> Root: branch-feedback`)
1294
-
1295
- for (const text of [
1296
- "Branch root",
1297
- "Upper branch",
1298
- "Lower branch",
1299
- "Merged branch",
1300
- "branch-up",
1301
- "branch-down",
1302
- "merge-up",
1303
- "merge-down",
1304
- "branch-feedback",
1305
- ]) {
1306
- expect(output).toContain(text)
1307
- }
1308
- })
1309
-
1310
- test("routes vertical branch feedback around sibling state bodies", () => {
1311
- const output = renderStateDiagram(`stateDiagram-v2
1312
- direction TB
1313
- [*] --> Root
1314
- Root --> A
1315
- Root --> B
1316
- A --> Merge
1317
- B --> Merge
1318
- Merge --> A: retry`)
1319
-
1320
- for (const state of ["Root", "A", "B", "Merge"]) {
1321
- expect(output.match(new RegExp(`\\b${state}\\b`, "g"))).toHaveLength(1)
1322
- }
1323
- expect(output).toContain("│ B │")
1324
- expect(output).toContain("retry")
1325
- })
1326
-
1327
- test("keeps lifecycle states intact around branches and feedback", () => {
1328
- const output = renderStateDiagram(`stateDiagram-v2
1329
- [*] --> Idle
1330
- Idle --> MailboxPending: enqueue + setAlarm
1331
- MailboxPending --> PromptSubmitted: drain mailbox
1332
- PromptSubmitted --> Polling: prompt admitted
1333
- Polling --> Polling: execution still active
1334
- Polling --> Completed: terminal log event
1335
- Polling --> Polling: retry after transient failure
1336
- Completed --> Idle: final Slack projection
1337
- Idle --> Expired: 30 days inactive
1338
- Expired --> [*]: delete SQLite state`)
1339
-
1340
- for (const state of ["Idle", "MailboxPending", "PromptSubmitted", "Polling", "Completed", "Expired"]) {
1341
- expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
1342
- }
1343
- })
1344
-
1345
- test("keeps composite titles intact under reciprocal composite routes", () => {
1346
- const source = `stateDiagram-v2
1347
- direction LR
1348
- state FirstGroup {
1349
- [*] --> FirstInner
1350
- FirstInner --> [*]: first-out
1351
- }
1352
- state SecondGroup {
1353
- [*] --> SecondInner
1354
- SecondInner --> [*]: second-out
1355
- }
1356
- FirstGroup --> SecondGroup: group-next
1357
- SecondGroup --> FirstGroup: group-back`
1358
-
1359
- for (const direction of ["LR", "TB"] as const) {
1360
- const drawing = createStateDiagramDrawing(parseMermaidStateDiagram(source), { direction })
1361
- const output = drawing.grid.toString({ trimTop: true, trimBottom: true })
1362
- for (const id of ["FirstGroup", "SecondGroup"]) {
1363
- const bounds = drawing.layout.compositeBounds.get(id)!
1364
- const right = bounds.left + bounds.width - 1
1365
- const bottom = bounds.top + bounds.height - 1
1366
- const boundaryStyles = [
1367
- ...Array.from({ length: bounds.height - 2 }, (_, offset) => [
1368
- drawing.grid.getCell(bounds.left, bounds.top + offset + 1)?.style,
1369
- drawing.grid.getCell(right, bounds.top + offset + 1)?.style,
1370
- ]).flat(),
1371
- ...Array.from(
1372
- { length: bounds.width - 2 },
1373
- (_, offset) => drawing.grid.getCell(bounds.left + offset + 1, bottom)?.style,
1374
- ),
1375
- ]
1376
-
1377
- expect(output.match(new RegExp(id, "g"))).toHaveLength(1)
1378
- expect(
1379
- boundaryStyles.every(
1380
- (style) => style === "composite" || style === "transition" || style?.startsWith("stateDepartureRamp"),
1381
- ),
1382
- ).toBe(true)
1383
- }
1384
- }
1385
- })
1386
- })