Virtual whiteboard for sketching hand-drawn like diagrams
feat(packages/excalidraw): support rendering into another document (#11974)
zsvicziane1bb9ff8f893
diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000000..29096e3674--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,3 @@+# Guidelines++- For new DOM/browser API usage, use `app.ownerDocument` and `app.ownerWindow` instead of globals; without `app`, derive them from the mounted node's `ownerDocument` and its `defaultView`.diff --git a/packages/common/src/utils.test.ts b/packages/common/src/utils.test.tsindex 677aaf2245..2f148cb66f 100644--- a/packages/common/src/utils.test.ts+++ b/packages/common/src/utils.test.ts@@ -1,5 +1,10 @@import {+ getNearestScrollableContainer,+ isInputLike,+ isInteractive,+ isToolIcon,isTransparent,+ isWritableElement,mapFind,reduceToCommonValue,} from "@excalidraw/common";@@ -11,6 +16,34 @@ import { throttleRAF } from "./utils";type RafCallback = FrameRequestCallback;describe("@excalidraw/common/utils", () => {+ describe("cross-document element guards", () => {+ it("uses constructors from the target element's window", () => {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);++ const iframeDocument = iframe.contentDocument!;+ const iframeWindow = iframe.contentWindow!;+ const textarea = iframeDocument.createElement("textarea");+ const button = iframeDocument.createElement("button");+ const toolIcon = iframeDocument.createElement("div");+ toolIcon.className = "ToolIcon__icon";++ expect(textarea).not.toBeInstanceOf(HTMLTextAreaElement);+ expect(textarea).toBeInstanceOf(+ (iframeWindow as Window & typeof globalThis).HTMLTextAreaElement,+ );+ expect(isInputLike(textarea)).toBe(true);+ expect(isWritableElement(textarea)).toBe(true);+ expect(isInteractive(button)).toBe(true);+ expect(isToolIcon(toolIcon)).toBe(true);++ iframeDocument.body.append(textarea);+ expect(getNearestScrollableContainer(textarea)).toBe(iframeDocument);++ iframe.remove();+ });+ });+describe("isTransparent()", () => {it("should return true when color is rgb transparent", () => {expect(isTransparent("#ff00")).toEqual(true);diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.tsindex 550bcdb208..bd015a99a4 100644--- a/packages/common/src/utils.ts+++ b/packages/common/src/utils.ts@@ -48,10 +48,23 @@ export const getDateTime = () => {export const capitalizeString = (str: string) =>str.charAt(0).toUpperCase() + str.slice(1);+const getTargetWindow = (+ target: Element | EventTarget | null,+): (Window & typeof globalThis) | null =>+ (target as (EventTarget & { ownerDocument?: Document | null }) | null)+ ?.ownerDocument?.defaultView ??+ (typeof window === "undefined" ? null : window);+export const isToolIcon = (target: Element | EventTarget | null,-): target is HTMLElement =>- target instanceof HTMLElement && target.className.includes("ToolIcon");+): target is HTMLElement => {+ const targetWindow = getTargetWindow(target);+ return (+ !!targetWindow &&+ target instanceof targetWindow.HTMLElement &&+ target.className.includes("ToolIcon")+ );+};export const isInputLike = (target: Element | EventTarget | null,@@ -60,17 +73,26 @@ export const isInputLike = (| HTMLTextAreaElement| HTMLSelectElement| HTMLBRElement- | HTMLDivElement =>- (target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||- target instanceof HTMLBRElement || // newline in wysiwyg- target instanceof HTMLInputElement ||- target instanceof HTMLTextAreaElement ||- target instanceof HTMLSelectElement;+ | HTMLDivElement => {+ const targetWindow = getTargetWindow(target);+ return (+ !!targetWindow &&+ ((target instanceof targetWindow.HTMLElement &&+ target.dataset.type === "wysiwyg") ||+ target instanceof targetWindow.HTMLBRElement || // newline in wysiwyg+ target instanceof targetWindow.HTMLInputElement ||+ target instanceof targetWindow.HTMLTextAreaElement ||+ target instanceof targetWindow.HTMLSelectElement)+ );+};export const isInteractive = (target: Element | EventTarget | null) => {+ const targetWindow = getTargetWindow(target);return (isInputLike(target) ||- (target instanceof Element && !!target.closest("label, button"))+ (!!targetWindow &&+ target instanceof targetWindow.Element &&+ !!target.closest("label, button")));};@@ -80,16 +102,23 @@ export const isWritableElement = (| HTMLInputElement| HTMLTextAreaElement| HTMLBRElement- | HTMLDivElement =>- (target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||- target instanceof HTMLBRElement || // newline in wysiwyg- target instanceof HTMLTextAreaElement ||- (target instanceof HTMLInputElement &&- (target.type === "text" ||- target.type === "number" ||- target.type === "password" ||- target.type === "search")) ||- (target instanceof HTMLElement && target.closest(".cm-editor") !== null);+ | HTMLDivElement => {+ const targetWindow = getTargetWindow(target);+ return (+ !!targetWindow &&+ ((target instanceof targetWindow.HTMLElement &&+ target.dataset.type === "wysiwyg") ||+ target instanceof targetWindow.HTMLBRElement || // newline in wysiwyg+ target instanceof targetWindow.HTMLTextAreaElement ||+ (target instanceof targetWindow.HTMLInputElement &&+ (target.type === "text" ||+ target.type === "number" ||+ target.type === "password" ||+ target.type === "search")) ||+ (target instanceof targetWindow.HTMLElement &&+ target.closest(".cm-editor") !== null))+ );+};export const getFontFamilyString = ({fontFamily,@@ -475,12 +504,14 @@ export const supportsEmoji = () => {export const getNearestScrollableContainer = (element: HTMLElement,): HTMLElement | Document => {+ const ownerDocument = element.ownerDocument;+ const ownerWindow = ownerDocument.defaultView ?? window;let parent = element.parentElement;while (parent) {- if (parent === document.body) {- return document;+ if (parent === ownerDocument.body) {+ return ownerDocument;}- const { overflowY } = window.getComputedStyle(parent);+ const { overflowY } = ownerWindow.getComputedStyle(parent);const hasScrollableContent = parent.scrollHeight > parent.clientHeight;if (hasScrollableContent &&@@ -492,7 +523,7 @@ export const getNearestScrollableContainer = (}parent = parent.parentElement;}- return document;+ return ownerDocument;};export const focusNearestParent = (element: HTMLInputElement) => {diff --git a/packages/excalidraw/actions/actionFinalize.tsx b/packages/excalidraw/actions/actionFinalize.tsxindex 0b080f7f4b..a0ee6aa82e 100644--- a/packages/excalidraw/actions/actionFinalize.tsx+++ b/packages/excalidraw/actions/actionFinalize.tsx@@ -202,9 +202,7 @@ export const actionFinalize = register<FormData>({}}- if (window.document.activeElement instanceof HTMLElement) {- focusContainer();- }+ focusContainer();// clean up pending gesture even if active tool is already not drawShapeconst hadPendingSketch = app.drawShape.hasPendingGesture();diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsxindex 6cfa77290a..5b04fc2b68 100644--- a/packages/excalidraw/actions/actionProperties.tsx+++ b/packages/excalidraw/actions/actionProperties.tsx@@ -1251,8 +1251,9 @@ export const actionChangeFontFamily = register<{fontFamily: nextFontFamily,})}`;const chars = Array.from(uniqueChars.values()).join();+ const ownerDocument = app.props.ownerDocument ?? document;- if (skipFontFaceCheck || window.document.fonts.check(fontString, chars)) {+ if (skipFontFaceCheck || ownerDocument.fonts.check(fontString, chars)) {// we either skip the check (have at least one font face loaded) or do the check and find out all the font faces have loadedfor (const [element, container] of elementContainerMapping) {// trigger synchronous redraw@@ -1260,7 +1261,7 @@ export const actionChangeFontFamily = register<{}} else {// otherwise try to load all font faces for the given chars and redraw elements once our font faces loaded- window.document.fonts.load(fontString, chars).then((fontFaces) => {+ ownerDocument.fonts.load(fontString, chars).then((fontFaces) => {for (const [element, container] of elementContainerMapping) {// use latest element state to ensure we don't have closure over an old instance in order to avoid possible race conditions (i.e. font faces load out-of-order while rapidly switching fonts)const latestElement = app.scene.getElement(element.id);@@ -1460,7 +1461,7 @@ export const actionChangeFontFamily = register<{// Refocus text editor when font picker closes if we were editing textif (isCompact && appState.editingTextElement) {- restoreCaretPosition(null); // Just refocus without saved position+ restoreCaretPosition(null, app.ownerDocument); // Just refocus without saved position}}}}diff --git a/packages/excalidraw/components/Actions.tsx b/packages/excalidraw/components/Actions.tsxindex ec5133a38a..b8a314d038 100644--- a/packages/excalidraw/components/Actions.tsx+++ b/packages/excalidraw/components/Actions.tsx@@ -420,7 +420,9 @@ const CombinedTextProperties = ({predicates: ShapeActionPredicates;container: HTMLDivElement | null;}) => {- const { saveCaretPosition, restoreCaretPosition } = useTextEditorFocus();+ const { saveCaretPosition, restoreCaretPosition } = useTextEditorFocus(+ container?.ownerDocument,+ );const isOpen = appState.openPopup === "compactTextProperties";return (diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex 291e4878ce..b6b1eb0a4f 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -54,7 +54,6 @@ import {MIN_ZOOM,POINTER_EVENTS,TOOL_TYPE,- supportsResizeObserver,DEFAULT_COLLISION_THRESHOLD,DEFAULT_TEXT_ALIGN,ARROW_TYPE,@@ -631,6 +630,19 @@ class App extends React.Component<AppProps, AppState> {private excalidrawContainerRef = React.createRef<HTMLDivElement>();+ public get ownerDocument(): Document {+ return (+ this.props.ownerDocument ??+ this.excalidrawContainerRef.current?.ownerDocument ??+ document+ );+ }++ public get ownerWindow(): Window & typeof globalThis {+ return (this.ownerDocument.defaultView ?? window) as Window &+ typeof globalThis;+ }+public scene: Scene;public fonts: Fonts;public renderer: Renderer;@@ -842,8 +854,8 @@ class App extends React.Component<AppProps, AppState> {objectsSnapModeEnabled,gridModeEnabled: gridModeEnabled ?? defaultAppState.gridModeEnabled,name,- width: window.innerWidth,- height: window.innerHeight,+ width: this.ownerWindow.innerWidth,+ height: this.ownerWindow.innerHeight,};this.refreshEditorInterface();@@ -859,7 +871,7 @@ class App extends React.Component<AppProps, AppState> {);this.scene = new Scene();- this.canvas = document.createElement("canvas");+ this.canvas = this.ownerDocument.createElement("canvas");this.rc = rough.canvas(this.canvas);this.renderer = new Renderer(this.scene);this.visibleElements = [];@@ -872,7 +884,7 @@ class App extends React.Component<AppProps, AppState> {id: this.id,};- this.fonts = new Fonts(this.scene);+ this.fonts = new Fonts(this.scene, this.ownerDocument);this.history = new History(this.store);this.actionManager.registerAll(actions);@@ -1061,7 +1073,7 @@ class App extends React.Component<AppProps, AppState> {return result;};- private onWindowMessage(event: MessageEvent) {+ private onWindowMessage = (event: MessageEvent) => {if (event.origin !== "https://player.vimeo.com" &&event.origin !== "https://www.youtube.com"@@ -1082,7 +1094,7 @@ class App extends React.Component<AppProps, AppState> {//Allowing for multiple instances of Excalidraw running in the windowif (data.method === "paused") {let source: Window | null = null;- const iframes = document.body.querySelectorAll(+ const iframes = this.ownerDocument.body.querySelectorAll("iframe.excalidraw__embeddable",);if (!iframes) {@@ -1122,7 +1134,7 @@ class App extends React.Component<AppProps, AppState> {}break;}- }+ };private handleSkipBindMode() {if (@@ -2061,7 +2073,7 @@ class App extends React.Component<AppProps, AppState> {bounds.zoom !== this.state.zoom.value ||bounds.versionNonce !== frameElement.versionNonce) {- const frameNameDiv = document.getElementById(+ const frameNameDiv = this.ownerDocument.getElementById(this.getFrameNameDOMId(frameElement),);@@ -2132,8 +2144,8 @@ class App extends React.Component<AppProps, AppState> {if (!isElementInViewport(f,- this.canvas.width / window.devicePixelRatio,- this.canvas.height / window.devicePixelRatio,+ this.canvas.width / this.ownerWindow.devicePixelRatio,+ this.canvas.height / this.ownerWindow.devicePixelRatio,{offsetLeft: this.state.offsetLeft,offsetTop: this.state.offsetTop,@@ -2203,7 +2215,9 @@ class App extends React.Component<AppProps, AppState> {: FRAME_STYLE.nameColorLightTheme,overflow: "hidden",maxWidth: `${- document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING+ this.ownerDocument.body.clientWidth -+ x1 -+ FRAME_NAME_EDIT_PADDING}px`,}}size={frameNameInEdit.length + 1 || 1}@@ -2270,12 +2284,12 @@ class App extends React.Component<AppProps, AppState> {});};- private toggleOverscrollBehavior(event: React.PointerEvent) {+ private toggleOverscrollBehavior = (event: React.PointerEvent) => {// when pointer inside editor, disable overscroll behavior to prevent// panning to trigger history back/forward on MacOS Chrome- document.documentElement.style.overscrollBehaviorX =+ this.ownerDocument.documentElement.style.overscrollBehaviorX =event.type === "pointerenter" ? "none" : "auto";- }+ };public render() {const selectedElements = this.scene.getSelectedElements(this.state);@@ -2313,7 +2327,7 @@ class App extends React.Component<AppProps, AppState> {const shouldBlockPointerEvents =// default back to `--ui-pointerEvents` flow if setPointerCapture// not supported- "setPointerCapture" in HTMLElement.prototype+ "setPointerCapture" in this.ownerWindow.HTMLElement.prototype? false: this.state.selectionElement ||this.state.newElement ||@@ -2572,7 +2586,7 @@ class App extends React.Component<AppProps, AppState> {selectionNonce={this.state.selectionElement?.versionNonce}- scale={window.devicePixelRatio}+ scale={this.ownerWindow.devicePixelRatio}appState={this.state}renderConfig={{imageCache: this.imageCache,@@ -2594,7 +2608,7 @@ class App extends React.Component<AppProps, AppState> {<NewElementCanvasappState={this.state}newElement={newElementCanvasElement}- scale={window.devicePixelRatio}+ scale={this.ownerWindow.devicePixelRatio}rc={this.rc}elementsMap={renderableElementsMap}allElementsMap={allElementsMap}@@ -2625,7 +2639,7 @@ class App extends React.Component<AppProps, AppState> {selectionNonce={this.state.selectionElement?.versionNonce}- scale={window.devicePixelRatio}+ scale={this.ownerWindow.devicePixelRatio}appState={this.state}renderScrollbars={this.props.renderScrollbars === true@@ -3465,8 +3479,11 @@ class App extends React.Component<AppProps, AppState> {);private initializeScene = async () => {- if ("launchQueue" in window && "LaunchParams" in window) {- (window as any).launchQueue.setConsumer(+ if (+ "launchQueue" in this.ownerWindow &&+ "LaunchParams" in this.ownerWindow+ ) {+ (this.ownerWindow as any).launchQueue.setConsumer(async (launchParams: { files: any[] }) => {if (!launchParams.files.length) {return;@@ -3604,9 +3621,9 @@ class App extends React.Component<AppProps, AppState> {this.fonts.onLoaded(fontFaces);});- if (isElementLink(window.location.href)) {+ if (isElementLink(this.ownerWindow.location.href)) {this.viewport.setViewport({- target: window.location.href,+ target: this.ownerWindow.location.href,fit: "scale-down",animation: false,});@@ -3751,15 +3768,20 @@ class App extends React.Component<AppProps, AppState> {this.focusContainer();}- if (supportsResizeObserver && this.excalidrawContainerRef.current) {- this.resizeObserver = new ResizeObserver(() => {+ if (+ typeof this.ownerWindow.ResizeObserver === "function" &&+ this.excalidrawContainerRef.current+ ) {+ this.resizeObserver = new this.ownerWindow.ResizeObserver(() => {this.refreshEditorInterface();this.updateDOMRect();});this.resizeObserver?.observe(this.excalidrawContainerRef.current);}- const searchParams = new URLSearchParams(window.location.search.slice(1));+ const searchParams = new URLSearchParams(+ this.ownerWindow.location.search.slice(1),+ );if (searchParams.has("web-share-target")) {// Obtain a file that was shared via the Web Share Target API.@@ -3809,12 +3831,12 @@ class App extends React.Component<AppProps, AppState> {this.props.onUnmount?.();this.props.onExcalidrawAPI?.(null);- (window as any).launchQueue?.setConsumer(() => {});+ (this.ownerWindow as any).launchQueue?.setConsumer(() => {});this.renderer.destroy();this.scene.destroy();this.scene = new Scene();- this.fonts = new Fonts(this.scene);+ this.fonts = new Fonts(this.scene, this.ownerDocument);this.renderer = new Renderer(this.scene);this.files = {};this.imageCache.clear();@@ -3837,7 +3859,7 @@ class App extends React.Component<AppProps, AppState> {isSomeElementSelected.clearCache();selectGroupsForSelectedElements.clearCache();touchTimeout = 0;- document.documentElement.style.overscrollBehaviorX = "";+ this.ownerDocument.documentElement.style.overscrollBehaviorX = "";}private onResize = withBatchedUpdates(() => {@@ -3853,7 +3875,7 @@ class App extends React.Component<AppProps, AppState> {private onFullscreenChange = () => {if (// points to the iframe element we fullscreened- !document.fullscreenElement &&+ !this.ownerDocument.fullscreenElement &&this.state.activeEmbeddable?.state === "active") {this.setState({@@ -3875,13 +3897,23 @@ class App extends React.Component<AppProps, AppState> {// -------------------------------------------------------------------------this.onRemoveEventListenersEmitter.once(- addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),- addEventListener(document, EVENT.POINTER_UP, this.removePointer, {- passive: false,- }), // #3553+ addEventListener(+ this.ownerWindow,+ EVENT.MESSAGE,+ this.onWindowMessage,+ false,+ ),+ addEventListener(+ this.ownerDocument,+ EVENT.POINTER_UP,+ this.removePointer,+ {+ passive: false,+ },+ ), // #3553// rerender text elements on font load to fix #637 && #1553addEventListener(- document.fonts,+ this.ownerDocument.fonts,"loadingdone",(event) => {const fontFaces = (event as FontFaceSetLoadEvent).fontfaces;@@ -3890,7 +3922,7 @@ class App extends React.Component<AppProps, AppState> {{ passive: false },),addEventListener(- window,+ this.ownerWindow,EVENT.FOCUS,() => {this.maybeCleanupAfterMissingPointerUp(null);@@ -3919,7 +3951,7 @@ class App extends React.Component<AppProps, AppState> {// navigation action shortcuts (canvas zoom & zoom-to-fit)addEventListener(this.props.handleKeyboardGlobally- ? document+ ? this.ownerDocument: this.excalidrawContainerRef.current,EVENT.KEYDOWN,this.handleNavigationModeKeyDown as EventListener,@@ -3927,26 +3959,26 @@ class App extends React.Component<AppProps, AppState> {),// wheel zoom is anchored on `viewport.lastPosition`addEventListener(- document,+ this.ownerDocument,EVENT.POINTER_MOVE,this.updateCurrentCursorPosition,{ passive: false },),// Safari-only desktop pinchaddEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_START,this.onGestureStart as any,false,),addEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_CHANGE,this.onGestureChange as any,false,),addEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_END,this.onGestureEnd as any,false,@@ -3991,7 +4023,7 @@ class App extends React.Component<AppProps, AppState> {this.onRemoveEventListenersEmitter.once(addEventListener(this.props.handleKeyboardGlobally- ? document+ ? this.ownerDocument: this.excalidrawContainerRef.current,EVENT.KEYDOWN,this.preventBrowserZoomKeyDown as EventListener,@@ -4008,7 +4040,12 @@ class App extends React.Component<AppProps, AppState> {if (this.props.handleKeyboardGlobally) {this.onRemoveEventListenersEmitter.once(- addEventListener(document, EVENT.KEYDOWN, this.onKeyDown, false),+ addEventListener(+ this.ownerDocument,+ EVENT.KEYDOWN,+ this.onKeyDown,+ false,+ ),);}@@ -4019,29 +4056,33 @@ class App extends React.Component<AppProps, AppState> {this.handleWheel,{ passive: false },),- addEventListener(document, EVENT.COPY, this.onCopy, { passive: false }),- addEventListener(document, EVENT.KEYUP, this.onKeyUp, { passive: true }),+ addEventListener(this.ownerDocument, EVENT.COPY, this.onCopy, {+ passive: false,+ }),+ addEventListener(this.ownerDocument, EVENT.KEYUP, this.onKeyUp, {+ passive: true,+ }),addEventListener(- document,+ this.ownerDocument,EVENT.POINTER_MOVE,this.updateCurrentCursorPosition,{ passive: false },),// Safari-only desktop pinch zoomaddEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_START,this.onGestureStart as any,false,),addEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_CHANGE,this.onGestureChange as any,false,),addEventListener(- document,+ this.ownerDocument,EVENT.GESTURE_END,this.onGestureEnd as any,false,@@ -4058,18 +4099,25 @@ class App extends React.Component<AppProps, AppState> {this.onRemoveEventListenersEmitter.once(addEventListener(- document,+ this.ownerDocument,EVENT.FULLSCREENCHANGE,this.onFullscreenChange,{ passive: false },),- addEventListener(document, EVENT.PASTE, this.pasteFromClipboard, {+ addEventListener(+ this.ownerDocument,+ EVENT.PASTE,+ this.pasteFromClipboard,+ {+ passive: false,+ },+ ),+ addEventListener(this.ownerDocument, EVENT.CUT, this.onCut, {passive: false,}),- addEventListener(document, EVENT.CUT, this.onCut, { passive: false }),- addEventListener(window, EVENT.RESIZE, this.onResize, false),- addEventListener(window, EVENT.UNLOAD, this.onUnload, false),- addEventListener(window, EVENT.BLUR, this.onBlur, false),+ addEventListener(this.ownerWindow, EVENT.RESIZE, this.onResize, false),+ addEventListener(this.ownerWindow, EVENT.UNLOAD, this.onUnload, false),+ addEventListener(this.ownerWindow, EVENT.BLUR, this.onBlur, false),addEventListener(this.excalidrawContainerRef.current,EVENT.WHEEL,@@ -4317,7 +4365,7 @@ class App extends React.Component<AppProps, AppState> {return;}const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(- document.activeElement,+ this.ownerDocument.activeElement,);if (!isExcalidrawActive || isWritableElement(event.target)) {return;@@ -4332,7 +4380,7 @@ class App extends React.Component<AppProps, AppState> {return;}const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(- document.activeElement,+ this.ownerDocument.activeElement,);if (!isExcalidrawActive || isWritableElement(event.target)) {return;@@ -4367,7 +4415,7 @@ class App extends React.Component<AppProps, AppState> {};}clearTimeout(tappedTwiceTimer);- tappedTwiceTimer = window.setTimeout(+ tappedTwiceTimer = this.ownerWindow.setTimeout(App.resetTapTwice,TAP_TWICE_TIMEOUT,);@@ -4607,20 +4655,20 @@ class App extends React.Component<AppProps, AppState> {const isPlainPaste = !!IS_PLAIN_PASTE;// #686- const target = document.activeElement;+ const target = this.ownerDocument.activeElement;const isExcalidrawActive =this.excalidrawContainerRef.current?.contains(target);if (event && !isExcalidrawActive) {return;}- const elementUnderCursor = document.elementFromPoint(+ const elementUnderCursor = this.ownerDocument.elementFromPoint(this.viewport.lastPosition.x,this.viewport.lastPosition.y,);if (event &&- (!(elementUnderCursor instanceof HTMLCanvasElement) ||+ (!(elementUnderCursor instanceof this.ownerWindow.HTMLCanvasElement) ||isWritableElement(target))) {return;@@ -4749,9 +4797,11 @@ class App extends React.Component<AppProps, AppState> {// paste event may not fire FontFace loadingdone event in Safari, hence loading font faces manuallyif (isSafari) {- Fonts.loadElementsFonts(duplicatedElements).then((fontFaces) => {- this.fonts.onLoaded(fontFaces);- });+ Fonts.loadElementsFonts(duplicatedElements, this.ownerDocument).then(+ (fontFaces) => {+ this.fonts.onLoaded(fontFaces);+ },+ );}if (opts.files) {@@ -5079,8 +5129,8 @@ class App extends React.Component<AppProps, AppState> {!elements.length ||isElementCompletelyInViewport(elements,- this.canvas.width / window.devicePixelRatio,- this.canvas.height / window.devicePixelRatio,+ this.canvas.width / this.ownerWindow.devicePixelRatio,+ this.canvas.height / this.ownerWindow.devicePixelRatio,{offsetLeft: this.state.offsetLeft,offsetTop: this.state.offsetTop,@@ -5136,7 +5186,11 @@ class App extends React.Component<AppProps, AppState> {const file = new File([blob], blob.name || "", { type: blob.type });this.loadFileToCanvas(file, null);await webShareTargetCache.delete("shared-file");- window.history.replaceState(null, APP_NAME, window.location.pathname);+ this.ownerWindow.history.replaceState(+ null,+ APP_NAME,+ this.ownerWindow.location.pathname,+ );}} catch (error: any) {this.setState({ errorMessage: error.message });@@ -5343,7 +5397,7 @@ class App extends React.Component<AppProps, AppState> {// normalize `event.key` when CapsLock is pressed #2372if (- "Proxy" in window &&+ "Proxy" in this.ownerWindow &&((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||(event.shiftKey && /^[a-z]$/.test(event.key)))) {@@ -5393,8 +5447,9 @@ class App extends React.Component<AppProps, AppState> {this.updateEditorAtom(convertElementTypePopupAtom, null);} else if (event.key === KEYS.TAB &&- (document.activeElement === this.excalidrawContainerRef?.current ||- document.activeElement?.classList.contains(+ (this.ownerDocument.activeElement ===+ this.excalidrawContainerRef?.current ||+ this.ownerDocument.activeElement?.classList.contains(CLASSES.CONVERT_ELEMENT_TYPE_POPUP,))) {@@ -5448,7 +5503,7 @@ class App extends React.Component<AppProps, AppState> {// reset (100ms to be safe that we it runs after the ensuing// paste event). Though, technically unnecessary to reset since we// (re)set the flag before each paste event.- IS_PLAIN_PASTE_TIMER = window.setTimeout(() => {+ IS_PLAIN_PASTE_TIMER = this.ownerWindow.setTimeout(() => {IS_PLAIN_PASTE = false;}, 100);}@@ -6027,7 +6082,7 @@ class App extends React.Component<AppProps, AppState> {} else if (!isHoldingSpace) {this.cursor.applyForTool(nextActiveTool);}- if (isToolIcon(document.activeElement)) {+ if (isToolIcon(this.ownerDocument.activeElement)) {this.focusContainer();}if (!isLinearElementType(nextActiveTool.type)) {@@ -7303,7 +7358,7 @@ class App extends React.Component<AppProps, AppState> {}if (!customEvent?.defaultPrevented) {const target = isLocalLink(url) ? "_self" : "_blank";- const newWindow = window.open(undefined, target);+ const newWindow = this.ownerWindow.open(undefined, target);// https://mathiasbynens.github.io/rel-noopener/if (newWindow) {newWindow.opener = null;@@ -8453,7 +8508,7 @@ class App extends React.Component<AppProps, AppState> {// remove any active selection when we start to interact with canvas// (mainly, we care about removing selection outside the component which// would prevent our copy handling otherwise)- const selection = document.getSelection();+ const selection = this.ownerDocument.getSelection();if (selection?.anchorNode) {selection.removeAllRanges();}@@ -8533,7 +8588,7 @@ class App extends React.Component<AppProps, AppState> {};const unsubPointerUp = addEventListener(- window,+ this.ownerWindow,EVENT.POINTER_UP,onPointerUp,{@@ -8544,7 +8599,7 @@ class App extends React.Component<AppProps, AppState> {// subscribe inside rAF lest it'd be triggered on the same pointerdown// if we start erasing while coming from blurred document since// we cleanup pointer events on focus- requestAnimationFrame(() => {+ this.ownerWindow.requestAnimationFrame(() => {unsubCleanup =this.missingPointerEventCleanupEmitter.once(onPointerUp);});@@ -8810,10 +8865,10 @@ class App extends React.Component<AppProps, AppState> {);if (!this.state.viewModeEnabled || this.isActiveToolPointerCapturing()) {- window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);- window.addEventListener(EVENT.POINTER_UP, onPointerUp);- window.addEventListener(EVENT.KEYDOWN, onKeyDown);- window.addEventListener(EVENT.KEYUP, onKeyUp);+ this.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove);+ this.ownerWindow.addEventListener(EVENT.POINTER_UP, onPointerUp);+ this.ownerWindow.addEventListener(EVENT.KEYDOWN, onKeyDown);+ this.ownerWindow.addEventListener(EVENT.KEYUP, onKeyUp);pointerDownState.eventListeners.onMove = onPointerMove;pointerDownState.eventListeners.onUp = onPointerUp;pointerDownState.eventListeners.onKeyUp = onKeyUp;@@ -8888,7 +8943,7 @@ class App extends React.Component<AppProps, AppState> {} else {// open the context menu with the first touch's clientX and clientY// if the touch is not moving- touchTimeout = window.setTimeout(() => {+ touchTimeout = this.ownerWindow.setTimeout(() => {touchTimeout = 0;if (!invalidateContextMenu) {this.handleCanvasContextMenu(event);@@ -8949,10 +9004,7 @@ class App extends React.Component<AppProps, AppState> {}let nextPastePrevented = false;- const isLinux =- typeof window === undefined- ? false- : /Linux/.test(window.navigator.platform);+ const isLinux = /Linux/.test(this.ownerWindow.navigator.platform);this.cursor.set(CURSOR_TYPE.GRABBING);let { clientX: lastX, clientY: lastY } = event;@@ -8975,7 +9027,10 @@ class App extends React.Component<AppProps, AppState> {/* Prevent the next paste event */const preventNextPaste = (event: ClipboardEvent) => {- document.body.removeEventListener(EVENT.PASTE, preventNextPaste);+ this.ownerDocument.body.removeEventListener(+ EVENT.PASTE,+ preventNextPaste,+ );event.stopPropagation();};@@ -8987,13 +9042,19 @@ class App extends React.Component<AppProps, AppState> {*/const enableNextPaste = () => {setTimeout(() => {- document.body.removeEventListener(EVENT.PASTE, preventNextPaste);- window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);+ this.ownerDocument.body.removeEventListener(+ EVENT.PASTE,+ preventNextPaste,+ );+ this.ownerWindow.removeEventListener(+ EVENT.POINTER_UP,+ enableNextPaste,+ );}, 100);};- document.body.addEventListener(EVENT.PASTE, preventNextPaste);- window.addEventListener(EVENT.POINTER_UP, enableNextPaste);+ this.ownerDocument.body.addEventListener(EVENT.PASTE, preventNextPaste);+ this.ownerWindow.addEventListener(EVENT.POINTER_UP, enableNextPaste);}this.viewport.translate({@@ -9017,17 +9078,17 @@ class App extends React.Component<AppProps, AppState> {this.viewport.releaseOverscroll,);this.savePointer(event.clientX, event.clientY, "up");- window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);- window.removeEventListener(EVENT.POINTER_UP, teardown);- window.removeEventListener(EVENT.BLUR, teardown);+ this.ownerWindow.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);+ this.ownerWindow.removeEventListener(EVENT.POINTER_UP, teardown);+ this.ownerWindow.removeEventListener(EVENT.BLUR, teardown);onPointerMove.flush();}),);- window.addEventListener(EVENT.BLUR, teardown);- window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {+ this.ownerWindow.addEventListener(EVENT.BLUR, teardown);+ this.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {passive: true,});- window.addEventListener(EVENT.POINTER_UP, teardown);+ this.ownerWindow.addEventListener(EVENT.POINTER_UP, teardown);return true;};@@ -9208,7 +9269,7 @@ class App extends React.Component<AppProps, AppState> {pointerDownState.lastCoords.y = event.clientY;const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {const target = event.target;- if (!(target instanceof HTMLElement)) {+ if (!(target instanceof this.ownerWindow.HTMLElement)) {return;}@@ -9222,15 +9283,15 @@ class App extends React.Component<AppProps, AppState> {cursorButton: "up",});this.savePointer(event.clientX, event.clientY, "up");- window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);- window.removeEventListener(EVENT.POINTER_UP, onPointerUp);+ this.ownerWindow.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);+ this.ownerWindow.removeEventListener(EVENT.POINTER_UP, onPointerUp);onPointerMove.flush();});lastPointerUp = onPointerUp;- window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);- window.addEventListener(EVENT.POINTER_UP, onPointerUp);+ this.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove);+ this.ownerWindow.addEventListener(EVENT.POINTER_UP, onPointerUp);return true;}@@ -10578,7 +10639,7 @@ class App extends React.Component<AppProps, AppState> {);}const target = event.target;- if (!(target instanceof HTMLElement)) {+ if (!(target instanceof this.ownerWindow.HTMLElement)) {return;}@@ -11656,19 +11717,19 @@ class App extends React.Component<AppProps, AppState> {this.missingPointerEventCleanupEmitter.clear();- window.removeEventListener(+ this.ownerWindow.removeEventListener(EVENT.POINTER_MOVE,pointerDownState.eventListeners.onMove!,);- window.removeEventListener(+ this.ownerWindow.removeEventListener(EVENT.POINTER_UP,pointerDownState.eventListeners.onUp!,);- window.removeEventListener(+ this.ownerWindow.removeEventListener(EVENT.KEYDOWN,pointerDownState.eventListeners.onKeyDown!,);- window.removeEventListener(+ this.ownerWindow.removeEventListener(EVENT.KEYUP,pointerDownState.eventListeners.onKeyUp!,);@@ -13685,10 +13746,10 @@ class App extends React.Component<AppProps, AppState> {}if (!(- event.target instanceof HTMLCanvasElement ||- event.target instanceof HTMLTextAreaElement ||- event.target instanceof HTMLIFrameElement ||- (event.target instanceof HTMLElement &&+ event.target instanceof this.ownerWindow.HTMLCanvasElement ||+ event.target instanceof this.ownerWindow.HTMLTextAreaElement ||+ event.target instanceof this.ownerWindow.HTMLIFrameElement ||+ (event.target instanceof this.ownerWindow.HTMLElement &&event.target.classList.contains(CLASSES.FRAME_NAME)))) {diff --git a/packages/excalidraw/components/ColorPicker/ColorPicker.tsx b/packages/excalidraw/components/ColorPicker/ColorPicker.tsxindex aa65bb8868..fbafca026b 100644--- a/packages/excalidraw/components/ColorPicker/ColorPicker.tsx+++ b/packages/excalidraw/components/ColorPicker/ColorPicker.tsx@@ -19,7 +19,7 @@ import type { ExcalidrawElement, Theme } from "@excalidraw/element/types";import { useAtom } from "../../editor-jotai";import { t } from "../../i18n";-import { useExcalidrawContainer, useStylesPanelMode } from "../App";+import { useApp, useExcalidrawContainer, useStylesPanelMode } from "../App";import { ButtonSeparator } from "../ButtonSeparator";import { activeEyeDropperAtom } from "../EyeDropper";import { PropertiesPopover } from "../PropertiesPopover";@@ -95,6 +95,7 @@ const ColorPickerPopupContent = ({getOpenPopup: () => AppState["openPopup"];}) => {const { container } = useExcalidrawContainer();+ const app = useApp();const stylesPanelMode = useStylesPanelMode();const isCompactMode = stylesPanelMode !== "full";const isMobileMode = stylesPanelMode === "mobile";@@ -130,12 +131,13 @@ const ColorPickerPopupContent = ({// Improve focus handling for text editing scenariospreventAutoFocusOnTouch={!!appState.editingTextElement}onFocusOutside={(event) => {+ const target = event.target;// focus moving into the top-picks context menu — let the menu keep// it (stealing it back would clear the menu's focus-driven// `data-highlighted` styling and break its keyboard navigation)if (- event.target instanceof HTMLElement &&- event.target.closest(".color-picker__context-menu")+ target instanceof app.ownerWindow.HTMLElement &&+ target.closest(".color-picker__context-menu")) {event.preventDefault();return;@@ -143,14 +145,14 @@ const ColorPickerPopupContent = ({// refocus due to eye dropperif (!isWritableElement(event.target)) {if (- event.target instanceof HTMLElement &&- event.target.matches(":active")+ target instanceof app.ownerWindow.HTMLElement &&+ target.matches(":active")) {// the focus escaped because a button outside is being pressed// (e.g. a top pick) — stealing focus mid-press makes the browser// drop the button's activation (`:active` styling), so wait for// the release- window.addEventListener("pointerup", focusPickerContent, {+ app.ownerWindow.addEventListener("pointerup", focusPickerContent, {once: true,});} else {@@ -176,8 +178,8 @@ const ColorPickerPopupContent = ({// Refocus text editor when popover closes if we were editing textif (appState.editingTextElement) {- setTimeout(() => {- const textEditor = document.querySelector(+ app.ownerWindow.setTimeout(() => {+ const textEditor = app.ownerDocument.querySelector(".excalidraw-wysiwyg",) as HTMLTextAreaElement;if (textEditor) {@@ -197,14 +199,14 @@ const ColorPickerPopupContent = ({onChange={(changedColor) => {// Save caret position before color change if editing textconst savedSelection = appState.editingTextElement- ? saveCaretPosition()+ ? saveCaretPosition(app.ownerDocument): null;onChange(changedColor);// Restore caret position after color change if editing textif (appState.editingTextElement && savedSelection) {- restoreCaretPosition(savedSelection);+ restoreCaretPosition(savedSelection, app.ownerDocument);}}}onEyeDropperToggle={(force) => {@@ -275,6 +277,7 @@ const ColorPickerTrigger = ({onToggle: () => void;editingTextElement?: boolean;}) => {+ const app = useApp();const stylesPanelMode = useStylesPanelMode();const isCompactMode = stylesPanelMode !== "full";const isMobileMode = stylesPanelMode === "mobile";@@ -289,7 +292,7 @@ const ColorPickerTrigger = ({// If editing text, temporarily disable the wysiwyg blur eventif (editingTextElement) {- temporarilyDisableTextEditorBlur();+ temporarilyDisableTextEditorBlur(app.ownerDocument);}onToggle();diff --git a/packages/excalidraw/components/EyeDropper.tsx b/packages/excalidraw/components/EyeDropper.tsxindex 02ec1fc129..7e43468732 100644--- a/packages/excalidraw/components/EyeDropper.tsx+++ b/packages/excalidraw/components/EyeDropper.tsx@@ -69,6 +69,7 @@ export const EyeDropper: React.FC<{const appState = useUIAppState();const elements = useExcalidrawElements();const app = useApp();+ const ownerWindow = app.ownerWindow;const selectedElements = getSelectedElements(elements, appState);@@ -111,8 +112,8 @@ export const EyeDropper: React.FC<{clientY: number;}) => {const pixel = ctx.getImageData(- (clientX - appState.offsetLeft) * window.devicePixelRatio,- (clientY - appState.offsetTop) * window.devicePixelRatio,+ (clientX - appState.offsetLeft) * ownerWindow.devicePixelRatio,+ (clientY - appState.offsetTop) * ownerWindow.devicePixelRatio,1,1,).data;@@ -221,10 +222,10 @@ export const EyeDropper: React.FC<{pointerDownListener,);eyeDropperContainer.addEventListener(EVENT.POINTER_UP, pointerUpListener);- window.addEventListener("pointermove", mouseMoveListener, {+ ownerWindow.addEventListener("pointermove", mouseMoveListener, {passive: true,});- window.addEventListener(EVENT.BLUR, onCancel);+ ownerWindow.addEventListener(EVENT.BLUR, onCancel);return () => {isHoldingPointerDown = false;@@ -237,8 +238,8 @@ export const EyeDropper: React.FC<{EVENT.POINTER_UP,pointerUpListener,);- window.removeEventListener("pointermove", mouseMoveListener);- window.removeEventListener(EVENT.BLUR, onCancel);+ ownerWindow.removeEventListener("pointermove", mouseMoveListener);+ ownerWindow.removeEventListener(EVENT.BLUR, onCancel);};}, [stableProps,@@ -249,6 +250,7 @@ export const EyeDropper: React.FC<{appState.offsetLeft,appState.offsetTop,appState.theme,+ ownerWindow,]);const ref = useRef<HTMLDivElement>(null);diff --git a/packages/excalidraw/components/LibraryMenu.tsx b/packages/excalidraw/components/LibraryMenu.tsxindex 81427cf29f..f6fadec582 100644--- a/packages/excalidraw/components/LibraryMenu.tsx+++ b/packages/excalidraw/components/LibraryMenu.tsx@@ -272,11 +272,16 @@ export const LibraryMenu = memo(() => {const pendingElements = usePendingElementsMemo(appState, app);useEffect(() => {+ const ownerDocument = app.ownerDocument;+ const ownerWindow = app.ownerWindow;return addEventListener(- document,+ ownerDocument,EVENT.KEYDOWN,(event) => {- if (event.key === KEYS.ESCAPE && event.target instanceof HTMLElement) {+ if (+ event.key === KEYS.ESCAPE &&+ event.target instanceof ownerWindow.HTMLElement+ ) {const target = event.target;if (target.closest(`.${CLASSES.SIDEBAR}`)) {// stop propagation so that we don't prevent it downstream@@ -285,8 +290,8 @@ export const LibraryMenu = memo(() => {event.stopPropagation();setSelectedItems([]);} else if (+ target instanceof ownerWindow.HTMLInputElement &&isWritableElement(target) &&- target instanceof HTMLInputElement &&!target.value) {event.stopPropagation();@@ -297,7 +302,7 @@ export const LibraryMenu = memo(() => {}} else if (selectedItems.length > 0) {const { x, y } = app.viewport.lastPosition;- const elementUnderCursor = document.elementFromPoint(x, y);+ const elementUnderCursor = ownerDocument.elementFromPoint(x, y);// also deselect elements if sidebar doesn't have focus but the// cursor is over itif (elementUnderCursor?.closest(`.${CLASSES.SIDEBAR}`)) {diff --git a/packages/excalidraw/components/Modal.tsx b/packages/excalidraw/components/Modal.tsxindex db68f76e49..2ff068fa52 100644--- a/packages/excalidraw/components/Modal.tsx+++ b/packages/excalidraw/components/Modal.tsx@@ -1,5 +1,5 @@import clsx from "clsx";-import { useRef } from "react";+import { useMemo } from "react";import { createPortal } from "react-dom";import { KEYS } from "@excalidraw/common";@@ -24,8 +24,12 @@ export const Modal: React.FC<{className: "excalidraw-modal-container",});- const animationsDisabledRef = useRef(- document.body.classList.contains("excalidraw-animations-disabled"),+ const animationsDisabled = useMemo(+ () =>+ modalRoot?.ownerDocument.body.classList.contains(+ "excalidraw-animations-disabled",+ ) ?? false,+ [modalRoot],);if (!modalRoot) {@@ -44,7 +48,7 @@ export const Modal: React.FC<{return createPortal(<divclassName={clsx("Modal", props.className, {- "animations-disabled": animationsDisabledRef.current,+ "animations-disabled": animationsDisabled,})}role="dialog"aria-modal="true"diff --git a/packages/excalidraw/components/SearchMenu.tsx b/packages/excalidraw/components/SearchMenu.tsxindex 3ecb79e4e2..0583da1791 100644--- a/packages/excalidraw/components/SearchMenu.tsx+++ b/packages/excalidraw/components/SearchMenu.tsx@@ -221,8 +221,8 @@ export const SearchMenu = () => {if (!isElementCompletelyInViewport([matchAsElement],- app.canvas.width / window.devicePixelRatio,- app.canvas.height / window.devicePixelRatio,+ app.canvas.width / app.ownerWindow.devicePixelRatio,+ app.canvas.height / app.ownerWindow.devicePixelRatio,{offsetLeft: app.state.offsetLeft,offsetTop: app.state.offsetTop,@@ -273,6 +273,7 @@ export const SearchMenu = () => {useEffect(() => {const eventHandler = (event: KeyboardEvent) => {+ const target = event.target;if (event.key === KEYS.ESCAPE &&!app.state.openDialog &&@@ -306,8 +307,8 @@ export const SearchMenu = () => {}if (- event.target instanceof HTMLElement &&- event.target.closest(".layer-ui__search")+ target instanceof app.ownerWindow.HTMLElement &&+ target.closest(".layer-ui__search")) {if (stableState.searchMatches.items.length) {if (event.key === KEYS.ENTER) {@@ -328,7 +329,7 @@ export const SearchMenu = () => {// `capture` needed to prevent firing on initial open from App.tsx,// as well as to handle events before App ones- return addEventListener(window, EVENT.KEYDOWN, eventHandler, {+ return addEventListener(app.ownerWindow, EVENT.KEYDOWN, eventHandler, {capture: true,passive: false,});diff --git a/packages/excalidraw/components/Stats/DragInput.tsx b/packages/excalidraw/components/Stats/DragInput.tsxindex 6479dbb1c3..2943d767da 100644--- a/packages/excalidraw/components/Stats/DragInput.tsx+++ b/packages/excalidraw/components/Stats/DragInput.tsx@@ -88,6 +88,8 @@ const StatsDragInput = <dragFinishedCallback,}: StatsDragInputProps<T, E>) => {const app = useApp();+ const ownerDocument = app.ownerDocument;+ const ownerWindow = app.ownerWindow;const setAppState = useExcalidrawSetAppState();const inputRef = useRef<HTMLInputElement>(null);const labelRef = useRef<HTMLDivElement>(null);@@ -189,12 +191,12 @@ const StatsDragInput = <// generally not needed, but in case `pointerup` doesn't fire and// we don't remove the listeners that way, we should at least remove// on unmount- window.removeEventListener(+ ownerWindow.removeEventListener(EVENT.POINTER_MOVE,callbacks.onPointerMove!,false,);- window.removeEventListener(+ ownerWindow.removeEventListener(EVENT.POINTER_UP,callbacks.onPointerUp!,false,@@ -208,6 +210,7 @@ const StatsDragInput = <// to an element that has a given property as non-editable would not trigger// blur/unmount and wouldn't update the value.editable,+ ownerWindow,]);if (!editable) {@@ -224,7 +227,7 @@ const StatsDragInput = <ref={labelRef}onPointerDown={(event) => {if (inputRef.current && editable) {- document.body.classList.add("excalidraw-cursor-resize");+ ownerDocument.body.classList.add("excalidraw-cursor-resize");let startValue = Number(inputRef.current.value);if (isNaN(startValue)) {@@ -297,7 +300,7 @@ const StatsDragInput = <};const onPointerUp = () => {- window.removeEventListener(+ ownerWindow.removeEventListener(EVENT.POINTER_MOVE,onPointerMove,false,@@ -321,16 +324,24 @@ const StatsDragInput = <originalElements = null;originalElementsMap = null;- document.body.classList.remove("excalidraw-cursor-resize");+ ownerDocument.body.classList.remove("excalidraw-cursor-resize");- window.removeEventListener(EVENT.POINTER_UP, onPointerUp, false);+ ownerWindow.removeEventListener(+ EVENT.POINTER_UP,+ onPointerUp,+ false,+ );};callbacksRef.current.onPointerMove = onPointerMove;callbacksRef.current.onPointerUp = onPointerUp;- window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, false);- window.addEventListener(EVENT.POINTER_UP, onPointerUp, false);+ ownerWindow.addEventListener(+ EVENT.POINTER_MOVE,+ onPointerMove,+ false,+ );+ ownerWindow.addEventListener(EVENT.POINTER_UP, onPointerUp, false);}}}onPointerEnter={() => {@@ -347,9 +358,9 @@ const StatsDragInput = <spellCheck="false"onKeyDown={(event) => {if (editable) {- const eventTarget = event.target;+ const eventTarget = event.currentTarget;if (- eventTarget instanceof HTMLInputElement &&+ eventTarget instanceof ownerWindow.HTMLInputElement &&event.key === KEYS.ENTER) {handleInputValue(eventTarget.value, elements, appState);diff --git a/packages/excalidraw/components/UserList.tsx b/packages/excalidraw/components/UserList.tsxindex f1a460ff19..ee8e1386fa 100644--- a/packages/excalidraw/components/UserList.tsx+++ b/packages/excalidraw/components/UserList.tsx@@ -2,7 +2,7 @@ import { Popover } from "radix-ui";import clsx from "clsx";import React, { useLayoutEffect } from "react";-import { supportsResizeObserver, isShallowEqual } from "@excalidraw/common";+import { isShallowEqual } from "@excalidraw/common";import { t } from "../i18n";@@ -154,17 +154,18 @@ export const UserList = React.memo(useLayoutEffect(() => {if (userListWrapper.current) {+ const ownerWindow = userListWrapper.current.ownerDocument.defaultView;const updateWrapperWidth = (width: number) => {setWrapperWidth(width);};updateWrapperWidth(userListWrapper.current.clientWidth);- if (!supportsResizeObserver) {+ if (!ownerWindow || typeof ownerWindow.ResizeObserver !== "function") {return;}- const resizeObserver = new ResizeObserver((entries) => {+ const resizeObserver = new ownerWindow.ResizeObserver((entries) => {for (const entry of entries) {const { width } = entry.contentRect;updateWrapperWidth(width);diff --git a/packages/excalidraw/fonts/Fonts.ts b/packages/excalidraw/fonts/Fonts.tsindex 195fb51f47..c028dbd8c0 100644--- a/packages/excalidraw/fonts/Fonts.ts+++ b/packages/excalidraw/fonts/Fonts.ts@@ -81,9 +81,11 @@ export class Fonts {}private readonly scene: Scene;+ private readonly ownerDocument: Document;- constructor(scene: Scene) {+ constructor(scene: Scene, ownerDocument: Document = document) {this.scene = scene;+ this.ownerDocument = ownerDocument;}/**@@ -154,7 +156,11 @@ export class Fonts {this.scene.getNonDeletedElements(),);- return Fonts.loadFontFaces(sceneFamilies, charsPerFamily);+ return Fonts.loadFontFaces(+ sceneFamilies,+ charsPerFamily,+ this.ownerDocument,+ );};/**@@ -162,11 +168,12 @@ export class Fonts {*/public static loadElementsFonts = async (elements: readonly ExcalidrawElement[],+ ownerDocument: Document = document,): Promise<FontFace[]> => {const fontFamilies = Fonts.getUniqueFamilies(elements);const charsPerFamily = Fonts.getCharsPerFamily(elements);- return Fonts.loadFontFaces(fontFamilies, charsPerFamily);+ return Fonts.loadFontFaces(fontFamilies, charsPerFamily, ownerDocument);};/**@@ -212,6 +219,7 @@ export class Fonts {private static async loadFontFaces(fontFamilies: Array<ExcalidrawTextElement["fontFamily"]>,charsPerFamily: Record<number, Set<string>>,+ ownerDocument: Document,) {// add all registered font faces into the `document.fonts` (if not added already)for (const { fontFaces, metadata } of Fonts.registered.values()) {@@ -221,14 +229,18 @@ export class Fonts {}for (const { fontFace } of fontFaces) {- if (!window.document.fonts.has(fontFace)) {- window.document.fonts.add(fontFace);+ if (!ownerDocument.fonts.has(fontFace)) {+ ownerDocument.fonts.add(fontFace);}}}// loading 10 font faces at a time, in a controlled manner- const iterator = Fonts.fontFacesLoader(fontFamilies, charsPerFamily);+ const iterator = Fonts.fontFacesLoader(+ fontFamilies,+ charsPerFamily,+ ownerDocument,+ );const concurrency = 10;const fontFaces = await new PromisePool(iterator, concurrency).all();return fontFaces.flat().filter(Boolean);@@ -237,6 +249,7 @@ export class Fonts {private static *fontFacesLoader(fontFamilies: Array<ExcalidrawTextElement["fontFamily"]>,charsPerFamily: Record<number, Set<string>>,+ ownerDocument: Document,): Generator<Promise<void | readonly [number, FontFace[]]>> {for (const [index, fontFamily] of fontFamilies.entries()) {const font = getFontString({@@ -248,12 +261,12 @@ export class Fonts {// instead, we are always checking chars used in the family, so that no required font faces remain unloadedconst text = Fonts.getCharacters(charsPerFamily, fontFamily);- if (!window.document.fonts.check(font, text)) {+ if (!ownerDocument.fonts.check(font, text)) {yield promiseTry(async () => {try {// WARN: browser prioritizes loading only font faces with unicode ranges for characters which are present in the document (html & canvas), other font faces could stay unloaded// we might want to retry here, i.e. in case CDN is down, but so far I didn't experience any issues - maybe it handles retry-like logic under the hood- const fontFaces = await window.document.fonts.load(font, text);+ const fontFaces = await ownerDocument.fonts.load(font, text);return [index, fontFaces];} catch (e) {diff --git a/packages/excalidraw/hooks/useCreatePortalContainer.ts b/packages/excalidraw/hooks/useCreatePortalContainer.tsindex c1fe2c9e8f..b85fb16842 100644--- a/packages/excalidraw/hooks/useCreatePortalContainer.ts+++ b/packages/excalidraw/hooks/useCreatePortalContainer.ts@@ -29,15 +29,16 @@ export const useCreatePortalContainer = (opts?: {}, [div, theme, editorInterface.formFactor, opts?.className]);useLayoutEffect(() => {+ const ownerDocument = excalidrawContainer?.ownerDocument;const container = opts?.parentSelector? excalidrawContainer?.querySelector(opts.parentSelector)- : document.body;+ : ownerDocument?.body;- if (!container) {+ if (!container || !ownerDocument) {return;}- const div = document.createElement("div");+ const div = ownerDocument.createElement("div");container.appendChild(div);diff --git a/packages/excalidraw/hooks/useOutsideClick.ts b/packages/excalidraw/hooks/useOutsideClick.tsindex a9e5ce11cb..3ee660a07d 100644--- a/packages/excalidraw/hooks/useOutsideClick.ts+++ b/packages/excalidraw/hooks/useOutsideClick.ts@@ -24,6 +24,12 @@ export function useOutsideClick<T extends HTMLElement>() => boolean | undefined,) {useEffect(() => {+ const refOwnerDocument = ref.current?.ownerDocument;+ if (!refOwnerDocument) {+ return;+ }+ const ownerDocument: Document = refOwnerDocument;+function onOutsideClick(event: Event) {const _event = event as Event & { target: T };@@ -45,7 +51,7 @@ export function useOutsideClick<T extends HTMLElement>(// target is detached from DOM (happens when the element is removed// on a pointerup event fired *before* this handler's pointerup is// dispatched)- !document.documentElement.contains(_event.target)+ !ownerDocument.documentElement.contains(_event.target)) {return;}@@ -56,8 +62,8 @@ export function useOutsideClick<T extends HTMLElement>(// the `body` element, so the target element is going to be the `html`// (note: this won't work if we selectively re-enable pointer events on// specific elements as we do with navbar or excalidraw UI elements)- (_event.target === document.documentElement &&- document.body.style.pointerEvents === "none");+ (_event.target === ownerDocument.documentElement &&+ ownerDocument.body.style.pointerEvents === "none");// if clicking on radix portal, assume it's a popup that// should be considered as part of the UI. Obviously this is a terrible@@ -76,12 +82,12 @@ export function useOutsideClick<T extends HTMLElement>(}// note: don't use `click` because it often reports incorrect `event.target`- document.addEventListener(EVENT.POINTER_DOWN, onOutsideClick);- document.addEventListener(EVENT.TOUCH_START, onOutsideClick);+ ownerDocument.addEventListener(EVENT.POINTER_DOWN, onOutsideClick);+ ownerDocument.addEventListener(EVENT.TOUCH_START, onOutsideClick);return () => {- document.removeEventListener(EVENT.POINTER_DOWN, onOutsideClick);- document.removeEventListener(EVENT.TOUCH_START, onOutsideClick);+ ownerDocument.removeEventListener(EVENT.POINTER_DOWN, onOutsideClick);+ ownerDocument.removeEventListener(EVENT.TOUCH_START, onOutsideClick);};}, [ref, callback, isInside]);}diff --git a/packages/excalidraw/hooks/useTextEditorFocus.ts b/packages/excalidraw/hooks/useTextEditorFocus.tsindex 25c6147d4a..1a2c19189b 100644--- a/packages/excalidraw/hooks/useTextEditorFocus.ts+++ b/packages/excalidraw/hooks/useTextEditorFocus.ts@@ -7,13 +7,17 @@ export type CaretPosition = {};// Utility function to get text editor element-const getTextEditor = (): HTMLTextAreaElement | null => {- return document.querySelector(".excalidraw-wysiwyg") as HTMLTextAreaElement;+const getTextEditor = (ownerDocument: Document): HTMLTextAreaElement | null => {+ return ownerDocument.querySelector(+ ".excalidraw-wysiwyg",+ ) as HTMLTextAreaElement;};// Utility functions for caret position management-export const saveCaretPosition = (): CaretPosition | null => {- const textEditor = getTextEditor();+export const saveCaretPosition = (+ ownerDocument: Document = document,+): CaretPosition | null => {+ const textEditor = getTextEditor(ownerDocument);if (textEditor) {return {start: textEditor.selectionStart,@@ -23,9 +27,13 @@ export const saveCaretPosition = (): CaretPosition | null => {return null;};-export const restoreCaretPosition = (position: CaretPosition | null): void => {- setTimeout(() => {- const textEditor = getTextEditor();+export const restoreCaretPosition = (+ position: CaretPosition | null,+ ownerDocument: Document = document,+): void => {+ const ownerWindow = ownerDocument.defaultView ?? window;+ ownerWindow.setTimeout(() => {+ const textEditor = getTextEditor(ownerDocument);if (textEditor) {textEditor.focus();if (position) {@@ -41,6 +49,7 @@ export const withCaretPositionPreservation = (isCompactMode: boolean,isEditingText: boolean,onPreventClose?: () => void,+ ownerDocument: Document = document,): void => {// Prevent popover from closing in compact modeif (isCompactMode && onPreventClose) {@@ -49,30 +58,31 @@ export const withCaretPositionPreservation = (// Save caret position if editing textconst savedPosition =- isCompactMode && isEditingText ? saveCaretPosition() : null;+ isCompactMode && isEditingText ? saveCaretPosition(ownerDocument) : null;// Execute the callbackcallback();// Restore caret position if neededif (isCompactMode && isEditingText) {- restoreCaretPosition(savedPosition);+ restoreCaretPosition(savedPosition, ownerDocument);}};// Hook for managing text editor caret position with state-export const useTextEditorFocus = () => {+export const useTextEditorFocus = (ownerDocument: Document = document) => {const [savedCaretPosition, setSavedCaretPosition] =useState<CaretPosition | null>(null);const saveCaretPositionToState = useCallback(() => {- const position = saveCaretPosition();+ const position = saveCaretPosition(ownerDocument);setSavedCaretPosition(position);- }, []);+ }, [ownerDocument]);const restoreCaretPositionFromState = useCallback(() => {- setTimeout(() => {- const textEditor = getTextEditor();+ const ownerWindow = ownerDocument.defaultView ?? window;+ ownerWindow.setTimeout(() => {+ const textEditor = getTextEditor(ownerDocument);if (textEditor) {textEditor.focus();if (savedCaretPosition) {@@ -82,7 +92,7 @@ export const useTextEditorFocus = () => {}}}, 0);- }, [savedCaretPosition]);+ }, [ownerDocument, savedCaretPosition]);const clearSavedPosition = useCallback(() => {setSavedCaretPosition(null);@@ -98,14 +108,16 @@ export const useTextEditorFocus = () => {// Utility function to temporarily disable text editor blurexport const temporarilyDisableTextEditorBlur = (+ ownerDocument: Document = document,duration: number = 100,): void => {- const textEditor = getTextEditor();+ const textEditor = getTextEditor(ownerDocument);if (textEditor) {const originalOnBlur = textEditor.onblur;textEditor.onblur = null;- setTimeout(() => {+ const ownerWindow = ownerDocument.defaultView ?? window;+ ownerWindow.setTimeout(() => {textEditor.onblur = originalOnBlur;}, duration);}diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsxindex 70ac526ef8..94daf3b69e 100644--- a/packages/excalidraw/index.tsx+++ b/packages/excalidraw/index.tsx@@ -68,6 +68,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {const {onExport,className,+ ownerDocument = document,onChange,onThemeChange,onIncrement,@@ -194,14 +195,14 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {}};- document.addEventListener("touchmove", handleTouchMove, {+ ownerDocument.addEventListener("touchmove", handleTouchMove, {passive: false,});return () => {- document.removeEventListener("touchmove", handleTouchMove);+ ownerDocument.removeEventListener("touchmove", handleTouchMove);};- }, [browserZoomAllowed]);+ }, [browserZoomAllowed, ownerDocument]);return (<EditorJotaiProvider store={editorJotaiStore}>@@ -209,6 +210,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {<ApponExport={onExport}className={className}+ ownerDocument={ownerDocument}onChange={onChange}onThemeChange={onThemeChange}onIncrement={onIncrement}diff --git a/packages/excalidraw/tests/crossDocument.test.tsx b/packages/excalidraw/tests/crossDocument.test.tsxnew file mode 100644index 0000000000..493c13306d--- /dev/null+++ b/packages/excalidraw/tests/crossDocument.test.tsx@@ -0,0 +1,147 @@+import React from "react";+import {+ act,+ fireEvent,+ render as renderReact,+ waitFor,+} from "@testing-library/react";+import { vi } from "vitest";++import { Excalidraw } from "../index";++import type { ExcalidrawImperativeAPI } from "../types";++describe("cross-document rendering", () => {+ it("scopes listeners, fonts, and portals to ownerDocument", async () => {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);++ const ownerDocument = iframe.contentDocument!;+ const ownerWindow = iframe.contentWindow! as Window & typeof globalThis;+ const mountNode = ownerDocument.createElement("div");+ ownerDocument.body.append(mountNode);++ const fonts = {+ load: vi.fn().mockResolvedValue([]),+ check: vi.fn().mockReturnValue(true),+ has: vi.fn().mockReturnValue(true),+ add: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };+ Object.defineProperty(ownerDocument, "fonts", { value: fonts });+ const addEventListener = vi.fn();+ Object.defineProperties(ownerWindow, {+ addEventListener: { value: addEventListener },+ removeEventListener: { value: vi.fn() },+ requestAnimationFrame: {+ value: window.requestAnimationFrame.bind(window),+ },+ ResizeObserver: { value: window.ResizeObserver },+ });+ Object.defineProperty(ownerDocument, "defaultView", {+ value: ownerWindow,+ });+ Object.defineProperty(+ ownerWindow.HTMLCanvasElement.prototype,+ "getContext",+ {+ value: window.HTMLCanvasElement.prototype.getContext,+ },+ );+ const addDocumentEventListener = vi.spyOn(+ ownerDocument,+ "addEventListener",+ );+ let unmount: (() => void) | null = null;+ try {+ let api: ExcalidrawImperativeAPI | null = null;+ const renderResult = renderReact(+ <Excalidraw+ ownerDocument={ownerDocument}+ handleKeyboardGlobally={true}+ onExcalidrawAPI={(nextApi) => {+ api = nextApi;+ }}+ />,+ { container: mountNode, baseElement: ownerDocument.body },+ );+ unmount = renderResult.unmount;+ const { container } = renderResult;++ await waitFor(() =>+ expect(container.querySelector("canvas.interactive")).not.toBeNull(),+ );+ expect(api).not.toBeNull();+ await waitFor(() => expect(api!.getAppState().isLoading).toBe(false));+ expect(+ addDocumentEventListener.mock.calls.some(+ ([eventName]) => eventName === "pointermove",+ ),+ ).toBe(true);+ expect(+ addDocumentEventListener.mock.calls.some(+ ([eventName]) => eventName === "keydown",+ ),+ ).toBe(true);+ expect(+ addDocumentEventListener.mock.calls.some(+ ([eventName]) => eventName === "paste",+ ),+ ).toBe(true);+ expect(+ addEventListener.mock.calls.some(+ ([eventName]) => eventName === "message",+ ),+ ).toBe(true);+ const messageHandler = addEventListener.mock.calls.find(+ ([eventName]) => eventName === "message",+ )?.[1] as EventListener | undefined;+ expect(typeof messageHandler).toBe("function");+ expect(() =>+ messageHandler!(+ new ownerWindow.MessageEvent("message", {+ data: JSON.stringify({ method: "paused", value: true }),+ origin: "https://player.vimeo.com",+ }),+ ),+ ).not.toThrow();++ const excalidrawContainer = container.querySelector(".excalidraw")!;+ fireEvent.pointerEnter(excalidrawContainer);+ expect(ownerDocument.documentElement.style.overscrollBehaviorX).toBe(+ "none",+ );+ fireEvent.pointerLeave(excalidrawContainer);+ expect(ownerDocument.documentElement.style.overscrollBehaviorX).toBe(+ "auto",+ );++ expect(fonts.addEventListener).toHaveBeenCalledWith(+ "loadingdone",+ expect.any(Function),+ { passive: false },+ );++ ownerDocument.body.classList.add("excalidraw-animations-disabled");+ act(() => {+ api!.updateScene({+ appState: { openDialog: { name: "imageExport" } },+ });+ });++ await waitFor(() =>+ expect(+ ownerDocument.querySelector(".excalidraw-modal-container"),+ ).not.toBeNull(),+ );+ expect(document.querySelector(".excalidraw-modal-container")).toBeNull();+ expect(ownerDocument.querySelector(".Modal")).toHaveClass(+ "animations-disabled",+ );+ } finally {+ unmount?.();+ iframe.remove();+ }+ });+});diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex 57429ad150..9bd45b1e02 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -781,6 +781,16 @@ export type UIConfig = {export interface ExcalidrawProps {className?: string;+ /**+ * Document that owns Excalidraw's mounted DOM.+ *+ * Set only when it differs from the global `document`, such as when code+ * executing in a parent window mounts Excalidraw into an iframe document.+ * The value must remain stable for the editor's lifetime.+ *+ * @default document+ */+ ownerDocument?: Document;onChange?: (elements: readonly OrderedExcalidrawElement[],appState: AppState,@@ -1093,6 +1103,8 @@ export type AppProps = Merge<export type AppClassProperties = {props: AppProps;state: AppState;+ readonly ownerDocument: Document;+ readonly ownerWindow: Window & typeof globalThis;api: App["api"];sessionExportThemeOverride: App["sessionExportThemeOverride"];interactiveCanvas: HTMLCanvasElement | null;diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsxindex 74bf7aebbb..b7973f2d4b 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx@@ -126,21 +126,27 @@ const getLineCaretOffsetFromNativeLayout = ({lineHeightPx,direction,targetX,+ ownerDocument,}: {text: string;font: ReturnType<typeof getFontString>;lineHeightPx: number;direction: "ltr" | "rtl";targetX: number;+ ownerDocument: Document;}) => {- if (!text || !document.body || typeof document.createRange !== "function") {+ if (+ !text ||+ !ownerDocument.body ||+ typeof ownerDocument.createRange !== "function"+ ) {return null;}const offsets = getCaretBoundaryOffsets(text);- const mirror = document.createElement("div");- const textNode = document.createTextNode(text);- const range = document.createRange();+ const mirror = ownerDocument.createElement("div");+ const textNode = ownerDocument.createTextNode(text);+ const range = ownerDocument.createRange();const positions: number[] = [];mirror.dir = direction;@@ -158,7 +164,7 @@ const getLineCaretOffsetFromNativeLayout = ({lineHeight: `${lineHeightPx}px`,});mirror.append(textNode);- document.body.append(mirror);+ ownerDocument.body.append(mirror);try {for (const offset of offsets) {@@ -223,6 +229,8 @@ export const textWysiwyg = ({autoSelect?: boolean;initialCaretSceneCoords?: { x: number; y: number } | null;}): SubmitHandler => {+ const ownerDocument = excalidrawContainer?.ownerDocument ?? document;+ const ownerWindow = ownerDocument.defaultView ?? window;let currentTextLayout: {angle: Radians;font: ReturnType<typeof getFontString>;@@ -424,7 +432,7 @@ export const textWysiwyg = ({}};- const editable = document.createElement("textarea");+ const editable = ownerDocument.createElement("textarea");editable.dir = "auto";editable.tabIndex = 0;@@ -510,6 +518,7 @@ export const textWysiwyg = ({lineHeightPx: layout.lineHeightPx,direction,targetX: relativeX,+ ownerDocument,});return line.start + (lineCaretOffset || 0);@@ -774,7 +783,7 @@ export const textWysiwyg = ({};const stopEvent = (event: Event) => {- if (event.target instanceof HTMLCanvasElement) {+ if (event.target instanceof ownerWindow.HTMLCanvasElement) {event.preventDefault();event.stopPropagation();}@@ -849,12 +858,12 @@ export const textWysiwyg = ({observer.disconnect();}- window.removeEventListener("resize", updateWysiwygStyle);- window.removeEventListener("wheel", stopEvent, true);- window.removeEventListener("pointerdown", onPointerDown);- window.removeEventListener("pointerup", bindBlurEvent);- window.removeEventListener("blur", handleSubmit);- window.removeEventListener("beforeunload", handleSubmit);+ ownerWindow.removeEventListener("resize", updateWysiwygStyle);+ ownerWindow.removeEventListener("wheel", stopEvent, true);+ ownerWindow.removeEventListener("pointerdown", onPointerDown);+ ownerWindow.removeEventListener("pointerup", bindBlurEvent);+ ownerWindow.removeEventListener("blur", handleSubmit);+ ownerWindow.removeEventListener("beforeunload", handleSubmit);unbindUpdate();unsubOnChange();unbindOnScroll();@@ -863,7 +872,7 @@ export const textWysiwyg = ({};const bindBlurEvent = (event?: MouseEvent) => {- window.removeEventListener("pointerup", bindBlurEvent);+ ownerWindow.removeEventListener("pointerup", bindBlurEvent);// Deferred so that the pointerdown that initiates the wysiwyg doesn't// trigger the blur on ensuing pointerup.// Also to handle cases such as picking a color which would trigger a blur@@ -871,17 +880,19 @@ export const textWysiwyg = ({const target = event?.target;const isPropertiesTrigger =- target instanceof HTMLElement &&+ target instanceof ownerWindow.HTMLElement &&target.classList.contains("properties-trigger");const isPropertiesContent =- (target instanceof HTMLElement || target instanceof SVGElement) &&+ (target instanceof ownerWindow.HTMLElement ||+ target instanceof ownerWindow.SVGElement) &&!!(target as Element).closest(".properties-content");const inShapeActionsMenu =- (target instanceof HTMLElement || target instanceof SVGElement) &&+ (target instanceof ownerWindow.HTMLElement ||+ target instanceof ownerWindow.SVGElement) &&(!!(target as Element).closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) ||!!(target as Element).closest(".compact-shape-actions-island"));- setTimeout(() => {+ ownerWindow.setTimeout(() => {// If we interacted within shape actions menu or its popovers/triggers,// keep submit disabled and don't steal focus back to textarea.if (inShapeActionsMenu || isPropertiesTrigger || isPropertiesContent) {@@ -903,10 +914,10 @@ export const textWysiwyg = ({const temporarilyDisableSubmit = () => {editable.onblur = null;- window.addEventListener("pointerup", bindBlurEvent);+ ownerWindow.addEventListener("pointerup", bindBlurEvent);// handle edge-case where pointerup doesn't fire e.g. due to user// alt-tabbing away- window.addEventListener("blur", handleSubmit);+ ownerWindow.addEventListener("blur", handleSubmit);};// prevent blur when changing properties from the menu@@ -916,7 +927,7 @@ export const textWysiwyg = ({// panning canvasif (event.button === POINTER_BUTTON.WHEEL) {// trying to pan by clicking inside text area itself -> handle here- if (target instanceof HTMLTextAreaElement) {+ if (target instanceof ownerWindow.HTMLTextAreaElement) {event.preventDefault();app.handleCanvasPanUsingWheelOrSpaceDrag(event);}@@ -926,15 +937,16 @@ export const textWysiwyg = ({}const isPropertiesTrigger =- target instanceof HTMLElement &&+ target instanceof ownerWindow.HTMLElement &&target.classList.contains("properties-trigger");const isPropertiesContent =- (target instanceof HTMLElement || target instanceof SVGElement) &&+ (target instanceof ownerWindow.HTMLElement ||+ target instanceof ownerWindow.SVGElement) &&!!(target as Element).closest(".properties-content");if (- ((event.target instanceof HTMLElement ||- event.target instanceof SVGElement) &&+ ((event.target instanceof ownerWindow.HTMLElement ||+ event.target instanceof ownerWindow.SVGElement) &&(event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}, .${CLASSES.ZOOM_ACTIONS}`,) ||@@ -945,7 +957,7 @@ export const textWysiwyg = ({) {temporarilyDisableSubmit();} else if (- event.target instanceof HTMLCanvasElement &&+ event.target instanceof ownerWindow.HTMLCanvasElement &&// Vitest simply ignores stopPropagation, capture-mode, or rAF// so without introducing crazier hacks, nothing we can do!isTestEnv()@@ -956,7 +968,7 @@ export const textWysiwyg = ({// immediately (if tools locked) so that users on mobile have chance// to submit first (to hide virtual keyboard).// Note: revisit if we want to differ this behavior on Desktop- requestAnimationFrame(() => {+ ownerWindow.requestAnimationFrame(() => {handleSubmit();});}@@ -972,7 +984,7 @@ export const textWysiwyg = ({// handle updates of textElement properties of editing elementconst unbindUpdate = app.scene.onUpdate(() => {updateWysiwygStyle();- const isPopupOpened = !!document.activeElement?.closest(+ const isPopupOpened = !!ownerDocument.activeElement?.closest(".properties-content",);if (!isPopupOpened) {@@ -998,23 +1010,25 @@ export const textWysiwyg = ({// reposition wysiwyg in case of canvas is resized. Using ResizeObserver// is preferred so we catch changes from host, where window may not resize.let observer: ResizeObserver | null = null;- if (canvas && "ResizeObserver" in window) {- observer = new window.ResizeObserver(() => {+ if (canvas && "ResizeObserver" in ownerWindow) {+ observer = new ownerWindow.ResizeObserver(() => {updateWysiwygStyle();});observer.observe(canvas);} else {- window.addEventListener("resize", updateWysiwygStyle);+ ownerWindow.addEventListener("resize", updateWysiwygStyle);}editable.onpointerdown = (event) => event.stopPropagation();// rAF (+ capture to by doubly sure) so we don't catch te pointerdown that// triggered the wysiwyg- requestAnimationFrame(() => {- window.addEventListener("pointerdown", onPointerDown, { capture: true });+ ownerWindow.requestAnimationFrame(() => {+ ownerWindow.addEventListener("pointerdown", onPointerDown, {+ capture: true,+ });});- window.addEventListener("beforeunload", handleSubmit);+ ownerWindow.addEventListener("beforeunload", handleSubmit);excalidrawContainer?.querySelector(".excalidraw-textEditorContainer")!.appendChild(editable);