diff --git a/src/app/components/DiagramColor.test.tsx b/src/app/components/DiagramColor.test.tsx
new file mode 100644
index 0000000..e612c65
--- /dev/null
+++ b/src/app/components/DiagramColor.test.tsx
@@ -0,0 +1,84 @@
+import { afterEach, expect, test } from 'bun:test'
+import { RGBA } from '@opentui/core'
+import { createTestRenderer } from '@opentui/core/testing'
+import { createRoot } from '@opentui/react'
+import { App } from '../App'
+import { buildTreeFromTokens, lexMarkdown } from '../lib/ast'
+import { renderDiagramBlocks } from '../lib/preprocess'
+import { theme } from '../styles/theme'
+import type { CliRenderer } from '@opentui/core'
+
+const FIXTURE = ['# Diagram', '', '```mermaid', 'graph LR', ' A[Start] --> B[Done]', '```'].join(
+ '\n',
+)
+
+let active: CliRenderer | undefined
+
+afterEach(() => {
+ active?.destroy()
+ active = undefined
+})
+
+async function setup() {
+ const { nodes, toc, headingIds } = buildTreeFromTokens(renderDiagramBlocks(lexMarkdown(FIXTURE)))
+ const { renderer, mockInput, flush, renderOnce, captureSpans } = await createTestRenderer({
+ width: 100,
+ height: 20,
+ })
+ active = renderer
+ const settle = async () => {
+ await flush({ maxPasses: 20 })
+ await new Promise(r => setTimeout(r, 30))
+ await renderOnce()
+ }
+ createRoot(renderer).render(
+ ,
+ )
+ await settle()
+ // The very first key is consumed by the terminal capability handshake.
+ await mockInput.typeText('x')
+ await settle()
+ return { mockInput, settle, captureSpans }
+}
+
+/** Every rendered span containing `text`; the search bar also echoes the query. */
+function spansWith(
+ captureSpans: Awaited>['captureSpans'],
+ text: string,
+) {
+ return captureSpans().lines.flatMap(line => line.spans.filter(s => s.text.includes(text)))
+}
+
+const sameColor = (a: RGBA, hex: string) => {
+ const b = RGBA.fromHex(hex)
+ return [a.r - b.r, a.g - b.g, a.b - b.b].every(d => Math.abs(d) < 0.02)
+}
+
+test('each diagram node paints in its own palette hue', async () => {
+ const { captureSpans } = await setup()
+ expect(spansWith(captureSpans, 'Start').some(s => sameColor(s.fg, theme.diagramNodes[0]))).toBe(
+ true,
+ )
+ expect(spansWith(captureSpans, 'Done').some(s => sameColor(s.fg, theme.diagramNodes[1]))).toBe(
+ true,
+ )
+})
+
+test('a search match inside a colored diagram keeps the match background', async () => {
+ const { mockInput, settle, captureSpans } = await setup()
+ await mockInput.typeText('/')
+ await settle()
+ await mockInput.typeText('Done')
+ await settle()
+ mockInput.pressEnter()
+ await settle()
+ const done = spansWith(captureSpans, 'Done')
+ expect(done.some(s => s.text === 'Done' && sameColor(s.bg, theme.searchCurrentBg))).toBe(true)
+})
diff --git a/src/app/components/blocks/CodeBlock.tsx b/src/app/components/blocks/CodeBlock.tsx
index 3091a45..bb348ca 100644
--- a/src/app/components/blocks/CodeBlock.tsx
+++ b/src/app/components/blocks/CodeBlock.tsx
@@ -1,11 +1,13 @@
import { RGBA, infoStringToFiletype } from '@opentui/core'
import type { TextChunk } from '@opentui/core'
+import { useMemo } from 'react'
import { HighlightedText, RunScope, matchRangesForRun } from './InlineRenderer'
import { theme } from '../../styles/theme'
import { syntaxStyle } from '../../styles/syntax-style'
import { useAppState } from '../../state'
import { MERMAID_ASCII_LANG } from '../../lib/preprocess'
import { codeText, DIAGRAM_MARGIN_X, textWidth } from '../../lib/diagram-fit'
+import { paintDiagram } from '../../lib/diagram-paint'
import type { Node } from '../../lib/ast'
import type { AppState } from '../../state'
@@ -22,16 +24,7 @@ export function CodeBlock({ node, id }: { node: Extract;
// reading column overflow it into the breakout columns; a `wrapMode="none"`
// text clips at its box edge otherwise.
if (node.lang === MERMAID_ASCII_LANG) {
- const ascii = codeText({ node, breakoutWidth })
- return (
-
-
-
-
-
-
-
- )
+ return
}
const rawLang = node.lang && node.lang !== 'text' ? node.lang : undefined
@@ -77,6 +70,27 @@ export function CodeBlock({ node, id }: { node: Extract;
)
}
+/**
+ * Runs concatenate back to `ascii`, so each `HighlightedText` piece advances the RunScope cursor
+ * in step with the projection and match spans paint over the run colors.
+ */
+function DiagramBlock({ ascii, id }: { ascii: string; id: string }) {
+ const runs = useMemo(() => paintDiagram(ascii), [ascii])
+ return (
+
+
+
+ {runs.map((run, i) => (
+
+
+
+ ))}
+
+
+
+ )
+}
+
const MATCH_BG = RGBA.fromHex(theme.searchMatchBg)
const MATCH_CURRENT_BG = RGBA.fromHex(theme.searchCurrentBg)
const MATCH_FG = RGBA.fromHex(theme.searchMatchFg)
diff --git a/src/app/lib/diagram-paint.test.ts b/src/app/lib/diagram-paint.test.ts
new file mode 100644
index 0000000..94a6666
--- /dev/null
+++ b/src/app/lib/diagram-paint.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, test } from 'bun:test'
+import { paintDiagram } from './diagram-paint'
+import { renderAscii } from './preprocess'
+import { theme } from '../styles/theme'
+import type { DiagramRun } from './diagram-paint'
+
+const render = (source: string): string => {
+ const ascii = renderAscii(source)
+ if (ascii === undefined) throw new Error(`diagram failed to render: ${source}`)
+ return ascii
+}
+
+const FLOW = render('graph LR\n A[Start] --> B{Ok?}\n B -->|yes| C(Done)\n B -->|no| A')
+const SUBGRAPH = render('graph TD\n subgraph S [Group]\n X --> Y\n end\n Y --> Z')
+const SEQUENCE = render('sequenceDiagram\n Alice->>Bob: Hi\n Bob-->>Alice: Yo')
+
+const [FIRST, SECOND, THIRD] = theme.diagramNodes
+
+/** Per-cell fg, rebuilt from the runs so tests assert on what each glyph paints as. */
+const colorGrid = (runs: DiagramRun[]): (string | undefined)[][] => {
+ const grid: (string | undefined)[][] = [[]]
+ for (const run of runs) {
+ for (const ch of Array.from(run.text)) {
+ if (ch === '\n') grid.push([])
+ else grid[grid.length - 1]?.push(run.fg)
+ }
+ }
+ return grid
+}
+
+/** Color of the nth occurrence of `needle` in the diagram text. */
+const colorOf = (text: string, needle: string, nth = 0): string | undefined => {
+ const lines = text.split('\n')
+ let seen = 0
+ for (let r = 0; r < lines.length; r++) {
+ const chars = Array.from(lines[r] ?? '')
+ for (let c = 0; c < chars.length; c++) {
+ if (!chars.slice(c).join('').startsWith(needle)) continue
+ if (seen++ === nth) return colorGrid(paintDiagram(text))[r]?.[c]
+ }
+ }
+ throw new Error(`"${needle}" #${nth} not found`)
+}
+
+describe('paintDiagram', () => {
+ test('run texts concatenate back to the input exactly', () => {
+ for (const text of [FLOW, SUBGRAPH, SEQUENCE]) {
+ expect(
+ paintDiagram(text)
+ .map(r => r.text)
+ .join(''),
+ ).toBe(text)
+ }
+ })
+
+ test('a node box and its label share one palette hue', () => {
+ expect(colorOf(FLOW, 'Start')).toBe(FIRST)
+ expect(colorOf(FLOW, '┌')).toBe(FIRST)
+ expect(colorOf(FLOW, '┘')).toBe(FIRST)
+ })
+
+ test('distinct labels take successive palette hues', () => {
+ expect(colorOf(FLOW, 'Ok?')).toBe(SECOND)
+ expect(colorOf(FLOW, 'Done')).toBe(THIRD)
+ })
+
+ test('a repeated label reuses its hue', () => {
+ expect(colorOf(SEQUENCE, 'Alice', 0)).toBe(FIRST)
+ expect(colorOf(SEQUENCE, 'Alice', 1)).toBe(FIRST)
+ expect(colorOf(SEQUENCE, 'Bob', 1)).toBe(SECOND)
+ })
+
+ test('the palette wraps once every hue is taken', () => {
+ const ids = 'ABCDEFG'.split('')
+ const chain = render(`graph LR\n ${ids.map(id => `${id}[N${id}]`).join(' --> ')}`)
+ expect(colorOf(chain, `N${ids[theme.diagramNodes.length]}`)).toBe(FIRST)
+ })
+
+ test('a subgraph frame paints as a line and its title as text', () => {
+ expect(colorOf(SUBGRAPH, '┌───────┐')).toBe(theme.diagramLine)
+ expect(colorOf(SUBGRAPH, 'Group')).toBe(theme.diagramText)
+ expect(colorOf(SUBGRAPH, 'X')).toBe(FIRST)
+ })
+
+ test('edges paint lines, arrowheads, and edge labels by role', () => {
+ expect(colorOf(FLOW, '─yes')).toBe(theme.diagramLine)
+ expect(colorOf(FLOW, '►')).toBe(theme.diagramArrow)
+ expect(colorOf(FLOW, 'yes')).toBe(theme.diagramText)
+ expect(colorOf(SEQUENCE, '▶')).toBe(theme.diagramArrow)
+ expect(colorOf(SEQUENCE, '◀')).toBe(theme.diagramArrow)
+ })
+})
diff --git a/src/app/lib/diagram-paint.ts b/src/app/lib/diagram-paint.ts
new file mode 100644
index 0000000..d4cc897
--- /dev/null
+++ b/src/app/lib/diagram-paint.ts
@@ -0,0 +1,104 @@
+import { theme } from '../styles/theme'
+
+/** A stretch of diagram text in one color; a diagram's runs concatenate back to its text. */
+export type DiagramRun = { text: string; fg: string }
+
+type Box = { top: number; left: number; bottom: number; right: number }
+
+const TOP_LEFT = /[┌╭]/
+const TOP_RIGHT = /[┐╮]/
+const BOTTOM_LEFT = /[└╰]/
+const BOTTOM_RIGHT = /[┘╯]/
+// Edges join box borders, so a border admits tees, crosses, and arrowheads.
+const TOP_BORDER = /[─┬┴┼▲▼]/
+const LEFT_BORDER = /[│├┤┼►◄▶◀]/
+const ARROW = /[►◄▲▼▶◀]/
+const BOX_DRAWING = /[─-╿]/
+
+/**
+ * Colors rendered diagram text. Each innermost box (border and label) takes the next node hue,
+ * keyed by label so a repeated node keeps its hue. Every other glyph is colored by role, so
+ * enclosing boxes such as subgraph frames paint as lines.
+ */
+export function paintDiagram(text: string): DiagramRun[] {
+ const grid = text.split('\n').map(line => Array.from(line))
+ const boxColors = paintBoxes(grid)
+ return grid.reduce((runs, row, r) => {
+ if (r > 0) appendCell(runs, '\n', undefined)
+ row.forEach((ch, c) => appendCell(runs, ch, boxColors[r]?.[c] ?? roleColor(ch)))
+ return runs
+ }, [])
+}
+
+/** Uncolored cells (whitespace, newlines) join the current run so runs stay few. */
+function appendCell(runs: DiagramRun[], ch: string, fg: string | undefined): DiagramRun[] {
+ const last = runs.at(-1)
+ if (last && (fg === undefined || fg === last.fg)) last.text += ch
+ else runs.push({ text: ch, fg: fg ?? theme.diagramText })
+ return runs
+}
+
+function roleColor(ch: string): string | undefined {
+ if (!ch.trim()) return undefined
+ if (ARROW.test(ch)) return theme.diagramArrow
+ if (BOX_DRAWING.test(ch)) return theme.diagramLine
+ return theme.diagramText
+}
+
+function paintBoxes(grid: string[][]): (string | undefined)[][] {
+ const colors = grid.map(row => row.map((): string | undefined => undefined))
+ const boxes = findBoxes(grid)
+ const hues = new Map()
+ for (const box of boxes.filter(outer => !boxes.some(inner => encloses(outer, inner)))) {
+ const label = boxLabel(grid, box)
+ const hue = hues.get(label) ?? nodeHue(hues.size)
+ hues.set(label, hue)
+ for (let r = box.top; r <= box.bottom; r++) {
+ const row = colors[r]
+ if (!row) continue
+ for (let c = box.left; c <= box.right; c++) if (grid[r]?.[c]?.trim()) row[c] = hue
+ }
+ }
+ return colors
+}
+
+function findBoxes(grid: string[][]): Box[] {
+ const at = (r: number, c: number) => grid[r]?.[c] ?? ''
+ const boxes: Box[] = []
+ grid.forEach((row, top) =>
+ row.forEach((ch, left) => {
+ if (!TOP_LEFT.test(ch)) return
+ let right = left + 1
+ while (TOP_BORDER.test(at(top, right))) right++
+ if (right === left + 1 || !TOP_RIGHT.test(at(top, right))) return
+ let bottom = top + 1
+ while (LEFT_BORDER.test(at(bottom, left))) bottom++
+ if (!BOTTOM_LEFT.test(at(bottom, left)) || !BOTTOM_RIGHT.test(at(bottom, right))) return
+ boxes.push({ top, left, bottom, right })
+ }),
+ )
+ return boxes
+}
+
+function encloses(outer: Box, inner: Box): boolean {
+ return (
+ inner !== outer &&
+ inner.top > outer.top &&
+ inner.bottom < outer.bottom &&
+ inner.left > outer.left &&
+ inner.right < outer.right
+ )
+}
+
+function boxLabel(grid: string[][], box: Box): string {
+ return grid
+ .slice(box.top + 1, box.bottom)
+ .map(row => row.slice(box.left + 1, box.right).join(''))
+ .join(' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
+
+function nodeHue(index: number): string {
+ return theme.diagramNodes[index % theme.diagramNodes.length] ?? theme.diagramText
+}
diff --git a/src/app/styles/theme.ts b/src/app/styles/theme.ts
index e6d6b60..8a5794b 100644
--- a/src/app/styles/theme.ts
+++ b/src/app/styles/theme.ts
@@ -36,6 +36,12 @@ export const theme = {
scrollMarkActive: '#f59e1f', // brightest — reuse searchCurrentBg
scrollbarThumb: '#585858', // thumb color; marker cells inside the thumb use it as bg
scrollbarTrack: '#252527', // track bg (OpenTUI default, pinned); marker cells outside the thumb use it as bg
+ // Node hues, assigned in order: cyan, green, magenta, codespanFg, blue. Yellow would read as a
+ // search match (searchMatchBg) and red as an error, so neither is a node hue.
+ diagramNodes: ['#11a8cd', '#23d18b', '#bc3fbc', '#ce9178', '#2472c8'],
+ diagramLine: '#666666', // matches border; edges recede so nodes carry the color
+ diagramArrow: '#9d9d9d', // matches foregroundMuted; brighter than lines so direction reads
+ diagramText: '#d4d4d4', // matches foreground
} as const
export type Theme = typeof theme
diff --git a/test/mermaid.md b/test/mermaid.md
index 8dbcf3c..ee73359 100644
--- a/test/mermaid.md
+++ b/test/mermaid.md
@@ -126,6 +126,9 @@ stateDiagram-v2
### Notes
+`beautiful-mermaid` parses notes only in sequence diagrams; it drops this
+state note silently, so only `[*] --> A` renders.
+
```mermaid
stateDiagram-v2
[*] --> A
@@ -205,6 +208,16 @@ sequenceDiagram
Note right of B: processing
```
+### Notes: left, over one, over a span
+
+```mermaid
+sequenceDiagram
+ A->>B: hi
+ Note left of A: before
+ Note over B: waiting
+ Note over A,B: shared
+```
+
## Class Diagrams
### Attributes and methods