Skip to content

Commit 37140af

Browse files
committed
fix(studio): target one element when adding a keyframe at the playhead
"Add keyframe at playhead" on an element with no id authored the bare class buildStableSelector hands back, so one add on a `.group` wrote `tl.to(".group", ...)`: a tween that animates all five siblings and that resolveSelectorElementIds reads back as all five, collapsing their timeline rows into one. It survived a reload, so the written file stayed un-editable. writeTargetSelector is the write-side counterpart to selectorFromSelection (which must keep returning the exact string findTweenAtTime compares against). It resolves the element's own identity to a selector that addresses exactly one element: `#id`, else `[data-hf-id="..."]`, else the selection's selector when it is already unique, else a `:nth-child` path anchored on the nearest identifiable ancestor (the selector + selectorIndex pair, resolved through the DOM the index was counted in). Applied to the two paths that author a NEW tween: the no-animation branch of useEnableKeyframes and commitKeyframeAtTimeImpl. replace-with-keyframes still writes the selection's own selector, since retargeting a tween the author aimed at a whole group is a different decision from adding a keyframe.
1 parent 59a818e commit 37140af

5 files changed

Lines changed: 281 additions & 3 deletions

File tree

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
22
import type { DomEditSelection } from "../components/editor/domEditingTypes";
33
import { absoluteToPercentageForAnimation, findTweenAtTime } from "../utils/globalTimeCompiler";
4-
import { PROPERTY_DEFAULTS, selectorFromSelection } from "./gsapShared";
4+
import { PROPERTY_DEFAULTS, selectorFromSelection, writeTargetSelector } from "./gsapShared";
55
import { roundToCenti } from "../utils/rounding";
66

77
type CommitFn = (
@@ -22,6 +22,9 @@ export async function commitKeyframeAtTimeImpl(
2222
properties: Record<string, number | string>,
2323
commitMutation: CommitFn,
2424
): Promise<void> {
25+
// Matching an authored tween is a string compare against what the author
26+
// wrote, so it keeps using the selection's own selector; the NEW tween below
27+
// is authored with the one-element form instead.
2528
const selector = selectorFromSelection(selection);
2629
if (!selector) return;
2730

@@ -65,7 +68,7 @@ export async function commitKeyframeAtTimeImpl(
6568
selection,
6669
{
6770
type: "add-with-keyframes" as const,
68-
targetSelector: selector,
71+
targetSelector: writeTargetSelector(selection) ?? selector,
6972
position: absoluteTime,
7073
duration: defaultDuration,
7174
keyframes: [

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,86 @@ export function selectorFromSelection(selection: DomEditSelection): string | nul
181181
return null;
182182
}
183183

184+
/** `[name="value"]`, with the quote/backslash escaping a CSS string needs. */
185+
function attributeSelector(name: string, value: string): string {
186+
return `[${name}="${value.replace(/(["\\])/g, "\\$1")}"]`;
187+
}
188+
189+
function matchesExactlyOne(doc: Document, selector: string, element: Element): boolean {
190+
try {
191+
const matches = doc.querySelectorAll(selector);
192+
return matches.length === 1 && matches[0] === element;
193+
} catch {
194+
return false;
195+
}
196+
}
197+
198+
/**
199+
* A structural address for an element that carries no identity of its own:
200+
* `:nth-child` steps up to the nearest ancestor that IS uniquely addressable
201+
* (an id or a data-hf-id). This is the `selector` + `selectorIndex` pair the
202+
* selection already carries, resolved through the live DOM the index was
203+
* counted in — an index can't be spelled in CSS, but the element's position can.
204+
*/
205+
function structuralSelector(element: Element): string | null {
206+
const doc = element.ownerDocument;
207+
if (!doc) return null;
208+
const parts: string[] = [];
209+
for (let node: Element | null = element; node; node = node.parentElement) {
210+
if (node !== element) {
211+
const id = node instanceof HTMLElement ? node.id : "";
212+
const hfId = node.getAttribute("data-hf-id");
213+
if (id) {
214+
parts.unshift(idSelector(id));
215+
break;
216+
}
217+
if (hfId) {
218+
parts.unshift(attributeSelector("data-hf-id", hfId));
219+
break;
220+
}
221+
}
222+
const parent = node.parentElement;
223+
if (!parent) break;
224+
const index = Array.prototype.indexOf.call(parent.children, node) + 1;
225+
if (index < 1) return null;
226+
parts.unshift(`${node.tagName.toLowerCase()}:nth-child(${index})`);
227+
}
228+
if (parts.length === 0) return null;
229+
const selector = parts.join(" > ");
230+
return matchesExactlyOne(doc, selector, element) ? selector : null;
231+
}
232+
233+
/**
234+
* The selector to author a NEW tween with. Distinct from
235+
* {@link selectorFromSelection}, which must keep returning the exact string an
236+
* already-authored tween is string-matched against (findTweenAtTime): this one
237+
* has to ADDRESS ONE ELEMENT.
238+
*
239+
* `buildStableSelector` hands back a bare class for any element without an id,
240+
* so "add keyframe at playhead" on one of five `.group` siblings wrote
241+
* `tl.set(".group", …)` — a tween that animates all five and that
242+
* {@link resolveSelectorElementIds} reads back as all five, collapsing their
243+
* timeline rows into one. Every rung below resolves to exactly one element.
244+
*
245+
* ponytail: the last rung returns the bare selector unchanged rather than null.
246+
* Refusing to write would turn a mis-targeted add into a silently dead button;
247+
* it is only reachable with no live DOM to disambiguate against.
248+
*/
249+
export function writeTargetSelector(selection: DomEditSelection): string | null {
250+
if (selection.id) return idSelector(selection.id);
251+
if (selection.hfId) return attributeSelector("data-hf-id", selection.hfId);
252+
const element = selection.element;
253+
const doc = element?.ownerDocument;
254+
if (element && doc) {
255+
if (selection.selector && matchesExactlyOne(doc, selection.selector, element)) {
256+
return selection.selector;
257+
}
258+
const structural = structuralSelector(element);
259+
if (structural) return structural;
260+
}
261+
return selection.selector ?? null;
262+
}
263+
184264
// ── Percentage computation ────────────────────────────────────────────────────
185265

186266
/**
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { parseGsapScript } from "@hyperframes/core/gsap-parser";
4+
import { addAnimationWithKeyframesToScript } from "@hyperframes/parsers/gsap-writer-acorn";
5+
import type { DomEditSelection } from "../components/editor/domEditingTypes";
6+
import { buildStableSelector, getSelectorIndex } from "../components/editor/domEditingDom";
7+
import { resolveSelectorElementIds, writeTargetSelector } from "./gsapShared";
8+
import { commitKeyframeAtTimeImpl } from "./gsapKeyframeCommit";
9+
10+
afterEach(() => {
11+
document.body.innerHTML = "";
12+
});
13+
14+
/**
15+
* A selection built the way production builds it (getDomLayerPatchTarget), so
16+
* the class-only case under test is the real one: buildStableSelector hands back
17+
* a BARE class for an element with no id / hf-id / composition id.
18+
*/
19+
function selectionFor(el: HTMLElement): DomEditSelection {
20+
const selector = buildStableSelector(el);
21+
return {
22+
element: el,
23+
id: el.id || undefined,
24+
hfId: el.getAttribute("data-hf-id") || undefined,
25+
selector,
26+
selectorIndex: getSelectorIndex(document, el, selector, "index.html", null),
27+
sourceFile: "index.html",
28+
dataAttributes: { start: "0", duration: "2" },
29+
} as unknown as DomEditSelection;
30+
}
31+
32+
/** Five class-only siblings — the shape that made one add collapse the timeline. */
33+
function mountGroupSiblings(): HTMLElement[] {
34+
document.body.innerHTML = `
35+
<div id="scene" class="clip" data-start="0" data-duration="2">
36+
<div class="group"></div>
37+
<div class="group"></div>
38+
<div class="group"></div>
39+
<div class="group"></div>
40+
<div class="group"></div>
41+
</div>
42+
`;
43+
return Array.from(document.querySelectorAll<HTMLElement>(".group"));
44+
}
45+
46+
const BASE_SCRIPT = `
47+
const tl = gsap.timeline({ paused: true });
48+
tl.to("#scene", { opacity: 1, duration: 0.5 }, 0);
49+
`.trim();
50+
51+
const KEYFRAMES = [
52+
{ percentage: 0, properties: { x: 0 } },
53+
{ percentage: 100, properties: { x: 40 } },
54+
];
55+
56+
/** Author the selector into a real script and read the tween's targets back. */
57+
function roundTripTargets(selector: string): { script: string; targets: string[] } {
58+
const { script } = addAnimationWithKeyframesToScript(BASE_SCRIPT, selector, 0, 1, KEYFRAMES);
59+
const added = parseGsapScript(script).animations.find((a) => a.targetSelector === selector);
60+
if (!added) throw new Error(`written selector did not re-parse: ${selector}`);
61+
return { script, targets: resolveSelectorElementIds(added.targetSelector, document) };
62+
}
63+
64+
describe("writeTargetSelector", () => {
65+
it("addresses exactly one element when the only identity is a shared class", () => {
66+
const groups = mountGroupSiblings();
67+
const selection = selectionFor(groups[2]);
68+
69+
// Precondition: this is the defect's input — a bare class hitting all five.
70+
expect(selection.selector).toBe(".group");
71+
expect(document.querySelectorAll(".group")).toHaveLength(5);
72+
73+
const written = writeTargetSelector(selection);
74+
75+
expect(written).toBeTruthy();
76+
expect(document.querySelectorAll(written!)).toHaveLength(1);
77+
expect(document.querySelector(written!)).toBe(groups[2]);
78+
});
79+
80+
it("keeps a unique #id target", () => {
81+
document.body.innerHTML = `<div id="box" class="card"></div>`;
82+
const el = document.querySelector<HTMLElement>("#box")!;
83+
84+
expect(writeTargetSelector(selectionFor(el))).toBe("#box");
85+
});
86+
87+
it("prefers data-hf-id over a generated structural selector", () => {
88+
document.body.innerHTML = `
89+
<div id="scene"><div class="group"></div><div class="group" data-hf-id="hf-42"></div></div>
90+
`;
91+
const el = document.querySelectorAll<HTMLElement>(".group")[1]!;
92+
93+
const written = writeTargetSelector(selectionFor(el));
94+
95+
expect(written).toBe('[data-hf-id="hf-42"]');
96+
expect(document.querySelector(written!)).toBe(el);
97+
});
98+
99+
it("keeps an already-unique class selector as authored", () => {
100+
document.body.innerHTML = `<div id="scene"><div class="header"></div></div>`;
101+
const el = document.querySelector<HTMLElement>(".header")!;
102+
103+
expect(writeTargetSelector(selectionFor(el))).toBe(".header");
104+
});
105+
});
106+
107+
describe("writeTargetSelector — write/read round trip", () => {
108+
it("re-parses and attributes the new tween to the one element it targeted", () => {
109+
const groups = mountGroupSiblings();
110+
// Ids let resolveSelectorElementIds name the attributed elements; the
111+
// SELECTION still has none, so the write path still faces the bare class.
112+
groups.forEach((el, i) => el.setAttribute("id", `group-${i}`));
113+
const selection = { ...selectionFor(groups[2]), id: undefined } as DomEditSelection;
114+
115+
const written = writeTargetSelector(selection);
116+
const { targets } = roundTripTargets(written!);
117+
118+
expect(targets).toEqual(["group-2"]);
119+
});
120+
121+
it("does not widen the add to the element's four class siblings", () => {
122+
const groups = mountGroupSiblings();
123+
groups.forEach((el, i) => el.setAttribute("id", `group-${i}`));
124+
const selection = { ...selectionFor(groups[0]), id: undefined } as DomEditSelection;
125+
126+
// The old bare-class write attributed the one add to every sibling — the
127+
// attribution blow-up behind "one add collapsed the timeline to a single row".
128+
expect(roundTripTargets(".group").targets).toHaveLength(5);
129+
130+
expect(roundTripTargets(writeTargetSelector(selection)!).targets).toHaveLength(1);
131+
});
132+
});
133+
134+
describe("commitKeyframeAtTimeImpl — new-tween target", () => {
135+
it("authors a one-element selector when no tween exists at the playhead", async () => {
136+
const groups = mountGroupSiblings();
137+
const selection = selectionFor(groups[3]);
138+
const commitMutation = vi.fn(async () => undefined);
139+
140+
await commitKeyframeAtTimeImpl(selection, 1, [], { x: 12 }, commitMutation);
141+
142+
const mutation = commitMutation.mock.calls[0]?.[1] as { targetSelector: string };
143+
expect(mutation.targetSelector).not.toBe(".group");
144+
expect(document.querySelectorAll(mutation.targetSelector)).toHaveLength(1);
145+
expect(document.querySelector(mutation.targetSelector)).toBe(groups[3]);
146+
});
147+
});

‎packages/studio/src/hooks/useEnableKeyframes.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,3 +466,47 @@ describe("useEnableKeyframes — flat tween transaction", () => {
466466
});
467467
});
468468
});
469+
470+
describe("useEnableKeyframes — new tween on a class-only element", () => {
471+
it("targets the selected sibling alone, not every element sharing its class", async () => {
472+
window.location.hash = "#/project/test-project";
473+
usePlayerStore.setState({ currentTime: 1 });
474+
vi.stubGlobal(
475+
"fetch",
476+
vi.fn(async () => ({ ok: true, json: async () => ({ animations: [] }) })),
477+
);
478+
const scene = document.body.appendChild(document.createElement("div"));
479+
scene.id = "scene";
480+
scene.innerHTML = '<i class="group"></i>'.repeat(5);
481+
const groups = Array.from(scene.querySelectorAll<HTMLElement>(".group"));
482+
const commitMutation = vi.fn(async () => undefined);
483+
const enable = renderEnableKeyframes({
484+
// A bare `.group` here writes `tl.to(".group", …)`, which animates all five
485+
// siblings and reads back as all five — one add wiped the timeline.
486+
domEditSelection: {
487+
selector: ".group",
488+
selectorIndex: 3,
489+
sourceFile: "index.html",
490+
element: groups[3],
491+
dataAttributes: { start: "0", duration: "2" },
492+
} as unknown as DomEditSelection,
493+
selectedGsapAnimations: [],
494+
previewIframeRef: {
495+
current: {
496+
contentWindow: { gsap: { getProperty: () => 7 } },
497+
} as unknown as HTMLIFrameElement,
498+
},
499+
handleGsapAddAnimation: vi.fn(),
500+
handleGsapConvertToKeyframes: vi.fn(),
501+
handleGsapRemoveKeyframe: vi.fn(),
502+
commitMutation,
503+
});
504+
505+
await act(async () => enable());
506+
507+
const mutation = commitMutation.mock.calls[0]?.[0] as { targetSelector: string };
508+
expect(mutation?.targetSelector).toBeTruthy();
509+
expect(document.querySelectorAll(mutation.targetSelector)).toHaveLength(1);
510+
expect(document.querySelector(mutation.targetSelector)).toBe(groups[3]);
511+
});
512+
});

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
KEYFRAME_PCT_MATCH,
1919
isInstantHold,
2020
resolveEditableTweenDuration,
21+
writeTargetSelector,
2122
} from "./gsapShared";
2223
import {
2324
absoluteToPercentage,
@@ -523,7 +524,10 @@ export function useEnableKeyframes(
523524
sel.dataAttributes?.duration,
524525
t,
525526
);
526-
const selector = selectorFromSelection(sel);
527+
// A brand-new tween: author it against the one element the user selected.
528+
// The bare class selectorFromSelection hands back for an id-less element
529+
// animates every sibling sharing the class (see writeTargetSelector).
530+
const selector = writeTargetSelector(sel);
527531

528532
if (!selector) {
529533
session.handleGsapAddAnimation("to");

0 commit comments

Comments
 (0)