Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): place GSAP step lists and duration-less tweens where GSAP plays them (#5024)
Miguel Ángeldb12b3e022ef
diff --git a/packages/parsers/src/gsapConstants.ts b/packages/parsers/src/gsapConstants.tsindex b5a7948a3e..b4018b0290 100644--- a/packages/parsers/src/gsapConstants.ts+++ b/packages/parsers/src/gsapConstants.ts@@ -7,6 +7,8 @@import type { GsapAnimation } from "./gsapSerialize.js";+export const GSAP_DEFAULT_DURATION = 0.5;+export const SUPPORTED_PROPS = [// 2D Transforms"x",@@ -138,7 +140,7 @@ function knownStart(animation: GsapAnimation): number | undefined {}/**- * What a Studio hold pins from t=0 before a later keyframed tween: its first keyframe's position props,+ * What a Studio hold pins from t=0 before a later keyframed tween: its 0% keyframe's position props,* minus those an earlier timeline tween on the target writes (a global `gsap.set` is a base value).*/export function positionHoldForAnimation(@@ -148,10 +150,8 @@ export function positionHoldForAnimation(if (!animation.keyframes) return null;const start = knownStart(animation) ?? 0;if (!(start > 0.001)) return null;- const first = [...animation.keyframes.keyframes].sort(- (left, right) => left.percentage - right.percentage,- )[0];- if (!first) return null;+ const atStart = animation.keyframes.keyframes.find((keyframe) => keyframe.percentage === 0);+ if (!atStart) return null;// A tween whose start the parser could not resolve (a label, say) is not known to come first.const earlier = animations.filter((other) => {const otherStart = knownStart(other);@@ -164,7 +164,7 @@ export function positionHoldForAnimation();});const position: Record<string, number> = {};- for (const [property, value] of Object.entries(first.properties)) {+ for (const [property, value] of Object.entries(atStart.properties)) {if (classifyPropertyGroup(property) !== "position" || typeof value !== "number") continue;if (earlier.some((other) => writesProperty(other, property))) continue;position[property] = value;diff --git a/packages/parsers/src/gsapObjectArrayTiming.test.ts b/packages/parsers/src/gsapObjectArrayTiming.test.tsindex b1d554058f..6768f09f42 100644--- a/packages/parsers/src/gsapObjectArrayTiming.test.ts+++ b/packages/parsers/src/gsapObjectArrayTiming.test.ts@@ -6,9 +6,21 @@ import {} from "./gsapObjectArrayTiming.js";describe("getObjectArrayKeyframeTiming", () => {- it("preserves tenth-percent precision for evenly distributed arrays", () => {- expect(getObjectArrayKeyframeTiming([undefined, undefined, undefined, undefined])).toEqual({- percentages: [0, 33.3, 66.7, 100],+ it("ends each equal step at its share of the tween, to a tenth of a percent", () => {+ expect(getObjectArrayKeyframeTiming([undefined, undefined, undefined])).toEqual({+ percentages: [33.3, 66.7, 100],+ totalDuration: 1.5,+ });+ expect(getObjectArrayKeyframeTiming([undefined])).toEqual({+ percentages: [100],+ totalDuration: 0.5,+ });+ });++ it("gives a step without a duration GSAP's 0.5 s beside authored ones", () => {+ expect(getObjectArrayKeyframeTiming([1, undefined, 1])).toEqual({+ percentages: [40, 60, 100],+ totalDuration: 2.5,});});@@ -24,7 +36,6 @@ describe("getObjectArrayKeyframeTiming", () => {[[1, -1, 1], "negative"],[[1, Number.NaN, 1], "non-finite"],[[1, "__raw:total * 0.5", 1], "expression"],- [[1, undefined, 1], "partial"],])("rejects %s duration timing (%s)", (durations) => {expect(getObjectArrayKeyframeTiming(durations)).toBeNull();});diff --git a/packages/parsers/src/gsapObjectArrayTiming.ts b/packages/parsers/src/gsapObjectArrayTiming.tsindex 1b63e3202d..b18383c3a3 100644--- a/packages/parsers/src/gsapObjectArrayTiming.ts+++ b/packages/parsers/src/gsapObjectArrayTiming.ts@@ -1,6 +1,8 @@+import { GSAP_DEFAULT_DURATION } from "./gsapConstants.js";+export interface ObjectArrayKeyframeTiming {percentages: number[];- totalDuration?: number;+ totalDuration: number;}const roundPercentage = (percentage: number): number => Math.round(percentage * 10) / 10;@@ -8,40 +10,30 @@ const OBJECT_ARRAY_PERCENTAGE_TOLERANCE = 2;/*** Resolve GSAP object-array keyframe positions exactly once for parsers and writers.- * Authored per-step durations place each keyframe at its cumulative end; arrays- * without durations are distributed evenly. A partially-authored or invalid duration- * sequence is unresolved: callers must preserve the source rather than silently- * invent different timing.+ * Each step's keyframe sits at its cumulative end; a step without a duration plays+ * GSAP's default. A non-positive or unresolved duration leaves the timing unresolved:+ * callers must preserve the source rather than silently invent different timing.*/export function getObjectArrayKeyframeTiming(durations: ReadonlyArray<unknown>,): ObjectArrayKeyframeTiming | null {- const hasAuthoredDuration = durations.some((duration) => duration !== undefined);- if (hasAuthoredDuration) {- if (- !durations.every(- (duration): duration is number =>- typeof duration === "number" && Number.isFinite(duration) && duration > 0,- )- ) {- return null;- }- const totalDuration = durations.reduce<number>((sum, duration) => sum + duration, 0);- let cumulative = 0;- return {- percentages: durations.map((duration) => {- cumulative += duration;- return roundPercentage((cumulative / totalDuration) * 100);- }),- totalDuration,- };+ const steps = durations.map((duration) => duration ?? GSAP_DEFAULT_DURATION);+ if (+ !steps.every(+ (duration): duration is number =>+ typeof duration === "number" && Number.isFinite(duration) && duration > 0,+ )+ ) {+ return null;}-- const lastIndex = durations.length - 1;+ const totalDuration = steps.reduce((sum, duration) => sum + duration, 0);+ let cumulative = 0;return {- percentages: durations.map((_, index) =>- lastIndex > 0 ? roundPercentage((index / lastIndex) * 100) : 0,- ),+ percentages: steps.map((duration) => {+ cumulative += duration;+ return roundPercentage((cumulative / totalDuration) * 100);+ }),+ totalDuration,};}@@ -51,7 +43,8 @@ export function getCompatibleObjectArrayKeyframeTiming(): ObjectArrayKeyframeTiming | null {const timing = getObjectArrayKeyframeTiming(durations);if (!timing) return null;- if (timing.totalDuration === undefined || outerDuration === undefined) return timing;+ const stepsAuthorDuration = durations.some((duration) => duration !== undefined);+ if (!stepsAuthorDuration || outerDuration === undefined) return timing;if (typeof outerDuration === "number" &&Math.abs(outerDuration - timing.totalDuration) <= Number.EPSILONdiff --git a/packages/parsers/src/gsapParser.test.ts b/packages/parsers/src/gsapParser.test.tsindex fa010d8d10..f7d5c4b67e 100644--- a/packages/parsers/src/gsapParser.test.ts+++ b/packages/parsers/src/gsapParser.test.ts@@ -31,6 +31,7 @@ import {import type { GsapAnimation } from "./gsapParser.js";import { syncPositionHoldsBeforeKeyframes as syncPositionHoldsBeforeKeyframesAcorn } from "./gsapWriterAcorn.js";import { classifyPropertyGroup, classifyTweenPropertyGroup } from "./gsapConstants.js";+import { parseGsapScriptAcorn } from "./gsapParserAcorn.js";import type { Keyframe } from "./types.js";import {parseAndSerialize,@@ -1840,6 +1841,60 @@ describe("keyframe mutations", () => {expect(hold!.properties).toEqual({ x: -50, data: "hf-hold" });});+ // A step list starts from the element's value before the tween; its first step is an end value.+ it.each([+ ["recast", syncPositionHoldsBeforeKeyframes],+ ["acorn", syncPositionHoldsBeforeKeyframesAcorn],+ ])("%s: holds nothing for a delayed step list that has no start keyframe", (_, sync) => {+ for (const tween of [+ `tl.to("#x", { keyframes: [{ x: 60 }, { x: 120 }] }, 1);`,+ `tl.to("#x", { keyframes: { "50%": { x: 60 }, "100%": { x: 120 } }, duration: 1 }, 1);`,+ `tl.fromTo("#x", { x: 10 }, { keyframes: [{ x: 60 }, { x: 120 }] }, 1);`,+ ]) {+ expect(sync(`const tl = gsap.timeline({ paused: true });\n${tween}`)).not.toContain(+ "hf-hold",+ );+ }+ const partial =+ `const tl = gsap.timeline({ paused: true });\n` ++ `tl.to("#x", { keyframes: { "0%": { x: -50 }, "50%": { y: 30 }, "100%": { x: 60, y: 0 } }, duration: 1 }, 2);`;+ const hold = parseGsapScript(sync(partial)).animations.find((a) => a.method === "set");+ expect(hold!.properties).toEqual({ x: -50, data: "hf-hold" });+ });++ it.each([+ ["recast", parseGsapScript],+ ["acorn", parseGsapScriptAcorn],+ ])(+ "%s: takes timeline defaults as GSAP 3.15 does, never onto a step list or a keyframed ease",+ (_, parse) => {+ const tweens = [+ `tl.to("#a", { keyframes: [{ x: 1 }, { x: 2 }, { x: 3 }] }, 0);`,+ `tl.to("#b", { keyframes: { "0%": { x: 0 }, "100%": { x: 1 } } }, 0);`,+ `tl.to("#c", { motionPath: { path: [{ x: 0, y: 0 }, { x: 9, y: 9 }] } }, 0);`,+ `tl.to("#d", { keyframes: { "0%": { x: 0 }, "100%": { x: 9 } }, motionPath: { path: [{ x: 0, y: 0 }, { x: 9, y: 9 }] } }, 0);`,+ ].join("\n");+ const defaults = `{ defaults: { duration: 2, ease: "power2.in" } }`;+ const [steps, percentages, motionPath, both] = parse(+ `const tl = gsap.timeline(${defaults});\n${tweens}`,+ ).animations;+ expect([steps!.duration, percentages!.duration, motionPath!.duration]).toEqual([1.5, 2, 2]);+ expect([steps!.ease, percentages!.ease, motionPath!.ease, both!.ease]).toEqual([+ undefined,+ undefined,+ "power2.in",+ undefined,+ ]);+ expect(parse(`const tl = gsap.timeline();\n${tweens}`).animations[0]!.duration).toBe(1.5);+ },+ );++ it("acorn: a step list whose tween duration is a variable leaves its length unresolved", () => {+ const script = `const tl = gsap.timeline();\ntl.to("#a", { keyframes: [{ x: 1, duration: 1 }, { x: 2, duration: 1 }], duration: D }, 0);`;+ const anim = parseGsapScriptAcorn(script).animations[0]!;+ expect([anim.duration, anim.durationUnresolved]).toEqual([undefined, true]);+ });+it("acorn: a re-sync of a one-line script is byte-stable", () => {const once = syncPositionHoldsBeforeKeyframesAcorn(`const tl = gsap.timeline({ paused: true });tl.to("#t", { keyframes: { "0%": { x: -50 }, "100%": { x: 60 } }, duration: 1 }, 2);`,@@ -1999,15 +2054,14 @@ describe("keyframe mutations", () => {});// Array-form keyframes (`keyframes: [{x,y}, …]`) carry no percentages — GSAP- // distributes them evenly. The motion-path overlay drags/adds by percentage,- // which used to no-op on array-authored tweens (#puck-b / #shuttle).+ // ends step i of n at (i+1)/n. The motion-path overlay drags/adds by percentage.const ARRAY_KF_SCRIPT ="const tl = gsap.timeline();\n" +'tl.to("#shuttle", { keyframes: [{ x: 0, y: 0 }, { x: 520, y: 120 }, { x: 1040, y: 0 }, { x: 1480, y: 160 }], duration: 4.4, ease: "none" }, 5.2);';- it("updateKeyframeInScript — array-form: drags node 2 (pct 33.3) by index", () => {+ it("updateKeyframeInScript — array-form: drags node 2 (pct 50) by index", () => {const id = getAnimId(ARRAY_KF_SCRIPT);- const updated = updateKeyframeInScript(ARRAY_KF_SCRIPT, id, 33.3, { x: 503, y: 642 });+ const updated = updateKeyframeInScript(ARRAY_KF_SCRIPT, id, 50, { x: 503, y: 642 });expect(updated).not.toBe(ARRAY_KF_SCRIPT);const kf = parseGsapScript(updated).animations[0].keyframes!.keyframes;expect([kf[1]!.properties.x, kf[1]!.properties.y]).toEqual([503, 642]);@@ -2017,26 +2071,26 @@ describe("keyframe mutations", () => {it("updateKeyframeInScript — array-form ease-only update preserves existing properties", () => {const id = getAnimId(ARRAY_KF_SCRIPT);- const updated = updateKeyframeInScript(ARRAY_KF_SCRIPT, id, 33.3, {}, "power2.inOut");+ const updated = updateKeyframeInScript(ARRAY_KF_SCRIPT, id, 50, {}, "power2.inOut");const kf = parseGsapScript(updated).animations[0].keyframes!.keyframes;expect(kf[1]!.properties.x).toBe(520);expect(kf[1]!.properties.y).toBe(120);expect(kf[1]!.ease).toBe("power2.inOut");});- it("addKeyframeToScript — array-form: normalizes to object form + inserts 50%", () => {+ it("addKeyframeToScript — array-form: normalizes to object form + inserts 62.5%", () => {const id = getAnimId(ARRAY_KF_SCRIPT);- const updated = addKeyframeToScript(ARRAY_KF_SCRIPT, id, 50, { x: 780, y: 60 });+ const updated = addKeyframeToScript(ARRAY_KF_SCRIPT, id, 62.5, { x: 780, y: 60 });expect(updated).not.toBe(ARRAY_KF_SCRIPT);const kf = parseGsapScript(updated).animations[0].keyframes!.keyframes;- expect(kf.length).toBe(5);- const at50 = kf.find((k) => Math.abs(k.percentage - 50) < 1)!;- expect([at50.properties.x, at50.properties.y]).toEqual([780, 60]);+ expect(kf.map((k) => k.percentage)).toEqual([25, 50, 62.5, 75, 100]);+ const added = kf.find((k) => k.percentage === 62.5)!;+ expect([added.properties.x, added.properties.y]).toEqual([780, 60]);});- it("removeKeyframeFromScript — array-form: drops node 3 (pct 66.7)", () => {+ it("removeKeyframeFromScript — array-form: drops node 3 (pct 75)", () => {const id = getAnimId(ARRAY_KF_SCRIPT);- const updated = removeKeyframeFromScript(ARRAY_KF_SCRIPT, id, 66.7);+ const updated = removeKeyframeFromScript(ARRAY_KF_SCRIPT, id, 75);expect(updated).not.toBe(ARRAY_KF_SCRIPT);const kf = parseGsapScript(updated).animations[0].keyframes!.keyframes;expect(kf.length).toBe(3);diff --git a/packages/parsers/src/gsapParser.ts b/packages/parsers/src/gsapParser.tsindex 671140639c..33285abb4e 100644--- a/packages/parsers/src/gsapParser.ts+++ b/packages/parsers/src/gsapParser.ts@@ -52,6 +52,7 @@ export {import {classifyPropertyGroup,classifyTweenPropertyGroup,+ GSAP_DEFAULT_DURATION,isXYPositionWrite,positionHoldForAnimation,} from "./gsapConstants";@@ -1085,7 +1086,7 @@ function tweenCallToAnimation(percentage: waypoints.length > 1 ? Math.round((i / (waypoints.length - 1)) * 100) : 0,properties: { x: wp.x, y: wp.y },}));- keyframesData = { format: "percentage", keyframes: kf };+ keyframesData = { format: "percentage", keyframes: kf, fromMotionPath: true };} else {// Merge waypoint positions into existing keyframes at matching percentages.// If keyframe count matches waypoint count, assign positionally.@@ -1153,8 +1154,6 @@ function tweenCallToAnimation(// ── Timeline Position Resolution ──────────────────────────────────────────-const GSAP_DEFAULT_DURATION = 0.5;-// NOTE: Label-based positions (e.g. "myLabel+=0.5") are not yet resolved —// they fall through to parseFloat which returns null for non-numeric strings.function resolvePositionString(pos: string, cursor: number, prevStart: number): number | null {@@ -1192,7 +1191,11 @@ function applyTimelineDefaults(if (anim.duration === undefined && defaults.duration !== undefined) {anim.duration = defaults.duration;}- if (anim.ease === undefined && defaults.ease !== undefined) {+ if (+ anim.ease === undefined &&+ defaults.ease !== undefined &&+ (!anim.keyframes || anim.keyframes.fromMotionPath)+ ) {anim.ease = defaults.ease;}}@@ -2224,7 +2227,7 @@ function convertArrayKeyframesToObjectNode(varsArg: AstNode, scope: ScopeBindingouterDuration,);if (!timing) return null;- if (timing.totalDuration !== undefined && findPropertyNode(varsArg, "duration") === undefined) {+ if (findPropertyNode(varsArg, "duration") === undefined) {setVarsKey(varsArg, "duration", timing.totalDuration);}const entries = els.map((el: AstNode, i: number) => {@@ -2233,7 +2236,7 @@ function convertArrayKeyframesToObjectNode(varsArg: AstNode, scope: ScopeBinding);return `${JSON.stringify(`${timing.percentages[i]}%`)}: ${recast.print(el).code}`;});- prop.value = parseExpr(`{ ${entries.join(", ")} }`);+ prop.value = parseExpr(`{ ${entries.join(", ")}, easeEach: "none" }`);return prop.value;}diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.tsindex bcdd931546..d2ca97ff9b 100644--- a/packages/parsers/src/gsapParserAcorn.ts+++ b/packages/parsers/src/gsapParserAcorn.ts@@ -23,6 +23,7 @@ import {classifyTweenPropertyGroup,DROPPED_VAR_KEYS,EXTRAS_KEYS,+ GSAP_DEFAULT_DURATION,} from "./gsapConstants.js";import { buildArcPath } from "./gsapSerialize.js";import { inlineComputedTimelines, readProvenance } from "./gsapInline.js";@@ -1320,7 +1321,7 @@ function tweenCallToAnimation(percentage: waypoints.length > 1 ? Math.round((i / (waypoints.length - 1)) * 100) : 0,properties: { x: wp.x, y: wp.y },}));- keyframesData = { format: "percentage", keyframes: kf };+ keyframesData = { format: "percentage", keyframes: kf, fromMotionPath: true };} else {const kfs = keyframesData.keyframes;if (kfs.length === waypoints.length) {@@ -1360,11 +1361,11 @@ function tweenCallToAnimation(let duration = typeof vars.duration === "number" ? vars.duration : undefined;const ease = typeof vars.ease === "string" ? vars.ease : undefined;- if (duration === undefined && keyframesData) {- duration = computeKeyframesTotalDuration(call.varsArg, scope, source);- }const durationUnresolved =call.method !== "set" && duration === undefined && hasUnknownDuration(call.varsArg, scope);+ if (duration === undefined && keyframesData && !durationUnresolved) {+ duration = computeKeyframesTotalDuration(call.varsArg, scope, source);+ }// Relabel object-proxy / empty-target tweens so they don't read as bare// __unresolved__: a dwell/hold spacer or an onUpdate-driven DOM channel (#5/#11).@@ -1509,8 +1510,6 @@ function annotateStaggeredCollections(anims: Omit<GsapAnimation, "id">[]): void// ── Timeline position resolution ─────────────────────────────────────────────-const GSAP_DEFAULT_DURATION = 0.5;-// fallow-ignore-next-line complexityfunction resolvePositionString(pos: string, cursor: number, prevStart: number): number | null {const trimmed = pos.trim();@@ -1646,7 +1645,11 @@ function applyTimelineDefaults(if (defaults.duration !== undefined) anim.duration = defaults.duration;else if (defaults.durationUnresolved) anim.durationUnresolved = true;}- if (anim.ease === undefined && defaults.ease !== undefined && !anim.keyframes) {+ if (+ anim.ease === undefined &&+ defaults.ease !== undefined &&+ (!anim.keyframes || anim.keyframes.fromMotionPath)+ ) {anim.ease = defaults.ease;}}diff --git a/packages/parsers/src/gsapParserExports.ts b/packages/parsers/src/gsapParserExports.tsindex d2def7337b..d655365d18 100644--- a/packages/parsers/src/gsapParserExports.ts+++ b/packages/parsers/src/gsapParserExports.ts@@ -38,10 +38,12 @@ export {export { isStudioHoldSet } from "./gsapParser.js";export type { PropertyGroupName } from "./gsapConstants.js";export {+ GSAP_DEFAULT_DURATION,PROPERTY_GROUPS,classifyPropertyGroup,classifyTweenPropertyGroup,} from "./gsapConstants.js";+export { getObjectArrayKeyframeTiming } from "./gsapObjectArrayTiming.js";export { generateSpringEaseData, SPRING_PRESETS } from "./springEase.js";export type { SpringPreset } from "./springEase.js";export { parseGsapScriptAcorn as parseGsapScript } from "./gsapParserAcorn.js";diff --git a/packages/parsers/src/gsapSerialize.ts b/packages/parsers/src/gsapSerialize.tsindex d2651f8d6d..bb450d1969 100644--- a/packages/parsers/src/gsapSerialize.ts+++ b/packages/parsers/src/gsapSerialize.ts@@ -144,6 +144,7 @@ export interface GsapKeyframesData<K extends GsapPercentageKeyframe = GsapPercenkeyframes: K[];ease?: string;easeEach?: string;+ fromMotionPath?: true;}export interface ArcPathSegment {diff --git a/packages/parsers/src/gsapWriter.acorn.test.ts b/packages/parsers/src/gsapWriter.acorn.test.tsindex 67829fd503..45cb3b1830 100644--- a/packages/parsers/src/gsapWriter.acorn.test.ts+++ b/packages/parsers/src/gsapWriter.acorn.test.ts@@ -314,14 +314,14 @@ describe("T6c — keyframe write ops", () => {});it("updateKeyframeInScript edits ARRAY-form keyframes by percentage→index (the #shuttle case)", () => {- // Array-form keyframes carry no explicit percentages; GSAP distributes 4 of- // them evenly → 0 / 33.3 / 66.7 / 100. Dragging the 2nd motion-path node- // (pct 33.3) must rewrite array index 1 — not no-op (regression: array form+ // Array-form keyframes carry no explicit percentages; GSAP ends 4 equal+ // steps at 25 / 50 / 75 / 100. Dragging the 2nd motion-path node+ // (pct 50) must rewrite array index 1 — not no-op (regression: array form// bailed the ObjectExpression check, so the drag committed nothing).const script ="const tl = gsap.timeline();\n" +'tl.to("#shuttle", { keyframes: [{ x: 0, y: 0 }, { x: 520, y: 120 }, { x: 1040, y: 0 }, { x: 1480, y: 160 }], duration: 4.4, ease: "none" }, 5.2);';- const result = updateKeyframeInScript(script, "#shuttle-to-5200-position", 33.3, {+ const result = updateKeyframeInScript(script, "#shuttle-to-5200-position", 50, {x: 503,y: 642,});@@ -356,17 +356,21 @@ describe("T6c — keyframe write ops", () => {expect(kf.keyframes.map((k) => k.properties.x)).toEqual([0, 50, 100]);});- it("addKeyframeToScript — ARRAY-form normalizes to object form + inserts 50%", () => {+ it("addKeyframeToScript — ARRAY-form normalizes to object form + inserts 62.5%", () => {const script ="const tl = gsap.timeline();\n" +'tl.to("#shuttle", { keyframes: [{ x: 0, y: 0 }, { x: 520, y: 120 }, { x: 1040, y: 0 }, { x: 1480, y: 160 }], duration: 4.4, ease: "none" }, 5.2);';- const result = addKeyframeToScript(script, "#shuttle-to-5200-position", 50, { x: 780, y: 60 });+ const result = addKeyframeToScript(script, "#shuttle-to-5200-position", 62.5, {+ x: 780,+ y: 60,+ });expect(result).not.toBe(script); // not a no-op- expect(result).toContain('"50%"'); // converted to percentage-object form+ expect(result).toContain('"62.5%"'); // converted to percentage-object formexpect(result).toContain("x: 780");- // Original even-distribution stops preserved as percentage keys.- expect(result).toContain('"0%"');+ // Original step ends preserved as percentage keys; no 0% is invented.+ expect(result).toContain('"25%"');expect(result).toContain('"100%"');+ expect(result).not.toContain('"0%"');});it("addKeyframeToScript inserts new percentage in sorted order", () => {diff --git a/packages/parsers/src/gsapWriter.parity.test.ts b/packages/parsers/src/gsapWriter.parity.test.tsindex 84401d55be..21005ef3a3 100644--- a/packages/parsers/src/gsapWriter.parity.test.ts+++ b/packages/parsers/src/gsapWriter.parity.test.ts@@ -238,15 +238,15 @@ describe("removeKeyframeFromScript: array-form keyframes (recast + acorn parity)const id = acornId(arrayScript);expect(parseGsapScript(arrayScript).animations[0]!.id).toBe(id);- const recastOut = removeKeyframeRecast(arrayScript, id, 67);- const acornOut = removeKeyframeAcorn(arrayScript, id, 67);+ const recastOut = removeKeyframeRecast(arrayScript, id, 75);+ const acornOut = removeKeyframeAcorn(arrayScript, id, 75);expect(recastOut).not.toBe(arrayScript);expect(acornOut).not.toBe(arrayScript);const recShape = shapeOf(recastOut);expect(recShape.keyframes?.keyframes.length).toBe(3);- // the 67% element { x: -320, y: 40 } is the one removed+ // the 75% element { x: -320, y: 40 } is the one removedexpect(JSON.stringify(recShape.keyframes)).not.toContain("-320");expect(modelOf(acornOut)).toEqual(modelOf(recastOut));});@@ -1320,25 +1320,25 @@ describe("moveKeyframeInScript: array-form keyframes (recast + acorn parity)", (] as const) {it(`${label}: normalizes the array then retimes the moved keyframe`, () => {const id = acornId(KF_ADD_ARRAY_SCRIPT);- const out = move(KF_ADD_ARRAY_SCRIPT, id, 50, 75);+ const out = move(KF_ADD_ARRAY_SCRIPT, id, 66.7, 50);expect(out).not.toBe(KF_ADD_ARRAY_SCRIPT);const kfs = shapeOf(out).keyframes?.keyframes ?? [];- expect(kfs.map((k) => k.percentage)).toEqual([0, 75, 100]);- expect(kfs.find((k) => k.percentage === 75)!.properties).toEqual({ x: 50, y: 80 });+ expect(kfs.map((k) => k.percentage)).toEqual([33.3, 50, 100]);+ expect(kfs.find((k) => k.percentage === 50)!.properties).toEqual({ x: 50, y: 80 });});}it("parity: both writers reparse to the same model", () => {const id = acornId(KF_ADD_ARRAY_SCRIPT);- expect(modelOf(moveKeyframeAcorn(KF_ADD_ARRAY_SCRIPT, id, 50, 75))).toEqual(- modelOf(moveKeyframeRecast(KF_ADD_ARRAY_SCRIPT, id, 50, 75)),+ expect(modelOf(moveKeyframeAcorn(KF_ADD_ARRAY_SCRIPT, id, 66.7, 50))).toEqual(+ modelOf(moveKeyframeRecast(KF_ADD_ARRAY_SCRIPT, id, 66.7, 50)),);});it("leaves array-form source untouched when the destination is occupied", () => {const id = acornId(KF_ADD_ARRAY_SCRIPT);- expect(moveKeyframeAcorn(KF_ADD_ARRAY_SCRIPT, id, 50, 100)).toBe(KF_ADD_ARRAY_SCRIPT);- expect(moveKeyframeRecast(KF_ADD_ARRAY_SCRIPT, id, 50, 100)).toBe(KF_ADD_ARRAY_SCRIPT);+ expect(moveKeyframeAcorn(KF_ADD_ARRAY_SCRIPT, id, 66.7, 100)).toBe(KF_ADD_ARRAY_SCRIPT);+ expect(moveKeyframeRecast(KF_ADD_ARRAY_SCRIPT, id, 66.7, 100)).toBe(KF_ADD_ARRAY_SCRIPT);});it("normalizes duration-authored percentages before moving", () => {@@ -1448,8 +1448,8 @@ describe("resizeKeyframedTweenInScript: preserves author intent (acorn + recast)// drag-to-retime re-keys existing keyframes to arbitrary percentages, which an// array can't host. Both writers now normalize array → object form first.const RESIZE_ARRAY_REMAP = [- { from: 0, to: 0 },- { from: 50, to: 25 },+ { from: 33.3, to: 16.7 },+ { from: 66.7, to: 33.3 },{ from: 100, to: 100 },];@@ -1463,8 +1463,8 @@ describe("resizeKeyframedTweenInScript: array-form keyframes (recast + acorn parconst out = resize(KF_ADD_ARRAY_SCRIPT, id, 0.2, 2, RESIZE_ARRAY_REMAP);expect(out).not.toBe(KF_ADD_ARRAY_SCRIPT);const kfs = shapeOf(out).keyframes?.keyframes ?? [];- expect(kfs.map((k) => k.percentage)).toEqual([0, 25, 100]);- expect(kfs.find((k) => k.percentage === 25)!.properties).toEqual({ x: 50, y: 80 });+ expect(kfs.map((k) => k.percentage)).toEqual([16.7, 33.3, 100]);+ expect(kfs.find((k) => k.percentage === 33.3)!.properties).toEqual({ x: 50, y: 80 });});}diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.tsindex 19c3019042..454208c1b3 100644--- a/packages/parsers/src/gsapWriterAcorn.ts+++ b/packages/parsers/src/gsapWriterAcorn.ts@@ -1089,8 +1089,8 @@ export function updateKeyframeInScript(}// Array-form keyframes (`keyframes: [{x,y}, ...]`) carry no explicit percentages- // — GSAP distributes them evenly, and the runtime read assigns even percentages- // (0, 100/(n-1), …). Map the percentage back to an array index and overwrite that+ // — GSAP ends step i of n at its cumulative share (getObjectArrayKeyframeTiming).+ // Map the percentage back to an array index and overwrite that// element in place (preserving the array form). Without this the function bailed// on the ObjectExpression check, so dragging a motion-path node on an array-form// tween committed nothing (server no-op).@@ -1226,11 +1226,12 @@ function convertArrayKeyframesToObject(script: string, target: Node): string {return `${JSON.stringify(`${timing.percentages[i]}%`)}: ${recordToCode(record)}`;});const ms = new MagicString(script);- ms.overwrite(kfPropNode.value.start, kfPropNode.value.end, `{ ${entries.join(", ")} }`);- if (- timing.totalDuration !== undefined &&- findPropertyNode(target.call.varsArg, "duration") === undefined- ) {+ ms.overwrite(+ kfPropNode.value.start,+ kfPropNode.value.end,+ `{ ${entries.join(", ")}, easeEach: "none" }`,+ );+ if (findPropertyNode(target.call.varsArg, "duration") === undefined) {upsertProp(ms, target.call.varsArg, "duration", timing.totalDuration);}return ms.toString();diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.tsindex 4ec9f359b3..573e7f0270 100644--- a/packages/studio-server/src/routes/files.ts+++ b/packages/studio-server/src/routes/files.ts@@ -1357,7 +1357,7 @@ function resolveReplacementEaseEach(// Mutations that can change a position tween's first keyframe (value/existence/timing)// and therefore require the pre-keyframe hold-`set`s to be re-synced afterwards.// `syncPositionHoldsBeforeKeyframes` rebuilds all `hf-hold` sets from scratch: it acts-// on every tween that has keyframes whose first percentage carries a position prop and+// on every tween whose 0% keyframe carries a position prop and// whose start is > 0. So any mutation that creates such a tween, retargets it, or moves// its start across the t=0 boundary must trigger a re-sync.const HOLD_SYNC_MUTATION_TYPES = new Set<string>([diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsxindex 0f317b623b..f4d0a18d1d 100644--- a/packages/studio/src/components/TimelineToolbar.tsx+++ b/packages/studio/src/components/TimelineToolbar.tsx@@ -11,7 +11,7 @@ import {isPlayheadWithinTween,type EnableKeyframesSession,} from "../hooks/useEnableKeyframes";-import { computeElementPercentage, KEYFRAME_PCT_MATCH } from "../hooks/gsapShared";+import { computeElementPercentage, playsNear } from "../hooks/gsapShared";import { useKeyframeKeyboard } from "../hooks/useKeyframeKeyboard";import {getNextTimelineZoomPercent,@@ -73,9 +73,8 @@ const NO_KEYFRAME_TOGGLE: KeyframeToggleState = {function isMotionPathEndpoint(animation: GsapAnimation | undefined, percentage: number): boolean {if (!animation?.keyframes) return false;const keyframes = animation.keyframes.keyframes;- return (- Math.abs((keyframes[0]?.percentage ?? -Infinity) - percentage) <= KEYFRAME_PCT_MATCH ||- Math.abs((keyframes.at(-1)?.percentage ?? Infinity) - percentage) <= KEYFRAME_PCT_MATCH+ return [keyframes[0], keyframes.at(-1)].some(+ (keyframe) => keyframe && playsNear(animation, keyframe.percentage, percentage),);}@@ -93,14 +92,14 @@ function resolveKeyframeToggleState(if (!animation?.keyframes) return NO_KEYFRAME_TOGGLE;const isMotionPath = Boolean(arcAnimation);- if (!isPlayheadWithinTween(animation, currentTime, session.domEditSelection)) {+ if (!isPlayheadWithinTween(animation, currentTime)) {return { state: "inactive", isMotionPath, pathEndpoint: false, willExtend: true };}const percentage = computeElementPercentage(currentTime, session.domEditSelection, animation);const pathEndpoint = isMotionPathEndpoint(arcAnimation, percentage);- const active = animation.keyframes.keyframes.some(- (keyframe) => Math.abs(keyframe.percentage - percentage) <= KEYFRAME_PCT_MATCH,+ const active = animation.keyframes.keyframes.some((keyframe) =>+ playsNear(animation, keyframe.percentage, percentage),);return {state: pathEndpoint ? "none" : active ? "active" : "inactive",diff --git a/packages/studio/src/components/editor/keyframeRetime.ts b/packages/studio/src/components/editor/keyframeRetime.tsindex c722e6abb0..a7ef2a3ec9 100644--- a/packages/studio/src/components/editor/keyframeRetime.ts+++ b/packages/studio/src/components/editor/keyframeRetime.ts@@ -14,6 +14,7 @@* Kept pure (no React/store/GSAP) so the trickiest math is unit-testable. The* caller supplies the resolved tween window + the drop's absolute time.*/+import { progressAtTime, timeAtProgress } from "../../utils/gsapKeyframeEases";export interface RetimeKeyframe {/** Tween-relative percentage (the writer/runtime key on this). */@@ -92,6 +93,7 @@ function resolveFlatTweenBoundaryRetime(opts: {* - `draggedTweenPct`: identifies which keyframe is being dragged (closest match).* - `tweenStart` / `tweenDuration`: the tween's resolved absolute window.* - `dropAbsTime`: the drop's absolute time (handler converts clip-% → seconds).+ * - `runEase`: the tween's run ease, which decides when each keyframe plays.*/export function resolveKeyframeRetime(opts: {keyframes: ReadonlyArray<RetimeKeyframe>;@@ -99,8 +101,9 @@ export function resolveKeyframeRetime(opts: {tweenStart: number;tweenDuration: number;dropAbsTime: number;+ runEase?: string;}): KeyframeRetimeResult {- const { keyframes, draggedTweenPct, tweenStart, tweenDuration, dropAbsTime } = opts;+ const { keyframes, draggedTweenPct, tweenStart, tweenDuration, dropAbsTime, runEase } = opts;if (tweenDuration <= 0) return { kind: "noop" };const tweenEnd = tweenStart + tweenDuration;@@ -124,7 +127,8 @@ export function resolveKeyframeRetime(opts: {// Round here, not at the return: the no-op test below and the value written// to source must be the same number. The resize branch already rounds, so// this keeps both write paths at the authored 3dp precision.- const toTweenPct = round3(clamp(((dropAbsTime - tweenStart) / tweenDuration) * 100, 0, 100));+ const dropTimePct = clamp(((dropAbsTime - tweenStart) / tweenDuration) * 100, 0, 100);+ const toTweenPct = round3(progressAtTime(runEase, dropTimePct));if (Math.abs(toTweenPct - draggedTweenPct) < NOOP_EPSILON_PCT) return { kind: "noop" };return { kind: "move", toTweenPct };}@@ -154,8 +158,11 @@ export function resolveKeyframeRetime(opts: {// survive verbatim (no rebuilt keyframes array).const pctRemap: KeyframePctRemap[] = keyframes.map((kf, i) => {const absTime =- i === draggedIdx ? dropAbsTime : tweenStart + (kf.percentage / 100) * tweenDuration;- return { from: kf.percentage, to: round3(((absTime - newStart) / newDuration) * 100) };+ i === draggedIdx+ ? dropAbsTime+ : tweenStart + (timeAtProgress(runEase, kf.percentage) / 100) * tweenDuration;+ const newTimePct = ((absTime - newStart) / newDuration) * 100;+ return { from: kf.percentage, to: round3(progressAtTime(runEase, newTimePct)) };});return {diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsxindex 53a6a64270..f531535115 100644--- a/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx+++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.test.tsx@@ -679,6 +679,33 @@ describe("useTimelineEditCallbacks — flat tween keyframe lanes", () => {view.unmount();});+ it("retimes a duration-less tween's keyframe in the window GSAP plays it, not the clip", async () => {+ const durationless = { ...authoredInteriorAnimation(), duration: undefined };+ mocks.animations = [durationless];+ usePlayerStore.setState({ gsapAnimations: new Map([["box", [durationless]]]) });+ const view = renderCallbacks();++ // GSAP plays it 0-0.5 s of the 1 s clip, so a drop at 0.4 s is 80% of the tween.+ await view.callbacks.onMoveKeyframe?.(+ "box",+ {+ percentage: 25,+ propertyGroup: "position",+ tweenPercentage: 50,+ animationId: durationless.id,+ },+ 40,+ );++ expect(mocks.actions.handleGsapMoveKeyframe).toHaveBeenCalledWith(+ durationless.id,+ 50,+ 80,+ mocks.selection,+ );+ view.unmount();+ });+// A drag starts on whatever diamond the pointer is over, which need not be the// selected element. Resolving against the selection would retime the selected// element's tween and commit it through the selected element's file.@@ -777,46 +804,4 @@ describe("useTimelineEditCallbacks — flat tween keyframe lanes", () => {expect(mocks.actions.handleGsapMoveKeyframe).not.toHaveBeenCalled();view.unmount();});-- it("uses the clip timing basis when retiming a duration-less tween", async () => {- const durationless = {- ...authoredInteriorAnimation(),- position: 3.2,- resolvedStart: 3.2,- duration: undefined,- };- const wideElement = { ...element, start: 10.94, duration: 16.26 };- mocks.animations = [durationless];- usePlayerStore.setState({- elements: [wideElement],- gsapAnimations: new Map([["box", [durationless]]]),- });- const view = renderCallbacks();-- await expect(- view.callbacks.onMoveKeyframe?.(- "box",- {- percentage: 19.1,- propertyGroup: "position",- tweenPercentage: 50,- animationId: durationless.id,- },- 40,- ),- ).resolves.toBe(true);-- // The whole point of the clip basis: the drop lands at 10.94 + 0.40 * 16.26 =- // 17.444s, and the duration-less tween borrows the clip's 16.26s window from- // its 3.2s start, so 17.444 - 3.2 over 16.26 is 87.601%. Any other basis (a- // zero-length tween, or the clip's own 0-100 %) produces a different number.- expect(mocks.actions.handleGsapMoveKeyframe).toHaveBeenCalledWith(- durationless.id,- 50,- expect.closeTo(87.601, 3),- mocks.selection,- );- expect(mocks.actions.handleGsapResizeKeyframedTween).not.toHaveBeenCalled();- view.unmount();- });});diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.tsindex 76792031c6..1faada4c3c 100644--- a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts+++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts@@ -12,6 +12,7 @@ import {useDomEditSelectionContext,} from "../../contexts/DomEditContext";import { resolveTweenStart, resolveTweenDuration } from "../../utils/globalTimeCompiler";+import { runEaseOf } from "../../utils/gsapKeyframeEases";import { resolveClipTimingBasis } from "../../hooks/useGsapTweenCache";import { elementCacheKeys } from "../../hooks/gsapKeyframeCacheHelpers";import { resolveKeyframeRetime } from "../editor/keyframeRetime";@@ -331,7 +332,7 @@ export function useTimelineEditCallbacks({elements,domClipChildren,);- const tweenDuration = resolveTweenDuration(anim, elDuration);+ const tweenDuration = resolveTweenDuration(anim);const dropAbsTime = elStart + (toClipPct / 100) * elDuration;const decision = resolveKeyframeRetime({keyframes: anim.keyframes?.keyframes ?? [],@@ -339,6 +340,7 @@ export function useTimelineEditCallbacks({tweenStart,tweenDuration,dropAbsTime,+ runEase: runEaseOf(anim),});if (decision.kind === "move" && decision.toTweenPct != null) {return handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct, sel);diff --git a/packages/studio/src/hooks/gsapDragCommit.ts b/packages/studio/src/hooks/gsapDragCommit.tsindex edc7f4873e..2461fbf2bd 100644--- a/packages/studio/src/hooks/gsapDragCommit.ts+++ b/packages/studio/src/hooks/gsapDragCommit.ts@@ -5,7 +5,11 @@import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { usePlayerStore } from "../player/store/playerStore";-import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";+import {+ percentageToAbsoluteForAnimation,+ resolveTweenStart,+ resolveTweenDuration,+} from "../utils/globalTimeCompiler";import { roundTo3, roundToLayoutPx } from "../utils/rounding";import { computeElementPercentage, keyframeEases, writeTargetSelector } from "./gsapShared";import { computeDraggedGsapPosition } from "./draggedGsapPosition";@@ -54,10 +58,9 @@ export function computeCurrentPercentage(// 1.2 start), so the post-commit reseek renders the element's base pose and the edit// looks like it snapped away. Keeping the playhead on the edited keyframe avoids that.export function parkPlayheadOnKeyframe(anim: GsapAnimation, pct: number): void {- const ts = resolveTweenStart(anim);- const td = resolveTweenDuration(anim);- if (ts == null || !td || td <= 0) return;- usePlayerStore.getState().requestSeek(roundTo3(ts + (pct / 100) * td));+ const time = percentageToAbsoluteForAnimation(pct, anim);+ if (time === null || resolveTweenDuration(anim) <= 0) return;+ usePlayerStore.getState().requestSeek(roundTo3(time));}async function replaceKeyframedPositionHold(diff --git a/packages/studio/src/hooks/gsapDragPositionCommit.ts b/packages/studio/src/hooks/gsapDragPositionCommit.tsindex 27dda31bd1..6c845dfd11 100644--- a/packages/studio/src/hooks/gsapDragPositionCommit.ts+++ b/packages/studio/src/hooks/gsapDragPositionCommit.ts@@ -1,8 +1,13 @@-import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import type { GsapAnimation, GsapPercentageKeyframe } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { usePlayerStore } from "../player/store/playerStore";-import { resolveTweenStart } from "../utils/globalTimeCompiler";-import { KEYFRAME_PCT_MATCH, resolveEditableTweenDuration } from "./gsapShared";+import {+ isTimeWithinTween,+ resolveTweenDuration,+ resolveTweenStart,+} from "../utils/globalTimeCompiler";+import { KEYFRAME_PCT_MATCH, playsNear } from "./gsapShared";+import { progressAtTime, runEaseOf, timeAtProgress } from "../utils/gsapKeyframeEases";import { roundTo3 } from "../utils/rounding";import { computeDraggedGsapPosition } from "./draggedGsapPosition";import {@@ -19,7 +24,8 @@ import { commitValueAtPlayhead, planValueEdit } from "./gsapValueAtPlayhead";* server takes a replace-with-keyframes list verbatim, so an append-only build* could hand it two keyframes a fraction of a percent apart. The invariant lives* here rather than in each caller's own pre-check, which is how the two callers- * ended up with different tolerances in the first place.+ * ended up with different tolerances in the first place. Arc writes are linear, so each+ * keyframe moves to the time GSAP reached it and `percentage` is a time percentage.*/export function buildTemporalArcKeyframes(anim: GsapAnimation,@@ -27,7 +33,7 @@ export function buildTemporalArcKeyframes(properties: Record<string, number>,) {return [- ...(anim.keyframes?.keyframes ?? [])+ ...linearArcKeyframes(anim).filter((keyframe) => Math.abs(keyframe.percentage - percentage) > KEYFRAME_PCT_MATCH).map((keyframe) => ({percentage: keyframe.percentage,@@ -38,6 +44,46 @@ export function buildTemporalArcKeyframes(].sort((a, b) => a.percentage - b.percentage);}+/** An arc's keyframes at the time percentages GSAP plays them, for a write with `ease: "none"`. */+export function linearArcKeyframes(anim: GsapAnimation): GsapPercentageKeyframe[] {+ const runEase = runEaseOf(anim);+ return (anim.keyframes?.keyframes ?? []).map((keyframe) => ({+ ...keyframe,+ percentage: roundTo3(timeAtProgress(runEase, keyframe.percentage)),+ }));+}++/** Grow a keyframe tween's range to a playhead outside it and add a keyframe there; every+ * existing keyframe keeps its absolute time under `writeEase`, the run ease the write keeps. */+export function buildExtendedKeyframes(+ anim: GsapAnimation,+ currentTime: number,+ position: Record<string, number>,+ sourceDuration = resolveTweenDuration(anim),+ writeEase = runEaseOf(anim),+): { position: number; duration: number; keyframes: GsapPercentageKeyframe[] } {+ const oldStart = resolveTweenStart(anim) ?? 0;+ const oldDuration = sourceDuration;+ const newStart = Math.min(oldStart, currentTime);+ const newEnd = Math.max(oldStart + oldDuration, currentTime);+ const newDuration = roundTo3(newEnd - newStart);+ const oldRunEase = runEaseOf(anim);+ const toPct = (absoluteTime: number) => {+ if (newDuration <= 0) return 0;+ const progress = progressAtTime(writeEase, ((absoluteTime - newStart) / newDuration) * 100);+ return Math.max(0, Math.min(100, Math.round(progress * 10) / 10));+ };+ const stops = anim.keyframes?.keyframes ?? [];+ const rescaled: GsapPercentageKeyframe[] = stops.map((stop) => ({+ percentage: toPct(oldStart + (timeAtProgress(oldRunEase, stop.percentage) / 100) * oldDuration),+ properties: stop.properties,+ ...(stop.ease ? { ease: stop.ease } : {}),+ }));+ const added: GsapPercentageKeyframe = { percentage: toPct(currentTime), properties: position };+ const keyframes = [...rescaled, added].sort((a, b) => a.percentage - b.percentage);+ return { position: roundTo3(newStart), duration: newDuration, keyframes };+}+/** commitGsapPositionFromDrag's refusal, decided without writing. */export function gsapPositionFromDragOutcome(selection: DomEditSelection,@@ -87,15 +133,45 @@ export async function commitGsapPositionFromDrag(};if (anim.arcPath?.enabled) {- const { activeKeyframePct, setActiveKeyframePct } = usePlayerStore.getState();+ const { activeKeyframePct, currentTime, setActiveKeyframePct } = usePlayerStore.getState();+ const tweenStart = resolveTweenStart(anim);+ const tweenDuration = resolveTweenDuration(anim);+ if (+ activeKeyframePct === null &&+ tweenStart !== null &&+ !isTimeWithinTween(currentTime, tweenStart, tweenDuration)+ ) {+ const extended = buildExtendedKeyframes(+ anim,+ currentTime,+ { x: newX, y: newY },+ tweenDuration,+ "none",+ );+ await callbacks.commitMutation(+ selection,+ {+ type: "replace-with-keyframes",+ animationId: anim.id,+ targetSelector: anim.targetSelector,+ ...extended,+ ease: "none",+ },+ {+ label: "Move layer (new keyframe)",+ keyframeAction: "add",+ softReload: true,+ beforeReload: restoreOffset,+ },+ );+ return { status: "persisted" };+ }const pct = activeKeyframePct ?? computeCurrentPercentage(selection, anim);const keyframes = anim.keyframes?.keyframes ?? [];- // Same tolerance as applyArcKeyframeAtPlayhead and isMotionPathEndpoint. A- // tighter one here meant a drag that landed a fraction of a percent off an- // authored waypoint skipped the update-point branch and appended instead.- const pointIndex = keyframes.findIndex(- (kf) => Math.abs(kf.percentage - pct) <= KEYFRAME_PCT_MATCH,- );+ // A drag counts as on a waypoint when it plays within KEYFRAME_PCT_MATCH of it,+ // so landing a fraction of a percent off an authored waypoint updates that point+ // instead of appending a new one.+ const pointIndex = keyframes.findIndex((kf) => playsNear(anim, kf.percentage, pct));if (pointIndex >= 0) {await callbacks.commitMutation(selection,@@ -113,13 +189,10 @@ export async function commitGsapPositionFromDrag(return { status: "persisted" };}- const tweenStart = resolveTweenStart(anim);- // Clip-wide, same as applyArcKeyframeAtPlayhead: authoring GSAP's 0.5s- // default here would collapse a duration-less arc's window on drag.- const tweenDuration = resolveEditableTweenDuration(anim, selection);if (tweenStart === null || tweenDuration <= 0 || keyframes.length < 2)return { status: "persisted" };- const temporalKeyframes = buildTemporalArcKeyframes(anim, pct, { x: newX, y: newY });+ const timePct = roundTo3(timeAtProgress(runEaseOf(anim), pct));+ const temporalKeyframes = buildTemporalArcKeyframes(anim, timePct, { x: newX, y: newY });await callbacks.commitMutation(selection,{diff --git a/packages/studio/src/hooks/gsapOvershootEase.test.ts b/packages/studio/src/hooks/gsapOvershootEase.test.tsnew file mode 100644index 0000000000..2e04b5b17e--- /dev/null+++ b/packages/studio/src/hooks/gsapOvershootEase.test.ts@@ -0,0 +1,67 @@+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn";+import { replaceTweenWithKeyframesInScript } from "@hyperframes/parsers/gsap-writer-acorn";+import { describe, expect, it } from "vitest";+import { resolveKeyframeRetime } from "../components/editor/keyframeRetime";+import { absoluteToPercentageForAnimation } from "../utils/globalTimeCompiler";+import { runEaseOf, timeAtProgress } from "../utils/gsapKeyframeEases";+import { buildExtendedKeyframes } from "./gsapDragPositionCommit";+import { keyframeEases } from "./gsapShared";++const script = (ease: string) =>+ `const tl = gsap.timeline({ paused: true });\ntl.to("#x", { keyframes: { "0%": { x: 0 }, "50%": { x: 600 }, "100%": { x: 1200 } }, duration: 2, ease: "${ease}" }, 1);`;++const percentages = (anim: GsapAnimation) => anim.keyframes!.keyframes.map((k) => k.percentage);+const distinctInRange = (pcts: number[]) =>+ pcts.every((p, i) => p >= 0 && p <= 100 && (i === 0 || p > pcts[i - 1]!));++describe.each(["back.out(1.7)", "back.in(1.7)", "elastic.out(1, 0.3)", "steps(4)"])(+ "an outer %s, which does not map time to progress one to one",+ (ease) => {+ const src = script(ease);+ const anim = parseGsapScriptAcorn(src).animations[0]!;++ it("adding a keyframe past the end keeps every keyframe, distinct and in range, after a reparse", () => {+ const out = buildExtendedKeyframes(anim, 5, { x: 1500 });+ const written = replaceTweenWithKeyframesInScript(src, anim.id, {+ targetSelector: "#x",+ ...keyframeEases(anim),+ ...out,+ })!;+ const back = parseGsapScriptAcorn(written).animations[0]!;+ expect(distinctInRange(percentages(back))).toBe(true);+ expect(back.keyframes!.keyframes.map((k) => k.properties.x)).toEqual([0, 600, 1200, 1500]);+ });++ it("a keyframe added inside the tween lands within 0-100%", () => {+ const pct = absoluteToPercentageForAnimation(1 + 0.7 * 2, anim)!;+ expect(pct).toBeGreaterThanOrEqual(0);+ expect(pct).toBeLessThanOrEqual(100);+ });++ it("dragging the last keyframe later keeps every keyframe distinct and in range", () => {+ const retime = resolveKeyframeRetime({+ keyframes: anim.keyframes!.keyframes,+ draggedTweenPct: 100,+ tweenStart: 1,+ tweenDuration: 2,+ dropAbsTime: 4,+ runEase: runEaseOf(anim),+ });+ expect(retime.kind).toBe("resize");+ expect(distinctInRange(retime.pctRemap!.map((r) => r.to))).toBe(true);+ });+ },+);++it("extending a tween under steps(4) loses no keyframe", () => {+ const src = `const tl = gsap.timeline({ paused: true });\ntl.to("#x", { keyframes: { "0%": { x: 0 }, "25%": { x: 60 }, "60%": { x: 120 }, "100%": { x: 30 } }, duration: 2, ease: "steps(4)" }, 1);`;+ const anim = parseGsapScriptAcorn(src).animations[0]!;+ const out = buildExtendedKeyframes(anim, 4, { x: 999 });+ expect(distinctInRange(out.keyframes.map((k) => k.percentage))).toBe(true);+ expect(out.keyframes.map((k) => k.properties.x)).toEqual([0, 60, 120, 30, 999]);+});++it("still times keyframes through an outer ease that rises one to one", () => {+ expect(timeAtProgress("power2.in", 50)).toBeCloseTo(79.37, 1);+});diff --git a/packages/studio/src/hooks/gsapParsedTween.ts b/packages/studio/src/hooks/gsapParsedTween.tsindex 71848cdad7..beedf8fecb 100644--- a/packages/studio/src/hooks/gsapParsedTween.ts+++ b/packages/studio/src/hooks/gsapParsedTween.ts@@ -247,14 +247,13 @@ const BUILT_IN_EASES = [export function withExactStepTimes(anim: GsapAnimation, tween: ParsedTween | null): GsapAnimation {const data = anim.keyframes;const parts = tween?.timeline?.getChildren?.() ?? [];- const total = tween?.timeline?.duration?.() ?? 0;- if (data?.format !== "object-array" || parts.length !== data.keyframes.length || !(total > 0))- return anim;- const ends = parts.map((part) => ((part.startTime?.() ?? 0) + (part.duration?.() ?? 0)) / total);- if (ends.some((end) => !Number.isFinite(end))) return anim;+ if (data?.format !== "object-array" || parts.length !== data.keyframes.length) return anim;+ const ends = parts.map((part) => (part.startTime?.() ?? 0) + (part.duration?.() ?? 0));+ const total = Math.max(...ends);+ if (!(total > 0) || ends.some((end) => !Number.isFinite(end))) return anim;const keyframes = data.keyframes.map((kf, i) => ({...kf,- percentage: Math.round(ends[i]! * 100000) / 1000,+ percentage: Math.round((ends[i]! / total) * 100000) / 1000,}));return { ...anim, keyframes: { ...data, keyframes } };}diff --git a/packages/studio/src/hooks/gsapPositionDetection.ts b/packages/studio/src/hooks/gsapPositionDetection.tsindex 1a63e11981..39105a6ee2 100644--- a/packages/studio/src/hooks/gsapPositionDetection.ts+++ b/packages/studio/src/hooks/gsapPositionDetection.ts@@ -8,6 +8,7 @@import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import { usePlayerStore } from "../player/store/playerStore";import { getIframeGsap, KEYFRAME_PCT_MATCH, queryIframeElement } from "./gsapShared";+import { runEaseOf, timeAtProgress } from "../utils/gsapKeyframeEases";import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";// fallow-ignore-next-line complexity@@ -60,7 +61,7 @@ export function findGsapPositionAnimation(function playheadProximity(a: GsapAnimation, currentTime: number): number {const pos = a.resolvedStart ?? (typeof a.position === "number" ? a.position : 0);- const dur = a.duration ?? 0;+ const dur = resolveTweenDuration(a);if (currentTime >= pos - 0.05 && currentTime <= pos + dur + 0.05) return 50;return -Math.round(Math.min(Math.abs(currentTime - pos), Math.abs(currentTime - pos - dur)) * 5);}@@ -71,7 +72,9 @@ function statesValueAt(anim: GsapAnimation, time: number): boolean {if (!(duration > 0)) return false;const pct = ((time - (resolveTweenStart(anim) ?? 0)) / duration) * 100;const near = (keyframe: number) => Math.abs(keyframe - pct) <= KEYFRAME_PCT_MATCH;- if (anim.keyframes) return anim.keyframes.keyframes.some((kf) => near(kf.percentage));+ const runEase = runEaseOf(anim);+ if (anim.keyframes)+ return anim.keyframes.keyframes.some((kf) => near(timeAtProgress(runEase, kf.percentage)));if (anim.method === "from") return near(0);return near(100) || (anim.method === "fromTo" && near(0));}diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts b/packages/studio/src/hooks/gsapRuntimeBridge.test.tsindex 4c4fb101f3..f5afd0ad2d 100644--- a/packages/studio/src/hooks/gsapRuntimeBridge.test.ts+++ b/packages/studio/src/hooks/gsapRuntimeBridge.test.ts@@ -582,6 +582,41 @@ describe("tryGsapDragIntercept — motion paths", () => {);});+ it("adds a node at a playhead past a duration-less arc, keeping the other nodes' times", async () => {+ usePlayerStore.setState({+ autoKeyframeEnabled: true,+ activeKeyframePct: null,+ currentTime: 15.9,+ });+ const durationless = { ...motionPathAnim, duration: undefined } as GsapAnimation;+ const commitMutation = vi.fn();+ await tryGsapDragIntercept(+ selection,+ { x: -50, y: 30 },+ [durationless],+ fakeIframe("puck-b", [+ { ...liveTween, vars: { motionPath: { path: [] } }, duration: () => 0.5 },+ ]),+ commitMutation,+ );+ // GSAP plays it 12.17-12.67 s; the nodes stay at 12.17, 12.42 and 12.67 s.+ expect(commitMutation).toHaveBeenCalledWith(+ selection,+ expect.objectContaining({+ type: "replace-with-keyframes",+ position: 12.17,+ duration: 3.73,+ keyframes: [+ { percentage: 0, properties: { x: -184, y: 326 } },+ { percentage: 6.7, properties: { x: 416, y: 804 } },+ { percentage: 13.4, properties: { x: 796, y: 237 } },+ { percentage: 100, properties: { x: -50, y: 30 } },+ ],+ }),+ expect.objectContaining({ label: "Move layer (new keyframe)", keyframeAction: "add" }),+ );+ });+it("keeps an explicitly selected path waypoint as a spatial edit", async () => {const { commitMutation, handled } = await dragMotionPath(50);diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.test.tsindex 32c6a432a4..aa39d00cb7 100644--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts@@ -1,9 +1,6 @@import { describe, expect, it, vi } from "vitest";-import {- arcPathFromMotionPathValue,- hasNonHoldTweenForElement,- readRuntimeKeyframes,-} from "./gsapRuntimeKeyframes";+import { hasNonHoldTweenForElement, readRuntimeKeyframes } from "./gsapRuntimeKeyframes";+import { arcPathFromMotionPathValue } from "./gsapRuntimeMotionPath";import { tweensTargeting, withTweenIndex } from "./gsapRuntimeTweenIndex";// Build a fake preview iframe whose runtime timeline holds the given child tweens@@ -263,6 +260,32 @@ describe("arcPathFromMotionPathValue", () => {});});+describe("readRuntimeKeyframes — a motion path runs GSAP's default tween ease", () => {+ const el = { id: "arc" };+ const arcTween = (ease?: string) => ({+ targets: () => [el],+ vars: {+ motionPath: {+ path: [+ { x: 0, y: 0 },+ { x: 100, y: -50 },+ { x: 200, y: 0 },+ ],+ },+ ease,+ },+ duration: () => 2,+ startTime: () => 0,+ });++ it("reads power1.out when the tween sets no ease, and the authored ease otherwise", () => {+ const read = (ease?: string) =>+ readRuntimeKeyframes(fakeIframe(el, [arcTween(ease)]), "#arc")?.runEase;+ expect(read()).toBe("power1.out");+ expect(read("none")).toBe("none");+ });+});+describe("withTweenIndex — many elements, one scan of the tweens", () => {const ids = Array.from({ length: 20 }, (_, i) => `clip-${i}`);const tweens = ids.map((id) => ({diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.tsindex 765fbb7d29..eb07332e5f 100644--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts@@ -8,8 +8,10 @@* `toAbsoluteTime` + the element's clip start/duration. `scanAllRuntimeKeyframes`* does that conversion itself when given a `clipById` map.*/-import { buildArcPath, type ArcPathConfig } from "@hyperframes/core/gsap-parser-acorn";+import type { ArcPathConfig } from "@hyperframes/core/gsap-parser-acorn";import { parsePercentageKeyframes, toAbsoluteTime } from "./gsapShared";+import { timeAtProgress } from "../utils/gsapKeyframeEases";+import { readMotionPathTween } from "./gsapRuntimeMotionPath";import { roundTo3 } from "../utils/rounding";import { matchesElement, tweensTargeting } from "./gsapRuntimeTweenIndex";import { withParsedStart } from "./gsapParsedTween";@@ -49,6 +51,7 @@ export type ReadTween = {keyframes: Pct[];easeEach?: string;arcPath?: ArcPathConfig;+ runEase?: string;/** GSAP's start values when the first keyframe is after 0%. */start?: Record<string, number>;};@@ -93,10 +96,6 @@ function timelinesOf(iframe: HTMLIFrameElement | null): Record<string, RuntimeTi}}-function isXY(p: unknown): p is { x: number; y: number } {- return !!p && typeof (p as any).x === "number" && typeof (p as any).y === "number";-}-/*** A tween we must skip when reading keyframes: a zero-duration `set`/hold (incl.* the studio pre-keyframe position hold, tagged `data: STUDIO_HOLD_MARKER`).@@ -108,31 +107,6 @@ function isZeroDurationSet(duration: number): boolean {return !(duration > 0);}-/** Coordinates + curviness from a live `vars.motionPath` value (object or array form), or null. */-function coordsFromMotionPath(mp: unknown): {- coords: Array<{ x: number; y: number }>;- curviness: number;- autoRotate: boolean | number;- isCubic: boolean;-} | null {- if (!mp || typeof mp !== "object") return null;- const obj = mp as Record<string, unknown>;- const pathVal = Array.isArray(mp) ? mp : obj.path;- if (!Array.isArray(pathVal)) return null;- const coords = pathVal.filter(isXY).map((p) => ({ x: p.x, y: p.y }));- if (coords.length < 2) return null;- const curviness = typeof obj.curviness === "number" ? obj.curviness : 1;- const autoRotate = typeof obj.autoRotate === "number" ? obj.autoRotate : obj.autoRotate === true;- return { coords, curviness, autoRotate, isCubic: obj.type === "cubic" };-}--/** Build an arcPath config from a live `vars.motionPath` value. */-export function arcPathFromMotionPathValue(mp: unknown): ArcPathConfig | undefined {- const parsed = coordsFromMotionPath(mp);- if (!parsed) return undefined;- return buildArcPath(parsed.coords, parsed.curviness, parsed.autoRotate, parsed.isCubic)?.arcPath;-}-function flatTweenKeyframes(vars: Record<string, unknown>): Pct[] | null {const properties: Record<string, number | string> = {};for (const [k, v] of Object.entries(vars)) {@@ -147,24 +121,18 @@ function flatTweenKeyframes(vars: Record<string, unknown>): Pct[] | null {];}+const stringOr = (value: unknown) => (typeof value === "string" ? value : undefined);+/** Tween-relative keyframes + optional arcPath for one live tween, or null. */function readTween(vars: Record<string, unknown>): ReadTween | null {+ const runEase = stringOr(vars.ease);if (vars.keyframes && typeof vars.keyframes === "object") {const parsed = parsePercentageKeyframes(vars.keyframes as Record<string, unknown>);- if (parsed) return parsed;- }- const mp = coordsFromMotionPath(vars.motionPath);- if (mp) {- const shape = buildArcPath(mp.coords, mp.curviness, mp.autoRotate, mp.isCubic);- if (shape) {- const n = shape.waypoints.length;- const keyframes = shape.waypoints.map((wp, i) => ({- percentage: n > 1 ? Math.round((i / (n - 1)) * 100) : 0,- properties: { x: wp.x, y: wp.y },- }));- return { keyframes, arcPath: shape.arcPath };- }+ const keyframesEase = stringOr((vars.keyframes as { ease?: unknown }).ease);+ if (parsed) return { ...parsed, runEase: keyframesEase ?? runEase };}+ const path = readMotionPathTween(vars, runEase);+ if (path) return path;const flat = flatTweenKeyframes(vars);return flat ? { keyframes: flat } : null;}@@ -521,14 +489,15 @@ function hasNonHoldTween(/** Convert tween-relative keyframes to clip-relative % using the element's clip dims. */function toClipRelative(- keyframes: Pct[],+ read: ReadTween,tweenStart: number,tweenDuration: number,clip: { start: number; duration: number } | undefined,): Pct[] {+ const { keyframes, runEase } = read;if (!clip || clip.duration <= 0) return keyframes;return keyframes.map((kf) => {- const abs = toAbsoluteTime(tweenStart, tweenDuration, kf.percentage);+ const abs = toAbsoluteTime(tweenStart, tweenDuration, timeAtProgress(runEase, kf.percentage));return { ...kf, percentage: Math.round(((abs - clip.start) / clip.duration) * 100000) / 1000 };});}@@ -540,7 +509,7 @@ function buildEntry(clip: { start: number; duration: number } | undefined,): RuntimeKeyframeEntry {return {- keyframes: toClipRelative(read.keyframes, start, duration, clip),+ keyframes: toClipRelative(read, start, duration, clip),tweenStart: start,tweenDuration: duration,...(read.easeEach ? { easeEach: read.easeEach } : {}),diff --git a/packages/studio/src/hooks/gsapRuntimeMotionPath.ts b/packages/studio/src/hooks/gsapRuntimeMotionPath.tsnew file mode 100644index 0000000000..1288b3aa44--- /dev/null+++ b/packages/studio/src/hooks/gsapRuntimeMotionPath.ts@@ -0,0 +1,47 @@+import { buildArcPath, type ArcPathConfig } from "@hyperframes/core/gsap-parser-acorn";+import { MOTION_PATH_RUN_EASE } from "../utils/gsapKeyframeEases";+import type { ReadTween } from "./gsapRuntimeKeyframes";++function isXY(p: unknown): p is { x: number; y: number } {+ return !!p && typeof (p as any).x === "number" && typeof (p as any).y === "number";+}++/** Coordinates + curviness from a live `vars.motionPath` value (object or array form), or null. */+function coordsFromMotionPath(mp: unknown): {+ coords: Array<{ x: number; y: number }>;+ curviness: number;+ autoRotate: boolean | number;+ isCubic: boolean;+} | null {+ if (!mp || typeof mp !== "object") return null;+ const obj = mp as Record<string, unknown>;+ const pathVal = Array.isArray(mp) ? mp : obj.path;+ if (!Array.isArray(pathVal)) return null;+ const coords = pathVal.filter(isXY).map((p) => ({ x: p.x, y: p.y }));+ if (coords.length < 2) return null;+ const curviness = typeof obj.curviness === "number" ? obj.curviness : 1;+ const autoRotate = typeof obj.autoRotate === "number" ? obj.autoRotate : obj.autoRotate === true;+ return { coords, curviness, autoRotate, isCubic: obj.type === "cubic" };+}++/** Build an arcPath config from a live `vars.motionPath` value. */+export function arcPathFromMotionPathValue(mp: unknown): ArcPathConfig | undefined {+ const parsed = coordsFromMotionPath(mp);+ if (!parsed) return undefined;+ return buildArcPath(parsed.coords, parsed.curviness, parsed.autoRotate, parsed.isCubic)?.arcPath;+}++export function readMotionPathTween(+ vars: Record<string, unknown>,+ runEase?: string,+): ReadTween | null {+ const mp = coordsFromMotionPath(vars.motionPath);+ const shape = mp && buildArcPath(mp.coords, mp.curviness, mp.autoRotate, mp.isCubic);+ if (!shape) return null;+ const n = shape.waypoints.length;+ const keyframes = shape.waypoints.map((wp, i) => ({+ percentage: n > 1 ? Math.round((i / (n - 1)) * 100) : 0,+ properties: { x: wp.x, y: wp.y },+ }));+ return { keyframes, arcPath: shape.arcPath, runEase: runEase ?? MOTION_PATH_RUN_EASE };+}diff --git a/packages/studio/src/hooks/gsapShared.test.ts b/packages/studio/src/hooks/gsapShared.test.tsindex a339c1ae3f..c2fad2245d 100644--- a/packages/studio/src/hooks/gsapShared.test.ts+++ b/packages/studio/src/hooks/gsapShared.test.ts@@ -1,33 +1,16 @@import { describe, it, expect } from "vitest";import type { GsapAnimation } from "@hyperframes/core/gsap-parser";-import type { DomEditSelection } from "../components/editor/domEditingTypes";import {idFromSelector,idSelector,isInstantHold,parsePercentageKeyframes,resolveClipTimingBasis,- resolveEditableTweenDuration,+ playsNear,toClipKeyframes,toClipPercentage,} from "./gsapShared";-// Fixtures carry only the fields the function under test reads; the double-cast-// is the documented way to stand in for the full runtime shape (CONTRIBUTING.md).-const tween = (duration: number | undefined) => ({ duration }) as unknown as GsapAnimation;--describe("resolveEditableTweenDuration", () => {- const selection = { dataAttributes: { duration: "16.26" } } as unknown as DomEditSelection;-- it("uses the owning clip duration when the tween omits an outer duration", () => {- expect(resolveEditableTweenDuration(tween(undefined), selection)).toBe(16.26);- });-- it("keeps an explicitly-authored tween duration", () => {- expect(resolveEditableTweenDuration(tween(4), selection)).toBe(4);- });-});-describe("isInstantHold", () => {const animation = (method: GsapAnimation["method"], duration?: number) =>({ method, duration }) as unknown as GsapAnimation;@@ -54,45 +37,49 @@ describe("parsePercentageKeyframes", () => {]);});- it("parses GSAP array-form keyframes as evenly-distributed steps", () => {- // Regression: a multi-point shuttle path authored as `keyframes: [...]` used to- // read as null (no `N%` keys) → no motion path. Steps map to i/(n-1)*100%.+ it("parses GSAP array-form keyframes at each step's end, as the parser does", () => {+ // A multi-point shuttle path authored as `keyframes: [...]` has no `N%` keys;+ // step i of n ends at (i+1)/n.const out = parsePercentageKeyframes([{ x: 0, y: 0 },{ x: 520, y: 120 },{ x: 1040, y: 0 },{ x: 1480, y: 160 },] as unknown as Record<string, unknown>);- expect(out?.keyframes.map((k) => k.percentage)).toEqual([0, 33.3, 66.7, 100]);+ expect(out?.keyframes.map((k) => k.percentage)).toEqual([25, 50, 75, 100]);expect(out?.keyframes.map((k) => k.step)).toEqual([0, 1, 2, 3]);expect(out?.keyframes[1]!.properties).toEqual({ x: 520, y: 120 });+ const timed = parsePercentageKeyframes([+ { x: 0, duration: 1 },+ { x: 50, duration: 3 },+ ] as unknown as Record<string, unknown>);+ expect(timed?.keyframes.map((k) => k.percentage)).toEqual([25, 100]);});- it("strips a per-entry ease without shifting the even index-spacing of the others", () => {+ it("strips a per-entry ease without shifting the step spacing of the others", () => {// GSAP positions array keyframes by array index, so a `{ ease }` carried on an// entry is a segment ease (skipped as a property) — it must not change where- // the surrounding keyframes land. 3 entries → 0 / 50 / 100, even though the+ // the surrounding keyframes land. 3 entries → 33.3 / 66.7 / 100, even though the// middle entry also carries an ease.const out = parsePercentageKeyframes([{ x: 0 },{ x: 100, ease: "power2.in" },{ x: 200 },] as unknown as Record<string, unknown>);- expect(out?.keyframes.map((k) => k.percentage)).toEqual([0, 50, 100]);+ expect(out?.keyframes.map((k) => k.percentage)).toEqual([33.3, 66.7, 100]);expect(out?.keyframes.map((k) => k.properties)).toEqual([{ x: 0 }, { x: 100 }, { x: 200 }]);});- it("keeps even spacing when an interior array slot has no animatable prop", () => {+ it("keeps the step spacing when an interior array slot has no animatable prop", () => {// A degenerate `{ ease }`-only slot contributes no output keyframe, but it is// still an array slot GSAP allocates a position to — so the remaining entries- // keep their original i/(n-1) percentages (0 and 100 for a 3-slot array), not- // 0/100 collapsed onto a 2-entry spacing.+ // keep their 3-slot percentages (33.3 and 100), not a 2-entry spacing.const out = parsePercentageKeyframes([{ x: 0 },{ ease: "power2.in" },{ x: 200 },] as unknown as Record<string, unknown>);- expect(out?.keyframes.map((k) => k.percentage)).toEqual([0, 100]);+ expect(out?.keyframes.map((k) => k.percentage)).toEqual([33.3, 100]);expect(out?.keyframes.map((k) => k.properties)).toEqual([{ x: 0 }, { x: 200 }]);});@@ -157,12 +144,38 @@ describe("toClipKeyframes", () => {resolvedStart: 0,} as unknown as GsapAnimation;- // A tween with no duration spans its clip everywhere else in Studio- // (resolveEditableTweenDuration), so the cache rows have to agree: a fixed 1s- // basis put the end keyframe at 25% of a 4s clip instead of 100%.- it("spans the clip when the tween has no duration", () => {+ it("places a duration-less tween's keyframes where GSAP plays them, not across the clip", () => {const rows = toClipKeyframes([{ percentage: 0 }, { percentage: 100 }], durationless, 0, 4);- expect(rows.map((row) => row.percentage)).toEqual([0, 100]);+ expect(rows.map((row) => row.percentage)).toEqual([0, 12.5]);+ });++ it("matches a keyframe by the time it plays, not its warped progress", () => {+ const eased = {+ ...durationless,+ duration: 1,+ ease: "power2.in",+ keyframes: { format: "percentage", keyframes: [] },+ } as unknown as GsapAnimation;+ // At 20% of the time power2.in (cubic) shows 0.8% progress: close in progress, far in time.+ expect(playsNear(eased, 0, 0.8)).toBe(false);+ expect(playsNear(eased, 50, 50.5)).toBe(true);+ });++ it("places a keyframe where an outer ease makes GSAP reach it", () => {+ const eased = {+ ...durationless,+ duration: 1,+ ease: "power2.in",+ keyframes: { format: "percentage", keyframes: [] },+ } as unknown as GsapAnimation;+ const rows = toClipKeyframes(+ [{ percentage: 0 }, { percentage: 50 }, { percentage: 100 }],+ eased,+ 0,+ 1,+ );+ // GSAP's power2 is cubic: it reaches 50% at the cube root of 0.5.+ expect(rows.map((row) => row.percentage)).toEqual([0, 79.37, 100]);});it("keeps the tween percentage and the animation identity on every row", () => {@@ -276,7 +289,7 @@ describe("sub-composition keyframe percentages", () => {it("puts a tween on the host's first frame at 0%, never below zero", () => {// A clip-relative percentage can never be negative; this one cached -12.- expect(percentages(inner(0))).toEqual([0, 100]);+ expect(percentages(inner(0))).toEqual([0, 4]);});it("puts the last tween's end keyframe at 100%", () => {diff --git a/packages/studio/src/hooks/gsapShared.ts b/packages/studio/src/hooks/gsapShared.tsindex 17e4277af8..bf5e8a47f6 100644--- a/packages/studio/src/hooks/gsapShared.ts+++ b/packages/studio/src/hooks/gsapShared.ts@@ -5,6 +5,8 @@*/import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { getObjectArrayKeyframeTiming } from "@hyperframes/parsers/gsap-parser";+import { progressAtTime, runEaseOf, timeAtProgress } from "../utils/gsapKeyframeEases";import type { DomEditSelection } from "../components/editor/domEditingTypes";import {absoluteToPercentage,@@ -88,6 +90,13 @@ const SAFE_HASH_ID = /^-?[A-Za-z_][\w-]*$/;*/export const KEYFRAME_PCT_MATCH = 1;+/** Whether the keyframe at `percentage` plays within KEYFRAME_PCT_MATCH of the time where GSAP shows `progress`. */+export function playsNear(anim: GsapAnimation, percentage: number, progress: number): boolean {+ const runEase = runEaseOf(anim);+ const gap = timeAtProgress(runEase, percentage) - timeAtProgress(runEase, progress);+ return Math.abs(gap) <= KEYFRAME_PCT_MATCH;+}+export function idSelector(id: string): string {// A `#id` selector is only valid for a CSS identifier. IDs that start with a// digit (e.g. "01-hook-hero-word") make `document.querySelector("#01-...")` and@@ -332,22 +341,6 @@ export function tweenTargetsElement(// ── Percentage computation ────────────────────────────────────────────────────-/**- * Resolve the timing basis used by editor keyframes. The timeline renders a- * duration-less tween across its owning clip, so mutations must use that same- * duration instead of silently falling back to GSAP's 0.5s default.- */-export function resolveEditableTweenDuration(- animation: GsapAnimation,- selection: DomEditSelection,-): number {- const clipDuration = Number.parseFloat(selection.dataAttributes?.duration ?? "");- return resolveTweenDuration(- animation,- Number.isFinite(clipDuration) && clipDuration > 0 ? clipDuration : 0.5,- );-}-/*** Compute the current playback percentage within an element's animation range.* Uses the animation's resolved timing if available, otherwise falls back to@@ -360,10 +353,13 @@ export function computeElementPercentage(): number {if (animation) {const start = resolveTweenStart(animation);- const duration = resolveEditableTweenDuration(animation, selection);+ const duration = resolveTweenDuration(animation);if (duration <= 0) return 0;if (start !== null) {- return absoluteToPercentage(currentTime, start, duration);+ return progressAtTime(+ runEaseOf(animation),+ absoluteToPercentage(currentTime, start, duration),+ );}}const elStart = Number.parseFloat(selection.dataAttributes?.start ?? "0") || 0;@@ -428,13 +424,9 @@ export function parsePercentageKeyframes(const keyframes: ParsedPercentageKeyframes["keyframes"] = [];let easeEach: string | undefined;- // GSAP array-form keyframes — `keyframes: [{x,y}, {x,y}, ...]` — are spread- // evenly across the tween by default: GSAP gives each entry an equal share of- // the duration unless an entry carries its own `duration`/`delay`, which the- // studio never emits. So entry i of n maps to i/(n-1)*100% (n=4 → 0/33.3/66.7/100).- // Index spacing counts EVERY array slot, including a degenerate entry that- // contributes no animatable prop (it's still a slot GSAP allocates a position- // to), so dropping such an entry from the output below must NOT shift the others.+ // GSAP array-form keyframes — `keyframes: [{x,y}, {x,y}, ...]` — place each step at+ // its cumulative end, the parser's rule (getObjectArrayKeyframeTiming). Spacing counts+ // EVERY array slot, so dropping an entry with no animatable prop must NOT shift the others.// A per-entry `ease` is a segment ease, not a keyframe value, so it's skipped as// a property; there is no array-form `easeEach` (that's an object-form sibling key).// (The object form further down uses explicit "0%" keys instead.) Without this@@ -442,11 +434,16 @@ export function parsePercentageKeyframes(// motion path.if (Array.isArray(kfObj)) {const steps = kfObj as unknown[];+ const timing = getObjectArrayKeyframeTiming(+ steps.map((entry) => (entry as { duration?: unknown } | null)?.duration),+ );+ if (!timing) return null;steps.forEach((entry, i) => {if (!entry || typeof entry !== "object") return;- const percentage = steps.length > 1 ? Math.round((i / (steps.length - 1)) * 1000) / 10 : 0;const properties = collectAnimatableKeyframeProperties(entry);- if (Object.keys(properties).length > 0) keyframes.push({ percentage, properties, step: i });+ if (Object.keys(properties).length > 0) {+ keyframes.push({ percentage: timing.percentages[i]!, properties, step: i });+ }});return keyframes.length > 0 ? { keyframes } : null;}@@ -575,14 +572,15 @@ export function toClipKeyframes<T extends { percentage: number }>(}> {const tweenStart = anim.resolvedStart ?? (typeof anim.position === "number" ? anim.position : 0);- // A duration-less tween spans the clip, the same rule the edit paths use- // (resolveEditableTweenDuration). A fixed 1s here put its keyframes at a- // percentage no editor agreed with.- const tweenDuration = anim.duration ?? clipDuration;+ const tweenDuration = resolveTweenDuration(anim);return source.map((keyframe) => ({...keyframe,percentage: toClipPercentage(- toAbsoluteTime(tweenStart, tweenDuration, keyframe.percentage),+ toAbsoluteTime(+ tweenStart,+ tweenDuration,+ timeAtProgress(runEaseOf(anim), keyframe.percentage),+ ),clipStart,clipDuration,keyframe.percentage,diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.realGsap.test.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.realGsap.test.tsindex 7a1b324026..0de550091a 100644--- a/packages/studio/src/hooks/gsapValueAtPlayhead.realGsap.test.ts+++ b/packages/studio/src/hooks/gsapValueAtPlayhead.realGsap.test.ts@@ -1,14 +1,20 @@// @vitest-environment happy-domimport { gsap } from "gsap";import { parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn";-import { replaceTweenWithKeyframesInScript } from "@hyperframes/parsers/gsap-writer-acorn";+import {+ replaceTweenWithKeyframesInScript,+ syncPositionHoldsBeforeKeyframes,+ updateKeyframeInScript,+} from "@hyperframes/parsers/gsap-writer-acorn";import { afterEach, expect, it, vi } from "vitest";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { usePlayerStore } from "../player/store/playerStore";import { findParsedTween, parsedImplicitEndValue, parsedTweenEase } from "./gsapParsedTween";import { readRuntimeKeyframes } from "./gsapRuntimeKeyframes";import { GsapEditBlockedError } from "./gsapEditOutcome";+import { toClipKeyframes } from "./gsapShared";import { commitValueAtPlayhead, planValueEdit } from "./gsapValueAtPlayhead";+import { applyKeyframeAtPlayhead, type EnableKeyframesSession } from "./useEnableKeyframes";/** Runs a composition script as the preview does: a paused timeline, bound, then seeked to `at`. */function play(script: string, at: number) {@@ -74,10 +80,10 @@ it("reads plain array nodes where the lane puts them, though GSAP fills in step});// Three default 0.5 s steps stretched over 3 s: GSAP reaches the middle one at 2 s, where the parse-// places it at 50%.+// places it at 66.7%.it.each([["at the playhead, timing array steps on their own timeline", undefined],- ["selected in the lane, in place", 50],+ ["selected in the lane, in place", 66.7],])("changes the middle array keyframe %s", (_, selectedPct) => {const { plan, shown } = dragAndReplay(script("keyframes: [{ x: 60 }, { x: 120 }, { x: 180 }], duration: 3"),@@ -244,6 +250,90 @@ it("writes an edit into a looping tween and keeps its repeat and yoyo, as main dexpect(written).toMatch(/repeat: 1[\s\S]*yoyo: true/);});+it("keeps a delayed step list where GSAP plays it, before and after a keyframe edit", () => {+ const box = Object.assign(document.body.appendChild(document.createElement("div")), { id: "x" });+ const stepList = `var tl = gsap.timeline({ paused: true });\ntl.to("#x", { keyframes: [{ x: 60 }, { x: 120 }], ease: "none" }, 1);\nwindow.__timelines["t"] = tl;`;+ const id = parseGsapScriptAcorn(stepList).animations[0]!.id;+ const edited = syncPositionHoldsBeforeKeyframes(+ updateKeyframeInScript(stepList, id, 100, { x: 130 }),+ );+ const xAt = (file: string, at: number) => {+ const { timeline } = play(file, at);+ const x = gsap.getProperty(box, "x");+ timeline.kill();+ gsap.set(box, { clearProps: "all" });+ return x;+ };+ for (const file of [stepList, edited]) {+ expect([xAt(file, 0.5), xAt(file, 1.25)]).toEqual([0, 30]);+ const tween = parseGsapScriptAcorn(file).animations.find((a) => a.keyframes)!;+ for (const { percentage, properties } of tween.keyframes!.keyframes) {+ expect(xAt(file, 1 + percentage / 100)).toBeCloseTo(Number(properties.x), 3);+ }+ }+});++it.each([+ [+ "an outer power2.in",+ `keyframes: { "0%": { x: 0 }, "50%": { x: 60 }, "100%": { x: 120 } }, duration: 1, ease: "power2.in"`,+ ],+ ["no duration", `keyframes: [{ x: 60 }, { x: 120 }], ease: "none"`],+])("draws each diamond of a keyframed tween with %s where GSAP shows its value", (_, vars) => {+ const box = Object.assign(document.body.appendChild(document.createElement("div")), { id: "x" });+ const file = `var tl = gsap.timeline({ paused: true });\ntl.to("#x", { ${vars} }, 1);\nwindow.__timelines["t"] = tl;`;+ const tween = parseGsapScriptAcornAnimation(file);+ for (const row of toClipKeyframes(tween.keyframes!.keyframes, tween, 0, 4)) {+ const { timeline } = play(file, (row.percentage / 100) * 4);+ expect(gsap.getProperty(box, "x")).toBeCloseTo(Number(row.properties.x), 1);+ timeline.kill();+ gsap.set(box, { clearProps: "all" });+ }+});++function parseGsapScriptAcornAnimation(file: string) {+ return parseGsapScriptAcorn(file).animations.find((a) => a.keyframes)!;+}++it("keeps a step list's steps where GSAP plays them when an outer duration stretches it", () => {+ const { plan, written } = dragAndReplay(+ script(`keyframes: [{ x: 100 }, { x: 200 }], duration: 2, ease: "none"`),+ 70,+ 0.5,+ );+ expect(plan.ok).toBe(true);+ const box = document.getElementById("x")!;+ const xAt = (at: number) => {+ const { timeline } = play(written!, at);+ const x = gsap.getProperty(box, "x");+ timeline.kill();+ return x;+ };+ expect([xAt(0.5), xAt(1), xAt(2)]).toEqual([70, 100, 200]);+});++it("adds a keyframe where GSAP plays a tween whose duration is an expression, and never rewrites the expression", async () => {+ const src = `var dur = () => 2;\nvar tl = gsap.timeline({ paused: true });\ntl.to("#x", { keyframes: { "0%": { x: 0 }, "100%": { x: 300 } }, duration: dur() }, 1);\nwindow.__timelines["t"] = tl;`;+ const box = document.body.appendChild(document.createElement("div"));+ box.id = "x";+ const { timeline, iframe } = play(src, 2);+ const anim = parseGsapScriptAcorn(src).animations[0]!;+ const writes: Array<[string, unknown]> = [];+ const session = {+ commitMutation: async (mutation: unknown) => void writes.push(["replace", mutation]),+ handleGsapRemoveKeyframe: () => void writes.push(["remove", null]),+ handleGsapAddKeyframeBatch: async (_id: string, pct: number) => void writes.push(["add", pct]),+ } as unknown as EnableKeyframesSession;+ const selection = { id: "x", selector: "#x", element: box } as DomEditSelection;++ await applyKeyframeAtPlayhead(session, selection, anim, 2, iframe);+ await applyKeyframeAtPlayhead(session, selection, anim, 3.5, iframe);+ timeline.kill();++ expect(anim.durationUnresolved).toBe(true);+ expect(writes).toEqual([["add", 50]]);+});+it("leaves a step list with a runBackwards step to the runtime: a rewrite would play it differently", async () => {const flagged = script("keyframes: [{ x: 60, duration: 1, runBackwards: true }, { x: 180, duration: 1 }], ease: 'none'",diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.test.tsindex 612680f497..667e75b956 100644--- a/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts+++ b/packages/studio/src/hooks/gsapValueAtPlayhead.test.ts@@ -568,6 +568,19 @@ describe("planValueAtPlayhead", () => {});});+ it("refuses an inner node of a motionPath tween, which GSAP runs power1.out", () => {+ const path = kf([+ { percentage: 0, properties: { x: 0 } },+ { percentage: 50, properties: { x: 100 } },+ { percentage: 100, properties: { x: 300 } },+ ]);+ const anim = { ...path, keyframes: { ...path.keyframes!, fromMotionPath: true as const } };+ expect(plan({ anim, at: { time: 2 }, values: { x: 5 } })).toEqual({+ ok: false,+ reason: "eased-keyframes",+ });+ });+it("changes an inner keyframe picked by its percentage, which the ease does not move", () => {const anim = {...kf([diff --git a/packages/studio/src/hooks/gsapValueAtPlayhead.ts b/packages/studio/src/hooks/gsapValueAtPlayhead.tsindex 3663958fe2..083cc8f45a 100644--- a/packages/studio/src/hooks/gsapValueAtPlayhead.ts+++ b/packages/studio/src/hooks/gsapValueAtPlayhead.ts@@ -2,6 +2,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { usePlayerStore } from "../player/store/playerStore";import { resolveTweenDuration, resolveTweenStart } from "../utils/globalTimeCompiler";+import { ARRAY_STEP_EASE, PERCENTAGE_SEGMENT_EASE, runEaseOf } from "../utils/gsapKeyframeEases";import { roundTo3 } from "../utils/rounding";import {materializeIfDynamic,@@ -66,10 +67,8 @@ export type PlayheadEditPlan =}| { ok: false; reason: PlayheadEditRefusal };-// GSAP 3.14 defaults: a percentage keyframe eases its segment power1.inOut; an array step is linear.-const PERCENTAGE_SEGMENT_EASE = "power1.inOut";-const ARRAY_STEP_EASE = "none";const roundPct = (pct: number) => Math.round(pct * 1000) / 1000;+const isLinear = (ease: string | undefined) => !ease || ease === "none" || ease === "linear";interface Normalized {@@ -92,7 +91,7 @@ function normalize(edit: PlayheadEdit): Normalized | { reason: PlayheadEditRefusconst blocked = stepListBlock(anim);if (blocked) return { reason: blocked };return {- runEase: data.ease ?? anim.ease,+ runEase: runEaseOf(anim),keyframes: data.keyframes.map((kf) => ({...kf,properties: { ...kf.properties },diff --git a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts b/packages/studio/src/hooks/useAnimatedPropertyCommit.tsindex a415ad46f1..b5ba08d4d6 100644--- a/packages/studio/src/hooks/useAnimatedPropertyCommit.ts+++ b/packages/studio/src/hooks/useAnimatedPropertyCommit.ts@@ -22,6 +22,7 @@ import {tweenTargetsElement,} from "./gsapShared";import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";+import { progressAtTime, runEaseOf, timeAtProgress } from "../utils/gsapKeyframeEases";import { roundTo3 } from "../utils/rounding";import { commitWholePropertyOffset } from "./gsapWholePropertyOffsetCommit";import {@@ -365,19 +366,18 @@ async function commitKeyframeProps(const newStart = Math.min(ct, ts);const newEnd = Math.max(ct, ts + td);const newDuration = Math.max(0.01, newEnd - newStart);+ const runEase = runEaseOf(anim);+ const toNewPct = (absTime: number) =>+ Math.round(progressAtTime(runEase, ((absTime - newStart) / newDuration) * 100) * 10) / 10;const remapped = kfs.map((kf) => {- const absTime = ts + (kf.percentage / 100) * td;- const newPct = Math.round(((absTime - newStart) / newDuration) * 1000) / 10;+ const newPct = toNewPct(ts + (timeAtProgress(runEase, kf.percentage) / 100) * td);const p: Record<string, number | string> = { ...kf.properties };for (const k of Object.keys(properties)) {if (!(k in p) && backfillDefaults[k] != null) p[k] = backfillDefaults[k];}return { percentage: newPct, properties: p };});- remapped.push({- percentage: Math.round(((ct - newStart) / newDuration) * 1000) / 10,- properties,- });+ remapped.push({ percentage: toNewPct(ct), properties });remapped.sort((a, b) => a.percentage - b.percentage);await commit(selection,diff --git a/packages/studio/src/hooks/useEnableKeyframes.test.ts b/packages/studio/src/hooks/useEnableKeyframes.test.tsindex d1405c0eea..7bb06e4cda 100644--- a/packages/studio/src/hooks/useEnableKeyframes.test.ts+++ b/packages/studio/src/hooks/useEnableKeyframes.test.ts@@ -7,13 +7,13 @@ import type { DomEditSelection } from "../components/editor/domEditingTypes";import {applyArcKeyframeAtPlayhead,animatedProps,- buildExtendedKeyframes,isPlayheadWithinTween,promoteSetToKeyframes,resolveNewTweenRange,useEnableKeyframes,type EnableKeyframesSession,} from "./useEnableKeyframes";+import { buildExtendedKeyframes } from "./gsapDragPositionCommit";import { usePlayerStore } from "../player/store/playerStore";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -109,17 +109,11 @@ describe("isPlayheadWithinTween", () => {expect(isPlayheadWithinTween(anim({ position: "+=1" }), 99)).toBe(true);});- // The toolbar's "extends animation" tooltip has to agree with what the edit- // paths do. Those span a duration-less tween across its clip, so answering- // from GSAP's 0.5s default reported the playhead outside a window the click- // then treated as clip-wide.- it("spans the clip for a duration-less tween when given the selection", () => {+ it("uses the window GSAP plays a duration-less tween in, not its clip", () => {const durationless = anim({ position: 0 });- const selection = { dataAttributes: { duration: "16" } } as unknown as DomEditSelection;+ expect(isPlayheadWithinTween(durationless, 0.4)).toBe(true);expect(isPlayheadWithinTween(durationless, 5)).toBe(false);- expect(isPlayheadWithinTween(durationless, 5, selection)).toBe(true);- expect(isPlayheadWithinTween(durationless, 20, selection)).toBe(false);});});@@ -238,6 +232,7 @@ describe("applyArcKeyframeAtPlayhead", () => {id: "#el-to-0-position",position: 0,duration: 10,+ ease: "none",keyframes: {format: "object-array",keyframes: [@@ -318,8 +313,8 @@ describe("applyArcKeyframeAtPlayhead", () => {);});- it("uses the owning clip duration when an arc omits its outer duration", async () => {- const fixture = arcFixture(25, 25);+ it("extends a duration-less arc to a later playhead, keeping the other nodes' times", async () => {+ const fixture = arcFixture(100, 0);const durationlessArc = { ...arcAnim, duration: undefined };await applyArcKeyframeAtPlayhead(@@ -330,12 +325,22 @@ describe("applyArcKeyframeAtPlayhead", () => {fixture.iframe,);+ // GSAP plays it 0-0.5 s, so the nodes stay at 0, 0.25 and 0.5 s.expect(fixture.commitMutation).toHaveBeenCalledWith(- expect.objectContaining({+ {type: "replace-with-keyframes",- duration: 10,- keyframes: expect.arrayContaining([{ percentage: 25, properties: { x: 25, y: 25 } }]),- }),+ animationId: arcAnim.id,+ targetSelector: "#el",+ position: 0,+ duration: 2.5,+ keyframes: [+ { percentage: 0, properties: { x: 0, y: 0 } },+ { percentage: 10, properties: { x: 50, y: 50 } },+ { percentage: 20, properties: { x: 100, y: 0 } },+ { percentage: 100, properties: { x: 100, y: 0 } },+ ],+ ease: "none",+ },{ label: "Add keyframe", softReload: true, keyframeAction: "add" },);});diff --git a/packages/studio/src/hooks/useEnableKeyframes.ts b/packages/studio/src/hooks/useEnableKeyframes.tsindex 7ccf8ddfed..99074ff25f 100644--- a/packages/studio/src/hooks/useEnableKeyframes.ts+++ b/packages/studio/src/hooks/useEnableKeyframes.ts@@ -8,7 +8,7 @@* Reads GSAP runtime values only (no CSS offset — it applies separately via translate).*/import { useCallback } from "react";-import type { GsapAnimation, GsapPercentageKeyframe } from "@hyperframes/core/gsap-parser";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { usePlayerStore } from "../player/store/playerStore";import { fetchParsedAnimations, getAnimationsForElement } from "./useGsapTweenCache";@@ -18,19 +18,25 @@ import {keyframeEases,KEYFRAME_PCT_MATCH,isInstantHold,- resolveEditableTweenDuration,+ playsNear,writeTargetSelector,} from "./gsapShared";import {absoluteToPercentage,+ absoluteToPercentageForAnimation,resolveTweenStart,resolveTweenDuration,isTimeWithinTween,} from "../utils/globalTimeCompiler";import { POSITION_PROPS } from "./gsapRuntimeReaders";+import { findParsedTween, withLiveTiming } from "./gsapParsedTween";import { roundTo3 } from "../utils/rounding";import type { CommitMutationOptions } from "./gsapScriptCommitTypes";-import { buildTemporalArcKeyframes } from "./gsapDragPositionCommit";+import {+ buildExtendedKeyframes,+ buildTemporalArcKeyframes,+ linearArcKeyframes,+} from "./gsapDragPositionCommit";let enableKeyframesTransactionCounter = 0;@@ -80,58 +86,11 @@ export function animatedProps(anim: GsapAnimation | null): string[] {* Whether the playhead sits inside an animation's tween range. When the tween's* start can't be resolved we don't block (the percentage falls back to clip range,* preserving prior behavior for elements without explicit timing).- *- * Pass the selection whenever the caller has one: a duration-less tween spans- * its clip, and answering from GSAP's 0.5s default reports the playhead outside- * a window the edit paths treat as clip-wide.*/-export function isPlayheadWithinTween(- anim: GsapAnimation,- currentTime: number,- selection?: DomEditSelection | null,-): boolean {+export function isPlayheadWithinTween(anim: GsapAnimation, currentTime: number): boolean {const start = resolveTweenStart(anim);if (start === null) return true;- const duration = selection- ? resolveEditableTweenDuration(anim, selection)- : resolveTweenDuration(anim);- return isTimeWithinTween(currentTime, start, duration);-}--/**- * Grow a keyframe tween's range to reach a playhead that sits outside it, and add a- * keyframe there. Existing keyframes keep their *absolute* timing (percentages- * rescale into the new range), so the current motion is preserved — the playhead- * just becomes a new hold at the start or end. Used when "add keyframe at playhead"- * fires beyond the tween instead of disabling the action.- */-export function buildExtendedKeyframes(- anim: GsapAnimation,- currentTime: number,- position: Record<string, number>,- sourceDuration = resolveTweenDuration(anim),-): { position: number; duration: number; keyframes: GsapPercentageKeyframe[] } {- const oldStart = resolveTweenStart(anim) ?? 0;- const oldDuration = sourceDuration;- const newStart = Math.min(oldStart, currentTime);- const newEnd = Math.max(oldStart + oldDuration, currentTime);- const newDuration = roundTo3(newEnd - newStart);- const toPct = (absoluteTime: number) =>- newDuration > 0- ? Math.max(- 0,- Math.min(100, Math.round(((absoluteTime - newStart) / newDuration) * 1000) / 10),- )- : 0;- const stops = anim.keyframes?.keyframes ?? [];- const rescaled: GsapPercentageKeyframe[] = stops.map((stop) => ({- percentage: toPct(oldStart + (stop.percentage / 100) * oldDuration),- properties: stop.properties,- ...(stop.ease ? { ease: stop.ease } : {}),- }));- const added: GsapPercentageKeyframe = { percentage: toPct(currentTime), properties: position };- const keyframes = [...rescaled, added].sort((a, b) => a.percentage - b.percentage);- return { position: roundTo3(newStart), duration: newDuration, keyframes };+ return isTimeWithinTween(currentTime, start, resolveTweenDuration(anim));}async function replaceSetWithSingleKeyframe(@@ -285,17 +244,24 @@ async function extendKeyframedTweenToPlayhead(* buildExtendedKeyframes). Shared by native keyframe tweens and flat tweens that* were just converted, so both behave identically.*/-async function applyKeyframeAtPlayhead(+export async function applyKeyframeAtPlayhead(session: EnableKeyframesSession,sel: DomEditSelection,kfAnim: GsapAnimation,t: number,iframe: HTMLIFrameElement | null,commitOverrides?: Partial<CommitMutationOptions>,+ liveTween?: ReturnType<typeof findParsedTween>,): Promise<void> {- const duration = resolveEditableTweenDuration(kfAnim, sel);+ const keepAuthoredDuration = kfAnim.durationUnresolved === true;+ if (keepAuthoredDuration) {+ kfAnim = withLiveTiming(kfAnim, liveTween ?? findParsedTween(iframe, sel.element, kfAnim));+ }+ if (keepAuthoredDuration && kfAnim.duration == null) return;+ const duration = resolveTweenDuration(kfAnim);const start = resolveTweenStart(kfAnim);if (start !== null && !isTimeWithinTween(t, start, duration)) {+ if (keepAuthoredDuration) return;await extendKeyframedTweenToPlayhead(session,sel,@@ -308,10 +274,10 @@ async function applyKeyframeAtPlayhead(return;}const pct =- start === null ? computeElementPercentage(t, sel) : absoluteToPercentage(t, start, duration);- const existing = kfAnim.keyframes?.keyframes.find(- (k) => Math.abs(k.percentage - pct) <= KEYFRAME_PCT_MATCH,- );+ start === null+ ? computeElementPercentage(t, sel)+ : (absoluteToPercentageForAnimation(t, kfAnim) ?? 0);+ const existing = kfAnim.keyframes?.keyframes.find((k) => playsNear(kfAnim, k.percentage, pct));if (existing) {session.handleGsapRemoveKeyframe(kfAnim.id, existing.percentage);return;@@ -404,21 +370,27 @@ export async function applyArcKeyframeAtPlayhead(const targetSelector = existingTweenTargetSelector(arcAnim, sel);if (!targetSelector) return;const start = resolveTweenStart(arcAnim) ?? 0;- const duration = resolveEditableTweenDuration(arcAnim, sel);+ const duration = resolveTweenDuration(arcAnim);if (!isTimeWithinTween(t, start, duration)) {- if (t > start) {- await session.commitMutation(- {- type: "update-meta",- animationId: arcAnim.id,- updates: { duration: roundTo3(t - start) },- },- { label: "Extend motion path", softReload: true },- );- }+ const held = readElementPosition(iframe, sel, arcAnim);+ if (t <= start || typeof held.x !== "number" || typeof held.y !== "number") return;+ const extended = buildExtendedKeyframes(arcAnim, t, { x: held.x, y: held.y }, duration, "none");+ await session.commitMutation(+ {+ type: "replace-with-keyframes",+ animationId: arcAnim.id,+ targetSelector,+ position: extended.position,+ duration: extended.duration,+ keyframes: extended.keyframes,+ ease: "none",+ },+ { label: "Add keyframe", keyframeAction: "add", softReload: true },+ );return;}- const nodes = arcAnim.keyframes?.keyframes ?? [];+ // The arc is rewritten linear: compare and write at the times GSAP plays each node.+ const nodes = linearArcKeyframes(arcAnim);const playheadPercentage = absoluteToPercentage(t, start, duration);const timedNodeIndex = nodes.findIndex((node) => Math.abs(node.percentage - playheadPercentage) <= KEYFRAME_PCT_MATCH,@@ -502,6 +474,9 @@ export function useEnableKeyframes(// resolvedFromValues, so the 0%/100% stops keep the real start→end motion// (passing the playhead value would flatten it). Then apply uniformly so an// out-of-range playhead extends the range just like a keyframe tween.+ const flatLive = flatAnim.durationUnresolved+ ? findParsedTween(iframe, sel.element, flatAnim)+ : undefined;enableKeyframesTransactionCounter += 1;const coalesceKey = `enable-keyframes:${flatAnim.id}:${enableKeyframesTransactionCounter}`;const convertCommitOverrides: Partial<CommitMutationOptions> = {@@ -527,7 +502,15 @@ export function useEnableKeyframes(// conversion splits into two undo entries under real latency.coalesceMs: Number.POSITIVE_INFINITY,};- await applyKeyframeAtPlayhead(session, sel, converted, t, iframe, applyCommitOverrides);+ await applyKeyframeAtPlayhead(+ session,+ sel,+ converted,+ t,+ iframe,+ applyCommitOverrides,+ flatLive,+ );}} else {const position = readElementPosition(iframe, sel, null);diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.tsindex 86de46e75a..adeadc2f12 100644--- a/packages/studio/src/hooks/useGestureCommit.ts+++ b/packages/studio/src/hooks/useGestureCommit.ts@@ -8,6 +8,7 @@ import { simplifyGestureSamples } from "../utils/rdpSimplify";import { fitEasesFromVelocity } from "../utils/velocityEaseFitter";import { smoothGestureKeyframes } from "../utils/gestureSmoother";import { usePlayerStore } from "../player";+import { resolveTweenDuration } from "../utils/globalTimeCompiler";import type { DomEditSelection } from "../components/editor/domEditing";import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { CommitMutationOptions } from "./gsapScriptCommitTypes";@@ -258,7 +259,7 @@ export function useGestureCommit({);} else {const tweenStart = existingPositionTween.resolvedStart ?? 0;- const tweenDur = existingPositionTween.duration ?? duration;+ const tweenDur = resolveTweenDuration(existingPositionTween);const tweenEnd = tweenStart + tweenDur;const recEnd = recStart + duration;diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.tsindex da976f7b96..82669588b4 100644--- a/packages/studio/src/hooks/useGsapTweenCache.ts+++ b/packages/studio/src/hooks/useGsapTweenCache.ts@@ -11,7 +11,7 @@ import {publishKeyframeCache,writeGsapAnimationsForElement,} from "./gsapKeyframeCacheHelpers";-import { resolveClipTimingBasis, toAbsoluteTime, toClipPercentage } from "./gsapShared";+import { resolveClipTimingBasis, toClipKeyframes } from "./gsapShared";import {deduplicateKeyframes,isStaticPositionHold,@@ -199,22 +199,7 @@ export function useGsapAnimationsForElement(if (isStaticPositionHold(anim)) continue;const kf = anim.keyframes ?? synthesizeFlatTweenKeyframes(anim);if (!kf) continue;- // Convert tween-relative percentages to clip-relative so diamonds- // render at the correct position within the timeline clip.- const tweenPos =- anim.resolvedStart ?? (typeof anim.position === "number" ? anim.position : 0);- const tweenDur = anim.duration ?? elDuration;- for (const k of kf.keyframes) {- const absTime = toAbsoluteTime(tweenPos, tweenDur, k.percentage);- const clipPct = toClipPercentage(absTime, elStart, elDuration, k.percentage);- allKeyframes.push({- ...k,- percentage: clipPct,- tweenPercentage: k.percentage,- propertyGroup: anim.propertyGroup,- animationId: anim.id,- });- }+ allKeyframes.push(...toClipKeyframes(kf.keyframes, anim, elStart, elDuration));format = kf.format;if (kf.ease) ease = kf.ease;if (kf.easeEach) easeEach = kf.easeEach;diff --git a/packages/studio/src/player/components/TimelinePropertyLanes.tsx b/packages/studio/src/player/components/TimelinePropertyLanes.tsxindex c3ea89dac9..01658071f9 100644--- a/packages/studio/src/player/components/TimelinePropertyLanes.tsx+++ b/packages/studio/src/player/components/TimelinePropertyLanes.tsx@@ -179,6 +179,7 @@ export function getTimelinePropertyLanes(return Array.from(sourceGroups(animations), ([group, groupAnimations]) => ({group,animations: groupAnimations,+ elementAnimations: animations,keyframes: groupKeyframes(groupAnimations, group, clipStart, clipDuration),})).filter((lane) => lane.keyframes.length > 0);}diff --git a/packages/studio/src/player/components/trackHeaderLaneState.ts b/packages/studio/src/player/components/trackHeaderLaneState.tsindex b86a4f94f8..9f0385b87e 100644--- a/packages/studio/src/player/components/trackHeaderLaneState.ts+++ b/packages/studio/src/player/components/trackHeaderLaneState.ts@@ -17,7 +17,7 @@ import {} from "../../utils/globalTimeCompiler";import type { TimelinePropertyGroupKeyframeToggle } from "./timelineCallbacks";import { getTimelinePropertyLanes } from "./TimelinePropertyLanes";-import { groupLabel, valuesAt, type LaneValues } from "./trackHeaderLaneValues";+import { groupLabel, valuesAt, valuesBefore, type LaneValues } from "./trackHeaderLaneValues";export type TimelinePropertyLane = ReturnType<typeof getTimelinePropertyLanes>[number];export type KeyframeNavigationState = ReturnType<@@ -110,7 +110,14 @@ export function resolveLaneHeaderState(currentTime,clipPercentage,);- const values = animation ? valuesAt(animation, lane.group, tweenPercentage) : {};+ const values = animation+ ? valuesAt(+ animation,+ lane.group,+ tweenPercentage,+ valuesBefore(animation, lane.elementAnimations),+ )+ : {};return {navigation,diff --git a/packages/studio/src/player/components/trackHeaderLaneValues.test.ts b/packages/studio/src/player/components/trackHeaderLaneValues.test.tsnew file mode 100644index 0000000000..b3b5ac64c5--- /dev/null+++ b/packages/studio/src/player/components/trackHeaderLaneValues.test.ts@@ -0,0 +1,89 @@+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { describe, expect, it } from "vitest";+import { progressAtTime, runEaseOf } from "../../utils/gsapKeyframeEases";+import { valuesAt, valuesBefore } from "./trackHeaderLaneValues";++const tween = (format: string, vars: { ease?: string; easeEach?: string }) =>+ ({+ id: "#x-to-0-position",+ targetSelector: "#x",+ method: "to",+ position: 0,+ duration: 1,+ properties: {},+ ...(vars.ease ? { ease: vars.ease } : {}),+ keyframes: {+ format,+ keyframes: [+ { percentage: 50, properties: { x: 60 } },+ { percentage: 100, properties: { x: 120 } },+ ],+ ...(vars.easeEach ? { easeEach: vars.easeEach } : {}),+ },+ }) as unknown as GsapAnimation;++const xAt = (animation: GsapAnimation, timePercentage: number) =>+ Number(+ valuesAt(animation, "position", progressAtTime(runEaseOf(animation), timePercentage)).x.toFixed(+ 2,+ ),+ );++// Each row is what GSAP 3.15 draws for x at 12.5, 37.5, 62.5 and 87.5% of the tween.+describe("valuesAt at the playhead", () => {+ it.each([+ ["a step list", tween("object-array", {}), [15, 45, 75, 105]],+ [+ "a step list with an outer ease",+ tween("object-array", { ease: "power1.out" }),+ [28.13, 73.13, 103.13, 118.13],+ ],+ ["percentage keyframes", tween("percentage", {}), [7.5, 52.5, 67.5, 112.5]],+ [+ "percentage keyframes with an outer ease",+ tween("percentage", { ease: "power1.out", easeEach: "power1.out" }),+ [43.07, 83.38, 115.25, 119.94],+ ],+ ])("reads %s as GSAP plays it", (_, animation, expected) => {+ expect([12.5, 37.5, 62.5, 87.5].map((at) => xAt(animation, at))).toEqual(expected);+ });+});++describe("valuesBefore", () => {+ it("starts a step list from the value an earlier set left, not a default", () => {+ const set = { id: "s", method: "set", position: 0, resolvedStart: 0, properties: { x: 300 } };+ const stepList = { ...tween("object-array", { ease: "none" }), position: 1, resolvedStart: 1 };+ stepList.keyframes!.keyframes = [+ { percentage: 50, properties: { x: 300 } },+ { percentage: 100, properties: { x: 500 } },+ ];+ const start = valuesBefore(stepList, [set as unknown as GsapAnimation, stepList]);+ expect(start).toEqual({ x: 300 });+ expect(valuesAt(stepList, "position", 25, start)).toEqual({ x: 300 });+ });++ it("takes a set placed at the tween's own start, and never a relative string", () => {+ const at = (id: string, resolvedStart: number, x: number | string) =>+ ({ id, method: "set", resolvedStart, properties: { x } }) as unknown as GsapAnimation;+ const stepList = { ...tween("object-array", { ease: "none" }), resolvedStart: 1 };+ const relative = at("r", 0.5, "+=50");+ expect(valuesBefore(stepList, [at("s", 1, 300), stepList])).toEqual({ x: 300 });+ expect(valuesBefore(stepList, [stepList, at("s", 1, 300)])).toEqual({});+ expect(valuesBefore(stepList, [at("s", 0, 300), relative, stepList])).toEqual({});+ });++ it("skips a tween still running when this one starts", () => {+ const set = { id: "s", method: "set", resolvedStart: 0, properties: { x: 300 } };+ const running = {+ id: "r",+ method: "to",+ resolvedStart: 0.5,+ duration: 1,+ properties: { x: 900 },+ };+ const stepList = { ...tween("object-array", { ease: "none" }), resolvedStart: 1 };+ const others = [set, running] as unknown as GsapAnimation[];+ expect(valuesBefore(stepList, [...others, stepList])).toEqual({ x: 300 });+ expect(valuesBefore({ ...stepList, resolvedStart: undefined }, others)).toEqual({});+ });+});diff --git a/packages/studio/src/player/components/trackHeaderLaneValues.ts b/packages/studio/src/player/components/trackHeaderLaneValues.tsindex 2ae0fe7626..c155c34b1c 100644--- a/packages/studio/src/player/components/trackHeaderLaneValues.ts+++ b/packages/studio/src/player/components/trackHeaderLaneValues.ts@@ -4,12 +4,14 @@* reads to a human. Kept apart from the header's JSX so a formatting change and* a layout change never touch the same file.*/-import gsap from "gsap";import {classifyPropertyGroup,type GsapAnimation,type PropertyGroupName,} from "@hyperframes/core/gsap-parser";+import { PROPERTY_DEFAULTS } from "../../hooks/gsapShared";+import { resolveTweenDuration, resolveTweenStart } from "../../utils/globalTimeCompiler";+import { easeFunction, keyframedTweenEases } from "../../utils/gsapKeyframeEases";export type LaneValues = Record<string, number | string>;@@ -17,15 +19,8 @@ function roundValue(value: number): string {return String(Math.round(value * 100) / 100);}-/** GSAP applies a keyframe's `ease` to the segment ARRIVING at it, so the curve- * between two keyframes is named by the later one (with the tween-level- * `easeEach`/`ease` as the fallback). Sampling linearly would report a value the- * element never has at that time, and stamp that wrong value onto a keyframe- * added from the track header. Unknown ease names parse to undefined -> linear. */function easedProgress(progress: number, animation: GsapAnimation, ease?: string): number {- const resolved = ease ?? animation.keyframes?.easeEach ?? animation.ease;- if (!resolved || resolved === "none") return progress;- return gsap.parseEase(resolved)?.(progress) ?? progress;+ return easeFunction(keyframedTweenEases(animation).segment({ ease }))?.(progress) ?? progress;}interface PropertyStop {@@ -34,14 +29,23 @@ interface PropertyStop {ease?: string;}-function propertyStops(animation: GsapAnimation, property: string): PropertyStop[] {- return (animation.keyframes?.keyframes ?? [])+/** Before its first keyframe a tween animates from the value it starts at (`start`), or the+ * property's base value as for a flat tween (synthesizeFlatTweenKeyframes). */+function propertyStops(+ animation: GsapAnimation,+ property: string,+ start?: number | string,+): PropertyStop[] {+ const stops = (animation.keyframes?.keyframes ?? []).filter((keyframe) => property in keyframe.properties).map((keyframe) => ({percentage: keyframe.percentage,value: keyframe.properties[property],ease: keyframe.ease,}));+ const first = stops[0];+ if (!first || first.percentage <= 0 || typeof first.value !== "number") return stops;+ return [{ percentage: 0, value: start ?? PROPERTY_DEFAULTS[property] ?? 0 }, ...stops];}/** A pair only interpolates when both ends are numeric and actually span time;@@ -60,8 +64,9 @@ function propertyValueAt(animation: GsapAnimation,property: string,tweenPercentage: number,+ start?: number | string,): number | string | undefined {- const stops = propertyStops(animation, property);+ const stops = propertyStops(animation, property, start);const before = stops.filter((stop) => stop.percentage <= tweenPercentage).at(-1);const after = stops.find((stop) => stop.percentage >= tweenPercentage);if (!before) return after?.value;@@ -77,6 +82,7 @@ export function valuesAt(animation: GsapAnimation,group: PropertyGroupName,tweenPercentage: number,+ startValues: LaneValues = {},): LaneValues {const propertyNames = new Set<string>();for (const keyframe of animation.keyframes?.keyframes ?? []) {@@ -86,12 +92,47 @@ export function valuesAt(}const values: LaneValues = {};for (const property of propertyNames) {- const value = propertyValueAt(animation, property, tweenPercentage);+ const value = propertyValueAt(animation, property, tweenPercentage, startValues[property]);if (value !== undefined) values[property] = value;}return values;}+const endValue = (animation: GsapAnimation, property: string) =>+ animation.keyframes?.keyframes.findLast((keyframe) => property in keyframe.properties)+ ?.properties[property] ?? animation.properties[property];++/** Each property's value as `animation` starts: the end of the last tween done writing it by then. */+export function valuesBefore(+ animation: GsapAnimation,+ animations: readonly GsapAnimation[],+): LaneValues {+ const start = resolveTweenStart(animation);+ if (start == null) return {};+ const endOf = (other: GsapAnimation) =>+ (resolveTweenStart(other) ?? Infinity) ++ (other.method === "set" ? 0 : resolveTweenDuration(other));+ const index = animations.indexOf(animation);+ const finished = animations+ .filter((other, i) => {+ if (other.method === "from" || i === index) return false;+ return endOf(other) < start || (endOf(other) === start && i < index);+ })+ .sort((a, b) => endOf(a) - endOf(b));+ const values: LaneValues = {};+ for (const other of finished) {+ const keyframes = other.keyframes?.keyframes ?? [{ properties: other.properties }];+ for (const property of new Set(+ keyframes.flatMap((keyframe) => Object.keys(keyframe.properties)),+ )) {+ const value = endValue(other, property);+ if (typeof value === "number") values[property] = value;+ else delete values[property];+ }+ }+ return values;+}+export function groupLabel(group: PropertyGroupName, properties: LaneValues): string {if (group === "visual" && ("opacity" in properties || "autoAlpha" in properties)) {return "Opacity";diff --git a/packages/studio/src/player/components/useTimelineKeyframeHandlers.ts b/packages/studio/src/player/components/useTimelineKeyframeHandlers.tsindex 9430ac493d..33dc64d994 100644--- a/packages/studio/src/player/components/useTimelineKeyframeHandlers.ts+++ b/packages/studio/src/player/components/useTimelineKeyframeHandlers.ts@@ -4,6 +4,7 @@ import {type PointerEvent as ReactPointerEvent,} from "react";import { clipToTweenPercentage } from "../../components/editor/KeyframeNavigation";+import { progressAtTime, runEaseOf, timeAtProgress } from "../../utils/gsapKeyframeEases";import {KEYFRAME_DRAG_THRESHOLD_PX,previewClipPct,@@ -162,6 +163,15 @@ export function subscribeTimelineKeyframeRetimePreview(return () => coordinator.previewListeners.delete(listener);}+function retimedRunEase(actor: TimelineKeyframeRetimeActor): string | undefined {+ const id = actor.target.animationId;+ if (id === undefined) return undefined;+ const { gsapAnimations } = usePlayerStore.getState();+ const animations = gsapAnimations.get(actor.elementId) ?? [...gsapAnimations.values()].flat();+ const animation = animations.find((candidate) => candidate.id === id);+ return animation ? runEaseOf(animation) : undefined;+}+function resolveRetimeTweenPercentage(actor: TimelineKeyframeRetimeActor,toClipPercentage: number,@@ -173,7 +183,13 @@ function resolveRetimeTweenPercentage(const tweenPercentages = animationKeyframes.map((keyframe) => keyframe.tweenPercentage).filter((value): value is number => typeof value === "number");- const mapped = clipToTweenPercentage(animationKeyframes, toClipPercentage);+ const runEase = retimedRunEase(actor);+ const timed = animationKeyframes.map((keyframe) =>+ keyframe.tweenPercentage === undefined+ ? keyframe+ : { ...keyframe, tweenPercentage: timeAtProgress(runEase, keyframe.tweenPercentage) },+ );+ const mapped = progressAtTime(runEase, clipToTweenPercentage(timed, toClipPercentage));if (tweenPercentages.length === 0) return mapped;return Math.max(Math.min(...tweenPercentages), Math.min(Math.max(...tweenPercentages), mapped));}diff --git a/packages/studio/src/utils/globalTimeCompiler.test.ts b/packages/studio/src/utils/globalTimeCompiler.test.tsindex ddf85b82df..650659d08b 100644--- a/packages/studio/src/utils/globalTimeCompiler.test.ts+++ b/packages/studio/src/utils/globalTimeCompiler.test.ts@@ -112,10 +112,6 @@ describe("resolveTweenDuration", () => {test("missing duration defaults to GSAP default (0.5)", () => {expect(resolveTweenDuration(makeAnim({ duration: undefined }))).toBe(0.5);});-- test("missing duration can use its editor timing basis", () => {- expect(resolveTweenDuration(makeAnim({ duration: undefined }), 16.26)).toBe(16.26);- });});describe("findTweenAtTime", () => {diff --git a/packages/studio/src/utils/globalTimeCompiler.ts b/packages/studio/src/utils/globalTimeCompiler.tsindex 5d158379f9..dac63229f3 100644--- a/packages/studio/src/utils/globalTimeCompiler.ts+++ b/packages/studio/src/utils/globalTimeCompiler.ts@@ -1,4 +1,6 @@import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { GSAP_DEFAULT_DURATION } from "@hyperframes/parsers/gsap-parser";+import { progressAtTime, runEaseOf, timeAtProgress } from "./gsapKeyframeEases";export function absoluteToPercentage(time: number,@@ -34,8 +36,8 @@ export function resolveTweenStart(animation: GsapAnimation): number | null {return null;}-export function resolveTweenDuration(animation: GsapAnimation, fallback = 0.5): number {- return animation.duration ?? fallback;+export function resolveTweenDuration(animation: GsapAnimation): number {+ return animation.duration ?? GSAP_DEFAULT_DURATION;}export function findTweenAtTime(@@ -60,7 +62,7 @@ export function absoluteToPercentageForAnimation(const start = resolveTweenStart(animation);if (start === null) return null;const duration = resolveTweenDuration(animation);- return absoluteToPercentage(time, start, duration);+ return progressAtTime(runEaseOf(animation), absoluteToPercentage(time, start, duration));}export function percentageToAbsoluteForAnimation(@@ -70,7 +72,7 @@ export function percentageToAbsoluteForAnimation(const start = resolveTweenStart(animation);if (start === null) return null;const duration = resolveTweenDuration(animation);- return percentageToAbsolute(pct, start, duration);+ return percentageToAbsolute(timeAtProgress(runEaseOf(animation), pct), start, duration);}function matchesSelector(tweenSelector: string, querySelector: string): boolean {diff --git a/packages/studio/src/utils/gsapKeyframeEases.ts b/packages/studio/src/utils/gsapKeyframeEases.tsnew file mode 100644index 0000000000..40b20b690a--- /dev/null+++ b/packages/studio/src/utils/gsapKeyframeEases.ts@@ -0,0 +1,79 @@+import gsap from "gsap";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";++// GSAP 3.15 defaults: a percentage keyframe eases its segment power1.inOut; an array step is linear.+export const PERCENTAGE_SEGMENT_EASE = "power1.inOut";+export const ARRAY_STEP_EASE = "none";+// A motionPath tween is a plain tween to GSAP, so it runs GSAP's default tween ease.+export const MOTION_PATH_RUN_EASE = "power1.out";++/** `run` warps a keyframed tween's whole progress; a segment eases with the keyframe it arrives+ * at, else easeEach, else GSAP's default for the form. A flat tween has no run ease. */+export function keyframedTweenEases(anim: GsapAnimation): {+ run?: string;+ segment: (arriving: { ease?: string }) => string;+} {+ const data = anim.keyframes;+ const fallback =+ data?.format === "object-array" ? ARRAY_STEP_EASE : (data?.easeEach ?? PERCENTAGE_SEGMENT_EASE);+ return {+ run: data+ ? (data.ease ?? anim.ease ?? (data.fromMotionPath ? MOTION_PATH_RUN_EASE : undefined))+ : undefined,+ segment: (arriving) => arriving.ease ?? fallback,+ };+}++export function easeFunction(name: string | undefined): ((progress: number) => number) | null {+ if (!name || name === "none" || name === "linear") return null;+ return gsap.parseEase(name) ?? null;+}++export const runEaseOf = (anim: GsapAnimation) => keyframedTweenEases(anim).run;++const SCAN_STEPS = 200;+const BISECT_STEPS = 40;+const timingEases = new Map<string, ((progress: number) => number) | null>();++/** The run ease as a one-to-one time/progress map; an ease that overshoots 0-1 or stalls times keys linearly. */+function timingEase(runEase: string | undefined): ((progress: number) => number) | null {+ if (!runEase) return null;+ if (!timingEases.has(runEase)) {+ const run = easeFunction(runEase);+ const samples = Array.from(+ { length: SCAN_STEPS + 1 },+ (_, step) => run?.(step / SCAN_STEPS) ?? 0,+ );+ const oneToOne = samples.every((v, i) => v >= 0 && v <= 1 && (i === 0 || v > samples[i - 1]!));+ timingEases.set(runEase, run && oneToOne ? run : null);+ }+ return timingEases.get(runEase) ?? null;+}++/** The keyframe progress (0-100) GSAP shows at `timePercentage` of a tween with this run ease. */+export function progressAtTime(runEase: string | undefined, timePercentage: number): number {+ const run = timingEase(runEase);+ return run ? run(timePercentage / 100) * 100 : timePercentage;+}++/** The time (0-100 of the tween) at which GSAP first reaches keyframe progress `percentage`. */+export function timeAtProgress(runEase: string | undefined, percentage: number): number {+ const run = timingEase(runEase);+ if (!run || percentage <= 0 || percentage >= 100) return percentage;+ const target = percentage / 100;+ let low = 0;+ let high = 1;+ for (let step = 1; step <= SCAN_STEPS; step++) {+ if (run(step / SCAN_STEPS) >= target) {+ low = (step - 1) / SCAN_STEPS;+ high = step / SCAN_STEPS;+ break;+ }+ }+ for (let step = 0; step < BISECT_STEPS; step++) {+ const mid = (low + high) / 2;+ if (run(mid) >= target) high = mid;+ else low = mid;+ }+ return high * 100;+}