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).
This commit is contained in:
David Luzar authored and GitHub committed 2026-12-05 15:26:21 +01:00
1 parent 4372494df0
commit 597a2c8fcb
4 files changed
+91 -14

No files matched your search

@@ -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 <T,>(load: () => Promise<T>): Promise<T> => {
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;
@@ -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 };
}
@@ -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<{
@@ -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 <MermaidToExcalidraw/>", () => {
beforeEach(async () => {
// the dialog restores the last definition from storage
localStorage.clear();
await render(
<Excalidraw
initialData={{
@@ -171,13 +173,55 @@ describe("Test <MermaidToExcalidraw/>", () => {
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();
});
});