Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): Lazy load and don't precache Firebase, lazy load mermaid (#12274)

Márk Tolmács1d4dc2c0e6e4
diff --git a/excalidraw-app/App.tsx b/excalidraw-app/App.tsx
index 8b9f940382..543bf05b6f 100644
--- a/excalidraw-app/App.tsx
+++ b/excalidraw-app/App.tsx
@@ -822,6 +822,14 @@ const ExcalidrawWrapper = () => {
};
const isOffline = useAtomValue(isOfflineAtom);
+ const isCollabAvailable =
+ !isCollabDisabled && (!isOffline || isCollaborating);
+
+ useEffect(() => {
+ if (!isCollabAvailable) {
+ setShareDialogState({ isOpen: false });
+ }
+ }, [isCollabAvailable, setShareDialogState]);
const localStorageQuotaExceeded = useAtomValue(localStorageQuotaExceededAtom);
@@ -993,7 +1001,7 @@ const ExcalidrawWrapper = () => {
theme={editorTheme}
onThemeChange={setAppTheme}
renderTopRightUI={(isMobile) => {
- if (isMobile || !collabAPI || isCollabDisabled) {
+ if (isMobile || !collabAPI || !isCollabAvailable) {
return null;
}
@@ -1030,13 +1038,13 @@ const ExcalidrawWrapper = () => {
<AppMainMenu
onCollabDialogOpen={onCollabDialogOpen}
isCollaborating={isCollaborating}
- isCollabEnabled={!isCollabDisabled}
+ isCollabEnabled={isCollabAvailable}
theme={appTheme}
refresh={() => forceRefresh((prev) => !prev)}
/>
<AppWelcomeScreen
onCollabDialogOpen={onCollabDialogOpen}
- isCollabEnabled={!isCollabDisabled}
+ isCollabEnabled={isCollabAvailable}
/>
<OverwriteConfirmDialog>
<OverwriteConfirmDialog.Actions.ExportToImage />
@@ -1113,6 +1121,7 @@ const ExcalidrawWrapper = () => {
{
label: t("labels.liveCollaboration"),
category: DEFAULT_CATEGORIES.app,
+ predicate: isCollabAvailable,
keywords: [
"team",
"multiplayer",
@@ -1154,7 +1163,7 @@ const ExcalidrawWrapper = () => {
{
label: t("labels.share"),
category: DEFAULT_CATEGORIES.app,
- predicate: true,
+ predicate: isCollabAvailable,
icon: share,
keywords: [
"link",
diff --git a/excalidraw-app/collab/Collab.tsx b/excalidraw-app/collab/Collab.tsx
index 34d225b37e..5569aa0fbf 100644
--- a/excalidraw-app/collab/Collab.tsx
+++ b/excalidraw-app/collab/Collab.tsx
@@ -12,6 +12,7 @@ import {
ACTIVE_THRESHOLD,
UserIdleState,
assertNever,
+ debounce,
isDevEnv,
isTestEnv,
preventUnload,
@@ -98,7 +99,11 @@ import type {
export const collabAPIAtom = atom<CollabAPI | null>(null);
export const isCollaboratingAtom = atom(false);
-export const isOfflineAtom = atom(false);
+export const isOfflineAtom = atom(
+ typeof navigator !== "undefined" && !navigator.onLine,
+);
+
+const OFFLINE_STATUS_DEBOUNCE_TIMEOUT = 1000;
interface CollabState {
errorMessage: string | null;
@@ -212,8 +217,8 @@ class Collab extends PureComponent<CollabProps, CollabState> {
componentDidMount() {
window.addEventListener(EVENT.BEFORE_UNLOAD, this.beforeUnload);
- window.addEventListener("online", this.onOfflineStatusToggle);
- window.addEventListener("offline", this.onOfflineStatusToggle);
+ window.addEventListener("online", this.onOfflineStatusChange);
+ window.addEventListener("offline", this.onOfflineStatusChange);
window.addEventListener(EVENT.UNLOAD, this.onUnload);
const unsubOnUserFollow = this.excalidrawAPI.onUserFollow((payload) => {
@@ -265,9 +270,15 @@ class Collab extends PureComponent<CollabProps, CollabState> {
appJotaiStore.set(isOfflineAtom, !window.navigator.onLine);
};
+ onOfflineStatusChange = debounce(
+ this.onOfflineStatusToggle,
+ OFFLINE_STATUS_DEBOUNCE_TIMEOUT,
+ );
+
componentWillUnmount() {
- window.removeEventListener("online", this.onOfflineStatusToggle);
- window.removeEventListener("offline", this.onOfflineStatusToggle);
+ window.removeEventListener("online", this.onOfflineStatusChange);
+ window.removeEventListener("offline", this.onOfflineStatusChange);
+ this.onOfflineStatusChange.cancel();
window.removeEventListener(EVENT.BEFORE_UNLOAD, this.beforeUnload);
window.removeEventListener(EVENT.UNLOAD, this.onUnload);
window.removeEventListener(EVENT.POINTER_MOVE, this.onPointerMove);
diff --git a/excalidraw-app/components/ExportToExcalidrawPlus.tsx b/excalidraw-app/components/ExportToExcalidrawPlus.tsx
index de40deacca..325bc8a439 100644
--- a/excalidraw-app/components/ExportToExcalidrawPlus.tsx
+++ b/excalidraw-app/components/ExportToExcalidrawPlus.tsx
@@ -1,5 +1,4 @@
import React from "react";
-import { uploadBytes, ref } from "firebase/storage";
import { nanoid } from "nanoid";
import { trackEvent } from "@excalidraw/excalidraw/analytics";
@@ -27,7 +26,7 @@ import type {
import { FILE_UPLOAD_MAX_BYTES } from "../app_constants";
import { encodeFilesForUpload } from "../data/FileManager";
-import { loadFirebaseStorage, saveFilesToFirebase } from "../data/firebase";
+import { saveFilesToFirebase, uploadBytesToFirebase } from "../data/firebase";
export const exportToExcalidrawPlus = async (
elements: readonly NonDeletedExcalidrawElement[],
@@ -35,8 +34,6 @@ export const exportToExcalidrawPlus = async (
files: BinaryFiles,
name: string,
) => {
- const storage = await loadFirebaseStorage();
-
const id = `${nanoid(12)}`;
const encryptionKey = (await generateEncryptionKey())!;
@@ -52,8 +49,7 @@ export const exportToExcalidrawPlus = async (
},
);
- const storageRef = ref(storage, `/migrations/scenes/${id}`);
- await uploadBytes(storageRef, blob, {
+ await uploadBytesToFirebase(`/migrations/scenes/${id}`, blob, {
customMetadata: {
data: JSON.stringify({ version: 2, name }),
created: Date.now().toString(),
diff --git a/excalidraw-app/data/firebase.ts b/excalidraw-app/data/firebase.ts
index 11177d90aa..e534f2ca65 100644
--- a/excalidraw-app/data/firebase.ts
+++ b/excalidraw-app/data/firebase.ts
@@ -7,15 +7,6 @@ import {
} from "@excalidraw/excalidraw/data/encryption";
import { restoreElements } from "@excalidraw/excalidraw/data/restore";
import { getSceneVersion } from "@excalidraw/element";
-import { initializeApp } from "firebase/app";
-import {
- getFirestore,
- doc,
- getDoc,
- runTransaction,
- Bytes,
-} from "firebase/firestore";
-import { getStorage, ref, uploadBytes } from "firebase/storage";
import type { RemoteExcalidrawElement } from "@excalidraw/excalidraw/data/reconcile";
import type {
@@ -37,6 +28,8 @@ import { getSyncableElements } from ".";
import type { SyncableExcalidrawElement } from ".";
import type Portal from "../collab/Portal";
import type { Socket } from "socket.io-client";
+import type { Bytes } from "firebase/firestore";
+import type { UploadMetadata } from "firebase/storage";
// private
// -----------------------------------------------------------------------------
@@ -53,35 +46,41 @@ try {
FIREBASE_CONFIG = {};
}
-let firebaseApp: ReturnType<typeof initializeApp> | null = null;
-let firestore: ReturnType<typeof getFirestore> | null = null;
-let firebaseStorage: ReturnType<typeof getStorage> | null = null;
-
-const _initializeFirebase = () => {
- if (!firebaseApp) {
- firebaseApp = initializeApp(FIREBASE_CONFIG);
- }
- return firebaseApp;
+const lazy = <T>(load: () => Promise<T>) => {
+ let promise: Promise<T> | null = null;
+ return () =>
+ (promise ??= load().catch((error) => {
+ promise = null;
+ throw error;
+ }));
};
-const _getFirestore = () => {
- if (!firestore) {
- firestore = getFirestore(_initializeFirebase());
- }
- return firestore;
-};
+const _initializeFirebase = lazy(async () => {
+ const sdk = await import("./firebaseSDK");
+ return { sdk, app: sdk.initializeApp(FIREBASE_CONFIG) };
+});
-const _getStorage = () => {
- if (!firebaseStorage) {
- firebaseStorage = getStorage(_initializeFirebase());
- }
- return firebaseStorage;
-};
+const _loadFirestore = lazy(async () => {
+ const { sdk, app } = await _initializeFirebase();
+ const { getFirestore, doc, getDoc, runTransaction, Bytes } = sdk;
+ return { firestore: getFirestore(app), doc, getDoc, runTransaction, Bytes };
+});
+
+const _loadStorage = lazy(async () => {
+ const { sdk, app } = await _initializeFirebase();
+ const { getStorage, ref, uploadBytes } = sdk;
+ return { storage: getStorage(app), ref, uploadBytes };
+});
// -----------------------------------------------------------------------------
-export const loadFirebaseStorage = async () => {
- return _getStorage();
+export const uploadBytesToFirebase = async (
+ path: string,
+ data: Blob | Uint8Array,
+ metadata?: UploadMetadata,
+) => {
+ const { storage, ref, uploadBytes } = await _loadStorage();
+ return uploadBytes(ref(storage, path), data, metadata);
};
type FirebaseStoredScene = {
@@ -149,7 +148,10 @@ export const saveFilesToFirebase = async ({
prefix: string;
files: { id: FileId; buffer: Uint8Array }[];
}) => {
- const storage = await loadFirebaseStorage();
+ // failing to load the SDK must fail the whole save rather than be reported
+ // per file as `erroredFiles` (which share links ignore, and collab never
+ // retries)
+ const { storage, ref, uploadBytes } = await _loadStorage();
const erroredFiles: FileId[] = [];
const savedFiles: FileId[] = [];
@@ -177,6 +179,7 @@ const createFirebaseSceneDocument = async (
) => {
const sceneVersion = getSceneVersion(elements);
const { ciphertext, iv } = await encryptElements(roomKey, elements);
+ const { Bytes } = await _loadFirestore();
return {
sceneVersion,
ciphertext: Bytes.fromUint8Array(new Uint8Array(ciphertext)),
@@ -200,7 +203,7 @@ export const saveToFirebase = async (
return null;
}
- const firestore = _getFirestore();
+ const { firestore, doc, runTransaction } = await _loadFirestore();
const docRef = doc(firestore, "scenes", roomId);
const storedScene = await runTransaction(firestore, async (transaction) => {
@@ -251,7 +254,7 @@ export const loadFromFirebase = async (
roomKey: string,
socket: Socket | null,
): Promise<readonly SyncableExcalidrawElement[] | null> => {
- const firestore = _getFirestore();
+ const { firestore, doc, getDoc } = await _loadFirestore();
const docRef = doc(firestore, "scenes", roomId);
const docSnap = await getDoc(docRef);
if (!docSnap.exists()) {
diff --git a/excalidraw-app/data/firebaseSDK.ts b/excalidraw-app/data/firebaseSDK.ts
new file mode 100644
index 0000000000..589625e08e
--- /dev/null
+++ b/excalidraw-app/data/firebaseSDK.ts
@@ -0,0 +1,15 @@
+// Firebase SDK subset used by the app. Loaded lazily from `./firebase.ts`
+// via `import("./firebaseSDK")` so it's not part of the main bundle.
+//
+// Static re-exports (rather than destructuring `await import("firebase/*")`)
+// keep the SDK tree-shakeable — Vite wraps dynamic imports in a preload
+// helper, which prevents Rollup from tree-shaking destructured imports.
+export { initializeApp } from "firebase/app";
+export {
+ getFirestore,
+ doc,
+ getDoc,
+ runTransaction,
+ Bytes,
+} from "firebase/firestore";
+export { getStorage, ref, uploadBytes } from "firebase/storage";
diff --git a/excalidraw-app/tests/firebase.test.ts b/excalidraw-app/tests/firebase.test.ts
new file mode 100644
index 0000000000..bca2d0b1b5
--- /dev/null
+++ b/excalidraw-app/tests/firebase.test.ts
@@ -0,0 +1,22 @@
+import { vi } from "vitest";
+
+import type { FileId } from "@excalidraw/element/types";
+
+import { saveFilesToFirebase } from "../data/firebase";
+
+vi.mock("../data/firebaseSDK", () => {
+ throw new TypeError(
+ "Failed to fetch dynamically imported module: http://localhost/assets/firebaseSDK.js",
+ );
+});
+
+describe("saveFilesToFirebase", () => {
+ it("should reject when the Firebase SDK fails to load", async () => {
+ await expect(
+ saveFilesToFirebase({
+ prefix: "/files/shareLinks/id",
+ files: [{ id: "file" as FileId, buffer: new Uint8Array([1]) }],
+ }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/excalidraw-app/vite.config.mts b/excalidraw-app/vite.config.mts
index 21469ebc94..0f2b3f7636 100644
--- a/excalidraw-app/vite.config.mts
+++ b/excalidraw-app/vite.config.mts
@@ -8,9 +8,102 @@ import checker from "vite-plugin-checker";
import { createHtmlPlugin } from "vite-plugin-html";
import Sitemap from "vite-plugin-sitemap";
import { woff2BrowserPlugin } from "../scripts/woff2/woff2-vite-plugins";
+
+import type { Plugin, Rollup } from "vite";
+
+/**
+ * Collects into `lazyChunkFileNames` the chunks reachable only via a dynamic
+ * 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.
+ */
+const lazyChunksPlugin = (
+ moduleRegex: RegExp,
+ lazyChunkFileNames: Set<string>,
+): Plugin => ({
+ name: "excalidraw-lazy-chunks",
+ apply: "build",
+ generateBundle(_options, bundle) {
+ const chunks = new Map<string, Rollup.OutputChunk>();
+ for (const file of Object.values(bundle)) {
+ if (file.type === "chunk") {
+ chunks.set(file.fileName, file);
+ }
+ }
+
+ // the dynamically imported module may share its chunk with its deps
+ // (no `facadeModuleId` then), so match on any contained module
+ const isLazyRoot = (chunk: Rollup.OutputChunk) =>
+ chunk.isDynamicEntry &&
+ !chunk.isEntry &&
+ chunk.moduleIds.some((id) => moduleRegex.test(id));
+
+ const collectReachable = (
+ roots: Rollup.OutputChunk[],
+ skipDynamicImport: (chunk: Rollup.OutputChunk) => boolean,
+ ) => {
+ const reachable = new Set<string>();
+ const stack = [...roots];
+ while (stack.length) {
+ const chunk = stack.pop()!;
+ if (reachable.has(chunk.fileName)) {
+ continue;
+ }
+ reachable.add(chunk.fileName);
+ // static imports are always followed: they're needed whenever the
+ // importing chunk is loaded
+ for (const fileName of chunk.imports) {
+ const next = chunks.get(fileName);
+ if (next) {
+ stack.push(next);
+ }
+ }
+ for (const fileName of chunk.dynamicImports) {
+ const next = chunks.get(fileName);
+ if (next && !skipDynamicImport(next)) {
+ stack.push(next);
+ }
+ }
+ }
+ return reachable;
+ };
+
+ const lazyRoots = [...chunks.values()].filter(isLazyRoot);
+ if (!lazyRoots.length) {
+ this.warn(`no lazy-loaded chunk found for ${moduleRegex}`);
+ }
+
+ // anything also reachable without dynamically importing the lazy roots
+ // (e.g. deps shared with the main bundle, or a lazy root that Rollup
+ // merged into a statically imported chunk) must stay precached
+ const reachableOtherwise = collectReachable(
+ [...chunks.values()].filter((chunk) => chunk.isEntry),
+ isLazyRoot,
+ );
+
+ for (const chunk of lazyRoots) {
+ if (reachableOtherwise.has(chunk.fileName)) {
+ this.warn(
+ `${chunk.fileName} (matching ${moduleRegex}) is reachable without a dynamic import, so it's not lazy-loaded and stays precached`,
+ );
+ }
+ }
+
+ lazyChunkFileNames.clear();
+ for (const fileName of collectReachable(lazyRoots, () => false)) {
+ if (!reachableOtherwise.has(fileName)) {
+ lazyChunkFileNames.add(fileName);
+ }
+ }
+ },
+});
+
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`.
+ const mermaidChunkFileNames = new Set<string>();
// https://vitejs.dev/config/
return {
server: {
@@ -108,6 +201,18 @@ export default defineConfig(({ mode }) => {
// app precache. en.json and percentages.json are needed for first load
// or fallback hence not clubbing with locales so first load followed by offline mode works fine. This is how CRA used to work too.
manualChunks(id) {
+ // Bundler runtime helpers (dynamic import preloading, CJS interop)
+ // would otherwise live in the main bundle, and every lazy chunk
+ // importing them would get a new file name with each deploy. Tabs
+ // still running the previous version would then fail to load
+ // non-precached lazy chunks (e.g. mermaid) after a deploy.
+ if (
+ id === "\0vite/preload-helper.js" ||
+ id === "\0commonjsHelpers.js"
+ ) {
+ return "bundler-helpers";
+ }
+
if (
id.includes("packages/excalidraw/locales") &&
id.match(/en.json|percentages.json/) === null
@@ -117,10 +222,6 @@ export default defineConfig(({ mode }) => {
return `locales/${id.substring(index + 8)}`;
}
- if (id.includes("@excalidraw/mermaid-to-excalidraw")) {
- return "mermaid-to-excalidraw";
- }
-
if (id.includes("@codemirror/") || id.includes("@lezer/")) {
return "codemirror.chunk";
}
@@ -140,6 +241,10 @@ export default defineConfig(({ mode }) => {
generateRobotsTxt: false,
}),
woff2BrowserPlugin(),
+ lazyChunksPlugin(
+ /[\\/]node_modules[\\/]@excalidraw[\\/]mermaid-to-excalidraw[\\/]/,
+ mermaidChunkFileNames,
+ ),
react(),
checker({
typescript: true,
@@ -173,6 +278,19 @@ export default defineConfig(({ mode }) => {
// via a static import from the main bundle, defeating lazy
// loading. So we exclude it by name instead.
"**/CodeMirrorEditor-*.js",
+ // lazy-loaded Firebase SDK, only needed for collab/sharing, which
+ // require network anyway
+ "**/firebaseSDK-*.js",
+ ],
+ // mermaid chunks are excluded here rather than via `globIgnores`
+ // as their file names are arbitrary
+ manifestTransforms: [
+ (entries) => ({
+ manifest: entries.filter(
+ (entry) => !mermaidChunkFileNames.has(entry.url),
+ ),
+ warnings: [],
+ }),
],
runtimeCaching: [
{
@@ -222,6 +340,17 @@ export default defineConfig(({ mode }) => {
},
},
},
+ {
+ urlPattern: new RegExp("/assets/[^/]+\\.js$"),
+ handler: "CacheFirst",
+ options: {
+ cacheName: "lazy-chunks",
+ expiration: {
+ maxEntries: 200,
+ maxAgeSeconds: 60 * 60 * 24 * 90, // <== 90 days
+ },
+ },
+ },
],
maximumFileSizeToCacheInBytes: 2.3 * 1024 ** 2, // 2.3MB
},
diff --git a/packages/excalidraw/components/App.clipboard.ts b/packages/excalidraw/components/App.clipboard.ts
index f81e3dc846..241b9e5322 100644
--- a/packages/excalidraw/components/App.clipboard.ts
+++ b/packages/excalidraw/components/App.clipboard.ts
@@ -206,8 +206,9 @@ export class AppClipboard {
// ------------------- Successful Mermaid -------------------
if (!isPlainPaste && isMaybeMermaidDefinition(data.text)) {
- const api = await import("@excalidraw/mermaid-to-excalidraw");
try {
+ // if this fails to load (e.g. offline), fall through and paste as text
+ const api = await import("@excalidraw/mermaid-to-excalidraw");
const { elements: skeletonElements, files = {} } =
await api.parseMermaidToExcalidraw(data.text);
diff --git a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx
index 4bf3f17767..df2d936a30 100644
--- a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx
+++ b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx
@@ -1,6 +1,12 @@
import { useState, useRef, useEffect, useDeferredValue } from "react";
-import { EDITOR_LS_KEYS, debounce, isDevEnv } from "@excalidraw/common";
+import {
+ EDITOR_LS_KEYS,
+ EVENT,
+ addEventListener,
+ debounce,
+ isDevEnv,
+} from "@excalidraw/common";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
@@ -62,9 +68,11 @@ const getErrorMessage = (error: unknown): string => {
const MermaidToExcalidraw = ({
mermaidToExcalidrawLib,
+ onRetryLoad,
isActive,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
+ onRetryLoad?: () => void;
isActive?: boolean;
}) => {
const [text, setText] = useState(
@@ -94,6 +102,9 @@ const MermaidToExcalidraw = ({
useEffect(() => {
const doRender = async () => {
+ if (mermaidToExcalidrawLib.status !== "loaded") {
+ return;
+ }
try {
if (!deferredText.trim()) {
resetPreview({ canvasRef, setError });
@@ -125,12 +136,18 @@ const MermaidToExcalidraw = ({
}
}, [deferredText, mermaidToExcalidrawLib, isActive, theme]);
- useEffect(
- () => () => {
- debouncedSaveMermaidDefinition.flush();
- },
- [],
- );
+ useEffect(() => {
+ const flush = () => debouncedSaveMermaidDefinition.flush();
+ const unsubscribe = addEventListener(
+ app.ownerWindow,
+ EVENT.BEFORE_UNLOAD,
+ flush,
+ );
+ return () => {
+ unsubscribe();
+ flush();
+ };
+ }, [app]);
useEffect(() => {
const errorMessage = error?.message ?? "";
@@ -139,7 +156,7 @@ const MermaidToExcalidraw = ({
isActive &&
isMermaidAutoFixableError(errorMessage) &&
!!sourceText.trim() &&
- mermaidToExcalidrawLib.loaded;
+ mermaidToExcalidrawLib.status === "loaded";
if (!shouldTryAutoFix) {
setAutoFixCandidate(null);
@@ -300,7 +317,9 @@ const MermaidToExcalidraw = ({
>
<TTDDialogOutput
canvasRef={canvasRef}
- loaded={mermaidToExcalidrawLib.loaded}
+ loadStatus={mermaidToExcalidrawLib.status}
+ loadErrorReloadRequired={mermaidToExcalidrawLib.reloadRequired}
+ onRetryLoad={onRetryLoad}
error={error}
sourceText={text}
autoFixAvailable={!!autoFixCandidate}
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
index a16c0cc385..0f0b824724 100644
--- a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
+++ b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx
@@ -1,4 +1,6 @@
-import { useEffect, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
+
+import { addEventListener } from "@excalidraw/common";
import { useUIAppState } from "../../context/ui-appState";
import { t } from "../../i18n";
@@ -12,6 +14,7 @@ import TTDDialogTabs from "./TTDDialogTabs";
import { TTDDialogTabTriggers } from "./TTDDialogTabTriggers";
import { TTDDialogTabTrigger } from "./TTDDialogTabTrigger";
import { TTDDialogTab } from "./TTDDialogTab";
+import { isModuleLoadError } from "./utils/mermaidError";
import "./TTDDialog.scss";
@@ -44,6 +47,32 @@ export const TTDDialog = (
TTDDialog.WelcomeMessage = TTDWelcomeMessage;
+const loadMermaidToExcalidrawLib = (
+ onChunkLoadError: (api: MermaidToExcalidrawLibProps["api"]) => void,
+): MermaidToExcalidrawLibProps["api"] => {
+ const api: MermaidToExcalidrawLibProps["api"] = import(
+ "@excalidraw/mermaid-to-excalidraw"
+ ).then((lib) => ({
+ // mermaid 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 {
+ return await lib.parseMermaidToExcalidraw(definition, config);
+ } catch (error) {
+ if (isModuleLoadError(error)) {
+ onChunkLoadError(api);
+ }
+ throw error;
+ }
+ },
+ }));
+ // called from state initializers/updaters, which React may invoke more than
+ // once and discard the result -> don't let a discarded promise's rejection
+ // go unhandled (consumers awaiting `api` still get the rejection)
+ api.catch(() => {});
+ return api;
+};
+
/**
* Text to diagram (TTD) dialog
*/
@@ -68,18 +97,74 @@ const TTDDialogBase = withInternalFallback(
const app = useApp();
const [mermaidToExcalidrawLib, setMermaidToExcalidrawLib] =
- useState<MermaidToExcalidrawLibProps>({
- loaded: false,
- api: import("@excalidraw/mermaid-to-excalidraw"),
- });
+ useState<MermaidToExcalidrawLibProps>(() => ({
+ status: "loading",
+ api: loadMermaidToExcalidrawLib((api) => setLoadError(api)),
+ }));
+
+ // `api` (or one of the chunks it lazy-loads) failed to load
+ const setLoadError = useCallback(
+ (api: MermaidToExcalidrawLibProps["api"]) => {
+ const reloadRequired = navigator.onLine;
+ setMermaidToExcalidrawLib((prev) =>
+ prev.api === api
+ ? {
+ ...prev,
+ status: "error",
+ reloadRequired: prev.reloadRequired || reloadRequired,
+ }
+ : prev,
+ );
+ },
+ [],
+ );
+
+ const retryLoadingMermaidToExcalidrawLib = useCallback(() => {
+ setMermaidToExcalidrawLib((prev) =>
+ prev.status === "error"
+ ? {
+ ...prev,
+ status: "loading",
+ api: loadMermaidToExcalidrawLib(setLoadError),
+ }
+ : prev,
+ );
+ }, [setLoadError]);
+ const { api: mermaidToExcalidrawLibApi } = mermaidToExcalidrawLib;
useEffect(() => {
- const fn = async () => {
- await mermaidToExcalidrawLib.api;
- setMermaidToExcalidrawLib((prev) => ({ ...prev, loaded: true }));
- };
- fn();
- }, [mermaidToExcalidrawLib.api]);
+ const api = mermaidToExcalidrawLibApi;
+ api.then(
+ () => {
+ setMermaidToExcalidrawLib((prev) =>
+ prev.api === api
+ ? { ...prev, status: "loaded", reloadRequired: false }
+ : prev,
+ );
+ },
+ (error: any) => {
+ console.error("Failed to load mermaid-to-excalidraw", error);
+ setLoadError(api);
+ },
+ );
+ }, [mermaidToExcalidrawLibApi, setLoadError]);
+
+ // the lib chunk isn't precached, so a failed load is most likely due to
+ // being offline -> retry automatically once we're back online
+ useEffect(() => {
+ if (mermaidToExcalidrawLib.status !== "error") {
+ return;
+ }
+ return addEventListener(
+ app.ownerWindow,
+ "online",
+ retryLoadingMermaidToExcalidrawLib,
+ );
+ }, [
+ app,
+ mermaidToExcalidrawLib.status,
+ retryLoadingMermaidToExcalidrawLib,
+ ]);
return (
<Dialog
@@ -115,6 +200,7 @@ const TTDDialogBase = withInternalFallback(
<TTDDialogTab className="ttd-dialog-content" tab="text-to-diagram">
<TextToDiagram
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
+ onRetryLoad={retryLoadingMermaidToExcalidrawLib}
onTextSubmit={rest.onTextSubmit}
renderWelcomeScreen={rest.renderWelcomeScreen}
renderWarning={rest.renderWarning}
@@ -125,6 +211,7 @@ const TTDDialogBase = withInternalFallback(
<TTDDialogTab className="ttd-dialog-content" tab="mermaid">
<MermaidToExcalidraw
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
+ onRetryLoad={retryLoadingMermaidToExcalidrawLib}
isActive={tab === "mermaid"}
/>
</TTDDialogTab>
diff --git a/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx b/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx
index 4d73018717..ed8b447574 100644
--- a/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx
+++ b/packages/excalidraw/components/TTDDialog/TTDDialogOutput.tsx
@@ -1,5 +1,6 @@
import clsx from "clsx";
+import { useApp } from "../App";
import { Button } from "../Button";
import Spinner from "../Spinner";
import { t } from "../../i18n";
@@ -9,12 +10,17 @@ import {
formatMermaidParseErrorMessage,
getMermaidSyntaxErrorGuidance,
isMermaidCaretLine,
+ isModuleLoadError,
} from "./utils/mermaidError";
+import type { MermaidToExcalidrawLibProps } from "./types";
+
interface TTDDialogOutputProps {
error: Error | null;
canvasRef: React.RefObject<HTMLDivElement | null>;
- loaded: boolean;
+ loadStatus: MermaidToExcalidrawLibProps["status"];
+ loadErrorReloadRequired?: boolean;
+ onRetryLoad?: () => void;
hideErrorDetails?: boolean;
sourceText?: string;
autoFixAvailable?: boolean;
@@ -24,20 +30,28 @@ interface TTDDialogOutputProps {
export const TTDDialogOutput = ({
error,
canvasRef,
- loaded,
+ loadStatus,
+ loadErrorReloadRequired,
+ onRetryLoad,
hideErrorDetails,
sourceText,
autoFixAvailable,
onApplyAutoFix,
}: TTDDialogOutputProps) => {
- const errorMessage = error
+ const app = useApp();
+ const loadFailed = loadStatus === "error";
+ // a chunk failing to load is shown as a load failure (see `loadStatus`),
+ // not as a syntax error
+ const parseError = isModuleLoadError(error) ? null : error;
+
+ const errorMessage = parseError
? hideErrorDetails
? t("chat.errors.mermaidParseError")
- : formatMermaidParseErrorMessage(error.message)
+ : formatMermaidParseErrorMessage(parseError.message)
: null;
const syntaxGuidance =
- error && !hideErrorDetails
- ? getMermaidSyntaxErrorGuidance(error.message, sourceText)
+ parseError && !hideErrorDetails
+ ? getMermaidSyntaxErrorGuidance(parseError.message, sourceText)
: null;
const showAutoFixButton =
!!autoFixAvailable && !!onApplyAutoFix && !hideErrorDetails;
@@ -47,10 +61,10 @@ export const TTDDialogOutput = ({
return (
<div
className={`ttd-dialog-output-wrapper ${
- error ? "ttd-dialog-output-wrapper--error" : ""
+ parseError || loadFailed ? "ttd-dialog-output-wrapper--error" : ""
}`}
>
- {error && (
+ {parseError && !loadFailed && (
<div
key="error"
data-testid="ttd-dialog-output-error"
@@ -105,11 +119,45 @@ export const TTDDialogOutput = ({
</div>
</div>
)}
- {loaded ? (
+ {loadFailed ? (
+ <div
+ key="load-error"
+ data-testid="ttd-dialog-output-load-error"
+ className="ttd-dialog-output-error"
+ >
+ <div className="ttd-dialog-output-error-content">
+ <div className="ttd-dialog-output-error-icon">
+ {alertTriangleIcon}
+ </div>
+ <div className="ttd-dialog-output-error-title">
+ {loadErrorReloadRequired
+ ? t("mermaid.loadErrorReload")
+ : t("mermaid.loadError")}
+ </div>
+ {loadErrorReloadRequired ? (
+ <Button
+ className="ttd-dialog-panel-button"
+ onSelect={() => app.ownerWindow.location.reload()}
+ >
+ {t("mermaid.reload")}
+ </Button>
+ ) : (
+ onRetryLoad && (
+ <Button
+ className="ttd-dialog-panel-button"
+ onSelect={onRetryLoad}
+ >
+ {t("chat.retry")}
+ </Button>
+ )
+ )}
+ </div>
+ </div>
+ ) : loadStatus === "loaded" ? (
<div
key="canvas"
className={clsx("ttd-dialog-output-canvas-container", {
- invisible: !!error,
+ invisible: !!parseError,
})}
>
<div ref={canvasRef} className="ttd-dialog-output-canvas-content" />
diff --git a/packages/excalidraw/components/TTDDialog/TTDPreviewPanel.tsx b/packages/excalidraw/components/TTDDialog/TTDPreviewPanel.tsx
index 84bebb4c7f..ce3d1bd4f8 100644
--- a/packages/excalidraw/components/TTDDialog/TTDPreviewPanel.tsx
+++ b/packages/excalidraw/components/TTDDialog/TTDPreviewPanel.tsx
@@ -5,11 +5,14 @@ import { TTDDialogPanel } from "./TTDDialogPanel";
import { TTDDialogOutput } from "./TTDDialogOutput";
import type { TTDPanelAction } from "./TTDDialogPanel";
+import type { MermaidToExcalidrawLibProps } from "./types";
interface TTDPreviewPanelProps {
canvasRef: React.RefObject<HTMLDivElement | null>;
error: Error | null;
- loaded: boolean;
+ loadStatus: MermaidToExcalidrawLibProps["status"];
+ loadErrorReloadRequired?: boolean;
+ onRetryLoad?: () => void;
onInsert: () => void;
hideErrorDetails?: boolean;
}
@@ -17,7 +20,9 @@ interface TTDPreviewPanelProps {
export const TTDPreviewPanel = ({
canvasRef,
error,
- loaded,
+ loadStatus,
+ loadErrorReloadRequired,
+ onRetryLoad,
onInsert,
hideErrorDetails,
}: TTDPreviewPanelProps) => {
@@ -39,7 +44,9 @@ export const TTDPreviewPanel = ({
<TTDDialogOutput
canvasRef={canvasRef}
error={error}
- loaded={loaded}
+ loadStatus={loadStatus}
+ loadErrorReloadRequired={loadErrorReloadRequired}
+ onRetryLoad={onRetryLoad}
hideErrorDetails={hideErrorDetails}
/>
</TTDDialogPanel>
diff --git a/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx b/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx
index da547602aa..177e396ab0 100644
--- a/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx
+++ b/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx
@@ -3,6 +3,7 @@ import { useRef } from "react";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { useAtom, useAtomValue } from "../../editor-jotai";
+import { t } from "../../i18n";
import { useApp, useExcalidrawSetAppState } from "../App";
@@ -34,12 +35,14 @@ import type {
const TextToDiagramContent = ({
mermaidToExcalidrawLib,
+ onRetryLoad,
onTextSubmit,
renderWelcomeScreen,
renderWarning,
persistenceAdapter,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
+ onRetryLoad?: () => void;
onTextSubmit: (
props: TTTDDialog.OnTextSubmitProps,
) => Promise<TTTDDialog.OnTextSubmitRetValue>;
@@ -68,6 +71,7 @@ const TextToDiagramContent = ({
const { onGenerate, handleAbort } = useTextGeneration({
onTextSubmit,
+ mermaidToExcalidrawLib,
});
const {
@@ -100,7 +104,21 @@ const TextToDiagramContent = ({
const handleInsertMessage = async (message: TChat.ChatMessage) => {
const mermaidContent = message.content || "";
- if (!mermaidContent.trim() || !mermaidToExcalidrawLib.loaded) {
+ if (!mermaidContent.trim()) {
+ return;
+ }
+
+ if (mermaidToExcalidrawLib.status !== "loaded") {
+ if (mermaidToExcalidrawLib.status === "error") {
+ setAppState({
+ toast: {
+ message: mermaidToExcalidrawLib.reloadRequired
+ ? t("mermaid.loadErrorReload")
+ : t("mermaid.loadError"),
+ closable: true,
+ },
+ });
+ }
return;
}
@@ -229,7 +247,9 @@ const TextToDiagramContent = ({
canvasRef={canvasRef}
hideErrorDetails={lastAssistantMessage?.errorType === "parse"}
error={error}
- loaded={mermaidToExcalidrawLib.loaded}
+ loadStatus={mermaidToExcalidrawLib.status}
+ loadErrorReloadRequired={mermaidToExcalidrawLib.reloadRequired}
+ onRetryLoad={onRetryLoad}
onInsert={handleInsertToEditor}
/>
)}
@@ -239,12 +259,14 @@ const TextToDiagramContent = ({
export const TextToDiagram = ({
mermaidToExcalidrawLib,
+ onRetryLoad,
onTextSubmit,
renderWelcomeScreen,
renderWarning,
persistenceAdapter,
}: {
mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
+ onRetryLoad?: () => void;
onTextSubmit(
props: TTTDDialog.OnTextSubmitProps,
): Promise<TTTDDialog.OnTextSubmitRetValue>;
@@ -255,6 +277,7 @@ export const TextToDiagram = ({
return (
<TextToDiagramContent
mermaidToExcalidrawLib={mermaidToExcalidrawLib}
+ onRetryLoad={onRetryLoad}
onTextSubmit={onTextSubmit}
renderWelcomeScreen={renderWelcomeScreen}
renderWarning={renderWarning}
diff --git a/packages/excalidraw/components/TTDDialog/common.test.ts b/packages/excalidraw/components/TTDDialog/common.test.ts
index 907c347e22..e8023ad3a6 100644
--- a/packages/excalidraw/components/TTDDialog/common.test.ts
+++ b/packages/excalidraw/components/TTDDialog/common.test.ts
@@ -18,7 +18,7 @@ const createConvertArgs = (
return {
canvasRef: { current: canvas },
mermaidToExcalidrawLib: {
- loaded: true,
+ status: "loaded" as const,
api: Promise.resolve({ parseMermaidToExcalidraw }),
},
mermaidDefinition,
diff --git a/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts b/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts
index 9f169c06f1..b444397af9 100644
--- a/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts
+++ b/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts
@@ -63,7 +63,10 @@ export const useMermaidRenderer = ({
const renderMermaid = useCallback(
async (mermaidDefinition: string): Promise<boolean> => {
- if (!mermaidDefinition.trim() || !mermaidToExcalidrawLib.loaded) {
+ if (
+ !mermaidDefinition.trim() ||
+ mermaidToExcalidrawLib.status !== "loaded"
+ ) {
return false;
}
diff --git a/packages/excalidraw/components/TTDDialog/hooks/useTextGeneration.ts b/packages/excalidraw/components/TTDDialog/hooks/useTextGeneration.ts
index e31847ae0c..16fc61a3af 100644
--- a/packages/excalidraw/components/TTDDialog/hooks/useTextGeneration.ts
+++ b/packages/excalidraw/components/TTDDialog/hooks/useTextGeneration.ts
@@ -1,5 +1,4 @@
-import { useRef } from "react";
-import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw";
+import { useEffect, useRef, useState } from "react";
import { isFiniteNumber } from "@excalidraw/math";
import { useAtom } from "../../../editor-jotai";
@@ -17,18 +16,25 @@ import {
removeLastAssistantMessage,
updateAssistantContent,
} from "../utils/chat";
+import { isModuleLoadError } from "../utils/mermaidError";
-import type { LLMMessage, TTTDDialog } from "../types";
+import type {
+ LLMMessage,
+ MermaidToExcalidrawLibProps,
+ TTTDDialog,
+} from "../types";
const MIN_PROMPT_LENGTH = 3;
const MAX_PROMPT_LENGTH = 10000;
export const useTextGeneration = ({
onTextSubmit,
+ mermaidToExcalidrawLib,
}: {
onTextSubmit: (
props: TTTDDialog.OnTextSubmitProps,
) => Promise<TTTDDialog.OnTextSubmitRetValue>;
+ mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;
}) => {
const [, setError] = useAtom(errorAtom);
const [rateLimits, setRateLimits] = useAtom(rateLimitsAtom);
@@ -39,6 +45,66 @@ export const useTextGeneration = ({
const streamingAbortControllerRef = useRef<AbortController | null>(null);
+ // the lib may get reloaded (retry) while a generation is in flight, so
+ // always validate against the latest one
+ const mermaidToExcalidrawLibRef = useRef(mermaidToExcalidrawLib);
+ mermaidToExcalidrawLibRef.current = mermaidToExcalidrawLib;
+
+ // generated mermaid that couldn't be validated because the lib failed to
+ // load (e.g. offline) -> validated once the lib loads
+ const [pendingValidation, setPendingValidation] = useState<string | null>(
+ null,
+ );
+
+ const validateMermaid = async (
+ { parseMermaidToExcalidraw }: Awaited<MermaidToExcalidrawLibProps["api"]>,
+ mermaidDefinition: string,
+ ) => {
+ try {
+ await parseMermaidToExcalidraw(mermaidDefinition);
+ trackEvent("ai", "mermaid parse success", "ttd");
+ } catch (error: any) {
+ if (isModuleLoadError(error)) {
+ // not a syntax error, but a diagram chunk failing to load
+ setPendingValidation(mermaidDefinition);
+ return;
+ }
+ trackEvent("ai", "mermaid parse failed", "ttd");
+ const _error = new Error(
+ error.message || t("chat.errors.mermaidParseError"),
+ );
+ setAssistantError(_error.message, "parse");
+ setError(_error);
+ }
+ };
+
+ useEffect(() => {
+ if (
+ pendingValidation === null ||
+ mermaidToExcalidrawLib.status !== "loaded"
+ ) {
+ return;
+ }
+ setPendingValidation(null);
+
+ // skip if the user has moved on (new generation, switched chats, ...)
+ const lastAssistantMessage = getLastAssistantMessage(chatHistory);
+ if (
+ lastAssistantMessage?.isGenerating ||
+ lastAssistantMessage?.error ||
+ (lastAssistantMessage?.content ?? "") !== pendingValidation
+ ) {
+ return;
+ }
+
+ mermaidToExcalidrawLib.api.then(
+ (api) => validateMermaid(api, pendingValidation),
+ () => {},
+ );
+ // validateMermaid only closes over stable setters
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [pendingValidation, mermaidToExcalidrawLib, chatHistory]);
+
const validatePrompt = (prompt: string): boolean => {
if (
prompt.length > MAX_PROMPT_LENGTH ||
@@ -76,6 +142,7 @@ export const useTextGeneration = ({
}
setError(null);
+ setPendingValidation(null);
const abortController = new AbortController();
streamingAbortControllerRef.current = abortController;
@@ -190,17 +257,16 @@ export const useTextGeneration = ({
return;
}
+ let api;
try {
- await parseMermaidToExcalidraw(generatedResponse ?? "");
- trackEvent("ai", "mermaid parse success", "ttd");
+ api = await mermaidToExcalidrawLibRef.current.api;
} catch (error: any) {
- trackEvent("ai", "mermaid parse failed", "ttd");
- const _error = new Error(
- error.message || t("chat.errors.mermaidParseError"),
- );
- setAssistantError(_error.message, "parse");
- setError(_error);
+ console.error("Failed to load mermaid-to-excalidraw", error);
+ setPendingValidation(generatedResponse ?? "");
+ return;
}
+
+ await validateMermaid(api, generatedResponse ?? "");
} catch (error: any) {
const _error = new Error(
error.message || t("chat.errors.generationFailed"),
diff --git a/packages/excalidraw/components/TTDDialog/types.ts b/packages/excalidraw/components/TTDDialog/types.ts
index 7f79894b92..c4ca90c1c7 100644
--- a/packages/excalidraw/components/TTDDialog/types.ts
+++ b/packages/excalidraw/components/TTDDialog/types.ts
@@ -72,7 +72,14 @@ export interface TTDPersistenceAdapter {
}
export interface MermaidToExcalidrawLibProps {
- loaded: boolean;
+ /** loading state of the (lazy) lib. "error" e.g. while offline */
+ status: "loading" | "loaded" | "error";
+ /**
+ * set when loading failed while online (e.g. stale app version after
+ * a deploy, or the browser cached the failed fetch), i.e. only a page
+ * reload will likely recover
+ */
+ reloadRequired?: boolean;
api: Promise<{
parseMermaidToExcalidraw: (
definition: string,
diff --git a/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts b/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
index 343cc9b57b..c6aea58b93 100644
--- a/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
+++ b/packages/excalidraw/components/TTDDialog/utils/mermaidError.ts
@@ -2,6 +2,13 @@ const MERMAID_SYNTAX_ERROR_LINE = /(?:Parse|Lexical) error on line (\d+)[.:]/i;
const MERMAID_INACTIVE_PARTICIPANT_ERROR =
/Trying to inactivate an inactive participant \((.+)\)/i;
const MERMAID_CARET_LINE = /^\s*-+\^\s*$/;
+// Chrome, Firefox and Safari messages respectively
+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 */
+export const isModuleLoadError = (error: unknown) =>
+ error instanceof Error && MODULE_LOAD_ERROR.test(error.message);
export const isMermaidParseSyntaxError = (message: string) =>
MERMAID_SYNTAX_ERROR_LINE.test(message);
diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.json
index 22daaac127..578129b843 100644
--- a/packages/excalidraw/locales/en.json
+++ b/packages/excalidraw/locales/en.json
@@ -682,7 +682,10 @@
"preview": "Preview",
"label": "Mermaid",
"inputPlaceholder": "Write Mermaid diagram definition here...",
- "autoFixAvailable": "Auto-fix is available"
+ "autoFixAvailable": "Auto-fix is available",
+ "loadError": "Couldn't load Mermaid. Check your internet connection and try again.",
+ "loadErrorReload": "Couldn't load Mermaid. Reload the page to try again.",
+ "reload": "Reload"
},
"ttd": {
"error": "Error!"
diff --git a/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx b/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx
index db1d32e314..1d1b9f0a9b 100644
--- a/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx
+++ b/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx
@@ -76,6 +76,12 @@ mockMermaidToExcalidraw({
},
],
});
+ } else if (firstLine === "sequenceDiagram") {
+ reject(
+ new TypeError(
+ "Failed to fetch dynamically imported module: http://localhost/assets/sequenceDiagram.js",
+ ),
+ );
} else {
reject(new Error("ERROR"));
}
@@ -142,4 +148,21 @@ describe("Test <MermaidToExcalidraw/>", () => {
dialog.querySelector('[data-testid="mermaid-error"]'),
).toMatchInlineSnapshot("null");
});
+
+ it("should show a load error when a diagram chunk fails to load", async () => {
+ const dialog = document.querySelector(".ttd-dialog")!;
+ const selector = ".ttd-dialog-input";
+ const editor = await getTextEditor({ selector, waitForEditor: true });
+
+ updateTextEditor(editor, "sequenceDiagram");
+
+ await waitFor(() =>
+ expect(
+ dialog.querySelector('[data-testid="ttd-dialog-output-load-error"]'),
+ ).not.toBeNull(),
+ );
+ expect(
+ dialog.querySelector('[data-testid="ttd-dialog-output-error"]'),
+ ).toBeNull();
+ });
});