@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
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package.json",
2
3
  "name": "@zyro-sec/merman",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "1.0.2",
5
+ "type": "module",
6
+ "exports": {
7
+ "./markdown": "./src/markdown.ts",
8
+ "./palette": "./src/palette.ts",
9
+ "./plugin": "./src/plugin.ts"
10
+ },
11
+ "scripts": {
12
+ "audit:layouts": "bun run script/layout-audit.ts",
13
+ "test": "bun test --timeout 30000 --only-failures",
14
+ "typecheck": "bun check --no-script",
15
+ "typecheck:tsc": "tsc --noEmit"
16
+ },
17
+ "dependencies": {
18
+ "@zyro-sec/plugin": "^1.0.2",
19
+ "@opentui/core": "0.9.9",
20
+ "entities": "7.0.1",
21
+ "string-width": "7.2.0"
22
+ },
23
+ "devDependencies": {
24
+ "@tsconfig/bun": "1.0.9",
25
+ "@types/bun": "1.4.3",
26
+ "@typescript/native": "npm:typescript@7.1.0-beta"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ }
31
+ }
@@ -0,0 +1,98 @@
1
+ import { mkdir } from "node:fs/promises"
2
+ import { dirname, resolve } from "node:path"
3
+ import {
4
+ auditAllFixtures,
5
+ summarizeAudits,
6
+ worstAudits,
7
+ type LayoutAudit,
8
+ type LayoutMetrics,
9
+ } from "../src/test/layout-audit/harness.js"
10
+
11
+ const outputPath = resolve(import.meta.dir, "../../../tmp/merman-layout-audit.md")
12
+ const startedAt = performance.now()
13
+ const audits = auditAllFixtures()
14
+ const elapsedMs = performance.now() - startedAt
15
+ const summary = summarizeAudits(audits)
16
+
17
+ function label(audit: LayoutAudit): string {
18
+ return `${audit.fixture.id} @${audit.viewport}`
19
+ }
20
+
21
+ function metricTable(items: readonly LayoutAudit[]): string {
22
+ return [
23
+ "| Fixture | Viewport | Size | Area | Route length | Bends | Crossings | Shared cells | Overflow |",
24
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
25
+ ...items.map(
26
+ (audit) =>
27
+ `| \`${audit.fixture.id}\` | ${audit.viewport} | ${audit.metrics.width}x${audit.metrics.height} | ${audit.metrics.area} | ${audit.metrics.routeLength} | ${audit.metrics.bends} | ${audit.metrics.crossings} | ${audit.metrics.sharedRouteCells} | ${audit.metrics.overflow} |`,
28
+ ),
29
+ ].join("\n")
30
+ }
31
+
32
+ function worstSection(metric: keyof LayoutMetrics): string {
33
+ const worst = worstAudits(audits, metric)
34
+ return [`### ${metric}`, "", metricTable(worst)].join("\n")
35
+ }
36
+
37
+ function fixtureSection(audit: LayoutAudit): string {
38
+ return [
39
+ `<details${audit.fixture.curated || audit.violations.length > 0 ? " open" : ""}>`,
40
+ `<summary><code>${label(audit)}</code> · ${audit.metrics.width}x${audit.metrics.height} · area ${audit.metrics.area} · bends ${audit.metrics.bends} · crossings ${audit.metrics.crossings} · overflow ${audit.metrics.overflow}</summary>`,
41
+ "",
42
+ ...(audit.violations.length > 0 ? ["Violations:", "", ...audit.violations.map((item) => `- ${item}`), ""] : []),
43
+ "Source:",
44
+ "",
45
+ "```mermaid",
46
+ audit.fixture.source,
47
+ "```",
48
+ "",
49
+ "Rendered output:",
50
+ "",
51
+ "```text",
52
+ audit.output,
53
+ "```",
54
+ "",
55
+ "</details>",
56
+ ].join("\n")
57
+ }
58
+
59
+ const grouped = Map.groupBy(audits, (audit) => `${audit.fixture.kind}/${audit.fixture.family}`)
60
+ const violations = audits.flatMap((audit) => audit.violations.map((violation) => `${label(audit)}: ${violation}`))
61
+ const markdown = [
62
+ "# Merman Layout Audit",
63
+ "",
64
+ `Generated from ${new Set(audits.map((audit) => audit.fixture.id)).size} sources and ${audits.length} layout runs.`,
65
+ "",
66
+ `Structural violations: **${violations.length}**`,
67
+ "",
68
+ "## Aggregate Metrics",
69
+ "",
70
+ "```json",
71
+ JSON.stringify(summary, null, 2),
72
+ "```",
73
+ "",
74
+ "## Worst Offenders",
75
+ "",
76
+ ...(["area", "bends", "crossings", "sharedRouteCells", "overflow"] as const).flatMap((metric) => [
77
+ worstSection(metric),
78
+ "",
79
+ ]),
80
+ "## Fixtures",
81
+ "",
82
+ ...[...grouped.entries()].flatMap(([family, items]) => [
83
+ `### ${family}`,
84
+ "",
85
+ metricTable(items),
86
+ "",
87
+ ...items.flatMap((audit) => [fixtureSection(audit), ""]),
88
+ ]),
89
+ ].join("\n")
90
+
91
+ await mkdir(dirname(outputPath), { recursive: true })
92
+ await Bun.write(outputPath, markdown)
93
+
94
+ console.log(`Wrote ${audits.length} layout runs to ${outputPath} in ${elapsedMs.toFixed(0)}ms`)
95
+ if (violations.length > 0) {
96
+ console.error(violations.join("\n"))
97
+ process.exitCode = 1
98
+ }
@@ -0,0 +1,203 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import stringWidth from "string-width"
3
+ import { DiagramCanvas, DiagramCanvasSizeError, type DiagramCanvasCell } from "./canvas.js"
4
+
5
+ describe("DiagramCanvas", () => {
6
+ test("rejects canvases that exceed the rendering budget", () => {
7
+ expect(() => new DiagramCanvas(1_000, 251)).toThrow(DiagramCanvasSizeError)
8
+ })
9
+
10
+ test("rejects invalid canvas dimensions", () => {
11
+ for (const [width, height] of [
12
+ [-1, 10],
13
+ [10, -1],
14
+ [1.5, 10],
15
+ [Number.NaN, 10],
16
+ [Number.POSITIVE_INFINITY, 10],
17
+ ]) {
18
+ expect(() => new DiagramCanvas(width, height)).toThrow(DiagramCanvasSizeError)
19
+ }
20
+ })
21
+
22
+ test("writes cells and text while clipping out-of-bounds positions", () => {
23
+ const canvas = new DiagramCanvas<"label">(5, 2)
24
+
25
+ canvas.setCell(0, 0, "A", "label")
26
+ canvas.setCell(9, 0, "X", "label")
27
+ canvas.setText(2, 1, "hey", "label")
28
+
29
+ expect(canvas.toString()).toBe("A\n hey")
30
+ })
31
+
32
+ test("uses measured character widths for text placement", () => {
33
+ const canvas = new DiagramCanvas<"label">(5, 1)
34
+
35
+ canvas.setText(0, 0, "a界b", "label")
36
+
37
+ expect(canvas.toString()).toBe("a界b")
38
+ expect(stringWidth(canvas.toString())).toBe(4)
39
+ })
40
+
41
+ test("does not emit partial wide graphemes", () => {
42
+ const clipped = new DiagramCanvas<"label">(1, 1)
43
+ clipped.setText(0, 0, "界", "label")
44
+ expect(clipped.toString()).toBe("")
45
+ })
46
+
47
+ test("keeps custom measurement for ASCII text", () => {
48
+ let measurements = 0
49
+ const canvas = new DiagramCanvas<"label">(5, 1, {
50
+ measure: () => {
51
+ measurements += 1
52
+ return 2
53
+ },
54
+ })
55
+
56
+ canvas.setText(0, 0, "ab", "label")
57
+
58
+ expect(measurements).toBe(2)
59
+ expect(canvas.getCell(2, 0)?.char).toBe("b")
60
+ })
61
+
62
+ test("preserves combined graphemes while placing later text", () => {
63
+ const canvas = new DiagramCanvas<"label">(4, 1)
64
+
65
+ canvas.setText(0, 0, "e\u0301x", "label")
66
+
67
+ expect(canvas.toString()).toBe("e\u0301x")
68
+ expect(stringWidth(canvas.toString())).toBe(2)
69
+ })
70
+
71
+ test("merges cells through the adapter-provided merge function", () => {
72
+ type Style = "line"
73
+ const canvas = new DiagramCanvas<Style>(3, 1, {
74
+ mergeCell: (existing, incoming): DiagramCanvasCell<Style> => ({
75
+ ...incoming,
76
+ char: existing.char === "─" && incoming.char === "│" ? "┼" : incoming.char,
77
+ }),
78
+ })
79
+
80
+ canvas.setCell(1, 0, "─", "line")
81
+ canvas.setCell(1, 0, "│", "line")
82
+
83
+ expect(canvas.toString()).toBe(" ┼")
84
+
85
+ canvas.replaceCell(1, 0, "│", "line")
86
+ expect(canvas.toString()).toBe(" │")
87
+ })
88
+
89
+ test("iterates style and metadata runs", () => {
90
+ interface Metadata {
91
+ stateId?: string
92
+ }
93
+ const canvas = new DiagramCanvas<"state", Metadata>(4, 1)
94
+ const runs: string[] = []
95
+
96
+ canvas.setText(0, 0, "AB", "state", { stateId: "A" })
97
+ canvas.setText(2, 0, "CD", "state", { stateId: "B" })
98
+ canvas.forEachRun(
99
+ (run) => runs.push(`${run.text}:${run.style}:${run.cell.stateId}`),
100
+ () => runs.push("newline"),
101
+ { key: (cell) => [cell.style, cell.stateId] },
102
+ )
103
+
104
+ expect(runs).toEqual(["AB:state:A", "CD:state:B"])
105
+ })
106
+
107
+ test("retains styled trailing padding in render runs without changing plain text", () => {
108
+ const canvas = new DiagramCanvas<"label">(8, 1)
109
+ const runs: string[] = []
110
+ canvas.setText(1, 0, " start ", "label")
111
+
112
+ canvas.forEachRun(
113
+ (run) => runs.push(run.text),
114
+ () => {},
115
+ )
116
+
117
+ expect(canvas.toString()).toBe(" start")
118
+ expect(runs).toEqual([" ", " start "])
119
+ })
120
+
121
+ test("can trim bottom whitespace for renderers with dynamic height", () => {
122
+ const canvas = new DiagramCanvas<"label">(3, 3)
123
+ const runs: string[] = []
124
+ canvas.setText(0, 0, "top", "label")
125
+
126
+ expect(canvas.toString()).toBe("top\n\n")
127
+ expect(canvas.toString({ trimBottom: true })).toBe("top")
128
+ expect(canvas.getTextSize()).toEqual({ width: 3, height: 3 })
129
+ expect(canvas.getTextSize({ trimBottom: true })).toEqual({ width: 3, height: 1 })
130
+
131
+ canvas.forEachRun(
132
+ (run) => runs.push(run.text),
133
+ () => runs.push("newline"),
134
+ { trimBottom: true },
135
+ )
136
+ expect(runs).toEqual(["top"])
137
+ })
138
+
139
+ test("can trim unused leading whitespace reserved by layout", () => {
140
+ const canvas = new DiagramCanvas<"label">(3, 3)
141
+ canvas.setText(0, 2, "end", "label")
142
+
143
+ expect(canvas.toString({ trimTop: true })).toBe("end")
144
+ expect(canvas.getTextSize({ trimTop: true })).toEqual({ width: 3, height: 1 })
145
+ })
146
+
147
+ test("measures trim-aware text height without measuring row width", () => {
148
+ let measurements = 0
149
+ const canvas = new DiagramCanvas(8, 5, {
150
+ measure: (text) => {
151
+ measurements += 1
152
+ return stringWidth(text)
153
+ },
154
+ })
155
+ canvas.setText(1, 2, "middle")
156
+ measurements = 0
157
+
158
+ expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(1)
159
+ expect(measurements).toBe(0)
160
+ })
161
+
162
+ test("updates tracked row extents when the last visible cell is cleared", () => {
163
+ const canvas = new DiagramCanvas(8, 1)
164
+ canvas.setText(1, 0, "abc")
165
+ canvas.setCell(3, 0, " ")
166
+
167
+ expect(canvas.toString()).toBe(" ab")
168
+ expect(canvas.getTextSize()).toEqual({ width: 3, height: 1 })
169
+ })
170
+
171
+ test("keeps tracked extents equivalent to scanning after mixed writes", () => {
172
+ const canvas = new DiagramCanvas<"line">(20, 10, {
173
+ mergeCell: (_existing, incoming) => incoming,
174
+ })
175
+ let seed = 42
176
+ const next = (limit: number) => {
177
+ seed = (seed * 1_664_525 + 1_013_904_223) >>> 0
178
+ return seed % limit
179
+ }
180
+
181
+ for (let index = 0; index < 200; index++) {
182
+ const x = next(canvas.width)
183
+ const y = next(canvas.height)
184
+ const char = [" ", "x", "─"][next(3)]!
185
+ if (next(2) === 0) canvas.setCell(x, y, char, "line")
186
+ else canvas.replaceCell(x, y, char, "line")
187
+ }
188
+
189
+ const scanned = canvas.rows.map((row) => {
190
+ let end = row.length
191
+ while (end > 0 && row[end - 1]?.char === " ") end -= 1
192
+ return row
193
+ .slice(0, end)
194
+ .map((cell) => cell.char)
195
+ .join("")
196
+ })
197
+ const first = scanned.findIndex((line) => line.length > 0)
198
+ const last = scanned.findLastIndex((line) => line.length > 0)
199
+
200
+ expect(canvas.toString()).toBe(scanned.join("\n"))
201
+ expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(first < 0 ? 0 : last - first + 1)
202
+ })
203
+ })
@@ -0,0 +1,228 @@
1
+ import stringWidth from "string-width"
2
+ import { diagramTextGraphemes } from "./text.js"
3
+
4
+ export type DiagramCanvasCell<Style extends string, Metadata extends object = object> = {
5
+ char: string
6
+ style?: Style
7
+ } & Partial<Metadata>
8
+
9
+ export interface DiagramCanvasRun<Style extends string, Metadata extends object = object> {
10
+ text: string
11
+ style: Style | undefined
12
+ cell: DiagramCanvasCell<Style, Metadata>
13
+ }
14
+
15
+ export interface DiagramCanvasOptions<Style extends string, Metadata extends object = object> {
16
+ measure?: (text: string) => number
17
+ mergeCell?: (
18
+ existing: DiagramCanvasCell<Style, Metadata>,
19
+ incoming: DiagramCanvasCell<Style, Metadata>,
20
+ ) => DiagramCanvasCell<Style, Metadata>
21
+ }
22
+
23
+ export interface DiagramCanvasTextOptions {
24
+ trimTop?: boolean
25
+ trimBottom?: boolean
26
+ }
27
+
28
+ export interface DiagramCanvasTextSize {
29
+ width: number
30
+ height: number
31
+ }
32
+
33
+ export type DiagramCanvasTextMetadata<Metadata extends object> =
34
+ | Partial<Metadata>
35
+ | ((x: number, y: number) => Partial<Metadata>)
36
+
37
+ export interface DiagramCanvasRunOptions<Style extends string, Metadata extends object = object> {
38
+ key?: (cell: DiagramCanvasCell<Style, Metadata>) => readonly unknown[]
39
+ trimTop?: boolean
40
+ trimBottom?: boolean
41
+ }
42
+
43
+ const MAX_DIAGRAM_CELLS = 250_000
44
+
45
+ export class DiagramCanvasSizeError extends Error {
46
+ constructor(
47
+ readonly width: number,
48
+ readonly height: number,
49
+ ) {
50
+ const invalid = !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0
51
+ super(
52
+ invalid
53
+ ? `Diagram canvas dimensions must be non-negative safe integers, received ${width}x${height}`
54
+ : `Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`,
55
+ )
56
+ this.name = "DiagramCanvasSizeError"
57
+ }
58
+ }
59
+
60
+ function createEmptyCell<Style extends string, Metadata extends object>(): DiagramCanvasCell<Style, Metadata> {
61
+ return { char: " " } as DiagramCanvasCell<Style, Metadata>
62
+ }
63
+
64
+ function sameKey(left: readonly unknown[] | undefined, right: readonly unknown[]): boolean {
65
+ return Boolean(left && left.length === right.length && left.every((value, index) => Object.is(value, right[index])))
66
+ }
67
+
68
+ export class DiagramCanvas<Style extends string, Metadata extends object = object> {
69
+ private readonly cells: Array<Array<DiagramCanvasCell<Style, Metadata>>>
70
+ private readonly measure: (text: string) => number
71
+ private readonly mergeCell?: DiagramCanvasOptions<Style, Metadata>["mergeCell"]
72
+ private readonly rowEnds: Uint32Array
73
+
74
+ constructor(
75
+ readonly width: number,
76
+ readonly height: number,
77
+ options: DiagramCanvasOptions<Style, Metadata> = {},
78
+ ) {
79
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0) {
80
+ throw new DiagramCanvasSizeError(width, height)
81
+ }
82
+ if (width * height > MAX_DIAGRAM_CELLS) throw new DiagramCanvasSizeError(width, height)
83
+ this.measure = options.measure ?? stringWidth
84
+ this.mergeCell = options.mergeCell
85
+ this.cells = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
86
+ this.rowEnds = new Uint32Array(height)
87
+ }
88
+
89
+ get rows(): ReadonlyArray<ReadonlyArray<Readonly<DiagramCanvasCell<Style, Metadata>>>> {
90
+ return this.cells
91
+ }
92
+
93
+ private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd: number): string {
94
+ return row
95
+ .slice(0, rowEnd)
96
+ .map((cell) => cell.char)
97
+ .join("")
98
+ }
99
+
100
+ private textRowRange(trimTop: boolean, trimBottom: boolean): { start: number; end: number } {
101
+ let start = 0
102
+ let end = this.cells.length
103
+ if (trimTop) while (start < end && this.rowEnds[start] === 0) start += 1
104
+ if (trimBottom) while (end > start && this.rowEnds[end - 1] === 0) end -= 1
105
+ return { start, end }
106
+ }
107
+
108
+ setCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
109
+ this.writeCell(x, y, char, style, metadata, true)
110
+ }
111
+
112
+ replaceCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
113
+ this.writeCell(x, y, char, style, metadata, false)
114
+ }
115
+
116
+ private writeCell(
117
+ x: number,
118
+ y: number,
119
+ char: string,
120
+ style: Style | undefined,
121
+ metadata: Partial<Metadata> | undefined,
122
+ merge: boolean,
123
+ ): void {
124
+ if (y < 0 || y >= this.cells.length || x < 0 || x >= this.cells[y]!.length) return
125
+ const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
126
+ const cell = merge ? (this.mergeCell?.(this.cells[y]![x]!, incoming) ?? incoming) : incoming
127
+ this.cells[y]![x] = cell
128
+ if (cell.char !== " ") {
129
+ this.rowEnds[y] = Math.max(this.rowEnds[y]!, x + 1)
130
+ } else if (this.rowEnds[y] === x + 1) {
131
+ let end = x
132
+ while (end > 0 && this.cells[y]![end - 1]?.char === " ") end -= 1
133
+ this.rowEnds[y] = end
134
+ }
135
+ }
136
+
137
+ getCell(x: number, y: number): Readonly<DiagramCanvasCell<Style, Metadata>> | undefined {
138
+ return this.cells[y]?.[x]
139
+ }
140
+
141
+ setText(x: number, y: number, text: string, style?: Style, metadata?: DiagramCanvasTextMetadata<Metadata>): void {
142
+ const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
143
+ if (this.measure === stringWidth && /^[\x20-\x7e]*$/.test(text)) {
144
+ for (let index = 0; index < text.length; index++) {
145
+ this.setCell(x + index, y, text[index]!, style, metadataAt(x + index))
146
+ }
147
+ return
148
+ }
149
+
150
+ let offset = 0
151
+ for (const grapheme of diagramTextGraphemes(text)) {
152
+ const width = Math.max(1, this.measure(grapheme))
153
+ if (x + offset < 0 || x + offset + width > this.width) {
154
+ offset += width
155
+ continue
156
+ }
157
+ this.setCell(x + offset, y, grapheme, style, metadataAt(x + offset))
158
+ for (let continuation = 1; continuation < width; continuation++) {
159
+ this.setCell(x + offset + continuation, y, "", style, metadataAt(x + offset + continuation))
160
+ }
161
+ offset += width
162
+ }
163
+ }
164
+
165
+ toString(options: DiagramCanvasTextOptions = {}): string {
166
+ const lines: string[] = []
167
+ const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
168
+ for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
169
+ lines.push(this.rowText(this.cells[rowIndex]!, this.rowEnds[rowIndex]!))
170
+ }
171
+ return lines.join("\n")
172
+ }
173
+
174
+ getTextSize(options: DiagramCanvasTextOptions = {}): DiagramCanvasTextSize {
175
+ const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
176
+ let width = 0
177
+ for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
178
+ const row = this.cells[rowIndex]!
179
+ const rowEnd = this.rowEnds[rowIndex]!
180
+ if (rowEnd > 0) width = Math.max(width, this.measure(this.rowText(row, rowEnd)))
181
+ }
182
+ return { width, height: rows.end - rows.start }
183
+ }
184
+
185
+ getTextHeight(options: DiagramCanvasTextOptions = {}): number {
186
+ const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
187
+ return rows.end - rows.start
188
+ }
189
+
190
+ forEachRun(
191
+ onRun: (run: DiagramCanvasRun<Style, Metadata>) => void,
192
+ onLineEnd: () => void,
193
+ options: DiagramCanvasRunOptions<Style, Metadata> = {},
194
+ ): void {
195
+ const key = options.key
196
+ const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
197
+
198
+ for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
199
+ const row = this.cells[rowIndex]!
200
+ let rowEnd = this.rowEnds[rowIndex]!
201
+ while (rowEnd < row.length && row[rowEnd]?.style !== undefined) rowEnd += 1
202
+
203
+ let currentCell: DiagramCanvasCell<Style, Metadata> | undefined
204
+ let currentKey: readonly unknown[] | undefined
205
+ let currentText = ""
206
+ const flush = () => {
207
+ if (!currentText || !currentCell) return
208
+ onRun({ text: currentText, style: currentCell.style, cell: currentCell })
209
+ currentText = ""
210
+ }
211
+
212
+ for (let x = 0; x < rowEnd; x++) {
213
+ const cell = row[x]!
214
+ const nextKey = key?.(cell)
215
+ const sameRun = currentCell && (key ? sameKey(currentKey, nextKey!) : currentCell.style === cell.style)
216
+ if (!sameRun) {
217
+ flush()
218
+ currentCell = cell
219
+ currentKey = nextKey
220
+ }
221
+ currentText += cell.char
222
+ }
223
+
224
+ flush()
225
+ if (rowIndex < rows.end - 1) onLineEnd()
226
+ }
227
+ }
228
+ }
@@ -0,0 +1,24 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { RGBA } from "@opentui/core"
3
+ import { blendColor, createColorRampTheme, numberedStyleKeys, rgba } from "./style.js"
4
+
5
+ describe("diagram style helpers", () => {
6
+ test("converts rgb tuples and blends optional RGBA values", () => {
7
+ const black = RGBA.fromInts(0, 0, 0, 255)
8
+ const white = RGBA.fromInts(10, 20, 30, 255)
9
+
10
+ expect(rgba([1, 2, 3]).equals(RGBA.fromInts(1, 2, 3, 255))).toBe(true)
11
+ expect(blendColor(black, white, 0.5).equals(RGBA.fromInts(5, 10, 15, 255))).toBe(true)
12
+ expect(blendColor(undefined, white, 0.5)?.equals(white)).toBe(true)
13
+ expect(blendColor(undefined, undefined, 0.5)).toBeUndefined()
14
+ })
15
+
16
+ test("creates numbered style keys and color ramps", () => {
17
+ const styles = numberedStyleKeys("requestFade", [1, 2, 3] as const)
18
+ const theme = createColorRampTheme(styles, RGBA.fromInts(0, 0, 0, 255), RGBA.fromInts(12, 24, 36, 255))
19
+
20
+ expect(styles).toEqual(["requestFade1", "requestFade2", "requestFade3"])
21
+ expect(theme.requestFade1.equals(RGBA.fromInts(3, 6, 9, 255))).toBe(true)
22
+ expect(theme.requestFade3.equals(RGBA.fromInts(9, 18, 27, 255))).toBe(true)
23
+ })
24
+ })
@@ -0,0 +1,56 @@
1
+ import { RGBA } from "@opentui/core"
2
+
3
+ export type DiagramRgb = readonly [number, number, number]
4
+ export type DiagramFadeStep = 1 | 2 | 3 | 4 | 5
5
+
6
+ export const DIAGRAM_FADE_STEPS = [1, 2, 3, 4, 5] as const satisfies readonly DiagramFadeStep[]
7
+
8
+ export function numberedStyleKeys<Prefix extends string, Step extends number>(
9
+ prefix: Prefix,
10
+ steps: readonly Step[],
11
+ ): Array<`${Prefix}${Step}`> {
12
+ return steps.map((step) => `${prefix}${step}` as `${Prefix}${Step}`)
13
+ }
14
+
15
+ export function rgba(rgb: DiagramRgb): RGBA {
16
+ return RGBA.fromInts(rgb[0], rgb[1], rgb[2], 255)
17
+ }
18
+
19
+ export function blendColor(from: RGBA, to: RGBA, amount: number): RGBA
20
+ export function blendColor(from: RGBA | undefined, to: RGBA | undefined, amount: number): RGBA | undefined
21
+ export function blendColor(from: RGBA | undefined, to: RGBA | undefined, amount: number): RGBA | undefined {
22
+ if (!from && !to) return undefined
23
+ if (!from) return to
24
+ if (!to) return from
25
+
26
+ const [fromR, fromG, fromB, fromA] = from.toInts()
27
+ const [toR, toG, toB, toA] = to.toInts()
28
+ const mix = (left: number, right: number) => left + (right - left) * amount
29
+
30
+ return RGBA.fromInts(mix(fromR, toR), mix(fromG, toG), mix(fromB, toB), mix(fromA, toA))
31
+ }
32
+
33
+ export function colorsEqual(left?: RGBA, right?: RGBA): boolean {
34
+ if (!left || !right) return left === right
35
+ return left.equals(right)
36
+ }
37
+
38
+ export function createColorRampTheme<Style extends string>(
39
+ styles: readonly Style[],
40
+ from: RGBA,
41
+ to: RGBA,
42
+ ): Record<Style, RGBA>
43
+ export function createColorRampTheme<Style extends string>(
44
+ styles: readonly Style[],
45
+ from: RGBA | undefined,
46
+ to: RGBA | undefined,
47
+ ): Record<Style, RGBA | undefined>
48
+ export function createColorRampTheme<Style extends string>(
49
+ styles: readonly Style[],
50
+ from: RGBA | undefined,
51
+ to: RGBA | undefined,
52
+ ): Record<Style, RGBA | undefined> {
53
+ return Object.fromEntries(
54
+ styles.map((style, index) => [style, blendColor(from, to, (index + 1) / (styles.length + 1))]),
55
+ ) as Record<Style, RGBA | undefined>
56
+ }