Skip to content

Commit 7734697

Browse files
fix(studio): a copied clip keeps its look and motion, and a duplicated section keeps its name (#4756)
* fix(studio): a copied clip keeps its look and motion, and a duplicated section keeps its name * fix(studio): a copy's tweens start where their originals do and stay in the timeline's scope * fix(studio): a copy takes only tweens it can place exactly, and never moves the film's own * fix(studio): a copy leaves out a tween that sits inside a callback or a guard * fix(studio): a copy leaves out a set that runs only inside an if or an else * chore(studio): keep the copy change under the comment ratchet
1 parent 14e8700 commit 7734697

8 files changed

Lines changed: 456 additions & 13 deletions

File tree

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -674,6 +674,19 @@ describe("collectRuntimeTimelinePayload", () => {
674674
expect(result.clips[0].label).toBe("Hero Card");
675675
});
676676

677+
it("names each instance of a repeated scene by its authored id, not the id the loader gave it", () => {
678+
document.body.innerHTML = `<div data-composition-id="main" data-duration="10">
679+
<div class="clip" data-composition-id="benefit-fresh__hf1" data-hf-original-composition-id="benefit-fresh"
680+
data-start="0" data-duration="3"></div>
681+
<div class="clip" data-composition-id="benefit-fresh__hf2" data-hf-original-composition-id="benefit-fresh"
682+
data-start="3" data-duration="3"></div>
683+
</div>`;
684+
685+
const result = collectRuntimeTimelinePayload(defaultParams);
686+
expect(result.clips.map((clip) => clip.label)).toEqual(["Benefit Fresh", "Benefit Fresh"]);
687+
expect(result.scenes.map((scene) => scene.label)).toEqual(["benefit-fresh", "benefit-fresh"]);
688+
});
689+
677690
it("falls back to a readable ordinal label instead of a node index id", () => {
678691
const root = document.createElement("div");
679692
root.setAttribute("data-composition-id", "main");

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,12 @@ function humanizeTimelineToken(value: string): string {
209209
return normalized.replace(/\b\w/g, (char) => char.toUpperCase());
210210
}
211211

212+
function authoredCompositionId(node: Element): string | null {
213+
return (
214+
node.getAttribute("data-hf-original-composition-id") ?? node.getAttribute("data-composition-id")
215+
);
216+
}
217+
212218
function buildTimelineClipLabel(node: Element, kind: RuntimeTimelineClip["kind"], ordinal: number) {
213219
const explicit =
214220
node.getAttribute("data-timeline-label") ??
@@ -217,7 +223,7 @@ function buildTimelineClipLabel(node: Element, kind: RuntimeTimelineClip["kind"]
217223
null;
218224
if (explicit?.trim()) return explicit.trim();
219225

220-
const compositionId = node.getAttribute("data-composition-id");
226+
const compositionId = authoredCompositionId(node);
221227
if (compositionId) return humanizeTimelineToken(compositionId);
222228

223229
const id = (node as HTMLElement).id;
@@ -679,7 +685,10 @@ export function collectRuntimeTimelinePayload(params: {
679685
if (clampedDuration <= 0) continue;
680686
scenes.push({
681687
id: compositionId,
682-
label: compositionNode.getAttribute("data-label") ?? compositionId,
688+
label:
689+
compositionNode.getAttribute("data-label") ??
690+
authoredCompositionId(compositionNode) ??
691+
compositionId,
683692
start,
684693
duration: clampedDuration,
685694
thumbnailUrl: toAbsoluteAssetUrl(compositionNode.getAttribute("data-thumbnail-url")),

‎packages/parsers/src/gsapWriter.acorn.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
addAnimationToScript,
1111
addKeyframeToScript,
1212
convertToKeyframesFromScript,
13+
copyAnimationsInScript,
1314
removeAnimationFromScript,
1415
removeKeyframeFromScript,
1516
updateAnimationInScript,
@@ -445,3 +446,92 @@ window.__timelines["t"] = tl;`;
445446
expect(reparsed.global).toBeFalsy();
446447
});
447448
});
449+
450+
describe("copyAnimationsInScript", () => {
451+
const script = `\
452+
gsap.set("#goodbye", { rotation: 4 });
453+
var tl = gsap.timeline({ paused: true });
454+
tl.from("#goodbye", { opacity: 0, y: 40, ease: EASE }, 1);
455+
tl.to("#title", { opacity: 0.5, duration: 10 });
456+
function pop(sel) { tl.to(sel, { scale: 1.2 }, 2); }
457+
pop("#goodbye");
458+
window.__timelines["t"] = tl;`;
459+
460+
it("adds each tween on the original for the copy, moved by the delta, with its own argument text", () => {
461+
const result = copyAnimationsInScript(script, "#goodbye", "#goodbye-2", 3);
462+
expect(result).toContain(`tl.from("#goodbye-2", { opacity: 0, y: 40, ease: EASE }, 4);`);
463+
expect(result).toContain(`gsap.set("#goodbye-2", { rotation: 4 });\nvar tl`);
464+
const copies = parseGsapScriptAcorn(result)?.animations.filter(
465+
(a) => a.targetSelector === "#goodbye-2" && a.method !== "set",
466+
);
467+
expect(copies?.map((a) => a.position)).toEqual([4]);
468+
// The original lines are left as they were; the tween's copy ends the timeline's block.
469+
expect(result.replace(/\n?.*goodbye-2.*/g, "")).toBe(script.replace(/\n?.*goodbye-2.*/g, ""));
470+
expect(
471+
result.endsWith(`= tl;\ntl.from("#goodbye-2", { opacity: 0, y: 40, ease: EASE }, 4);`),
472+
).toBe(true);
473+
});
474+
475+
it("copies no tween whose start is not a number, rather than guess it", () => {
476+
const unsure = `var tl = gsap.timeline();
477+
tl.to("#title", { x: 1, duration: 2 });
478+
tl.from("#goodbye", { opacity: 0 });
479+
tl.addLabel("end");
480+
tl.to("#goodbye", { x: 2 }, "end");`;
481+
expect(copyAnimationsInScript(unsure, "#goodbye", "#goodbye-2", 3)).toBe(unsure);
482+
});
483+
484+
it("keeps the copy in the block that declares the timeline", () => {
485+
const guarded = `if (window.gsap) {
486+
const tl = gsap.timeline();
487+
tl.from("#goodbye", { opacity: 0 }, 1);
488+
window.__timelines["main"] = tl;
489+
}`;
490+
expect(copyAnimationsInScript(guarded, "#goodbye", "#goodbye-2", 3)).toContain(
491+
` window.__timelines["main"] = tl;\n tl.from("#goodbye-2", { opacity: 0 }, 4);\n}`,
492+
);
493+
});
494+
495+
it("copies no tween inside a callback or a guard, which may never run", () => {
496+
const deferred = `var tl = gsap.timeline();
497+
el.addEventListener("click", () => tl.to("#goodbye", { x: 1 }, 1));
498+
window.go && tl.from("#goodbye", { opacity: 0 }, 1);
499+
tl.call(() => tl.to("#goodbye", { y: 1 }, 1));
500+
tl.to("#title", { x: 1 }, 0).from("#goodbye", { opacity: 0 }, 2);`;
501+
const result = copyAnimationsInScript(deferred, "#goodbye", "#goodbye-2", 3);
502+
expect(result.match(/goodbye-2/g)).toEqual(["goodbye-2"]);
503+
expect(result).toContain(`tl.from("#goodbye-2", { opacity: 0 }, 5);`);
504+
});
505+
506+
it("copies no set that is the bare body of an if or an else", () => {
507+
const guarded = `var tl = gsap.timeline();
508+
if (window.go) gsap.set("#goodbye", { x: 9 });
509+
else gsap.set("#goodbye", { x: 1 });`;
510+
expect(copyAnimationsInScript(guarded, "#goodbye", "#goodbye-2", 3)).toBe(guarded);
511+
});
512+
513+
it("puts the copy before the block's return", () => {
514+
const built = `function build() {
515+
const tl = gsap.timeline();
516+
tl.from("#goodbye", { opacity: 0, stagger: 0.1 }, 1);
517+
return tl;
518+
}`;
519+
expect(copyAnimationsInScript(built, "#goodbye", "#goodbye-2", 3)).toContain(
520+
` tl.from("#goodbye-2", { opacity: 0, stagger: 0.1 }, 4);\n return tl;`,
521+
);
522+
});
523+
524+
it("puts a set's copy right after it, where what it reads is defined", () => {
525+
const late = `const tl = gsap.timeline();
526+
const X = 40;
527+
gsap.set("#goodbye", { x: X });
528+
tl.from("#goodbye", { opacity: 0 }, 1);`;
529+
expect(copyAnimationsInScript(late, "#goodbye", "#goodbye-2", 3)).toContain(
530+
`gsap.set("#goodbye", { x: X });\ngsap.set("#goodbye-2", { x: X });`,
531+
);
532+
});
533+
534+
it("leaves the script as it was when nothing targets the original", () => {
535+
expect(copyAnimationsInScript(script, "#tag", "#tag-2", 3)).toBe(script);
536+
});
537+
});

‎packages/parsers/src/gsapWriterAcorn.ts‎

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,13 +461,108 @@ export function shiftPositionsInScript(
461461
for (const entry of parsed.located) {
462462
if (entry.animation.targetSelector !== targetSelector) continue;
463463
if (typeof entry.animation.position !== "number") continue;
464-
const newPos = Math.max(0, Math.round((entry.animation.position + delta) * 1000) / 1000);
465-
overwritePosition(ms, entry.call, newPos);
464+
overwritePosition(ms, entry.call, shiftedPosition(entry.animation.position, delta));
466465
changed = true;
467466
}
468467
return changed ? ms.toString() : script;
469468
}
470469

470+
/** Copies each tween on `fromSelector` for `toSelector`, `delta` seconds later, in its own argument text. Exact or
471+
* absent: only a tween at a number, written straight in the timeline's own block, is copied. */
472+
export function copyAnimationsInScript(
473+
script: string,
474+
fromSelector: string,
475+
toSelector: string,
476+
delta: number,
477+
): string {
478+
const parsed = parseGsapScriptAcornForWrite(script);
479+
if (!parsed) return script;
480+
const block = timelineBlock(parsed);
481+
const target = JSON.stringify(toSelector);
482+
const ms = new MagicString(script);
483+
const tweens: string[] = [];
484+
for (const { animation, call } of parsed.located) {
485+
if (animation.targetSelector !== fromSelector || !copyable(call)) continue;
486+
const args = [target, ...argumentText(call, script)];
487+
const statement = findEnclosingExpressionStatement(call.ancestors);
488+
if (call.global && statement && inBlock(call, statement)) {
489+
ms.appendLeft(
490+
statement.end,
491+
`\n${indentAt(script, statement.start)}gsap.set(${args.join(", ")});`,
492+
);
493+
} else if (block.body.includes(statement) && typeof call.positionArg?.value === "number") {
494+
const position = valueToCode(shiftedPosition(call.positionArg.value, delta));
495+
tweens.push(`${parsed.timelineVar}.${call.method}(${[...args, position].join(", ")});`);
496+
}
497+
}
498+
appendAtBlockEnd(ms, script, block, tweens);
499+
return ms.toString();
500+
}
501+
502+
/** A tween in a loop runs once per pass, one on a variable reads a name bound elsewhere, and one inside a callback or a
503+
* guard may never run: none is copied. The statement must be the tween's own chain. */
504+
function copyable(call: TweenCallInfo): boolean {
505+
if (call.node.arguments[0]?.type !== "Literal" || call.ancestors.some(isLoopOrForEach))
506+
return false;
507+
let link = findEnclosingExpressionStatement(call.ancestors)?.expression;
508+
while (link?.type === "CallExpression" && link !== call.node) link = link.callee?.object;
509+
return link === call.node;
510+
}
511+
512+
/** A statement straight in a block or the script: one that is an `if`'s bare body runs only when the `if` does. */
513+
function inBlock(call: TweenCallInfo, statement: Node): boolean {
514+
return Array.isArray(call.ancestors[call.ancestors.indexOf(statement) - 1]?.body);
515+
}
516+
517+
/** The call's own text for every argument but its target and position. */
518+
function argumentText(call: TweenCallInfo, script: string): string[] {
519+
return call.node.arguments
520+
.slice(1)
521+
.filter((arg: Node) => arg !== call.positionArg)
522+
.map((arg: Node) => script.slice(arg.start, arg.end));
523+
}
524+
525+
function indentAt(script: string, at: number): string {
526+
return /^[ \t]*/.exec(script.slice(script.lastIndexOf("\n", at - 1) + 1))![0];
527+
}
528+
529+
/** At the end of the timeline's own block, before its return, so nothing that follows in its scope is pushed back. */
530+
function appendAtBlockEnd(
531+
ms: MagicString,
532+
script: string,
533+
block: { body: Node[]; end: number },
534+
lines: string[],
535+
): void {
536+
if (lines.length === 0) return;
537+
const last = block.body.at(-1);
538+
const indent = last ? indentAt(script, last.start) : "";
539+
const code = lines.map((line) => `${indent}${line}`).join("\n");
540+
if (last?.type === "ReturnStatement") ms.appendLeft(last.start, `${code.trimStart()}\n${indent}`);
541+
else ms.appendLeft(last?.end ?? block.end, `\n${code}`);
542+
}
543+
544+
function shiftedPosition(position: number, delta: number): number {
545+
return Math.max(0, Math.round((position + delta) * 1000) / 1000);
546+
}
547+
548+
/** The block (or program) whose statements declare the timeline; a timeline with no declaration lives at the top. */
549+
function timelineBlock(parsed: ParsedGsapAcornForWrite): { body: Node[]; end: number } {
550+
const declaration = findTimelineDeclarationStatement(parsed.ast, parsed.timelineVar);
551+
let block: Node = parsed.ast;
552+
if (declaration) {
553+
acornWalk.ancestor(parsed.ast, {
554+
VariableDeclaration(node: Node, _state: unknown, ancestors: Node[]) {
555+
if (node === declaration) block = ancestors[ancestors.length - 2];
556+
},
557+
});
558+
}
559+
return Array.isArray(block?.body) ? block : parsed.ast;
560+
}
561+
562+
function isLoopOrForEach(node: Node): boolean {
563+
return isLoopNode(node) || isForEachStatement(node) || node?.type === "DoWhileStatement";
564+
}
565+
471566
/**
472567
* Linearly remap every tween targeting `targetSelector` from the old clip
473568
* [oldStart, oldDuration] onto the new [newStart, newDuration] (position and,

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

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
deduplicateIds,
1212
insertAsSibling,
1313
} from "../utils/clipboardPayload";
14+
import { carryLook, renamedIds } from "../utils/clipboardLook";
1415
import { collectHtmlIds } from "../utils/studioHelpers";
1516
import { insertTimelineAssetIntoSource } from "../utils/timelineAssetDrop";
1617
import { extendRootDurationInSource } from "../utils/rootDuration";
@@ -165,15 +166,16 @@ export function pasteElementHtml(
165166
return insertAsSibling(content, deduped, payload.originSelector, payload.originSelectorIndex);
166167
}
167168

168-
/** Shared insertion path for paste and duplicate, anchored at the playhead or
169-
* the selection's end respectively. Returns the final ids so the caller can
170-
* select what it just placed, and the furthest end any clip lands at so the
171-
* caller can grow the root composition's duration to cover it. */
169+
/** Shared insertion path for paste and duplicate, anchored at the playhead or the selection's end. Returns the
170+
* final ids so the caller can select what it placed, and the furthest end any clip lands at so it can grow the
171+
* root duration to cover it. `fromThisFile`: the clips came from `content`, so a renamed copy takes its
172+
* original's look. */
172173
export function pasteTimelineClips(
173174
content: string,
174175
clips: readonly TimelineClipboardClip[],
175176
anchorTime: number,
176177
liveElements: readonly TimelineElement[],
178+
fromThisFile = false,
177179
): { content: string; ids: string[]; requiredEnd: number } {
178180
const groupMinStart = Math.min(...clips.map((c) => c.start));
179181
let existingIds = collectHtmlIds(content);
@@ -209,6 +211,11 @@ export function pasteTimelineClips(
209211
.replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
210212
const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
211213
result = insertTimelineAssetIntoSource(result, withPatched);
214+
if (fromThisFile) {
215+
const authored = Number(rootTag.match(/data-start="([^"]*)"/)?.[1]);
216+
const authoredStart = Number.isFinite(authored) ? authored : clip.start;
217+
result = carryLook(result, renamedIds(reminted, deduped), newStart - authoredStart);
218+
}
212219

213220
const id = patchedRootTag.match(ID_ATTR_RE)?.[1];
214221
if (id) ids.push(id);
@@ -294,7 +301,12 @@ export function useClipboard({
294301
const sourceFile = targets.elements[0]?.sourceFile || activeCompPath || "index.html";
295302
return readClips(targets).then((clips) => {
296303
showToast(clips.length > 1 ? `Copied ${clips.length} clips` : "Copied clip", "info");
297-
return { kind: "timeline-clip", clips, sourceFile };
304+
return {
305+
kind: "timeline-clip",
306+
clips,
307+
sourceFile,
308+
projectId: projectIdRef.current ?? undefined,
309+
};
298310
});
299311
}, [activeCompPath, findSelectedClips, readClips, showToast]);
300312

@@ -364,7 +376,13 @@ export function useClipboard({
364376
const paste = (originalContent: string) => {
365377
if (payload.kind !== "timeline-clip") return pasteElementHtml(originalContent, payload);
366378
const { currentTime, elements } = usePlayerStore.getState();
367-
const pasted = pasteTimelineClips(originalContent, payload.clips, currentTime, elements);
379+
const pasted = pasteTimelineClips(
380+
originalContent,
381+
payload.clips,
382+
currentTime,
383+
elements,
384+
payload.sourceFile === targetPath && payload.projectId === pid,
385+
);
368386
pastedIds = pasted.ids;
369387
// A clip pasted past the current composition end would exist in the
370388
// file but never appear on the timeline or in playback/export (the
@@ -433,7 +451,7 @@ export function useClipboard({
433451
.getState()
434452
.elements.filter((el) => pathOf(el) === targetPath)
435453
.map((el) => ({ ...el, start: toAuthoredStart(el, el.start) }));
436-
const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements);
454+
const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements, true);
437455
ids = pasted.ids;
438456
return extendRootDurationInSource(pasted.content, pasted.requiredEnd);
439457
};

0 commit comments

Comments
 (0)