Skip to content

Commit 5d1caff

Browse files
committed
fix(studio): address review findings on graded-element editing
Review follow-ups (both reviewers, all findings): - resize captures scope to the resize group: convert-to-keyframes resolvedFromValues and the whole-offset backfill pass the group filter, so an opacity-touching intro tween can't ride into a converted scale tween (the rotation fix's contract, now uniform across intercepts) - commitStaticSet resolves every group's target set BEFORE committing and coalesces groups landing on the same legacy mixed set into one commit — the second commit can no longer chase a stale group-derived id - installAuthoredOpacityCapture also stamps an element the moment it GAINS data-color-grading at runtime (attributeFilter), not just at insertion - both writer twins now share the same emitted-set dedupe shape - applySoftReload's positional tail becomes a SoftReloadOptions object - readAllAnimatedProperties builds the group-filtered key set immutably instead of deleting from the set mid-iteration - applyAuthoredInlineOpacity documents the priority-lossy round-trip - the marquee hit-test reads activeCompositionPathRef like its neighbors New tests: resize intercept (scale route + group filter + non-uniform longhands), after-write-HTML / stamp / empty-stamp opacity restore, the no-op-commit-with-missed-instant-patch soft-reload contract, and the runtime-gained-grading stamp.
1 parent 67cfae2 commit 5d1caff

13 files changed

Lines changed: 367 additions & 88 deletions

‎packages/core/src/runtime/colorGrading.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,4 +643,26 @@ describe("installAuthoredOpacityCapture", () => {
643643
expect(el.getAttribute("data-hf-authored-opacity")).toBe("");
644644
el.remove();
645645
});
646+
647+
it("stamps an already-inserted element the moment it GAINS grading at runtime", async () => {
648+
installAuthoredOpacityCapture();
649+
const el = document.createElement("img");
650+
el.style.opacity = "0.9";
651+
document.body.appendChild(el);
652+
await Promise.resolve();
653+
expect(el.hasAttribute("data-hf-authored-opacity")).toBe(false);
654+
655+
// Studio applies a preset to a previously ungraded element — no re-insert.
656+
el.setAttribute(HF_COLOR_GRADING_ATTR, serializeHfColorGrading({ adjust: { exposure: 0.5 } }));
657+
await Promise.resolve();
658+
expect(el.getAttribute("data-hf-authored-opacity")).toBe("0.9");
659+
660+
// Later attribute rewrites (preset tweaks) never overwrite the stamp,
661+
// even if a transient is live by then.
662+
el.style.opacity = "0";
663+
el.setAttribute(HF_COLOR_GRADING_ATTR, serializeHfColorGrading({ adjust: { exposure: 0.9 } }));
664+
await Promise.resolve();
665+
expect(el.getAttribute("data-hf-authored-opacity")).toBe("0.9");
666+
el.remove();
667+
});
646668
});

‎packages/core/src/runtime/colorGrading.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,21 @@ export function installAuthoredOpacityCapture(): void {
239239
new MutationObserver((mutations) => {
240240
for (const mutation of mutations) {
241241
for (const node of mutation.addedNodes) scan(node);
242+
// An element can also GAIN grading at runtime (studio applies a preset to
243+
// a previously ungraded element). Stamp at that moment — strictly earlier
244+
// than the engine's hide, so the captured value can never be worse than
245+
// the hide-time fallback, and after a soft reload's authored restore it
246+
// IS the authored value. stamp() is idempotent: an existing stamp wins.
247+
if (mutation.type === "attributes" && mutation.target instanceof Element) {
248+
if (mutation.target.hasAttribute(HF_COLOR_GRADING_ATTR)) stamp(mutation.target);
249+
}
242250
}
243-
}).observe(root, { childList: true, subtree: true });
251+
}).observe(root, {
252+
childList: true,
253+
subtree: true,
254+
attributes: true,
255+
attributeFilter: [HF_COLOR_GRADING_ATTR],
256+
});
244257
}
245258

246259
// Map insertion order gives us simple FIFO eviction for authoring sessions that cycle LUTs.

‎packages/parsers/src/gsapWriterAcorn.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,15 @@ function buildTweenStatementCode(timelineVar: string, anim: Omit<GsapAnimation,
5757
if (anim.method !== "set" && anim.duration !== undefined) props.duration = anim.duration;
5858
if (anim.ease) props.ease = anim.ease;
5959
const entries = Object.entries(props).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);
60+
const emitted = new Set(Object.keys(props));
6061
if (anim.extras) {
6162
for (const [k, v] of Object.entries(anim.extras)) {
6263
// A key carried by both properties and extras (a set's parsed
63-
// `immediateRender: true`) must emit once — properties win.
64-
if (!(k in props)) entries.push(`${safeKey(k)}: ${valueToCode(v)}`);
64+
// `immediateRender: true`) must emit once — properties win. Same
65+
// dedupe shape as the recast twin (gsapParser.ts buildTweenStatementCode).
66+
if (emitted.has(k)) continue;
67+
emitted.add(k);
68+
entries.push(`${safeKey(k)}: ${valueToCode(v)}`);
6569
}
6670
}
6771
const objCode = `{ ${entries.join(", ")} }`;

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,12 @@ export const DomEditOverlay = memo(function DomEditOverlay({
315315
if (!hoverSelectionRef.current && onMarqueeSelectRef.current && compRect.width > 0) {
316316
const iframe = iframeRef.current;
317317
const freshTarget = iframe
318-
? getPreviewTargetFromPointer(iframe, event.clientX, event.clientY, activeCompositionPath)
318+
? getPreviewTargetFromPointer(
319+
iframe,
320+
event.clientX,
321+
event.clientY,
322+
activeCompositionPathRef.current,
323+
)
319324
: null;
320325
if (freshTarget) return;
321326
const overlayEl = overlayRef.current;
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// @vitest-environment happy-dom
2+
import { afterEach, expect, it, vi } from "vitest";
3+
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
4+
import type { DomEditSelection } from "../components/editor/domEditingTypes";
5+
import { usePlayerStore } from "../player/store/playerStore";
6+
import { tryGsapResizeIntercept } from "./gsapResizeIntercept";
7+
8+
afterEach(() => {
9+
vi.restoreAllMocks();
10+
usePlayerStore.setState({ currentTime: 0, activeKeyframePct: null });
11+
});
12+
13+
/**
14+
* Scale-route resize: an element whose visual size is driven by a scale-group
15+
* tween. The intercept must (a) route the commit through SCALE, never
16+
* width/height, and (b) resolve convert-to-keyframes from-values through the
17+
* group filter — an opacity-touching intro tween on the same element must not
18+
* ride into the converted keyframes (the disappearance bake class).
19+
*/
20+
function makeGradedElement(): HTMLElement {
21+
const el = document.createElement("img");
22+
el.id = "clip";
23+
el.setAttribute("data-hf-studio-original-width", "640");
24+
el.setAttribute("data-hf-studio-original-height", "360");
25+
// Grading contract: source hidden, canvas carries effective opacity.
26+
el.setAttribute("data-hf-color-grading-source-hidden", "");
27+
const canvas = document.createElement("canvas");
28+
canvas.id = "__hf_color_grading_clip";
29+
canvas.style.opacity = "0.98";
30+
document.body.append(el, canvas);
31+
return el;
32+
}
33+
34+
function fakeIframe(el: HTMLElement, gsapValues: Record<string, number>) {
35+
// The element's OPACITY intro tween lives on the timeline: unfiltered
36+
// capture would pick `opacity` up via the other-tween sweep.
37+
const opacityIntro = { targets: () => [el], vars: { opacity: 0, duration: 0.8 } };
38+
return {
39+
contentWindow: {
40+
__timelines: { main: { getChildren: () => [opacityIntro] } },
41+
gsap: { getProperty: (_el: Element, prop: string) => gsapValues[prop] ?? 0 },
42+
},
43+
contentDocument: document,
44+
} as unknown as HTMLIFrameElement;
45+
}
46+
47+
function scaleFromTween(): GsapAnimation {
48+
return {
49+
id: "#clip-from-200-scale",
50+
targetSelector: "#clip",
51+
propertyGroup: "scale",
52+
method: "from",
53+
properties: { scale: 0.9 },
54+
position: 0.2,
55+
resolvedStart: 0.2,
56+
duration: 0.8,
57+
} as unknown as GsapAnimation;
58+
}
59+
60+
function keyframedScaleFixture(): GsapAnimation {
61+
return {
62+
...scaleFromTween(),
63+
keyframes: {
64+
keyframes: [
65+
{ percentage: 0, properties: { scale: 0.9 } },
66+
{ percentage: 100, properties: { scale: 1 } },
67+
],
68+
},
69+
} as unknown as GsapAnimation;
70+
}
71+
72+
/** Drive one resize through the intercept, returning every committed mutation. */
73+
async function runResize(
74+
el: HTMLElement,
75+
iframe: HTMLIFrameElement,
76+
size: { width: number; height: number },
77+
): Promise<Array<Record<string, unknown>>> {
78+
const selection = { id: "clip", selector: "#clip", element: el } as unknown as DomEditSelection;
79+
usePlayerStore.setState({ currentTime: 0.5 }); // inside the tween's range
80+
const committed: Array<Record<string, unknown>> = [];
81+
const commitMutation = vi.fn(async (_sel: unknown, mutation: Record<string, unknown>) => {
82+
committed.push(mutation);
83+
});
84+
const handled = await tryGsapResizeIntercept(
85+
selection,
86+
size,
87+
[scaleFromTween()],
88+
iframe,
89+
commitMutation as never,
90+
async () => [keyframedScaleFixture()],
91+
);
92+
expect(handled).toBe(true);
93+
return committed;
94+
}
95+
96+
it("scale-route resize converts via the group filter and commits scale, not width/height", async () => {
97+
const el = makeGradedElement();
98+
const iframe = fakeIframe(el, { scale: 1, scaleX: 1, scaleY: 1, opacity: 0, rotation: 0 });
99+
// uniform: 800/640 === 450/360
100+
const committed = await runResize(el, iframe, { width: 800, height: 450 });
101+
102+
const convert = committed.find((m) => m.type === "convert-to-keyframes");
103+
expect(convert).toBeDefined();
104+
const fromValues = convert!.resolvedFromValues as Record<string, number>;
105+
// Group filter: the opacity intro tween must NOT leak into the conversion.
106+
expect(fromValues).not.toHaveProperty("opacity");
107+
expect(fromValues).toHaveProperty("scale");
108+
109+
// Every committed property is scale-group — the resize never writes
110+
// width/height for a scale-driven element (the double-apply bug class).
111+
const allProps = committed.flatMap((m) => [
112+
...Object.keys((m.properties as Record<string, unknown>) ?? {}),
113+
...Object.keys((m.resolvedFromValues as Record<string, unknown>) ?? {}),
114+
]);
115+
expect(allProps).not.toContain("width");
116+
expect(allProps).not.toContain("height");
117+
expect(allProps.some((p) => p === "scale" || p === "scaleX")).toBe(true);
118+
});
119+
120+
it("non-uniform drag commits scaleX/scaleY longhands", async () => {
121+
const el = makeGradedElement();
122+
const iframe = fakeIframe(el, { scale: 1, scaleX: 1, scaleY: 1, opacity: 0 });
123+
// scaleX 1.25 vs scaleY 1.0 → non-uniform
124+
const committed = await runResize(el, iframe, { width: 800, height: 360 });
125+
126+
const serialized = JSON.stringify(committed);
127+
expect(serialized).toContain("scaleX");
128+
expect(serialized).toContain("scaleY");
129+
});

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,12 @@ export async function tryGsapResizeIntercept(
106106
const coalesceKey = `gsap:resize:${anim.id}`;
107107

108108
const selector = selectorFromSelection(selection);
109-
const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {};
109+
// Scope every capture to the resize group — same contract as the rotation
110+
// intercept. Unfiltered, an opacity-touching intro tween on the element
111+
// would ride into resize conversions/backfills (the Fix-2 bake class).
112+
const runtimeProps = selector
113+
? readAllAnimatedProperties(iframe, selector, anim, resizeGroup)
114+
: {};
110115

111116
let resizeProps: Record<string, number>;
112117
let scaleDraftEl: HTMLElement | null = null;
@@ -254,7 +259,7 @@ export async function tryGsapResizeIntercept(
254259
if (newId) anim = { ...anim, id: newId };
255260
} else if (!anim.keyframes) {
256261
const resolvedFromValues = selector
257-
? readAllAnimatedProperties(iframe, selector, anim)
262+
? readAllAnimatedProperties(iframe, selector, anim, resizeGroup)
258263
: undefined;
259264
await commitMutation(
260265
selection,

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,9 @@ export function readAllAnimatedProperties(
106106
// point of property-group tweens is that a rotation commit never carries
107107
// opacity/rotationX/etc. captured from unrelated tweens on the element.
108108
const inGroup = (p: string) => !group || classifyPropertyGroup(p) === group;
109-
for (const p of propKeys) {
110-
if (!inGroup(p)) propKeys.delete(p);
111-
}
109+
const groupedPropKeys = new Set([...propKeys].filter(inGroup));
112110

113-
for (const prop of propKeys) {
111+
for (const prop of groupedPropKeys) {
114112
const val = readLiveGsapValue(gsap, el, prop);
115113
if (Number.isFinite(val)) {
116114
result[prop] = POSITION_PROPS.has(prop) ? Math.round(val) : roundTo3(val);
@@ -142,7 +140,7 @@ export function readAllAnimatedProperties(
142140
}
143141
}
144142
} catch {}
145-
for (const p of propKeys) otherTweenProps.delete(p);
143+
for (const p of groupedPropKeys) otherTweenProps.delete(p);
146144

147145
// Tier 1: Transform + visual properties with universal CSS defaults.
148146
// Safe to compare against hardcoded values — these are always 0 or 1
@@ -174,7 +172,7 @@ export function readAllAnimatedProperties(
174172
// Collect all properties that ANY tween on this element explicitly targets.
175173
// Only capture baseline values for these — GSAP reports non-default values
176174
// (scaleZ=0, brightness=0) for untouched properties, polluting keyframes.
177-
const allTweenedProps = new Set([...propKeys, ...otherTweenProps]);
175+
const allTweenedProps = new Set([...groupedPropKeys, ...otherTweenProps]);
178176
for (const [prop, defaultVal] of Object.entries(UNIVERSAL_BASELINE)) {
179177
if (prop in result) continue;
180178
if (!allTweenedProps.has(prop)) continue;

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

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -186,19 +186,40 @@ async function commitStaticSet(
186186
byGroup.set(group, batch);
187187
}
188188
const sets = animations.filter((a) => a.method === "set" && a.targetSelector === selector);
189+
// Resolve every group's target BEFORE committing anything, and coalesce
190+
// groups that land on the SAME set into one commit: the `sets` snapshot is
191+
// captured once, so if two groups resolved to one legacy mixed set, a first
192+
// commit could re-shape it server-side and leave the second chasing a stale
193+
// id (404 on legacy pre-split files).
194+
const byTargetSet = new Map<GsapAnimation, [string, number | string][]>();
195+
const newSetBatches: [string, number | string][][] = [];
189196
for (const [group, batch] of byGroup) {
190-
const existingSet =
191-
// A set already dedicated to this group wins; else a mixed set that
192-
// already carries a property of this group (merging same-group values
193-
// there beats spawning a second writer for the same channel).
194-
sets.find((a) => a.propertyGroup === group) ??
195-
sets.find((a) => Object.keys(a.properties).some((k) => classifyPropertyGroup(k) === group));
197+
const existingSet = findGroupOwningSet(sets, group);
196198
if (existingSet) {
197-
await commitSetProps(selection, existingSet, batch, selector, animations, commit);
199+
byTargetSet.set(existingSet, [...(byTargetSet.get(existingSet) ?? []), ...batch]);
198200
} else {
199-
await addGlobalStaticSet(selection, batch, selector, commit);
201+
newSetBatches.push(batch);
200202
}
201203
}
204+
for (const [targetSet, batch] of byTargetSet) {
205+
await commitSetProps(selection, targetSet, batch, selector, animations, commit);
206+
}
207+
// Fresh adds don't reshape existing sets, so their ids can't go stale.
208+
for (const batch of newSetBatches) {
209+
await addGlobalStaticSet(selection, batch, selector, commit);
210+
}
211+
}
212+
213+
/**
214+
* The set that owns a property group: one already dedicated to the group wins;
215+
* else a mixed set that already carries a property of the group (merging
216+
* same-group values there beats spawning a second writer for the channel).
217+
*/
218+
function findGroupOwningSet(sets: GsapAnimation[], group: string): GsapAnimation | undefined {
219+
return (
220+
sets.find((a) => a.propertyGroup === group) ??
221+
sets.find((a) => Object.keys(a.properties).some((k) => classifyPropertyGroup(k) === group))
222+
);
202223
}
203224

204225
/**

0 commit comments

Comments
 (0)