Skip to content

Commit 98fe011

Browse files
fix(studio): undo takes back the last edit, even right after a resize or a nudge (#5048)
* fix(studio): a size edit right after a resize is its own undo step * fix(studio): a nudge still saving is recorded before the next edit * fix(studio): published types name cn by its package, not a node_modules path * fix(studio): drop baseUrl so declarations never name a node_modules path * fix(studio): an edit started inside the save of another edit never flushes * fix(studio): an edit made while a nudge is still saving writes after it * fix(studio): a later edit never overtakes one still waiting on a nudge save * fix(studio): undoing a gsap.set clears what it applied from the preview * fix(studio): an edit never waits on itself behind a nudge save * fix(studio): a second nudge burst saves when its commit runs behind the first * fix(studio): undoing a W on an animated box clears the width it set live * fix(studio): any GSAP edit that drops a live-applied set clears it from the preview * fix(studio): a soft reload clears exactly the set props a live patch applied * fix(studio): name width and height as set-patch props
1 parent f7d6734 commit 98fe011

13 files changed

Lines changed: 423 additions & 50 deletions

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

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// fallow-ignore-file code-duplication
12
import { trackStudioEvent } from "../../utils/studioTelemetry";
23
// @vitest-environment happy-dom
34
import React, { act } from "react";
@@ -7,7 +8,11 @@ import { installReactActEnvironment, makeSelection } from "../../hooks/domSelect
78
import { useDomEditNudge, type UseDomEditNudgeParams } from "./useDomEditNudge";
89
import { CANVAS_NUDGE_COMMIT_DEBOUNCE_MS, CANVAS_NUDGE_STEP_PX } from "./domEditNudge";
910
import { __resetForTests } from "../../utils/canvasNudgeGate";
10-
import { flushStudioPendingEdits, hasStudioPendingEdits } from "../../utils/studioPendingEdits";
11+
import {
12+
flushStudioPendingEdits,
13+
hasStudioPendingEdits,
14+
trackedStudioEdit,
15+
} from "../../utils/studioPendingEdits";
1116
import type { DomEditSelection } from "./domEditing";
1217
import type { OverlayRect } from "./domEditOverlayGeometry";
1318

@@ -392,23 +397,32 @@ describe("useDomEditNudge pauses playback before it snapshots the timelines", ()
392397
});
393398
});
394399

400+
/** A burst-ready Harness on a fresh element, under fake timers. */
401+
function mountBurstHarness(
402+
id: string,
403+
onPathOffsetCommit: UseDomEditNudgeParams["onPathOffsetCommitRef"]["current"],
404+
) {
405+
__resetForTests();
406+
vi.useFakeTimers();
407+
const root = createRoot(document.body.appendChild(document.createElement("div")));
408+
const element = document.body.appendChild(document.createElement("div"));
409+
element.id = id;
410+
act(() => {
411+
root.render(
412+
React.createElement(Harness, {
413+
selection: makeSelection("Dot", element),
414+
onPathOffsetCommit,
415+
}),
416+
);
417+
});
418+
return root;
419+
}
420+
395421
describe("useDomEditNudge — undo right after a burst", () => {
396422
it("undo's drain commits a burst still inside its debounce and waits for its save", async () => {
397-
__resetForTests();
398-
vi.useFakeTimers();
399-
const root = createRoot(document.body.appendChild(document.createElement("div")));
400-
const element = document.body.appendChild(document.createElement("div"));
401-
element.id = "dot-undo";
402423
let saved!: () => void;
403424
const commit = vi.fn(() => new Promise<void>((resolve) => (saved = resolve)));
404-
act(() => {
405-
root.render(
406-
React.createElement(Harness, {
407-
selection: makeSelection("Dot", element),
408-
onPathOffsetCommit: commit,
409-
}),
410-
);
411-
});
425+
const root = mountBurstHarness("dot-undo", commit);
412426
act(() => dispatchArrowRight());
413427

414428
let drained = false;
@@ -424,21 +438,9 @@ describe("useDomEditNudge — undo right after a burst", () => {
424438
});
425439

426440
it("counts the burst as a pending edit from its first key until its save lands", async () => {
427-
__resetForTests();
428-
vi.useFakeTimers();
429-
const root = createRoot(document.body.appendChild(document.createElement("div")));
430-
const element = document.body.appendChild(document.createElement("div"));
431-
element.id = "dot-pending";
432441
let saved!: () => void;
433442
const commit = vi.fn(() => new Promise<void>((resolve) => (saved = resolve)));
434-
act(() => {
435-
root.render(
436-
React.createElement(Harness, {
437-
selection: makeSelection("Dot", element),
438-
onPathOffsetCommit: commit,
439-
}),
440-
);
441-
});
443+
const root = mountBurstHarness("dot-pending", commit);
442444
expect(hasStudioPendingEdits()).toBe(false);
443445
act(() => dispatchArrowRight());
444446
expect(hasStudioPendingEdits()).toBe(true);
@@ -452,6 +454,25 @@ describe("useDomEditNudge — undo right after a burst", () => {
452454
});
453455
});
454456

457+
describe("useDomEditNudge — a Design-panel edit during a burst", () => {
458+
it("commits the burst before the panel edit, so one undo takes back the panel edit", async () => {
459+
const order: string[] = [];
460+
const root = mountBurstHarness("dot-panel", async () => void order.push("nudge"));
461+
try {
462+
act(() => dispatchArrowRight());
463+
const panelEdit = trackedStudioEdit(async () => void order.push("width"), {
464+
afterOlderSaves: true,
465+
})();
466+
vi.useRealTimers();
467+
await panelEdit;
468+
expect(order).toEqual(["nudge", "width"]);
469+
} finally {
470+
vi.useRealTimers();
471+
act(() => root.unmount());
472+
}
473+
});
474+
});
475+
455476
describe("useDomEditNudge — a commit that throws", () => {
456477
it("still ends the burst's pending edit, so undo and export never wait on it", async () => {
457478
__resetForTests();

‎packages/studio/src/components/ui/cn.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* invents (`text-step-*`, `ctl`/`ctl-sm`/`ctl-lg`) so overrides replace, not stack.
44
*/
55

6+
import type { CnFunction } from "cn";
67
import { createCn } from "cn/config";
78

89
/** `text-step-11`, `text-step-9`, … — the type scale from `theme.css`. */
@@ -11,7 +12,7 @@ const isTypeStep = (value: string) => /^step-\d+$/.test(value);
1112
/** `ctl`, `ctl-sm`, `ctl-lg` — the control heights from `theme.css`. */
1213
const isControlSize = (value: string) => /^ctl(-sm|-lg)?$/.test(value);
1314

14-
export const cn = createCn({
15+
export const cn: CnFunction = createCn({
1516
extend: {
1617
classGroups: {
1718
"font-size": [{ text: [isTypeStep] }],

‎packages/studio/src/contexts/DomEditContext.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ function trackEditCommits(actions: DomEditActionsValue): DomEditActionsValue {
107107
const tracked: Record<string, unknown> = { ...actions };
108108
for (const key of Object.keys(SAVES_AN_EDIT) as Array<keyof typeof SAVES_AN_EDIT>) {
109109
if (!SAVES_AN_EDIT[key]) continue;
110-
tracked[key] = trackedStudioEdit(actions[key] as (...args: unknown[]) => unknown);
110+
tracked[key] = trackedStudioEdit(actions[key] as (...args: unknown[]) => unknown, {
111+
afterOlderSaves: true,
112+
});
111113
}
112114
return tracked as unknown as DomEditActionsValue;
113115
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
type RuntimeTween,
2020
type RuntimeTimeline,
2121
} from "./gsapRuntimeKeyframes";
22+
import { recordLiveSet } from "../utils/softReloadTargets";
2223

2324
/** Value-only channels a `tl.set(...)` patch may touch. */
2425
export interface SetPatchProps {
@@ -34,6 +35,8 @@ export interface SetPatchProps {
3435
scaleY?: number;
3536
scale?: number;
3637
opacity?: number;
38+
width?: number;
39+
height?: number;
3740
}
3841

3942
/** A single keyframe step's numeric channels (the GSAP array-keyframe form). */
@@ -101,6 +104,7 @@ function applyGlobalSet(
101104
const numeric = finiteNumericProps(props);
102105
if (!gsapLib?.set || !el || !numeric) return false;
103106
gsapLib.set(el, numeric);
107+
recordLiveSet(el, numeric);
104108
return true;
105109
} catch {
106110
return false;

‎packages/studio/src/hooks/useDomGeometryCommits.test.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,27 @@ describe("Reset after a plain move puts the author's translate back", () => {
376376
});
377377
});
378378

379+
describe("useDomGeometryCommits undo steps", () => {
380+
it("never merges a resize with the next size edit of the same element", async () => {
381+
const element = document.createElement("div");
382+
element.id = "box";
383+
document.body.append(element);
384+
const selection = { id: "box", selector: "#box", element } as unknown as DomEditSelection;
385+
const commitPositionPatchToHtml = vi
386+
.fn<UseDomGeometryCommitsParams["commitPositionPatchToHtml"]>()
387+
.mockResolvedValue(undefined);
388+
const { commits, unmount } = mountCommits(commitPositionPatchToHtml);
389+
390+
await commits().handleDomBoxSizeCommit(selection, { width: 418, height: 200 });
391+
await commits().handleDomBoxSizeCommit(selection, { width: 280, height: 200 });
392+
393+
const [resize, field] = commitPositionPatchToHtml.mock.calls.map(([, , options]) => options);
394+
expect(resize!.coalesceKey).not.toBe(field!.coalesceKey);
395+
unmount();
396+
element.remove();
397+
});
398+
});
399+
379400
describe("useDomGeometryCommits resize of a cropped element", () => {
380401
it("saves the crop scaled per axis with the box in the resize's own commit", async () => {
381402
const element = withInlineLayoutBox(document.createElement("div"));

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ import {
2626
} from "../components/editor/manualEditsDomPatches";
2727
import type { PatchOperation } from "../utils/sourcePatcher";
2828

29+
let boxSizeCommitCounter = 0;
30+
2931
// ── Hook ──
3032

3133
export interface UseDomGeometryCommitsParams {
@@ -90,7 +92,10 @@ export function useDomGeometryCommits({
9092
label: "Resize layer box",
9193
...(undoKey
9294
? { coalesceKey: undoKey, coalesceMs: Number.POSITIVE_INFINITY, deferRender: true }
93-
: { coalesceKey: `box-size:${getDomEditTargetKey(selection)}` }),
95+
: {
96+
coalesceKey: `box-size:${++boxSizeCommitCounter}`,
97+
coalesceMs: Number.POSITIVE_INFINITY,
98+
}),
9499
}).catch((error) => {
95100
restoreStudioBoxSize(element, beforeSize);
96101
if (offset) restoreStudioPathOffset(element, beforeOffset);

‎packages/studio/src/utils/gsapSoftReload.test.ts‎

Lines changed: 98 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
// fallow-ignore-file code-duplication
12
// @vitest-environment happy-dom
23

4+
import { patchRuntimeTweenInPlace } from "../hooks/gsapRuntimePatch";
35
import { afterEach, describe, it, expect, vi } from "vitest";
46
import {
57
readNestedFiles,
@@ -70,6 +72,29 @@ function buildMockIframe(overrides: Record<string, unknown> = {}) {
7072
};
7173
}
7274

75+
/** A mock iframe whose document holds one GSAP script and one composition root; `byId` answers id selectors. */
76+
function iframeWithComposition(script: string, root: Element, byId: Record<string, Element> = {}) {
77+
const scriptEl = document.createElement("script");
78+
scriptEl.textContent = script;
79+
const container = document.createElement("div");
80+
container.appendChild(scriptEl);
81+
const { iframe } = buildMockIframe({ gsap: { timeline: vi.fn(), set: vi.fn() } });
82+
(iframe as unknown as { contentDocument: unknown }).contentDocument = {
83+
querySelectorAll: (sel: string) =>
84+
sel === "script:not([src])"
85+
? [scriptEl]
86+
: sel.includes("composition-id")
87+
? [root]
88+
: byId[sel]
89+
? [byId[sel]]
90+
: [],
91+
createElement: (tag: string) => document.createElement(tag),
92+
body: container,
93+
head: document.createElement("div"),
94+
};
95+
return iframe;
96+
}
97+
7398
describe("applySoftReload", () => {
7499
it('returns "cannot-soft-reload" when iframe is null', () => {
75100
expect(applySoftReload(null, SCRIPT_TEXT)).toBe("cannot-soft-reload");
@@ -127,30 +152,51 @@ describe("applySoftReload", () => {
127152
orphan.style.cssText = "left: 1240px; top: 200px; transform: translate(449px, 0px)";
128153
Object.assign(orphan, { _gsap: {} }); // GSAP cache marker (set by gsap.set)
129154

130-
const scriptEl = document.createElement("script");
131-
scriptEl.textContent = 'const tl = gsap.timeline({ paused: true }); tl.to("#x", { x: 1 });';
132-
const container = document.createElement("div");
133-
container.appendChild(scriptEl);
134-
135155
const root = document.createElement("div");
136156
root.setAttribute("data-composition-id", "root");
137157
root.appendChild(orphan);
138-
139-
const { iframe } = buildMockIframe({ gsap: { timeline: vi.fn(), set: vi.fn() } });
140-
(iframe as unknown as { contentDocument: unknown }).contentDocument = {
141-
querySelectorAll: (sel: string) =>
142-
sel === "script:not([src])" ? [scriptEl] : sel.includes("composition-id") ? [root] : [],
143-
createElement: (tag: string) => document.createElement(tag),
144-
body: container,
145-
head: document.createElement("div"),
146-
};
158+
const iframe = iframeWithComposition(
159+
'const tl = gsap.timeline({ paused: true }); tl.to("#x", { x: 1 });',
160+
root,
161+
);
147162

148163
applySoftReload(iframe, SCRIPT_TEXT);
149164

150165
expect(orphan.style.transform).toBe(""); // stale GSAP transform stripped
151166
expect(orphan.style.left).toBe("1240px"); // authored CSS base preserved
152167
});
153168

169+
it("clears what a standalone gsap.set wrote once the new script no longer sets it", () => {
170+
// An undo of a Design-panel W edit on an animated box removes its gsap.set width.
171+
const target = document.createElement("div");
172+
target.id = "target";
173+
target.style.cssText = "left: 10px; width: 300px";
174+
Object.assign(target, { _gsap: {} });
175+
const root = document.createElement("div");
176+
root.setAttribute("data-composition-id", "root");
177+
root.appendChild(target);
178+
const iframe = iframeWithComposition(
179+
`window.__timelines = window.__timelines || {};
180+
const tl = gsap.timeline({ paused: true });
181+
tl.to("#target", { x: 100 });
182+
gsap.set("#target", { width: 300 });
183+
window.__timelines["root"] = tl;`,
184+
root,
185+
{ "#target": target },
186+
);
187+
const restored = `window.__timelines = window.__timelines || {};
188+
const tl = gsap.timeline({ paused: true });
189+
tl.to("#target", { x: 100 });
190+
window.__timelines["root"] = tl;`;
191+
192+
applySoftReload(iframe, restored, {
193+
authoredHtml: `<html><body><div data-composition-id="root"><div id="target" style="left: 10px"></div></div><script>${restored}</script></body></html>`,
194+
});
195+
196+
expect(target.style.width).toBe("");
197+
expect(target.style.left).toBe("10px");
198+
});
199+
154200
it("wraps execution in __hfSuppressSceneMutations when available", () => {
155201
let suppressionCalled = false;
156202
const { iframe } = buildMockIframe({
@@ -917,3 +963,41 @@ describe("applySoftReload over a composition's own markup", () => {
917963
expect(applySoftReload(iframe, SCRIPT_TEXT)).toBe("cannot-soft-reload");
918964
});
919965
});
966+
967+
describe("a gsap.set a live patch applied", () => {
968+
it("is cleared by the next soft reload once the new script no longer sets it, and only once", () => {
969+
const markup = `<div data-composition-id="root"><div id="a" style="left: 10px"></div></div>`;
970+
const doc = document.implementation.createHTMLDocument("");
971+
doc.body.innerHTML = `${markup}<script>window.__timelines["root"]=gsap.timeline();</script>`;
972+
const set = (target: HTMLElement | HTMLElement[], vars: Record<string, unknown>) => {
973+
for (const el of [target].flat()) {
974+
if (vars.clearProps) el.removeAttribute("style");
975+
else for (const [k, v] of Object.entries(vars)) el.style.setProperty(k, `${v}px`);
976+
}
977+
};
978+
const iframe = {
979+
contentDocument: doc,
980+
contentWindow: {
981+
gsap: { timeline: () => {}, set },
982+
__hfForceTimelineRebind: () => {},
983+
__timelines: {},
984+
__player: { getTime: () => 0, seek: () => {} },
985+
},
986+
} as unknown as HTMLIFrameElement;
987+
const el = doc.getElementById("a")!;
988+
const reload = () => {
989+
const script = `window.__timelines["root"]=gsap.timeline();gsap.set("#a",{width:300});`;
990+
applySoftReload(iframe, script, { authoredHtml: `${markup}<script>${script}</script>` });
991+
};
992+
993+
// W 300, then H 200, then a commit that removes height from the set.
994+
patchRuntimeTweenInPlace(iframe, "#a", { kind: "global-set", props: { width: 300 } });
995+
patchRuntimeTweenInPlace(iframe, "#a", { kind: "global-set", props: { height: 200 } });
996+
reload();
997+
expect([el.style.height, el.style.left]).toEqual(["", "10px"]);
998+
999+
el.style.height = "50px";
1000+
reload();
1001+
expect(el.style.height).toBe("50px");
1002+
});
1003+
});

‎packages/studio/src/utils/gsapSoftReload.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-gradin
22
import { motionPathPluginUrl } from "@hyperframes/core/gsap-cdn";
33
import { findAuthoredElement } from "./authoredSource";
44
import { applyAuthoredInlineOpacity, readStampedAuthoredOpacity } from "./authoredOpacity";
5-
import { authoringFile, collectResetTargets, compositionFile, fileDocs } from "./softReloadTargets";
5+
import {
6+
authoringFile,
7+
collectResetTargets,
8+
compositionFile,
9+
fileDocs,
10+
forgetLiveSets,
11+
} from "./softReloadTargets";
612

713
type IframeWindow = Window & {
814
__timelines?: Record<string, { kill?: () => void; pause?: () => void }>;
@@ -370,7 +376,12 @@ export function applySoftReload(
370376
// fallow-ignore-next-line complexity
371377
const doReload = () => {
372378
const timelines = win.__timelines;
373-
const targets = collectResetTargets(win, doc, targetKeys);
379+
const targets = collectResetTargets(
380+
win,
381+
doc,
382+
targetKeys,
383+
staleScripts.map((script) => script.textContent ?? ""),
384+
);
374385

375386
// Kill ONLY the target composition's timeline(s) — leaving every other
376387
// composition's timeline (and its children on the global timeline) intact.
@@ -423,6 +434,7 @@ export function applySoftReload(
423434
}
424435
}
425436
}
437+
forgetLiveSets(targets);
426438

427439
for (const script of staleScripts) script.remove();
428440

0 commit comments

Comments
 (0)