Skip to content

Commit a0a86cc

Browse files
committed
fix(studio): resizing a cropped element keeps the same part of it in view
1 parent d2851aa commit a0a86cc

14 files changed

Lines changed: 317 additions & 61 deletions

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

Lines changed: 24 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,21 @@ import type { OverlayRect } from "./domEditOverlayGeometry";
44
import {
55
type CropEdge,
66
cropRectFromInsets,
7+
hasCropInsets,
78
readElementCropFrame,
89
readElementCropInsets,
910
resolveCropInsetFromEdgeDrag,
1011
resolveCropInsetFromMoveDrag,
1112
rotateDeltaIntoFrame,
1213
} from "./domEditOverlayCrop";
1314
import { buildInsetClipPathSides, type ClipPathInsetSides } from "./clipPathHelpers";
15+
import {
16+
dropElementCropLift,
17+
isElementCropLifted,
18+
liftElementCrop,
19+
readLiftedCrop,
20+
setLiftedCrop,
21+
} from "./liftedCrop";
1422

1523
interface CropGestureState {
1624
edge: CropEdge | "move";
@@ -116,41 +124,18 @@ export function DomEditCropHandles({
116124
setState(cropStateFor(selection.element));
117125
}
118126

119-
const hasCrop =
120-
state.insets.top > 0 ||
121-
state.insets.right > 0 ||
122-
state.insets.bottom > 0 ||
123-
state.insets.left > 0;
127+
// Once lifted, the committed crop is the lift's (a resize rescales it there); a crop drag draws its draft.
128+
const insets = (!dragging && readLiftedCrop(selection.element)) || state.insets;
129+
const hasCrop = hasCropInsets(insets);
124130

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

156141
// The crop applies in the element's LOCAL frame (clip-path precedes the
@@ -163,7 +148,7 @@ export function DomEditCropHandles({
163148
// Crop rect in FRAME-LOCAL coordinates (origin = frame top-left).
164149
const cropRect = cropRectFromInsets(
165150
{ left: 0, top: 0, width: frame.width, height: frame.height },
166-
state.insets,
151+
insets,
167152
frame.scaleX,
168153
frame.scaleY,
169154
);
@@ -178,14 +163,15 @@ export function DomEditCropHandles({
178163
pointerId: event.pointerId,
179164
startX: event.clientX,
180165
startY: event.clientY,
181-
startInsets: state.insets,
166+
startInsets: insets,
182167
didMove: false,
183168
angleDeg: frame.angleDeg,
184169
scaleX: frame.scaleX,
185170
scaleY: frame.scaleY,
186171
};
187172
// Clip is already lifted by the selection effect; just flag the drag so the
188173
// rule-of-thirds grid shows.
174+
setState((prev) => ({ ...prev, insets }));
189175
setDragging(true);
190176
};
191177

@@ -228,25 +214,19 @@ export function DomEditCropHandles({
228214
// still restores crop-mode presentation without an unhandled rejection.
229215
const el = selection.element;
230216
const reLift = () => {
231-
if (liftedRef.current) el.style.setProperty("clip-path", "none");
217+
if (isElementCropLifted(el)) el.style.setProperty("clip-path", "none");
232218
};
233219
const committedValue = buildInsetClipPathSides(state.insets, state.radius);
234-
const cropped =
235-
state.insets.top > 0 ||
236-
state.insets.right > 0 ||
237-
state.insets.bottom > 0 ||
238-
state.insets.left > 0;
239220
const commit = onStyleCommit?.("clip-path", committedValue);
240221
// handleDomStyleCommit applies the persisted value to the live element
241222
// synchronously before its first await. Restore the crop-mode lift in this
242223
// same turn so the browser never paints that intermediate cropped state.
243224
reLift();
244-
void Promise.resolve(commit).then(() => {
245-
// Only a landed commit makes the rebuilt inset the restore value; a
246-
// failed one keeps restoring the pre-lift clip. Store the value itself —
247-
// by deselect time, render state describes the next selection.
248-
committedClipRef.current = cropped ? committedValue : "";
249-
}, reLift);
225+
const revert = setLiftedCrop(el, hasCropInsets(state.insets) ? committedValue : "");
226+
void Promise.resolve(commit).then(undefined, () => {
227+
revert();
228+
reLift();
229+
});
250230
};
251231

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

‎packages/studio/src/components/editor/domEditOverlayCrop.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { composeElementTransform, type PlanarTransformOps } from "./domEditOverlayTransform";
2-
import { parseInsetClipPathSides, type ClipPathInsetSides } from "./clipPathHelpers";
2+
import {
3+
parseInsetClipPathSides,
4+
type ClipPathInsetSides,
5+
type ParsedInsetClipPathSides,
6+
} from "./clipPathHelpers";
37

48
export type CropEdge = "top" | "right" | "bottom" | "left";
59

@@ -29,23 +33,29 @@ export function cropRectFromInsets(
2933
};
3034
}
3135

32-
/**
33-
* Current inset crop of an element (inline first, computed fallback).
34-
* Zeros = no clip (croppable, nothing cropped yet). `null` = the element
35-
* carries a clip-path this tool cannot represent (circle/polygon/non-px
36-
* inset) — croppers must not lift, edit, or restore it, or the clip gets
37-
* silently replaced or destroyed on deselect.
38-
*/
39-
export function readElementCropInsets(
40-
element: HTMLElement,
41-
): (ClipPathInsetSides & { radius: number }) | null {
36+
/** The element's clip-path, inline first, computed fallback. */
37+
export function readElementClipPath(element: HTMLElement): string {
4238
const inline = element.style.getPropertyValue("clip-path").trim();
43-
const value =
44-
inline || element.ownerDocument.defaultView?.getComputedStyle(element).clipPath.trim() || "";
39+
return (
40+
inline || element.ownerDocument.defaultView?.getComputedStyle(element).clipPath.trim() || ""
41+
);
42+
}
43+
44+
/** Zeros = no clip yet. `null` = a clip this tool cannot represent (circle/polygon/non-px inset):
45+
* croppers must not lift, edit, or restore it, or deselect silently replaces or destroys it. */
46+
export function parseCropClipPath(value: string): ParsedInsetClipPathSides | null {
4547
if (!value || value === "none") return { top: 0, right: 0, bottom: 0, left: 0, radius: 0 };
4648
return parseInsetClipPathSides(value);
4749
}
4850

51+
export function readElementCropInsets(element: HTMLElement): ParsedInsetClipPathSides | null {
52+
return parseCropClipPath(readElementClipPath(element));
53+
}
54+
55+
export function hasCropInsets(insets: ClipPathInsetSides): boolean {
56+
return insets.top > 0 || insets.right > 0 || insets.bottom > 0 || insets.left > 0;
57+
}
58+
4959
export interface CropInsetDragInput {
5060
edge: CropEdge;
5161
startInsets: ClipPathInsetSides;

‎packages/studio/src/components/editor/domEditOverlayStartGesture.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
readStudioBoxSize,
1919
readStudioRotation,
2020
} from "./manualEdits";
21+
import { beginLiftedCropResize } from "./liftedCrop";
2122
import {
2223
type OverlayRect,
2324
elementCornerOverlayPoints,
@@ -290,6 +291,7 @@ export function startGesture(
290291
resizeFixedCenterStart,
291292
};
292293
if (kind === "resize") {
294+
if (manualEditDragToken) beginLiftedCropResize(sel.element, manualEditDragToken);
293295
resetResizeMoveLog();
294296
logResize("start", {
295297
handle: options?.resizeHandle ?? "se",
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// @vitest-environment happy-dom
2+
import { describe, expect, it } from "vitest";
3+
import {
4+
beginLiftedCropResize,
5+
liftElementCrop,
6+
prepareLiftedCropResize,
7+
readLiftedCrop,
8+
} from "./liftedCrop";
9+
import { beginStudioManualEditGesture, endStudioManualEditGesture } from "./manualEdits";
10+
import { withInlineLayoutBox } from "../../hooks/domSelectionTestHarness";
11+
12+
function sizedElement(width: number, height: number, clip: string): HTMLElement {
13+
const el = withInlineLayoutBox(document.createElement("div"));
14+
el.style.cssText = `width: ${width}px; height: ${height}px; clip-path: ${clip}`;
15+
return el;
16+
}
17+
18+
describe("lifted crop during a resize", () => {
19+
it("follows the box only while the resize gesture is live", () => {
20+
const el = sizedElement(300, 200, "inset(10px 60px 20px 30px round 8px)");
21+
liftElementCrop(el);
22+
const token = beginStudioManualEditGesture(el);
23+
beginLiftedCropResize(el, token);
24+
el.style.width = "600px";
25+
el.style.height = "400px";
26+
expect(readLiftedCrop(el)).toEqual({ top: 20, right: 120, bottom: 40, left: 60, radius: 8 });
27+
endStudioManualEditGesture(el, token);
28+
// An animated width is not a resize: the crop keeps its pixels.
29+
expect(readLiftedCrop(el)).toEqual({ top: 10, right: 60, bottom: 20, left: 30, radius: 8 });
30+
});
31+
32+
it("leaves the crop alone when the box kept its size (a resize saved as scale)", () => {
33+
const el = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
34+
liftElementCrop(el);
35+
const token = beginStudioManualEditGesture(el);
36+
beginLiftedCropResize(el, token);
37+
const stage = prepareLiftedCropResize(el);
38+
el.style.width = "450px";
39+
expect(readLiftedCrop(el)?.right).toBe(90);
40+
// The scale route drops the width draft before the stage runs.
41+
el.style.width = "300px";
42+
expect(stage()).toBeNull();
43+
});
44+
});
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import type { PatchOperation } from "../../utils/sourcePatcher";
2+
import { buildInsetClipPathSides, type ParsedInsetClipPathSides } from "./clipPathHelpers";
3+
import { hasCropInsets, parseCropClipPath, readElementClipPath } from "./domEditOverlayCrop";
4+
import { isStudioManualEditGestureCurrent } from "./manualEdits";
5+
6+
interface Box {
7+
width: number;
8+
height: number;
9+
}
10+
11+
interface LiftedCrop {
12+
clip: string;
13+
/** Written back inline on deselect: the authored value verbatim until a commit replaces it. */
14+
restore: string;
15+
resizeFrom?: Box & { token: string };
16+
}
17+
18+
// A selected croppable element shows uncropped so the crop UI can dim what is cut away. Its crop
19+
// waits here, where a resize can rescale it, until deselect puts it back.
20+
const liftedCrops = new WeakMap<HTMLElement, LiftedCrop>();
21+
22+
const boxOf = (element: HTMLElement): Box => ({
23+
width: element.offsetWidth,
24+
height: element.offsetHeight,
25+
});
26+
27+
export function liftElementCrop(element: HTMLElement): void {
28+
liftedCrops.set(element, {
29+
clip: readElementClipPath(element),
30+
restore: element.style.getPropertyValue("clip-path"),
31+
});
32+
element.style.setProperty("clip-path", "none");
33+
}
34+
35+
export function dropElementCropLift(element: HTMLElement): void {
36+
const lifted = liftedCrops.get(element);
37+
if (!lifted) return;
38+
liftedCrops.delete(element);
39+
if (lifted.restore) element.style.setProperty("clip-path", lifted.restore);
40+
else element.style.removeProperty("clip-path");
41+
}
42+
43+
export function isElementCropLifted(element: HTMLElement): boolean {
44+
return liftedCrops.has(element);
45+
}
46+
47+
/** A commit made `clip` the element's crop. Returns the revert for a save that fails. */
48+
export function setLiftedCrop(element: HTMLElement, clip: string): () => void {
49+
const before = liftedCrops.get(element);
50+
if (!before) return () => undefined;
51+
liftedCrops.set(element, { clip, restore: clip });
52+
return () => {
53+
if (liftedCrops.has(element)) liftedCrops.set(element, before);
54+
};
55+
}
56+
57+
export function beginLiftedCropResize(element: HTMLElement, token: string): void {
58+
const lifted = liftedCrops.get(element);
59+
if (lifted) lifted.resizeFrom = { ...boxOf(element), token };
60+
}
61+
62+
function activeResizeFrom(element: HTMLElement, lifted: LiftedCrop): Box | null {
63+
const from = lifted.resizeFrom;
64+
return from && isStudioManualEditGestureCurrent(element, from.token) ? from : null;
65+
}
66+
67+
function scaleCrop(crop: ParsedInsetClipPathSides, from: Box, to: Box): ParsedInsetClipPathSides {
68+
const sx = from.width > 0 ? to.width / from.width : 1;
69+
const sy = from.height > 0 ? to.height / from.height : 1;
70+
return {
71+
top: crop.top * sy,
72+
right: crop.right * sx,
73+
bottom: crop.bottom * sy,
74+
left: crop.left * sx,
75+
radius: crop.radius,
76+
};
77+
}
78+
79+
/** The held crop, following the box while a resize gesture is live. Null when not lifted. */
80+
export function readLiftedCrop(element: HTMLElement): ParsedInsetClipPathSides | null {
81+
const lifted = liftedCrops.get(element);
82+
const crop = lifted ? parseCropClipPath(lifted.clip) : null;
83+
if (!lifted || !crop) return null;
84+
const from = activeResizeFrom(element, lifted);
85+
return from ? scaleCrop(crop, from, boxOf(element)) : crop;
86+
}
87+
88+
/** Call before a resize lands. Once the new size is live, the stage gives the clip-path patch that
89+
* keeps the same part of the element in view, or null when there is nothing to rescale. */
90+
export function prepareLiftedCropResize(
91+
element: HTMLElement,
92+
): () => { patch: PatchOperation; revert: () => void } | null {
93+
const lifted = liftedCrops.get(element);
94+
const crop = lifted ? parseCropClipPath(lifted.clip) : null;
95+
if (!lifted || !crop || !hasCropInsets(crop)) return () => null;
96+
const from = activeResizeFrom(element, lifted) ?? boxOf(element);
97+
return () => {
98+
const to = boxOf(element);
99+
if (!(to.width > 0 && to.height > 0)) return null;
100+
if (to.width === from.width && to.height === from.height) return null;
101+
const clip = buildInsetClipPathSides(scaleCrop(crop, from, to), crop.radius);
102+
return {
103+
patch: { type: "inline-style", property: "clip-path", value: clip },
104+
revert: setLiftedCrop(element, clip),
105+
};
106+
};
107+
}

‎packages/studio/src/hooks/domSelectionTestHarness.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@ export function installReactActEnvironment(): void {
1212
});
1313
}
1414

15+
/** happy-dom has no layout: make the element's box follow its inline width and height. */
16+
export function withInlineLayoutBox<T extends HTMLElement>(el: T): T {
17+
Object.defineProperties(el, {
18+
offsetWidth: { get: () => Number.parseFloat(el.style.width) || 0 },
19+
offsetHeight: { get: () => Number.parseFloat(el.style.height) || 0 },
20+
});
21+
return el;
22+
}
23+
1524
/** Mount a React element into a fresh detached host and return its root. */
1625
export function mountReactHarness(node: React.ReactElement): Root {
1726
const host = document.createElement("div");

‎packages/studio/src/hooks/useDomEditCommits.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ export function useDomEditCommits({
314314
handleDomAddTextField,
315315
handleDomRemoveTextField,
316316
stageElementPositionOffset,
317+
commitPositionPatchToHtml,
317318
handleDomPathOffsetCommit,
318319
handleDomBoxSizeCommit,
319320
handleDomRotationCommit,

‎packages/studio/src/hooks/useDomEditPositionPatchCommit.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ interface UseDomEditPositionPatchCommitParams {
1212
showToast: (message: string, tone?: "error" | "info") => void;
1313
}
1414

15-
interface PositionPatchOptions {
15+
type PositionPatchOptions = {
1616
label: string;
1717
coalesceKey: string;
1818
coalesceMs?: number;
1919
skipRefresh?: boolean;
20-
}
20+
};
2121

2222
export function useDomEditPositionPatchCommit({
2323
activeCompPath,

0 commit comments

Comments
 (0)