@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,360 +1,360 @@
1
- import { BorderChars, type BorderCharacters, type BorderStyle } from "@opentui/core"
2
- import { DiagramCanvas, DiagramCanvasSizeError, type DiagramCanvasCell } from "../core/canvas.js"
3
- import { directionBetween, orthogonalPathPoints, type DiagramDirection } from "../core/geometry.js"
4
- import {
5
- diagramArrowHead,
6
- diagramLineGlyph,
7
- drawDiagramFrame,
8
- fillDiagramFrameInterior,
9
- mergeDiagramLineGlyph,
10
- } from "../core/drawing.js"
11
- import { DIAGRAM_LABEL_PADDING_X, diagramTextWidth } from "../core/text.js"
12
- import {
13
- createStateDiagramLayout,
14
- expandCompositeBoundsForFeedback,
15
- expandCompositeBoundsForInternalTransitions,
16
- separateExternalBoundsFromComposites,
17
- translateStateDiagramLayout,
18
- type StateDiagramBoxBounds as BoxBounds,
19
- type StateDiagramNoteBounds as StateNoteBounds,
20
- } from "./layout.js"
21
- import { stateDiagramNoteConnector } from "./note.js"
22
- import { DEFAULT_STATE_ARROW_HEAD_STYLE, DEFAULT_STATE_BORDER_STYLE, normalizeStateMinStateGap } from "./options.js"
23
- import type { StateGrid } from "./render-grid.js"
24
- import {
25
- createStateTransitionJunctionPlans,
26
- createStateTransitionRenderPlans,
27
- measureStateTransitionLabel,
28
- type StateTransitionRenderPlan,
29
- } from "./routing.js"
30
- import { createStateSearchBudget } from "./search.js"
31
- import { NOTE_CONNECTOR_RAMP_STYLES, STATE_DEPARTURE_RAMP_STYLES } from "./style.js"
32
- import type {
33
- StateCellStyle,
34
- StateDiagram,
35
- StateDiagramArrowHeadStyle,
36
- StateDiagramRenderOptions,
37
- StateDiagramState,
38
- } from "./types.js"
39
- import { isHiddenCompositeMarker, prepareVisibleStateDiagram } from "./visible-model.js"
40
-
41
- type StateCell = DiagramCanvasCell<StateCellStyle>
42
-
43
- function translateTransitionPlans(
44
- plans: readonly StateTransitionRenderPlan[],
45
- dx: number,
46
- dy: number,
47
- ): StateTransitionRenderPlan[] {
48
- return plans.map((plan) => ({
49
- ...plan,
50
- cells: plan.cells.map((cell) => ({ ...cell, x: cell.x + dx, y: cell.y + dy })),
51
- path: plan.path.map(([x, y]) => [x + dx, y + dy]),
52
- label: plan.label ? { ...plan.label, x: plan.label.x + dx, y: plan.label.y + dy } : undefined,
53
- }))
54
- }
55
-
56
- function makeGrid(width: number, height: number): StateGrid {
57
- return new DiagramCanvas(width, height, {
58
- mergeCell: (existing, incoming): StateCell => {
59
- const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
60
- const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
61
- const shouldMerge = incomingIsTransition && existingIsTransition
62
- return {
63
- ...incoming,
64
- char: shouldMerge
65
- ? (mergeDiagramLineGlyph(existing.char, incoming.char, "rounded") ?? incoming.char)
66
- : incoming.char,
67
- }
68
- },
69
- })
70
- }
71
-
72
- function setCell(grid: StateGrid, x: number, y: number, char: string, style?: StateCellStyle): void {
73
- grid.setCell(x, y, char, style)
74
- }
75
-
76
- function setText(grid: StateGrid, x: number, y: number, text: string, style?: StateCellStyle): void {
77
- grid.setText(x, y, text, style)
78
- }
79
-
80
- function drawBox(
81
- grid: StateGrid,
82
- state: StateDiagramState,
83
- bounds: BoxBounds,
84
- lines: string[],
85
- borderStyle: BorderStyle,
86
- ): void {
87
- if (isHiddenCompositeMarker(state)) return
88
-
89
- if (state.kind !== "state") {
90
- setCell(grid, bounds.left, bounds.top, state.label, state.kind)
91
- return
92
- }
93
- fillDiagramFrameInterior(bounds, (x, y) => setCell(grid, x, y, " ", "state"))
94
- drawStateFrame(grid, bounds, BorderChars[borderStyle], "stateBorder")
95
- lines.forEach((line, index) => {
96
- setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "state")
97
- })
98
- }
99
-
100
- function drawStateFrame(grid: StateGrid, bounds: BoxBounds, chars: BorderCharacters, style: StateCellStyle): void {
101
- drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
102
- }
103
-
104
- function drawContainerFrame(
105
- grid: StateGrid,
106
- bounds: BoxBounds,
107
- label: string,
108
- chars: BorderCharacters,
109
- style: StateCellStyle,
110
- ): void {
111
- drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
112
- drawContainerLabel(grid, bounds, label, style)
113
- }
114
-
115
- function drawContainerLabel(grid: StateGrid, bounds: BoxBounds, label: string, style: StateCellStyle): void {
116
- if (label) setText(grid, bounds.left + 2, bounds.top, ` ${label} `, style)
117
- }
118
-
119
- function noteConnectorGlyph(directions: ReadonlySet<DiagramDirection>): string {
120
- const chars = BorderChars.double
121
- const up = directions.has("up")
122
- const down = directions.has("down")
123
- const left = directions.has("left")
124
- const right = directions.has("right")
125
- if (up && down && left && right) return chars.cross
126
- if (up && down && right) return chars.leftT
127
- if (up && down && left) return chars.rightT
128
- if (left && right && down) return chars.topT
129
- if (left && right && up) return chars.bottomT
130
- if (up && right) return chars.bottomLeft
131
- if (up && left) return chars.bottomRight
132
- if (down && right) return chars.topLeft
133
- if (down && left) return chars.topRight
134
- if (up || down) return chars.vertical
135
- return chars.horizontal
136
- }
137
-
138
- function drawNote(grid: StateGrid, bounds: StateNoteBounds, target: BoxBounds): void {
139
- const chars = BorderChars.double
140
- const connector = stateDiagramNoteConnector(bounds, target)
141
- const points = orthogonalPathPoints(connector.points)
142
- for (const [index, point] of points.entries()) {
143
- const directions = new Set<DiagramDirection>()
144
- const previous = points[index - 1]
145
- const next = points[index + 1]
146
- if (previous) directions.add(directionBetween(point, previous)!)
147
- if (next) directions.add(directionBetween(point, next)!)
148
- const distanceFromNote = points.length - index - 1
149
- const style = distanceFromNote < 3 ? NOTE_CONNECTOR_RAMP_STYLES[2 - distanceFromNote]! : "noteConnector"
150
- setCell(grid, point.x, point.y, noteConnectorGlyph(directions), style)
151
- }
152
-
153
- drawContainerFrame(grid, bounds, "", chars, "noteBorder")
154
- setCell(
155
- grid,
156
- bounds.note.position === "right" ? bounds.left : bounds.left + bounds.width - 1,
157
- connector.connectorY,
158
- bounds.note.position === "right" ? chars.rightT : chars.leftT,
159
- "noteBorder",
160
- )
161
- bounds.lines.forEach((line, index) => setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "noteText"))
162
- }
163
-
164
- function drawTransitionRenderPlan(
165
- grid: StateGrid,
166
- plan: StateTransitionRenderPlan,
167
- arrowHeadStyle: StateDiagramArrowHeadStyle,
168
- rampDeparture: boolean,
169
- ): void {
170
- const departure = new Map(
171
- rampDeparture
172
- ? plan.path.slice(0, 3).map(([x, y], index) => [`${x}:${y}`, STATE_DEPARTURE_RAMP_STYLES[index]!])
173
- : [],
174
- )
175
- for (const cell of plan.cells) {
176
- const char = cell.arrowDirection ? diagramArrowHead(cell.arrowDirection, arrowHeadStyle) : cell.char
177
- setCell(grid, cell.x, cell.y, char, departure.get(`${cell.x}:${cell.y}`) ?? "transition")
178
- }
179
- if (plan.label) {
180
- plan.label.lines.forEach((line, index) => {
181
- const y = plan.label!.y + index
182
- const leftX = plan.label!.x - DIAGRAM_LABEL_PADDING_X
183
- if (grid.getCell(leftX, y)?.char === " ") setCell(grid, leftX, y, " ", "label")
184
- setText(grid, plan.label!.x, y, line, "label")
185
- const rightX = plan.label!.x + diagramTextWidth(line) + DIAGRAM_LABEL_PADDING_X - 1
186
- if (grid.getCell(rightX, y)?.char === " ") setCell(grid, rightX, y, " ", "label")
187
- })
188
- }
189
- }
190
-
191
- function drawTransitionJunctionPlans(
192
- grid: StateGrid,
193
- diagram: StateDiagram,
194
- bounds: Map<string, BoxBounds>,
195
- renderPlans: readonly StateTransitionRenderPlan[],
196
- ): void {
197
- for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
198
- const style = plan.kind === "choice" ? "choice" : "transition"
199
- const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
200
- setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
201
- }
202
- }
203
-
204
- export function drawStateDiagramGrid(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}): StateGrid {
205
- return createStateDiagramDrawing(sourceDiagram, options).grid
206
- }
207
-
208
- export function createStateDiagramDrawing(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}) {
209
- const direction = options.direction ?? sourceDiagram.direction
210
- if (direction !== "LR" && direction !== "RL") {
211
- return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
212
- }
213
- if (options.layoutMaxWidth === undefined || !Number.isFinite(options.layoutMaxWidth)) {
214
- return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
215
- }
216
- const fallbackDirection = direction === "RL" ? "BT" : "TB"
217
- const maxWidth = Math.max(1, Math.trunc(options.layoutMaxWidth))
218
- const drawing = (() => {
219
- try {
220
- return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
221
- } catch (error) {
222
- if (error instanceof DiagramCanvasSizeError) return undefined
223
- throw error
224
- }
225
- })()
226
- if (!drawing) return createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
227
- if (drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width <= maxWidth) {
228
- return drawing
229
- }
230
- const fallback = createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
231
- if (
232
- fallback.grid.getTextSize({ trimTop: true, trimBottom: true }).width >=
233
- drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width
234
- ) {
235
- return drawing
236
- }
237
- return fallback
238
- }
239
-
240
- function createStateDiagramDrawingWithDirection(
241
- sourceDiagram: StateDiagram,
242
- options: StateDiagramRenderOptions,
243
- direction: StateDiagram["direction"],
244
- ) {
245
- const diagram = prepareVisibleStateDiagram(
246
- direction === sourceDiagram.direction ? sourceDiagram : { ...sourceDiagram, direction },
247
- )
248
- const borderStyle = options.borderStyle ?? DEFAULT_STATE_BORDER_STYLE
249
- const arrowHeadStyle = options.arrowHeadStyle ?? DEFAULT_STATE_ARROW_HEAD_STYLE
250
- const minStateGap = normalizeStateMinStateGap(options.minStateGap)
251
- const searchBudget = createStateSearchBudget()
252
- const layout = createStateDiagramLayout(diagram, {
253
- minStateGap,
254
- searchBudget,
255
- })
256
- const { bounds, sizes, compositeBounds, noteBounds } = layout
257
- let allBounds = [...bounds.values(), ...noteBounds]
258
- let maxY = Math.max(0, ...allBounds.map((bound) => bound.top + bound.height))
259
- const feedbackLaneY = maxY + 3
260
- const feedbackTopY = Math.min(0, ...allBounds.map((bound) => bound.top)) - 3
261
- expandCompositeBoundsForFeedback(diagram, bounds, compositeBounds, feedbackLaneY)
262
- let transitionPlans: StateTransitionRenderPlan[] = []
263
- const separationAttempts = diagram.states.length + diagram.composites.length + 1
264
- for (let attempt = 0; attempt < separationAttempts; attempt++) {
265
- transitionPlans = createStateTransitionRenderPlans(diagram, bounds, feedbackLaneY, {
266
- feedbackTopY,
267
- noteBounds,
268
- searchBudget,
269
- })
270
- expandCompositeBoundsForInternalTransitions(diagram, compositeBounds, transitionPlans)
271
- if (!separateExternalBoundsFromComposites(diagram, layout)) break
272
- if (attempt === separationAttempts - 1) throw new Error("State composite separation did not converge")
273
- }
274
- const connectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
275
- const contentLeft = Math.min(
276
- 0,
277
- ...[...bounds.values(), ...noteBounds].map((bound) => bound.left),
278
- ...connectorPoints.map((point) => point.x),
279
- ...transitionPlans.flatMap((plan) => [
280
- ...plan.cells.map((cell) => cell.x),
281
- ...(plan.label ? [plan.label.x - DIAGRAM_LABEL_PADDING_X] : []),
282
- ]),
283
- )
284
- const contentTop = Math.min(
285
- 0,
286
- ...[...bounds.values(), ...noteBounds].map((bound) => bound.top),
287
- ...connectorPoints.map((point) => point.y),
288
- ...transitionPlans.flatMap((plan) => [...plan.cells.map((cell) => cell.y), ...(plan.label ? [plan.label.y] : [])]),
289
- )
290
- if (contentLeft < 0 || contentTop < 0) {
291
- translateStateDiagramLayout(layout, -contentLeft, -contentTop)
292
- transitionPlans = translateTransitionPlans(transitionPlans, -contentLeft, -contentTop)
293
- }
294
- allBounds = [...bounds.values(), ...noteBounds]
295
- const translatedConnectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
296
- const maxX = Math.max(
297
- 0,
298
- ...allBounds.map((bound) => bound.left + bound.width),
299
- ...translatedConnectorPoints.map((point) => point.x + 1),
300
- )
301
- maxY = Math.max(
302
- 0,
303
- ...allBounds.map((bound) => bound.top + bound.height),
304
- ...translatedConnectorPoints.map((point) => point.y + 1),
305
- )
306
- const transitionLabelSizes = diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label))
307
- const maxTransitionLabelWidth = Math.max(0, ...transitionLabelSizes.map((size) => size.width))
308
- const maxTransitionLabelLines = Math.max(0, ...transitionLabelSizes.map((size) => size.height))
309
- const transitionRight = Math.max(
310
- maxX,
311
- ...transitionPlans.flatMap((plan) => [
312
- ...plan.cells.map((cell) => cell.x + 1),
313
- ...(plan.label
314
- ? [plan.label.x + measureStateTransitionLabel(plan.route.transition.label).width + DIAGRAM_LABEL_PADDING_X]
315
- : []),
316
- ]),
317
- )
318
- const transitionBottom = Math.max(
319
- maxY,
320
- ...transitionPlans.flatMap((plan) => [
321
- ...plan.cells.map((cell) => cell.y + 1),
322
- ...(plan.label ? [plan.label.y + plan.label.lines.length] : []),
323
- ]),
324
- )
325
- const grid = makeGrid(
326
- Math.max(maxX + Math.max(24, maxTransitionLabelWidth + 4), transitionRight + 2),
327
- Math.max(maxY + 8 + maxTransitionLabelLines, transitionBottom + 2),
328
- )
329
- for (const composite of diagram.composites) {
330
- const bound = compositeBounds.get(composite.id)
331
- if (!bound) continue
332
- drawContainerFrame(grid, bound, composite.label, BorderChars[borderStyle], "composite")
333
- }
334
-
335
- for (const state of diagram.states) {
336
- const bound = bounds.get(state.id)
337
- const size = sizes.get(state.id)
338
- if (!bound || !size) continue
339
- drawBox(grid, state, bound, size.lines, borderStyle)
340
- }
341
-
342
- for (const plan of transitionPlans) {
343
- const source = diagram.states.find((state) => state.id === plan.route.transition.from)
344
- drawTransitionRenderPlan(grid, plan, arrowHeadStyle, source?.kind === "state")
345
- }
346
-
347
- drawTransitionJunctionPlans(grid, diagram, bounds, transitionPlans)
348
-
349
- for (const composite of diagram.composites) {
350
- const bound = compositeBounds.get(composite.id)
351
- if (bound) drawContainerLabel(grid, bound, composite.label, "compositeLabel")
352
- }
353
-
354
- for (const noteBound of noteBounds) {
355
- const target = bounds.get(noteBound.note.target)
356
- if (target) drawNote(grid, noteBound, target)
357
- }
358
-
359
- return { grid, diagram, layout, transitionPlans }
360
- }
1
+ import { BorderChars, type BorderCharacters, type BorderStyle } from "@opentui/core"
2
+ import { DiagramCanvas, DiagramCanvasSizeError, type DiagramCanvasCell } from "../core/canvas.js"
3
+ import { directionBetween, orthogonalPathPoints, type DiagramDirection } from "../core/geometry.js"
4
+ import {
5
+ diagramArrowHead,
6
+ diagramLineGlyph,
7
+ drawDiagramFrame,
8
+ fillDiagramFrameInterior,
9
+ mergeDiagramLineGlyph,
10
+ } from "../core/drawing.js"
11
+ import { DIAGRAM_LABEL_PADDING_X, diagramTextWidth } from "../core/text.js"
12
+ import {
13
+ createStateDiagramLayout,
14
+ expandCompositeBoundsForFeedback,
15
+ expandCompositeBoundsForInternalTransitions,
16
+ separateExternalBoundsFromComposites,
17
+ translateStateDiagramLayout,
18
+ type StateDiagramBoxBounds as BoxBounds,
19
+ type StateDiagramNoteBounds as StateNoteBounds,
20
+ } from "./layout.js"
21
+ import { stateDiagramNoteConnector } from "./note.js"
22
+ import { DEFAULT_STATE_ARROW_HEAD_STYLE, DEFAULT_STATE_BORDER_STYLE, normalizeStateMinStateGap } from "./options.js"
23
+ import type { StateGrid } from "./render-grid.js"
24
+ import {
25
+ createStateTransitionJunctionPlans,
26
+ createStateTransitionRenderPlans,
27
+ measureStateTransitionLabel,
28
+ type StateTransitionRenderPlan,
29
+ } from "./routing.js"
30
+ import { createStateSearchBudget } from "./search.js"
31
+ import { NOTE_CONNECTOR_RAMP_STYLES, STATE_DEPARTURE_RAMP_STYLES } from "./style.js"
32
+ import type {
33
+ StateCellStyle,
34
+ StateDiagram,
35
+ StateDiagramArrowHeadStyle,
36
+ StateDiagramRenderOptions,
37
+ StateDiagramState,
38
+ } from "./types.js"
39
+ import { isHiddenCompositeMarker, prepareVisibleStateDiagram } from "./visible-model.js"
40
+
41
+ type StateCell = DiagramCanvasCell<StateCellStyle>
42
+
43
+ function translateTransitionPlans(
44
+ plans: readonly StateTransitionRenderPlan[],
45
+ dx: number,
46
+ dy: number,
47
+ ): StateTransitionRenderPlan[] {
48
+ return plans.map((plan) => ({
49
+ ...plan,
50
+ cells: plan.cells.map((cell) => ({ ...cell, x: cell.x + dx, y: cell.y + dy })),
51
+ path: plan.path.map(([x, y]) => [x + dx, y + dy]),
52
+ label: plan.label ? { ...plan.label, x: plan.label.x + dx, y: plan.label.y + dy } : undefined,
53
+ }))
54
+ }
55
+
56
+ function makeGrid(width: number, height: number): StateGrid {
57
+ return new DiagramCanvas(width, height, {
58
+ mergeCell: (existing, incoming): StateCell => {
59
+ const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
60
+ const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
61
+ const shouldMerge = incomingIsTransition && existingIsTransition
62
+ return {
63
+ ...incoming,
64
+ char: shouldMerge
65
+ ? (mergeDiagramLineGlyph(existing.char, incoming.char, "rounded") ?? incoming.char)
66
+ : incoming.char,
67
+ }
68
+ },
69
+ })
70
+ }
71
+
72
+ function setCell(grid: StateGrid, x: number, y: number, char: string, style?: StateCellStyle): void {
73
+ grid.setCell(x, y, char, style)
74
+ }
75
+
76
+ function setText(grid: StateGrid, x: number, y: number, text: string, style?: StateCellStyle): void {
77
+ grid.setText(x, y, text, style)
78
+ }
79
+
80
+ function drawBox(
81
+ grid: StateGrid,
82
+ state: StateDiagramState,
83
+ bounds: BoxBounds,
84
+ lines: string[],
85
+ borderStyle: BorderStyle,
86
+ ): void {
87
+ if (isHiddenCompositeMarker(state)) return
88
+
89
+ if (state.kind !== "state") {
90
+ setCell(grid, bounds.left, bounds.top, state.label, state.kind)
91
+ return
92
+ }
93
+ fillDiagramFrameInterior(bounds, (x, y) => setCell(grid, x, y, " ", "state"))
94
+ drawStateFrame(grid, bounds, BorderChars[borderStyle], "stateBorder")
95
+ lines.forEach((line, index) => {
96
+ setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "state")
97
+ })
98
+ }
99
+
100
+ function drawStateFrame(grid: StateGrid, bounds: BoxBounds, chars: BorderCharacters, style: StateCellStyle): void {
101
+ drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
102
+ }
103
+
104
+ function drawContainerFrame(
105
+ grid: StateGrid,
106
+ bounds: BoxBounds,
107
+ label: string,
108
+ chars: BorderCharacters,
109
+ style: StateCellStyle,
110
+ ): void {
111
+ drawDiagramFrame(bounds, chars, (x, y, char) => setCell(grid, x, y, char, style))
112
+ drawContainerLabel(grid, bounds, label, style)
113
+ }
114
+
115
+ function drawContainerLabel(grid: StateGrid, bounds: BoxBounds, label: string, style: StateCellStyle): void {
116
+ if (label) setText(grid, bounds.left + 2, bounds.top, ` ${label} `, style)
117
+ }
118
+
119
+ function noteConnectorGlyph(directions: ReadonlySet<DiagramDirection>): string {
120
+ const chars = BorderChars.double
121
+ const up = directions.has("up")
122
+ const down = directions.has("down")
123
+ const left = directions.has("left")
124
+ const right = directions.has("right")
125
+ if (up && down && left && right) return chars.cross
126
+ if (up && down && right) return chars.leftT
127
+ if (up && down && left) return chars.rightT
128
+ if (left && right && down) return chars.topT
129
+ if (left && right && up) return chars.bottomT
130
+ if (up && right) return chars.bottomLeft
131
+ if (up && left) return chars.bottomRight
132
+ if (down && right) return chars.topLeft
133
+ if (down && left) return chars.topRight
134
+ if (up || down) return chars.vertical
135
+ return chars.horizontal
136
+ }
137
+
138
+ function drawNote(grid: StateGrid, bounds: StateNoteBounds, target: BoxBounds): void {
139
+ const chars = BorderChars.double
140
+ const connector = stateDiagramNoteConnector(bounds, target)
141
+ const points = orthogonalPathPoints(connector.points)
142
+ for (const [index, point] of points.entries()) {
143
+ const directions = new Set<DiagramDirection>()
144
+ const previous = points[index - 1]
145
+ const next = points[index + 1]
146
+ if (previous) directions.add(directionBetween(point, previous)!)
147
+ if (next) directions.add(directionBetween(point, next)!)
148
+ const distanceFromNote = points.length - index - 1
149
+ const style = distanceFromNote < 3 ? NOTE_CONNECTOR_RAMP_STYLES[2 - distanceFromNote]! : "noteConnector"
150
+ setCell(grid, point.x, point.y, noteConnectorGlyph(directions), style)
151
+ }
152
+
153
+ drawContainerFrame(grid, bounds, "", chars, "noteBorder")
154
+ setCell(
155
+ grid,
156
+ bounds.note.position === "right" ? bounds.left : bounds.left + bounds.width - 1,
157
+ connector.connectorY,
158
+ bounds.note.position === "right" ? chars.rightT : chars.leftT,
159
+ "noteBorder",
160
+ )
161
+ bounds.lines.forEach((line, index) => setText(grid, bounds.left + 2, bounds.top + 1 + index, line, "noteText"))
162
+ }
163
+
164
+ function drawTransitionRenderPlan(
165
+ grid: StateGrid,
166
+ plan: StateTransitionRenderPlan,
167
+ arrowHeadStyle: StateDiagramArrowHeadStyle,
168
+ rampDeparture: boolean,
169
+ ): void {
170
+ const departure = new Map(
171
+ rampDeparture
172
+ ? plan.path.slice(0, 3).map(([x, y], index) => [`${x}:${y}`, STATE_DEPARTURE_RAMP_STYLES[index]!])
173
+ : [],
174
+ )
175
+ for (const cell of plan.cells) {
176
+ const char = cell.arrowDirection ? diagramArrowHead(cell.arrowDirection, arrowHeadStyle) : cell.char
177
+ setCell(grid, cell.x, cell.y, char, departure.get(`${cell.x}:${cell.y}`) ?? "transition")
178
+ }
179
+ if (plan.label) {
180
+ plan.label.lines.forEach((line, index) => {
181
+ const y = plan.label!.y + index
182
+ const leftX = plan.label!.x - DIAGRAM_LABEL_PADDING_X
183
+ if (grid.getCell(leftX, y)?.char === " ") setCell(grid, leftX, y, " ", "label")
184
+ setText(grid, plan.label!.x, y, line, "label")
185
+ const rightX = plan.label!.x + diagramTextWidth(line) + DIAGRAM_LABEL_PADDING_X - 1
186
+ if (grid.getCell(rightX, y)?.char === " ") setCell(grid, rightX, y, " ", "label")
187
+ })
188
+ }
189
+ }
190
+
191
+ function drawTransitionJunctionPlans(
192
+ grid: StateGrid,
193
+ diagram: StateDiagram,
194
+ bounds: Map<string, BoxBounds>,
195
+ renderPlans: readonly StateTransitionRenderPlan[],
196
+ ): void {
197
+ for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
198
+ const style = plan.kind === "choice" ? "choice" : "transition"
199
+ const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
200
+ setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
201
+ }
202
+ }
203
+
204
+ export function drawStateDiagramGrid(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}): StateGrid {
205
+ return createStateDiagramDrawing(sourceDiagram, options).grid
206
+ }
207
+
208
+ export function createStateDiagramDrawing(sourceDiagram: StateDiagram, options: StateDiagramRenderOptions = {}) {
209
+ const direction = options.direction ?? sourceDiagram.direction
210
+ if (direction !== "LR" && direction !== "RL") {
211
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
212
+ }
213
+ if (options.layoutMaxWidth === undefined || !Number.isFinite(options.layoutMaxWidth)) {
214
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
215
+ }
216
+ const fallbackDirection = direction === "RL" ? "BT" : "TB"
217
+ const maxWidth = Math.max(1, Math.trunc(options.layoutMaxWidth))
218
+ const drawing = (() => {
219
+ try {
220
+ return createStateDiagramDrawingWithDirection(sourceDiagram, options, direction)
221
+ } catch (error) {
222
+ if (error instanceof DiagramCanvasSizeError) return undefined
223
+ throw error
224
+ }
225
+ })()
226
+ if (!drawing) return createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
227
+ if (drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width <= maxWidth) {
228
+ return drawing
229
+ }
230
+ const fallback = createStateDiagramDrawingWithDirection(sourceDiagram, options, fallbackDirection)
231
+ if (
232
+ fallback.grid.getTextSize({ trimTop: true, trimBottom: true }).width >=
233
+ drawing.grid.getTextSize({ trimTop: true, trimBottom: true }).width
234
+ ) {
235
+ return drawing
236
+ }
237
+ return fallback
238
+ }
239
+
240
+ function createStateDiagramDrawingWithDirection(
241
+ sourceDiagram: StateDiagram,
242
+ options: StateDiagramRenderOptions,
243
+ direction: StateDiagram["direction"],
244
+ ) {
245
+ const diagram = prepareVisibleStateDiagram(
246
+ direction === sourceDiagram.direction ? sourceDiagram : { ...sourceDiagram, direction },
247
+ )
248
+ const borderStyle = options.borderStyle ?? DEFAULT_STATE_BORDER_STYLE
249
+ const arrowHeadStyle = options.arrowHeadStyle ?? DEFAULT_STATE_ARROW_HEAD_STYLE
250
+ const minStateGap = normalizeStateMinStateGap(options.minStateGap)
251
+ const searchBudget = createStateSearchBudget()
252
+ const layout = createStateDiagramLayout(diagram, {
253
+ minStateGap,
254
+ searchBudget,
255
+ })
256
+ const { bounds, sizes, compositeBounds, noteBounds } = layout
257
+ let allBounds = [...bounds.values(), ...noteBounds]
258
+ let maxY = Math.max(0, ...allBounds.map((bound) => bound.top + bound.height))
259
+ const feedbackLaneY = maxY + 3
260
+ const feedbackTopY = Math.min(0, ...allBounds.map((bound) => bound.top)) - 3
261
+ expandCompositeBoundsForFeedback(diagram, bounds, compositeBounds, feedbackLaneY)
262
+ let transitionPlans: StateTransitionRenderPlan[] = []
263
+ const separationAttempts = diagram.states.length + diagram.composites.length + 1
264
+ for (let attempt = 0; attempt < separationAttempts; attempt++) {
265
+ transitionPlans = createStateTransitionRenderPlans(diagram, bounds, feedbackLaneY, {
266
+ feedbackTopY,
267
+ noteBounds,
268
+ searchBudget,
269
+ })
270
+ expandCompositeBoundsForInternalTransitions(diagram, compositeBounds, transitionPlans)
271
+ if (!separateExternalBoundsFromComposites(diagram, layout)) break
272
+ if (attempt === separationAttempts - 1) throw new Error("State composite separation did not converge")
273
+ }
274
+ const connectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
275
+ const contentLeft = Math.min(
276
+ 0,
277
+ ...[...bounds.values(), ...noteBounds].map((bound) => bound.left),
278
+ ...connectorPoints.map((point) => point.x),
279
+ ...transitionPlans.flatMap((plan) => [
280
+ ...plan.cells.map((cell) => cell.x),
281
+ ...(plan.label ? [plan.label.x - DIAGRAM_LABEL_PADDING_X] : []),
282
+ ]),
283
+ )
284
+ const contentTop = Math.min(
285
+ 0,
286
+ ...[...bounds.values(), ...noteBounds].map((bound) => bound.top),
287
+ ...connectorPoints.map((point) => point.y),
288
+ ...transitionPlans.flatMap((plan) => [...plan.cells.map((cell) => cell.y), ...(plan.label ? [plan.label.y] : [])]),
289
+ )
290
+ if (contentLeft < 0 || contentTop < 0) {
291
+ translateStateDiagramLayout(layout, -contentLeft, -contentTop)
292
+ transitionPlans = translateTransitionPlans(transitionPlans, -contentLeft, -contentTop)
293
+ }
294
+ allBounds = [...bounds.values(), ...noteBounds]
295
+ const translatedConnectorPoints = noteBounds.flatMap((bound) => bound.connector?.points ?? [])
296
+ const maxX = Math.max(
297
+ 0,
298
+ ...allBounds.map((bound) => bound.left + bound.width),
299
+ ...translatedConnectorPoints.map((point) => point.x + 1),
300
+ )
301
+ maxY = Math.max(
302
+ 0,
303
+ ...allBounds.map((bound) => bound.top + bound.height),
304
+ ...translatedConnectorPoints.map((point) => point.y + 1),
305
+ )
306
+ const transitionLabelSizes = diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label))
307
+ const maxTransitionLabelWidth = Math.max(0, ...transitionLabelSizes.map((size) => size.width))
308
+ const maxTransitionLabelLines = Math.max(0, ...transitionLabelSizes.map((size) => size.height))
309
+ const transitionRight = Math.max(
310
+ maxX,
311
+ ...transitionPlans.flatMap((plan) => [
312
+ ...plan.cells.map((cell) => cell.x + 1),
313
+ ...(plan.label
314
+ ? [plan.label.x + measureStateTransitionLabel(plan.route.transition.label).width + DIAGRAM_LABEL_PADDING_X]
315
+ : []),
316
+ ]),
317
+ )
318
+ const transitionBottom = Math.max(
319
+ maxY,
320
+ ...transitionPlans.flatMap((plan) => [
321
+ ...plan.cells.map((cell) => cell.y + 1),
322
+ ...(plan.label ? [plan.label.y + plan.label.lines.length] : []),
323
+ ]),
324
+ )
325
+ const grid = makeGrid(
326
+ Math.max(maxX + Math.max(24, maxTransitionLabelWidth + 4), transitionRight + 2),
327
+ Math.max(maxY + 8 + maxTransitionLabelLines, transitionBottom + 2),
328
+ )
329
+ for (const composite of diagram.composites) {
330
+ const bound = compositeBounds.get(composite.id)
331
+ if (!bound) continue
332
+ drawContainerFrame(grid, bound, composite.label, BorderChars[borderStyle], "composite")
333
+ }
334
+
335
+ for (const state of diagram.states) {
336
+ const bound = bounds.get(state.id)
337
+ const size = sizes.get(state.id)
338
+ if (!bound || !size) continue
339
+ drawBox(grid, state, bound, size.lines, borderStyle)
340
+ }
341
+
342
+ for (const plan of transitionPlans) {
343
+ const source = diagram.states.find((state) => state.id === plan.route.transition.from)
344
+ drawTransitionRenderPlan(grid, plan, arrowHeadStyle, source?.kind === "state")
345
+ }
346
+
347
+ drawTransitionJunctionPlans(grid, diagram, bounds, transitionPlans)
348
+
349
+ for (const composite of diagram.composites) {
350
+ const bound = compositeBounds.get(composite.id)
351
+ if (bound) drawContainerLabel(grid, bound, composite.label, "compositeLabel")
352
+ }
353
+
354
+ for (const noteBound of noteBounds) {
355
+ const target = bounds.get(noteBound.note.target)
356
+ if (target) drawNote(grid, noteBound, target)
357
+ }
358
+
359
+ return { grid, diagram, layout, transitionPlans }
360
+ }