@zyro-sec/merman 0.0.0-stage → 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 (69) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.ts +228 -0
  4. package/src/core/color/style.ts +56 -0
  5. package/src/core/drawing.ts +301 -0
  6. package/src/core/geometry.ts +347 -0
  7. package/src/core/mermaid.ts +38 -0
  8. package/src/core/render-grid.ts +51 -0
  9. package/src/core/spatial.ts +243 -0
  10. package/src/core/text-lines.ts +32 -0
  11. package/src/core/text.ts +44 -0
  12. package/src/detect.ts +17 -0
  13. package/src/diagnostics.ts +16 -0
  14. package/src/flowchart/drawing.ts +340 -0
  15. package/src/flowchart/labels.ts +144 -0
  16. package/src/flowchart/layout.ts +1427 -0
  17. package/src/flowchart/options.ts +12 -0
  18. package/src/flowchart/parser.ts +467 -0
  19. package/src/flowchart/render.ts +10 -0
  20. package/src/flowchart/routing.ts +1542 -0
  21. package/src/flowchart/style.ts +79 -0
  22. package/src/flowchart/types.ts +65 -0
  23. package/src/gantt/diagram.ts +8 -0
  24. package/src/gantt/drawing.ts +191 -0
  25. package/src/gantt/parser.ts +161 -0
  26. package/src/gantt/render-grid.ts +17 -0
  27. package/src/gantt/style.ts +36 -0
  28. package/src/gantt/types.ts +44 -0
  29. package/src/gitgraph/diagram.ts +8 -0
  30. package/src/gitgraph/drawing.ts +234 -0
  31. package/src/gitgraph/parser.ts +219 -0
  32. package/src/gitgraph/render-grid.ts +17 -0
  33. package/src/gitgraph/style.ts +37 -0
  34. package/src/gitgraph/types.ts +36 -0
  35. package/src/markdown.ts +336 -0
  36. package/src/palette.ts +75 -0
  37. package/src/plugin.ts +15 -0
  38. package/src/sequence/diagram.ts +8 -0
  39. package/src/sequence/drawing.ts +287 -0
  40. package/src/sequence/options.ts +8 -0
  41. package/src/sequence/parser.ts +282 -0
  42. package/src/sequence/placement.ts +684 -0
  43. package/src/sequence/render-grid.ts +22 -0
  44. package/src/sequence/style.ts +81 -0
  45. package/src/sequence/types.ts +74 -0
  46. package/src/state/diagram.ts +8 -0
  47. package/src/state/drawing.ts +360 -0
  48. package/src/state/endpoint.ts +15 -0
  49. package/src/state/layout.ts +1134 -0
  50. package/src/state/note.ts +59 -0
  51. package/src/state/options.ts +11 -0
  52. package/src/state/parser.ts +224 -0
  53. package/src/state/render-grid.ts +22 -0
  54. package/src/state/routing.ts +1522 -0
  55. package/src/state/search.ts +103 -0
  56. package/src/state/style.ts +52 -0
  57. package/src/state/types.ts +63 -0
  58. package/src/state/visible-model.ts +77 -0
  59. package/src/test/diagram.ts +32 -0
  60. package/src/test/layout-audit/fixtures.ts +538 -0
  61. package/src/test/layout-audit/harness.ts +522 -0
  62. package/src/timeline/diagram.ts +8 -0
  63. package/src/timeline/drawing.ts +109 -0
  64. package/src/timeline/parser.ts +119 -0
  65. package/src/timeline/render-grid.ts +17 -0
  66. package/src/timeline/style.ts +36 -0
  67. package/src/timeline/types.ts +31 -0
  68. package/tsconfig.json +10 -0
  69. package/README.md +0 -3
@@ -0,0 +1,684 @@
1
+ import { diagramTextWidth } from "../core/text.js"
2
+ import { normalizeSequenceMinParticipantGap } from "./options.js"
3
+ import type {
4
+ SequenceDiagram,
5
+ SequenceDiagramRenderOptions,
6
+ SequenceFragment,
7
+ SequenceMessage,
8
+ SequenceNote,
9
+ SequenceParticipant,
10
+ SequenceParticipantGroup,
11
+ SequenceStep,
12
+ } from "./types.js"
13
+
14
+ const NOTE_HORIZONTAL_PADDING = 2
15
+ const GROUP_HORIZONTAL_PADDING = 2
16
+ const FRAGMENT_HORIZONTAL_OVERHANG = 3
17
+
18
+ export interface SequenceHorizontalBounds {
19
+ leftX: number
20
+ rightX: number
21
+ }
22
+
23
+ export interface SequenceParticipantPlacement {
24
+ participant: SequenceParticipant
25
+ centerX: number
26
+ headerLeftX: number
27
+ headerRightX: number
28
+ labelLines: string[]
29
+ }
30
+
31
+ export interface SequenceGroupPlacement {
32
+ group: SequenceParticipantGroup
33
+ labelText: string
34
+ leftX: number
35
+ rightX: number
36
+ }
37
+
38
+ export interface SequenceWallPlacement {
39
+ bounds: SequenceHorizontalBounds
40
+ startY: number
41
+ endY: number
42
+ }
43
+
44
+ export interface SequenceActivationPlacement {
45
+ participant: string
46
+ centerX: number
47
+ startY: number
48
+ endY: number
49
+ depth: number
50
+ }
51
+
52
+ export type SequenceStepPlacement =
53
+ | { type: "note"; note: SequenceNote; textLines: string[]; textX: number; textY: number }
54
+ | {
55
+ type: "fragment"
56
+ fragment: SequenceFragment
57
+ labelText: string
58
+ bounds: SequenceHorizontalBounds
59
+ y: number
60
+ wallsBefore?: SequenceWallPlacement
61
+ }
62
+ | {
63
+ type: "message"
64
+ message: SequenceMessage
65
+ labelLines: string[]
66
+ labelX: number
67
+ labelY: number
68
+ arrowY: number
69
+ fromX: number
70
+ toX: number
71
+ leftX: number
72
+ rightX: number
73
+ headX: number
74
+ direction: 1 | -1
75
+ inlineLabel?: string
76
+ }
77
+ | {
78
+ type: "selfMessage"
79
+ message: SequenceMessage
80
+ labelLines: string[]
81
+ centerX: number
82
+ rightX: number
83
+ topY: number
84
+ bottomY: number
85
+ }
86
+
87
+ export interface SequencePlacementPlan {
88
+ width: number
89
+ height: number
90
+ rows: {
91
+ participantHeaderTopY: number
92
+ participantHeaderY: number
93
+ participantRuleY: number
94
+ lifelineStartY: number
95
+ lifelineEndY: number
96
+ }
97
+ participants: SequenceParticipantPlacement[]
98
+ groups: SequenceGroupPlacement[]
99
+ activations: SequenceActivationPlacement[]
100
+ steps: SequenceStepPlacement[]
101
+ }
102
+
103
+ interface SequenceGroupRange {
104
+ group: SequenceParticipantGroup
105
+ startIndex: number
106
+ endIndex: number
107
+ }
108
+
109
+ interface PendingFragmentFrame {
110
+ startIndex: number
111
+ bounds: SequenceHorizontalBounds
112
+ }
113
+
114
+ interface ActiveFragmentFrame {
115
+ bounds: SequenceHorizontalBounds
116
+ boundaryY: number
117
+ }
118
+
119
+ function visualLength(value: string): number {
120
+ return diagramTextWidth(value)
121
+ }
122
+
123
+ function mermaidLabelLines(label: string): string[] {
124
+ const lines = label.split(/(?:<br\s*\/?\s*>|\\n)/i).map((line) => line.trimEnd())
125
+ return lines.length > 0 ? lines : [""]
126
+ }
127
+
128
+ function noteLabelLines(label: string): string[] {
129
+ const lines = mermaidLabelLines(label)
130
+ const width = labelLinesWidth(lines)
131
+ const padding = " ".repeat(NOTE_HORIZONTAL_PADDING)
132
+ return lines.map((line) => `${padding}${line}${" ".repeat(width - visualLength(line))}${padding}`)
133
+ }
134
+
135
+ function messageLabelText(message: SequenceMessage): string {
136
+ return message.number === undefined ? message.label : `${message.number}. ${message.label}`
137
+ }
138
+
139
+ function participantHeaderWidth(label: string, compact: boolean): number {
140
+ const width = labelLinesWidth(mermaidLabelLines(label))
141
+ return compact ? width : Math.max(3, width)
142
+ }
143
+
144
+ function fragmentLabelText(fragment: SequenceFragment): string {
145
+ if (fragment.kind === "end") return ""
146
+ const prefix = fragment.kind === "loop" ? "↻ loop" : fragment.kind
147
+ return ` ${prefix}: ${fragment.label} `
148
+ }
149
+
150
+ function messageLabelLines(label: string): string[] {
151
+ return mermaidLabelLines(label)
152
+ }
153
+
154
+ function labelLinesWidth(lines: string[]): number {
155
+ return lines.reduce((max, line) => Math.max(max, visualLength(line)), 0)
156
+ }
157
+
158
+ function messageWidth(message: SequenceMessage): number {
159
+ return labelLinesWidth(messageLabelLines(messageLabelText(message)))
160
+ }
161
+
162
+ function selfMessageLoopWidthForLines(labelLines: string[]): number {
163
+ return Math.max(10, labelLinesWidth(labelLines) + 4)
164
+ }
165
+
166
+ function selfMessageLoopWidth(message: SequenceMessage): number {
167
+ return selfMessageLoopWidthForLines(messageLabelLines(messageLabelText(message)))
168
+ }
169
+
170
+ function arrowHeadX(toX: number, direction: 1 | -1, head: SequenceMessage["head"]): number {
171
+ return head === undefined ? toX : toX - direction
172
+ }
173
+
174
+ function inlineMessageLabel(
175
+ message: SequenceMessage,
176
+ labelLines: string[],
177
+ fromX: number,
178
+ toX: number,
179
+ compact: boolean,
180
+ ): string | undefined {
181
+ if (!compact || message.from === message.to || labelLines.length !== 1) return undefined
182
+ const label = ` ${labelLines[0]} `
183
+ return visualLength(label) <= Math.abs(toX - fromX) - 3 ? label : undefined
184
+ }
185
+
186
+ function getStepHeight(
187
+ step: SequenceStep,
188
+ centers: number[],
189
+ participantIndexes: Map<string, number>,
190
+ compact: boolean,
191
+ ): number {
192
+ if (step.type === "note") return noteLabelLines(step.note.label).length + 2
193
+ if (step.type === "activation") return 0
194
+ if (step.type === "fragment") return 2
195
+ const labelLines = messageLabelLines(messageLabelText(step.message))
196
+ const fromX = centers[participantIndexes.get(step.message.from) ?? -1]
197
+ const toX = centers[participantIndexes.get(step.message.to) ?? -1]
198
+ if (fromX !== undefined && toX !== undefined && inlineMessageLabel(step.message, labelLines, fromX, toX, compact)) {
199
+ return 2
200
+ }
201
+ return labelLines.length + (step.message.from === step.message.to ? 3 : 2)
202
+ }
203
+
204
+ function createParticipantIndexMap(diagram: SequenceDiagram): Map<string, number> {
205
+ return new Map(diagram.participants.map((participant, index) => [participant.id, index]))
206
+ }
207
+
208
+ function getParticipantIndexes(participantIndexes: Map<string, number>, participantIds: string[]): number[] {
209
+ return participantIds.map((id) => participantIndexes.get(id) ?? -1).filter((index) => index >= 0)
210
+ }
211
+
212
+ function groupLabelText(group: SequenceParticipantGroup): string {
213
+ return group.label ? ` ${group.label} ` : ""
214
+ }
215
+
216
+ function getGroupRanges(diagram: SequenceDiagram, participantIndexes: Map<string, number>): SequenceGroupRange[] {
217
+ return diagram.groups.flatMap((group) => {
218
+ const indexes = getParticipantIndexes(participantIndexes, group.participantIds)
219
+ return indexes.length === 0 ? [] : [{ group, startIndex: Math.min(...indexes), endIndex: Math.max(...indexes) }]
220
+ })
221
+ }
222
+
223
+ function getStepParticipantIndexes(step: SequenceStep, participantIndexes: Map<string, number>): number[] {
224
+ if (step.type === "message") {
225
+ return getParticipantIndexes(participantIndexes, [step.message.from, step.message.to])
226
+ }
227
+ if (step.type === "note") return getParticipantIndexes(participantIndexes, step.note.over)
228
+ return []
229
+ }
230
+
231
+ function getStepContentBounds(
232
+ step: SequenceStep,
233
+ centers: number[],
234
+ participantIndexes: Map<string, number>,
235
+ ): SequenceHorizontalBounds | undefined {
236
+ if (step.type === "message") {
237
+ const fromIndex = participantIndexes.get(step.message.from) ?? -1
238
+ const toIndex = participantIndexes.get(step.message.to) ?? -1
239
+ if (fromIndex < 0 || toIndex < 0) return undefined
240
+ const fromX = centers[fromIndex]!
241
+ const toX = centers[toIndex]!
242
+ if (fromIndex === toIndex) return { leftX: fromX, rightX: fromX + selfMessageLoopWidth(step.message) }
243
+ const leftX = Math.min(fromX, toX)
244
+ const rightX = Math.max(fromX, toX)
245
+ const labelWidth = messageWidth(step.message)
246
+ const labelLeftX = leftX + 2
247
+ return { leftX: Math.min(leftX, labelLeftX), rightX: Math.max(rightX, labelLeftX + labelWidth - 1) }
248
+ }
249
+ if (step.type !== "note") return undefined
250
+ const indexes = getParticipantIndexes(participantIndexes, step.note.over)
251
+ if (indexes.length === 0) return undefined
252
+ const centerX = Math.floor((centers[Math.min(...indexes)]! + centers[Math.max(...indexes)]!) / 2)
253
+ const textLines = noteLabelLines(step.note.label)
254
+ const width = labelLinesWidth(textLines)
255
+ const leftX =
256
+ step.note.position === "left"
257
+ ? centerX - width - 2
258
+ : step.note.position === "right"
259
+ ? centerX + 2
260
+ : centerX - Math.floor(width / 2)
261
+ return { leftX, rightX: leftX + width - 1 }
262
+ }
263
+
264
+ function rangeContainsIndexes(range: SequenceGroupRange, indexes: readonly number[]): boolean {
265
+ return indexes.length > 0 && indexes.every((index) => index >= range.startIndex && index <= range.endIndex)
266
+ }
267
+
268
+ function resolveGroupBounds(
269
+ diagram: SequenceDiagram,
270
+ centers: number[],
271
+ participantIndexes: Map<string, number>,
272
+ groupRanges: SequenceGroupRange[],
273
+ compact: boolean,
274
+ ): SequenceGroupPlacement[] {
275
+ return groupRanges.map((range) => {
276
+ let contentLeftX = centers[range.startIndex]!
277
+ let contentRightX = centers[range.endIndex]!
278
+ for (let i = range.startIndex; i <= range.endIndex; i++) {
279
+ const headerWidth = participantHeaderWidth(diagram.participants[i]!.label, compact)
280
+ const headerStartX = centers[i]! - Math.floor(headerWidth / 2)
281
+ contentLeftX = Math.min(contentLeftX, headerStartX)
282
+ contentRightX = Math.max(contentRightX, headerStartX + headerWidth - 1)
283
+ }
284
+ for (const step of diagram.steps) {
285
+ const indexes = getStepParticipantIndexes(step, participantIndexes)
286
+ if (!rangeContainsIndexes(range, indexes)) continue
287
+ const bounds = getStepContentBounds(step, centers, participantIndexes)
288
+ if (bounds) {
289
+ contentLeftX = Math.min(contentLeftX, bounds.leftX)
290
+ contentRightX = Math.max(contentRightX, bounds.rightX)
291
+ }
292
+ }
293
+ const labelText = groupLabelText(range.group)
294
+ let leftX = contentLeftX - GROUP_HORIZONTAL_PADDING
295
+ let rightX = contentRightX + GROUP_HORIZONTAL_PADDING
296
+ const extraWidth = Math.max(0, visualLength(labelText) + 4 - (rightX - leftX + 1))
297
+ leftX -= Math.floor(extraWidth / 2)
298
+ rightX += Math.ceil(extraWidth / 2)
299
+ return { group: range.group, labelText, leftX, rightX }
300
+ })
301
+ }
302
+
303
+ function expandHorizontalBounds(bounds: SequenceHorizontalBounds, leftX: number, rightX: number): void {
304
+ bounds.leftX = Math.min(bounds.leftX, leftX)
305
+ bounds.rightX = Math.max(bounds.rightX, rightX)
306
+ }
307
+
308
+ function getDiagramContentBounds(
309
+ diagram: SequenceDiagram,
310
+ centers: number[],
311
+ participantIndexes: Map<string, number>,
312
+ compact: boolean,
313
+ ): SequenceHorizontalBounds {
314
+ const bounds = { leftX: 0, rightX: 0 }
315
+ for (let i = 0; i < diagram.participants.length; i++) {
316
+ const headerWidth = participantHeaderWidth(diagram.participants[i]!.label, compact)
317
+ const labelStartX = centers[i]! - Math.floor(headerWidth / 2)
318
+ expandHorizontalBounds(bounds, labelStartX, labelStartX + headerWidth - 1)
319
+ }
320
+ for (const step of diagram.steps) {
321
+ const content = getStepContentBounds(step, centers, participantIndexes)
322
+ if (content) expandHorizontalBounds(bounds, content.leftX, content.rightX)
323
+ }
324
+ return bounds
325
+ }
326
+
327
+ function getFragmentFrameBounds(
328
+ centers: number[],
329
+ fragment: SequenceFragment,
330
+ nestingDepth = 0,
331
+ ): SequenceHorizontalBounds | undefined {
332
+ const leftParticipantX = centers[0]
333
+ const rightParticipantX = centers[centers.length - 1]
334
+ if (leftParticipantX === undefined || rightParticipantX === undefined) return undefined
335
+ const leftX = leftParticipantX - FRAGMENT_HORIZONTAL_OVERHANG + nestingDepth
336
+ const participantRightX = rightParticipantX + FRAGMENT_HORIZONTAL_OVERHANG - nestingDepth
337
+ return { leftX, rightX: Math.max(participantRightX, leftX + 2 + visualLength(fragmentLabelText(fragment)) + 1) }
338
+ }
339
+
340
+ function getFragmentFrameBoundsByStep(
341
+ centers: number[],
342
+ steps: SequenceStep[],
343
+ participantIndexes: Map<string, number>,
344
+ ): Map<number, SequenceHorizontalBounds> {
345
+ const boundsByStep = new Map<number, SequenceHorizontalBounds>()
346
+ const activeFrames: PendingFragmentFrame[] = []
347
+ for (const [index, step] of steps.entries()) {
348
+ if (step.type !== "fragment") {
349
+ const content = getStepContentBounds(step, centers, participantIndexes)
350
+ if (content) {
351
+ for (const frame of activeFrames) {
352
+ expandHorizontalBounds(frame.bounds, content.leftX - 1, content.rightX + 1)
353
+ }
354
+ }
355
+ continue
356
+ }
357
+ const bounds = getFragmentFrameBounds(centers, step.fragment, activeFrames.length)
358
+ if (!bounds) continue
359
+ if (step.fragment.kind === "alt" || step.fragment.kind === "loop") {
360
+ activeFrames.push({ startIndex: index, bounds: { ...bounds } })
361
+ continue
362
+ }
363
+ const frame = activeFrames[activeFrames.length - 1]
364
+ if (!frame) continue
365
+ expandHorizontalBounds(frame.bounds, bounds.leftX, bounds.rightX)
366
+ if (step.fragment.kind !== "end") continue
367
+ activeFrames.pop()
368
+ boundsByStep.set(frame.startIndex, frame.bounds)
369
+ const parent = activeFrames[activeFrames.length - 1]
370
+ if (parent) expandHorizontalBounds(parent.bounds, frame.bounds.leftX - 1, frame.bounds.rightX + 1)
371
+ }
372
+ for (const frame of activeFrames) boundsByStep.set(frame.startIndex, frame.bounds)
373
+ return boundsByStep
374
+ }
375
+
376
+ function resolveParticipantCenters(
377
+ diagram: SequenceDiagram,
378
+ participantIndexes: Map<string, number>,
379
+ minParticipantGap: number,
380
+ compact: boolean,
381
+ ): number[] {
382
+ const gaps = Array.from({ length: Math.max(0, diagram.participants.length - 1) }, (_, index) => {
383
+ const left = diagram.participants[index]!
384
+ const right = diagram.participants[index + 1]!
385
+ return Math.max(
386
+ minParticipantGap,
387
+ Math.ceil(participantHeaderWidth(left.label, compact) / 2) +
388
+ Math.ceil(participantHeaderWidth(right.label, compact) / 2) +
389
+ 6,
390
+ )
391
+ })
392
+ for (const message of diagram.messages) {
393
+ const fromIndex = participantIndexes.get(message.from) ?? -1
394
+ const toIndex = participantIndexes.get(message.to) ?? -1
395
+ if (fromIndex === toIndex && fromIndex >= 0 && fromIndex < diagram.participants.length - 1) {
396
+ gaps[fromIndex] = Math.max(
397
+ gaps[fromIndex]!,
398
+ selfMessageLoopWidth(message) +
399
+ Math.ceil(labelLinesWidth(mermaidLabelLines(diagram.participants[fromIndex + 1]!.label)) / 2) +
400
+ 2,
401
+ )
402
+ continue
403
+ }
404
+ if (fromIndex < 0 || toIndex < 0 || Math.abs(fromIndex - toIndex) !== 1) continue
405
+ const gapIndex = Math.min(fromIndex, toIndex)
406
+ gaps[gapIndex] = Math.max(gaps[gapIndex]!, messageWidth(message) + 6)
407
+ }
408
+ for (const step of diagram.steps) {
409
+ if (step.type !== "note") continue
410
+ const indexes = getParticipantIndexes(participantIndexes, step.note.over)
411
+ if (indexes.length === 1 && step.note.position && step.note.position !== "over") {
412
+ const participantIndex = indexes[0]!
413
+ const gapIndex = step.note.position === "left" ? participantIndex - 1 : participantIndex
414
+ if (gapIndex >= 0 && gapIndex < gaps.length) {
415
+ gaps[gapIndex] = Math.max(gaps[gapIndex]!, labelLinesWidth(noteLabelLines(step.note.label)) + 4)
416
+ }
417
+ continue
418
+ }
419
+ if (indexes.length !== 2 || Math.abs(indexes[0]! - indexes[1]!) !== 1) continue
420
+ const gapIndex = Math.min(indexes[0]!, indexes[1]!)
421
+ gaps[gapIndex] = Math.max(gaps[gapIndex]!, labelLinesWidth(noteLabelLines(step.note.label)) + 4)
422
+ }
423
+ const centers = [Math.max(1, Math.floor(participantHeaderWidth(diagram.participants[0]?.label ?? "", compact) / 2))]
424
+ for (let i = 1; i < diagram.participants.length; i++) centers[i] = centers[i - 1]! + gaps[i - 1]!
425
+ return centers
426
+ }
427
+
428
+ function separateExpandedGroupsFromExternalParticipants(
429
+ diagram: SequenceDiagram,
430
+ centers: number[],
431
+ participantIndexes: Map<string, number>,
432
+ ranges: SequenceGroupRange[],
433
+ compact: boolean,
434
+ ): number[] {
435
+ const adjusted = [...centers]
436
+ for (let boundary = 0; boundary < adjusted.length - 1; boundary++) {
437
+ const groups = resolveGroupBounds(diagram, adjusted, participantIndexes, ranges, compact)
438
+ const leftWidth = participantHeaderWidth(diagram.participants[boundary]!.label, compact)
439
+ const rightWidth = participantHeaderWidth(diagram.participants[boundary + 1]!.label, compact)
440
+ let leftRight = adjusted[boundary]! - Math.floor(leftWidth / 2) + leftWidth - 1
441
+ let rightLeft = adjusted[boundary + 1]! - Math.floor(rightWidth / 2)
442
+ let bordersGroup = false
443
+
444
+ for (const [index, range] of ranges.entries()) {
445
+ if (range.endIndex === boundary) {
446
+ leftRight = Math.max(leftRight, groups[index]!.rightX)
447
+ bordersGroup = true
448
+ }
449
+ if (range.startIndex === boundary + 1) {
450
+ rightLeft = Math.min(rightLeft, groups[index]!.leftX)
451
+ bordersGroup = true
452
+ }
453
+ }
454
+
455
+ if (!bordersGroup) continue
456
+ const shift = leftRight + GROUP_HORIZONTAL_PADDING + 1 - rightLeft
457
+ if (shift <= 0) continue
458
+ for (let participantIndex = boundary + 1; participantIndex < adjusted.length; participantIndex++) {
459
+ adjusted[participantIndex]! += shift
460
+ }
461
+ }
462
+ return adjusted
463
+ }
464
+
465
+ export function createSequencePlacementPlan(
466
+ diagram: SequenceDiagram,
467
+ options: Pick<SequenceDiagramRenderOptions, "compact" | "minParticipantGap"> = {},
468
+ ): SequencePlacementPlan {
469
+ if (diagram.participants.length === 0) {
470
+ return {
471
+ width: 0,
472
+ height: 0,
473
+ rows: {
474
+ participantHeaderTopY: 0,
475
+ participantHeaderY: 0,
476
+ participantRuleY: 0,
477
+ lifelineStartY: 0,
478
+ lifelineEndY: 0,
479
+ },
480
+ participants: [],
481
+ groups: [],
482
+ activations: [],
483
+ steps: [],
484
+ }
485
+ }
486
+ const indexes = createParticipantIndexMap(diagram)
487
+ const compact = options.compact ?? false
488
+ let centers = resolveParticipantCenters(
489
+ diagram,
490
+ indexes,
491
+ normalizeSequenceMinParticipantGap(options.minParticipantGap),
492
+ compact,
493
+ )
494
+ const ranges = getGroupRanges(diagram, indexes)
495
+ centers = separateExpandedGroupsFromExternalParticipants(diagram, centers, indexes, ranges, compact)
496
+ let groups = resolveGroupBounds(diagram, centers, indexes, ranges, compact)
497
+ let contentBounds = getDiagramContentBounds(diagram, centers, indexes, compact)
498
+ let frameBounds = getFragmentFrameBoundsByStep(centers, diagram.steps, indexes)
499
+ const fragmentBounds = (): SequenceHorizontalBounds => {
500
+ const result = { leftX: 0, rightX: 0 }
501
+ for (const bounds of frameBounds.values()) expandHorizontalBounds(result, bounds.leftX, bounds.rightX)
502
+ return result
503
+ }
504
+ let fragments = fragmentBounds()
505
+ const leftOverflow = Math.min(
506
+ groups.reduce((left, group) => Math.min(left, group.leftX), 0),
507
+ contentBounds.leftX,
508
+ fragments.leftX,
509
+ 0,
510
+ )
511
+ if (leftOverflow < 0) {
512
+ centers = centers.map((center) => center - leftOverflow)
513
+ groups = resolveGroupBounds(diagram, centers, indexes, ranges, compact)
514
+ contentBounds = getDiagramContentBounds(diagram, centers, indexes, compact)
515
+ frameBounds = getFragmentFrameBoundsByStep(centers, diagram.steps, indexes)
516
+ fragments = fragmentBounds()
517
+ }
518
+ const hasGroups = groups.length > 0
519
+ const participantLabelHeight = Math.max(
520
+ 1,
521
+ ...diagram.participants.map((participant) => mermaidLabelLines(participant.label).length),
522
+ )
523
+ const participantHeaderTopY = hasGroups ? 1 : 0
524
+ const participantHeaderY = participantHeaderTopY
525
+ const participantRuleY = participantHeaderTopY + (compact ? participantLabelHeight - 1 : participantLabelHeight)
526
+ const lifelineStartY = participantRuleY + 1
527
+ const stepStartY = lifelineStartY + 1
528
+ const width = Math.max(contentBounds.rightX + 1, ...groups.map((group) => group.rightX + 1), fragments.rightX + 1)
529
+ const baseHeight =
530
+ stepStartY + diagram.steps.reduce((total, step) => total + getStepHeight(step, centers, indexes, compact), 0)
531
+ const height = hasGroups ? Math.max(5, baseHeight + 1) : Math.max(3, baseHeight)
532
+ const lifelineEndY = hasGroups ? height - 2 : height - 1
533
+ const participants = diagram.participants.map((participant, index) => {
534
+ const centerX = centers[index]!
535
+ const width = participantHeaderWidth(participant.label, compact)
536
+ const headerLeftX = centerX - Math.floor(width / 2)
537
+ const labelLines = mermaidLabelLines(participant.label)
538
+ return {
539
+ participant,
540
+ centerX,
541
+ headerLeftX,
542
+ headerRightX: headerLeftX + width - 1,
543
+ labelLines,
544
+ }
545
+ })
546
+ const steps: SequenceStepPlacement[] = []
547
+ const activations: SequenceActivationPlacement[] = []
548
+ const activeByParticipant = new Map<string, Array<{ startY: number; depth: number }>>()
549
+ const lastEventYByParticipant = new Map<string, number>()
550
+ const openActivation = (participant: string, y: number): void => {
551
+ const active = activeByParticipant.get(participant) ?? []
552
+ active.push({ startY: y, depth: active.length })
553
+ activeByParticipant.set(participant, active)
554
+ }
555
+ const closeActivation = (participant: string, y: number): void => {
556
+ const active = activeByParticipant.get(participant)
557
+ const opened = active?.pop()
558
+ const participantIndex = indexes.get(participant)
559
+ if (!opened || participantIndex === undefined) return
560
+ activations.push({
561
+ participant,
562
+ centerX: centers[participantIndex]!,
563
+ startY: opened.startY,
564
+ endY: y,
565
+ depth: opened.depth,
566
+ })
567
+ }
568
+ let stepY = stepStartY
569
+ const activeFrames: ActiveFragmentFrame[] = []
570
+ for (const [stepIndex, step] of diagram.steps.entries()) {
571
+ if (step.type === "activation") {
572
+ const eventY = Math.min(lastEventYByParticipant.get(step.activation.participant) ?? stepY, lifelineEndY)
573
+ if (step.activation.active) openActivation(step.activation.participant, eventY)
574
+ else closeActivation(step.activation.participant, eventY)
575
+ continue
576
+ }
577
+ const stepHeight = getStepHeight(step, centers, indexes, compact)
578
+ if (step.type === "note") {
579
+ const noteIndexes = getParticipantIndexes(indexes, step.note.over)
580
+ if (noteIndexes.length > 0) {
581
+ const centerX = Math.floor((centers[Math.min(...noteIndexes)]! + centers[Math.max(...noteIndexes)]!) / 2)
582
+ const textLines = noteLabelLines(step.note.label)
583
+ const width = labelLinesWidth(textLines)
584
+ const textX =
585
+ step.note.position === "left"
586
+ ? centerX - width - 2
587
+ : step.note.position === "right"
588
+ ? centerX + 2
589
+ : centerX - Math.floor(width / 2)
590
+ steps.push({ type: "note", note: step.note, textLines, textX, textY: stepY + 1 })
591
+ }
592
+ stepY += stepHeight
593
+ continue
594
+ }
595
+ if (step.type === "fragment") {
596
+ let bounds = frameBounds.get(stepIndex) ?? getFragmentFrameBounds(centers, step.fragment)
597
+ let wallsBefore: SequenceWallPlacement | undefined
598
+ if (step.fragment.kind === "alt" || step.fragment.kind === "loop") {
599
+ if (bounds) activeFrames.push({ bounds, boundaryY: stepY })
600
+ } else {
601
+ const frame = activeFrames[activeFrames.length - 1]
602
+ if (frame) {
603
+ bounds = frame.bounds
604
+ wallsBefore = { bounds, startY: frame.boundaryY + 1, endY: stepY - 1 }
605
+ if (step.fragment.kind === "end") activeFrames.pop()
606
+ else frame.boundaryY = stepY
607
+ }
608
+ }
609
+ if (bounds)
610
+ steps.push({
611
+ type: "fragment",
612
+ fragment: step.fragment,
613
+ labelText: fragmentLabelText(step.fragment),
614
+ bounds,
615
+ y: stepY,
616
+ wallsBefore,
617
+ })
618
+ stepY += stepHeight
619
+ continue
620
+ }
621
+ const fromIndex = indexes.get(step.message.from) ?? -1
622
+ const toIndex = indexes.get(step.message.to) ?? -1
623
+ if (fromIndex < 0 || toIndex < 0) continue
624
+ const labelLines = messageLabelLines(messageLabelText(step.message))
625
+ if (fromIndex === toIndex) {
626
+ const centerX = centers[fromIndex]!
627
+ const bottomY = stepY + labelLines.length + 1
628
+ steps.push({
629
+ type: "selfMessage",
630
+ message: step.message,
631
+ labelLines,
632
+ centerX,
633
+ rightX: centerX + selfMessageLoopWidthForLines(labelLines),
634
+ topY: stepY,
635
+ bottomY,
636
+ })
637
+ if (step.message.activate) openActivation(step.message.activate, bottomY)
638
+ if (step.message.deactivate) closeActivation(step.message.deactivate, bottomY)
639
+ lastEventYByParticipant.set(step.message.from, bottomY)
640
+ } else {
641
+ const fromX = centers[fromIndex]!
642
+ const toX = centers[toIndex]!
643
+ const direction: 1 | -1 = toX > fromX ? 1 : -1
644
+ const leftX = Math.min(fromX, toX)
645
+ const rightX = Math.max(fromX, toX)
646
+ const inlineLabel = inlineMessageLabel(step.message, labelLines, fromX, toX, compact)
647
+ const arrowY = inlineLabel ? stepY : stepY + labelLines.length
648
+ const renderedLabelWidth = inlineLabel ? visualLength(inlineLabel) : labelLinesWidth(labelLines)
649
+ const labelX = inlineLabel ? Math.floor((leftX + rightX - renderedLabelWidth) / 2) : leftX + 2
650
+ steps.push({
651
+ type: "message",
652
+ message: step.message,
653
+ labelLines,
654
+ labelX,
655
+ labelY: stepY,
656
+ arrowY,
657
+ fromX,
658
+ toX,
659
+ leftX,
660
+ rightX,
661
+ direction,
662
+ headX: arrowHeadX(toX, direction, step.message.head),
663
+ inlineLabel,
664
+ })
665
+ if (step.message.activate) openActivation(step.message.activate, arrowY)
666
+ if (step.message.deactivate) closeActivation(step.message.deactivate, arrowY)
667
+ lastEventYByParticipant.set(step.message.from, arrowY)
668
+ lastEventYByParticipant.set(step.message.to, arrowY)
669
+ }
670
+ stepY += stepHeight
671
+ }
672
+ for (const [participant, active] of activeByParticipant) {
673
+ while (active.length > 0) closeActivation(participant, lifelineEndY)
674
+ }
675
+ return {
676
+ width,
677
+ height,
678
+ rows: { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY },
679
+ participants,
680
+ groups,
681
+ activations,
682
+ steps,
683
+ }
684
+ }
@@ -0,0 +1,22 @@
1
+ import type { StyledText } from "@opentui/core"
2
+ import type { DiagramCanvas } from "../core/canvas.js"
3
+ import { renderDiagramGridStyledText } from "../core/render-grid.js"
4
+ import { sequenceStyleBackgroundColor, sequenceStyleColor, type SequenceStyleColors } from "./style.js"
5
+ import type { SequenceCellStyle } from "./types.js"
6
+
7
+ export type SequenceGrid = DiagramCanvas<SequenceCellStyle>
8
+
9
+ export function renderSequenceGridText(grid: SequenceGrid): string {
10
+ return grid.toString()
11
+ }
12
+
13
+ export function renderSequenceGridStyledText(
14
+ grid: SequenceGrid,
15
+ colors: Parameters<typeof sequenceStyleColor>[1],
16
+ ): StyledText {
17
+ return renderDiagramGridStyledText(
18
+ grid,
19
+ (run) => sequenceStyleColor(run.style, colors),
20
+ (run) => sequenceStyleBackgroundColor(run.style, colors as Required<SequenceStyleColors>),
21
+ )
22
+ }