From 9c1daec0011b53ce77201f595117977f31567330 Mon Sep 17 00:00:00 2001
From: dwelle <5153846+dwelle@users.noreply.github.com>
Date: Tue, 27 Oct 2026 22:24:36 +0100
Subject: [PATCH] feat(app): cache all Mermaid chunks for offline use once the
TTD dialog opens
mermaid-to-excalidraw 3.1 splits Pele into a chunk per diagram type,
which aren't precached. With 3.0, the single Pele chunk cached on first
use covered every diagram type offline; now only the types converted
while online would.
`lazyChunksPlugin` emits the list of mermaid chunks as a hashed JSON
asset, which index.html points to with a `` (+33 B br). Once the
TTD dialog is opened, the app fetches the list and the chunks (after 5 s,
so the dialog's own chunks aren't fetched twice, at low priority) for the
service worker to cache in `lazy-chunks` (~200 kB br on top of what the
dialog loads). App only: package hosts (e.g. E+) are unaffected.
Claude Opus 5.5 (xhigh)
---
excalidraw-app/components/AI.tsx | 11 ++++++
excalidraw-app/data/cacheMermaidChunks.ts | 42 +++++++++++++++++++++++
excalidraw-app/vite.config.mts | 41 +++++++++++++++++++++-
3 files changed, 93 insertions(+), 1 deletion(-)
create mode 100644 excalidraw-app/data/cacheMermaidChunks.ts
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 (
<>
` 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 | 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(
+ `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 (``), for the
+ * app to cache them when it needs them.
*/
const lazyChunksPlugin = (
moduleRegex: RegExp,
lazyChunkFileNames: Set,
+ 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();
// 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({