Skip to content

Commit d84e999

Browse files
committed
fix(parsers): preserve authored keyframe intent
1 parent 5acbf24 commit d84e999

7 files changed

Lines changed: 346 additions & 67 deletions

File tree

‎packages/parsers/src/gsapParser.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3057,6 +3057,29 @@ describe("single position write per element (consolidation)", () => {
30573057
expect(out).not.toMatch(/gsap\.set\("#box",\s*\{\s*x:/);
30583058
expect(parseGsapScript(out).animations.some((a) => "opacity" in a.properties)).toBe(true);
30593059
});
3060+
3061+
it("remove-all-keyframes collapses synthetic motionPath keyframes to a held position", () => {
3062+
const script = `
3063+
const tl = gsap.timeline({ paused: true });
3064+
tl.to("#box", {
3065+
motionPath: { path: [{ x: 0, y: 10 }, { x: 200, y: 40 }] },
3066+
duration: 2,
3067+
ease: "power1.inOut",
3068+
}, 1);
3069+
`;
3070+
const motionPathTween = parseGsapScript(script).animations.find(
3071+
(animation) => animation.arcPath?.enabled,
3072+
)!;
3073+
3074+
const out = removeAllKeyframesFromScript(script, motionPathTween.id);
3075+
const kept = posWritesFor(out, "#box");
3076+
3077+
expect(out).not.toBe(script);
3078+
expect(kept).toHaveLength(1);
3079+
expect(kept[0].arcPath).toBeUndefined();
3080+
expect(kept[0].duration).toBe(0);
3081+
expect(kept[0].properties).toMatchObject({ x: 200, y: 40 });
3082+
});
30603083
});
30613084

30623085
describe("recast writer never doubles vars keys", () => {

‎packages/parsers/src/gsapParser.ts‎

Lines changed: 69 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
serializeValue as valueToCode,
2222
safeJsKey as safeKey,
2323
resolveConversionProps,
24+
mergePercentageKeyframes,
2425
} from "./gsapSerialize";
2526

2627
export type {
@@ -1967,7 +1968,7 @@ function buildKeyframeObjectCode(
19671968
}>,
19681969
options?: { easeEach?: string },
19691970
): string {
1970-
const entries = keyframes.map((kf) => {
1971+
const entries = mergePercentageKeyframes(keyframes).map((kf) => {
19711972
const props = keyframePropsToCode(kf);
19721973
if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`);
19731974
if (kf.auto) props.push(`_auto: 1`);
@@ -2361,10 +2362,9 @@ export function removeKeyframeFromScript(
23612362
/**
23622363
* Retime a keyframe: move the keyframe at `fromPercentage` to `toPercentage`,
23632364
* PRESERVING its properties and per-keyframe ease (the Studio "Move to Playhead"
2364-
* gesture). Re-sorts keyframes by percentage. If a keyframe already exists at
2365-
* `toPercentage`, it is overwritten by the moved one (no duplicate). No-op when
2366-
* the animation/keyframe isn't found, the tween has no object-form keyframes, or
2367-
* the move resolves onto the same keyframe. Acorn twin: moveKeyframeInScript.
2365+
* gesture). Re-sorts keyframes by percentage. No-op when the animation/keyframe
2366+
* isn't found, the tween has no object-form keyframes, the move resolves onto the
2367+
* same keyframe, or the destination is occupied. Acorn twin: moveKeyframeInScript.
23682368
*/
23692369
export function moveKeyframeInScript(
23702370
script: string,
@@ -2388,19 +2388,19 @@ export function moveKeyframeInScript(
23882388
// retime, because findKeyframePropByPct resolves the destination back onto the
23892389
// from-keyframe — so a deliberate 1% drag committed nothing. Acorn twin too.
23902390
if (Math.abs(fromPercentage - toPercentage) < MOVE_NOOP_EPSILON_PCT) return script;
2391-
// A destination keyframe is only a real collision (overwrite) when it's a
2392-
// DIFFERENT keyframe; resolving back onto the from-keyframe is not.
2391+
// Never overwrite another authored keyframe. Resolving the destination back
2392+
// onto the source keyframe is not a collision (the tolerance is intentionally
2393+
// wider than MOVE_NOOP_EPSILON_PCT).
23932394
const dest = findKeyframePropByPct(kfNode, toPercentage);
2394-
const collision = dest && dest.prop !== match.prop ? dest : null;
2395+
if (dest && dest.prop !== match.prop) return script;
23952396

23962397
// Reuse each keyframe's value node verbatim (preserves properties +
2397-
// per-keyframe ease + _auto). Drop the moved keyframe (and any destination
2398-
// keyframe it overwrites), re-key the moved value to toPercentage, then re-sort.
2398+
// per-keyframe ease + _auto). Drop the moved keyframe, re-key its value to
2399+
// toPercentage, then re-sort.
23992400
const movedValue = match.prop.value;
24002401
const entries: Array<{ pct: number; value: AstNode }> = [];
24012402
for (const prop of filterPercentageProps(kfNode)) {
24022403
if (prop === match.prop) continue;
2403-
if (collision && prop === collision.prop) continue;
24042404
const pct = percentageFromKey(propKeyName(prop) ?? "");
24052405
if (Number.isNaN(pct)) continue;
24062406
entries.push({ pct, value: prop.value });
@@ -2452,7 +2452,12 @@ export function resizeKeyframedTweenInScript(
24522452
match.prop.key = parseExpr(`{ ${JSON.stringify(`${to}%`)}: 0 }`).properties[0].key;
24532453
}
24542454

2455-
applyUpdatesToCall(loc.target.call, { position: newPosition, duration: newDuration });
2455+
applyUpdatesToCall(loc.target.call, {
2456+
position: newPosition,
2457+
// Resizing is an explicit duration-authoring gesture. Promote GSAP's
2458+
// implicit default so the dragged window is the window that plays.
2459+
duration: newDuration,
2460+
});
24562461
return recast.print(loc.parsed.ast).code;
24572462
}
24582463

@@ -2501,6 +2506,36 @@ export function updateKeyframeInScript(
25012506
return recast.print(arrLoc.parsed.ast).code;
25022507
}
25032508

2509+
// motionPath waypoints are exposed as synthetic keyframes. Their positions
2510+
// live in `motionPath.path`, while one tween-level ease owns every segment.
2511+
// Commit both parts when a Studio gesture carries x/y + ease.
2512+
if (arrLoc && !arrVal && arrLoc.target.animation.arcPath?.enabled) {
2513+
const propertyKeys = Object.keys(properties);
2514+
if (propertyKeys.some((key) => key !== "x" && key !== "y")) return script;
2515+
let next = script;
2516+
if (propertyKeys.length > 0) {
2517+
const waypoints = extractArcWaypoints(arrLoc.target.animation);
2518+
if (waypoints.length < 2) return script;
2519+
const pointIndex = Math.max(
2520+
0,
2521+
Math.min(waypoints.length - 1, Math.round((percentage / 100) * (waypoints.length - 1))),
2522+
);
2523+
const current = waypoints[pointIndex];
2524+
if (!current) return script;
2525+
const x = properties.x ?? current.x;
2526+
const y = properties.y ?? current.y;
2527+
if (typeof x !== "number" || typeof y !== "number") return script;
2528+
next = updateMotionPathPointInScript(next, animationId, pointIndex, { x, y });
2529+
}
2530+
if (ease !== undefined) {
2531+
const updated = locateAnimationWithFallback(next, animationId);
2532+
if (!updated) return script;
2533+
applyUpdatesToCall(updated.target.call, { ease });
2534+
next = recast.print(updated.parsed.ast).code;
2535+
}
2536+
return next;
2537+
}
2538+
25042539
const ctx = locateKeyframeCtx(script, animationId, percentage);
25052540
if (!ctx) return script;
25062541
const { loc, kfNode } = ctx;
@@ -2640,19 +2675,29 @@ export function removeAllKeyframesFromScript(script: string, animationId: string
26402675
const kfNode =
26412676
findKeyframesObjectNode(loc.target.call.varsArg) ??
26422677
convertArrayKeyframesToObjectNode(loc.target.call.varsArg);
2643-
if (!kfNode) return script;
2644-
2645-
const kfEntries = filterPercentageProps(kfNode)
2646-
.map((p: AstNode) => ({ pct: percentageFromKey(propKeyName(p)!), prop: p }))
2647-
.filter((e) => !Number.isNaN(e.pct))
2648-
.sort((a, b) => a.pct - b.pct);
2649-
if (kfEntries.length === 0) return script;
2650-
2651-
// For to()/set(): collapse to last keyframe (the destination = visible state).
2652-
// For from(): collapse to first keyframe (the starting state).
26532678
const method = loc.target.call.method;
2654-
const collapseEntry = method === "from" ? kfEntries[0]! : kfEntries[kfEntries.length - 1]!;
2655-
const record = objectExpressionToRecord(collapseEntry.prop.value, loc.parsed.scope);
2679+
let record: Record<string, unknown>;
2680+
if (kfNode) {
2681+
const kfEntries = filterPercentageProps(kfNode)
2682+
.map((p: AstNode) => ({ pct: percentageFromKey(propKeyName(p)!), prop: p }))
2683+
.filter((e) => !Number.isNaN(e.pct))
2684+
.sort((a, b) => a.pct - b.pct);
2685+
if (kfEntries.length === 0) return script;
2686+
const collapseEntry = method === "from" ? kfEntries[0]! : kfEntries[kfEntries.length - 1]!;
2687+
record = objectExpressionToRecord(collapseEntry.prop.value, loc.parsed.scope);
2688+
} else {
2689+
// motionPath waypoints are exposed to Studio as synthetic keyframes. They
2690+
// have no literal `keyframes` node, so collapse the parsed endpoint and
2691+
// remove the authored path instead of silently returning the original file.
2692+
const synthetic = loc.target.animation.arcPath?.enabled
2693+
? loc.target.animation.keyframes?.keyframes
2694+
: undefined;
2695+
if (!synthetic?.length) return script;
2696+
const sorted = [...synthetic].sort((a, b) => a.percentage - b.percentage);
2697+
record = (method === "from" ? sorted[0] : sorted[sorted.length - 1])!.properties;
2698+
removeVarsKey(loc.target.call.varsArg, "motionPath");
2699+
}
2700+
26562701
collapseKeyframesToFlat(loc.target.call.varsArg, record);
26572702
// Removing ALL keyframes HOLDS the element statically — collapse to a
26582703
// zero-duration immediateRender tween (a `gsap.set` equivalent), dropping the

‎packages/parsers/src/gsapSerialize.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,36 @@ export interface GsapPercentageKeyframe {
9090
ease?: string;
9191
}
9292

93+
export interface WritableGsapPercentageKeyframe extends GsapPercentageKeyframe {
94+
auto?: boolean;
95+
}
96+
97+
/**
98+
* Collapse duplicate percentage entries before serializing an object literal.
99+
* Matches addKeyframeToScript's merge contract: later properties/ease win while
100+
* unrelated authored properties and an earlier ease survive. An explicit later
101+
* `auto` value wins, and output is always sorted by percentage.
102+
*/
103+
export function mergePercentageKeyframes(
104+
keyframes: readonly WritableGsapPercentageKeyframe[],
105+
): WritableGsapPercentageKeyframe[] {
106+
const byPercentage = new Map<number, WritableGsapPercentageKeyframe>();
107+
for (const keyframe of keyframes) {
108+
const existing = byPercentage.get(keyframe.percentage);
109+
if (!existing) {
110+
byPercentage.set(keyframe.percentage, {
111+
...keyframe,
112+
properties: { ...keyframe.properties },
113+
});
114+
continue;
115+
}
116+
existing.properties = { ...existing.properties, ...keyframe.properties };
117+
if (keyframe.ease !== undefined) existing.ease = keyframe.ease;
118+
if (keyframe.auto !== undefined) existing.auto = keyframe.auto;
119+
}
120+
return [...byPercentage.values()].sort((a, b) => a.percentage - b.percentage);
121+
}
122+
93123
export type GsapKeyframeFormat = "percentage" | "object-array" | "simple-array";
94124

95125
export interface GsapKeyframesData {

0 commit comments

Comments
 (0)