Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

perf(editor): load Mermaid diagram code per diagram type (mermaid-to-excalidraw 3.1) (#12481)

David Luzarb99a49dbebd2
diff --git a/excalidraw-app/components/AI.tsx b/excalidraw-app/components/AI.tsx
index cc8b28cb9c..dcee47f845 100644
--- a/excalidraw-app/components/AI.tsx
+++ b/excalidraw-app/components/AI.tsx
@@ -7,6 +7,7 @@ import {
TTDDialog,
TTDStreamFetch,
THEME,
+ useOnExcalidrawStateChange,
} from "@excalidraw/excalidraw";
import { getDataURL } from "@excalidraw/excalidraw/data/blob";
import { safelyParseJSON } from "@excalidraw/common";
@@ -14,6 +15,7 @@ import { safelyParseJSON } from "@excalidraw/common";
import type { StreamChunk } from "@excalidraw/excalidraw";
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
+import { cacheMermaidChunks } from "../data/cacheMermaidChunks";
import { TTDIndexedDBAdapter } from "../data/TTDStorage";
export const AIComponents = ({
@@ -21,6 +23,15 @@ export const AIComponents = ({
}: {
excalidrawAPI: ExcalidrawImperativeAPI;
}) => {
+ useOnExcalidrawStateChange(
+ (appState) => appState.openDialog?.name === "ttd",
+ (isTTDDialogOpen) => {
+ if (isTTDDialogOpen) {
+ cacheMermaidChunks();
+ }
+ },
+ );
+
return (
<>
<DiagramToCodePlugin
diff --git a/excalidraw-app/data/cacheMermaidChunks.ts b/excalidraw-app/data/cacheMermaidChunks.ts
new file mode 100644
index 0000000000..b99139a22e
--- /dev/null
+++ b/excalidraw-app/data/cacheMermaidChunks.ts
@@ -0,0 +1,42 @@
+/**
+ * The name of the `<meta>` that points to the JSON list of the mermaid chunks,
+ * which `lazyChunksPlugin` (vite.config.mts) emits in production builds.
+ */
+export const MERMAID_CHUNKS_LIST_NAME = "mermaid-chunks";
+
+// Lets the dialog load the chunks it needs first (mermaid-to-excalidraw, and
+// those of the diagram type it converts), so that they aren't fetched twice:
+// cached chunks are then served from the cache.
+const CACHE_DELAY_MS = 5000;
+
+let caching: Promise<unknown> | null = null;
+
+/**
+ * The mermaid chunks (mermaid-to-excalidraw, and Pele's chunk per diagram
+ * type) aren't precached, as most users never use Mermaid. Once the TTD dialog
+ * is opened, they're all fetched for the service worker to cache (`lazy-chunks`
+ * runtime caching), so that offline, every diagram type converts, not just the
+ * ones used while online.
+ */
+export const cacheMermaidChunks = () => {
+ const listFileName = document.querySelector<HTMLMetaElement>(
+ `meta[name="${MERMAID_CHUNKS_LIST_NAME}"]`,
+ )?.content;
+ if (caching || !listFileName || !navigator.serviceWorker?.controller) {
+ return;
+ }
+ caching = new Promise((resolve) => setTimeout(resolve, CACHE_DELAY_MS))
+ .then(() => fetch(`${import.meta.env.BASE_URL}${listFileName}`))
+ .then((response) => response.json())
+ .then((fileNames: string[]) =>
+ Promise.all(
+ fileNames.map((fileName) =>
+ fetch(`${import.meta.env.BASE_URL}${fileName}`, { priority: "low" }),
+ ),
+ ),
+ )
+ .catch(() => {
+ // e.g. offline -> retry once the dialog is opened again
+ caching = null;
+ });
+};
diff --git a/excalidraw-app/vite.config.mts b/excalidraw-app/vite.config.mts
index 0f2b3f7636..0488bb1d3d 100644
--- a/excalidraw-app/vite.config.mts
+++ b/excalidraw-app/vite.config.mts
@@ -9,6 +9,8 @@ import { createHtmlPlugin } from "vite-plugin-html";
import Sitemap from "vite-plugin-sitemap";
import { woff2BrowserPlugin } from "../scripts/woff2/woff2-vite-plugins";
+import { MERMAID_CHUNKS_LIST_NAME } from "./data/cacheMermaidChunks";
+
import type { Plugin, Rollup } from "vite";
/**
@@ -16,10 +18,15 @@ import type { Plugin, Rollup } from "vite";
* import of a module matching `moduleRegex`, so we can exclude them from the
* PWA precache. Needed for large lazy deps that Rollup splits into many
* arbitrarily named chunks (e.g. mermaid), which `globIgnores` can't target.
+ *
+ * With `listName`, their file names are also emitted as a JSON asset that
+ * index.html points to (`<meta name={listName} content={fileName}>`), for the
+ * app to cache them when it needs them.
*/
const lazyChunksPlugin = (
moduleRegex: RegExp,
lazyChunkFileNames: Set<string>,
+ listName?: string,
): Plugin => ({
name: "excalidraw-lazy-chunks",
apply: "build",
@@ -95,6 +102,36 @@ const lazyChunksPlugin = (
lazyChunkFileNames.add(fileName);
}
}
+
+ if (listName) {
+ this.emitFile({
+ type: "asset",
+ name: `${listName}.json`,
+ source: JSON.stringify([...lazyChunkFileNames]),
+ });
+ }
+ },
+ // "post" handlers run in Vite's HTML plugin's `generateBundle`, after ours
+ transformIndexHtml: {
+ order: "post",
+ handler: (_html, { bundle }) => {
+ if (!listName) {
+ return;
+ }
+ const list = Object.values(bundle ?? {}).find(
+ (file) => file.type === "asset" && file.name === `${listName}.json`,
+ );
+ if (!list) {
+ throw new Error(`${listName}.json wasn't emitted`);
+ }
+ return [
+ {
+ tag: "meta",
+ attrs: { name: listName, content: list.fileName },
+ injectTo: "head",
+ },
+ ];
+ },
},
});
@@ -102,7 +139,8 @@ export default defineConfig(({ mode }) => {
// To load .env variables
const envVars = loadEnv(mode, `../`);
// mermaid (+ its many deps & per-diagram chunks) is lazy-loaded and large,
- // so we don't precache it. Populated at build time by `lazyChunksPlugin`.
+ // so we don't precache it (the app caches it once the TTD dialog is opened,
+ // see `cacheMermaidChunks`). Populated at build time by `lazyChunksPlugin`.
const mermaidChunkFileNames = new Set<string>();
// https://vitejs.dev/config/
return {
@@ -244,6 +282,7 @@ export default defineConfig(({ mode }) => {
lazyChunksPlugin(
/[\\/]node_modules[\\/]@excalidraw[\\/]mermaid-to-excalidraw[\\/]/,
mermaidChunkFileNames,
+ MERMAID_CHUNKS_LIST_NAME,
),
react(),
checker({
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index 95630ea3b8..84f3c5d175 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -197,7 +197,7 @@ 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)
+- 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. Each diagram type's code is loaded the first time one is converted. [#12480](https://github.com/excalidraw/excalidraw/pull/12480), [#12481](https://github.com/excalidraw/excalidraw/pull/12481)
- `label.labelPosition` (0–1) of skeleton arrows places their label along the arrow, instead of halfway. [#12425](https://github.com/excalidraw/excalidraw/pull/12425)
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
index 0f0b824724..5cdff5c82a 100644
--- a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
+++ b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
@@ -53,7 +53,7 @@ const loadMermaidToExcalidrawLib = (
const api: MermaidToExcalidrawLibProps["api"] = import(
"@excalidraw/mermaid-to-excalidraw"
).then((lib) => ({
- // mermaid lazy-loads a chunk per diagram type, which can fail to load
+ // Pele lazy-loads a chunk per diagram type, which can fail to load
// (e.g. offline) even though the lib itself loaded fine
parseMermaidToExcalidraw: async (definition, config) => {
try {
diff --git a/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts b/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
index bb9cc6b8d9..89201e2f49 100644
--- a/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
+++ b/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
@@ -9,7 +9,7 @@ const MERMAID_UNKNOWN_DIAGRAM_ERROR = /No diagram type detected/i;
const MODULE_LOAD_ERROR =
/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed/i;
-/** a lazy-loaded chunk (e.g. one of mermaid's diagram chunks) failed to load */
+/** a lazy-loaded chunk (e.g. one of Pele's diagram chunks) failed to load */
export const isModuleLoadError = (error: unknown) =>
error instanceof Error && MODULE_LOAD_ERROR.test(error.message);
diff --git a/packages/excalidraw/package.json b/packages/excalidraw/package.json
index 700c1ea4ee..7ea97eb28e 100644
--- a/packages/excalidraw/package.json
+++ b/packages/excalidraw/package.json
@@ -88,7 +88,7 @@
"@excalidraw/element": "0.18.0",
"@excalidraw/laser-pointer": "1.3.1",
"@excalidraw/math": "0.18.0",
- "@excalidraw/mermaid-to-excalidraw": "3.0.0",
+ "@excalidraw/mermaid-to-excalidraw": "3.1.0",
"@excalidraw/random-username": "1.1.0",
"browser-fs-access": "0.38.0",
"canvas-roundrect-polyfill": "0.0.1",
diff --git a/yarn.lock b/yarn.lock
index 52bb64f5e5..3b37abbd90 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1481,10 +1481,10 @@
resolved "https://registry.yarnpkg.com/@excalidraw/markdown-to-text/-/markdown-to-text-0.1.2.tgz#1703705e7da608cf478f17bfe96fb295f55a23eb"
integrity sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==
-"@excalidraw/[email protected]":
- version "3.0.0"
- resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-3.0.0.tgz#a7d1c3b6c0d81fa912b0d5a6a5207bbc606415d7"
- integrity sha512-jNWyeXP8kltRc8TBOS2IMEveBqFfpjNs2jklaR6AnTgT0yE4nqfsTbfyVxdAmwKtRmGg1MwQNJQ/FG8ELcAyOA==
+"@excalidraw/[email protected]":
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-3.1.0.tgz#352c9eaf7a56fa0e55015df70cc96c97fe7e8d20"
+ integrity sha512-B3H6aXm4f4O4+f7k1z/Eu1xNj3ZurnCX9RQNzjx00RCfnanLY4z8Pj/1r76FP8yZ1Ue84z50gJoRFCUIZy5xDg==
dependencies:
"@excalidraw/markdown-to-text" "0.1.2"
nanoid "4.0.2"