@zyro-sec/merman 0.0.0-stage → 1.0.2

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 (92) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.test.ts +203 -0
  4. package/src/core/canvas.ts +228 -0
  5. package/src/core/color/style.test.ts +24 -0
  6. package/src/core/color/style.ts +56 -0
  7. package/src/core/drawing.test.ts +116 -0
  8. package/src/core/drawing.ts +301 -0
  9. package/src/core/geometry.test.ts +112 -0
  10. package/src/core/geometry.ts +347 -0
  11. package/src/core/mermaid.ts +38 -0
  12. package/src/core/render-grid.ts +51 -0
  13. package/src/core/spatial.test.ts +87 -0
  14. package/src/core/spatial.ts +243 -0
  15. package/src/core/text-lines.ts +32 -0
  16. package/src/core/text.test.ts +33 -0
  17. package/src/core/text.ts +44 -0
  18. package/src/detect.ts +17 -0
  19. package/src/diagnostics.ts +16 -0
  20. package/src/flowchart/drawing.ts +340 -0
  21. package/src/flowchart/flowchart.test.ts +2800 -0
  22. package/src/flowchart/labels.test.ts +127 -0
  23. package/src/flowchart/labels.ts +144 -0
  24. package/src/flowchart/layout.ts +1427 -0
  25. package/src/flowchart/options.ts +12 -0
  26. package/src/flowchart/parser.ts +467 -0
  27. package/src/flowchart/render.ts +10 -0
  28. package/src/flowchart/routing.test.ts +368 -0
  29. package/src/flowchart/routing.ts +1542 -0
  30. package/src/flowchart/style.ts +79 -0
  31. package/src/flowchart/types.ts +65 -0
  32. package/src/gantt/diagram.test.ts +124 -0
  33. package/src/gantt/diagram.ts +8 -0
  34. package/src/gantt/drawing.ts +191 -0
  35. package/src/gantt/parser.ts +161 -0
  36. package/src/gantt/render-grid.ts +17 -0
  37. package/src/gantt/style.ts +36 -0
  38. package/src/gantt/types.ts +44 -0
  39. package/src/gitgraph/diagram.test.ts +183 -0
  40. package/src/gitgraph/diagram.ts +8 -0
  41. package/src/gitgraph/drawing.ts +234 -0
  42. package/src/gitgraph/parser.ts +219 -0
  43. package/src/gitgraph/render-grid.ts +17 -0
  44. package/src/gitgraph/style.ts +37 -0
  45. package/src/gitgraph/types.ts +36 -0
  46. package/src/layout-audit.test.ts +92 -0
  47. package/src/markdown.ts +336 -0
  48. package/src/palette.test.ts +103 -0
  49. package/src/palette.ts +75 -0
  50. package/src/plugin.ts +15 -0
  51. package/src/sequence/diagram.test.ts +757 -0
  52. package/src/sequence/diagram.ts +8 -0
  53. package/src/sequence/drawing.ts +287 -0
  54. package/src/sequence/options.ts +8 -0
  55. package/src/sequence/parser.ts +282 -0
  56. package/src/sequence/placement.test.ts +219 -0
  57. package/src/sequence/placement.ts +684 -0
  58. package/src/sequence/render-grid.ts +22 -0
  59. package/src/sequence/style.ts +81 -0
  60. package/src/sequence/types.ts +74 -0
  61. package/src/state/diagram.test.ts +1386 -0
  62. package/src/state/diagram.ts +8 -0
  63. package/src/state/drawing.ts +360 -0
  64. package/src/state/endpoint.ts +15 -0
  65. package/src/state/layout.test.ts +314 -0
  66. package/src/state/layout.ts +1134 -0
  67. package/src/state/note.ts +59 -0
  68. package/src/state/options.ts +11 -0
  69. package/src/state/parser.ts +224 -0
  70. package/src/state/render-grid.ts +22 -0
  71. package/src/state/routing.test.ts +693 -0
  72. package/src/state/routing.ts +1522 -0
  73. package/src/state/search.ts +103 -0
  74. package/src/state/style.test.ts +113 -0
  75. package/src/state/style.ts +52 -0
  76. package/src/state/types.ts +63 -0
  77. package/src/state/visible-model.test.ts +84 -0
  78. package/src/state/visible-model.ts +77 -0
  79. package/src/test/diagnostics.test.ts +129 -0
  80. package/src/test/diagram.ts +32 -0
  81. package/src/test/layout-audit/fixtures.ts +538 -0
  82. package/src/test/layout-audit/harness.ts +522 -0
  83. package/src/test/markdown.test.ts +474 -0
  84. package/src/timeline/diagram.test.ts +188 -0
  85. package/src/timeline/diagram.ts +8 -0
  86. package/src/timeline/drawing.ts +109 -0
  87. package/src/timeline/parser.ts +119 -0
  88. package/src/timeline/render-grid.ts +17 -0
  89. package/src/timeline/style.ts +36 -0
  90. package/src/timeline/types.ts +31 -0
  91. package/tsconfig.json +10 -0
  92. package/README.md +0 -3
@@ -0,0 +1,17 @@
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 type { GitGraphStyleColors } from "./style.js"
5
+ import type { GitGraphCellStyle } from "./types.js"
6
+
7
+ export type GitGraphGrid = DiagramCanvas<GitGraphCellStyle>
8
+
9
+ export function renderGitGraphGridText(grid: GitGraphGrid): string {
10
+ return grid.toString({ trimBottom: true })
11
+ }
12
+
13
+ export function renderGitGraphGridStyledText(grid: GitGraphGrid, colors: GitGraphStyleColors): StyledText {
14
+ return renderDiagramGridStyledText(grid, (run) => (run.style ? colors[run.style] : undefined), undefined, {
15
+ trimBottom: true,
16
+ })
17
+ }
@@ -0,0 +1,37 @@
1
+ import { RGBA } from "@opentui/core"
2
+ import { rgba, type DiagramRgb } from "../core/color/style.js"
3
+ import type { GitGraphCellStyle } from "./types.js"
4
+
5
+ const BRANCH_RGB = [
6
+ [134, 225, 200],
7
+ [230, 177, 126],
8
+ [154, 184, 169],
9
+ [198, 160, 246],
10
+ [126, 189, 230],
11
+ [225, 134, 166],
12
+ [190, 210, 120],
13
+ [180, 180, 210],
14
+ ] as const satisfies readonly DiagramRgb[]
15
+
16
+ export type GitGraphStyleColors = Required<Record<GitGraphCellStyle, RGBA>>
17
+
18
+ export function resolveGitGraphStyleColors(
19
+ colors: Partial<Record<"primary" | "secondary" | "muted" | "warning" | "text", RGBA | undefined>> = {},
20
+ ): GitGraphStyleColors {
21
+ const rail = colors.muted ?? rgba([111, 138, 126])
22
+ return {
23
+ branch0: rail,
24
+ branch1: rail,
25
+ branch2: rail,
26
+ branch3: rail,
27
+ branch4: rail,
28
+ branch5: rail,
29
+ branch6: rail,
30
+ branch7: rail,
31
+ commit: colors.primary ?? rgba(BRANCH_RGB[0]),
32
+ merge: colors.secondary ?? rgba(BRANCH_RGB[2]),
33
+ highlight: colors.warning ?? rgba(BRANCH_RGB[1]),
34
+ reverse: colors.warning ?? rgba(BRANCH_RGB[5]),
35
+ label: colors.text ?? rgba([228, 239, 232]),
36
+ }
37
+ }
@@ -0,0 +1,36 @@
1
+ export type GitGraphDirection = "LR" | "TB" | "BT"
2
+ export type GitGraphCommitType = "NORMAL" | "REVERSE" | "HIGHLIGHT"
3
+
4
+ export interface GitGraphBranch {
5
+ name: string
6
+ order?: number
7
+ head?: string
8
+ }
9
+
10
+ export interface GitGraphCommit {
11
+ id: string
12
+ message?: string
13
+ tags: string[]
14
+ type: GitGraphCommitType
15
+ branch: string
16
+ parents: string[]
17
+ }
18
+
19
+ export interface GitGraphDiagram {
20
+ direction: GitGraphDirection
21
+ branches: GitGraphBranch[]
22
+ commits: GitGraphCommit[]
23
+ }
24
+
25
+ export interface GitGraphDiagramRenderOptions {
26
+ /** Parsed for Mermaid compatibility. Git graphs always use a vertical terminal layout. */
27
+ direction?: GitGraphDirection
28
+ }
29
+
30
+ export type GitGraphCellStyle =
31
+ | `branch${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`
32
+ | "commit"
33
+ | "merge"
34
+ | "highlight"
35
+ | "reverse"
36
+ | "label"
@@ -0,0 +1,92 @@
1
+ import { expect, test } from "bun:test"
2
+ import { auditAllFixtures, auditFixture, summarizeAudits, worstAudits } from "./test/layout-audit/harness.js"
3
+ import { layoutFixtures } from "./test/layout-audit/fixtures.js"
4
+
5
+ test("audits deterministic flowchart and state layout families", () => {
6
+ const fixtures = layoutFixtures()
7
+ const flowcharts = fixtures.filter((fixture) => fixture.kind === "flowchart")
8
+ const states = fixtures.filter((fixture) => fixture.kind === "state")
9
+ expect(flowcharts.length).toBeGreaterThanOrEqual(100)
10
+ expect(states.length).toBeGreaterThanOrEqual(100)
11
+ expect(new Set(fixtures.map((fixture) => fixture.id)).size).toBe(fixtures.length)
12
+
13
+ const startedAt = performance.now()
14
+ const audits = auditAllFixtures()
15
+ const elapsedMs = performance.now() - startedAt
16
+ const violations = audits.flatMap((audit) =>
17
+ audit.violations.map((violation) => `${audit.fixture.id} @${audit.viewport}: ${violation}`),
18
+ )
19
+ const summary = summarizeAudits(audits)
20
+
21
+ expect(audits.length).toBeGreaterThanOrEqual(fixtures.length)
22
+ expect(violations).toEqual([])
23
+ for (const audit of audits.filter((audit) => audit.fixture.kind === "state")) {
24
+ expect(audit.viewport).toBe(audit.fixture.profile === "short" ? 60 : audit.fixture.profile === "unicode" ? 80 : 120)
25
+ }
26
+ for (const id of ["state/chain/lr-long", "state/chain/rl-long"]) {
27
+ const audit = audits.find((candidate) => candidate.fixture.id === id)!
28
+ expect(audit.viewport).toBe(120)
29
+ expect([audit.metrics.width, audit.metrics.height, audit.metrics.overflow]).toEqual([84, 41, 0])
30
+ }
31
+ expect(
32
+ audits
33
+ .filter((audit) => audit.fixture.id === "flowchart/deployment-architecture/curated")
34
+ .map((audit) => audit.viewport),
35
+ ).toEqual([60, 80, 120])
36
+ // decision-loops is a deliberately crossing-heavy family; ceiling it separately so it cannot absorb the
37
+ // p95 headroom of the established families.
38
+ const established = summarizeAudits(audits.filter((audit) => audit.fixture.family !== "decision-loops")).total
39
+ expect(established.area.max).toBeLessThanOrEqual(11_011)
40
+ expect(established.area.p95).toBeLessThanOrEqual(5_313)
41
+ expect(established.bends.max).toBeLessThanOrEqual(30)
42
+ expect(established.bends.p95).toBeLessThanOrEqual(11)
43
+ expect(established.crossings.total).toBeLessThanOrEqual(40)
44
+ expect(established.crossings.max).toBeLessThanOrEqual(3)
45
+ expect(established.routeLength.max).toBeLessThanOrEqual(930)
46
+ expect(established.routeLength.p95).toBeLessThanOrEqual(364)
47
+ expect(established.sharedRouteCells.max).toBeLessThanOrEqual(547)
48
+ expect(established.sharedRouteCells.p95).toBeLessThanOrEqual(122)
49
+ expect(established.overflow.max).toBeLessThanOrEqual(170)
50
+ expect(established.overflow.p95).toBeLessThanOrEqual(99)
51
+ const decisionLoops = summarizeAudits(audits.filter((audit) => audit.fixture.family === "decision-loops")).total
52
+ expect(decisionLoops.runs).toBeGreaterThan(0)
53
+ expect(decisionLoops.area.max).toBeLessThanOrEqual(8_784)
54
+ expect(decisionLoops.bends.max).toBeLessThanOrEqual(24)
55
+ expect(decisionLoops.crossings.total).toBeLessThanOrEqual(24)
56
+ expect(decisionLoops.crossings.max).toBeLessThanOrEqual(8)
57
+ expect(decisionLoops.routeLength.max).toBeLessThanOrEqual(526)
58
+ expect(decisionLoops.sharedRouteCells.max).toBeLessThanOrEqual(352)
59
+ expect(decisionLoops.overflow.max).toBeLessThanOrEqual(84)
60
+ expect(summary.state.crossings.total).toBe(0)
61
+
62
+ for (const fixture of [...Map.groupBy(fixtures, (candidate) => `${candidate.kind}/${candidate.family}`).values()].map(
63
+ (family) => family[0]!,
64
+ )) {
65
+ const first = auditFixture(fixture, 80)
66
+ const second = auditFixture(fixture, 80)
67
+ expect(second.output).toBe(first.output)
68
+ expect(second.metrics).toEqual(first.metrics)
69
+ expect(second.violations).toEqual(first.violations)
70
+ }
71
+
72
+ console.log(
73
+ `[layout-audit] ${fixtures.length} sources, ${audits.length} runs, ${elapsedMs.toFixed(0)}ms`,
74
+ JSON.stringify({
75
+ summary,
76
+ worst: {
77
+ area: worstAudits(audits, "area", 3).map((audit) => [audit.fixture.id, audit.viewport, audit.metrics.area]),
78
+ bends: worstAudits(audits, "bends", 3).map((audit) => [audit.fixture.id, audit.viewport, audit.metrics.bends]),
79
+ crossings: worstAudits(audits, "crossings", 3).map((audit) => [
80
+ audit.fixture.id,
81
+ audit.viewport,
82
+ audit.metrics.crossings,
83
+ ]),
84
+ overflow: worstAudits(audits, "overflow", 3).map((audit) => [
85
+ audit.fixture.id,
86
+ audit.viewport,
87
+ audit.metrics.overflow,
88
+ ]),
89
+ },
90
+ }),
91
+ )
92
+ }, 40_000)
@@ -0,0 +1,336 @@
1
+ import {
2
+ TextRenderable,
3
+ RenderableEvents,
4
+ createMarkdownCodeBlockRenderer,
5
+ parseColor,
6
+ type ColorInput,
7
+ type MarkdownOptions,
8
+ type MarkdownCodeBlockRenderer,
9
+ type MouseEvent,
10
+ type RenderContext,
11
+ type RGBA,
12
+ type StyledText,
13
+ } from "@opentui/core"
14
+ import { MermaidSyntaxError } from "./diagnostics.js"
15
+ import type { OpenCodeDiagramPalette } from "./palette.js"
16
+ import { DiagramCanvasSizeError } from "./core/canvas.js"
17
+ import { detectMermaidDiagram } from "./detect.js"
18
+ import { drawFlowchartDiagramGrid } from "./flowchart/drawing.js"
19
+ import { parseMermaidFlowchartDiagram } from "./flowchart/parser.js"
20
+ import { renderGridStyledText, resolveFlowchartStyleColors } from "./flowchart/style.js"
21
+ import { drawGanttDiagramGrid } from "./gantt/drawing.js"
22
+ import { parseMermaidGanttDiagram } from "./gantt/parser.js"
23
+ import { renderGanttGridStyledText } from "./gantt/render-grid.js"
24
+ import { resolveGanttStyleColors } from "./gantt/style.js"
25
+ import type { GanttDiagramRenderOptions } from "./gantt/types.js"
26
+ import { drawGitGraphDiagramGrid } from "./gitgraph/drawing.js"
27
+ import { parseMermaidGitGraphDiagram } from "./gitgraph/parser.js"
28
+ import { renderGitGraphGridStyledText } from "./gitgraph/render-grid.js"
29
+ import { resolveGitGraphStyleColors } from "./gitgraph/style.js"
30
+ import { drawSequenceDiagramGrid } from "./sequence/drawing.js"
31
+ import { parseMermaidSequenceDiagram } from "./sequence/parser.js"
32
+ import { renderSequenceGridStyledText } from "./sequence/render-grid.js"
33
+ import { resolveSequenceStyleColors } from "./sequence/style.js"
34
+ import { drawStateDiagramGrid } from "./state/drawing.js"
35
+ import { parseMermaidStateDiagram } from "./state/parser.js"
36
+ import { renderStateGridStyledText } from "./state/render-grid.js"
37
+ import { resolveStateStyleColors } from "./state/style.js"
38
+ import { drawTimelineDiagramGrid } from "./timeline/drawing.js"
39
+ import { parseMermaidTimelineDiagram } from "./timeline/parser.js"
40
+ import { renderTimelineGridStyledText } from "./timeline/render-grid.js"
41
+ import { resolveTimelineStyleColors } from "./timeline/style.js"
42
+
43
+ type DiagramKind = NonNullable<ReturnType<typeof detectMermaidDiagram>>
44
+
45
+ interface PreparedDiagram {
46
+ readonly kind: DiagramKind
47
+ readonly source: string
48
+ readonly text: StyledText
49
+ readonly height: number
50
+ }
51
+
52
+ export interface MermaidMarkdownRendererOptions {
53
+ /** Use terminal-optimized diagram spacing. Defaults to true. */
54
+ compact?: boolean
55
+ /** Fold responsive horizontal diagrams that exceed this width. Defaults to 120 columns. */
56
+ layoutMaxWidth?: number
57
+ /** Gantt-specific terminal rendering options. */
58
+ gantt?: Omit<GanttDiagramRenderOptions, "layoutMaxWidth">
59
+ colors?: Partial<Record<keyof OpenCodeDiagramPalette, ColorInput>>
60
+ }
61
+
62
+ function color(value: ColorInput | undefined): RGBA | undefined {
63
+ return value === undefined ? undefined : parseColor(value)
64
+ }
65
+
66
+ class StaticDiagramRenderable extends TextRenderable {
67
+ constructor(ctx: RenderContext, prepared: PreparedDiagram) {
68
+ super(ctx, {
69
+ content: prepared.text,
70
+ width: "100%",
71
+ height: prepared.height,
72
+ wrapMode: "none",
73
+ selectable: false,
74
+ marginTop: 1,
75
+ })
76
+ let dragX: number | undefined
77
+ this.onMouseDown = (event: MouseEvent) => {
78
+ if (event.button !== 0) return
79
+ ctx.clearSelection()
80
+ dragX = event.x
81
+ event.preventDefault()
82
+ event.stopPropagation()
83
+ }
84
+ this.onMouseDrag = (event: MouseEvent) => {
85
+ event.preventDefault()
86
+ event.stopPropagation()
87
+ if (dragX === undefined) return
88
+ const dx = event.x - dragX
89
+ dragX = event.x
90
+ if (dx) this.scrollX -= dx
91
+ }
92
+ this.onMouseDragEnd = (event: MouseEvent) => {
93
+ dragX = undefined
94
+ event.preventDefault()
95
+ event.stopPropagation()
96
+ }
97
+ this.onMouseUp = (event: MouseEvent) => {
98
+ if (event.button !== 0) return
99
+ dragX = undefined
100
+ event.preventDefault()
101
+ event.stopPropagation()
102
+ }
103
+ this.onMouseScroll = (event: MouseEvent) => {
104
+ const scroll = event.scroll
105
+ if (!scroll || (scroll.direction !== "left" && scroll.direction !== "right")) return
106
+ event.preventDefault()
107
+ event.stopPropagation()
108
+ }
109
+ }
110
+ }
111
+
112
+ function prepareDiagram(
113
+ kind: DiagramKind,
114
+ source: string,
115
+ options: MermaidMarkdownRendererOptions,
116
+ layoutMaxWidth: number,
117
+ ): PreparedDiagram {
118
+ const colors = options.colors ?? {}
119
+ const compact = options.compact ?? true
120
+ switch (kind) {
121
+ case "flowchart": {
122
+ const grid = drawFlowchartDiagramGrid(parseMermaidFlowchartDiagram(source), {
123
+ compact,
124
+ layoutMaxWidth,
125
+ })
126
+ const size = grid.getTextSize({ trimTop: true, trimBottom: true })
127
+ return {
128
+ kind,
129
+ source,
130
+ text: renderGridStyledText(
131
+ grid,
132
+ resolveFlowchartStyleColors({
133
+ node: color(colors.boxText ?? colors.primary),
134
+ nodeBorder: color(colors.boxBorder ?? colors.muted),
135
+ database: color(colors.boxText ?? colors.primary),
136
+ databaseBorder: color(colors.boxBorder ?? colors.muted),
137
+ edge: color(colors.line ?? colors.secondary),
138
+ label: color(colors.text),
139
+ group: color(colors.group ?? colors.muted),
140
+ groupLabel: color(colors.groupText ?? colors.group ?? colors.muted),
141
+ }),
142
+ { label: color(colors.labelBackground) },
143
+ ),
144
+ height: size.height,
145
+ }
146
+ }
147
+ case "gitGraph": {
148
+ const grid = drawGitGraphDiagramGrid(parseMermaidGitGraphDiagram(source))
149
+ const size = grid.getTextSize({ trimBottom: true })
150
+ return {
151
+ kind,
152
+ source,
153
+ text: renderGitGraphGridStyledText(
154
+ grid,
155
+ resolveGitGraphStyleColors({
156
+ primary: color(colors.primary),
157
+ secondary: color(colors.secondary),
158
+ muted: color(colors.muted),
159
+ warning: color(colors.warning),
160
+ text: color(colors.text),
161
+ }),
162
+ ),
163
+ height: size.height,
164
+ }
165
+ }
166
+ case "gantt": {
167
+ const grid = drawGanttDiagramGrid(parseMermaidGanttDiagram(source), { ...options.gantt, layoutMaxWidth })
168
+ const size = grid.getTextSize({ trimBottom: true })
169
+ return {
170
+ kind,
171
+ source,
172
+ text: renderGanttGridStyledText(
173
+ grid,
174
+ resolveGanttStyleColors({
175
+ title: color(colors.text),
176
+ axis: color(colors.muted),
177
+ background: color(colors.background),
178
+ section: color(colors.secondary),
179
+ task: color(colors.primary),
180
+ active: color(colors.primary),
181
+ critical: color(colors.warning),
182
+ done: color(colors.muted),
183
+ }),
184
+ ),
185
+ height: size.height,
186
+ }
187
+ }
188
+ case "sequence": {
189
+ const grid = drawSequenceDiagramGrid(parseMermaidSequenceDiagram(source), { compact })
190
+ const size = grid.getTextSize()
191
+ return {
192
+ kind,
193
+ source,
194
+ text: renderSequenceGridStyledText(
195
+ grid,
196
+ resolveSequenceStyleColors({
197
+ participant: color(colors.primary),
198
+ lifeline: color(colors.muted),
199
+ group: color(colors.secondary),
200
+ request: color(colors.request ?? colors.primary),
201
+ response: color(colors.response ?? colors.primary),
202
+ fragment: color(colors.secondary),
203
+ fragmentLabelBg: color(colors.background),
204
+ note: color(colors.note ?? colors.warning),
205
+ noteBg: color(colors.noteBackground ?? colors.background),
206
+ }),
207
+ ),
208
+ height: size.height,
209
+ }
210
+ }
211
+ case "state": {
212
+ const grid = drawStateDiagramGrid(parseMermaidStateDiagram(source), { layoutMaxWidth })
213
+ const size = grid.getTextSize({ trimTop: true, trimBottom: true })
214
+ return {
215
+ kind,
216
+ source,
217
+ text: renderStateGridStyledText(
218
+ grid,
219
+ resolveStateStyleColors({
220
+ state: color(colors.boxText ?? colors.primary),
221
+ stateBorder: color(colors.boxBorder ?? colors.primary),
222
+ composite: color(colors.group ?? colors.muted),
223
+ compositeLabel: color(colors.groupText ?? colors.group ?? colors.muted),
224
+ transition: color(colors.line ?? colors.secondary),
225
+ label: color(colors.text),
226
+ noteBorder: color(colors.noteBorder ?? colors.warning),
227
+ noteText: color(colors.noteText ?? colors.warning),
228
+ noteConnector: color(colors.noteConnector ?? colors.muted),
229
+ start: color(colors.marker ?? colors.muted),
230
+ end: color(colors.marker ?? colors.muted),
231
+ choice: color(colors.marker ?? colors.secondary),
232
+ }),
233
+ { label: color(colors.labelBackground) },
234
+ ),
235
+ height: size.height,
236
+ }
237
+ }
238
+ case "timeline": {
239
+ const grid = drawTimelineDiagramGrid(parseMermaidTimelineDiagram(source))
240
+ const size = grid.getTextSize({ trimBottom: true })
241
+ return {
242
+ kind,
243
+ source,
244
+ text: renderTimelineGridStyledText(
245
+ grid,
246
+ resolveTimelineStyleColors({
247
+ title: color(colors.text),
248
+ section: color(colors.secondary),
249
+ period: color(colors.warning),
250
+ spine: color(colors.muted),
251
+ event: color(colors.primary),
252
+ }),
253
+ ),
254
+ height: size.height,
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ /** Create an OpenTUI Markdown node renderer for fenced Mermaid diagrams. */
261
+ export function createMermaidMarkdownRenderer(
262
+ ctx: RenderContext,
263
+ input: MermaidMarkdownRendererOptions | (() => MermaidMarkdownRendererOptions) = {},
264
+ ): NonNullable<MarkdownOptions["renderBlock"]> {
265
+ return createMarkdownCodeBlockRenderer({ mermaid: createMermaidCodeBlockRenderer(ctx, input) })!
266
+ }
267
+
268
+ export function createMermaidCodeBlockRenderer(
269
+ ctx: RenderContext,
270
+ input: MermaidMarkdownRendererOptions | (() => MermaidMarkdownRendererOptions) = {},
271
+ ): MarkdownCodeBlockRenderer {
272
+ const lastGood = new Map<string, PreparedDiagram>()
273
+ return (token, context) => {
274
+ const kind = detectMermaidDiagram(token.text)
275
+ if (!kind) return undefined
276
+ // OpenTUI's default block ID is the stable identity available for this fence across streaming updates.
277
+ const key = context.defaultRender()?.id
278
+ const options = typeof input === "function" ? input() : input
279
+ const configuredMaxWidth =
280
+ options.layoutMaxWidth === undefined ? 120 : Math.max(1, Math.trunc(options.layoutMaxWidth))
281
+ const layoutMaxWidth = Math.min(configuredMaxWidth, Math.max(1, Math.trunc(ctx.width)))
282
+
283
+ try {
284
+ const prepared = prepareDiagram(kind, token.text, options, layoutMaxWidth)
285
+ const diagram = new StaticDiagramRenderable(ctx, prepared)
286
+ if (key) claimLastGood(key, prepared, diagram, lastGood)
287
+ return diagram
288
+ } catch (error) {
289
+ if (error instanceof MermaidSyntaxError) {
290
+ const previous = key ? lastGood.get(key) : undefined
291
+ if (previous?.kind === kind) {
292
+ const diagram = new StaticDiagramRenderable(ctx, previous)
293
+ claimLastGood(key!, previous, diagram, lastGood)
294
+ return diagram
295
+ }
296
+
297
+ const lines = token.text.split("\n")
298
+ if (error.lineNumber <= 2 || lines.slice(error.lineNumber).some((line) => line.trim())) return undefined
299
+
300
+ try {
301
+ const prepared = prepareDiagram(
302
+ kind,
303
+ lines.slice(0, error.lineNumber - 1).join("\n"),
304
+ options,
305
+ layoutMaxWidth,
306
+ )
307
+ if (!prepared.height) return undefined
308
+ const diagram = new StaticDiagramRenderable(ctx, prepared)
309
+ if (key) claimLastGood(key, prepared, diagram, lastGood)
310
+ return diagram
311
+ } catch (error) {
312
+ if (error instanceof MermaidSyntaxError || error instanceof DiagramCanvasSizeError) return undefined
313
+ throw error
314
+ }
315
+ }
316
+ if (error instanceof DiagramCanvasSizeError) return undefined
317
+ throw error
318
+ }
319
+ }
320
+ }
321
+
322
+ function claimLastGood(
323
+ key: string,
324
+ value: PreparedDiagram,
325
+ owner: StaticDiagramRenderable,
326
+ cache: Map<string, PreparedDiagram>,
327
+ ): void {
328
+ const claim = { ...value }
329
+ cache.set(key, claim)
330
+ owner.once(RenderableEvents.DESTROYED, () => {
331
+ // Reconciliation destroys the old block before synchronously creating its replacement.
332
+ queueMicrotask(() => {
333
+ if (cache.get(key) === claim) cache.delete(key)
334
+ })
335
+ })
336
+ }
@@ -0,0 +1,103 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { RGBA } from "@opentui/core"
3
+ import { blendColor } from "./core/color/style.js"
4
+ import { createOpenCodeDiagramPalette, resolveOpenCodeDiagramPalette } from "./palette.js"
5
+
6
+ type Rgb = readonly [number, number, number]
7
+
8
+ const rgb = (value: Rgb) => RGBA.fromInts(...value)
9
+
10
+ describe("OpenCode diagram palette", () => {
11
+ test.each([
12
+ {
13
+ name: "dark theme",
14
+ text: [230, 232, 240],
15
+ subdued: [114, 120, 138],
16
+ secondary: [172, 176, 189],
17
+ muted: [149, 154, 169],
18
+ },
19
+ {
20
+ name: "light theme",
21
+ text: [32, 35, 43],
22
+ subdued: [119, 125, 138],
23
+ secondary: [76, 80, 91],
24
+ muted: [93, 98, 110],
25
+ },
26
+ ] satisfies ReadonlyArray<{
27
+ name: string
28
+ text: Rgb
29
+ subdued: Rgb
30
+ secondary: Rgb
31
+ muted: Rgb
32
+ }>)("derives a controlled neutral ladder for a $name", ({ text, subdued, secondary, muted }) => {
33
+ const primary = rgb(text)
34
+ const info = RGBA.fromInts(40, 120, 220)
35
+ const success = RGBA.fromInts(80, 180, 120)
36
+ const warning = RGBA.fromInts(220, 160, 80)
37
+ const background = RGBA.fromInts(10, 20, 30)
38
+ const accent = {
39
+ soft: RGBA.fromInts(180, 100, 40),
40
+ clear: RGBA.fromInts(240, 160, 80),
41
+ }
42
+ const palette = createOpenCodeDiagramPalette({
43
+ text: primary,
44
+ subdued: rgb(subdued),
45
+ info,
46
+ success,
47
+ warning,
48
+ background,
49
+ accent,
50
+ })
51
+
52
+ expect(palette.text).toBe(primary)
53
+ expect(palette.primary).toBe(primary)
54
+ expect(palette.secondary.equals(rgb(secondary))).toBe(true)
55
+ expect(palette.muted.equals(rgb(muted))).toBe(true)
56
+ expect(palette.warning).toBe(info)
57
+ expect(palette.background).toBe(background)
58
+ expect(palette.request).toBe(success)
59
+ expect(palette.response).toBe(warning)
60
+ expect(palette.note).toBe(primary)
61
+ expect(palette.noteBackground.equals(blendColor(background, rgb(subdued), 0.25))).toBe(true)
62
+ expect(palette.boxText).toBe(primary)
63
+ expect(palette.boxBorder.equals(rgb(muted))).toBe(true)
64
+ expect(palette.line.equals(rgb(subdued))).toBe(true)
65
+ expect(palette.labelBackground.toInts()[3]).toBe(20)
66
+ expect(palette.group).toBe(accent.soft)
67
+ expect(palette.groupText).toBe(accent.soft)
68
+ expect(palette.marker.equals(rgb(secondary))).toBe(true)
69
+ expect(palette.noteBorder).toBe(accent.soft)
70
+ expect(palette.noteText).toBe(accent.clear)
71
+ expect(palette.noteConnector).toBe(accent.soft)
72
+ })
73
+
74
+ test.each([
75
+ { mode: "dark", soft: 300, clear: 200 },
76
+ { mode: "light", soft: 700, clear: 800 },
77
+ ] as const)("uses the selected $mode mode even with a literal background", ({ mode, soft, clear }) => {
78
+ const accent = {
79
+ 200: rgb([200, 100, 100]),
80
+ 300: rgb([180, 90, 90]),
81
+ 700: rgb([120, 60, 60]),
82
+ 800: rgb([100, 50, 50]),
83
+ }
84
+ const theme = {
85
+ text: {
86
+ base: rgb([230, 232, 240]),
87
+ muted: rgb([114, 120, 138]),
88
+ feedback: {
89
+ info: { base: rgb([40, 120, 220]) },
90
+ success: { base: rgb([80, 180, 120]) },
91
+ warning: { base: rgb([220, 160, 80]) },
92
+ },
93
+ },
94
+ background: { base: rgb([250, 250, 250]) },
95
+ categorical: [accent],
96
+ }
97
+ const palette = resolveOpenCodeDiagramPalette(theme, mode)
98
+
99
+ expect(palette.group).toBe(accent[soft])
100
+ expect(palette.noteBorder).toBe(accent[soft])
101
+ expect(palette.noteText).toBe(accent[clear])
102
+ })
103
+ })