mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-09 10:59:49 -04:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ec126b1963 | |||
| 84fd347afa | |||
| e8f215bfbc | |||
| 445af9ce70 |
@@ -577,6 +577,7 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1316,7 +1316,15 @@ export function write(
|
||||
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
|
||||
{ concurrency: 8, discard: true },
|
||||
)
|
||||
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
|
||||
// Format the manifest with the same prettier settings as the repo-wide
|
||||
// format pass, so `check:generated` stays clean after the generate bot
|
||||
// reformats the tree.
|
||||
const manifestJson = JSON.stringify(output.files.map((file) => file.path).sort())
|
||||
const manifestContent = yield* Effect.tryPromise({
|
||||
try: () => format(manifestJson, { filepath: manifest, parser: "json", printWidth: 120 }),
|
||||
catch: (error) => new GenerationError({ reason: `Failed to format ${manifest}: ${String(error)}` }),
|
||||
})
|
||||
yield* fs.writeFileString(manifest, manifestContent)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ describe("HttpApiCodegen.write", () => {
|
||||
|
||||
expect(writes).toEqual([
|
||||
{ path: "/generated/session.ts", content: "export const session = {}\n" },
|
||||
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
|
||||
{ path: "/generated/.httpapi-codegen.json", content: '["session.ts"]\n' },
|
||||
])
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -7,6 +7,18 @@ describe("DiagramCanvas", () => {
|
||||
expect(() => new DiagramCanvas(2_000, 1_000)).toThrow(DiagramCanvasSizeError)
|
||||
})
|
||||
|
||||
test("rejects invalid canvas dimensions", () => {
|
||||
for (const [width, height] of [
|
||||
[-1, 10],
|
||||
[10, -1],
|
||||
[1.5, 10],
|
||||
[Number.NaN, 10],
|
||||
[Number.POSITIVE_INFINITY, 10],
|
||||
]) {
|
||||
expect(() => new DiagramCanvas(width, height)).toThrow(DiagramCanvasSizeError)
|
||||
}
|
||||
})
|
||||
|
||||
test("writes cells and text while clipping out-of-bounds positions", () => {
|
||||
const canvas = new DiagramCanvas<"label">(5, 2)
|
||||
|
||||
@@ -26,6 +38,21 @@ describe("DiagramCanvas", () => {
|
||||
expect(stringWidth(canvas.toString())).toBe(4)
|
||||
})
|
||||
|
||||
test("keeps custom measurement for ASCII text", () => {
|
||||
let measurements = 0
|
||||
const canvas = new DiagramCanvas<"label">(5, 1, {
|
||||
measure: () => {
|
||||
measurements += 1
|
||||
return 2
|
||||
},
|
||||
})
|
||||
|
||||
canvas.setText(0, 0, "ab", "label")
|
||||
|
||||
expect(measurements).toBe(2)
|
||||
expect(canvas.getCell(2, 0)?.char).toBe("b")
|
||||
})
|
||||
|
||||
test("preserves combined graphemes while placing later text", () => {
|
||||
const canvas = new DiagramCanvas<"label">(4, 1)
|
||||
|
||||
@@ -48,6 +75,9 @@ describe("DiagramCanvas", () => {
|
||||
canvas.setCell(1, 0, "│", "line")
|
||||
|
||||
expect(canvas.toString()).toBe(" ┼")
|
||||
|
||||
canvas.replaceCell(1, 0, "│", "line")
|
||||
expect(canvas.toString()).toBe(" │")
|
||||
})
|
||||
|
||||
test("iterates style and metadata runs", () => {
|
||||
@@ -93,4 +123,61 @@ describe("DiagramCanvas", () => {
|
||||
expect(canvas.toString({ trimTop: true })).toBe("end")
|
||||
expect(canvas.getTextSize({ trimTop: true })).toEqual({ width: 3, height: 1 })
|
||||
})
|
||||
|
||||
test("measures trim-aware text height without measuring row width", () => {
|
||||
let measurements = 0
|
||||
const canvas = new DiagramCanvas(8, 5, {
|
||||
measure: (text) => {
|
||||
measurements += 1
|
||||
return stringWidth(text)
|
||||
},
|
||||
})
|
||||
canvas.setText(1, 2, "middle")
|
||||
measurements = 0
|
||||
|
||||
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(1)
|
||||
expect(measurements).toBe(0)
|
||||
})
|
||||
|
||||
test("updates tracked row extents when the last visible cell is cleared", () => {
|
||||
const canvas = new DiagramCanvas(8, 1)
|
||||
canvas.setText(1, 0, "abc")
|
||||
canvas.setCell(3, 0, " ")
|
||||
|
||||
expect(canvas.toString()).toBe(" ab")
|
||||
expect(canvas.getTextSize()).toEqual({ width: 3, height: 1 })
|
||||
})
|
||||
|
||||
test("keeps tracked extents equivalent to scanning after mixed writes", () => {
|
||||
const canvas = new DiagramCanvas<"line">(20, 10, {
|
||||
mergeCell: (_existing, incoming) => incoming,
|
||||
})
|
||||
let seed = 42
|
||||
const next = (limit: number) => {
|
||||
seed = (seed * 1_664_525 + 1_013_904_223) >>> 0
|
||||
return seed % limit
|
||||
}
|
||||
|
||||
for (let index = 0; index < 200; index++) {
|
||||
const x = next(canvas.width)
|
||||
const y = next(canvas.height)
|
||||
const char = [" ", "x", "─"][next(3)]!
|
||||
if (next(2) === 0) canvas.setCell(x, y, char, "line")
|
||||
else canvas.replaceCell(x, y, char, "line")
|
||||
}
|
||||
|
||||
const scanned = canvas.rows.map((row) => {
|
||||
let end = row.length
|
||||
while (end > 0 && row[end - 1]?.char === " ") end -= 1
|
||||
return row
|
||||
.slice(0, end)
|
||||
.map((cell) => cell.char)
|
||||
.join("")
|
||||
})
|
||||
const first = scanned.findIndex((line) => line.length > 0)
|
||||
const last = scanned.findLastIndex((line) => line.length > 0)
|
||||
|
||||
expect(canvas.toString()).toBe(scanned.join("\n"))
|
||||
expect(canvas.getTextHeight({ trimTop: true, trimBottom: true })).toBe(first < 0 ? 0 : last - first + 1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -47,7 +47,12 @@ export class DiagramCanvasSizeError extends Error {
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
) {
|
||||
super(`Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`)
|
||||
const invalid = !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0
|
||||
super(
|
||||
invalid
|
||||
? `Diagram canvas dimensions must be non-negative safe integers, received ${width}x${height}`
|
||||
: `Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`,
|
||||
)
|
||||
this.name = "DiagramCanvasSizeError"
|
||||
}
|
||||
}
|
||||
@@ -61,29 +66,31 @@ function sameKey(left: readonly unknown[] | undefined, right: readonly unknown[]
|
||||
}
|
||||
|
||||
export class DiagramCanvas<Style extends string, Metadata extends object = object> {
|
||||
readonly rows: Array<Array<DiagramCanvasCell<Style, Metadata>>>
|
||||
|
||||
private readonly cells: Array<Array<DiagramCanvasCell<Style, Metadata>>>
|
||||
private readonly measure: (text: string) => number
|
||||
private readonly mergeCell?: DiagramCanvasOptions<Style, Metadata>["mergeCell"]
|
||||
private readonly rowEnds: Uint32Array
|
||||
|
||||
constructor(
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
options: DiagramCanvasOptions<Style, Metadata> = {},
|
||||
) {
|
||||
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 0 || height < 0) {
|
||||
throw new DiagramCanvasSizeError(width, height)
|
||||
}
|
||||
if (width * height > MAX_DIAGRAM_CELLS) throw new DiagramCanvasSizeError(width, height)
|
||||
this.measure = options.measure ?? stringWidth
|
||||
this.mergeCell = options.mergeCell
|
||||
this.rows = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
this.cells = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
this.rowEnds = new Uint32Array(height)
|
||||
}
|
||||
|
||||
private rowTextEnd(row: Array<DiagramCanvasCell<Style, Metadata>>): number {
|
||||
let rowEnd = row.length
|
||||
while (rowEnd > 0 && row[rowEnd - 1]?.char === " ") rowEnd -= 1
|
||||
return rowEnd
|
||||
get rows(): ReadonlyArray<ReadonlyArray<Readonly<DiagramCanvasCell<Style, Metadata>>>> {
|
||||
return this.cells
|
||||
}
|
||||
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd = this.rowTextEnd(row)): string {
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd: number): string {
|
||||
return row
|
||||
.slice(0, rowEnd)
|
||||
.map((cell) => cell.char)
|
||||
@@ -92,28 +99,58 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
|
||||
private textRowRange(trimTop: boolean, trimBottom: boolean): { start: number; end: number } {
|
||||
let start = 0
|
||||
let end = this.rows.length
|
||||
if (trimTop) while (start < end && this.rowTextEnd(this.rows[start]!) === 0) start += 1
|
||||
if (trimBottom) while (end > start && this.rowTextEnd(this.rows[end - 1]!) === 0) end -= 1
|
||||
let end = this.cells.length
|
||||
if (trimTop) while (start < end && this.rowEnds[start] === 0) start += 1
|
||||
if (trimBottom) while (end > start && this.rowEnds[end - 1] === 0) end -= 1
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
setCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
|
||||
if (y < 0 || y >= this.rows.length || x < 0 || x >= this.rows[y]!.length) return
|
||||
|
||||
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
|
||||
this.rows[y]![x] = this.mergeCell?.(this.rows[y]![x]!, incoming) ?? incoming
|
||||
this.writeCell(x, y, char, style, metadata, true)
|
||||
}
|
||||
|
||||
getCell(x: number, y: number): DiagramCanvasCell<Style, Metadata> | undefined {
|
||||
return this.rows[y]?.[x]
|
||||
replaceCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
|
||||
this.writeCell(x, y, char, style, metadata, false)
|
||||
}
|
||||
|
||||
private writeCell(
|
||||
x: number,
|
||||
y: number,
|
||||
char: string,
|
||||
style: Style | undefined,
|
||||
metadata: Partial<Metadata> | undefined,
|
||||
merge: boolean,
|
||||
): void {
|
||||
if (y < 0 || y >= this.cells.length || x < 0 || x >= this.cells[y]!.length) return
|
||||
|
||||
const incoming = { char, style, ...metadata } as DiagramCanvasCell<Style, Metadata>
|
||||
const cell = merge ? (this.mergeCell?.(this.cells[y]![x]!, incoming) ?? incoming) : incoming
|
||||
this.cells[y]![x] = cell
|
||||
if (cell.char !== " ") {
|
||||
this.rowEnds[y] = Math.max(this.rowEnds[y]!, x + 1)
|
||||
} else if (this.rowEnds[y] === x + 1) {
|
||||
let end = x
|
||||
while (end > 0 && this.cells[y]![end - 1]?.char === " ") end -= 1
|
||||
this.rowEnds[y] = end
|
||||
}
|
||||
}
|
||||
|
||||
getCell(x: number, y: number): Readonly<DiagramCanvasCell<Style, Metadata>> | undefined {
|
||||
return this.cells[y]?.[x]
|
||||
}
|
||||
|
||||
setText(x: number, y: number, text: string, style?: Style, metadata?: DiagramCanvasTextMetadata<Metadata>): void {
|
||||
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
|
||||
if (this.measure === stringWidth && /^[\x20-\x7e]*$/.test(text)) {
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
this.setCell(x + index, y, text[index]!, style, metadataAt(x + index))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let offset = 0
|
||||
for (const grapheme of diagramTextGraphemes(text)) {
|
||||
const width = Math.max(1, this.measure(grapheme))
|
||||
const metadataAt = (cellX: number) => (typeof metadata === "function" ? metadata(cellX, y) : metadata)
|
||||
this.setCell(x + offset, y, grapheme, style, metadataAt(x + offset))
|
||||
for (let continuation = 1; continuation < width; continuation++) {
|
||||
this.setCell(x + offset + continuation, y, "", style, metadataAt(x + offset + continuation))
|
||||
@@ -126,7 +163,7 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const lines: string[] = []
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
lines.push(this.rowText(this.rows[rowIndex]!))
|
||||
lines.push(this.rowText(this.cells[rowIndex]!, this.rowEnds[rowIndex]!))
|
||||
}
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -135,13 +172,18 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
let width = 0
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
const row = this.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
if (rowEnd > 0) width = Math.max(width, this.measure(this.rowText(row, rowEnd)))
|
||||
}
|
||||
return { width, height: rows.end - rows.start }
|
||||
}
|
||||
|
||||
getTextHeight(options: DiagramCanvasTextOptions = {}): number {
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
return rows.end - rows.start
|
||||
}
|
||||
|
||||
forEachRun(
|
||||
onRun: (run: DiagramCanvasRun<Style, Metadata>) => void,
|
||||
onLineEnd: () => void,
|
||||
@@ -151,8 +193,8 @@ export class DiagramCanvas<Style extends string, Metadata extends object = objec
|
||||
const rows = this.textRowRange(options.trimTop ?? false, options.trimBottom ?? false)
|
||||
|
||||
for (let rowIndex = rows.start; rowIndex < rows.end; rowIndex++) {
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
const row = this.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
|
||||
let currentCell: DiagramCanvasCell<Style, Metadata> | undefined
|
||||
let currentKey: readonly unknown[] | undefined
|
||||
|
||||
@@ -27,7 +27,12 @@ export function firstMeaningfulMermaidLine(content: string): string | undefined
|
||||
export function stripMermaidQuotes(value: string): string {
|
||||
const trimmed = value.trim()
|
||||
if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
|
||||
return trimmed.slice(1, -1)
|
||||
return decodeMermaidText(trimmed.slice(1, -1))
|
||||
}
|
||||
return trimmed
|
||||
return decodeMermaidText(trimmed)
|
||||
}
|
||||
|
||||
export function decodeMermaidText(value: string): string {
|
||||
return decodeHTMLStrict(value)
|
||||
}
|
||||
import { decodeHTMLStrict } from "entities"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "./spatial.js"
|
||||
|
||||
const body = spatialRectClaim("body", "node:A", "body", { left: 2, top: 1, width: 4, height: 3 })
|
||||
const label = spatialRectClaim("label", "edge:A-B", "label", { left: 8, top: 1, width: 5, height: 1 })
|
||||
const route = spatialPathClaim("route", "edge:A-B", "route", [
|
||||
{ x: 5, y: 2 },
|
||||
{ x: 10, y: 2 },
|
||||
])
|
||||
|
||||
describe("SpatialIndex", () => {
|
||||
test("composition is associative, commutative, idempotent, and has an identity", () => {
|
||||
const a = SpatialIndex.empty().add(body)
|
||||
const b = SpatialIndex.empty().add(label)
|
||||
const c = SpatialIndex.empty().add(route)
|
||||
|
||||
expect(SpatialIndex.empty().overlay(a).claims).toEqual(a.claims)
|
||||
expect(a.overlay(b).claims).toEqual(b.overlay(a).claims)
|
||||
expect(a.overlay(b).overlay(c).claims).toEqual(a.overlay(b.overlay(c)).claims)
|
||||
expect(a.overlay(a).claims).toEqual(a.claims)
|
||||
})
|
||||
|
||||
test("routes may share routes but cannot cross unrelated semantic bodies", () => {
|
||||
const index = SpatialIndex.empty().add(body, route)
|
||||
const crossingBody = spatialPathClaim("cross-body", "edge:C-D", "route", [
|
||||
{ x: 0, y: 2 },
|
||||
{ x: 8, y: 2 },
|
||||
])
|
||||
const crossingRoute = spatialPathClaim("cross-route", "edge:C-D", "route", [
|
||||
{ x: 7, y: 0 },
|
||||
{ x: 7, y: 4 },
|
||||
])
|
||||
|
||||
expect(index.isFree(crossingBody)).toBe(false)
|
||||
expect(index.isFree(crossingRoute)).toBe(true)
|
||||
})
|
||||
|
||||
test("declared endpoint contacts do not permit contact elsewhere", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const candidate = spatialPathClaim("candidate", "edge:B-A", "route", [
|
||||
{ x: 0, y: 2 },
|
||||
{ x: 2, y: 2 },
|
||||
])
|
||||
|
||||
expect(index.isFree(candidate)).toBe(false)
|
||||
expect(index.isFree(candidate, { contacts: [{ owner: "node:A", points: [{ x: 2, y: 2 }] }] })).toBe(true)
|
||||
})
|
||||
|
||||
test("firstFit chooses the first collision-free candidate", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const blocked = spatialRectClaim("blocked", "label:B", "label", { left: 3, top: 2, width: 2, height: 1 })
|
||||
const clear = spatialRectClaim("clear", "label:B", "label", { left: 7, top: 2, width: 2, height: 1 })
|
||||
|
||||
expect(index.firstFit([{ claim: blocked }, { claim: clear }])?.claim.id).toBe("clear")
|
||||
})
|
||||
|
||||
test("clearance is symmetric in both axes", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
|
||||
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
|
||||
|
||||
expect(index.isFree(touchingRight)).toBe(true)
|
||||
expect(index.isFree(touchingRight, { clearance: 1 })).toBe(false)
|
||||
expect(index.isFree(touchingBelow)).toBe(true)
|
||||
expect(index.isFree(touchingBelow, { clearance: 1 })).toBe(false)
|
||||
})
|
||||
|
||||
test("axis-specific clearance does not move unrelated rows", () => {
|
||||
const index = SpatialIndex.empty().add(body)
|
||||
const touchingRight = spatialRectClaim("right", "label:B", "label", { left: 6, top: 1, width: 2, height: 1 })
|
||||
const touchingBelow = spatialRectClaim("below", "label:C", "label", { left: 2, top: 4, width: 2, height: 1 })
|
||||
|
||||
expect(index.isFree(touchingRight, { clearance: { x: 1, y: 0 } })).toBe(false)
|
||||
expect(index.isFree(touchingBelow, { clearance: { x: 1, y: 0 } })).toBe(true)
|
||||
})
|
||||
|
||||
test("rejects malformed geometry instead of weakening collision checks", () => {
|
||||
expect(() => spatialRectClaim("zero", "node", "body", { left: 0, top: 0, width: 0, height: 1 })).toThrow()
|
||||
expect(() =>
|
||||
spatialPathClaim("diagonal", "edge", "route", [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 1 },
|
||||
]),
|
||||
).toThrow()
|
||||
expect(() => SpatialIndex.empty().add(body).isFree(label, { clearance: Number.POSITIVE_INFINITY })).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,242 @@
|
||||
import { orthogonalPathPoints, type DiagramBounds, type DiagramPoint } from "./geometry.js"
|
||||
|
||||
export type SpatialRole = "body" | "boundary" | "terminal" | "route" | "label"
|
||||
|
||||
export interface SpatialSpan {
|
||||
readonly y: number
|
||||
readonly fromX: number
|
||||
readonly toX: number
|
||||
}
|
||||
|
||||
export interface SpatialClaim {
|
||||
readonly id: string
|
||||
readonly owner: string
|
||||
readonly role: SpatialRole
|
||||
readonly spans: readonly SpatialSpan[]
|
||||
}
|
||||
|
||||
export interface SpatialContact {
|
||||
owner: string
|
||||
points: readonly DiagramPoint[]
|
||||
}
|
||||
|
||||
export interface SpatialConflict {
|
||||
moving: SpatialClaim
|
||||
existing: SpatialClaim
|
||||
point: DiagramPoint
|
||||
}
|
||||
|
||||
export interface SpatialClearance {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface SpatialCollisionPolicy {
|
||||
contacts?: readonly SpatialContact[]
|
||||
clearance?: number | SpatialClearance | Partial<Record<SpatialRole, number | SpatialClearance>>
|
||||
}
|
||||
|
||||
function normalizedSpan(y: number, fromX: number, toX: number): SpatialSpan {
|
||||
return { y, fromX: Math.min(fromX, toX), toX: Math.max(fromX, toX) }
|
||||
}
|
||||
|
||||
function assertFiniteInteger(value: number, name: string): void {
|
||||
if (!Number.isFinite(value) || !Number.isInteger(value)) throw new RangeError(`${name} must be a finite integer`)
|
||||
}
|
||||
|
||||
export function spatialRectSpans(bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">): SpatialSpan[] {
|
||||
assertFiniteInteger(bounds.left, "bounds.left")
|
||||
assertFiniteInteger(bounds.top, "bounds.top")
|
||||
assertFiniteInteger(bounds.width, "bounds.width")
|
||||
assertFiniteInteger(bounds.height, "bounds.height")
|
||||
if (bounds.width <= 0 || bounds.height <= 0) throw new RangeError("Spatial bounds must have positive dimensions")
|
||||
return Array.from({ length: bounds.height }, (_, offset) =>
|
||||
normalizedSpan(bounds.top + offset, bounds.left, bounds.left + bounds.width - 1),
|
||||
)
|
||||
}
|
||||
|
||||
export function spatialPathSpans(points: readonly DiagramPoint[]): SpatialSpan[] {
|
||||
for (const [index, point] of points.entries()) {
|
||||
assertFiniteInteger(point.x, `points[${index}].x`)
|
||||
assertFiniteInteger(point.y, `points[${index}].y`)
|
||||
if (index > 0 && point.x !== points[index - 1]!.x && point.y !== points[index - 1]!.y) {
|
||||
throw new RangeError("Spatial paths must be orthogonal")
|
||||
}
|
||||
}
|
||||
const cells = new Map<number, Set<number>>()
|
||||
const add = (point: DiagramPoint): void => {
|
||||
const row = cells.get(point.y) ?? new Set<number>()
|
||||
row.add(point.x)
|
||||
cells.set(point.y, row)
|
||||
}
|
||||
|
||||
if (points.length === 1) add(points[0]!)
|
||||
for (const point of orthogonalPathPoints(points)) add(point)
|
||||
|
||||
return [...cells.entries()]
|
||||
.sort(([left], [right]) => left - right)
|
||||
.flatMap(([y, xs]) => {
|
||||
const sorted = [...xs].sort((left, right) => left - right)
|
||||
const spans: SpatialSpan[] = []
|
||||
let start = sorted[0]
|
||||
let end = start
|
||||
if (start === undefined) return spans
|
||||
for (const x of sorted.slice(1)) {
|
||||
if (x === end! + 1) {
|
||||
end = x
|
||||
continue
|
||||
}
|
||||
spans.push(normalizedSpan(y, start, end!))
|
||||
start = x
|
||||
end = x
|
||||
}
|
||||
spans.push(normalizedSpan(y, start, end!))
|
||||
return spans
|
||||
})
|
||||
}
|
||||
|
||||
export function spatialRectClaim(
|
||||
id: string,
|
||||
owner: string,
|
||||
role: SpatialRole,
|
||||
bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">,
|
||||
): SpatialClaim {
|
||||
return { id, owner, role, spans: spatialRectSpans(bounds) }
|
||||
}
|
||||
|
||||
export function spatialPathClaim(
|
||||
id: string,
|
||||
owner: string,
|
||||
role: Extract<SpatialRole, "boundary" | "route">,
|
||||
points: readonly DiagramPoint[],
|
||||
): SpatialClaim {
|
||||
return { id, owner, role, spans: spatialPathSpans(points) }
|
||||
}
|
||||
|
||||
function compareClaims(left: SpatialClaim, right: SpatialClaim): number {
|
||||
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0
|
||||
}
|
||||
|
||||
function sameClaim(left: SpatialClaim, right: SpatialClaim): boolean {
|
||||
return (
|
||||
left.id === right.id &&
|
||||
left.owner === right.owner &&
|
||||
left.role === right.role &&
|
||||
left.spans.length === right.spans.length &&
|
||||
left.spans.every(
|
||||
(span, index) =>
|
||||
span.y === right.spans[index]!.y &&
|
||||
span.fromX === right.spans[index]!.fromX &&
|
||||
span.toX === right.spans[index]!.toX,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function pointIsContact(point: DiagramPoint, existing: SpatialClaim, contacts: readonly SpatialContact[]): boolean {
|
||||
return contacts.some(
|
||||
(contact) =>
|
||||
contact.owner === existing.owner &&
|
||||
contact.points.some((candidate) => candidate.x === point.x && candidate.y === point.y),
|
||||
)
|
||||
}
|
||||
|
||||
function rolesMayOverlap(moving: SpatialClaim, existing: SpatialClaim): boolean {
|
||||
if (moving.owner === existing.owner) return true
|
||||
return moving.role === "route" && existing.role === "route"
|
||||
}
|
||||
|
||||
function normalizeClearance(clearance: number | SpatialClearance | undefined): SpatialClearance {
|
||||
const x = typeof clearance === "number" ? clearance : (clearance?.x ?? 0)
|
||||
const y = typeof clearance === "number" ? clearance : (clearance?.y ?? 0)
|
||||
assertFiniteInteger(x, "clearance.x")
|
||||
assertFiniteInteger(y, "clearance.y")
|
||||
if (x < 0 || y < 0) throw new RangeError("Spatial clearance cannot be negative")
|
||||
return { x, y }
|
||||
}
|
||||
|
||||
function inflateSpan(span: SpatialSpan, clearance: SpatialClearance): SpatialSpan {
|
||||
return { y: span.y, fromX: span.fromX - clearance.x, toX: span.toX + clearance.x }
|
||||
}
|
||||
|
||||
export class SpatialIndex {
|
||||
static empty(): SpatialIndex {
|
||||
return new SpatialIndex([])
|
||||
}
|
||||
|
||||
readonly claims: readonly SpatialClaim[]
|
||||
|
||||
private constructor(claims: readonly SpatialClaim[]) {
|
||||
this.claims = Object.freeze(
|
||||
claims.map((claim) =>
|
||||
Object.freeze({
|
||||
...claim,
|
||||
spans: Object.freeze(
|
||||
[...claim.spans]
|
||||
.map((span) => Object.freeze({ ...span }))
|
||||
.sort((left, right) => left.y - right.y || left.fromX - right.fromX || left.toX - right.toX),
|
||||
),
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
add(...claims: readonly SpatialClaim[]): SpatialIndex {
|
||||
return this.overlay(new SpatialIndex(claims))
|
||||
}
|
||||
|
||||
overlay(other: SpatialIndex): SpatialIndex {
|
||||
const claims = new Map(this.claims.map((claim) => [claim.id, claim]))
|
||||
for (const claim of other.claims) {
|
||||
const existing = claims.get(claim.id)
|
||||
if (existing && !sameClaim(existing, claim)) throw new Error(`Conflicting spatial claim id: ${claim.id}`)
|
||||
claims.set(claim.id, claim)
|
||||
}
|
||||
return new SpatialIndex([...claims.values()].sort(compareClaims))
|
||||
}
|
||||
|
||||
conflicts(moving: SpatialClaim, policy: SpatialCollisionPolicy = {}): SpatialConflict[] {
|
||||
const contacts = policy.contacts ?? []
|
||||
const conflicts: SpatialConflict[] = []
|
||||
|
||||
for (const existing of this.claims) {
|
||||
if (rolesMayOverlap(moving, existing)) continue
|
||||
const configuredClearance =
|
||||
typeof policy.clearance === "number" || (policy.clearance && "x" in policy.clearance)
|
||||
? policy.clearance
|
||||
: policy.clearance?.[existing.role]
|
||||
const clearance = normalizeClearance(configuredClearance)
|
||||
for (const movingSpan of moving.spans) {
|
||||
for (let dy = -clearance.y; dy <= clearance.y; dy++) {
|
||||
const inflated = inflateSpan({ ...movingSpan, y: movingSpan.y + dy }, clearance)
|
||||
for (const existingSpan of existing.spans) {
|
||||
if (inflated.y !== existingSpan.y) continue
|
||||
const fromX = Math.max(inflated.fromX, existingSpan.fromX)
|
||||
const toX = Math.min(inflated.toX, existingSpan.toX)
|
||||
for (let x = fromX; x <= toX; x++) {
|
||||
const point = { x, y: inflated.y }
|
||||
const movingOccupiesPoint = moving.spans.some(
|
||||
(span) => span.y === point.y && point.x >= span.fromX && point.x <= span.toX,
|
||||
)
|
||||
if (!(movingOccupiesPoint && pointIsContact(point, existing, contacts))) {
|
||||
conflicts.push({ moving, existing, point })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conflicts
|
||||
}
|
||||
|
||||
isFree(claim: SpatialClaim, policy: SpatialCollisionPolicy = {}): boolean {
|
||||
return this.conflicts(claim, policy).length === 0
|
||||
}
|
||||
|
||||
firstFit<T extends { claim: SpatialClaim }>(
|
||||
candidates: readonly T[],
|
||||
policy: SpatialCollisionPolicy = {},
|
||||
): T | undefined {
|
||||
return candidates.find((candidate) => this.isFree(candidate.claim, policy))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
export type MermaidDiagramKind = "flowchart" | "sequence" | "state"
|
||||
|
||||
/** An otherwise valid diagram contains syntax that merman does not support. */
|
||||
/** An otherwise valid diagram contains syntax that this renderer does not support. */
|
||||
export class MermaidSyntaxError extends Error {
|
||||
readonly _tag = "MermaidSyntaxError"
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ function drawSubgraphLabel(grid: FlowchartGrid, bounds: FlowchartSubgraphBounds)
|
||||
}
|
||||
|
||||
function drawEdgeLabel(grid: FlowchartGrid, route: FlowchartEdgeRoute, style: FlowchartCellStyle): void {
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
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)
|
||||
}
|
||||
@@ -249,15 +249,22 @@ function drawSourceConnectors(
|
||||
if (routeDirection && connectorDirection) {
|
||||
const cell = grid.getCell(sourcePoint.x, sourcePoint.y)
|
||||
if (cell) {
|
||||
cell.char = diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
grid.replaceCell(
|
||||
sourcePoint.x,
|
||||
sourcePoint.y,
|
||||
diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
),
|
||||
"edge",
|
||||
)
|
||||
cell.style = "edge"
|
||||
}
|
||||
}
|
||||
fadeSourcePath(grid, connector, route.points, styles, occupancy)
|
||||
if (route.edge.sourceArrowhead && route.points[1]) {
|
||||
grid.setCell(sourcePoint.x, sourcePoint.y, diagramArrowHeadBetween(route.points[1], sourcePoint), "edge")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { parseColor } from "@opentui/core"
|
||||
import stringWidth from "string-width"
|
||||
import { colorsEqual } from "../core/color/style.js"
|
||||
import { expectDiagram } from "../test/diagram.js"
|
||||
import { drawFlowchartDiagramGrid as drawParsedFlowchartDiagramGrid } from "./drawing.js"
|
||||
import {
|
||||
@@ -9,6 +8,7 @@ import {
|
||||
DEFAULT_MIN_VERTICAL_RANK_GAP,
|
||||
layoutFlowchartDiagram as layoutParsedFlowchartDiagram,
|
||||
} from "./layout.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import { parseMermaidFlowchartDiagram } from "./parser.js"
|
||||
import { renderFlowchartDiagram } from "./render.js"
|
||||
import { renderGridStyledText, resolveFlowchartStyleColors } from "./style.js"
|
||||
@@ -55,6 +55,63 @@ function routeRunsAlongVerticalBorder(
|
||||
return false
|
||||
}
|
||||
|
||||
function routeIntersectsBounds(
|
||||
route: { points: readonly { x: number; y: number }[] },
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
for (let index = 1; index < route.points.length; index++) {
|
||||
const from = route.points[index - 1]!
|
||||
const to = route.points[index]!
|
||||
if (from.x === to.x) {
|
||||
if (
|
||||
from.x >= bounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= bounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
) {
|
||||
return true
|
||||
}
|
||||
} else if (
|
||||
from.y >= bounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= bounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function terminalPointsTowardBounds(
|
||||
route: { points: readonly { x: number; y: number }[] },
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const before = route.points.at(-2)!
|
||||
const end = route.points.at(-1)!
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
if (end.x === bounds.left - 1 && end.y >= bounds.top && end.y <= bottom) return before.x < end.x && before.y === end.y
|
||||
if (end.x === right + 1 && end.y >= bounds.top && end.y <= bottom) return before.x > end.x && before.y === end.y
|
||||
if (end.y === bounds.top - 1 && end.x >= bounds.left && end.x <= right) return before.y < end.y && before.x === end.x
|
||||
if (end.y === bottom + 1 && end.x >= bounds.left && end.x <= right) return before.y > end.y && before.x === end.x
|
||||
return false
|
||||
}
|
||||
|
||||
function boundsIntersect(
|
||||
left: { left: number; top: number; width: number; height: number },
|
||||
right: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
return (
|
||||
left.left <= right.left + right.width - 1 &&
|
||||
left.left + left.width - 1 >= right.left &&
|
||||
left.top <= right.top + right.height - 1 &&
|
||||
left.top + left.height - 1 >= right.top
|
||||
)
|
||||
}
|
||||
|
||||
describe("FlowchartDiagram", () => {
|
||||
test("renders compact horizontal flowcharts with shorter routes", () => {
|
||||
const output = renderFlowchartDiagram(
|
||||
@@ -208,6 +265,67 @@ describe("FlowchartDiagram", () => {
|
||||
`)
|
||||
})
|
||||
|
||||
test("keeps vertical feedback labels clear of unrelated nodes", () => {
|
||||
const content = `flowchart TD
|
||||
S[Source] --> A[Alpha]
|
||||
S --> B{Beta?}
|
||||
S --> C[(Store)]
|
||||
A --> J[[Join]]
|
||||
B --> J
|
||||
C --> J
|
||||
J -->|cycle back| S`
|
||||
const layout = layoutFlowchartDiagram(content)
|
||||
const feedback = layout.routes.find((route) => route.edge.from === "J" && route.edge.to === "S")!
|
||||
const label = flowchartEdgeLabelLayout(feedback.points, feedback.edge.label, stringWidth)
|
||||
const labelBounds = { left: label.point.x, top: label.point.y, width: label.width, height: label.height }
|
||||
|
||||
for (const id of ["A", "B", "C"]) expect(boundsIntersect(labelBounds, layout.bounds.get(id)!)).toBe(false)
|
||||
expect(renderFlowchartDiagram(content)).toContain("cycle back")
|
||||
})
|
||||
|
||||
test("routes horizontal feedback edges around sibling nodes", () => {
|
||||
for (const direction of ["LR", "RL"] as const) {
|
||||
const layout = layoutFlowchartDiagram(`flowchart ${direction}
|
||||
S[Start] --> D{Ready?}
|
||||
D --> O[Output]
|
||||
D --> R[Retry]
|
||||
R --> S`)
|
||||
const feedback = layout.routes.find((route) => route.edge.from === "R" && route.edge.to === "S")!
|
||||
|
||||
expect(routeIntersectsBounds(feedback, layout.bounds.get("O")!)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps compact vertical fan-in arrowheads pointed at the target", () => {
|
||||
const content = `flowchart TD
|
||||
A[Left] -->|left| C[Merge]
|
||||
B[Right] -->|right| C`
|
||||
const layout = layoutFlowchartDiagram(content, { compact: true })
|
||||
|
||||
for (const route of layout.routes) {
|
||||
const beforeTarget = route.points.at(-2)!
|
||||
const target = route.points.at(-1)!
|
||||
expect(beforeTarget.x).toBe(target.x)
|
||||
expect(beforeTarget.y).toBeLessThan(target.y)
|
||||
}
|
||||
expect(renderFlowchartDiagram(content, { compact: true })).toContain("▼")
|
||||
})
|
||||
|
||||
test("routes same-rank vertical-flow edges into the target side", () => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart TD
|
||||
B[Start] --> D{Choose}
|
||||
D --> E[[Primary]]
|
||||
D --> F[Fallback]
|
||||
E --> B
|
||||
F --> E`)
|
||||
const route = layout.routes.find((candidate) => candidate.edge.from === "F" && candidate.edge.to === "E")!
|
||||
const beforeTarget = route.points.at(-2)!
|
||||
const target = route.points.at(-1)!
|
||||
|
||||
expect(beforeTarget.y).toBe(target.y)
|
||||
expect(beforeTarget.x).toBeGreaterThan(target.x)
|
||||
})
|
||||
|
||||
test("renders parallel same-endpoint edges without losing labels", () => {
|
||||
const content = `flowchart LR
|
||||
A[Source] -->|first| B[Target]
|
||||
@@ -238,6 +356,36 @@ describe("FlowchartDiagram", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps five parallel multiline edge labels distinct", () => {
|
||||
const output = renderFlowchartDiagram(`flowchart TD
|
||||
A[Source] -->|one alpha<br/>one beta| B[Target]
|
||||
A -->|two alpha<br/>two beta| B
|
||||
A -->|three alpha<br/>three beta| B
|
||||
A -->|four alpha<br/>four beta| B
|
||||
A -->|five alpha<br/>five beta| B`)
|
||||
|
||||
for (const number of ["one", "two", "three", "four", "five"]) {
|
||||
expect(output.match(new RegExp(`${number} alpha`, "g"))).toHaveLength(1)
|
||||
expect(output.match(new RegExp(`${number} beta`, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("does not reserve label gaps for unlabeled fan-out", () => {
|
||||
const output = renderFlowchartDiagram(`flowchart TD
|
||||
S[The Boss] --> A[A]
|
||||
S --> B[B]
|
||||
S --> C[C]
|
||||
S --> D[D]
|
||||
S --> E[E]
|
||||
S --> F[F]
|
||||
S --> G[G]
|
||||
S --> H[H]
|
||||
S --> I[I]
|
||||
S --> J[J]`)
|
||||
|
||||
expect(Math.max(...output.split("\n").map((line) => stringWidth(line)))).toBeLessThanOrEqual(100)
|
||||
})
|
||||
|
||||
test("keeps transitive targets below intermediate vertical stages", () => {
|
||||
const content = `flowchart TD
|
||||
A[Start] --> B[Validate]
|
||||
@@ -389,6 +537,14 @@ flowchart TD
|
||||
])
|
||||
})
|
||||
|
||||
test("decodes HTML entities in node and edge labels", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
A[HMAC verify <3s & continue] -->|result ≥ 1| B[Done]`)
|
||||
|
||||
expect(diagram.nodes.find((node) => node.id === "A")?.label).toBe("HMAC verify <3s & continue")
|
||||
expect(diagram.edges[0]?.label).toBe("result ≥ 1")
|
||||
})
|
||||
|
||||
test("parses and renders each edge in a chained flowchart statement", () => {
|
||||
const content = `flowchart LR
|
||||
API --> Worker --> DB[(Database)]`
|
||||
@@ -434,6 +590,25 @@ flowchart TD
|
||||
])
|
||||
})
|
||||
|
||||
test("parses labeled undirected dashed and bidirectional edges", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)]
|
||||
API[Slack API]
|
||||
DB -. no shared transaction .- API
|
||||
API <--> DB`)
|
||||
|
||||
expect(diagram.edges).toEqual([
|
||||
{ from: "DB", to: "API", label: "no shared transaction", style: "dashed", arrowhead: false },
|
||||
{ from: "API", to: "DB", label: "", sourceArrowhead: true },
|
||||
])
|
||||
const dashedOutput = renderFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)] -. no shared transaction .- API[Slack API]`)
|
||||
const bidirectionalOutput = renderFlowchartDiagram(`flowchart LR
|
||||
DB[(Durable Object SQLite)] <--> API[Slack API]`)
|
||||
expect(dashedOutput).toContain("no shared transaction")
|
||||
expect(bidirectionalOutput.match(/[◀▶▲▼]/g)?.length).toBeGreaterThanOrEqual(2)
|
||||
})
|
||||
|
||||
test("renders the volume persistence diagram with an undirected solid edge", () => {
|
||||
const content = `flowchart LR
|
||||
subgraph durable [Durable — survives everything]
|
||||
@@ -884,6 +1059,94 @@ flowchart TD
|
||||
expect(route.points[0]!.y).toBe(route.points[route.points.length - 1]!.y)
|
||||
})
|
||||
|
||||
test("routes cross-subgraph edges around local-direction siblings", () => {
|
||||
const layout = layoutFlowchartDiagram(`flowchart TD
|
||||
subgraph Workers
|
||||
direction TD
|
||||
A[Worker one] --> B[Worker two]
|
||||
end
|
||||
subgraph Peer
|
||||
direction RL
|
||||
C[Store] --> D[Transform]
|
||||
end
|
||||
B --> D`)
|
||||
const route = layout.routes.find((candidate) => candidate.edge.from === "B" && candidate.edge.to === "D")!
|
||||
|
||||
expect(routeIntersectsBounds(route, layout.bounds.get("C")!)).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["BT", { compact: true }],
|
||||
["LR", { compact: true }],
|
||||
["RL", { compact: true }],
|
||||
] as const)("keeps labeled cross-group routes clear of sibling nodes in %s layouts", (direction, options) => {
|
||||
const content = `flowchart ${direction}
|
||||
subgraph Left
|
||||
direction RL
|
||||
A[API] --> B[Queue]
|
||||
end
|
||||
subgraph Right
|
||||
direction TB
|
||||
C[Transform] --> D[Accept]
|
||||
end
|
||||
B -->|cross group| C
|
||||
D -->|retry group| A`
|
||||
const layout = layoutFlowchartDiagram(content, options)
|
||||
const crossGroup = layout.routes.find((route) => route.edge.from === "B" && route.edge.to === "C")!
|
||||
|
||||
if (direction !== "LR") expect(routeIntersectsBounds(crossGroup, layout.bounds.get("A")!)).toBe(false)
|
||||
expect(renderFlowchartDiagram(content, options)).toContain("cross group")
|
||||
expect(renderFlowchartDiagram(content, options)).toContain("retry group")
|
||||
})
|
||||
|
||||
test.each(["LR", "RL"] as const)(
|
||||
"keeps nested result labels and target-facing entry routes in %s layouts",
|
||||
(direction) => {
|
||||
const content = `flowchart ${direction}
|
||||
I[Input] --> A
|
||||
subgraph Outer
|
||||
direction LR
|
||||
subgraph Inner
|
||||
direction BT
|
||||
A[Parse] --> B[Valid]
|
||||
B --> C[Cache]
|
||||
C --> B
|
||||
end
|
||||
B --> D[Dispatch]
|
||||
end
|
||||
D -->|result path| O[Output]`
|
||||
const layout = layoutFlowchartDiagram(content)
|
||||
const entry = layout.routes.find((route) => route.edge.from === "I" && route.edge.to === "A")!
|
||||
|
||||
expect(renderFlowchartDiagram(content)).toContain("result path")
|
||||
expect(terminalPointsTowardBounds(entry, layout.bounds.get("A")!)).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
test("routes nested RL local edges around outer siblings", () => {
|
||||
const layout = layoutFlowchartDiagram(
|
||||
`flowchart RL
|
||||
I([Input λ]) --> A
|
||||
subgraph Outer [Outer group 長い]
|
||||
direction LR
|
||||
subgraph Inner [Inner<br/>工程]
|
||||
direction BT
|
||||
A[Parse request] -->|inner edge| B{Valid?}
|
||||
B --> C[(Cache Ω)]
|
||||
C --> B
|
||||
end
|
||||
B --> D[[Dispatch work]]
|
||||
end
|
||||
D -.->|result path| O([Output μ])`,
|
||||
{ compact: true },
|
||||
)
|
||||
|
||||
for (const route of layout.routes.filter((route) => ["A", "B", "C"].includes(route.edge.from))) {
|
||||
if (route.edge.to === "D") continue
|
||||
expect(routeIntersectsBounds(route, layout.bounds.get("D")!)).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
test("compacts stacked subgraph-local direction rows", () => {
|
||||
const layout = layoutFlowchartDiagram(`
|
||||
flowchart TD
|
||||
@@ -1311,6 +1574,6 @@ flowchart LR
|
||||
const node = parseColor("#ff0000")
|
||||
const styled = renderGridStyledText(grid, resolveFlowchartStyleColors({ node }))
|
||||
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && colorsEqual(chunk.fg, node))).toBe(true)
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && chunk.fg?.equals(node))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -67,6 +67,22 @@ describe("flowchart edge labels", () => {
|
||||
).toEqual({ x: 151, y: 7 })
|
||||
})
|
||||
|
||||
test("keeps side-route labels on the vertical bus when horizontal arms grow", () => {
|
||||
expect(
|
||||
flowchartEdgeLabelLayout(
|
||||
[
|
||||
{ x: 5, y: 2 },
|
||||
{ x: 30, y: 2 },
|
||||
{ x: 30, y: 10 },
|
||||
{ x: 5, y: 10 },
|
||||
],
|
||||
"parallel label",
|
||||
measure,
|
||||
"y",
|
||||
).point,
|
||||
).toEqual({ x: 31, y: 6 })
|
||||
})
|
||||
|
||||
test("measures br-delimited edge label lines as a block", () => {
|
||||
const layout = flowchartEdgeLabelLayout(
|
||||
[
|
||||
|
||||
@@ -67,14 +67,23 @@ function segmentLabelPoint(segment: DiagramSegment, labelWidth: number, labelHei
|
||||
return clampPoint(shiftPoint(center, "up", Math.floor((labelHeight - 1) / 2)))
|
||||
}
|
||||
|
||||
function bestLabelSegment(points: readonly FlowchartPoint[], labelWidth: number): DiagramSegment | undefined {
|
||||
function bestLabelSegment(
|
||||
points: readonly FlowchartPoint[],
|
||||
labelWidth: number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): DiagramSegment | undefined {
|
||||
const segments = points.slice(1).flatMap((to, index) => {
|
||||
const segment = segmentBetween(points[index]!, to)
|
||||
return segment ? [segment] : []
|
||||
})
|
||||
const preferred = preferredAxis ? segments.find((segment) => segment.axis === preferredAxis) : undefined
|
||||
if (preferred) return preferred
|
||||
|
||||
let roomyHorizontal: DiagramSegment | undefined
|
||||
let verticalBus: DiagramSegment | undefined
|
||||
let longest: DiagramSegment | undefined
|
||||
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
const segment = segmentBetween(points[index - 1]!, points[index]!)
|
||||
if (!segment) continue
|
||||
for (const segment of segments) {
|
||||
if (!roomyHorizontal && segment.axis === "x" && inlineLabelSlot(segment, labelWidth).fits) roomyHorizontal = segment
|
||||
if (!verticalBus && segment.axis === "y") verticalBus = segment
|
||||
if (!longest || segment.length > longest.length) longest = segment
|
||||
@@ -87,8 +96,9 @@ function flowchartLabelPoint(
|
||||
points: readonly FlowchartPoint[],
|
||||
labelWidth: number,
|
||||
labelHeight: number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): FlowchartPoint {
|
||||
const segment = bestLabelSegment(points, labelWidth)
|
||||
const segment = bestLabelSegment(points, labelWidth, preferredAxis)
|
||||
return segment ? segmentLabelPoint(segment, labelWidth, labelHeight) : (points[0] ?? point(0, 0))
|
||||
}
|
||||
|
||||
@@ -96,9 +106,10 @@ export function flowchartEdgeLabelLayout(
|
||||
points: readonly FlowchartPoint[],
|
||||
label: string,
|
||||
measure: (text: string) => number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): FlowchartEdgeLabelLayout {
|
||||
const lines = splitDiagramLines(label).map(flowchartLabelText)
|
||||
const width = flowchartLabelWidth(label, measure)
|
||||
const height = lines.length
|
||||
return { lines, point: flowchartLabelPoint(points, width, height), width, height }
|
||||
return { lines, point: flowchartLabelPoint(points, width, height, preferredAxis), width, height }
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import type {
|
||||
|
||||
export const DEFAULT_MIN_NODE_GAP = 5
|
||||
export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
|
||||
const DEFAULT_MAX_UNLABELED_RANK_WIDTH = 120
|
||||
export const DEFAULT_MIN_RANK_GAP = 7
|
||||
export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
|
||||
export const COMPACT_MIN_RANK_GAP = 4
|
||||
@@ -316,7 +317,7 @@ function pathBounds(points: readonly { x: number; y: number }[]): FlowchartBound
|
||||
|
||||
function labelBounds(route: FlowchartEdgeRoute): FlowchartBounds | undefined {
|
||||
if (!route.edge.label) return undefined
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis)
|
||||
const { point, width, height } = label
|
||||
return {
|
||||
left: point.x,
|
||||
@@ -358,9 +359,6 @@ function layoutRankedNodes(
|
||||
if (edge.label)
|
||||
widestPaddedEdgeLabel = Math.max(widestPaddedEdgeLabel, flowchartLabelWidth(edge.label, visualLength))
|
||||
}
|
||||
const rankNodeGap = horizontal
|
||||
? minNodeGap
|
||||
: Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP, flowchartVerticalBranchLabelGap(widestPaddedEdgeLabel))
|
||||
const ranks = rankNodes(diagram)
|
||||
const maxRank = Math.max(0, ...ranks.values())
|
||||
const ranksByIndex = new Map<number, FlowchartNode[]>()
|
||||
@@ -375,6 +373,23 @@ function layoutRankedNodes(
|
||||
ranksByIndex.set(normalizedRank, nodes)
|
||||
}
|
||||
|
||||
const spaciousNodeGap = Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP)
|
||||
const widestUnlabeledRank = Math.max(
|
||||
0,
|
||||
...[...ranksByIndex.values()].map(
|
||||
(nodes) =>
|
||||
nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
|
||||
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 rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
|
||||
const horizontalGaps = horizontal ? horizontalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap) : []
|
||||
const verticalGaps = horizontal ? [] : verticalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap)
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
} from "./types.js"
|
||||
import { MermaidSyntaxError } from "../diagnostics.js"
|
||||
import {
|
||||
decodeMermaidText,
|
||||
firstMeaningfulMermaidLine,
|
||||
meaningfulNumberedMermaidLines,
|
||||
stripMermaidQuotes as stripQuotes,
|
||||
@@ -28,8 +29,9 @@ const DECISION_NODE_RE = new RegExp(`^(${ID_RE})\\{(.+)\\}$`)
|
||||
const BOX_NODE_RE = new RegExp(`^(${ID_RE})\\[(.+)\\]$`)
|
||||
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*)?/g
|
||||
|
||||
function normalizeDirection(value?: string): FlowchartDirection {
|
||||
const upper = value?.toUpperCase()
|
||||
@@ -79,6 +81,20 @@ function parseNodeToken(token: string): FlowchartNode {
|
||||
return { id: trimmed, label: trimmed, shape: "box" }
|
||||
}
|
||||
|
||||
function isSupportedNodeToken(token: string): boolean {
|
||||
const trimmed = stripNodeToken(token)
|
||||
if (CIRCLE_NODE_RE.test(trimmed)) return false
|
||||
return (
|
||||
ID_ONLY_RE.test(trimmed) ||
|
||||
DATABASE_NODE_RE.test(trimmed) ||
|
||||
SUBROUTINE_NODE_RE.test(trimmed) ||
|
||||
ROUNDED_BRACKET_NODE_RE.test(trimmed) ||
|
||||
ROUNDED_NODE_RE.test(trimmed) ||
|
||||
DECISION_NODE_RE.test(trimmed) ||
|
||||
BOX_NODE_RE.test(trimmed)
|
||||
)
|
||||
}
|
||||
|
||||
function hasExplicitNodeShape(token: string): boolean {
|
||||
return EXPLICIT_NODE_SHAPE_RE.test(token.trim())
|
||||
}
|
||||
@@ -122,9 +138,11 @@ function createEdge(
|
||||
label: string,
|
||||
style: FlowchartEdgeStyle | undefined,
|
||||
arrowhead: boolean,
|
||||
sourceArrowhead: boolean,
|
||||
): FlowchartEdge {
|
||||
const edge: FlowchartEdge = style ? { from, to, label, style } : { from, to, label }
|
||||
if (!arrowhead) edge.arrowhead = false
|
||||
if (sourceArrowhead) edge.sourceArrowhead = true
|
||||
return edge
|
||||
}
|
||||
|
||||
@@ -134,25 +152,91 @@ interface ParsedEdgeOperator {
|
||||
label: string
|
||||
style: FlowchartEdgeStyle | undefined
|
||||
arrowhead: boolean
|
||||
sourceArrowhead: boolean
|
||||
orderOnly: boolean
|
||||
}
|
||||
|
||||
function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
|
||||
return [...line.matchAll(EDGE_OPERATOR_RE)].map((match) => {
|
||||
return [...maskNodeLabelOperators(line).matchAll(EDGE_OPERATOR_RE)].map((match) => {
|
||||
const inlineDashedArrow = match[1]
|
||||
const startArrow = inlineDashedArrow ?? match[3] ?? match[6]!
|
||||
const endArrow = inlineDashedArrow ?? match[5] ?? match[6]!
|
||||
return {
|
||||
index: match.index,
|
||||
end: match.index + match[0].length,
|
||||
label: (match[2] ?? match[4] ?? match[7] ?? "").trim(),
|
||||
label: decodeMermaidText((match[2] ?? match[4] ?? match[7] ?? "").trim()),
|
||||
style: edgeStyleFromArrow(startArrow, endArrow),
|
||||
arrowhead: endArrow !== "---",
|
||||
arrowhead: endArrow === "~~~" || endArrow.endsWith(">"),
|
||||
sourceArrowhead: startArrow.startsWith("<"),
|
||||
orderOnly: endArrow === "~~~",
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function maskNodeLabelOperators(line: string): string {
|
||||
const characters = line.split("")
|
||||
const stack: string[] = []
|
||||
let quote: '"' | "'" | undefined
|
||||
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
|
||||
|
||||
for (let index = 0; index < characters.length; index++) {
|
||||
const character = characters[index]!
|
||||
if (quote) {
|
||||
if (character === quote && characters[index - 1] !== "\\") quote = undefined
|
||||
else if (/[<>=.-]/.test(character)) characters[index] = " "
|
||||
continue
|
||||
}
|
||||
if (character === '"' || character === "'") {
|
||||
quote = character
|
||||
continue
|
||||
}
|
||||
if (character in closes) {
|
||||
stack.push(character)
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
|
||||
stack.pop()
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && /[<>=.-]/.test(character)) characters[index] = " "
|
||||
}
|
||||
return characters.join("")
|
||||
}
|
||||
|
||||
function hasInternalStatementSeparator(line: string): boolean {
|
||||
const stack: string[] = []
|
||||
let quote: '"' | "'" | undefined
|
||||
let edgeLabel = false
|
||||
const closes: Record<string, string> = { "[": "]", "(": ")", "{": "}" }
|
||||
const finalIndex = line.trimEnd().length - 1
|
||||
|
||||
for (let index = 0; index < line.length; index++) {
|
||||
const character = line[index]!
|
||||
if (quote) {
|
||||
if (character === quote && line[index - 1] !== "\\") quote = undefined
|
||||
continue
|
||||
}
|
||||
if (character === '"' || character === "'") {
|
||||
quote = character
|
||||
continue
|
||||
}
|
||||
if (character in closes) {
|
||||
stack.push(character)
|
||||
continue
|
||||
}
|
||||
if (stack.length > 0 && character === closes[stack.at(-1)!]) {
|
||||
stack.pop()
|
||||
continue
|
||||
}
|
||||
if (stack.length === 0 && character === "|") {
|
||||
edgeLabel = !edgeLabel
|
||||
continue
|
||||
}
|
||||
if (character === ";" && index < finalIndex && stack.length === 0 && !edgeLabel) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function isMermaidFlowchartDiagram(content: string): boolean {
|
||||
return FLOWCHART_HEADER_RE.test(firstMeaningfulMermaidLine(content) ?? "")
|
||||
}
|
||||
@@ -166,6 +250,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
|
||||
for (const source of meaningfulNumberedMermaidLines(content)) {
|
||||
const line = source.text
|
||||
if (hasInternalStatementSeparator(line)) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
|
||||
const header = line.match(FLOWCHART_HEADER_RE)
|
||||
if (header) {
|
||||
direction = normalizeDirection(header[2])
|
||||
@@ -222,6 +307,15 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
]
|
||||
|
||||
if (nodeTokens.every((token) => stripNodeToken(token).length > 0)) {
|
||||
const unsupportedEndpoint = nodeTokens.find((token, index) => {
|
||||
const stripped = stripNodeToken(token)
|
||||
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
|
||||
return (
|
||||
!(orderOnlyEndpoint && subgraphs.some((subgraph) => subgraph.id === stripped)) &&
|
||||
!isSupportedNodeToken(stripped)
|
||||
)
|
||||
})
|
||||
if (unsupportedEndpoint) throw new MermaidSyntaxError("flowchart", source.lineNumber, line)
|
||||
const chainNodeIds = nodeTokens.map((token, index) => {
|
||||
const stripped = stripNodeToken(token)
|
||||
const orderOnlyEndpoint = edgeOperators[index - 1]?.orderOnly || edgeOperators[index]?.orderOnly
|
||||
@@ -239,6 +333,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
operator.label,
|
||||
operator.style,
|
||||
operator.arrowhead,
|
||||
operator.sourceArrowhead,
|
||||
)
|
||||
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
|
||||
}
|
||||
@@ -246,7 +341,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
}
|
||||
}
|
||||
|
||||
if (hasExplicitNodeShape(line) || ID_ONLY_RE.test(stripNodeToken(line))) {
|
||||
if (isSupportedNodeToken(line)) {
|
||||
const node = ensureNode(nodes, line)
|
||||
addNodeToSubgraph(currentSubgraph, node.id)
|
||||
continue
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import type { FlowchartDiagram, FlowchartNodeBounds } from "./types.js"
|
||||
import { routeFlowchartEdges } from "./routing.js"
|
||||
|
||||
@@ -21,6 +23,31 @@ function diagram(direction: FlowchartDiagram["direction"], edges: FlowchartDiagr
|
||||
return { direction, nodes: [], edges, subgraphs: [] }
|
||||
}
|
||||
|
||||
function routeIntersectsBounds(
|
||||
points: readonly { x: number; y: number }[],
|
||||
nodeBounds: { left: number; top: number; width: number; height: number },
|
||||
): boolean {
|
||||
const right = nodeBounds.left + nodeBounds.width - 1
|
||||
const bottom = nodeBounds.top + nodeBounds.height - 1
|
||||
return points.slice(1).some((to, index) => {
|
||||
const from = points[index]!
|
||||
if (from.x === to.x) {
|
||||
return (
|
||||
from.x >= nodeBounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= nodeBounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
)
|
||||
}
|
||||
return (
|
||||
from.y >= nodeBounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= nodeBounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
describe("flowchart routing", () => {
|
||||
test("routes a simple horizontal edge from source port to target port", () => {
|
||||
const edge = { from: "A", to: "B", label: "" }
|
||||
@@ -269,4 +296,79 @@ describe("flowchart routing", () => {
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
test("does not route a fallback through its own source node", () => {
|
||||
const labeled = { from: "A", to: "B", label: "route" }
|
||||
const crossing = { from: "C", to: "D", label: "" }
|
||||
const nodeBounds = new Map([
|
||||
["A", bounds("A", 0, 0)],
|
||||
["B", bounds("B", 100, 0)],
|
||||
["C", bounds("C", 48, -12)],
|
||||
["D", bounds("D", 48, 12)],
|
||||
])
|
||||
const routes = routeFlowchartEdges(diagram("LR", [labeled, crossing]), nodeBounds, undefined, new Map())
|
||||
const route = routes.find((candidate) => candidate.edge === labeled)!
|
||||
|
||||
expect(routeIntersectsBounds(route.points, nodeBounds.get("A")!)).toBe(false)
|
||||
expect(routeIntersectsBounds(route.points, nodeBounds.get("B")!)).toBe(false)
|
||||
})
|
||||
|
||||
test("ignores zero-width blank label interiors as route obstacles", () => {
|
||||
const blankLabel = { from: "A", to: "B", label: "<br/>" }
|
||||
const crossing = { from: "C", to: "D", label: "" }
|
||||
const routes = routeFlowchartEdges(
|
||||
diagram("TD", [blankLabel, crossing]),
|
||||
new Map([
|
||||
["A", bounds("A", 0, 0)],
|
||||
["B", bounds("B", 0, 100)],
|
||||
["C", bounds("C", -20, 50)],
|
||||
["D", bounds("D", 20, 50)],
|
||||
]),
|
||||
(edge) => (edge === blankLabel ? "TD" : "LR"),
|
||||
new Map(),
|
||||
)
|
||||
|
||||
expect(routes.find((route) => route.edge === blankLabel)!.points).toEqual([
|
||||
{ x: 2, y: 3 },
|
||||
{ x: 2, y: 99 },
|
||||
])
|
||||
})
|
||||
|
||||
test("checks earlier labels against finalized later fallback routes", () => {
|
||||
const edges = [
|
||||
{ from: "C", to: "B", label: "alpha" },
|
||||
{ from: "A", to: "F", label: "beta long" },
|
||||
{ from: "C", to: "D", label: "gamma" },
|
||||
{ from: "A", to: "B", label: "" },
|
||||
]
|
||||
const directions = ["TD", "RL", "LR", "BT"] as const
|
||||
const routes = routeFlowchartEdges(
|
||||
diagram("LR", edges),
|
||||
new Map([
|
||||
["A", bounds("A", -24, 6)],
|
||||
["B", bounds("B", 48, 24)],
|
||||
["C", bounds("C", -24, 24)],
|
||||
["D", bounds("D", -24, -18)],
|
||||
["F", bounds("F", -16, -6)],
|
||||
]),
|
||||
(edge) => directions[edges.indexOf(edge)]!,
|
||||
new Map(),
|
||||
)
|
||||
const labeled = routes.find((route) => route.edge === edges[0])!
|
||||
const laterFallback = routes.find((route) => route.edge === edges[3])!
|
||||
const label = flowchartEdgeLabelLayout(labeled.points, labeled.edge.label, diagramTextWidth)
|
||||
|
||||
expect(labeled.points).toEqual([
|
||||
{ x: -19, y: 25 },
|
||||
{ x: 47, y: 25 },
|
||||
])
|
||||
expect(
|
||||
routeIntersectsBounds(laterFallback.points, {
|
||||
left: label.point.x + 1,
|
||||
top: label.point.y,
|
||||
width: label.width - 2,
|
||||
height: label.height,
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
pathViaLane,
|
||||
sideForDirection,
|
||||
snapCoordinate,
|
||||
shiftPoint,
|
||||
withCoordinate,
|
||||
type DiagramAxis,
|
||||
type DiagramDirection,
|
||||
@@ -22,7 +23,7 @@ import {
|
||||
type DiagramSide,
|
||||
} from "../core/geometry.js"
|
||||
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import { flowchartEdgeLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
|
||||
import type {
|
||||
FlowchartDiagram,
|
||||
FlowchartDirection,
|
||||
@@ -130,7 +131,9 @@ function horizontalEdgePath(
|
||||
|
||||
const travel = horizontalTravel(from, to, direction)
|
||||
const startSide = sideForDirection(travel)
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)))
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)), {
|
||||
preferredAxis: "x",
|
||||
})
|
||||
}
|
||||
|
||||
function selfEdgePath(bounds: FlowchartNodeBounds): FlowchartPoint[] {
|
||||
@@ -165,7 +168,7 @@ function labelHeight(edge: FlowchartEdge): number {
|
||||
function rightRenderExtent(route: FlowchartEdgeRoute): number {
|
||||
let right = Math.max(...route.points.map((point) => point.x))
|
||||
if (route.edge.label) {
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth, route.labelAxis)
|
||||
right = Math.max(right, label.point.x + label.width - 1)
|
||||
}
|
||||
return right
|
||||
@@ -179,6 +182,14 @@ function edgePath(
|
||||
): FlowchartPoint[] {
|
||||
if (from.id === to.id) return selfEdgePath(from)
|
||||
if (!isVerticalDirection(direction)) return horizontalEdgePath(from, to, direction)
|
||||
const overlapsVertically = from.top < to.top + to.height && to.top < from.top + from.height
|
||||
if (overlapsVertically) {
|
||||
const travel: HorizontalTravel = centerCoordinate(to, "x") >= centerCoordinate(from, "x") ? "right" : "left"
|
||||
return orthogonalPath(
|
||||
boundsSidePoint(from, sideForDirection(travel)),
|
||||
boundsSidePoint(to, oppositeSide(sideForDirection(travel))),
|
||||
)
|
||||
}
|
||||
return isVerticalBackEdge(from, to, direction)
|
||||
? verticalBackEdgePath(from, to, leftBoundary)
|
||||
: verticalForwardEdgePath(from, to)
|
||||
@@ -211,7 +222,7 @@ function targetFanInLane(
|
||||
afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
|
||||
travel,
|
||||
)
|
||||
return keepBefore(unclamped, targetCoordinate, travel)
|
||||
return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
|
||||
}
|
||||
|
||||
function portForTravel(bounds: FlowchartNodeBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
|
||||
@@ -468,7 +479,11 @@ function routeParallelEdges(
|
||||
Math.max(boundsSidePoint(from, "bottom").y, boundsSidePoint(to, "bottom").y) + BUS_CLEARANCE,
|
||||
Math.max(...previousRoute.points.map((point) => point.y)) + Math.max(2, labelHeight(edge) + 1),
|
||||
)
|
||||
const route = { edge, points: parallelEdgePath(from, to, direction, laneCoordinate) }
|
||||
const route: FlowchartEdgeRoute = {
|
||||
edge,
|
||||
points: parallelEdgePath(from, to, direction, laneCoordinate),
|
||||
labelAxis: isVerticalDirection(direction) ? "y" : "x",
|
||||
}
|
||||
routes.push(route)
|
||||
handled.add(edge)
|
||||
previousRoute = route
|
||||
@@ -571,59 +586,238 @@ function routeHorizontalSubgraphEntries(
|
||||
}
|
||||
}
|
||||
|
||||
function pathIntersectsBounds(points: readonly FlowchartPoint[], bounds: FlowchartNodeBounds): boolean {
|
||||
function pathIntersectsBounds(
|
||||
points: readonly FlowchartPoint[],
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
allowedContact: "source" | "target" | "both" | undefined = undefined,
|
||||
): boolean {
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
const from = points[index - 1]!
|
||||
const to = points[index]!
|
||||
if (from.x === to.x) {
|
||||
if (
|
||||
from.x >= bounds.left &&
|
||||
from.x <= right &&
|
||||
Math.max(from.y, to.y) >= bounds.top &&
|
||||
Math.min(from.y, to.y) <= bottom
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (from.x < bounds.left || from.x > right) continue
|
||||
const overlapTop = Math.max(Math.min(from.y, to.y), bounds.top)
|
||||
const overlapBottom = Math.min(Math.max(from.y, to.y), bottom)
|
||||
if (overlapTop > overlapBottom) continue
|
||||
const sourceContact =
|
||||
(allowedContact === "source" || allowedContact === "both") &&
|
||||
index === 1 &&
|
||||
overlapTop === overlapBottom &&
|
||||
from.x === points[0]!.x &&
|
||||
overlapTop === points[0]!.y
|
||||
const targetContact =
|
||||
(allowedContact === "target" || allowedContact === "both") &&
|
||||
index === points.length - 1 &&
|
||||
overlapTop === overlapBottom &&
|
||||
to.x === points.at(-1)!.x &&
|
||||
overlapTop === points.at(-1)!.y
|
||||
if (!sourceContact && !targetContact) return true
|
||||
continue
|
||||
}
|
||||
if (
|
||||
from.y >= bounds.top &&
|
||||
from.y <= bottom &&
|
||||
Math.max(from.x, to.x) >= bounds.left &&
|
||||
Math.min(from.x, to.x) <= right
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (from.y < bounds.top || from.y > bottom) continue
|
||||
const overlapLeft = Math.max(Math.min(from.x, to.x), bounds.left)
|
||||
const overlapRight = Math.min(Math.max(from.x, to.x), right)
|
||||
if (overlapLeft > overlapRight) continue
|
||||
const sourceContact =
|
||||
(allowedContact === "source" || allowedContact === "both") &&
|
||||
index === 1 &&
|
||||
overlapLeft === overlapRight &&
|
||||
overlapLeft === points[0]!.x &&
|
||||
from.y === points[0]!.y
|
||||
const targetContact =
|
||||
(allowedContact === "target" || allowedContact === "both") &&
|
||||
index === points.length - 1 &&
|
||||
overlapLeft === overlapRight &&
|
||||
overlapLeft === points.at(-1)!.x &&
|
||||
to.y === points.at(-1)!.y
|
||||
if (!sourceContact && !targetContact) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function labelIntersectsBounds(label: FlowchartEdgeLabelLayout | undefined, bounds: FlowchartNodeBounds): boolean {
|
||||
if (!label) return false
|
||||
return (
|
||||
label.point.x <= bounds.left + bounds.width - 1 &&
|
||||
label.point.x + label.width - 1 >= bounds.left &&
|
||||
label.point.y <= bounds.top + bounds.height - 1 &&
|
||||
label.point.y + label.height - 1 >= bounds.top
|
||||
)
|
||||
}
|
||||
|
||||
function labelIntersectsSubgraphFrame(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
bounds: FlowchartSubgraphBounds,
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
const labelRight = label.point.x + label.width - 1
|
||||
const labelBottom = label.point.y + label.height - 1
|
||||
const right = bounds.left + bounds.width - 1
|
||||
const bottom = bounds.top + bounds.height - 1
|
||||
return (
|
||||
(label.point.x <= right &&
|
||||
labelRight >= bounds.left &&
|
||||
((label.point.y <= bounds.top && labelBottom >= bounds.top) ||
|
||||
(label.point.y <= bottom && labelBottom >= bottom))) ||
|
||||
(label.point.y <= bottom &&
|
||||
labelBottom >= bounds.top &&
|
||||
((label.point.x <= bounds.left && labelRight >= bounds.left) || (label.point.x <= right && labelRight >= right)))
|
||||
)
|
||||
}
|
||||
|
||||
function routeLength(route: FlowchartEdgeRoute): number {
|
||||
let length = 0
|
||||
for (let index = 1; index < route.points.length; index++) {
|
||||
const from = route.points[index - 1]!
|
||||
const to = route.points[index]!
|
||||
length += Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
function labelIntersectsLabels(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
otherLabels: readonly FlowchartEdgeLabelLayout[],
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
return otherLabels.some((otherLabel) => {
|
||||
return label.lines.some((line, lineIndex) => {
|
||||
const textLeft = label.point.x + 1
|
||||
const textRight = label.point.x + diagramTextWidth(line) - 2
|
||||
const y = label.point.y + lineIndex
|
||||
return otherLabel.lines.some((otherLine, otherLineIndex) => {
|
||||
const otherLeft = otherLabel.point.x
|
||||
const otherRight = otherLeft + diagramTextWidth(otherLine) - 1
|
||||
return y === otherLabel.point.y + otherLineIndex && textLeft <= otherRight && textRight >= otherLeft
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function labelIntersectsLaterRoutePaths(
|
||||
label: FlowchartEdgeLabelLayout | undefined,
|
||||
laterRoutes: readonly FlowchartEdgeRoute[],
|
||||
): boolean {
|
||||
if (!label) return false
|
||||
return label.lines.some((line, lineIndex) => {
|
||||
const width = diagramTextWidth(line) - 2
|
||||
if (width <= 0) return false
|
||||
return laterRoutes.some((other) =>
|
||||
pathIntersectsBounds(other.points, {
|
||||
left: label.point.x + 1,
|
||||
top: label.point.y + lineIndex,
|
||||
width,
|
||||
height: 1,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function avoidNodeObstacles(
|
||||
route: FlowchartEdgeRoute,
|
||||
routes: readonly FlowchartEdgeRoute[],
|
||||
bounds: Map<string, FlowchartNodeBounds>,
|
||||
direction: FlowchartDirection,
|
||||
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
|
||||
routeIndex: number,
|
||||
): FlowchartEdgeRoute {
|
||||
const obstacle = [...bounds.values()].some(
|
||||
(bound) => bound.id !== route.edge.from && bound.id !== route.edge.to && pathIntersectsBounds(route.points, bound),
|
||||
const allNodeBounds = [...bounds.values()]
|
||||
const allSubgraphBounds = [...(subgraphBounds?.values() ?? [])]
|
||||
const laterRoutes = routes.slice(routeIndex + 1)
|
||||
const laterLabels = laterRoutes.flatMap((laterRoute) =>
|
||||
laterRoute.edge.label
|
||||
? [flowchartEdgeLabelLayout(laterRoute.points, laterRoute.edge.label, diagramTextWidth, laterRoute.labelAxis)]
|
||||
: [],
|
||||
)
|
||||
if (!obstacle) return route
|
||||
const intersectsObstacle = (candidate: FlowchartEdgeRoute): boolean => {
|
||||
const label = candidate.edge.label
|
||||
? flowchartEdgeLabelLayout(candidate.points, candidate.edge.label, diagramTextWidth, candidate.labelAxis)
|
||||
: undefined
|
||||
return (
|
||||
allNodeBounds.some((bound) => {
|
||||
const isSource = bound.id === route.edge.from
|
||||
const isTarget = bound.id === route.edge.to
|
||||
const allowedContact = isSource && isTarget ? "both" : isSource ? "source" : isTarget ? "target" : undefined
|
||||
return pathIntersectsBounds(candidate.points, bound, allowedContact)
|
||||
}) ||
|
||||
allNodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
|
||||
allSubgraphBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
|
||||
(subgraphBounds !== undefined &&
|
||||
(labelIntersectsLabels(label, laterLabels) || labelIntersectsLaterRoutePaths(label, laterRoutes)))
|
||||
)
|
||||
}
|
||||
if (!intersectsObstacle(route)) return route
|
||||
|
||||
const from = bounds.get(route.edge.from)
|
||||
const to = bounds.get(route.edge.to)
|
||||
if (!from || !to) return route
|
||||
if (isVerticalDirection(direction)) {
|
||||
const start = boundsSidePoint(from, "right")
|
||||
const end = boundsSidePoint(to, "right")
|
||||
const busX = Math.max(...[...bounds.values()].map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
|
||||
return { edge: route.edge, points: pathViaLane(start, lane("x", busX), end) }
|
||||
const routingBounds = [...allNodeBounds, ...allSubgraphBounds]
|
||||
const rightBusX = Math.max(...routingBounds.map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
|
||||
const leftBusX = Math.min(...routingBounds.map((bound) => bound.left)) - BUS_CLEARANCE
|
||||
const topBusY = Math.min(...routingBounds.map((bound) => bound.top)) - BUS_CLEARANCE
|
||||
const bottomBusY = Math.max(...routingBounds.map((bound) => bound.top + bound.height - 1)) + BUS_CLEARANCE
|
||||
const start = route.points[0]!
|
||||
const end = route.points.at(-1)!
|
||||
const targetSide = sideForOutsidePoint(to, end)
|
||||
const approach = shiftPoint(
|
||||
end,
|
||||
targetSide === "left" ? "left" : targetSide === "right" ? "right" : targetSide === "top" ? "up" : "down",
|
||||
)
|
||||
const preservedTargetCandidates: FlowchartEdgeRoute[] = [
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathThrough([start, { x: leftBusX, y: start.y }, { x: leftBusX, y: approach.y }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathThrough([start, { x: rightBusX, y: start.y }, { x: rightBusX, y: approach.y }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathThrough([start, { x: start.x, y: topBusY }, { x: approach.x, y: topBusY }, approach, end]),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathThrough([start, { x: start.x, y: bottomBusY }, { x: approach.x, y: bottomBusY }, approach, end]),
|
||||
},
|
||||
]
|
||||
const candidates: FlowchartEdgeRoute[] = [
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathViaLane(boundsSidePoint(from, "right"), lane("x", rightBusX), boundsSidePoint(to, "right")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "y",
|
||||
points: pathViaLane(boundsSidePoint(from, "left"), lane("x", leftBusX), boundsSidePoint(to, "left")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathViaLane(boundsSidePoint(from, "top"), lane("y", topBusY), boundsSidePoint(to, "top")),
|
||||
},
|
||||
{
|
||||
...route,
|
||||
labelAxis: route.labelAxis === undefined ? undefined : "x",
|
||||
points: pathViaLane(boundsSidePoint(from, "bottom"), lane("y", bottomBusY), boundsSidePoint(to, "bottom")),
|
||||
},
|
||||
]
|
||||
const shortestValid = (candidateRoutes: FlowchartEdgeRoute[]): FlowchartEdgeRoute | undefined =>
|
||||
candidateRoutes
|
||||
.filter((candidate) => !intersectsObstacle(candidate))
|
||||
.sort((left, right) => routeLength(left) - routeLength(right))[0]
|
||||
if (subgraphBounds) {
|
||||
return shortestValid(preservedTargetCandidates) ?? shortestValid(candidates) ?? route
|
||||
}
|
||||
|
||||
const start = boundsSidePoint(from, "top")
|
||||
const end = boundsSidePoint(to, "top")
|
||||
const busY = Math.min(...[...bounds.values()].map((bound) => bound.top)) - BUS_CLEARANCE
|
||||
return { edge: route.edge, points: pathViaLane(start, lane("y", busY), end) }
|
||||
return (
|
||||
candidates.find((candidate) => !intersectsObstacle(candidate)) ?? shortestValid(preservedTargetCandidates) ?? route
|
||||
)
|
||||
}
|
||||
|
||||
export function routeFlowchartEdges(
|
||||
@@ -671,7 +865,10 @@ export function routeFlowchartEdges(
|
||||
if (!from || !to) continue
|
||||
routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
|
||||
}
|
||||
return routes.map((route) => avoidNodeObstacles(route, bounds, directionForEdge(route.edge)))
|
||||
for (let index = routes.length - 1; index >= 0; index--) {
|
||||
routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, subgraphBounds, index)
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
function sideForOutsidePoint(bounds: FlowchartNodeBounds, sourcePoint: FlowchartPoint): DiagramSide {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
import type { DiagramAxis, DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
|
||||
export type FlowchartDirection = "TB" | "TD" | "BT" | "LR" | "RL"
|
||||
export type FlowchartNodeShape = "box" | "rounded" | "database" | "decision" | "subroutine"
|
||||
@@ -16,6 +16,7 @@ export interface FlowchartEdge {
|
||||
label: string
|
||||
style?: FlowchartEdgeStyle
|
||||
arrowhead?: false
|
||||
sourceArrowhead?: true
|
||||
orderOnly?: boolean
|
||||
}
|
||||
|
||||
@@ -55,6 +56,7 @@ export type FlowchartPoint = DiagramPoint
|
||||
export interface FlowchartEdgeRoute {
|
||||
edge: FlowchartEdge
|
||||
points: FlowchartPoint[]
|
||||
labelAxis?: DiagramAxis
|
||||
}
|
||||
|
||||
export type FlowchartEdgeDirection = DiagramDirection
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { expectDiagram } from "../test/diagram.js"
|
||||
import { renderSequenceDiagram } from "./diagram.js"
|
||||
import { drawSequenceDiagramGrid } from "./drawing.js"
|
||||
@@ -28,6 +29,18 @@ sequenceDiagram
|
||||
])
|
||||
})
|
||||
|
||||
test("decodes HTML entities in participant, message, and note labels", () => {
|
||||
const diagram = parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
participant A as Worker & signer
|
||||
participant B
|
||||
A->>B: ack <3s
|
||||
Note over A,B: result ≥ 1`)
|
||||
|
||||
expect(diagram.participants[0]?.label).toBe("Worker & signer")
|
||||
expect(diagram.messages[0]?.label).toBe("ack <3s")
|
||||
expect(diagram.steps.find((step) => step.type === "note")?.note.label).toBe("result ≥ 1")
|
||||
})
|
||||
|
||||
test("renders a terminal sequence diagram", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -42,11 +55,11 @@ sequenceDiagram
|
||||
│ Browser │ │ Server │
|
||||
╰────┬────╯ ╰────┬───╯
|
||||
│ │
|
||||
│ GET / │
|
||||
├─────────────────▶
|
||||
│ GET / │
|
||||
├─────────────────►
|
||||
│ │
|
||||
│ 401 WWW-Auth │
|
||||
◀─────────────────┤
|
||||
│ 401 WWW-Auth │
|
||||
◄─────────────────┤
|
||||
│ │
|
||||
`)
|
||||
})
|
||||
@@ -70,15 +83,15 @@ sequenceDiagram
|
||||
expectDiagram(output).toEqualDiagram(`
|
||||
leaf tool LocationMutation FileMutation
|
||||
│ │ │
|
||||
├─ resolve(path) ───────────────────▶ │
|
||||
├───────── resolve(path) ───────────► │
|
||||
│ │ │
|
||||
◀─ Plan(target, authority anchor) ──┤ │
|
||||
◄─ Plan(target, authority anchor) ──┤ │
|
||||
│ │ │
|
||||
├─ commit(plan) ───────────────────────────────────────────────▶
|
||||
├─────────────────────── commit(plan) ─────────────────────────►
|
||||
│ │ │
|
||||
│ ◀─ revalidate(plan) ───────┤
|
||||
│ ◄─── revalidate(plan) ─────┤
|
||||
│ │ │
|
||||
│ ├─ same target or reject ──▶
|
||||
│ ├─ same target or reject ──►
|
||||
│ │ │
|
||||
`)
|
||||
})
|
||||
@@ -109,7 +122,7 @@ sequenceDiagram
|
||||
const lines = output.split("\n")
|
||||
|
||||
expect(lines.findIndex((line) => line.includes("deliberately"))).toBeLessThan(
|
||||
lines.findIndex((line) => line.includes("▶")),
|
||||
lines.findIndex((line) => line.includes("►")),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -245,18 +258,29 @@ sequenceDiagram
|
||||
])
|
||||
})
|
||||
|
||||
test("parses activation syntax without rendering activation bars", () => {
|
||||
test("renders activation syntax as visible intervals", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>+Server: request
|
||||
Server-->>-Browser: response
|
||||
`)
|
||||
|
||||
expect(output).not.toContain("┃")
|
||||
expect(output).toContain("┃")
|
||||
expect(output).toContain("request")
|
||||
expect(output).toContain("response")
|
||||
})
|
||||
|
||||
test("renders br-delimited participant aliases on separate lines", () => {
|
||||
const output = renderSequenceDiagram(`sequenceDiagram
|
||||
participant A as First line<br/>Second line
|
||||
participant B as Normal
|
||||
A->>B: hello`)
|
||||
|
||||
expect(output).not.toContain("<br")
|
||||
expect(output).toContain("│ First line │")
|
||||
expect(output).toContain("│ Second line │")
|
||||
})
|
||||
|
||||
test("parses Mermaid arrow head variants", () => {
|
||||
const diagram = parseMermaidSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -294,22 +318,22 @@ sequenceDiagram
|
||||
│ A │ │ B │
|
||||
╰─┬─╯ ╰─┬─╯
|
||||
│ │
|
||||
│ open solid │
|
||||
│ open solid │
|
||||
├─────────────────>│
|
||||
│ │
|
||||
│ open dashed │
|
||||
│ open dashed │
|
||||
│<─────────────────┤
|
||||
│ │
|
||||
│ failed solid │
|
||||
│ failed solid │
|
||||
├─────────────────✕│
|
||||
│ │
|
||||
│ failed dashed │
|
||||
│ failed dashed │
|
||||
│✕─────────────────┤
|
||||
│ │
|
||||
│ async solid │
|
||||
│ async solid │
|
||||
├─────────────────)│
|
||||
│ │
|
||||
│ async dashed │
|
||||
│ async dashed │
|
||||
│(─────────────────┤
|
||||
│ │"
|
||||
`)
|
||||
@@ -533,7 +557,7 @@ sequenceDiagram
|
||||
const fragmentMessageRow = fragment.split("\n").find((line) => line.includes("this non adjacent message"))!
|
||||
expect(groupMessageRow.trimEnd().endsWith("│")).toBe(true)
|
||||
expect(fragmentMessageRow).toContain("this non adjacent message is deliberately much wider than the frame")
|
||||
expect(fragmentMessageRow.match(/│/g)?.length).toBe(3)
|
||||
expect(fragmentMessageRow.match(/│/g)?.length).toBe(2)
|
||||
})
|
||||
|
||||
test("keeps long notes inside groups and nested fragment frames intact", () => {
|
||||
@@ -581,6 +605,42 @@ sequenceDiagram
|
||||
expect(externalHeaderLeft).toBeGreaterThan(groupBorderRight)
|
||||
})
|
||||
|
||||
test("keeps adjacent wide participant group frames separate", () => {
|
||||
const output = renderSequenceDiagram(
|
||||
`sequenceDiagram
|
||||
box First very wide group heading
|
||||
participant A
|
||||
end
|
||||
box Second very wide group heading
|
||||
participant B
|
||||
end
|
||||
A->>B: hi`,
|
||||
{ compact: true },
|
||||
)
|
||||
const topRow = output.split("\n")[0]!
|
||||
|
||||
expect(topRow).toContain("First very wide group heading")
|
||||
expect(topRow).toContain("Second very wide group heading")
|
||||
expect(topRow.indexOf("╮")).toBeLessThan(topRow.lastIndexOf("╭"))
|
||||
})
|
||||
|
||||
test("renders many adjacent wide participant groups without excessive canvas growth", () => {
|
||||
const groupCount = 16
|
||||
const output = renderSequenceDiagram(
|
||||
`sequenceDiagram
|
||||
${Array.from(
|
||||
{ length: groupCount },
|
||||
(_, index) => ` box Group ${index} has a deliberately wide heading
|
||||
participant P${index}
|
||||
end`,
|
||||
).join("\n")}
|
||||
P0->>P15: hi`,
|
||||
{ compact: true },
|
||||
)
|
||||
|
||||
expect(Math.max(...output.split("\n").map(diagramTextWidth))).toBeLessThan(groupCount * 60)
|
||||
})
|
||||
|
||||
test("renders full-height participant group boxes", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -600,11 +660,11 @@ sequenceDiagram
|
||||
│ Browser │ │ │ API │ │ Cache │ │ DB │ │
|
||||
╰────┬────╯ │ ╰──┬──╯ ╰───┬───╯ ╰──┬─╯ │
|
||||
│ │ │ │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────▶ │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────► │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────▶ │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────► │ │
|
||||
│ │ │ │ │ │
|
||||
╰────────────────────────────────────────────╯"
|
||||
`)
|
||||
@@ -619,12 +679,25 @@ sequenceDiagram
|
||||
end
|
||||
Browser->>API: GET /users/42
|
||||
`)
|
||||
const arrowLine = output.split("\n").find((line) => line.includes("▶"))!
|
||||
const arrowLine = output.split("\n").find((line) => line.includes("►"))!
|
||||
|
||||
expect(arrowLine).toContain("───────────────▶")
|
||||
expect(arrowLine).toContain("───────────────►")
|
||||
expect(arrowLine).not.toContain("┼")
|
||||
})
|
||||
|
||||
test("keeps filled arrowheads to one terminal column", () => {
|
||||
const output = renderSequenceDiagram(`sequenceDiagram
|
||||
box Backend
|
||||
participant A
|
||||
participant B
|
||||
A->>B: request
|
||||
end`)
|
||||
const lines = output.split("\n")
|
||||
const frameWidth = diagramTextWidth(lines.at(-1)!)
|
||||
|
||||
expect(Math.max(...lines.map(diagramTextWidth))).toBe(frameWidth)
|
||||
})
|
||||
|
||||
test("renders self messages as loopback arrows", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
@@ -639,12 +712,12 @@ sequenceDiagram
|
||||
│
|
||||
├────────────────────╮
|
||||
│ Check Permissions │
|
||||
◀────────────────────╯
|
||||
◄────────────────────╯
|
||||
│"
|
||||
`)
|
||||
})
|
||||
|
||||
test("places two spacer rows above note badges and one below", () => {
|
||||
test("frames notes in their reserved rows", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>Server: one
|
||||
@@ -656,9 +729,11 @@ sequenceDiagram
|
||||
const nextMessageRow = lines.findIndex((line) => line.includes("two"))
|
||||
|
||||
expect(noteRow).toBeGreaterThan(0)
|
||||
expect(lines[noteRow - 1]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow - 2]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow + 1]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow - 1]).toContain("╭")
|
||||
expect(lines[noteRow - 1]).toContain("╮")
|
||||
expect(lines[noteRow]).toContain("│ phase │")
|
||||
expect(lines[noteRow + 1]).toContain("╰")
|
||||
expect(lines[noteRow + 1]).toContain("╯")
|
||||
expect(nextMessageRow).toBe(noteRow + 2)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BorderChars, type BorderStyle } from "@opentui/core"
|
||||
import { DiagramCanvas } from "../core/canvas.js"
|
||||
import { diagramTextWidth } from "../core/text.js"
|
||||
import { DEFAULT_FRAGMENT_BORDER_STYLE } from "./options.js"
|
||||
import {
|
||||
createSequencePlacementPlan,
|
||||
@@ -19,6 +20,10 @@ import type {
|
||||
|
||||
const SEQUENCE_BORDER = BorderChars.rounded
|
||||
|
||||
function centeredStart(center: number, text: string): number {
|
||||
return center - Math.floor(diagramTextWidth(text) / 2)
|
||||
}
|
||||
|
||||
function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1): string {
|
||||
switch (head) {
|
||||
case "open":
|
||||
@@ -28,7 +33,7 @@ function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1):
|
||||
case "async":
|
||||
return direction === 1 ? ")" : "("
|
||||
default:
|
||||
return direction === 1 ? "▶" : "◀"
|
||||
return direction === 1 ? "►" : "◄"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +190,32 @@ function renderSelfMessage(
|
||||
setCell(grid, rightX, bottomRow, SEQUENCE_BORDER.bottomRight, style)
|
||||
}
|
||||
|
||||
function renderNote(grid: SequenceGrid, placement: Extract<SequenceStepPlacement, { type: "note" }>): void {
|
||||
const width = Math.max(...placement.textLines.map(diagramTextWidth))
|
||||
const left = placement.textX
|
||||
const right = left + width - 1
|
||||
const top = placement.textY - 1
|
||||
const bottom = placement.textY + placement.textLines.length
|
||||
|
||||
for (let x = left + 1; x < right; x++) {
|
||||
setCell(grid, x, top, SEQUENCE_BORDER.horizontal, "note")
|
||||
setCell(grid, x, bottom, SEQUENCE_BORDER.horizontal, "note")
|
||||
}
|
||||
for (let y = top + 1; y < bottom; y++) {
|
||||
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
|
||||
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
|
||||
}
|
||||
setCell(grid, left, top, SEQUENCE_BORDER.topLeft, "note")
|
||||
setCell(grid, right, top, SEQUENCE_BORDER.topRight, "note")
|
||||
setCell(grid, left, bottom, SEQUENCE_BORDER.bottomLeft, "note")
|
||||
setCell(grid, right, bottom, SEQUENCE_BORDER.bottomRight, "note")
|
||||
placement.textLines.forEach((line, index) => setText(grid, left, placement.textY + index, line, "noteBadge"))
|
||||
for (let y = placement.textY; y < bottom; y++) {
|
||||
setCell(grid, left, y, SEQUENCE_BORDER.vertical, "note")
|
||||
setCell(grid, right, y, SEQUENCE_BORDER.vertical, "note")
|
||||
}
|
||||
}
|
||||
|
||||
export function drawSequenceDiagramGrid(
|
||||
diagram: SequenceDiagram,
|
||||
options: SequenceDiagramRenderOptions = {},
|
||||
@@ -197,11 +228,13 @@ export function drawSequenceDiagramGrid(
|
||||
if (plan.groups.length > 0) renderParticipantGroups(grid, plan.groups, plan.height - 1)
|
||||
|
||||
for (const placement of plan.participants) {
|
||||
const { participant, centerX: center, headerLeftX, headerRightX, labelX } = placement
|
||||
const { centerX: center, headerLeftX, headerRightX, labelLines } = placement
|
||||
const { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY } = plan.rows
|
||||
|
||||
if (options.compact) {
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
} else {
|
||||
for (let x = headerLeftX; x <= headerRightX; x++) {
|
||||
setCell(grid, x, participantHeaderTopY, SEQUENCE_BORDER.horizontal, "participant")
|
||||
@@ -210,11 +243,15 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
setCell(grid, headerLeftX, participantHeaderTopY, SEQUENCE_BORDER.topLeft, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderTopY, SEQUENCE_BORDER.topRight, "participant")
|
||||
setCell(grid, headerLeftX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
for (let y = participantHeaderY; y < participantRuleY; y++) {
|
||||
setCell(grid, headerLeftX, y, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerRightX, y, SEQUENCE_BORDER.vertical, "participant")
|
||||
}
|
||||
setCell(grid, headerLeftX, participantRuleY, SEQUENCE_BORDER.bottomLeft, "participant")
|
||||
setCell(grid, headerRightX, participantRuleY, SEQUENCE_BORDER.bottomRight, "participant")
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
setCell(grid, center, participantRuleY, SEQUENCE_BORDER.topT, "participant")
|
||||
}
|
||||
|
||||
@@ -227,9 +264,7 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
for (const placement of plan.steps) {
|
||||
if (placement.type === "note") {
|
||||
for (let lineIndex = 0; lineIndex < placement.textLines.length; lineIndex++) {
|
||||
setText(grid, placement.textX, placement.textY + lineIndex, placement.textLines[lineIndex]!, "noteBadge")
|
||||
}
|
||||
renderNote(grid, placement)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -270,5 +305,13 @@ export function drawSequenceDiagramGrid(
|
||||
if (placement.inlineLabel) setText(grid, placement.labelX, placement.labelY, placement.inlineLabel, messageStyle)
|
||||
}
|
||||
|
||||
for (const activation of plan.activations) {
|
||||
for (let y = activation.startY; y <= activation.endY; y++) {
|
||||
if (grid.getCell(activation.centerX, y)?.char === SEQUENCE_BORDER.vertical) {
|
||||
setCell(grid, activation.centerX, y, "┃", "lifeline")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return grid
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ const ALT_RE = /^alt\s+(.+)$/i
|
||||
const ELSE_RE = /^else(?:\s+(.+))?$/i
|
||||
const LOOP_RE = /^loop\s+(.+)$/i
|
||||
const AUTONUMBER_RE = /^autonumber(?:\s+(\d+)(?:\s+(\d+))?)?$/i
|
||||
const UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE = /<<-{1,2}>>/
|
||||
const CSS_COLOR_NAMES = new Set([
|
||||
"black",
|
||||
"white",
|
||||
@@ -132,6 +133,9 @@ export function parseMermaidSequenceDiagram(content: string): SequenceDiagram {
|
||||
for (const source of meaningfulNumberedMermaidLines(content)) {
|
||||
const line = source.text
|
||||
if (line.toLowerCase() === "sequencediagram") continue
|
||||
if (UNSUPPORTED_BIDIRECTIONAL_MESSAGE_RE.test(line)) {
|
||||
throw new MermaidSyntaxError("sequence", source.lineNumber, line)
|
||||
}
|
||||
|
||||
const autonumberMatch = line.match(AUTONUMBER_RE)
|
||||
if (autonumberMatch) {
|
||||
|
||||
@@ -90,6 +90,25 @@ describe("createSequencePlacementPlan", () => {
|
||||
expect(external.headerLeftX).toBeGreaterThan(group.rightX)
|
||||
})
|
||||
|
||||
test("keeps many adjacent wide groups at a linear width", () => {
|
||||
const groupCount = 16
|
||||
const source = `sequenceDiagram
|
||||
${Array.from(
|
||||
{ length: groupCount },
|
||||
(_, index) => ` box Group ${index} has a deliberately wide heading
|
||||
participant P${index}
|
||||
end`,
|
||||
).join("\n")}
|
||||
P0->>P15: hi`
|
||||
const plan = createSequencePlacementPlan(parseMermaidSequenceDiagram(source), { compact: true })
|
||||
|
||||
expect(plan.groups).toHaveLength(groupCount)
|
||||
for (let index = 1; index < plan.groups.length; index++) {
|
||||
expect(plan.groups[index]!.leftX).toBeGreaterThan(plan.groups[index - 1]!.rightX)
|
||||
}
|
||||
expect(plan.width).toBeLessThan(groupCount * 60)
|
||||
})
|
||||
|
||||
test("expands group and fragment frames around contained long content", () => {
|
||||
const groupPlan = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
@@ -169,4 +188,34 @@ describe("createSequencePlacementPlan", () => {
|
||||
|
||||
expect(starts[0]!.bounds.rightX).toBeGreaterThan(starts[1]!.bounds.rightX)
|
||||
})
|
||||
|
||||
test("aligns explicit and shorthand activation intervals to message events", () => {
|
||||
const shorthand = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
A->>+B: request
|
||||
B-->>-A: response`),
|
||||
)
|
||||
const explicit = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
A->>B: request
|
||||
activate B
|
||||
B-->>A: response
|
||||
deactivate B`),
|
||||
)
|
||||
|
||||
expect(explicit.activations).toEqual(shorthand.activations)
|
||||
})
|
||||
|
||||
test("centers message label blocks over their arrow span", () => {
|
||||
const plan = createSequencePlacementPlan(
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
participant A
|
||||
participant B
|
||||
A->>B: short<br/>a much longer line`),
|
||||
)
|
||||
const message = plan.steps.find((step) => step.type === "message")!
|
||||
const labelWidth = Math.max(...message.labelLines.map(diagramTextWidth))
|
||||
|
||||
expect(message.labelX * 2 + labelWidth).toBe(message.leftX + message.rightX)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
SequenceStep,
|
||||
} from "./types.js"
|
||||
|
||||
const NOTE_HORIZONTAL_PADDING = 1
|
||||
const NOTE_HORIZONTAL_PADDING = 2
|
||||
const GROUP_HORIZONTAL_PADDING = 2
|
||||
const FRAGMENT_HORIZONTAL_OVERHANG = 3
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface SequenceParticipantPlacement {
|
||||
centerX: number
|
||||
headerLeftX: number
|
||||
headerRightX: number
|
||||
labelX: number
|
||||
labelLines: string[]
|
||||
}
|
||||
|
||||
export interface SequenceGroupPlacement {
|
||||
@@ -41,6 +41,14 @@ export interface SequenceWallPlacement {
|
||||
endY: number
|
||||
}
|
||||
|
||||
export interface SequenceActivationPlacement {
|
||||
participant: string
|
||||
centerX: number
|
||||
startY: number
|
||||
endY: number
|
||||
depth: number
|
||||
}
|
||||
|
||||
export type SequenceStepPlacement =
|
||||
| { type: "note"; note: SequenceNote; textLines: string[]; textX: number; textY: number }
|
||||
| {
|
||||
@@ -88,6 +96,7 @@ export interface SequencePlacementPlan {
|
||||
}
|
||||
participants: SequenceParticipantPlacement[]
|
||||
groups: SequenceGroupPlacement[]
|
||||
activations: SequenceActivationPlacement[]
|
||||
steps: SequenceStepPlacement[]
|
||||
}
|
||||
|
||||
@@ -132,7 +141,8 @@ function messageLabelText(message: SequenceMessage): string {
|
||||
}
|
||||
|
||||
function participantHeaderWidth(label: string, compact: boolean): number {
|
||||
return compact ? visualLength(label) : Math.max(5, visualLength(label) + 4)
|
||||
const width = labelLinesWidth(mermaidLabelLines(label))
|
||||
return compact ? width : Math.max(5, width + 4)
|
||||
}
|
||||
|
||||
function fragmentLabelText(fragment: SequenceFragment): string {
|
||||
@@ -236,7 +246,9 @@ function getStepContentBounds(
|
||||
if (fromIndex === toIndex) return { leftX: fromX, rightX: fromX + selfMessageLoopWidth(step.message) }
|
||||
const leftX = Math.min(fromX, toX)
|
||||
const rightX = Math.max(fromX, toX)
|
||||
return { leftX, rightX: Math.max(rightX, leftX + 2 + messageWidth(step.message) - 1) }
|
||||
const labelWidth = messageWidth(step.message)
|
||||
const labelLeftX = Math.floor((leftX + rightX - labelWidth) / 2)
|
||||
return { leftX: Math.min(leftX, labelLeftX), rightX: Math.max(rightX, labelLeftX + labelWidth - 1) }
|
||||
}
|
||||
if (step.type !== "note") return undefined
|
||||
const indexes = getParticipantIndexes(participantIndexes, step.note.over)
|
||||
@@ -387,7 +399,9 @@ function resolveParticipantCenters(
|
||||
if (fromIndex === toIndex && fromIndex >= 0 && fromIndex < diagram.participants.length - 1) {
|
||||
gaps[fromIndex] = Math.max(
|
||||
gaps[fromIndex]!,
|
||||
selfMessageLoopWidth(message) + Math.ceil(visualLength(diagram.participants[fromIndex + 1]!.label) / 2) + 2,
|
||||
selfMessageLoopWidth(message) +
|
||||
Math.ceil(labelLinesWidth(mermaidLabelLines(diagram.participants[fromIndex + 1]!.label)) / 2) +
|
||||
2,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -423,37 +437,31 @@ function separateExpandedGroupsFromExternalParticipants(
|
||||
compact: boolean,
|
||||
): number[] {
|
||||
const adjusted = [...centers]
|
||||
for (let pass = 0; pass < Math.max(1, ranges.length * 2); pass++) {
|
||||
let changed = false
|
||||
for (let boundary = 0; boundary < adjusted.length - 1; boundary++) {
|
||||
const groups = resolveGroupBounds(diagram, adjusted, participantIndexes, ranges, compact)
|
||||
const leftWidth = participantHeaderWidth(diagram.participants[boundary]!.label, compact)
|
||||
const rightWidth = participantHeaderWidth(diagram.participants[boundary + 1]!.label, compact)
|
||||
let leftRight = adjusted[boundary]! - Math.floor(leftWidth / 2) + leftWidth - 1
|
||||
let rightLeft = adjusted[boundary + 1]! - Math.floor(rightWidth / 2)
|
||||
let bordersGroup = false
|
||||
|
||||
for (const [index, range] of ranges.entries()) {
|
||||
const group = groups[index]!
|
||||
if (range.startIndex > 0) {
|
||||
const previousIndex = range.startIndex - 1
|
||||
const previousWidth = participantHeaderWidth(diagram.participants[previousIndex]!.label, compact)
|
||||
const previousRight = adjusted[previousIndex]! - Math.floor(previousWidth / 2) + previousWidth - 1
|
||||
const shift = previousRight + GROUP_HORIZONTAL_PADDING + 1 - group.leftX
|
||||
if (shift > 0) {
|
||||
for (let participantIndex = range.startIndex; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if (range.endIndex === boundary) {
|
||||
leftRight = Math.max(leftRight, groups[index]!.rightX)
|
||||
bordersGroup = true
|
||||
}
|
||||
if (range.endIndex < diagram.participants.length - 1) {
|
||||
const nextIndex = range.endIndex + 1
|
||||
const nextWidth = participantHeaderWidth(diagram.participants[nextIndex]!.label, compact)
|
||||
const nextLeft = adjusted[nextIndex]! - Math.floor(nextWidth / 2)
|
||||
const shift = group.rightX + GROUP_HORIZONTAL_PADDING + 1 - nextLeft
|
||||
if (shift > 0) {
|
||||
for (let participantIndex = nextIndex; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if (range.startIndex === boundary + 1) {
|
||||
rightLeft = Math.min(rightLeft, groups[index]!.leftX)
|
||||
bordersGroup = true
|
||||
}
|
||||
}
|
||||
if (!changed) return adjusted
|
||||
|
||||
if (!bordersGroup) continue
|
||||
const shift = leftRight + GROUP_HORIZONTAL_PADDING + 1 - rightLeft
|
||||
if (shift <= 0) continue
|
||||
for (let participantIndex = boundary + 1; participantIndex < adjusted.length; participantIndex++) {
|
||||
adjusted[participantIndex]! += shift
|
||||
}
|
||||
}
|
||||
return adjusted
|
||||
}
|
||||
@@ -475,6 +483,7 @@ export function createSequencePlacementPlan(
|
||||
},
|
||||
participants: [],
|
||||
groups: [],
|
||||
activations: [],
|
||||
steps: [],
|
||||
}
|
||||
}
|
||||
@@ -511,9 +520,13 @@ export function createSequencePlacementPlan(
|
||||
fragments = fragmentBounds()
|
||||
}
|
||||
const hasGroups = groups.length > 0
|
||||
const participantLabelHeight = Math.max(
|
||||
1,
|
||||
...diagram.participants.map((participant) => mermaidLabelLines(participant.label).length),
|
||||
)
|
||||
const participantHeaderTopY = hasGroups ? 1 : 0
|
||||
const participantHeaderY = participantHeaderTopY + (compact ? 0 : 1)
|
||||
const participantRuleY = participantHeaderTopY + (compact ? 0 : 2)
|
||||
const participantRuleY = participantHeaderTopY + (compact ? participantLabelHeight - 1 : participantLabelHeight + 1)
|
||||
const lifelineStartY = participantRuleY + 1
|
||||
const stepStartY = lifelineStartY + 1
|
||||
const width = Math.max(contentBounds.rightX + 1, ...groups.map((group) => group.rightX + 1), fragments.rightX + 1)
|
||||
@@ -525,19 +538,46 @@ export function createSequencePlacementPlan(
|
||||
const centerX = centers[index]!
|
||||
const width = participantHeaderWidth(participant.label, compact)
|
||||
const headerLeftX = centerX - Math.floor(width / 2)
|
||||
const labelLines = mermaidLabelLines(participant.label)
|
||||
return {
|
||||
participant,
|
||||
centerX,
|
||||
headerLeftX,
|
||||
headerRightX: headerLeftX + width - 1,
|
||||
labelX: centeredStart(centerX, participant.label),
|
||||
labelLines,
|
||||
}
|
||||
})
|
||||
const steps: SequenceStepPlacement[] = []
|
||||
const activations: SequenceActivationPlacement[] = []
|
||||
const activeByParticipant = new Map<string, Array<{ startY: number; depth: number }>>()
|
||||
const lastEventYByParticipant = new Map<string, number>()
|
||||
const openActivation = (participant: string, y: number): void => {
|
||||
const active = activeByParticipant.get(participant) ?? []
|
||||
active.push({ startY: y, depth: active.length })
|
||||
activeByParticipant.set(participant, active)
|
||||
}
|
||||
const closeActivation = (participant: string, y: number): void => {
|
||||
const active = activeByParticipant.get(participant)
|
||||
const opened = active?.pop()
|
||||
const participantIndex = indexes.get(participant)
|
||||
if (!opened || participantIndex === undefined) return
|
||||
activations.push({
|
||||
participant,
|
||||
centerX: centers[participantIndex]!,
|
||||
startY: opened.startY,
|
||||
endY: y,
|
||||
depth: opened.depth,
|
||||
})
|
||||
}
|
||||
let stepY = stepStartY
|
||||
const activeFrames: ActiveFragmentFrame[] = []
|
||||
for (const [stepIndex, step] of diagram.steps.entries()) {
|
||||
if (step.type === "activation") continue
|
||||
if (step.type === "activation") {
|
||||
const eventY = Math.min(lastEventYByParticipant.get(step.activation.participant) ?? stepY, lifelineEndY)
|
||||
if (step.activation.active) openActivation(step.activation.participant, eventY)
|
||||
else closeActivation(step.activation.participant, eventY)
|
||||
continue
|
||||
}
|
||||
const stepHeight = getStepHeight(step, centers, indexes, compact)
|
||||
if (step.type === "note") {
|
||||
const noteIndexes = getParticipantIndexes(indexes, step.note.over)
|
||||
@@ -588,6 +628,7 @@ export function createSequencePlacementPlan(
|
||||
const labelLines = messageLabelLines(messageLabelText(step.message))
|
||||
if (fromIndex === toIndex) {
|
||||
const centerX = centers[fromIndex]!
|
||||
const bottomY = stepY + labelLines.length + 1
|
||||
steps.push({
|
||||
type: "selfMessage",
|
||||
message: step.message,
|
||||
@@ -595,8 +636,11 @@ export function createSequencePlacementPlan(
|
||||
centerX,
|
||||
rightX: centerX + selfMessageLoopWidthForLines(labelLines),
|
||||
topY: stepY,
|
||||
bottomY: stepY + labelLines.length + 1,
|
||||
bottomY,
|
||||
})
|
||||
if (step.message.activate) openActivation(step.message.activate, bottomY)
|
||||
if (step.message.deactivate) closeActivation(step.message.deactivate, bottomY)
|
||||
lastEventYByParticipant.set(step.message.from, bottomY)
|
||||
} else {
|
||||
const fromX = centers[fromIndex]!
|
||||
const toX = centers[toIndex]!
|
||||
@@ -604,13 +648,16 @@ export function createSequencePlacementPlan(
|
||||
const leftX = Math.min(fromX, toX)
|
||||
const rightX = Math.max(fromX, toX)
|
||||
const inlineLabel = inlineMessageLabel(step.message, labelLines, fromX, toX, compact)
|
||||
const arrowY = inlineLabel ? stepY : stepY + labelLines.length
|
||||
const renderedLabelWidth = inlineLabel ? visualLength(inlineLabel) : labelLinesWidth(labelLines)
|
||||
const labelX = Math.floor((leftX + rightX - renderedLabelWidth) / 2)
|
||||
steps.push({
|
||||
type: "message",
|
||||
message: step.message,
|
||||
labelLines,
|
||||
labelX: leftX + 2,
|
||||
labelX,
|
||||
labelY: stepY,
|
||||
arrowY: inlineLabel ? stepY : stepY + labelLines.length,
|
||||
arrowY,
|
||||
fromX,
|
||||
toX,
|
||||
leftX,
|
||||
@@ -619,15 +666,23 @@ export function createSequencePlacementPlan(
|
||||
headX: arrowHeadX(toX, direction, step.message.head),
|
||||
inlineLabel,
|
||||
})
|
||||
if (step.message.activate) openActivation(step.message.activate, arrowY)
|
||||
if (step.message.deactivate) closeActivation(step.message.deactivate, arrowY)
|
||||
lastEventYByParticipant.set(step.message.from, arrowY)
|
||||
lastEventYByParticipant.set(step.message.to, arrowY)
|
||||
}
|
||||
stepY += stepHeight
|
||||
}
|
||||
for (const [participant, active] of activeByParticipant) {
|
||||
while (active.length > 0) closeActivation(participant, lifelineEndY)
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
rows: { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY },
|
||||
participants,
|
||||
groups,
|
||||
activations,
|
||||
steps,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,17 @@ stateDiagram-v2
|
||||
})
|
||||
})
|
||||
|
||||
test("decodes HTML entities in state, transition, and note labels", () => {
|
||||
const diagram = parseMermaidStateDiagram(`stateDiagram-v2
|
||||
state "Ready & waiting" as Ready
|
||||
Ready --> Done: elapsed <3s
|
||||
note right of Done: result ≥ 1`)
|
||||
|
||||
expect(diagram.states.find((state) => state.id === "Ready")?.label).toBe("Ready & waiting")
|
||||
expect(diagram.transitions[0]?.label).toBe("elapsed <3s")
|
||||
expect(diagram.notes[0]?.lines).toEqual(["result ≥ 1"])
|
||||
})
|
||||
|
||||
test("parses choice pseudo-states", () => {
|
||||
const diagram = parseMermaidStateDiagram(`
|
||||
stateDiagram-v2
|
||||
@@ -55,7 +66,7 @@ stateDiagram-v2
|
||||
Decision --> Accepted: yes
|
||||
`)
|
||||
|
||||
expect(diagram.states).toContainEqual({ id: "Decision", label: "┼", kind: "choice" })
|
||||
expect(diagram.states).toContainEqual({ id: "Decision", label: "", kind: "choice" })
|
||||
})
|
||||
|
||||
test("parses composite states and notes", () => {
|
||||
@@ -188,7 +199,7 @@ stateDiagram-v2
|
||||
●───────────────────────▶│ Running │
|
||||
╰──┬──────╯ 💥 sandbox dies BEFORE hook fires
|
||||
▲ │ ▲ (crash, our bug, race)
|
||||
╭────────┼─╰───┼───────╮
|
||||
╭────────┼─┴───┼───────╮
|
||||
▼ ╭────┼─────╯ ▼
|
||||
╭──────┴──╮ │ ╭──────╮
|
||||
│ Dormant │ │ │ Lost │
|
||||
@@ -384,7 +395,7 @@ stateDiagram-v2
|
||||
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─────────╮ submit ok ╭───────╮
|
||||
●────────────▶│ Editing ├─────────────┬────────────▶│ Saved │
|
||||
●────────────▶│ Editing ├────────────▶◆────────────▶│ Saved │
|
||||
╰──┬──────╯ │ ╰───────╯
|
||||
▲ │ ▲ type │ fail
|
||||
│ ╰────╯ │
|
||||
@@ -411,7 +422,7 @@ stateDiagram-v2
|
||||
Decision --> Done
|
||||
Done --> [*]`)
|
||||
|
||||
expect(output).toContain("Upper ├─────────────┬────────────▶│ Done")
|
||||
expect(output).toContain("Upper ├────────────▶◆────────────▶│ Done")
|
||||
})
|
||||
|
||||
test("renders self transitions as loops in vertical diagrams", () => {
|
||||
@@ -444,6 +455,65 @@ stateDiagram-v2
|
||||
expect(vertical).toContain("second")
|
||||
})
|
||||
|
||||
test("separates labels on four parallel vertical transitions", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
A --> B: one
|
||||
A --> B: two
|
||||
A --> B: three
|
||||
A --> B: four`)
|
||||
|
||||
expect(output).not.toContain("twothree")
|
||||
for (const label of ["one", "two", "three", "four"]) {
|
||||
expect(output.match(new RegExp(label, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps explicit choices visible in choice-only cycles", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state One <<choice>>
|
||||
state Two <<choice>>
|
||||
state Three <<choice>>
|
||||
One --> Two: clockwise
|
||||
Two --> Three: clockwise
|
||||
Three --> One: clockwise`)
|
||||
|
||||
expect(output.match(/◆/g)).toHaveLength(3)
|
||||
})
|
||||
|
||||
test("routes dense horizontal transitions around unrelated states", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction LR
|
||||
A --> B: ab
|
||||
A --> C: ac
|
||||
A --> D: ad
|
||||
B --> A: ba
|
||||
B --> C: bc
|
||||
B --> D: bd
|
||||
C --> A: ca
|
||||
C --> B: cb
|
||||
C --> D: cd
|
||||
D --> A: da
|
||||
D --> B: db
|
||||
D --> C: dc`)
|
||||
|
||||
for (const state of ["A", "B", "C", "D"]) expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("routes parallel transitions around vertically offset states", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
A --> B: first<br/>line two
|
||||
A --> B: second<br/>another line
|
||||
B --> A: return<br/>with details`)
|
||||
|
||||
expect(output).toContain(" A ")
|
||||
expect(output).toContain("│ B │")
|
||||
expect(output).toContain("first")
|
||||
expect(output).toContain("second")
|
||||
expect(output).toContain("return")
|
||||
})
|
||||
|
||||
test("keeps independent overlapping feedback labels and paths distinct", () => {
|
||||
const content = (direction: "LR" | "RL") => `stateDiagram-v2
|
||||
direction ${direction}
|
||||
@@ -561,15 +631,46 @@ stateDiagram-v2
|
||||
})
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─ Authenticated ──────────────────╮
|
||||
│ │
|
||||
login │ ╭──────╮ open ╭─────────╮ │ save
|
||||
●────────────▶│ Idle ├────────────▶│ Editing ├────────────▶◎
|
||||
│ │ save
|
||||
login │ ╭──────╮ open ╭─────────╮ │ logout
|
||||
●───────────┼▶│ Idle ├────────────▶│ Editing ├─┼──────────▶◎
|
||||
│ ╰──────╯ ╰─────────╯ │
|
||||
│ │
|
||||
╰──────────────────────────────────╯"
|
||||
`)
|
||||
})
|
||||
|
||||
test("keeps nested composite entry and exit routes within the outer frame height", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
state Session {
|
||||
[*] --> Open
|
||||
state Open {
|
||||
[*] --> Clean
|
||||
Clean --> Dirty: edit
|
||||
Dirty --> Clean: save
|
||||
}
|
||||
note right of Open: document lifecycle
|
||||
Open --> [*]: close
|
||||
}
|
||||
[*] --> Session
|
||||
Session --> [*]`)
|
||||
const lines = output.split("\n")
|
||||
const outerFrameTop = lines.find((line) => line.includes("Session"))!
|
||||
const frameLeft = outerFrameTop.indexOf("╭")
|
||||
const frameRight = outerFrameTop.lastIndexOf("╮")
|
||||
const outerFrameBottom = lines.findIndex((line) => line[frameLeft] === "╰" && line[frameRight] === "╯")
|
||||
const startColumn = lines.find((line) => line.includes("●"))!.indexOf("●")
|
||||
const endColumn = lines.find((line) => line.includes("◎"))!.indexOf("◎")
|
||||
|
||||
expect(outerFrameBottom).toBeGreaterThan(0)
|
||||
expect(startColumn).toBeLessThan(frameLeft)
|
||||
expect(endColumn).toBeGreaterThan(frameRight)
|
||||
expect(lines.slice(outerFrameBottom + 1).every((line) => line.trim() === "")).toBe(true)
|
||||
expect(output).toContain("Open")
|
||||
expect(output).toContain("document lifecycle")
|
||||
expect(output).toContain("close")
|
||||
})
|
||||
|
||||
test("renders notes attached to states", () => {
|
||||
const output = renderStateDiagram(`
|
||||
stateDiagram-v2
|
||||
@@ -600,6 +701,91 @@ stateDiagram-v2
|
||||
state Decision <<choice>>
|
||||
Decision --> [*]`)
|
||||
|
||||
expect(output).toContain("╰─────────────┬\n")
|
||||
expect(output).toContain("╰─────────────▼")
|
||||
expect(output).toContain("◆────────────▶◎")
|
||||
})
|
||||
|
||||
test("keeps vertical branch labels from overwriting state labels", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state "Branch root" as Root
|
||||
state "Upper branch" as Upper
|
||||
state "Lower branch" as Lower
|
||||
state "Merged branch" as Merge
|
||||
Root --> Upper: branch-up
|
||||
Root --> Lower: branch-down
|
||||
Upper --> Merge: merge-up
|
||||
Lower --> Merge: merge-down
|
||||
Merge --> Root: branch-feedback`)
|
||||
|
||||
for (const text of [
|
||||
"Branch root",
|
||||
"Upper branch",
|
||||
"Lower branch",
|
||||
"Merged branch",
|
||||
"branch-up",
|
||||
"branch-down",
|
||||
"merge-up",
|
||||
"merge-down",
|
||||
"branch-feedback",
|
||||
]) {
|
||||
expect(output).toContain(text)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps lifecycle states intact around branches and feedback", () => {
|
||||
const output = renderStateDiagram(`stateDiagram-v2
|
||||
[*] --> Idle
|
||||
Idle --> MailboxPending: enqueue + setAlarm
|
||||
MailboxPending --> PromptSubmitted: drain mailbox
|
||||
PromptSubmitted --> Polling: prompt admitted
|
||||
Polling --> Polling: execution still active
|
||||
Polling --> Completed: terminal log event
|
||||
Polling --> Polling: retry after transient failure
|
||||
Completed --> Idle: final Slack projection
|
||||
Idle --> Expired: 30 days inactive
|
||||
Expired --> [*]: delete SQLite state`)
|
||||
|
||||
for (const state of ["Idle", "MailboxPending", "PromptSubmitted", "Polling", "Completed", "Expired"]) {
|
||||
expect(output.match(new RegExp(state, "g"))).toHaveLength(1)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps composite titles intact under reciprocal composite routes", () => {
|
||||
const source = `stateDiagram-v2
|
||||
direction LR
|
||||
state FirstGroup {
|
||||
[*] --> FirstInner
|
||||
FirstInner --> [*]: first-out
|
||||
}
|
||||
state SecondGroup {
|
||||
[*] --> SecondInner
|
||||
SecondInner --> [*]: second-out
|
||||
}
|
||||
FirstGroup --> SecondGroup: group-next
|
||||
SecondGroup --> FirstGroup: group-back`
|
||||
|
||||
for (const direction of ["LR", "TB"] as const) {
|
||||
const lines = renderStateDiagram(source, { direction }).split("\n")
|
||||
for (const title of ["FirstGroup", "SecondGroup"]) {
|
||||
const top = lines.findIndex((line) => line.includes(title))
|
||||
const left = lines[top]!.lastIndexOf("╭", lines[top]!.indexOf(title))
|
||||
const right = lines[top]!.indexOf("╮", left)
|
||||
const bottom = lines.findIndex((line, index) => index > top && line[left] === "╰" && line[right] === "╯")
|
||||
|
||||
expect(top).toBeGreaterThanOrEqual(0)
|
||||
expect(left).toBeGreaterThanOrEqual(0)
|
||||
expect(right).toBeGreaterThan(left)
|
||||
expect(bottom).toBeGreaterThan(top)
|
||||
expect(
|
||||
lines.slice(top + 1, bottom).every((line) => "│├┤┼".includes(line[left]!) && "│├┤┼".includes(line[right]!)),
|
||||
).toBe(true)
|
||||
expect(
|
||||
lines[bottom]!.slice(left + 1, right)
|
||||
.split("")
|
||||
.every((char) => "─┬┴┼".includes(char)),
|
||||
).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -49,7 +49,9 @@ function translateTransitionPlans(
|
||||
function makeGrid(width: number, height: number): StateGrid {
|
||||
return new DiagramCanvas(width, height, {
|
||||
mergeCell: (existing, incoming): StateCell => {
|
||||
const shouldMerge = existing.style === "transition" && incoming.style === "transition"
|
||||
const existingIsTransition = existing.style === "transition" || existing.style?.startsWith("stateDepartureRamp")
|
||||
const incomingIsTransition = incoming.style === "transition" || incoming.style?.startsWith("stateDepartureRamp")
|
||||
const shouldMerge = incomingIsTransition && (existingIsTransition || existing.style === "composite")
|
||||
return {
|
||||
...incoming,
|
||||
char: shouldMerge
|
||||
@@ -198,7 +200,8 @@ function drawTransitionJunctionPlans(
|
||||
): void {
|
||||
for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
|
||||
const style = plan.kind === "choice" ? "choice" : "transition"
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, diagramLineGlyph(plan.connections, "rounded"), style)
|
||||
const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,14 +40,6 @@ export interface StateDiagramLayoutOptions {
|
||||
minStateGap: number
|
||||
}
|
||||
|
||||
function visualLength(value: string): number {
|
||||
return diagramTextWidth(value)
|
||||
}
|
||||
|
||||
function splitStateDiagramLines(value: string): string[] {
|
||||
return splitDiagramLines(value)
|
||||
}
|
||||
|
||||
function computeRanks(diagram: StateDiagram): Map<string, number> {
|
||||
const ranks = new Map<string, number>()
|
||||
const outgoing = new Map<string, string[]>()
|
||||
@@ -88,8 +80,11 @@ function outgoingTransitions(diagram: StateDiagram): Map<string, StateDiagramTra
|
||||
return outgoing
|
||||
}
|
||||
|
||||
function reaches(diagram: StateDiagram, from: string, target: string): boolean {
|
||||
const outgoing = outgoingTransitions(diagram)
|
||||
function reaches(
|
||||
outgoing: ReadonlyMap<string, readonly StateDiagramTransition[]>,
|
||||
from: string,
|
||||
target: string,
|
||||
): boolean {
|
||||
const visited = new Set<string>()
|
||||
const stack = [from]
|
||||
while (stack.length > 0) {
|
||||
@@ -104,6 +99,7 @@ function reaches(diagram: StateDiagram, from: string, target: string): boolean {
|
||||
|
||||
function computeMainPath(diagram: StateDiagram): string[] {
|
||||
const outgoing = outgoingTransitions(diagram)
|
||||
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
|
||||
const start = diagram.states.find((state) => state.kind === "start")?.id ?? diagram.states[0]?.id
|
||||
if (!start) return []
|
||||
|
||||
@@ -114,9 +110,14 @@ function computeMainPath(diagram: StateDiagram): string[] {
|
||||
const candidates = (outgoing.get(current) ?? []).filter((transition) => !visited.has(transition.to))
|
||||
if (candidates.length === 0) break
|
||||
const next =
|
||||
candidates.find((transition) => diagram.states.find((state) => state.id === transition.to)?.kind === "end") ??
|
||||
candidates.find((transition) => !reaches(diagram, transition.to, current)) ??
|
||||
candidates.find((transition) => !hasReverseTransition(diagram, transition))
|
||||
candidates.find((transition) => statesById.get(transition.to)?.kind === "end") ??
|
||||
candidates.find((transition) => !reaches(outgoing, transition.to, current)) ??
|
||||
candidates.find((transition) => !hasReverseTransition(diagram, transition)) ??
|
||||
candidates.find((transition) => {
|
||||
const fromParent = statesById.get(current)?.parentId
|
||||
const toParent = statesById.get(transition.to)?.parentId
|
||||
return Boolean(fromParent && toParent && fromParent !== toParent)
|
||||
})
|
||||
if (!next) break
|
||||
path.push(next.to)
|
||||
visited.add(next.to)
|
||||
@@ -132,7 +133,7 @@ function stateSize(state: StateDiagramState): { width: number; height: number; l
|
||||
}
|
||||
|
||||
function noteLines(note: StateDiagramNote): string[] {
|
||||
const lines = note.lines.flatMap(splitStateDiagramLines).map((line) => line.trim())
|
||||
const lines = note.lines.flatMap(splitDiagramLines).map((line) => line.trim())
|
||||
return lines.length > 0 ? lines : [""]
|
||||
}
|
||||
|
||||
@@ -202,7 +203,7 @@ function addCompositeBounds(diagram: StateDiagram, layout: StateDiagramLayout):
|
||||
const top = Math.min(...childBounds.map((bound) => bound.top)) - 2
|
||||
const right = Math.max(...childBounds.map((bound) => bound.left + bound.width)) + 2
|
||||
const bottom = Math.max(...childBounds.map((bound) => bound.top + bound.height)) + 2
|
||||
const width = Math.max(right - left, visualLength(composite.label) + 5)
|
||||
const width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
|
||||
const bound = {
|
||||
id: composite.id,
|
||||
left,
|
||||
@@ -349,7 +350,7 @@ function expandCompositeBoundsForNotes(diagram: StateDiagram, layout: StateDiagr
|
||||
|
||||
bound.left = left
|
||||
bound.top = top
|
||||
bound.width = Math.max(right - left, visualLength(composite.label) + 5)
|
||||
bound.width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
|
||||
bound.height = bottom - top
|
||||
bound.centerX = bound.left + Math.floor(bound.width / 2)
|
||||
bound.centerY = bound.top + Math.floor(bound.height / 2)
|
||||
@@ -461,7 +462,8 @@ export function createStateDiagramLayout(
|
||||
x += size.width + options.minStateGap + 8
|
||||
}
|
||||
const labelRows = states.reduce((rows, state) => Math.max(rows, outgoingLabelRows.get(state.id) ?? 0), 0)
|
||||
y += rowHeight + Math.max(4, labelRows + 3)
|
||||
const pseudoStateApproachClearance = states.some((state) => state.kind === "choice") ? 2 : 0
|
||||
y += rowHeight + Math.max(4, labelRows + 3) + pseudoStateApproachClearance
|
||||
}
|
||||
|
||||
return finalizeLayout(diagram, emptyLayout(bounds, sizes))
|
||||
@@ -499,7 +501,10 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
|
||||
const adjacentLabelWidth = diagram.transitions
|
||||
.filter((transition) => transition.from === id && transition.to === nextId)
|
||||
.reduce((width, transition) => Math.max(width, measureStateTransitionLabel(transition.label).width), 0)
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + 2)
|
||||
const crossesCompositeBoundary = Boolean(
|
||||
nextId && statesById.get(id)?.parentId !== statesById.get(nextId)?.parentId,
|
||||
)
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + (crossesCompositeBoundary ? 6 : 2))
|
||||
}
|
||||
|
||||
const branchesByParent = new Map<string, string[]>()
|
||||
@@ -550,12 +555,25 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
|
||||
}
|
||||
|
||||
const ranks = computeRanks(diagram)
|
||||
const fallbackStates = diagram.states.filter((state) => !bounds.has(state.id))
|
||||
const fallbackStates = diagram.states
|
||||
.filter((state) => !bounds.has(state.id))
|
||||
.sort((left, right) => (ranks.get(left.id) ?? 0) - (ranks.get(right.id) ?? 0))
|
||||
for (const state of fallbackStates) {
|
||||
const size = sizes.get(state.id)!
|
||||
const rank = ranks.get(state.id) ?? bounds.size
|
||||
const top = baselineY + 5
|
||||
const left = rank * (size.width + defaultGap)
|
||||
const rank = ranks.get(state.id) ?? bounds.size
|
||||
let left = rank * (size.width + defaultGap)
|
||||
while (true) {
|
||||
const collision = [...bounds.values()].find(
|
||||
(bound) =>
|
||||
left < bound.left + bound.width + defaultGap &&
|
||||
left + size.width + defaultGap > bound.left &&
|
||||
top < bound.top + bound.height &&
|
||||
top + size.height > bound.top,
|
||||
)
|
||||
if (!collision) break
|
||||
left = collision.left + collision.width + defaultGap
|
||||
}
|
||||
bounds.set(state.id, {
|
||||
id: state.id,
|
||||
left,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
|
||||
import { decodeMermaidText, firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
|
||||
import { splitDiagramLines } from "../core/text-lines.js"
|
||||
import { MermaidSyntaxError } from "../diagnostics.js"
|
||||
import { normalizeStateDiagramEndpoint, stateDiagramEndMarkerId, stateDiagramStartMarkerId } from "./endpoint.js"
|
||||
@@ -96,7 +96,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
notes.push({
|
||||
target: pendingNote.target,
|
||||
position: pendingNote.position,
|
||||
lines: pendingNote.lines,
|
||||
lines: pendingNote.lines.map(decodeMermaidText),
|
||||
})
|
||||
pendingNote = undefined
|
||||
} else if (line || pendingNote.lines.length > 0) {
|
||||
@@ -119,6 +119,9 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
|
||||
const directionMatch = line.match(DIRECTION_RE)
|
||||
if (directionMatch) {
|
||||
if (parentStack.length > 0) {
|
||||
throw new MermaidSyntaxError("state", source.lineNumber, line, "Composite-local direction is not supported")
|
||||
}
|
||||
direction = normalizeDirection(directionMatch[1])
|
||||
continue
|
||||
}
|
||||
@@ -128,7 +131,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
notes.push({
|
||||
position: inlineNoteMatch[1]!.toLowerCase() as "left" | "right",
|
||||
target: inlineNoteMatch[2]!,
|
||||
lines: splitDiagramLines(inlineNoteMatch[3]!.trim()),
|
||||
lines: splitDiagramLines(decodeMermaidText(inlineNoteMatch[3]!.trim())),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -150,7 +153,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
const id = compositeMatch[2]!
|
||||
composites.push({
|
||||
id,
|
||||
label: compositeMatch[1] ?? id,
|
||||
label: decodeMermaidText(compositeMatch[1] ?? id),
|
||||
...(parentId ? { parentId } : {}),
|
||||
})
|
||||
parentStack.push({ id, lineNumber: source.lineNumber, sourceLine: line })
|
||||
@@ -159,13 +162,13 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
|
||||
const stateMatch = line.match(STATE_RE)
|
||||
if (stateMatch) {
|
||||
ensureState(states, stateMatch[2]!, stateMatch[1]!, "state", parentId)
|
||||
ensureState(states, stateMatch[2]!, decodeMermaidText(stateMatch[1]!), "state", parentId)
|
||||
continue
|
||||
}
|
||||
|
||||
const choiceMatch = line.match(CHOICE_STATE_RE)
|
||||
if (choiceMatch) {
|
||||
ensureState(states, choiceMatch[1]!, "┼", "choice", parentId)
|
||||
ensureState(states, choiceMatch[1]!, "", "choice", parentId)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -177,7 +180,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
const to = normalizeStateDiagramEndpoint(rawTo, "to", parentId)
|
||||
ensureState(states, from, rawFrom === "[*]" ? "●" : from, rawFrom === "[*]" ? "start" : "state", parentId)
|
||||
ensureState(states, to, rawTo === "[*]" ? "◎" : to, rawTo === "[*]" ? "end" : "state", parentId)
|
||||
transitions.push({ from, to, label: transitionMatch[3]?.trim() ?? "" })
|
||||
transitions.push({ from, to, label: decodeMermaidText(transitionMatch[3]?.trim() ?? "") })
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { StateDiagramBoxBounds } from "./layout.js"
|
||||
import { createStateDiagramLayout } from "./layout.js"
|
||||
import { parseMermaidStateDiagram } from "./parser.js"
|
||||
import {
|
||||
createStateTransitionJunctionPlans,
|
||||
createStateTransitionRenderPlans,
|
||||
createStateTransitionRoutePlans,
|
||||
} from "./routing.js"
|
||||
import { prepareVisibleStateDiagram, type StateVisibleDiagram } from "./visible-model.js"
|
||||
import type { StateVisibleDiagram } from "./visible-model.js"
|
||||
import { prepareVisibleStateDiagram } from "./visible-model.js"
|
||||
|
||||
function bounds(id: string, centerX: number, centerY: number): StateDiagramBoxBounds {
|
||||
return { id, left: centerX - 2, top: centerY - 1, width: 5, height: 3, centerX, centerY }
|
||||
@@ -207,6 +210,39 @@ describe("createStateTransitionRenderPlans", () => {
|
||||
[11, 4],
|
||||
])
|
||||
})
|
||||
|
||||
test("keeps vertical branch routes out of unrelated state bounds", () => {
|
||||
const diagram = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
direction TB
|
||||
state "Branch root" as Root
|
||||
state "Upper branch" as Upper
|
||||
state "Lower branch" as Lower
|
||||
state "Merged branch" as Merge
|
||||
Root --> Upper: branch-up
|
||||
Root --> Lower: branch-down
|
||||
Upper --> Merge: merge-up
|
||||
Lower --> Merge: merge-down
|
||||
Merge --> Root: branch-feedback`),
|
||||
)
|
||||
const layout = createStateDiagramLayout(diagram, { minStateGap: 4 })
|
||||
const plans = createStateTransitionRenderPlans(diagram, layout.bounds, 30)
|
||||
|
||||
for (const plan of plans) {
|
||||
const unrelated = diagram.states
|
||||
.filter((state) => state.id !== plan.route.transition.from && state.id !== plan.route.transition.to)
|
||||
.map((state) => layout.bounds.get(state.id)!)
|
||||
expect(
|
||||
plan.path.some(([x, y]) =>
|
||||
unrelated.some(
|
||||
(bound) =>
|
||||
x >= bound.left && x < bound.left + bound.width && y >= bound.top && y < bound.top + bound.height,
|
||||
),
|
||||
),
|
||||
`${plan.route.transition.from} -> ${plan.route.transition.to}`,
|
||||
).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("createStateTransitionJunctionPlans", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { BorderChars } from "@opentui/core"
|
||||
import type { DiagramDirection } from "../core/geometry.js"
|
||||
import { SpatialIndex, spatialPathClaim, spatialRectClaim } from "../core/spatial.js"
|
||||
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
|
||||
import type { StateDiagramBoxBounds as BoxBounds } from "./layout.js"
|
||||
import type { StateDiagram, StateDiagramState, StateDiagramTransition } from "./types.js"
|
||||
@@ -10,14 +11,15 @@ interface StateTransitionRoutePlanBase {
|
||||
from: BoxBounds
|
||||
to: BoxBounds
|
||||
targetIsChoice: boolean
|
||||
targetIsHiddenMarker: boolean
|
||||
}
|
||||
|
||||
export type StateTransitionRoutePlan =
|
||||
| (StateTransitionRoutePlanBase & { kind: "self" })
|
||||
| (StateTransitionRoutePlanBase & { kind: "horizontal-forward"; leftToRight: boolean })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "top-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical-elbow"; hasReverse: boolean; offsetConnector: boolean })
|
||||
| (StateTransitionRoutePlanBase & { kind: "side-parallel"; railX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical" })
|
||||
@@ -192,6 +194,93 @@ function hasOpposingTopConnector(
|
||||
})
|
||||
}
|
||||
|
||||
function verticalCorridorCrossesUnrelatedState(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
): boolean {
|
||||
const top = Math.min(from.top + from.height, to.top + to.height)
|
||||
const bottom = Math.max(from.top - 1, to.top - 1)
|
||||
return diagram.states.some((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
|
||||
const bound = bounds.get(state.id)
|
||||
return Boolean(
|
||||
bound &&
|
||||
from.centerX >= bound.left &&
|
||||
from.centerX < bound.left + bound.width &&
|
||||
top < bound.top + bound.height &&
|
||||
bottom >= bound.top,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function horizontalCorridorCrossesUnrelatedState(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
): boolean {
|
||||
const leftToRight = from.centerX <= to.centerX
|
||||
const startX = leftToRight ? from.left + from.width : from.left - 1
|
||||
const endX = leftToRight ? to.left - 1 : to.left + to.width
|
||||
const space = SpatialIndex.empty().add(
|
||||
...diagram.states.flatMap((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return []
|
||||
const bound = bounds.get(state.id)
|
||||
return bound ? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)] : []
|
||||
}),
|
||||
)
|
||||
const corridor = spatialPathClaim(
|
||||
`corridor:${transition.from}:${transition.to}`,
|
||||
`transition:${transition.from}:${transition.to}`,
|
||||
"route",
|
||||
[
|
||||
{ x: startX, y: from.centerY },
|
||||
{ x: endX, y: from.centerY },
|
||||
],
|
||||
)
|
||||
return !space.isFree(corridor)
|
||||
}
|
||||
|
||||
function bottomApproachX(
|
||||
diagram: StateVisibleDiagram,
|
||||
transition: StateVisibleTransition,
|
||||
from: BoxBounds,
|
||||
to: BoxBounds,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
railY: number,
|
||||
): number {
|
||||
const targetX = to.width > 1 ? (from.centerX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
|
||||
const targetBottomY = to.top + to.height
|
||||
const top = Math.min(targetBottomY, railY)
|
||||
const bottom = Math.max(targetBottomY, railY)
|
||||
const isClear = (x: number): boolean =>
|
||||
!diagram.states.some((state) => {
|
||||
if (state.id === transition.from || state.id === transition.to || isHiddenCompositeMarker(state)) return false
|
||||
const bound = bounds.get(state.id)
|
||||
return Boolean(
|
||||
bound &&
|
||||
x >= bound.left &&
|
||||
x < bound.left + bound.width &&
|
||||
top < bound.top + bound.height &&
|
||||
bottom >= bound.top,
|
||||
)
|
||||
})
|
||||
|
||||
if (isClear(targetX)) return targetX
|
||||
const maxX = Math.max(targetX, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 1
|
||||
for (let distance = 1; distance <= maxX; distance++) {
|
||||
const right = targetX + distance
|
||||
if (isClear(right)) return right
|
||||
const left = targetX - distance
|
||||
if (left >= 0 && isClear(left)) return left
|
||||
}
|
||||
return targetX
|
||||
}
|
||||
|
||||
export function createStateTransitionRoutePlans(
|
||||
diagram: StateVisibleDiagram,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
@@ -200,16 +289,29 @@ export function createStateTransitionRoutePlans(
|
||||
): StateTransitionRoutePlan[] {
|
||||
const statesById = new Map(diagram.states.map((state) => [state.id, state]))
|
||||
const endpointOccurrences = new Map<string, number>()
|
||||
const maxLabelWidth = Math.max(
|
||||
0,
|
||||
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).width),
|
||||
)
|
||||
const parallelLaneGap = Math.max(
|
||||
3,
|
||||
...diagram.transitions.map((transition) => measureStateTransitionLabel(transition.label).height + 2),
|
||||
)
|
||||
const sideLaneX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + maxLabelWidth + 3
|
||||
let nextSideRailX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 3
|
||||
const feedbackAllocations = createFeedbackAllocations(diagram, bounds, feedbackLaneY, parallelLaneGap, feedbackTopY)
|
||||
let nextBottomRailY =
|
||||
Math.max(
|
||||
feedbackLaneY - parallelLaneGap,
|
||||
...[...feedbackAllocations.values()]
|
||||
.filter((allocation) => allocation.side === "bottom")
|
||||
.map((allocation) => allocation.railY),
|
||||
) + parallelLaneGap
|
||||
const allocateSideRail = (label: string): number => {
|
||||
const railX = nextSideRailX
|
||||
nextSideRailX += Math.max(3, measureStateTransitionLabel(label).width + 2)
|
||||
return railX
|
||||
}
|
||||
const allocateBottomRail = (): number => {
|
||||
const railY = nextBottomRailY
|
||||
nextBottomRailY += parallelLaneGap
|
||||
return railY
|
||||
}
|
||||
|
||||
return diagram.transitions.flatMap((transition): StateTransitionRoutePlan[] => {
|
||||
const from = bounds.get(transition.from)
|
||||
@@ -217,8 +319,9 @@ export function createStateTransitionRoutePlans(
|
||||
if (!from || !to) return []
|
||||
|
||||
const targetState = statesById.get(transition.to)
|
||||
const targetIsChoice = targetState?.kind === "choice" || isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice }
|
||||
const targetIsChoice = targetState?.kind === "choice"
|
||||
const targetIsHiddenMarker = isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice, targetIsHiddenMarker }
|
||||
if (transition.from === transition.to) return [{ ...base, kind: "self" }]
|
||||
const endpointKey = `${transition.from}\u0000${transition.to}`
|
||||
const parallelIndex = endpointOccurrences.get(endpointKey) ?? 0
|
||||
@@ -227,30 +330,80 @@ export function createStateTransitionRoutePlans(
|
||||
(diagram.direction === "LR" || diagram.direction === "RL") && isStateHorizontalFeedback(diagram, from, to)
|
||||
const feedbackAllocation = feedbackAllocations.get(transition)
|
||||
if (feedbackAllocation) {
|
||||
if (feedbackAllocation.side === "bottom") {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackAllocation.railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackAllocation.railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: feedbackAllocation.side === "bottom" ? "bottom-feedback" : "top-feedback",
|
||||
kind: "top-feedback",
|
||||
railY: feedbackAllocation.railY,
|
||||
},
|
||||
]
|
||||
}
|
||||
if (parallelIndex > 0) {
|
||||
if (diagram.direction === "LR" || diagram.direction === "RL") {
|
||||
if ((diagram.direction === "LR" || diagram.direction === "RL") && from.centerY === to.centerY) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY: feedbackLaneY + (parallelIndex - 1) * parallelLaneGap,
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "side-parallel", railX: sideLaneX + (parallelIndex - 1) * parallelLaneGap }]
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (diagram.direction !== "LR" && diagram.direction !== "RL") {
|
||||
const fromParent = statesById.get(transition.from)?.parentId
|
||||
const toParent = statesById.get(transition.to)?.parentId
|
||||
if (fromParent && toParent && fromParent !== toParent) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (verticalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (from.centerY > to.centerY) {
|
||||
return [{ ...base, kind: "side-parallel", railX: allocateSideRail(transition.label) }]
|
||||
}
|
||||
if (from.centerY === to.centerY) {
|
||||
if (hasReverseTransition(diagram, transition) && from.centerX > to.centerX) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
|
||||
}
|
||||
if (from.centerX !== to.centerX) {
|
||||
return [{ ...base, kind: "vertical-elbow", hasReverse: false, offsetConnector: false }]
|
||||
}
|
||||
return [{ ...base, kind: "vertical" }]
|
||||
}
|
||||
if (diagram.direction !== "LR" && diagram.direction !== "RL") return [{ ...base, kind: "vertical" }]
|
||||
|
||||
if (from.centerY !== to.centerY) {
|
||||
if (from.centerY > to.centerY && feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
if (from.centerY > to.centerY && feedback)
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackLaneY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
|
||||
},
|
||||
]
|
||||
const hasReverse = hasReverseTransition(diagram, transition)
|
||||
return [
|
||||
{
|
||||
@@ -261,7 +414,26 @@ export function createStateTransitionRoutePlans(
|
||||
},
|
||||
]
|
||||
}
|
||||
if (feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
if (feedback)
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-feedback",
|
||||
railY: feedbackLaneY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
|
||||
},
|
||||
]
|
||||
if (horizontalCorridorCrossesUnrelatedState(diagram, transition, from, to, bounds)) {
|
||||
const railY = allocateBottomRail()
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
},
|
||||
]
|
||||
}
|
||||
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
|
||||
})
|
||||
}
|
||||
@@ -333,7 +505,7 @@ function addTopDeparture(builder: StateTransitionRenderBuilder, bounds: BoxBound
|
||||
}
|
||||
|
||||
function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, leftToRight, transition } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, leftToRight, transition } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "horizontal-forward" }
|
||||
>
|
||||
@@ -343,9 +515,12 @@ function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
|
||||
const step = leftToRight ? 1 : -1
|
||||
const startX = leftToRight ? from.left + from.width : from.left - 1
|
||||
const endX = leftToRight ? to.left - 1 : to.left + to.width
|
||||
addHorizontalLine(builder, startX, targetIsChoice ? endX : endX - step, y, step)
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, y)
|
||||
else addCell(builder, { x: endX, y, arrowDirection: leftToRight ? "right" : "left" })
|
||||
addHorizontalLine(builder, startX, endX - step, y, step)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker ? { x: endX, y, char: "─" } : { x: endX, y, arrowDirection: leftToRight ? "right" : "left" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, y)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const labelX = Math.min(startX, endX) + Math.max(1, Math.floor((Math.abs(endX - startX) - metrics.width) / 2))
|
||||
@@ -378,14 +553,14 @@ function outsideTopY(bounds: BoxBounds): number {
|
||||
}
|
||||
|
||||
function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY, approachX } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "bottom-feedback" | "bottom-parallel" }
|
||||
>
|
||||
const sourceX = from.centerX
|
||||
const targetX = to.width > 1 ? (sourceX > to.centerX ? to.left + 1 : to.left + to.width - 2) : to.centerX
|
||||
const targetRailCutsSource = targetX >= from.left && targetX <= from.left + from.width - 1
|
||||
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : targetX
|
||||
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : approachX
|
||||
const sourceBottomY = outsideBottomY(from)
|
||||
const targetBottomY = outsideBottomY(to)
|
||||
addBottomDeparture(builder, from, sourceX)
|
||||
@@ -406,8 +581,13 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, { x, y: targetBottomY, char: "─" })
|
||||
}
|
||||
}
|
||||
addCell(builder, { x: targetX, y: targetBottomY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "up" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetBottomY, char: "│" }
|
||||
: { x: targetX, y: targetBottomY, arrowDirection: "up" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - railTargetX) - 2
|
||||
@@ -419,7 +599,7 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "top-feedback" }
|
||||
>
|
||||
@@ -437,8 +617,13 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
addCell(builder, { x: targetX, y: railY, char: sourceX > targetX ? "╭" : "╮" })
|
||||
for (let y = railY + 1; y < targetTopY; y++) addCell(builder, { x: targetX, y, char: "│" })
|
||||
addCell(builder, { x: targetX, y: targetTopY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "down" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetTopY, char: "│" }
|
||||
: { x: targetX, y: targetTopY, arrowDirection: "down" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - targetX) - 2
|
||||
@@ -450,7 +635,7 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addSideParallelTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, transition, railX } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railX } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "side-parallel" }
|
||||
>
|
||||
@@ -465,9 +650,16 @@ function addSideParallelTransition(builder: StateTransitionRenderBuilder): void
|
||||
for (let y = startY + verticalStep; y !== endY; y += verticalStep) addCell(builder, { x: railX, y, char: "│" })
|
||||
addCell(builder, { x: railX, y: endY, char: verticalStep === 1 ? "╯" : "╮" })
|
||||
for (let x = railX - 1; x > endX; x--) addCell(builder, { x, y: endY, char: "─" })
|
||||
addCell(builder, { x: endX, y: endY, ...(targetIsChoice ? { char: "─" } : { arrowDirection: "left" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) addLabel(builder, railX + 2, Math.min(startY, endY) + 1, transition.label)
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker ? { x: endX, y: endY, char: "─" } : { x: endX, y: endY, arrowDirection: "left" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) {
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const labelY = Math.max(0, Math.floor((startY + endY - metrics.height + 1) / 2))
|
||||
addLabel(builder, railX + 2, labelY, transition.label)
|
||||
}
|
||||
}
|
||||
|
||||
function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
@@ -476,10 +668,8 @@ function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
}
|
||||
|
||||
function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice, hasReverse, offsetConnector } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "vertical-elbow" }
|
||||
>
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker, hasReverse, offsetConnector } =
|
||||
builder.route as Extract<StateTransitionRoutePlan, { kind: "vertical-elbow" }>
|
||||
const topToBottom = from.centerY < to.centerY
|
||||
const offset = offsetConnector ? (topToBottom ? -2 : 2) : 0
|
||||
const startX = innerConnectorX(from, from.centerX + offset)
|
||||
@@ -513,13 +703,19 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
}
|
||||
}
|
||||
const targetChar = targetIsChoice ? (hasTargetApproach || startX === endX ? "│" : topToBottom ? "┬" : "┴") : undefined
|
||||
const targetChar = targetIsHiddenMarker
|
||||
? hasTargetApproach || startX === endX
|
||||
? "│"
|
||||
: topToBottom
|
||||
? "┬"
|
||||
: "┴"
|
||||
: undefined
|
||||
addCell(builder, {
|
||||
x: endX,
|
||||
y: endY,
|
||||
...(targetChar ? { char: targetChar } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
if (topToBottom) {
|
||||
@@ -543,7 +739,7 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
|
||||
function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice } = builder.route
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker } = builder.route
|
||||
const topToBottom = from.centerY <= to.centerY
|
||||
const x = from.centerX
|
||||
const startY = topToBottom ? from.top + from.height : from.top - 1
|
||||
@@ -555,9 +751,9 @@ function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, {
|
||||
x,
|
||||
y: endY,
|
||||
...(targetIsChoice ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
...(targetIsHiddenMarker ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) addLabel(builder, x + 2, Math.min(startY, endY) + 1, transition.label)
|
||||
}
|
||||
|
||||
@@ -590,69 +786,47 @@ function createStateTransitionRenderPlan(route: StateTransitionRoutePlan): State
|
||||
return builder
|
||||
}
|
||||
|
||||
interface StateTransitionLabelRect {
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
function labelRect(label: StateTransitionRenderLabel, width: number): StateTransitionLabelRect {
|
||||
return { left: label.x, top: label.y, width, height: label.lines.length }
|
||||
}
|
||||
|
||||
function rectsOverlap(left: StateTransitionLabelRect, right: StateTransitionLabelRect): boolean {
|
||||
return (
|
||||
left.left < right.left + right.width &&
|
||||
left.left + left.width > right.left &&
|
||||
left.top < right.top + right.height &&
|
||||
left.top + left.height > right.top
|
||||
)
|
||||
}
|
||||
|
||||
function placeStateTransitionLabels(
|
||||
plans: readonly StateTransitionRenderPlan[],
|
||||
diagram: StateVisibleDiagram,
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
): StateTransitionRenderPlan[] {
|
||||
const routeCells = new Set(plans.flatMap((plan) => plan.cells.map((cell) => `${cell.x}:${cell.y}`)))
|
||||
const placedLabels: StateTransitionLabelRect[] = []
|
||||
const stateRects = diagram.states.flatMap((state) => {
|
||||
const bound = bounds.get(state.id)
|
||||
return bound && !isHiddenCompositeMarker(state)
|
||||
? [{ left: bound.left, top: bound.top, width: bound.width, height: bound.height }]
|
||||
: []
|
||||
})
|
||||
let space = SpatialIndex.empty().add(
|
||||
...diagram.states.flatMap((state) => {
|
||||
const bound = bounds.get(state.id)
|
||||
return bound && !isHiddenCompositeMarker(state)
|
||||
? [spatialRectClaim(`state:${state.id}`, `state:${state.id}`, "body", bound)]
|
||||
: []
|
||||
}),
|
||||
...plans.map((plan, index) =>
|
||||
spatialPathClaim(
|
||||
`route:${index}`,
|
||||
`route:${index}`,
|
||||
"route",
|
||||
plan.path.map(([x, y]) => ({ x, y })),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
return plans.map((plan) => {
|
||||
return plans.map((plan, planIndex) => {
|
||||
if (!plan.label) return plan
|
||||
const width = Math.max(...plan.label.lines.map(diagramTextWidth))
|
||||
if (plan.label.lines.length === 1) {
|
||||
placedLabels.push(labelRect(plan.label, width))
|
||||
return plan
|
||||
}
|
||||
const statePadding = 1
|
||||
const statePadding = plan.label.lines.length === 1 ? 0 : 1
|
||||
const labelClaim = (x: number, y: number) =>
|
||||
spatialRectClaim(`label:${planIndex}`, `label:${planIndex}`, "label", {
|
||||
left: x,
|
||||
top: y,
|
||||
width,
|
||||
height: plan.label!.lines.length,
|
||||
})
|
||||
const isClear = (x: number, y: number): boolean => {
|
||||
if (x < 0 || y < 0) return false
|
||||
const rect = labelRect({ ...plan.label!, x, y }, width)
|
||||
if (
|
||||
stateRects.some((state) =>
|
||||
rectsOverlap(rect, {
|
||||
left: state.left - statePadding,
|
||||
top: state.top - statePadding,
|
||||
width: state.width + statePadding * 2,
|
||||
height: state.height + statePadding * 2,
|
||||
}),
|
||||
)
|
||||
)
|
||||
return false
|
||||
if (placedLabels.some((label) => rectsOverlap(rect, label))) return false
|
||||
for (let row = rect.top; row < rect.top + rect.height; row++) {
|
||||
for (let column = rect.left; column < rect.left + rect.width; column++) {
|
||||
if (routeCells.has(`${column}:${row}`)) return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
return space.isFree(labelClaim(x, y), {
|
||||
clearance: {
|
||||
body: statePadding,
|
||||
label: { x: 1, y: 0 },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
let x = plan.label.x
|
||||
@@ -672,7 +846,7 @@ function placeStateTransitionLabels(
|
||||
}
|
||||
}
|
||||
|
||||
placedLabels.push(labelRect({ ...plan.label, x, y }, width))
|
||||
space = space.add(labelClaim(x, y))
|
||||
return { ...plan, label: { ...plan.label, x, y } }
|
||||
})
|
||||
}
|
||||
@@ -703,6 +877,7 @@ export function createStateTransitionJunctionPlans(
|
||||
bounds: ReadonlyMap<string, BoxBounds>,
|
||||
renderPlans: readonly StateTransitionRenderPlan[],
|
||||
): StateTransitionJunctionPlan[] {
|
||||
const renderPlanByTransition = new Map(renderPlans.map((plan) => [plan.route.transition, plan]))
|
||||
return diagram.states.flatMap((state): StateTransitionJunctionPlan[] => {
|
||||
const kind =
|
||||
state.kind === "choice" ? "choice" : isHiddenCompositeMarker(state) ? "hidden-composite-marker" : undefined
|
||||
@@ -713,7 +888,7 @@ export function createStateTransitionJunctionPlans(
|
||||
const connections = new Set<DiagramDirection>()
|
||||
const transitions: StateVisibleTransition[] = []
|
||||
for (const transition of diagram.transitions) {
|
||||
const renderPlan = renderPlans.find((plan) => plan.route.transition === transition)
|
||||
const renderPlan = renderPlanByTransition.get(transition)
|
||||
let connected = false
|
||||
if (transition.to === state.id) {
|
||||
const junction = renderPlan?.path.at(-1)
|
||||
|
||||
@@ -20,6 +20,43 @@ describe("prepareVisibleStateDiagram", () => {
|
||||
expect(visible.states.some((state) => state.id === "Authenticated.__start")).toBe(false)
|
||||
expect(visible.states.some((state) => state.id === "Authenticated.__end")).toBe(false)
|
||||
expect(entry).toMatchObject({ from: "__start", to: "Idle", label: "login" })
|
||||
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save" })
|
||||
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save<br/>logout" })
|
||||
})
|
||||
|
||||
test("collapses nested composite entry chains without retaining scoped markers", () => {
|
||||
const visible = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
state Session {
|
||||
[*] --> Open
|
||||
state Open {
|
||||
[*] --> Clean
|
||||
Clean --> Dirty: edit
|
||||
Dirty --> Clean: save
|
||||
}
|
||||
Open --> [*]: close
|
||||
}
|
||||
[*] --> Session
|
||||
Session --> [*]`),
|
||||
)
|
||||
|
||||
expect(visible.states.map((state) => state.id)).toEqual(["Clean", "Dirty", "__start", "__end"])
|
||||
expect(visible.transitions).toContainEqual({ from: "__start", to: "Clean", label: "" })
|
||||
expect(visible.transitions.some((transition) => transition.from.includes(".__start"))).toBe(false)
|
||||
expect(visible.transitions.some((transition) => transition.to.includes(".__start"))).toBe(false)
|
||||
})
|
||||
|
||||
test("preserves labels on both sides of collapsed composite markers", () => {
|
||||
const visible = prepareVisibleStateDiagram(
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
[*] --> Session: open session
|
||||
state Session {
|
||||
[*] --> Ready: initialize
|
||||
Ready --> [*]: finalize
|
||||
}
|
||||
Session --> [*]: close session`),
|
||||
)
|
||||
|
||||
expect(visible.transitions).toContainEqual({ from: "__start", to: "Ready", label: "open session<br/>initialize" })
|
||||
expect(visible.transitions).toContainEqual({ from: "Ready", to: "__end", label: "finalize<br/>close session" })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ export function isHiddenCompositeMarker(state: StateDiagramState | undefined): b
|
||||
}
|
||||
|
||||
function composeTransitionLabel(incoming: StateDiagramTransition, outgoing: StateDiagramTransition): string {
|
||||
return incoming.label || outgoing.label
|
||||
return [incoming.label, outgoing.label].filter(Boolean).join("<br/>")
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitionsOnce(
|
||||
@@ -23,33 +23,28 @@ function collapseHiddenCompositeMarkerTransitionsOnce(
|
||||
)
|
||||
if (hiddenMarkers.size === 0) return { transitions: [...transitions], changed: false }
|
||||
|
||||
const skipped = new Set<StateVisibleTransition>()
|
||||
const collapsed: StateVisibleTransition[] = []
|
||||
let changed = false
|
||||
|
||||
for (const markerId of hiddenMarkers) {
|
||||
const incoming = transitions.filter((transition) => transition.to === markerId && transition.from !== markerId)
|
||||
const outgoing = transitions.filter((transition) => transition.from === markerId && transition.to !== markerId)
|
||||
if (incoming.length === 0 || outgoing.length === 0) continue
|
||||
|
||||
changed = true
|
||||
for (const incomingTransition of incoming) {
|
||||
skipped.add(incomingTransition)
|
||||
for (const outgoingTransition of outgoing) {
|
||||
skipped.add(outgoingTransition)
|
||||
collapsed.push({
|
||||
from: incomingTransition.from,
|
||||
to: outgoingTransition.to,
|
||||
label: composeTransitionLabel(incomingTransition, outgoingTransition),
|
||||
})
|
||||
}
|
||||
const skipped = new Set([...incoming, ...outgoing])
|
||||
return {
|
||||
transitions: [
|
||||
...transitions.filter((transition) => !skipped.has(transition)),
|
||||
...incoming.flatMap((incomingTransition) =>
|
||||
outgoing.map((outgoingTransition) => ({
|
||||
from: incomingTransition.from,
|
||||
to: outgoingTransition.to,
|
||||
label: composeTransitionLabel(incomingTransition, outgoingTransition),
|
||||
})),
|
||||
),
|
||||
],
|
||||
changed: true,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
transitions: [...transitions.filter((transition) => !skipped.has(transition)), ...collapsed],
|
||||
changed,
|
||||
}
|
||||
return { transitions: [...transitions], changed: false }
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitions(diagram: StateDiagram): StateVisibleTransition[] {
|
||||
|
||||
@@ -26,6 +26,21 @@ describe("parser diagnostics", () => {
|
||||
).toThrow('Unsupported syntax in flowchart diagram at line 3: "A --o B"')
|
||||
})
|
||||
|
||||
test("does not partially parse unsupported flowchart syntax", () => {
|
||||
for (const statement of ["A & B --> C", "A((Start)) --> B", "A-->B; B-->C"]) {
|
||||
expect(() => parseMermaidFlowchartDiagram(`flowchart LR\n ${statement}`)).toThrow(MermaidSyntaxError)
|
||||
}
|
||||
})
|
||||
|
||||
test("does not treat arrows inside flowchart node labels as edges", () => {
|
||||
const diagram = parseMermaidFlowchartDiagram(`flowchart LR
|
||||
A["send --> receive"] --> B`)
|
||||
|
||||
expect(diagram.nodes.map((node) => node.id)).toEqual(["A", "B"])
|
||||
expect(diagram.nodes[0]?.label).toBe("send --> receive")
|
||||
expect(diagram.edges).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("exposes structured syntax errors through top-level rendering", () => {
|
||||
try {
|
||||
renderSequenceDiagram(`sequenceDiagram
|
||||
@@ -41,6 +56,12 @@ describe("parser diagnostics", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("rejects unsupported bidirectional sequence arrows without phantom participants", () => {
|
||||
for (const message of ["A<<->>B: hello", "A<<-->>B: hello"]) {
|
||||
expect(() => parseMermaidSequenceDiagram(`sequenceDiagram\n ${message}`)).toThrow(MermaidSyntaxError)
|
||||
}
|
||||
})
|
||||
|
||||
test("reports unclosed state constructs at their opening line", () => {
|
||||
expect(() =>
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
@@ -55,6 +76,17 @@ describe("parser diagnostics", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects unsupported composite-local state directions", () => {
|
||||
expect(() =>
|
||||
parseMermaidStateDiagram(`stateDiagram-v2
|
||||
direction LR
|
||||
state Parent {
|
||||
direction TB
|
||||
A --> B
|
||||
}`),
|
||||
).toThrow("Composite-local direction is not supported")
|
||||
})
|
||||
|
||||
test("reports malformed sequence block endings", () => {
|
||||
expect(() =>
|
||||
parseMermaidSequenceDiagram(`sequenceDiagram
|
||||
|
||||
Reference in New Issue
Block a user