mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-09 02:49:57 -04:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5291d5ff5 | |||
| ea1c3b9a97 | |||
| e7bd4f17c0 |
@@ -577,7 +577,6 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { AgentSideConnection, PermissionOption, ToolCallContent, ToolCallLocation } from "@agentclientprotocol/sdk"
|
||||
import type { AgentSideConnection, PermissionOption, ToolCallLocation } from "@agentclientprotocol/sdk"
|
||||
import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/promise"
|
||||
import { Patch } from "@opencode-ai/util/patch"
|
||||
import { Result } from "effect"
|
||||
import { isAbsolute, resolve } from "node:path"
|
||||
import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool"
|
||||
|
||||
@@ -28,9 +26,8 @@ export async function replyPermission(input: {
|
||||
}) {
|
||||
const toolName = input.tool?.name ?? input.event.data.action
|
||||
const toolInput = { ...input.event.data.metadata, ...input.tool?.input }
|
||||
const previews = await permissionPreviews(toolName, toolInput, input.cwd)
|
||||
const toolCallID = input.event.data.source?.id ?? input.event.data.id
|
||||
const title = permissionTitle(toolName, toolInput, previews)
|
||||
const title = permissionTitle(toolName, toolInput, input.event.data.resources)
|
||||
const result = await input.connection
|
||||
.requestPermission({
|
||||
sessionId: input.clientSessionID ?? input.sessionID,
|
||||
@@ -44,8 +41,7 @@ export async function replyPermission(input: {
|
||||
},
|
||||
cwd: input.cwd,
|
||||
}),
|
||||
locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd, previews),
|
||||
...(previews.length > 0 ? { content: previews } : {}),
|
||||
locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd),
|
||||
},
|
||||
options,
|
||||
})
|
||||
@@ -94,54 +90,8 @@ export async function syncEditedFiles(input: {
|
||||
)
|
||||
}
|
||||
|
||||
async function permissionPreviews(toolName: string, input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
|
||||
const tool = toolName.toLocaleLowerCase()
|
||||
if (tool === "patch" || tool === "apply_patch") return patchPreviews(input, cwd)
|
||||
const path = filePath(input)
|
||||
if (!path) return []
|
||||
const oldText = await readText(path, cwd)
|
||||
if (tool === "write") {
|
||||
const content = stringValue(input.content)
|
||||
return content === undefined ? [] : [{ type: "diff", path, oldText, newText: content }]
|
||||
}
|
||||
if (tool !== "edit") return []
|
||||
const oldString = stringValue(input.oldString)
|
||||
const newString = stringValue(input.newString)
|
||||
if (oldString === undefined || newString === undefined) return []
|
||||
const newText =
|
||||
input.replaceAll === true ? oldText.replaceAll(oldString, newString) : oldText.replace(oldString, newString)
|
||||
return [{ type: "diff", path, oldText, newText }]
|
||||
}
|
||||
|
||||
async function patchPreviews(input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
|
||||
const patchText = stringValue(input.patchText)
|
||||
if (!patchText) return []
|
||||
try {
|
||||
const parsed = Patch.parse(patchText)
|
||||
if (Result.isFailure(parsed)) return []
|
||||
return await Promise.all(
|
||||
parsed.success.map(async (hunk): Promise<ToolCallContent> => {
|
||||
const oldText = hunk.type === "add" ? "" : await readText(hunk.path, cwd)
|
||||
if (hunk.type === "add") {
|
||||
const newText = hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
|
||||
return { type: "diff", path: hunk.path, oldText, newText }
|
||||
}
|
||||
if (hunk.type === "delete") return { type: "diff", path: hunk.path, oldText, newText: "" }
|
||||
return {
|
||||
type: "diff",
|
||||
path: hunk.movePath ?? hunk.path,
|
||||
oldText,
|
||||
newText: Patch.derive(hunk.path, hunk.chunks, oldText).content,
|
||||
}
|
||||
}),
|
||||
)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyArray<ToolCallContent>) {
|
||||
if (previews.length > 1) return `${previews.length} files`
|
||||
function permissionTitle(toolName: string, input: ToolInput, resources: ReadonlyArray<string>) {
|
||||
if (toToolKind(toolName) === "edit" && resources.length > 1) return `${resources.length} files`
|
||||
switch (toolName.toLocaleLowerCase()) {
|
||||
case "external_directory":
|
||||
return stringValue(input.description) ?? stringValue(input.command) ?? stringValue(input.parentDir)
|
||||
@@ -157,7 +107,7 @@ function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyA
|
||||
case "write":
|
||||
case "patch":
|
||||
case "apply_patch":
|
||||
return filePath(input) ?? (previews[0]?.type === "diff" ? previews[0].path : undefined)
|
||||
return filePath(input)
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
@@ -168,21 +118,12 @@ function permissionLocations(
|
||||
input: ToolInput,
|
||||
resources: ReadonlyArray<string>,
|
||||
cwd: string,
|
||||
previews: ReadonlyArray<ToolCallContent>,
|
||||
): ToolCallLocation[] {
|
||||
const paths = previews.flatMap((preview) => (preview.type === "diff" ? [preview.path] : []))
|
||||
if (paths.length > 0) return [...new Set(paths)].map((path) => ({ path }))
|
||||
const locations = toLocations(toolName, input, cwd)
|
||||
if (locations.length > 0) return locations
|
||||
return resources.filter((resource) => resource !== "*").map((path) => ({ path }))
|
||||
}
|
||||
|
||||
function readText(path: string, cwd: string) {
|
||||
return Bun.file(resolvePath(path, cwd))
|
||||
.text()
|
||||
.catch(() => "")
|
||||
}
|
||||
|
||||
function filePath(input: ToolInput) {
|
||||
return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath)
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ describe("acp permission behavior", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("previews edits during approval and syncs the completed file", async () => {
|
||||
test("authorizes edit resources and syncs the completed file", async () => {
|
||||
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-permission-"))
|
||||
const file = path.join(cwd, "file.ts")
|
||||
await fs.writeFile(file, "before")
|
||||
@@ -240,6 +240,7 @@ describe("acp permission behavior", () => {
|
||||
send(
|
||||
permissionAsked("ses_edit", "perm_edit", {
|
||||
action: "edit",
|
||||
resources: ["file.ts"],
|
||||
source: { type: "tool", messageID: "msg_edit", id: "call_edit" },
|
||||
}),
|
||||
)
|
||||
@@ -278,8 +279,8 @@ describe("acp permission behavior", () => {
|
||||
title: "file.ts",
|
||||
kind: "edit",
|
||||
locations: [{ path: "file.ts" }],
|
||||
content: [{ type: "diff", path: "file.ts", oldText: "before", newText: "after" }],
|
||||
})
|
||||
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
|
||||
expect(writes).toEqual([{ sessionId: "ses_edit", path: file, content: "after" }])
|
||||
} finally {
|
||||
await fixture.stop()
|
||||
@@ -287,7 +288,7 @@ describe("acp permission behavior", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("previews and syncs each file in a patch", async () => {
|
||||
test("authorizes and syncs each file in a patch", async () => {
|
||||
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-acp-patch-permission-"))
|
||||
await Promise.all([
|
||||
fs.writeFile(path.join(cwd, "first.ts"), "one\n"),
|
||||
@@ -330,6 +331,7 @@ describe("acp permission behavior", () => {
|
||||
send(
|
||||
permissionAsked("ses_patch", "perm_patch", {
|
||||
action: "edit",
|
||||
resources: ["first.ts", "second.ts"],
|
||||
source: { type: "tool", messageID: "msg_patch", id: "call_patch" },
|
||||
}),
|
||||
)
|
||||
@@ -371,11 +373,8 @@ describe("acp permission behavior", () => {
|
||||
title: "2 files",
|
||||
kind: "edit",
|
||||
locations: [{ path: "first.ts" }, { path: "second.ts" }],
|
||||
content: [
|
||||
{ type: "diff", path: "first.ts", oldText: "one\n", newText: "two\n" },
|
||||
{ type: "diff", path: "second.ts", oldText: "alpha\n", newText: "beta\n" },
|
||||
],
|
||||
})
|
||||
expect(permissionRequests[0]?.toolCall.content).toBeUndefined()
|
||||
expect(writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
|
||||
{ sessionId: "ses_patch", path: path.join(cwd, "first.ts"), content: "two\n" },
|
||||
{ sessionId: "ses_patch", path: path.join(cwd, "second.ts"), content: "beta\n" },
|
||||
@@ -556,6 +555,7 @@ function permissionAsked(
|
||||
id: string,
|
||||
input: {
|
||||
readonly action?: string
|
||||
readonly resources?: ReadonlyArray<string>
|
||||
readonly metadata?: Record<string, unknown>
|
||||
readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string }
|
||||
} = {},
|
||||
@@ -564,7 +564,7 @@ function permissionAsked(
|
||||
id,
|
||||
sessionID,
|
||||
action: input.action ?? "shell",
|
||||
resources: ["*"],
|
||||
resources: [...(input.resources ?? ["*"])],
|
||||
metadata: input.metadata ?? { command: "printf hello" },
|
||||
...(input.source ? { source: input.source } : {}),
|
||||
})
|
||||
|
||||
@@ -48,15 +48,13 @@ export const readText = Effect.fn("FileMutation.readText")(function* (files: Fil
|
||||
return Bom.decodeBytes((yield* files.read(target)).bytes)
|
||||
})
|
||||
|
||||
export const syncTextBom = Effect.fn("FileMutation.syncTextBom")(function* (
|
||||
files: Files,
|
||||
target: string,
|
||||
bom: boolean,
|
||||
) {
|
||||
const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom)
|
||||
if (synced.bytes) yield* files.write(target, synced.bytes)
|
||||
return synced.text
|
||||
})
|
||||
export const syncTextBom = Effect.fn("FileMutation.syncTextBom")((files: Files, target: string, bom: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
const synced = Bom.syncBytes((yield* files.read(target)).bytes, bom)
|
||||
if (synced.bytes) yield* files.write(target, synced.bytes)
|
||||
return synced.text
|
||||
}).pipe(Effect.uninterruptible),
|
||||
)
|
||||
|
||||
/** Share transaction locks across Location graphs that address the same file. */
|
||||
const transactionLocks = KeyedMutex.makeUnsafe<string>()
|
||||
@@ -70,15 +68,10 @@ const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* Environment.Service
|
||||
const locks = KeyedMutex.makeUnsafe<string>()
|
||||
const withLock: Interface["withLock"] = (targets) => (effect) =>
|
||||
[...new Set(targets.map(FSUtil.resolve))]
|
||||
.sort()
|
||||
.reduceRight((result, target) => transactionLocks.withLock(target)(result), effect)
|
||||
const withTargetLock =
|
||||
(target: Target) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
locks.withLock(target.absolute)(Effect.uninterruptible(effect))
|
||||
|
||||
const writeResult = (target: Target, existed: boolean): WriteResult => ({
|
||||
operation: "write",
|
||||
@@ -88,36 +81,32 @@ const layer = Layer.effect(
|
||||
})
|
||||
|
||||
const write = Effect.fn("FileMutation.write")((input: WriteInput) =>
|
||||
withTargetLock(input.target)(
|
||||
Effect.gen(function* () {
|
||||
const existed = yield* environment.files.stat(input.target.absolute).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)),
|
||||
)
|
||||
yield* environment.files.write(
|
||||
input.target.absolute,
|
||||
typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content,
|
||||
)
|
||||
return writeResult(input.target, existed)
|
||||
}),
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
const existed = yield* environment.files.stat(input.target.absolute).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTag("Environment.NotFound", () => Effect.succeed(false)),
|
||||
)
|
||||
yield* environment.files.write(
|
||||
input.target.absolute,
|
||||
typeof input.content === "string" ? new TextEncoder().encode(input.content) : input.content,
|
||||
)
|
||||
return writeResult(input.target, existed)
|
||||
}).pipe(Effect.uninterruptible),
|
||||
)
|
||||
|
||||
const writeTextPreservingBom = Effect.fn("FileMutation.writeTextPreservingBom")((input: TextWriteInput) =>
|
||||
withTargetLock(input.target)(
|
||||
Effect.gen(function* () {
|
||||
const next = Bom.split(input.content)
|
||||
const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe(
|
||||
Effect.map((result) => result.bytes),
|
||||
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
|
||||
)
|
||||
yield* environment.files.write(
|
||||
input.target.absolute,
|
||||
new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)),
|
||||
)
|
||||
return writeResult(input.target, current !== undefined)
|
||||
}),
|
||||
),
|
||||
Effect.gen(function* () {
|
||||
const next = Bom.split(input.content)
|
||||
const current = yield* environment.files.read(input.target.absolute, { offset: 0, length: 3 }).pipe(
|
||||
Effect.map((result) => result.bytes),
|
||||
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
|
||||
)
|
||||
yield* environment.files.write(
|
||||
input.target.absolute,
|
||||
new TextEncoder().encode(Bom.join(next.text, Boolean(current && Bom.has(current)) || next.bom)),
|
||||
)
|
||||
return writeResult(input.target, current !== undefined)
|
||||
}).pipe(Effect.uninterruptible),
|
||||
)
|
||||
|
||||
return Service.of({ withLock, write, writeTextPreservingBom })
|
||||
|
||||
@@ -11,11 +11,9 @@ import { ToolFailure } from "@opencode-ai/ai"
|
||||
import { FileDiff } from "@opencode-ai/schema/file-diff"
|
||||
import { Bom } from "@opencode-ai/util/bom"
|
||||
import { Effect, Schema } from "effect"
|
||||
import path from "path"
|
||||
import { Environment } from "../../environment"
|
||||
import { FileMutation } from "../../file-mutation"
|
||||
import { Formatter } from "../../formatter"
|
||||
import { Location } from "../../location"
|
||||
import { LocationMutation } from "../../location-mutation"
|
||||
import { Permission } from "../../permission"
|
||||
import { fileDiff } from "./file-diff"
|
||||
@@ -87,7 +85,7 @@ const findLineOccurrences = (content: string, search: string) => {
|
||||
if (
|
||||
!actual.every(
|
||||
(item, lineIndex) =>
|
||||
normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex]!.trimEnd()),
|
||||
normalizeForMatch(item.text.trimEnd()) === normalizeForMatch(expected[lineIndex].trimEnd()),
|
||||
)
|
||||
)
|
||||
return []
|
||||
@@ -114,7 +112,6 @@ export const Plugin = {
|
||||
const fileMutation = yield* FileMutation.Service
|
||||
const environment = yield* Environment.Service
|
||||
const formatter = yield* Formatter.Service
|
||||
const location = yield* Location.Service
|
||||
const permission = yield* Permission.Service
|
||||
|
||||
yield* ctx.tool
|
||||
@@ -154,72 +151,69 @@ export const Plugin = {
|
||||
source: permissionSource,
|
||||
})
|
||||
}
|
||||
|
||||
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.catchTag("Environment.NotFound", () =>
|
||||
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })),
|
||||
),
|
||||
Effect.catchTag("Environment.WrongKind", (error) =>
|
||||
error.actual === "directory"
|
||||
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` }))
|
||||
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })),
|
||||
),
|
||||
)
|
||||
const source = original.text
|
||||
const ending = source.includes(crlf) ? crlf : "\n"
|
||||
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending)
|
||||
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending)
|
||||
const exact = findOccurrences(source, oldString)
|
||||
// These one-to-one mappings preserve offsets into the original source.
|
||||
const unicode =
|
||||
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString))
|
||||
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString)
|
||||
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing
|
||||
const replacements = matches.length
|
||||
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
|
||||
.toReversed()
|
||||
.reduce(
|
||||
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
|
||||
source,
|
||||
)
|
||||
const preview =
|
||||
replacements > 0 && (replacements === 1 || input.replaceAll === true)
|
||||
? fileDiff(target.resource, source, replaced)
|
||||
: undefined
|
||||
yield* permission.assert({
|
||||
action: "edit",
|
||||
resources: [target.resource],
|
||||
save: ["*"],
|
||||
metadata: preview ? { files: [preview] } : undefined,
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source: permissionSource,
|
||||
})
|
||||
if (replacements === 0) {
|
||||
return yield* new ToolFailure({
|
||||
message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
|
||||
})
|
||||
}
|
||||
if (replacements > 1 && input.replaceAll !== true) {
|
||||
return yield* new ToolFailure({
|
||||
message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
|
||||
})
|
||||
}
|
||||
const replacementBom = replaced.startsWith("\uFEFF")
|
||||
const result = yield* fileMutation.write({
|
||||
target,
|
||||
content: Bom.join(replaced, original.bom || replacementBom),
|
||||
})
|
||||
const bom = original.bom || replacementBom
|
||||
const formatted = (yield* formatter.file(target.absolute))
|
||||
? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
|
||||
: (yield* FileMutation.readText(environment.files, target.absolute)).text
|
||||
return {
|
||||
files: [fileDiff(result.resource, source, formatted)],
|
||||
replacements,
|
||||
} satisfies Output
|
||||
return yield* fileMutation.withLock([target.absolute])(
|
||||
Effect.gen(function* () {
|
||||
const original = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.catchTag("Environment.NotFound", () =>
|
||||
Effect.fail(new ToolFailure({ message: `File not found: ${input.path}` })),
|
||||
),
|
||||
Effect.catchTag("Environment.WrongKind", (error) =>
|
||||
error.actual === "directory"
|
||||
? Effect.fail(new ToolFailure({ message: `Path is a directory, not a file: ${input.path}` }))
|
||||
: Effect.fail(new ToolFailure({ message: `Unable to edit ${input.path}`, error })),
|
||||
),
|
||||
)
|
||||
const source = original.text
|
||||
const ending = source.includes(crlf) ? crlf : "\n"
|
||||
const oldString = input.oldString.replaceAll(crlf, "\n").replaceAll("\n", ending)
|
||||
const newString = input.newString.replaceAll(crlf, "\n").replaceAll("\n", ending)
|
||||
const exact = findOccurrences(source, oldString)
|
||||
// These one-to-one mappings preserve offsets into the original source.
|
||||
const unicode =
|
||||
exact.length > 0 ? [] : findOccurrences(normalizeForMatch(source), normalizeForMatch(oldString))
|
||||
const trailing = exact.length > 0 || unicode.length > 0 ? [] : findLineOccurrences(source, oldString)
|
||||
const matches = exact.length > 0 ? exact : unicode.length > 0 ? unicode : trailing
|
||||
const replacements = matches.length
|
||||
const replaced = (input.replaceAll === true ? matches : matches.slice(0, 1))
|
||||
.toReversed()
|
||||
.reduce(
|
||||
(content, match) => `${content.slice(0, match.start)}${newString}${content.slice(match.end)}`,
|
||||
source,
|
||||
)
|
||||
if (replacements === 0) {
|
||||
return yield* new ToolFailure({
|
||||
message: `Could not find oldString in ${input.path}. It must match exactly, including whitespace and indentation.`,
|
||||
})
|
||||
}
|
||||
if (replacements > 1 && input.replaceAll !== true) {
|
||||
return yield* new ToolFailure({
|
||||
message: `Found ${replacements} matches for oldString, but expected exactly one. Add more surrounding context to make oldString unique, or set replaceAll to true to replace every occurrence.`,
|
||||
})
|
||||
}
|
||||
const replacementBom = replaced.startsWith("\uFEFF")
|
||||
const result = yield* fileMutation.write({
|
||||
target,
|
||||
content: Bom.join(replaced, original.bom || replacementBom),
|
||||
})
|
||||
const bom = original.bom || replacementBom
|
||||
const formatted = (yield* formatter.file(target.absolute))
|
||||
? yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
|
||||
: (yield* FileMutation.readText(environment.files, target.absolute)).text
|
||||
return {
|
||||
files: [fileDiff(result.resource, source, formatted)],
|
||||
replacements,
|
||||
} satisfies Output
|
||||
}),
|
||||
)
|
||||
}).pipe(
|
||||
fileMutation.withLock([path.resolve(location.directory, input.path)]),
|
||||
Effect.map((output) => ({
|
||||
output,
|
||||
content: `Edited ${output.files[0]?.file} (${output.replacements} replacement${output.replacements === 1 ? "" : "s"})`,
|
||||
|
||||
@@ -3,7 +3,7 @@ export * as PatchTool from "./patch"
|
||||
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { ToolFailure } from "@opencode-ai/ai"
|
||||
import { FileDiff } from "@opencode-ai/schema/file-diff"
|
||||
import { Effect, Result, Schema } from "effect"
|
||||
import { Effect, Schema } from "effect"
|
||||
import path from "path"
|
||||
import { Bom } from "@opencode-ai/util/bom"
|
||||
import { FSUtil } from "@opencode-ai/util/fs-util"
|
||||
@@ -93,12 +93,6 @@ export const Plugin = {
|
||||
execute: (input, context) => {
|
||||
const applied: Array<typeof Applied.Type> = []
|
||||
const parsed = Patch.parse(input.patchText)
|
||||
const lockTargets = Result.isSuccess(parsed)
|
||||
? parsed.success.flatMap((hunk) => [
|
||||
path.resolve(location.directory, hunk.path),
|
||||
...(hunk.type === "update" && hunk.movePath ? [path.resolve(location.directory, hunk.movePath)] : []),
|
||||
])
|
||||
: []
|
||||
const fail = (operation: string, error: unknown) => {
|
||||
const completed = applied.map((item) => item.resource).join(", ")
|
||||
return new ToolFailure({
|
||||
@@ -118,202 +112,196 @@ export const Plugin = {
|
||||
if (hunks.length === 0) {
|
||||
return yield* new ToolFailure({ message: "patch rejected: empty patch" })
|
||||
}
|
||||
const prepared: Prepared[] = []
|
||||
const targets: Target[] = []
|
||||
const updates = new Map<string, string>()
|
||||
for (const hunk of hunks) {
|
||||
yield* Effect.gen(function* () {
|
||||
const target = resolveTarget(location, hunk.path)
|
||||
targets.push(target)
|
||||
if (target.externalDirectory) {
|
||||
yield* permission.assert({
|
||||
action: "external_directory",
|
||||
resources: [target.externalDirectory.resource],
|
||||
save: [target.externalDirectory.resource],
|
||||
metadata: {
|
||||
filepath: target.absolute,
|
||||
parentDir: target.externalDirectory.directory,
|
||||
},
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
}
|
||||
if (hunk.type === "add") {
|
||||
const content =
|
||||
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
|
||||
prepared.push({
|
||||
...hunk,
|
||||
target,
|
||||
content,
|
||||
before: "",
|
||||
after: Bom.split(content).text,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (hunk.type === "delete") {
|
||||
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolFailure({
|
||||
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
prepared.push({ ...hunk, target, before: content.text, after: "" })
|
||||
return
|
||||
}
|
||||
const previous = updates.get(target.absolute)
|
||||
const original =
|
||||
previous ??
|
||||
(yield* Effect.gen(function* () {
|
||||
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolFailure({
|
||||
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
return Bom.join(content.text, content.bom)
|
||||
}))
|
||||
const before = Bom.split(original).text
|
||||
const update = yield* Effect.try({
|
||||
try: () => Patch.derive(hunk.path, hunk.chunks, original),
|
||||
catch: (error) => new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
|
||||
const plans = hunks.map((hunk) => ({
|
||||
hunk,
|
||||
target: resolveTarget(location, hunk.path),
|
||||
moveTarget:
|
||||
hunk.type === "update" && hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined,
|
||||
}))
|
||||
const targets = plans.flatMap((plan) => [plan.target, ...(plan.moveTarget ? [plan.moveTarget] : [])])
|
||||
for (const target of targets) {
|
||||
if (target.externalDirectory) {
|
||||
yield* permission.assert({
|
||||
action: "external_directory",
|
||||
resources: [target.externalDirectory.resource],
|
||||
save: [target.externalDirectory.resource],
|
||||
metadata: {
|
||||
filepath: target.absolute,
|
||||
parentDir: target.externalDirectory.directory,
|
||||
},
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
const moveTarget = hunk.movePath ? resolveTarget(location, hunk.movePath) : undefined
|
||||
if (moveTarget) targets.push(moveTarget)
|
||||
if (moveTarget?.externalDirectory) {
|
||||
yield* permission.assert({
|
||||
action: "external_directory",
|
||||
resources: [moveTarget.externalDirectory.resource],
|
||||
save: [moveTarget.externalDirectory.resource],
|
||||
metadata: {
|
||||
filepath: moveTarget.absolute,
|
||||
parentDir: moveTarget.externalDirectory.directory,
|
||||
},
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
}
|
||||
prepared.push({
|
||||
...hunk,
|
||||
target,
|
||||
content: Patch.joinBom(update.content, update.bom),
|
||||
before,
|
||||
after: update.content,
|
||||
moveTarget,
|
||||
})
|
||||
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom))
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error instanceof ToolFailure
|
||||
? error
|
||||
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const patchFiles = prepared.map((change) => patchFile(change))
|
||||
yield* permission.assert({
|
||||
action: "edit",
|
||||
resources: [...new Set(targets.map((target) => target.resource))],
|
||||
save: ["*"],
|
||||
metadata: {
|
||||
filepath: targets.map((target) => target.resource).join(", "),
|
||||
diff: patchFiles.map((file) => `${file.patch}\n`).join(""),
|
||||
files: patchFiles,
|
||||
},
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
|
||||
yield* Effect.forEach(
|
||||
prepared,
|
||||
(change) =>
|
||||
Effect.gen(function* () {
|
||||
if (change.type === "add") {
|
||||
yield* environment.files
|
||||
.write(change.target.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (change.type === "delete") {
|
||||
yield* environment.files
|
||||
.remove(change.target.absolute)
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (change.moveTarget) {
|
||||
const moveTarget = change.moveTarget
|
||||
yield* environment.files
|
||||
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
|
||||
yield* environment.files
|
||||
.remove(change.target.absolute)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
fail(`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`, error),
|
||||
return yield* mutation.withLock(targets.map((target) => target.absolute))(
|
||||
Effect.gen(function* () {
|
||||
const prepared: Prepared[] = []
|
||||
const updates = new Map<string, string>()
|
||||
for (const plan of plans) {
|
||||
const hunk = plan.hunk
|
||||
const target = plan.target
|
||||
yield* Effect.gen(function* () {
|
||||
if (hunk.type === "add") {
|
||||
const content =
|
||||
hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
|
||||
prepared.push({
|
||||
...hunk,
|
||||
target,
|
||||
content,
|
||||
before: "",
|
||||
after: Bom.split(content).text,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (hunk.type === "delete") {
|
||||
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolFailure({
|
||||
message: `patch verification failed: Failed to delete ${target.resource}: ${errorMessage(error)}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.moveTarget.resource,
|
||||
target: change.moveTarget.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
yield* environment.files
|
||||
.write(change.target.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
}),
|
||||
{ discard: true },
|
||||
)
|
||||
const formatted = new Map<string, string>()
|
||||
yield* Effect.forEach(
|
||||
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
|
||||
(target) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* FileMutation.readText(environment.files, target).pipe(
|
||||
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
|
||||
)
|
||||
formatted.set(
|
||||
target,
|
||||
(yield* formatter.file(target))
|
||||
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
|
||||
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
|
||||
prepared.push({ ...hunk, target, before: content.text, after: "" })
|
||||
return
|
||||
}
|
||||
const previous = updates.get(target.absolute)
|
||||
const original =
|
||||
previous ??
|
||||
(yield* Effect.gen(function* () {
|
||||
const content = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolFailure({
|
||||
message: `patch verification failed: Failed to read file to update ${target.absolute}: ${errorMessage(error)}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: current.text,
|
||||
return Bom.join(content.text, content.bom)
|
||||
}))
|
||||
const before = Bom.split(original).text
|
||||
const update = yield* Effect.try({
|
||||
try: () => Patch.derive(hunk.path, hunk.chunks, original),
|
||||
catch: (error) =>
|
||||
new ToolFailure({ message: `patch verification failed: ${errorMessage(error)}` }),
|
||||
})
|
||||
const moveTarget = plan.moveTarget
|
||||
prepared.push({
|
||||
...hunk,
|
||||
target,
|
||||
content: Patch.joinBom(update.content, update.bom),
|
||||
before,
|
||||
after: update.content,
|
||||
moveTarget,
|
||||
})
|
||||
if (!moveTarget) updates.set(target.absolute, Patch.joinBom(update.content, update.bom))
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
error instanceof ToolFailure
|
||||
? error
|
||||
: new ToolFailure({ message: `Unable to prepare patch at ${hunk.path}`, error }),
|
||||
),
|
||||
)
|
||||
}),
|
||||
{ discard: true },
|
||||
}
|
||||
|
||||
yield* Effect.forEach(
|
||||
prepared,
|
||||
(change) =>
|
||||
Effect.gen(function* () {
|
||||
if (change.type === "add") {
|
||||
yield* environment.files
|
||||
.write(change.target.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (change.type === "delete") {
|
||||
yield* environment.files
|
||||
.remove(change.target.absolute)
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to delete ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
if (change.moveTarget) {
|
||||
const moveTarget = change.moveTarget
|
||||
yield* environment.files
|
||||
.write(moveTarget.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${moveTarget.resource}`, error)))
|
||||
yield* environment.files
|
||||
.remove(change.target.absolute)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
fail(
|
||||
`Wrote ${moveTarget.resource} but failed to remove ${change.target.resource}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
)
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.moveTarget.resource,
|
||||
target: change.moveTarget.absolute,
|
||||
})
|
||||
return
|
||||
}
|
||||
yield* environment.files
|
||||
.write(change.target.absolute, new TextEncoder().encode(change.content))
|
||||
.pipe(Effect.mapError((error) => fail(`Failed to write ${change.target.resource}`, error)))
|
||||
applied.push({
|
||||
type: change.type,
|
||||
resource: change.target.resource,
|
||||
target: change.target.absolute,
|
||||
})
|
||||
}),
|
||||
{ discard: true },
|
||||
)
|
||||
const formatted = new Map<string, string>()
|
||||
yield* Effect.forEach(
|
||||
[...new Set(applied.filter((item) => item.type !== "delete").map((item) => item.target))],
|
||||
(target) =>
|
||||
Effect.gen(function* () {
|
||||
const current = yield* FileMutation.readText(environment.files, target).pipe(
|
||||
Effect.mapError((error) => fail(`Failed to read ${target}`, error)),
|
||||
)
|
||||
formatted.set(
|
||||
target,
|
||||
(yield* formatter.file(target))
|
||||
? yield* FileMutation.syncTextBom(environment.files, target, current.bom).pipe(
|
||||
Effect.mapError((error) => fail(`Failed to sync ${target}`, error)),
|
||||
)
|
||||
: current.text,
|
||||
)
|
||||
}),
|
||||
{ discard: true },
|
||||
)
|
||||
const files = yield* Effect.forEach(prepared, (change) => {
|
||||
if (change.type === "delete") return Effect.succeed(patchFile(change))
|
||||
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
|
||||
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
|
||||
})
|
||||
return { applied, files }
|
||||
}),
|
||||
)
|
||||
const files = yield* Effect.forEach(prepared, (change) => {
|
||||
if (change.type === "delete") return Effect.succeed(patchFile(change))
|
||||
const target = change.type === "update" && change.moveTarget ? change.moveTarget : change.target
|
||||
return Effect.succeed(patchFile(change, formatted.get(target.absolute)))
|
||||
})
|
||||
return { applied, files }
|
||||
}).pipe(
|
||||
mutation.withLock(lockTargets),
|
||||
Effect.map((output) => ({
|
||||
output,
|
||||
content: toModelOutput(output),
|
||||
|
||||
@@ -9,13 +9,11 @@ export * as WriteTool from "./write"
|
||||
import type { Context as PluginContext } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { ToolFailure } from "@opencode-ai/ai"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Bom } from "@opencode-ai/util/bom"
|
||||
import { Environment } from "../../environment"
|
||||
import { FileMutation } from "../../file-mutation"
|
||||
import { Formatter } from "../../formatter"
|
||||
import { LocationMutation } from "../../location-mutation"
|
||||
import { Permission } from "../../permission"
|
||||
import { fileDiff } from "./file-diff"
|
||||
|
||||
export const name = "write"
|
||||
|
||||
@@ -77,26 +75,24 @@ export const Plugin = {
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
const current = yield* FileMutation.readText(environment.files, target.absolute).pipe(
|
||||
Effect.catchTag("Environment.NotFound", () => Effect.succeed(undefined)),
|
||||
)
|
||||
const next = Bom.split(input.content)
|
||||
const preview = fileDiff(target.resource, current?.text ?? "", next.text, current ? "modified" : "added")
|
||||
yield* permission.assert({
|
||||
action: "edit",
|
||||
resources: [target.resource],
|
||||
save: ["*"],
|
||||
metadata: { files: [preview] },
|
||||
sessionID: context.sessionID,
|
||||
agent: context.agent,
|
||||
source,
|
||||
})
|
||||
const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content })
|
||||
const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom
|
||||
if (yield* formatter.file(target.absolute)) {
|
||||
yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
|
||||
}
|
||||
return result
|
||||
return yield* fileMutation.withLock([target.absolute])(
|
||||
Effect.gen(function* () {
|
||||
const result = yield* fileMutation.writeTextPreservingBom({ target, content: input.content })
|
||||
const bom = (yield* FileMutation.readText(environment.files, target.absolute)).bom
|
||||
if (yield* formatter.file(target.absolute)) {
|
||||
yield* FileMutation.syncTextBom(environment.files, target.absolute, bom)
|
||||
}
|
||||
return result
|
||||
}),
|
||||
)
|
||||
}).pipe(
|
||||
Effect.map((output) => ({ output, content: toModelOutput(output) })),
|
||||
Effect.mapError((error) => new ToolFailure({ message: `Unable to write ${input.path}`, error })),
|
||||
|
||||
@@ -110,49 +110,6 @@ describe("FileMutation", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.live("serializes concurrent writes to the same absolute target", () =>
|
||||
withTmp((directory) =>
|
||||
Effect.gen(function* () {
|
||||
const targetPath = path.join(directory, "shared.txt")
|
||||
yield* Effect.promise(() => fs.writeFile(targetPath, "initial"))
|
||||
const firstStarted = yield* Deferred.make<void>()
|
||||
const releaseFirst = yield* Deferred.make<void>()
|
||||
const secondStarted = yield* Deferred.make<void>()
|
||||
let writes = 0
|
||||
const filesystem = instrumentWrites((write) =>
|
||||
Effect.gen(function* () {
|
||||
writes++
|
||||
if (writes === 1) {
|
||||
yield* Deferred.succeed(firstStarted, undefined)
|
||||
yield* Deferred.await(releaseFirst)
|
||||
} else {
|
||||
yield* Deferred.succeed(secondStarted, undefined)
|
||||
}
|
||||
yield* write
|
||||
}),
|
||||
)
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const mutation = yield* LocationMutation.Service
|
||||
const files = yield* FileMutation.Service
|
||||
const firstPlan = yield* mutation.resolve({ path: "shared.txt" })
|
||||
const secondPlan = yield* mutation.resolve({ path: "shared.txt" })
|
||||
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(firstStarted)
|
||||
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
|
||||
yield* Effect.yieldNow
|
||||
expect(yield* Deferred.isDone(secondStarted)).toBe(false)
|
||||
|
||||
yield* Deferred.succeed(releaseFirst, undefined)
|
||||
yield* Deferred.await(secondStarted)
|
||||
yield* Fiber.join(first)
|
||||
yield* Fiber.join(second)
|
||||
expect(yield* Effect.promise(() => fs.readFile(targetPath, "utf8"))).toBe("second")
|
||||
}).pipe(provide(directory, filesystem))
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("shares transaction locks across Location service instances", () =>
|
||||
withTmp((directory) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -203,46 +160,4 @@ describe("FileMutation", () => {
|
||||
}).pipe(provide(directory)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("allows distinct absolute targets to proceed independently", () =>
|
||||
withTmp((directory) =>
|
||||
Effect.gen(function* () {
|
||||
const firstStarted = yield* Deferred.make<void>()
|
||||
const releaseFirst = yield* Deferred.make<void>()
|
||||
const secondFinished = yield* Deferred.make<void>()
|
||||
const secondPath = path.join(directory, "second.txt")
|
||||
let writes = 0
|
||||
const filesystem = instrumentWrites((write) =>
|
||||
++writes === 1
|
||||
? Deferred.succeed(firstStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseFirst)),
|
||||
Effect.andThen(write),
|
||||
)
|
||||
: write.pipe(Effect.andThen(Deferred.succeed(secondFinished, undefined))),
|
||||
)
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const mutation = yield* LocationMutation.Service
|
||||
const files = yield* FileMutation.Service
|
||||
const firstPlan = yield* mutation.resolve({ path: "first.txt" })
|
||||
const secondPlan = yield* mutation.resolve({ path: "second.txt" })
|
||||
const first = yield* files.write({ target: firstPlan, content: "first" }).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(firstStarted)
|
||||
const second = yield* files.write({ target: secondPlan, content: "second" }).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(secondFinished)
|
||||
expect(yield* Effect.promise(() => fs.readFile(secondPath, "utf8"))).toBe("second")
|
||||
|
||||
yield* Deferred.succeed(releaseFirst, undefined)
|
||||
yield* Fiber.join(first)
|
||||
yield* Fiber.join(second)
|
||||
}).pipe(provide(directory, filesystem))
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
function instrumentWrites(
|
||||
run: <E>(write: Effect.Effect<void, E>, target: string) => Effect.Effect<void, E>,
|
||||
): EnvironmentFilesTransform {
|
||||
return (files) => ({ write: (target, content) => run(files.write(target, content), target) })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { Deferred, Effect, Fiber, Layer } from "effect"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { Environment } from "@opencode-ai/core/environment"
|
||||
@@ -40,6 +40,7 @@ const assertions: Permission.AssertInput[] = []
|
||||
const writes: string[] = []
|
||||
let reads = 0
|
||||
let denyAction: string | undefined
|
||||
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
|
||||
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
|
||||
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
|
||||
|
||||
@@ -48,6 +49,7 @@ const permission = Layer.succeed(
|
||||
Permission.Service.of({
|
||||
assert: (input) =>
|
||||
Effect.sync(() => assertions.push(input)).pipe(
|
||||
Effect.andThen(Effect.suspend(() => afterPermission(input))),
|
||||
Effect.andThen(
|
||||
input.action === denyAction
|
||||
? Effect.fail(
|
||||
@@ -77,6 +79,7 @@ const reset = () => {
|
||||
writes.length = 0
|
||||
reads = 0
|
||||
denyAction = undefined
|
||||
afterPermission = () => Effect.void
|
||||
afterRead = () => Effect.void
|
||||
formatFile = () => Effect.succeed(false)
|
||||
}
|
||||
@@ -174,17 +177,7 @@ describe("EditTool", () => {
|
||||
})
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
|
||||
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
|
||||
expect(assertions[0]?.metadata).toMatchObject({
|
||||
files: [
|
||||
{
|
||||
file: "hello.txt",
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
patch: expect.stringContaining("-before\n+after"),
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(assertions[0]?.metadata).toBeUndefined()
|
||||
expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
|
||||
}),
|
||||
),
|
||||
@@ -349,7 +342,7 @@ describe("EditTool", () => {
|
||||
error: { type: "permission.rejected", message: "Permission denied: edit" },
|
||||
})
|
||||
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
|
||||
expect(reads).toBe(1)
|
||||
expect(reads).toBe(0)
|
||||
expect(writes).toEqual([])
|
||||
expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
|
||||
}),
|
||||
@@ -386,7 +379,7 @@ describe("EditTool", () => {
|
||||
})
|
||||
expect(missing).toEqual(matching)
|
||||
expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
|
||||
expect(reads).toBe(2)
|
||||
expect(reads).toBe(0)
|
||||
expect(writes).toEqual([])
|
||||
}),
|
||||
),
|
||||
@@ -643,58 +636,77 @@ describe("EditTool", () => {
|
||||
(tmp) => {
|
||||
reset()
|
||||
const target = path.join(tmp.path, "concurrent.txt")
|
||||
afterRead = () => (reads === 1 ? Effect.sleep("50 millis") : Effect.void)
|
||||
return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
|
||||
Effect.andThen(
|
||||
withTool(tmp.path, (registry) =>
|
||||
Effect.all(
|
||||
[
|
||||
executeTool(
|
||||
registry,
|
||||
call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
|
||||
),
|
||||
executeTool(
|
||||
registry,
|
||||
call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n"))
|
||||
const firstRead = yield* Deferred.make<void>()
|
||||
const releaseFirst = yield* Deferred.make<void>()
|
||||
const secondApproved = yield* Deferred.make<void>()
|
||||
afterRead = () =>
|
||||
reads === 1
|
||||
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst)))
|
||||
: Effect.void
|
||||
afterPermission = (input) =>
|
||||
input.source?.id === "call-edit-two"
|
||||
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void
|
||||
|
||||
const first = yield* withTool(tmp.path, (registry) =>
|
||||
executeTool(
|
||||
registry,
|
||||
call({ path: "concurrent.txt", oldString: "one", newString: "ONE" }, "call-edit-one"),
|
||||
),
|
||||
),
|
||||
Effect.andThen((results) =>
|
||||
Effect.gen(function* () {
|
||||
expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
|
||||
}),
|
||||
),
|
||||
)
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(firstRead)
|
||||
const second = yield* withTool(tmp.path, (registry) =>
|
||||
executeTool(
|
||||
registry,
|
||||
call({ path: "concurrent.txt", oldString: "two", newString: "TWO" }, "call-edit-two"),
|
||||
),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(secondApproved)
|
||||
expect(reads).toBe(1)
|
||||
|
||||
yield* Deferred.succeed(releaseFirst, undefined)
|
||||
expect((yield* Fiber.join(first)).status).toBe("completed")
|
||||
expect((yield* Fiber.join(second)).status).toBe("completed")
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
|
||||
})
|
||||
},
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("applies the edit when content changes after matching", () =>
|
||||
it.live("validates current content after permission succeeds", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => {
|
||||
reset()
|
||||
const target = path.join(tmp.path, "concurrent.txt")
|
||||
afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
|
||||
return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
|
||||
Effect.andThen(
|
||||
withTool(tmp.path, (registry) =>
|
||||
executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
|
||||
),
|
||||
),
|
||||
Effect.andThen((result) =>
|
||||
Effect.gen(function* () {
|
||||
expect(result).toMatchObject({ status: "completed", output: { replacements: 1 } })
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
|
||||
expect(writes).toEqual([target])
|
||||
}),
|
||||
),
|
||||
)
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(() => fs.writeFile(target, "before\n"))
|
||||
const permissionReached = yield* Deferred.make<void>()
|
||||
const releasePermission = yield* Deferred.make<void>()
|
||||
afterPermission = (input) =>
|
||||
input.action === "edit"
|
||||
? Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission)))
|
||||
: Effect.void
|
||||
|
||||
const edit = yield* withTool(tmp.path, (registry) =>
|
||||
executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(permissionReached)
|
||||
expect(reads).toBe(0)
|
||||
yield* Effect.promise(() => fs.writeFile(target, "newer\n"))
|
||||
yield* Deferred.succeed(releasePermission, undefined)
|
||||
|
||||
expect(yield* Fiber.join(edit)).toMatchObject({
|
||||
status: "error",
|
||||
error: { message: expect.stringContaining("Could not find oldString") },
|
||||
})
|
||||
expect(reads).toBe(1)
|
||||
expect(writes).toEqual([])
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
|
||||
})
|
||||
},
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Exit, Layer, Schema } from "effect"
|
||||
import { Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { Environment } from "@opencode-ai/core/environment"
|
||||
@@ -33,9 +33,11 @@ let denyAction: string | undefined
|
||||
let failRemoveTarget: string | undefined
|
||||
let failRemoveErrorTarget: string | undefined
|
||||
let failWriteTarget: string | undefined
|
||||
let reads = 0
|
||||
let readsBeforeEditApproval = 0
|
||||
let editApproved = false
|
||||
let afterEditApproval = (): Effect.Effect<void> => Effect.void
|
||||
let afterEditApproval = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
|
||||
let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
|
||||
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
|
||||
|
||||
const permission = Layer.succeed(
|
||||
@@ -46,7 +48,7 @@ const permission = Layer.succeed(
|
||||
assertions.push(input)
|
||||
if (input.action === "edit") editApproved = true
|
||||
}).pipe(
|
||||
Effect.andThen(input.action === "edit" ? Effect.suspend(afterEditApproval) : Effect.void),
|
||||
Effect.andThen(input.action === "edit" ? Effect.suspend(() => afterEditApproval(input)) : Effect.void),
|
||||
Effect.andThen(
|
||||
input.action === denyAction
|
||||
? Effect.fail(
|
||||
@@ -77,9 +79,11 @@ const reset = () => {
|
||||
failRemoveTarget = undefined
|
||||
failRemoveErrorTarget = undefined
|
||||
failWriteTarget = undefined
|
||||
reads = 0
|
||||
readsBeforeEditApproval = 0
|
||||
editApproved = false
|
||||
afterEditApproval = () => Effect.void
|
||||
afterRead = () => Effect.void
|
||||
formatFile = () => Effect.succeed(false)
|
||||
}
|
||||
|
||||
@@ -104,8 +108,12 @@ const withTool = <A, E, R>(
|
||||
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||
read: (target, range) =>
|
||||
Effect.sync(() => {
|
||||
reads++
|
||||
if (!editApproved) readsBeforeEditApproval++
|
||||
}).pipe(Effect.andThen(files.read(target, range))),
|
||||
}).pipe(
|
||||
Effect.andThen(files.read(target, range)),
|
||||
Effect.tap((result) => Effect.suspend(() => afterRead(target, result.bytes))),
|
||||
),
|
||||
remove: (target) => {
|
||||
if (failRemoveTarget && path.basename(target) === failRemoveTarget)
|
||||
return Effect.die("forced remove failure")
|
||||
@@ -219,14 +227,10 @@ describe("PatchTool", () => {
|
||||
action: "edit",
|
||||
resources: ["nested/new.txt", "update.txt", "remove.txt"],
|
||||
save: ["*"],
|
||||
metadata: {
|
||||
filepath: "nested/new.txt, update.txt, remove.txt",
|
||||
diff: expect.stringContaining("Index:"),
|
||||
files: expect.any(Array),
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(readsBeforeEditApproval).toBe(2)
|
||||
expect(assertions[0]?.metadata).toBeUndefined()
|
||||
expect(readsBeforeEditApproval).toBe(0)
|
||||
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe(
|
||||
"created\n",
|
||||
)
|
||||
@@ -267,40 +271,69 @@ describe("PatchTool", () => {
|
||||
it.live("serializes concurrent patch transactions", () =>
|
||||
withTempTool((directory, registry) => {
|
||||
const target = path.join(directory, "concurrent.txt")
|
||||
afterEditApproval = () =>
|
||||
assertions.filter((input) => input.action === "edit").length === 1 ? Effect.sleep("50 millis") : Effect.void
|
||||
return Effect.promise(() => fs.writeFile(target, "one\ntwo\n")).pipe(
|
||||
Effect.andThen(
|
||||
Effect.all(
|
||||
[
|
||||
executeTool(
|
||||
registry,
|
||||
call(
|
||||
"*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch",
|
||||
"call-patch-one",
|
||||
),
|
||||
),
|
||||
executeTool(
|
||||
registry,
|
||||
call(
|
||||
"*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch",
|
||||
"call-patch-two",
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.andThen((results) =>
|
||||
Effect.gen(function* () {
|
||||
expect(results.map((result) => result.status)).toEqual(["completed", "completed"])
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
|
||||
}),
|
||||
),
|
||||
)
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(() => fs.writeFile(target, "one\ntwo\n"))
|
||||
const firstRead = yield* Deferred.make<void>()
|
||||
const releaseFirst = yield* Deferred.make<void>()
|
||||
const secondApproved = yield* Deferred.make<void>()
|
||||
afterRead = () =>
|
||||
reads === 1
|
||||
? Deferred.succeed(firstRead, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst)))
|
||||
: Effect.void
|
||||
afterEditApproval = (input) =>
|
||||
input.source?.id === "call-patch-two"
|
||||
? Deferred.succeed(secondApproved, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void
|
||||
|
||||
const first = yield* executeTool(
|
||||
registry,
|
||||
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-one\n+ONE\n*** End Patch", "call-patch-one"),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(firstRead)
|
||||
const second = yield* executeTool(
|
||||
registry,
|
||||
call("*** Begin Patch\n*** Update File: concurrent.txt\n@@\n-two\n+TWO\n*** End Patch", "call-patch-two"),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(secondApproved)
|
||||
expect(reads).toBe(1)
|
||||
|
||||
yield* Deferred.succeed(releaseFirst, undefined)
|
||||
expect((yield* Fiber.join(first)).status).toBe("completed")
|
||||
expect((yield* Fiber.join(second)).status).toBe("completed")
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("ONE\nTWO\n")
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("validates patch context after permission succeeds", () =>
|
||||
withTempTool((directory, registry) =>
|
||||
Effect.gen(function* () {
|
||||
const target = path.join(directory, "current.txt")
|
||||
yield* Effect.promise(() => fs.writeFile(target, "before\n"))
|
||||
const permissionReached = yield* Deferred.make<void>()
|
||||
const releasePermission = yield* Deferred.make<void>()
|
||||
afterEditApproval = () =>
|
||||
Deferred.succeed(permissionReached, undefined).pipe(Effect.andThen(Deferred.await(releasePermission)))
|
||||
|
||||
const patch = yield* executeTool(
|
||||
registry,
|
||||
call("*** Begin Patch\n*** Update File: current.txt\n@@\n-before\n+after\n*** End Patch"),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(permissionReached)
|
||||
expect(reads).toBe(0)
|
||||
yield* Effect.promise(() => fs.writeFile(target, "newer\n"))
|
||||
yield* Deferred.succeed(releasePermission, undefined)
|
||||
|
||||
expect(yield* Fiber.join(patch)).toMatchObject({
|
||||
status: "error",
|
||||
error: { message: expect.stringContaining("Failed to find expected lines") },
|
||||
})
|
||||
expect(reads).toBe(1)
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("returns file diffs for final formatted content", () =>
|
||||
withTempTool((directory, registry) => {
|
||||
const target = path.join(directory, "formatted.txt")
|
||||
@@ -783,7 +816,7 @@ describe("PatchTool", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.live("approves an external directory before reading and requests edit permission afterward", () =>
|
||||
it.live("approves external-directory and edit access before reading", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
|
||||
([active, outside]) => {
|
||||
@@ -800,7 +833,7 @@ describe("PatchTool", () => {
|
||||
),
|
||||
).toMatchObject({ status: "completed" })
|
||||
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
|
||||
expect(readsBeforeEditApproval).toBe(1)
|
||||
expect(readsBeforeEditApproval).toBe(0)
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
|
||||
}),
|
||||
),
|
||||
@@ -931,7 +964,7 @@ describe("PatchTool", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.live("approves a relative external target before reading and requests edit permission afterward", () =>
|
||||
it.live("approves a relative external target before reading", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
|
||||
([active, outside]) => {
|
||||
@@ -949,7 +982,7 @@ describe("PatchTool", () => {
|
||||
),
|
||||
).toMatchObject({ status: "completed" })
|
||||
expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
|
||||
expect(readsBeforeEditApproval).toBe(1)
|
||||
expect(readsBeforeEditApproval).toBe(0)
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { Deferred, Effect, Fiber, Layer } from "effect"
|
||||
import { FileMutation } from "@opencode-ai/core/file-mutation"
|
||||
import { Formatter } from "@opencode-ai/core/formatter"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
@@ -13,6 +13,7 @@ import { Permission } from "@opencode-ai/core/permission"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Tool } from "@opencode-ai/core/tool"
|
||||
import { EditTool } from "@opencode-ai/core/tool/plugin/edit"
|
||||
import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
|
||||
import { transformEnvironmentFiles } from "./fixture/environment"
|
||||
import { location } from "./fixture/location"
|
||||
@@ -27,10 +28,26 @@ const writeToolNode = makeLocationNode({
|
||||
deps: [Tool.node, LocationMutation.node, FileMutation.node, Environment.node, Formatter.node, Permission.node],
|
||||
})
|
||||
|
||||
const editToolNode = makeLocationNode({
|
||||
name: "test/edit-tool-plugin",
|
||||
layer: Layer.effectDiscard(registerToolPlugin(EditTool.Plugin)),
|
||||
deps: [
|
||||
Tool.node,
|
||||
LocationMutation.node,
|
||||
FileMutation.node,
|
||||
Environment.node,
|
||||
Formatter.node,
|
||||
Location.node,
|
||||
Permission.node,
|
||||
],
|
||||
})
|
||||
|
||||
const sessionID = Session.ID.make("ses_write_tool_test")
|
||||
const assertions: Permission.AssertInput[] = []
|
||||
const writes: string[] = []
|
||||
let reads = 0
|
||||
let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
|
||||
let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
|
||||
let denyAction: string | undefined
|
||||
|
||||
const permission = Layer.succeed(
|
||||
@@ -38,6 +55,7 @@ const permission = Layer.succeed(
|
||||
Permission.Service.of({
|
||||
assert: (input) =>
|
||||
Effect.sync(() => assertions.push(input)).pipe(
|
||||
Effect.andThen(Effect.suspend(() => afterPermission(input))),
|
||||
Effect.andThen(
|
||||
input.action === denyAction
|
||||
? Effect.fail(
|
||||
@@ -65,11 +83,17 @@ const formatter = Layer.mock(Formatter.Service, {
|
||||
const reset = () => {
|
||||
assertions.length = 0
|
||||
writes.length = 0
|
||||
reads = 0
|
||||
formatFile = () => Effect.succeed(false)
|
||||
afterPermission = () => Effect.void
|
||||
denyAction = undefined
|
||||
}
|
||||
|
||||
const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
|
||||
const withTool = <A, E, R>(
|
||||
directory: string,
|
||||
body: (registry: Tool.Interface) => Effect.Effect<A, E, R>,
|
||||
options?: { edit?: boolean },
|
||||
) => {
|
||||
const activeLocation = Layer.succeed(
|
||||
Location.Service,
|
||||
Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
|
||||
@@ -79,11 +103,18 @@ const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) =
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Tool.node, Tool.node, LocationMutation.node, FileMutation.node, writeToolNode]),
|
||||
LayerNode.group([
|
||||
Tool.node,
|
||||
LocationMutation.node,
|
||||
FileMutation.node,
|
||||
writeToolNode,
|
||||
...(options?.edit ? [editToolNode] : []),
|
||||
]),
|
||||
[
|
||||
[
|
||||
Environment.node,
|
||||
transformEnvironmentFiles(activeLocation, (files) => ({
|
||||
read: (target, range) => Effect.sync(() => reads++).pipe(Effect.andThen(files.read(target, range))),
|
||||
write: (target, content) =>
|
||||
Effect.sync(() => writes.push(target)).pipe(Effect.andThen(files.write(target, content))),
|
||||
})),
|
||||
@@ -103,6 +134,12 @@ const call = (input: typeof WriteTool.Input.Type, id = "call-write") => ({
|
||||
call: { type: "tool-call" as const, id, name: "write", input },
|
||||
})
|
||||
|
||||
const editCall = (input: typeof EditTool.Input.Type, id = "call-edit") => ({
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call" as const, id, name: "edit", input },
|
||||
})
|
||||
|
||||
const it = testEffect(Layer.empty)
|
||||
|
||||
describe("WriteTool", () => {
|
||||
@@ -129,17 +166,7 @@ describe("WriteTool", () => {
|
||||
"created",
|
||||
)
|
||||
expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }])
|
||||
expect(assertions[0]?.metadata).toMatchObject({
|
||||
files: [
|
||||
{
|
||||
file: "src/new.txt",
|
||||
status: "added",
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
patch: expect.stringContaining("+created"),
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(assertions[0]?.metadata).toBeUndefined()
|
||||
expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")])
|
||||
}),
|
||||
)
|
||||
@@ -187,17 +214,7 @@ describe("WriteTool", () => {
|
||||
if (settled.status !== "completed") return
|
||||
expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }])
|
||||
expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true })
|
||||
expect(assertions[0]?.metadata).toMatchObject({
|
||||
files: [
|
||||
{
|
||||
file: "existing.txt",
|
||||
status: "modified",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
patch: expect.stringMatching(/-before[\s\S]*\+after/),
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(assertions[0]?.metadata).toBeUndefined()
|
||||
expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe(
|
||||
"after",
|
||||
)
|
||||
@@ -412,4 +429,93 @@ describe("WriteTool", () => {
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("authorizes an edit while a write holds the same-path execution lock", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => {
|
||||
reset()
|
||||
const target = path.join(tmp.path, "shared.txt")
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(() => fs.writeFile(target, "initial"))
|
||||
const formatting = yield* Deferred.make<void>()
|
||||
const releaseFormatting = yield* Deferred.make<void>()
|
||||
const editApproved = yield* Deferred.make<void>()
|
||||
let formats = 0
|
||||
formatFile = () =>
|
||||
++formats === 1
|
||||
? Deferred.succeed(formatting, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(releaseFormatting)),
|
||||
Effect.as(false),
|
||||
)
|
||||
: Effect.succeed(false)
|
||||
afterPermission = (input) =>
|
||||
input.source?.id === "call-serialized-edit" && input.action === "edit"
|
||||
? Deferred.succeed(editApproved, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void
|
||||
|
||||
const write = yield* withTool(
|
||||
tmp.path,
|
||||
(registry) =>
|
||||
executeTool(registry, call({ path: "shared.txt", content: "before" }, "call-serialized-write")),
|
||||
{ edit: true },
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(formatting)
|
||||
const edit = yield* withTool(
|
||||
tmp.path,
|
||||
(registry) =>
|
||||
executeTool(
|
||||
registry,
|
||||
editCall({ path: "shared.txt", oldString: "before", newString: "after" }, "call-serialized-edit"),
|
||||
),
|
||||
{ edit: true },
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(editApproved)
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("before")
|
||||
|
||||
yield* Deferred.succeed(releaseFormatting, undefined)
|
||||
expect((yield* Fiber.join(write)).status).toBe("completed")
|
||||
expect((yield* Fiber.join(edit)).status).toBe("completed")
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
|
||||
})
|
||||
},
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("does not hold the execution lock while waiting for permission", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => {
|
||||
reset()
|
||||
const target = path.join(tmp.path, "shared.txt")
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.promise(() => fs.writeFile(target, "initial"))
|
||||
const firstAsked = yield* Deferred.make<void>()
|
||||
const releaseFirst = yield* Deferred.make<void>()
|
||||
afterPermission = (input) =>
|
||||
input.source?.id === "call-waiting-write" && input.action === "edit"
|
||||
? Deferred.succeed(firstAsked, undefined).pipe(Effect.andThen(Deferred.await(releaseFirst)))
|
||||
: Effect.void
|
||||
|
||||
const first = yield* withTool(tmp.path, (registry) =>
|
||||
executeTool(registry, call({ path: "shared.txt", content: "first" }, "call-waiting-write")),
|
||||
).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(firstAsked)
|
||||
expect(reads).toBe(0)
|
||||
|
||||
const second = yield* withTool(tmp.path, (registry) =>
|
||||
executeTool(registry, call({ path: "shared.txt", content: "second" }, "call-approved-write")),
|
||||
)
|
||||
expect(second.status).toBe("completed")
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("second")
|
||||
|
||||
yield* Deferred.succeed(releaseFirst, undefined)
|
||||
expect((yield* Fiber.join(first)).status).toBe("completed")
|
||||
expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("first")
|
||||
})
|
||||
},
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1316,15 +1316,7 @@ export function write(
|
||||
}).pipe(Effect.flatMap((content) => fs.writeFileString(join(directory, file.path), content))),
|
||||
{ concurrency: 8, discard: true },
|
||||
)
|
||||
// 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)
|
||||
yield* fs.writeFileString(manifest, JSON.stringify(output.files.map((file) => file.path).sort(), null, 2) + "\n")
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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: '["session.ts"]\n' },
|
||||
{ path: "/generated/.httpapi-codegen.json", content: '[\n "session.ts"\n]\n' },
|
||||
])
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "workspace:*",
|
||||
"@opentui/core": "catalog:",
|
||||
"entities": "7.0.1",
|
||||
"string-width": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -7,18 +7,6 @@ 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)
|
||||
|
||||
@@ -38,21 +26,6 @@ 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)
|
||||
|
||||
@@ -75,9 +48,6 @@ 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", () => {
|
||||
@@ -123,61 +93,4 @@ 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,12 +47,7 @@ export class DiagramCanvasSizeError extends Error {
|
||||
readonly width: number,
|
||||
readonly height: number,
|
||||
) {
|
||||
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`,
|
||||
)
|
||||
super(`Diagram canvas ${width}x${height} exceeds the ${MAX_DIAGRAM_CELLS.toLocaleString()} cell limit`)
|
||||
this.name = "DiagramCanvasSizeError"
|
||||
}
|
||||
}
|
||||
@@ -66,31 +61,29 @@ function sameKey(left: readonly unknown[] | undefined, right: readonly unknown[]
|
||||
}
|
||||
|
||||
export class DiagramCanvas<Style extends string, Metadata extends object = object> {
|
||||
private readonly cells: Array<Array<DiagramCanvasCell<Style, Metadata>>>
|
||||
readonly rows: 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.cells = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
this.rowEnds = new Uint32Array(height)
|
||||
this.rows = Array.from({ length: height }, () => Array.from({ length: width }, () => createEmptyCell()))
|
||||
}
|
||||
|
||||
get rows(): ReadonlyArray<ReadonlyArray<Readonly<DiagramCanvasCell<Style, Metadata>>>> {
|
||||
return this.cells
|
||||
private rowTextEnd(row: Array<DiagramCanvasCell<Style, Metadata>>): number {
|
||||
let rowEnd = row.length
|
||||
while (rowEnd > 0 && row[rowEnd - 1]?.char === " ") rowEnd -= 1
|
||||
return rowEnd
|
||||
}
|
||||
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd: number): string {
|
||||
private rowText(row: Array<DiagramCanvasCell<Style, Metadata>>, rowEnd = this.rowTextEnd(row)): string {
|
||||
return row
|
||||
.slice(0, rowEnd)
|
||||
.map((cell) => cell.char)
|
||||
@@ -99,58 +92,28 @@ 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.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
|
||||
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
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
setCell(x: number, y: number, char: string, style?: Style, metadata?: Partial<Metadata>): void {
|
||||
this.writeCell(x, y, char, style, metadata, true)
|
||||
}
|
||||
|
||||
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
|
||||
if (y < 0 || y >= this.rows.length || x < 0 || x >= this.rows[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
|
||||
}
|
||||
this.rows[y]![x] = this.mergeCell?.(this.rows[y]![x]!, incoming) ?? incoming
|
||||
}
|
||||
|
||||
getCell(x: number, y: number): Readonly<DiagramCanvasCell<Style, Metadata>> | undefined {
|
||||
return this.cells[y]?.[x]
|
||||
getCell(x: number, y: number): DiagramCanvasCell<Style, Metadata> | undefined {
|
||||
return this.rows[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))
|
||||
@@ -163,7 +126,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.cells[rowIndex]!, this.rowEnds[rowIndex]!))
|
||||
lines.push(this.rowText(this.rows[rowIndex]!))
|
||||
}
|
||||
return lines.join("\n")
|
||||
}
|
||||
@@ -172,18 +135,13 @@ 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.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
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,
|
||||
@@ -193,8 +151,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.cells[rowIndex]!
|
||||
const rowEnd = this.rowEnds[rowIndex]!
|
||||
const row = this.rows[rowIndex]!
|
||||
const rowEnd = this.rowTextEnd(row)
|
||||
|
||||
let currentCell: DiagramCanvasCell<Style, Metadata> | undefined
|
||||
let currentKey: readonly unknown[] | undefined
|
||||
|
||||
@@ -27,12 +27,7 @@ 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 decodeMermaidText(trimmed.slice(1, -1))
|
||||
return trimmed.slice(1, -1)
|
||||
}
|
||||
return decodeMermaidText(trimmed)
|
||||
return trimmed
|
||||
}
|
||||
|
||||
export function decodeMermaidText(value: string): string {
|
||||
return decodeHTMLStrict(value)
|
||||
}
|
||||
import { decodeHTMLStrict } from "entities"
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -1,242 +0,0 @@
|
||||
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 this renderer does not support. */
|
||||
/** An otherwise valid diagram contains syntax that merman 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, route.labelAxis)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
for (const [index, line] of label.lines.entries()) {
|
||||
grid.setText(label.point.x, label.point.y + index, line, style)
|
||||
}
|
||||
@@ -249,22 +249,15 @@ function drawSourceConnectors(
|
||||
if (routeDirection && connectorDirection) {
|
||||
const cell = grid.getCell(sourcePoint.x, sourcePoint.y)
|
||||
if (cell) {
|
||||
grid.replaceCell(
|
||||
sourcePoint.x,
|
||||
sourcePoint.y,
|
||||
diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
),
|
||||
"edge",
|
||||
cell.char = diagramLineGlyph(
|
||||
new Set([routeDirection, connectorDirection]),
|
||||
"rounded",
|
||||
route.edge.style === "thick" ? "heavy" : "single",
|
||||
)
|
||||
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,6 +1,7 @@
|
||||
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 {
|
||||
@@ -8,7 +9,6 @@ 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,63 +55,6 @@ 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(
|
||||
@@ -265,67 +208,6 @@ 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]
|
||||
@@ -356,36 +238,6 @@ 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]
|
||||
@@ -537,14 +389,6 @@ 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)]`
|
||||
@@ -590,25 +434,6 @@ 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]
|
||||
@@ -1059,94 +884,6 @@ 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
|
||||
@@ -1574,6 +1311,6 @@ flowchart LR
|
||||
const node = parseColor("#ff0000")
|
||||
const styled = renderGridStyledText(grid, resolveFlowchartStyleColors({ node }))
|
||||
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && chunk.fg?.equals(node))).toBe(true)
|
||||
expect(styled.chunks.some((chunk) => chunk.text.includes("Alpha") && colorsEqual(chunk.fg, node))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -67,22 +67,6 @@ 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,23 +67,14 @@ function segmentLabelPoint(segment: DiagramSegment, labelWidth: number, labelHei
|
||||
return clampPoint(shiftPoint(center, "up", Math.floor((labelHeight - 1) / 2)))
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
function bestLabelSegment(points: readonly FlowchartPoint[], labelWidth: number): DiagramSegment | undefined {
|
||||
let roomyHorizontal: DiagramSegment | undefined
|
||||
let verticalBus: DiagramSegment | undefined
|
||||
let longest: DiagramSegment | undefined
|
||||
|
||||
for (const segment of segments) {
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
const segment = segmentBetween(points[index - 1]!, points[index]!)
|
||||
if (!segment) continue
|
||||
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
|
||||
@@ -96,9 +87,8 @@ function flowchartLabelPoint(
|
||||
points: readonly FlowchartPoint[],
|
||||
labelWidth: number,
|
||||
labelHeight: number,
|
||||
preferredAxis?: DiagramSegment["axis"],
|
||||
): FlowchartPoint {
|
||||
const segment = bestLabelSegment(points, labelWidth, preferredAxis)
|
||||
const segment = bestLabelSegment(points, labelWidth)
|
||||
return segment ? segmentLabelPoint(segment, labelWidth, labelHeight) : (points[0] ?? point(0, 0))
|
||||
}
|
||||
|
||||
@@ -106,10 +96,9 @@ 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, preferredAxis), width, height }
|
||||
return { lines, point: flowchartLabelPoint(points, width, height), width, height }
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ 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
|
||||
@@ -317,7 +316,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, route.labelAxis)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength)
|
||||
const { point, width, height } = label
|
||||
return {
|
||||
left: point.x,
|
||||
@@ -359,6 +358,9 @@ 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[]>()
|
||||
@@ -373,23 +375,6 @@ 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,7 +8,6 @@ import type {
|
||||
} from "./types.js"
|
||||
import { MermaidSyntaxError } from "../diagnostics.js"
|
||||
import {
|
||||
decodeMermaidText,
|
||||
firstMeaningfulMermaidLine,
|
||||
meaningfulNumberedMermaidLines,
|
||||
stripMermaidQuotes as stripQuotes,
|
||||
@@ -29,9 +28,8 @@ 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()
|
||||
@@ -81,20 +79,6 @@ 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())
|
||||
}
|
||||
@@ -138,11 +122,9 @@ 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
|
||||
}
|
||||
|
||||
@@ -152,91 +134,25 @@ interface ParsedEdgeOperator {
|
||||
label: string
|
||||
style: FlowchartEdgeStyle | undefined
|
||||
arrowhead: boolean
|
||||
sourceArrowhead: boolean
|
||||
orderOnly: boolean
|
||||
}
|
||||
|
||||
function parseEdgeOperators(line: string): ParsedEdgeOperator[] {
|
||||
return [...maskNodeLabelOperators(line).matchAll(EDGE_OPERATOR_RE)].map((match) => {
|
||||
return [...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: decodeMermaidText((match[2] ?? match[4] ?? match[7] ?? "").trim()),
|
||||
label: (match[2] ?? match[4] ?? match[7] ?? "").trim(),
|
||||
style: edgeStyleFromArrow(startArrow, endArrow),
|
||||
arrowhead: endArrow === "~~~" || endArrow.endsWith(">"),
|
||||
sourceArrowhead: startArrow.startsWith("<"),
|
||||
arrowhead: endArrow !== "---",
|
||||
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) ?? "")
|
||||
}
|
||||
@@ -250,7 +166,6 @@ 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])
|
||||
@@ -307,15 +222,6 @@ 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
|
||||
@@ -333,7 +239,6 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
operator.label,
|
||||
operator.style,
|
||||
operator.arrowhead,
|
||||
operator.sourceArrowhead,
|
||||
)
|
||||
edges.push(operator.orderOnly ? { ...edge, orderOnly: true } : edge)
|
||||
}
|
||||
@@ -341,7 +246,7 @@ export function parseMermaidFlowchartDiagram(content: string): FlowchartDiagram
|
||||
}
|
||||
}
|
||||
|
||||
if (isSupportedNodeToken(line)) {
|
||||
if (hasExplicitNodeShape(line) || ID_ONLY_RE.test(stripNodeToken(line))) {
|
||||
const node = ensureNode(nodes, line)
|
||||
addNodeToSubgraph(currentSubgraph, node.id)
|
||||
continue
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
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"
|
||||
|
||||
@@ -23,31 +21,6 @@ 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: "" }
|
||||
@@ -296,79 +269,4 @@ 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,7 +15,6 @@ import {
|
||||
pathViaLane,
|
||||
sideForDirection,
|
||||
snapCoordinate,
|
||||
shiftPoint,
|
||||
withCoordinate,
|
||||
type DiagramAxis,
|
||||
type DiagramDirection,
|
||||
@@ -23,7 +22,7 @@ import {
|
||||
type DiagramSide,
|
||||
} from "../core/geometry.js"
|
||||
import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
|
||||
import { flowchartEdgeLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
|
||||
import { flowchartEdgeLabelLayout } from "./labels.js"
|
||||
import type {
|
||||
FlowchartDiagram,
|
||||
FlowchartDirection,
|
||||
@@ -131,9 +130,7 @@ function horizontalEdgePath(
|
||||
|
||||
const travel = horizontalTravel(from, to, direction)
|
||||
const startSide = sideForDirection(travel)
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)), {
|
||||
preferredAxis: "x",
|
||||
})
|
||||
return orthogonalPath(boundsSidePoint(from, startSide), boundsSidePoint(to, oppositeSide(startSide)))
|
||||
}
|
||||
|
||||
function selfEdgePath(bounds: FlowchartNodeBounds): FlowchartPoint[] {
|
||||
@@ -168,7 +165,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, route.labelAxis)
|
||||
const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth)
|
||||
right = Math.max(right, label.point.x + label.width - 1)
|
||||
}
|
||||
return right
|
||||
@@ -182,14 +179,6 @@ 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)
|
||||
@@ -222,7 +211,7 @@ function targetFanInLane(
|
||||
afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
|
||||
travel,
|
||||
)
|
||||
return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
|
||||
return keepBefore(unclamped, targetCoordinate, travel)
|
||||
}
|
||||
|
||||
function portForTravel(bounds: FlowchartNodeBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
|
||||
@@ -479,11 +468,7 @@ 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: FlowchartEdgeRoute = {
|
||||
edge,
|
||||
points: parallelEdgePath(from, to, direction, laneCoordinate),
|
||||
labelAxis: isVerticalDirection(direction) ? "y" : "x",
|
||||
}
|
||||
const route = { edge, points: parallelEdgePath(from, to, direction, laneCoordinate) }
|
||||
routes.push(route)
|
||||
handled.add(edge)
|
||||
previousRoute = route
|
||||
@@ -586,238 +571,59 @@ function routeHorizontalSubgraphEntries(
|
||||
}
|
||||
}
|
||||
|
||||
function pathIntersectsBounds(
|
||||
points: readonly FlowchartPoint[],
|
||||
bounds: { left: number; top: number; width: number; height: number },
|
||||
allowedContact: "source" | "target" | "both" | undefined = undefined,
|
||||
): boolean {
|
||||
function pathIntersectsBounds(points: readonly FlowchartPoint[], bounds: FlowchartNodeBounds): 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) 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
|
||||
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
|
||||
}
|
||||
continue
|
||||
}
|
||||
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
|
||||
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 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>,
|
||||
subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
|
||||
routeIndex: number,
|
||||
direction: FlowchartDirection,
|
||||
): FlowchartEdgeRoute {
|
||||
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)]
|
||||
: [],
|
||||
const obstacle = [...bounds.values()].some(
|
||||
(bound) => bound.id !== route.edge.from && bound.id !== route.edge.to && pathIntersectsBounds(route.points, bound),
|
||||
)
|
||||
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
|
||||
if (!obstacle) return route
|
||||
|
||||
const from = bounds.get(route.edge.from)
|
||||
const to = bounds.get(route.edge.to)
|
||||
if (!from || !to) return route
|
||||
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
|
||||
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) }
|
||||
}
|
||||
return (
|
||||
candidates.find((candidate) => !intersectsObstacle(candidate)) ?? shortestValid(preservedTargetCandidates) ?? 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) }
|
||||
}
|
||||
|
||||
export function routeFlowchartEdges(
|
||||
@@ -865,10 +671,7 @@ export function routeFlowchartEdges(
|
||||
if (!from || !to) continue
|
||||
routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
|
||||
}
|
||||
for (let index = routes.length - 1; index >= 0; index--) {
|
||||
routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, subgraphBounds, index)
|
||||
}
|
||||
return routes
|
||||
return routes.map((route) => avoidNodeObstacles(route, bounds, directionForEdge(route.edge)))
|
||||
}
|
||||
|
||||
function sideForOutsidePoint(bounds: FlowchartNodeBounds, sourcePoint: FlowchartPoint): DiagramSide {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { DiagramAxis, DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
import type { DiagramBounds, DiagramDirection, DiagramPoint } from "../core/geometry.js"
|
||||
|
||||
export type FlowchartDirection = "TB" | "TD" | "BT" | "LR" | "RL"
|
||||
export type FlowchartNodeShape = "box" | "rounded" | "database" | "decision" | "subroutine"
|
||||
@@ -16,7 +16,6 @@ export interface FlowchartEdge {
|
||||
label: string
|
||||
style?: FlowchartEdgeStyle
|
||||
arrowhead?: false
|
||||
sourceArrowhead?: true
|
||||
orderOnly?: boolean
|
||||
}
|
||||
|
||||
@@ -56,7 +55,6 @@ export type FlowchartPoint = DiagramPoint
|
||||
export interface FlowchartEdgeRoute {
|
||||
edge: FlowchartEdge
|
||||
points: FlowchartPoint[]
|
||||
labelAxis?: DiagramAxis
|
||||
}
|
||||
|
||||
export type FlowchartEdgeDirection = DiagramDirection
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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"
|
||||
@@ -29,18 +28,6 @@ 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
|
||||
@@ -55,11 +42,11 @@ sequenceDiagram
|
||||
│ Browser │ │ Server │
|
||||
╰────┬────╯ ╰────┬───╯
|
||||
│ │
|
||||
│ GET / │
|
||||
├─────────────────►
|
||||
│ GET / │
|
||||
├─────────────────▶
|
||||
│ │
|
||||
│ 401 WWW-Auth │
|
||||
◄─────────────────┤
|
||||
│ 401 WWW-Auth │
|
||||
◀─────────────────┤
|
||||
│ │
|
||||
`)
|
||||
})
|
||||
@@ -83,15 +70,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 ──▶
|
||||
│ │ │
|
||||
`)
|
||||
})
|
||||
@@ -122,7 +109,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("▶")),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -258,29 +245,18 @@ sequenceDiagram
|
||||
])
|
||||
})
|
||||
|
||||
test("renders activation syntax as visible intervals", () => {
|
||||
test("parses activation syntax without rendering activation bars", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>+Server: request
|
||||
Server-->>-Browser: response
|
||||
`)
|
||||
|
||||
expect(output).toContain("┃")
|
||||
expect(output).not.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
|
||||
@@ -318,22 +294,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 │
|
||||
│(─────────────────┤
|
||||
│ │"
|
||||
`)
|
||||
@@ -557,7 +533,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(2)
|
||||
expect(fragmentMessageRow.match(/│/g)?.length).toBe(3)
|
||||
})
|
||||
|
||||
test("keeps long notes inside groups and nested fragment frames intact", () => {
|
||||
@@ -605,42 +581,6 @@ 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
|
||||
@@ -660,11 +600,11 @@ sequenceDiagram
|
||||
│ Browser │ │ │ API │ │ Cache │ │ DB │ │
|
||||
╰────┬────╯ │ ╰──┬──╯ ╰───┬───╯ ╰──┬─╯ │
|
||||
│ │ │ │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────► │ │ │
|
||||
│ GET /users/42 │ │ │ │
|
||||
├──────────────────▶ │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────► │ │
|
||||
│ │ │ get user:42 │ │ │
|
||||
│ │ ├─────────────────▶ │ │
|
||||
│ │ │ │ │ │
|
||||
╰────────────────────────────────────────────╯"
|
||||
`)
|
||||
@@ -679,25 +619,12 @@ 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
|
||||
@@ -712,12 +639,12 @@ sequenceDiagram
|
||||
│
|
||||
├────────────────────╮
|
||||
│ Check Permissions │
|
||||
◄────────────────────╯
|
||||
◀────────────────────╯
|
||||
│"
|
||||
`)
|
||||
})
|
||||
|
||||
test("frames notes in their reserved rows", () => {
|
||||
test("places two spacer rows above note badges and one below", () => {
|
||||
const output = renderSequenceDiagram(`
|
||||
sequenceDiagram
|
||||
Browser->>Server: one
|
||||
@@ -729,11 +656,9 @@ sequenceDiagram
|
||||
const nextMessageRow = lines.findIndex((line) => line.includes("two"))
|
||||
|
||||
expect(noteRow).toBeGreaterThan(0)
|
||||
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(lines[noteRow - 1]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow - 2]?.trim()).toBe("│ │")
|
||||
expect(lines[noteRow + 1]?.trim()).toBe("│ │")
|
||||
expect(nextMessageRow).toBe(noteRow + 2)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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,
|
||||
@@ -20,10 +19,6 @@ 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":
|
||||
@@ -33,7 +28,7 @@ function arrowHeadChar(head: SequenceArrowHead | undefined, direction: 1 | -1):
|
||||
case "async":
|
||||
return direction === 1 ? ")" : "("
|
||||
default:
|
||||
return direction === 1 ? "►" : "◄"
|
||||
return direction === 1 ? "▶" : "◀"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,32 +185,6 @@ 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 = {},
|
||||
@@ -228,13 +197,11 @@ export function drawSequenceDiagramGrid(
|
||||
if (plan.groups.length > 0) renderParticipantGroups(grid, plan.groups, plan.height - 1)
|
||||
|
||||
for (const placement of plan.participants) {
|
||||
const { centerX: center, headerLeftX, headerRightX, labelLines } = placement
|
||||
const { participant, centerX: center, headerLeftX, headerRightX, labelX } = placement
|
||||
const { participantHeaderTopY, participantHeaderY, participantRuleY, lifelineStartY, lifelineEndY } = plan.rows
|
||||
|
||||
if (options.compact) {
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
} else {
|
||||
for (let x = headerLeftX; x <= headerRightX; x++) {
|
||||
setCell(grid, x, participantHeaderTopY, SEQUENCE_BORDER.horizontal, "participant")
|
||||
@@ -243,15 +210,11 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
setCell(grid, headerLeftX, participantHeaderTopY, SEQUENCE_BORDER.topLeft, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderTopY, SEQUENCE_BORDER.topRight, "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, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerRightX, participantHeaderY, SEQUENCE_BORDER.vertical, "participant")
|
||||
setCell(grid, headerLeftX, participantRuleY, SEQUENCE_BORDER.bottomLeft, "participant")
|
||||
setCell(grid, headerRightX, participantRuleY, SEQUENCE_BORDER.bottomRight, "participant")
|
||||
labelLines.forEach((line, index) =>
|
||||
setText(grid, centeredStart(center, line), participantHeaderY + index, line, "participant"),
|
||||
)
|
||||
setText(grid, labelX, participantHeaderY, participant.label, "participant")
|
||||
setCell(grid, center, participantRuleY, SEQUENCE_BORDER.topT, "participant")
|
||||
}
|
||||
|
||||
@@ -264,7 +227,9 @@ export function drawSequenceDiagramGrid(
|
||||
|
||||
for (const placement of plan.steps) {
|
||||
if (placement.type === "note") {
|
||||
renderNote(grid, placement)
|
||||
for (let lineIndex = 0; lineIndex < placement.textLines.length; lineIndex++) {
|
||||
setText(grid, placement.textX, placement.textY + lineIndex, placement.textLines[lineIndex]!, "noteBadge")
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -305,13 +270,5 @@ 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,7 +22,6 @@ 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",
|
||||
@@ -133,9 +132,6 @@ 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,25 +90,6 @@ 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
|
||||
@@ -188,34 +169,4 @@ ${Array.from(
|
||||
|
||||
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 = 2
|
||||
const NOTE_HORIZONTAL_PADDING = 1
|
||||
const GROUP_HORIZONTAL_PADDING = 2
|
||||
const FRAGMENT_HORIZONTAL_OVERHANG = 3
|
||||
|
||||
@@ -25,7 +25,7 @@ export interface SequenceParticipantPlacement {
|
||||
centerX: number
|
||||
headerLeftX: number
|
||||
headerRightX: number
|
||||
labelLines: string[]
|
||||
labelX: number
|
||||
}
|
||||
|
||||
export interface SequenceGroupPlacement {
|
||||
@@ -41,14 +41,6 @@ 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 }
|
||||
| {
|
||||
@@ -96,7 +88,6 @@ export interface SequencePlacementPlan {
|
||||
}
|
||||
participants: SequenceParticipantPlacement[]
|
||||
groups: SequenceGroupPlacement[]
|
||||
activations: SequenceActivationPlacement[]
|
||||
steps: SequenceStepPlacement[]
|
||||
}
|
||||
|
||||
@@ -141,8 +132,7 @@ function messageLabelText(message: SequenceMessage): string {
|
||||
}
|
||||
|
||||
function participantHeaderWidth(label: string, compact: boolean): number {
|
||||
const width = labelLinesWidth(mermaidLabelLines(label))
|
||||
return compact ? width : Math.max(5, width + 4)
|
||||
return compact ? visualLength(label) : Math.max(5, visualLength(label) + 4)
|
||||
}
|
||||
|
||||
function fragmentLabelText(fragment: SequenceFragment): string {
|
||||
@@ -246,9 +236,7 @@ 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)
|
||||
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) }
|
||||
return { leftX, rightX: Math.max(rightX, leftX + 2 + messageWidth(step.message) - 1) }
|
||||
}
|
||||
if (step.type !== "note") return undefined
|
||||
const indexes = getParticipantIndexes(participantIndexes, step.note.over)
|
||||
@@ -399,9 +387,7 @@ function resolveParticipantCenters(
|
||||
if (fromIndex === toIndex && fromIndex >= 0 && fromIndex < diagram.participants.length - 1) {
|
||||
gaps[fromIndex] = Math.max(
|
||||
gaps[fromIndex]!,
|
||||
selfMessageLoopWidth(message) +
|
||||
Math.ceil(labelLinesWidth(mermaidLabelLines(diagram.participants[fromIndex + 1]!.label)) / 2) +
|
||||
2,
|
||||
selfMessageLoopWidth(message) + Math.ceil(visualLength(diagram.participants[fromIndex + 1]!.label) / 2) + 2,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -437,31 +423,37 @@ function separateExpandedGroupsFromExternalParticipants(
|
||||
compact: boolean,
|
||||
): number[] {
|
||||
const adjusted = [...centers]
|
||||
for (let boundary = 0; boundary < adjusted.length - 1; boundary++) {
|
||||
for (let pass = 0; pass < Math.max(1, ranges.length * 2); pass++) {
|
||||
let changed = false
|
||||
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()) {
|
||||
if (range.endIndex === boundary) {
|
||||
leftRight = Math.max(leftRight, groups[index]!.rightX)
|
||||
bordersGroup = true
|
||||
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.startIndex === boundary + 1) {
|
||||
rightLeft = Math.min(rightLeft, groups[index]!.leftX)
|
||||
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 (!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
|
||||
}
|
||||
if (!changed) return adjusted
|
||||
}
|
||||
return adjusted
|
||||
}
|
||||
@@ -483,7 +475,6 @@ export function createSequencePlacementPlan(
|
||||
},
|
||||
participants: [],
|
||||
groups: [],
|
||||
activations: [],
|
||||
steps: [],
|
||||
}
|
||||
}
|
||||
@@ -520,13 +511,9 @@ 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 ? participantLabelHeight - 1 : participantLabelHeight + 1)
|
||||
const participantRuleY = participantHeaderTopY + (compact ? 0 : 2)
|
||||
const lifelineStartY = participantRuleY + 1
|
||||
const stepStartY = lifelineStartY + 1
|
||||
const width = Math.max(contentBounds.rightX + 1, ...groups.map((group) => group.rightX + 1), fragments.rightX + 1)
|
||||
@@ -538,46 +525,19 @@ 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,
|
||||
labelLines,
|
||||
labelX: centeredStart(centerX, participant.label),
|
||||
}
|
||||
})
|
||||
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") {
|
||||
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
|
||||
}
|
||||
if (step.type === "activation") continue
|
||||
const stepHeight = getStepHeight(step, centers, indexes, compact)
|
||||
if (step.type === "note") {
|
||||
const noteIndexes = getParticipantIndexes(indexes, step.note.over)
|
||||
@@ -628,7 +588,6 @@ 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,
|
||||
@@ -636,11 +595,8 @@ export function createSequencePlacementPlan(
|
||||
centerX,
|
||||
rightX: centerX + selfMessageLoopWidthForLines(labelLines),
|
||||
topY: stepY,
|
||||
bottomY,
|
||||
bottomY: stepY + labelLines.length + 1,
|
||||
})
|
||||
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]!
|
||||
@@ -648,16 +604,13 @@ 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,
|
||||
labelX: leftX + 2,
|
||||
labelY: stepY,
|
||||
arrowY,
|
||||
arrowY: inlineLabel ? stepY : stepY + labelLines.length,
|
||||
fromX,
|
||||
toX,
|
||||
leftX,
|
||||
@@ -666,23 +619,15 @@ 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,17 +47,6 @@ 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
|
||||
@@ -66,7 +55,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", () => {
|
||||
@@ -199,7 +188,7 @@ stateDiagram-v2
|
||||
●───────────────────────▶│ Running │
|
||||
╰──┬──────╯ 💥 sandbox dies BEFORE hook fires
|
||||
▲ │ ▲ (crash, our bug, race)
|
||||
╭────────┼─┴───┼───────╮
|
||||
╭────────┼─╰───┼───────╮
|
||||
▼ ╭────┼─────╯ ▼
|
||||
╭──────┴──╮ │ ╭──────╮
|
||||
│ Dormant │ │ │ Lost │
|
||||
@@ -395,7 +384,7 @@ stateDiagram-v2
|
||||
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─────────╮ submit ok ╭───────╮
|
||||
●────────────▶│ Editing ├────────────▶◆────────────▶│ Saved │
|
||||
●────────────▶│ Editing ├─────────────┬────────────▶│ Saved │
|
||||
╰──┬──────╯ │ ╰───────╯
|
||||
▲ │ ▲ type │ fail
|
||||
│ ╰────╯ │
|
||||
@@ -422,7 +411,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", () => {
|
||||
@@ -455,65 +444,6 @@ 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}
|
||||
@@ -631,46 +561,15 @@ stateDiagram-v2
|
||||
})
|
||||
expect(output).toMatchInlineSnapshot(`
|
||||
" ╭─ Authenticated ──────────────────╮
|
||||
│ │ save
|
||||
login │ ╭──────╮ open ╭─────────╮ │ logout
|
||||
●───────────┼▶│ Idle ├────────────▶│ Editing ├─┼──────────▶◎
|
||||
│ │
|
||||
login │ ╭──────╮ open ╭─────────╮ │ save
|
||||
●────────────▶│ 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
|
||||
@@ -701,91 +600,6 @@ stateDiagram-v2
|
||||
state Decision <<choice>>
|
||||
Decision --> [*]`)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
expect(output).toContain("╰─────────────┬\n")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -49,9 +49,7 @@ function translateTransitionPlans(
|
||||
function makeGrid(width: number, height: number): StateGrid {
|
||||
return new DiagramCanvas(width, height, {
|
||||
mergeCell: (existing, incoming): StateCell => {
|
||||
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")
|
||||
const shouldMerge = existing.style === "transition" && incoming.style === "transition"
|
||||
return {
|
||||
...incoming,
|
||||
char: shouldMerge
|
||||
@@ -200,8 +198,7 @@ function drawTransitionJunctionPlans(
|
||||
): void {
|
||||
for (const plan of createStateTransitionJunctionPlans(diagram, bounds, renderPlans)) {
|
||||
const style = plan.kind === "choice" ? "choice" : "transition"
|
||||
const char = plan.kind === "choice" ? "◆" : diagramLineGlyph(plan.connections, "rounded")
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, char, style)
|
||||
setCell(grid, plan.bounds.left, plan.bounds.top, diagramLineGlyph(plan.connections, "rounded"), style)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,14 @@ 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[]>()
|
||||
@@ -80,11 +88,8 @@ function outgoingTransitions(diagram: StateDiagram): Map<string, StateDiagramTra
|
||||
return outgoing
|
||||
}
|
||||
|
||||
function reaches(
|
||||
outgoing: ReadonlyMap<string, readonly StateDiagramTransition[]>,
|
||||
from: string,
|
||||
target: string,
|
||||
): boolean {
|
||||
function reaches(diagram: StateDiagram, from: string, target: string): boolean {
|
||||
const outgoing = outgoingTransitions(diagram)
|
||||
const visited = new Set<string>()
|
||||
const stack = [from]
|
||||
while (stack.length > 0) {
|
||||
@@ -99,7 +104,6 @@ function reaches(
|
||||
|
||||
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 []
|
||||
|
||||
@@ -110,14 +114,9 @@ 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) => 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)
|
||||
})
|
||||
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))
|
||||
if (!next) break
|
||||
path.push(next.to)
|
||||
visited.add(next.to)
|
||||
@@ -133,7 +132,7 @@ function stateSize(state: StateDiagramState): { width: number; height: number; l
|
||||
}
|
||||
|
||||
function noteLines(note: StateDiagramNote): string[] {
|
||||
const lines = note.lines.flatMap(splitDiagramLines).map((line) => line.trim())
|
||||
const lines = note.lines.flatMap(splitStateDiagramLines).map((line) => line.trim())
|
||||
return lines.length > 0 ? lines : [""]
|
||||
}
|
||||
|
||||
@@ -203,7 +202,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, diagramTextWidth(composite.label) + 5)
|
||||
const width = Math.max(right - left, visualLength(composite.label) + 5)
|
||||
const bound = {
|
||||
id: composite.id,
|
||||
left,
|
||||
@@ -350,7 +349,7 @@ function expandCompositeBoundsForNotes(diagram: StateDiagram, layout: StateDiagr
|
||||
|
||||
bound.left = left
|
||||
bound.top = top
|
||||
bound.width = Math.max(right - left, diagramTextWidth(composite.label) + 5)
|
||||
bound.width = Math.max(right - left, visualLength(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)
|
||||
@@ -462,8 +461,7 @@ export function createStateDiagramLayout(
|
||||
x += size.width + options.minStateGap + 8
|
||||
}
|
||||
const labelRows = states.reduce((rows, state) => Math.max(rows, outgoingLabelRows.get(state.id) ?? 0), 0)
|
||||
const pseudoStateApproachClearance = states.some((state) => state.kind === "choice") ? 2 : 0
|
||||
y += rowHeight + Math.max(4, labelRows + 3) + pseudoStateApproachClearance
|
||||
y += rowHeight + Math.max(4, labelRows + 3)
|
||||
}
|
||||
|
||||
return finalizeLayout(diagram, emptyLayout(bounds, sizes))
|
||||
@@ -501,10 +499,7 @@ 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)
|
||||
const crossesCompositeBoundary = Boolean(
|
||||
nextId && statesById.get(id)?.parentId !== statesById.get(nextId)?.parentId,
|
||||
)
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + (crossesCompositeBoundary ? 6 : 2))
|
||||
x += size.width + Math.max(defaultGap, adjacentLabelWidth + 2)
|
||||
}
|
||||
|
||||
const branchesByParent = new Map<string, string[]>()
|
||||
@@ -555,25 +550,12 @@ function createHorizontalLayout(diagram: StateDiagram, options: StateDiagramLayo
|
||||
}
|
||||
|
||||
const ranks = computeRanks(diagram)
|
||||
const fallbackStates = diagram.states
|
||||
.filter((state) => !bounds.has(state.id))
|
||||
.sort((left, right) => (ranks.get(left.id) ?? 0) - (ranks.get(right.id) ?? 0))
|
||||
const fallbackStates = diagram.states.filter((state) => !bounds.has(state.id))
|
||||
for (const state of fallbackStates) {
|
||||
const size = sizes.get(state.id)!
|
||||
const top = baselineY + 5
|
||||
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
|
||||
}
|
||||
const top = baselineY + 5
|
||||
const left = rank * (size.width + defaultGap)
|
||||
bounds.set(state.id, {
|
||||
id: state.id,
|
||||
left,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { decodeMermaidText, firstMeaningfulMermaidLine, numberedMermaidLines } from "../core/mermaid.js"
|
||||
import { 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.map(decodeMermaidText),
|
||||
lines: pendingNote.lines,
|
||||
})
|
||||
pendingNote = undefined
|
||||
} else if (line || pendingNote.lines.length > 0) {
|
||||
@@ -119,9 +119,6 @@ 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
|
||||
}
|
||||
@@ -131,7 +128,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
notes.push({
|
||||
position: inlineNoteMatch[1]!.toLowerCase() as "left" | "right",
|
||||
target: inlineNoteMatch[2]!,
|
||||
lines: splitDiagramLines(decodeMermaidText(inlineNoteMatch[3]!.trim())),
|
||||
lines: splitDiagramLines(inlineNoteMatch[3]!.trim()),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -153,7 +150,7 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
const id = compositeMatch[2]!
|
||||
composites.push({
|
||||
id,
|
||||
label: decodeMermaidText(compositeMatch[1] ?? id),
|
||||
label: compositeMatch[1] ?? id,
|
||||
...(parentId ? { parentId } : {}),
|
||||
})
|
||||
parentStack.push({ id, lineNumber: source.lineNumber, sourceLine: line })
|
||||
@@ -162,13 +159,13 @@ export function parseMermaidStateDiagram(content: string): StateDiagram {
|
||||
|
||||
const stateMatch = line.match(STATE_RE)
|
||||
if (stateMatch) {
|
||||
ensureState(states, stateMatch[2]!, decodeMermaidText(stateMatch[1]!), "state", parentId)
|
||||
ensureState(states, stateMatch[2]!, 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
|
||||
}
|
||||
|
||||
@@ -180,7 +177,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: decodeMermaidText(transitionMatch[3]?.trim() ?? "") })
|
||||
transitions.push({ from, to, label: transitionMatch[3]?.trim() ?? "" })
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
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 type { StateVisibleDiagram } from "./visible-model.js"
|
||||
import { prepareVisibleStateDiagram } from "./visible-model.js"
|
||||
import { prepareVisibleStateDiagram, type StateVisibleDiagram } 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 }
|
||||
@@ -210,39 +207,6 @@ 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,6 +1,5 @@
|
||||
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"
|
||||
@@ -11,15 +10,14 @@ 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; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "top-feedback"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number; approachX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "bottom-parallel"; railY: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical-elbow"; hasReverse: boolean; offsetConnector: boolean })
|
||||
| (StateTransitionRoutePlanBase & { kind: "side-parallel"; railX: number })
|
||||
| (StateTransitionRoutePlanBase & { kind: "vertical" })
|
||||
@@ -194,93 +192,6 @@ 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>,
|
||||
@@ -289,29 +200,16 @@ 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),
|
||||
)
|
||||
let nextSideRailX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + 3
|
||||
const sideLaneX = Math.max(0, ...[...bounds.values()].map((bound) => bound.left + bound.width)) + maxLabelWidth + 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)
|
||||
@@ -319,9 +217,8 @@ export function createStateTransitionRoutePlans(
|
||||
if (!from || !to) return []
|
||||
|
||||
const targetState = statesById.get(transition.to)
|
||||
const targetIsChoice = targetState?.kind === "choice"
|
||||
const targetIsHiddenMarker = isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice, targetIsHiddenMarker }
|
||||
const targetIsChoice = targetState?.kind === "choice" || isHiddenCompositeMarker(targetState)
|
||||
const base = { transition, from, to, targetIsChoice }
|
||||
if (transition.from === transition.to) return [{ ...base, kind: "self" }]
|
||||
const endpointKey = `${transition.from}\u0000${transition.to}`
|
||||
const parallelIndex = endpointOccurrences.get(endpointKey) ?? 0
|
||||
@@ -330,80 +227,30 @@ 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: "top-feedback",
|
||||
kind: feedbackAllocation.side === "bottom" ? "bottom-feedback" : "top-feedback",
|
||||
railY: feedbackAllocation.railY,
|
||||
},
|
||||
]
|
||||
}
|
||||
if (parallelIndex > 0) {
|
||||
if ((diagram.direction === "LR" || diagram.direction === "RL") && from.centerY === to.centerY) {
|
||||
const railY = allocateBottomRail()
|
||||
if (diagram.direction === "LR" || diagram.direction === "RL") {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
kind: "bottom-parallel",
|
||||
railY,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, railY),
|
||||
railY: feedbackLaneY + (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" }]
|
||||
return [{ ...base, kind: "side-parallel", railX: sideLaneX + (parallelIndex - 1) * parallelLaneGap }]
|
||||
}
|
||||
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,
|
||||
approachX: bottomApproachX(diagram, transition, from, to, bounds, feedbackLaneY),
|
||||
},
|
||||
]
|
||||
if (from.centerY > to.centerY && feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
const hasReverse = hasReverseTransition(diagram, transition)
|
||||
return [
|
||||
{
|
||||
@@ -414,26 +261,7 @@ export function createStateTransitionRoutePlans(
|
||||
},
|
||||
]
|
||||
}
|
||||
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),
|
||||
},
|
||||
]
|
||||
}
|
||||
if (feedback) return [{ ...base, kind: "bottom-feedback", railY: feedbackLaneY }]
|
||||
return [{ ...base, kind: "horizontal-forward", leftToRight: from.centerX <= to.centerX }]
|
||||
})
|
||||
}
|
||||
@@ -505,7 +333,7 @@ function addTopDeparture(builder: StateTransitionRenderBuilder, bounds: BoxBound
|
||||
}
|
||||
|
||||
function addHorizontalForward(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, leftToRight, transition } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, leftToRight, transition } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "horizontal-forward" }
|
||||
>
|
||||
@@ -515,12 +343,9 @@ 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, 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)
|
||||
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" })
|
||||
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))
|
||||
@@ -553,14 +378,14 @@ function outsideTopY(bounds: BoxBounds): number {
|
||||
}
|
||||
|
||||
function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY, approachX } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, transition, railY } = 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 : approachX
|
||||
const railTargetX = targetRailCutsSource ? Math.max(from.left + from.width, to.left + to.width) + 2 : targetX
|
||||
const sourceBottomY = outsideBottomY(from)
|
||||
const targetBottomY = outsideBottomY(to)
|
||||
addBottomDeparture(builder, from, sourceX)
|
||||
@@ -581,13 +406,8 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, { x, y: targetBottomY, char: "─" })
|
||||
}
|
||||
}
|
||||
addCell(
|
||||
builder,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetBottomY, char: "│" }
|
||||
: { x: targetX, y: targetBottomY, arrowDirection: "up" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
addCell(builder, { x: targetX, y: targetBottomY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "up" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - railTargetX) - 2
|
||||
@@ -599,7 +419,7 @@ function addBottomLaneTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railY } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, transition, railY } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "top-feedback" }
|
||||
>
|
||||
@@ -617,13 +437,8 @@ 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,
|
||||
targetIsHiddenMarker
|
||||
? { x: targetX, y: targetTopY, char: "│" }
|
||||
: { x: targetX, y: targetTopY, arrowDirection: "down" },
|
||||
)
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
addCell(builder, { x: targetX, y: targetTopY, ...(targetIsChoice ? { char: "│" } : { arrowDirection: "down" }) })
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
const horizontalRoom = Math.abs(sourceX - targetX) - 2
|
||||
@@ -635,7 +450,7 @@ function addTopFeedbackTransition(builder: StateTransitionRenderBuilder): void {
|
||||
}
|
||||
|
||||
function addSideParallelTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, targetIsChoice, targetIsHiddenMarker, transition, railX } = builder.route as Extract<
|
||||
const { from, to, targetIsChoice, transition, railX } = builder.route as Extract<
|
||||
StateTransitionRoutePlan,
|
||||
{ kind: "side-parallel" }
|
||||
>
|
||||
@@ -650,16 +465,9 @@ 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,
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
@@ -668,8 +476,10 @@ function innerConnectorX(bounds: BoxBounds, preferredX: number): number {
|
||||
}
|
||||
|
||||
function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker, hasReverse, offsetConnector } =
|
||||
builder.route as Extract<StateTransitionRoutePlan, { kind: "vertical-elbow" }>
|
||||
const { from, to, transition, targetIsChoice, 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)
|
||||
@@ -703,19 +513,13 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
}
|
||||
}
|
||||
const targetChar = targetIsHiddenMarker
|
||||
? hasTargetApproach || startX === endX
|
||||
? "│"
|
||||
: topToBottom
|
||||
? "┬"
|
||||
: "┴"
|
||||
: undefined
|
||||
const targetChar = targetIsChoice ? (hasTargetApproach || startX === endX ? "│" : topToBottom ? "┬" : "┴") : undefined
|
||||
addCell(builder, {
|
||||
x: endX,
|
||||
y: endY,
|
||||
...(targetChar ? { char: targetChar } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (!transition.label) return
|
||||
const metrics = measureStateTransitionLabel(transition.label)
|
||||
if (topToBottom) {
|
||||
@@ -739,7 +543,7 @@ function addVerticalElbowTransition(builder: StateTransitionRenderBuilder): void
|
||||
}
|
||||
|
||||
function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
const { from, to, transition, targetIsChoice, targetIsHiddenMarker } = builder.route
|
||||
const { from, to, transition, targetIsChoice } = builder.route
|
||||
const topToBottom = from.centerY <= to.centerY
|
||||
const x = from.centerX
|
||||
const startY = topToBottom ? from.top + from.height : from.top - 1
|
||||
@@ -751,9 +555,9 @@ function addVerticalTransition(builder: StateTransitionRenderBuilder): void {
|
||||
addCell(builder, {
|
||||
x,
|
||||
y: endY,
|
||||
...(targetIsHiddenMarker ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
...(targetIsChoice ? { char: "│" } : { arrowDirection: topToBottom ? "down" : "up" }),
|
||||
})
|
||||
if (targetIsChoice || targetIsHiddenMarker) addPathPoint(builder, to.left, to.top)
|
||||
if (targetIsChoice) addPathPoint(builder, to.left, to.top)
|
||||
if (transition.label) addLabel(builder, x + 2, Math.min(startY, endY) + 1, transition.label)
|
||||
}
|
||||
|
||||
@@ -786,47 +590,69 @@ 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[] {
|
||||
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 })),
|
||||
),
|
||||
),
|
||||
)
|
||||
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 }]
|
||||
: []
|
||||
})
|
||||
|
||||
return plans.map((plan, planIndex) => {
|
||||
return plans.map((plan) => {
|
||||
if (!plan.label) return plan
|
||||
const width = Math.max(...plan.label.lines.map(diagramTextWidth))
|
||||
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,
|
||||
})
|
||||
if (plan.label.lines.length === 1) {
|
||||
placedLabels.push(labelRect(plan.label, width))
|
||||
return plan
|
||||
}
|
||||
const statePadding = 1
|
||||
const isClear = (x: number, y: number): boolean => {
|
||||
if (x < 0 || y < 0) return false
|
||||
return space.isFree(labelClaim(x, y), {
|
||||
clearance: {
|
||||
body: statePadding,
|
||||
label: { x: 1, y: 0 },
|
||||
},
|
||||
})
|
||||
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
|
||||
}
|
||||
|
||||
let x = plan.label.x
|
||||
@@ -846,7 +672,7 @@ function placeStateTransitionLabels(
|
||||
}
|
||||
}
|
||||
|
||||
space = space.add(labelClaim(x, y))
|
||||
placedLabels.push(labelRect({ ...plan.label, x, y }, width))
|
||||
return { ...plan, label: { ...plan.label, x, y } }
|
||||
})
|
||||
}
|
||||
@@ -877,7 +703,6 @@ 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
|
||||
@@ -888,7 +713,7 @@ export function createStateTransitionJunctionPlans(
|
||||
const connections = new Set<DiagramDirection>()
|
||||
const transitions: StateVisibleTransition[] = []
|
||||
for (const transition of diagram.transitions) {
|
||||
const renderPlan = renderPlanByTransition.get(transition)
|
||||
const renderPlan = renderPlans.find((plan) => plan.route.transition === transition)
|
||||
let connected = false
|
||||
if (transition.to === state.id) {
|
||||
const junction = renderPlan?.path.at(-1)
|
||||
|
||||
@@ -20,43 +20,6 @@ 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<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" })
|
||||
expect(exit).toMatchObject({ from: "Editing", to: "__end", label: "save" })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,7 +11,7 @@ export function isHiddenCompositeMarker(state: StateDiagramState | undefined): b
|
||||
}
|
||||
|
||||
function composeTransitionLabel(incoming: StateDiagramTransition, outgoing: StateDiagramTransition): string {
|
||||
return [incoming.label, outgoing.label].filter(Boolean).join("<br/>")
|
||||
return incoming.label || outgoing.label
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitionsOnce(
|
||||
@@ -23,28 +23,33 @@ 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
|
||||
|
||||
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,
|
||||
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),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { transitions: [...transitions], changed: false }
|
||||
return {
|
||||
transitions: [...transitions.filter((transition) => !skipped.has(transition)), ...collapsed],
|
||||
changed,
|
||||
}
|
||||
}
|
||||
|
||||
function collapseHiddenCompositeMarkerTransitions(diagram: StateDiagram): StateVisibleTransition[] {
|
||||
|
||||
@@ -26,21 +26,6 @@ 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
|
||||
@@ -56,12 +41,6 @@ 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
|
||||
@@ -76,17 +55,6 @@ 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
|
||||
|
||||
@@ -38,7 +38,6 @@ export function permissionPresentation(
|
||||
title: `Edit ${formatPath(file)}`,
|
||||
lines: [],
|
||||
diff,
|
||||
patch: diff ? undefined : text(input.patchText) || undefined,
|
||||
file,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ describe("run permission shared", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("uses source patch text when an edit has no generated diff", () => {
|
||||
test("uses the resource display when an edit has no generated diff", () => {
|
||||
const patch = '*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+const arrow = "→"\n*** End Patch'
|
||||
const request = req({
|
||||
action: "edit",
|
||||
@@ -171,13 +171,11 @@ describe("run permission shared", () => {
|
||||
expect(permissionInfo(request)).toMatchObject({
|
||||
title: "Edit src/index.ts",
|
||||
diff: undefined,
|
||||
patch,
|
||||
})
|
||||
expect(permissionInfo(request, undefined, true)).toMatchObject({
|
||||
title: "Edit src/index.ts",
|
||||
lines: [patch],
|
||||
lines: [],
|
||||
diff: undefined,
|
||||
patch: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user