fix(tui): render Mermaid rich labels compactly (#42103)

This commit is contained in:
Kit Langton
2026-08-12 14:28:54 -04:00
committed by GitHub
Unverified
parent f8f50ee375
commit c86b3079ac
10 changed files with 219 additions and 36 deletions
+10 -2
View File
@@ -5,13 +5,21 @@ export function renderDiagramGridStyledText<Style extends string, Metadata exten
grid: DiagramCanvas<Style, Metadata>,
fg: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["fg"],
bg?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["bg"],
options?: DiagramCanvasRunOptions<Style, Metadata>,
options?: DiagramCanvasRunOptions<Style, Metadata> & {
attributes?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["attributes"]
},
): StyledText {
const chunks: TextChunk[] = []
grid.forEachRun(
(run) => {
chunks.push({ __isChunk: true, text: run.text, fg: fg(run), bg: bg?.(run) })
chunks.push({
__isChunk: true,
text: run.text,
fg: fg(run),
bg: bg?.(run),
attributes: options?.attributes?.(run),
})
},
() => {
chunks.push({ __isChunk: true, text: "\n" })
+31 -2
View File
@@ -1,3 +1,32 @@
export function splitDiagramLines(value: string): string[] {
return value.split(/<br\s*\/?>/i).map((line) => line.trim())
export interface DiagramTextRun {
text: string
italic: boolean
}
export interface DiagramTextLine {
text: string
runs: DiagramTextRun[]
}
export function parseDiagramTextLines(value: string): DiagramTextLine[] {
return value.split(/<br\s*\/?>/i).map((line) => {
const runs: DiagramTextRun[] = []
const source = line.trim()
const tag = /<\/?(?:i|em)\s*>/gi
let italic = false
let offset = 0
for (const match of source.matchAll(tag)) {
if (match.index > offset) runs.push({ text: source.slice(offset, match.index), italic })
italic = !match[0].startsWith("</")
offset = match.index + match[0].length
}
if (offset < source.length) runs.push({ text: source.slice(offset), italic })
return { text: runs.map((run) => run.text).join(""), runs }
})
}
export function splitDiagramLines(value: string): string[] {
return parseDiagramTextLines(value).map((line) => line.text)
}
+14 -1
View File
@@ -1,11 +1,24 @@
import { describe, expect, test } from "bun:test"
import { diagramTextWidth, measureDiagramTextBox, splitDiagramLines } from "./text.js"
import { diagramTextWidth, measureDiagramTextBox, parseDiagramTextLines, splitDiagramLines } from "./text.js"
describe("diagram text helpers", () => {
test("splits Mermaid-style line breaks", () => {
expect(splitDiagramLines("one<br/> two <br>three")).toEqual(["one", "two", "three"])
})
test("extracts Mermaid italic markup from visible text", () => {
expect(parseDiagramTextLines("plain <i>italic</i><br/><em>again</em>")).toEqual([
{
text: "plain italic",
runs: [
{ text: "plain ", italic: false },
{ text: "italic", italic: true },
],
},
{ text: "again", runs: [{ text: "again", italic: true }] },
])
})
test("measures padded text boxes", () => {
expect(measureDiagramTextBox("wide<br/>x", { paddingX: 2, paddingY: 1 })).toEqual({
width: 8,
+1 -1
View File
@@ -1,7 +1,7 @@
import stringWidth from "string-width"
import { splitDiagramLines } from "./text-lines.js"
export { splitDiagramLines } from "./text-lines.js"
export { parseDiagramTextLines, splitDiagramLines } from "./text-lines.js"
export interface DiagramTextBoxSize {
width: number
+28 -10
View File
@@ -1,7 +1,8 @@
import { BorderChars, type BorderCharacters, type BorderStyle } from "@opentui/core"
import { BorderChars, TextAttributes, type BorderCharacters, type BorderStyle } from "@opentui/core"
import { walkOrthogonalSegment } from "../core/geometry.js"
import { DiagramCanvas, type DiagramCanvasCell } from "../core/canvas.js"
import { splitDiagramLines } from "../core/text.js"
import { parseDiagramTextLines } from "../core/text.js"
import type { DiagramTextRun } from "../core/text-lines.js"
import {
DIAGRAM_ARROW_HEADS,
diagramArrowHeadBetween,
@@ -21,6 +22,7 @@ import {
DATABASE_EDGE_FADE_STYLES,
NODE_EDGE_FADE_STYLES,
type FlowchartCellStyle,
type FlowchartCellMetadata,
type FlowchartEdgeFadeStyle,
type FlowchartGrid,
} from "./style.js"
@@ -50,8 +52,19 @@ function mergeFlowchartCell(
} as DiagramCanvasCell<FlowchartCellStyle>
}
function setNodeText(grid: FlowchartGrid, x: number, y: number, text: string, style: FlowchartCellStyle): void {
grid.setText(x, y, text, style)
function setRichText(
grid: FlowchartGrid,
x: number,
y: number,
runs: readonly DiagramTextRun[],
style: FlowchartCellStyle,
): number {
let offset = 0
for (const run of runs) {
grid.setText(x + offset, y, run.text, style, run.italic ? { attributes: TextAttributes.ITALIC } : undefined)
offset += visualLength(run.text)
}
return offset
}
function drawNode(
@@ -86,12 +99,13 @@ function drawNode(
: node.shape === "database"
? bounds.top + 2
: bounds.top + 1
const lines = parseDiagramTextLines(node.label)
for (const [index, line] of bounds.lines.entries()) {
const lineX =
node.shape === "subroutine"
? bounds.left + 3
: bounds.left + Math.max(1, Math.floor((bounds.width - visualLength(line)) / 2))
setNodeText(grid, lineX, textTop + index, line, style)
setRichText(grid, lineX, textTop + index, lines[index]!.runs, style)
}
}
@@ -139,18 +153,22 @@ function drawSubgraphFrame(grid: FlowchartGrid, bounds: FlowchartSubgraphBounds,
function drawSubgraphLabel(grid: FlowchartGrid, bounds: FlowchartSubgraphBounds): void {
if (bounds.label) {
const lines = splitDiagramLines(bounds.label)
const lines = parseDiagramTextLines(bounds.label)
const labelY = bounds.labelSide === "top" ? bounds.top : bounds.top + bounds.height - lines.length
for (const [index, line] of lines.entries()) {
grid.setText(bounds.left + 2, labelY + index, ` ${line} `, "group")
grid.setText(bounds.left + 2, labelY + index, " ", "group")
const width = setRichText(grid, bounds.left + 3, labelY + index, line.runs, "group")
grid.setText(bounds.left + width + 3, labelY + index, " ", "group")
}
}
}
function drawEdgeLabel(grid: FlowchartGrid, route: FlowchartEdgeRoute, style: FlowchartCellStyle): void {
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
for (const [index, line] of label.lines.entries()) {
grid.setText(label.point.x, label.point.y + index, line, style)
for (const [index, line] of parseDiagramTextLines(route.edge.label).entries()) {
grid.setText(label.point.x, label.point.y + index, " ", style)
const width = setRichText(grid, label.point.x + 1, label.point.y + index, line.runs, style)
grid.setText(label.point.x + width + 1, label.point.y + index, " ", style)
}
}
@@ -276,7 +294,7 @@ export function drawFlowchartDiagramGrid(
const layout = layoutFlowchartDiagram(diagram, options)
const { bounds, routes, subgraphBounds, width, height } = layout
diagram = layout.diagram
const grid = new DiagramCanvas<FlowchartCellStyle>(width, height, {
const grid = new DiagramCanvas<FlowchartCellStyle, FlowchartCellMetadata>(width, height, {
mergeCell: mergeFlowchartCell,
})
for (const subgraph of diagram.subgraphs ?? []) {
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"
import { parseColor } from "@opentui/core"
import { parseColor, TextAttributes } from "@opentui/core"
import stringWidth from "string-width"
import { expectDiagram } from "../test/diagram.js"
import { drawFlowchartDiagramGrid as drawParsedFlowchartDiagramGrid } from "./drawing.js"
@@ -545,6 +545,19 @@ flowchart TD
expect(diagram.edges[0]?.label).toBe("result ≥ 1")
})
test("preserves quoted multiline edge labels", () => {
const diagram = parseMermaidFlowchartDiagram(`flowchart TD
A -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>A --> B"| B`)
expect(diagram.edges).toEqual([
{
from: "A",
to: "B",
label: "fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>A --> B",
},
])
})
test("parses and renders each edge in a chained flowchart statement", () => {
const content = `flowchart LR
API --> Worker --> DB[(Database)]`
@@ -913,6 +926,61 @@ flowchart LR
expect(output).not.toContain("<br")
})
test("keeps quoted multiline labels compact and renders italic node text", () => {
const source = `flowchart TB
DO["ServerWorkerd.create({ storage, config })"]
DO --> SO["serverOptions()<br/><i>option flags</i>"]
DO --> RP["replacements()<br/><i>layer overrides</i>"]
SO -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>config as string"| SF["ServerFetch.make(options, { overrides })"]
RP -->|"Database → DO-SQLite<br/>Shell/FS/Pty → typed-unavailable<br/>Snapshot/Vcs → no-op<br/>plugins → precompiled only"| SF
SF --> GRAPH["LayerNode graph<br/>(core builds normally,<br/>swapped nodes substituted)"]`
const grid = drawFlowchartDiagramGrid(source)
const output = grid.toString({ trimTop: true, trimBottom: true })
const styled = renderGridStyledText(grid, resolveFlowchartStyleColors())
expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThan(140)
expect(output).not.toMatch(/<\/?i>|<br|events persist|mcp stdio|^[^\n]*"fs:/)
expect(
styled.chunks.some((chunk) => chunk.text.includes("option flags") && chunk.attributes === TextAttributes.ITALIC),
).toBe(true)
})
test("keeps quoted architecture labels from distorting subgraph routes", () => {
const source = `flowchart TB
subgraph consumer["Durable Object"]
DO["ServerWorkerd.create({ storage, config })"]
end
DO --> SO["serverOptions()<br/><i>option flags</i>"]
DO --> RP["replacements()<br/><i>layer overrides</i>"]
SO -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>config as string"| SF["ServerFetch.make(options, { overrides })"]
RP -->|"Database → DO-SQLite<br/>Shell/FS/Pty → typed-unavailable<br/>Snapshot/Vcs → no-op<br/>plugins → precompiled only"| SF
SF --> GRAPH["LayerNode graph<br/>(core builds normally,<br/>swapped nodes substituted)"]
subgraph bundle["3rd mechanism: bundle conditions (build time)"]
COND["--conditions=workerd<br/>pty / fff / photon / shell-parser<br/>native modules → inert stubs<br/>#global-roots → workerd path rooting"]
end
COND -.->|import resolution| GRAPH`
const output = renderFlowchartDiagram(source)
expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThan(130)
expect(output).not.toMatch(/<\/?i>|<br|^[^\n]*"(?:fs:|Database)/)
for (const label of [
"fs: watcher/fff off",
"events.persist: true",
"mcp.stdio: false",
"config as string",
"Database → DO-SQLite",
"Shell/FS/Pty → typed-unavailable",
"Snapshot/Vcs → no-op",
"plugins → precompiled only",
]) {
expect(output).toContain(label)
}
})
test("keeps tall multiline branch labels out of sibling nodes", () => {
const output = renderFlowchartDiagram(`flowchart LR
A[Start] -->|one<br/>two<br/>three<br/>four<br/>five| B[Upper]
+17 -16
View File
@@ -354,11 +354,6 @@ function layoutRankedNodes(
requestedMinRankGap: number,
): Map<string, FlowchartNodeBounds> {
const horizontal = isHorizontalDirection(direction)
let widestPaddedEdgeLabel = 0
for (const edge of diagram.edges) {
if (edge.label)
widestPaddedEdgeLabel = Math.max(widestPaddedEdgeLabel, flowchartLabelWidth(edge.label, visualLength))
}
const ranks = rankNodes(diagram)
const maxRank = Math.max(0, ...ranks.values())
const ranksByIndex = new Map<number, FlowchartNode[]>()
@@ -382,13 +377,18 @@ function layoutRankedNodes(
Math.max(0, nodes.length - 1) * spaciousNodeGap,
),
)
const rankNodeGap = horizontal
? minNodeGap
: widestPaddedEdgeLabel > 0
? Math.max(spaciousNodeGap, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
: widestUnlabeledRank > DEFAULT_MAX_UNLABELED_RANK_WIDTH
? minNodeGap
: spaciousNodeGap
const verticalNodeGap = (rank: number): number => {
const widestLabel = Math.max(
0,
...diagram.edges
.filter(
(edge) => edge.label && (normalizedRanks.get(edge.from) === rank || normalizedRanks.get(edge.to) === rank),
)
.map((edge) => flowchartLabelWidth(edge.label, visualLength)),
)
if (widestLabel > 0) return Math.max(spaciousNodeGap, flowchartVerticalBranchLabelGap(widestLabel))
return widestUnlabeledRank > DEFAULT_MAX_UNLABELED_RANK_WIDTH ? minNodeGap : spaciousNodeGap
}
const rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
const horizontalGaps = horizontal ? horizontalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap) : []
@@ -403,7 +403,7 @@ function layoutRankedNodes(
const nodes = ranksByIndex.get(rank)!
return (
nodes.reduce((total, node) => total + sizes.get(node.id)!.height, 0) +
Math.max(0, nodes.length - 1) * rankNodeGap
Math.max(0, nodes.length - 1) * minNodeGap
)
})
const canvasHeight = Math.max(1, ...columnHeights)
@@ -425,7 +425,7 @@ function layoutRankedNodes(
centerX: left + Math.floor(size.width / 2),
centerY: y + Math.floor(size.height / 2),
})
y += size.height + rankNodeGap
y += size.height + minNodeGap
}
x += columnWidth + (horizontalGaps[rankIndex] ?? 0)
}
@@ -437,7 +437,7 @@ function layoutRankedNodes(
const nodes = ranksByIndex.get(rank)!
return (
nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
Math.max(0, nodes.length - 1) * rankNodeGap
Math.max(0, nodes.length - 1) * verticalNodeGap(rank)
)
})
const canvasWidth = Math.max(1, ...rowWidths)
@@ -446,6 +446,7 @@ function layoutRankedNodes(
const rank = rankKeys[rankIndex]!
const nodes = ranksByIndex.get(rank)!
const rowHeight = rowHeights[rankIndex]!
const nodeGap = verticalNodeGap(rank)
let x = Math.floor((canvasWidth - rowWidths[rankIndex]!) / 2)
for (const node of nodes) {
const size = sizes.get(node.id)!
@@ -458,7 +459,7 @@ function layoutRankedNodes(
centerX: x + Math.floor(size.width / 2),
centerY: top + Math.floor(size.height / 2),
})
x += size.width + rankNodeGap
x += size.width + nodeGap
}
y += rowHeight + (verticalGaps[rankIndex] ?? 0)
}
+4 -2
View File
@@ -31,7 +31,7 @@ const ID_ONLY_RE = new RegExp(`^${ID_RE}$`)
const EXPLICIT_NODE_SHAPE_RE = new RegExp(`^${ID_RE}(?:\\[|\\(|\\{)`)
const CIRCLE_NODE_RE = new RegExp(`^${ID_RE}\\(\\(.+\\)\\)$`)
const EDGE_OPERATOR_RE =
/(-\.(?!->)(.+?)\.(?:->|-))|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->|\.-)|(<-->|-->|==>|-\.->|---|~~~)\s*(?:\|([^|]*)\|\s*)?/g
/(-\.(?!->)(.+?)\.(?:->|-))|(--|==|-\.)\s+(.+?)\s+(-->|==>|\.->|-\.->|\.-)|(<-->|-->|==>|-\.->|---|~~~)\s*(?:\|([^|]*)\|\s*)?/dg
function normalizeDirection(value?: string): FlowchartDirection {
const upper = value?.toUpperCase()
@@ -161,10 +161,12 @@ function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
const inlineDashedArrow = match[1]
const startArrow = inlineDashedArrow ?? match[3] ?? match[6]!
const endArrow = inlineDashedArrow ?? match[5] ?? match[6]!
const labelGroup = match[2] ? 2 : match[4] ? 4 : match[7] ? 7 : undefined
const labelRange = labelGroup === undefined ? undefined : match.indices?.[labelGroup]
return {
index: match.index,
end: match.index + match[0].length,
label: decodeMermaidText((match[2] ?? match[4] ?? match[7] ?? "").trim()),
label: stripQuotes(labelRange ? line.slice(labelRange[0], labelRange[1]) : ""),
style: edgeStyleFromArrow(startArrow, endArrow),
arrowhead: endArrow === "~~~" || endArrow.endsWith(">"),
sourceArrowhead: startArrow.startsWith("<"),
+6 -1
View File
@@ -15,7 +15,10 @@ export type FlowchartNodeEdgeFadeStyle = `nodeEdgeFade${DiagramFadeStep}`
export type FlowchartDatabaseEdgeFadeStyle = `databaseEdgeFade${DiagramFadeStep}`
export type FlowchartEdgeFadeStyle = FlowchartNodeEdgeFadeStyle | FlowchartDatabaseEdgeFadeStyle
export type FlowchartCellStyle = FlowchartBaseCellStyle | FlowchartEdgeFadeStyle
export type FlowchartGrid = DiagramCanvas<FlowchartCellStyle>
export interface FlowchartCellMetadata {
attributes?: number
}
export type FlowchartGrid = DiagramCanvas<FlowchartCellStyle, FlowchartCellMetadata>
export type FlowchartStyleColors = Required<Record<FlowchartCellStyle, RGBA>>
export const DEFAULT_THEME_RGB = {
node: [228, 239, 232],
@@ -47,6 +50,8 @@ export function resolveFlowchartStyleColors(
export function renderGridStyledText(grid: FlowchartGrid, colors: FlowchartStyleColors): StyledText {
return renderDiagramGridStyledText(grid, (run) => (run.style ? colors[run.style] : undefined), undefined, {
key: (cell) => [cell.style, cell.attributes],
attributes: (run) => run.cell.attributes,
trimTop: true,
trimBottom: true,
})
+39
View File
@@ -250,6 +250,45 @@ sequenceDiagram
expect(diagram.scrollX).toBeGreaterThan(0)
})
test("keeps surrounding Markdown anchored around a wide flowchart", async () => {
const testRenderer = await createTestRenderer({ width: 100, height: 40 })
renderer = testRenderer.renderer
const markdown = new MarkdownRenderable(renderer, {
id: "markdown-wide-flowchart",
content: `## Architecture — the profile is three mechanisms
\`\`\`mermaid
flowchart TB
subgraph consumer["Durable Object"]
DO["ServerWorkerd.create({ storage, config })"]
end
DO --> SO["serverOptions()<br/><i>option flags</i>"]
DO --> RP["replacements()<br/><i>layer overrides</i>"]
SO -->|"fs: watcher/fff off<br/>events.persist: true<br/>mcp.stdio: false<br/>config as string"| SF["ServerFetch.make(options, { overrides })"]
RP -->|"Database → DO-SQLite<br/>Shell/FS/Pty → typed-unavailable<br/>Snapshot/Vcs → no-op<br/>plugins → precompiled only"| SF
SF --> GRAPH["LayerNode graph<br/>(core builds normally,<br/>swapped nodes substituted)"]
subgraph bundle["3rd mechanism: bundle conditions (build time)"]
COND["--conditions=workerd<br/>pty / fff / photon / shell-parser<br/>native modules → inert stubs<br/>#global-roots → workerd path rooting"]
end
COND -.->|import resolution| GRAPH
\`\`\``,
syntaxStyle,
treeSitterClient,
renderNode: createMermaidMarkdownRenderer(renderer),
})
renderer.root.add(markdown)
await renderMarkdown(markdown, testRenderer.renderOnce)
const frame = testRenderer.captureCharFrame()
const heading = frame.split("\n").find((line) => line.includes("Architecture"))
const diagram = markdown.getChildren().find((child) => child instanceof CodeRenderable) as CodeRenderable
expect(heading?.trimStart()).toStartWith("Architecture")
expect(diagram.scrollX).toBe(0)
expect(frame).toContain("Durable Object")
expect(frame).not.toMatch(/<\/?i>|<br|events persist|mcp stdio/)
})
test("renders a Mermaid state fence inside MarkdownRenderable", async () => {
const testRenderer = await createTestRenderer({ width: 80, height: 14 })
renderer = testRenderer.renderer