Skip to content

Build your personal knowledge base with Trilium Notes

feat(mermaid): revive the diagram linter on CodeMirror 6

Elian Doran24363f113d2e
diff --git a/apps/client/src/widgets/type_widgets/linters/mermaid.spec.ts b/apps/client/src/widgets/type_widgets/linters/mermaid.spec.ts
new file mode 100644
index 0000000000..0de9f2f761
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/linters/mermaid.spec.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { trimIndentation } from "@triliumnext/commons";
+import { getMermaidDiagnostics } from "./mermaid.js";
+
+describe("Mermaid linter", () => {
+
+ it("reports correctly bad diagram type", async () => {
+ const input = trimIndentation`\
+ stateDiagram-v23
+ [*] -> Still
+ `;
+
+ const result = await getMermaidDiagnostics(input);
+ expect(result).toMatchObject([{
+ message: "Expecting 'SPACE', 'NL', 'SD', got 'ID'",
+ fromLine: 1,
+ fromColumn: 0,
+ toLine: 1,
+ toColumn: 1
+ }]);
+ });
+
+ it("reports lexical errors by highlighting the whole line", async () => {
+ const input = trimIndentation`\
+ flowchart TDs
+ A[Christmas] -->|Get money| B(Go shopping)
+ `;
+
+ const result = await getMermaidDiagnostics(input);
+ expect(result).toMatchObject([{
+ message: "Lexical error on line 1. Unrecognized text.",
+ fromLine: 1,
+ fromColumn: 0,
+ toLine: 1,
+ toColumn: "flowchart TDs".length
+ }]);
+ });
+
+ it("reports correctly basic arrow missing in diagram", async () => {
+ const input = trimIndentation`\
+ xychart-beta horizontal
+ title "Percentage usge"
+ x-axis [data, sys, usr, var]
+ y-axis 0--->100
+ bar [20, 70, 0, 0]
+ `;
+
+ const result = await getMermaidDiagnostics(input);
+ expect(result).toMatchObject([{
+ message: "Expecting 'ARROW_DELIMITER', got 'MINUS'",
+ fromLine: 4,
+ fromColumn: 8,
+ toLine: 4,
+ toColumn: 9
+ }]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/linters/mermaid.ts b/apps/client/src/widgets/type_widgets/linters/mermaid.ts
new file mode 100644
index 0000000000..1f7855cb2e
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/linters/mermaid.ts
@@ -0,0 +1,142 @@
+import { type Diagnostic, linter, lintGutter } from "@codemirror/lint";
+import type { EditorView } from "@codemirror/view";
+
+interface MermaidParseError extends Error {
+ hash: {
+ text: string;
+ token: string | null;
+ /** 0-based line number reported for lexical errors. */
+ line: number;
+ /** Present for parser (grammar) errors; absent for lexical errors. */
+ loc?: {
+ first_line: number;
+ first_column: number;
+ last_line: number;
+ last_column: number;
+ };
+ expected?: string[];
+ };
+}
+
+/** A Mermaid parse error expressed in editor line/column coordinates. */
+export interface MermaidLineDiagnostic {
+ message: string;
+ /** 1-based line number, matching CodeMirror's `doc.line()`. */
+ fromLine: number;
+ fromColumn: number;
+ toLine: number;
+ toColumn: number;
+}
+
+/**
+ * Builds a CodeMirror 6 lint extension that surfaces Mermaid parse errors inline
+ * as the user edits the diagram source. The extension re-runs (debounced) on
+ * every document change, so no manual re-triggering is required. `lintGutter()`
+ * adds the error markers in the gutter alongside the inline underline.
+ */
+export default function mermaidLinter() {
+ return [ linter(validateMermaid), lintGutter() ];
+}
+
+/**
+ * Lint source for {@link mermaidLinter}: parses the editor content and maps any
+ * Mermaid error onto CodeMirror's absolute-offset {@link Diagnostic} positions.
+ */
+export async function validateMermaid(view: EditorView): Promise<Diagnostic[]> {
+ const { doc } = view.state;
+ const diagnostics = await getMermaidDiagnostics(doc.toString());
+
+ return diagnostics.map(({ message, fromLine, fromColumn, toLine, toColumn }) => ({
+ severity: "error",
+ message,
+ from: doc.line(fromLine).from + fromColumn,
+ to: doc.line(toLine).from + toColumn
+ }));
+}
+
+/**
+ * Parses Mermaid diagram source and returns any parse error as a line/column
+ * diagnostic. Extracted from {@link validateMermaid} so the message and position
+ * handling can be unit-tested without a live editor.
+ *
+ * Mermaid throws two differently-shaped errors: grammar (parser) errors carry a
+ * `hash.loc` with precise positions, while lexical errors only report a 0-based
+ * `hash.line` — for those we highlight the whole offending line.
+ */
+export async function getMermaidDiagnostics(text: string): Promise<MermaidLineDiagnostic[]> {
+ if (!text.trim()) {
+ return [];
+ }
+
+ const mermaid = (await import("mermaid")).default;
+
+ try {
+ await mermaid.parse(text);
+ } catch (e: unknown) {
+ const hash = (e as MermaidParseError).hash;
+ if (!hash) {
+ // Some diagram types (e.g. the newer Langium-based parsers) throw errors
+ // without jison-style position info; we can't place a marker for those.
+ return [];
+ }
+
+ const message = (e as MermaidParseError).message;
+
+ if (hash.loc) {
+ return [ buildParseDiagnostic(message, hash.loc) ];
+ }
+
+ if (typeof hash.line === "number") {
+ return [ buildLexicalDiagnostic(message, hash.line, text) ];
+ }
+
+ return [];
+ }
+
+ return [];
+}
+
+/** Builds a precise diagnostic from a grammar (parser) error's `loc`. */
+function buildParseDiagnostic(message: string, loc: NonNullable<MermaidParseError["hash"]["loc"]>): MermaidLineDiagnostic {
+ let fromColumn = loc.first_column + 1;
+ const toColumn = loc.last_column + 1;
+
+ // A zero-width error at the very start of a line points before the first
+ // character; anchor it to the line start so the marker stays visible.
+ if (fromColumn === 1 && toColumn === 1) {
+ fromColumn = 0;
+ }
+
+ // Mermaid prepends a few lines of boilerplate ("Parse error on line N:" plus
+ // a caret diagram) before the useful "Expecting …" message.
+ let messageLines = message.split("\n");
+ if (messageLines.length >= 4) {
+ messageLines = messageLines.slice(3);
+ }
+
+ return {
+ message: messageLines.join("\n"),
+ fromLine: loc.first_line,
+ fromColumn,
+ toLine: loc.last_line,
+ toColumn
+ };
+}
+
+/**
+ * Builds a diagnostic for a lexical error, which carries no column info — only a
+ * 0-based line. The whole offending line is highlighted, and only the first
+ * message line is kept (the rest is a caret diagram that can't be re-aligned).
+ */
+function buildLexicalDiagnostic(message: string, zeroBasedLine: number, text: string): MermaidLineDiagnostic {
+ const line = zeroBasedLine + 1;
+ const lineContent = text.split("\n")[line - 1] ?? "";
+
+ return {
+ message: message.split("\n")[0],
+ fromLine: line,
+ fromColumn: 0,
+ toLine: line,
+ toColumn: lineContent.length
+ };
+}
diff --git a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
index 8293560cd2..a70ff9c523 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
@@ -1,3 +1,4 @@
+import type CodeMirror from "@triliumnext/codemirror";
import { useCallback } from "preact/hooks";
import { t } from "../../../services/i18n";
@@ -5,19 +6,15 @@ import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "../../
import NoteContentSwitcher from "../../layout/NoteContentSwitcher";
import SvgSplitEditor from "../helpers/SvgSplitEditor";
import { TypeWidgetProps } from "../type_widget";
+import mermaidLinter from "../linters/mermaid";
import SAMPLE_DIAGRAMS from "./sample_diagrams";
let idCounter = 1;
-let registeredErrorReporter = false;
export default function Mermaid(props: TypeWidgetProps) {
const renderSvg = useCallback(async (content: string) => {
const mermaid = (await import("mermaid")).default;
await loadElkIfNeeded(mermaid, content);
- if (!registeredErrorReporter) {
- // (await import("./linters/mermaid.js")).default();
- registeredErrorReporter = true;
- }
if (!content.trim()) {
return "";
@@ -33,10 +30,16 @@ export default function Mermaid(props: TypeWidgetProps) {
return postprocessMermaidSvg(svg);
}, []);
+ // Attach the Mermaid lint extension once the underlying CodeMirror editor is ready.
+ const setupEditor = useCallback((editor: CodeMirror | null) => {
+ editor?.setNamedExtension("mermaid-lint", mermaidLinter());
+ }, []);
+
return (
<SvgSplitEditor
attachmentName="mermaid-export"
renderSvg={renderSvg}
+ editorRef={setupEditor}
noteType="mermaid"
extraContent={(
<NoteContentSwitcher