From f244ad584bf991e6f858a71e1d740eeea8def178 Mon Sep 17 00:00:00 2001 From: Mark Tolmacs Date: Mon, 28 Sep 2026 17:39:56 +0000 Subject: [PATCH] fix: Fullscreen support and external error display Signed-off-by: Mark Tolmacs --- excalidraw-app/components/AI.tsx | 58 ++- packages/common/src/utils.ts | 10 - packages/excalidraw/components/App.tsx | 114 +++-- .../DiagramToCodePlugin/DiagramToCodeError.ts | 15 + .../DiagramToCodePlugin.tsx | 20 +- packages/excalidraw/css/styles.scss | 42 +- packages/excalidraw/index.tsx | 7 +- packages/excalidraw/tests/embeddable.test.tsx | 415 ++++++++++++++++-- packages/excalidraw/types.ts | 15 + 9 files changed, 581 insertions(+), 115 deletions(-) create mode 100644 packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodeError.ts diff --git a/excalidraw-app/components/AI.tsx b/excalidraw-app/components/AI.tsx index dcee47f845..3440c74b7f 100644 --- a/excalidraw-app/components/AI.tsx +++ b/excalidraw-app/components/AI.tsx @@ -1,4 +1,5 @@ import { + DiagramToCodeError, DiagramToCodePlugin, exportScene, getNonDeletedElements, @@ -12,12 +13,48 @@ import { import { getDataURL } from "@excalidraw/excalidraw/data/blob"; import { safelyParseJSON } from "@excalidraw/common"; -import type { StreamChunk } from "@excalidraw/excalidraw"; +import type { + RenderDiagramToCodeError, + StreamChunk, +} from "@excalidraw/excalidraw"; import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types"; import { cacheMermaidChunks } from "../data/cacheMermaidChunks"; import { TTDIndexedDBAdapter } from "../data/TTDStorage"; +const ERR_RATE_LIMIT = "ERR_RATE_LIMIT"; + +// rendered by the editor as app UI over the failed `iframe` element (not +// inside its sandboxed frame). Error data comes from the (untrusted) element, +// so we only use the `code` to pick our own content. +const renderDiagramToCodeError: RenderDiagramToCodeError = ({ code }) => { + if (code !== ERR_RATE_LIMIT) { + return null; + } + return ( + <> +
+ Too many requests today, +
+ please try again tomorrow! +
+
+ You can also try{" "} + + Excalidraw+ + {" "} + to get more requests. +
+ + ); +}; + export const AIComponents = ({ excalidrawAPI, }: { @@ -35,6 +72,7 @@ export const AIComponents = ({ return ( <> { const appState = excalidrawAPI.getAppState(); @@ -89,20 +127,10 @@ export const AIComponents = ({ } if (errorJSON.statusCode === 429) { - return { - html: ` - -
-
Too many requests today,
please try again tomorrow!
-
-
-
You can also try Excalidraw+ to get more requests.
-
- - `, - }; + throw new DiagramToCodeError( + "Too many requests today, please try again tomorrow!", + ERR_RATE_LIMIT, + ); } throw new Error(errorJSON.message || text); diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts index b0d108eddf..be2e4b1384 100644 --- a/packages/common/src/utils.ts +++ b/packages/common/src/utils.ts @@ -1163,16 +1163,6 @@ export const escapeDoubleQuotes = (str: string) => { return str.replace(/"/g, """); }; -/** escapes an unsafe string for use as HTML text or (quoted) attribute value */ -export const escapeHTML = (str: string) => { - return str - .replace(/&/g, "&") - .replace(//g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -}; - export const castArray = (value: T | T[]): T[] => Array.isArray(value) ? value : [value]; diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index 7f369a4ad7..8d38f54710 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -8,7 +8,6 @@ import { nanoid } from "nanoid"; import { clamp, pointFrom, pointDistance } from "@excalidraw/math"; import { - COLOR_PALETTE, CODES, shouldResizeFromCenter, shouldMaintainAspectRatio, @@ -50,7 +49,6 @@ import { debounce, distance, getFontString, - escapeHTML, getNearestScrollableContainer, isInputLike, isToolIcon, @@ -417,6 +415,7 @@ import LayerUI from "./LayerUI"; import { ElementCanvasButton } from "./MagicButton"; import { SVGLayer } from "./SVGLayer"; import Spinner from "./Spinner"; +import { DiagramToCodeError } from "./DiagramToCodePlugin/DiagramToCodeError"; import { searchItemInFocusAtom } from "./SearchMenu"; import { isSidebarDockedAtom } from "./Sidebar/Sidebar"; import { hideTooltip } from "./Tooltip"; @@ -468,6 +467,7 @@ import type { ElementsPendingErasure, ExcalidrawImperativeAPIEventMap, GenerateDiagramToCode, + RenderDiagramToCodeError, NullableGridSize, UIConfig, UIControl, @@ -1522,6 +1522,28 @@ class App extends React.Component { return this.iFrameRefs.get(element.id); } + private renderIframeElementGenerationError(error: { + code: string; + message?: string; + }) { + const hostContent = this.plugins.diagramToCode?.renderError?.(error); + + return ( +
+ {hostContent ?? ( + <> +
Error!
+
+ {error.code === "ERR_GENERATION_INTERRUPTED" + ? "Generation was interrupted..." + : error.message || "Generation failed"} +
+ + )} +
+ ); + } + /** * AI-generated iframe elements aren't interactive while their generation * is still in progress (the partial content is render-only). @@ -1861,6 +1883,7 @@ class App extends React.Component { let src: IframeData | null; let isPendingGeneration = false; + let generationError: { code: string; message?: string } | null = null; if (isIframeElement(el)) { src = null; @@ -1943,40 +1966,18 @@ class App extends React.Component { } as const; isPendingGeneration = true; } else { - let message: string; - if (data.code === "ERR_GENERATION_INTERRUPTED") { - message = "Generation was interrupted..."; - } else { - message = data.message || "Generation failed"; - } src = { intrinsicSize: { w: el.width, h: el.height }, type: "document", - srcdoc: () => { - return injectIframeElementCSP( - createSrcDoc(` - -

Error!

-

${escapeHTML(message)}

- `), - ); - }, + srcdoc: () => injectIframeElementCSP(createSrcDoc("")), } as const; + generationError = { + // element data is untrusted (collaborators, share links, + // files) — only ever use it as plain text + code: typeof data.code === "string" ? data.code : "", + message: + typeof data.message === "string" ? data.message : undefined, + }; } } else { src = getEmbedLink(toValidURL(el.link || "")); @@ -2093,6 +2094,7 @@ class App extends React.Component { } // https://stackoverflow.com/q/18470015 scrolling="no" + referrerPolicy="no-referrer-when-downgrade" title="Excalidraw Embedded Content" {...(isIframeElement(el) ? { @@ -2100,13 +2102,11 @@ class App extends React.Component { allow: IFRAME_ELEMENT_PERMISSIONS_POLICY, // content could otherwise spoof browser UI allowFullScreen: false, - referrerPolicy: "no-referrer", } : { allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture", allowFullScreen: true, - referrerPolicy: "no-referrer-when-downgrade", })} sandbox={ isIframeElement(el) @@ -2132,6 +2132,8 @@ class App extends React.Component { Generating… )} + {generationError && + this.renderIframeElementGenerationError(generationError)} ); @@ -2622,7 +2624,7 @@ class App extends React.Component { } /> { @@ -2630,9 +2632,20 @@ class App extends React.Component { this.getHTMLIFrameElement( firstSelectedElement, ); - if (iframe) { - try { - iframe.requestFullscreen(); + if (!iframe) { + return; + } + new Promise((resolve) => + resolve(iframe.requestFullscreen()), + ).then( + () => { + if ( + this.unmounted || + this.ownerDocument + .fullscreenElement !== iframe + ) { + return; + } this.setState({ activeEmbeddable: { element: firstSelectedElement, @@ -2644,14 +2657,17 @@ class App extends React.Component { newElement: null, selectionElement: null, }); - } catch (err: any) { + }, + (err: unknown) => { console.warn(err); - this.setState({ - errorMessage: - "Couldn't enter fullscreen", - }); - } - } + if (!this.unmounted) { + this.setState({ + errorMessage: + "Couldn't enter fullscreen", + }); + } + }, + ); }} /> @@ -2909,11 +2925,17 @@ class App extends React.Component { public plugins: { diagramToCode?: { generate: GenerateDiagramToCode; + renderError?: RenderDiagramToCodeError; }; } = {}; public setPlugins(plugins: Partial) { + const prevRenderError = this.plugins.diagramToCode?.renderError; Object.assign(this.plugins, plugins); + // rerender any (already rendered) generation error overlays + if (this.plugins.diagramToCode?.renderError !== prevRenderError) { + this.triggerRender(); + } } private async onMagicFrameGenerate( @@ -3028,7 +3050,7 @@ class App extends React.Component { frameElement, data: { status: "error", - code: "ERR_OAI", + code: error instanceof DiagramToCodeError ? error.code : "ERR_OAI", message: error.message || "Unknown error during generation", }, }); diff --git a/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodeError.ts b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodeError.ts new file mode 100644 index 0000000000..5993627c88 --- /dev/null +++ b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodeError.ts @@ -0,0 +1,15 @@ +/** + * Throw from `DiagramToCodePlugin.generate` to fail the generation with + * a well-known `code` (e.g. "ERR_RATE_LIMIT"), which the plugin's + * `renderError` can then use to render host-specific UI. Other thrown errors + * are stored with a generic code. + */ +export class DiagramToCodeError extends Error { + code: string; + + constructor(message: string, code: string) { + super(message); + this.name = "DiagramToCodeError"; + this.code = code; + } +} diff --git a/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx index e225ca193f..de3557885c 100644 --- a/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx +++ b/packages/excalidraw/components/DiagramToCodePlugin/DiagramToCodePlugin.tsx @@ -2,18 +2,32 @@ import { useLayoutEffect } from "react"; import { useApp } from "../App"; -import type { GenerateDiagramToCode } from "../../types"; +import type { + GenerateDiagramToCode, + RenderDiagramToCodeError, +} from "../../types"; + +export { DiagramToCodeError } from "./DiagramToCodeError"; export const DiagramToCodePlugin = (props: { generate: GenerateDiagramToCode; + /** + * Optionally render the error shown over a failed generation, e.g. for + * a host-specific error code. Rendered as app UI (not inside the + * sandboxed frame). Keep the reference stable to avoid rerenders. + */ + renderError?: RenderDiagramToCodeError; }) => { const app = useApp(); useLayoutEffect(() => { app.setPlugins({ - diagramToCode: { generate: props.generate }, + diagramToCode: { + generate: props.generate, + renderError: props.renderError, + }, }); - }, [app, props.generate]); + }, [app, props.generate, props.renderError]); return null; }; diff --git a/packages/excalidraw/css/styles.scss b/packages/excalidraw/css/styles.scss index 7a7c4b8d1d..5b4e81fa8f 100644 --- a/packages/excalidraw/css/styles.scss +++ b/packages/excalidraw/css/styles.scss @@ -1059,6 +1059,45 @@ body.excalidraw-cursor-resize * { } } + // failed generation of an `iframe` element — rendered as app UI over the + // (empty) frame. Inherits the container's pointer-events so that it's + // interactive (e.g. host-supplied links) only while the element is active. + .excalidraw__embeddable__error { + position: absolute; + z-index: 1; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.5rem; + padding: 1rem 2rem; + box-sizing: border-box; + overflow: auto; + border-radius: var(--embeddable-radius); + background: var(--island-bg-color); + color: var(--text-primary-color); + font-family: "Assistant"; + font-size: 1rem; + text-align: center; + overflow-wrap: anywhere; + + &__title { + color: var(--color-danger); + font-size: 1.5rem; + font-weight: 700; + } + + &__message { + color: var(--color-danger); + white-space: pre-wrap; + } + + a { + color: var(--link-color); + } + } + .excalidraw__embeddable__outer { width: 100%; height: 100%; @@ -1077,7 +1116,8 @@ body.excalidraw-cursor-resize * { .excalidraw__embeddable-hint { position: absolute; - z-index: 1; + // above the error overlay + z-index: 2; background: rgba(0, 0, 0, 0.5); padding: 1rem 1.6rem; border-radius: 12px; diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsx index 44df155558..eb8cf4ef5d 100644 --- a/packages/excalidraw/index.tsx +++ b/packages/excalidraw/index.tsx @@ -513,6 +513,8 @@ export type { ViewportStatusFrame, ElementRenderOverride, ElementRenderOverrides, + GenerateDiagramToCode, + RenderDiagramToCodeError, } from "./types"; export { zoomToFitBounds, DEFAULT_OVERSCROLL } from "./viewport"; @@ -525,7 +527,10 @@ export { export { elementsOverlappingBBox } from "@excalidraw/element"; -export { DiagramToCodePlugin } from "./components/DiagramToCodePlugin/DiagramToCodePlugin"; +export { + DiagramToCodePlugin, + DiagramToCodeError, +} from "./components/DiagramToCodePlugin/DiagramToCodePlugin"; export { getDataURL } from "./data/blob"; export { isElementLink } from "@excalidraw/element"; diff --git a/packages/excalidraw/tests/embeddable.test.tsx b/packages/excalidraw/tests/embeddable.test.tsx index e3c04e9a82..170ece4006 100644 --- a/packages/excalidraw/tests/embeddable.test.tsx +++ b/packages/excalidraw/tests/embeddable.test.tsx @@ -7,11 +7,14 @@ import { injectIframeElementCSP, } from "@excalidraw/element"; -import { Excalidraw } from "../index"; +import { DiagramToCodeError, DiagramToCodePlugin, Excalidraw } from "../index"; +import { t } from "../i18n"; import { API } from "./helpers/api"; import { Pointer } from "./helpers/ui"; import { + act, + fireEvent, mockBoundingClientRect, render, restoreOriginalGetBoundingClientRect, @@ -141,7 +144,6 @@ describe("embeddable & iframe sandbox", () => { expect(allow).toContain("fullscreen 'none'"); expect(allow).toContain("autoplay 'none'"); expect(iframe.hasAttribute("allowfullscreen")).toBe(false); - expect(iframe.getAttribute("referrerpolicy")).toBe("no-referrer"); const tokens = getSandboxTokens(iframe); expect(tokens).toContain("allow-scripts"); @@ -189,53 +191,388 @@ describe("embeddable & iframe sandbox", () => { expect(tokens).toContain("allow-popups-to-escape-sandbox"); }); - describe("iframe element srcdoc", () => { - const createIframeElement = (generationData: any) => ({ - ...API.createElement({ - type: "iframe", - x: 10, - y: 10, - width: 300, - height: 200, - }), - customData: { generationData }, + describe("iframe element fullscreen button", () => { + const h = window.h; + const originalFullscreenElement = Object.getOwnPropertyDescriptor( + document, + "fullscreenElement", + ); + let fullscreenElement: Element | null = null; + + beforeEach(() => { + fullscreenElement = null; + Object.defineProperty(document, "fullscreenElement", { + configurable: true, + get: () => fullscreenElement, + }); }); - const getIframe = (container: HTMLElement) => - container.querySelector( - "iframe.excalidraw__embeddable", + afterEach(() => { + if (originalFullscreenElement) { + Object.defineProperty( + document, + "fullscreenElement", + originalFullscreenElement, + ); + } else { + delete (document as any).fullscreenElement; + } + vi.restoreAllMocks(); + }); + + const renderSelectedDoneIframe = async () => { + const iframeElement = { + ...API.createElement({ + type: "iframe", + x: 10, + y: 10, + width: 300, + height: 200, + }), + customData: { + generationData: { status: "done", html: "

hi

" }, + }, + }; + + const { container } = await render( + , ); - const waitForIframe = (container: HTMLElement) => - waitFor(() => { - const iframe = getIframe(container); + const iframe = await waitFor(() => { + const iframe = container.querySelector( + "iframe.excalidraw__embeddable", + ); expect(iframe).not.toBeNull(); return iframe!; }); - it("escapes the error message", async () => { - const payload = ``; - const { container } = await render( - , - ); + API.setAppState({ selectedElementIds: { [iframeElement.id]: true } }); - const srcdoc = (await waitForIframe(container)).getAttribute("srcdoc")!; - expect(srcdoc).not.toContain(payload); - expect(srcdoc).not.toContain("`, + const button = await waitFor(() => { + const button = container.querySelector( + `.excalidraw-canvas-buttons button[aria-label="${t( + "buttons.fullScreen", + )}"]`, + ); + expect(button).not.toBeNull(); + return button!; + }); + + return { iframe, button, element: h.elements[0] }; + }; + + it("is shown for a selected done iframe element and fullscreens its