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({