Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

fix(packages/excalidraw): complete cross-document runtime ownership (#11997)

zsvicziand3a9c2a19518
diff --git a/packages/common/src/editorInterface.ts b/packages/common/src/editorInterface.ts
index d18b7a7d08..40e26ae10c 100644
--- a/packages/common/src/editorInterface.ts
+++ b/packages/common/src/editorInterface.ts
@@ -34,24 +34,32 @@ export const MQ_RIGHT_SIDEBAR_MIN_WIDTH = 1229;
// -----------------------------------------------------------------------------
// user agent detections
-export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
-export const isWindows = /^Win/.test(navigator.platform);
-export const isAndroid = /\b(android)\b/i.test(navigator.userAgent);
+//
+// evaluated at module scope, so they must tolerate a non-browser realm --
+// these modules are imported by the export pipeline, which is expected to be
+// loadable under Node
+const ua = typeof navigator === "undefined" ? undefined : navigator;
+const uaPlatform = ua?.platform ?? "";
+const uaString = ua?.userAgent ?? "";
+
+export const isDarwin = /Mac|iPod|iPhone|iPad/.test(uaPlatform);
+export const isWindows = /^Win/.test(uaPlatform);
+export const isAndroid = /\b(android)\b/i.test(uaString);
export const isFirefox =
typeof window !== "undefined" &&
"netscape" in window &&
- navigator.userAgent.indexOf("rv:") > 1 &&
- navigator.userAgent.indexOf("Gecko") > 1;
-export const isChrome = navigator.userAgent.indexOf("Chrome") !== -1;
-export const isSafari =
- !isChrome && navigator.userAgent.indexOf("Safari") !== -1;
+ uaString.indexOf("rv:") > 1 &&
+ uaString.indexOf("Gecko") > 1;
+export const isChrome = uaString.indexOf("Chrome") !== -1;
+export const isSafari = !isChrome && uaString.indexOf("Safari") !== -1;
export const isIOS =
- /iPad|iPhone/i.test(navigator.platform) ||
+ /iPad|iPhone/i.test(uaPlatform) ||
// iPadOS 13+
- (navigator.userAgent.includes("Mac") && "ontouchend" in document);
+ (uaString.includes("Mac") &&
+ typeof document !== "undefined" &&
+ "ontouchend" in document);
// keeping function so it can be mocked in test
-export const isBrave = () =>
- (navigator as any).brave?.isBrave?.name === "isBrave";
+export const isBrave = () => (ua as any)?.brave?.isBrave?.name === "isBrave";
// export const isMobile =
// isIOS ||
diff --git a/packages/common/src/utils.ts b/packages/common/src/utils.ts
index dcab0fcd56..be2e4b1384 100644
--- a/packages/common/src/utils.ts
+++ b/packages/common/src/utils.ts
@@ -48,12 +48,26 @@ 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);
+/**
+ * Resolves the window owning `target`, so that we keep working when the editor
+ * is rendered into another document. Accepts a `Document` as well, in which
+ * case its `defaultView` is used. Falls back to the module realm's window.
+ */
+export const getTargetWindow = (
+ target: Element | EventTarget | Document | null,
+): (Window & typeof globalThis) | null => {
+ const owner = target as
+ | (EventTarget & {
+ ownerDocument?: Document | null;
+ defaultView?: (Window & typeof globalThis) | null;
+ })
+ | null;
+ return (
+ owner?.ownerDocument?.defaultView ??
+ owner?.defaultView ??
+ (typeof window === "undefined" ? null : window)
+ );
+};
export const isToolIcon = (
target: Element | EventTarget | null,
@@ -181,12 +195,19 @@ export const debounce = <T extends any[]>(
};
// throttle callback to execute once per animation frame using the latest args
-export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
+export const throttleRAF = <T extends any[]>(
+ fn: (...args: T) => void,
+ ownerWindow?: Pick<Window, "requestAnimationFrame" | "cancelAnimationFrame">,
+) => {
let timerId: number | null = null;
let lastArgs: T | null = null;
+ // resolved lazily so module-scope callers work in environments without
+ // a global window (headless import)
+ const getOwnerWindow = () => ownerWindow ?? window;
+
const scheduleFunc = () => {
- timerId = window.requestAnimationFrame(() => {
+ timerId = getOwnerWindow().requestAnimationFrame(() => {
timerId = null;
const args = lastArgs;
lastArgs = null;
@@ -205,7 +226,7 @@ export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
};
ret.flush = () => {
if (timerId !== null) {
- cancelAnimationFrame(timerId);
+ getOwnerWindow().cancelAnimationFrame(timerId);
timerId = null;
}
if (lastArgs) {
@@ -216,7 +237,7 @@ export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
ret.cancel = () => {
lastArgs = null;
if (timerId !== null) {
- cancelAnimationFrame(timerId);
+ getOwnerWindow().cancelAnimationFrame(timerId);
timerId = null;
}
};
diff --git a/packages/element/src/__tests__/stickyNote.test.ts b/packages/element/src/__tests__/stickyNote.test.ts
index a8d8e58e81..aec3283724 100644
--- a/packages/element/src/__tests__/stickyNote.test.ts
+++ b/packages/element/src/__tests__/stickyNote.test.ts
@@ -48,6 +48,7 @@ import {
redrawTextBoundingBox,
} from "../textElement";
+import type { RenderEnvironment } from "../renderEnvironment";
import type {
ExcalidrawElement,
ExcalidrawStickyNoteElement,
@@ -712,6 +713,42 @@ describe("sticky note text layout", () => {
measure.mockRestore();
});
+ it("measures the fit through the given render environment", () => {
+ // the test-env canvas provider reports 10px per character; a host whose
+ // canvas measures three times as wide is observable in the fitted label
+ const perChar = 3;
+ const env: RenderEnvironment = {
+ createCanvas: () =>
+ ({
+ getContext: () => ({
+ font: "",
+ measureText: (text: string) => ({ width: text.length * perChar }),
+ }),
+ } as unknown as HTMLCanvasElement),
+ createImage: () => ({} as HTMLImageElement),
+ };
+ const { scene, stickyId, textId } = createStickyWithText("short");
+ const sticky = getSticky(scene, stickyId);
+ const text = getBoundText(scene, textId);
+ const defaultWidth = getStickyNoteLayout(sticky, text).text!.width;
+ expect(defaultWidth).toBe("short".length * 10);
+
+ // the pure layout
+ expect(
+ getStickyNoteLayout(sticky, text, { renderEnvironment: env }).text!.width,
+ ).toBe(defaultWidth * perChar);
+
+ // ...and both ways of applying it to a scene
+ updateStickyNoteLayout(sticky, scene, { renderEnvironment: env });
+ expect(getBoundText(scene, textId).width).toBe(defaultWidth * perChar);
+
+ redrawTextBoundingBox(getBoundText(scene, textId), sticky, scene);
+ expect(getBoundText(scene, textId).width).toBe(defaultWidth);
+
+ redrawTextBoundingBox(getBoundText(scene, textId), sticky, scene, env);
+ expect(getBoundText(scene, textId).width).toBe(defaultWidth * perChar);
+ });
+
it("honors a lowered ceiling even when the old fitted size still fits", () => {
const { scene, stickyId, textId } = createStickyWithText("short");
const sticky = getSticky(scene, stickyId);
diff --git a/packages/element/src/dragElements.ts b/packages/element/src/dragElements.ts
index 3f8c427b34..7678c0a18b 100644
--- a/packages/element/src/dragElements.ts
+++ b/packages/element/src/dragElements.ts
@@ -32,6 +32,7 @@ import {
isTextElement,
} from "./typeChecks";
+import type { RenderEnvironment } from "./renderEnvironment";
import type { Scene } from "./Scene";
import type { ExcalidrawElement, ExcalidrawTextElement } from "./types";
@@ -247,6 +248,7 @@ export const dragNewTextElement = ({
nextY,
zoom,
scene,
+ renderEnvironment,
informMutation = true,
}: {
newElement: ExcalidrawTextElement;
@@ -258,6 +260,7 @@ export const dragNewTextElement = ({
nextY?: number;
zoom: NormalizedZoomValue;
scene: Scene;
+ renderEnvironment?: RenderEnvironment;
informMutation?: boolean;
}) => {
const offset = pointerX - anchorX;
@@ -276,6 +279,7 @@ export const dragNewTextElement = ({
fontFamily: newElement.fontFamily,
}),
newElement.lineHeight,
+ renderEnvironment,
),
);
@@ -304,6 +308,7 @@ export const dragNewElement = ({
shouldResizeFromCenter,
zoom,
scene,
+ renderEnvironment,
widthAspectRatio = null,
originOffset = null,
informMutation = true,
@@ -320,6 +325,7 @@ export const dragNewElement = ({
shouldResizeFromCenter: boolean;
zoom: NormalizedZoomValue;
scene: Scene;
+ renderEnvironment?: RenderEnvironment;
/** whether to keep given aspect ratio when `isResizeWithSidesSameLength` is
true */
widthAspectRatio?: number | null;
@@ -367,6 +373,7 @@ export const dragNewElement = ({
nextY: originY + (originOffset?.y ?? 0),
zoom,
scene,
+ renderEnvironment,
informMutation,
});
return;
diff --git a/packages/element/src/embeddable.ts b/packages/element/src/embeddable.ts
index 8d938b5ad0..dceda3281e 100644
--- a/packages/element/src/embeddable.ts
+++ b/packages/element/src/embeddable.ts
@@ -12,6 +12,7 @@ import { newTextElement } from "./newElement";
import { wrapText } from "./textWrapping";
import { isIframeElement } from "./typeChecks";
+import type { RenderEnvironment } from "./renderEnvironment";
import type {
ExcalidrawIframeLikeElement,
IframeData,
@@ -401,6 +402,7 @@ export const getEmbedLink = (
export const createPlaceholderEmbeddableLabel = (
element: ExcalidrawIframeLikeElement,
+ renderEnvironment?: RenderEnvironment,
): NonDeletedExcalidrawElement => {
let text: string;
if (isIframeElement(element)) {
@@ -429,10 +431,11 @@ export const createPlaceholderEmbeddableLabel = (
backgroundColor: "transparent",
fontFamily,
fontSize,
- text: wrapText(text, fontString, element.width - 20),
+ text: wrapText(text, fontString, element.width - 20, renderEnvironment),
textAlign: "center",
verticalAlign: VERTICAL_ALIGN.MIDDLE,
angle: element.angle ?? 0,
+ renderEnvironment,
});
};
diff --git a/packages/element/src/image.ts b/packages/element/src/image.ts
index 562b489048..c28a270e7a 100644
--- a/packages/element/src/image.ts
+++ b/packages/element/src/image.ts
@@ -10,6 +10,7 @@ import type {
BinaryFiles,
} from "@excalidraw/excalidraw/types";
+import { getRenderEnvironment } from "./renderEnvironment";
import { isInitializedImageElement } from "./typeChecks";
import type {
@@ -18,9 +19,13 @@ import type {
InitializedExcalidrawImageElement,
} from "./types";
-export const loadHTMLImageElement = (dataURL: DataURL) => {
+export const loadHTMLImageElement = (
+ dataURL: DataURL,
+ createImage: () => HTMLImageElement = () =>
+ getRenderEnvironment().createImage(),
+) => {
return new Promise<HTMLImageElement>((resolve, reject) => {
- const image = new Image();
+ const image = createImage();
image.onload = () => {
resolve(image);
};
@@ -37,10 +42,14 @@ export const updateImageCache = async ({
fileIds,
files,
imageCache,
+ createImage,
}: {
fileIds: FileId[];
files: BinaryFiles;
imageCache: AppClassProperties["imageCache"];
+ /** creates images in the owner window so cross-document scenes keep
+ * runtime ownership of their HTMLImageElements */
+ createImage?: () => HTMLImageElement;
}) => {
const updatedFiles = new Map<FileId, true>();
const erroredFiles = new Map<FileId, true>();
@@ -57,7 +66,10 @@ export const updateImageCache = async ({
throw new Error("Only images can be added to ImageCache");
}
- const imagePromise = loadHTMLImageElement(fileData.dataURL);
+ const imagePromise = loadHTMLImageElement(
+ fileData.dataURL,
+ createImage,
+ );
const data = {
image: imagePromise,
mimeType: fileData.mimeType,
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index 8fa93b2de6..8732bd9ecf 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -86,6 +86,7 @@ export * from "./mutateElement";
export * from "./newElement";
export * from "./positionElementsOnGrid";
export * from "./renderElement";
+export * from "./renderEnvironment";
export * from "./resizeElements";
export * from "./resizeTest";
export * from "./Scene";
diff --git a/packages/element/src/newElement.ts b/packages/element/src/newElement.ts
index 02026067e1..75b98c9ced 100644
--- a/packages/element/src/newElement.ts
+++ b/packages/element/src/newElement.ts
@@ -34,6 +34,8 @@ import { wrapText } from "./textWrapping";
import { isLineElement } from "./typeChecks";
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type {
ExcalidrawElement,
ExcalidrawImageElement,
@@ -345,6 +347,7 @@ export const newTextElement = (
autoResize?: ExcalidrawTextElement["autoResize"];
labelPosition?: ExcalidrawTextElement["labelPosition"];
baseFontSize?: ExcalidrawTextElement["baseFontSize"];
+ renderEnvironment?: RenderEnvironment;
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawTextElement> => {
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
@@ -355,6 +358,7 @@ export const newTextElement = (
text,
getFontString({ fontFamily, fontSize }),
lineHeight,
+ opts.renderEnvironment,
);
const textAlign = opts.textAlign || DEFAULT_TEXT_ALIGN;
const verticalAlign = opts.verticalAlign || DEFAULT_VERTICAL_ALIGN;
@@ -396,6 +400,7 @@ const getAdjustedDimensions = (
nextText: string,
/** the width the text is to take regardless of its content */
nextFixedWidth?: number,
+ renderEnvironment?: RenderEnvironment,
): {
x: number;
y: number;
@@ -406,6 +411,7 @@ const getAdjustedDimensions = (
nextText,
getFontString(element),
element.lineHeight,
+ renderEnvironment,
);
// wrapped text
@@ -428,6 +434,7 @@ const getAdjustedDimensions = (
element.text,
getFontString(element),
element.lineHeight,
+ renderEnvironment,
);
const offsets = getTextElementPositionOffsets(element, {
width: nextWidth - prevMetrics.width,
@@ -542,6 +549,7 @@ export const refreshTextDimensions = (
* text that is already wider keeps growing.
*/
maxWidth?: number,
+ renderEnvironment?: RenderEnvironment,
) => {
if (textElement.isDeleted) {
return;
@@ -553,8 +561,11 @@ export const refreshTextDimensions = (
textElement.width <= maxWidth
) {
const font = getFontString(textElement);
- if (measureText(text, font, textElement.lineHeight).width > maxWidth) {
- const wrappedText = wrapText(text, font, maxWidth);
+ if (
+ measureText(text, font, textElement.lineHeight, renderEnvironment).width >
+ maxWidth
+ ) {
+ const wrappedText = wrapText(text, font, maxWidth, renderEnvironment);
return {
text: wrappedText,
autoResize: false,
@@ -563,6 +574,7 @@ export const refreshTextDimensions = (
elementsMap,
wrappedText,
maxWidth,
+ renderEnvironment,
),
};
}
@@ -574,9 +586,16 @@ export const refreshTextDimensions = (
container
? getBoundTextMaxWidth(container, textElement)
: textElement.width,
+ renderEnvironment,
);
}
- const dimensions = getAdjustedDimensions(textElement, elementsMap, text);
+ const dimensions = getAdjustedDimensions(
+ textElement,
+ elementsMap,
+ text,
+ undefined,
+ renderEnvironment,
+ );
return { text, ...dimensions };
};
diff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.ts
index 833743a217..8cea865371 100644
--- a/packages/element/src/renderElement.ts
+++ b/packages/element/src/renderElement.ts
@@ -46,6 +46,8 @@ import type {
InteractiveCanvasRenderConfig,
} from "@excalidraw/excalidraw/scene/types";
+import { getCreatePath, getRenderEnvironment } from "./renderEnvironment";
+
import { getElementAbsoluteCoords, getElementBounds } from "./bounds";
import { getUncroppedImageElement } from "./cropElement";
import { LinearElementEditor } from "./linearElementEditor";
@@ -78,6 +80,8 @@ import {
type StickyNotePathCommand,
} from "./stickyNote";
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type {
ExcalidrawElement,
ExcalidrawTextElement,
@@ -206,6 +210,9 @@ export interface ExcalidrawElementWithCanvas {
canvas: HTMLCanvasElement;
theme: AppState["theme"];
scale: number;
+ /** backing-store scale the bitmap was rasterized at, see StaticCanvasRenderConfig["scale"] */
+ deviceScale: number;
+ environment: RenderEnvironment;
zoomValue: AppState["zoom"]["value"];
canvasOffsetX: number;
canvasOffsetY: number;
@@ -217,6 +224,8 @@ const cappedElementCanvasSize = (
element: NonDeletedExcalidrawElement,
elementsMap: ElementsMap,
zoom: Zoom,
+ /** backing-store scale, see StaticCanvasRenderConfig["scale"] */
+ deviceScale: number,
): {
width: number;
height: number;
@@ -244,8 +253,8 @@ const cappedElementCanvasSize = (
? distance(y1, y2)
: element.height;
- let width = elementWidth * window.devicePixelRatio + padding * 2;
- let height = elementHeight * window.devicePixelRatio + padding * 2;
+ let width = elementWidth * deviceScale + padding * 2;
+ let height = elementHeight * deviceScale + padding * 2;
let scale: number = zoom.value;
@@ -275,7 +284,8 @@ const generateElementCanvas = (
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
): ExcalidrawElementWithCanvas | null => {
- const canvas = document.createElement("canvas");
+ const environment = getRenderEnvironment(renderConfig.renderEnvironment);
+ const canvas = environment.createCanvas();
const context = canvas.getContext("2d")!;
const padding = getCanvasPadding(element);
@@ -283,6 +293,7 @@ const generateElementCanvas = (
element,
elementsMap,
zoom,
+ renderConfig.scale,
);
if (!width || !height) {
@@ -299,24 +310,17 @@ const generateElementCanvas = (
const [x1, y1] = getElementAbsoluteCoords(element, elementsMap);
canvasOffsetX =
- element.x > x1
- ? distance(element.x, x1) * window.devicePixelRatio * scale
- : 0;
+ element.x > x1 ? distance(element.x, x1) * renderConfig.scale * scale : 0;
canvasOffsetY =
- element.y > y1
- ? distance(element.y, y1) * window.devicePixelRatio * scale
- : 0;
+ element.y > y1 ? distance(element.y, y1) * renderConfig.scale * scale : 0;
context.translate(canvasOffsetX, canvasOffsetY);
}
context.save();
context.translate(padding * scale, padding * scale);
- context.scale(
- window.devicePixelRatio * scale,
- window.devicePixelRatio * scale,
- );
+ context.scale(renderConfig.scale * scale, renderConfig.scale * scale);
const rc = rough.canvas(canvas);
@@ -329,6 +333,8 @@ const generateElementCanvas = (
canvas,
theme: appState.theme,
scale,
+ deviceScale: renderConfig.scale,
+ environment,
zoomValue: zoom.value,
canvasOffsetX,
canvasOffsetY,
@@ -340,28 +346,31 @@ const generateElementCanvas = (
export const DEFAULT_LINK_SIZE = 14;
-const IMAGE_PLACEHOLDER_IMG =
- typeof document !== "undefined"
- ? document.createElement("img")
- : ({ src: "" } as HTMLImageElement); // mock image element outside of browser
-
-IMAGE_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
+const IMAGE_PLACEHOLDER_SRC = `data:${MIME_TYPES.svg},${encodeURIComponent(
`<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="image" class="svg-inline--fa fa-image fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="#888" d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"></path></svg>`,
)}`;
-const IMAGE_ERROR_PLACEHOLDER_IMG =
- typeof document !== "undefined"
- ? document.createElement("img")
- : ({ src: "" } as HTMLImageElement); // mock image element outside of browser
-
-IMAGE_ERROR_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
+const IMAGE_ERROR_PLACEHOLDER_SRC = `data:${
+ MIME_TYPES.svg
+},${encodeURIComponent(
`<svg viewBox="0 0 668 668" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48ZM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56ZM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.81709 0 0 .81709 124.825 145.825)"/><path d="M256 8C119.034 8 8 119.033 8 256c0 136.967 111.034 248 248 248s248-111.034 248-248S392.967 8 256 8Zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676ZM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.30366 0 0 .30366 506.822 60.065)"/></svg>`,
)}`;
+/**
+ * Built lazily so that importing this module never touches `document`, and so
+ * that a custom render environment supplies the element.
+ */
+const getPlaceholderImg = (src: string, env: RenderEnvironment) => {
+ const img = env.createImage();
+ img.src = src;
+ return img;
+};
+
const drawImagePlaceholder = (
element: ExcalidrawImageElement,
context: CanvasRenderingContext2D,
theme: StaticCanvasRenderConfig["theme"],
+ env: RenderEnvironment,
) => {
context.fillStyle = theme === THEME.DARK ? "#2E2E2E" : "#E7E7E7";
context.fillRect(0, 0, element.width, element.height);
@@ -374,9 +383,12 @@ const drawImagePlaceholder = (
);
context.drawImage(
- element.status === "error"
- ? IMAGE_ERROR_PLACEHOLDER_IMG
- : IMAGE_PLACEHOLDER_IMG,
+ getPlaceholderImg(
+ element.status === "error"
+ ? IMAGE_ERROR_PLACEHOLDER_SRC
+ : IMAGE_PLACEHOLDER_SRC,
+ env,
+ ),
element.width / 2 - size / 2,
element.height / 2 - size / 2,
size,
@@ -428,6 +440,23 @@ const strokeStickyNoteEdge = (
context.restore();
};
+/**
+ * `save()`s the context around `draw`, restoring it even when `draw` throws:
+ * the scene renderer logs a failing element and carries on, and the element
+ * mustn't leave its transforms and clips behind for the next one.
+ */
+export const withSavedContext = (
+ context: CanvasRenderingContext2D,
+ draw: () => void,
+) => {
+ context.save();
+ try {
+ draw();
+ } finally {
+ context.restore();
+ }
+};
+
const drawElementOnCanvas = (
element: NonDeletedExcalidrawElement,
rc: RoughCanvas,
@@ -436,38 +465,37 @@ const drawElementOnCanvas = (
) => {
switch (element.type) {
case "stickynote": {
- context.save();
- context.fillStyle = `rgba(0, 0, 0, ${STICKY_NOTE_SHADOW_OPACITY})`;
- fillStickyNoteShape(
- context,
- getStickyNotePathCommands(element, { shadow: true }),
- );
+ withSavedContext(context, () => {
+ context.fillStyle = `rgba(0, 0, 0, ${STICKY_NOTE_SHADOW_OPACITY})`;
+ fillStickyNoteShape(
+ context,
+ getStickyNotePathCommands(element, { shadow: true }),
+ );
- const commands = getStickyNotePathCommands(element);
- context.fillStyle = applyDarkModeFilter(
- element.backgroundColor,
- renderConfig.theme === THEME.DARK,
- );
- fillStickyNoteShape(context, commands);
- strokeStickyNoteEdge(context, commands);
-
- // the label is absolute, so this cached canvas only goes stale at a
- // year boundary — and is regenerated on the next zoom, theme or
- // element change anyway
- const footer = getStickyNoteFooter(element);
- if (footer) {
- context.font = `${STICKY_NOTE_FOOTER.fontSize}px ${STICKY_NOTE_FOOTER.fontFamily}`;
- context.textAlign = "right";
- context.textBaseline = "alphabetic";
+ const commands = getStickyNotePathCommands(element);
context.fillStyle = applyDarkModeFilter(
- element.strokeColor,
+ element.backgroundColor,
renderConfig.theme === THEME.DARK,
);
- context.globalAlpha *= STICKY_NOTE_FOOTER.opacity;
- context.fillText(footer.text, footer.x, footer.y);
- }
-
- context.restore();
+ fillStickyNoteShape(context, commands);
+ strokeStickyNoteEdge(context, commands);
+
+ // the label is absolute, so this cached canvas only goes stale at a
+ // year boundary — and is regenerated on the next zoom, theme or
+ // element change anyway
+ const footer = getStickyNoteFooter(element);
+ if (footer) {
+ context.font = `${STICKY_NOTE_FOOTER.fontSize}px ${STICKY_NOTE_FOOTER.fontFamily}`;
+ context.textAlign = "right";
+ context.textBaseline = "alphabetic";
+ context.fillStyle = applyDarkModeFilter(
+ element.strokeColor,
+ renderConfig.theme === THEME.DARK,
+ );
+ context.globalAlpha *= STICKY_NOTE_FOOTER.opacity;
+ context.fillText(footer.text, footer.x, footer.y);
+ }
+ });
break;
}
case "rectangle":
@@ -495,180 +523,194 @@ const drawElementOnCanvas = (
}
case "freedraw": {
// Draw directly to canvas
- context.save();
-
- const shapes = ShapeCache.generateElementShape(element, renderConfig);
-
- for (const shape of shapes) {
- if (typeof shape === "string") {
- context.fillStyle = applyDarkModeFilter(
- element.strokeColor,
- renderConfig.theme === THEME.DARK,
- );
- context.fill(new Path2D(shape));
- } else {
- rc.draw(shape);
+ withSavedContext(context, () => {
+ const shapes = ShapeCache.generateElementShape(element, renderConfig);
+ const createPath = getCreatePath(renderConfig.renderEnvironment);
+
+ for (const shape of shapes) {
+ if (typeof shape === "string") {
+ context.fillStyle = applyDarkModeFilter(
+ element.strokeColor,
+ renderConfig.theme === THEME.DARK,
+ );
+ context.fill(createPath(shape));
+ } else {
+ rc.draw(shape);
+ }
}
- }
-
- context.restore();
+ });
break;
}
case "image": {
- context.save();
- const cacheEntry =
- element.fileId !== null
- ? renderConfig.imageCache.get(element.fileId)
- : null;
- const img = isInitializedImageElement(element)
- ? cacheEntry?.image
- : undefined;
-
- if (img != null && !(img instanceof Promise)) {
- if (element.roundness && context.roundRect) {
- context.beginPath();
- context.roundRect(
- 0,
- 0,
- element.width,
- element.height,
- getCornerRadius(Math.min(element.width, element.height), element),
- );
- context.clip();
- }
-
- const { x, y, width, height } = element.crop
- ? element.crop
- : {
- x: 0,
- y: 0,
- width: img.naturalWidth,
- height: img.naturalHeight,
- };
-
- const shouldInvertImage =
- renderConfig.theme === THEME.DARK &&
- cacheEntry?.mimeType === MIME_TYPES.svg;
-
- if (shouldInvertImage && isSafari) {
- const devicePixelRatio = window.devicePixelRatio || 1;
- const tempCanvas = document.createElement("canvas");
- tempCanvas.width = element.width * devicePixelRatio;
- tempCanvas.height = element.height * devicePixelRatio;
- const tempContext = tempCanvas.getContext("2d");
-
- if (tempContext) {
- tempContext.scale(devicePixelRatio, devicePixelRatio);
- tempContext.drawImage(
- img,
- x,
- y,
- width,
- height,
+ withSavedContext(context, () => {
+ const cacheEntry =
+ element.fileId !== null
+ ? renderConfig.imageCache.get(element.fileId)
+ : null;
+ const img = isInitializedImageElement(element)
+ ? cacheEntry?.image
+ : undefined;
+
+ if (img != null && !(img instanceof Promise)) {
+ if (element.roundness && context.roundRect) {
+ context.beginPath();
+ context.roundRect(
0,
0,
element.width,
element.height,
+ getCornerRadius(Math.min(element.width, element.height), element),
);
+ context.clip();
+ }
- const imageData = tempContext.getImageData(
- 0,
- 0,
- tempCanvas.width,
- tempCanvas.height,
- );
+ const { x, y, width, height } = element.crop
+ ? element.crop
+ : {
+ x: 0,
+ y: 0,
+ width: img.naturalWidth,
+ height: img.naturalHeight,
+ };
+
+ const shouldInvertImage =
+ renderConfig.theme === THEME.DARK &&
+ cacheEntry?.mimeType === MIME_TYPES.svg;
+
+ if (shouldInvertImage && isSafari) {
+ const devicePixelRatio = renderConfig.scale || 1;
+ const tempCanvas = getRenderEnvironment(
+ renderConfig.renderEnvironment,
+ ).createCanvas();
+ tempCanvas.width = element.width * devicePixelRatio;
+ tempCanvas.height = element.height * devicePixelRatio;
+ const tempContext = tempCanvas.getContext("2d");
+
+ if (tempContext) {
+ tempContext.scale(devicePixelRatio, devicePixelRatio);
+ tempContext.drawImage(
+ img,
+ x,
+ y,
+ width,
+ height,
+ 0,
+ 0,
+ element.width,
+ element.height,
+ );
- const data = imageData.data;
+ const imageData = tempContext.getImageData(
+ 0,
+ 0,
+ tempCanvas.width,
+ tempCanvas.height,
+ );
- for (let i = 0; i < data.length; i += 4) {
- data[i] = 255 - data[i];
- data[i + 1] = 255 - data[i + 1];
- data[i + 2] = 255 - data[i + 2];
+ const data = imageData.data;
+
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = 255 - data[i];
+ data[i + 1] = 255 - data[i + 1];
+ data[i + 2] = 255 - data[i + 2];
+ }
+
+ tempContext.putImageData(imageData, 0, 0);
+ context.drawImage(
+ tempCanvas,
+ 0,
+ 0,
+ tempCanvas.width,
+ tempCanvas.height,
+ 0,
+ 0,
+ element.width,
+ element.height,
+ );
+ }
+ } else {
+ if (shouldInvertImage) {
+ context.filter = DARK_THEME_FILTER;
}
- tempContext.putImageData(imageData, 0, 0);
context.drawImage(
- tempCanvas,
- 0,
- 0,
- tempCanvas.width,
- tempCanvas.height,
- 0,
+ img,
+ x,
+ y,
+ width,
+ height,
+ 0 /* hardcoded for the selection box*/,
0,
element.width,
element.height,
);
}
} else {
- if (shouldInvertImage) {
- context.filter = DARK_THEME_FILTER;
- }
-
- context.drawImage(
- img,
- x,
- y,
- width,
- height,
- 0 /* hardcoded for the selection box*/,
- 0,
- element.width,
- element.height,
+ drawImagePlaceholder(
+ element,
+ context,
+ renderConfig.theme,
+ getRenderEnvironment(renderConfig.renderEnvironment),
);
}
- } else {
- drawImagePlaceholder(element, context, renderConfig.theme);
- }
- context.restore();
+ });
break;
}
default: {
if (isTextElement(element)) {
const rtl = isRTL(element.text);
- const shouldTemporarilyAttach = rtl && !context.canvas.isConnected;
+ // NOTE: `isConnected === false` rather than `!isConnected` -- a
+ // non-DOM canvas (node-canvas et al) has no such property, and must
+ // not be handed to `document.body`
+ const shouldTemporarilyAttach =
+ rtl &&
+ context.canvas.isConnected === false &&
+ typeof document !== "undefined";
if (shouldTemporarilyAttach) {
// to correctly render RTL text mixed with LTR, we have to append it
// to the DOM
document.body.appendChild(context.canvas);
}
- context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
- context.save();
- context.font = getFontString(element);
- context.fillStyle = applyDarkModeFilter(
- element.strokeColor,
- renderConfig.theme === THEME.DARK,
- );
- context.textAlign = element.textAlign as CanvasTextAlign;
-
- // Canvas does not support multiline text by default
- const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
+ if (typeof context.canvas.setAttribute === "function") {
+ context.canvas.setAttribute("dir", rtl ? "rtl" : "ltr");
+ }
+ withSavedContext(context, () => {
+ context.font = getFontString(element);
+ context.fillStyle = applyDarkModeFilter(
+ element.strokeColor,
+ renderConfig.theme === THEME.DARK,
+ );
+ context.textAlign = element.textAlign as CanvasTextAlign;
- const horizontalOffset =
- element.textAlign === "center"
- ? element.width / 2
- : element.textAlign === "right"
- ? element.width
- : 0;
+ // Canvas does not support multiline text by default
+ const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
- const lineHeightPx = getLineHeightInPx(
- element.fontSize,
- element.lineHeight,
- );
+ const horizontalOffset =
+ element.textAlign === "center"
+ ? element.width / 2
+ : element.textAlign === "right"
+ ? element.width
+ : 0;
- const verticalOffset = getVerticalOffset(
- element.fontFamily,
- element.fontSize,
- lineHeightPx,
- );
+ const lineHeightPx = getLineHeightInPx(
+ element.fontSize,
+ element.lineHeight,
+ );
- for (let index = 0; index < lines.length; index++) {
- context.fillText(
- lines[index],
- horizontalOffset,
- index * lineHeightPx + verticalOffset,
+ const verticalOffset = getVerticalOffset(
+ element.fontFamily,
+ element.fontSize,
+ lineHeightPx,
);
- }
- context.restore();
+
+ for (let index = 0; index < lines.length; index++) {
+ context.fillText(
+ lines[index],
+ horizontalOffset,
+ index * lineHeightPx + verticalOffset,
+ );
+ }
+ });
if (shouldTemporarilyAttach) {
context.canvas.remove();
}
@@ -691,6 +733,9 @@ const generateElementWithCanvas = (
appState: StaticCanvasAppState | InteractiveCanvasAppState,
) => {
const zoom: Zoom = renderConfig ? appState.zoom : DEFAULT_ZOOM;
+ const renderEnvironment = getRenderEnvironment(
+ renderConfig.renderEnvironment,
+ );
const prevElementWithCanvas = elementWithCanvasCache.get(element);
const shouldRegenerateBecauseZoom =
prevElementWithCanvas &&
@@ -705,6 +750,8 @@ const generateElementWithCanvas = (
!prevElementWithCanvas ||
shouldRegenerateBecauseZoom ||
prevElementWithCanvas.theme !== appState.theme ||
+ prevElementWithCanvas.deviceScale !== renderConfig.scale ||
+ prevElementWithCanvas.environment !== renderEnvironment ||
prevElementWithCanvas.imageCrop !== imageCrop ||
prevElementWithCanvas.containingFrameOpacity !== containingFrameOpacity
) {
@@ -768,9 +815,10 @@ const drawElementFromCanvas = (
positionOffset: RenderPositionOffset,
) => {
const element = elementWithCanvas.element;
- // the ratio the cached bitmap was generated with (`generateElementCanvas`);
- // the blit's size math needs the same one, so it is not the owner window's
- const devicePixelRatio = window.devicePixelRatio;
+ // the backing-store scale the cached bitmap was generated with
+ // (`generateElementCanvas`); the blit's size math needs the same one, so it
+ // is the render config's, not the owner window's
+ const devicePixelRatio = renderConfig.scale;
const padding = getCanvasPadding(element);
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, allElementsMap);
const cx =
@@ -778,157 +826,166 @@ const drawElementFromCanvas = (
const cy =
((y1 + y2) / 2 + positionOffset.y + appState.scrollY) * devicePixelRatio;
- context.save();
- context.scale(1 / devicePixelRatio, 1 / devicePixelRatio);
+ withSavedContext(context, () => {
+ context.scale(1 / devicePixelRatio, 1 / devicePixelRatio);
- const boundTextElement = getBoundTextElement(element, allElementsMap);
+ const boundTextElement = getBoundTextElement(element, allElementsMap);
- if (isArrowElement(element) && boundTextElement) {
- // punch the label "hole" by clipping the arrow's blit out of the label
- // rect (even-odd) instead of baking a rotated arrow copy with a cleared
- // hole into a separate (`maxDim`-squared!) canvas. The hole stays
- // axis-aligned in scene space while the blit below rotates.
- const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
- boundTextElement,
- allElementsMap,
- );
- // generously covers the arrow's blit at any rotation
- const outerHalf =
- Math.max(distance(x1, x2), distance(y1, y2)) * devicePixelRatio +
- padding * 10;
- context.beginPath();
- context.rect(cx - outerHalf, cy - outerHalf, outerHalf * 2, outerHalf * 2);
- context.rect(
- (boundTextCx -
- boundTextElement.width / 2 -
- BOUND_TEXT_PADDING +
- positionOffset.x +
- appState.scrollX) *
- devicePixelRatio,
- (boundTextCy -
- boundTextElement.height / 2 -
- BOUND_TEXT_PADDING +
- positionOffset.y +
- appState.scrollY) *
- devicePixelRatio,
- (boundTextElement.width + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
- (boundTextElement.height + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
- );
- context.clip("evenodd");
- }
-
- // we translate context to element center so that rotation and scale
- // originates from the element center
- context.translate(cx, cy);
-
- context.rotate(element.angle);
+ if (isArrowElement(element) && boundTextElement) {
+ // punch the label "hole" by clipping the arrow's blit out of the label
+ // rect (even-odd) instead of baking a rotated arrow copy with a cleared
+ // hole into a separate (`maxDim`-squared!) canvas. The hole stays
+ // axis-aligned in scene space while the blit below rotates.
+ const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
+ boundTextElement,
+ allElementsMap,
+ );
+ // generously covers the arrow's blit at any rotation
+ const outerHalf =
+ Math.max(distance(x1, x2), distance(y1, y2)) * devicePixelRatio +
+ padding * 10;
+ context.beginPath();
+ context.rect(
+ cx - outerHalf,
+ cy - outerHalf,
+ outerHalf * 2,
+ outerHalf * 2,
+ );
+ context.rect(
+ (boundTextCx -
+ boundTextElement.width / 2 -
+ BOUND_TEXT_PADDING +
+ positionOffset.x +
+ appState.scrollX) *
+ devicePixelRatio,
+ (boundTextCy -
+ boundTextElement.height / 2 -
+ BOUND_TEXT_PADDING +
+ positionOffset.y +
+ appState.scrollY) *
+ devicePixelRatio,
+ (boundTextElement.width + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
+ (boundTextElement.height + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
+ );
+ context.clip("evenodd");
+ }
- if (
- "scale" in elementWithCanvas.element &&
- !isPendingImageElement(element, renderConfig)
- ) {
- context.scale(
- elementWithCanvas.element.scale[0],
- elementWithCanvas.element.scale[1],
- );
- }
+ // we translate context to element center so that rotation and scale
+ // originates from the element center
+ context.translate(cx, cy);
- // revert afterwards we don't have account for it during drawing
- context.translate(-cx, -cy);
-
- // the blit origin, in the space the context is in here (scaled by
- // canvas scale × zoom ÷ devicePixelRatio)
- let drawX =
- (x1 + positionOffset.x + appState.scrollX) * devicePixelRatio - padding;
- let drawY =
- (y1 + positionOffset.y + appState.scrollY) * devicePixelRatio - padding;
-
- const transform = context.getTransform();
-
- if (canSnapElement(element, appState)) {
- // blit the cached bitmap on whole device pixels. Nearest-neighbor at a
- // fractional offset is a pixel-exact copy shifted to the nearest pixel
- // — except at an exact half pixel, where a GPU-accelerated canvas
- // decides the rounding per scanline by float precision and a few rows
- // sample the neighboring row: doubled or broken strokes, varying with
- // scroll and position. A centered label lands on a half pixel
- // routinely.
- //
- // Done by moving the transform's origin onto the rounded device
- // position of the blit and drawing at (0, 0): the rotation, mirroring
- // and scale stay in `a`–`d` (a right angle keeps its scale in `b`/`c`),
- // and the origin is an exact integer even in the canvas's float32
- // matrix. Rounding `drawX` itself only lands on device pixels at 100%
- // zoom.
- const { a, b, c, d, e, f } = transform;
- const container = isTextElement(element)
- ? getContainerElement(element, allElementsMap)
- : null;
- // A bound label shares its unrotated container's offset and anchor.
- // Other bitmaps anchor to themselves.
- const anchor = container && !container.angle ? container : element;
- const anchorCoords =
- anchor === element
- ? null
- : getElementAbsoluteCoords(anchor, allElementsMap);
- const anchorSceneX = anchorCoords?.[0] ?? x1;
- const anchorSceneY = anchorCoords?.[1] ?? y1;
- const anchorPadding =
- anchor === element ? padding : getCanvasPadding(anchor);
- const anchorX =
- (anchorSceneX + positionOffset.x + appState.scrollX) * devicePixelRatio -
- anchorPadding;
- const anchorY =
- (anchorSceneY + positionOffset.y + appState.scrollY) * devicePixelRatio -
- anchorPadding;
-
- // Form the relative vector before introducing the scroll translation.
- const dx = (x1 - anchorSceneX) * devicePixelRatio + anchorPadding - padding;
- const dy = (y1 - anchorSceneY) * devicePixelRatio + anchorPadding - padding;
- context.setTransform(
- a,
- b,
- c,
- d,
- Math.round(a * anchorX + c * anchorY + e) +
- Math.round(a * dx + c * dy + SNAP_TIE_BIAS),
- Math.round(b * anchorX + d * anchorY + f) +
- Math.round(b * dx + d * dy + SNAP_TIE_BIAS),
- );
- drawX = 0;
- drawY = 0;
- }
+ context.rotate(element.angle);
- context.drawImage(
- elementWithCanvas.canvas!,
- drawX,
- drawY,
- elementWithCanvas.canvas!.width / elementWithCanvas.scale,
- elementWithCanvas.canvas!.height / elementWithCanvas.scale,
- );
+ if (
+ "scale" in elementWithCanvas.element &&
+ !isPendingImageElement(element, renderConfig)
+ ) {
+ context.scale(
+ elementWithCanvas.element.scale[0],
+ elementWithCanvas.element.scale[1],
+ );
+ }
- context.setTransform(transform);
+ // revert afterwards we don't have account for it during drawing
+ context.translate(-cx, -cy);
+
+ // the blit origin, in the space the context is in here (scaled by
+ // canvas scale × zoom ÷ devicePixelRatio)
+ let drawX =
+ (x1 + positionOffset.x + appState.scrollX) * devicePixelRatio - padding;
+ let drawY =
+ (y1 + positionOffset.y + appState.scrollY) * devicePixelRatio - padding;
+
+ const transform = context.getTransform();
+
+ if (canSnapElement(element, appState)) {
+ // blit the cached bitmap on whole device pixels. Nearest-neighbor at a
+ // fractional offset is a pixel-exact copy shifted to the nearest pixel
+ // — except at an exact half pixel, where a GPU-accelerated canvas
+ // decides the rounding per scanline by float precision and a few rows
+ // sample the neighboring row: doubled or broken strokes, varying with
+ // scroll and position. A centered label lands on a half pixel
+ // routinely.
+ //
+ // Done by moving the transform's origin onto the rounded device
+ // position of the blit and drawing at (0, 0): the rotation, mirroring
+ // and scale stay in `a`–`d` (a right angle keeps its scale in `b`/`c`),
+ // and the origin is an exact integer even in the canvas's float32
+ // matrix. Rounding `drawX` itself only lands on device pixels at 100%
+ // zoom.
+ const { a, b, c, d, e, f } = transform;
+ const container = isTextElement(element)
+ ? getContainerElement(element, allElementsMap)
+ : null;
+ // A bound label shares its unrotated container's offset and anchor.
+ // Other bitmaps anchor to themselves.
+ const anchor = container && !container.angle ? container : element;
+ const anchorCoords =
+ anchor === element
+ ? null
+ : getElementAbsoluteCoords(anchor, allElementsMap);
+ const anchorSceneX = anchorCoords?.[0] ?? x1;
+ const anchorSceneY = anchorCoords?.[1] ?? y1;
+ const anchorPadding =
+ anchor === element ? padding : getCanvasPadding(anchor);
+ const anchorX =
+ (anchorSceneX + positionOffset.x + appState.scrollX) *
+ devicePixelRatio -
+ anchorPadding;
+ const anchorY =
+ (anchorSceneY + positionOffset.y + appState.scrollY) *
+ devicePixelRatio -
+ anchorPadding;
+
+ // Form the relative vector before introducing the scroll translation.
+ const dx =
+ (x1 - anchorSceneX) * devicePixelRatio + anchorPadding - padding;
+ const dy =
+ (y1 - anchorSceneY) * devicePixelRatio + anchorPadding - padding;
+ context.setTransform(
+ a,
+ b,
+ c,
+ d,
+ Math.round(a * anchorX + c * anchorY + e) +
+ Math.round(a * dx + c * dy + SNAP_TIE_BIAS),
+ Math.round(b * anchorX + d * anchorY + f) +
+ Math.round(b * dx + d * dy + SNAP_TIE_BIAS),
+ );
+ drawX = 0;
+ drawY = 0;
+ }
- if (
- import.meta.env.VITE_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX ===
- "true" &&
- hasBoundTextElement(element)
- ) {
- const textElement = getBoundTextElement(
- element,
- allElementsMap,
- ) as ExcalidrawTextElementWithContainer;
- const coords = getContainerCoords(element);
- context.strokeStyle = "#c92a2a";
- context.lineWidth = 3;
- context.strokeRect(
- (coords.x + positionOffset.x + appState.scrollX) * devicePixelRatio,
- (coords.y + positionOffset.y + appState.scrollY) * devicePixelRatio,
- getBoundTextMaxWidth(element, textElement) * devicePixelRatio,
- getBoundTextMaxHeight(element, textElement) * devicePixelRatio,
+ context.drawImage(
+ elementWithCanvas.canvas!,
+ drawX,
+ drawY,
+ elementWithCanvas.canvas!.width / elementWithCanvas.scale,
+ elementWithCanvas.canvas!.height / elementWithCanvas.scale,
);
- }
- context.restore();
+
+ context.setTransform(transform);
+
+ if (
+ import.meta.env.VITE_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX ===
+ "true" &&
+ hasBoundTextElement(element)
+ ) {
+ const textElement = getBoundTextElement(
+ element,
+ allElementsMap,
+ ) as ExcalidrawTextElementWithContainer;
+ const coords = getContainerCoords(element);
+ context.strokeStyle = "#c92a2a";
+ context.lineWidth = 3;
+ context.strokeRect(
+ (coords.x + positionOffset.x + appState.scrollX) * devicePixelRatio,
+ (coords.y + positionOffset.y + appState.scrollY) * devicePixelRatio,
+ getBoundTextMaxWidth(element, textElement) * devicePixelRatio,
+ getBoundTextMaxHeight(element, textElement) * devicePixelRatio,
+ );
+ }
+ });
// Clear the nested element we appended to the DOM
};
@@ -1022,43 +1079,42 @@ const drawElement = (
case "magicframe":
case "frame": {
if (appState.frameRendering.enabled && appState.frameRendering.outline) {
- context.save();
- context.translate(
- element.x + appState.scrollX,
- element.y + appState.scrollY,
- );
- context.fillStyle = "rgba(0, 0, 200, 0.04)";
-
- context.lineWidth = FRAME_STYLE.strokeWidth / appState.zoom.value;
- context.strokeStyle = applyDarkModeFilter(
- FRAME_STYLE.strokeColor,
- appState.theme === THEME.DARK,
- );
-
- // TODO change later to only affect AI frames
- if (isMagicFrameElement(element)) {
- context.strokeStyle =
- appState.theme === THEME.LIGHT
- ? "#7affd7"
- : applyDarkModeFilter("#1d8264");
- }
+ withSavedContext(context, () => {
+ context.translate(
+ element.x + appState.scrollX,
+ element.y + appState.scrollY,
+ );
+ context.fillStyle = "rgba(0, 0, 200, 0.04)";
- if (FRAME_STYLE.radius && context.roundRect) {
- context.beginPath();
- context.roundRect(
- 0,
- 0,
- element.width,
- element.height,
- FRAME_STYLE.radius / appState.zoom.value,
+ context.lineWidth = FRAME_STYLE.strokeWidth / appState.zoom.value;
+ context.strokeStyle = applyDarkModeFilter(
+ FRAME_STYLE.strokeColor,
+ appState.theme === THEME.DARK,
);
- context.stroke();
- context.closePath();
- } else {
- context.strokeRect(0, 0, element.width, element.height);
- }
- context.restore();
+ // TODO change later to only affect AI frames
+ if (isMagicFrameElement(element)) {
+ context.strokeStyle =
+ appState.theme === THEME.LIGHT
+ ? "#7affd7"
+ : applyDarkModeFilter("#1d8264");
+ }
+
+ if (FRAME_STYLE.radius && context.roundRect) {
+ context.beginPath();
+ context.roundRect(
+ 0,
+ 0,
+ element.width,
+ element.height,
+ FRAME_STYLE.radius / appState.zoom.value,
+ );
+ context.stroke();
+ context.closePath();
+ } else {
+ context.strokeRect(0, 0, element.width, element.height);
+ }
+ });
}
break;
}
@@ -1069,12 +1125,12 @@ const drawElement = (
const cy = (y1 + y2) / 2 + appState.scrollY;
const shiftX = (x2 - x1) / 2 - (element.x - x1);
const shiftY = (y2 - y1) / 2 - (element.y - y1);
- context.save();
- context.translate(cx, cy);
- context.rotate(element.angle);
- context.translate(-shiftX, -shiftY);
- drawElementOnCanvas(element, rc, context, renderConfig);
- context.restore();
+ withSavedContext(context, () => {
+ context.translate(cx, cy);
+ context.rotate(element.angle);
+ context.translate(-shiftX, -shiftY);
+ drawElementOnCanvas(element, rc, context, renderConfig);
+ });
} else {
const elementWithCanvas = generateElementWithCanvas(
element,
@@ -1129,65 +1185,69 @@ const drawElement = (
shiftY = (y2 - y1) / 2 - (boundTextCoords.y - y1);
}
}
- context.save();
- context.translate(cx, cy);
-
- const boundTextElement = getBoundTextElement(element, elementsMap);
-
- if (isArrowElement(element) && boundTextElement) {
- // Draw arrow directly as vector (no temp-canvas bitmap blit which
- // introduces resampling blur). The label "hole" is cut by clipping
- // the arrow's own strokes out of the label rect (even-odd clip)
- // so that elements rendered beneath the arrow keep showing through
- // the gap.
- shiftX = element.width / 2 - (element.x - x1);
- shiftY = element.height / 2 - (element.y - y1);
-
- const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
- boundTextElement,
- elementsMap,
- );
- const holeX =
- boundTextCx -
- centerX -
- boundTextElement.width / 2 -
- BOUND_TEXT_PADDING;
- const holeY =
- boundTextCy -
- centerY -
- boundTextElement.height / 2 -
- BOUND_TEXT_PADDING;
- const holeWidth = boundTextElement.width + BOUND_TEXT_PADDING * 2;
- const holeHeight = boundTextElement.height + BOUND_TEXT_PADDING * 2;
-
- // generously covers the arrow's painted extent at any rotation
- // (the hole rect stays axis-aligned in scene space)
- const outerHalf =
- Math.max(distance(x1, x2), distance(y1, y2)) +
- getCanvasPadding(element) * 10;
-
- context.save();
- context.beginPath();
- context.rect(-outerHalf, -outerHalf, outerHalf * 2, outerHalf * 2);
- context.rect(holeX, holeY, holeWidth, holeHeight);
- context.clip("evenodd");
- context.rotate(element.angle);
- context.translate(-shiftX, -shiftY);
- drawElementOnCanvas(element, rc, context, renderConfig);
- context.restore();
- } else {
- context.rotate(element.angle);
+ withSavedContext(context, () => {
+ context.translate(cx, cy);
+
+ const boundTextElement = getBoundTextElement(element, elementsMap);
+
+ if (isArrowElement(element) && boundTextElement) {
+ // Draw arrow directly as vector (no temp-canvas bitmap blit which
+ // introduces resampling blur). The label "hole" is cut by clipping
+ // the arrow's own strokes out of the label rect (even-odd clip)
+ // so that elements rendered beneath the arrow keep showing through
+ // the gap.
+ shiftX = element.width / 2 - (element.x - x1);
+ shiftY = element.height / 2 - (element.y - y1);
+
+ const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
+ boundTextElement,
+ elementsMap,
+ );
+ const holeX =
+ boundTextCx -
+ centerX -
+ boundTextElement.width / 2 -
+ BOUND_TEXT_PADDING;
+ const holeY =
+ boundTextCy -
+ centerY -
+ boundTextElement.height / 2 -
+ BOUND_TEXT_PADDING;
+ const holeWidth = boundTextElement.width + BOUND_TEXT_PADDING * 2;
+ const holeHeight = boundTextElement.height + BOUND_TEXT_PADDING * 2;
+
+ // generously covers the arrow's painted extent at any rotation
+ // (the hole rect stays axis-aligned in scene space)
+ const outerHalf =
+ Math.max(distance(x1, x2), distance(y1, y2)) +
+ getCanvasPadding(element) * 10;
+
+ withSavedContext(context, () => {
+ context.beginPath();
+ context.rect(
+ -outerHalf,
+ -outerHalf,
+ outerHalf * 2,
+ outerHalf * 2,
+ );
+ context.rect(holeX, holeY, holeWidth, holeHeight);
+ context.clip("evenodd");
+ context.rotate(element.angle);
+ context.translate(-shiftX, -shiftY);
+ drawElementOnCanvas(element, rc, context, renderConfig);
+ });
+ } else {
+ context.rotate(element.angle);
+
+ if (element.type === "image") {
+ // note: scale must be applied *after* rotating
+ context.scale(element.scale[0], element.scale[1]);
+ }
- if (element.type === "image") {
- // note: scale must be applied *after* rotating
- context.scale(element.scale[0], element.scale[1]);
+ context.translate(-shiftX, -shiftY);
+ drawElementOnCanvas(element, rc, context, renderConfig);
}
-
- context.translate(-shiftX, -shiftY);
- drawElementOnCanvas(element, rc, context, renderConfig);
- }
-
- context.restore();
+ });
// not exporting → optimized rendering (cache & render from element
// canvases)
} else {
@@ -1238,44 +1298,44 @@ const drawElement = (
// crop: one bitmap, so cropping moves only the crop's edges over it
// (the cropped image's own bitmap snaps to whole pixels by its own
// corner, shifting the image by a pixel as that corner moves)
- context.save();
- context.globalAlpha = 0.1;
- drawElementFromCanvas(
- uncroppedElementCanvas,
- context,
- renderConfig,
- appState,
- allElementsMap,
- // The crop editor's uncropped preview stays at document coordinates.
- ZERO_RENDER_OFFSET,
- );
- context.restore();
+ withSavedContext(context, () => {
+ context.globalAlpha = 0.1;
+ drawElementFromCanvas(
+ uncroppedElementCanvas,
+ context,
+ renderConfig,
+ appState,
+ allElementsMap,
+ // The crop editor's uncropped preview stays at document coordinates.
+ ZERO_RENDER_OFFSET,
+ );
+ });
const [x1, y1, x2, y2] = getElementAbsoluteCoords(
elementWithCanvas.element,
allElementsMap,
);
- context.save();
- // (built in the element's rotated box: save/restore leaves the path)
- context.save();
- context.translate(
- (x1 + x2) / 2 + renderState.offset.x + appState.scrollX,
- (y1 + y2) / 2 + renderState.offset.y + appState.scrollY,
- );
- context.rotate(elementWithCanvas.element.angle);
- context.beginPath();
- context.rect((x1 - x2) / 2, (y1 - y2) / 2, x2 - x1, y2 - y1);
- context.restore();
- context.clip();
- drawElementFromCanvas(
- uncroppedElementCanvas,
- context,
- renderConfig,
- appState,
- allElementsMap,
- renderState.offset,
- );
- context.restore();
+ withSavedContext(context, () => {
+ // (built in the element's rotated box: save/restore leaves the path)
+ context.save();
+ context.translate(
+ (x1 + x2) / 2 + renderState.offset.x + appState.scrollX,
+ (y1 + y2) / 2 + renderState.offset.y + appState.scrollY,
+ );
+ context.rotate(elementWithCanvas.element.angle);
+ context.beginPath();
+ context.rect((x1 - x2) / 2, (y1 - y2) / 2, x2 - x1, y2 - y1);
+ context.restore();
+ context.clip();
+ drawElementFromCanvas(
+ uncroppedElementCanvas,
+ context,
+ renderConfig,
+ appState,
+ allElementsMap,
+ renderState.offset,
+ );
+ });
} else {
drawElementFromCanvas(
elementWithCanvas,
diff --git a/packages/element/src/renderEnvironment.ts b/packages/element/src/renderEnvironment.ts
new file mode 100644
index 0000000000..56cb7af50e
--- /dev/null
+++ b/packages/element/src/renderEnvironment.ts
@@ -0,0 +1,120 @@
+/**
+ * Host environment used by the renderer and export pipeline.
+ *
+ * The default is the browser's. An explicit environment (see
+ * `StaticCanvasRenderConfig["renderEnvironment"]`) scopes canvas and image
+ * creation to one render target -- e.g. the editor's owner window, so that
+ * one process can host editors in multiple realms (popouts, multi-tenant
+ * embeds), or an export running where `document`/`window` don't exist (Node
+ * with `node-canvas` / `@napi-rs/canvas`, passed in `config.environment`).
+ * There is deliberately no process-wide override: every render and export
+ * takes its environment explicitly.
+ *
+ * `document` is the DOM side of the same host: what SVG exports are built in
+ * (a DOM implementation such as `linkedom` under Node).
+ */
+import type { TextMetricsProvider } from "./textMeasurements";
+
+export type RenderEnvironment = {
+ /** Creates a blank canvas. Callers set `width`/`height` themselves. */
+ createCanvas: () => HTMLCanvasElement;
+ /**
+ * Creates an image to be decoded from a data URL and later used as a
+ * `drawImage` source.
+ *
+ * NOTE: typed as `HTMLImageElement` because the renderer is typed against
+ * the DOM lib throughout. Non-DOM implementations (node-canvas et al) need
+ * to cast; they must support `src`, `onload`, `onerror`, `naturalWidth`,
+ * `naturalHeight` and be accepted by their canvas' `drawImage`.
+ */
+ createImage: () => HTMLImageElement;
+ /**
+ * Creates a fillable path from an SVG path string -- freedraw elements are
+ * filled through one.
+ *
+ * Optional, because browsers always have the global `Path2D` this falls back
+ * to. A Node host MUST supply it (e.g. `@napi-rs/canvas`'s `Path2D`) or
+ * install `globalThis.Path2D` itself: Node has no such global, and without
+ * one every freedraw element fails to render.
+ */
+ createPath?: (svgPath: string) => Path2D;
+ /**
+ * The document SVG exports are built in: the editor's owner document, or
+ * outside the browser a DOM implementation's (e.g. `linkedom`).
+ *
+ * Optional; falls back to the global `document`.
+ */
+ document?: Document;
+ /**
+ * Measures text (line widths, for wrapping and layout).
+ *
+ * Optional; falls back to the global provider set with
+ * `setCustomTextMetricsProvider`, else to measuring on a canvas from
+ * `createCanvas`.
+ */
+ textMetrics?: TextMetricsProvider;
+};
+
+const defaultCreateCanvas = () => {
+ if (typeof document === "undefined") {
+ throw new Error(
+ "Excalidraw: creating a canvas needs a `document`, and this " +
+ "environment has none. Pass `createCanvas` in the export's " +
+ "`config.environment` (e.g. backed by `@napi-rs/canvas`), or, if the " +
+ "canvas was only needed to measure text, set a provider via " +
+ "`setCustomTextMetricsProvider`.",
+ );
+ }
+ return document.createElement("canvas");
+};
+const defaultCreateImage = () => {
+ if (typeof Image === "undefined") {
+ throw new Error(
+ "Excalidraw: decoding an image needs a global `Image`, and this " +
+ "environment has none. Pass `createImage` in the export's " +
+ "`config.environment` (e.g. `@napi-rs/canvas`'s `Image`).",
+ );
+ }
+ return new Image();
+};
+const defaultCreatePath = (svgPath: string) => {
+ if (typeof Path2D === "undefined") {
+ throw new Error(
+ "Excalidraw: rendering a freedraw element needs a `Path2D` " +
+ "implementation, and this environment has no global one. Pass " +
+ "`createPath` in the render environment (e.g. `@napi-rs/canvas`'s " +
+ "`Path2D`) or assign `globalThis.Path2D`.",
+ );
+ }
+ return new Path2D(svgPath);
+};
+
+/**
+ * NOTE: deliberately does NOT carry a devicePixelRatio. The backing-store scale
+ * is per-canvas, not per-process -- it is threaded through
+ * `StaticCanvasRenderConfig["scale"]`, which already carries the owner window's
+ * ratio (editor) or exportScale (export).
+ */
+const defaultEnvironment: RenderEnvironment = {
+ createCanvas: defaultCreateCanvas,
+ createImage: defaultCreateImage,
+ createPath: defaultCreatePath,
+};
+
+/**
+ * Resolves the host environment for a render: the explicitly scoped one (e.g.
+ * the editor's owner window, or an export's), else the browser default.
+ */
+export const getRenderEnvironment = (
+ env?: RenderEnvironment,
+): RenderEnvironment => env ?? defaultEnvironment;
+
+/**
+ * Resolves the path factory for a render. `createPath` is the one optional
+ * member of the contract, so this fills in the global-`Path2D` default for
+ * environments that omit it.
+ */
+export const getCreatePath = (
+ env?: RenderEnvironment,
+): ((svgPath: string) => Path2D) =>
+ getRenderEnvironment(env).createPath ?? defaultCreatePath;
diff --git a/packages/element/src/resizeElements.ts b/packages/element/src/resizeElements.ts
index 5e0e56b2cb..78aad8e163 100644
--- a/packages/element/src/resizeElements.ts
+++ b/packages/element/src/resizeElements.ts
@@ -49,6 +49,7 @@ import {
getApproxMinLineHeight,
} from "./textMeasurements";
import { wrapText } from "./textWrapping";
+
import {
isArrowElement,
isBindingElement,
@@ -69,6 +70,8 @@ import {
updateStickyNoteLayout,
} from "./stickyNote";
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type { Scene } from "./Scene";
import type { BoundingBox } from "./bounds";
@@ -103,6 +106,7 @@ export const transformElements = (
pointerY: number,
centerX: number,
centerY: number,
+ renderEnvironment?: RenderEnvironment,
): boolean => {
const elementsMap = scene.getNonDeletedElementsMap();
if (selectedElements.length === 1) {
@@ -148,6 +152,7 @@ export const transformElements = (
{
shouldMaintainAspectRatio,
shouldResizeFromCenter,
+ renderEnvironment,
},
);
}
@@ -198,6 +203,7 @@ export const transformElements = (
nextWidth,
nextHeight,
originalBoundingBox,
+ renderEnvironment,
},
);
@@ -322,6 +328,7 @@ export const resizeSingleTextElement = (
shouldResizeFromCenter: boolean,
nextWidth: number,
nextHeight: number,
+ renderEnvironment?: RenderEnvironment,
) => {
const elementsMap = scene.getNonDeletedElementsMap();
@@ -373,6 +380,7 @@ export const resizeSingleTextElement = (
fontFamily: element.fontFamily,
}),
element.lineHeight,
+ renderEnvironment,
);
const newWidth = Math.max(minWidth, nextWidth);
@@ -381,11 +389,13 @@ export const resizeSingleTextElement = (
element.originalText,
getFontString(element),
Math.abs(newWidth),
+ renderEnvironment,
);
const metrics = measureText(
text,
getFontString(element),
element.lineHeight,
+ renderEnvironment,
);
const newHeight = metrics.height;
@@ -747,10 +757,12 @@ export const resizeSingleElement = (
shouldInformMutation = true,
shouldMaintainAspectRatio = false,
shouldResizeFromCenter = false,
+ renderEnvironment,
}: {
shouldMaintainAspectRatio?: boolean;
shouldResizeFromCenter?: boolean;
shouldInformMutation?: boolean;
+ renderEnvironment?: RenderEnvironment;
} = {},
) => {
if (isTextElement(latestElement) && isTextElement(origElement)) {
@@ -762,6 +774,7 @@ export const resizeSingleElement = (
shouldResizeFromCenter,
nextWidth,
nextHeight,
+ renderEnvironment,
);
}
@@ -789,6 +802,7 @@ export const resizeSingleElement = (
width: getApproxMinLineWidth(
getFontString(boundTextElement),
boundTextElement.lineHeight,
+ renderEnvironment,
),
height: getApproxMinLineHeight(
boundTextElement.fontSize,
@@ -973,6 +987,7 @@ export const resizeSingleElement = (
),
// the arrow pass below is this function's — keep it single
bindings: false,
+ renderEnvironment,
});
} else {
if (boundTextElement && boundTextFont != null) {
@@ -987,6 +1002,7 @@ export const resizeSingleElement = (
shouldMaintainAspectRatio,
shouldResizeFromCenter,
flipFactorY < 0,
+ renderEnvironment,
);
}
@@ -1229,6 +1245,7 @@ export const resizeMultipleElements = (
nextHeight,
nextWidth,
originalBoundingBox,
+ renderEnvironment,
}: {
nextWidth?: number;
nextHeight?: number;
@@ -1238,6 +1255,7 @@ export const resizeMultipleElements = (
flipByY?: boolean;
// added to improve performance
originalBoundingBox?: BoundingBox;
+ renderEnvironment?: RenderEnvironment;
} = {},
) => {
// in the case of just flipping, there is no need to specify the next width and height
@@ -1557,6 +1575,7 @@ export const resizeMultipleElements = (
},
),
bindings: { simultaneouslyUpdated: elementsToUpdate },
+ renderEnvironment,
});
} else {
updateBoundElements(element, scene, {
@@ -1594,6 +1613,7 @@ export const resizeMultipleElements = (
true,
shouldResizeFromCenter,
flipByY,
+ renderEnvironment,
);
}
}
diff --git a/packages/element/src/stickyNote.ts b/packages/element/src/stickyNote.ts
index 9036136da0..f7ab36c5da 100644
--- a/packages/element/src/stickyNote.ts
+++ b/packages/element/src/stickyNote.ts
@@ -28,6 +28,7 @@ import { measureText } from "./textMeasurements";
import { wrapText } from "./textWrapping";
import { isStickyNoteElement, isTextElement } from "./typeChecks";
+import type { RenderEnvironment } from "./renderEnvironment";
import type { Scene } from "./Scene";
import type { VerticalResizeAnchor } from "./sizeHelpers";
import type { TransformHandleDirection } from "./transformHandles";
@@ -543,6 +544,12 @@ export type StickyNoteLayoutOpts = {
baseFontSize?: number;
/** the edge that stays put when the content correction changes the height */
anchor?: StickyNoteLayoutAnchor;
+ /**
+ * the host whose text metrics the fit measures with; omitted = the global
+ * environment. An editor passes its own so a note laid out in one window
+ * (or headlessly) is measured with that realm's fonts and canvas.
+ */
+ renderEnvironment?: RenderEnvironment;
};
export type StickyNoteLayout = {
@@ -677,6 +684,7 @@ export const getStickyNoteLayout = (
STICKY_NOTE_MIN_SIZE,
);
const anchor = opts.anchor ?? "top";
+ const { renderEnvironment } = opts;
if (!textElement) {
// an empty note sits at its base height
@@ -702,8 +710,12 @@ export const getStickyNoteLayout = (
const fit = (fontSize: number): FontFit => {
const font = getFontString({ fontFamily, fontSize });
- const text = wrapText(originalText, font, maxWidth);
- return { text, fontSize, ...measureText(text, font, lineHeight) };
+ const text = wrapText(originalText, font, maxWidth, renderEnvironment);
+ return {
+ text,
+ fontSize,
+ ...measureText(text, font, lineHeight, renderEnvironment),
+ };
};
const isBlank = !originalText.trim();
@@ -715,6 +727,7 @@ export const getStickyNoteLayout = (
"",
getFontString({ fontFamily, fontSize: baseFontSize }),
lineHeight,
+ renderEnvironment,
),
}
: fitStickyNoteFont(fit, {
@@ -913,7 +926,10 @@ const hasStickyNoteLayoutInputChanged = (
export const relayoutStickyNotes = <T extends ExcalidrawElement>(
elements: readonly T[],
affectedIds: ReadonlySet<ExcalidrawElement["id"]>,
- opts?: { prevElementsMap?: ElementsMap },
+ opts?: {
+ prevElementsMap?: ElementsMap;
+ renderEnvironment?: RenderEnvironment;
+ },
): readonly T[] => {
if (!affectedIds.size) {
return elements;
@@ -952,7 +968,9 @@ export const relayoutStickyNotes = <T extends ExcalidrawElement>(
) {
continue;
}
- const layout = getStickyNoteLayout(container, textElement);
+ const layout = getStickyNoteLayout(container, textElement, {
+ renderEnvironment: opts?.renderEnvironment,
+ });
const nextContainer = newElementWith(container, layout.container);
if (nextContainer !== container) {
replacements.set(id, nextContainer as unknown as T);
diff --git a/packages/element/src/textElement.ts b/packages/element/src/textElement.ts
index 64c05c1313..843b5d0f3a 100644
--- a/packages/element/src/textElement.ts
+++ b/packages/element/src/textElement.ts
@@ -26,6 +26,7 @@ import { getPositionAfterHeightChange } from "./sizeHelpers";
import { updateStickyNoteLayout } from "./stickyNote";
import { measureText } from "./textMeasurements";
import { wrapText } from "./textWrapping";
+
import {
isBoundToContainer,
isArrowElement,
@@ -35,6 +36,8 @@ import {
import { isNonDeletedElement } from ".";
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type { Scene } from "./Scene";
import type { MaybeTransformHandleType } from "./transformHandles";
@@ -52,6 +55,7 @@ export const redrawTextBoundingBox = (
textElement: ExcalidrawTextElement,
container: ExcalidrawElement | null,
scene: Scene,
+ renderEnvironment?: RenderEnvironment,
) => {
const elementsMap = scene.getNonDeletedElementsMap();
@@ -59,7 +63,10 @@ export const redrawTextBoundingBox = (
// the sticky fit owns both halves (label + note geometry). `textElement`
// may be an uncommitted clone (font actions clone before install), so it
// is passed explicitly instead of looked up in the scene
- updateStickyNoteLayout(container, scene, { text: textElement });
+ updateStickyNoteLayout(container, scene, {
+ text: textElement,
+ renderEnvironment,
+ });
return;
}
@@ -95,6 +102,7 @@ export const redrawTextBoundingBox = (
textElement.originalText,
getFontString(textElement),
maxWidth,
+ renderEnvironment,
);
}
@@ -102,6 +110,7 @@ export const redrawTextBoundingBox = (
boundTextUpdates.text,
getFontString(textElement),
textElement.lineHeight,
+ renderEnvironment,
);
// Note: only update width for unwrapped text and bound texts (which always have autoResize set to true)
@@ -159,11 +168,15 @@ export const handleBindTextResize = (
shouldMaintainAspectRatio = false,
shouldResizeFromCenter = false,
flipByY = false,
+ renderEnvironment?: RenderEnvironment,
) => {
if (isStickyNoteElement(container)) {
// resize callers pass their intents to `updateStickyNoteLayout` directly
// and own the bound-arrow pass; this is the fallback for generic callers
- updateStickyNoteLayout(container, scene, { bindings: false });
+ updateStickyNoteLayout(container, scene, {
+ bindings: false,
+ renderEnvironment,
+ });
return;
}
const elementsMap = scene.getNonDeletedElementsMap();
@@ -193,12 +206,14 @@ export const handleBindTextResize = (
textElement.originalText,
getFontString(textElement),
maxWidth,
+ renderEnvironment,
);
}
const metrics = measureText(
text,
getFontString(textElement),
textElement.lineHeight,
+ renderEnvironment,
);
nextHeight = metrics.height;
nextWidth = metrics.width;
diff --git a/packages/element/src/textMeasurements.ts b/packages/element/src/textMeasurements.ts
index 5e790261d1..f5081f3eab 100644
--- a/packages/element/src/textMeasurements.ts
+++ b/packages/element/src/textMeasurements.ts
@@ -7,12 +7,17 @@ import {
normalizeEOL,
} from "@excalidraw/common";
+import { getRenderEnvironment } from "./renderEnvironment";
+
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type { FontString, ExcalidrawTextElement } from "./types";
export const measureText = (
text: string,
font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ env?: RenderEnvironment,
) => {
const _text = text
.split("\n")
@@ -22,7 +27,7 @@ export const measureText = (
.join("\n");
const fontSize = parseFloat(font);
const height = getTextHeight(_text, fontSize, lineHeight);
- const width = getTextWidth(_text, font);
+ const width = getTextWidth(_text, font, env);
return { width, height };
};
@@ -32,11 +37,13 @@ const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
export const getApproxMinLineWidth = (
font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ env?: RenderEnvironment,
) => {
- const maxCharWidth = getMaxCharWidth(font);
+ const maxCharWidth = getMaxCharWidth(font, env);
if (maxCharWidth === 0) {
return (
- measureText(DUMMY_TEXT.split("").join("\n"), font, lineHeight).width +
+ measureText(DUMMY_TEXT.split("").join("\n"), font, lineHeight, env)
+ .width +
BOUND_TEXT_PADDING * 2
);
}
@@ -46,8 +53,9 @@ export const getApproxMinLineWidth = (
export const getMinTextElementWidth = (
font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ env?: RenderEnvironment,
) => {
- return measureText("", font, lineHeight).width + BOUND_TEXT_PADDING * 2;
+ return measureText("", font, lineHeight, env).width + BOUND_TEXT_PADDING * 2;
};
export const isMeasureTextSupported = () => {
@@ -103,15 +111,30 @@ export const getApproxMinLineHeight = (
return getLineHeightInPx(fontSize, lineHeight) + BOUND_TEXT_PADDING * 2;
};
-let textMetricsProvider: TextMetricsProvider | undefined;
+let customTextMetricsProvider: TextMetricsProvider | undefined;
+/**
+ * The lazily-built canvas-backed default provider per environment -- each
+ * environment (e.g. each editor's owner window) measures on a canvas of its
+ * own. A custom provider (the environment's `textMetrics`, or the global one
+ * set with `setCustomTextMetricsProvider`) replaces it.
+ */
+const defaultTextMetricsProviders = new WeakMap<
+ RenderEnvironment,
+ TextMetricsProvider
+>();
/**
- * Set a custom text metrics provider.
+ * Set a custom text metrics provider, for all text measured in an environment
+ * without its own (`RenderEnvironment["textMetrics"]`) -- e.g. elements
+ * created outside the editor, on a server. Pass `undefined` to go back to
+ * measuring on a canvas.
*
* Useful for overriding the width calculation algorithm where canvas API is not available / desired.
*/
-export const setCustomTextMetricsProvider = (provider: TextMetricsProvider) => {
- textMetricsProvider = provider;
+export const setCustomTextMetricsProvider = (
+ provider: TextMetricsProvider | undefined,
+) => {
+ customTextMetricsProvider = provider;
};
export interface TextMetricsProvider {
@@ -121,8 +144,8 @@ export interface TextMetricsProvider {
class CanvasTextMetricsProvider implements TextMetricsProvider {
private canvas: HTMLCanvasElement;
- constructor() {
- this.canvas = document.createElement("canvas");
+ constructor(env: RenderEnvironment) {
+ this.canvas = getRenderEnvironment(env).createCanvas();
}
/**
@@ -149,19 +172,40 @@ class CanvasTextMetricsProvider implements TextMetricsProvider {
}
}
-export const getLineWidth = (text: string, font: FontString) => {
- if (!textMetricsProvider) {
- textMetricsProvider = new CanvasTextMetricsProvider();
+const getDefaultTextMetricsProvider = (
+ env: RenderEnvironment | undefined,
+): TextMetricsProvider => {
+ const resolvedEnv = getRenderEnvironment(env);
+ let provider = defaultTextMetricsProviders.get(resolvedEnv);
+ if (!provider) {
+ provider = new CanvasTextMetricsProvider(resolvedEnv);
+ defaultTextMetricsProviders.set(resolvedEnv, provider);
}
+ return provider;
+};
- return textMetricsProvider.getLineWidth(text, font);
+export const getLineWidth = (
+ text: string,
+ font: FontString,
+ env?: RenderEnvironment,
+) => {
+ const resolvedEnv = getRenderEnvironment(env);
+ const provider =
+ resolvedEnv.textMetrics ??
+ customTextMetricsProvider ??
+ getDefaultTextMetricsProvider(resolvedEnv);
+ return provider.getLineWidth(text, font);
};
-export const getTextWidth = (text: string, font: FontString) => {
+export const getTextWidth = (
+ text: string,
+ font: FontString,
+ env?: RenderEnvironment,
+) => {
const lines = splitIntoLines(text);
let width = 0;
lines.forEach((line) => {
- width = Math.max(width, getLineWidth(line, font));
+ width = Math.max(width, getLineWidth(line, font, env));
});
return width;
@@ -177,27 +221,47 @@ export const getTextHeight = (
};
export const charWidth = (() => {
- const cachedCharWidth: { [key: FontString]: Array<number> } = {};
+ // one env's metrics at a time: two realms measure the same font string
+ // differently, so a different env drops the cache rather than mixing them.
+ // Held weakly -- an editor's env closes over its owner window, and a strong
+ // ref here would pin a closed popout's realm for the life of the process.
+ let cachedEnv: WeakRef<RenderEnvironment> | undefined;
+ let cachedCharWidth: { [key: FontString]: Array<number> } = {};
+
+ const isCachedEnv = (resolvedEnv: RenderEnvironment) =>
+ cachedEnv?.deref() === resolvedEnv;
+
+ const selectEnv = (env: RenderEnvironment | undefined) => {
+ const resolvedEnv = getRenderEnvironment(env);
+ if (!isCachedEnv(resolvedEnv)) {
+ cachedEnv = new WeakRef(resolvedEnv);
+ cachedCharWidth = {};
+ }
+ };
- const calculate = (char: string, font: FontString) => {
+ const calculate = (
+ char: string,
+ font: FontString,
+ env?: RenderEnvironment,
+ ) => {
+ selectEnv(env);
const unicode = char.charCodeAt(0);
if (!cachedCharWidth[font]) {
cachedCharWidth[font] = [];
}
- if (!cachedCharWidth[font][unicode]) {
- const width = getLineWidth(char, font);
- cachedCharWidth[font][unicode] = width;
+ if (cachedCharWidth[font][unicode] === undefined) {
+ cachedCharWidth[font][unicode] = getLineWidth(char, font, env);
}
-
return cachedCharWidth[font][unicode];
};
- const getCache = (font: FontString) => {
- return cachedCharWidth[font];
- };
+ const getCache = (font: FontString, env?: RenderEnvironment) =>
+ isCachedEnv(getRenderEnvironment(env)) ? cachedCharWidth[font] : undefined;
+ // dropped rather than emptied, so that the approximation helpers fall back
+ // to measuring instead of reducing over an empty array
const clearCache = (font: FontString) => {
- cachedCharWidth[font] = [];
+ delete cachedCharWidth[font];
};
return {
@@ -207,8 +271,8 @@ export const charWidth = (() => {
};
})();
-export const getMinCharWidth = (font: FontString) => {
- const cache = charWidth.getCache(font);
+export const getMinCharWidth = (font: FontString, env?: RenderEnvironment) => {
+ const cache = charWidth.getCache(font, env);
if (!cache) {
return 0;
}
@@ -217,8 +281,8 @@ export const getMinCharWidth = (font: FontString) => {
return Math.min(...cacheWithOutEmpty);
};
-export const getMaxCharWidth = (font: FontString) => {
- const cache = charWidth.getCache(font);
+export const getMaxCharWidth = (font: FontString, env?: RenderEnvironment) => {
+ const cache = charWidth.getCache(font, env);
if (!cache) {
return 0;
}
diff --git a/packages/element/src/textWrapping.ts b/packages/element/src/textWrapping.ts
index b580f52ed1..7f5064456c 100644
--- a/packages/element/src/textWrapping.ts
+++ b/packages/element/src/textWrapping.ts
@@ -2,6 +2,7 @@ import { isDevEnv, isTestEnv } from "@excalidraw/common";
import { charWidth, getLineWidth } from "./textMeasurements";
+import type { RenderEnvironment } from "./renderEnvironment";
import type { FontString } from "./types";
/**
@@ -106,7 +107,7 @@ const CJK = {
* ↑ BREAK AFTER "」"
*/
// eslint-disable-next-line prettier/prettier
- OPENING:/([{〈《⦅「「『【〖〔〘〚<〝/u,
+ OPENING: /([{〈《⦅「「『【〖〔〘〚<〝/u,
CLOSING: /)]}〉》⦆」」』】〗〕〙〛>。.,、〟‥?!:;・〜〞/u,
/**
* Currency symbols break before, not after
@@ -398,8 +399,9 @@ export const wrapText = (
text: string,
font: FontString,
maxWidth: number,
+ env?: RenderEnvironment,
): string => {
- return getWrappedTextLines(text, font, maxWidth)
+ return getWrappedTextLines(text, font, maxWidth, env)
.map((line) => line.text)
.join("\n");
};
@@ -447,6 +449,7 @@ export const getWrappedTextLines = (
text: string,
font: FontString,
maxWidth: number,
+ env?: RenderEnvironment,
): WrappedTextLine[] => {
// if maxWidth is not finite or NaN which can happen in case of bugs in
// computation, we need to make sure we don't continue as we'll end up
@@ -459,7 +462,7 @@ export const getWrappedTextLines = (
let offset = 0;
for (const originalLine of text.split("\n")) {
- const originalLineWidth = getLineWidth(originalLine, font);
+ const originalLineWidth = getLineWidth(originalLine, font, env);
if (originalLineWidth <= maxWidth) {
lines.push({
@@ -468,7 +471,7 @@ export const getWrappedTextLines = (
end: offset + originalLine.length,
});
} else {
- lines.push(...wrapLine(originalLine, font, maxWidth, offset));
+ lines.push(...wrapLine(originalLine, font, maxWidth, offset, env));
}
offset += originalLine.length + 1;
@@ -488,6 +491,7 @@ const wrapLine = (
font: FontString,
maxWidth: number,
lineStart: number,
+ env?: RenderEnvironment,
): WrappedTextLine[] => {
const lines: WrappedTextLine[] = [];
const tokens = parseTokens(line);
@@ -508,8 +512,8 @@ const wrapLine = (
// cache single codepoint whitespace, CJK or emoji width calc. as kerning should not apply here
const testLineWidth = isSingleCharacter(token)
- ? currentLineWidth + charWidth.calculate(token, font)
- : getLineWidth(testLine, font);
+ ? currentLineWidth + charWidth.calculate(token, font, env)
+ : getLineWidth(testLine, font, env);
// build up the current line, skipping length check for possibly trailing whitespaces
if (/\s/.test(token) || testLineWidth <= maxWidth) {
@@ -526,7 +530,7 @@ const wrapLine = (
// current line is empty => just the token (word) is longer than `maxWidth` and needs to be wrapped
if (!currentLine) {
- const wrappedWord = wrapWord(token, font, maxWidth, tokenStart);
+ const wrappedWord = wrapWord(token, font, maxWidth, tokenStart, env);
const trailingLine = wrappedWord[wrappedWord.length - 1] ?? {
text: "",
start: tokenStart,
@@ -540,7 +544,7 @@ const wrapLine = (
currentLine = trailingLine.text;
currentLineStart = trailingLine.start;
currentLineEnd = trailingLine.end;
- currentLineWidth = getLineWidth(trailingLine.text, font);
+ currentLineWidth = getLineWidth(trailingLine.text, font, env);
tokenOffset = tokenEnd;
tokenIndex++;
} else {
@@ -565,6 +569,7 @@ const wrapLine = (
currentLineEnd,
font,
maxWidth,
+ env,
);
lines.push(trailingLine);
}
@@ -580,6 +585,7 @@ const wrapWord = (
font: FontString,
maxWidth: number,
wordStart: number,
+ env?: RenderEnvironment,
): WrappedTextLine[] => {
// multi-codepoint emojis are already broken apart and shouldn't be broken further
if (getEmojiRegex().test(word)) {
@@ -606,7 +612,7 @@ const wrapWord = (
for (const char of chars) {
const charStart = offset;
const charEnd = charStart + char.length;
- const _charWidth = charWidth.calculate(char, font);
+ const _charWidth = charWidth.calculate(char, font, env);
const testLineWidth = currentLineWidth + _charWidth;
if (testLineWidth <= maxWidth) {
@@ -658,8 +664,9 @@ const trimLine = (
end: number,
font: FontString,
maxWidth: number,
+ env?: RenderEnvironment,
): WrappedTextLine => {
- const shouldTrimWhitespaces = getLineWidth(line, font) > maxWidth;
+ const shouldTrimWhitespaces = getLineWidth(line, font, env) > maxWidth;
if (!shouldTrimWhitespaces) {
return {
@@ -676,10 +683,10 @@ const trimLine = (
"",
];
- let trimmedLineWidth = getLineWidth(trimmedLine, font);
+ let trimmedLineWidth = getLineWidth(trimmedLine, font, env);
for (const whitespace of Array.from(whitespaces)) {
- const _charWidth = charWidth.calculate(whitespace, font);
+ const _charWidth = charWidth.calculate(whitespace, font, env);
const testLineWidth = trimmedLineWidth + _charWidth;
if (testLineWidth > maxWidth) {
diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.ts
index 2e5f401963..d14ba3214b 100644
--- a/packages/element/src/transform.ts
+++ b/packages/element/src/transform.ts
@@ -56,6 +56,8 @@ import { getCommonBounds } from "./bounds";
import { Scene } from "./Scene";
+import type { RenderEnvironment } from "./renderEnvironment";
+
import type {
ExcalidrawArrowElement,
ExcalidrawBindableElement,
@@ -260,6 +262,7 @@ const bindTextToContainer = (
container: ExcalidrawElement,
textProps: { text: string } & FragmentConstructorOpts,
scene: Scene,
+ renderEnvironment?: RenderEnvironment,
) => {
// a note and its label share one ink: a label that sets its own color
// gives it to the note (the footer paints with it); transparent falls
@@ -282,6 +285,7 @@ const bindTextToContainer = (
labelPosition: isArrowElement(container)
? DEFAULT_BOUND_TEXT_LABEL_POSITION
: null,
+ renderEnvironment,
});
Object.assign(container, {
@@ -294,7 +298,7 @@ const bindTextToContainer = (
: null),
});
- redrawTextBoundingBox(textElement, container, scene);
+ redrawTextBoundingBox(textElement, container, scene, renderEnvironment);
return [container, textElement] as const;
};
@@ -306,6 +310,7 @@ const bindLinearElementToElement = (
elementStore: ElementStore,
scene: Scene,
zoom: Zoom,
+ renderEnvironment?: RenderEnvironment,
): {
linearElement: ExcalidrawLinearElement;
startBoundElement?: ExcalidrawElement;
@@ -355,6 +360,7 @@ const bindLinearElementToElement = (
...existingElement,
...start,
text,
+ renderEnvironment,
});
// to position the text correctly when coordinates not provided
Object.assign(startBoundElement, {
@@ -433,6 +439,7 @@ const bindLinearElementToElement = (
...existingElement,
...end,
text,
+ renderEnvironment,
});
// to position the text correctly when coordinates not provided
Object.assign(endBoundElement, {
@@ -571,7 +578,7 @@ class ElementStore {
export const convertToExcalidrawElements = (
elementsSkeleton: ExcalidrawElementSkeleton[] | null,
- opts?: { regenerateIds: boolean },
+ opts?: { regenerateIds?: boolean; renderEnvironment?: RenderEnvironment },
) => {
if (!elementsSkeleton) {
return [];
@@ -652,6 +659,7 @@ export const convertToExcalidrawElements = (
normalizedText,
getFontString({ fontFamily, fontSize }),
lineHeight,
+ opts?.renderEnvironment,
);
excalidrawElement = newTextElement({
@@ -660,6 +668,7 @@ export const convertToExcalidrawElements = (
fontFamily,
fontSize,
...element,
+ renderEnvironment: opts?.renderEnvironment,
});
break;
}
@@ -759,6 +768,7 @@ export const convertToExcalidrawElements = (
excalidrawElement,
element?.label,
scene,
+ opts?.renderEnvironment,
);
elementStore.add(container);
elementStore.add(text);
@@ -788,6 +798,7 @@ export const convertToExcalidrawElements = (
elementStore,
scene,
DEFAULT_ZOOM,
+ opts?.renderEnvironment,
);
container = linearElement;
elementStore.add(linearElement);
@@ -814,6 +825,7 @@ export const convertToExcalidrawElements = (
elementStore,
scene,
DEFAULT_ZOOM,
+ opts?.renderEnvironment,
);
elementStore.add(linearElement);
diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsx
index b0a23cf55b..acbf649d42 100644
--- a/packages/element/tests/linearElementEditor.test.tsx
+++ b/packages/element/tests/linearElementEditor.test.tsx
@@ -1595,6 +1595,7 @@ describe("Test Linear Elements", () => {
false,
false,
false,
+ h.app.renderEnvironment,
);
expect(
wrapText(
diff --git a/packages/element/tests/renderEnvironmentCaches.test.ts b/packages/element/tests/renderEnvironmentCaches.test.ts
new file mode 100644
index 0000000000..37f2416f16
--- /dev/null
+++ b/packages/element/tests/renderEnvironmentCaches.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect } from "vitest";
+
+import {
+ charWidth,
+ getMaxCharWidth,
+ getTextWidth,
+} from "../src/textMeasurements";
+
+import type { RenderEnvironment } from "../src/renderEnvironment";
+import type { FontString } from "../src/types";
+
+const FONT = "20px Excalifont" as FontString;
+
+// in the test env the canvas provider multiplies the mocked advance width
+// (character count) by 10, so an env measuring different widths is observable
+const makeEnv = (perChar: number): RenderEnvironment => ({
+ createCanvas: () =>
+ ({
+ getContext: () => ({
+ font: "",
+ measureText: (text: string) => ({ width: text.length * perChar }),
+ }),
+ } as unknown as HTMLCanvasElement),
+ createImage: () => ({} as HTMLImageElement),
+});
+
+/**
+ * Everything the renderer memoizes per host realm (text metrics providers,
+ * element bitmaps, link icons) is keyed on the render environment's identity,
+ * so a swap must invalidate rather than serve one realm's pixels to another.
+ */
+describe("render environment cache invalidation", () => {
+ it("builds a text metrics provider per environment", () => {
+ const makeCountingEnv = () => {
+ const canvases: HTMLCanvasElement[] = [];
+ const env: RenderEnvironment = {
+ createCanvas: () => {
+ const canvas = document.createElement("canvas");
+ canvases.push(canvas);
+ return canvas;
+ },
+ createImage: () => ({} as HTMLImageElement),
+ };
+ return { env, canvases };
+ };
+ const first = makeCountingEnv();
+ const second = makeCountingEnv();
+
+ // builds + caches the provider's canvas
+ getTextWidth("measure me", FONT, first.env);
+ getTextWidth("measure me twice", FONT, first.env);
+ expect(first.canvases).toHaveLength(1);
+
+ getTextWidth("measure me again", FONT, second.env);
+
+ // measured on a canvas of its own rather than the first env's
+ expect(second.canvases).toHaveLength(1);
+ expect(first.canvases).toHaveLength(1);
+ });
+
+ it("never serves one environment's char widths to another", () => {
+ const env = makeEnv(3);
+
+ expect(charWidth.calculate("A", FONT, env)).toBe(30);
+ // switching env drops the cache rather than reusing the other env's width
+ expect(charWidth.calculate("A", FONT)).toBe(10);
+ expect(charWidth.getCache(FONT, env)).toBeUndefined();
+ // cached while the env stays put
+ expect(charWidth.calculate("A", FONT, env)).toBe(30);
+ expect(charWidth.getCache(FONT, env)?.["A".charCodeAt(0)]).toBe(30);
+
+ // clearing a font drops the entry rather than emptying it, so the
+ // approximation helpers fall back to measuring
+ charWidth.clearCache(FONT);
+ expect(charWidth.getCache(FONT, env)).toBeUndefined();
+ expect(getMaxCharWidth(FONT, env)).toBe(0);
+
+ charWidth.calculate("A", FONT, env);
+ expect(getMaxCharWidth(FONT, env)).toBe(30);
+ // ...and asking about a different env reports "unmeasured", not 30
+ expect(getMaxCharWidth(FONT)).toBe(0);
+ });
+});
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index ab3b75908a..690dfbc91f 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -36,7 +36,7 @@ Breaking. `exportToCanvas`, `exportToBlob` and `exportToSvg` (in both `@excalidr
| `maxWidthOrHeight`, `exportingFrame`, `renderEmbeddables`, `skipInliningFonts`, `reuseImages` | same names, in `config` |
- New sizing options: `width`/`height` (only one given: the other follows the content's aspect ratio), `widthOrHeight` (scales the longest side to exactly that size), `fit: "contain" | "none"` and `position: "center" | "topLeft"` within a `width`/`height` frame, and `x`/`y`/`origin` to export a region (cropped, with padding on all sides). The size options are mutually exclusive in the types, and `fit`, `position` and `x`/`y` only combine with `width`/`height`.
-- `config.environment` for non-browser hosts: `createCanvas` (e.g. `node-canvas`) and `loadFonts`.
+- `config.environment` for non-browser hosts and other windows, the same for every format: `createCanvas` (e.g. `node-canvas`), `createImage`, `createPath`, `document` (the one SVG is built in, e.g. `linkedom`), `textMetrics` and `loadFonts`.
- Canvas dimensions are rounded instead of truncated, so float noise no longer costs a pixel (a 20.5px frame-label band now rounds up), and are at least 1px (flat content with no padding used to produce an empty canvas that couldn't be encoded).
- In dark exports, frame names now use the editor's dark frame-name color (they were dark-filtered twice and came out lighter).
diff --git a/packages/excalidraw/actions/actionBoundText.tsx b/packages/excalidraw/actions/actionBoundText.tsx
index 85f4757738..49737f6e80 100644
--- a/packages/excalidraw/actions/actionBoundText.tsx
+++ b/packages/excalidraw/actions/actionBoundText.tsx
@@ -117,7 +117,9 @@ export const actionUnbindText = register({
unbindTextFromContainer(element, boundTextElement, app.scene);
if (isStickyNoteElement(element)) {
// an empty note sits at its base height; bound arrows follow
- updateStickyNoteLayout(element, app.scene);
+ updateStickyNoteLayout(element, app.scene, {
+ renderEnvironment: app.renderEnvironment,
+ });
} else {
app.scene.mutateElement(element, {
height: originalContainerHeight
@@ -245,7 +247,12 @@ export const bindTextToContainer = (
...(stickyInk ? { strokeColor: stickyInk } : null),
});
const originalContainerHeight = container.height;
- redrawTextBoundingBox(textElement, container, app.scene);
+ redrawTextBoundingBox(
+ textElement,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
// overwritting the cache with original container height so
// it can be restored when unbind
updateOriginalContainerCache(container.id, originalContainerHeight);
@@ -415,7 +422,12 @@ export const wrapTextsInContainers = (
autoResize: true,
});
- redrawTextBoundingBox(textElement, container, app.scene);
+ redrawTextBoundingBox(
+ textElement,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
updatedElements = pushContainerBelowText(
[...updatedElements, container],
diff --git a/packages/excalidraw/actions/actionClipboard.tsx b/packages/excalidraw/actions/actionClipboard.tsx
index a1ed98d2b6..3c0a145c47 100644
--- a/packages/excalidraw/actions/actionClipboard.tsx
+++ b/packages/excalidraw/actions/actionClipboard.tsx
@@ -154,6 +154,7 @@ export const actionCopyAsSvg = register({
{
exportingFrame,
name: app.getName(),
+ renderEnvironment: app.renderEnvironment,
},
);
@@ -220,6 +221,7 @@ export const actionCopyAsPng = register({
await exportCanvas("clipboard", exportedElements, appState, app.files, {
exportingFrame,
name: app.getName(),
+ renderEnvironment: app.renderEnvironment,
});
return {
appState: {
diff --git a/packages/excalidraw/actions/actionFlip.ts b/packages/excalidraw/actions/actionFlip.ts
index b7e15275d8..02690e7888 100644
--- a/packages/excalidraw/actions/actionFlip.ts
+++ b/packages/excalidraw/actions/actionFlip.ts
@@ -146,6 +146,7 @@ const flipElements = (
flipByY: flipDirection === "vertical",
shouldResizeFromCenter: true,
shouldMaintainAspectRatio: true,
+ renderEnvironment: app.renderEnvironment,
},
);
diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsx
index 86d69482f5..17297434fb 100644
--- a/packages/excalidraw/actions/actionProperties.tsx
+++ b/packages/excalidraw/actions/actionProperties.tsx
@@ -314,7 +314,12 @@ const changeFontSize = (
oldElement,
getBaseFontSizeUpdate(oldElement, newFontSize, elementsMap),
);
- redrawTextBoundingBox(newElement, container, app.scene);
+ redrawTextBoundingBox(
+ newElement,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
newElement = offsetElementAfterFontResize(
oldElement,
@@ -1328,7 +1333,12 @@ export const actionChangeFontFamily = register<{
// we either skip the check (have at least one font face loaded) or do the check and find out all the font faces have loaded
for (const [element, container] of elementContainerMapping) {
// trigger synchronous redraw
- redrawTextBoundingBox(element, container, app.scene);
+ redrawTextBoundingBox(
+ element,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
}
} else {
// otherwise try to load all font faces for the given chars and redraw elements once our font faces loaded
@@ -1346,6 +1356,7 @@ export const actionChangeFontFamily = register<{
latestElement as ExcalidrawTextElement,
latestContainer,
app.scene,
+ app.renderEnvironment,
);
}
}
@@ -1563,6 +1574,7 @@ export const actionChangeTextAlign = register<TextAlign>({
newElement,
app.scene.getContainerElement(oldElement),
app.scene,
+ app.renderEnvironment,
);
return newElement;
}
@@ -1665,6 +1677,7 @@ export const actionChangeVerticalAlign = register<VerticalAlign>({
newElement,
app.scene.getContainerElement(oldElement),
app.scene,
+ app.renderEnvironment,
);
return newElement;
}
diff --git a/packages/excalidraw/actions/actionStyles.ts b/packages/excalidraw/actions/actionStyles.ts
index bb1b96906a..2ec81bcbf3 100644
--- a/packages/excalidraw/actions/actionStyles.ts
+++ b/packages/excalidraw/actions/actionStyles.ts
@@ -171,7 +171,12 @@ export const actionPasteStyles = register({
} else {
// sticky labels are laid out together with their (possibly
// also restyled) note in the post-pass below
- redrawTextBoundingBox(newTextElement, container, app.scene);
+ redrawTextBoundingBox(
+ newTextElement,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
}
}
@@ -203,7 +208,10 @@ export const actionPasteStyles = register({
elementsMap,
),
new Set(selectedElementIds),
- { prevElementsMap: elementsMap },
+ {
+ prevElementsMap: elementsMap,
+ renderEnvironment: app.renderEnvironment,
+ },
);
// a restyled note may have grown or shrunk — arrows bound to it follow
diff --git a/packages/excalidraw/animatedTrail.ts b/packages/excalidraw/animatedTrail.ts
index e98e6e50ee..dca3c529eb 100644
--- a/packages/excalidraw/animatedTrail.ts
+++ b/packages/excalidraw/animatedTrail.ts
@@ -93,16 +93,20 @@ export class AnimatedTrail implements Trail {
}
if (!AnimationController.running(this.key)) {
- AnimationController.start(this.key, () => {
- const needsNext = this.onFrame();
- if (needsNext) {
- return { keep: true };
- }
-
- this.cleanup();
-
- return null;
- });
+ AnimationController.start(
+ this.key,
+ () => {
+ const needsNext = this.onFrame();
+ if (needsNext) {
+ return { keep: true };
+ }
+
+ this.cleanup();
+
+ return null;
+ },
+ this.app.ownerWindow,
+ );
}
}
diff --git a/packages/excalidraw/appState.ts b/packages/excalidraw/appState.ts
index e4017c73eb..2bd1db37e6 100644
--- a/packages/excalidraw/appState.ts
+++ b/packages/excalidraw/appState.ts
@@ -17,9 +17,15 @@ import {
import type { AppState, InputDevice, NormalizedZoomValue } from "./types";
-const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
- ? devicePixelRatio
- : 1;
+/**
+ * Resolved lazily rather than at module scope: this module is pulled in by the
+ * export pipeline, which must be importable outside a browser realm.
+ */
+const getDefaultExportScale = () => {
+ const devicePixelRatio =
+ typeof window === "undefined" ? 1 : window.devicePixelRatio || 1;
+ return EXPORT_SCALES.includes(devicePixelRatio) ? devicePixelRatio : 1;
+};
export const getDefaultAppState = (): Omit<
AppState,
@@ -67,7 +73,7 @@ export const getDefaultAppState = (): Omit<
penDetected: false,
errorMessage: null,
exportBackground: true,
- exportScale: defaultExportScale,
+ exportScale: getDefaultExportScale(),
exportEmbedScene: false,
exportWithDarkMode: false,
fileHandle: null,
diff --git a/packages/excalidraw/charts/charts.bar.ts b/packages/excalidraw/charts/charts.bar.ts
index b1a7759606..09cc7f7cb5 100644
--- a/packages/excalidraw/charts/charts.bar.ts
+++ b/packages/excalidraw/charts/charts.bar.ts
@@ -2,6 +2,8 @@ import { isDevEnv } from "@excalidraw/common";
import { newElement } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import { commonProps } from "./charts.constants";
import {
chartBaseElements,
@@ -22,6 +24,7 @@ export const renderBarChart = (
x: number,
y: number,
colorSeed?: number,
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
const series = spreadsheet.series;
const layout = getCartesianChartLayout("bar", series.length);
@@ -83,8 +86,16 @@ export const renderBarChart = (
layout,
max,
isDevEnv(),
+ renderEnvironment,
+ );
+ const xLabels = chartXLabels(
+ spreadsheet,
+ x,
+ y,
+ backgroundColor,
+ layout,
+ renderEnvironment,
);
- const xLabels = chartXLabels(spreadsheet, x, y, backgroundColor, layout);
const xLabelsBottomY = Math.max(
y + layout.gap / 2,
...xLabels.map((label) => getRotatedTextElementBottom(label)),
@@ -97,6 +108,7 @@ export const renderBarChart = (
xLabelsBottomY,
y + layout.gap * 5,
backgroundColor,
+ renderEnvironment,
);
return [...baseElements, ...bars, ...seriesLegend];
diff --git a/packages/excalidraw/charts/charts.helpers.ts b/packages/excalidraw/charts/charts.helpers.ts
index 18097b1df9..e7b7867a16 100644
--- a/packages/excalidraw/charts/charts.helpers.ts
+++ b/packages/excalidraw/charts/charts.helpers.ts
@@ -22,6 +22,8 @@ import {
wrapText,
} from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import type {
ChartType,
ExcalidrawTextElement,
@@ -268,9 +270,10 @@ export const getRadarDisplayText = (
text: string,
fontString: ReturnType<typeof getFontString>,
maxWidth: number,
+ renderEnvironment?: RenderEnvironment,
) => {
return shouldWrapRadarText(text)
- ? wrapText(text, fontString, maxWidth)
+ ? wrapText(text, fontString, maxWidth, renderEnvironment)
: text;
};
@@ -281,6 +284,7 @@ export const createRadarAxisLabels = (
centerY: number,
radius: number,
backgroundColor: string,
+ renderEnvironment?: RenderEnvironment,
): {
axisLabels: ChartElements;
axisLabelTopY: number;
@@ -294,7 +298,11 @@ export const createRadarAxisLabels = (
RADAR_AXIS_LABEL_MAX_WIDTH,
radius * (labels.length > 8 ? 0.56 : 0.72),
);
- const minLabelWidth = getApproxMinLineWidth(fontString, lineHeight);
+ const minLabelWidth = getApproxMinLineWidth(
+ fontString,
+ lineHeight,
+ renderEnvironment,
+ );
const axisLabels = labels.map((label, index) => {
const angle = angles[index];
@@ -304,15 +312,28 @@ export const createRadarAxisLabels = (
.trim()
.split(/\s+/)
.filter(Boolean)
- .map((word) => measureText(word, fontString, lineHeight).width),
+ .map(
+ (word) =>
+ measureText(word, fontString, lineHeight, renderEnvironment).width,
+ ),
);
const maxLabelWidth = Math.max(
minLabelWidth,
baseLabelWidth,
longestWordWidth,
);
- const displayLabel = getRadarDisplayText(label, fontString, maxLabelWidth);
- const metrics = measureText(displayLabel, fontString, lineHeight);
+ const displayLabel = getRadarDisplayText(
+ label,
+ fontString,
+ maxLabelWidth,
+ renderEnvironment,
+ );
+ const metrics = measureText(
+ displayLabel,
+ fontString,
+ lineHeight,
+ renderEnvironment,
+ );
const cos = Math.cos(angle);
const sin = Math.sin(angle);
@@ -353,6 +374,7 @@ export const createRadarAxisLabels = (
lineHeight,
textAlign,
verticalAlign: "middle",
+ renderEnvironment,
});
});
@@ -370,6 +392,7 @@ export const createSeriesLegend = (
minLegendTopY: number,
fallbackLegendY: number,
backgroundColor: string,
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
if (series.length <= 1) {
return [];
@@ -381,8 +404,18 @@ export const createSeriesLegend = (
const fontString = getFontString({ fontFamily, fontSize });
const legendItems = series.map((seriesItem, index) => {
const label = seriesItem.title?.trim() || `Series ${index + 1}`;
- const displayLabel = getRadarDisplayText(label, fontString, BAR_HEIGHT);
- const metrics = measureText(displayLabel, fontString, lineHeight);
+ const displayLabel = getRadarDisplayText(
+ label,
+ fontString,
+ BAR_HEIGHT,
+ renderEnvironment,
+ );
+ const metrics = measureText(
+ displayLabel,
+ fontString,
+ lineHeight,
+ renderEnvironment,
+ );
const itemWidth =
RADAR_LEGEND_SWATCH_SIZE + RADAR_LEGEND_TEXT_GAP + metrics.width;
return {
@@ -463,6 +496,7 @@ export const createSeriesLegend = (
lineHeight,
textAlign: "left",
verticalAlign: "middle",
+ renderEnvironment,
}),
);
@@ -477,15 +511,22 @@ const ellipsifyTextToWidth = (
maxWidth: number,
fontString: ReturnType<typeof getFontString>,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ renderEnvironment?: RenderEnvironment,
) => {
- if (measureText(text, fontString, lineHeight).width <= maxWidth) {
+ if (
+ measureText(text, fontString, lineHeight, renderEnvironment).width <=
+ maxWidth
+ ) {
return text;
}
let end = text.length;
while (end > 1) {
const candidate = `${text.slice(0, end)}...`;
- if (measureText(candidate, fontString, lineHeight).width <= maxWidth) {
+ if (
+ measureText(candidate, fontString, lineHeight, renderEnvironment).width <=
+ maxWidth
+ ) {
return candidate;
}
end--;
@@ -499,27 +540,44 @@ const wrapOrEllipsifyTextToWidth = (
maxWidth: number,
fontString: ReturnType<typeof getFontString>,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ renderEnvironment?: RenderEnvironment,
) => {
- if (measureText(text, fontString, lineHeight).width <= maxWidth) {
+ if (
+ measureText(text, fontString, lineHeight, renderEnvironment).width <=
+ maxWidth
+ ) {
return { wrapped: false, text };
}
const words = text.trim().split(/\s+/).filter(Boolean);
if (words.length > 1) {
const hasLongWord = words.some((word) => {
- return measureText(word, fontString, lineHeight).width > maxWidth;
+ return (
+ measureText(word, fontString, lineHeight, renderEnvironment).width >
+ maxWidth
+ );
});
if (
!hasLongWord &&
- maxWidth >= getApproxMinLineWidth(fontString, lineHeight)
+ maxWidth >=
+ getApproxMinLineWidth(fontString, lineHeight, renderEnvironment)
) {
- return { wrapped: true, text: wrapText(text, fontString, maxWidth) };
+ return {
+ wrapped: true,
+ text: wrapText(text, fontString, maxWidth, renderEnvironment),
+ };
}
}
return {
wrapped: false,
- text: ellipsifyTextToWidth(text, maxWidth, fontString, lineHeight),
+ text: ellipsifyTextToWidth(
+ text,
+ maxWidth,
+ fontString,
+ lineHeight,
+ renderEnvironment,
+ ),
};
};
@@ -553,10 +611,11 @@ const getCartesianAxisLabelSpec = (
maxRotatedWidth: number,
fontString: ReturnType<typeof getFontString>,
lineHeight: ExcalidrawTextElement["lineHeight"],
+ renderEnvironment?: RenderEnvironment,
): CartesianAxisLabelSpec => {
const minWidth = Math.max(
CARTESIAN_LABEL_MIN_WIDTH,
- Math.ceil(getApproxMinLineWidth(fontString, lineHeight)),
+ Math.ceil(getApproxMinLineWidth(fontString, lineHeight, renderEnvironment)),
);
const maxWidth = Math.max(minWidth, Math.floor(maxLabelWidth));
const candidateWidths: number[] = [];
@@ -614,8 +673,14 @@ const getCartesianAxisLabelSpec = (
width,
fontString,
lineHeight,
+ renderEnvironment,
+ );
+ const metrics = measureText(
+ text,
+ fontString,
+ lineHeight,
+ renderEnvironment,
);
- const metrics = measureText(text, fontString, lineHeight);
const rotated = getRotatedBoundingBox(
metrics.width,
metrics.height,
@@ -691,6 +756,7 @@ export const chartXLabels = (
y: number,
backgroundColor: string,
layout: CartesianChartLayout,
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
const fontFamily = commonProps.fontFamily;
const fontSize = FONT_SIZES.sm;
@@ -713,6 +779,7 @@ export const chartXLabels = (
maxRotatedWidth,
fontString,
lineHeight,
+ renderEnvironment,
);
const centerX =
x +
@@ -737,6 +804,7 @@ export const chartXLabels = (
lineHeight,
textAlign: "center",
verticalAlign: "top",
+ renderEnvironment,
});
}) || []
);
@@ -749,6 +817,7 @@ const chartYLabels = (
backgroundColor: string,
layout: CartesianChartLayout,
maxValue = Math.max(...spreadsheet.series[0].values),
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
const minYLabel = newTextElement({
backgroundColor,
@@ -757,6 +826,7 @@ const chartYLabels = (
y: y - layout.gap,
text: "0",
textAlign: "right",
+ renderEnvironment,
});
const maxYLabel = newTextElement({
@@ -766,6 +836,7 @@ const chartYLabels = (
y: y - layout.chartHeight - minYLabel.height / 2,
text: maxValue.toLocaleString(),
textAlign: "right",
+ renderEnvironment,
});
return [minYLabel, maxYLabel];
@@ -823,6 +894,7 @@ export const chartBaseElements = (
layout: CartesianChartLayout,
maxValue = Math.max(...spreadsheet.series[0].values),
debug?: boolean,
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
const { chartWidth, chartHeight } = getChartDimensions(spreadsheet, layout);
@@ -837,6 +909,7 @@ export const chartBaseElements = (
textAlign: "center",
fontSize: FONT_SIZES.xl,
fontFamily: FONT_FAMILY["Lilita One"],
+ renderEnvironment,
})
: null;
@@ -858,8 +931,23 @@ export const chartBaseElements = (
return [
...(debugRect ? [debugRect] : []),
...(title ? [title] : []),
- ...chartXLabels(spreadsheet, x, y, backgroundColor, layout),
- ...chartYLabels(spreadsheet, x, y, backgroundColor, layout, maxValue),
+ ...chartXLabels(
+ spreadsheet,
+ x,
+ y,
+ backgroundColor,
+ layout,
+ renderEnvironment,
+ ),
+ ...chartYLabels(
+ spreadsheet,
+ x,
+ y,
+ backgroundColor,
+ layout,
+ maxValue,
+ renderEnvironment,
+ ),
...chartLines(spreadsheet, x, y, backgroundColor, layout),
];
};
diff --git a/packages/excalidraw/charts/charts.line.ts b/packages/excalidraw/charts/charts.line.ts
index b08774d8b3..b8709047e3 100644
--- a/packages/excalidraw/charts/charts.line.ts
+++ b/packages/excalidraw/charts/charts.line.ts
@@ -4,6 +4,8 @@ import { isDevEnv } from "@excalidraw/common";
import { newElement, newLinearElement } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import type { LocalPoint } from "@excalidraw/math";
import { GRID_OPACITY, commonProps } from "./charts.constants";
@@ -26,6 +28,7 @@ export const renderLineChart = (
x: number,
y: number,
colorSeed?: number,
+ renderEnvironment?: RenderEnvironment,
): ChartElements => {
const series = spreadsheet.series;
const layout = getCartesianChartLayout("line", series.length);
@@ -110,8 +113,16 @@ export const renderLineChart = (
layout,
max,
isDevEnv(),
+ renderEnvironment,
+ );
+ const xLabels = chartXLabels(
+ spreadsheet,
+ x,
+ y,
+ backgroundColor,
+ layout,
+ renderEnvironment,
);
- const xLabels = chartXLabels(spreadsheet, x, y, backgroundColor, layout);
const xLabelsBottomY = Math.max(
y + layout.gap / 2,
...xLabels.map((label) => getRotatedTextElementBottom(label)),
@@ -124,6 +135,7 @@ export const renderLineChart = (
xLabelsBottomY,
y + layout.gap * 5,
backgroundColor,
+ renderEnvironment,
);
return [...baseElements, ...lines, ...guides, ...dots, ...seriesLegend];
diff --git a/packages/excalidraw/charts/charts.radar.ts b/packages/excalidraw/charts/charts.radar.ts
index 6606a4af60..8f366779ff 100644
--- a/packages/excalidraw/charts/charts.radar.ts
+++ b/packages/excalidraw/charts/charts.radar.ts
@@ -14,6 +14,8 @@ import {
newTextElement,
} from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import type { LocalPoint } from "@excalidraw/math";
import {
@@ -43,6 +45,7 @@ export const renderRadarChart = (
x: number,
y: number,
colorSeed?: number,
+ renderEnvironment?: RenderEnvironment,
): ChartElements | null => {
if (!isSpreadsheetValidForChartType(spreadsheet, "radar")) {
return null;
@@ -72,6 +75,7 @@ export const renderRadarChart = (
centerY,
radius,
backgroundColor,
+ renderEnvironment,
);
const titleFontFamily = FONT_FAMILY["Lilita One"];
@@ -86,10 +90,16 @@ export const renderRadarChart = (
spreadsheet.title,
titleFontString,
chartWidth + RADAR_LABEL_OFFSET * 2,
+ renderEnvironment,
)
: null;
const titleTextMetrics = titleText
- ? measureText(titleText, titleFontString, titleLineHeight)
+ ? measureText(
+ titleText,
+ titleFontString,
+ titleLineHeight,
+ renderEnvironment,
+ )
: null;
const title = titleText
? newTextElement({
@@ -103,6 +113,7 @@ export const renderRadarChart = (
fontSize: titleFontSize,
lineHeight: titleLineHeight,
textAlign: "center",
+ renderEnvironment,
})
: null;
@@ -186,6 +197,7 @@ export const renderRadarChart = (
axisLabelBottomY,
y + BAR_GAP * 5,
backgroundColor,
+ renderEnvironment,
);
return [
diff --git a/packages/excalidraw/charts/index.ts b/packages/excalidraw/charts/index.ts
index d806546a49..279bb2bf32 100644
--- a/packages/excalidraw/charts/index.ts
+++ b/packages/excalidraw/charts/index.ts
@@ -1,5 +1,7 @@
import type { ChartType } from "@excalidraw/element/types";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import { renderBarChart } from "./charts.bar";
import { renderLineChart } from "./charts.line";
import {
@@ -27,12 +29,13 @@ export const renderSpreadsheet = (
x: number,
y: number,
colorSeed?: number,
+ renderEnvironment?: RenderEnvironment,
): ChartElements | null => {
if (chartType === "line") {
- return renderLineChart(spreadsheet, x, y, colorSeed);
+ return renderLineChart(spreadsheet, x, y, colorSeed, renderEnvironment);
}
if (chartType === "radar") {
- return renderRadarChart(spreadsheet, x, y, colorSeed);
+ return renderRadarChart(spreadsheet, x, y, colorSeed, renderEnvironment);
}
- return renderBarChart(spreadsheet, x, y, colorSeed);
+ return renderBarChart(spreadsheet, x, y, colorSeed, renderEnvironment);
};
diff --git a/packages/excalidraw/components/App.arrowText.ts b/packages/excalidraw/components/App.arrowText.ts
index b5f18bb86e..aed8704c5d 100644
--- a/packages/excalidraw/components/App.arrowText.ts
+++ b/packages/excalidraw/components/App.arrowText.ts
@@ -154,6 +154,7 @@ export class AppArrowText {
pointerX: pointerCoords.x,
zoom: this.app.state.zoom.value,
scene: this.app.scene,
+ renderEnvironment: this.app.renderEnvironment,
});
return true;
diff --git a/packages/excalidraw/components/App.bucketFill.ts b/packages/excalidraw/components/App.bucketFill.ts
index 03bc3087d5..bc63b9c9d9 100644
--- a/packages/excalidraw/components/App.bucketFill.ts
+++ b/packages/excalidraw/components/App.bucketFill.ts
@@ -111,7 +111,7 @@ export class AppBucketFill {
},
};
this.temporaryEyeDropper = eyeDropper;
- this.app.updateEditorAtom(activeEyeDropperAtom, eyeDropper);
+ this.app.host.setActiveEyeDropper(eyeDropper);
};
closeTemporaryEyeDropper = () => {
@@ -121,7 +121,7 @@ export class AppBucketFill {
eyeDropper &&
editorJotaiStore.get(activeEyeDropperAtom) === eyeDropper
) {
- this.app.updateEditorAtom(activeEyeDropperAtom, null);
+ this.app.host.setActiveEyeDropper(null);
}
};
diff --git a/packages/excalidraw/components/App.clipboard.ts b/packages/excalidraw/components/App.clipboard.ts
index 068d0a6613..c494044c4e 100644
--- a/packages/excalidraw/components/App.clipboard.ts
+++ b/packages/excalidraw/components/App.clipboard.ts
@@ -181,6 +181,7 @@ export class AppClipboard {
data.programmaticAPI
? convertToExcalidrawElements(
data.elements as ExcalidrawElementSkeleton[],
+ { renderEnvironment: this.app.renderEnvironment },
)
: data.elements
) as readonly ExcalidrawElement[];
@@ -212,6 +213,7 @@ export class AppClipboard {
const elements = convertToExcalidrawElements(skeletonElements, {
regenerateIds: true,
+ renderEnvironment: this.app.renderEnvironment,
});
this.app.addElementsFromPasteOrLibrary({
@@ -459,15 +461,30 @@ export class AppClipboard {
y: currentY,
});
- let metrics = measureText(originalText, fontString, lineHeight);
+ let metrics = measureText(
+ originalText,
+ fontString,
+ lineHeight,
+ this.app.renderEnvironment,
+ );
const isTextUnwrapped = metrics.width > maxTextWidth;
const text = isTextUnwrapped
- ? wrapText(originalText, fontString, maxTextWidth)
+ ? wrapText(
+ originalText,
+ fontString,
+ maxTextWidth,
+ this.app.renderEnvironment,
+ )
: originalText;
metrics = isTextUnwrapped
- ? measureText(text, fontString, lineHeight)
+ ? measureText(
+ text,
+ fontString,
+ lineHeight,
+ this.app.renderEnvironment,
+ )
: metrics;
const startX = x - metrics.width / 2;
@@ -482,6 +499,7 @@ export class AppClipboard {
lineHeight,
autoResize: !isTextUnwrapped,
frameId: topLayerFrame ? topLayerFrame.id : null,
+ renderEnvironment: this.app.renderEnvironment,
});
acc.push(element);
currentY += element.height + LINE_GAP;
diff --git a/packages/excalidraw/components/App.cursor.ts b/packages/excalidraw/components/App.cursor.ts
index cf5419dcbc..9689ed4260 100644
--- a/packages/excalidraw/components/App.cursor.ts
+++ b/packages/excalidraw/components/App.cursor.ts
@@ -211,7 +211,7 @@ export class AppCursor {
if (!this.eraserCanvasCache || this.eraserCanvasCache.theme !== theme) {
const isDarkTheme = theme === THEME.DARK;
- this.eraserCanvasCache = document.createElement("canvas");
+ this.eraserCanvasCache = this.app.ownerDocument.createElement("canvas");
this.eraserCanvasCache.theme = theme;
this.eraserCanvasCache.height = cursorImageSizePx;
this.eraserCanvasCache.width = cursorImageSizePx;
diff --git a/packages/excalidraw/components/App.host.ts b/packages/excalidraw/components/App.host.ts
new file mode 100644
index 0000000000..e34c411b4b
--- /dev/null
+++ b/packages/excalidraw/components/App.host.ts
@@ -0,0 +1,234 @@
+import { isDevEnv, isTestEnv } from "@excalidraw/common";
+
+import type { RenderEnvironment } from "@excalidraw/element";
+
+import { editorJotaiStore } from "../editor-jotai";
+
+import { activeEyeDropperAtom, type EyeDropperProperties } from "./EyeDropper";
+import {
+ hideHyperlinkToolip,
+ type HyperlinkTooltipOwner,
+} from "./hyperlink/Hyperlink";
+import { startLinkImgDecoding } from "./hyperlink/helpers";
+
+import type { AppProps } from "../types";
+import type App from "./App";
+
+/**
+ * The pointerup handler of whichever editor is mid-interaction. Shared by
+ * every editor in the process; `AppHost.ownedPointerUp` says whose it is.
+ */
+let activePointerUp: (() => void) | null = null;
+
+/**
+ * Owns everything that ties this editor to the document/window it renders
+ * into (cross-document runtime ownership): the render environment the
+ * canvases, images and paths are minted from, and the state that has to be
+ * re-primed whenever that environment is swapped.
+ */
+export class AppHost {
+ constructor(private app: App) {}
+
+ /**
+ * Identity token for the hyperlink tooltip, which is a module-level
+ * singleton shared by every editor in the process — the owner tells it
+ * which editor the currently shown tooltip belongs to, so one editor never
+ * hides (or leaks a timer into) another's tooltip.
+ */
+ readonly hyperlinkTooltipOwner: HyperlinkTooltipOwner = {};
+
+ /**
+ * The process-wide interaction slots this editor currently owns: the
+ * pointerup handler of the interaction in flight, and the eye dropper (one
+ * atom in the editor-wide store). Both hold closures over this editor, so a
+ * teardown that leaves one set retains the editor -- and with it its owner
+ * window and document, e.g. a closed popout.
+ *
+ * @see releaseOwnedInteractionState
+ */
+ private ownedPointerUp: (() => void) | null = null;
+ private ownedEyeDropper: EyeDropperProperties | null = null;
+
+ /** Takes over the pointerup slot (or clears it, on `null`). */
+ public setPointerUp(handler: (() => void) | null) {
+ activePointerUp = handler;
+ this.ownedPointerUp = handler;
+ }
+
+ /**
+ * Runs the pending pointerup, whoever owns it -- pointerup does not always
+ * fire (the user tabs away), so interactions are settled manually.
+ */
+ public runPendingPointerUp() {
+ activePointerUp?.();
+ }
+
+ /** Opens the eye dropper (or closes it, on `null`), taking ownership. */
+ public setActiveEyeDropper(eyeDropper: EyeDropperProperties | null) {
+ this.ownedEyeDropper = eyeDropper;
+ this.app.updateEditorAtom(activeEyeDropperAtom, eyeDropper);
+ }
+
+ /**
+ * Drops the ownership token without touching the atom -- for callers that
+ * have just closed the eye dropper themselves.
+ */
+ public releaseEyeDropperOwnership() {
+ this.ownedEyeDropper = null;
+ }
+
+ /**
+ * Releases the process-wide slots this editor owns, so nothing outside it
+ * keeps it alive once it is torn down. Ownership-checked: a sibling
+ * editor's in-flight interaction must survive our teardown.
+ */
+ private releaseOwnedInteractionState() {
+ // an unmount mid-drag never reaches the pointerup that would clear this
+ if (this.ownedPointerUp && activePointerUp === this.ownedPointerUp) {
+ activePointerUp = null;
+ }
+ this.ownedPointerUp = null;
+
+ if (
+ this.ownedEyeDropper &&
+ editorJotaiStore.get(activeEyeDropperAtom) === this.ownedEyeDropper
+ ) {
+ editorJotaiStore.set(activeEyeDropperAtom, null);
+ }
+ this.ownedEyeDropper = null;
+ }
+
+ /**
+ * Render environment scoped to this editor's owner window, so that the
+ * canvases, images and paths created during rendering live in the owner
+ * document. Memoized keyed on the resolved document because render caches
+ * are keyed by environment identity: the identity must not survive a
+ * document switch, or caches would mix canvases and images from two realms
+ * under one bucket.
+ */
+ private _renderEnvironment: RenderEnvironment | null = null;
+ private _renderEnvironmentDocument: Document | null = null;
+ public get renderEnvironment(): RenderEnvironment {
+ if (this.app.props.renderEnvironment) {
+ return this.app.props.renderEnvironment;
+ }
+ const ownerDocument = this.app.ownerDocument;
+ if (
+ !this._renderEnvironment ||
+ this._renderEnvironmentDocument !== ownerDocument
+ ) {
+ this._renderEnvironmentDocument = ownerDocument;
+ this._renderEnvironment = {
+ createCanvas: () => this.app.ownerDocument.createElement("canvas"),
+ createImage: () => new this.app.ownerWindow.Image(),
+ // Browsers accept a `Path2D` minted in another realm, but taking it
+ // from the owner window keeps runtime ownership complete. Falls back
+ // to the global for realms without one (e.g. jsdom iframes).
+ createPath: (svgPath: string) =>
+ new (this.app.ownerWindow.Path2D ?? Path2D)(svgPath),
+ document: ownerDocument,
+ };
+ }
+ return this._renderEnvironment;
+ }
+
+ /**
+ * Re-primes whatever the render environment owns. Called on mount and on
+ * every update, so an environment swap is picked up wherever it happens.
+ */
+ public sync(prevProps?: AppProps) {
+ this.ensureLinkImgDecoding();
+ if (prevProps) {
+ this.warnOnUnstableRenderEnvironment(prevProps);
+ }
+ }
+
+ /**
+ * Releases what this editor owns outside itself, so we don't retain the
+ * (soon detached) document/window, or leave a pending tooltip timer around.
+ */
+ public destroy() {
+ this._destroyed = true;
+ hideHyperlinkToolip(this.hyperlinkTooltipOwner);
+ this.releaseOwnedInteractionState();
+ }
+ private _destroyed = false;
+
+ /**
+ * Link icons decode asynchronously and the static scene skips an icon that
+ * is not decoded yet, so start the decode on mount rather than on the
+ * first render that happens to have a link, so the decode is settled long
+ * before there is a link element to draw an icon for.
+ *
+ * Re-run on an environment swap: the images are keyed by env identity, so
+ * a new environment starts with none.
+ *
+ * The decode landing only flips a status, which invalidates nothing, so the
+ * scene is nudged once when an icon becomes drawable -- otherwise a scene
+ * that paints before the decode settles and is then left alone (an initial
+ * scene with links, never scrolled or edited) keeps its icons missing until
+ * something unrelated repaints. Same shape as a font or an image file
+ * landing: repaint only when there is something new to draw.
+ */
+ private _linkImgDecodingEnvironment: RenderEnvironment | null = null;
+ private ensureLinkImgDecoding() {
+ const renderEnvironment = this.renderEnvironment;
+ if (this._linkImgDecodingEnvironment === renderEnvironment) {
+ return;
+ }
+ this._linkImgDecodingEnvironment = renderEnvironment;
+ startLinkImgDecoding(renderEnvironment).then((didDecode) => {
+ if (
+ !didDecode ||
+ this._destroyed ||
+ // the environment was swapped while we waited; that swap started its
+ // own decode, and this one's images are no longer the ones drawn
+ this._linkImgDecodingEnvironment !== renderEnvironment ||
+ // nothing in the scene draws a link icon, so there is nothing to
+ // repaint for; an element gaining a link repaints on its own
+ !this.app.scene
+ .getNonDeletedElements()
+ .some((element) => !!element.link)
+ ) {
+ return;
+ }
+ this.app.scene.triggerUpdate();
+ });
+ }
+
+ /**
+ * Every render cache is keyed by environment identity, so a host passing an
+ * inline `renderEnvironment` literal re-mints the identity on each render
+ * and re-rasterizes everything, with no visible symptom other than being
+ * slow. Detected by the factories' source being unchanged across the swap:
+ * a genuine environment switch (e.g. a document change) reads differently.
+ */
+ private _warnedUnstableRenderEnvironment = false;
+ private warnOnUnstableRenderEnvironment(prevProps: AppProps) {
+ if (
+ (!isDevEnv() && !isTestEnv()) ||
+ this._warnedUnstableRenderEnvironment
+ ) {
+ return;
+ }
+ const prev = prevProps.renderEnvironment;
+ const next = this.app.props.renderEnvironment;
+ if (
+ !prev ||
+ !next ||
+ prev === next ||
+ String(prev.createCanvas) !== String(next.createCanvas) ||
+ String(prev.createImage) !== String(next.createImage)
+ ) {
+ return;
+ }
+ this._warnedUnstableRenderEnvironment = true;
+ console.warn(
+ "Excalidraw: the `renderEnvironment` prop changed identity while its " +
+ "implementation stayed the same. Render caches are keyed by this " +
+ "object's identity, so a new identity per render defeats all of them " +
+ "(elements are re-rasterized every frame). Hoist the object to a " +
+ "module constant or memoize it (e.g. `useMemo`).",
+ );
+ }
+}
diff --git a/packages/excalidraw/components/App.pan.ts b/packages/excalidraw/components/App.pan.ts
index 81504a3492..a1b0d37ee6 100644
--- a/packages/excalidraw/components/App.pan.ts
+++ b/packages/excalidraw/components/App.pan.ts
@@ -194,7 +194,7 @@ export class AppPan {
* - empty clipboard
*/
const enableNextPaste = () => {
- setTimeout(() => {
+ app.ownerWindow.setTimeout(() => {
app.ownerDocument.body.removeEventListener(
EVENT.PASTE,
preventNextPaste,
@@ -217,7 +217,7 @@ export class AppPan {
scrollX: state.scrollX - deltaX / state.zoom.value,
scrollY: state.scrollY - deltaY / state.zoom.value,
}));
- });
+ }, app.ownerWindow);
this.pendingMoveFlush = onPointerMove.flush;
const teardown = withBatchedUpdates(
(upEvent?: PointerEvent | FocusEvent) => {
diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.ts
index dbc67f301c..b1ec916e84 100644
--- a/packages/excalidraw/components/App.selectionTool.ts
+++ b/packages/excalidraw/components/App.selectionTool.ts
@@ -701,6 +701,7 @@ export class AppSelectionTool {
resizeY,
pointerDownState.resize.center.x,
pointerDownState.resize.center.y,
+ this.app.renderEnvironment,
)
) {
const elementsToHighlight = new Set<NonDeletedExcalidrawElement>();
diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.ts
index 496e2867d4..bce77ccb2c 100644
--- a/packages/excalidraw/components/App.text.ts
+++ b/packages/excalidraw/components/App.text.ts
@@ -199,6 +199,7 @@ export class AppText {
const stickyLayout = stickyContainer
? getStickyNoteLayout(stickyContainer, latestTextElement, {
originalText: nextOriginalText,
+ renderEnvironment: this.app.renderEnvironment,
})
: null;
// a free text stops growing at the view's width (between the side
@@ -230,6 +231,7 @@ export class AppText {
elementsMap,
nextOriginalText,
maxWidth,
+ this.app.renderEnvironment,
)),
});
}
@@ -719,6 +721,7 @@ export class AppText {
const minWidth = getApproxMinLineWidth(
getFontString(fontString),
lineHeight,
+ this.app.renderEnvironment,
);
const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
const newHeight = Math.max(container.height, minHeight);
@@ -823,6 +826,7 @@ export class AppText {
? container.angle
: (0 as Radians),
frameId,
+ renderEnvironment: this.app.renderEnvironment,
});
if (!existingTextElement && shouldBindToContainer && container) {
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 18c06ac8c6..7e8164eea0 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -237,7 +237,10 @@ import type {
ExcalidrawBindableElement,
} from "@excalidraw/element/types";
-import type { TransformHandleDirection } from "@excalidraw/element";
+import type {
+ RenderEnvironment,
+ TransformHandleDirection,
+} from "@excalidraw/element";
import type { Mutable, ValueOf } from "@excalidraw/common/utility-types";
@@ -410,6 +413,7 @@ import { hideTooltip } from "./Tooltip";
import { StaticCanvas, InteractiveCanvas } from "./canvases";
import NewElementCanvas from "./canvases/NewElementCanvas";
import { isPointHittingLink } from "./hyperlink/helpers";
+import { AppHost } from "./App.host";
import { CursorHint, CursorHints } from "./CursorHint";
import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
import { AppStateObserver, type OnStateChange } from "./AppStateObserver";
@@ -569,7 +573,6 @@ const GOOGLE_DRIVE_AUTOPLAYED = new WeakSet<HTMLIFrameElement>();
const MAX_EMBEDDABLE_VIEWPORT_SCALE = 4;
-let lastPointerUp: (() => void) | null = null;
const gesture: Gesture = {
pointers: new Map(),
lastCenter: null,
@@ -605,6 +608,18 @@ class App extends React.Component<AppProps, AppState> {
typeof globalThis;
}
+ /**
+ * Everything binding this editor to the document/window it renders into
+ * (render environment, hyperlink tooltip ownership). Delegated to so the
+ * cross-document ownership rules live in one place.
+ */
+ public host: AppHost = new AppHost(this);
+
+ /** @see AppHost.renderEnvironment */
+ public get renderEnvironment(): RenderEnvironment {
+ return this.host.renderEnvironment;
+ }
+
public scene: Scene;
public fonts: Fonts;
public renderer: Renderer;
@@ -1091,7 +1106,7 @@ class App extends React.Component<AppProps, AppState> {
let data = null;
try {
data = JSON.parse(event.data);
- } catch (e) {}
+ } catch {}
if (!data) {
return;
}
@@ -2624,6 +2639,8 @@ class App extends React.Component<AppProps, AppState> {
renderConfig={{
imageCache: this.imageCache,
isExporting: false,
+ scale: this.ownerWindow.devicePixelRatio,
+ renderEnvironment: this.renderEnvironment,
renderGrid: isGridModeEnabled(this),
renderLinks: this.isLinksEnabled(),
canvasBackgroundColor:
@@ -2649,6 +2666,8 @@ class App extends React.Component<AppProps, AppState> {
renderConfig={{
imageCache: this.imageCache,
isExporting: false,
+ scale: this.ownerWindow.devicePixelRatio,
+ renderEnvironment: this.renderEnvironment,
renderGrid: false,
canvasBackgroundColor:
this.state.viewBackgroundColor,
@@ -2773,6 +2792,7 @@ class App extends React.Component<AppProps, AppState> {
{
name: this.getName(),
exportingFrame: opts.exportingFrame,
+ renderEnvironment: this.renderEnvironment,
},
)
.catch(muteFSAbortError)
@@ -3032,7 +3052,7 @@ class App extends React.Component<AppProps, AppState> {
};
private openEyeDropper = ({ type }: { type: "stroke" | "background" }) => {
- this.updateEditorAtom(activeEyeDropperAtom, {
+ this.host.setActiveEyeDropper({
swapPreviewOnAlt: true,
colorPickerType:
type === "stroke" ? "elementStroke" : "elementBackground",
@@ -3289,7 +3309,7 @@ class App extends React.Component<AppProps, AppState> {
this.pan.setSpaceHeld(false);
this.modifiers.reset();
isDraggingScrollBar = false;
- lastPointerUp = null;
+ this.host.setPointerUp(null);
gesture.pointers.clear();
gesture.lastCenter = null;
@@ -3313,6 +3333,7 @@ class App extends React.Component<AppProps, AppState> {
// These components install their own DOM listeners rather than going
// through App's input handlers, so they must be explicitly unmounted.
editorJotaiStore.set(activeEyeDropperAtom, null);
+ this.host.releaseEyeDropperOwnership();
editorJotaiStore.set(convertElementTypePopupAtom, null);
if (this.state.editingFrame) {
@@ -3405,7 +3426,7 @@ class App extends React.Component<AppProps, AppState> {
if (this.isLinksEnabled(prevProps) !== this.isLinksEnabled()) {
if (!this.isLinksEnabled()) {
this.hitLinkElement = undefined;
- hideHyperlinkToolip();
+ hideHyperlinkToolip(this.host.hyperlinkTooltipOwner);
this.cursor.reset();
}
}
@@ -3682,10 +3703,16 @@ class App extends React.Component<AppProps, AppState> {
// can be loaded fresh
this.clearImageShapeCache();
- // manually loading the font faces seems faster even in browsers that do fire the loadingdone event
- this.fonts.loadSceneFonts().then((fontFaces) => {
- this.fonts.onLoaded(fontFaces);
- });
+ // manually loading the font faces seems faster even in browsers that do
+ // fire the loadingdone event. Prewarming the default font family, so that
+ // the first text element is not rendered with a fallback font.
+ // NOTE: reading from `restoredAppState` instead of `this.state`, as the
+ // `syncActionResult` above sets the state asynchronously
+ this.fonts
+ .loadSceneFonts(restoredAppState.currentItemFontFamily)
+ .then((fontFaces) => {
+ this.fonts.onLoaded(fontFaces);
+ });
if (isElementLink(this.ownerWindow.location.href)) {
this.viewport.setViewport({
@@ -3747,7 +3774,7 @@ class App extends React.Component<AppProps, AppState> {
this.viewport.invalidateUIOffset("stylesPanel");
if (prevStylesPanelMode !== "full" && nextStylesPanelMode === "full") {
- this.setState((prevState) => ({
+ this.setState(() => ({
preferredSelectionTool: {
type: "selection",
initialized: true,
@@ -3778,6 +3805,7 @@ class App extends React.Component<AppProps, AppState> {
public async componentDidMount() {
this.unmounted = false;
this.api = this.createExcalidrawAPI();
+ this.host.sync();
this.excalidrawContainerValue.container =
this.excalidrawContainerRef.current;
@@ -3903,7 +3931,9 @@ class App extends React.Component<AppProps, AppState> {
(this.ownerWindow as any).launchQueue?.setConsumer(() => {});
- this.renderer.destroy();
+ this.host.destroy();
+
+ this.renderer.destroy(this.canvas);
this.scene.destroy();
this.scene = new Scene();
this.fonts = new Fonts(this.scene, this.ownerDocument);
@@ -4282,6 +4312,7 @@ class App extends React.Component<AppProps, AppState> {
this.handleInteractionStateChange(prevProps, prevState);
this.handleForcedToolChange(prevProps, prevState);
+ this.host.sync(prevProps);
this.appStateObserver.flush(prevState);
@@ -4403,8 +4434,9 @@ class App extends React.Component<AppProps, AppState> {
// execute only if the condition still holds when the deferred callback
// executes (it can be scheduled multiple times depending on how
// many times the component renders)
- this.state.selectedLinearElement?.isEditing &&
+ if (this.state.selectedLinearElement?.isEditing) {
this.actionManager.executeAction(actionFinalize);
+ }
});
}
@@ -4629,7 +4661,12 @@ class App extends React.Component<AppProps, AppState> {
newElement,
this.scene.getElementsMapIncludingDeleted(),
);
- redrawTextBoundingBox(newElement, container, this.scene);
+ redrawTextBoundingBox(
+ newElement,
+ container,
+ this.scene,
+ this.renderEnvironment,
+ );
}
});
@@ -6502,7 +6539,7 @@ class App extends React.Component<AppProps, AppState> {
this.editorInterface.formFactor === "phone",
);
if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
- hideHyperlinkToolip();
+ hideHyperlinkToolip(this.host.hyperlinkTooltipOwner);
let url = this.hitLinkElement.link;
if (url) {
url = normalizeLink(url);
@@ -6546,10 +6583,12 @@ class App extends React.Component<AppProps, AppState> {
this.hitLinkElement,
this.state,
this.scene.getNonDeletedElementsMap(),
+ this.ownerDocument,
+ this.host.hyperlinkTooltipOwner,
);
return true;
}
- hideHyperlinkToolip();
+ hideHyperlinkToolip(this.host.hyperlinkTooltipOwner);
return false;
};
@@ -7344,7 +7383,7 @@ class App extends React.Component<AppProps, AppState> {
};
// set touch moving for mobile context menu
- private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
+ private handleTouchMove = (_event: React.TouchEvent<HTMLCanvasElement>) => {
if (!this.isInteractionEnabled()) {
return;
}
@@ -7632,7 +7671,7 @@ class App extends React.Component<AppProps, AppState> {
//fires only once, if pen is detected, penMode is enabled
//the user can disable this by toggling the penMode button
if (!this.state.penDetected && event.pointerType === "pen") {
- this.setState((prevState) => {
+ this.setState(() => {
return {
penMode: true,
penDetected: true,
@@ -8014,7 +8053,7 @@ class App extends React.Component<AppProps, AppState> {
*/
private maybeCleanupAfterMissingPointerUp = (event: PointerEvent | null) => {
this.pan.end();
- lastPointerUp?.();
+ this.host.runPendingPointerUp();
this.missingPointerEventCleanupEmitter.trigger(event).clear();
};
@@ -8205,9 +8244,9 @@ class App extends React.Component<AppProps, AppState> {
}
this.handlePointerMoveOverScrollbars(event, pointerDownState);
- });
+ }, this.ownerWindow);
const onPointerUp = withBatchedUpdates(() => {
- lastPointerUp = null;
+ this.host.setPointerUp(null);
isDraggingScrollBar = false;
this.cursor.applyForTool();
this.setState({
@@ -8219,7 +8258,7 @@ class App extends React.Component<AppProps, AppState> {
onPointerMove.flush();
});
- lastPointerUp = onPointerUp;
+ this.host.setPointerUp(onPointerUp);
this.ownerWindow.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
this.ownerWindow.addEventListener(EVENT.POINTER_UP, onPointerUp);
@@ -8938,7 +8977,9 @@ class App extends React.Component<AppProps, AppState> {
): (event: KeyboardEvent) => void {
return withBatchedUpdates((event: KeyboardEvent) => {
// Prevents focus from escaping excalidraw tab
- event.key === KEYS.ALT && event.preventDefault();
+ if (event.key === KEYS.ALT) {
+ event.preventDefault();
+ }
if (this.selectionTool.maybeHandleResize(pointerDownState, event)) {
return;
}
@@ -9368,7 +9409,7 @@ class App extends React.Component<AppProps, AppState> {
event,
pointerDownState,
);
- });
+ }, this.ownerWindow);
}
// Returns whether the pointer move happened over either scrollbar
@@ -9541,7 +9582,9 @@ class App extends React.Component<AppProps, AppState> {
.map((e) => elementsMap.get(e.id))
.filter((e) => isElbowArrow(e))
.forEach((e) => {
- !!e && this.scene.mutateElement(e, {});
+ if (e) {
+ this.scene.mutateElement(e, {});
+ }
});
}
}
@@ -9803,6 +9846,7 @@ class App extends React.Component<AppProps, AppState> {
fontFamily: newElement.fontFamily,
}),
newElement.lineHeight,
+ this.renderEnvironment,
);
if (newElement.width < minWidth) {
@@ -10564,6 +10608,7 @@ class App extends React.Component<AppProps, AppState> {
imageCache: this.imageCache,
fileIds: elements.map((element) => element.fileId),
files,
+ createImage: () => this.renderEnvironment.createImage(),
});
if (erroredFiles.size) {
@@ -11073,6 +11118,7 @@ class App extends React.Component<AppProps, AppState> {
shouldResizeFromCenter: false,
scene: this.scene,
zoom: this.state.zoom.value,
+ renderEnvironment: this.renderEnvironment,
informMutation: false,
});
return;
@@ -11146,6 +11192,7 @@ class App extends React.Component<AppProps, AppState> {
shouldResizeFromCenter: shouldResizeFromCenter(event),
zoom: this.state.zoom.value,
scene: this.scene,
+ renderEnvironment: this.renderEnvironment,
widthAspectRatio: aspectRatio,
originOffset: this.state.originSnapOffset,
informMutation,
@@ -11358,7 +11405,9 @@ class App extends React.Component<AppProps, AppState> {
offsetTop,
},
() => {
- cb && cb();
+ if (cb) {
+ cb();
+ }
},
);
// a smaller viewport may push the min zoom up / shrink the pan range
diff --git a/packages/excalidraw/components/App.viewport.ts b/packages/excalidraw/components/App.viewport.ts
index 5437d82f93..288c24b52e 100644
--- a/packages/excalidraw/components/App.viewport.ts
+++ b/packages/excalidraw/components/App.viewport.ts
@@ -22,7 +22,11 @@ import type {
} from "@excalidraw/element/types";
import { getLanguage, t } from "../i18n";
-import { AnimationController } from "../renderer/animation";
+import {
+ AnimationController,
+ type AnimationKey,
+ type AnimationScheduler,
+} from "../renderer/animation";
import {
constrainScrollState,
DEFAULT_OVERSCROLL,
@@ -44,9 +48,13 @@ import type {
} from "../types";
import type App from "./App";
-export const SCROLL_TO_CONTENT_ANIMATION_KEY = "animateScrollToContent";
-export const SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY =
- "animateScrollConstraintsSnapBack";
+/** The AnimationController keys a viewport uses, unique per AppViewport so
+ * concurrent editors in the same window never share (or cancel) each
+ * other's animations. */
+export type ViewportAnimationKeys = {
+ scrollToContent: AnimationKey;
+ snapBack: AnimationKey;
+};
const DEFAULT_SCROLL_ANIMATION_DURATION = 500;
@@ -325,6 +333,8 @@ const animateToViewport = (
from: Viewport,
target: Viewport,
duration: number,
+ key: AnimationKey,
+ scheduler: AnimationScheduler,
onFrame: (
state: Pick<
AppState,
@@ -334,7 +344,7 @@ const animateToViewport = (
onComplete: () => void,
) => {
AnimationController.start<{ elapsed: number }>(
- SCROLL_TO_CONTENT_ANIMATION_KEY,
+ key,
({ deltaTime, state }) => {
const elapsed = (state?.elapsed ?? 0) + deltaTime;
const progress = Math.min(elapsed / duration, 1);
@@ -352,6 +362,7 @@ const animateToViewport = (
return null;
},
+ scheduler,
);
};
@@ -379,6 +390,8 @@ export const snapBackToConstraints = (
>,
) => Viewport | null,
) => void,
+ keys: ViewportAnimationKeys,
+ scheduler: AnimationScheduler = window,
duration = SNAP_BACK_ANIMATION_DURATION,
) => {
const target = constrainScrollState(state);
@@ -393,7 +406,7 @@ export const snapBackToConstraints = (
// A programmatic navigation owns the viewport until it settles. A stale
// rubberband debounce must not supersede it.
- if (AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)) {
+ if (AnimationController.running(keys.scrollToContent)) {
return;
}
@@ -404,7 +417,7 @@ export const snapBackToConstraints = (
const overscrollY = (state.scrollY - target.scrollY) * state.zoom.value;
AnimationController.start<{ elapsed: number }>(
- SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY,
+ keys.snapBack,
({ deltaTime, state: animationState }) => {
const elapsed = (animationState?.elapsed ?? 0) + deltaTime;
const progress = Math.min(elapsed / duration, 1);
@@ -426,6 +439,7 @@ export const snapBackToConstraints = (
return progress < 1 ? { elapsed } : null;
},
+ scheduler,
);
};
@@ -446,6 +460,11 @@ export class AppViewport {
{ side: "left" | "right"; offset: number }
>();
+ /** Unique per instance (see `ViewportAnimationKeys`); exposed for tests
+ * observing the animations. */
+ readonly scrollToContentAnimationKey = Symbol("scrollToContentAnimation");
+ readonly snapBackAnimationKey = Symbol("snapBackAnimation");
+
constructor(
private app: App,
private dependencies: AppViewportDependencies,
@@ -453,8 +472,8 @@ export class AppViewport {
get isAnimating() {
return (
- AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY) ||
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY)
+ AnimationController.running(this.scrollToContentAnimationKey) ||
+ AnimationController.running(this.snapBackAnimationKey)
);
}
@@ -725,7 +744,7 @@ export class AppViewport {
setViewport = (opts: SetViewportOptions | null) => {
if (opts === null) {
this.cancelTransition();
- AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ AnimationController.cancel(this.snapBackAnimationKey);
this.snapBackDebounced.cancel();
this.app.setState({
scrollConstraints: null,
@@ -774,7 +793,7 @@ export class AppViewport {
// A new programmatic navigation supersedes the previous one and starts
// from whatever viewport its last rendered frame reached.
this.cancelTransition();
- AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ AnimationController.cancel(this.snapBackAnimationKey);
this.snapBackDebounced.cancel();
if (duration === null) {
@@ -801,6 +820,8 @@ export class AppViewport {
from,
viewportUpdate,
duration,
+ this.scrollToContentAnimationKey,
+ this.app.ownerWindow,
(state) => {
if (this.activeTransition === transition) {
this.app.setState(state);
@@ -851,7 +872,7 @@ export class AppViewport {
}
this.cancelTransition();
if (!opts?.preserveScrollConstraintsSnapBack) {
- AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ AnimationController.cancel(this.snapBackAnimationKey);
}
this.app.requestUnfollow();
@@ -900,8 +921,14 @@ export class AppViewport {
if (this.app.unmounted || this.dependencies.isGestureActive()) {
return;
}
- snapBackToConstraints(this.app.state, (updater) =>
- this.app.setState((state) => updater(state)),
+ snapBackToConstraints(
+ this.app.state,
+ (updater) => this.app.setState((state) => updater(state)),
+ {
+ scrollToContent: this.scrollToContentAnimationKey,
+ snapBack: this.snapBackAnimationKey,
+ },
+ this.app.ownerWindow,
);
};
@@ -912,12 +939,12 @@ export class AppViewport {
private cancelTransition = () => {
this.activeTransition = null;
- AnimationController.cancel(SCROLL_TO_CONTENT_ANIMATION_KEY);
+ AnimationController.cancel(this.scrollToContentAnimationKey);
};
destroy = () => {
this.cancelTransition();
- AnimationController.cancel(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ AnimationController.cancel(this.snapBackAnimationKey);
this.snapBackDebounced.cancel();
};
}
diff --git a/packages/excalidraw/components/ColorPicker/colorTopPicksDnD.ts b/packages/excalidraw/components/ColorPicker/colorTopPicksDnD.ts
index f4055d0bd5..ba0ed64c50 100644
--- a/packages/excalidraw/components/ColorPicker/colorTopPicksDnD.ts
+++ b/packages/excalidraw/components/ColorPicker/colorTopPicksDnD.ts
@@ -23,7 +23,9 @@ const createColorGhost: CreateTopPicksGhost<string> = ({
value: color,
sourceEl,
}) => {
- const swatch = document.createElement("div");
+ // the source may live in another window's document (e.g. a popout)
+ const ownerDocument = sourceEl.ownerDocument;
+ const swatch = ownerDocument.createElement("div");
swatch.className = "excalidraw-color-dnd-ghost-swatch";
if (isTransparent(color)) {
swatch.classList.add("is-transparent");
@@ -31,7 +33,9 @@ const createColorGhost: CreateTopPicksGhost<string> = ({
// swatches render the theme-adjusted color (dark mode remaps colors
// rather than CSS-filtering them) — sample the rendered color so the
// ghost matches what the user picked up
- const rendered = getComputedStyle(sourceEl).backgroundColor;
+ const rendered = (ownerDocument.defaultView ?? window).getComputedStyle(
+ sourceEl,
+ ).backgroundColor;
swatch.style.backgroundColor =
rendered && rendered !== "rgba(0, 0, 0, 0)" ? rendered : color;
}
diff --git a/packages/excalidraw/components/ConvertElementTypePopup.tsx b/packages/excalidraw/components/ConvertElementTypePopup.tsx
index f0445ee2d0..6c135ea4bc 100644
--- a/packages/excalidraw/components/ConvertElementTypePopup.tsx
+++ b/packages/excalidraw/components/ConvertElementTypePopup.tsx
@@ -81,6 +81,8 @@ import type {
import type { Scene } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
import { trackEvent } from "../analytics";
import { atom } from "../editor-jotai";
@@ -371,6 +373,7 @@ export const adjustBoundTextSize = (
container: ExcalidrawTextContainer,
boundText: ExcalidrawTextElementWithContainer,
scene: Scene,
+ renderEnvironment?: RenderEnvironment,
) => {
const maxWidth = getBoundTextMaxWidth(container, boundText);
const maxHeight = getBoundTextMaxHeight(container, boundText);
@@ -379,12 +382,14 @@ export const adjustBoundTextSize = (
boundText.text,
getFontString(boundText),
maxWidth,
+ renderEnvironment,
);
let metrics = measureText(
wrappedText,
getFontString(boundText),
boundText.lineHeight,
+ renderEnvironment,
);
let nextFontSize = boundText.fontSize;
@@ -401,6 +406,7 @@ export const adjustBoundTextSize = (
boundText.text,
getFontString(_updatedTextElement),
boundText.lineHeight,
+ renderEnvironment,
);
}
@@ -410,7 +416,7 @@ export const adjustBoundTextSize = (
height: metrics.height,
});
- redrawTextBoundingBox(boundText, container, scene);
+ redrawTextBoundingBox(boundText, container, scene, renderEnvironment);
};
type ConversionType = "generic" | "linear" | null;
@@ -501,6 +507,7 @@ export const convertElementTypes = (
element as ExcalidrawTextContainer,
boundText,
app.scene,
+ app.renderEnvironment,
);
}
}
diff --git a/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts b/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts
index 61b9659807..4273ec5466 100644
--- a/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts
+++ b/packages/excalidraw/components/FontPicker/fontTopPicksDnD.ts
@@ -20,6 +20,9 @@ const createFontGhost: CreateTopPicksGhost<FontFamilyValues> = ({
sourceEl,
stripEl,
}) => {
+ // the source may live in another window's document (e.g. a popout)
+ const ownerDocument = sourceEl.ownerDocument;
+ const ownerWindow = ownerDocument.defaultView ?? window;
const isPick = sourceEl.dataset.topPickIndex != null;
const template =
(isPick
@@ -27,10 +30,10 @@ const createFontGhost: CreateTopPicksGhost<FontFamilyValues> = ({
: stripEl.querySelector<HTMLElement>(
"[data-top-pick-index]:not(.active)",
)) ?? stripEl.querySelector<HTMLElement>("[data-top-pick-index]")!;
- const templateStyle = getComputedStyle(template);
+ const templateStyle = ownerWindow.getComputedStyle(template);
const templateRect = template.getBoundingClientRect();
- const tile = document.createElement("div");
+ const tile = ownerDocument.createElement("div");
tile.className = "excalidraw-font-dnd-ghost-tile";
tile.style.backgroundColor = templateStyle.backgroundColor;
tile.style.color = templateStyle.color;
@@ -58,7 +61,8 @@ const createFontGhost: CreateTopPicksGhost<FontFamilyValues> = ({
if (sample) {
const sampleClone = sample.cloneNode(true) as HTMLElement;
// the ghost is outside the editor's CSS scope
- sampleClone.style.fontSize = getComputedStyle(sample).fontSize;
+ sampleClone.style.fontSize =
+ ownerWindow.getComputedStyle(sample).fontSize;
sampleClone.style.lineHeight = "1";
tile.appendChild(sampleClone);
}
diff --git a/packages/excalidraw/components/PasteChartDialog.tsx b/packages/excalidraw/components/PasteChartDialog.tsx
index 596afc59df..e54c845ca7 100644
--- a/packages/excalidraw/components/PasteChartDialog.tsx
+++ b/packages/excalidraw/components/PasteChartDialog.tsx
@@ -48,6 +48,7 @@ const ChartPreviewBtn = (props: {
null,
);
const { theme } = useUIAppState();
+ const { renderEnvironment } = useApp();
useLayoutEffect(() => {
if (!props.spreadsheet) {
@@ -61,6 +62,7 @@ const ChartPreviewBtn = (props: {
0,
0,
props.colorSeed,
+ renderEnvironment,
);
if (!elements) {
setChartElements(null);
@@ -82,6 +84,7 @@ const ChartPreviewBtn = (props: {
skipInliningFonts: true,
theme,
canvasBackgroundColor: false,
+ environment: renderEnvironment,
},
});
svg.querySelector(".style-fonts")?.remove();
@@ -92,7 +95,13 @@ const ChartPreviewBtn = (props: {
return () => {
previewNode.replaceChildren();
};
- }, [props.spreadsheet, props.chartType, props.colorSeed, theme]);
+ }, [
+ props.spreadsheet,
+ props.chartType,
+ props.colorSeed,
+ theme,
+ renderEnvironment,
+ ]);
const chartTypeLabel = getChartTypeLabel(props.chartType);
@@ -119,6 +128,7 @@ const PlainTextPreviewBtn = (props: {
}) => {
const previewRef = useRef<HTMLDivElement | null>(null);
const { theme } = useUIAppState();
+ const { renderEnvironment } = useApp();
useLayoutEffect(() => {
if (!props.rawText) {
@@ -144,6 +154,7 @@ const PlainTextPreviewBtn = (props: {
skipInliningFonts: true,
theme,
canvasBackgroundColor: false,
+ environment: renderEnvironment,
},
});
svg.querySelector(".style-fonts")?.remove();
@@ -154,7 +165,7 @@ const PlainTextPreviewBtn = (props: {
return () => {
previewNode.replaceChildren();
};
- }, [props.rawText, theme]);
+ }, [props.rawText, theme, renderEnvironment]);
return (
<button
@@ -182,7 +193,7 @@ export const PasteChartDialog = ({
rawText: string;
onClose: () => void;
}) => {
- const { onInsertElements, focusContainer } = useApp();
+ const { onInsertElements, focusContainer, renderEnvironment } = useApp();
const [colorSeed, setColorSeed] = useState(Math.random());
const handleReshuffleColors = React.useCallback(() => {
@@ -207,6 +218,7 @@ export const PasteChartDialog = ({
text: rawText,
x: 0,
y: 0,
+ renderEnvironment,
});
onInsertElements([textElement]);
trackEvent("paste", "chart", "plaintext");
diff --git a/packages/excalidraw/components/PublishLibrary.tsx b/packages/excalidraw/components/PublishLibrary.tsx
index 40e9c524b5..495d9b3af0 100644
--- a/packages/excalidraw/components/PublishLibrary.tsx
+++ b/packages/excalidraw/components/PublishLibrary.tsx
@@ -15,6 +15,7 @@ import { canvasToBlob, resizeImageFile } from "../data/blob";
import { t } from "../i18n";
import { exportScene } from "../scene/export";
+import { useExcalidrawContainer } from "./App";
import { Dialog } from "./Dialog";
import DialogActionButton from "./DialogActionButton";
import { IconButton } from "./IconButton";
@@ -36,7 +37,10 @@ interface PublishLibraryDataParams {
website: string;
}
-const generatePreviewImage = async (libraryItems: LibraryItems) => {
+const generatePreviewImage = async (
+ libraryItems: LibraryItems,
+ ownerDocument: Document,
+) => {
const MAX_ITEMS_PER_ROW = 6;
const BOX_SIZE = 128;
const BOX_PADDING = Math.round(BOX_SIZE / 16);
@@ -44,7 +48,7 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
const rows = chunk(libraryItems, MAX_ITEMS_PER_ROW);
- const canvas = document.createElement("canvas");
+ const canvas = ownerDocument.createElement("canvas");
canvas.width =
rows[0].length * BOX_SIZE +
@@ -228,6 +232,8 @@ const PublishLibrary = ({
updateItemsInStorage: (items: LibraryItems) => void;
onRemove: (id: string) => void;
}) => {
+ const { container } = useExcalidrawContainer();
+
const [libraryData, setLibraryData] = useState<PublishLibraryDataParams>({
authorName: "",
githubHandle: "",
@@ -283,7 +289,10 @@ const PublishLibrary = ({
return;
}
- const previewImage = await generatePreviewImage(clonedLibItems);
+ const previewImage = await generatePreviewImage(
+ clonedLibItems,
+ container?.ownerDocument ?? document,
+ );
const libContent: ExportedLibraryData = {
type: EXPORT_DATA_TYPES.excalidrawLibrary,
diff --git a/packages/excalidraw/components/SearchMenu.tsx b/packages/excalidraw/components/SearchMenu.tsx
index 0583da1791..2b5884b345 100644
--- a/packages/excalidraw/components/SearchMenu.tsx
+++ b/packages/excalidraw/components/SearchMenu.tsx
@@ -29,6 +29,7 @@ import { isTextElement, isFrameLikeElement } from "@excalidraw/element";
import { getDefaultFrameName } from "@excalidraw/element/frame";
+import type { RenderEnvironment } from "@excalidraw/element";
import type {
ExcalidrawFrameLikeElement,
ExcalidrawTextElement,
@@ -630,6 +631,7 @@ const getMatchedLines = (
textElement: ExcalidrawTextElement,
searchQuery: SearchQuery,
index: number,
+ renderEnvironment?: RenderEnvironment,
) => {
const normalizedText = normalizeWrappedText(
textElement.text,
@@ -687,6 +689,7 @@ const getMatchedLines = (
textToStart,
getFontString(textElement),
textElement.lineHeight,
+ renderEnvironment,
);
// measureText returns a non-zero width for the empty string
@@ -700,6 +703,7 @@ const getMatchedLines = (
lineIndexRange.line,
getFontString(textElement),
textElement.lineHeight,
+ renderEnvironment,
);
const spaceToStart =
@@ -713,6 +717,7 @@ const getMatchedLines = (
matchedWord,
getFontString(textElement),
textElement.lineHeight,
+ renderEnvironment,
);
const offsetX = offset.width;
@@ -738,6 +743,7 @@ const getMatchInFrame = (
searchQuery: SearchQuery,
index: number,
zoomValue: number,
+ renderEnvironment?: RenderEnvironment,
): SearchMatch["matchedLines"] => {
const text = frame.name ?? getDefaultFrameName(frame);
const matchedText = text.slice(index, index + searchQuery.length);
@@ -750,14 +756,19 @@ const getMatchInFrame = (
const lineHeight = getLineHeight(FONT_FAMILY.Assistant);
- const offset = measureText(prefixText, font, lineHeight);
+ const offset = measureText(prefixText, font, lineHeight, renderEnvironment);
// Correct non-zero width for empty string
if (prefixText === "") {
offset.width = 0;
}
- const matchedMetrics = measureText(matchedText, font, lineHeight);
+ const matchedMetrics = measureText(
+ matchedText,
+ font,
+ lineHeight,
+ renderEnvironment,
+ );
const offsetX = offset.width;
const offsetY = -offset.height - FRAME_STYLE.strokeWidth;
@@ -811,7 +822,12 @@ const handleSearch = debounce(
while ((match = regex.exec(text)) !== null) {
const preview = getMatchPreview(text, match.index, searchQuery);
- const matchedLines = getMatchedLines(textEl, searchQuery, match.index);
+ const matchedLines = getMatchedLines(
+ textEl,
+ searchQuery,
+ match.index,
+ app.renderEnvironment,
+ );
if (matchedLines.length > 0) {
textMatches.push({
@@ -838,6 +854,7 @@ const handleSearch = debounce(
searchQuery,
match.index,
app.state.zoom.value,
+ app.renderEnvironment,
);
if (matchedLines.length > 0) {
diff --git a/packages/excalidraw/components/Stats/FontSize.tsx b/packages/excalidraw/components/Stats/FontSize.tsx
index 5cbdce8cce..e751d4bc7c 100644
--- a/packages/excalidraw/components/Stats/FontSize.tsx
+++ b/packages/excalidraw/components/Stats/FontSize.tsx
@@ -40,6 +40,7 @@ const handleFontSizeChange: DragInputCallbackType<
shouldChangeByStepSize,
nextValue,
scene,
+ app,
}) => {
const elementsMap = scene.getNonDeletedElementsMap();
@@ -77,6 +78,7 @@ const handleFontSizeChange: DragInputCallbackType<
latestElement,
scene.getContainerElement(latestElement),
scene,
+ app.renderEnvironment,
);
}
}
diff --git a/packages/excalidraw/components/Stats/MultiDimension.tsx b/packages/excalidraw/components/Stats/MultiDimension.tsx
index 64a83172da..1d3d5325ff 100644
--- a/packages/excalidraw/components/Stats/MultiDimension.tsx
+++ b/packages/excalidraw/components/Stats/MultiDimension.tsx
@@ -31,7 +31,7 @@ import type {
NonDeletedSceneElementsMap,
} from "@excalidraw/element/types";
-import type { Scene } from "@excalidraw/element";
+import type { RenderEnvironment, Scene } from "@excalidraw/element";
import DragInput from "./DragInput";
import { getAtomicUnits, getStepSizedValue, isPropertyEditable } from "./utils";
@@ -89,6 +89,7 @@ const resizeElementInGroup = (
origElement: NonDeletedExcalidrawElement,
originalElementsMap: ElementsMap,
scene: Scene,
+ renderEnvironment?: RenderEnvironment,
) => {
const elementsMap = scene.getNonDeletedElementsMap();
@@ -116,6 +117,7 @@ const resizeElementInGroup = (
{ proportional: true, fromCenter: false },
),
anchor: "top",
+ renderEnvironment,
});
return;
}
@@ -137,6 +139,9 @@ const resizeElementInGroup = (
scene,
property === "width" ? "e" : "s",
true,
+ false,
+ false,
+ renderEnvironment,
);
}
}
@@ -153,6 +158,7 @@ const resizeGroup = (
originalElements: NonDeletedExcalidrawElement[],
originalElementsMap: ElementsMap,
scene: Scene,
+ renderEnvironment?: RenderEnvironment,
) => {
// keep aspect ratio for groups
if (property === "width") {
@@ -176,6 +182,7 @@ const resizeGroup = (
origElement,
originalElementsMap,
scene,
+ renderEnvironment,
);
}
};
@@ -231,6 +238,7 @@ const handleDimensionChange: DragInputCallbackType<
originalElements,
originalElementsMap,
scene,
+ app.renderEnvironment,
);
} else {
const [el] = elementsInUnit;
@@ -277,6 +285,7 @@ const handleDimensionChange: DragInputCallbackType<
property === "width" ? "e" : "s",
{
shouldInformMutation: false,
+ renderEnvironment: app.renderEnvironment,
},
);
diff --git a/packages/excalidraw/components/Stats/MultiFontSize.tsx b/packages/excalidraw/components/Stats/MultiFontSize.tsx
index 8d1f76965a..3e71f33409 100644
--- a/packages/excalidraw/components/Stats/MultiFontSize.tsx
+++ b/packages/excalidraw/components/Stats/MultiFontSize.tsx
@@ -71,6 +71,7 @@ const handleFontSizeChange: DragInputCallbackType<
shouldChangeByStepSize,
nextValue,
scene,
+ app,
}) => {
const elementsMap = scene.getNonDeletedElementsMap();
const latestTextElements = originalElements.map((el) =>
@@ -92,6 +93,7 @@ const handleFontSizeChange: DragInputCallbackType<
textElement,
scene.getContainerElement(textElement),
scene,
+ app.renderEnvironment,
);
}
@@ -123,6 +125,7 @@ const handleFontSizeChange: DragInputCallbackType<
latestElement,
scene.getContainerElement(latestElement),
scene,
+ app.renderEnvironment,
);
}
diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.ts
index acf38dac9a..6f59c0727b 100644
--- a/packages/excalidraw/components/TTDDialog/common.ts
+++ b/packages/excalidraw/components/TTDDialog/common.ts
@@ -110,7 +110,7 @@ export const convertMermaidToExcalidraw = async ({
padding: DEFAULT_EXPORT_PADDING,
maxWidthOrHeight:
Math.max(parent.offsetWidth, parent.offsetHeight) *
- window.devicePixelRatio,
+ (parent.ownerDocument.defaultView?.devicePixelRatio ?? 1),
theme,
},
});
diff --git a/packages/excalidraw/components/Tooltip.tsx b/packages/excalidraw/components/Tooltip.tsx
index 201aba41e9..8b3dc93d13 100644
--- a/packages/excalidraw/components/Tooltip.tsx
+++ b/packages/excalidraw/components/Tooltip.tsx
@@ -1,21 +1,36 @@
import clsx from "clsx";
import React from "react";
+import { getTargetWindow } from "@excalidraw/common";
+
import "./Tooltip.scss";
-export const getTooltipDiv = () => {
- const existingDiv = document.querySelector<HTMLDivElement>(
- ".excalidraw-tooltip",
+export const TOOLTIP_CLASS = "excalidraw-tooltip";
+export const TOOLTIP_VISIBLE_CLASS = "excalidraw-tooltip--visible";
+
+export const getTooltipDiv = (ownerDocument: Document) => {
+ const existingDiv = ownerDocument.querySelector<HTMLDivElement>(
+ `.${TOOLTIP_CLASS}`,
);
if (existingDiv) {
return existingDiv;
}
- const div = document.createElement("div");
- document.body.appendChild(div);
- div.classList.add("excalidraw-tooltip");
+ const div = ownerDocument.createElement("div");
+ ownerDocument.body.appendChild(div);
+ div.classList.add(TOOLTIP_CLASS);
return div;
};
+/**
+ * Hides `ownerDocument`'s tooltip, for tooltips not shown through
+ * `showTooltip` (see `hideTooltip`).
+ */
+export const hideDocumentTooltip = (ownerDocument: Document) => {
+ ownerDocument
+ .querySelector(`.${TOOLTIP_CLASS}`)
+ ?.classList.remove(TOOLTIP_VISIBLE_CLASS);
+};
+
export const updateTooltipPosition = (
tooltip: HTMLDivElement,
item: {
@@ -27,9 +42,15 @@ export const updateTooltipPosition = (
position: "bottom" | "top" = "bottom",
) => {
const tooltipRect = tooltip.getBoundingClientRect();
+ // callers have already made the tooltip visible, so it must always end up
+ // positioned — falls back to the module realm for a detached document
+ const ownerWindow = getTargetWindow(tooltip);
+ if (!ownerWindow) {
+ return;
+ }
- const viewportWidth = window.innerWidth;
- const viewportHeight = window.innerHeight;
+ const viewportWidth = ownerWindow.innerWidth;
+ const viewportHeight = ownerWindow.innerHeight;
const margin = 5;
@@ -61,29 +82,43 @@ export const updateTooltipPosition = (
};
/** ms before a `delay`ed tooltip shows */
-const TOOLTIP_DELAY = 500;
+export const TOOLTIP_DELAY = 500;
/**
* ms after a tooltip hides during which a `delay`ed tooltip shows right away
* (e.g. when moving across adjacent buttons)
*/
const TOOLTIP_WARM_WINDOW = 300;
-let showTooltipTimer = 0;
+/** a pending delayed tooltip, timed in its item's window */
+let showTooltipTimer: { id: number; ownerWindow: Window } | null = null;
let tooltipHiddenAt = 0;
+/**
+ * the tooltip `showTooltip` showed last (it lives in its item's document,
+ * which may be another window's)
+ */
+let shownTooltip: HTMLDivElement | null = null;
/**
* while a tooltip is visible, hides it once its item is removed from the DOM
* (e.g. unmounted while hovered, which doesn't fire pointerleave)
*/
let tooltipItemObserver: MutationObserver | null = null;
+const clearShowTooltipTimer = () => {
+ if (showTooltipTimer) {
+ showTooltipTimer.ownerWindow.clearTimeout(showTooltipTimer.id);
+ showTooltipTimer = null;
+ }
+};
+
+/** Hides the tooltip `showTooltip` shows, and cancels a pending one. */
export const hideTooltip = () => {
- clearTimeout(showTooltipTimer);
+ clearShowTooltipTimer();
tooltipItemObserver?.disconnect();
tooltipItemObserver = null;
- // a plain query, so that hiding never creates the tooltip node
- const tooltip = document.querySelector<HTMLDivElement>(".excalidraw-tooltip");
- if (tooltip?.classList.contains("excalidraw-tooltip--visible")) {
- tooltip.classList.remove("excalidraw-tooltip--visible");
+ const tooltip = shownTooltip;
+ shownTooltip = null;
+ if (tooltip?.classList.contains(TOOLTIP_VISIBLE_CLASS)) {
+ tooltip.classList.remove(TOOLTIP_VISIBLE_CLASS);
tooltipHiddenAt = Date.now();
}
};
@@ -95,7 +130,12 @@ const updateTooltip = (
long: boolean,
position: "bottom" | "top",
) => {
- tooltip.classList.add("excalidraw-tooltip--visible");
+ if (shownTooltip && shownTooltip !== tooltip) {
+ // shown in another document before
+ shownTooltip.classList.remove(TOOLTIP_VISIBLE_CLASS);
+ }
+ shownTooltip = tooltip;
+ tooltip.classList.add(TOOLTIP_VISIBLE_CLASS);
tooltip.style.minWidth = long ? "50ch" : "10ch";
tooltip.style.maxWidth = long ? "50ch" : "15ch";
@@ -110,7 +150,7 @@ const updateTooltip = (
hideTooltip();
}
});
- tooltipItemObserver.observe(document.body, {
+ tooltipItemObserver.observe(item.ownerDocument.body, {
childList: true,
subtree: true,
});
@@ -136,13 +176,28 @@ export const showTooltip = (
) => {
const show = () => {
// item may have been unmounted while the delayed tooltip was pending
+ showTooltipTimer = null;
if (item.isConnected) {
- updateTooltip(item, getTooltipDiv(), label, long, position);
+ updateTooltip(
+ item,
+ getTooltipDiv(item.ownerDocument),
+ label,
+ long,
+ position,
+ );
}
};
- clearTimeout(showTooltipTimer);
- if (delay && Date.now() - tooltipHiddenAt > TOOLTIP_WARM_WINDOW) {
- showTooltipTimer = window.setTimeout(show, TOOLTIP_DELAY);
+ clearShowTooltipTimer();
+ const ownerWindow = getTargetWindow(item);
+ if (
+ ownerWindow &&
+ delay &&
+ Date.now() - tooltipHiddenAt > TOOLTIP_WARM_WINDOW
+ ) {
+ showTooltipTimer = {
+ id: ownerWindow.setTimeout(show, TOOLTIP_DELAY),
+ ownerWindow,
+ };
} else {
show();
}
diff --git a/packages/excalidraw/components/TopPicksDnD/topPicksDnD.tsx b/packages/excalidraw/components/TopPicksDnD/topPicksDnD.tsx
index cf1e361f8a..c06b1cf9cf 100644
--- a/packages/excalidraw/components/TopPicksDnD/topPicksDnD.tsx
+++ b/packages/excalidraw/components/TopPicksDnD/topPicksDnD.tsx
@@ -41,7 +41,7 @@ export type TopPicksDragState<T> = {
} | null;
export type TopPicksGhost = {
- /** the ghost's visual. Rendered into `document.body` — outside the
+ /** the ghost's visual. Rendered into the source's `document.body` — outside the
* editor's CSS scope, so theme-dependent styling must be resolved from the
* rendered DOM (computed styles) rather than CSS variables */
content: HTMLElement;
@@ -60,6 +60,8 @@ export type CreateTopPicksGhost<T> = (args: {
}) => TopPicksGhost;
type DragSession<T> = {
+ ownerDocument: Document;
+ ownerWindow: Window;
pointerId: number;
startX: number;
startY: number;
@@ -245,13 +247,18 @@ export const useTopPicksDnD = <T,>({
if (!session) {
return;
}
- const { ghostContent, homeRect: rect } = session;
+ const {
+ ownerDocument,
+ ownerWindow,
+ ghostContent,
+ homeRect: rect,
+ } = session;
- const ghost = document.createElement("div");
+ const ghost = ownerDocument.createElement("div");
ghost.className = GHOST_CLASS;
ghostContent.classList.add(`${GHOST_CLASS}__content`);
ghost.appendChild(ghostContent);
- document.body.appendChild(ghost);
+ ownerDocument.body.appendChild(ghost);
session.ghost = ghost;
session.ghostW = rect.width;
@@ -260,7 +267,7 @@ export const useTopPicksDnD = <T,>({
ghost.style.height = `${rect.height}px`;
positionGhost(x, y);
// let the spawn frame paint at rest, then "lift" (scale-up transition)
- requestAnimationFrame(() => {
+ ownerWindow.requestAnimationFrame(() => {
// unless the drag already ended — don't restyle a ghost that's
// mid-flight in its release animation (or already removed)
if (session?.ghost === ghost) {
@@ -268,7 +275,7 @@ export const useTopPicksDnD = <T,>({
}
});
- document.body.classList.add(BODY_CLASS);
+ ownerDocument.body.classList.add(BODY_CLASS);
session.activated = true;
publish();
};
@@ -342,7 +349,7 @@ export const useTopPicksDnD = <T,>({
if (!session?.ghost) {
return;
}
- const { ghost } = session;
+ const { ghost, ownerWindow } = session;
session.ghost = null;
ghost.classList.add(`${GHOST_CLASS}--dropping`);
const rect = target.rect;
@@ -351,10 +358,10 @@ export const useTopPicksDnD = <T,>({
ghost.style.height = `${rect.height}px`;
ghost.style.transform = `translate(${rect.left}px, ${rect.top}px)`;
}
- window.setTimeout(() => {
+ ownerWindow.setTimeout(() => {
ghost.classList.add(`${GHOST_CLASS}--fade`);
}, 160);
- window.setTimeout(() => {
+ ownerWindow.setTimeout(() => {
ghost.remove();
}, 340);
};
@@ -388,28 +395,43 @@ export const useTopPicksDnD = <T,>({
};
const suppressNextClick = () => {
+ if (!session) {
+ return;
+ }
+ const { ownerWindow } = session;
const suppress = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
- window.addEventListener("click", suppress, { capture: true, once: true });
- window.setTimeout(() => {
- window.removeEventListener("click", suppress, { capture: true });
+ ownerWindow.addEventListener("click", suppress, {
+ capture: true,
+ once: true,
+ });
+ ownerWindow.setTimeout(() => {
+ ownerWindow.removeEventListener("click", suppress, { capture: true });
}, 100);
};
const removeListeners = () => {
- window.removeEventListener("pointermove", onPointerMove, true);
- window.removeEventListener("pointerup", onPointerUp, true);
- window.removeEventListener("pointercancel", onPointerCancel, true);
- window.removeEventListener("keydown", onKeyDown, true);
+ session?.ownerWindow.removeEventListener(
+ "pointermove",
+ onPointerMove,
+ true,
+ );
+ session?.ownerWindow.removeEventListener("pointerup", onPointerUp, true);
+ session?.ownerWindow.removeEventListener(
+ "pointercancel",
+ onPointerCancel,
+ true,
+ );
+ session?.ownerWindow.removeEventListener("keydown", onKeyDown, true);
};
const dispose = () => {
removeListeners();
- document.body.classList.remove(BODY_CLASS);
+ session?.ownerDocument.body.classList.remove(BODY_CLASS);
if (session?.activationTimer != null) {
- window.clearTimeout(session.activationTimer);
+ session.ownerWindow.clearTimeout(session.activationTimer);
}
session = null;
setDragState(null);
@@ -460,18 +482,19 @@ export const useTopPicksDnD = <T,>({
// while we were beyond it no longer applies (wiggle-and-return
// must stay a click)
if (session.activationTimer !== null) {
- window.clearTimeout(session.activationTimer);
+ session.ownerWindow.clearTimeout(session.activationTimer);
session.activationTimer = null;
}
return;
}
- const elapsed = performance.now() - session.startTime;
+ const elapsed =
+ session.ownerWindow.performance.now() - session.startTime;
if (elapsed < DRAG_TIME_THRESHOLD_MS) {
// spatial threshold crossed, temporal not yet — likely a fast
// sloppy click. Wait out the rest of the grace period; the timeout
// covers "flick then hold still", where no further moves fire
if (session.activationTimer === null) {
- session.activationTimer = window.setTimeout(() => {
+ session.activationTimer = session.ownerWindow.setTimeout(() => {
if (session) {
session.activationTimer = null;
// the pointer may have returned inside the tolerance after
@@ -564,6 +587,12 @@ export const useTopPicksDnD = <T,>({
) {
return;
}
+ const sourceEl = event.currentTarget as HTMLElement;
+ const ownerDocument = sourceEl.ownerDocument;
+ const ownerWindow = ownerDocument.defaultView;
+ if (!ownerWindow) {
+ return;
+ }
const stripEl = stripRef.current;
if (!stripEl) {
return;
@@ -576,14 +605,16 @@ export const useTopPicksDnD = <T,>({
const { content: ghostContent, rect: homeRect } =
latestRef.current.createGhost({
value,
- sourceEl: event.currentTarget as HTMLElement,
+ sourceEl,
stripEl,
});
session = {
+ ownerDocument,
+ ownerWindow,
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
- startTime: performance.now(),
+ startTime: ownerWindow.performance.now(),
lastX: event.clientX,
lastY: event.clientY,
activationTimer: null,
@@ -601,10 +632,10 @@ export const useTopPicksDnD = <T,>({
overIndex: null,
duplicateIndex: null,
};
- window.addEventListener("pointermove", onPointerMove, true);
- window.addEventListener("pointerup", onPointerUp, true);
- window.addEventListener("pointercancel", onPointerCancel, true);
- window.addEventListener("keydown", onKeyDown, true);
+ ownerWindow.addEventListener("pointermove", onPointerMove, true);
+ ownerWindow.addEventListener("pointerup", onPointerUp, true);
+ ownerWindow.addEventListener("pointercancel", onPointerCancel, true);
+ ownerWindow.addEventListener("keydown", onKeyDown, true);
};
return {
diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
index cf5bb14641..c5e656221f 100644
--- a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
+++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx
@@ -83,11 +83,22 @@ type InteractiveCanvasProps = {
>;
};
-export const INTERACTIVE_SCENE_ANIMATION_KEY = "animateInteractiveScene";
-
const InteractiveCanvas = (props: InteractiveCanvasProps) => {
const isComponentMounted = useRef(false);
const rendererParams = useRef(null as InteractiveSceneRenderConfig | null);
+ // Unique per mounted instance so concurrent editors don't share the
+ // interactive scene animation slot.
+ const animationKeyRef = useRef<symbol | null>(null);
+ if (animationKeyRef.current === null) {
+ animationKeyRef.current = Symbol("interactiveSceneAnimation");
+ }
+ const animationKey = animationKeyRef.current;
+
+ useEffect(() => {
+ return () => {
+ AnimationController.cancel(animationKey);
+ };
+ }, [animationKey]);
useEffect(() => {
if (!isComponentMounted.current) {
@@ -146,7 +157,7 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
visibleElements: props.visibleElements,
selectedElements: props.selectedElements,
allElementsMap: props.allElementsMap,
- scale: window.devicePixelRatio,
+ scale: props.scale,
appState: props.appState,
renderConfig: {
remotePointerViewportCoords,
@@ -167,9 +178,9 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
deltaTime: 0,
};
- if (!AnimationController.running(INTERACTIVE_SCENE_ANIMATION_KEY)) {
+ if (!AnimationController.running(animationKey)) {
AnimationController.start<InteractiveSceneRenderAnimationState>(
- INTERACTIVE_SCENE_ANIMATION_KEY,
+ animationKey,
({ deltaTime, state }) => {
const nextAnimationState = renderInteractiveScene({
...rendererParams.current!,
@@ -191,6 +202,7 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
return undefined;
},
+ props.app.ownerWindow,
);
}
});
diff --git a/packages/excalidraw/components/hyperlink/Hyperlink.tsx b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
index d5fa4475a7..e68357085f 100644
--- a/packages/excalidraw/components/hyperlink/Hyperlink.tsx
+++ b/packages/excalidraw/components/hyperlink/Hyperlink.tsx
@@ -8,7 +8,12 @@ import {
useState,
} from "react";
-import { EVENT, HYPERLINK_TOOLTIP_DELAY, KEYS } from "@excalidraw/common";
+import {
+ EVENT,
+ HYPERLINK_TOOLTIP_DELAY,
+ KEYS,
+ getTargetWindow,
+} from "@excalidraw/common";
import { getElementAbsoluteCoords } from "@excalidraw/element";
@@ -37,11 +42,21 @@ import type {
} from "@excalidraw/element/types";
import { trackEvent } from "../../analytics";
-import { getTooltipDiv, updateTooltipPosition } from "../../components/Tooltip";
+import {
+ TOOLTIP_VISIBLE_CLASS,
+ getTooltipDiv,
+ hideDocumentTooltip,
+ updateTooltipPosition,
+} from "../../components/Tooltip";
import { t } from "../../i18n";
-import { useAppProps, useEditorInterface, useExcalidrawAppState } from "../App";
+import {
+ useApp,
+ useAppProps,
+ useEditorInterface,
+ useExcalidrawAppState,
+} from "../App";
import { IconButton } from "../IconButton";
import { FreedrawIcon, TrashIcon, elementLinkIcon } from "../icons";
import { getSelectedElements } from "../../scene";
@@ -58,7 +73,42 @@ const POPUP_PADDING = 5;
const SPACE_BOTTOM = 85;
const AUTO_HIDE_TIMEOUT = 500;
+export type HyperlinkTooltipOwner = Record<string, unknown>;
+
let IS_HYPERLINK_TOOLTIP_VISIBLE = false;
+let HYPERLINK_TOOLTIP_OWNER: HyperlinkTooltipOwner | null = null;
+let HYPERLINK_TOOLTIP_OWNER_DOCUMENT: Document | null = null;
+let HYPERLINK_TOOLTIP_OWNER_WINDOW: Window | null = null;
+
+// When the owning window loses focus, the pointer leaves it, or it is
+// hidden (pagehide on close/navigation), no in-window event will ever
+// call hideHyperlinkToolip again, and a sibling window's hide call is a
+// no-op due to the ownership guard, so the owning window itself must
+// drop the tooltip in that case.
+const TOOLTIP_WINDOW_CLEANUPS = new WeakMap<Window, void>();
+
+const registerTooltipWindowCleanup = (ownerWindow: Window) => {
+ if (TOOLTIP_WINDOW_CLEANUPS.has(ownerWindow)) {
+ return;
+ }
+ const dropIfOwned = () => {
+ if (HYPERLINK_TOOLTIP_OWNER_WINDOW === ownerWindow) {
+ clearHyperlinkTooltip();
+ }
+ };
+ const onPointerOut = (event: MouseEvent) => {
+ // relatedTarget is null only when the pointer left the window
+ if (event.relatedTarget === null) {
+ dropIfOwned();
+ }
+ };
+ ownerWindow.addEventListener("blur", dropIfOwned);
+ ownerWindow.addEventListener("mouseout", onPointerOut);
+ // covers window close/navigation that skips blur, so the globals
+ // never retain the detached document/window
+ ownerWindow.addEventListener("pagehide", dropIfOwned);
+ TOOLTIP_WINDOW_CLEANUPS.set(ownerWindow, undefined);
+};
const embeddableLinkCache = new Map<
ExcalidrawEmbeddableElement["id"],
@@ -87,6 +137,7 @@ export const Hyperlink = ({
}) => {
const elementsMap = scene.getNonDeletedElementsMap();
const appState = useExcalidrawAppState();
+ const app = useApp();
const appProps = useAppProps();
const editorInterface = useEditorInterface();
@@ -198,12 +249,16 @@ export const Hyperlink = ({
useEffect(() => {
let timeoutId: number | null = null;
+ // the editor may be rendered into another document, in which case pointer
+ // events never reach the module-realm window
+ const ownerWindow = app.ownerWindow;
+
const handlePointerMove = (event: PointerEvent) => {
if (isEditing) {
return;
}
if (timeoutId) {
- clearTimeout(timeoutId);
+ ownerWindow.clearTimeout(timeoutId);
}
const shouldHide = shouldHideLinkPopup(
element,
@@ -212,19 +267,23 @@ export const Hyperlink = ({
pointFrom(event.clientX, event.clientY),
) as boolean;
if (shouldHide) {
- timeoutId = window.setTimeout(() => {
+ timeoutId = ownerWindow.setTimeout(() => {
setAppState({ showHyperlinkPopup: false });
}, AUTO_HIDE_TIMEOUT);
}
};
- window.addEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
+ ownerWindow.addEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
return () => {
- window.removeEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
+ ownerWindow.removeEventListener(
+ EVENT.POINTER_MOVE,
+ handlePointerMove,
+ false,
+ );
if (timeoutId) {
- clearTimeout(timeoutId);
+ ownerWindow.clearTimeout(timeoutId);
}
};
- }, [appState, element, isEditing, setAppState, elementsMap]);
+ }, [app, appState, element, isEditing, setAppState, elementsMap]);
const handleRemove = useCallback(() => {
trackEvent("hyperlink", "delete");
@@ -386,12 +445,31 @@ export const showHyperlinkTooltip = (
element: NonDeletedExcalidrawElement,
appState: AppState,
elementsMap: ElementsMap,
+ ownerDocument: Document,
+ owner: HyperlinkTooltipOwner,
) => {
- if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
- clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ const ownerWindow = getTargetWindow(ownerDocument);
+ if (!ownerWindow) {
+ return;
+ }
+ // there's only ever one tooltip visible, so take over the ownership from
+ // whichever App currently holds it. Without this, a tooltip shown by
+ // another App would stay visible forever, as that App no longer receives
+ // the pointer events that would hide it.
+ if (HYPERLINK_TOOLTIP_OWNER && HYPERLINK_TOOLTIP_OWNER !== owner) {
+ clearHyperlinkTooltip();
+ } else if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
+ // same owner -> only restart the timer, leaving an already visible
+ // tooltip alone (this runs on every pointer move over a link)
+ HYPERLINK_TOOLTIP_OWNER_WINDOW?.clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ HYPERLINK_TOOLTIP_TIMEOUT_ID = null;
}
- HYPERLINK_TOOLTIP_TIMEOUT_ID = window.setTimeout(
- () => renderTooltip(element, appState, elementsMap),
+ HYPERLINK_TOOLTIP_OWNER = owner;
+ HYPERLINK_TOOLTIP_OWNER_DOCUMENT = ownerDocument;
+ HYPERLINK_TOOLTIP_OWNER_WINDOW = ownerWindow;
+ registerTooltipWindowCleanup(ownerWindow);
+ HYPERLINK_TOOLTIP_TIMEOUT_ID = ownerWindow.setTimeout(
+ () => renderTooltip(element, appState, elementsMap, ownerDocument, owner),
HYPERLINK_TOOLTIP_DELAY,
);
};
@@ -400,14 +478,23 @@ const renderTooltip = (
element: NonDeletedExcalidrawElement,
appState: AppState,
elementsMap: ElementsMap,
+ ownerDocument: Document,
+ owner: HyperlinkTooltipOwner,
) => {
+ HYPERLINK_TOOLTIP_TIMEOUT_ID = null;
+ // ownership may have been cleared or taken over while the timer was
+ // pending (pointer left the window or another App showed its own
+ // tooltip) -> don't render a stale tooltip in an unfocused window
+ if (HYPERLINK_TOOLTIP_OWNER !== owner) {
+ return;
+ }
if (!element.link) {
return;
}
- const tooltipDiv = getTooltipDiv();
+ const tooltipDiv = getTooltipDiv(ownerDocument);
- tooltipDiv.classList.add("excalidraw-tooltip--visible");
+ tooltipDiv.classList.add(TOOLTIP_VISIBLE_CLASS);
tooltipDiv.style.maxWidth = "20rem";
tooltipDiv.textContent = isElementLink(element.link)
? t("labels.link.goToElement")
@@ -440,14 +527,27 @@ const renderTooltip = (
IS_HYPERLINK_TOOLTIP_VISIBLE = true;
};
-export const hideHyperlinkToolip = () => {
+const clearHyperlinkTooltip = () => {
if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
- clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ HYPERLINK_TOOLTIP_OWNER_WINDOW?.clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
+ HYPERLINK_TOOLTIP_TIMEOUT_ID = null;
}
- if (IS_HYPERLINK_TOOLTIP_VISIBLE) {
+ if (IS_HYPERLINK_TOOLTIP_VISIBLE && HYPERLINK_TOOLTIP_OWNER_DOCUMENT) {
IS_HYPERLINK_TOOLTIP_VISIBLE = false;
- getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
+ hideDocumentTooltip(HYPERLINK_TOOLTIP_OWNER_DOCUMENT);
+ }
+ HYPERLINK_TOOLTIP_OWNER = null;
+ HYPERLINK_TOOLTIP_OWNER_DOCUMENT = null;
+ HYPERLINK_TOOLTIP_OWNER_WINDOW = null;
+};
+
+export const hideHyperlinkToolip = (owner?: HyperlinkTooltipOwner) => {
+ // another App owns the tooltip (possibly a sibling App in the same
+ // document) -> it's not ours to hide
+ if (HYPERLINK_TOOLTIP_OWNER && HYPERLINK_TOOLTIP_OWNER !== owner) {
+ return;
}
+ clearHyperlinkTooltip();
};
const shouldHideLinkPopup = (
diff --git a/packages/excalidraw/components/hyperlink/helpers.ts b/packages/excalidraw/components/hyperlink/helpers.ts
index f49c1a961d..a6711b77ce 100644
--- a/packages/excalidraw/components/hyperlink/helpers.ts
+++ b/packages/excalidraw/components/hyperlink/helpers.ts
@@ -2,8 +2,11 @@ import { pointFrom, pointRotateRads } from "@excalidraw/math";
import { MIME_TYPES } from "@excalidraw/common";
import { getElementAbsoluteCoords } from "@excalidraw/element";
+
import { hitElementBoundingBox } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
import type { GlobalPoint, Radians } from "@excalidraw/math";
import type { Bounds } from "@excalidraw/common";
@@ -16,16 +19,113 @@ import type { AppState } from "../../types";
export const DEFAULT_LINK_SIZE = 12;
-export const EXTERNAL_LINK_IMG = document.createElement("img");
-EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
+const EXTERNAL_LINK_SRC = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" class="feather feather-external-link"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
)}`;
-export const ELEMENT_LINK_IMG = document.createElement("img");
-ELEMENT_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
+const ELEMENT_LINK_SRC = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-arrow-big-right-line"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 9v-3.586a1 1 0 0 1 1.707 -.707l6.586 6.586a1 1 0 0 1 0 1.414l-6.586 6.586a1 1 0 0 1 -1.707 -.707v-3.586h-6v-6h6z" /><path d="M3 9v6" /></svg>`,
)}`;
+type LinkImgSlot = "external" | "element";
+type SettledLinkImgStatus = Exclude<LinkImgStatus, "decoding">;
+
+export type LinkImgStatus = "decoding" | "decoded" | "failed";
+
+export type LinkImg = {
+ /** Only safe as a `drawImage` source while `status` is `decoded`. */
+ img: HTMLImageElement;
+ status: LinkImgStatus;
+ settled: Promise<SettledLinkImgStatus>;
+};
+
+/**
+ * Built lazily so that importing this module never touches `document`. The
+ * export pipeline pulls it in even in headless environments.
+ *
+ * Browsers decode `src` asynchronously, so a `drawImage` in the same task as
+ * the `src` set silently draws nothing. Callers must check `status` and skip
+ * the icon until the decode lands; `startLinkImgDecoding` kicks the decode off
+ * on mount so it is settled long before a link icon is drawn.
+ */
+const linkImgs = new WeakMap<
+ RenderEnvironment,
+ Partial<Record<LinkImgSlot, LinkImg>>
+>();
+
+const settleLinkImg = (
+ entry: LinkImg,
+ status: SettledLinkImgStatus,
+ resolve: (status: SettledLinkImgStatus) => void,
+) => {
+ // a host `createImage` may fire both handlers; the first settle wins, so a
+ // late `onerror` can't undo a successful decode
+ if (entry.status !== "decoding") {
+ return;
+ }
+ entry.status = status;
+ resolve(status);
+};
+
+const getLinkImg = (
+ slot: LinkImgSlot,
+ src: string,
+ env: RenderEnvironment,
+): LinkImg => {
+ let slots = linkImgs.get(env);
+ const existing = slots?.[slot];
+ if (existing) {
+ return existing;
+ }
+ const img = env.createImage();
+ const decoded = img.complete && img.naturalWidth > 0;
+ let settle: (status: SettledLinkImgStatus) => void = () => {};
+ const entry: LinkImg = {
+ img,
+ status: decoded ? "decoded" : "decoding",
+ settled: decoded
+ ? Promise.resolve("decoded")
+ : new Promise((resolve) => {
+ settle = resolve;
+ }),
+ };
+ if (entry.status === "decoding") {
+ img.onload = () => settleLinkImg(entry, "decoded", settle);
+ img.onerror = () => settleLinkImg(entry, "failed", settle);
+ }
+ if (!slots) {
+ slots = {};
+ linkImgs.set(env, slots);
+ }
+ // registered before `src` so that a host firing `onload` synchronously
+ // re-enters into the slot rather than starting another image
+ slots[slot] = entry;
+ img.src = src;
+ return entry;
+};
+
+export const getExternalLinkImg = (renderEnvironment: RenderEnvironment) =>
+ getLinkImg("external", EXTERNAL_LINK_SRC, renderEnvironment);
+export const getElementLinkImg = (renderEnvironment: RenderEnvironment) =>
+ getLinkImg("element", ELEMENT_LINK_SRC, renderEnvironment);
+
+export const startLinkImgDecoding = async (
+ renderEnvironment: RenderEnvironment,
+) => {
+ const pending = [
+ getExternalLinkImg(renderEnvironment),
+ getElementLinkImg(renderEnvironment),
+ ].filter((entry) => entry.status === "decoding");
+
+ if (!pending.length) {
+ return false;
+ }
+
+ const statuses = await Promise.all(pending.map((entry) => entry.settled));
+
+ return statuses.includes("decoded");
+};
+
export const getLinkHandleFromCoords = (
[x1, y1, x2, y2]: Bounds,
angle: Radians,
diff --git a/packages/excalidraw/data/blob.ts b/packages/excalidraw/data/blob.ts
index 3234965960..5ff3102071 100644
--- a/packages/excalidraw/data/blob.ts
+++ b/packages/excalidraw/data/blob.ts
@@ -7,6 +7,8 @@ import {
isPromiseLike,
} from "@excalidraw/common";
+import { getRenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
import type { ValueOf } from "@excalidraw/common/utility-types";
import type { ExcalidrawElement, FileId } from "@excalidraw/element/types";
@@ -327,7 +329,7 @@ const getImageFileDimensions = async (file: File) => {
}
return new Promise<{ width: number; height: number }>((resolve, reject) => {
- const image = new Image();
+ const image = getRenderEnvironment().createImage();
const cleanup = () => {
image.onload = null;
diff --git a/packages/excalidraw/data/index.ts b/packages/excalidraw/data/index.ts
index d98fc2ff51..4c51de3ed5 100644
--- a/packages/excalidraw/data/index.ts
+++ b/packages/excalidraw/data/index.ts
@@ -21,6 +21,7 @@ import type {
NonDeleted,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
+import type { RenderEnvironment } from "@excalidraw/element";
import {
copyBlobToClipboardAsPng,
@@ -105,12 +106,14 @@ export const exportCanvas = async (
name = appState.name || DEFAULT_FILENAME,
fileHandle = null,
exportingFrame = null,
+ renderEnvironment,
}: {
exportPadding?: number;
/** filename, if applicable */
name?: string;
fileHandle?: FileSystemFileHandle | null;
exportingFrame: NonDeleted<ExcalidrawFrameLikeElement> | null;
+ renderEnvironment?: RenderEnvironment;
},
) => {
if (elements.length === 0) {
@@ -134,6 +137,7 @@ export const exportCanvas = async (
config: {
...config,
embedScene: appState.exportEmbedScene && type === "svg",
+ environment: renderEnvironment,
},
});
@@ -172,7 +176,7 @@ export const exportCanvas = async (
appState,
files,
},
- config,
+ config: { ...config, environment: renderEnvironment },
});
if (type === "png") {
diff --git a/packages/excalidraw/fonts/Fonts.ts b/packages/excalidraw/fonts/Fonts.ts
index c028dbd8c0..3180091123 100644
--- a/packages/excalidraw/fonts/Fonts.ts
+++ b/packages/excalidraw/fonts/Fonts.ts
@@ -1,5 +1,6 @@
import {
FONT_FAMILY,
+ DEFAULT_FONT_FAMILY,
FONT_FAMILY_FALLBACKS,
CJK_HAND_DRAWN_FALLBACK_FONT,
WINDOWS_EMOJI_FALLBACK_FONT,
@@ -44,8 +45,6 @@ import { VirgilFontFaces } from "./Virgil";
import { XiaolaiFontFaces } from "./Xiaolai";
export class Fonts {
- // it's ok to track fonts across multiple instances only once, so let's use
- // a static member to reduce memory footprint
public static readonly loadedFontsCache = new Set<string>();
private static _registered:
@@ -82,6 +81,7 @@ export class Fonts {
private readonly scene: Scene;
private readonly ownerDocument: Document;
+ private readonly loadedFonts = new Set<string>();
constructor(scene: Scene, ownerDocument: Document = document) {
this.scene = scene;
@@ -104,17 +104,19 @@ export class Fonts {
* of the supplied fontFaces has not already been processed.
*/
public onLoaded = (fontFaces: readonly FontFace[]): void => {
- // bail if all fonts with have been processed. We're checking just a
- // subset of the font properties (though it should be enough), so it
- // can technically bail on a false positive.
+ // bail if all fonts with have been processed by THIS instance. We're
+ // checking just a subset of the font properties (though it should be
+ // enough), so it can technically bail on a false positive.
let shouldBail = true;
for (const fontFace of fontFaces) {
const sig = `${fontFace.family}-${fontFace.style}-${fontFace.weight}-${fontFace.unicodeRange}`;
// make sure to update our cache with all the loaded font faces
- if (!Fonts.loadedFontsCache.has(sig)) {
- Fonts.loadedFontsCache.add(sig);
+ Fonts.loadedFontsCache.add(sig);
+
+ if (!this.loadedFonts.has(sig)) {
+ this.loadedFonts.add(sig);
shouldBail = false;
}
}
@@ -150,11 +152,19 @@ export class Fonts {
/**
* Load font faces for a given scene and trigger scene update.
*/
- public loadSceneFonts = async (): Promise<FontFace[]> => {
- const sceneFamilies = this.getSceneFamilies();
- const charsPerFamily = Fonts.getCharsPerFamily(
- this.scene.getNonDeletedElements(),
- );
+ public loadSceneFonts = async (
+ defaultFontFamily: ExcalidrawTextElement["fontFamily"] = DEFAULT_FONT_FAMILY,
+ ): Promise<FontFace[]> => {
+ const elements = this.scene.getNonDeletedElements();
+ const sceneFamilies = Fonts.getUniqueFamilies(elements);
+ const charsPerFamily = Fonts.getCharsPerFamily(elements);
+
+ // prewarm the default font so that the first text element is not
+ // rendered with a fallback font
+ if (!sceneFamilies.includes(defaultFontFamily)) {
+ sceneFamilies.push(defaultFontFamily);
+ charsPerFamily[defaultFontFamily] = new Set("Excalidraw");
+ }
return Fonts.loadFontFaces(
sceneFamilies,
@@ -168,12 +178,20 @@ export class Fonts {
*/
public static loadElementsFonts = async (
elements: readonly ExcalidrawElement[],
- ownerDocument: Document = document,
+ ownerDocument?: Document,
): Promise<FontFace[]> => {
+ const doc =
+ ownerDocument ?? (typeof document !== "undefined" ? document : null);
+
+ // NOTE: headless environments should register fonts prior to rendering
+ if (!doc?.fonts) {
+ return [];
+ }
+
const fontFamilies = Fonts.getUniqueFamilies(elements);
const charsPerFamily = Fonts.getCharsPerFamily(elements);
- return Fonts.loadFontFaces(fontFamilies, charsPerFamily, ownerDocument);
+ return Fonts.loadFontFaces(fontFamilies, charsPerFamily, doc);
};
/**
@@ -468,13 +486,6 @@ export class Fonts {
? Array.from(charsPerFamily[family]).join("")
: "";
}
-
- /**
- * Get all registered font families.
- */
- private static getAllFamilies() {
- return Array.from(Fonts.registered.keys());
- }
}
export interface ExcalidrawFontFaceDescriptor {
diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsx
index 3f66b76367..01636ba107 100644
--- a/packages/excalidraw/index.tsx
+++ b/packages/excalidraw/index.tsx
@@ -69,6 +69,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
onExport,
className,
ownerDocument = document,
+ renderEnvironment,
onChange,
onThemeChange,
onIncrement,
@@ -211,6 +212,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
onExport={onExport}
className={className}
ownerDocument={ownerDocument}
+ renderEnvironment={renderEnvironment}
onChange={onChange}
onThemeChange={onThemeChange}
onIncrement={onIncrement}
@@ -515,6 +517,7 @@ export { isElementLink } from "@excalidraw/element";
export { Fonts } from "./fonts/Fonts";
export { setCustomTextMetricsProvider } from "@excalidraw/element";
+export type { RenderEnvironment } from "@excalidraw/element";
export { CommandPalette } from "./components/CommandPalette/CommandPalette";
diff --git a/packages/excalidraw/package.json b/packages/excalidraw/package.json
index d2f3d9f0b2..8cbaa2613d 100644
--- a/packages/excalidraw/package.json
+++ b/packages/excalidraw/package.json
@@ -53,7 +53,7 @@
"not dead",
"not ie <= 11",
"not op_mini all",
- "not safari < 12",
+ "not safari < 14.1",
"not kaios <= 2.5",
"not edge < 79",
"not chrome < 70",
diff --git a/packages/excalidraw/reactUtils.ts b/packages/excalidraw/reactUtils.ts
index a779fcfccf..ccceb00d02 100644
--- a/packages/excalidraw/reactUtils.ts
+++ b/packages/excalidraw/reactUtils.ts
@@ -24,11 +24,15 @@ export const withBatchedUpdatesThrottled = <
TFunction extends ((event: any) => void) | (() => void),
>(
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
+ ownerWindow: Window = window,
) => {
- // @ts-ignore
- return throttleRAF<Parameters<TFunction>>(((event) => {
- unstable_batchedUpdates(func, event);
- }) as TFunction);
+ return throttleRAF<Parameters<TFunction>>(
+ // @ts-ignore
+ ((event) => {
+ unstable_batchedUpdates(func, event);
+ }) as TFunction,
+ ownerWindow,
+ );
};
export const isRenderThrottlingEnabled = (() => {
diff --git a/packages/excalidraw/renderer/animation.ts b/packages/excalidraw/renderer/animation.ts
index 27f85bb472..af8d38222f 100644
--- a/packages/excalidraw/renderer/animation.ts
+++ b/packages/excalidraw/renderer/animation.ts
@@ -1,5 +1,10 @@
import { isRenderThrottlingEnabled } from "../reactUtils";
+/** String keys are shared process-wide; symbols are created per owning
+ * instance, which lets concurrent instances run the same named animation
+ * independently. */
+export type AnimationKey = string | symbol;
+
export type Animation<R extends object> = (params: {
deltaTime: number;
state?: R;
@@ -9,16 +14,34 @@ type AnimationRecord = {
animation: Animation<any>;
lastTime: number;
state: any;
+ scheduler: AnimationScheduler;
};
-export class AnimationController {
- private static scheduledFrame:
- | { id: ReturnType<typeof requestAnimationFrame>; type: "raf" }
- | { id: ReturnType<typeof setTimeout>; type: "timeout" }
- | null = null;
- private static animations = new Map<string, AnimationRecord>();
+export type AnimationScheduler = Pick<
+ Window,
+ | "requestAnimationFrame"
+ | "cancelAnimationFrame"
+ | "setTimeout"
+ | "clearTimeout"
+>;
+
+type ScheduledFrame =
+ | { id: number; type: "raf" }
+ | { id: number; type: "timeout" };
- static start<R extends object>(key: string, animation: Animation<R>) {
+export class AnimationController {
+ private static scheduledFrames = new Map<
+ AnimationScheduler,
+ ScheduledFrame
+ >();
+ private static animations = new Map<AnimationKey, AnimationRecord>();
+ private static readonly schedulerCleanups = new WeakMap<Window, void>();
+
+ static start<R extends object>(
+ key: AnimationKey,
+ animation: Animation<R>,
+ scheduler: AnimationScheduler = window,
+ ) {
if (AnimationController.animations.has(key)) {
return;
}
@@ -27,6 +50,7 @@ export class AnimationController {
animation,
lastTime: 0,
state: undefined,
+ scheduler,
};
AnimationController.animations.set(key, record);
@@ -39,7 +63,7 @@ export class AnimationController {
} catch (error) {
if (AnimationController.animations.get(key) === record) {
AnimationController.animations.delete(key);
- AnimationController.cancelScheduledFrameIfIdle();
+ AnimationController.cancelScheduledFrameIfIdle(record.scheduler);
}
throw error;
}
@@ -53,63 +77,95 @@ export class AnimationController {
if (!initialState) {
AnimationController.animations.delete(key);
- AnimationController.cancelScheduledFrameIfIdle();
+ AnimationController.cancelScheduledFrameIfIdle(record.scheduler);
return;
}
record.state = initialState;
- AnimationController.scheduleNextFrame();
+ AnimationController.scheduleNextFrame(record.scheduler);
}
- private static scheduleNextFrame() {
- if (AnimationController.scheduledFrame) {
+ private static scheduleNextFrame(scheduler: AnimationScheduler) {
+ if (AnimationController.scheduledFrames.has(scheduler)) {
return;
}
+ AnimationController.registerSchedulerCleanup(scheduler);
if (isRenderThrottlingEnabled()) {
- AnimationController.scheduledFrame = {
- id: requestAnimationFrame(AnimationController.tick),
+ AnimationController.scheduledFrames.set(scheduler, {
+ id: scheduler.requestAnimationFrame(() =>
+ AnimationController.tick(scheduler),
+ ),
type: "raf",
- };
+ });
} else {
- AnimationController.scheduledFrame = {
- id: setTimeout(AnimationController.tick, 0),
+ AnimationController.scheduledFrames.set(scheduler, {
+ id: scheduler.setTimeout(() => AnimationController.tick(scheduler), 0),
type: "timeout",
- };
+ });
}
}
- private static cancelScheduledFrame() {
- if (!AnimationController.scheduledFrame) {
+ private static cancelScheduledFrame(scheduler: AnimationScheduler) {
+ const scheduledFrame = AnimationController.scheduledFrames.get(scheduler);
+ if (!scheduledFrame) {
return;
}
- if (AnimationController.scheduledFrame.type === "raf") {
- cancelAnimationFrame(AnimationController.scheduledFrame.id);
+ if (scheduledFrame.type === "raf") {
+ scheduler.cancelAnimationFrame(scheduledFrame.id);
} else {
- clearTimeout(AnimationController.scheduledFrame.id);
+ scheduler.clearTimeout(scheduledFrame.id);
}
- AnimationController.scheduledFrame = null;
+ AnimationController.scheduledFrames.delete(scheduler);
}
- private static cancelScheduledFrameIfIdle() {
- if (AnimationController.animations.size > 0) {
+ private static cancelScheduledFrameIfIdle(scheduler: AnimationScheduler) {
+ if (
+ [...AnimationController.animations.values()].some(
+ (animation) => animation.scheduler === scheduler,
+ )
+ ) {
return false;
}
- AnimationController.cancelScheduledFrame();
+ AnimationController.cancelScheduledFrame(scheduler);
return true;
}
- private static tick() {
- AnimationController.scheduledFrame = null;
+ private static registerSchedulerCleanup(scheduler: AnimationScheduler) {
+ const win = scheduler as Window;
+ if (typeof win.addEventListener !== "function") {
+ return;
+ }
+ if (AnimationController.schedulerCleanups.has(win)) {
+ return;
+ }
+ const drop = () => {
+ for (const [key, record] of AnimationController.animations) {
+ if (record.scheduler === scheduler) {
+ AnimationController.animations.delete(key);
+ }
+ }
+ // The scheduled frame lives in the closing window and never fires
+ AnimationController.scheduledFrames.delete(scheduler);
+ };
+ win.addEventListener("pagehide", drop);
+ AnimationController.schedulerCleanups.set(win, undefined);
+ }
- if (AnimationController.animations.size > 0) {
+ private static tick(scheduler: AnimationScheduler) {
+ AnimationController.scheduledFrames.delete(scheduler);
+
+ const animations = [...AnimationController.animations].filter(
+ ([, animation]) => animation.scheduler === scheduler,
+ );
+
+ if (animations.length > 0) {
// A callback may synchronously add, cancel, or replace animations. Work
// from the frame's starting set so newly started animations begin on the
// next frame and every record runs at most once per tick.
- const animations = [...AnimationController.animations];
for (const [key, animation] of animations) {
if (AnimationController.animations.get(key) !== animation) {
continue;
@@ -133,7 +189,7 @@ export class AnimationController {
if (!state) {
AnimationController.animations.delete(key);
- if (AnimationController.cancelScheduledFrameIfIdle()) {
+ if (AnimationController.cancelScheduledFrameIfIdle(scheduler)) {
return;
}
} else {
@@ -142,25 +198,30 @@ export class AnimationController {
}
}
- if (AnimationController.cancelScheduledFrameIfIdle()) {
+ if (AnimationController.cancelScheduledFrameIfIdle(scheduler)) {
return;
}
- AnimationController.scheduleNextFrame();
+ AnimationController.scheduleNextFrame(scheduler);
}
}
- static running(key: string) {
+ static running(key: AnimationKey) {
return AnimationController.animations.has(key);
}
- static cancel(key: string) {
+ static cancel(key: AnimationKey) {
+ const record = AnimationController.animations.get(key);
AnimationController.animations.delete(key);
- AnimationController.cancelScheduledFrameIfIdle();
+ if (record) {
+ AnimationController.cancelScheduledFrameIfIdle(record.scheduler);
+ }
}
static reset() {
AnimationController.animations.clear();
- AnimationController.cancelScheduledFrame();
+ for (const scheduler of [...AnimationController.scheduledFrames.keys()]) {
+ AnimationController.cancelScheduledFrame(scheduler);
+ }
}
}
diff --git a/packages/excalidraw/renderer/staticScene.ts b/packages/excalidraw/renderer/staticScene.ts
index 4307e502ba..631454f26e 100644
--- a/packages/excalidraw/renderer/staticScene.ts
+++ b/packages/excalidraw/renderer/staticScene.ts
@@ -23,10 +23,15 @@ import {
getRenderElementWithPositionOverride,
resolveElementRenderState,
renderElement,
+ withSavedContext,
} from "@excalidraw/element";
+import { getRenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
import { getElementAbsoluteCoords } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
import type { ElementRenderState } from "@excalidraw/element";
import type {
@@ -37,8 +42,8 @@ import type {
} from "@excalidraw/element/types";
import {
- EXTERNAL_LINK_IMG,
- ELEMENT_LINK_IMG,
+ getExternalLinkImg,
+ getElementLinkImg,
getLinkHandleFromCoords,
} from "../components/hyperlink/helpers";
@@ -54,6 +59,25 @@ import type {
} from "../scene/types";
import type { StaticCanvasAppState, Zoom } from "../types";
+/**
+ * A render failure is per-element on purpose, on export too: one bad element
+ * must not blank the canvas or fail the export, the rest of the scene
+ * survives it.
+ */
+const logElementRenderError = (
+ error: unknown,
+ element: NonDeletedExcalidrawElement,
+) => {
+ console.error(
+ error,
+ element.id,
+ element.x,
+ element.y,
+ element.width,
+ element.height,
+ );
+};
+
const GridLineColor = {
[THEME.LIGHT]: {
bold: "#dddddd",
@@ -188,15 +212,20 @@ export const frameClip = (
);
};
-type LinkIconCanvas = HTMLCanvasElement & { zoom: number };
+type LinkIconCanvasCacheType = "regularLink" | "elementLink";
-const linkIconCanvasCache: {
- regularLink: LinkIconCanvas | null;
- elementLink: LinkIconCanvas | null;
-} = {
- regularLink: null,
- elementLink: null,
-};
+const linkIconCanvasCache = new WeakMap<
+ RenderEnvironment,
+ Map<string, HTMLCanvasElement>
+>();
+const LINK_ICON_CACHE_MAX_ENTRIES = 8;
+
+const getLinkIconCacheKey = (
+ type: LinkIconCanvasCacheType,
+ canvasWidth: number,
+ canvasHeight: number,
+ backgroundColor: string,
+) => `${type}:${canvasWidth}x${canvasHeight}:${backgroundColor}`;
const renderLinkIcon = (
element: NonDeletedExcalidrawElement,
@@ -204,6 +233,9 @@ const renderLinkIcon = (
appState: StaticCanvasAppState,
elementsMap: ElementsMap,
renderState: ElementRenderState,
+ /** backing-store scale, see StaticCanvasRenderConfig["scale"] */
+ scale: number,
+ renderEnvironment: RenderEnvironment,
) => {
if (element.link && !appState.selectedElementIds[element.id]) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
@@ -223,46 +255,73 @@ const renderLinkIcon = (
context.translate(appState.scrollX + centerX, appState.scrollY + centerY);
context.rotate(element.angle);
- const canvasKey = isElementLink(element.link)
+ const canvasKey: LinkIconCanvasCacheType = isElementLink(element.link)
? "elementLink"
: "regularLink";
- let linkCanvas = linkIconCanvasCache[canvasKey];
+ const linkImg =
+ canvasKey === "elementLink"
+ ? getElementLinkImg(renderEnvironment)
+ : getExternalLinkImg(renderEnvironment);
- if (!linkCanvas || linkCanvas.zoom !== appState.zoom.value) {
- linkCanvas = Object.assign(document.createElement("canvas"), {
- zoom: appState.zoom.value,
- });
- linkCanvas.width = width * window.devicePixelRatio * appState.zoom.value;
- linkCanvas.height =
- height * window.devicePixelRatio * appState.zoom.value;
- linkIconCanvasCache[canvasKey] = linkCanvas;
+ if (linkImg.status !== "decoded") {
+ context.restore();
+ return;
+ }
+
+ const canvasWidth = Math.max(
+ 1,
+ Math.floor(width * scale * appState.zoom.value),
+ );
+ const canvasHeight = Math.max(
+ 1,
+ Math.floor(height * scale * appState.zoom.value),
+ );
+ const backgroundColor = appState.viewBackgroundColor || COLOR_WHITE;
+ const cacheKey = getLinkIconCacheKey(
+ canvasKey,
+ canvasWidth,
+ canvasHeight,
+ backgroundColor,
+ );
+
+ let cache = linkIconCanvasCache.get(renderEnvironment);
+ if (!cache) {
+ cache = new Map();
+ linkIconCanvasCache.set(renderEnvironment, cache);
+ }
+
+ let linkCanvas = cache.get(cacheKey);
+
+ if (linkCanvas) {
+ cache.delete(cacheKey);
+ cache.set(cacheKey, linkCanvas);
+ } else {
+ linkCanvas = renderEnvironment.createCanvas();
+ linkCanvas.width = canvasWidth;
+ linkCanvas.height = canvasHeight;
+ cache.set(cacheKey, linkCanvas);
+ if (cache.size > LINK_ICON_CACHE_MAX_ENTRIES) {
+ const lruKey = cache.keys().next().value;
+ if (lruKey !== undefined) {
+ cache.delete(lruKey);
+ }
+ }
const linkCanvasCacheContext = linkCanvas.getContext("2d")!;
linkCanvasCacheContext.scale(
- window.devicePixelRatio * appState.zoom.value,
- window.devicePixelRatio * appState.zoom.value,
+ scale * appState.zoom.value,
+ scale * appState.zoom.value,
);
// Seed a sane default so a corrupted color (silently rejected by the
// canvas) falls back to white instead of a stale fillStyle.
linkCanvasCacheContext.fillStyle = COLOR_WHITE;
- linkCanvasCacheContext.fillStyle =
- appState.viewBackgroundColor || COLOR_WHITE;
+ linkCanvasCacheContext.fillStyle = backgroundColor;
linkCanvasCacheContext.fillRect(0, 0, width, height);
- if (canvasKey === "elementLink") {
- linkCanvasCacheContext.drawImage(ELEMENT_LINK_IMG, 0, 0, width, height);
- } else {
- linkCanvasCacheContext.drawImage(
- EXTERNAL_LINK_IMG,
- 0,
- 0,
- width,
- height,
- );
- }
+ linkCanvasCacheContext.drawImage(linkImg.img, 0, 0, width, height);
linkCanvasCacheContext.restore();
}
@@ -418,48 +477,48 @@ const _renderStaticScene = ({
return;
}
- context.save();
const boundTextElement = getBoundTextElement(element, elementsMap);
const renderState = getRenderState(element);
- clipElementToFrame(element, renderState);
- renderElement(
- element,
- elementsMap,
- allElementsMap,
- rc,
- context,
- renderConfig,
- appState,
- renderState,
- );
-
- if (boundTextElement) {
+ withSavedContext(context, () => {
+ clipElementToFrame(element, renderState);
renderElement(
- boundTextElement,
+ element,
elementsMap,
allElementsMap,
rc,
context,
renderConfig,
appState,
+ renderState,
);
- }
- context.restore();
+ if (boundTextElement) {
+ renderElement(
+ boundTextElement,
+ elementsMap,
+ allElementsMap,
+ rc,
+ context,
+ renderConfig,
+ appState,
+ );
+ }
+ });
if (!isExporting && renderConfig.renderLinks !== false) {
- renderLinkIcon(element, context, appState, elementsMap, renderState);
+ renderLinkIcon(
+ element,
+ context,
+ appState,
+ elementsMap,
+ renderState,
+ scale,
+ getRenderEnvironment(renderConfig.renderEnvironment),
+ );
}
} catch (error: any) {
- console.error(
- error,
- element.id,
- element.x,
- element.y,
- element.width,
- element.height,
- );
+ logElementRenderError(error, element);
}
});
@@ -469,50 +528,62 @@ const _renderStaticScene = ({
.forEach((element) => {
try {
const renderState = getRenderState(element);
- context.save();
- clipElementToFrame(element, renderState);
- renderElement(
- element,
- elementsMap,
- allElementsMap,
- rc,
- context,
- renderConfig,
- appState,
- renderState,
- );
-
- if (
- isIframeLikeElement(element) &&
- (isExporting ||
- (isEmbeddableElement(element) &&
- renderConfig.embedsValidationStatus.get(element.id) !== true)) &&
- element.width &&
- element.height
- ) {
- const label = {
- ...createPlaceholderEmbeddableLabel(element),
- // Synthetic visual: resolve overrides and frame opacity through
- // its owner, without creating another animation target.
- id: element.id,
- frameId: element.frameId,
- };
+ withSavedContext(context, () => {
+ clipElementToFrame(element, renderState);
renderElement(
- label,
+ element,
elementsMap,
allElementsMap,
rc,
context,
renderConfig,
appState,
+ renderState,
);
- }
- if (!isExporting && renderConfig.renderLinks !== false) {
- renderLinkIcon(element, context, appState, elementsMap, renderState);
- }
- context.restore();
+
+ if (
+ isIframeLikeElement(element) &&
+ (isExporting ||
+ (isEmbeddableElement(element) &&
+ renderConfig.embedsValidationStatus.get(element.id) !==
+ true)) &&
+ element.width &&
+ element.height
+ ) {
+ const label = {
+ ...createPlaceholderEmbeddableLabel(
+ element,
+ renderConfig.renderEnvironment,
+ ),
+ // Synthetic visual: resolve overrides and frame opacity through
+ // its owner, without creating another animation target.
+ id: element.id,
+ frameId: element.frameId,
+ };
+ renderElement(
+ label,
+ elementsMap,
+ allElementsMap,
+ rc,
+ context,
+ renderConfig,
+ appState,
+ );
+ }
+ if (!isExporting && renderConfig.renderLinks !== false) {
+ renderLinkIcon(
+ element,
+ context,
+ appState,
+ elementsMap,
+ renderState,
+ scale,
+ getRenderEnvironment(renderConfig.renderEnvironment),
+ );
+ }
+ });
} catch (error: any) {
- console.error(error);
+ logElementRenderError(error, element);
}
});
@@ -529,17 +600,57 @@ const _renderStaticScene = ({
appState,
);
} catch (error) {
- console.error(error);
+ logElementRenderError(error, element);
}
});
};
-/** throttled to animation framerate */
-export const renderStaticSceneThrottled = throttleRAF(
- (config: StaticSceneRenderConfig) => {
- _renderStaticScene(config);
- },
-);
+type StaticSceneThrottle = ReturnType<typeof throttleRAF>;
+
+const staticSceneThrottles = new WeakMap<
+ HTMLCanvasElement,
+ { throttle: StaticSceneThrottle; ownerWindow: Window }
+>();
+
+const getStaticSceneThrottle = (canvas: HTMLCanvasElement) => {
+ const ownerWindow = canvas.ownerDocument.defaultView ?? window;
+ let entry = staticSceneThrottles.get(canvas);
+ // the owner window is captured when the throttle is built, so a canvas
+ // adopted into another document (moved rather than remounted) would keep
+ // scheduling on the old window's rAF -- which never fires once that window
+ // is closed. rebuild whenever the owner window no longer matches.
+ if (entry && entry.ownerWindow !== ownerWindow) {
+ entry.throttle.cancel();
+ entry = undefined;
+ }
+ if (!entry) {
+ entry = {
+ throttle: throttleRAF((config: StaticSceneRenderConfig) => {
+ _renderStaticScene(config);
+ }, ownerWindow),
+ ownerWindow,
+ };
+ staticSceneThrottles.set(canvas, entry);
+ }
+ return entry.throttle;
+};
+
+/**
+ * Throttled to animation framerate, one throttle per canvas. A shared
+ * throttle drops all but the last caller's pending frame when multiple
+ * editors render in the same frame, and a module-realm scheduler would run
+ * popout renders on the main window's rAF, which freezes while that window
+ * is hidden.
+ */
+export const renderStaticSceneThrottled = (config: StaticSceneRenderConfig) => {
+ getStaticSceneThrottle(config.canvas)(config);
+};
+
+/** Drops the canvas' pending frame; the throttle itself is dropped with the
+ * canvas. */
+export const cancelStaticSceneThrottle = (canvas: HTMLCanvasElement) => {
+ staticSceneThrottles.get(canvas)?.throttle.cancel();
+};
/**
* Static scene is the non-ui canvas where we render elements.
diff --git a/packages/excalidraw/renderer/staticSvgScene.ts b/packages/excalidraw/renderer/staticSvgScene.ts
index 17f69cfa50..1ef111739f 100644
--- a/packages/excalidraw/renderer/staticSvgScene.ts
+++ b/packages/excalidraw/renderer/staticSvgScene.ts
@@ -323,7 +323,10 @@ const renderElementToSvg = (
);
addToRoot(node, element);
- const label = createPlaceholderEmbeddableLabel(element);
+ const label = createPlaceholderEmbeddableLabel(
+ element,
+ renderConfig.renderEnvironment,
+ );
renderElementToSvg(
label,
elementsMap,
@@ -743,7 +746,7 @@ const renderElementToSvg = (
renderConfig.frameRendering.enabled &&
renderConfig.frameRendering.outline
) {
- const rect = document.createElementNS(SVG_NS, "rect");
+ const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");
rect.setAttribute(
"transform",
diff --git a/packages/excalidraw/scene/Renderer.ts b/packages/excalidraw/scene/Renderer.ts
index ba7a8f9d42..2f1dfd0733 100644
--- a/packages/excalidraw/scene/Renderer.ts
+++ b/packages/excalidraw/scene/Renderer.ts
@@ -18,7 +18,7 @@ import type {
import type { Scene } from "@excalidraw/element";
-import { renderStaticSceneThrottled } from "../renderer/staticScene";
+import { cancelStaticSceneThrottle } from "../renderer/staticScene";
import type { RenderableElementsMap } from "./types";
@@ -416,8 +416,8 @@ export class Renderer {
// NOTE Doesn't destroy everything (scene, rc, etc.) because it may not be
// safe to break TS contract here (for upstream cases)
- public destroy() {
- renderStaticSceneThrottled.cancel();
+ public destroy(staticCanvas: HTMLCanvasElement) {
+ cancelStaticSceneThrottle(staticCanvas);
this._getRenderableElements.clear();
this._getVisibleElementsWithRenderOffsets.clear();
}
diff --git a/packages/excalidraw/scene/export.ts b/packages/excalidraw/scene/export.ts
index 84300e9c01..fb025ee480 100644
--- a/packages/excalidraw/scene/export.ts
+++ b/packages/excalidraw/scene/export.ts
@@ -21,7 +21,9 @@ import { getCommonBounds, getElementAbsoluteCoords } from "@excalidraw/element";
import {
getInitializedImageElements,
+ getLineWidth,
getNonDeletedElements,
+ getRenderEnvironment,
updateImageCache,
} from "@excalidraw/element";
@@ -42,6 +44,8 @@ import { type Mutable } from "@excalidraw/common/utility-types";
import { newTextElement } from "@excalidraw/element";
+import type { RenderEnvironment } from "@excalidraw/element";
+
import type {
ExcalidrawFrameLikeElement,
ExcalidrawTextElement,
@@ -92,33 +96,33 @@ const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;
const truncateText = (
element: NonDeleted<ExcalidrawTextElement>,
maxWidth: number,
+ renderEnvironment: RenderEnvironment,
) => {
if (element.width <= maxWidth) {
return element;
}
- const canvas = document.createElement("canvas");
- const ctx = canvas.getContext("2d")!;
- ctx.font = getFontString({
+ const font = getFontString({
fontFamily: element.fontFamily,
fontSize: element.fontSize,
});
let text = element.text;
- const metrics = ctx.measureText(text);
-
- if (metrics.width > maxWidth) {
+ if (getLineWidth(text, font, renderEnvironment) > maxWidth) {
// we iterate from the right, removing characters one by one instead
// of building the string up. This assumes that it's more likely
// your frame names will overflow by not that many characters
- // (if ever), so it should be faster this way.
- for (let i = text.length; i > 0; i--) {
+ // (if ever), so it should be faster this way. Down to just the ellipsis,
+ // and no label at all where even that overflows the frame.
+ let truncated = "";
+ for (let i = text.length; i >= 0; i--) {
const newText = `${text.slice(0, i)}...`;
- if (ctx.measureText(newText).width <= maxWidth) {
- text = newText;
+ if (getLineWidth(newText, font, renderEnvironment) <= maxWidth) {
+ truncated = newText;
break;
}
}
+ text = truncated;
}
return newElementWith(element, { text, width: maxWidth });
};
@@ -131,7 +135,7 @@ const truncateText = (
*/
const addFrameLabelsAsTextElements = (
elements: readonly NonDeletedExcalidrawElement[],
- opts: { theme: Theme },
+ opts: { theme: Theme; renderEnvironment: RenderEnvironment },
) => {
const nextElements: NonDeletedExcalidrawElement[] = [];
for (const element of elements) {
@@ -152,10 +156,15 @@ const addFrameLabelsAsTextElements = (
removeDarkModeFilter(FRAME_STYLE.nameColorDarkTheme)
: FRAME_STYLE.nameColorLightTheme,
text: getFrameLikeTitle(element),
+ renderEnvironment: opts.renderEnvironment,
});
textElement.y -= textElement.height;
- textElement = truncateText(textElement, element.width);
+ textElement = truncateText(
+ textElement,
+ element.width,
+ opts.renderEnvironment,
+ );
nextElements.push(textElement);
}
@@ -180,11 +189,13 @@ const prepareElementsForRender = ({
exportingFrame,
frameRendering,
theme,
+ renderEnvironment,
}: {
elements: readonly NonDeletedExcalidrawElement[];
exportingFrame: ExcalidrawFrameLikeElement | null | undefined;
frameRendering: AppState["frameRendering"];
theme: Theme;
+ renderEnvironment: RenderEnvironment;
}) => {
let nextElements: readonly NonDeletedExcalidrawElement[];
@@ -195,7 +206,10 @@ const prepareElementsForRender = ({
arrayToMap(elements),
);
} else if (frameRendering.enabled && frameRendering.name) {
- nextElements = addFrameLabelsAsTextElements(elements, { theme });
+ nextElements = addFrameLabelsAsTextElements(elements, {
+ theme,
+ renderEnvironment,
+ });
} else {
nextElements = elements;
}
@@ -219,16 +233,54 @@ export type ExportSceneData = {
files?: BinaryFiles | null;
};
+/**
+ * The host capabilities an export uses, shared by every format: e.g. for test
+ * environments, Node.js or another window.
+ *
+ * Unlike the editor's `renderEnvironment` prop, this needn't be the same
+ * object across exports (e.g. on a server): exports draw without the element
+ * caches keyed by an environment, and measure little text. Passing a complete
+ * one (`createCanvas` and `createImage`) as-is, as the editor does, only keeps
+ * its measuring caches warm.
+ */
type ExportEnvironment = {
/**
- * Creates the canvas to export into.
+ * Creates the canvas a canvas/PNG/JPEG export renders into, and any canvas
+ * the export measures text with (e.g. frame labels, embed placeholders).
*
* Do not set `canvas.width/height` or modify the canvas context as that's
* handled by Excalidraw.
*
* Defaults to `document.createElement("canvas")`.
*/
- createCanvas?: () => HTMLCanvasElement;
+ createCanvas?: RenderEnvironment["createCanvas"];
+ /**
+ * Creates the images that image elements are decoded into.
+ *
+ * Defaults to `new Image()`.
+ */
+ createImage?: RenderEnvironment["createImage"];
+ /**
+ * Creates the paths that freedraw elements are filled through.
+ *
+ * Defaults to the global `Path2D`.
+ */
+ createPath?: RenderEnvironment["createPath"];
+ /**
+ * The document an SVG export is built in, e.g. a popout window's or,
+ * outside the browser, a DOM implementation's (such as `linkedom`).
+ *
+ * Defaults to the global `document`.
+ */
+ document?: RenderEnvironment["document"];
+ /**
+ * Measures text (frame labels, embed placeholders), e.g. where there is no
+ * canvas to measure on.
+ *
+ * Defaults to the global provider set with `setCustomTextMetricsProvider`,
+ * else to measuring on a canvas from `createCanvas`.
+ */
+ textMetrics?: RenderEnvironment["textMetrics"];
/**
* Loads the fonts the exported elements use, before rendering.
*
@@ -444,6 +496,28 @@ type ExportSizeConfig =
export type ExportSceneConfig = ExportSceneBaseConfig & ExportSizeConfig;
+/**
+ * The render environment of an export: `config.environment` over the browser
+ * defaults.
+ */
+const getExportRenderEnvironment = (
+ environment: ExportEnvironment | undefined,
+): RenderEnvironment => {
+ // a complete one (e.g. the editor's) is used as-is, keeping the caches
+ // keyed by its identity
+ if (environment?.createCanvas && environment.createImage) {
+ return environment as RenderEnvironment;
+ }
+ const defaults = getRenderEnvironment();
+ return {
+ createCanvas: environment?.createCanvas ?? defaults.createCanvas,
+ createImage: environment?.createImage ?? defaults.createImage,
+ createPath: environment?.createPath ?? defaults.createPath,
+ document: environment?.document ?? defaults.document,
+ textMetrics: environment?.textMetrics ?? defaults.textMetrics,
+ };
+};
+
/**
* The export config the editor's export settings translate to. Internal: hosts
* pass their own config.
@@ -475,9 +549,12 @@ export const getExportConfigFromAppState = (
const configExportDimension = async ({
data,
config,
+ renderEnvironment,
}: {
data: ExportSceneData;
config?: ExportSceneConfig;
+ /** measures what the export adds (frame labels) */
+ renderEnvironment: RenderEnvironment;
}) => {
// clone (widened, as the size options get normalized below)
const cfg: ExportSceneBaseConfig & ExportSizeOptions = Object.assign(
@@ -534,6 +611,7 @@ const configExportDimension = async ({
exportingFrame,
theme,
frameRendering,
+ renderEnvironment,
});
if (exportingFrame) {
@@ -764,6 +842,8 @@ const exportToCanvas = async ({
data: ExportSceneData;
config?: ExportSceneConfig;
}) => {
+ const renderEnvironment = getExportRenderEnvironment(config?.environment);
+
const {
config: cfg,
elements,
@@ -781,11 +861,9 @@ const exportToCanvas = async ({
backgroundColor,
paintedBackgroundColor,
theme,
- } = await configExportDimension({ data, config });
+ } = await configExportDimension({ data, config, renderEnvironment });
- const canvas = cfg.environment?.createCanvas
- ? cfg.environment.createCanvas()
- : document.createElement("canvas");
+ const canvas = renderEnvironment.createCanvas();
// round rather than letting the canvas truncate, which would turn float
// noise (e.g. 28.999999999999996) into a pixel lost
@@ -798,6 +876,7 @@ const exportToCanvas = async ({
(element) => element.fileId,
),
files: data.files || {},
+ createImage: renderEnvironment.createImage,
});
renderStaticScene({
@@ -829,6 +908,8 @@ const exportToCanvas = async ({
renderConfig: {
canvasBackgroundColor: backgroundColor,
clipToFrame: cfg.exportingFrame ?? null,
+ scale: exportScale,
+ renderEnvironment,
imageCache,
renderGrid: false,
isExporting: true,
@@ -855,12 +936,9 @@ type ExportToSvgConfig = Pick<
| "exportingFrame"
| "scale"
| "frames"
+ | "environment"
> &
ExportSizeConfig & {
- /**
- * Host environment overrides, e.g. for test environments or Node.js.
- */
- environment?: Pick<ExportEnvironment, "loadFonts">;
/**
* if true, all embeddables passed in will be rendered when possible.
*/
@@ -874,11 +952,11 @@ type ExportToSvgConfig = Pick<
embedScene?: boolean;
};
-const createHTMLComment = (text: string) => {
+const createHTMLComment = (ownerDocument: Document, text: string) => {
// surrounding with spaces to maintain prettified consistency with previous
// iterations
// <!-- comment -->
- return document.createComment(` ${text} `);
+ return ownerDocument.createComment(` ${text} `);
};
const exportToSvg = async ({
@@ -888,6 +966,19 @@ const exportToSvg = async ({
data: ExportSceneData;
config?: ExportToSvgConfig;
}) => {
+ const renderEnvironment = getExportRenderEnvironment(config?.environment);
+
+ const ownerDocument =
+ renderEnvironment.document ??
+ (typeof document !== "undefined" ? document : null);
+
+ if (!ownerDocument) {
+ throw new Error(
+ "exportScene: no document to build the SVG in. Pass " +
+ "`config.environment.document` when running outside the browser.",
+ );
+ }
+
const {
config: cfg,
elements,
@@ -903,7 +994,7 @@ const exportToSvg = async ({
backgroundColor,
paintedBackgroundColor,
theme,
- } = await configExportDimension({ data, config });
+ } = await configExportDimension({ data, config, renderEnvironment });
const offsetX = -(x - normalizedPadding);
const offsetY = -(y - normalizedPadding);
@@ -914,7 +1005,7 @@ const exportToSvg = async ({
// initialize SVG root element
// ---------------------------------------------------------------------------
- const svgRoot = document.createElementNS(SVG_NS, "svg");
+ const svgRoot = ownerDocument.createElementNS(SVG_NS, "svg");
svgRoot.setAttribute("version", "1.1");
svgRoot.setAttribute("xmlns", SVG_NS);
@@ -925,14 +1016,13 @@ const exportToSvg = async ({
svgRoot.setAttribute("width", `${exportWidth}`);
svgRoot.setAttribute("height", `${exportHeight}`);
- const defsElement = svgRoot.ownerDocument.createElementNS(SVG_NS, "defs");
+ const defsElement = ownerDocument.createElementNS(SVG_NS, "defs");
- const metadataElement = svgRoot.ownerDocument.createElementNS(
- SVG_NS,
- "metadata",
- );
+ const metadataElement = ownerDocument.createElementNS(SVG_NS, "metadata");
- svgRoot.appendChild(createHTMLComment("svg-source:excalidraw"));
+ svgRoot.appendChild(
+ createHTMLComment(ownerDocument, "svg-source:excalidraw"),
+ );
svgRoot.appendChild(metadataElement);
svgRoot.appendChild(defsElement);
@@ -975,10 +1065,7 @@ const exportToSvg = async ({
const elementsMap = arrayToMap(elements);
for (const frame of frameElements) {
- const clipPath = svgRoot.ownerDocument.createElementNS(
- SVG_NS,
- "clipPath",
- );
+ const clipPath = ownerDocument.createElementNS(SVG_NS, "clipPath");
clipPath.setAttribute("id", frame.id);
@@ -986,7 +1073,7 @@ const exportToSvg = async ({
const cx = (x2 - x1) / 2 - (frame.x - x1);
const cy = (y2 - y1) / 2 - (frame.y - y1);
- const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");
+ const rect = ownerDocument.createElementNS(SVG_NS, "rect");
rect.setAttribute(
"transform",
`translate(${frame.x + offsetX} ${frame.y + offsetY}) rotate(${
@@ -1018,10 +1105,10 @@ const exportToSvg = async ({
const delimiter = "\n "; // 6 spaces
- const style = svgRoot.ownerDocument.createElementNS(SVG_NS, "style");
+ const style = ownerDocument.createElementNS(SVG_NS, "style");
style.classList.add("style-fonts");
style.appendChild(
- document.createTextNode(`${delimiter}${fontFaces.join(delimiter)}`),
+ ownerDocument.createTextNode(`${delimiter}${fontFaces.join(delimiter)}`),
);
defsElement.appendChild(style);
@@ -1032,7 +1119,7 @@ const exportToSvg = async ({
// render background rect
if (paintedBackgroundColor !== "transparent") {
- const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");
+ const rect = ownerDocument.createElementNS(SVG_NS, "rect");
rect.setAttribute("x", "0");
rect.setAttribute("y", "0");
rect.setAttribute("width", `${exportWidth / exportScale}`);
@@ -1056,7 +1143,7 @@ const exportToSvg = async ({
// square corners), as the export may be larger than the frame
let elementsRoot: SVGElement = svgRoot;
if (cfg.exportingFrame) {
- elementsRoot = svgRoot.ownerDocument.createElementNS(SVG_NS, "g");
+ elementsRoot = ownerDocument.createElementNS(SVG_NS, "g");
elementsRoot.setAttribute("clip-path", `url(#${cfg.exportingFrame.id})`);
svgRoot.appendChild(elementsRoot);
}
@@ -1071,6 +1158,7 @@ const exportToSvg = async ({
offsetX,
offsetY,
isExporting: true,
+ renderEnvironment,
exportWithDarkMode,
renderEmbeddables,
frameRendering,
@@ -1108,13 +1196,19 @@ export const encodeSvgBase64Payload = ({
true /* is already byte string */,
);
+ const ownerDocument = metadataElement.ownerDocument;
+
+ metadataElement.appendChild(
+ createHTMLComment(ownerDocument, `payload-type:${MIME_TYPES.excalidraw}`),
+ );
+ metadataElement.appendChild(
+ createHTMLComment(ownerDocument, "payload-version:2"),
+ );
metadataElement.appendChild(
- createHTMLComment(`payload-type:${MIME_TYPES.excalidraw}`),
+ createHTMLComment(ownerDocument, "payload-start"),
);
- metadataElement.appendChild(createHTMLComment("payload-version:2"));
- metadataElement.appendChild(createHTMLComment("payload-start"));
- metadataElement.appendChild(document.createTextNode(base64));
- metadataElement.appendChild(createHTMLComment("payload-end"));
+ metadataElement.appendChild(ownerDocument.createTextNode(base64));
+ metadataElement.appendChild(createHTMLComment(ownerDocument, "payload-end"));
};
export const decodeSvgBase64Payload = ({ svg }: { svg: string }) => {
diff --git a/packages/excalidraw/scene/types.ts b/packages/excalidraw/scene/types.ts
index eb2f507caa..7cc465d942 100644
--- a/packages/excalidraw/scene/types.ts
+++ b/packages/excalidraw/scene/types.ts
@@ -8,6 +8,7 @@ import type {
} from "@excalidraw/element/types";
import type { MakeBrand } from "@excalidraw/common/utility-types";
+import type { RenderEnvironment } from "@excalidraw/element/renderEnvironment";
import type {
AppClassProperties,
@@ -28,6 +29,19 @@ export type RenderableElementsMap = NonDeletedElementsMap &
export type StaticCanvasRenderConfig = {
canvasBackgroundColor: AppState["viewBackgroundColor"];
+ /**
+ * Backing-store scale the target canvas was bootstrapped with -- the owner
+ * window's devicePixelRatio when rendering into the editor, exportScale when
+ * exporting. Element caches are built and blitted at this ratio, so it must
+ * be the same value passed as `StaticSceneRenderConfig["scale"]`.
+ */
+ scale: number;
+ /**
+ * Host environment that creates the canvases and images this render
+ * rasterizes (per-editor owner window in the app; the export's
+ * `config.environment` when exporting). Defaults to the browser's.
+ */
+ renderEnvironment?: RenderEnvironment;
/** export only: clips everything drawn to this frame (square corners) */
clipToFrame?: ExcalidrawFrameLikeElement | null;
// extra options passed to the renderer
@@ -48,6 +62,12 @@ export type StaticCanvasRenderConfig = {
};
export type SVGRenderConfig = {
+ /**
+ * Host environment used for the text measurements this render needs (the
+ * SVG itself is built through `exportToSvg`'s owner document). Defaults to
+ * the browser's.
+ */
+ renderEnvironment?: RenderEnvironment;
offsetX: number;
offsetY: number;
isExporting: boolean;
diff --git a/packages/excalidraw/tests/crossDocument.test.tsx b/packages/excalidraw/tests/crossDocument.test.tsx
index 493c13306d..7741e5d320 100644
--- a/packages/excalidraw/tests/crossDocument.test.tsx
+++ b/packages/excalidraw/tests/crossDocument.test.tsx
@@ -7,11 +7,153 @@ import {
} from "@testing-library/react";
import { vi } from "vitest";
+import { FONT_FAMILY } from "@excalidraw/common";
+
+import type { FontFamilyValues } from "@excalidraw/element/types";
+
import { Excalidraw } from "../index";
+import { useColorTopPicksDnD } from "../components/ColorPicker/colorTopPicksDnD";
import type { ExcalidrawImperativeAPI } from "../types";
+const mountEditorInOwnDocument = (currentItemFontFamily?: FontFamilyValues) => {
+ 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([]),
+ // pretend nothing is loaded yet, so that the editor actually goes
+ // through `fonts.load()` for its scene & current item fonts
+ check: vi.fn().mockReturnValue(false),
+ has: vi.fn().mockReturnValue(true),
+ add: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ };
+ Object.defineProperty(ownerDocument, "fonts", { value: fonts });
+ Object.defineProperties(ownerWindow, {
+ addEventListener: { value: vi.fn() },
+ 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,
+ });
+
+ let api: ExcalidrawImperativeAPI | null = null;
+ const { container, unmount } = renderReact(
+ <Excalidraw
+ ownerDocument={ownerDocument}
+ initialData={{
+ appState: currentItemFontFamily ? { currentItemFontFamily } : undefined,
+ }}
+ onExcalidrawAPI={(nextApi) => {
+ api = nextApi;
+ }}
+ />,
+ { container: mountNode, baseElement: ownerDocument.body },
+ );
+
+ return {
+ fonts,
+ container,
+ getAPI: () => api,
+ cleanup: () => {
+ unmount();
+ iframe.remove();
+ },
+ };
+};
+
describe("cross-document rendering", () => {
+ it("binds top-picks drag interactions to the source window", () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const ownerDocument = iframe.contentDocument!;
+ const ownerWindow = iframe.contentWindow!;
+ const mountNode = ownerDocument.createElement("div");
+ ownerDocument.body.append(mountNode);
+ const ownerAddEventListener = vi.fn();
+ Object.defineProperties(ownerWindow, {
+ addEventListener: { value: ownerAddEventListener },
+ removeEventListener: { value: vi.fn() },
+ });
+ let startPickDrag:
+ | ReturnType<typeof useColorTopPicksDnD>["startPickDrag"]
+ | null = null;
+
+ const Harness = () => {
+ const drag = useColorTopPicksDnD({
+ enabled: true,
+ picks: ["#000000", "#ffffff"],
+ onPicksChange: vi.fn(),
+ });
+ startPickDrag = drag.startPickDrag;
+ return (
+ <div ref={drag.setStripEl}>
+ <button data-top-pick-index="0" />
+ <button data-top-pick-index="1" />
+ </div>
+ );
+ };
+
+ const renderResult = renderReact(<Harness />, {
+ container: mountNode,
+ baseElement: ownerDocument.body,
+ });
+ const mainAddEventListener = vi.spyOn(window, "addEventListener");
+
+ try {
+ const sourceEl = ownerDocument.querySelector<HTMLElement>(
+ "[data-top-pick-index='0']",
+ )!;
+ act(() =>
+ startPickDrag!(
+ {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ currentTarget: sourceEl,
+ } as unknown as React.PointerEvent,
+ 0,
+ "#000000",
+ ),
+ );
+
+ for (const eventName of [
+ "pointermove",
+ "pointerup",
+ "pointercancel",
+ "keydown",
+ ]) {
+ expect(ownerAddEventListener).toHaveBeenCalledWith(
+ eventName,
+ expect.any(Function),
+ true,
+ );
+ expect(mainAddEventListener).not.toHaveBeenCalledWith(
+ eventName,
+ expect.any(Function),
+ true,
+ );
+ }
+ } finally {
+ renderResult.unmount();
+ mainAddEventListener.mockRestore();
+ iframe.remove();
+ }
+ });
+
it("scopes listeners, fonts, and portals to ownerDocument", async () => {
const iframe = document.createElement("iframe");
document.body.append(iframe);
@@ -144,4 +286,50 @@ describe("cross-document rendering", () => {
iframe.remove();
}
});
+
+ it("loads each editor's current item font through its own ownerDocument.fonts", async () => {
+ const defaultFontEditor = mountEditorInOwnDocument();
+ const nunitoEditor = mountEditorInOwnDocument(FONT_FAMILY.Nunito);
+
+ try {
+ for (const editor of [defaultFontEditor, nunitoEditor]) {
+ await waitFor(() =>
+ expect(
+ editor.container.querySelector("canvas.interactive"),
+ ).not.toBeNull(),
+ );
+ await waitFor(() =>
+ expect(editor.getAPI()!.getAppState().isLoading).toBe(false),
+ );
+ }
+
+ // each editor prewarms its own current item font (the default one
+ // included) through its own document's font faces
+ await waitFor(() =>
+ expect(defaultFontEditor.fonts.load).toHaveBeenCalledWith(
+ expect.stringContaining("Excalifont"),
+ expect.stringContaining("Excalidr"),
+ ),
+ );
+ await waitFor(() =>
+ expect(nunitoEditor.fonts.load).toHaveBeenCalledWith(
+ expect.stringContaining("Nunito"),
+ expect.stringContaining("Excalidr"),
+ ),
+ );
+
+ // ...and never through the other document's
+ expect(defaultFontEditor.fonts.load).not.toHaveBeenCalledWith(
+ expect.stringContaining("Nunito"),
+ expect.anything(),
+ );
+ expect(nunitoEditor.fonts.load).not.toHaveBeenCalledWith(
+ expect.stringContaining("Excalifont"),
+ expect.anything(),
+ );
+ } finally {
+ nunitoEditor.cleanup();
+ defaultFontEditor.cleanup();
+ }
+ });
});
diff --git a/packages/excalidraw/tests/fitToContent.test.tsx b/packages/excalidraw/tests/fitToContent.test.tsx
index d42bcd4ffd..e59e252a85 100644
--- a/packages/excalidraw/tests/fitToContent.test.tsx
+++ b/packages/excalidraw/tests/fitToContent.test.tsx
@@ -2,7 +2,6 @@ import React from "react";
import { vi } from "vitest";
import { Excalidraw } from "../index";
-import { SCROLL_TO_CONTENT_ANIMATION_KEY } from "../components/App.viewport";
import { AnimationController } from "../renderer/animation";
import { getNormalizedZoom } from "../scene";
@@ -52,7 +51,9 @@ const waitForAnimationToStop = (maxFrames = 200) => {
let remaining = maxFrames;
const check = () => {
if (
- !AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY) ||
+ !AnimationController.running(
+ h.app.viewport.scrollToContentAnimationKey,
+ ) ||
--remaining <= 0
) {
resolve();
@@ -392,9 +393,9 @@ describe("scale-down animated", () => {
// the animation must remove itself from the controller rather than keep
// ticking forever after reaching the target
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(false);
// it should have settled on the target viewport (moved off the origin)
const settledScrollX = h.state.scrollX;
diff --git a/packages/excalidraw/tests/hostAbstraction.test.tsx b/packages/excalidraw/tests/hostAbstraction.test.tsx
new file mode 100644
index 0000000000..0724b9021c
--- /dev/null
+++ b/packages/excalidraw/tests/hostAbstraction.test.tsx
@@ -0,0 +1,508 @@
+import React from "react";
+import {
+ act,
+ fireEvent,
+ render as renderReact,
+ waitFor,
+} from "@testing-library/react";
+import { vi } from "vitest";
+
+import { MIME_TYPES } from "@excalidraw/common";
+import {
+ newElement,
+ newFreeDrawElement,
+ newImageElement,
+ newTextElement,
+} from "@excalidraw/element";
+import { pointFrom } from "@excalidraw/math";
+
+import type { LocalPoint } from "@excalidraw/math";
+import type { RenderEnvironment } from "@excalidraw/element";
+import type { FileId } from "@excalidraw/element/types";
+
+import { Excalidraw } from "../index";
+import { getDefaultAppState } from "../appState";
+import { AnimationController } from "../renderer/animation";
+import { exportScene } from "../scene/export";
+import {
+ TOOLTIP_CLASS,
+ TOOLTIP_DELAY,
+ TOOLTIP_VISIBLE_CLASS,
+} from "../components/Tooltip";
+
+import type { AppState, BinaryFiles, DataURL } from "../types";
+import type App from "../components/App";
+
+/** a 1x1 transparent PNG, so image elements take the real rendering path */
+const PNG_DATA_URL =
+ `data:${MIME_TYPES.png};base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==` as DataURL;
+
+const makeScene = () => {
+ const fileId = "host-abstraction-image" as FileId;
+ const elements = [
+ newTextElement({ x: 0, y: 0, text: "hello", fontSize: 20 }),
+ newElement({
+ type: "rectangle",
+ x: 0,
+ y: 40,
+ width: 100,
+ height: 50,
+ link: "https://excalidraw.com",
+ }),
+ newImageElement({
+ type: "image",
+ x: 120,
+ y: 40,
+ width: 10,
+ height: 10,
+ fileId,
+ status: "saved",
+ scale: [1, 1],
+ }),
+ newFreeDrawElement({
+ type: "freedraw",
+ x: 0,
+ y: 120,
+ simulatePressure: true,
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(10, 10),
+ pointFrom<LocalPoint>(20, 5),
+ ],
+ }),
+ ];
+ const files: BinaryFiles = {
+ [fileId]: {
+ id: fileId,
+ dataURL: PNG_DATA_URL,
+ mimeType: MIME_TYPES.png,
+ created: 0,
+ lastRetrieved: 0,
+ },
+ };
+ return { elements, files };
+};
+
+/**
+ * The editor must be able to run in a document that isn't the module's own --
+ * a popout window, an iframe, a multi-tenant embed -- with every host object
+ * it mints (canvases, images, portals, tooltips) and every frame it schedules
+ * belonging to *that* realm. Two editors alive at once is what turns any
+ * process-global into a bug, so this exercises a pair of them.
+ */
+describe("multi-window editors", () => {
+ /**
+ * An iframe standing in for a second browser window. jsdom gives each frame
+ * a real document but a mostly inert window, so the bits the editor reaches
+ * for are filled in here from the main realm.
+ */
+ const createRealm = () => {
+ 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 images: HTMLImageElement[] = [];
+ const RealmImage = function () {
+ const image = ownerDocument.createElement("img");
+ images.push(image);
+ return image;
+ } as unknown as typeof Image;
+
+ const setTimeoutSpy = vi.fn((...args: Parameters<typeof setTimeout>) =>
+ window.setTimeout(...args),
+ );
+
+ Object.defineProperties(ownerWindow, {
+ addEventListener: { value: vi.fn() },
+ removeEventListener: { value: vi.fn() },
+ requestAnimationFrame: {
+ value: window.requestAnimationFrame.bind(window),
+ },
+ cancelAnimationFrame: {
+ value: window.cancelAnimationFrame.bind(window),
+ },
+ setTimeout: { value: setTimeoutSpy },
+ clearTimeout: { value: window.clearTimeout.bind(window) },
+ ResizeObserver: { value: window.ResizeObserver },
+ Image: { value: RealmImage },
+ });
+ Object.defineProperty(ownerDocument, "defaultView", { value: ownerWindow });
+ Object.defineProperty(ownerDocument, "fonts", {
+ value: {
+ load: vi.fn().mockResolvedValue([]),
+ check: vi.fn().mockReturnValue(true),
+ has: vi.fn().mockReturnValue(true),
+ add: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ },
+ });
+
+ // the canvas mock only patches the main realm's prototype, and it
+ // type-checks `drawImage` sources against the main realm's classes --
+ // per spec a canvas accepts image sources from any realm, so make it
+ // permissive enough for cross-document canvases to be drawn
+ const mainGetContext = window.HTMLCanvasElement.prototype.getContext;
+ Object.defineProperty(
+ ownerWindow.HTMLCanvasElement.prototype,
+ "getContext",
+ {
+ value(this: HTMLCanvasElement, contextType: string) {
+ const context = mainGetContext.call(this, contextType);
+ if (context) {
+ (context as CanvasRenderingContext2D).drawImage = () => undefined;
+ }
+ return context;
+ },
+ },
+ );
+
+ const createElement = vi.spyOn(ownerDocument, "createElement");
+
+ return {
+ iframe,
+ ownerDocument,
+ ownerWindow,
+ mountNode,
+ images,
+ setTimeoutSpy,
+ canvasCount: () =>
+ createElement.mock.calls.filter(([tag]) => tag === "canvas").length,
+ };
+ };
+
+ const mount = async (
+ realm: ReturnType<typeof createRealm>,
+ { elements, files }: ReturnType<typeof makeScene>,
+ ) => {
+ const renderResult = renderReact(
+ <Excalidraw
+ ownerDocument={realm.ownerDocument}
+ initialData={{ elements, files }}
+ />,
+ { container: realm.mountNode, baseElement: realm.ownerDocument.body },
+ );
+ await waitFor(() =>
+ expect(
+ renderResult.container.querySelector("canvas.interactive"),
+ ).not.toBeNull(),
+ );
+ return { renderResult, app: window.h.app as InstanceType<typeof App> };
+ };
+
+ it("scopes host objects, scheduling and tooltips to each editor's own realm", async () => {
+ const realmA = createRealm();
+ const realmB = createRealm();
+ // built up front: measuring their text mints a canvas through the
+ // default environment, which is not what is under test here
+ const sceneA = makeScene();
+ const sceneB = makeScene();
+ const mainCreateElement = vi.spyOn(document, "createElement");
+
+ const a = await mount(realmA, sceneA);
+ const b = await mount(realmB, sceneB);
+ expect(a.app).not.toBe(b.app);
+
+ try {
+ // --- host objects come from the realm the editor lives in -------------
+
+ // per-element bitmaps and the link icon canvas are minted through each
+ // editor's own render environment
+ await waitFor(() => expect(realmA.canvasCount()).toBeGreaterThan(0));
+ await waitFor(() => expect(realmB.canvasCount()).toBeGreaterThan(0));
+ // the module's own document is not a fallback for either of them
+ expect(
+ mainCreateElement.mock.calls.filter(([tag]) => tag === "canvas"),
+ ).toHaveLength(0);
+
+ // the same goes for images: the scene image, the not-yet-decoded
+ // placeholder and the link icon
+ const srcsOf = (images: HTMLImageElement[]) => images.map((i) => i.src);
+ for (const realm of [realmA, realmB]) {
+ await waitFor(() =>
+ expect(
+ srcsOf(realm.images).some((src) => src.includes(";base64")),
+ ).toBe(true),
+ );
+ await waitFor(() =>
+ expect(
+ srcsOf(realm.images).some((src) =>
+ src.includes("feather-external-link"),
+ ),
+ ).toBe(true),
+ );
+ expect(
+ realm.images.every(
+ (image) => image.ownerDocument === realm.ownerDocument,
+ ),
+ ).toBe(true);
+ }
+
+ // --- frames are scheduled on the owning window ------------------------
+
+ realmA.setTimeoutSpy.mockClear();
+ realmB.setTimeoutSpy.mockClear();
+
+ act(() => {
+ a.app.viewport.setViewport({
+ target: [0, 0, 1000, 1000],
+ fit: "scale-down",
+ animation: { duration: 1000 },
+ });
+ b.app.viewport.setViewport({
+ target: [2000, 2000, 3000, 3000],
+ fit: "scale-down",
+ animation: { duration: 1000 },
+ });
+ });
+
+ // with process-global animation keys the second start was a silent
+ // no-op; each editor must own its animation slot
+ expect(
+ AnimationController.running(a.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
+ expect(
+ AnimationController.running(b.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
+ // ...and drive its frames through its own window, not the module's
+ expect(realmA.setTimeoutSpy).toHaveBeenCalled();
+ expect(realmB.setTimeoutSpy).toHaveBeenCalled();
+
+ // cancelling one editor's transition must not touch the other's
+ act(() => {
+ a.app.viewport.setViewport(null);
+ });
+ expect(
+ AnimationController.running(a.app.viewport.scrollToContentAnimationKey),
+ ).toBe(false);
+ expect(
+ AnimationController.running(b.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
+ act(() => {
+ b.app.viewport.setViewport(null);
+ });
+
+ // --- the shared tooltip lives in the document that triggered it -------
+
+ const wrapperA = a.renderResult.container.querySelector(
+ ".excalidraw-tooltip-wrapper",
+ )!;
+ expect(wrapperA).not.toBeNull();
+ // the trigger may show its tooltip after a delay, timed in its own window
+ vi.useFakeTimers();
+ act(() => {
+ fireEvent.pointerEnter(wrapperA);
+ vi.advanceTimersByTime(TOOLTIP_DELAY);
+ });
+ expect(
+ realmA.ownerDocument.querySelector(`.${TOOLTIP_CLASS}`),
+ ).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ expect(
+ realmB.ownerDocument.querySelector(`.${TOOLTIP_CLASS}`),
+ ).toBeNull();
+ expect(document.querySelector(`.${TOOLTIP_CLASS}`)).toBeNull();
+
+ // a hover in the other realm takes the tooltip over rather than
+ // reusing the first realm's stale node
+ const wrapperB = b.renderResult.container.querySelector(
+ ".excalidraw-tooltip-wrapper",
+ )!;
+ act(() => {
+ fireEvent.pointerLeave(wrapperA);
+ fireEvent.pointerEnter(wrapperB);
+ });
+ expect(
+ realmB.ownerDocument.querySelector(`.${TOOLTIP_CLASS}`),
+ ).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ expect(
+ realmA.ownerDocument.querySelector(`.${TOOLTIP_CLASS}`),
+ ).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ } finally {
+ vi.useRealTimers();
+ a.renderResult.unmount();
+ b.renderResult.unmount();
+ realmA.iframe.remove();
+ realmB.iframe.remove();
+ mainCreateElement.mockRestore();
+ }
+ });
+});
+
+/**
+ * The export pipeline must run where `document` / `window` / `Path2D` don't
+ * exist at all -- server-side thumbnailing under Node. The host objects a Node
+ * canvas library would supply (`node-canvas`, `@napi-rs/canvas`) are stubbed
+ * here rather than installed, so the suite stays free of native dependencies.
+ */
+describe("headless (server-side) export", () => {
+ it("renders a scene with no browser globals, through an injected environment", async () => {
+ // every host object is built while the globals still exist, standing in
+ // for what a Node canvas library would hand back
+ const hostDocument = document;
+ const Path2DCtor = globalThis.Path2D;
+
+ const canvases: HTMLCanvasElement[] = [];
+ const createCanvas = () => {
+ const canvas = hostDocument.createElement("canvas");
+ // node-canvas / OffscreenCanvas are not DOM elements
+ Object.defineProperty(canvas, "setAttribute", { value: undefined });
+ Object.defineProperty(canvas, "isConnected", { value: undefined });
+ canvases.push(canvas);
+ return canvas;
+ };
+ const createImage = () => {
+ const image = hostDocument.createElement("img");
+ Object.defineProperty(image, "naturalWidth", { value: 10 });
+ Object.defineProperty(image, "naturalHeight", { value: 10 });
+ let src = "";
+ Object.defineProperty(image, "src", {
+ get: () => src,
+ set: (value: string) => {
+ src = value;
+ // nothing decodes on its own here, so settle like a browser would
+ queueMicrotask(() => image.onload?.({} as Event));
+ },
+ });
+ return image;
+ };
+ const createPath = vi.fn((svgPath: string) => new Path2DCtor(svgPath));
+
+ const renderEnvironment: RenderEnvironment = {
+ createCanvas,
+ createImage,
+ createPath,
+ // a DOM shim's, for SVG export
+ document: hostDocument,
+ };
+
+ const appState = {
+ ...getDefaultAppState(),
+ width: 200,
+ height: 200,
+ } as AppState;
+ const { elements, files } = makeScene();
+
+ const fillText = vi.spyOn(
+ Object.getPrototypeOf(
+ hostDocument.createElement("canvas").getContext("2d")!,
+ ) as CanvasRenderingContext2D,
+ "fillText",
+ );
+
+ // no DOM, and no global `Path2D` for freedraw to fall back on
+ vi.stubGlobal("document", undefined);
+ vi.stubGlobal("window", undefined);
+ vi.stubGlobal("Path2D", undefined);
+
+ try {
+ const canvas = await exportScene({
+ type: "canvas",
+ data: { elements, appState, files },
+ config: {
+ canvasBackgroundColor: "#ffffff",
+ environment: renderEnvironment,
+ },
+ });
+
+ expect(canvases).toContain(canvas);
+ // text was measured and painted rather than swallowed by the
+ // renderer's per-element error handling
+ expect(fillText).toHaveBeenCalledWith("hello", 0, expect.any(Number));
+ // the freedraw stroke was filled through the injected path factory
+ expect(createPath).toHaveBeenCalled();
+ expect(createPath.mock.calls[0][0]).toMatch(/^M/);
+
+ // `exportToSvg` builds real DOM nodes, so a server-side caller supplies
+ // the document (a DOM shim)
+ const svg = await exportScene({
+ type: "svg",
+ data: { elements, files },
+ config: {
+ canvasBackgroundColor: "#ffffff",
+ environment: renderEnvironment,
+ },
+ });
+
+ expect(svg.tagName.toLowerCase()).toBe("svg");
+ expect(svg.ownerDocument).toBe(hostDocument);
+ expect(svg.querySelector("text")?.textContent).toBe("hello");
+ } finally {
+ vi.unstubAllGlobals();
+ fillText.mockRestore();
+ }
+ });
+
+ it("exports the rest of the scene when an element fails to render", async () => {
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ const { elements } = makeScene();
+ // the failing element first: what's drawn after it must not inherit its
+ // transforms (or clips)
+ const freedraw = elements.find((element) => element.type === "freedraw")!;
+ const scene = [
+ freedraw,
+ ...elements.filter((element) => element !== freedraw),
+ ];
+ const appState = {
+ ...getDefaultAppState(),
+ width: 200,
+ height: 200,
+ } as AppState;
+
+ /** the transform each text line of the export was drawn with */
+ const exportTextTransforms = async () => {
+ const target = document.createElement("canvas");
+ const context = target.getContext("2d")!;
+ const transforms: number[][] = [];
+ vi.spyOn(context, "fillText").mockImplementation(() => {
+ const { a, b, c, d, e, f } = context.getTransform();
+ transforms.push([a, b, c, d, e, f]);
+ });
+ const canvas = await exportScene({
+ type: "canvas",
+ data: { elements: scene, appState },
+ config: {
+ canvasBackgroundColor: "#ffffff",
+ environment: {
+ createCanvas: () => target,
+ loadFonts: async () => {},
+ },
+ },
+ });
+ expect(canvas).toBe(target);
+ return transforms;
+ };
+
+ try {
+ const rendered = await exportTextTransforms();
+ expect(rendered).toHaveLength(1);
+ expect(consoleError).not.toHaveBeenCalled();
+
+ // a Node host that supplies no `createPath` and has no global `Path2D`:
+ // the freedraw element is unrenderable
+ vi.stubGlobal("Path2D", undefined);
+ const failed = await exportTextTransforms();
+
+ // the bad element is logged...
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringMatching(/Path2D/) }),
+ expect.any(String),
+ expect.any(Number),
+ expect.any(Number),
+ expect.any(Number),
+ expect.any(Number),
+ );
+ // ...and the rest still painted, where it would have been
+ expect(failed).toEqual(rendered);
+ } finally {
+ vi.unstubAllGlobals();
+ consoleError.mockRestore();
+ }
+ });
+});
diff --git a/packages/excalidraw/tests/renderCaches.test.ts b/packages/excalidraw/tests/renderCaches.test.ts
new file mode 100644
index 0000000000..9520cafbbd
--- /dev/null
+++ b/packages/excalidraw/tests/renderCaches.test.ts
@@ -0,0 +1,291 @@
+// @vitest-environment-options {"url": "http://localhost/"}
+
+import { RoughCanvas } from "roughjs/bin/canvas";
+
+import { newElement } from "@excalidraw/element";
+
+import { vi } from "vitest";
+
+import type { RenderEnvironment } from "@excalidraw/element/renderEnvironment";
+
+import type {
+ ElementsMap,
+ NonDeletedExcalidrawElement,
+ NonDeletedSceneElementsMap,
+} from "@excalidraw/element/types";
+
+import { getDefaultAppState } from "../appState";
+import { renderStaticScene } from "../renderer/staticScene";
+
+import type { StaticCanvasAppState } from "../types";
+import type {
+ RenderableElementsMap,
+ StaticSceneRenderConfig,
+} from "../scene/types";
+
+/** already decoded, so a link icon bakes in the first render with no tick */
+const makeDecodedImage = () => {
+ const image = document.createElement("img");
+ Object.defineProperty(image, "complete", { value: true });
+ Object.defineProperty(image, "naturalWidth", { value: 16 });
+ return image;
+};
+
+const makeEnv = () => {
+ const canvases: HTMLCanvasElement[] = [];
+ const env: RenderEnvironment = {
+ createCanvas: () => {
+ const canvas = document.createElement("canvas");
+ canvases.push(canvas);
+ return canvas;
+ },
+ createImage: makeDecodedImage,
+ };
+ return { env, canvases };
+};
+
+const getDrawImageSources = (canvas: HTMLCanvasElement) =>
+ (
+ canvas.getContext("2d") as unknown as {
+ drawImage: { mock: { calls: unknown[][] } };
+ }
+ ).drawImage.mock.calls.map((args) => args[0]);
+
+const appState = {
+ ...getDefaultAppState(),
+ width: 1000,
+ height: 1000,
+ offsetLeft: 0,
+ offsetTop: 0,
+} as StaticCanvasAppState;
+
+const makeScene = () =>
+ Object.assign(document.createElement("canvas"), {
+ width: 1000,
+ height: 1000,
+ });
+
+const makeConfig = (
+ elements: NonDeletedExcalidrawElement[],
+ {
+ scale,
+ renderEnvironment,
+ canvas = makeScene(),
+ }: {
+ scale: number;
+ renderEnvironment: RenderEnvironment;
+ canvas?: HTMLCanvasElement;
+ },
+): StaticSceneRenderConfig => {
+ const elementsMap = new Map(
+ elements.map((element) => [element.id, element]),
+ ) as unknown as ElementsMap;
+
+ return {
+ canvas,
+ rc: new RoughCanvas(canvas),
+ elementsMap: elementsMap as unknown as RenderableElementsMap,
+ allElementsMap: elementsMap as unknown as NonDeletedSceneElementsMap,
+ visibleElements: elements,
+ scale,
+ appState,
+ renderConfig: {
+ canvasBackgroundColor: "",
+ scale,
+ imageCache: new Map(),
+ renderGrid: false,
+ renderLinks: true,
+ isExporting: false,
+ embedsValidationStatus: new Map(),
+ elementsPendingErasure: new Set(),
+ pendingFlowchartNodes: null,
+ theme: appState.theme,
+ renderEnvironment,
+ },
+ };
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/**
+ * The element bitmap is rasterized at the backing-store scale
+ * (renderConfig.scale, i.e. the owner window's devicePixelRatio in the editor)
+ * in a specific realm's canvas. Reusing it across either would blit the wrong
+ * scene size, or a canvas belonging to another document.
+ */
+describe("element canvas cache", () => {
+ const rect = () =>
+ newElement({
+ type: "rectangle",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 50,
+ }) as NonDeletedExcalidrawElement;
+
+ it("regenerates when the backing-store scale changes", () => {
+ const { env, canvases } = makeEnv();
+ const elements = [rect()];
+
+ // bitmap width is elementWidth * deviceScale + padding * 2
+ renderStaticScene(
+ makeConfig(elements, { scale: 1, renderEnvironment: env }),
+ );
+ expect(canvases).toHaveLength(1);
+ expect(canvases[0].width).toBe(100 * 1 + 40);
+
+ // same element identity, backing-store scale changes (e.g. the window
+ // moved to a higher-DPI monitor): the stale bitmap must not be reused
+ renderStaticScene(
+ makeConfig(elements, { scale: 2, renderEnvironment: env }),
+ );
+ expect(canvases).toHaveLength(2);
+ expect(canvases[1].width).toBe(100 * 2 + 40);
+ });
+
+ it("regenerates when the environment changes, and reuses within one", () => {
+ const a = makeEnv();
+ const b = makeEnv();
+ const elements = [rect()];
+
+ renderStaticScene(
+ makeConfig(elements, { scale: 1, renderEnvironment: a.env }),
+ );
+ expect(a.canvases).toHaveLength(1);
+
+ // a second instance (e.g. a popout) renders the very same element object
+ // in its own environment: it must mint its own canvas rather than blit a
+ // bitmap belonging to env A's realm
+ renderStaticScene(
+ makeConfig(elements, { scale: 1, renderEnvironment: b.env }),
+ );
+ expect(b.canvases).toHaveLength(1);
+ expect(a.canvases).toHaveLength(1);
+
+ // re-rendering under the same environment reuses the cached canvas
+ renderStaticScene(
+ makeConfig(elements, { scale: 1, renderEnvironment: b.env }),
+ );
+ expect(b.canvases).toHaveLength(1);
+
+ // NOTE going back to env A regenerates rather than restoring env A's
+ // earlier bitmap: the cache holds one entry per element, not one per
+ // element per environment. An element object alternating between two
+ // editors frame after frame does not happen in practice, so the extra
+ // per-element map is not worth its allocation and lookup.
+ renderStaticScene(
+ makeConfig(elements, { scale: 1, renderEnvironment: a.env }),
+ );
+ expect(a.canvases).toHaveLength(2);
+ expect(b.canvases).toHaveLength(1);
+ });
+});
+
+describe("link icon cache", () => {
+ const linkedRect = () =>
+ newElement({
+ type: "rectangle",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 50,
+ link: "https://excalidraw.com",
+ }) as NonDeletedExcalidrawElement;
+
+ // the icon canvas bakes at the fixed link icon size while the element
+ // bitmap is element-width + padding, so filter on width to isolate the
+ // icon blits
+ const iconBlits = (scene: HTMLCanvasElement, canvases: HTMLCanvasElement[]) =>
+ getDrawImageSources(scene).filter(
+ (source): source is HTMLCanvasElement =>
+ canvases.includes(source as HTMLCanvasElement) &&
+ (source as HTMLCanvasElement).width < 64,
+ );
+
+ it("bakes a separate icon per backing-store scale", () => {
+ const { env, canvases } = makeEnv();
+ const elements = [linkedRect()];
+
+ const config1 = makeConfig(elements, { scale: 1, renderEnvironment: env });
+ renderStaticScene(config1);
+ const [firstBake] = iconBlits(config1.canvas, canvases);
+ expect(firstBake).toBeDefined();
+
+ // another window at the same zoom but a different backing-store scale
+ // must not reuse the first bake
+ const config2 = makeConfig(elements, { scale: 2, renderEnvironment: env });
+ renderStaticScene(config2);
+ const [secondBake] = iconBlits(config2.canvas, canvases);
+ expect(secondBake).toBeDefined();
+ expect(secondBake).not.toBe(firstBake);
+ expect(secondBake.width).toBe(firstBake.width * 2);
+ expect(secondBake.height).toBe(firstBake.height * 2);
+ });
+
+ it("bakes an icon only for the environment whose image decoded", () => {
+ const makeUndecodedEnv = () => {
+ const canvases: HTMLCanvasElement[] = [];
+ const images: HTMLImageElement[] = [];
+ const env: RenderEnvironment = {
+ createCanvas: () => {
+ const canvas = document.createElement("canvas");
+ canvases.push(canvas);
+ return canvas;
+ },
+ createImage: () => {
+ const image = document.createElement("img");
+ let src = "";
+ Object.defineProperty(image, "src", {
+ get: () => src,
+ // jsdom never decodes, so the load is settled by hand below
+ set: (value: string) => {
+ src = value;
+ },
+ });
+ images.push(image);
+ return image;
+ },
+ };
+ return { env, canvases, images };
+ };
+
+ const a = makeUndecodedEnv();
+ const b = makeUndecodedEnv();
+ const elements = [linkedRect()];
+ const sceneA = makeScene();
+ const sceneB = makeScene();
+ const configA = makeConfig(elements, {
+ scale: 1,
+ renderEnvironment: a.env,
+ canvas: sceneA,
+ });
+ const configB = makeConfig(elements, {
+ scale: 1,
+ renderEnvironment: b.env,
+ canvas: sceneB,
+ });
+
+ renderStaticScene(configA);
+ renderStaticScene(configB);
+ expect(a.images).toHaveLength(1);
+ expect(b.images).toHaveLength(1);
+ // nothing is baked while the image is undecoded -- the bake is memoized
+ // under a key with no notion of load state, so a blank one would stick
+ expect(iconBlits(sceneA, a.canvases)).toHaveLength(0);
+ expect(iconBlits(sceneB, b.canvases)).toHaveLength(0);
+
+ // environment A's image decodes; environment B's does not
+ a.images[0].onload?.({} as Event);
+
+ renderStaticScene(configA);
+ const aBlits = iconBlits(sceneA, a.canvases);
+ expect(aBlits).toHaveLength(1);
+ expect(getDrawImageSources(aBlits[0])).toContain(a.images[0]);
+
+ // decode state is per environment: B still bakes nothing
+ renderStaticScene(configB);
+ expect(iconBlits(sceneB, b.canvases)).toHaveLength(0);
+ });
+});
diff --git a/packages/excalidraw/tests/renderOverrides.test.tsx b/packages/excalidraw/tests/renderOverrides.test.tsx
index 6d5b0b9715..06d0f8842a 100644
--- a/packages/excalidraw/tests/renderOverrides.test.tsx
+++ b/packages/excalidraw/tests/renderOverrides.test.tsx
@@ -545,6 +545,18 @@ describe("setElementRenderOverrides", () => {
});
describe("render override geometry", () => {
+ // link icons are drawn only once their image decoded, which jsdom never
+ // does on its own
+ const renderEnvironment: Element.RenderEnvironment = {
+ createCanvas: () => document.createElement("canvas"),
+ createImage: () => {
+ const image = document.createElement("img");
+ Object.defineProperty(image, "complete", { value: true });
+ Object.defineProperty(image, "naturalWidth", { value: 16 });
+ return image;
+ },
+ };
+
const setup = (elements: NonDeletedExcalidrawElement[]) => {
const scene = new Element.Scene(elements, { skipValidation: true });
const renderer = new Renderer(scene);
@@ -568,6 +580,8 @@ describe("render override geometry", () => {
imageCache: new Map(),
renderGrid: false,
isExporting: false,
+ scale: 1,
+ renderEnvironment,
canvasBackgroundColor: "#fff",
embedsValidationStatus: new Map(),
elementsPendingErasure: new Set(),
diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.ts
index 36be2ee33e..34256e489f 100644
--- a/packages/excalidraw/tests/scene/export.test.ts
+++ b/packages/excalidraw/tests/scene/export.test.ts
@@ -531,6 +531,24 @@ describe("export inputs", () => {
expect(loadFonts).toHaveBeenCalledTimes(1);
});
+ it("measures text through environment.textMetrics", async () => {
+ const getLineWidth = vi.fn((text: string) => text.length * 100);
+ const frame = API.createElement({ type: "frame", width: 450 });
+
+ const svg = await exportScene({
+ type: "svg",
+ data: { elements: [frame] },
+ config: { environment: { textMetrics: { getLineWidth } } },
+ });
+
+ // "Frame" is 500 wide by these metrics, so the label is truncated to fit
+ // the 450 wide frame
+ expect(getLineWidth).toHaveBeenCalledWith("Frame", expect.any(String));
+ expect(
+ Array.from(svg.querySelectorAll("text")).map((text) => text.textContent),
+ ).toContain("F...");
+ });
+
it("renders frame decorations per config.frames", async () => {
const elements = [API.createElement({ type: "frame" })];
const countFrameNames = (svg: SVGSVGElement) =>
@@ -655,6 +673,25 @@ describe("exporting frames", () => {
expect(label).toHaveAttribute("fill", FRAME_STYLE.nameColorDarkTheme);
});
+ it("truncates frame names to what fits, down to no name at all", async () => {
+ // 10px per character in tests, so "..." is 30 wide
+ const svg = await exportScene({
+ type: "svg",
+ data: {
+ elements: [
+ API.createElement({ type: "frame", x: 0, width: 20 }),
+ API.createElement({ type: "frame", x: 100, width: 35 }),
+ ],
+ },
+ });
+
+ expect(
+ Array.from(svg.querySelectorAll("text"))
+ .map((text) => text.textContent)
+ .filter(Boolean),
+ ).toEqual(["..."]);
+ });
+
it("clips a frame export larger than the frame to the frame", async () => {
const frame = API.createElement({
type: "frame",
diff --git a/packages/excalidraw/tests/scrollConstraints.test.tsx b/packages/excalidraw/tests/scrollConstraints.test.tsx
index abbdaaf1e7..4c1b5bc8b2 100644
--- a/packages/excalidraw/tests/scrollConstraints.test.tsx
+++ b/packages/excalidraw/tests/scrollConstraints.test.tsx
@@ -12,17 +12,13 @@ import {
actionZoomToFitSelection,
} from "../actions/actionCanvas";
import { getNormalizedZoom } from "../scene";
-import {
- snapBackToConstraints,
- SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY,
- SCROLL_TO_CONTENT_ANIMATION_KEY,
-} from "../components/App.viewport";
+import { snapBackToConstraints } from "../components/App.viewport";
import {
constrainScrollState,
DEFAULT_OVERSCROLL,
getViewportForZoomWithScrollConstraints,
} from "../viewport";
-import { AnimationController } from "../renderer/animation";
+import { AnimationController, type AnimationKey } from "../renderer/animation";
import { API } from "./helpers/api";
import { Keyboard, Pointer } from "./helpers/ui";
@@ -71,7 +67,7 @@ const makeLock = (
...overrides,
});
-const waitForAnimationToStop = (key: string, maxFrames = 200) => {
+const waitForAnimationToStop = (key: AnimationKey, maxFrames = 200) => {
return React.act(
() =>
new Promise<void>((resolve) => {
@@ -360,6 +356,13 @@ describe("animateToConstraints (rubberband snap-back)", () => {
AnimationController.reset();
});
+ // Animation keys are instance-owned in production; the pure function takes
+ // them as a parameter so tests supply their own
+ const keys = {
+ scrollToContent: "test-scrollToContent",
+ snapBack: "test-snapBack",
+ };
+
const lock = makeLock({
x: 0,
y: 0,
@@ -374,10 +377,9 @@ describe("animateToConstraints (rubberband snap-back)", () => {
snapBackToConstraints(
makeState({ scrollX: 200, scrollConstraints: lock }),
onFrame,
+ keys,
);
- expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
- ).toBe(true);
+ expect(AnimationController.running(keys.snapBack)).toBe(true);
expect(onFrame).toHaveBeenCalled();
});
@@ -386,27 +388,23 @@ describe("animateToConstraints (rubberband snap-back)", () => {
snapBackToConstraints(
makeState({ scrollX: -100, scrollConstraints: lock }),
onFrame,
+ keys,
);
- expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
- ).toBe(false);
+ expect(AnimationController.running(keys.snapBack)).toBe(false);
expect(onFrame).not.toHaveBeenCalled();
});
it("does not supersede an active viewport navigation", () => {
- AnimationController.start(SCROLL_TO_CONTENT_ANIMATION_KEY, () => ({}));
+ AnimationController.start(keys.scrollToContent, () => ({}));
snapBackToConstraints(
makeState({ scrollX: 200, scrollConstraints: lock }),
vi.fn(),
+ keys,
);
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
- expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
- ).toBe(false);
+ expect(AnimationController.running(keys.scrollToContent)).toBe(true);
+ expect(AnimationController.running(keys.snapBack)).toBe(false);
});
});
@@ -522,9 +520,9 @@ describe("setViewport lock (integration)", () => {
// the animation is in flight and the lock has NOT been installed yet —
// it's chained to run once the scroll settles
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
// The previous active lock is superseded immediately; the destination
// lock is held internally until the animation lands.
expect(h.state.scrollConstraints).toBe(null);
@@ -551,20 +549,20 @@ describe("setViewport lock (integration)", () => {
h.app.actionManager.executeAction(actionZoomToFitSelection, "ui");
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
expect({
scrollX: h.state.scrollX,
scrollY: h.state.scrollY,
zoom: h.state.zoom.value,
}).toEqual(viewportDuringTransition);
- await waitForAnimationToStop(SCROLL_TO_CONTENT_ANIMATION_KEY);
+ await waitForAnimationToStop(h.app.viewport.scrollToContentAnimationKey);
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(false);
expect(h.app.viewport.isLockedTransitionPending).toBe(false);
expect(h.state.scrollConstraints).toMatchObject({
x: rect.x,
@@ -618,12 +616,12 @@ describe("setViewport lock (integration)", () => {
});
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
expect(h.app.viewport.isLockedTransitionPending).toBe(true);
- await waitForAnimationToStop(SCROLL_TO_CONTENT_ANIMATION_KEY);
+ await waitForAnimationToStop(h.app.viewport.scrollToContentAnimationKey);
expect(h.app.viewport.isLockedTransitionPending).toBe(false);
expect(h.state.scrollConstraints).toMatchObject({
@@ -668,9 +666,9 @@ describe("setViewport lock (integration)", () => {
h.app.viewport.setViewport(null);
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(false);
expect(h.app.viewport.isLockedTransitionPending).toBe(false);
expect(h.state.scrollConstraints).toBe(null);
expect(h.state.shouldCacheIgnoreZoom).toBe(false);
@@ -689,9 +687,9 @@ describe("setViewport lock (integration)", () => {
});
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- true,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(true);
expect(h.app.viewport.isLockedTransitionPending).toBe(false);
// the animation's frames draw from zoom-scaled bitmaps
@@ -703,9 +701,9 @@ describe("setViewport lock (integration)", () => {
h.app.viewport.translate({ scrollX: 123, scrollY: 456 });
});
- expect(AnimationController.running(SCROLL_TO_CONTENT_ANIMATION_KEY)).toBe(
- false,
- );
+ expect(
+ AnimationController.running(h.app.viewport.scrollToContentAnimationKey),
+ ).toBe(false);
expect(h.state.scrollX).toBe(123);
expect(h.state.scrollY).toBe(456);
// the interrupted animation's completion handler no longer runs, so the
@@ -1142,14 +1140,14 @@ describe("rubberband overscroll (integration)", () => {
h.app.viewport["snapBackDebounced"].flush();
});
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(false);
expect(h.state.scrollY).toBe(heldScrollY);
// lifting one finger ends the gesture → the rubberband releases
finger1.up();
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(true);
finger2.up();
@@ -1184,20 +1182,20 @@ describe("rubberband overscroll (integration)", () => {
h.app.viewport["snapBackDebounced"].flush();
});
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(false);
expect(h.state.scrollY).toBe(heldScrollY);
mouse.up();
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(true);
// Direct manipulation takes ownership of the viewport again.
mouse.downAt(50, 7);
mouse.move(0, 1);
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(false);
mouse.up();
});
@@ -1261,7 +1259,7 @@ describe("rubberband overscroll (integration)", () => {
mouse.up();
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(true);
expect(h.state.scrollY).toBeGreaterThan(
constrainScrollState(h.state).scrollY,
@@ -1278,13 +1276,13 @@ describe("rubberband overscroll (integration)", () => {
constrainScrollState(h.state).scrollY,
);
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(true);
- await waitForAnimationToStop(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY);
+ await waitForAnimationToStop(h.app.viewport.snapBackAnimationKey);
expect(
- AnimationController.running(SCROLL_CONSTRAINTS_SNAP_BACK_ANIMATION_KEY),
+ AnimationController.running(h.app.viewport.snapBackAnimationKey),
).toBe(false);
expect(h.state.zoom.value).toBeGreaterThan(zoomBefore);
const restingViewport = constrainScrollState(h.state);
diff --git a/packages/excalidraw/tests/tooltip.test.tsx b/packages/excalidraw/tests/tooltip.test.tsx
index 5a9bc1030c..dfcedaabc2 100644
--- a/packages/excalidraw/tests/tooltip.test.tsx
+++ b/packages/excalidraw/tests/tooltip.test.tsx
@@ -1,18 +1,35 @@
import { render as renderComponent, fireEvent } from "@testing-library/react";
import { vi } from "vitest";
-import { Tooltip, hideTooltip } from "../components/Tooltip";
+import { HYPERLINK_TOOLTIP_DELAY } from "@excalidraw/common";
+import { newTextElement } from "@excalidraw/element";
+
+import type { ElementsMap } from "@excalidraw/element/types";
+
+import {
+ TOOLTIP_CLASS,
+ TOOLTIP_VISIBLE_CLASS,
+ Tooltip,
+ hideTooltip,
+} from "../components/Tooltip";
+import {
+ hideHyperlinkToolip,
+ showHyperlinkTooltip,
+ type HyperlinkTooltipOwner,
+} from "../components/hyperlink/Hyperlink";
import { act } from "./test-utils";
+import type { AppState } from "../types";
+
const TOOLTIP_DELAY = 500;
const TOOLTIP_WARM_WINDOW = 300;
const getTooltip = () =>
- document.querySelector<HTMLDivElement>(".excalidraw-tooltip");
+ document.querySelector<HTMLDivElement>(`.${TOOLTIP_CLASS}`);
const isTooltipVisible = () =>
- !!getTooltip()?.classList.contains("excalidraw-tooltip--visible");
+ !!getTooltip()?.classList.contains(TOOLTIP_VISIBLE_CLASS);
const wrapperOf = (container: HTMLElement, label: string) =>
container.querySelector<HTMLDivElement>(`[data-testid="${label}"]`)!
@@ -103,4 +120,133 @@ describe("Tooltip", () => {
expect(isTooltipVisible()).toBe(false);
});
+
+ it("hides when the Tooltip showing it gets disabled", async () => {
+ const { container, rerender } = renderComponent(
+ <Tooltip label="a" disabled={false}>
+ <button data-testid="a" />
+ </Tooltip>,
+ );
+
+ fireEvent.pointerEnter(wrapperOf(container, "a"));
+ expect(isTooltipVisible()).toBe(true);
+
+ // a disabled Tooltip renders no wrapper, so its onPointerLeave never fires
+ rerender(
+ <Tooltip label="a" disabled>
+ <button data-testid="a" />
+ </Tooltip>,
+ );
+ await Promise.resolve();
+
+ expect(isTooltipVisible()).toBe(false);
+ });
+});
+
+describe("hyperlink tooltip", () => {
+ const appState = {
+ scrollX: 0,
+ scrollY: 0,
+ zoom: { value: 1 },
+ offsetLeft: 0,
+ offsetTop: 0,
+ } as AppState;
+
+ const show = (link: string, owner: HyperlinkTooltipOwner = {}) => {
+ const element = newTextElement({ x: 0, y: 0, text: "hello", link });
+ const elementsMap = new Map([[element.id, element]]) as ElementsMap;
+ act(() => {
+ showHyperlinkTooltip(element, appState, elementsMap, document, owner);
+ });
+ return owner;
+ };
+
+ const showAndRender = (link: string) => {
+ const owner = show(link);
+ act(() => {
+ vi.advanceTimersByTime(HYPERLINK_TOOLTIP_DELAY + 1);
+ });
+ expect(getTooltip()).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ return owner;
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("drops the tooltip when its owning window goes away", () => {
+ const tooltip = () => getTooltip();
+
+ // no in-window event will ever call `hideHyperlinkToolip` once the window
+ // loses focus, so the window itself must drop the tooltip
+ showAndRender("https://example.com");
+ act(() => window.dispatchEvent(new Event("blur")));
+ expect(tooltip()).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+
+ // pagehide fires on window close even when blur is skipped (e.g. a
+ // programmatic close), so the globals must not retain the detached
+ // document/window
+ showAndRender("https://example.com");
+ act(() => window.dispatchEvent(new Event("pagehide")));
+ expect(tooltip()).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+
+ // a null relatedTarget means the pointer actually left the window...
+ showAndRender("https://example.com");
+ act(() => window.dispatchEvent(new MouseEvent("mouseout")));
+ expect(tooltip()).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+
+ // ...while a move within it must leave the tooltip alone
+ const owner = showAndRender("https://example.com");
+ const withinWindow = new MouseEvent("mouseout");
+ Object.defineProperty(withinWindow, "relatedTarget", {
+ value: document.body,
+ });
+ act(() => window.dispatchEvent(withinWindow));
+ expect(tooltip()).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ hideHyperlinkToolip(owner);
+
+ // a tooltip still waiting out its hover delay must be dropped too, rather
+ // than rendering into a window that is already gone
+ show("https://example.com");
+ act(() => {
+ window.dispatchEvent(new Event("blur"));
+ vi.advanceTimersByTime(HYPERLINK_TOOLTIP_DELAY + 1);
+ });
+ expect(tooltip()).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ });
+
+ it("lets a new owner take over from a stale one", () => {
+ showAndRender("https://first.example");
+ const tooltip = getTooltip();
+ expect(tooltip?.textContent).toBe("https://first.example");
+
+ show("https://second.example");
+ // the previous owner's tooltip is cleared immediately on takeover, not
+ // left visible while the new one is pending
+ expect(tooltip).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+
+ act(() => {
+ vi.advanceTimersByTime(HYPERLINK_TOOLTIP_DELAY + 1);
+ });
+ expect(tooltip).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ expect(tooltip?.textContent).toBe("https://second.example");
+ });
+
+ it("ignores hide calls from a foreign owner", () => {
+ const owner = showAndRender("https://example.com");
+ const tooltip = getTooltip();
+
+ // another editor's pointer leaving its own link must not tear down the
+ // tooltip this one owns
+ hideHyperlinkToolip({});
+ expect(tooltip).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ hideHyperlinkToolip();
+ expect(tooltip).toHaveClass(TOOLTIP_VISIBLE_CLASS);
+
+ hideHyperlinkToolip(owner);
+ expect(tooltip).not.toHaveClass(TOOLTIP_VISIBLE_CLASS);
+ });
});
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index 7c81c832c2..52f7a714c7 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -52,6 +52,7 @@ import type {
CaptureUpdateActionType,
DurableIncrement,
EphemeralIncrement,
+ RenderEnvironment,
OnDuplicateData,
} from "@excalidraw/element";
import type { GlobalPoint } from "@excalidraw/math";
@@ -851,6 +852,30 @@ export interface ExcalidrawProps {
* @default document
*/
ownerDocument?: Document;
+ /**
+ * Host environment used by the renderer and export pipeline to create
+ * canvases and images. Supply a custom implementation to redirect canvas
+ * creation and image decoding to e.g. a host canvas pool, an
+ * `OffscreenCanvas`, or a non-DOM image decoder. When omitted, canvas and
+ * image creation fall back to `ownerDocument` / `ownerWindow`.
+ *
+ * The value must be referentially stable -- every render cache (element
+ * canvases, text metrics, char widths, link icons) is keyed by this
+ * object's identity, so a new identity is a full cache miss. Passing an
+ * inline object literal mints a fresh identity on every React render,
+ * which silently re-rasterizes every element on every frame; hoist it to a
+ * module constant or memoize it (e.g. `useMemo`) instead.
+ *
+ * Only `createCanvas` and `createImage` are required. `createPath` (used to
+ * fill freedraw strokes) falls back to the global `Path2D`, which every
+ * browser has -- a non-browser host without one must supply it. Pass
+ * `document` (the owner document) for SVG exports to be built in it rather
+ * than in the global `document`, and `textMetrics` to measure the editor's
+ * text with your own provider.
+ *
+ * @default { createCanvas: () => ownerDocument.createElement("canvas"), createImage: () => new ownerWindow.Image(), createPath: (d) => new ownerWindow.Path2D(d), document: ownerDocument }
+ */
+ renderEnvironment?: RenderEnvironment;
onChange?: (
elements: readonly OrderedExcalidrawElement[],
appState: AppState,
@@ -1182,6 +1207,7 @@ export type AppClassProperties = {
state: AppState;
readonly ownerDocument: Document;
readonly ownerWindow: Window & typeof globalThis;
+ renderEnvironment: RenderEnvironment;
api: App["api"];
sessionExportThemeOverride: App["sessionExportThemeOverride"];
interactiveCanvas: HTMLCanvasElement | null;
diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
index c9a1db0cca..7022d012e1 100644
--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx
+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx
@@ -586,6 +586,7 @@ export const textWysiwyg = ({
editable.value,
layout.font,
whiteSpace === "pre-wrap" ? layout.width : Infinity,
+ app.renderEnvironment,
);
const lineIndex = Math.max(
0,
@@ -593,7 +594,11 @@ export const textWysiwyg = ({
);
const line = lines[lineIndex];
const direction = getLineDirection(editable.value, line.start);
- const lineWidth = getLineWidth(line.text, layout.font);
+ const lineWidth = getLineWidth(
+ line.text,
+ layout.font,
+ app.renderEnvironment,
+ );
const lineStartX =
layout.textAlign === "center"
? (layout.width - lineWidth) / 2
@@ -827,8 +832,16 @@ export const textWysiwyg = ({
const { selectionStart, selectionEnd, value } = editable;
const nextText =
value.slice(0, selectionStart) + text + value.slice(selectionEnd);
- const wrappedText = wrapText(nextText, font, maxWidth);
- const width = Math.min(getTextWidth(wrappedText, font), maxWidth);
+ const wrappedText = wrapText(
+ nextText,
+ font,
+ maxWidth,
+ app.renderEnvironment,
+ );
+ const width = Math.min(
+ getTextWidth(wrappedText, font, app.renderEnvironment),
+ maxWidth,
+ );
editable.style.width = `${width}px`;
}
};
@@ -1057,7 +1070,12 @@ export const textWysiwyg = ({
});
}
- redrawTextBoundingBox(updateElement, container, app.scene);
+ redrawTextBoundingBox(
+ updateElement,
+ container,
+ app.scene,
+ app.renderEnvironment,
+ );
}
onSubmit({
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index a3fd873ce0..58827e5c85 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -13,3 +13,4 @@ export type {
export { elementsOverlappingBBox } from "@excalidraw/element";
export { getCommonBounds } from "@excalidraw/element";
+export type { RenderEnvironment } from "@excalidraw/element";