### Install Packages Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md Use this command to install project dependencies. ```bash yarn ``` -------------------------------- ### Start Development Playground Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md Run this command to start the development playground for interactive testing. ```bash yarn start ``` -------------------------------- ### Example Usage of parseMermaidToExcalidraw Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md This example demonstrates how to import and use the `parseMermaidToExcalidraw` function, including passing custom theme variables and handling potential parsing errors. ```typescript import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; try { const { elements, files } = await parseMermaidToExcalidraw( diagramDefinition, { themeVariables: { fontSize: "25px", }, } ); // Render elements and files on Excalidraw } catch (e) { // Parse error, displaying error message to users } ``` -------------------------------- ### Convert Mermaid to Excalidraw Elements (Custom Config) Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt This example demonstrates how to pass a custom MermaidConfig object to tune rendering behavior, such as edge curves and theme variables. The library merges these with default settings. ```typescript const { elements } = await parseMermaidToExcalidraw( `flowchart LR A --> B --> C`, { flowchart: { curve: "basis" }, // "linear" | "basis" themeVariables: { fontSize: "24px" }, // controls label size maxEdges: 200, // default 500 maxTextSize: 10000, // default 50000 startOnLoad: false, // default false } ); ``` -------------------------------- ### Convert Mermaid to Excalidraw Elements (Basic) Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Use this basic example to convert a simple flowchart. Ensure you handle potential errors during parsing. The resulting elements and files can be passed directly to the Excalidraw component. ```typescript import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; // --- Basic flowchart --- try { const { elements, files } = await parseMermaidToExcalidraw( `flowchart TD A[Start] --> B{Is it?} B -- Yes --> C[OK] B -- No --> D[Not OK]` ); // Pass elements + files directly to the component // excalidrawAPI.updateScene({ elements, files }); console.log("elements:", elements); // [ // { type: "rectangle", id: "A", x: ..., y: ..., width: ..., height: ..., label: { text: "Start" } }, // { type: "diamond", id: "B", ... }, // { type: "arrow", startX: ..., endX: ..., label: { text: "Yes" } }, // ... // ] } catch (e) { console.error("Mermaid parse error:", e); } ``` -------------------------------- ### Build Project Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md Execute this command to build the project for production. ```bash yarn build ``` -------------------------------- ### Initialize Test Case Navigation and UI Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/visual-tests/index.html Sets up event listeners for navigation controls, UI toggles (dark mode, overlap), and URL parameter synchronization. It also includes logic for handling mouse wheel scrolling to switch test cases when the page is not scrollable. ```javascript const wait = () => new Promise((r) => { const check = () => window.__HARNESS__READY__ ? r() : setTimeout(check, 50); check(); }); await wait(); const picker = document.getElementById("picker"); const cases = window.ALL_TESTCASES; cases.forEach((tc, i) => { const opt = document.createElement("option"); opt.value = i; opt.textContent = `#${i} [${tc.type}] ${tc.name}`; picker.appendChild(opt); }); const isPw = new URLSearchParams(location.search).has("pw"); if (isPw) document.body.classList.add("pw"); let showingAll = false; let overlapping = false; const overlapBtn = document.getElementById("overlap-btn"); let darkMode = window.matchMedia("(prefers-color-scheme: dark)").matches; const darkBtn = document.getElementById("dark-btn"); const updateUrl = ({ push = false } = {}) => { if (isPw) return; const params = new URLSearchParams(); params.set("case", picker.value); if (showingAll) params.set("all", ""); if (overlapping) params.set("overlap", ""); if (darkMode) params.set("dark", ""); const url = `?${params.toString()}`; if (push) { history.pushState(null, "", url); } else { history.replaceState(null, "", url); } }; const syncOverlapState = () => { document.body.classList.toggle("overlap", overlapping); overlapBtn.classList.toggle("active", overlapping); }; syncOverlapState(); const syncDarkState = () => { document.body.classList.toggle("dark", darkMode); darkBtn.textContent = darkMode ? "☀️ Light" : "🌙 Dark"; }; syncDarkState(); const go = (i, { push = false } = {}) => { i = Math.max(0, Math.min(cases.length - 1, i)); picker.value = i; updateUrl({ push }); window.renderTestCase(i); }; picker.addEventListener("change", () => go(+picker.value)); document .getElementById("prev") .addEventListener("click", () => go(+picker.value - 1)); document .getElementById("next") .addEventListener("click", () => go(+picker.value + 1)); document.addEventListener("keydown", (e) => { if (e.key === "ArrowLeft") go(+picker.value - 1); if (e.key === "ArrowRight") go(+picker.value + 1); if (e.key === "q") { overlapping = !overlapping; syncOverlapState(); updateUrl(); } if (e.key === "D" && e.altKey && e.shiftKey) { e.preventDefault(); darkMode = !darkMode; syncDarkState(); updateUrl(); } }); // Scroll up/down switches cases in single mode when page isn't scrollable. // Accumulates scroll deltas so rapid scrolling skips multiple cases. let pendingIndex = null; let scrollTimer = null; const SCROLL_STEP = 100; // pixels of deltaY per case step let accumulatedDelta = 0; document.addEventListener( "wheel", (e) => { if (showingAll) return; const isScrollable = document.documentElement.scrollHeight > window.innerHeight; if (isScrollable) return; e.preventDefault(); accumulatedDelta += e.deltaY; const steps = Math.trunc(accumulatedDelta / SCROLL_STEP); if (steps !== 0) { accumulatedDelta -= steps * SCROLL_STEP; pendingIndex = (pendingIndex ?? +picker.value) + steps; pendingIndex = Math.max( 0, Math.min(cases.length - 1, pendingIndex) ); picker.value = pendingIndex; updateUrl(); } clearTimeout(scrollTimer); scrollTimer = setTimeout(() => { if (pendingIndex != null) { go(pendingIndex); pendingIndex = null; } accumulatedDelta = 0; }, 150); }, { passive: false } ); // Copy buttons document .getElementById("copy-mermaid-svg") .addEventListener("click", () => { const svg = document.querySelector("#mermaid-output svg"); if (svg) navigator.clipboard.writeText(svg.outerHTML); }); document .getElementById("copy-excalidraw-svg") .addEventListener("click", () => { const svg = document.querySelector("#excalidraw-output svg"); if (svg) navigator.clipboard.writeText(svg.outerHTML); }); document .getElementById("copy-mermaid-def") .addEventListener("click", () => { const tc = cases[+picker.value]; if (tc) navigator.clipboard.writeText(tc.definition); }); const showAllBtn = document.getElementById("show-all"); const showSingle = (i) => { showingAll = false; document.body.classList.remove("showing-all"); showAllBtn.textContent = "Show All"; window.hideAllView(); go(i, { push: true }); }; window.__showSingle__ = showSingle; const enterShowAll = ({ push = false } = {}) => { showingAll = true; document.body.classList.add("showing-all"); showAllBtn.textContent = "Show Single"; updateUrl({ push }); window.renderAllTestCases(); }; showAllBtn.addEventListener("click", () => { if (showingAll) { showSingle(+picker.value); } else { enterShowAll({ push: true }); } }); overlapBtn.addEventListener("click", () => { overlapping = !overlapping; syncOverlapState(); updateUrl(); }); darkBtn.addEventListener("click", () => { darkMode = !darkMode; syncDarkState(); updateUrl(); }); // Restore full UI state from current URL params. const restoreFromUrl = () => { const p = new URLSearchParams(location.search); const wantAll = p.has("all"); const wantOverlap = p.has("overlap"); const wantDark = p.has("dark"); const wantCase = +(p.get("case") ?? 0); overlapping = wa ``` -------------------------------- ### Excalidraw State and URL Management Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/visual-tests/index.html Manages Excalidraw state synchronization, dark mode, and restores state from URL parameters. It also handles initial rendering based on URL parameters, especially in 'pw' mode. ```javascript ntOverlap; syncOverlapState(); darkMode = wantDark; syncDarkState(); if (wantAll && !showingAll) { enterShowAll(); } else if (!wantAll && showingAll) { showingAll = false; document.body.classList.remove("showing-all"); showAllBtn.textContent = "Show All"; window.hideAllView(); } if (!wantAll) { picker.value = wantCase; window.renderTestCase(wantCase); } }; window.addEventListener("popstate", restoreFromUrl); // Load initial state from URL params. // In pw mode, only render if ?case= is explicitly set (for debugging); // otherwise skip to avoid redundant renders across parallel workers. if (isPw) { const initialParams = new URLSearchParams(location.search); if (initialParams.has("case")) { go(+(initialParams.get("case") ?? 0)); } } else { restoreFromUrl(); } ``` -------------------------------- ### MermaidConfig Interface Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Configuration object to tune Mermaid rendering behavior. All fields are optional and merged with sensible defaults. ```APIDOC ## MermaidConfig Interface ### Description An interface defining the configuration object that can be passed as the second argument to `parseMermaidToExcalidraw` to customize Mermaid rendering. ### Fields - **`startOnLoad`** (boolean, optional): Default `false`. - **`flowchart`** (object, optional): Configuration for flowchart rendering. - **`curve`** (string, optional): Controls the curve of edges. Options: `"linear"` (straight edges) or `"basis"` (smoothed edges). Default `"linear"`. - **`themeVariables`** (object, optional): Customizes theme variables. - **`fontSize`** (string, optional): Controls the font size for labels. Example: `"20px"`. - **`maxEdges`** (number, optional): Maximum number of edges allowed. Default `500`. - **`maxTextSize`** (number, optional): Maximum text size allowed for labels. Default `50000`. ### Usage Example ```ts import type { MermaidConfig } from "@excalidraw/mermaid-to-excalidraw"; const config: MermaidConfig = { startOnLoad: false, flowchart: { curve: "linear", }, themeVariables: { fontSize: "18px", }, maxEdges: 1000, maxTextSize: 100000, }; // Example of using the config with parseMermaidToExcalidraw // const { elements } = await parseMermaidToExcalidraw( // `flowchart TD; A-->B; B-->C; C-->D`, // config // ); ``` ``` -------------------------------- ### Mermaid Configuration Options Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md These are the supported configuration parameters for Mermaid when used with `mermaid-to-excalidraw`. They control aspects like automatic loading, flowchart curve styles, theme variables, and rendering limits. ```typescript { /** * Whether to start the diagram automatically when the page loads. * @default false */ startOnLoad?: boolean; /** * The flowchart curve style. * @default "linear" */ flowchart?: { curve?: "linear" | "basis"; }; /** * Theme variables * @default { fontSize: "20px" } */ themeVariables?: { fontSize?: string; }; /** * Maximum number of edges to be rendered. * @default 500 */ maxEdges?: number; /** * Maximum number of characters to be rendered. * @default 50000 */ maxTextSize?: number; } ``` -------------------------------- ### Handle Unsupported Diagram Types with SVG Fallback Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Renders unsupported Mermaid diagram types (e.g., Gantt charts) as SVG images. The SVG is serialized to a base-64 data URL and returned as a single Excalidraw image element. The `files` property must be passed to Excalidraw along with `elements`. ```ts import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; // Gantt is not natively parsed — will fall back to SVG image const { elements, files } = await parseMermaidToExcalidraw( ` gantt title A Gantt Diagram dateFormat YYYY-MM-DD section Section A task : a1, 2024-01-01, 30d Another task : after a1, 20d ` ); // elements[0].type === "image" // files contains the binary SVG asset keyed by the image element's fileId // Pass both to Excalidraw: // excalidrawAPI.updateScene({ elements }); // excalidrawAPI.addFiles(Object.values(files ?? {})); console.log("image element:", elements[0]); // { type: "image", fileId: "...", x: 0, y: 0, width: ..., height: ... } console.log("files keys:", Object.keys(files ?? {})); // [""] ``` -------------------------------- ### parseMermaidToExcalidraw Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md Converts a mermaid diagram definition string into Excalidraw elements and files. It accepts an optional configuration object to customize the parsing process. ```APIDOC ## parseMermaidToExcalidraw ### Description Converts a mermaid diagram definition string into Excalidraw elements and files. It accepts an optional configuration object to customize the parsing process. ### Method Signature ```ts parseMermaidToExcalidraw(diagramDefinition: string, config?: MermaidConfig) ``` ### Parameters #### `diagramDefinition` - **Type**: `string` - **Description**: The mermaid diagram definition string. #### `config` - **Type**: `MermaidConfig` (optional) - **Description**: An optional configuration object to pass custom settings to mermaid. ### `MermaidConfig` Options ```ts { /** * Whether to start the diagram automatically when the page loads. * @default false */ startOnLoad?: boolean; /** * The flowchart curve style. * @default "linear" */ flowchart?: { curve?: "linear" | "basis"; }; /** * Theme variables * @default { fontSize: "20px" } */ themeVariables?: { fontSize?: string; }; /** * Maximum number of edges to be rendered. * @default 500 */ maxEdges?: number; /** * Maximum number of characters to be rendered. * @default 50000 */ maxTextSize?: number; } ``` ### Request Example ```ts import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; try { const diagramDefinition = ` graph TD A[Start] --> B{Decide}; B --> C{Make decision}; C --> D[End]; `; const { elements, files } = await parseMermaidToExcalidraw( diagramDefinition, { themeVariables: { fontSize: "25px", }, } ); // Render elements and files on Excalidraw } catch (e) { // Parse error, displaying error message to users console.error("Error parsing mermaid diagram:", e); } ``` ### Response - **Type**: `Promise<{ elements: ExcalidrawElement[], files: Record }> ` #### Success Response Returns an object containing: - `elements`: An array of Excalidraw elements representing the diagram. - `files`: A record of files associated with the diagram (e.g., images). #### Error Response Throws an error if the mermaid diagram definition is invalid or cannot be parsed. ``` -------------------------------- ### Apply Dark Mode Preference Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/playground/index.html Applies the 'dark-mode' class to the body if the user's system prefers dark color scheme. This is useful for theme switching. ```javascript if (window.matchMedia("(prefers-color-scheme: dark)").matches) { document.body.classList.add("dark-mode"); } ``` -------------------------------- ### parseMermaidToExcalidraw Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Converts a Mermaid diagram string to Excalidraw elements. Accepts a Mermaid diagram definition string and an optional MermaidConfig object. Returns a Promise. ```APIDOC ## parseMermaidToExcalidraw ### Description Converts a Mermaid diagram string into Excalidraw element skeletons. This is the primary public API of the library. ### Method Signature ```ts async parseMermaidToExcalidraw(mermaidString: string, config?: MermaidConfig): Promise ``` ### Parameters #### `mermaidString` - **Type**: `string` - **Description**: The Mermaid diagram definition string to convert. #### `config` (Optional) - **Type**: `MermaidConfig` - **Description**: An optional object to customize Mermaid rendering behavior. ### Returns - **Type**: `Promise` - **Description**: A promise that resolves to an object containing: - `elements`: An array of Excalidraw element descriptors. - `files`: A map of binary assets, used for SVG-image fallback. ### Request Example (Basic) ```ts import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; try { const { elements, files } = await parseMermaidToExcalidraw( `flowchart TD A[Start] --> B{Is it?} B -- Yes --> C[OK] B -- No --> D[Not OK]` ); console.log("elements:", elements); } catch (e) { console.error("Mermaid parse error:", e); } ``` ### Request Example (With Custom Config) ```ts import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw"; const { elements } = await parseMermaidToExcalidraw( `flowchart LR A --> B --> C`, { flowchart: { curve: "basis" }, themeVariables: { fontSize: "24px" }, maxEdges: 200, maxTextSize: 10000, startOnLoad: false, } ); ``` ``` -------------------------------- ### Serialize Concurrent Mermaid Conversions Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Uses `runMermaidTaskSequentially` to serialize concurrent calls to `parseMermaidToExcalidraw`. This prevents race conditions caused by Mermaid's singleton nature and ensures that each conversion completes before the next begins, while still propagating individual errors. ```ts // Internal usage (not exported from the public package surface) import { runMermaidTaskSequentially } from "./mermaidExecutionQueue.js"; // Simulate multiple concurrent conversion calls — all are safely serialized: const results = await Promise.all([ parseMermaidToExcalidraw(`flowchart TD; A-->B`), parseMermaidToExcalidraw(`sequenceDiagram; Alice->>Bob: Hi`), parseMermaidToExcalidraw(`flowchart LR; X-->Y-->Z`), ]); // Despite being launched concurrently, each Mermaid render runs sequentially. // A failure in one call does NOT prevent subsequent calls from running. ``` -------------------------------- ### Parse State Diagram to Excalidraw Elements Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Converts a Mermaid state diagram into Excalidraw elements. Supports states, transitions, composite states, forks, and notes. The output includes various Excalidraw element types corresponding to the diagram's structure. ```ts const { elements } = await parseMermaidToExcalidraw( ` stateDiagram-v2 [*] --> Idle Idle --> Running : start Running --> Idle : stop Running --> Error : fail state Running { [*] --> Executing Executing --> Waiting Waiting --> Executing } note right of Error Retry up to 3 times end note ` ); // elements contains: // - stateStart node (filled circle shape) // - rectangle nodes for Idle, Running, Error // - composite container for Running with inner states // - divider line separating Running title from its sub-states // - arrows with transition labels ("start", "stop", "fail") // - dashed note rectangle with null-arrowhead connector ``` -------------------------------- ### MermaidConfig Interface Definition Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Define a MermaidConfig object to customize Mermaid rendering. All fields are optional and will be merged with sensible defaults if not provided. ```typescript import type { MermaidConfig } from "@excalidraw/mermaid-to-excalidraw"; const config: MermaidConfig = { startOnLoad: false, flowchart: { curve: "linear", // "linear" produces straight edges; "basis" smooths them }, themeVariables: { fontSize: "18px", // affects all label text sizes }, maxEdges: 1000, // raise for very large diagrams maxTextSize: 100000, // raise for diagrams with long embedded text }; const { elements } = await parseMermaidToExcalidraw( `flowchart TD; A-->B; B-->C; C-->D`, config ); ``` -------------------------------- ### Parse Mermaid to Excalidraw Source: https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/README.md Use the `parseMermaidToExcalidraw` function to convert a Mermaid diagram definition. The optional `config` parameter allows customization of Mermaid's behavior, such as theme variables or maximum edge count. ```typescript parseMermaidToExcalidraw(diagramDefinition: string, config?: MermaidConfig) ``` -------------------------------- ### Convert Sequence Diagram to Excalidraw Elements Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Converts a Mermaid sequence diagram, including actors, messages, notes, loops, and conditional frames, into Excalidraw elements. Supports autonumbering and various arrow styles. ```ts const { elements } = await parseMermaidToExcalidraw(` sequenceDiagram autonumber participant Alice actor Bob Alice ->> Bob : Hello Bob! Bob -->> Alice: Hi Alice! Note right of Bob: Bob thinks loop Every minute Bob ->> Bob: Self call end alt Happy path Alice ->> Bob: OK else Sad path Alice ->> Bob: Error end `); ``` -------------------------------- ### Convert Entity-Relationship Diagram to Excalidraw Elements Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Converts a Mermaid ER diagram, including entities, attributes, and cardinality relationships, into Excalidraw elements. Preserves table-like entity structures and ER-specific arrowheads. ```ts const { elements } = await parseMermaidToExcalidraw(` erDiagram CUSTOMER { int id PK string name string email } ORDER { int id PK int customerId FK string status } CUSTOMER ||--o{ ORDER : "places" `); ``` -------------------------------- ### Convert Class Diagram to Excalidraw Elements Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Parses a Mermaid class diagram, including classes, members, methods, and relationships, into Excalidraw elements. Handles UML class structures and relationship arrow types. ```ts const { elements } = await parseMermaidToExcalidraw(` classDiagram direction LR class Animal { +String name +int age +makeSound() void } class Dog { +fetch() void } class Cat { +purr() void } Animal <|-- Dog : extends Animal <|-- Cat : extends note for Dog "Loyal companion" `); ``` -------------------------------- ### Convert Flowchart Diagram to Excalidraw Elements Source: https://context7.com/excalidraw/mermaid-to-excalidraw/llms.txt Parses a Mermaid flowchart definition, including class definitions and inline styles, into Excalidraw elements. Preserves node shapes, subgraph grouping, and styling attributes. ```ts const { elements } = await parseMermaidToExcalidraw(` flowchart TD classDef important fill:#f96,stroke:#333,stroke-width:2px classDef db fill:#bbf,stroke:#00f A([Oval start]):::important --> B[(Database)]:::db B --> C{Decision} C -- left --> D[/Parallelogram/] C -- right --> E[[Subroutine]] subgraph Cluster F --> G end E --> Cluster `); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.