mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-11-20 21:23:22 +03:00
feat(editor): lay Mermaid diagrams out with Pele (mermaid-to-excalidraw v3) (#12480)
* chore: type-check linked packages' `@excalidraw/excalidraw/{element,common}/*` imports against the sources
Packages linked into the monorepo (e.g. a local `@excalidraw/mermaid-to-excalidraw`)
import types from `@excalidraw/excalidraw/element/*` and `.../common/*`, which
didn't map to the sources and fell back to the linked package's own (published)
copy of `@excalidraw/excalidraw`, failing the type check. The mocked arrows in
the Mermaid tests now use the `LocalPoint` their points are typed as.
Claude Opus 5.5 (xhigh)
* feat(editor): TTD Mermaid errors on their source line, with guidance by diagram type
- Mermaid (and Pele) number lines as they parse the definition: without its
front matter, directives, comment lines and leading blank lines (and in
flowcharts and ER diagrams, a line ending with a comment runs on into the
next one). Errors are now mapped back to the line of the source they're on
for the highlighted line, the summary, the shown message, the auto-fixer and
the AI repair prompt. Errors past the end (e.g. a missing `end`) are on its
last non-empty line.
- The likely causes depend on the diagram type: an unclosed class body,
composite state or entity (not "a decision node"), sequence blocks missing
their `end`, labels with brackets or parentheses that need quoting, `end`
used as a node.
- Definitions without a (known) diagram type get a summary and hint, and their
first line is highlighted. Mermaid and Pele word that error differently.
Claude Opus 5.5 (xhigh)
* feat(editor): auto-fix more common Mermaid mistakes in TTD
New auto-fix candidates (each still only offered if it parses):
- quote labels with brackets or parentheses in them:
`A[Process (main)]` -> `A["Process (main)"]`
- close unclosed blocks (`subgraph`/`loop`/... `end`s, class/state/entity
`}`s) where their indentation ends, not only at the end of the definition
- close a node label left open before its edge (`A[Start --> B` ->
`A[Start] --> B`), and drop closing brackets that close nothing
- `->` -> `-->` in flowcharts and state diagrams (labels left alone)
- `end` used as a flowchart node -> `End`
- the `:` missing before a sequence message's or ER relationship's label
- an invalid flowchart direction -> `TD`
- a misspelled diagram type (`flowchar TD`, `sequencediagram`), or a missing
one
Claude Opus 5.5 (xhigh)
* feat(editor): fix and explain invalid or misplaced directions in TTD Mermaid
- A flowchart subgraph's `direction` is uppercased (`lr` -> `LR`), `TD` is
`TB` there (unlike in the flowchart's header), and one that isn't any
direction is dropped, for the subgraph to keep the flowchart's.
- A direction on the first line of a class, state or ER diagram
(`classDiagram LR`, `erDiagram direction LR`) is moved to a `direction`
statement on the next line, unless the diagram has one already.
- Sequence diagrams have no direction: it's dropped from their first line and
their `direction` statements.
- The likely causes explain all of these.
Claude Opus 5.5 (xhigh)
* feat(editor): mark TTD assistant messages rendered with Pele
Assistant messages are saved with the chat with `renderer: "pele"`, to tell
their diagrams from those of chats saved before mermaid-to-excalidraw v3,
which Mermaid rendered (and which can't be told apart later).
Claude Opus 5.5 (xhigh)
* feat(editor): paste `swimlane-beta` diagrams as Mermaid
mermaid-to-excalidraw v3 converts them (Pele renders them, Mermaid doesn't),
but pasting one inserted it as text, as `swimlane` wasn't a diagram type
that marks pasted text as Mermaid.
Claude Opus 5.5 (xhigh)
* feat(editor): lay Mermaid diagrams out with Pele (mermaid-to-excalidraw 3.0.0)
mermaid-to-excalidraw 3.0.0 parses and lays out diagrams with Pele instead
of Mermaid, which is no longer bundled. It keeps labels where Pele placed
them along their arrows with `label.labelPosition`, which skeleton arrows
support since #12425.
Claude Opus 5.5 (xhigh)
* docs: changelog for mermaid-to-excalidraw v3 and skeleton bound arrows
Claude Opus 5.5 (xhigh)
This commit is contained in:
1 parent
c711e80ec5
commit
14bb42edee
16 files changed
+1227
-862
No files matched your search
@@ -162,6 +162,8 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
|
||||
|
||||
### Other Breaking changes
|
||||
|
||||
- `convertToExcalidrawElements()` places bound arrows where their bindings put them, as the editor does whenever it updates their bindings (e.g. on undo/redo, or moving what they're bound to), instead of keeping their ends exactly where given. An end given just short of what it's bound to is extended onto it, and one beyond its binding area is unbound. Shapes created from an arrow's `start`/`end` are placed along its end segment. [#12425](https://github.com/excalidraw/excalidraw/pull/12425)
|
||||
|
||||
- `UIAppState` no longer includes `zoom`, `shouldCacheIgnoreZoom`, and the canvas-interaction transients `snapLines`, `originSnapOffset`, `suggestedBinding`, `frameToHighlight`, and `elementsToHighlight`. These update per pointermove or per animation frame and no longer re-render the editor UI, so UI render props receiving `UIAppState` (`renderCustomStats`, custom `<Footer/>` content, etc.) don't receive them anymore and would render stale values if they read them off the full `AppState`. Subscribe through `useExcalidrawStateValue` instead — the component re-renders only when the selected value changes:
|
||||
|
||||
```tsx
|
||||
@@ -195,6 +197,10 @@ The toolbar UI was rewritten from hidden radio/checkbox inputs to real `<button>
|
||||
|
||||
### Other Features
|
||||
|
||||
- Mermaid diagrams (in the TTD dialog and on paste) are converted with `@excalidraw/mermaid-to-excalidraw` v3, which lays them out with [Pele](https://pele.run) instead of Mermaid, no longer bundled. Layouts differ from before, and `swimlane-beta` diagrams are supported. [#12480](https://github.com/excalidraw/excalidraw/pull/12480)
|
||||
|
||||
- `label.labelPosition` (0–1) of skeleton arrows places their label along the arrow, instead of halfway. [#12425](https://github.com/excalidraw/excalidraw/pull/12425)
|
||||
|
||||
- Added `ExcalidrawAPI.isDestroyed` flag. Set to `true` once the editor unmounts. Calling any `get*` method, `onStateChange`, or `onEvent` on a destroyed API instance will throw in development and `console.error` in production. The `ExcalidrawAPI` will be reset to `null` on unmount, but to be extra safe, you should check `ExcalidrawAPI.isDestroyed` before calling these methods to guard against subtle race conditions in your code.
|
||||
|
||||
- Added `onMount`, `onInitialize`, and `onUnmount` props. `onMount` receives `{ excalidrawAPI, container }` once the editor root is mounted. `onInitialize` fires once the initial scene has loaded. `onUnmount` fires just before unmounting.
|
||||
|
||||
@@ -26,6 +26,9 @@ export const useChatAgent = () => {
|
||||
type: "assistant",
|
||||
content: "",
|
||||
isGenerating: true,
|
||||
// saved with the chat, to tell its diagrams from those of chats
|
||||
// saved before
|
||||
renderer: "pele",
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
@@ -47,7 +47,7 @@ export const TTDDialogOutput = ({
|
||||
const errorMessage = parseError
|
||||
? hideErrorDetails
|
||||
? t("chat.errors.mermaidParseError")
|
||||
: formatMermaidParseErrorMessage(parseError.message)
|
||||
: formatMermaidParseErrorMessage(parseError.message, sourceText)
|
||||
: null;
|
||||
const syntaxGuidance =
|
||||
parseError && !hideErrorDetails
|
||||
|
||||
@@ -24,6 +24,7 @@ import { TTDChatPanel } from "./Chat/TTDChatPanel";
|
||||
import { TTDPreviewPanel } from "./TTDPreviewPanel";
|
||||
|
||||
import { getLastAssistantMessage } from "./utils/chat";
|
||||
import { withMermaidSourceLineNumber } from "./utils/mermaidError";
|
||||
|
||||
import type { BinaryFiles } from "../../types";
|
||||
import type {
|
||||
@@ -151,7 +152,10 @@ const TextToDiagramContent = ({
|
||||
|
||||
const handleAiRepairClick = async (message: TChat.ChatMessage) => {
|
||||
const mermaidContent = message.content || "";
|
||||
const errorMessage = message.error || "";
|
||||
const errorMessage = withMermaidSourceLineNumber(
|
||||
message.error || "",
|
||||
mermaidContent,
|
||||
);
|
||||
|
||||
if (!mermaidContent) {
|
||||
return;
|
||||
|
||||
@@ -36,6 +36,12 @@ export namespace TChat {
|
||||
warningType?: /* daily rate limit */
|
||||
"messageLimitExceeded" | /* general 429 */ "rateLimitExceeded";
|
||||
content?: string;
|
||||
/**
|
||||
* What an assistant's diagram was rendered with: Pele, since
|
||||
* `@excalidraw/mermaid-to-excalidraw` v3. Not set on (saved) messages
|
||||
* from before, which were rendered with Mermaid.
|
||||
*/
|
||||
renderer?: "pele";
|
||||
};
|
||||
|
||||
export type ChatHistory = {
|
||||
|
||||
@@ -113,4 +113,256 @@ Expecting 'NODE_STRING', got 'GT'`;
|
||||
participant QAEngineer as QA
|
||||
QA->>QA: Verifies Fix`);
|
||||
});
|
||||
|
||||
it("quotes node labels with brackets or parentheses in them", () => {
|
||||
const sourceText = `flowchart TD
|
||||
A[Process (main)] --> B{Valid (yes/no)?}
|
||||
B --> C(Retry [x])`;
|
||||
|
||||
const errorMessage = `Parse error on line 2:
|
||||
A[Process (main)] --> B{Valid (yes/no)?}
|
||||
------------^
|
||||
Expecting 'SQE', 'UNICODE_TEXT', 'TEXT', 'TAGSTART', got 'PS'`;
|
||||
|
||||
expect(getMermaidAutoFixCandidates(sourceText, errorMessage)).toContain(
|
||||
`flowchart TD
|
||||
A["Process (main)"] --> B{"Valid (yes/no)?"}
|
||||
B --> C("Retry [x]")`,
|
||||
);
|
||||
});
|
||||
|
||||
it("closes a node label left open, before the edge after it", () => {
|
||||
const sourceText = `flowchart TD
|
||||
A[Start --> B
|
||||
B --> C`;
|
||||
|
||||
const errorMessage = `Parse error on line 3:
|
||||
B --> C
|
||||
-------^
|
||||
Expecting 'SQE', got '$end'`;
|
||||
|
||||
const candidates = getMermaidAutoFixCandidates(sourceText, errorMessage);
|
||||
expect(candidates).toContain(`flowchart TD
|
||||
A[Start] --> B
|
||||
B --> C`);
|
||||
// never by emptying the line
|
||||
expect(candidates).not.toContain(`flowchart TD\n\n B --> C`);
|
||||
// before closing it at the end of the line
|
||||
expect(
|
||||
candidates.indexOf(`flowchart TD
|
||||
A[Start] --> B
|
||||
B --> C`),
|
||||
).toBeLessThan(
|
||||
candidates.indexOf(`flowchart TD
|
||||
A[Start --> B]
|
||||
B --> C`),
|
||||
);
|
||||
});
|
||||
|
||||
it("drops closing brackets that close nothing", () => {
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"flowchart TD\n A --> B]\n B --> C",
|
||||
"Lexical error on line 2. Unrecognized text.\n A --> B]\n---------^",
|
||||
),
|
||||
).toContain("flowchart TD\n A --> B\n B --> C");
|
||||
});
|
||||
|
||||
it("turns flowchart and state diagram `->` into `-->`, outside labels", () => {
|
||||
const errorMessage = `Parse error on line 2:
|
||||
A -> B
|
||||
----^
|
||||
Expecting 'SEMI', 'NEWLINE', 'EOF', got 'MINUS'`;
|
||||
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
`flowchart TD\n A -> B["x -> y"]\n B -> C`,
|
||||
errorMessage,
|
||||
),
|
||||
).toContain(`flowchart TD\n A --> B["x -> y"]\n B --> C`);
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"stateDiagram-v2\n [*] -> Idle : go -> stop\n Idle --> [*]",
|
||||
errorMessage,
|
||||
),
|
||||
).toContain("stateDiagram-v2\n [*] --> Idle : go -> stop\n Idle --> [*]");
|
||||
});
|
||||
|
||||
it("renames `end` used as a flowchart node", () => {
|
||||
const sourceText = `flowchart TD
|
||||
subgraph S
|
||||
A --> end
|
||||
end
|
||||
end --> B`;
|
||||
|
||||
const errorMessage = `Parse error on line 3:
|
||||
A --> end
|
||||
----------^
|
||||
Expecting 'NODE_STRING', got 'end'`;
|
||||
|
||||
expect(getMermaidAutoFixCandidates(sourceText, errorMessage)).toContain(
|
||||
`flowchart TD
|
||||
subgraph S
|
||||
A --> End
|
||||
end
|
||||
End --> B`,
|
||||
);
|
||||
});
|
||||
|
||||
it("closes unclosed blocks where their indentation ends", () => {
|
||||
const sourceText = `classDiagram
|
||||
class Animal {
|
||||
+int age
|
||||
Animal <|-- Duck`;
|
||||
|
||||
const errorMessage = `Parse error on line 4:
|
||||
Animal <|-- Duck
|
||||
------------------^
|
||||
Expecting 'STRUCT_STOP', got 'EOF_IN_STRUCT'`;
|
||||
|
||||
expect(getMermaidAutoFixCandidates(sourceText, errorMessage)[0]).toBe(
|
||||
`classDiagram
|
||||
class Animal {
|
||||
+int age
|
||||
}
|
||||
Animal <|-- Duck`,
|
||||
);
|
||||
});
|
||||
|
||||
it("appends the `end`s of unclosed sequence blocks", () => {
|
||||
const sourceText = `sequenceDiagram
|
||||
Alice->>Bob: hi
|
||||
loop Every minute
|
||||
Bob->>Alice: ping`;
|
||||
|
||||
const errorMessage = `Parse error on line 4:
|
||||
Bob->>Alice: ping
|
||||
---------------------^
|
||||
Expecting 'end', got '$end'`;
|
||||
|
||||
expect(getMermaidAutoFixCandidates(sourceText, errorMessage)).toContain(
|
||||
`${sourceText}\n end`,
|
||||
);
|
||||
});
|
||||
|
||||
it("adds the colon missing before a message or relationship label", () => {
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"sequenceDiagram\n Alice->>Bob hi there\n Bob->>Alice: ok",
|
||||
"Parse error on line 2:\n Alice->>Bob hi there\n----------------------^\nExpecting 'TXT', got 'NEWLINE'",
|
||||
),
|
||||
).toContain("sequenceDiagram\n Alice->>Bob: hi there\n Bob->>Alice: ok");
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"erDiagram\n CUSTOMER ||--o{ ORDER places",
|
||||
"Parse error on line 2:\n CUSTOMER ||--o{ ORDER places\n------------------------^\nExpecting 'COLON', got 'UNICODE_TEXT'",
|
||||
),
|
||||
).toContain("erDiagram\n CUSTOMER ||--o{ ORDER : places");
|
||||
});
|
||||
|
||||
it("fixes an invalid flowchart direction", () => {
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"flowchart XY\n A --> B",
|
||||
"Lexical error on line 1. Unrecognized text.\nflowchart XY\n---------^",
|
||||
),
|
||||
).toContain("flowchart TD\n A --> B");
|
||||
});
|
||||
|
||||
it("fixes flowchart subgraphs' directions, and drops sequence diagrams' ones", () => {
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
`flowchart LR
|
||||
subgraph A
|
||||
direction lr
|
||||
a1 --> a2
|
||||
end
|
||||
subgraph B
|
||||
direction TD
|
||||
b1 --> b2
|
||||
end
|
||||
subgraph C
|
||||
direction sideways
|
||||
c1 --> c2
|
||||
end`,
|
||||
"Lexical error on line 3. Unrecognized text.\n direction lr\n--------------^",
|
||||
),
|
||||
).toContain(`flowchart LR
|
||||
subgraph A
|
||||
direction LR
|
||||
a1 --> a2
|
||||
end
|
||||
subgraph B
|
||||
direction TB
|
||||
b1 --> b2
|
||||
end
|
||||
subgraph C
|
||||
c1 --> c2
|
||||
end`);
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"sequenceDiagram\n direction LR\n Alice->>Bob: hi",
|
||||
"Parse error on line 2:\n direction LR\n----^",
|
||||
),
|
||||
).toContain("sequenceDiagram\n Alice->>Bob: hi");
|
||||
});
|
||||
|
||||
it("moves a direction off the first line of class, state and ER diagrams", () => {
|
||||
const fix = (sourceText: string) =>
|
||||
getMermaidAutoFixCandidates(
|
||||
sourceText,
|
||||
"Parse error on line 1:\nclassDiagram TD\n-------------^",
|
||||
);
|
||||
|
||||
expect(fix("classDiagram TD\n A <|-- B")).toContain(
|
||||
"classDiagram\n direction TB\n A <|-- B",
|
||||
);
|
||||
expect(fix("erDiagram direction LR\n A ||--o{ B : x")).toContain(
|
||||
"erDiagram\n direction LR\n A ||--o{ B : x",
|
||||
);
|
||||
// they have one already: theirs, not a second one
|
||||
expect(fix("classDiagram TD\n direction TB\n A <|-- B")).toContain(
|
||||
"classDiagram\n direction TB\n A <|-- B",
|
||||
);
|
||||
expect(
|
||||
fix("classDiagram TD\n direction TB\n A <|-- B"),
|
||||
).not.toContainEqual(expect.stringMatching(/direction[^]*direction/));
|
||||
// a composite state's isn't the diagram's
|
||||
expect(
|
||||
fix(
|
||||
"stateDiagram-v2 direction LR\n state X {\n direction TB\n [*] --> A\n }",
|
||||
),
|
||||
).toContain(
|
||||
"stateDiagram-v2\n direction LR\n state X {\n direction TB\n [*] --> A\n }",
|
||||
);
|
||||
// not a direction
|
||||
expect(fix("classDiagram sideways\n A <|-- B")).toContain(
|
||||
"classDiagram\n A <|-- B",
|
||||
);
|
||||
// sequence diagrams have none
|
||||
expect(fix("sequenceDiagram LR\n Alice->>Bob: hi")).toContain(
|
||||
"sequenceDiagram\n Alice->>Bob: hi",
|
||||
);
|
||||
});
|
||||
|
||||
it("fixes a misspelled or missing diagram type", () => {
|
||||
const errorMessage = "No diagram type detected for the given text.";
|
||||
|
||||
expect(
|
||||
getMermaidAutoFixCandidates("flowchar TD\n A --> B", errorMessage),
|
||||
).toEqual(["flowchart TD\n A --> B"]);
|
||||
expect(
|
||||
getMermaidAutoFixCandidates(
|
||||
"%% comment\nsequencediagram\n Alice->>Bob: hi",
|
||||
errorMessage,
|
||||
),
|
||||
).toEqual(["%% comment\nsequenceDiagram\n Alice->>Bob: hi"]);
|
||||
expect(
|
||||
getMermaidAutoFixCandidates("A --> B\n B --> C", errorMessage),
|
||||
).toEqual(["flowchart TD\nA --> B\n B --> C"]);
|
||||
// not anything
|
||||
expect(
|
||||
getMermaidAutoFixCandidates("gantt\n title A", errorMessage),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,17 @@
|
||||
import {
|
||||
getMermaidDiagramType,
|
||||
getMermaidEndBlockOpener,
|
||||
getMermaidErrorLineNumber,
|
||||
getMermaidHeaderLineIndex,
|
||||
getMermaidInactiveParticipant,
|
||||
isMermaidAutoFixableError,
|
||||
isMermaidParseSyntaxError,
|
||||
isMermaidUnknownDiagramError,
|
||||
MERMAID_END_LINE,
|
||||
} from "./mermaidError";
|
||||
|
||||
import type { MermaidDiagramType } from "./mermaidError";
|
||||
|
||||
const getErrorLineIndex = (message: string, sourceText: string) => {
|
||||
const lineNumber = getMermaidErrorLineNumber(message, sourceText);
|
||||
if (lineNumber == null) {
|
||||
@@ -95,17 +102,403 @@ const removeAllDeactivateForParticipant = (
|
||||
return removedAny ? remainingLines.join("\n") : null;
|
||||
};
|
||||
|
||||
const appendMissingEnds = (sourceText: string) => {
|
||||
const subgraphCount = (sourceText.match(/^\s*subgraph\b/gm) || []).length;
|
||||
const endCount = (sourceText.match(/^\s*end\s*$/gm) || []).length;
|
||||
const missingCount = subgraphCount - endCount;
|
||||
const getIndentation = (line: string) => line.match(/^\s*/)![0].length;
|
||||
|
||||
if (missingCount <= 0) {
|
||||
/**
|
||||
* Closes the blocks (e.g. `subgraph`, `loop`, `class X {`) that aren't, as
|
||||
* their indentation tells: before the first line after their (indented) body
|
||||
* that isn't indented deeper than them, or with `atEnd`, all at the end.
|
||||
*/
|
||||
const closeUnclosedBlocks = (
|
||||
sourceText: string,
|
||||
opener: RegExp,
|
||||
isCloser: RegExp,
|
||||
closer: string,
|
||||
{ atEnd = false } = {},
|
||||
) => {
|
||||
const lines = sourceText.trimEnd().split(/\r?\n/);
|
||||
const unclosed: number[] = [];
|
||||
lines.forEach((line, index) => {
|
||||
if (opener.test(line)) {
|
||||
unclosed.push(index);
|
||||
} else if (isCloser.test(line)) {
|
||||
unclosed.pop();
|
||||
}
|
||||
});
|
||||
if (!unclosed.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const endings = Array.from({ length: missingCount }, () => "end").join("\n");
|
||||
return `${sourceText.trimEnd()}\n${endings}`;
|
||||
// closers to insert before a line (or at the end, at `lines.length`)
|
||||
const insertions = new Map<number, string[]>();
|
||||
// innermost first
|
||||
for (const openerIndex of unclosed.reverse()) {
|
||||
const indentation = getIndentation(lines[openerIndex]);
|
||||
let index = openerIndex + 1;
|
||||
while (
|
||||
!atEnd &&
|
||||
index < lines.length &&
|
||||
(!lines[index].trim() || getIndentation(lines[index]) > indentation)
|
||||
) {
|
||||
index++;
|
||||
}
|
||||
// without an indented body, where the block ends is anyone's guess
|
||||
if (atEnd || index === openerIndex + 1) {
|
||||
index = lines.length;
|
||||
}
|
||||
while (index - 1 > openerIndex && !lines[index - 1].trim()) {
|
||||
index--;
|
||||
}
|
||||
const line = `${lines[openerIndex].match(/^\s*/)![0]}${closer}`;
|
||||
insertions.set(index, [...(insertions.get(index) ?? []), line]);
|
||||
}
|
||||
|
||||
const result: string[] = [];
|
||||
lines.forEach((line, index) => {
|
||||
result.push(...(insertions.get(index) ?? []), line);
|
||||
});
|
||||
result.push(...(insertions.get(lines.length) ?? []));
|
||||
return result.join("\n");
|
||||
};
|
||||
|
||||
const BRACE_BLOCK_OPENER = /\{\s*$/;
|
||||
const BRACE_BLOCK_CLOSER = /^\s*\}\s*$/;
|
||||
|
||||
/** `end`s and `}`s the diagram's unclosed blocks are missing */
|
||||
const getUnclosedBlockCandidates = (
|
||||
sourceText: string,
|
||||
type: MermaidDiagramType | null,
|
||||
) => {
|
||||
if (type === "class" || type === "state" || type === "er") {
|
||||
return [false, true].map((atEnd) =>
|
||||
closeUnclosedBlocks(
|
||||
sourceText,
|
||||
BRACE_BLOCK_OPENER,
|
||||
BRACE_BLOCK_CLOSER,
|
||||
"}",
|
||||
{ atEnd },
|
||||
),
|
||||
);
|
||||
}
|
||||
const opener = getMermaidEndBlockOpener(type) ?? /^\s*subgraph\b/;
|
||||
return [false, true].map((atEnd) =>
|
||||
closeUnclosedBlocks(sourceText, opener, MERMAID_END_LINE, "end", {
|
||||
atEnd,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies `transform` to the parts of a flowchart line outside its labels
|
||||
* (`[...]`, `(...)`, `{...}`, `|...|`, `"..."`).
|
||||
*/
|
||||
const mapOutsideLabels = (
|
||||
line: string,
|
||||
transform: (segment: string) => string,
|
||||
) => {
|
||||
let result = "";
|
||||
let segment = "";
|
||||
let depth = 0;
|
||||
let inQuotes = false;
|
||||
let inPipes = false;
|
||||
for (const char of line) {
|
||||
const isLabel = depth > 0 || inQuotes || inPipes;
|
||||
if (char === '"') {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (!inQuotes && char === "|" && depth === 0) {
|
||||
inPipes = !inPipes;
|
||||
} else if (!inQuotes && !inPipes && "[({".includes(char)) {
|
||||
depth++;
|
||||
} else if (!inQuotes && !inPipes && "])}".includes(char)) {
|
||||
depth = Math.max(0, depth - 1);
|
||||
}
|
||||
if (isLabel || depth > 0 || inQuotes || inPipes) {
|
||||
result += transform(segment) + char;
|
||||
segment = "";
|
||||
} else {
|
||||
segment += char;
|
||||
}
|
||||
}
|
||||
return result + transform(segment);
|
||||
};
|
||||
|
||||
// `A[Process (main)]` -> `A["Process (main)"]`: labels with brackets or
|
||||
// parentheses in them are only allowed quoted (skipping shapes that start
|
||||
// with a bracket, e.g. `[[subroutine]]`, `[(cylinder)]`, `((circle))`)
|
||||
const UNQUOTED_LABELS_WITH_BRACKETS: Array<[RegExp, string]> = [
|
||||
[/([\w-]+)\[(?![[(/\\])([^[\]"]*?[(){}][^[\]"]*?)\](?!\])/g, '$1["$2"]'],
|
||||
[/([\w-]+)\{(?!\{)([^{}"]*?[()[\]][^{}"]*?)\}(?!\})/g, '$1{"$2"}'],
|
||||
[/([\w-]+)\((?![([])([^()"]*?[[\]{}][^()"]*?)\)(?!\))/g, '$1("$2")'],
|
||||
[/([\w-]+)\((?![([])([^()"]*\([^()"]*\)[^()"]*)\)(?!\))/g, '$1("$2")'],
|
||||
];
|
||||
|
||||
const quoteLabelsWithBrackets = (text: string) =>
|
||||
UNQUOTED_LABELS_WITH_BRACKETS.reduce(
|
||||
(result, [pattern, replacement]) => result.replace(pattern, replacement),
|
||||
text,
|
||||
);
|
||||
|
||||
const FLOWCHART_ARROW = /\s*(?:<?-->|<?---|<?-\.->|-\.-|<?==>|===|--[ox])/;
|
||||
const SHAPE_CLOSERS: Record<string, string> = { "[": "]", "(": ")", "{": "}" };
|
||||
|
||||
/**
|
||||
* Closes a flowchart node's label left open on the line: before the edge
|
||||
* after it (`A[Start --> B` -> `A[Start] --> B`), or at the end of the line.
|
||||
*/
|
||||
const closeUnclosedShape = (line: string) => {
|
||||
const openers: number[] = [];
|
||||
let inQuotes = false;
|
||||
for (let index = 0; index < line.length; index++) {
|
||||
const char = line[index];
|
||||
if (char === '"') {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (!inQuotes && char in SHAPE_CLOSERS) {
|
||||
openers.push(index);
|
||||
} else if (!inQuotes && "])}".includes(char)) {
|
||||
openers.pop();
|
||||
}
|
||||
}
|
||||
if (!openers.length) {
|
||||
return [];
|
||||
}
|
||||
const opener = openers[openers.length - 1];
|
||||
const closer = SHAPE_CLOSERS[line[opener]];
|
||||
const arrow = line.slice(opener).search(FLOWCHART_ARROW);
|
||||
return [
|
||||
...(arrow > 0
|
||||
? [
|
||||
`${line.slice(0, opener + arrow)}${closer}${line.slice(
|
||||
opener + arrow,
|
||||
)}`,
|
||||
]
|
||||
: []),
|
||||
`${line.trimEnd()}${closer}`,
|
||||
];
|
||||
};
|
||||
|
||||
/** Drops the closing brackets on a flowchart line that close nothing */
|
||||
const removeUnmatchedClosers = (line: string) => {
|
||||
const openers: string[] = [];
|
||||
let inQuotes = false;
|
||||
let result = "";
|
||||
for (const char of line) {
|
||||
if (char === '"') {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (!inQuotes && char in SHAPE_CLOSERS) {
|
||||
openers.push(SHAPE_CLOSERS[char]);
|
||||
} else if (!inQuotes && "])}".includes(char)) {
|
||||
if (openers[openers.length - 1] !== char) {
|
||||
continue;
|
||||
}
|
||||
openers.pop();
|
||||
}
|
||||
result += char;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const replaceSingleDashArrows = (text: string) =>
|
||||
text.replace(/(^|[^-<=.])->(?!>)/g, "$1-->");
|
||||
|
||||
// `A -> B` -> `A --> B` (flowcharts and state diagrams have no `->`)
|
||||
const fixSingleDashArrows = (line: string) =>
|
||||
mapOutsideLabels(line, replaceSingleDashArrows);
|
||||
|
||||
// ... in state diagrams, before their transitions' label (`A -> B : x`)
|
||||
const fixStateSingleDashArrows = (line: string) => {
|
||||
const labelStart = line.indexOf(":");
|
||||
return labelStart === -1
|
||||
? replaceSingleDashArrows(line)
|
||||
: `${replaceSingleDashArrows(line.slice(0, labelStart))}${line.slice(
|
||||
labelStart,
|
||||
)}`;
|
||||
};
|
||||
|
||||
// `A --> end` -> `A --> End`: `end` closes subgraphs, it can't be a node
|
||||
const capitalizeEndNodes = (line: string) =>
|
||||
MERMAID_END_LINE.test(line)
|
||||
? line
|
||||
: mapOutsideLabels(line, (segment) =>
|
||||
segment.replace(/(^|[\s&;>])end(?=$|[\s&;[({]|--|==|-\.)/g, "$1End"),
|
||||
);
|
||||
|
||||
// `Alice->>Bob hi` -> `Alice->>Bob: hi`
|
||||
const addSequenceMessageColon = (line: string) =>
|
||||
line.replace(
|
||||
/^(\s*[^\s:]+?\s*(?:<<-->>|<<->>|-->>|->>|-->|->|--x|-x|--\)|-\))\s*[+-]?[^\s:]+)\s+([^\s:].*)$/,
|
||||
"$1: $2",
|
||||
);
|
||||
|
||||
// `A ||--o{ B places` -> `A ||--o{ B : places`
|
||||
const addRelationshipColon = (line: string) =>
|
||||
line.replace(
|
||||
/^(\s*[\w-]+\s+[|o{}]{1,2}(?:--|\.\.)[|o{}]{1,2}\s+[\w-]+)\s+([^\s:].*)$/,
|
||||
"$1 : $2",
|
||||
);
|
||||
|
||||
const FLOWCHART_DIRECTIONS = new Set(["TB", "TD", "BT", "RL", "LR"]);
|
||||
|
||||
// `flowchart XY` -> `flowchart TD`
|
||||
const fixFlowchartDirection = (line: string) =>
|
||||
line.replace(
|
||||
/^(\s*(?:flowchart|graph)\s+)(\S+)/,
|
||||
(match, keyword, direction) =>
|
||||
FLOWCHART_DIRECTIONS.has(direction.toUpperCase())
|
||||
? `${keyword}${direction.toUpperCase()}`
|
||||
: `${keyword}TD`,
|
||||
);
|
||||
|
||||
const countMatches = (text: string, pattern: RegExp) =>
|
||||
(text.match(pattern) || []).length;
|
||||
|
||||
const DIRECTION_STATEMENT = /^(\s*direction\s+)(\S+)\s*$/;
|
||||
// `TD` is only one in a flowchart's header
|
||||
const DIRECTION_STATEMENT_DIRECTIONS = new Set(["TB", "BT", "RL", "LR"]);
|
||||
|
||||
/**
|
||||
* `direction lr` -> `direction LR` in a flowchart's subgraphs, without the
|
||||
* statements that aren't any direction (for the subgraph to keep the
|
||||
* flowchart's), or with `remove`, without any (sequence diagrams have none).
|
||||
*/
|
||||
const fixDirectionStatements = (lines: string[], { remove = false } = {}) => {
|
||||
const result = lines.flatMap((line) => {
|
||||
const match = line.match(DIRECTION_STATEMENT);
|
||||
if (!match) {
|
||||
return [line];
|
||||
}
|
||||
const direction = match[2].toUpperCase() === "TD" ? "TB" : match[2];
|
||||
return !remove &&
|
||||
DIRECTION_STATEMENT_DIRECTIONS.has(direction.toUpperCase())
|
||||
? [`${match[1]}${direction.toUpperCase()}`]
|
||||
: [];
|
||||
});
|
||||
return result.join("\n");
|
||||
};
|
||||
|
||||
/**
|
||||
* A direction on the first line of a class (`classDiagram LR`), state or ER
|
||||
* diagram (`erDiagram direction LR`), which they only take as a `direction`
|
||||
* statement: `classDiagram` + `direction LR` on the next line (unless they
|
||||
* have one already). Sequence diagrams have none.
|
||||
*/
|
||||
const fixHeaderDirection = (
|
||||
sourceText: string,
|
||||
type: MermaidDiagramType | null,
|
||||
) => {
|
||||
const headerIndex = getMermaidHeaderLineIndex(sourceText);
|
||||
if (
|
||||
headerIndex === null ||
|
||||
(type !== "class" &&
|
||||
type !== "state" &&
|
||||
type !== "er" &&
|
||||
type !== "sequence")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const match = lines[headerIndex].match(/^(\s*\S+)\s+(.+?)\s*$/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
const [, header, rest] = match;
|
||||
const value = rest.match(/^(?:direction\s+)?(\S+)$/)?.[1];
|
||||
if (!value && type !== "sequence") {
|
||||
return null;
|
||||
}
|
||||
const direction = value?.toUpperCase() === "TD" ? "TB" : value?.toUpperCase();
|
||||
const bodyLines = lines.slice(headerIndex + 1);
|
||||
// the diagram's, not one of a composite state's (`state X {`)
|
||||
let depth = 0;
|
||||
const hasDirectionStatement = bodyLines.some((line) => {
|
||||
const isTopLevel = depth === 0;
|
||||
depth += countMatches(line, /\{/g) - countMatches(line, /\}/g);
|
||||
return isTopLevel && DIRECTION_STATEMENT.test(line);
|
||||
});
|
||||
const body = bodyLines.find((line) => line.trim());
|
||||
const statement =
|
||||
type !== "sequence" &&
|
||||
!hasDirectionStatement &&
|
||||
direction &&
|
||||
DIRECTION_STATEMENT_DIRECTIONS.has(direction)
|
||||
? [`${body?.match(/^\s*/)![0] || " "}direction ${direction}`]
|
||||
: [];
|
||||
return [
|
||||
...lines.slice(0, headerIndex),
|
||||
header,
|
||||
...statement,
|
||||
...lines.slice(headerIndex + 1),
|
||||
].join("\n");
|
||||
};
|
||||
|
||||
const DIAGRAM_KEYWORDS = [
|
||||
"flowchart",
|
||||
"graph",
|
||||
"sequenceDiagram",
|
||||
"classDiagram",
|
||||
"stateDiagram-v2",
|
||||
"stateDiagram",
|
||||
"erDiagram",
|
||||
];
|
||||
|
||||
const getEditDistance = (a: string, b: string) => {
|
||||
const distances = Array.from({ length: b.length + 1 }, (_, index) => index);
|
||||
for (let i = 1; i <= a.length; i++) {
|
||||
let previous = distances[0];
|
||||
distances[0] = i;
|
||||
for (let j = 1; j <= b.length; j++) {
|
||||
const current = distances[j];
|
||||
distances[j] = Math.min(
|
||||
distances[j] + 1,
|
||||
distances[j - 1] + 1,
|
||||
previous + (a[i - 1] === b[j - 1] ? 0 : 1),
|
||||
);
|
||||
previous = current;
|
||||
}
|
||||
}
|
||||
return distances[b.length];
|
||||
};
|
||||
|
||||
/**
|
||||
* Fixes the misspelled diagram type of a definition (`flowchar TD`,
|
||||
* `sequencediagram`), or declares it if it's missing, as its first line
|
||||
* suggests.
|
||||
*/
|
||||
const getDiagramTypeCandidates = (sourceText: string) => {
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const headerIndex = getMermaidHeaderLineIndex(sourceText);
|
||||
if (headerIndex === null) {
|
||||
return [];
|
||||
}
|
||||
const header = lines[headerIndex];
|
||||
const [, indentation, keyword, rest] = header.match(/^(\s*)(\S+)(.*)$/)!;
|
||||
const withHeader = (nextHeader: string) =>
|
||||
[
|
||||
...lines.slice(0, headerIndex),
|
||||
nextHeader,
|
||||
...lines.slice(headerIndex + 1),
|
||||
].join("\n");
|
||||
const withHeaderBefore = (newHeader: string) =>
|
||||
[
|
||||
...lines.slice(0, headerIndex),
|
||||
newHeader,
|
||||
...lines.slice(headerIndex),
|
||||
].join("\n");
|
||||
|
||||
const [closest] = DIAGRAM_KEYWORDS.map((candidate) => ({
|
||||
candidate,
|
||||
distance: getEditDistance(keyword.toLowerCase(), candidate.toLowerCase()),
|
||||
})).sort((a, b) => a.distance - b.distance);
|
||||
const candidates: string[] = [];
|
||||
if (closest.distance <= Math.min(2, Math.floor(keyword.length / 3))) {
|
||||
candidates.push(withHeader(`${indentation}${closest.candidate}${rest}`));
|
||||
}
|
||||
// no diagram type at all
|
||||
if (/-->>|->>/.test(header)) {
|
||||
candidates.push(withHeaderBefore("sequenceDiagram"));
|
||||
} else if (/-->|---|==>|-\.->/.test(header)) {
|
||||
candidates.push(withHeaderBefore("flowchart TD"));
|
||||
}
|
||||
return candidates;
|
||||
};
|
||||
|
||||
const normalizeSmartQuotes = (sourceText: string) =>
|
||||
@@ -129,6 +522,11 @@ export const getMermaidAutoFixCandidates = (
|
||||
candidates.push(candidate);
|
||||
};
|
||||
|
||||
if (isMermaidUnknownDiagramError(errorMessage)) {
|
||||
getDiagramTypeCandidates(sourceText).forEach(addCandidate);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
const inactiveParticipant = getMermaidInactiveParticipant(errorMessage);
|
||||
if (inactiveParticipant) {
|
||||
addCandidate(
|
||||
@@ -141,12 +539,39 @@ export const getMermaidAutoFixCandidates = (
|
||||
}
|
||||
|
||||
if (isMermaidParseSyntaxError(errorMessage)) {
|
||||
const type = getMermaidDiagramType(sourceText);
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const errorLineIndex = getErrorLineIndex(errorMessage, sourceText);
|
||||
const lineIndexesToTry =
|
||||
errorLineIndex == null
|
||||
? []
|
||||
: [errorLineIndex, errorLineIndex - 1, errorLineIndex + 1];
|
||||
// fixes of a line, and of all of them (e.g. a mistake repeated on others)
|
||||
const lineFixes: Array<(line: string) => string> = [];
|
||||
const textFixes: Array<(line: string) => string> = [
|
||||
removeExtraArrowheadAfterEdgeLabel,
|
||||
];
|
||||
|
||||
if (type === "flowchart") {
|
||||
lineFixes.push(
|
||||
quoteLabelsWithBrackets,
|
||||
fixSingleDashArrows,
|
||||
removeUnmatchedClosers,
|
||||
);
|
||||
textFixes.push(
|
||||
quoteLabelsWithBrackets,
|
||||
fixSingleDashArrows,
|
||||
capitalizeEndNodes,
|
||||
);
|
||||
} else if (type === "state") {
|
||||
lineFixes.push(fixStateSingleDashArrows);
|
||||
textFixes.push(fixStateSingleDashArrows);
|
||||
} else if (type === "sequence") {
|
||||
lineFixes.push(addSequenceMessageColon);
|
||||
} else if (type === "er") {
|
||||
lineFixes.push(addRelationshipColon);
|
||||
textFixes.push(addRelationshipColon);
|
||||
}
|
||||
|
||||
for (const lineIndex of lineIndexesToTry) {
|
||||
addCandidate(
|
||||
@@ -159,13 +584,38 @@ export const getMermaidAutoFixCandidates = (
|
||||
removeExtraArrowheadAfterEdgeLabel(line),
|
||||
),
|
||||
);
|
||||
for (const fix of lineFixes) {
|
||||
addCandidate(replaceLineAt(lines, lineIndex, fix));
|
||||
}
|
||||
if (type === "flowchart" && lineIndex >= 0 && lineIndex < lines.length) {
|
||||
for (const closed of closeUnclosedShape(lines[lineIndex])) {
|
||||
addCandidate(replaceLineAt(lines, lineIndex, () => closed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also try full-text replacement so repeated occurrences on other lines
|
||||
// are fixed together in a single candidate.
|
||||
addCandidate(removeExtraArrowheadAfterEdgeLabel(sourceText));
|
||||
for (const fix of textFixes) {
|
||||
addCandidate(lines.map(fix).join("\n"));
|
||||
}
|
||||
|
||||
addCandidate(appendMissingEnds(sourceText));
|
||||
if (type === "flowchart" || type === "sequence") {
|
||||
addCandidate(
|
||||
fixDirectionStatements(lines, { remove: type === "sequence" }),
|
||||
);
|
||||
}
|
||||
|
||||
addCandidate(fixHeaderDirection(sourceText, type));
|
||||
|
||||
getUnclosedBlockCandidates(sourceText, type).forEach(addCandidate);
|
||||
|
||||
if (type === "flowchart") {
|
||||
const headerIndex = getMermaidHeaderLineIndex(sourceText);
|
||||
if (headerIndex !== null) {
|
||||
addCandidate(replaceLineAt(lines, headerIndex, fixFlowchartDirection));
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedQuotes = normalizeSmartQuotes(sourceText);
|
||||
addCandidate(normalizedQuotes === sourceText ? null : normalizedQuotes);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
formatMermaidParseErrorMessage,
|
||||
getMermaidDiagramType,
|
||||
getMermaidErrorLineNumber,
|
||||
getMermaidInactiveParticipant,
|
||||
getMermaidSyntaxErrorGuidance,
|
||||
@@ -30,6 +31,20 @@ Expecting 'SEMI', 'NEWLINE', 'SPACE', got 'NODE_STRING'`;
|
||||
expect(formatMermaidParseErrorMessage(message)).toBe(message);
|
||||
});
|
||||
|
||||
it("reports the error on its source line, given the source", () => {
|
||||
expect(
|
||||
formatMermaidParseErrorMessage(
|
||||
`Parse error on line 3:
|
||||
C --> D]
|
||||
---------^
|
||||
Expecting 'SEMI', got 'SQE'`,
|
||||
"%% a\n%% b\nflowchart TD\n A --> B\n C --> D]",
|
||||
),
|
||||
).toBe(`Parse error on line 5:
|
||||
C --> D]
|
||||
---------^`);
|
||||
});
|
||||
|
||||
it("does not modify non-Mermaid parse messages", () => {
|
||||
const message =
|
||||
"Unexpected token while parsing JSON. Expecting value at position 10.";
|
||||
@@ -77,6 +92,12 @@ describe("isMermaidAutoFixableError", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true for unknown diagram types", () => {
|
||||
expect(
|
||||
isMermaidAutoFixableError("No diagram type detected for the given text."),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for non-fixable errors", () => {
|
||||
expect(isMermaidAutoFixableError("Network error")).toBe(false);
|
||||
});
|
||||
@@ -99,6 +120,46 @@ describe("getMermaidInactiveParticipant", () => {
|
||||
});
|
||||
|
||||
describe("getMermaidErrorLineNumber", () => {
|
||||
it("reports errors after the last line on the last line", () => {
|
||||
expect(
|
||||
getMermaidErrorLineNumber(
|
||||
"Parse error on line 4: ...",
|
||||
"graph TD\nsubgraph A\n A1[Start]\n",
|
||||
),
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it("maps lines as Mermaid and Pele number them to the source's", () => {
|
||||
// [source, the line they report the error on line `actual` on]
|
||||
const cases: Array<[string, number, number]> = [
|
||||
["%% a\n%% b\nflowchart TD\n A --> B\n C --> D]", 3, 5],
|
||||
["flowchart TD\n %% c\n A --> B\n C --> D]", 3, 4],
|
||||
["\n\nflowchart TD\n A --> B\n C --> D]", 3, 5],
|
||||
["flowchart TD\n\n A --> B\n\n C --> D]", 5, 5],
|
||||
["---\ntitle: x\n---\nflowchart TD\n A --> B\n C --> D]", 3, 6],
|
||||
["%%{init: {'theme':'dark'}}%%\nflowchart TD\n C --> D]", 2, 3],
|
||||
["flowchart TD\n %%\n A --> B\n C --> D]", 4, 4],
|
||||
// a flowchart line ending with a comment runs on into the next one
|
||||
["flowchart TD\n A --> B %% note\n C --> D]", 2, 2],
|
||||
["sequenceDiagram\n Alice->>Bob: hi %% note\n Alice-B: x", 3, 3],
|
||||
["classDiagram\n %% c\n A <|-- B\n A <|-|> C", 3, 4],
|
||||
];
|
||||
for (const [source, reported, actual] of cases) {
|
||||
expect(
|
||||
getMermaidErrorLineNumber(`Parse error on line ${reported}:`, source),
|
||||
).toBe(actual);
|
||||
}
|
||||
});
|
||||
|
||||
it("reports unknown diagram types on the line declaring it", () => {
|
||||
expect(
|
||||
getMermaidErrorLineNumber(
|
||||
"No diagram type detected for the given text.",
|
||||
"%% comment\nflowchar TD\n A --> B",
|
||||
),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("extracts line number from parse error format", () => {
|
||||
expect(getMermaidErrorLineNumber("Parse error on line 6: ...")).toBe(6);
|
||||
});
|
||||
@@ -137,6 +198,9 @@ describe("getMermaidSyntaxErrorGuidance", () => {
|
||||
|
||||
const source = `graph TD
|
||||
subgraph Layers["X"]
|
||||
L0["Physical"]
|
||||
L1["Data link"]
|
||||
L2["Network"]
|
||||
L3_TCP["TCP (Transmission Control Protocol)"]x`;
|
||||
|
||||
expect(getMermaidSyntaxErrorGuidance(message, source)).toEqual({
|
||||
@@ -152,4 +216,124 @@ subgraph Layers["X"]
|
||||
getMermaidSyntaxErrorGuidance("Network error", "graph TD"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("names the block a brace is missing from by diagram type", () => {
|
||||
const message = `Parse error on line 4:
|
||||
Animal <|-- Duck
|
||||
------------------^`;
|
||||
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
message,
|
||||
`classDiagram
|
||||
class Animal {
|
||||
+int age
|
||||
Animal <|-- Duck`,
|
||||
)?.likelyCauses,
|
||||
).toEqual(["A class body is missing its closing `}`."]);
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
message,
|
||||
`flowchart TD
|
||||
A --> B{Is it?
|
||||
B --> C`,
|
||||
)?.likelyCauses,
|
||||
).toEqual(["Unbalanced braces in a decision node."]);
|
||||
});
|
||||
|
||||
it("counts the sequence blocks closed by `end`", () => {
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
`Parse error on line 4:
|
||||
Bob->>Alice: ping
|
||||
---------------------^`,
|
||||
`sequenceDiagram
|
||||
Alice->>Bob: hi
|
||||
loop Every minute
|
||||
Bob->>Alice: ping`,
|
||||
)?.likelyCauses,
|
||||
).toEqual(["A block is missing an `end` statement."]);
|
||||
});
|
||||
|
||||
it("suggests quoting labels with parentheses in them", () => {
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
`Parse error on line 2:
|
||||
A[Process (main)] --> B
|
||||
------------^
|
||||
Expecting 'SQE', 'UNICODE_TEXT', 'TEXT', 'TAGSTART', got 'PS'`,
|
||||
`flowchart TD
|
||||
A[Process (main)] --> B`,
|
||||
)?.likelyCauses,
|
||||
).toEqual([
|
||||
'A label contains brackets or parentheses: wrap it in double quotes, e.g. `A["Label (detail)"]`.',
|
||||
]);
|
||||
});
|
||||
|
||||
it("explains invalid directions", () => {
|
||||
const message = "Parse error on line 2:\n direction LR\n----^";
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
message,
|
||||
"sequenceDiagram\n direction LR\n Alice->>Bob: hi",
|
||||
)?.likelyCauses,
|
||||
).toContain("Sequence diagrams have no `direction`.");
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
message,
|
||||
"flowchart lr\n subgraph A\n direction TD\n end",
|
||||
)?.likelyCauses,
|
||||
).toEqual([
|
||||
"The flowchart's direction must be `TB` (or `TD`), `BT`, `RL` or `LR`.",
|
||||
"A subgraph's `direction` must be `TB`, `BT`, `RL` or `LR`.",
|
||||
]);
|
||||
});
|
||||
|
||||
it("explains directions on the first line", () => {
|
||||
const message = "Parse error on line 1:\nclassDiagram LR\n-------------^";
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(message, "classDiagram LR\n A <|-- B")
|
||||
?.likelyCauses,
|
||||
).toContain(
|
||||
"The diagram's direction goes on the next line, as a `direction` statement: e.g. `direction LR`.",
|
||||
);
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(
|
||||
message,
|
||||
"sequenceDiagram LR\n Alice->>Bob: hi",
|
||||
)?.likelyCauses,
|
||||
).toContain("Sequence diagrams have no `direction`.");
|
||||
});
|
||||
|
||||
it("explains unknown diagram types, as Mermaid and Pele word them", () => {
|
||||
for (const message of [
|
||||
"No diagram type detected matching given configuration for text: flowchar TD",
|
||||
"No diagram type detected for the given text.",
|
||||
]) {
|
||||
expect(
|
||||
getMermaidSyntaxErrorGuidance(message, "flowchar TD\n A --> B"),
|
||||
).toEqual({
|
||||
summary: "Unknown diagram type.",
|
||||
likelyCauses: [expect.stringContaining("`flowchart TD`")],
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMermaidDiagramType", () => {
|
||||
it("reads the diagram type past comments, directives and front matter", () => {
|
||||
expect(
|
||||
getMermaidDiagramType(`---
|
||||
title: Example
|
||||
---
|
||||
%%{init: {"theme": "dark"}}%%
|
||||
%% a comment
|
||||
|
||||
sequenceDiagram
|
||||
Alice->>Bob: hi`),
|
||||
).toBe("sequence");
|
||||
expect(getMermaidDiagramType("graph LR\n A --> B")).toBe("flowchart");
|
||||
expect(getMermaidDiagramType("stateDiagram-v2\n [*] --> A")).toBe("state");
|
||||
expect(getMermaidDiagramType('pie\n "A": 1')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,9 @@ const MERMAID_SYNTAX_ERROR_LINE = /(?:Parse|Lexical) error on line (\d+)[.:]/i;
|
||||
const MERMAID_INACTIVE_PARTICIPANT_ERROR =
|
||||
/Trying to inactivate an inactive participant \((.+)\)/i;
|
||||
const MERMAID_CARET_LINE = /^\s*-+\^\s*$/;
|
||||
// Mermaid: "No diagram type detected matching given configuration for text:
|
||||
// ...", Pele: "No diagram type detected for the given text."
|
||||
const MERMAID_UNKNOWN_DIAGRAM_ERROR = /No diagram type detected/i;
|
||||
// Chrome, Firefox and Safari messages respectively
|
||||
const MODULE_LOAD_ERROR =
|
||||
/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;
|
||||
@@ -13,9 +16,73 @@ export const isModuleLoadError = (error: unknown) =>
|
||||
export const isMermaidParseSyntaxError = (message: string) =>
|
||||
MERMAID_SYNTAX_ERROR_LINE.test(message);
|
||||
|
||||
/** the definition doesn't start with a (known) diagram type */
|
||||
export const isMermaidUnknownDiagramError = (message: string) =>
|
||||
MERMAID_UNKNOWN_DIAGRAM_ERROR.test(message);
|
||||
|
||||
export const isMermaidAutoFixableError = (message: string) =>
|
||||
isMermaidParseSyntaxError(message) ||
|
||||
MERMAID_INACTIVE_PARTICIPANT_ERROR.test(message);
|
||||
MERMAID_INACTIVE_PARTICIPANT_ERROR.test(message) ||
|
||||
isMermaidUnknownDiagramError(message);
|
||||
|
||||
export type MermaidDiagramType =
|
||||
| "flowchart"
|
||||
| "sequence"
|
||||
| "class"
|
||||
| "state"
|
||||
| "er";
|
||||
|
||||
const MERMAID_DIAGRAM_TYPES: Record<string, MermaidDiagramType> = {
|
||||
flowchart: "flowchart",
|
||||
graph: "flowchart",
|
||||
sequencediagram: "sequence",
|
||||
classdiagram: "class",
|
||||
"classdiagram-v2": "class",
|
||||
statediagram: "state",
|
||||
"statediagram-v2": "state",
|
||||
erdiagram: "er",
|
||||
};
|
||||
|
||||
/**
|
||||
* Index of the line that declares the diagram type: the first one that isn't
|
||||
* empty, a comment, a directive (`%%{...}%%`) or front matter (`---` block).
|
||||
*/
|
||||
export const getMermaidHeaderLineIndex = (sourceText: string) => {
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
let index = 0;
|
||||
const isSkipped = (line: string) => !line.trim() || /^\s*%%/.test(line);
|
||||
while (index < lines.length && isSkipped(lines[index])) {
|
||||
index++;
|
||||
}
|
||||
if (lines[index]?.trim() === "---") {
|
||||
const end = lines.findIndex(
|
||||
(line, lineIndex) => lineIndex > index && line.trim() === "---",
|
||||
);
|
||||
if (end !== -1) {
|
||||
index = end + 1;
|
||||
while (index < lines.length && isSkipped(lines[index])) {
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return index < lines.length ? index : null;
|
||||
};
|
||||
|
||||
/** The diagram type the definition declares (of those Excalidraw converts). */
|
||||
export const getMermaidDiagramType = (
|
||||
sourceText: string,
|
||||
): MermaidDiagramType | null => {
|
||||
const headerIndex = getMermaidHeaderLineIndex(sourceText);
|
||||
if (headerIndex === null) {
|
||||
return null;
|
||||
}
|
||||
const keyword = sourceText
|
||||
.split(/\r?\n/)
|
||||
[headerIndex].trim()
|
||||
.split(/\s/)[0]
|
||||
.toLowerCase();
|
||||
return MERMAID_DIAGRAM_TYPES[keyword] ?? null;
|
||||
};
|
||||
|
||||
export const isMermaidCaretLine = (line: string) =>
|
||||
MERMAID_CARET_LINE.test(line);
|
||||
@@ -63,18 +130,122 @@ export const getMermaidErrorLineNumber = (
|
||||
if (!sourceText) {
|
||||
return null;
|
||||
}
|
||||
if (isMermaidUnknownDiagramError(message)) {
|
||||
const headerIndex = getMermaidHeaderLineIndex(sourceText);
|
||||
return headerIndex === null ? null : headerIndex + 1;
|
||||
}
|
||||
return getInactiveParticipantLineNumber(message, sourceText);
|
||||
}
|
||||
return Number.parseInt(match[1], 10);
|
||||
const line = Number.parseInt(match[1], 10);
|
||||
return sourceText ? getMermaidSourceLineNumber(line, sourceText) : line;
|
||||
};
|
||||
|
||||
/**
|
||||
* The (0-based) indexes of the source lines the lines Mermaid (and Pele)
|
||||
* number errors by start at. They parse a definition without its front
|
||||
* matter, directives, comment lines and leading blank lines, and in
|
||||
* flowcharts and ER diagrams, a line ending with a comment runs on into the
|
||||
* next one.
|
||||
*/
|
||||
const getParsedLineStarts = (sourceText: string) => {
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const type = getMermaidDiagramType(sourceText);
|
||||
const runsOnAfterComments = type === "flowchart" || type === "er";
|
||||
const starts: number[] = [];
|
||||
let index = 0;
|
||||
if (lines[0]?.trim() === "---") {
|
||||
const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
|
||||
if (end !== -1) {
|
||||
index = end + 1;
|
||||
}
|
||||
}
|
||||
let runsOn = false;
|
||||
for (; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
// a directive, possibly over several lines
|
||||
if (/^\s*%%\{/.test(line)) {
|
||||
while (index < lines.length - 1 && !/\}%%/.test(lines[index])) {
|
||||
index++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (/^\s*%%(?!\{)./.test(line) || (!starts.length && !line.trim())) {
|
||||
continue;
|
||||
}
|
||||
if (!runsOn) {
|
||||
starts.push(index);
|
||||
}
|
||||
runsOn = runsOnAfterComments && /\S.*%%/.test(line);
|
||||
}
|
||||
return starts;
|
||||
};
|
||||
|
||||
/**
|
||||
* The line of the source an error Mermaid (or Pele) reports on `line` is on:
|
||||
* errors past its end (e.g. a missing `end`) are on its last non-empty line.
|
||||
*/
|
||||
export const getMermaidSourceLineNumber = (
|
||||
line: number,
|
||||
sourceText: string,
|
||||
) => {
|
||||
const starts = getParsedLineStarts(sourceText);
|
||||
if (line >= 1 && line <= starts.length) {
|
||||
let index = starts[line - 1];
|
||||
// e.g. the empty line Mermaid reports an error at the end on
|
||||
while (index > 0 && !sourceText.split(/\r?\n/)[index].trim()) {
|
||||
index--;
|
||||
}
|
||||
return index + 1;
|
||||
}
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
let lastLine = lines.length;
|
||||
while (lastLine > 1 && !lines[lastLine - 1].trim()) {
|
||||
lastLine--;
|
||||
}
|
||||
return lastLine;
|
||||
};
|
||||
|
||||
const countMatches = (text: string, re: RegExp) =>
|
||||
(text.match(re) || []).length;
|
||||
|
||||
// Blocks closed by `end`
|
||||
const MERMAID_END_BLOCK_OPENERS: Partial<Record<MermaidDiagramType, RegExp>> = {
|
||||
flowchart: /^\s*subgraph\b/,
|
||||
sequence: /^\s*(?:loop|alt|opt|par|par_over|critical|break|rect|box)\b/,
|
||||
};
|
||||
|
||||
/** A line closing a block that `end`s */
|
||||
export const MERMAID_END_LINE = /^\s*end\s*$/;
|
||||
|
||||
/** What's missing when a block opened by a line ending with `{` isn't closed */
|
||||
const MERMAID_UNCLOSED_BRACE_BLOCKS: Partial<
|
||||
Record<MermaidDiagramType, string>
|
||||
> = {
|
||||
class: "A class body is missing its closing `}`.",
|
||||
state: "A composite state is missing its closing `}`.",
|
||||
er: "An entity's attributes are missing their closing `}`.",
|
||||
};
|
||||
|
||||
export const getMermaidEndBlockOpener = (type: MermaidDiagramType | null) =>
|
||||
type ? MERMAID_END_BLOCK_OPENERS[type] ?? null : null;
|
||||
|
||||
// How the definitions of the diagram types Excalidraw converts start
|
||||
const KNOWN_DIAGRAM_TYPES =
|
||||
"`flowchart TD`, `sequenceDiagram`, `classDiagram`, `stateDiagram-v2` or `erDiagram`";
|
||||
|
||||
export const getMermaidSyntaxErrorGuidance = (
|
||||
message: string,
|
||||
sourceText?: string,
|
||||
): { summary: string; likelyCauses: string[] } | null => {
|
||||
if (isMermaidUnknownDiagramError(message)) {
|
||||
return {
|
||||
summary: "Unknown diagram type.",
|
||||
likelyCauses: [
|
||||
`The first line must name the diagram type, e.g. ${KNOWN_DIAGRAM_TYPES}.`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (!isMermaidParseSyntaxError(message)) {
|
||||
return null;
|
||||
}
|
||||
@@ -85,39 +256,114 @@ export const getMermaidSyntaxErrorGuidance = (
|
||||
: "Syntax error in Mermaid diagram.";
|
||||
|
||||
const likelyCauses: string[] = [];
|
||||
const type = sourceText ? getMermaidDiagramType(sourceText) : null;
|
||||
|
||||
if (sourceText) {
|
||||
const openBrackets = countMatches(sourceText, /\[/g);
|
||||
const closeBrackets = countMatches(sourceText, /\]/g);
|
||||
if (openBrackets !== closeBrackets) {
|
||||
likelyCauses.push("Unbalanced square brackets in a node label.");
|
||||
likelyCauses.push(
|
||||
type === "flowchart"
|
||||
? "Unbalanced square brackets in a node label."
|
||||
: "Unbalanced square brackets.",
|
||||
);
|
||||
}
|
||||
|
||||
const openParens = countMatches(sourceText, /\(/g);
|
||||
const closeParens = countMatches(sourceText, /\)/g);
|
||||
if (openParens !== closeParens) {
|
||||
likelyCauses.push("Unbalanced parentheses in a node shape.");
|
||||
likelyCauses.push(
|
||||
type === "flowchart"
|
||||
? "Unbalanced parentheses in a node shape."
|
||||
: "Unbalanced parentheses.",
|
||||
);
|
||||
}
|
||||
|
||||
const openBraces = countMatches(sourceText, /\{/g);
|
||||
const closeBraces = countMatches(sourceText, /\}/g);
|
||||
if (openBraces !== closeBraces) {
|
||||
likelyCauses.push("Unbalanced braces in a decision node.");
|
||||
const unclosedBlock = type && MERMAID_UNCLOSED_BRACE_BLOCKS[type];
|
||||
likelyCauses.push(
|
||||
type === "flowchart"
|
||||
? "Unbalanced braces in a decision node."
|
||||
: unclosedBlock && openBraces > closeBraces
|
||||
? unclosedBlock
|
||||
: "Unbalanced braces.",
|
||||
);
|
||||
}
|
||||
|
||||
const subgraphCount = countMatches(sourceText, /^\s*subgraph\b/gm);
|
||||
const endCount = countMatches(sourceText, /^\s*end\s*$/gm);
|
||||
if (subgraphCount > endCount) {
|
||||
likelyCauses.push("A block is missing an `end` statement.");
|
||||
const opener = getMermaidEndBlockOpener(type);
|
||||
if (opener) {
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const openerCount = lines.filter((line) => opener.test(line)).length;
|
||||
const endCount = lines.filter((line) =>
|
||||
MERMAID_END_LINE.test(line),
|
||||
).length;
|
||||
if (openerCount > endCount) {
|
||||
likelyCauses.push("A block is missing an `end` statement.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (/got 'NODE_STRING'/.test(message) || /got 'PS'/.test(message)) {
|
||||
const header = sourceText
|
||||
? sourceText.split(/\r?\n/)[getMermaidHeaderLineIndex(sourceText) ?? 0]
|
||||
: "";
|
||||
// e.g. `sequenceDiagram LR`, `classDiagram direction LR`
|
||||
const headerRest = header.match(/^\s*\S+\s+(?!%%)(.+?)\s*$/)?.[1];
|
||||
if (
|
||||
type === "sequence" &&
|
||||
(headerRest || /^\s*direction\b/m.test(sourceText ?? ""))
|
||||
) {
|
||||
likelyCauses.push("Sequence diagrams have no `direction`.");
|
||||
}
|
||||
if (
|
||||
headerRest &&
|
||||
((type === "class" && /^(?:direction\s+)?\S+$/.test(headerRest)) ||
|
||||
((type === "state" || type === "er") && /^direction\b/.test(headerRest)))
|
||||
) {
|
||||
likelyCauses.push(
|
||||
"The diagram's direction goes on the next line, as a `direction` statement: e.g. `direction LR`.",
|
||||
);
|
||||
}
|
||||
if (sourceText && type === "flowchart") {
|
||||
const lines = sourceText.split(/\r?\n/);
|
||||
const header = lines[getMermaidHeaderLineIndex(sourceText) ?? 0];
|
||||
const headerDirection = header.match(
|
||||
/^\s*(?:flowchart|graph)\s+(\S+)/,
|
||||
)?.[1];
|
||||
if (headerDirection && !/^(?:TB|TD|BT|RL|LR)$/.test(headerDirection)) {
|
||||
likelyCauses.push(
|
||||
"The flowchart's direction must be `TB` (or `TD`), `BT`, `RL` or `LR`.",
|
||||
);
|
||||
}
|
||||
if (
|
||||
lines.some((line) => {
|
||||
const direction = line.match(/^\s*direction\s+(\S+)\s*$/)?.[1];
|
||||
return direction && !/^(?:TB|BT|RL|LR)$/.test(direction);
|
||||
})
|
||||
) {
|
||||
likelyCauses.push(
|
||||
"A subgraph's `direction` must be `TB`, `BT`, `RL` or `LR`.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (/got '(?:PS|PE|SQS|SQE|DIAMOND_START|DIAMOND_STOP)'/.test(message)) {
|
||||
likelyCauses.push(
|
||||
'A label contains brackets or parentheses: wrap it in double quotes, e.g. `A["Label (detail)"]`.',
|
||||
);
|
||||
} else if (/got 'NODE_STRING'/.test(message)) {
|
||||
likelyCauses.push(
|
||||
"An extra character/token may appear after a node or label definition.",
|
||||
);
|
||||
}
|
||||
|
||||
if (/got 'end'/.test(message)) {
|
||||
likelyCauses.push(
|
||||
"`end` is a reserved word: capitalize it (e.g. `End`) to use it as a node.",
|
||||
);
|
||||
}
|
||||
|
||||
if (likelyCauses.length === 0) {
|
||||
likelyCauses.push(
|
||||
"A node or edge line is malformed (missing/extra delimiters).",
|
||||
@@ -131,10 +377,32 @@ export const getMermaidSyntaxErrorGuidance = (
|
||||
};
|
||||
};
|
||||
|
||||
export const formatMermaidParseErrorMessage = (message: string) => {
|
||||
/** The error, reported on its line of `sourceText` (see `getMermaidSourceLineNumber`) */
|
||||
export const withMermaidSourceLineNumber = (
|
||||
message: string,
|
||||
sourceText: string,
|
||||
) =>
|
||||
message.replace(MERMAID_SYNTAX_ERROR_LINE, (match, line) =>
|
||||
match.replace(
|
||||
line,
|
||||
String(getMermaidSourceLineNumber(Number(line), sourceText)),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* The parse error, without the tokens it expected, and if given the source,
|
||||
* on its line of it.
|
||||
*/
|
||||
export const formatMermaidParseErrorMessage = (
|
||||
message: string,
|
||||
sourceText?: string,
|
||||
) => {
|
||||
if (!isMermaidParseSyntaxError(message)) {
|
||||
return message;
|
||||
}
|
||||
|
||||
return message.replace(/\n\s*Expecting[\s\S]*$/, "").trimEnd();
|
||||
const formatted = message.replace(/\n\s*Expecting[\s\S]*$/, "").trimEnd();
|
||||
return sourceText
|
||||
? withMermaidSourceLineNumber(formatted, sourceText)
|
||||
: formatted;
|
||||
};
|
||||
@@ -7,6 +7,9 @@ describe("isMaybeMermaidDefinition", () => {
|
||||
expect(isMaybeMermaidDefinition("flowchart LR\nola")).toBe(true);
|
||||
expect(isMaybeMermaidDefinition("%%{}%%flowchart")).toBe(true);
|
||||
expect(isMaybeMermaidDefinition("%%{}%% flowchart")).toBe(true);
|
||||
expect(
|
||||
isMaybeMermaidDefinition("swimlane-beta LR\n subgraph Customer"),
|
||||
).toBe(true);
|
||||
|
||||
expect(isMaybeMermaidDefinition("graphs")).toBe(false);
|
||||
expect(isMaybeMermaidDefinition("this flowchart")).toBe(false);
|
||||
|
||||
@@ -21,6 +21,8 @@ export const isMaybeMermaidDefinition = (text: string) => {
|
||||
"sankey",
|
||||
"xychart",
|
||||
"block",
|
||||
// `swimlane-beta`, which Pele (unlike Mermaid) renders, as a flowchart
|
||||
"swimlane",
|
||||
];
|
||||
|
||||
const re = new RegExp(
|
||||
|
||||
@@ -88,7 +88,7 @@
|
||||
"@excalidraw/element": "0.18.0",
|
||||
"@excalidraw/laser-pointer": "1.3.1",
|
||||
"@excalidraw/math": "0.18.0",
|
||||
"@excalidraw/mermaid-to-excalidraw": "2.2.2",
|
||||
"@excalidraw/mermaid-to-excalidraw": "3.0.0",
|
||||
"@excalidraw/random-username": "1.1.0",
|
||||
"browser-fs-access": "0.38.0",
|
||||
"canvas-roundrect-polyfill": "0.0.1",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { expect, vi } from "vitest";
|
||||
|
||||
import { pointFrom } from "@excalidraw/math";
|
||||
|
||||
import type { LocalPoint } from "@excalidraw/math";
|
||||
|
||||
import { Excalidraw } from "../index";
|
||||
|
||||
import { mockMermaidToExcalidraw } from "./helpers/mocks";
|
||||
@@ -61,8 +65,8 @@ mockMermaidToExcalidraw({
|
||||
y: 44,
|
||||
strokeWidth: 2,
|
||||
points: [
|
||||
[0, 0],
|
||||
[0, 50],
|
||||
pointFrom<LocalPoint>(0, 0),
|
||||
pointFrom<LocalPoint>(0, 50),
|
||||
],
|
||||
roundness: {
|
||||
type: 2,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KEYS, reseed } from "@excalidraw/common";
|
||||
import { pointFrom } from "@excalidraw/math";
|
||||
|
||||
import type { RenderEnvironment } from "@excalidraw/element";
|
||||
import type { LocalPoint } from "@excalidraw/math";
|
||||
import type {
|
||||
ExcalidrawArrowElement,
|
||||
ExcalidrawTextElement,
|
||||
@@ -182,8 +183,8 @@ describe("mermaid labels measured with the host's render environment", () => {
|
||||
x: 100,
|
||||
y: 50,
|
||||
points: [
|
||||
[0, 0],
|
||||
[300, 0],
|
||||
pointFrom<LocalPoint>(0, 0),
|
||||
pointFrom<LocalPoint>(300, 0),
|
||||
],
|
||||
start: { id: "A" },
|
||||
end: { id: "B" },
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
"@excalidraw/common/*": ["./packages/common/src/*"],
|
||||
"@excalidraw/excalidraw": ["./packages/excalidraw/index.tsx"],
|
||||
"@excalidraw/excalidraw/*": ["./packages/excalidraw/*"],
|
||||
"@excalidraw/excalidraw/common/*": ["./packages/common/src/*"],
|
||||
"@excalidraw/excalidraw/element/*": ["./packages/element/src/*"],
|
||||
"@excalidraw/element": ["./packages/element/src/index.ts"],
|
||||
"@excalidraw/element/*": ["./packages/element/src/*"],
|
||||
"@excalidraw/fractional-indexing": ["./packages/fractional-indexing/src/index.ts"],
|
||||
|
||||
Reference in new issue
Block a user