@hyperframes/studio 0.8.98 → 0.8.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/assets/{hyperframes-player-C6muFtfk.js → hyperframes-player-Rml34FRW.js} +1 -1
  2. package/dist/assets/{index-itc1XziP.js → index-CVDArg3m.js} +178 -178
  3. package/dist/assets/{index-B6vU39NM.js → index-C_fi-jTe.js} +1 -1
  4. package/dist/assets/{index-BxnoLgxG.js → index-D9YzDuBx.js} +1 -1
  5. package/dist/index.html +1 -1
  6. package/dist/index.js +542 -373
  7. package/dist/index.js.map +1 -1
  8. package/package.json +9 -9
  9. package/src/components/editor/DomEditCropHandles.test.tsx +34 -66
  10. package/src/components/editor/DomEditCropHandles.tsx +30 -62
  11. package/src/components/editor/DomEditOverlay.test.ts +2 -2
  12. package/src/components/editor/cropResize.test.ts +129 -0
  13. package/src/components/editor/cropResize.ts +143 -0
  14. package/src/components/editor/domEditOverlayCrop.ts +65 -15
  15. package/src/components/editor/domEditOverlayCropLift.test.ts +44 -0
  16. package/src/components/editor/domEditOverlayGestures.ts +2 -5
  17. package/src/components/editor/elementPositionOffset.ts +5 -4
  18. package/src/components/editor/manualEdits.test.ts +22 -8
  19. package/src/components/editor/manualEditsDom.ts +27 -11
  20. package/src/components/editor/manualEditsParsing.ts +0 -4
  21. package/src/components/editor/manualEditsSnapshot.ts +3 -0
  22. package/src/components/editor/manualOffsetDrag.test.ts +14 -0
  23. package/src/hooks/domSelectionTestHarness.ts +8 -0
  24. package/src/hooks/draggedGsapPosition.ts +4 -2
  25. package/src/hooks/gsapDragCommit.ts +6 -6
  26. package/src/hooks/gsapEditOutcome.ts +6 -0
  27. package/src/hooks/gsapResizeIntercept.ts +5 -5
  28. package/src/hooks/gsapRuntimeBridge.test.ts +11 -0
  29. package/src/hooks/gsapRuntimeBridge.ts +2 -1
  30. package/src/hooks/gsapRuntimeKeyframes.test.ts +7 -0
  31. package/src/hooks/gsapRuntimeKeyframes.ts +34 -21
  32. package/src/hooks/timelineTimingSync.ts +40 -4
  33. package/src/hooks/useAnimatedPropertyCommit.test.tsx +40 -1
  34. package/src/hooks/useAnimatedPropertyCommit.ts +11 -13
  35. package/src/hooks/useCropOverlay.ts +8 -2
  36. package/src/hooks/useDomEditCommits.test.tsx +6 -1
  37. package/src/hooks/useDomEditCommits.ts +1 -0
  38. package/src/hooks/useDomEditPositionPatchCommit.ts +2 -2
  39. package/src/hooks/useDomEditSession.ts +2 -0
  40. package/src/hooks/useDomGeometryCommit.ts +1 -0
  41. package/src/hooks/useDomGeometryCommits.test.tsx +112 -0
  42. package/src/hooks/useDomGeometryCommits.ts +5 -0
  43. package/src/hooks/useElementLifecycleOps.multiDelete.test.tsx +3 -1
  44. package/src/hooks/useGsapAwareEditing.test.tsx +101 -5
  45. package/src/hooks/useGsapAwareEditing.ts +37 -23
  46. package/src/hooks/useTimelineEditing.test.tsx +190 -135
  47. package/src/hooks/useTimelineEditing.ts +13 -13
  48. package/src/hooks/useTimelineGroupEditing.ts +13 -9
  49. package/src/player/components/useTimelineVirtualRows.test.tsx +30 -1
  50. package/src/utils/rounding.ts +5 -0
  51. package/src/utils/sdkEditTransaction.ts +10 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/studio",
3
- "version": "0.8.98",
3
+ "version": "0.8.99",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -54,18 +54,18 @@
54
54
  "@codemirror/view": "6.40.0",
55
55
  "@mcp-b/global": "^5.0.1",
56
56
  "@phosphor-icons/react": "^2.1.10",
57
- "@tanstack/react-virtual": "^3.14.6",
57
+ "@tanstack/react-virtual": "^3.14.13",
58
58
  "bpm-detective": "^2.0.5",
59
59
  "cn": "0.2.4",
60
60
  "dockview-react": "8.3.1",
61
61
  "gsap": "^3.13.0",
62
62
  "mediabunny": "^1.45.3",
63
- "@hyperframes/core": "0.8.98",
64
- "@hyperframes/parsers": "0.8.98",
65
- "@hyperframes/player": "0.8.98",
66
- "@hyperframes/sdk": "0.8.98",
67
- "@hyperframes/shader-transitions": "0.8.98",
68
- "@hyperframes/studio-server": "0.8.98"
63
+ "@hyperframes/core": "0.8.99",
64
+ "@hyperframes/parsers": "0.8.99",
65
+ "@hyperframes/player": "0.8.99",
66
+ "@hyperframes/sdk": "0.8.99",
67
+ "@hyperframes/studio-server": "0.8.99",
68
+ "@hyperframes/shader-transitions": "0.8.99"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@tailwindcss/vite": "^4.3.3",
@@ -81,7 +81,7 @@
81
81
  "vite": "^6.4.2",
82
82
  "vitest": "^4.1.11",
83
83
  "zustand": "^5.0.0",
84
- "@hyperframes/producer": "0.8.98"
84
+ "@hyperframes/producer": "0.8.99"
85
85
  },
86
86
  "peerDependencies": {
87
87
  "react": "19",
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
5
5
  import type { DomEditSelection } from "./domEditing";
6
6
  import type { OverlayRect } from "./domEditOverlayGeometry";
7
7
  import { DomEditCropHandles } from "./DomEditCropHandles";
8
+ import { isElementCropLifted } from "./domEditOverlayCrop";
8
9
 
9
10
  (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
10
11
 
@@ -55,27 +56,27 @@ function render(
55
56
  return { root, rerender: draw };
56
57
  }
57
58
 
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", () => {
64
63
  const a = makeEl("a", "inset(16px round 12px)");
65
64
  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)");
67
67
  act(() => root.unmount());
68
+ expect(isElementCropLifted(a)).toBe(false);
68
69
  expect(a.style.getPropertyValue("clip-path")).toBe("inset(16px round 12px)");
69
70
  });
70
71
 
71
- it("restores A's own clip when switching directly to B", () => {
72
+ it("drops A's lift when switching directly to B", () => {
72
73
  const a = makeEl("a", "inset(16px)");
73
74
  const b = makeEl("b", "inset(40px 8px 4px 2px)");
74
75
  const { root, rerender } = render(a);
75
76
  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);
77
79
  expect(a.style.getPropertyValue("clip-path")).toBe("inset(16px)");
78
- expect(b.style.getPropertyValue("clip-path")).toBe("none");
79
80
  act(() => root.unmount());
80
81
  expect(b.style.getPropertyValue("clip-path")).toBe("inset(40px 8px 4px 2px)");
81
82
  });
@@ -83,49 +84,11 @@ describe("DomEditCropHandles clip lift/restore", () => {
83
84
  it("never lifts an uneditable clip and leaves it untouched across select/deselect", () => {
84
85
  const a = makeEl("a", "circle(50% at 50% 50%)");
85
86
  const { root } = render(a);
86
- expect(a.style.getPropertyValue("clip-path")).toBe("circle(50% at 50% 50%)");
87
+ expect(isElementCropLifted(a)).toBe(false);
87
88
  act(() => root.unmount());
88
89
  expect(a.style.getPropertyValue("clip-path")).toBe("circle(50% at 50% 50%)");
89
90
  });
90
91
 
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
-
129
92
  it.each([
130
93
  { name: "a crop edge", clip: "inset(10px)", handle: "Crop right", dx: -20, dy: 0 },
131
94
  {
@@ -189,33 +152,38 @@ describe("DomEditCropHandles clip lift/restore", () => {
189
152
  expect(a.style.getPropertyValue("clip-path")).toBe("inset(0px 20px 0px 0px)");
190
153
  });
191
154
 
192
- it("re-lifts when the crop commit rejects", async () => {
155
+ it("commits the dragged crop and stays lifted when the save fails", async () => {
193
156
  const a = makeEl("a", "inset(10px)");
194
157
  const onStyleCommit = vi.fn((property: string, value: string) => {
195
158
  a.style.setProperty(property, value);
196
159
  return Promise.reject(new Error("persist failed"));
197
160
  });
198
161
  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 })),
214
166
  );
167
+ press("pointerdown", 100);
168
+ press("pointermove", 80);
169
+ await act(async () => {
170
+ press("pointerup", 80);
215
171
  await Promise.resolve();
216
172
  });
217
173
 
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");
219
187
  act(() => root.unmount());
220
188
  });
221
189
  });
@@ -4,6 +4,9 @@ import { type OverlayRect, RESIZE_HANDLE_HIT_PX } from "./domEditOverlayGeometry
4
4
  import {
5
5
  type CropEdge,
6
6
  cropRectFromInsets,
7
+ dropElementCropLift,
8
+ hasCropInsets,
9
+ liftElementCrop,
7
10
  readElementCropFrame,
8
11
  readElementCropInsets,
9
12
  resolveCropInsetFromEdgeDrag,
@@ -11,6 +14,7 @@ import {
11
14
  rotateDeltaIntoFrame,
12
15
  } from "./domEditOverlayCrop";
13
16
  import { buildInsetClipPathSides, type ClipPathInsetSides } from "./clipPathHelpers";
17
+ import { readCropFollowingResize } from "./cropResize";
14
18
 
15
19
  interface CropGestureState {
16
20
  edge: CropEdge | "move";
@@ -19,6 +23,7 @@ interface CropGestureState {
19
23
  startY: number;
20
24
  startInsets: ClipPathInsetSides;
21
25
  insets: ClipPathInsetSides;
26
+ radius: number;
22
27
  /** Element frame captured at gesture start: pointer deltas rotate into it. */
23
28
  angleDeg: number;
24
29
  scaleX: number;
@@ -83,6 +88,7 @@ function repositionHandleSize(rect: Rect): number {
83
88
  }
84
89
 
85
90
  const EDGES: CropEdge[] = ["top", "right", "bottom", "left"];
91
+ const NO_CROP = { top: 0, right: 0, bottom: 0, left: 0, radius: 0 };
86
92
 
87
93
  /**
88
94
  * Always-on crop, integrated with the selection (no crop "mode"): while a
@@ -92,7 +98,7 @@ const EDGES: CropEdge[] = ["top", "right", "bottom", "left"];
92
98
  * grid guides framing); release commits `clip-path: inset(...)` through the
93
99
  * normal style-commit path (one undo step per drag). When cropped, a center
94
100
  * 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
96
102
  * is the source of truth — nothing here mutates layout.
97
103
  */
98
104
  export function DomEditCropHandles({
@@ -109,54 +115,29 @@ export function DomEditCropHandles({
109
115
  // clip with an inset (or deletes it).
110
116
  const cropStateFor = (element: HTMLElement) => {
111
117
  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 } };
114
120
  };
115
121
  const [state, setState] = useState(() => cropStateFor(selection.element));
116
122
 
117
123
  // 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).
121
125
  if (state.element !== selection.element) {
122
126
  setState(cropStateFor(selection.element));
123
127
  }
124
128
 
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);
130
133
 
131
134
  // 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.
146
136
  useEffect(() => {
147
137
  const el = selection.element;
148
138
  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);
160
141
  }, [selection.element]);
161
142
 
162
143
  // The crop applies in the element's LOCAL frame (clip-path precedes the
@@ -169,7 +150,7 @@ export function DomEditCropHandles({
169
150
  // Crop rect in FRAME-LOCAL coordinates (origin = frame top-left).
170
151
  const cropRect = cropRectFromInsets(
171
152
  { left: 0, top: 0, width: frame.width, height: frame.height },
172
- state.insets,
153
+ insets,
173
154
  frame.scaleX,
174
155
  frame.scaleY,
175
156
  );
@@ -180,19 +161,23 @@ export function DomEditCropHandles({
180
161
  event.preventDefault();
181
162
  event.stopPropagation();
182
163
  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;
183
166
  gestureRef.current = {
184
167
  edge,
185
168
  pointerId: event.pointerId,
186
169
  startX: event.clientX,
187
170
  startY: event.clientY,
188
- startInsets: state.insets,
189
- insets: state.insets,
171
+ startInsets: pressed,
172
+ insets: pressed,
173
+ radius: pressed.radius,
190
174
  angleDeg: frame.angleDeg,
191
175
  scaleX: frame.scaleX,
192
176
  scaleY: frame.scaleY,
193
177
  };
194
178
  // Clip is already lifted by the selection effect; just flag the drag so the
195
179
  // rule-of-thirds grid shows.
180
+ setState((prev) => ({ ...prev, insets: pressed }));
196
181
  setDragging(true);
197
182
  };
198
183
 
@@ -234,29 +219,12 @@ export function DomEditCropHandles({
234
219
  const finishCropGesture = (event: ReactPointerEvent<HTMLElement>) => {
235
220
  const gesture = endCropGesture(event);
236
221
  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);
260
228
  };
261
229
 
262
230
  const cancelCropGesture = (event: ReactPointerEvent<HTMLElement>) => {
@@ -697,7 +697,7 @@ describe("resolveDomEditRotationGesture", () => {
697
697
  ).toEqual({ angle: 15 });
698
698
  });
699
699
 
700
- it("allows small pointer movements when the rounded angle changes", () => {
700
+ it("allows small pointer movements and keeps the exact angle", () => {
701
701
  const nextRotation = resolveDomEditRotationGesture({
702
702
  centerX: 0,
703
703
  centerY: 0,
@@ -709,7 +709,7 @@ describe("resolveDomEditRotationGesture", () => {
709
709
  snap: false,
710
710
  });
711
711
 
712
- expect(nextRotation.angle).toBe(1.4);
712
+ expect(nextRotation.angle).toBe(1.432);
713
713
  expect(hasDomEditRotationChanged(0, nextRotation.angle)).toBe(true);
714
714
  expect(hasDomEditRotationChanged(0, 0)).toBe(false);
715
715
  });
@@ -0,0 +1,129 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { prepareCropResize, readCropFollowingResize, saveCropResize } from "./cropResize";
4
+ import type { DomEditSelection } from "./domEditingTypes";
5
+ import {
6
+ applyStudioBoxSizeDraft,
7
+ captureStudioBoxSize,
8
+ clearStudioBoxSize,
9
+ restoreStudioBoxSize,
10
+ } from "./manualEdits";
11
+ import { withInlineLayoutBox } from "../../hooks/domSelectionTestHarness";
12
+
13
+ function sizedElement(width: number, height: number, clip: string): HTMLElement {
14
+ const el = withInlineLayoutBox(document.createElement("div"));
15
+ el.style.cssText = `width: ${width}px; height: ${height}px; clip-path: ${clip}`;
16
+ return el;
17
+ }
18
+
19
+ describe("crop during a resize", () => {
20
+ it("follows the box only while a resize draft is live", () => {
21
+ const el = sizedElement(300, 200, "inset(10px 60px 20px 30px round 8px)");
22
+ const before = captureStudioBoxSize(el);
23
+ const crop = (top: number, right: number, bottom: number, left: number) => ({
24
+ top,
25
+ right,
26
+ bottom,
27
+ left,
28
+ radius: 8,
29
+ });
30
+ applyStudioBoxSizeDraft(el, { width: 600, height: 400 });
31
+ expect(readCropFollowingResize(el)).toEqual(crop(20, 120, 40, 60));
32
+ restoreStudioBoxSize(el, before);
33
+ // An animated width is not a resize: the crop keeps its pixels.
34
+ el.style.width = "600px";
35
+ expect(readCropFollowingResize(el)).toEqual(crop(10, 60, 20, 30));
36
+ });
37
+
38
+ it("leaves the crop alone when the box kept its size (a resize saved as scale)", () => {
39
+ const el = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
40
+ applyStudioBoxSizeDraft(el, { width: 450, height: 300 });
41
+ const stage = prepareCropResize(el);
42
+ clearStudioBoxSize(el);
43
+ el.style.width = "300px";
44
+ el.style.height = "200px";
45
+ expect(stage()).toBeNull();
46
+ expect(el.style.getPropertyValue("clip-path")).toBe("inset(0px 60px 0px 0px)");
47
+ });
48
+
49
+ it("puts the crop back, !important and all, when its save fails", async () => {
50
+ const el = sizedElement(300, 200, "none");
51
+ el.style.setProperty("clip-path", "inset(0px 60px 0px 0px)", "important");
52
+ const stage = prepareCropResize(el);
53
+ el.style.width = "450px";
54
+ let priorityWhileSaving = "";
55
+ const commit = vi.fn(() => {
56
+ priorityWhileSaving = el.style.getPropertyPriority("clip-path");
57
+ return Promise.reject(new Error("save failed"));
58
+ });
59
+ const selection = { element: el } as unknown as DomEditSelection;
60
+ await expect(saveCropResize(stage, selection, commit, "undo-key")).rejects.toThrow(
61
+ "save failed",
62
+ );
63
+
64
+ const value = "inset(0px 90px 0px 0px) !important";
65
+ expect(commit.mock.calls[0]![1]).toEqual([
66
+ { type: "inline-style", property: "clip-path", value },
67
+ ]);
68
+ expect(priorityWhileSaving).toBe("important");
69
+ expect(el.style.getPropertyValue("clip-path")).toBe("inset(0px 60px 0px 0px)");
70
+ expect(el.style.getPropertyPriority("clip-path")).toBe("important");
71
+ });
72
+
73
+ it("scales the crop once: the stage ends the draft", () => {
74
+ const el = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
75
+ applyStudioBoxSizeDraft(el, { width: 450, height: 300 });
76
+ prepareCropResize(el)();
77
+ expect(readCropFollowingResize(el)).toMatchObject({ right: 90 });
78
+ });
79
+
80
+ it("leaves a crop edited while the size saved, and a tweened crop, alone", () => {
81
+ const edited = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
82
+ const stageEdited = prepareCropResize(edited);
83
+ edited.style.width = "450px";
84
+ edited.style.setProperty("clip-path", "inset(0px 100px 0px 0px)");
85
+ expect(stageEdited()).toBeNull();
86
+
87
+ const tweened = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
88
+ const child = { targets: () => [tweened], vars: { clipPath: "inset(0px 120px 0px 0px)" } };
89
+ Object.assign(window, { __timelines: { main: { getChildren: () => [child] } } });
90
+ const stageTweened = prepareCropResize(tweened);
91
+ tweened.style.width = "450px";
92
+ expect(stageTweened()).toBeNull();
93
+ Object.assign(window, { __timelines: undefined });
94
+ });
95
+
96
+ it("decides before the write, which may add a width tween of its own", () => {
97
+ const el = sizedElement(300, 200, "inset(0px 60px 0px 0px)");
98
+ const stage = prepareCropResize(el);
99
+ const tween = { targets: () => [el], vars: { width: 600 }, duration: () => 4 };
100
+ Object.assign(window, { __timelines: { main: { getChildren: () => [tween] } } });
101
+ el.style.width = "600px";
102
+ expect(stage()?.patch.value).toBe("inset(0px 120px 0px 0px)");
103
+ Object.assign(window, { __timelines: undefined });
104
+ });
105
+
106
+ it("follows only the axes GSAP does not tween, while dragging and once saved", () => {
107
+ const resize = (vars: object, duration: number) => {
108
+ const el = sizedElement(300, 200, "inset(20px 60px 20px 0px)");
109
+ const tween = { targets: () => [el], vars, duration: () => duration };
110
+ // The tween's timeline is not the first key, as after a soft reload.
111
+ const timelines = { sub: { getChildren: () => [] }, main: { getChildren: () => [tween] } };
112
+ Object.assign(window, { __timelines: timelines });
113
+ applyStudioBoxSizeDraft(el, { width: 600, height: 400 });
114
+ const { top, right } = readCropFollowingResize(el)!;
115
+ const saved = prepareCropResize(el)()?.patch.value ?? null;
116
+ Object.assign(window, { __timelines: undefined });
117
+ return [[top, right], saved];
118
+ };
119
+ // A held width still scales; a height tween leaves the width free.
120
+ expect(resize({ width: 473 }, 0)).toEqual([[40, 120], "inset(40px 120px 40px 0px)"]);
121
+ expect(resize({ height: 300 }, 4)).toEqual([[20, 120], "inset(20px 120px 20px 0px)"]);
122
+ // A width tween, in either keyframe form, leaves the height free.
123
+ const widthOnly = [[40, 60], "inset(40px 60px 40px 0px)"];
124
+ const percent = { "0%": { width: 300 }, "100%": { width: 600 } };
125
+ expect(resize({ keyframes: percent }, 4)).toEqual(widthOnly);
126
+ expect(resize({ keyframes: { width: [300, 600] } }, 4)).toEqual(widthOnly);
127
+ expect(resize({ width: 600, height: 400 }, 4)).toEqual([[20, 60], null]);
128
+ });
129
+ });
@@ -0,0 +1,143 @@
1
+ import type { PatchOperation } from "../../utils/sourcePatcher";
2
+ import type { CommitMutation } from "../../hooks/gsapScriptCommitTypes";
3
+ import type { DomEditSelection } from "./domEditingTypes";
4
+ import { gsapAnimatesProperty } from "./gsapAnimatesProperty";
5
+ import { elementHasNonHoldTween } from "../../hooks/gsapRuntimeKeyframes";
6
+ import { buildInsetClipPathSides, type ParsedInsetClipPathSides } from "./clipPathHelpers";
7
+ import { hasCropInsets, readElementCropInsets } from "./domEditOverlayCrop";
8
+ import { forgetStudioBoxSizeDraftBase, readStudioBoxSizeDraftBase } from "./manualEditsDom";
9
+
10
+ interface Box {
11
+ width: number;
12
+ height: number;
13
+ }
14
+
15
+ const boxOf = (element: HTMLElement): Box => ({
16
+ width: element.offsetWidth,
17
+ height: element.offsetHeight,
18
+ });
19
+
20
+ type Follows = Record<keyof Box, boolean>;
21
+
22
+ /** Per axis, whether a crop follows a resize: not when GSAP drives the clip or tweens that axis's size. */
23
+ function cropFollows(element: HTMLElement): Follows {
24
+ const clip = gsapAnimatesProperty(element, "clipPath");
25
+ return {
26
+ width: !clip && !elementHasNonHoldTween(element, ["width"]),
27
+ height: !clip && !elementHasNonHoldTween(element, ["height"]),
28
+ };
29
+ }
30
+
31
+ function scaleCrop(
32
+ crop: ParsedInsetClipPathSides,
33
+ from: Box,
34
+ to: Box,
35
+ follows: Follows,
36
+ ): ParsedInsetClipPathSides {
37
+ const sx = follows.width && from.width > 0 ? to.width / from.width : 1;
38
+ const sy = follows.height && from.height > 0 ? to.height / from.height : 1;
39
+ return {
40
+ top: crop.top * sy,
41
+ right: crop.right * sx,
42
+ bottom: crop.bottom * sy,
43
+ left: crop.left * sx,
44
+ radius: crop.radius,
45
+ };
46
+ }
47
+
48
+ /** The element's crop as the crop UI draws it: it follows the box while a resize draft is live. */
49
+ export function readCropFollowingResize(element: HTMLElement): ParsedInsetClipPathSides | null {
50
+ const crop = readElementCropInsets(element);
51
+ const base = readStudioBoxSizeDraftBase(element);
52
+ return crop && base ? scaleCrop(crop, base, boxOf(element), cropFollows(element)) : crop;
53
+ }
54
+
55
+ export interface CropResize {
56
+ patch: PatchOperation;
57
+ revert: () => void;
58
+ }
59
+
60
+ /** Call before a resize lands. Once the new size is live, the stage writes the crop that keeps the
61
+ * same part of the element in view and returns its patch, or null when nothing needs rescaling. */
62
+ export function prepareCropResize(element: HTMLElement): () => CropResize | null {
63
+ const from = readStudioBoxSizeDraftBase(element) ?? boxOf(element);
64
+ const before = element.style.getPropertyValue("clip-path");
65
+ const priority = element.style.getPropertyPriority("clip-path");
66
+ // Decided before the write lands: a W edit may add a width keyframe of its own.
67
+ const follows = cropFollows(element);
68
+ const crop = readElementCropInsets(element);
69
+ return () => {
70
+ forgetStudioBoxSizeDraftBase(element);
71
+ const to = boxOf(element);
72
+ // A crop edited while the size saved was drawn in the new box already.
73
+ const untouched = element.style.getPropertyValue("clip-path") === before;
74
+ if (!crop || !hasCropInsets(crop) || !untouched || !(to.width > 0 && to.height > 0))
75
+ return null;
76
+ const clip = buildInsetClipPathSides(scaleCrop(crop, from, to, follows), crop.radius);
77
+ // Unchanged when the box is (a resize saved as a `scale`) or no resized axis follows.
78
+ if (clip === buildInsetClipPathSides(crop, crop.radius)) return null;
79
+ element.style.setProperty("clip-path", clip, priority);
80
+ return {
81
+ patch: {
82
+ type: "inline-style",
83
+ property: "clip-path",
84
+ value: priority ? `${clip} !important` : clip,
85
+ },
86
+ revert: () => {
87
+ if (before) element.style.setProperty("clip-path", before, priority);
88
+ else element.style.removeProperty("clip-path");
89
+ },
90
+ };
91
+ };
92
+ }
93
+
94
+ type PatchCommit = (
95
+ selection: DomEditSelection,
96
+ patches: PatchOperation[],
97
+ options: { label: string; coalesceKey: string; coalesceMs?: number },
98
+ ) => Promise<void>;
99
+
100
+ /** Stage the crop and save it under the resize's undo key, taking it back off the element if that fails. */
101
+ export async function saveCropResize(
102
+ stage: () => CropResize | null,
103
+ selection: DomEditSelection,
104
+ commit: PatchCommit,
105
+ coalesceKey: string,
106
+ ): Promise<void> {
107
+ const crop = stage();
108
+ if (!crop) return;
109
+ try {
110
+ await commit(selection, [crop.patch], {
111
+ label: "Resize layer",
112
+ coalesceKey,
113
+ coalesceMs: Number.POSITIVE_INFINITY,
114
+ });
115
+ } catch (error) {
116
+ crop.revert();
117
+ throw error;
118
+ }
119
+ }
120
+
121
+ let sizeWriteCounter = 0;
122
+
123
+ /** A property write that may size the element (a W/H field on an animated element): when it
124
+ * does, its writes and the rescaled crop share one undo step. */
125
+ export async function writeSizeWithCrop(
126
+ selection: DomEditSelection,
127
+ properties: Record<string, unknown>,
128
+ mutation: CommitMutation | null,
129
+ commit: PatchCommit,
130
+ write: (keyed?: CommitMutation) => Promise<void>,
131
+ ): Promise<void> {
132
+ if (!mutation || !("width" in properties || "height" in properties)) return write();
133
+ const stage = prepareCropResize(selection.element);
134
+ const coalesceKey = `size-write:${++sizeWriteCounter}`;
135
+ const undoStep = { coalesceKey, coalesceMs: Number.POSITIVE_INFINITY };
136
+ const keyed: CommitMutation = (s, m, options) => mutation(s, m, { ...options, ...undoStep });
137
+ if (mutation.batch) {
138
+ const batch = mutation.batch;
139
+ keyed.batch = (calls, options) => batch(calls, { ...options, ...undoStep });
140
+ }
141
+ await write(keyed);
142
+ await saveCropResize(stage, selection, commit, coalesceKey);
143
+ }