Skip to content

Commit 76c634d

Browse files
fix(studio): resizing a cropped element keeps the same part of it in view (#4743)
* fix(studio): resizing a cropped element keeps the same part of it in view Rebased onto main as one commit (was a0a86cc..080dfec). Merged with the crop release rule from main: a drag that ends where it started saves nothing. * fix(studio): the crop follows each axis GSAP does not tween, while dragging and once saved * fix(studio): the live-tween check reads every timeline, not only the first after a soft reload
1 parent 04b0134 commit 76c634d

23 files changed

Lines changed: 838 additions & 209 deletions

‎packages/studio/src/components/editor/DomEditCropHandles.test.tsx‎

Lines changed: 34 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
55
import type { DomEditSelection } from "./domEditing";
66
import type { OverlayRect } from "./domEditOverlayGeometry";
77
import { DomEditCropHandles } from "./DomEditCropHandles";
8+
import { isElementCropLifted } from "./domEditOverlayCrop";
89

910
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
1011

@@ -55,77 +56,39 @@ function render(
5556
return { root, rerender: draw };
5657
}
5758

58-
// Regression: the deselect restore used a ref recomputed from RENDER state — on
59-
// a direct A→B selection switch, state re-syncs to B before A's effect cleanup
60-
// runs, so A used to get B's crop string (or lose its crop entirely). The
61-
// restore value must be owned by A's own lift effect / crop gesture.
62-
describe("DomEditCropHandles clip lift/restore", () => {
63-
it("lifts on select and restores the inline clip verbatim on unmount", () => {
59+
// The lift never touches the element's own clip-path: select+deselect must leave what the author
60+
// wrote verbatim, and a direct A→B switch must drop A's lift, not B's.
61+
describe("DomEditCropHandles clip lift", () => {
62+
it("lifts on select without rewriting the inline clip, and drops the lift on unmount", () => {
6463
const a = makeEl("a", "inset(16px round 12px)");
6564
const { root } = render(a);
66-
expect(a.style.getPropertyValue("clip-path")).toBe("none");
65+
expect(isElementCropLifted(a)).toBe(true);
66+
expect(a.style.getPropertyValue("clip-path")).toBe("inset(16px round 12px)");
6767
act(() => root.unmount());
68+
expect(isElementCropLifted(a)).toBe(false);
6869
expect(a.style.getPropertyValue("clip-path")).toBe("inset(16px round 12px)");
6970
});
7071

71-
it("restores A's own clip when switching directly to B", () => {
72+
it("drops A's lift when switching directly to B", () => {
7273
const a = makeEl("a", "inset(16px)");
7374
const b = makeEl("b", "inset(40px 8px 4px 2px)");
7475
const { root, rerender } = render(a);
7576
rerender(b);
76-
// A got ITS clip back, not B's (and not removed); B is now lifted.
77+
expect(isElementCropLifted(a)).toBe(false);
78+
expect(isElementCropLifted(b)).toBe(true);
7779
expect(a.style.getPropertyValue("clip-path")).toBe("inset(16px)");
78-
expect(b.style.getPropertyValue("clip-path")).toBe("none");
7980
act(() => root.unmount());
8081
expect(b.style.getPropertyValue("clip-path")).toBe("inset(40px 8px 4px 2px)");
8182
});
8283

8384
it("never lifts an uneditable clip and leaves it untouched across select/deselect", () => {
8485
const a = makeEl("a", "circle(50% at 50% 50%)");
8586
const { root } = render(a);
86-
expect(a.style.getPropertyValue("clip-path")).toBe("circle(50% at 50% 50%)");
87+
expect(isElementCropLifted(a)).toBe(false);
8788
act(() => root.unmount());
8889
expect(a.style.getPropertyValue("clip-path")).toBe("circle(50% at 50% 50%)");
8990
});
9091

91-
it("re-lifts synchronously after the commit path re-applies the cropped value", async () => {
92-
const a = makeEl("a", "inset(10px)");
93-
let resolveCommit: (() => void) | undefined;
94-
const pendingCommit = new Promise<void>((resolve) => {
95-
resolveCommit = resolve;
96-
});
97-
const onStyleCommit = vi.fn((property: string, value: string) => {
98-
a.style.setProperty(property, value);
99-
return pendingCommit;
100-
});
101-
const { root } = render(a, onStyleCommit);
102-
const handle = document.querySelector<HTMLButtonElement>('[aria-label="Crop right"]');
103-
expect(handle).toBeTruthy();
104-
105-
act(() =>
106-
handle!.dispatchEvent(
107-
new PointerEvent("pointerdown", { bubbles: true, pointerId: 1, clientX: 100 }),
108-
),
109-
);
110-
act(() =>
111-
handle!.dispatchEvent(
112-
new PointerEvent("pointermove", { bubbles: true, pointerId: 1, clientX: 80 }),
113-
),
114-
);
115-
act(() =>
116-
handle!.dispatchEvent(
117-
new PointerEvent("pointerup", { bubbles: true, pointerId: 1, clientX: 80 }),
118-
),
119-
);
120-
121-
expect(onStyleCommit).toHaveBeenCalledWith("clip-path", "inset(10px 30px 10px 10px)");
122-
expect(a.style.getPropertyValue("clip-path")).toBe("none");
123-
resolveCommit?.();
124-
await act(async () => pendingCommit);
125-
act(() => root.unmount());
126-
expect(a.style.getPropertyValue("clip-path")).toBe("inset(10px 30px 10px 10px)");
127-
});
128-
12992
it.each([
13093
{ name: "a crop edge", clip: "inset(10px)", handle: "Crop right", dx: -20, dy: 0 },
13194
{
@@ -189,33 +152,38 @@ describe("DomEditCropHandles clip lift/restore", () => {
189152
expect(a.style.getPropertyValue("clip-path")).toBe("inset(0px 20px 0px 0px)");
190153
});
191154

192-
it("re-lifts when the crop commit rejects", async () => {
155+
it("commits the dragged crop and stays lifted when the save fails", async () => {
193156
const a = makeEl("a", "inset(10px)");
194157
const onStyleCommit = vi.fn((property: string, value: string) => {
195158
a.style.setProperty(property, value);
196159
return Promise.reject(new Error("persist failed"));
197160
});
198161
const { root } = render(a, onStyleCommit);
199-
const handle = document.querySelector<HTMLButtonElement>('[aria-label="Crop right"]');
200-
201-
act(() =>
202-
handle!.dispatchEvent(
203-
new PointerEvent("pointerdown", { bubbles: true, pointerId: 2, clientX: 100 }),
204-
),
205-
);
206-
act(() =>
207-
handle!.dispatchEvent(
208-
new PointerEvent("pointermove", { bubbles: true, pointerId: 2, clientX: 80 }),
209-
),
210-
);
211-
await act(async () => {
212-
handle!.dispatchEvent(
213-
new PointerEvent("pointerup", { bubbles: true, pointerId: 2, clientX: 80 }),
162+
const handle = document.querySelector<HTMLButtonElement>('[aria-label="Crop right"]')!;
163+
const press = (type: string, clientX: number) =>
164+
act(() =>
165+
handle.dispatchEvent(new PointerEvent(type, { bubbles: true, pointerId: 1, clientX })),
214166
);
167+
press("pointerdown", 100);
168+
press("pointermove", 80);
169+
await act(async () => {
170+
press("pointerup", 80);
215171
await Promise.resolve();
216172
});
217173

218-
expect(a.style.getPropertyValue("clip-path")).toBe("none");
174+
expect(onStyleCommit).toHaveBeenCalledWith("clip-path", "inset(10px 30px 10px 10px)");
175+
expect(isElementCropLifted(a)).toBe(true);
176+
act(() => root.unmount());
177+
});
178+
179+
it("draws the crop the element has now, after an undo rewrites it", () => {
180+
const a = makeEl("a", "inset(0px 20px 0px 0px)");
181+
const { root, rerender } = render(a);
182+
const outline = () => document.querySelector<HTMLElement>(".border-dashed")!.style.width;
183+
expect(outline()).toBe("180px");
184+
a.style.setProperty("clip-path", "inset(0px 50px 0px 0px)");
185+
rerender(a);
186+
expect(outline()).toBe("150px");
219187
act(() => root.unmount());
220188
});
221189
});

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

Lines changed: 30 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@ import { type OverlayRect, RESIZE_HANDLE_HIT_PX } from "./domEditOverlayGeometry
44
import {
55
type CropEdge,
66
cropRectFromInsets,
7+
dropElementCropLift,
8+
hasCropInsets,
9+
liftElementCrop,
710
readElementCropFrame,
811
readElementCropInsets,
912
resolveCropInsetFromEdgeDrag,
1013
resolveCropInsetFromMoveDrag,
1114
rotateDeltaIntoFrame,
1215
} from "./domEditOverlayCrop";
1316
import { buildInsetClipPathSides, type ClipPathInsetSides } from "./clipPathHelpers";
17+
import { readCropFollowingResize } from "./cropResize";
1418

1519
interface CropGestureState {
1620
edge: CropEdge | "move";
@@ -19,6 +23,7 @@ interface CropGestureState {
1923
startY: number;
2024
startInsets: ClipPathInsetSides;
2125
insets: ClipPathInsetSides;
26+
radius: number;
2227
/** Element frame captured at gesture start: pointer deltas rotate into it. */
2328
angleDeg: number;
2429
scaleX: number;
@@ -83,6 +88,7 @@ function repositionHandleSize(rect: Rect): number {
8388
}
8489

8590
const EDGES: CropEdge[] = ["top", "right", "bottom", "left"];
91+
const NO_CROP = { top: 0, right: 0, bottom: 0, left: 0, radius: 0 };
8692

8793
/**
8894
* Always-on crop, integrated with the selection (no crop "mode"): while a
@@ -92,7 +98,7 @@ const EDGES: CropEdge[] = ["top", "right", "bottom", "left"];
9298
* grid guides framing); release commits `clip-path: inset(...)` through the
9399
* normal style-commit path (one undo step per drag). When cropped, a center
94100
* handle pans the crop window. Corners stay free for the selection's own resize
95-
* handle. Leaving the selection restores the committed crop. The clip-path model
101+
* handle. Leaving the selection drops the lift. The element's clip-path
96102
* is the source of truth — nothing here mutates layout.
97103
*/
98104
export function DomEditCropHandles({
@@ -109,54 +115,29 @@ export function DomEditCropHandles({
109115
// clip with an inset (or deletes it).
110116
const cropStateFor = (element: HTMLElement) => {
111117
const parsed = readElementCropInsets(element);
112-
const { radius, ...insets } = parsed ?? { top: 0, right: 0, bottom: 0, left: 0, radius: 0 };
113-
return { element, croppable: parsed !== null, insets, radius };
118+
const { top, right, bottom, left } = parsed ?? NO_CROP;
119+
return { element, croppable: parsed !== null, insets: { top, right, bottom, left } };
114120
};
115121
const [state, setState] = useState(() => cropStateFor(selection.element));
116122

117123
// Re-sync when the selection targets a different element (reselect, or an
118-
// undo/redo that re-keys the node): read its committed crop before the lift
119-
// effect runs. Read inside the guard so a drag's per-frame setState doesn't
120-
// re-run getComputedStyle every frame.
124+
// undo/redo that re-keys the node).
121125
if (state.element !== selection.element) {
122126
setState(cropStateFor(selection.element));
123127
}
124128

125-
const hasCrop =
126-
state.insets.top > 0 ||
127-
state.insets.right > 0 ||
128-
state.insets.bottom > 0 ||
129-
state.insets.left > 0;
129+
// The element's clip-path is the crop; state only holds a crop drag's draft.
130+
const committed = readCropFollowingResize(selection.element) ?? NO_CROP;
131+
const insets = dragging ? state.insets : committed;
132+
const hasCrop = hasCropInsets(insets);
130133

131134
// Lift the clip while the element is selected so the full content shows and the
132-
// cropped-away area can be dimmed; restore on deselect. Keyed on the element so
133-
// switching selections restores the previous one. Runs after render, so the
134-
// state re-sync above still reads the element's real committed clip. Restore
135-
// prefers the pre-lift inline value VERBATIM — the rebuilt inset only replaces
136-
// it after a crop gesture actually commits, so a mere select+deselect can
137-
// never reformat (or drop) what the author wrote. Both refs are written only
138-
// by THIS element's lift effect and crop gestures — never derived from render
139-
// state, which by cleanup time already describes the NEXT selection (a direct
140-
// A→B switch re-syncs state to B before A's cleanup runs).
141-
const liftedRef = useRef(false);
142-
const preLiftInlineClipRef = useRef("");
143-
// null = no crop gesture committed this selection; "" = committed a crop
144-
// removal; anything else = the exact committed clip-path value.
145-
const committedClipRef = useRef<string | null>(null);
135+
// cropped-away area can be dimmed. Keyed on the element so a direct A→B switch drops A's lift.
146136
useEffect(() => {
147137
const el = selection.element;
148138
if (readElementCropInsets(el) === null) return;
149-
preLiftInlineClipRef.current = el.style.getPropertyValue("clip-path");
150-
committedClipRef.current = null;
151-
el.style.setProperty("clip-path", "none");
152-
liftedRef.current = true;
153-
return () => {
154-
liftedRef.current = false;
155-
const committed = committedClipRef.current;
156-
const restore = committed !== null ? committed || null : preLiftInlineClipRef.current || null;
157-
if (restore) el.style.setProperty("clip-path", restore);
158-
else el.style.removeProperty("clip-path");
159-
};
139+
liftElementCrop(el);
140+
return () => dropElementCropLift(el);
160141
}, [selection.element]);
161142

162143
// The crop applies in the element's LOCAL frame (clip-path precedes the
@@ -169,7 +150,7 @@ export function DomEditCropHandles({
169150
// Crop rect in FRAME-LOCAL coordinates (origin = frame top-left).
170151
const cropRect = cropRectFromInsets(
171152
{ left: 0, top: 0, width: frame.width, height: frame.height },
172-
state.insets,
153+
insets,
173154
frame.scaleX,
174155
frame.scaleY,
175156
);
@@ -180,19 +161,23 @@ export function DomEditCropHandles({
180161
event.preventDefault();
181162
event.stopPropagation();
182163
event.currentTarget.setPointerCapture(event.pointerId);
164+
// Read at press: a resize may have rescaled the crop since the last render.
165+
const pressed = readCropFollowingResize(selection.element) ?? NO_CROP;
183166
gestureRef.current = {
184167
edge,
185168
pointerId: event.pointerId,
186169
startX: event.clientX,
187170
startY: event.clientY,
188-
startInsets: state.insets,
189-
insets: state.insets,
171+
startInsets: pressed,
172+
insets: pressed,
173+
radius: pressed.radius,
190174
angleDeg: frame.angleDeg,
191175
scaleX: frame.scaleX,
192176
scaleY: frame.scaleY,
193177
};
194178
// Clip is already lifted by the selection effect; just flag the drag so the
195179
// rule-of-thirds grid shows.
180+
setState((prev) => ({ ...prev, insets: pressed }));
196181
setDragging(true);
197182
};
198183

@@ -234,29 +219,12 @@ export function DomEditCropHandles({
234219
const finishCropGesture = (event: ReactPointerEvent<HTMLElement>) => {
235220
const gesture = endCropGesture(event);
236221
if (!gesture) return;
237-
// Commit to the file. The commit path re-applies the value to the live
238-
// element synchronously, so re-lift in the same turn to keep showing the full
239-
// content + dim while selected. Re-lift again on rejection so a failed commit
240-
// still restores crop-mode presentation without an unhandled rejection.
241-
const el = selection.element;
242-
const reLift = () => {
243-
if (liftedRef.current) el.style.setProperty("clip-path", "none");
244-
};
245-
const { insets } = gesture;
246-
const committedValue = buildInsetClipPathSides(insets, state.radius);
247-
if (committedValue === buildInsetClipPathSides(gesture.startInsets, state.radius)) return;
248-
const cropped = insets.top > 0 || insets.right > 0 || insets.bottom > 0 || insets.left > 0;
249-
const commit = onStyleCommit?.("clip-path", committedValue);
250-
// handleDomStyleCommit applies the persisted value to the live element
251-
// synchronously before its first await. Restore the crop-mode lift in this
252-
// same turn so the browser never paints that intermediate cropped state.
253-
reLift();
254-
void Promise.resolve(commit).then(() => {
255-
// Only a landed commit makes the rebuilt inset the restore value; a
256-
// failed one keeps restoring the pre-lift clip. Store the value itself —
257-
// by deselect time, render state describes the next selection.
258-
committedClipRef.current = cropped ? committedValue : "";
259-
}, reLift);
222+
// The commit writes the element's clip-path (and puts it back if the save fails);
223+
// the lift keeps it hidden while selected. A drag that ends where it started saves nothing.
224+
const value = buildInsetClipPathSides(gesture.insets, gesture.radius);
225+
if (value === buildInsetClipPathSides(gesture.startInsets, gesture.radius)) return;
226+
const commit = onStyleCommit?.("clip-path", value);
227+
void Promise.resolve(commit).catch(() => undefined);
260228
};
261229

262230
const cancelCropGesture = (event: ReactPointerEvent<HTMLElement>) => {

0 commit comments

Comments
 (0)