Skip to content

Commit 1f3fd28

Browse files
committed
fix(studio): give the motion path and the fallbacks a one-element target
The narrowing this branch adds missed the motion-path overlay, and every caller that could not narrow fell back to the exact bare class the narrowing exists to replace. - motionPathSelection.selectorFor now goes through writeTargetSelector. It feeds both the geometry read and the "set destination" write, so a class sibling measured its home off the FIRST sibling and then authored add-motion-path onto all of them. The toolbar toggle hides when no one-element form exists rather than arming a press that is dropped. - The five new-tween writers that fell back to the selection's own selector now drop the commit instead. A gesture that does not persist reverts on the next reload; a tween silently aimed at five elements does not. - tweenTargetsElement only follows the DOM to a target that matches exactly one element. A target the element merely shares with its siblings is a group tween, and these callers mutate what they find, so an individual nudge was rewriting the group's own tween and moving all five.
1 parent 3d92436 commit 1f3fd28

9 files changed

Lines changed: 190 additions & 41 deletions

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
132132
const createMode = geometryResolved && !geometry && Boolean(selection?.element) && !isPlaying;
133133
const createSelector = createMode ? selectorFor(selection) : null;
134134
const compW = compositionSize?.width ?? null;
135-
const canCreate = createMode && hasMotionPathPlugin(iframeRef.current);
135+
// No one-element selector means the path could only be authored onto the
136+
// element's class siblings, so the toolbar toggle stays hidden instead of
137+
// arming a press that the effect below would silently drop.
138+
const canCreate = createMode && !!createSelector && hasMotionPathPlugin(iframeRef.current);
136139

137140
// Publish whether the selected element can take a path so the preview toolbar
138141
// shows its "set destination" toggle. Drops to false when this overlay unmounts
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, describe, expect, it } from "vitest";
3+
import type { DomEditSelection } from "./domEditingTypes";
4+
import { buildStableSelector, getSelectorIndex } from "./domEditingDom";
5+
import { selectorFor } from "./motionPathSelection";
6+
7+
afterEach(() => {
8+
document.body.innerHTML = "";
9+
});
10+
11+
function selectionFor(el: HTMLElement): DomEditSelection {
12+
const selector = buildStableSelector(el);
13+
return {
14+
element: el,
15+
id: el.id || undefined,
16+
hfId: el.getAttribute("data-hf-id") || undefined,
17+
selector,
18+
selectorIndex: getSelectorIndex(document, el, selector, "index.html", null),
19+
sourceFile: "index.html",
20+
dataAttributes: { start: "0", duration: "2" },
21+
} as unknown as DomEditSelection;
22+
}
23+
24+
function mountGroupSiblings(): HTMLElement[] {
25+
document.body.innerHTML = `
26+
<div id="scene" class="clip" data-start="0" data-duration="2">
27+
<div class="group"></div>
28+
<div class="group"></div>
29+
<div class="group"></div>
30+
</div>
31+
`;
32+
return Array.from(document.querySelectorAll<HTMLElement>(".group"));
33+
}
34+
35+
describe("selectorFor", () => {
36+
it("addresses one element for a class-only sibling", () => {
37+
const groups = mountGroupSiblings();
38+
const selector = selectorFor(selectionFor(groups[2]!));
39+
40+
// The bare ".group" both measured home off the FIRST sibling and wrote the
41+
// new motion path onto all three.
42+
expect(selector).not.toBe(".group");
43+
expect(document.querySelectorAll(selector!)).toHaveLength(1);
44+
expect(document.querySelector(selector!)).toBe(groups[2]);
45+
});
46+
47+
it("keeps a unique id target", () => {
48+
document.body.innerHTML = `<div id="hero"></div>`;
49+
const el = document.querySelector<HTMLElement>("#hero")!;
50+
51+
expect(selectorFor(selectionFor(el))).toBe("#hero");
52+
});
53+
54+
it("returns null with no selection", () => {
55+
expect(selectorFor(null)).toBeNull();
56+
});
57+
58+
it("returns null when no rung addresses one element", () => {
59+
const groups = mountGroupSiblings();
60+
const selection = selectionFor(groups[1]!);
61+
groups[1]!.remove();
62+
63+
expect(selectorFor(selection)).toBeNull();
64+
});
65+
});

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,21 @@
55
*/
66
import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";
77
import type { DomEditSelection } from "./domEditing";
8+
import { writeTargetSelector } from "../../hooks/gsapShared";
89

10+
/**
11+
* The selector the overlay both MEASURES the element by and authors a new
12+
* motion path against.
13+
*
14+
* Both halves need exactly one element. The selection's own selector is a bare
15+
* class for an id-less element, so a `.group` sibling read its home position off
16+
* the FIRST sibling (skewing the destination the click computes) and then wrote
17+
* `add-motion-path` onto all five. `writeTargetSelector` is the same one-element
18+
* narrowing every other new-tween writer goes through; null means no such form
19+
* exists, and the overlay hides "set destination" rather than write a wrong one.
20+
*/
921
export function selectorFor(sel: DomEditSelection | null): string | null {
10-
if (!sel) return null;
11-
if (sel.id) return `#${CSS.escape(sel.id)}`;
12-
return sel.selector ?? null;
22+
return sel ? writeTargetSelector(sel) : null;
1323
}
1424

1525
/** The animation whose path is editable on-canvas: literal, statically resolved,

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

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,14 @@ export interface GsapDragCommitCallbacks {
5151
* write over every sibling sharing the class. Retargets of an EXISTING tween
5252
* must NOT come through here (they keep `anim.targetSelector`, so a tween the
5353
* author aimed at a group stays aimed at it).
54+
*
55+
* Null means no one-element form exists, and every caller drops the commit
56+
* rather than falling back to `selector` (see writeTargetSelector): the drag
57+
* reverts on the next reload, which is recoverable, where a `.group` write is
58+
* not.
5459
*/
55-
function newTweenTarget(selection: DomEditSelection, selector: string): string {
56-
return writeTargetSelector(selection) ?? selector;
60+
function newTweenTarget(selection: DomEditSelection): string | null {
61+
return writeTargetSelector(selection);
5762
}
5863

5964
// Re-export for backward compatibility with existing imports.
@@ -77,17 +82,18 @@ export function parkPlayheadOnKeyframe(anim: GsapAnimation, pct: number): void {
7782

7883
async function replaceKeyframedPositionHold(
7984
selection: DomEditSelection,
80-
selector: string,
8185
existingSet: GsapAnimation,
8286
properties: { x: number; y: number },
8387
commitMutation: GsapDragCommitCallbacks["commitMutation"],
8488
): Promise<void> {
89+
const target = newTweenTarget(selection);
90+
if (!target) return;
8591
const persist = async (commit: GsapDragCommitCallbacks["commitMutation"]) => {
8692
await commit(
8793
selection,
8894
{
8995
type: "add",
90-
targetSelector: newTweenTarget(selection, selector),
96+
targetSelector: target,
9197
method: "set",
9298
position: 0,
9399
properties,
@@ -186,7 +192,6 @@ export async function commitStaticGsapPosition(
186192
// least one hold on disk, then delete the corrupt tween in one transaction.
187193
await replaceKeyframedPositionHold(
188194
selection,
189-
selector,
190195
existingSet,
191196
{ x: newX, y: newY },
192197
callbacks.commitMutation,
@@ -213,7 +218,8 @@ export async function commitStaticGsapPosition(
213218
// an instant patch so the first nudge shows immediately (no soft-reload flash).
214219
// The patch reuses the WRITTEN target so the runtime moves exactly the element
215220
// the source write names.
216-
const target = newTweenTarget(selection, selector);
221+
const target = newTweenTarget(selection);
222+
if (!target) return;
217223
await callbacks.commitMutation(
218224
selection,
219225
{
@@ -270,7 +276,8 @@ export async function commitStaticGsapRotation(
270276
return;
271277
}
272278
// New static hold → off-timeline `gsap.set` (no 0% keyframe marker) + instant patch.
273-
const target = newTweenTarget(selection, selector);
279+
const target = newTweenTarget(selection);
280+
if (!target) return;
274281
await callbacks.commitMutation(
275282
selection,
276283
{
@@ -323,11 +330,13 @@ export async function commitStaticGsapSize(
323330
);
324331
return;
325332
}
333+
const target = newTweenTarget(selection);
334+
if (!target) return;
326335
await callbacks.commitMutation(
327336
selection,
328337
{
329338
type: "add",
330-
targetSelector: newTweenTarget(selection, selector),
339+
targetSelector: target,
331340
method: "set",
332341
position: 0,
333342
properties: { width, height },
@@ -411,11 +420,13 @@ export async function commitKeyframedSizeFromResize(
411420
// transport applies both in one ordered batch; a plain commit fallback keeps the
412421
// same recoverable ordering. Only the transaction's result triggers the reload.
413422
const addLabel = `Resize (size keyframe ${pct.toFixed(0)}%)`;
423+
const target = newTweenTarget(selection);
424+
if (!target) return false;
414425
await callbacks.commitMutation(
415426
selection,
416427
{
417428
type: "add-with-keyframes",
418-
targetSelector: newTweenTarget(selection, selector),
429+
targetSelector: target,
419430
position: roundTo3(ts),
420431
duration: roundTo3(td),
421432
keyframes,

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,18 @@ export async function commitKeyframeAtTimeImpl(
6363
},
6464
);
6565
} else {
66+
// Null means the live DOM could not prove any one-element form. Falling
67+
// back to the author's own selector would write the group-collapsing
68+
// target this narrowing exists to prevent, so the keyframe is dropped
69+
// instead (see writeTargetSelector).
70+
const target = writeTargetSelector(selection);
71+
if (!target) return;
6672
const defaultDuration = 0.5;
6773
await commitMutation(
6874
selection,
6975
{
7076
type: "add-with-keyframes" as const,
71-
// Null here means the live DOM could not prove any one-element form.
72-
// This branch has no graceful no-op to fall to, so it takes the
73-
// author's own selector, group collapse and all, over dropping the
74-
// keyframe the user just asked for.
75-
targetSelector: writeTargetSelector(selection) ?? selector,
77+
targetSelector: target,
7678
position: absoluteTime,
7779
duration: defaultDuration,
7880
keyframes: [

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

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -251,11 +251,12 @@ function structuralSelector(element: Element): string | null {
251251
* against, a failed structural walk (detached between select and commit, a
252252
* shadow-root boundary, a chain that no longer re-resolves) IS that evidence,
253253
* so returning the bare selector anyway would hand back the exact input this
254-
* function exists to replace. Callers decide what to do with the null: the
255-
* add-keyframe path has a graceful no-animation fallback, and the paths that
256-
* cannot afford to drop a user edit opt back in with `?? selectorFromSelection`
257-
* where the trade is visible. The bare selector comes back only with no DOM to
258-
* disambiguate against, where refusing would be guessing rather than knowing.
254+
* function exists to replace. Every caller treats the null as "do not author
255+
* this tween": falling back to the selection's own selector would write the
256+
* group-collapsing target this function exists to prevent, and a gesture that
257+
* does not persist reverts visibly on the next reload, where a tween silently
258+
* aimed at five elements does not. The bare selector comes back only with no DOM
259+
* to disambiguate against, where refusing would be guessing rather than knowing.
259260
*/
260261
export function writeTargetSelector(selection: DomEditSelection): string | null {
261262
if (selection.id) return idSelector(selection.id);
@@ -298,22 +299,24 @@ export function existingTweenTargetSelector(
298299
* String equality against `selectorFromSelection` alone is not enough once new
299300
* tweens are authored with a narrowed one-element selector: the next edit would
300301
* miss the write it just made and append a second, conflicting one. Falling back
301-
* to the live DOM keeps the pair consistent, and still matches a deliberate group
302-
* tween (`.group` matches each of its siblings) so merges into it keep working.
302+
* to the live DOM keeps the pair consistent.
303+
*
304+
* That fallback is `matchesExactlyOne`, not a bare `element.matches`. A target
305+
* the element merely shares with its siblings is a GROUP tween, and the callers
306+
* here MUTATE what they find: an individual nudge on one of five `.group`
307+
* siblings would rewrite the group's own tween and move all five. Only the
308+
* selection that IS the group (string equality above, where the author selected
309+
* `.group` itself) may edit it; every other element authors its own write.
303310
*/
304311
export function tweenTargetsElement(
305312
targetSelector: string,
306313
selector: string,
307314
element: Element | null | undefined,
308315
): boolean {
309316
if (targetSelector === selector) return true;
310-
if (!element) return false;
311-
try {
312-
return element.matches(targetSelector);
313-
} catch {
314-
// Not a selector `matches()` understands, so it never addressed this element.
315-
return false;
316-
}
317+
const doc = element?.ownerDocument;
318+
if (!element || !doc) return false;
319+
return matchesExactlyOne(doc, targetSelector, element);
317320
}
318321

319322
// ── Percentage computation ────────────────────────────────────────────────────

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

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { parseGsapScript } from "@hyperframes/core/gsap-parser";
44
import { addAnimationWithKeyframesToScript } from "@hyperframes/parsers/gsap-writer-acorn";
55
import type { DomEditSelection } from "../components/editor/domEditingTypes";
66
import { buildStableSelector, getSelectorIndex } from "../components/editor/domEditingDom";
7-
import { resolveSelectorElementIds, writeTargetSelector } from "./gsapShared";
7+
import { resolveSelectorElementIds, tweenTargetsElement, writeTargetSelector } from "./gsapShared";
88
import { commitKeyframeAtTimeImpl } from "./gsapKeyframeCommit";
99
import { promoteSetToKeyframes } from "./useEnableKeyframes";
1010

@@ -244,3 +244,46 @@ describe("commitKeyframeAtTimeImpl — new-tween target", () => {
244244
expect(document.querySelector(mutation.targetSelector)).toBe(groups[3]);
245245
});
246246
});
247+
248+
describe("tweenTargetsElement", () => {
249+
it("matches a tween narrowed to this element by a selector the selection does not use", () => {
250+
const groups = mountGroupSiblings();
251+
groups[2]!.id = "narrowed";
252+
253+
// The write half authored "#narrowed"; the read half still has ".group".
254+
expect(tweenTargetsElement("#narrowed", ".group", groups[2])).toBe(true);
255+
});
256+
257+
it("does not hand an individual element the group tween it merely inherits", () => {
258+
const groups = mountGroupSiblings();
259+
260+
// Selecting one sibling by its own address must not let an edit mutate the
261+
// ".group" tween: that write moves all five, not the one being nudged.
262+
expect(tweenTargetsElement(".group", "#scene > div:nth-child(3)", groups[2])).toBe(false);
263+
});
264+
265+
it("still edits a group tween when the group itself is the selection", () => {
266+
const groups = mountGroupSiblings();
267+
268+
expect(tweenTargetsElement(".group", ".group", groups[0])).toBe(true);
269+
});
270+
271+
it("does not match a target that is not a selector matches() understands", () => {
272+
const groups = mountGroupSiblings();
273+
274+
expect(tweenTargetsElement("div[unclosed", ".group", groups[0])).toBe(false);
275+
});
276+
});
277+
278+
describe("commitKeyframeAtTimeImpl — no one-element target", () => {
279+
it("drops the keyframe rather than authoring the bare class", async () => {
280+
const groups = mountGroupSiblings();
281+
const selection = selectionFor(groups[3]!);
282+
groups[3]!.remove();
283+
const commitMutation = vi.fn(async () => undefined);
284+
285+
await commitKeyframeAtTimeImpl(selection, 1, [], { x: 12 }, commitMutation);
286+
287+
expect(commitMutation).not.toHaveBeenCalled();
288+
});
289+
});

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

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ async function commitStaticSet(
214214
}
215215
// Fresh adds don't reshape existing sets, so their ids can't go stale.
216216
for (const batch of newSetBatches) {
217-
await addGlobalStaticSet(selection, batch, selector, commit);
217+
await addGlobalStaticSet(selection, batch, commit);
218218
}
219219
}
220220

@@ -244,16 +244,17 @@ function findGroupOwningStaticWrite(
244244
async function addGlobalStaticSet(
245245
selection: DomEditSelection,
246246
batch: [string, number | string][],
247-
selector: string,
248247
commit: Commit,
249248
): Promise<void> {
250249
const numericProps: SetPatchProps = {};
251250
for (const [k, v] of batch) {
252251
if (typeof v === "number") numericProps[k as keyof SetPatchProps] = v;
253252
}
254-
// A brand-new write, so it must address ONE element: `selector` is the bare
255-
// class an id-less selection yields, which would hold every sibling.
256-
const target = writeTargetSelector(selection) ?? selector;
253+
// A brand-new write, so it must address ONE element: the selection's own
254+
// selector is the bare class an id-less element yields, which would hold every
255+
// sibling. No one-element form means no write at all (see writeTargetSelector).
256+
const target = writeTargetSelector(selection);
257+
if (!target) return;
257258
await commit(
258259
selection,
259260
{
@@ -493,7 +494,11 @@ export function useAnimatedPropertyCommit(deps: CommitAnimatedPropertyDeps) {
493494
// contaminating a foreign-group tween. Mirror an existing keyframed tween's
494495
// time range so the new group animates over the same span. The 0% baseline is
495496
// an `_auto` endpoint so it tracks the nearest keyframe as you add more.
496-
if (selector) {
497+
// A fresh tween, so its target must address ONE element; with no
498+
// one-element form the edit is dropped rather than written onto every
499+
// class sibling (see writeTargetSelector).
500+
const newTweenTarget = writeTargetSelector(selection);
501+
if (selector && newTweenTarget) {
497502
const template = selectedGsapAnimations.find((a) => !!a.keyframes);
498503
const tStart = template ? (resolveTweenStart(template) ?? 0) : 0;
499504
const tDur = template ? resolveTweenDuration(template) || 1 : 1;
@@ -514,7 +519,7 @@ export function useAnimatedPropertyCommit(deps: CommitAnimatedPropertyDeps) {
514519
selection,
515520
{
516521
type: "add-with-keyframes",
517-
targetSelector: writeTargetSelector(selection) ?? selector,
522+
targetSelector: newTweenTarget,
518523
position: roundTo3(tStart),
519524
duration: roundTo3(tDur),
520525
keyframes,

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,14 @@ export function useGestureCommit({
178178
showToast("Cannot save — element has no selector", "error");
179179
return;
180180
}
181-
const writeSelector = writeTargetSelector(sel) ?? selector;
181+
// A recorded gesture becomes a NEW tween, so its target must address one
182+
// element; the selection's own selector would record the motion onto
183+
// every sibling sharing its class (see writeTargetSelector).
184+
const writeSelector = writeTargetSelector(sel);
185+
if (!writeSelector) {
186+
showToast("Cannot save: element has no unique selector", "error");
187+
return;
188+
}
182189
if (liveSession.commitMutation) {
183190
const recStart = recordingStartTimeRef.current;
184191
const rawKeyframes = sortedPcts.map((pct) => ({

0 commit comments

Comments
 (0)