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 `<meta>` (+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)
This commit is contained in:
dwelle committed 2026-10-28 08:55:50 +01:00
1 parent e3856c2417
commit 9c1daec001
3 files changed
+93 -1

No files matched your search

+11
View File
@@ -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
+42
View File
@@ -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;
});
};
+40 -1
View File
@@ -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({