fix(editor): keep z-order when splitting layers for a framed new element

Elements drawn over a moved element now move with it, and a new element
not clipped to its frame (arrows, clipping off) moves everything above it.
Adds unionBounds to the element bounds helpers.

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
This commit is contained in:
Mark Tolmacs committed 2026-11-12 16:35:06 +01:00
1 parent 66afe93381
commit b61cbb6dbc
8 files changed
+254 -67

No files matched your search

+8
View File
@@ -1516,6 +1516,14 @@ export const doBoundsIntersect = (
return minX1 < maxX2 && maxX1 > minX2 && minY1 < maxY2 && maxY1 > minY2;
};
/** the smallest bounds containing both */
export const unionBounds = (bounds1: Bounds, bounds2: Bounds): Bounds => [
Math.min(bounds1[0], bounds2[0]),
Math.min(bounds1[1], bounds2[1]),
Math.max(bounds1[2], bounds2[2]),
Math.max(bounds1[3], bounds2[3]),
];
export const boundsContainBounds = (outerBounds: Bounds, innerBounds: Bounds) =>
[
pointFrom<GlobalPoint>(innerBounds[0], innerBounds[1]),
+6 -5
View File
@@ -2360,9 +2360,9 @@ class App extends React.Component<AppProps, AppState> {
const allElementsMap = this.scene.getNonDeletedElementsMap();
// the elements covering a framed new element are drawn on top of it on
// the new-element canvas instead of the static canvas
const { staticElements, coveringElements } =
// the elements that may be drawn over a framed new element are drawn on
// top of it on the new-element canvas instead of the static canvas
const { staticElements, elementsAboveNewElement } =
this.renderer.getNewElementLayers({
visibleElements: this.elementRenderOffsets.size
? this.renderer.getVisibleElementsWithRenderOffsets(
@@ -2375,6 +2375,7 @@ class App extends React.Component<AppProps, AppState> {
elementsMap: renderableElementsMap,
newElementCanvasElement,
offsets: this.elementRenderOffsets,
appState: this.state,
});
// a tool dragged out of the toolbar previews on the new-element canvas
@@ -2672,7 +2673,7 @@ class App extends React.Component<AppProps, AppState> {
<NewElementCanvas
appState={this.state}
newElement={previewElement}
coveringElements={coveringElements}
elementsAboveNewElement={elementsAboveNewElement}
scale={this.ownerWindow.devicePixelRatio}
rc={this.rc}
elementsMap={renderableElementsMap}
@@ -2683,7 +2684,7 @@ class App extends React.Component<AppProps, AppState> {
scale: this.ownerWindow.devicePixelRatio,
renderEnvironment: this.renderEnvironment,
renderGrid: false,
// covering elements get their link icons
// the elements above the new element get their link icons
// as on the static canvas
renderLinks: this.isLinksEnabled(),
canvasBackgroundColor:
@@ -22,7 +22,7 @@ interface NewElementCanvasProps {
appState: AppState;
newElement: NonNullable<AppState["newElement"]>;
/** elements above a framed new element, drawn on top of it */
coveringElements?: readonly NonDeletedExcalidrawElement[];
elementsAboveNewElement?: readonly NonDeletedExcalidrawElement[];
elementsMap: RenderableElementsMap;
allElementsMap: NonDeletedSceneElementsMap;
scale: number;
@@ -43,7 +43,7 @@ const NewElementCanvas = (props: NewElementCanvasProps) => {
canvas: canvasRef.current,
scale: props.scale,
newElement: props.newElement,
coveringElements: props.coveringElements,
elementsAboveNewElement: props.elementsAboveNewElement,
elementsMap: props.elementsMap,
allElementsMap: props.allElementsMap,
rc: props.rc,
@@ -21,7 +21,7 @@ const _renderNewElementScene = ({
canvas,
rc,
newElement,
coveringElements,
elementsAboveNewElement,
elementsMap,
allElementsMap,
scale,
@@ -92,11 +92,11 @@ const _renderNewElementScene = ({
// the elements above a framed new element, moved off the static canvas
// (see Renderer.getNewElementLayers). Drawn even while the new element
// isn't, as the static canvas no longer draws them.
if (coveringElements?.length) {
if (elementsAboveNewElement?.length) {
renderSceneElements({
context,
rc,
elements: coveringElements,
elements: elementsAboveNewElement,
elementsMap,
allElementsMap,
appState,
+2 -2
View File
@@ -335,8 +335,8 @@ const renderLinkIcon = (
/**
* Paints `elements` in order (embeddables last), each clipped to its frame,
* with bound text and link icons. Shared by the static scene and the new
* element scene, which paints the elements covering a framed new element on
* top of it.
* element scene, which paints the elements that may be drawn over a framed
* new element on top of it.
*/
export const renderSceneElements = ({
context,
+163 -48
View File
@@ -1,4 +1,5 @@
import {
doBoundsIntersect,
getCanvasPadding,
getCommonFrameId,
getElementBounds,
@@ -8,10 +9,14 @@ import {
isFrameLikeElement,
isIframeLikeElement,
isTextElement,
shouldApplyFrameClip,
unionBounds,
} from "@excalidraw/element";
import { arrayToMap, memoize, toBrandedType } from "@excalidraw/common";
import type { Bounds } from "@excalidraw/common";
import type {
ExcalidrawElement,
ExcalidrawFrameLikeElement,
@@ -27,7 +32,11 @@ import { cancelStaticSceneThrottle } from "../renderer/staticScene";
import type { RenderableElementsMap } from "./types";
import type { AppState, ElementRenderOffsets } from "../types";
import type {
AppState,
ElementRenderOffsets,
StaticCanvasAppState,
} from "../types";
type GetRenderableElementsOpts = {
zoom: AppState["zoom"];
@@ -44,6 +53,84 @@ type GetRenderableElementsOpts = {
frameToHighlight: AppState["frameToHighlight"];
};
/** where an element may paint, conservatively, with offsets applied */
const getPaintBounds = (
element: NonDeletedExcalidrawElement,
elementsMap: RenderableElementsMap,
offsets: ElementRenderOffsets,
): Bounds => {
const offset = offsets.get(element.id);
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
// conservative: an extra moved element only costs a redraw
const padding =
getCanvasPadding(element) + (element.link ? DEFAULT_LINK_SIZE * 2 : 0);
const dx = offset?.x ?? 0;
const dy = offset?.y ?? 0;
return [
x1 + dx - padding,
y1 + dy - padding,
x2 + dx + padding,
y2 + dy + padding,
];
};
/** a bound text is drawn with its container, it goes where it goes */
const getRenderTarget = (
element: NonDeletedExcalidrawElement,
elementsMap: RenderableElementsMap,
) =>
(isTextElement(element) && element.containerId
? elementsMap.get(element.containerId)
: null) ?? element;
type NewElementLayersState = {
elementsMap: RenderableElementsMap;
offsets: ElementRenderOffsets;
/** the elements above the new element in z-order */
above: ReadonlySet<NonDeletedExcalidrawElement>;
/** where the new element may paint, null if anywhere */
newElementRegion: Bounds | null;
/** the bounds of the moved elements, and their union for a quick reject */
moved: Bounds[];
movedUnion: Bounds | null;
/** whether an element has to move to the new element canvas */
decided: Map<NonDeletedExcalidrawElement, boolean>;
};
/**
* Whether an element has to move to the new element canvas: it's drawn after
* the new element and may overlap it, or it's drawn after an element that
* moved and overlaps that. Has to be called in drawing order.
*/
const mustMoveToNewElementCanvas = (
element: NonDeletedExcalidrawElement,
state: NewElementLayersState,
) => {
const decided = state.decided.get(element);
if (decided !== undefined) {
return decided;
}
const isDrawnAfterNewElement =
state.above.has(element) || isIframeLikeElement(element);
const bounds = getPaintBounds(element, state.elementsMap, state.offsets);
const mustMove =
(isDrawnAfterNewElement &&
(!state.newElementRegion ||
doBoundsIntersect(bounds, state.newElementRegion))) ||
(doBoundsIntersect(bounds, state.movedUnion) &&
state.moved.some((moved) => doBoundsIntersect(bounds, moved)));
if (mustMove) {
state.moved.push(bounds);
state.movedUnion = state.movedUnion
? unionBounds(state.movedUnion, bounds)
: bounds;
}
state.decided.set(element, mustMove);
return mustMove;
};
export class Renderer {
private scene: Scene;
@@ -256,8 +343,8 @@ export class Renderer {
const elementsMap = toBrandedType<RenderableElementsMap>(new Map());
// A new text doubles as `editingTextElement` (drawn by the wysiwyg), so a
// framed one isn't drawn on any canvas. Every other new element goes to
// the new element canvas, framed ones included: the elements covering it
// are drawn there on top of it (see getNewElementLayers).
// the new element canvas, framed ones included: the elements that may be
// drawn over it are drawn there on top of it (see getNewElementLayers).
const newElementCanvasElement =
newElement?.frameId && isTextElement(newElement) ? null : newElement;
@@ -423,15 +510,23 @@ export class Renderer {
/**
* Splits the static canvas' elements around a framed new element drawn on
* the new element canvas. The new element sits at its frame's children
* insertion index, so elements above it in z-order that overlap its frame
* have to be drawn on top of it. They're moved off the static canvas to the
* new element canvas, which draws them after the new element. Embeddables
* are drawn on top of everything on the static canvas, so overlapping ones
* move regardless of z-order.
* insertion index, so elements drawn after it that may overlap it have to
* be drawn on top of it. They're moved off the static canvas to the new
* element canvas, which draws them after the new element. Embeddables are
* drawn on top of everything on the static canvas, so overlapping ones move
* regardless of z-order.
*
* Source-over compositing is associative, so the two layers composite to
* the same pixels as drawing everything in order on one canvas, and the
* static canvas doesn't re-render while the new element is being sized.
* the same pixels as drawing everything in order on one canvas as long as
* no static element drawn after a moved one overlaps it. Moving is
* therefore transitive: whatever is drawn after a moved element and
* overlaps it moves too. The static canvas then doesn't re-render while the
* new element is being sized.
*
* A frame-clipped new element can only ever paint inside its frame, so
* only elements overlapping the frame can cover it. One that isn't clipped
* (arrows, or frame clipping disabled) can paint anywhere, so everything
* drawn after it moves.
*/
public getNewElementLayers = (opts: {
/** the static canvas' visible elements (with render offsets applied) */
@@ -439,12 +534,28 @@ export class Renderer {
elementsMap: RenderableElementsMap;
newElementCanvasElement: NonDeletedExcalidrawElement | null;
offsets: ElementRenderOffsets;
}) =>
this._getNewElementLayers({
...opts,
appState: StaticCanvasAppState;
}) => {
const { appState, ...rest } = opts;
const newElement = opts.newElementCanvasElement;
const frame = newElement?.frameId
? opts.elementsMap.get(newElement.frameId)
: null;
// mirrors the new element canvas' decision to clip it
const isFrameClipped =
!!newElement &&
!!frame &&
isFrameLikeElement(frame) &&
appState.frameRendering.enabled &&
shouldApplyFrameClip(newElement, frame, appState, opts.elementsMap);
return this._getNewElementLayers({
...rest,
// the new element is mutated in place, memoize on what matters
frameId: opts.newElementCanvasElement?.frameId ?? null,
frameId: newElement?.frameId ?? null,
isFrameClipped,
});
};
private _getNewElementLayers = memoize(
({
@@ -453,20 +564,22 @@ export class Renderer {
newElementCanvasElement: newElement,
offsets,
frameId,
isFrameClipped,
}: {
visibleElements: readonly NonDeletedExcalidrawElement[];
elementsMap: RenderableElementsMap;
newElementCanvasElement: NonDeletedExcalidrawElement | null;
offsets: ElementRenderOffsets;
frameId: string | null;
isFrameClipped: boolean;
}): {
staticElements: readonly NonDeletedExcalidrawElement[];
coveringElements: readonly NonDeletedExcalidrawElement[];
elementsAboveNewElement: readonly NonDeletedExcalidrawElement[];
} => {
const frame = frameId ? elementsMap.get(frameId) : null;
if (!newElement || !frame || !isFrameLikeElement(frame)) {
return { staticElements: visibleElements, coveringElements: [] };
return { staticElements: visibleElements, elementsAboveNewElement: [] };
}
const elements = this.scene.getNonDeletedElements();
@@ -474,7 +587,7 @@ export class Renderer {
(element) => element.id === newElement.id,
);
if (newElementIndex === -1) {
return { staticElements: visibleElements, coveringElements: [] };
return { staticElements: visibleElements, elementsAboveNewElement: [] };
}
const above = new Set<NonDeletedExcalidrawElement>(
elements.slice(newElementIndex + 1),
@@ -483,50 +596,52 @@ export class Renderer {
const frameOffset = offsets.get(frame.id);
const fx1 = frame.x + (frameOffset?.x ?? 0);
const fy1 = frame.y + (frameOffset?.y ?? 0);
const fx2 = fx1 + frame.width;
const fy2 = fy1 + frame.height;
const overlapsFrame = (element: NonDeletedExcalidrawElement) => {
const offset = offsets.get(element.id);
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
// conservative: an extra covering element only costs a redraw
const padding =
getCanvasPadding(element) +
(element.link ? DEFAULT_LINK_SIZE * 2 : 0);
const dx = offset?.x ?? 0;
const dy = offset?.y ?? 0;
return (
x1 + dx - padding < fx2 &&
x2 + dx + padding > fx1 &&
y1 + dy - padding < fy2 &&
y2 + dy + padding > fy1
);
const state: NewElementLayersState = {
elementsMap,
offsets,
above,
newElementRegion: isFrameClipped
? [fx1, fy1, fx1 + frame.width, fy1 + frame.height]
: null,
moved: [],
movedUnion: null,
decided: new Map(),
};
// decide in the static canvas' drawing order: embeddables last
for (const isIframePass of [false, true]) {
for (const element of visibleElements) {
if (
getRenderTarget(element, elementsMap) === element &&
isIframeLikeElement(element) === isIframePass
) {
mustMoveToNewElementCanvas(element, state);
}
}
}
const staticElements: NonDeletedExcalidrawElement[] = [];
const coveringElements: NonDeletedExcalidrawElement[] = [];
const elementsAboveNewElement: NonDeletedExcalidrawElement[] = [];
for (const element of visibleElements) {
// a bound text is drawn with its container, it goes where it goes
const container =
isTextElement(element) && element.containerId
? elementsMap.get(element.containerId)
: null;
const target = container ?? element;
// a bound text whose container isn't visible is decided here, on
// the container
if (
(above.has(target) || isIframeLikeElement(target)) &&
overlapsFrame(target)
mustMoveToNewElementCanvas(
getRenderTarget(element, elementsMap),
state,
)
) {
coveringElements.push(element);
elementsAboveNewElement.push(element);
} else {
staticElements.push(element);
}
}
return coveringElements.length
? { staticElements, coveringElements }
: { staticElements: visibleElements, coveringElements };
return elementsAboveNewElement.length
? { staticElements, elementsAboveNewElement }
: { staticElements: visibleElements, elementsAboveNewElement };
},
);
+1 -1
View File
@@ -141,7 +141,7 @@ export type NewElementSceneRenderConfig = {
rc: RoughCanvas;
newElement: NonDeletedExcalidrawElement | null;
/** elements above a framed new element, drawn on top of it (in order) */
coveringElements?: readonly NonDeletedExcalidrawElement[];
elementsAboveNewElement?: readonly NonDeletedExcalidrawElement[];
elementsMap: RenderableElementsMap;
allElementsMap: NonDeletedSceneElementsMap;
scale: number;
@@ -25,8 +25,8 @@ const lastStaticIds = () =>
renderStaticScene.mock.lastCall![0].visibleElements.map(
(element) => element.id,
);
const lastCoveringIds = () =>
(renderNewElementScene.mock.lastCall![0].coveringElements ?? []).map(
const lastAboveNewElementIds = () =>
(renderNewElementScene.mock.lastCall![0].elementsAboveNewElement ?? []).map(
(element) => element.id,
);
@@ -122,7 +122,7 @@ describe("new element inside a frame", () => {
mouse.move(10, 10);
// the frame (its outline) and the overlapping rectangle
expect(lastCoveringIds()).toEqual(["frame", "covering"]);
expect(lastAboveNewElementIds()).toEqual(["frame", "covering"]);
expect(lastStaticIds()).toEqual(["child", "elsewhere"]);
mouse.up();
@@ -141,7 +141,7 @@ describe("new element inside a frame", () => {
startDrawing("freedraw", 400, 400);
mouse.move(10, 10);
expect(lastCoveringIds()).toEqual([]);
expect(lastAboveNewElementIds()).toEqual([]);
expect(lastStaticIds()).toEqual([
"child",
"frame",
@@ -155,7 +155,7 @@ describe("new element inside a frame", () => {
it("re-splits the layers when the scene changes mid-stroke", () => {
startDrawing("freedraw", 50, 50);
mouse.move(10, 10);
expect(lastCoveringIds()).toEqual(["frame", "covering"]);
expect(lastAboveNewElementIds()).toEqual(["frame", "covering"]);
// e.g. a collaborator drops an element over the frame
act(() => {
@@ -175,9 +175,72 @@ describe("new element inside a frame", () => {
});
mouse.move(10, 10);
expect(lastCoveringIds()).toEqual(["frame", "covering", "remote"]);
expect(lastAboveNewElementIds()).toEqual(["frame", "covering", "remote"]);
expect(lastStaticIds()).toEqual(["child", "elsewhere"]);
mouse.up();
});
it("moves the elements drawn over a moved element along with it", () => {
API.updateScene({
elements: [
...h.elements,
// above "covering", overlapping it outside of the frame only
API.createElement({
type: "rectangle",
id: "over-covering",
x: 220,
y: 220,
width: 50,
height: 50,
}),
],
});
startDrawing("freedraw", 50, 50);
mouse.move(10, 10);
expect(lastAboveNewElementIds()).toEqual([
"frame",
"covering",
"over-covering",
]);
expect(lastStaticIds()).toEqual(["child", "elsewhere"]);
mouse.up();
});
it("moves everything above a new element that isn't frame-clipped", () => {
// arrows aren't clipped to their frame
startDrawing("arrow", 50, 50);
mouse.move(10, 10);
expect(h.state.newElement?.frameId).toBe("frame");
expect(lastAboveNewElementIds()).toEqual([
"frame",
"covering",
"elsewhere",
]);
expect(lastStaticIds()).toEqual(["child"]);
mouse.up();
});
it("moves everything above a new element when frame clipping is off", () => {
API.setAppState({
frameRendering: { ...h.state.frameRendering, clip: false },
});
startDrawing("freedraw", 50, 50);
mouse.move(10, 10);
expect(lastAboveNewElementIds()).toEqual([
"frame",
"covering",
"elsewhere",
]);
expect(lastStaticIds()).toEqual(["child"]);
mouse.up();
});
});