From 597a2c8fcbfba4f99d3a4d3b0758c663eb18657c Mon Sep 17 00:00:00 2001 From: David Luzar <5153846+dwelle@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:26:21 +0100 Subject: [PATCH] fix(editor): retry Mermaid chunks that fail to load before asking for a reload (#12868) Browsers no longer cache a failed dynamic import (Chrome 156+, Firefox, Safari), so a chunk that failed to load (e.g. a network blip) can be loaded again without reloading the page. The Mermaid lib and its per-diagram-type chunks are now retried twice (after 0.5 s and 1.5 s) while online; the reload message shows only if the retries fail too (a chunk removed by a newer deploy, or an older browser that caches the failure). --- .../components/TTDDialog/TTDDialog.tsx | 39 ++++++++++++-- .../excalidraw/components/TTDDialog/common.ts | 6 ++- .../excalidraw/components/TTDDialog/types.ts | 6 +-- .../tests/MermaidToExcalidraw.test.tsx | 54 +++++++++++++++++-- 4 files changed, 91 insertions(+), 14 deletions(-) diff --git a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx index 518d52d17d..aaafcd1c42 100644 --- a/packages/excalidraw/components/TTDDialog/TTDDialog.tsx +++ b/packages/excalidraw/components/TTDDialog/TTDDialog.tsx @@ -48,20 +48,48 @@ export const TTDDialog = ( TTDDialog.WelcomeMessage = TTDWelcomeMessage; +/** waits before each retry of a lazy chunk that failed to load */ +const CHUNK_LOAD_RETRY_DELAYS = [500, 1500]; + +/** + * Re-runs `load` while it fails to load a lazy chunk (e.g. a network blip). + * Browsers no longer cache a failed dynamic import (Chrome 156+, Firefox, + * Safari), so a retry fetches the chunk again. Older browsers fail every + * retry straight away, and a chunk a deploy removed keeps failing: both end + * up asking for a reload. Offline, we fail right away instead and retry once + * the browser is back online. + */ +const retryChunkLoad = async (load: () => Promise): Promise => { + for (const delay of CHUNK_LOAD_RETRY_DELAYS) { + try { + return await load(); + } catch (error) { + if (!isModuleLoadError(error) || !navigator.onLine) { + throw error; + } + } + await new Promise((resolve) => setTimeout(resolve, delay)); + } + return load(); +}; + const loadMermaidToExcalidrawLib = ( onChunkLoadError: (api: MermaidToExcalidrawLibProps["api"]) => void, ): MermaidToExcalidrawLibProps["api"] => { - const api: MermaidToExcalidrawLibProps["api"] = import( - "@excalidraw/mermaid-to-excalidraw" + const api: MermaidToExcalidrawLibProps["api"] = retryChunkLoad( + () => import("@excalidraw/mermaid-to-excalidraw"), ).then((lib) => ({ // Pele lazy-loads a chunk per diagram type, which can fail to load - // (e.g. offline) even though the lib itself loaded fine + // (e.g. offline) even though the lib itself loaded fine. Both the lib and + // Pele import such a chunk again on each call, so the parse is retried parseMermaidToExcalidraw: async ( definition, config = MERMAID_TO_EXCALIDRAW_CONFIG, ) => { try { - return await lib.parseMermaidToExcalidraw(definition, config); + return await retryChunkLoad(() => + lib.parseMermaidToExcalidraw(definition, config), + ); } catch (error) { if (isModuleLoadError(error)) { onChunkLoadError(api); @@ -106,7 +134,8 @@ const TTDDialogBase = withInternalFallback( api: loadMermaidToExcalidrawLib((api) => setLoadError(api)), })); - // `api` (or one of the chunks it lazy-loads) failed to load + // `api` (or one of the chunks it lazy-loads) failed to load, after the + // retries if online const setLoadError = useCallback( (api: MermaidToExcalidrawLibProps["api"]) => { const reloadRequired = navigator.onLine; diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.ts index c1d6f192d9..c9642d1a08 100644 --- a/packages/excalidraw/components/TTDDialog/common.ts +++ b/packages/excalidraw/components/TTDDialog/common.ts @@ -12,6 +12,8 @@ import { exportScene } from "../../scene/export"; import { EditorLocalStorage } from "../../data/EditorLocalStorage"; +import { isModuleLoadError } from "./utils/mermaidError"; + import type { MermaidToExcalidrawLibProps } from "./types"; import type { AppClassProperties, BinaryFiles } from "../../types"; @@ -79,7 +81,9 @@ export const convertMermaidToExcalidraw = async ({ } catch (err: unknown) { const originalParseError = err as Error; - if (!mermaidDefinition.includes('"')) { + // a chunk that failed to load (after retries) won't load for the + // quote-fixed definition either + if (isModuleLoadError(err) || !mermaidDefinition.includes('"')) { return { success: false, error: originalParseError }; } diff --git a/packages/excalidraw/components/TTDDialog/types.ts b/packages/excalidraw/components/TTDDialog/types.ts index 786ec6031c..9dcbd3a01c 100644 --- a/packages/excalidraw/components/TTDDialog/types.ts +++ b/packages/excalidraw/components/TTDDialog/types.ts @@ -81,9 +81,9 @@ export interface MermaidToExcalidrawLibProps { /** 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 + * set when loading still failed after retrying while online (e.g. stale app + * version after a deploy, or an older browser that caches the failed + * fetch), i.e. only a page reload will likely recover */ reloadRequired?: boolean; api: Promise<{ diff --git a/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx b/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx index 82cc2ae3f3..bf7b9a19a9 100644 --- a/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx +++ b/packages/excalidraw/tests/MermaidToExcalidraw.test.tsx @@ -1,4 +1,4 @@ -import { expect, vi } from "vitest"; +import { expect, onTestFinished, vi } from "vitest"; import * as MermaidToExcalidrawLib from "@excalidraw/mermaid-to-excalidraw"; import { pointFrom } from "@excalidraw/math"; @@ -116,6 +116,8 @@ const normalizeDialogSnapshot = (dialog: Element) => { describe("Test ", () => { beforeEach(async () => { + // the dialog restores the last definition from storage + localStorage.clear(); await render( ", () => { updateTextEditor(editor, "sequenceDiagram"); - await waitFor(() => - expect( - dialog.querySelector('[data-testid="ttd-dialog-output-load-error"]'), - ).not.toBeNull(), + // shown once the retries failed too + await waitFor( + () => + expect( + dialog.querySelector('[data-testid="ttd-dialog-output-load-error"]'), + ).not.toBeNull(), + { timeout: 3000 }, ); expect( dialog.querySelector('[data-testid="ttd-dialog-output-error"]'), ).toBeNull(); }); + + it("should retry a diagram chunk that failed to load", async () => { + const dialog = document.querySelector(".ttd-dialog")!; + const selector = ".ttd-dialog-input"; + const editor = await getTextEditor({ selector, waitForEditor: true }); + await waitFor(() => expect(dialog.querySelector("canvas")).not.toBeNull()); + + const definition = "flowchart TD\n A --> B"; + const parse = vi.mocked(MermaidToExcalidrawLib.parseMermaidToExcalidraw); + const parseImpl = parse.getMockImplementation()!; + let failed = false; + // the diagram's chunk fails to load once (e.g. a network blip) + parse.mockImplementation(async (text, config) => { + if (text === definition && !failed) { + failed = true; + throw new TypeError( + "Failed to fetch dynamically imported module: http://localhost/assets/flowchart.js", + ); + } + return parseImpl(text, config); + }); + onTestFinished(() => { + parse.mockImplementation(parseImpl); + }); + + updateTextEditor(editor, definition); + + await waitFor( + () => + expect( + parse.mock.calls.filter(([text]) => text === definition), + ).toHaveLength(2), + { timeout: 2000 }, + ); + expect( + dialog.querySelector('[data-testid="ttd-dialog-output-load-error"]'), + ).toBeNull(); + expect(dialog.querySelector("canvas")).not.toBeNull(); + }); });