Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(packages/excalidraw): add renderOverrides to allow overriding of element rendering (#12100)

David Luzara9186480121a
diff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.ts
index 1cd349bf0f..2edc0989b6 100644
--- a/packages/element/src/renderElement.ts
+++ b/packages/element/src/renderElement.ts
@@ -1,6 +1,7 @@
import rough from "roughjs/bin/rough";
import {
+ clamp,
type GlobalPoint,
isRightAngleRads,
lineSegment,
@@ -35,9 +36,8 @@ import type {
StaticCanvasAppState,
Zoom,
InteractiveCanvasAppState,
- ElementsPendingErasure,
- PendingExcalidrawElements,
NormalizedZoomValue,
+ ElementRenderOverrides,
} from "@excalidraw/excalidraw/types";
import type {
@@ -65,6 +65,7 @@ import {
isArrowElement,
hasBoundTextElement,
isMagicFrameElement,
+ isFrameLikeElement,
isImageElement,
} from "./typeChecks";
import { getContainingFrame } from "./frame";
@@ -85,7 +86,6 @@ import type {
ExcalidrawFreeDrawElement,
ExcalidrawImageElement,
ExcalidrawTextElementWithContainer,
- ExcalidrawFrameLikeElement,
NonDeletedSceneElementsMap,
ElementsMap,
} from "./types";
@@ -115,30 +115,90 @@ const getCanvasPadding = (element: ExcalidrawElement) => {
}
};
-export const getRenderOpacity = (
+export type RenderPositionOffset = Readonly<{ x: number; y: number }>;
+
+const ZERO_RENDER_OFFSET: RenderPositionOffset = { x: 0, y: 0 };
+
+/** Bound labels follow their container; a label's own offset is ignored. */
+export const getElementRenderOffset = (
element: ExcalidrawElement,
- containingFrame: ExcalidrawFrameLikeElement | null,
- elementsPendingErasure: ElementsPendingErasure,
- pendingNodes: Readonly<PendingExcalidrawElements> | null,
- globalAlpha: number = 1,
-) => {
- // multiplying frame opacity with element opacity to combine them
- // (e.g. frame 50% and element 50% opacity should result in 25% opacity)
- let opacity =
- (((containingFrame?.opacity ?? 100) * element.opacity) / 10000) *
- globalAlpha;
+ elementsMap: ElementsMap,
+ overrides: ElementRenderOverrides | undefined,
+): RenderPositionOffset | undefined => {
+ const container = isTextElement(element)
+ ? getContainerElement(element, elementsMap)
+ : null;
+ return overrides?.get((container ?? element).id)?.offset;
+};
+
+export const getRenderElementWithPositionOverride = <
+ TElement extends ExcalidrawElement,
+>(
+ element: TElement,
+ positionOffset: RenderPositionOffset,
+): TElement => {
+ if (positionOffset.x === 0 && positionOffset.y === 0) {
+ return element;
+ }
+
+ return {
+ ...element,
+ x: element.x + positionOffset.x,
+ y: element.y + positionOffset.y,
+ } as TElement;
+};
- // if pending erasure, multiply again to combine further
- // (so that erasing always results in lower opacity than original)
+export type ElementRenderState = Readonly<{
+ /** Alpha including frame opacity and pending erasure; selection dimming is separate. */
+ opacity: number;
+ offset: RenderPositionOffset;
+}>;
+
+/** Resolve visual state at the drawing boundary, preserving document cache keys. */
+export const resolveElementRenderState = (
+ element: ExcalidrawElement,
+ elementsMap: ElementsMap,
+ renderConfig: Pick<
+ StaticCanvasRenderConfig,
+ | "elementRenderOverrides"
+ | "elementsPendingErasure"
+ | "pendingFlowchartNodes"
+ >,
+ allElementsMap: ElementsMap = elementsMap,
+): ElementRenderState => {
+ const {
+ elementRenderOverrides,
+ elementsPendingErasure,
+ pendingFlowchartNodes,
+ } = renderConfig;
+ const override = elementRenderOverrides?.get(element.id);
+ const containingFrame = getContainingFrame(element, elementsMap);
+ const frameOpacity = containingFrame
+ ? clamp(
+ elementRenderOverrides?.get(containingFrame.id)?.opacity ??
+ containingFrame.opacity,
+ 0,
+ 100,
+ )
+ : 100;
+ // Frame and element alpha multiply (50% each produces 25%).
+ let opacity =
+ (frameOpacity * clamp(override?.opacity ?? element.opacity, 0, 100)) /
+ 10000;
if (
elementsPendingErasure.has(element.id) ||
- (pendingNodes && pendingNodes.some((node) => node.id === element.id)) ||
+ pendingFlowchartNodes?.some((node) => node.id === element.id) ||
(containingFrame && elementsPendingErasure.has(containingFrame.id))
) {
opacity *= ELEMENT_READY_TO_ERASE_OPACITY / 100;
}
+ const offset = getElementRenderOffset(
+ element,
+ allElementsMap,
+ elementRenderOverrides,
+ );
- return opacity;
+ return { opacity, offset: offset ?? ZERO_RENDER_OFFSET };
};
export interface ExcalidrawElementWithCanvas {
@@ -709,6 +769,7 @@ const drawElementFromCanvas = (
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
allElementsMap: NonDeletedSceneElementsMap,
+ positionOffset: RenderPositionOffset,
) => {
const element = elementWithCanvas.element;
// the ratio the cached bitmap was generated with (`generateElementCanvas`);
@@ -716,8 +777,10 @@ const drawElementFromCanvas = (
const devicePixelRatio = window.devicePixelRatio;
const padding = getCanvasPadding(element);
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, allElementsMap);
- const cx = ((x1 + x2) / 2 + appState.scrollX) * devicePixelRatio;
- const cy = ((y1 + y2) / 2 + appState.scrollY) * devicePixelRatio;
+ const cx =
+ ((x1 + x2) / 2 + positionOffset.x + appState.scrollX) * devicePixelRatio;
+ const cy =
+ ((y1 + y2) / 2 + positionOffset.y + appState.scrollY) * devicePixelRatio;
context.save();
context.scale(1 / devicePixelRatio, 1 / devicePixelRatio);
@@ -743,11 +806,13 @@ const drawElementFromCanvas = (
(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,
@@ -777,8 +842,10 @@ const drawElementFromCanvas = (
// the blit origin, in the space the context is in here (scaled by
// canvas scale × zoom ÷ devicePixelRatio)
- let drawX = (x1 + appState.scrollX) * devicePixelRatio - padding;
- let drawY = (y1 + appState.scrollY) * devicePixelRatio - padding;
+ let drawX =
+ (x1 + positionOffset.x + appState.scrollX) * devicePixelRatio - padding;
+ let drawY =
+ (y1 + positionOffset.y + appState.scrollY) * devicePixelRatio - padding;
const transform = context.getTransform();
@@ -801,8 +868,8 @@ const drawElementFromCanvas = (
const container = isTextElement(element)
? getContainerElement(element, allElementsMap)
: null;
- // A bound label shares its unrotated container's anchor. Other bitmaps
- // anchor to themselves, with a zero relative offset.
+ // 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
@@ -813,9 +880,11 @@ const drawElementFromCanvas = (
const anchorPadding =
anchor === element ? padding : getCanvasPadding(anchor);
const anchorX =
- (anchorSceneX + appState.scrollX) * devicePixelRatio - anchorPadding;
+ (anchorSceneX + positionOffset.x + appState.scrollX) * devicePixelRatio -
+ anchorPadding;
const anchorY =
- (anchorSceneY + appState.scrollY) * devicePixelRatio - anchorPadding;
+ (anchorSceneY + positionOffset.y + appState.scrollY) * devicePixelRatio -
+ anchorPadding;
// Form the relative vector before introducing the scroll translation.
const dx = (x1 - anchorSceneX) * devicePixelRatio + anchorPadding - padding;
@@ -857,8 +926,8 @@ const drawElementFromCanvas = (
context.strokeStyle = "#c92a2a";
context.lineWidth = 3;
context.strokeRect(
- (coords.x + appState.scrollX) * devicePixelRatio,
- (coords.y + appState.scrollY) * devicePixelRatio,
+ (coords.x + positionOffset.x + appState.scrollX) * devicePixelRatio,
+ (coords.y + positionOffset.y + appState.scrollY) * devicePixelRatio,
getBoundTextMaxWidth(element, textElement) * devicePixelRatio,
getBoundTextMaxHeight(element, textElement) * devicePixelRatio,
);
@@ -903,20 +972,56 @@ export const renderElement = (
context: CanvasRenderingContext2D,
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
+ renderState = resolveElementRenderState(
+ element,
+ elementsMap,
+ renderConfig,
+ allElementsMap,
+ ),
) => {
const reduceAlphaForSelection =
appState.openDialog?.name === "elementLinkSelector" &&
!appState.selectedElementIds[element.id] &&
!appState.hoveredElementIds[element.id];
- context.globalAlpha = getRenderOpacity(
- element,
- getContainingFrame(element, elementsMap),
- renderConfig.elementsPendingErasure,
- renderConfig.pendingFlowchartNodes,
- reduceAlphaForSelection ? DEFAULT_REDUCED_GLOBAL_ALPHA : 1,
- );
+ context.save();
+ context.globalAlpha =
+ renderState.opacity *
+ (reduceAlphaForSelection ? DEFAULT_REDUCED_GLOBAL_ALPHA : 1);
+ // Cached bitmaps apply the offset before pixel snapping. Moving it into
+ // the canvas transform first loses precision at half-device-pixel ties.
+ if (
+ (renderConfig.isExporting || isFrameLikeElement(element)) &&
+ (renderState.offset.x || renderState.offset.y)
+ ) {
+ context.translate(renderState.offset.x, renderState.offset.y);
+ }
+ try {
+ drawElement(
+ element,
+ elementsMap,
+ allElementsMap,
+ rc,
+ context,
+ renderConfig,
+ appState,
+ renderState,
+ );
+ } finally {
+ context.restore();
+ }
+};
+const drawElement = (
+ element: NonDeletedExcalidrawElement,
+ elementsMap: RenderableElementsMap,
+ allElementsMap: NonDeletedSceneElementsMap,
+ rc: RoughCanvas,
+ context: CanvasRenderingContext2D,
+ renderConfig: StaticCanvasRenderConfig,
+ appState: StaticCanvasAppState | InteractiveCanvasAppState,
+ renderState: ElementRenderState,
+) => {
switch (element.type) {
case "magicframe":
case "frame": {
@@ -991,6 +1096,7 @@ export const renderElement = (
renderConfig,
appState,
allElementsMap,
+ renderState.offset,
);
}
@@ -1141,6 +1247,8 @@ export const renderElement = (
renderConfig,
appState,
allElementsMap,
+ // The crop editor's uncropped preview stays at document coordinates.
+ ZERO_RENDER_OFFSET,
);
}
@@ -1153,6 +1261,7 @@ export const renderElement = (
renderConfig,
appState,
allElementsMap,
+ renderState.offset,
);
// reset
@@ -1165,8 +1274,6 @@ export const renderElement = (
throw new Error(`Unimplemented type ${element.type}`);
}
}
-
- context.globalAlpha = 1;
};
export function getFreedrawOutlineAsSegments(
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 9d0826914f..a1055d2050 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -209,7 +209,8 @@ import {
getApproxMinLineHeight,
getMinTextElementWidth,
ShapeCache,
- getRenderOpacity,
+ resolveElementRenderState,
+ getRenderElementWithPositionOverride,
editGroupForSelectedElement,
getElementsInGroup,
getSelectedGroupIdForElement,
@@ -366,6 +367,10 @@ import { exportCanvas, loadFromBlob } from "../data";
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
import { restoreAppState, restoreElements } from "../data/restore";
import { getCenter, getDistance } from "../gesture";
+import {
+ copyElementRenderOverrides,
+ getElementRenderOffsets,
+} from "../renderOverrides";
import { History } from "../history";
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
@@ -487,6 +492,8 @@ import type {
AppClassProperties,
AppProps,
AppState,
+ ElementRenderOffsets,
+ ElementRenderOverrides,
BinaryFileData,
ExcalidrawImperativeAPI,
BinaryFiles,
@@ -795,6 +802,24 @@ class App extends React.Component<AppProps, AppState> {
onRemoveEventListenersEmitter = new Emitter<[]>();
api: ExcalidrawImperativeAPI;
+ private elementRenderOverrides: ElementRenderOverrides = new Map();
+ /** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
+ private elementRenderOffsets: ElementRenderOffsets = new Map();
+ private renderOverridesUpdatePending = false;
+
+ private getRenderOverrideConfig = () => ({
+ elementRenderOverrides: this.elementRenderOverrides,
+ });
+
+ private getElementRenderState = (
+ element: ExcalidrawElement,
+ overrides: ElementRenderOverrides | null = this.elementRenderOverrides,
+ ) =>
+ resolveElementRenderState(element, this.scene.getNonDeletedElementsMap(), {
+ elementRenderOverrides: overrides ?? undefined,
+ elementsPendingErasure: this.elementsPendingErasure,
+ pendingFlowchartNodes: null,
+ });
private createExcalidrawAPI(): ExcalidrawImperativeAPI {
const api: ExcalidrawImperativeAPI = {
@@ -813,6 +838,7 @@ class App extends React.Component<AppProps, AppState> {
},
setViewport: this.viewport.setViewport,
getViewportOffsets: this.viewport.getOffsets,
+ setElementRenderOverrides: this.setElementRenderOverrides,
getSceneElements: this.getSceneElements,
getAppState: () => this.state,
getFiles: () => this.files,
@@ -1822,13 +1848,14 @@ class App extends React.Component<AppProps, AppState> {
return (
<>
{embeddableElements.map((el) => {
+ const renderState = this.getElementRenderState(el);
const { x, y } = sceneCoordsToViewportCoords(
{ sceneX: el.x, sceneY: el.y },
this.state,
);
const isVisible = isElementInViewport(
- el,
+ getRenderElementWithPositionOverride(el, renderState.offset),
normalizedWidth,
normalizedHeight,
this.state,
@@ -1982,20 +2009,22 @@ class App extends React.Component<AppProps, AppState> {
})}
style={{
transform: isVisible
- ? `translate(${x - this.state.offsetLeft}px, ${
- y - this.state.offsetTop
+ ? `translate(${
+ x +
+ renderState.offset.x * this.state.zoom.value -
+ this.state.offsetLeft
+ }px, ${
+ y +
+ renderState.offset.y * this.state.zoom.value -
+ this.state.offsetTop
}px) scale(${scale})`
: "none",
display: isVisible ? "block" : "none",
- opacity: getRenderOpacity(
- el,
- getContainingFrame(el, this.scene.getNonDeletedElementsMap()),
- this.elementsPendingErasure,
- null,
- this.state.openDialog?.name === "elementLinkSelector"
+ opacity:
+ renderState.opacity *
+ (this.state.openDialog?.name === "elementLinkSelector"
? DEFAULT_REDUCED_GLOBAL_ALPHA
- : 1,
- ),
+ : 1),
["--embeddable-radius" as string]: `${getCornerRadius(
Math.min(el.width, el.height),
el,
@@ -2109,21 +2138,17 @@ class App extends React.Component<AppProps, AppState> {
if (frameNameDiv) {
const box = frameNameDiv.getBoundingClientRect();
- const boxSceneTopLeft = viewportCoordsToSceneCoords(
- { clientX: box.x, clientY: box.y },
- this.state,
- );
- const boxSceneBottomRight = viewportCoordsToSceneCoords(
- { clientX: box.right, clientY: box.bottom },
- this.state,
- );
+ const zoom = this.state.zoom.value;
+ // Only the title's size comes from layout: its visual position may
+ // have an override. Hit bounds stay anchored to the document frame,
+ // with the title's bottom nameOffsetY screen pixels above it.
bounds = {
- x: boxSceneTopLeft.x,
- y: boxSceneTopLeft.y,
- width: boxSceneBottomRight.x - boxSceneTopLeft.x,
- height: boxSceneBottomRight.y - boxSceneTopLeft.y,
- zoom: this.state.zoom.value,
+ x: frameElement.x,
+ y: frameElement.y - (box.height + FRAME_STYLE.nameOffsetY) / zoom,
+ width: box.width / zoom,
+ height: box.height / zoom,
+ zoom,
versionNonce: frameElement.versionNonce,
};
@@ -2171,9 +2196,18 @@ class App extends React.Component<AppProps, AppState> {
: null;
return nonDeletedFramesLikes.map((f) => {
+ // The name is a decoration that follows the frame's render overrides,
+ // except while it's being edited: editing is interaction and keeps to
+ // document geometry like everything else interactive. Culling by the
+ // translated frame would otherwise end the edit (and commit the name)
+ // from a render-only override.
+ const renderState = this.getElementRenderState(
+ f,
+ f.id === this.state.editingFrame ? null : this.elementRenderOverrides,
+ );
if (
!isElementInViewport(
- f,
+ getRenderElementWithPositionOverride(f, renderState.offset),
this.canvas.width / this.ownerWindow.devicePixelRatio,
this.canvas.height / this.ownerWindow.devicePixelRatio,
{
@@ -2194,7 +2228,10 @@ class App extends React.Component<AppProps, AppState> {
}
const { x: x1, y: y1 } = sceneCoordsToViewportCoords(
- { sceneX: f.x, sceneY: f.y },
+ {
+ sceneX: f.x + renderState.offset.x,
+ sceneY: f.y + renderState.offset.y,
+ },
this.state,
);
@@ -2268,6 +2305,7 @@ class App extends React.Component<AppProps, AppState> {
key={f.id}
style={{
position: "absolute",
+ opacity: renderState.opacity,
// Positioning from bottom so that we don't to either
// calculate text height or adjust using transform (which)
// messes up input position when editing the frame name.
@@ -2614,7 +2652,16 @@ class App extends React.Component<AppProps, AppState> {
rc={this.rc}
elementsMap={renderableElementsMap}
allElementsMap={allElementsMap}
- visibleElements={visibleElements}
+ visibleElements={
+ this.elementRenderOffsets.size
+ ? this.renderer.getVisibleElementsWithRenderOffsets(
+ visibleElements,
+ renderableElementsMap,
+ this.state,
+ this.elementRenderOffsets,
+ )
+ : visibleElements
+ }
canvasNonce={canvasNonce}
selectionNonce={
this.state.selectionElement?.versionNonce
@@ -2635,6 +2682,7 @@ class App extends React.Component<AppProps, AppState> {
pendingFlowchartNodes:
this.flowchart.pendingNodes,
theme: this.state.theme,
+ ...this.getRenderOverrideConfig(),
}}
/>
{previewElement && (
@@ -2657,6 +2705,7 @@ class App extends React.Component<AppProps, AppState> {
this.elementsPendingErasure,
pendingFlowchartNodes: null,
theme: this.state.theme,
+ ...this.getRenderOverrideConfig(),
}}
// a tool dragged out of the toolbar previews
// translucently; the element itself is drawn
@@ -3517,6 +3566,8 @@ class App extends React.Component<AppProps, AppState> {
*/
private resetScene = withBatchedUpdates(
(opts?: { resetLoadingState: boolean }) => {
+ this.elementRenderOverrides = new Map();
+ this.elementRenderOffsets = new Map();
this.scene.replaceAllElements([]);
this.setState((state) => ({
...getDefaultAppState(),
@@ -3880,6 +3931,8 @@ class App extends React.Component<AppProps, AppState> {
this.editorLifecycleEvents.emit("editor:unmount");
this.props.onUnmount?.();
this.props.onExcalidrawAPI?.(null);
+ this.elementRenderOverrides = new Map();
+ this.elementRenderOffsets = new Map();
(this.ownerWindow as any).launchQueue?.setConsumer(() => {});
@@ -4202,6 +4255,18 @@ class App extends React.Component<AppProps, AppState> {
}
componentDidUpdate(prevProps: AppProps, prevState: AppState) {
+ const renderOverridesUpdatePending = this.renderOverridesUpdatePending;
+ this.renderOverridesUpdatePending = false;
+ // Only a requested visual update can skip the document pipeline. Real
+ // props/state changes batched with it must still commit and notify.
+ if (
+ renderOverridesUpdatePending &&
+ prevProps === this.props &&
+ prevState === this.state
+ ) {
+ return;
+ }
+
// must be updated *before* state change listeners are triggered below
if (!this._initialized && !this.state.isLoading) {
this._initialized = true;
@@ -5353,6 +5418,30 @@ class App extends React.Component<AppProps, AppState> {
},
);
+ /**
+ * see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details
+ */
+ public setElementRenderOverrides = (
+ overrides: ElementRenderOverrides | null,
+ ) => {
+ if (this.unmounted) {
+ return;
+ }
+ const nextOverrides = copyElementRenderOverrides(overrides);
+ // clearing an already clear snapshot is the one cheap no-op worth having
+ if (!nextOverrides.size && !this.elementRenderOverrides.size) {
+ return;
+ }
+ this.elementRenderOverrides = nextOverrides;
+ this.elementRenderOffsets = getElementRenderOffsets(
+ this.elementRenderOverrides,
+ this.elementRenderOffsets,
+ );
+ this.renderOverridesUpdatePending = true;
+ // Preserve AppState identity and explicitly request a visual-only commit.
+ this.forceUpdate();
+ };
+
public applyDeltas = (
deltas: StoreDelta[],
options?: ApplyToOptions,
diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsx
index 94daf3b69e..217c4e782a 100644
--- a/packages/excalidraw/index.tsx
+++ b/packages/excalidraw/index.tsx
@@ -491,7 +491,11 @@ export type {
SavedChats,
} from "./components/TTDDialog/types";
-export type { ViewportStatusFrame } from "./types";
+export type {
+ ViewportStatusFrame,
+ ElementRenderOverride,
+ ElementRenderOverrides,
+} from "./types";
export { zoomToFitBounds, DEFAULT_OVERSCROLL } from "./viewport";
diff --git a/packages/excalidraw/renderOverrides.ts b/packages/excalidraw/renderOverrides.ts
new file mode 100644
index 0000000000..3288d3829a
--- /dev/null
+++ b/packages/excalidraw/renderOverrides.ts
@@ -0,0 +1,70 @@
+import { clamp } from "@excalidraw/math";
+
+import type {
+ ElementRenderOffsets,
+ ElementRenderOverride,
+ ElementRenderOverrides,
+} from "./types";
+
+/** Validate and copy before publishing, so a rejected snapshot changes nothing. */
+export const copyElementRenderOverrides = (
+ overrides: ElementRenderOverrides | null,
+): ElementRenderOverrides => {
+ const copy = new Map<string, ElementRenderOverride>();
+ for (const [id, value] of overrides ?? []) {
+ const { opacity, offset } = value;
+ if (
+ (opacity !== undefined && !Number.isFinite(opacity)) ||
+ (offset !== undefined &&
+ (offset === null ||
+ !Number.isFinite(offset.x) ||
+ !Number.isFinite(offset.y)))
+ ) {
+ throw new TypeError(`Render overrides for ${id} must be finite numbers`);
+ }
+ if (opacity === undefined && offset === undefined) {
+ continue;
+ }
+ copy.set(id, {
+ ...(opacity !== undefined ? { opacity: clamp(opacity, 0, 100) } : {}),
+ ...(offset ? { offset: { x: offset.x, y: offset.y } } : {}),
+ });
+ }
+ return copy;
+};
+
+/**
+ * Extracts the offsets of a snapshot, returning `previous` when they are the
+ * same. Visibility is memoized on this map's identity, so a snapshot that only
+ * changes opacities (a fade) never re-runs viewport geometry.
+ */
+export const getElementRenderOffsets = (
+ overrides: ElementRenderOverrides,
+ previous: ElementRenderOffsets,
+): ElementRenderOffsets => {
+ // Compare before allocating: fades can carry many unchanged offsets.
+ let offsetCount = 0;
+ let changed = false;
+ for (const [id, { offset }] of overrides) {
+ if (!offset) {
+ continue;
+ }
+ offsetCount++;
+ const before = previous.get(id);
+ if (!before || before.x !== offset.x || before.y !== offset.y) {
+ changed = true;
+ break;
+ }
+ }
+ if (!changed && offsetCount === previous.size) {
+ return previous;
+ }
+
+ const next = new Map<string, NonNullable<ElementRenderOverride["offset"]>>();
+ for (const [id, { offset }] of overrides) {
+ if (offset) {
+ next.set(id, offset);
+ }
+ }
+ return next;
+};
diff --git a/packages/excalidraw/renderer/staticScene.ts b/packages/excalidraw/renderer/staticScene.ts
index 0d3566fe14..65cfeb3d5b 100644
--- a/packages/excalidraw/renderer/staticScene.ts
+++ b/packages/excalidraw/renderer/staticScene.ts
@@ -19,12 +19,19 @@ import {
shouldApplyFrameClip,
} from "@excalidraw/element";
-import { renderElement } from "@excalidraw/element";
+import {
+ getRenderElementWithPositionOverride,
+ resolveElementRenderState,
+ renderElement,
+} from "@excalidraw/element";
import { getElementAbsoluteCoords } from "@excalidraw/element";
+import type { ElementRenderState } from "@excalidraw/element";
+
import type {
ElementsMap,
+ ExcalidrawElement,
ExcalidrawFrameLikeElement,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
@@ -196,11 +203,17 @@ const renderLinkIcon = (
context: CanvasRenderingContext2D,
appState: StaticCanvasAppState,
elementsMap: ElementsMap,
+ renderState: ElementRenderState,
) => {
if (element.link && !appState.selectedElementIds[element.id]) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
const [x, y, width, height] = getLinkHandleFromCoords(
- [x1, y1, x2, y2],
+ [
+ x1 + renderState.offset.x,
+ y1 + renderState.offset.y,
+ x2 + renderState.offset.x,
+ y2 + renderState.offset.y,
+ ],
element.angle,
appState,
);
@@ -253,7 +266,7 @@ const renderLinkIcon = (
linkCanvasCacheContext.restore();
}
- context.globalAlpha = element.opacity / 100;
+ context.globalAlpha = renderState.opacity;
context.drawImage(linkCanvas, x - centerX, y - centerY, width, height);
context.restore();
}
@@ -334,13 +347,56 @@ const _renderStaticScene = ({
const inFrameGroupsMap = new Map<string, boolean>();
+ const getRenderState = (element: ExcalidrawElement) =>
+ resolveElementRenderState(
+ element,
+ elementsMap,
+ renderConfig,
+ allElementsMap,
+ );
+
+ const clipElementToFrame = (
+ element: NonDeletedExcalidrawElement,
+ renderState: ElementRenderState,
+ ) => {
+ if (
+ !(element.frameId || appState.frameToHighlight?.id) ||
+ !appState.frameRendering.enabled ||
+ !appState.frameRendering.clip
+ ) {
+ return;
+ }
+ const targetFrame = getTargetFrame(element, elementsMap, appState);
+ if (!targetFrame) {
+ return;
+ }
+ const frameState = getRenderState(targetFrame);
+ const frame = getRenderElementWithPositionOverride(
+ targetFrame,
+ frameState.offset,
+ );
+ const isTranslated = (state: ElementRenderState) =>
+ state.offset.x !== 0 || state.offset.y !== 0;
+ if (
+ (element.frameId === frame.id &&
+ (isTranslated(renderState) || isTranslated(frameState))) ||
+ shouldApplyFrameClip(
+ getRenderElementWithPositionOverride(element, renderState.offset),
+ frame,
+ appState,
+ elementsMap,
+ inFrameGroupsMap,
+ )
+ ) {
+ frameClip(frame, context, renderConfig, appState);
+ }
+ };
+
// Paint visible elements
visibleElements
.filter((el) => !isIframeLikeElement(el))
.forEach((element) => {
try {
- const frameId = element.frameId || appState.frameToHighlight?.id;
-
if (
isTextElement(element) &&
element.containerId &&
@@ -351,47 +407,21 @@ const _renderStaticScene = ({
}
context.save();
+ const boundTextElement = getBoundTextElement(element, elementsMap);
- if (
- frameId &&
- appState.frameRendering.enabled &&
- appState.frameRendering.clip
- ) {
- const frame = getTargetFrame(element, elementsMap, appState);
- if (
- frame &&
- shouldApplyFrameClip(
- element,
- frame,
- appState,
- elementsMap,
- inFrameGroupsMap,
- )
- ) {
- frameClip(frame, context, renderConfig, appState);
- }
- renderElement(
- element,
- elementsMap,
- allElementsMap,
- rc,
- context,
- renderConfig,
- appState,
- );
- } else {
- renderElement(
- element,
- elementsMap,
- allElementsMap,
- rc,
- context,
- renderConfig,
- appState,
- );
- }
+ const renderState = getRenderState(element);
+ clipElementToFrame(element, renderState);
+ renderElement(
+ element,
+ elementsMap,
+ allElementsMap,
+ rc,
+ context,
+ renderConfig,
+ appState,
+ renderState,
+ );
- const boundTextElement = getBoundTextElement(element, elementsMap);
if (boundTextElement) {
renderElement(
boundTextElement,
@@ -407,7 +437,7 @@ const _renderStaticScene = ({
context.restore();
if (!isExporting && renderConfig.renderLinks !== false) {
- renderLinkIcon(element, context, appState, elementsMap);
+ renderLinkIcon(element, context, appState, elementsMap, renderState);
}
} catch (error: any) {
console.error(
@@ -426,9 +456,37 @@ const _renderStaticScene = ({
.filter((el) => isIframeLikeElement(el))
.forEach((element) => {
try {
- const render = () => {
+ 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,
+ };
renderElement(
- element,
+ label,
elementsMap,
allElementsMap,
rc,
@@ -436,62 +494,11 @@ const _renderStaticScene = ({
renderConfig,
appState,
);
-
- if (
- isIframeLikeElement(element) &&
- (isExporting ||
- (isEmbeddableElement(element) &&
- renderConfig.embedsValidationStatus.get(element.id) !==
- true)) &&
- element.width &&
- element.height
- ) {
- const label = createPlaceholderEmbeddableLabel(element);
- renderElement(
- label,
- elementsMap,
- allElementsMap,
- rc,
- context,
- renderConfig,
- appState,
- );
- }
- if (!isExporting && renderConfig.renderLinks !== false) {
- renderLinkIcon(element, context, appState, elementsMap);
- }
- };
- // - when exporting the whole canvas, we DO NOT apply clipping
- // - when we are exporting a particular frame, apply clipping
- // if the containing frame is not selected, apply clipping
- const frameId = element.frameId || appState.frameToHighlight?.id;
-
- if (
- frameId &&
- appState.frameRendering.enabled &&
- appState.frameRendering.clip
- ) {
- context.save();
-
- const frame = getTargetFrame(element, elementsMap, appState);
-
- if (
- frame &&
- shouldApplyFrameClip(
- element,
- frame,
- appState,
- elementsMap,
- inFrameGroupsMap,
- )
- ) {
- frameClip(frame, context, renderConfig, appState);
- }
- render();
- context.restore();
- } else {
- render();
}
+ if (!isExporting && renderConfig.renderLinks !== false) {
+ renderLinkIcon(element, context, appState, elementsMap, renderState);
+ }
+ context.restore();
} catch (error: any) {
console.error(error);
}
diff --git a/packages/excalidraw/scene/Renderer.ts b/packages/excalidraw/scene/Renderer.ts
index fdcee2a68d..34f75aa59c 100644
--- a/packages/excalidraw/scene/Renderer.ts
+++ b/packages/excalidraw/scene/Renderer.ts
@@ -1,7 +1,9 @@
import {
getCommonFrameId,
getFrameChildrenInsertionIndex,
+ getContainerElement,
isElementInViewport,
+ isTextElement,
} from "@excalidraw/element";
import { arrayToMap, memoize, toBrandedType } from "@excalidraw/common";
@@ -20,7 +22,7 @@ import { renderStaticSceneThrottled } from "../renderer/staticScene";
import type { RenderableElementsMap } from "./types";
-import type { AppState } from "../types";
+import type { AppState, ElementRenderOffsets } from "../types";
type GetRenderableElementsOpts = {
zoom: AppState["zoom"];
@@ -44,6 +46,157 @@ export class Renderer {
this.scene = scene;
}
+ /**
+ * Adjusts the document-visible set for render-override translations: an
+ * element leaves it when its offset moves it out of view and enters it when
+ * its offset brings it in; everything else keeps its document visibility.
+ * Only translated elements go through viewport geometry. The result is
+ * memoized on the offsets' identity so that opacity-only snapshots don't
+ * reach it at all.
+ */
+ public getVisibleElementsWithRenderOffsets(
+ visibleElements: readonly NonDeletedExcalidrawElement[],
+ elementsMap: RenderableElementsMap,
+ appState: AppState,
+ offsets: ElementRenderOffsets,
+ ) {
+ return this._getVisibleElementsWithRenderOffsets({
+ visibleElements,
+ elementsMap,
+ offsets,
+ zoom: appState.zoom,
+ scrollX: appState.scrollX,
+ scrollY: appState.scrollY,
+ offsetLeft: appState.offsetLeft,
+ offsetTop: appState.offsetTop,
+ width: appState.width,
+ height: appState.height,
+ selectedElements: this.scene.getSelectedElements(appState),
+ frameToHighlight: appState.selectedElementsAreBeingDragged
+ ? appState.frameToHighlight
+ : null,
+ });
+ }
+
+ private _getVisibleElementsWithRenderOffsets = memoize(
+ ({
+ visibleElements,
+ elementsMap,
+ offsets,
+ selectedElements,
+ frameToHighlight,
+ ...viewport
+ }: Pick<
+ GetRenderableElementsOpts,
+ | "zoom"
+ | "scrollX"
+ | "scrollY"
+ | "offsetLeft"
+ | "offsetTop"
+ | "width"
+ | "height"
+ | "selectedElements"
+ | "frameToHighlight"
+ > & {
+ visibleElements: readonly NonDeletedExcalidrawElement[];
+ elementsMap: RenderableElementsMap;
+ offsets: ElementRenderOffsets;
+ }) => {
+ // Shifting the viewport instead of the element also works for arrow
+ // labels, whose coordinates derive from their container.
+ const isVisible = (
+ element: NonDeletedExcalidrawElement,
+ offset: ElementRenderOffsets extends ReadonlyMap<string, infer T>
+ ? T
+ : never,
+ ) =>
+ isElementInViewport(
+ element,
+ viewport.width,
+ viewport.height,
+ {
+ ...viewport,
+ scrollX: viewport.scrollX + offset.x,
+ scrollY: viewport.scrollY + offset.y,
+ },
+ elementsMap,
+ );
+
+ const documentVisible = this.getVisibleSet(visibleElements);
+ const added = new Set<NonDeletedExcalidrawElement>();
+ const removed = new Set<NonDeletedExcalidrawElement>();
+ const update = (
+ element: NonDeletedExcalidrawElement,
+ visible: boolean,
+ ) => {
+ if (documentVisible.has(element) !== visible) {
+ (visible ? added : removed).add(element);
+ }
+ };
+ for (const [id, offset] of offsets) {
+ const element = elementsMap.get(id);
+ // A bound label's own offset is ignored, and it needs no entry of
+ // its own: the static renderer draws it with its container and skips
+ // its entry, so its document visibility can stay as it is.
+ if (
+ !element ||
+ (isTextElement(element) && getContainerElement(element, elementsMap))
+ ) {
+ continue;
+ }
+ update(element, isVisible(element, offset));
+ }
+
+ if (!added.size && !removed.size) {
+ return visibleElements;
+ }
+
+ const needsFrameReordering =
+ frameToHighlight &&
+ getCommonFrameId(selectedElements) !== frameToHighlight.id;
+ if (!added.size && !needsFrameReordering) {
+ return visibleElements.filter((element) => !removed.has(element));
+ }
+
+ // Rebuild in scene order when elements enter the view. Frame-drag
+ // ordering also needs rebuilding on removals, since the anchoring frame
+ // may have left the view.
+ const result: NonDeletedExcalidrawElement[] = [];
+ for (const element of elementsMap.values()) {
+ if (
+ added.has(element) ||
+ (documentVisible.has(element) && !removed.has(element))
+ ) {
+ result.push(element);
+ }
+ }
+ return needsFrameReordering
+ ? this.sortSelectedElementsIntoHighlightedFrame({
+ visibleElements: result,
+ selectedElements,
+ frameToHighlight,
+ })
+ : result;
+ },
+ );
+
+ /** the document-visible elements as a set, cached per visible array */
+ private visibleSets = new WeakMap<
+ readonly NonDeletedExcalidrawElement[],
+ Set<NonDeletedExcalidrawElement>
+ >();
+
+ private getVisibleSet(
+ visibleElements: readonly NonDeletedExcalidrawElement[],
+ ) {
+ let set = this.visibleSets.get(visibleElements);
+ if (!set) {
+ set = new Set(visibleElements);
+ this.visibleSets.set(visibleElements, set);
+ }
+ return set;
+ }
+
private getVisibleCanvasElements({
elementsMap,
zoom,
@@ -258,5 +411,6 @@ export class Renderer {
public destroy() {
renderStaticSceneThrottled.cancel();
this._getRenderableElements.clear();
+ this._getVisibleElementsWithRenderOffsets.clear();
}
}
diff --git a/packages/excalidraw/scene/types.ts b/packages/excalidraw/scene/types.ts
index d67628388a..52d4439b32 100644
--- a/packages/excalidraw/scene/types.ts
+++ b/packages/excalidraw/scene/types.ts
@@ -12,6 +12,7 @@ import type {
AppClassProperties,
AppState,
EmbedsValidationStatus,
+ ElementRenderOverrides,
ElementsPendingErasure,
InteractiveCanvasAppState,
StaticCanvasAppState,
@@ -40,6 +41,7 @@ export type StaticCanvasRenderConfig = {
elementsPendingErasure: ElementsPendingErasure;
pendingFlowchartNodes: PendingExcalidrawElements | null;
theme: AppState["theme"];
+ elementRenderOverrides?: ElementRenderOverrides;
};
export type SVGRenderConfig = {
diff --git a/packages/excalidraw/tests/pixelSnap.test.tsx b/packages/excalidraw/tests/pixelSnap.test.tsx
index 56045d618f..cd5c36c4da 100644
--- a/packages/excalidraw/tests/pixelSnap.test.tsx
+++ b/packages/excalidraw/tests/pixelSnap.test.tsx
@@ -4,7 +4,7 @@ import { Excalidraw } from "../index";
import { snapScrollToDevicePixels } from "../renderer/helpers";
import { API } from "./helpers/api";
-import { GlobalTestState, render, waitFor } from "./test-utils";
+import { act, GlobalTestState, render, waitFor } from "./test-utils";
import type { NormalizedZoomValue } from "../types";
@@ -190,6 +190,110 @@ describe("element pixel snap", () => {
});
expect(distanceToWholePixel(blit)).toBeGreaterThan(1e-3);
});
+
+ it.each([0, Math.PI / 2, 0.4])(
+ "places overridden bitmaps like translated document geometry (%s rad)",
+ async (angle) => {
+ const ownerWindow = GlobalTestState.canvas.ownerDocument.defaultView!;
+ const pixelRatioDescriptor = Object.getOwnPropertyDescriptor(
+ ownerWindow,
+ "devicePixelRatio",
+ )!;
+ try {
+ for (const devicePixelRatio of [1, 2]) {
+ Object.defineProperty(ownerWindow, "devicePixelRatio", {
+ configurable: true,
+ value: devicePixelRatio,
+ });
+ for (const zoom of [1, 1.5, 0.73]) {
+ const props = {
+ type: "rectangle" as const,
+ x: 110.37,
+ y: 140.61,
+ width: 120,
+ height: 60,
+ angle: angle as any,
+ };
+ const element = API.createElement(props);
+ API.setElements([element]);
+ await renderAt(zoom, 3.3, -7.77);
+ (GlobalTestState.canvas.getContext("2d") as any).__clearEvents();
+ act(() =>
+ window.h.app.api.setElementRenderOverrides(
+ new Map([[element.id, { offset: { x: 13.37, y: -7.61 } }]]),
+ ),
+ );
+ const [overridden] = await waitFor(() => {
+ const blits = getBlits();
+ expect(blits).toHaveLength(1);
+ return blits;
+ });
+ act(() => window.h.app.api.setElementRenderOverrides(null));
+ API.setElements([
+ API.createElement({
+ ...props,
+ x: props.x + 13.37,
+ y: props.y - 7.61,
+ }),
+ ]);
+ const [translated] = await renderAt(zoom, 3.3, -7.77);
+ expect(overridden.x).toBeCloseTo(translated.x, 6);
+ expect(overridden.y).toBeCloseTo(translated.y, 6);
+ expect(overridden.scale).toBeCloseTo(translated.scale, 6);
+ if (angle !== 0.4) {
+ expect(distanceToWholePixel(overridden)).toBeLessThan(1e-6);
+ }
+ }
+ }
+ } finally {
+ Object.defineProperty(
+ ownerWindow,
+ "devicePixelRatio",
+ pixelRatioDescriptor,
+ );
+ }
+ },
+ );
+
+ it("keeps bound-label snapping stable through inherited fractional offsets", async () => {
+ const box = API.createElement({
+ type: "rectangle",
+ id: "box",
+ x: 10,
+ y: 10,
+ width: 200,
+ height: 100,
+ boundElements: [{ type: "text", id: "label" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label",
+ x: 61,
+ y: 30,
+ text: "hi",
+ fontSize: 20,
+ containerId: box.id,
+ });
+ API.setElements([box, label]);
+ await renderAt(1.5, 3.3, -7.77);
+ const offsets = new Set<string>();
+ for (const translation of [0, 0.3, 0.4, 0.7, 1.4]) {
+ (GlobalTestState.canvas.getContext("2d") as any).__clearEvents();
+ act(() =>
+ window.h.app.api.setElementRenderOverrides(
+ new Map([[box.id, { offset: { x: translation, y: translation } }]]),
+ ),
+ );
+ const blits = await waitFor(() => {
+ const blits = getBlits();
+ expect(blits).toHaveLength(2);
+ return blits;
+ });
+ const [labelBlit, boxBlit] = [...blits].sort((p, q) => p.width - q.width);
+ offsets.add(`${labelBlit.x - boxBlit.x},${labelBlit.y - boxBlit.y}`);
+ }
+ expect(offsets.size).toBe(1);
+ });
});
describe("scroll pixel snap", () => {
diff --git a/packages/excalidraw/tests/renderOverrides.test.tsx b/packages/excalidraw/tests/renderOverrides.test.tsx
new file mode 100644
index 0000000000..a2307a6695
--- /dev/null
+++ b/packages/excalidraw/tests/renderOverrides.test.tsx
@@ -0,0 +1,1282 @@
+import React from "react";
+import rough from "roughjs/bin/rough";
+
+import * as Element from "@excalidraw/element";
+import {
+ BOUND_TEXT_PADDING,
+ DEFAULT_REDUCED_GLOBAL_ALPHA,
+ ELEMENT_READY_TO_ERASE_OPACITY,
+} from "@excalidraw/common";
+import { pointFrom, type LocalPoint } from "@excalidraw/math";
+
+import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
+
+import { Excalidraw } from "../index";
+import { getDefaultAppState } from "../appState";
+import * as StaticScene from "../renderer/staticScene";
+import { Renderer } from "../scene/Renderer";
+import { exportToSvg } from "../scene/export";
+import { getNormalizedZoom } from "../scene";
+import { getElementRenderOffsets } from "../renderOverrides";
+
+import { API } from "./helpers/api";
+import {
+ act,
+ GlobalTestState,
+ mockBoundingClientRect,
+ render,
+ restoreOriginalGetBoundingClientRect,
+ waitFor,
+} from "./test-utils";
+
+import type {
+ AppState,
+ ElementRenderOffsets,
+ ElementRenderOverride,
+ ElementRenderOverrides,
+} from "../types";
+import type {
+ RenderableElementsMap,
+ StaticCanvasRenderConfig,
+} from "../scene/types";
+
+const { h } = window;
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ restoreOriginalGetBoundingClientRect();
+});
+
+describe("setElementRenderOverrides", () => {
+ const setup = async () => {
+ const element = API.createElement({ type: "rectangle", opacity: 70 });
+ const onChange = vi.fn();
+ const mounted = await render(
+ <Excalidraw initialData={{ elements: [element] }} onChange={onChange} />,
+ );
+ const rendering = vi.spyOn(StaticScene, "renderStaticScene");
+ const submit = (snapshot: ElementRenderOverrides | null) => {
+ act(() => h.app.api.setElementRenderOverrides(snapshot));
+ // Equivalent snapshots need not render, but the published state remains
+ // available for checking snapshot ownership and identity.
+ // eslint-disable-next-line dot-notation -- inspect private state without triggering a render
+ return h.app["elementRenderOverrides"];
+ };
+ onChange.mockClear();
+ return { element: h.elements[0], onChange, rendering, submit, ...mounted };
+ };
+
+ it("copies and replaces the complete snapshot, including omitted fields", async () => {
+ const { element, submit } = await setup();
+ const value = { opacity: 25, offset: { x: 100, y: 20 } };
+ const input = new Map([[element.id, value]]);
+ const published = submit(input);
+ value.opacity = 99;
+ value.offset.x = 999;
+ input.clear();
+ expect(published.get(element.id)).toEqual({
+ opacity: 25,
+ offset: { x: 100, y: 20 },
+ });
+
+ const next = submit(new Map([[element.id, { offset: { x: 10, y: 0 } }]]));
+ expect(
+ Element.resolveElementRenderState(
+ element,
+ h.app.scene.getNonDeletedElementsMap(),
+ {
+ elementRenderOverrides: next,
+ elementsPendingErasure: new Set(),
+ pendingFlowchartNodes: null,
+ },
+ ).opacity,
+ ).toBe(0.7);
+ expect(submit(new Map())).toHaveLength(0);
+ expect(submit(null)).toHaveLength(0);
+ });
+
+ it("rejects an invalid snapshot atomically and clamps finite opacity", async () => {
+ const { element, submit, rendering } = await setup();
+ const previous = submit(new Map([[element.id, { opacity: 200 }]]));
+ expect(previous.get(element.id)?.opacity).toBe(100);
+ rendering.mockClear();
+ expect(() =>
+ submit(
+ new Map([
+ [element.id, { opacity: 0 }],
+ ["unknown", { offset: { x: Number.NaN, y: 0 } }],
+ ]),
+ ),
+ ).toThrow(TypeError);
+ expect(rendering).not.toHaveBeenCalled();
+ act(() => h.app.api.updateScene({ appState: { scrollX: 1 } }));
+ expect(
+ rendering.mock.lastCall![0].renderConfig.elementRenderOverrides,
+ ).toBe(previous);
+ });
+
+ it("drops empty entries and rejects null offsets without replacing the snapshot", async () => {
+ const { element, submit, rendering } = await setup();
+ const snapshot = submit(new Map([[element.id, {}]]));
+ expect(snapshot.size).toBe(0);
+ rendering.mockClear();
+ expect(() =>
+ submit(
+ new Map([
+ [element.id, { offset: null } as unknown as ElementRenderOverride],
+ ]),
+ ),
+ ).toThrow(TypeError);
+ expect(rendering).not.toHaveBeenCalled();
+ });
+
+ it("skips empty submissions and repeated clears, but repaints the first clear", async () => {
+ const { element, submit, rendering, onChange } = await setup();
+ const renders = vi.spyOn(h.app, "render");
+ const empty = submit(null);
+ expect(submit(new Map())).toBe(empty);
+ expect(submit(new Map([[element.id, {}]]))).toBe(empty);
+ expect(renders).not.toHaveBeenCalled();
+ expect(rendering).not.toHaveBeenCalled();
+
+ submit(new Map([[element.id, { opacity: 50 }]]));
+ renders.mockClear();
+ rendering.mockClear();
+ const cleared = submit(null);
+ expect(cleared.size).toBe(0);
+ expect(renders).toHaveBeenCalledTimes(1);
+ expect(rendering).toHaveBeenCalledTimes(1);
+ expect(submit(null)).toBe(cleared);
+ expect(submit(new Map([[element.id, {}]]))).toBe(cleared);
+ expect(renders).toHaveBeenCalledTimes(1);
+ expect(rendering).toHaveBeenCalledTimes(1);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("detects caller mutations and complete replacements in a reused map", async () => {
+ const { element, submit, rendering } = await setup();
+ const value = { opacity: 25, offset: { x: 10, y: 20 } };
+ const input: Map<string, ElementRenderOverride> = new Map([
+ [element.id, value],
+ ]);
+ const first = submit(input);
+ rendering.mockClear();
+
+ value.opacity = 60;
+ value.offset.x = 30;
+ const changed = submit(input);
+ expect(changed).not.toBe(first);
+ expect(changed.get(element.id)).toEqual({
+ opacity: 60,
+ offset: { x: 30, y: 20 },
+ });
+ expect(first.get(element.id)).toEqual({
+ opacity: 25,
+ offset: { x: 10, y: 20 },
+ });
+ input.set(element.id, { opacity: 60 });
+ expect(submit(input).get(element.id)).toEqual({ opacity: 60 });
+ input.delete(element.id);
+ input.set("future", { opacity: 60 });
+ expect([...submit(input)]).toEqual([["future", { opacity: 60 }]]);
+ input.clear();
+ expect(submit(input).size).toBe(0);
+ expect(rendering).toHaveBeenCalledTimes(4);
+ });
+
+ it("preserves a pending visual update when followed by an equivalent snapshot", async () => {
+ const { element, rendering, onChange } = await setup();
+ const input = new Map([[element.id, { opacity: 50 }]]);
+ act(() => {
+ h.app.api.setElementRenderOverrides(input);
+ h.app.api.setElementRenderOverrides(new Map(input));
+ });
+ expect(rendering).toHaveBeenCalledTimes(1);
+ expect(
+ rendering.mock.lastCall![0].renderConfig.elementRenderOverrides?.get(
+ element.id,
+ ),
+ ).toEqual({ opacity: 50 });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it.each(["opacity", "translation", "unknown", "empty"])(
+ "does not repaint for unrelated updates with a %s snapshot",
+ async (kind) => {
+ const { element, submit, rendering } = await setup();
+ submit(
+ new Map([
+ [
+ kind === "unknown" ? "unknown" : element.id,
+ kind === "translation"
+ ? { offset: { x: 10, y: 0 } }
+ : kind === "empty"
+ ? {}
+ : { opacity: 0 },
+ ],
+ ]),
+ );
+ rendering.mockClear();
+ act(() => h.app.setState({ cursorButton: "down" }));
+ act(() => h.app.setState({ cursorButton: "up" }));
+ expect(rendering).not.toHaveBeenCalled();
+ act(() => h.app.api.updateScene({ appState: { scrollX: 10 } }));
+ expect(rendering).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("repaints without changing elements, history, store or onChange", async () => {
+ const { element, submit, onChange, rendering } = await setup();
+ const elements = h.elements;
+ const before = JSON.stringify(elements);
+ const state = h.state;
+ const cached = Element.elementWithCanvasCache.get(element);
+ const commit = vi.spyOn(h.store, "commit");
+ const subscriber = vi.fn();
+ const unsubscribe = h.app.api.onChange(subscriber);
+ for (let opacity = 0; opacity <= 100; opacity += 20) {
+ submit(
+ new Map([[element.id, { opacity, offset: { x: opacity, y: 0 } }]]),
+ );
+ }
+ expect(rendering).toHaveBeenCalledTimes(6);
+ expect(h.elements).toBe(elements);
+ expect(JSON.stringify(h.elements)).toBe(before);
+ expect(h.state).toBe(state);
+ expect(cached).toBeDefined();
+ expect(Element.elementWithCanvasCache.get(element)).toBe(cached);
+ expect(commit).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(subscriber).not.toHaveBeenCalled();
+ unsubscribe();
+ });
+
+ it("still commits document changes batched with visual updates", async () => {
+ const { element, onChange } = await setup();
+ act(() => {
+ h.app.api.setElementRenderOverrides(
+ new Map([[element.id, { opacity: 0 }]]),
+ );
+ h.app.api.updateScene({ appState: { viewBackgroundColor: "#ff0000" } });
+ });
+ expect(onChange).toHaveBeenCalled();
+ expect(h.state.viewBackgroundColor).toBe("#ff0000");
+ });
+
+ it("does not skip ordinary forceUpdate calls after a visual-only commit", async () => {
+ const { element, submit, onChange } = await setup();
+ submit(new Map([[element.id, { opacity: 0 }]]));
+ submit(new Map([[element.id, { opacity: 0 }]]));
+ expect(onChange).not.toHaveBeenCalled();
+ act(() => h.app.forceUpdate());
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves exported geometry and opacity unchanged", async () => {
+ const { element, submit } = await setup();
+ const exportScene = async () =>
+ (await exportToSvg(h.app.api.getSceneElements(), h.state, null))
+ .outerHTML;
+ const before = await exportScene();
+ submit(
+ new Map([[element.id, { opacity: 0, offset: { x: 1000, y: 1000 } }]]),
+ );
+ expect(await exportScene()).toBe(before);
+ });
+
+ it("clears on reset and ignores submissions after unmount", async () => {
+ const { element, submit, rendering, unmount } = await setup();
+ submit(new Map([[element.id, { opacity: 0 }]]));
+ act(() => h.app.api.resetScene());
+ expect(
+ rendering.mock.lastCall![0].renderConfig.elementRenderOverrides,
+ ).toHaveLength(0);
+ const api = h.app.api;
+ unmount();
+ rendering.mockClear();
+ expect(() =>
+ api.setElementRenderOverrides(new Map([[element.id, { opacity: 0 }]])),
+ ).not.toThrow();
+ expect(rendering).not.toHaveBeenCalled();
+ });
+
+ it("keeps frame-name editing on document geometry while the frame is translated", async () => {
+ mockBoundingClientRect();
+ const { onChange, submit } = await setup();
+ await waitFor(() => expect(h.state.width).toBe(200));
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ x: 20,
+ y: 30,
+ width: 80,
+ height: 50,
+ });
+ API.setElements([frame]);
+ API.updateElement(frame, { name: " Draft " });
+ act(() => h.setState({ editingFrame: frame.id }));
+ const query = (selector: string) =>
+ GlobalTestState.renderResult.container.querySelector<HTMLElement>(
+ selector,
+ );
+ const nameElement = await waitFor(() => {
+ const element = query(".frame-name");
+ expect(element?.querySelector("input")).not.toBe(null);
+ return element!;
+ });
+ const documentLeft = nameElement.style.left;
+ onChange.mockClear();
+
+ // A render-only offset that puts the frame far off-screen must neither
+ // end the edit (which trims and commits the name) nor move the editor.
+ submit(new Map([[frame.id, { offset: { x: 10000, y: 0 } }]]));
+ expect(h.state.editingFrame).toBe(frame.id);
+ expect(API.getElement(frame).name).toBe(" Draft ");
+ expect(onChange).not.toHaveBeenCalled();
+ expect(query(".frame-name input")).not.toBe(null);
+ expect(query(".frame-name")!.style.left).toBe(documentLeft);
+
+ // Back to being a decoration, the name follows the offset and is culled.
+ act(() => h.setState({ editingFrame: null }));
+ expect(query(".frame-name")).toBe(null);
+ });
+
+ it.each([
+ { type: "frame", zoom: 1, editing: false },
+ { type: "frame", zoom: 2, editing: false },
+ { type: "frame", zoom: 2, editing: true },
+ { type: "magicframe", zoom: 2, editing: false },
+ ] as const)(
+ "keeps $type title hit bounds in document coordinates at zoom $zoom (editing: $editing)",
+ async ({ type, zoom, editing }) => {
+ mockBoundingClientRect({
+ width: 1200,
+ height: 1000,
+ x: 40,
+ left: 40,
+ y: 30,
+ top: 30,
+ right: 1240,
+ bottom: 1030,
+ });
+ const { onChange, submit } = await setup();
+ await waitFor(() => expect(h.state.width).toBe(1200));
+ const frame = API.createElement({
+ type,
+ id: "frame",
+ x: 200,
+ y: 200,
+ width: 200,
+ height: 80,
+ });
+ API.setElements([frame]);
+ API.updateElement(frame, { name: "Frame title" });
+ act(() =>
+ h.setState({
+ zoom: { value: getNormalizedZoom(zoom) },
+ scrollX: 25,
+ scrollY: -30,
+ editingFrame: editing ? frame.id : null,
+ }),
+ );
+ const title = await waitFor(() => {
+ const element =
+ GlobalTestState.renderResult.container.querySelector<HTMLElement>(
+ ".frame-name",
+ );
+ expect(element).not.toBe(null);
+ return element!;
+ });
+ // JSDOM has no layout: measure the rendered CSS position, including
+ // visual offsets, within the editor's viewport rectangle.
+ const measure = vi
+ .spyOn(title, "getBoundingClientRect")
+ .mockImplementation(() => {
+ const width = 60;
+ const height = editing ? 32 : 20;
+ const left = h.state.offsetLeft + parseFloat(title.style.left);
+ const bottom =
+ h.state.offsetTop + h.state.height - parseFloat(title.style.bottom);
+ return {
+ x: left,
+ y: bottom - height,
+ left,
+ top: bottom - height,
+ right: left + width,
+ bottom,
+ width,
+ height,
+ toJSON: () => ({}),
+ };
+ });
+ const cache = h.app.frameNameBoundsCache;
+ cache._cache.clear();
+ const documentBounds = cache.get(frame)!;
+ const point = {
+ x: documentBounds.x + documentBounds.width / 2,
+ y: documentBounds.y + documentBounds.height / 2,
+ };
+ expect(h.app.hitElement(point.x, point.y, frame, false)).toBe(true);
+ cache._cache.clear();
+ onChange.mockClear();
+ const documentElements = JSON.stringify(h.elements);
+
+ // First measurement happens with a translated title (unless editing).
+ submit(new Map([[frame.id, { offset: { x: 120, y: 150 } }]]));
+ const bounds = cache.get(frame);
+ expect(bounds).toEqual(documentBounds);
+ measure.mockClear();
+ submit(new Map([[frame.id, { offset: { x: 140, y: 160 } }]]));
+ expect(cache.get(frame)).toBe(bounds);
+ submit(null);
+ expect(cache.get(frame)).toBe(bounds);
+ expect(h.app.hitElement(point.x, point.y, frame, false)).toBe(true);
+ expect(h.app.hitElement(point.x + 120, point.y + 150, frame, false)).toBe(
+ false,
+ );
+ expect(measure).not.toHaveBeenCalled();
+ expect(JSON.stringify(h.elements)).toBe(documentElements);
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps the offsets map identity while only opacities change", () => {
+ const first = getElementRenderOffsets(
+ new Map([
+ ["a", { opacity: 10, offset: { x: 1, y: 2 } }],
+ ["b", { opacity: 20 }],
+ ]),
+ new Map(),
+ );
+ expect([...first]).toEqual([["a", { x: 1, y: 2 }]]);
+ expect(
+ getElementRenderOffsets(
+ new Map([
+ ["a", { opacity: 99, offset: { x: 1, y: 2 } }],
+ ["b", { opacity: 0 }],
+ ["c", { opacity: 0 }],
+ ]),
+ first,
+ ),
+ ).toBe(first);
+ expect(
+ getElementRenderOffsets(
+ new Map([["a", { offset: { x: 1, y: 3 } }]]),
+ first,
+ ),
+ ).not.toBe(first);
+ expect(getElementRenderOffsets(new Map(), first).size).toBe(0);
+ expect(
+ getElementRenderOffsets(
+ new Map([["b", { offset: { x: 1, y: 2 } }]]),
+ first,
+ ),
+ ).not.toBe(first);
+ });
+
+ it("does not populate a replacement offsets map during a fade", () => {
+ const snapshot = (opacity: number): ElementRenderOverrides =>
+ new Map(
+ Array.from({ length: 1000 }, (_, index) => [
+ `r${index}`,
+ { opacity, offset: { x: index, y: -index } },
+ ]),
+ );
+ const first = getElementRenderOffsets(snapshot(20), new Map());
+ // Snapshot iteration order does not affect offsets or their identity.
+ const fade = new Map([...snapshot(80)].reverse());
+ const set = vi.spyOn(Map.prototype, "set");
+ const next = getElementRenderOffsets(fade, first);
+ const writes = set.mock.calls.length;
+ set.mockRestore();
+
+ expect(next).toBe(first);
+ expect(writes).toBe(0);
+ });
+
+ it.each([
+ [
+ "a later offset changes",
+ [
+ ["a", { x: 1, y: 2 }],
+ ["b", { x: 3, y: 5 }],
+ ],
+ ],
+ [
+ "an offset is appended after unchanged entries",
+ [
+ ["a", { x: 1, y: 2 }],
+ ["b", { x: 3, y: 4 }],
+ ["c", { x: 5, y: 6 }],
+ ],
+ ],
+ ["an offset is removed", [["a", { x: 1, y: 2 }]]],
+ [
+ "an ID changes without changing the number of offsets",
+ [
+ ["a", { x: 1, y: 2 }],
+ ["c", { x: 3, y: 4 }],
+ ],
+ ],
+ ] as const)("replaces the offsets map when %s", (_, entries) => {
+ const previous: ElementRenderOffsets = new Map([
+ ["a", { x: 1, y: 2 }],
+ ["b", { x: 3, y: 4 }],
+ ]);
+ const next = getElementRenderOffsets(
+ new Map(entries.map(([id, offset]) => [id, { offset }])),
+ previous,
+ );
+ expect(next).not.toBe(previous);
+ expect([...next]).toEqual(entries);
+ expect([...previous]).toEqual([
+ ["a", { x: 1, y: 2 }],
+ ["b", { x: 3, y: 4 }],
+ ]);
+ });
+});
+
+describe("render override geometry", () => {
+ const setup = (elements: NonDeletedExcalidrawElement[]) => {
+ const scene = new Element.Scene(elements, { skipValidation: true });
+ const renderer = new Renderer(scene);
+ const appState: AppState = {
+ ...getDefaultAppState(),
+ width: 500,
+ height: 500,
+ offsetLeft: 0,
+ offsetTop: 0,
+ scrollX: 0,
+ scrollY: 0,
+ };
+ const { elementsMap } = renderer.getRenderableElements({
+ ...appState,
+ selectedElements: [],
+ });
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 500;
+ const context = canvas.getContext("2d")!;
+ const renderConfig: StaticCanvasRenderConfig = {
+ imageCache: new Map(),
+ renderGrid: false,
+ isExporting: false,
+ canvasBackgroundColor: "#fff",
+ embedsValidationStatus: new Map(),
+ elementsPendingErasure: new Set(),
+ pendingFlowchartNodes: null,
+ theme: "light",
+ };
+ // What App hands the static canvas: document culling, adjusted for the
+ // snapshot's offsets, whose identity is kept while they don't change.
+ let offsets: ElementRenderOffsets = new Map();
+ const visibleWith = (
+ overrides: ElementRenderOverrides,
+ state: AppState = appState,
+ map: RenderableElementsMap = elementsMap,
+ ) => {
+ const { visibleElements } = renderer.getRenderableElements({
+ ...state,
+ selectedElements: scene.getSelectedElements(state),
+ });
+ offsets = getElementRenderOffsets(overrides, offsets);
+ return offsets.size
+ ? renderer.getVisibleElementsWithRenderOffsets(
+ visibleElements,
+ map,
+ state,
+ offsets,
+ )
+ : visibleElements;
+ };
+ const draw = (overrides: ElementRenderOverrides) =>
+ StaticScene.renderStaticScene({
+ canvas,
+ rc: rough.canvas(canvas),
+ scale: 1,
+ elementsMap,
+ allElementsMap: scene.getNonDeletedElementsMap(),
+ visibleElements: visibleWith(overrides),
+ appState,
+ renderConfig: {
+ ...renderConfig,
+ elementRenderOverrides: overrides,
+ },
+ });
+ return {
+ scene,
+ renderer,
+ appState,
+ elementsMap,
+ context,
+ draw,
+ visibleWith,
+ renderConfig,
+ };
+ };
+
+ it("culls at visual coordinates while preserving interaction geometry", () => {
+ const rect = API.createElement({
+ type: "rectangle",
+ x: 600,
+ y: 100,
+ width: 50,
+ height: 50,
+ });
+ const { renderer, appState, visibleWith } = setup([rect]);
+ const overrides = new Map([[rect.id, { offset: { x: -300, y: 0 } }]]);
+ expect(visibleWith(overrides)).toContain(rect);
+ expect(
+ renderer.getRenderableElements({ ...appState, selectedElements: [] })
+ .visibleElements,
+ ).not.toContain(rect);
+ expect(rect.x).toBe(600);
+ });
+
+ it("updates cached visibility for new overrides, viewport bounds and scene elements", () => {
+ const rect = API.createElement({
+ type: "rectangle",
+ id: "a",
+ x: 600,
+ y: 100,
+ width: 50,
+ height: 50,
+ });
+ const { renderer, appState, scene, visibleWith } = setup([rect]);
+ const overrides = new Map([[rect.id, { offset: { x: -300, y: 0 } }]]);
+ const visible = visibleWith(overrides);
+ expect(visible).toContain(rect);
+ expect(visibleWith(overrides, { ...appState, cursorButton: "down" })).toBe(
+ visible,
+ );
+ // a new snapshot with the same offsets keeps the result too
+ expect(
+ visibleWith(
+ new Map([[rect.id, { opacity: 50, offset: { x: -300, y: 0 } }]]),
+ ),
+ ).toBe(visible);
+ expect(visibleWith(overrides, { ...appState, width: 100 })).not.toContain(
+ rect,
+ );
+ expect(
+ visibleWith(overrides, { ...appState, scrollX: -600 }),
+ ).not.toContain(rect);
+ expect(visibleWith(new Map())).not.toContain(rect);
+
+ const moved = { ...rect, x: 1200 };
+ scene.replaceAllElements([moved], { skipValidation: true });
+ const changed = renderer.getRenderableElements({
+ ...appState,
+ selectedElements: [],
+ });
+ expect(visibleWith(overrides, appState, changed.elementsMap)).not.toContain(
+ moved,
+ );
+ });
+
+ it("reuses the document-visible set for opacity-only snapshots without viewport geometry", () => {
+ const rects = Array.from({ length: 20 }, (_, index) =>
+ API.createElement({
+ type: "rectangle",
+ id: `r${index}`,
+ x: index * 30,
+ y: 10,
+ width: 20,
+ height: 20,
+ }),
+ );
+ const { renderer, appState, visibleWith } = setup(rects);
+ const documentVisible = renderer.getRenderableElements({
+ ...appState,
+ selectedElements: [],
+ }).visibleElements;
+ const inViewport = vi.spyOn(Element, "isElementInViewport");
+
+ expect(visibleWith(new Map([[rects[3].id, { opacity: 50 }]]))).toBe(
+ documentVisible,
+ );
+ expect(visibleWith(new Map([[rects[3].id, { opacity: 51 }]]))).toBe(
+ documentVisible,
+ );
+ expect(inViewport).not.toHaveBeenCalled();
+
+ // translating one element checks that element only, not the scene
+ const moving = visibleWith(
+ new Map([[rects[3].id, { opacity: 50, offset: { x: 5, y: 0 } }]]),
+ );
+ expect(moving).toBe(documentVisible);
+ expect(inViewport).toHaveBeenCalledTimes(1);
+ expect(inViewport.mock.calls[0][0]).toBe(rects[3]);
+ expect(
+ visibleWith(
+ new Map([[rects[3].id, { opacity: 50, offset: { x: 5000, y: 0 } }]]),
+ ),
+ ).toEqual(documentVisible.filter((element) => element !== rects[3]));
+ expect(inViewport).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps frame-drag ordering responsive to selection and drag-state changes", () => {
+ // `a` is off-screen in the document and only visible through its offset,
+ // so the visible set is rebuilt in scene order on every change here.
+ const a = API.createElement({ type: "rectangle", id: "a", x: 600, y: 10 });
+ const b = API.createElement({ type: "rectangle", id: "b", x: 10, y: 10 });
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ width: 300,
+ height: 300,
+ });
+ const child = API.createElement({
+ type: "rectangle",
+ id: "child",
+ frameId: frame.id,
+ x: 20,
+ y: 20,
+ });
+ const { appState, visibleWith } = setup([a, b, frame, child]);
+ const overrides = new Map([[a.id, { offset: { x: -590, y: 0 } }]]);
+ const ids = (state: AppState) =>
+ visibleWith(overrides, state).map((element) => element.id);
+ const selected: AppState = {
+ ...appState,
+ selectedElementIds: { [a.id]: true },
+ frameToHighlight: frame,
+ };
+ expect(ids(selected)).toEqual(["a", "b", "frame", "child"]);
+ expect(ids({ ...selected, selectedElementsAreBeingDragged: true })).toEqual(
+ ["b", "frame", "child", "a"],
+ );
+ expect(
+ ids({
+ ...selected,
+ selectedElementsAreBeingDragged: true,
+ selectedElementIds: { [b.id]: true },
+ }),
+ ).toEqual(["a", "frame", "child", "b"]);
+ expect(ids(selected)).toEqual(["a", "b", "frame", "child"]);
+ });
+
+ it("drops the frame-drag reordering when the anchoring frame is translated away", () => {
+ const a = API.createElement({ type: "rectangle", id: "a", x: 10, y: 10 });
+ const b = API.createElement({ type: "rectangle", id: "b", x: 10, y: 10 });
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ x: 200,
+ y: 200,
+ width: 100,
+ height: 100,
+ });
+ const { appState, visibleWith } = setup([a, b, frame]);
+ const dragging: AppState = {
+ ...appState,
+ selectedElementIds: { [a.id]: true },
+ frameToHighlight: frame,
+ selectedElementsAreBeingDragged: true,
+ };
+ const ids = (overrides: ElementRenderOverrides) =>
+ visibleWith(overrides, dragging).map((element) => element.id);
+ expect(ids(new Map())).toEqual(["b", "a", "frame"]);
+ // the frame leaves the view: back to plain scene order, like a full
+ // recalculation would produce
+ expect(ids(new Map([[frame.id, { offset: { x: 10000, y: 0 } }]]))).toEqual([
+ "a",
+ "b",
+ ]);
+ expect(ids(new Map([[frame.id, { offset: { x: 0, y: 0 } }]]))).toEqual([
+ "b",
+ "a",
+ "frame",
+ ]);
+ });
+
+ it.each(["a", "b", "c"])(
+ "preserves scene order as %s is translated into and out of view",
+ (id) => {
+ const sceneIds = ["a", "b", "c"];
+ const { visibleWith } = setup(
+ sceneIds.map((elementId) =>
+ API.createElement({
+ type: "rectangle",
+ id: elementId,
+ x: elementId === id ? 600 : 10,
+ y: 10,
+ }),
+ ),
+ );
+ const ids = (offsetX: number) =>
+ visibleWith(new Map([[id, { offset: { x: offsetX, y: 0 } }]])).map(
+ (element) => element.id,
+ );
+ expect(ids(-590)).toEqual(sceneIds);
+ expect(ids(-580)).toEqual(sceneIds);
+ expect(ids(-570)).toEqual(sceneIds);
+ expect(ids(0)).toEqual(sceneIds.filter((elementId) => elementId !== id));
+ },
+ );
+
+ it("preserves scene order when elements enter and leave in the same update", () => {
+ const a = API.createElement({ type: "rectangle", id: "a", x: 600, y: 10 });
+ const b = API.createElement({ type: "rectangle", id: "b", x: 10, y: 10 });
+ const c = API.createElement({ type: "rectangle", id: "c", x: 600, y: 60 });
+ const d = API.createElement({ type: "rectangle", id: "d", x: 10, y: 60 });
+ const { visibleWith } = setup([a, b, c, d]);
+ expect(
+ visibleWith(
+ new Map([
+ [c.id, { offset: { x: -590, y: 0 } }],
+ [b.id, { offset: { x: 1000, y: 0 } }],
+ [a.id, { offset: { x: -590, y: 0 } }],
+ ]),
+ ),
+ ).toEqual([a, c, d]);
+ expect(visibleWith(new Map())).toEqual([b, d]);
+ });
+
+ it("does not rebuild the visible set for a translated arrow whose label is off-screen", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ id: "arrow",
+ x: -1000,
+ y: 100,
+ width: 1100,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(1100, 0)],
+ boundElements: [{ id: "label", type: "text" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label",
+ x: -500,
+ y: 90,
+ width: 50,
+ text: "label",
+ containerId: arrow.id,
+ });
+ const { renderer, appState, elementsMap, visibleWith } = setup([
+ arrow,
+ label,
+ ]);
+ const documentVisible = renderer.getRenderableElements({
+ ...appState,
+ selectedElements: [],
+ }).visibleElements;
+ expect(documentVisible).toEqual([arrow]);
+ const walk = vi.spyOn(elementsMap, "values");
+ for (const x of [10, 20, 30]) {
+ expect(visibleWith(new Map([[arrow.id, { offset: { x, y: 0 } }]]))).toBe(
+ documentVisible,
+ );
+ }
+ expect(walk).not.toHaveBeenCalled();
+ });
+
+ it.each(["rectangle", "arrow"] as const)(
+ "culls a %s by its container offset; its label needs no entry of its own",
+ (type) => {
+ const container = API.createElement({
+ type,
+ id: "a",
+ x: 900,
+ y: 100,
+ width: 100,
+ points:
+ type === "arrow"
+ ? [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)]
+ : undefined,
+ boundElements: [{ id: "label", type: "text" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label",
+ x: 750,
+ y: 110,
+ width: 400,
+ text: "label",
+ containerId: container.id,
+ });
+ const { renderer, appState, visibleWith } = setup([container, label]);
+ const visible = visibleWith;
+ expect(visible(new Map())).toEqual([]);
+ // The container comes into view through its offset; the label is drawn
+ // with it, so its own (document, off-screen) entry stays out and any
+ // offset targeting it directly is ignored.
+ expect(
+ visible(new Map([[container.id, { offset: { x: -500, y: 0 } }]])),
+ ).toEqual([container]);
+ expect(
+ visible(
+ new Map([
+ [container.id, { offset: { x: -500, y: 0 } }],
+ [label.id, { offset: { x: 2000, y: 0 } }],
+ ]),
+ ),
+ ).toEqual([container]);
+ expect(
+ visible(new Map([[label.id, { offset: { x: -800, y: 0 } }]])),
+ ).toEqual([]);
+ expect(
+ visible(
+ new Map([
+ [container.id, { offset: { x: -2000, y: 0 } }],
+ [label.id, { offset: { x: -800, y: 0 } }],
+ ]),
+ ),
+ ).toEqual([]);
+ expect(
+ renderer.getRenderableElements({ ...appState, selectedElements: [] })
+ .visibleElements,
+ ).toEqual([]);
+ },
+ );
+
+ it.each(["arrow", "rectangle", "ellipse", "diamond", "stickynote"] as const)(
+ "moves a %s label with its container while keeping label opacity independent",
+ (type) => {
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ width: 500,
+ height: 500,
+ opacity: 50,
+ });
+ const container = API.createElement({
+ type,
+ id: "container",
+ x: 50,
+ y: 100,
+ width: 200,
+ height: 100,
+ frameId: frame.id,
+ points:
+ type === "arrow"
+ ? [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)]
+ : undefined,
+ boundElements: [{ id: "label", type: "text" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label",
+ text: "Label",
+ x: 100,
+ y: 140,
+ width: 50,
+ height: 25,
+ opacity: 70,
+ containerId: container.id,
+ frameId: frame.id,
+ });
+ const { context, draw } = setup([container, label, frame]);
+ draw(new Map());
+ const bitmap = Element.elementWithCanvasCache.get(label)!;
+ expect(bitmap).toBeDefined();
+ const original = JSON.stringify([container, label, frame]);
+ const paints: { x: number; y: number; alpha: number }[] = [];
+ const drawImage = vi.mocked(context.drawImage).getMockImplementation()!;
+ vi.spyOn(context, "drawImage").mockImplementation((...args) => {
+ const [source, x, y] = args;
+ if (source === bitmap.canvas) {
+ const t = context.getTransform();
+ paints.push({
+ x: t.a * x + t.c * y + t.e,
+ y: t.b * x + t.d * y + t.f,
+ alpha: context.globalAlpha,
+ });
+ }
+ drawImage.call(context, ...args);
+ });
+ const offset = { x: 20, y: 10 };
+ draw(new Map());
+ draw(new Map([[container.id, { offset }]]));
+ draw(
+ new Map([
+ [container.id, { offset }],
+ [label.id, { offset }],
+ ]),
+ );
+ draw(
+ new Map([
+ [container.id, { offset, opacity: 10 }],
+ [label.id, { offset: { x: 1000, y: -1000 }, opacity: 40 }],
+ ]),
+ );
+ draw(new Map([[label.id, { offset: { x: 1000, y: -1000 } }]]));
+ draw(new Map());
+ expect(paints).toHaveLength(6);
+ const [baseline] = paints;
+ expect(baseline.alpha).toBe(0.35);
+ const translated = {
+ x: baseline.x + offset.x,
+ y: baseline.y + offset.y,
+ alpha: baseline.alpha,
+ };
+ expect(paints.slice(1)).toEqual([
+ translated,
+ translated,
+ { ...translated, alpha: 0.2 },
+ baseline,
+ baseline,
+ ]);
+ expect(Element.elementWithCanvasCache.get(label)).toBe(bitmap);
+ expect(JSON.stringify([container, label, frame])).toBe(original);
+ },
+ );
+
+ it("keeps offsets on unbound text independent", () => {
+ const label = API.createElement({
+ type: "text",
+ x: 600,
+ y: 100,
+ text: "Label",
+ });
+ const { elementsMap, renderConfig, visibleWith } = setup([label]);
+ const overrides = new Map([[label.id, { offset: { x: -400, y: 10 } }]]);
+ expect(
+ Element.resolveElementRenderState(label, elementsMap, {
+ ...renderConfig,
+ elementRenderOverrides: overrides,
+ }).offset,
+ ).toEqual({ x: -400, y: 10 });
+ expect(visibleWith(overrides)).toContain(label);
+ });
+
+ it("clips a translated child against the translated frame boundary", () => {
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 200,
+ });
+ const rect = API.createElement({
+ type: "rectangle",
+ x: 120,
+ y: 120,
+ width: 50,
+ height: 50,
+ frameId: frame.id,
+ });
+ const { draw, context } = setup([rect, frame]);
+ const clip = vi.spyOn(context, "clip");
+ const translate = vi.spyOn(context, "translate");
+ draw(
+ new Map([
+ [rect.id, { offset: { x: -60, y: 0 } }],
+ [frame.id, { offset: { x: 10, y: 0 } }],
+ ]),
+ );
+ expect(clip).toHaveBeenCalled();
+ expect(translate).toHaveBeenCalledWith(110, 100);
+ });
+
+ it("multiplies overridden frame and child opacities", () => {
+ const frame = API.createElement({ type: "frame", id: "frame" });
+ const rect = API.createElement({ type: "rectangle", frameId: frame.id });
+ expect(
+ Element.resolveElementRenderState(
+ rect,
+ new Map<string, NonDeletedExcalidrawElement>([
+ [frame.id, frame],
+ [rect.id, rect],
+ ]),
+ {
+ elementRenderOverrides: new Map([
+ [frame.id, { opacity: 50 }],
+ [rect.id, { opacity: 50 }],
+ ]),
+ elementsPendingErasure: new Set(),
+ pendingFlowchartNodes: null,
+ },
+ ).opacity,
+ ).toBe(0.25);
+ });
+
+ it("gives a synthetic embed label its owner's overrides and frame", () => {
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ width: 500,
+ height: 500,
+ });
+ const embed = API.createElement({
+ type: "embeddable",
+ id: "embed",
+ width: 200,
+ height: 100,
+ frameId: frame.id,
+ });
+ const { draw } = setup([embed, frame]);
+ const renderElement = vi.spyOn(Element, "renderElement");
+ draw(new Map([[embed.id, { opacity: 0, offset: { x: 20, y: 0 } }]]));
+ const label = renderElement.mock.calls.find(
+ ([element]) => element.type === "text",
+ )?.[0];
+ expect(label).toMatchObject({ id: embed.id, frameId: frame.id });
+ });
+
+ it.each([
+ [0, 80],
+ [80, 0],
+ [30, 80],
+ [80, 80],
+ ])(
+ "keeps the label gap with its arrow (arrow %s, ignored label %s)",
+ (arrowX, labelX) => {
+ const arrow = API.createElement({
+ type: "arrow",
+ id: "arrow",
+ x: 50,
+ y: 100,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(300, 0)],
+ boundElements: [{ id: "label", type: "text" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label",
+ containerId: arrow.id,
+ text: "Label",
+ width: 50,
+ height: 25,
+ });
+ const { context, draw } = setup([arrow, label]);
+ const holes: number[] = [];
+ const rect = vi.mocked(context.rect).getMockImplementation()!;
+ vi.spyOn(context, "rect").mockImplementation((x, y, width, height) => {
+ if (width === label.width + BOUND_TEXT_PADDING * 2) {
+ const transform = context.getTransform();
+ holes.push(transform.a * x + transform.c * y + transform.e);
+ }
+ rect.call(context, x, y, width, height);
+ });
+ draw(new Map());
+ draw(
+ new Map([
+ [arrow.id, { offset: { x: arrowX, y: 0 } }],
+ [label.id, { offset: { x: labelX, y: 0 } }],
+ ]),
+ );
+ expect(holes).toHaveLength(2);
+ expect(holes[1] - holes[0]).toBeCloseTo(arrowX, 8);
+ },
+ );
+
+ it("reuses original arrow shapes and bitmaps when rendering translated links", () => {
+ const arrow = {
+ ...API.createElement({
+ type: "arrow",
+ x: 50,
+ y: 100,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],
+ }),
+ link: "https://example.com",
+ };
+ const { draw } = setup([arrow]);
+ draw(new Map());
+ const bitmap = Element.elementWithCanvasCache.get(arrow);
+ const shape = Element.ShapeCache.get(arrow, null);
+ const generateShape = vi.spyOn(Element.ShapeCache, "generateElementShape");
+ for (const x of [10, 20, 0]) {
+ draw(new Map([[arrow.id, { offset: { x, y: 0 }, opacity: 40 }]]));
+ }
+ expect(bitmap).toBeDefined();
+ expect(shape).toBeDefined();
+ expect(Element.elementWithCanvasCache.get(arrow)).toBe(bitmap);
+ expect(Element.ShapeCache.get(arrow, null)).toBe(shape);
+ expect(generateShape).toHaveBeenCalled();
+ expect(
+ generateShape.mock.calls.every(([element]) => element === arrow),
+ ).toBe(true);
+ });
+
+ it("preserves frame, erasure and selection alpha without leaking it to siblings or links", () => {
+ const frame = API.createElement({
+ type: "frame",
+ id: "frame",
+ width: 400,
+ height: 400,
+ });
+ const child = {
+ ...API.createElement({
+ type: "rectangle",
+ x: 50,
+ y: 50,
+ frameId: frame.id,
+ }),
+ link: "https://example.com",
+ };
+ const sibling = API.createElement({ type: "rectangle", x: 200, y: 200 });
+ const { context, draw, appState, renderConfig } = setup([
+ child,
+ frame,
+ sibling,
+ ]);
+ appState.openDialog = {
+ name: "elementLinkSelector",
+ sourceElementId: sibling.id,
+ };
+ appState.selectedElementIds = { [sibling.id]: true };
+ renderConfig.elementsPendingErasure.add(child.id);
+ const alphas: number[] = [];
+ const drawImage = vi.mocked(context.drawImage).getMockImplementation()!;
+ vi.spyOn(context, "drawImage").mockImplementation((...args) => {
+ alphas.push(context.globalAlpha);
+ drawImage.call(context, ...args);
+ });
+ draw(
+ new Map([
+ [child.id, { opacity: 50 }],
+ [frame.id, { opacity: 50 }],
+ ]),
+ );
+ const erasedAlpha = (0.25 * ELEMENT_READY_TO_ERASE_OPACITY) / 100;
+ expect(alphas).toEqual([
+ erasedAlpha * DEFAULT_REDUCED_GLOBAL_ALPHA,
+ erasedAlpha,
+ 1,
+ ]);
+ expect(context.globalAlpha).toBe(1);
+ });
+
+ it("keeps the uncropped preview at document coordinates while translating the image", () => {
+ const image = {
+ ...API.createElement({
+ type: "image",
+ x: 100,
+ y: 100,
+ width: 100,
+ height: 60,
+ }),
+ crop: {
+ x: 10,
+ y: 5,
+ width: 50,
+ height: 30,
+ naturalWidth: 100,
+ naturalHeight: 60,
+ },
+ };
+ const { context, draw, appState } = setup([image]);
+ appState.croppingElementId = image.id;
+ const paints: { x: number; y: number; alpha: number }[] = [];
+ const drawImage = vi.mocked(context.drawImage).getMockImplementation()!;
+ vi.spyOn(context, "drawImage").mockImplementation((...args) => {
+ const [, x, y] = args;
+ const t = context.getTransform();
+ paints.push({
+ x: t.a * x + t.c * y + t.e,
+ y: t.b * x + t.d * y + t.f,
+ alpha: context.globalAlpha,
+ });
+ drawImage.call(context, ...args);
+ });
+ draw(new Map());
+ draw(new Map([[image.id, { offset: { x: 80, y: 40 }, opacity: 25 }]]));
+ expect(paints).toHaveLength(4);
+ expect(paints[2]).toEqual(paints[0]);
+ expect(paints[2].alpha).toBe(0.1);
+ expect(paints[3]).toEqual({
+ x: paints[1].x + 80,
+ y: paints[1].y + 40,
+ alpha: 0.25,
+ });
+ });
+});
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index e24326a6d6..c9c13ca9e6 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -798,6 +798,26 @@ export type UIConfig = {
};
};
+/** Supported visual changes. Geometry, content, bindings and styles are not overridable. */
+export type ElementRenderOverride = Readonly<{
+ /** Absolute render opacity (0–100, clamped). Omitted: use element.opacity. */
+ opacity?: number;
+ /** Translation in scene units. Bound labels inherit their container's offset and ignore this field. */
+ offset?: Readonly<{ x: number; y: number }>;
+}>;
+
+/** see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details */
+export type ElementRenderOverrides = ReadonlyMap<
+ ExcalidrawElement["id"],
+ ElementRenderOverride
+>;
+
+/** The translation part of a snapshot: only the entries that carry an offset. */
+export type ElementRenderOffsets = ReadonlyMap<
+ ExcalidrawElement["id"],
+ NonNullable<ElementRenderOverride["offset"]>
+>;
+
export interface ExcalidrawProps {
className?: string;
/**
@@ -1308,6 +1328,24 @@ export interface ExcalidrawImperativeAPI {
getName: InstanceType<typeof App>["getName"];
setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
+ /**
+ * Atomically replaces all transient visual overrides. Values are copied;
+ * omitted IDs/fields use document values, except for inherited label offsets.
+ * null clears the snapshot.
+ * Repaints without document changes, history entries or onChange events;
+ * an equivalent snapshot may still repaint (clearing an already clear
+ * snapshot does not), so submit only when something changed.
+ * Finite opacity is clamped to 0–100; non-finite values reject the snapshot.
+ * Unknown/deleted IDs are ignored when rendering. Reset/unmount clears it.
+ * Bound labels inherit their container's offset; offsets targeting them are
+ * ignored. Label opacity remains independent. Target frame children explicitly.
+ * Frame opacity still multiplies child opacity. Decorations follow their owner.
+ * Exports and interactive geometry (hit tests, selection, editing) use document
+ * values, including while authoring an animation preview in edit mode.
+ */
+ setElementRenderOverrides: InstanceType<
+ typeof App
+ >["setElementRenderOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];