Skip to content

Commit 6a9cc51

Browse files
committed
fix(studio): off-canvas indicators track live layout instead of going stale
The dashed indicators for elements outside the canvas stayed pinned at an element's old position after a move or a seek: they were recomputed by an effect keyed on compRect/activeCompositionPath, neither of which changes on an in-place soft-reload edit or a playhead seek. They now recompute via a MutationObserver on the preview document (coalesced to one recompute per frame), so they follow the element live. Crop-hugging is preserved. Adds a regression test that mutates an element in place and asserts the indicator moves.
1 parent 037266e commit 6a9cc51

4 files changed

Lines changed: 360 additions & 47 deletions

File tree

‎packages/studio/src/components/editor/DomEditOverlay.tsx‎

Lines changed: 33 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@ import { type DomEditSelection } from "./domEditing";
33
import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
44
import { useMarqueeGestures } from "./marqueeCommit";
55
import { MarqueeOverlay } from "./MarqueeOverlay";
6-
import { groupAwareOverlayRect, resolveDomEditGroupOverlayRect } from "./domEditOverlayGeometry";
7-
import { collectDomEditLayerItems } from "./domEditingLayers";
8-
import { isElementComputedVisible } from "./domEditingElement";
6+
import { resolveDomEditGroupOverlayRect } from "./domEditOverlayGeometry";
97
import {
108
type BlockedMoveState,
119
type DomEditGroupPathOffsetCommit,
@@ -26,6 +24,8 @@ import { hugRectForElement } from "./domEditOverlayCrop";
2624
import { useCropOverlay } from "../../hooks/useCropMode";
2725
import { readDomEditSelectionShapeStyles, resolveBoxChromeClass } from "./domEditOverlayShape";
2826
import { useDomEditCompositionRect } from "./useDomEditCompositionRect";
27+
import { useMountEffect } from "../../hooks/useMountEffect";
28+
import { startOffCanvasIndicatorRefresh } from "./offCanvasIndicatorRefresh";
2929

3030
// Re-exports for external consumers — preserving existing import paths.
3131
export {
@@ -173,6 +173,8 @@ export const DomEditOverlay = memo(function DomEditOverlay({
173173
});
174174

175175
const compRect = useDomEditCompositionRect({ iframeRef, overlayRef });
176+
const compRectRef = useRef(compRect);
177+
compRectRef.current = compRect;
176178

177179
const { hasCropInsets, cropOutlineInsetPx } = useCropOverlay({
178180
selection,
@@ -189,51 +191,35 @@ export const DomEditOverlay = memo(function DomEditOverlay({
189191
// outside the composition bounds so users can find them.
190192
const offCanvasElementsRef = useRef<Map<string, HTMLElement>>(new Map());
191193
const [offCanvasRects, setOffCanvasRects] = useState<OffCanvasRect[]>([]);
192-
// fallow-ignore-next-line complexity
194+
const offCanvasDirtyRef = useRef(true);
195+
const offCanvasSigRef = useRef("");
196+
const offCanvasObserverRef = useRef<MutationObserver | null>(null);
197+
const offCanvasObservedDocRef = useRef<Document | null>(null);
198+
199+
// Positions depend on live iframe layout, not selection — the selected-element
200+
// suppression is a render-time filter, so selection/groupSelections stay out
201+
// of the geometry walk.
202+
useMountEffect(() =>
203+
startOffCanvasIndicatorRefresh({
204+
iframeRef,
205+
overlayRef,
206+
compRectRef,
207+
activeCompositionPathRef,
208+
dirtyRef: offCanvasDirtyRef,
209+
sigRef: offCanvasSigRef,
210+
observerRef: offCanvasObserverRef,
211+
observedDocRef: offCanvasObservedDocRef,
212+
elementsRef: offCanvasElementsRef,
213+
setRects: setOffCanvasRects,
214+
}),
215+
);
216+
217+
// Switching compositions may not swap the iframe document (so the observer's
218+
// doc-swap detection wouldn't fire) yet changes which elements are off-canvas.
219+
// Force a recompute explicitly on comp change.
193220
useEffect(() => {
194-
const iframe = iframeRef.current;
195-
const overlay = overlayRef.current;
196-
if (!iframe || !overlay || compRect.width <= 0) {
197-
setOffCanvasRects([]);
198-
return;
199-
}
200-
const doc = iframe.contentDocument;
201-
if (!doc) return;
202-
const root = doc.querySelector<HTMLElement>("[data-composition-id]") ?? doc.body;
203-
const acp = activeCompositionPath ?? "index.html";
204-
const items = collectDomEditLayerItems(root, {
205-
activeCompositionPath: acp,
206-
isMasterView: !acp || acp === "index.html",
207-
});
208-
const rects: typeof offCanvasRects = [];
209-
const elMap = new Map<string, HTMLElement>();
210-
for (const item of items) {
211-
if (!isElementComputedVisible(item.element)) continue;
212-
// Groups use their members' union (where they actually render), so a group
213-
// whose members sit inside the canvas isn't flagged off-canvas by a stale
214-
// wrapper box. Crop-hug the result so an inset crop that keeps the visible
215-
// part on-canvas doesn't flag the element either.
216-
const base = groupAwareOverlayRect(overlay, iframe, item.element);
217-
const r = base ? { ...base, ...hugRectForElement(base, item.element) } : null;
218-
if (!r) continue;
219-
// Any edge crossing the composition border → gray-zone indicator (the
220-
// in-canvas portion is clipped away below, so only the sliver shows).
221-
const extendsOutsideComp =
222-
r.left < compRect.left ||
223-
r.left + r.width > compRect.left + compRect.width ||
224-
r.top < compRect.top ||
225-
r.top + r.height > compRect.top + compRect.height;
226-
if (extendsOutsideComp) {
227-
rects.push({ key: item.key, left: r.left, top: r.top, width: r.width, height: r.height });
228-
elMap.set(item.key, item.element);
229-
}
230-
}
231-
offCanvasElementsRef.current = elMap;
232-
setOffCanvasRects(rects);
233-
// Positions depend on layout, not selection — the selected-element
234-
// suppression is a render-time filter, so selection/groupSelections stay
235-
// out of the deps to avoid re-walking geometry on each selection change.
236-
}, [iframeRef, compRect, activeCompositionPath]);
221+
offCanvasDirtyRef.current = true;
222+
}, [activeCompositionPath]);
237223

238224
const gestures = createDomEditOverlayGestureHandlers({
239225
overlayRef,
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import type React from "react";
2+
import type { OffCanvasRect } from "./OffCanvasIndicators";
3+
import { hugRectForElement } from "./domEditOverlayCrop";
4+
import { groupAwareOverlayRect } from "./domEditOverlayGeometry";
5+
import { isElementComputedVisible } from "./domEditingElement";
6+
import { collectDomEditLayerItems } from "./domEditingLayers";
7+
8+
function rounded(value: number): number {
9+
return Math.round(value * 100) / 100;
10+
}
11+
12+
function offCanvasSignature(rects: OffCanvasRect[]): string {
13+
return rects
14+
.map(
15+
(rect) =>
16+
`${rect.key}:${rounded(rect.left)},${rounded(rect.top)},${rounded(rect.width)},${rounded(rect.height)}`,
17+
)
18+
.join("|");
19+
}
20+
21+
// fallow-ignore-next-line complexity
22+
export function recomputeOffCanvasIndicators(
23+
iframe: HTMLIFrameElement,
24+
overlay: HTMLDivElement,
25+
doc: Document | null | undefined,
26+
comp: { left: number; top: number; width: number; height: number },
27+
activeCompositionPath: string | null,
28+
sigRef: React.MutableRefObject<string>,
29+
elementsRef: React.MutableRefObject<Map<string, HTMLElement>>,
30+
setRects: (rects: OffCanvasRect[]) => void,
31+
): void {
32+
if (comp.width <= 0 || !doc) {
33+
sigRef.current = "";
34+
elementsRef.current = new Map();
35+
setRects([]);
36+
return;
37+
}
38+
39+
const root = doc.querySelector<HTMLElement>("[data-composition-id]") ?? doc.body;
40+
const acp = activeCompositionPath ?? "index.html";
41+
const items = collectDomEditLayerItems(root, {
42+
activeCompositionPath: acp,
43+
isMasterView: !acp || acp === "index.html",
44+
});
45+
const rects: OffCanvasRect[] = [];
46+
const elMap = new Map<string, HTMLElement>();
47+
for (const item of items) {
48+
if (!isElementComputedVisible(item.element)) continue;
49+
// Groups use their members' union (where they actually render), so a group
50+
// whose members sit inside the canvas isn't flagged off-canvas by a stale
51+
// wrapper box. Crop-hug the result so an inset crop that keeps the visible
52+
// part on-canvas doesn't flag the element either.
53+
const base = groupAwareOverlayRect(overlay, iframe, item.element);
54+
const r = base ? { ...base, ...hugRectForElement(base, item.element) } : null;
55+
if (!r) continue;
56+
// Any edge crossing the composition border → gray-zone indicator (the
57+
// in-canvas portion is clipped away below, so only the sliver shows).
58+
const extendsOutsideComp =
59+
r.left < comp.left ||
60+
r.left + r.width > comp.left + comp.width ||
61+
r.top < comp.top ||
62+
r.top + r.height > comp.top + comp.height;
63+
if (extendsOutsideComp) {
64+
rects.push({ key: item.key, left: r.left, top: r.top, width: r.width, height: r.height });
65+
elMap.set(item.key, item.element);
66+
}
67+
}
68+
69+
const nextSig = offCanvasSignature(rects);
70+
if (nextSig === sigRef.current) return;
71+
sigRef.current = nextSig;
72+
elementsRef.current = elMap;
73+
setRects(rects);
74+
}
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
// @vitest-environment happy-dom
2+
3+
import React, { act } from "react";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { describe, expect, it } from "vitest";
6+
import { DomEditOverlay } from "./DomEditOverlay";
7+
8+
Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
9+
10+
const INDICATOR = '[aria-label="Select off-canvas element index.html:headline:0"]';
11+
12+
function domRect(left: number, top: number, width: number, height: number): DOMRect {
13+
return {
14+
left,
15+
top,
16+
right: left + width,
17+
bottom: top + height,
18+
width,
19+
height,
20+
x: left,
21+
y: top,
22+
toJSON: () => ({}),
23+
};
24+
}
25+
26+
async function flushAnimationFrames(): Promise<void> {
27+
await new Promise<void>((resolve) => {
28+
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
29+
});
30+
}
31+
32+
interface OverlayHarness {
33+
host: HTMLElement;
34+
movedElement: HTMLElement;
35+
cleanup: () => void;
36+
}
37+
38+
// Mount DomEditOverlay over an iframe whose #headline sits at `initialLeft`, with a
39+
// getBoundingClientRect stub that reads the element's live inline geometry (so a
40+
// style mutation moves it) and reports the composition/overlay as 800x450 at origin.
41+
function mountOverlayWithHeadline(initialLeft: number): OverlayHarness {
42+
const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
43+
const host = document.createElement("div");
44+
document.body.append(host);
45+
const root: Root = createRoot(host);
46+
const iframe = document.createElement("iframe");
47+
document.body.append(iframe);
48+
const doc = iframe.contentDocument;
49+
if (!doc) throw new Error("Expected iframe content document");
50+
51+
doc.body.innerHTML = `
52+
<div data-composition-id="root" data-width="800" data-height="450">
53+
<div id="headline" style="position:absolute; left:${initialLeft}px; top:40px; width:100px; height:40px;">Headline</div>
54+
</div>
55+
`;
56+
const movedElement = doc.getElementById("headline");
57+
if (!movedElement) throw new Error("Expected test element");
58+
59+
Element.prototype.getBoundingClientRect = function (): DOMRect {
60+
if (this === movedElement) {
61+
return domRect(
62+
Number.parseFloat(movedElement.style.left),
63+
Number.parseFloat(movedElement.style.top),
64+
Number.parseFloat(movedElement.style.width),
65+
Number.parseFloat(movedElement.style.height),
66+
);
67+
}
68+
return domRect(0, 0, 800, 450);
69+
};
70+
71+
act(() => {
72+
root.render(
73+
<DomEditOverlay
74+
iframeRef={{ current: iframe }}
75+
activeCompositionPath={null}
76+
selection={null}
77+
hoverSelection={null}
78+
groupSelections={[]}
79+
onCanvasMouseDown={() => {}}
80+
onCanvasPointerMove={() => Promise.resolve(null)}
81+
onCanvasPointerLeave={() => {}}
82+
onSelectionChange={() => {}}
83+
onBlockedMove={() => {}}
84+
onPathOffsetCommit={() => {}}
85+
onGroupPathOffsetCommit={() => {}}
86+
onBoxSizeCommit={() => {}}
87+
onRotationCommit={() => {}}
88+
/>,
89+
);
90+
});
91+
92+
return {
93+
host,
94+
movedElement,
95+
cleanup: () => {
96+
act(() => root.unmount());
97+
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
98+
iframe.remove();
99+
host.remove();
100+
},
101+
};
102+
}
103+
104+
describe("off-canvas indicator refresh", () => {
105+
it("removes the indicator when an off-canvas element moves in-canvas (off->on)", async () => {
106+
const h = mountOverlayWithHeadline(760);
107+
try {
108+
await act(async () => {
109+
await flushAnimationFrames();
110+
});
111+
expect(h.host.querySelector(INDICATOR)).toBeTruthy();
112+
113+
act(() => {
114+
h.movedElement.style.left = "120px";
115+
});
116+
await act(async () => {
117+
await Promise.resolve();
118+
await flushAnimationFrames();
119+
});
120+
121+
expect(h.host.querySelector(INDICATOR)).toBeNull();
122+
} finally {
123+
h.cleanup();
124+
}
125+
});
126+
127+
it("tracks the indicator to the new position when it stays off-canvas (off->off)", async () => {
128+
const h = mountOverlayWithHeadline(760);
129+
try {
130+
await act(async () => {
131+
await flushAnimationFrames();
132+
});
133+
const before = h.host.querySelector(INDICATOR);
134+
expect(before).toBeTruthy();
135+
const leftBefore = (before!.parentElement as HTMLElement).style.left;
136+
137+
// Move further off-canvas (still outside the 800px-wide composition).
138+
act(() => {
139+
h.movedElement.style.left = "1200px";
140+
});
141+
await act(async () => {
142+
await Promise.resolve();
143+
await flushAnimationFrames();
144+
});
145+
146+
const after = h.host.querySelector(INDICATOR);
147+
expect(after).toBeTruthy();
148+
const leftAfter = (after!.parentElement as HTMLElement).style.left;
149+
expect(leftAfter).not.toEqual(leftBefore);
150+
} finally {
151+
h.cleanup();
152+
}
153+
});
154+
});

0 commit comments

Comments
 (0)