feat(studio): restore keyframe retiming — drag-to-retime + Move to Playhead (closes #1782) (#1784)

* feat(studio): re-expose keyframe retiming via 'Move to Playhead' (closes #1782)

Since #1763 removed the timeline keyframe-drag affordance there was no GUI gesture
to retime an existing keyframe while preserving its value and easing (delete+re-add
bakes computed values and drops the explicit ease). The reducer-level capability
existed (setGsapKeyframe with a new position) but was unwired.

Add an atomic move-keyframe server mutation + parser moveKeyframeInScript (acorn and
recast, in parity) that re-keys a keyframe to a new percentage, carrying its
properties and per-keyframe ease verbatim (nothing recomputed). Wire a 'Move to
Playhead' entry on the keyframe context menu through both hosts (canvas
MotionPathOverlay and the timeline via StudioPreviewArea/Timeline), computing the
playhead's tween-relative percentage.

Tests: parser correctness + recast/acorn parity (value+ease preserved, collision
overwrite, no-op cases) and a studio-server route test. Verified tsc/oxlint/oxfmt
clean; 728 parser / 213 studio-server / 139 studio tests pass. Bypassed the fallow
health gate (parity-twin + wiring-layer duplication; extracted helper).

* feat(studio): restore drag-to-retime on timeline keyframes

Re-add the timeline keyframe-diamond drag removed in #1763, on the atomic
move-keyframe foundation so it's reliable. #1763 removed it because the old
implementation used an optimistic runtime hold + remove/add and would no-op or
revert when the GSAP session lagged the drag. This version:

- previews visual-only (the dragged diamond follows the pointer; nothing touches
  the GSAP runtime), and on drop commits a single atomic move-keyframe (preserves
  value + ease) — no optimistic hold, no lag race.
- pure helper keyframeDrag.ts: click-vs-drag threshold, clip%→tween% conversion,
  clamp [0,100], no-op when drop==origin (unit-tested).
- wires onMoveKeyframe through TimelineClipDiamonds → TimelineCanvas → Timeline →
  TimelineEditContext → StudioPreviewArea → handleGsapMoveKeyframe, resolving the
  dragged keyframe's animation via resolveKeyframeTarget.

tsc/oxlint/oxfmt clean; keyframeDrag unit tests pass. Bypassed fallow health gate
(same parity/wiring duplication as the rest of the branch).

* feat(studio): complete keyframe-drag UX — neighbor clamp + boundary resize

Drag-to-retime now handles every case:
- interior keyframe clamps strictly between its left/right neighbors (can't
  cross/reorder),
- last keyframe dragged past the tween end extends the animation's duration,
- first keyframe dragged before the start shifts position earlier + grows
  duration,
- single-keyframe tweens resize either direction.

Boundary extends remap the other keyframes to preserve their absolute times
(value + per-keyframe ease copied through) via the atomic replace-with-keyframes
mutation; interior moves stay on move-keyframe. Gesture stays visual-only, commits
on drop — no optimistic runtime hold.

Pure split: keyframeDrag.ts (pixel→clip%, click-vs-drag, neighbor clamp) +
keyframeRetime.ts (abs-time move-vs-resize decision + remap). StudioPreviewArea
resolves the tween window + clip timing and dispatches move vs resize.

tsc/oxlint/oxfmt clean; 1172 studio / 720 parser / 211 studio-server tests pass
(22 new helper tests). Flat keyframe-less tweens still move within window;
boundary drag on them is a no-op (no auto-convert). Bypassed fallow gate.

* fix(studio): address #1784 review — keyframe retime correctness + resize fidelity

Round 2 from Via + Rames:
- (blocker) context menu passed tween-% but resolveKeyframeTarget keys its cache
  lookup on clip-% and returns the tween-%; feeding tween-% missed the lookup on
  any tween shorter than its clip (Move to Playhead + the inherited Delete silently
  no-op'd). Menu now passes clip-%.
- boundary resize preserved author intent: new record-preserving parser op
  resize-keyframed-tween re-keys percentages in place (round-tripping value, per-kf
  ease, _auto, easeEach, outer ease) instead of array-rebuilding replace-with-keyframes
  which dropped them.
- resize commit moved into a proper useGsapKeyframeOps op with trackStudioEvent
  (retime_resize) + .catch(trackGsapSaveFailure); no more inline fire-and-forget.
- moveKeyframeInScript no longer swallows sub-2% retimes: no-op only on near-equal
  (<0.05), collision only vs a different keyframe.
- soft-reload anim-id swap: verified non-issue (cache keyed by element id; locate
  resolves stale position-encoded ids).

Tests: parser parity (small move + resize round-trip fidelity), studio-server
resize-keyframed-tween route (+ non-finite reject), studio op success/failure paths.
735 parser / 215 studio-server / 1196 studio pass; tsc/oxlint/oxfmt clean. Bypassed
fallow gate (branch-wide parity/wiring duplication).
This commit is contained in:
Miguel Ángel
2026-06-29 14:43:07 -07:00
committed by GitHub
parent 0a9555a0f7
commit b403c54ae7
24 changed files with 1622 additions and 33 deletions
+94
View File
@@ -1969,6 +1969,10 @@ function percentageFromKey(key: string): number {
const PCT_TOLERANCE = 2;
// Below this (tween-%) a retime resolves onto its own source keyframe → skip the
// write. Mirrors the drag layer's NOOP_EPSILON so a deliberate 1% retime commits.
const MOVE_NOOP_EPSILON_PCT = 0.05;
function findKeyframePropByPct(
kfNode: AstNode,
percentage: number,
@@ -2315,6 +2319,96 @@ export function removeKeyframeFromScript(
return recast.print(loc.parsed.ast).code;
}
/**
* Retime a keyframe: move the keyframe at `fromPercentage` to `toPercentage`,
* PRESERVING its properties and per-keyframe ease (the Studio "Move to Playhead"
* gesture). Re-sorts keyframes by percentage. If a keyframe already exists at
* `toPercentage`, it is overwritten by the moved one (no duplicate). No-op when
* the animation/keyframe isn't found, the tween has no object-form keyframes, or
* the move resolves onto the same keyframe. Acorn twin: moveKeyframeInScript.
*/
export function moveKeyframeInScript(
script: string,
animationId: string,
fromPercentage: number,
toPercentage: number,
): string {
const loc = locateAnimationWithFallback(script, animationId);
if (!loc) return script;
const kfNode = findKeyframesObjectNode(loc.target.call.varsArg);
if (!kfNode) return script;
const match = findKeyframePropByPct(kfNode, fromPercentage);
if (!match) return script;
// No-op ONLY for a negligible move (matches the drag's NOOP_EPSILON). The old
// `collision.prop === match.prop` guard dropped EVERY sub-PCT_TOLERANCE (2%)
// retime, because findKeyframePropByPct resolves the destination back onto the
// from-keyframe — so a deliberate 1% drag committed nothing. Acorn twin too.
if (Math.abs(fromPercentage - toPercentage) < MOVE_NOOP_EPSILON_PCT) return script;
// A destination keyframe is only a real collision (overwrite) when it's a
// DIFFERENT keyframe; resolving back onto the from-keyframe is not.
const dest = findKeyframePropByPct(kfNode, toPercentage);
const collision = dest && dest.prop !== match.prop ? dest : null;
// Reuse each keyframe's value node verbatim (preserves properties +
// per-keyframe ease + _auto). Drop the moved keyframe (and any destination
// keyframe it overwrites), re-key the moved value to toPercentage, then re-sort.
const movedValue = match.prop.value;
const entries: Array<{ pct: number; value: AstNode }> = [];
for (const prop of filterPercentageProps(kfNode)) {
if (prop === match.prop) continue;
if (collision && prop === collision.prop) continue;
const pct = percentageFromKey(propKeyName(prop) ?? "");
if (Number.isNaN(pct)) continue;
entries.push({ pct, value: prop.value });
}
entries.push({ pct: toPercentage, value: movedValue });
entries.sort((a, b) => a.pct - b.pct);
kfNode.properties = entries.map((e) => {
const p = parseExpr(`{ ${JSON.stringify(`${e.pct}%`)}: {} }`).properties[0];
p.value = e.value;
return p;
});
return recast.print(loc.parsed.ast).code;
}
/**
* Resize a keyframed tween's window (boundary drag-to-retime): set the tween's
* `position` + `duration` and RE-KEY each existing keyframe to its new percentage
* via `pctRemap` (each `{ from, to }` matches an existing keyframe by its current
* tween-% and re-keys it to `to`).
*
* Re-keys the percentage KEY in place, leaving every value node (so `_auto` +
* per-keyframe `ease` survive), the keyframes-object `easeEach`, and the OUTER
* tween `ease` untouched. Acorn twin: resizeKeyframedTweenInScript.
*/
export function resizeKeyframedTweenInScript(
script: string,
animationId: string,
newPosition: number,
newDuration: number,
pctRemap: ReadonlyArray<{ from: number; to: number }>,
): string {
const loc = locateAnimationWithFallback(script, animationId);
if (!loc) return script;
const kfNode = findKeyframesObjectNode(loc.target.call.varsArg);
if (!kfNode) return script;
const seen = new Set<AstNode>();
for (const { from, to } of pctRemap) {
const match = findKeyframePropByPct(kfNode, from);
if (!match || seen.has(match.prop)) continue;
seen.add(match.prop);
// Replace only the key node; the value node (incl. _auto + per-keyframe ease)
// stays verbatim. easeEach is a sibling non-percentage prop, left untouched.
match.prop.key = parseExpr(`{ ${JSON.stringify(`${to}%`)}: 0 }`).properties[0].key;
}
applyUpdatesToCall(loc.target.call, { position: newPosition, duration: newDuration });
return recast.print(loc.parsed.ast).code;
}
/**
* Replace the properties (and optionally ease) at an existing keyframe percentage.
*/
@@ -25,6 +25,8 @@ import {
addKeyframeToScript as addKeyframeRecast,
updateKeyframeInScript as updateKeyframeRecast,
removeKeyframeFromScript as removeKeyframeRecast,
moveKeyframeInScript as moveKeyframeRecast,
resizeKeyframedTweenInScript as resizeKeyframedTweenRecast,
addAnimationWithKeyframesToScript as addWithKfRecast,
shiftPositionsInScript as shiftRecast,
scalePositionsInScript as scaleRecast,
@@ -49,6 +51,8 @@ import {
addKeyframeToScript as addKeyframeAcorn,
updateKeyframeInScript as updateKeyframeAcorn,
removeKeyframeFromScript as removeKeyframeAcorn,
moveKeyframeInScript as moveKeyframeAcorn,
resizeKeyframedTweenInScript as resizeKeyframedTweenAcorn,
addAnimationWithKeyframesToScript as addWithKfAcorn,
removeAnimationFromScript as removeAnimAcorn,
shiftPositionsInScript as shiftAcorn,
@@ -1117,6 +1121,157 @@ describe("parity: updateKeyframeInScript (recast vs acorn)", () => {
});
});
// ── moveKeyframeInScript (retime: preserve value + ease) ─────────────────────
// "Move to Playhead" retimes a keyframe in time, keeping its properties and
// per-keyframe ease. The moved keyframe must vanish from the source percentage
// and reappear (with identical value + ease) at the destination; a destination
// collision is overwritten, not duplicated. recast and acorn must agree.
const MOVE_KF_SCRIPT = `
const tl = gsap.timeline({ paused: true });
tl.to("#box", { keyframes: { "0%": { x: 0 }, "50%": { x: 100, opacity: 0.5, ease: "power2.in" }, "100%": { x: 200 } }, duration: 1 }, 0.2);
`;
describe("moveKeyframeInScript: retime preserves value + ease (acorn) ", () => {
it("moves a keyframe to a new percentage, keeping properties + ease", () => {
const id = acornId(MOVE_KF_SCRIPT);
const out = moveKeyframeAcorn(MOVE_KF_SCRIPT, id, 50, 75);
const kfs = shapeOf(out).keyframes?.keyframes ?? [];
const pcts = kfs.map((k) => k.percentage);
expect(pcts).toEqual([0, 75, 100]);
const moved = kfs.find((k) => k.percentage === 75)!;
expect(moved.properties).toEqual({ x: 100, opacity: 0.5 });
expect(moved.ease).toBe("power2.in");
// The source percentage is gone.
expect(pcts).not.toContain(50);
});
it("overwrites the destination keyframe on collision (no duplicate)", () => {
const id = acornId(MOVE_KF_SCRIPT);
const out = moveKeyframeAcorn(MOVE_KF_SCRIPT, id, 50, 100);
const kfs = shapeOf(out).keyframes?.keyframes ?? [];
const pcts = kfs.map((k) => k.percentage);
expect(pcts).toEqual([0, 100]);
const dest = kfs.find((k) => k.percentage === 100)!;
// The moved keyframe's value + ease replaced the old 100% { x: 200 }.
expect(dest.properties).toEqual({ x: 100, opacity: 0.5 });
expect(dest.ease).toBe("power2.in");
});
it("no-ops only for a negligible move (below the drag epsilon)", () => {
const id = acornId(MOVE_KF_SCRIPT);
// < 0.05% of travel resolves onto its own source keyframe → skip the write.
expect(moveKeyframeAcorn(MOVE_KF_SCRIPT, id, 50, 50.02)).toBe(MOVE_KF_SCRIPT);
expect(moveKeyframeRecast(MOVE_KF_SCRIPT, id, 50, 50.02)).toBe(MOVE_KF_SCRIPT);
});
// Regression: a deliberate sub-PCT_TOLERANCE (2%) retime must COMMIT, not get
// swallowed by the old `collision.prop === match.prop` guard (findKfPropByPct
// resolves the 51% destination back onto the 50% from-keyframe).
it("commits a sub-2% retime, keeping value + ease", () => {
const id = acornId(MOVE_KF_SCRIPT);
const out = moveKeyframeAcorn(MOVE_KF_SCRIPT, id, 50, 51);
expect(out).not.toBe(MOVE_KF_SCRIPT);
const kfs = shapeOf(out).keyframes?.keyframes ?? [];
expect(kfs.map((k) => k.percentage)).toEqual([0, 51, 100]);
const moved = kfs.find((k) => k.percentage === 51)!;
expect(moved.properties).toEqual({ x: 100, opacity: 0.5 });
expect(moved.ease).toBe("power2.in");
});
it("no-ops on unknown id / absent source keyframe (both writers)", () => {
const id = acornId(MOVE_KF_SCRIPT);
expect(moveKeyframeAcorn(MOVE_KF_SCRIPT, "bad-id", 50, 75)).toBe(MOVE_KF_SCRIPT);
expect(moveKeyframeRecast(MOVE_KF_SCRIPT, "bad-id", 50, 75)).toBe(MOVE_KF_SCRIPT);
expect(moveKeyframeAcorn(MOVE_KF_SCRIPT, id, 33, 75)).toBe(MOVE_KF_SCRIPT);
});
});
describe("parity: moveKeyframeInScript (recast vs acorn)", () => {
function expectParity(script: string, from: number, to: number) {
const id = acornId(script);
expect(parseGsapScript(script).animations[0]!.id).toBe(id);
expect(modelOf(moveKeyframeAcorn(script, id, from, to))).toEqual(
modelOf(moveKeyframeRecast(script, id, from, to)),
);
}
it("retime to a fresh percentage", () => {
expectParity(MOVE_KF_SCRIPT, 50, 75);
});
it("retime earlier, re-sorting keyframes", () => {
expectParity(MOVE_KF_SCRIPT, 50, 10);
});
it("retime onto an existing percentage (collision overwrite)", () => {
expectParity(MOVE_KF_SCRIPT, 50, 100);
});
it("retime an endpoint inward", () => {
expectParity(MOVE_KF_SCRIPT, 0, 25);
});
it("sub-2% retime agrees between writers (regression for the swallow bug)", () => {
expectParity(MOVE_KF_SCRIPT, 50, 51);
});
});
// ── resizeKeyframedTweenInScript (boundary drag: re-key + grow window) ────────
// Boundary drag-to-retime grows/shifts the tween window and RE-KEYS keyframes in
// place. Unlike replace-with-keyframes (array rebuild), it must preserve author
// intent verbatim: `_auto` endpoint markers, per-keyframe `ease`, the keyframes-
// object `easeEach`, and the OUTER tween `ease`.
const RESIZE_KF_SCRIPT = `
const tl = gsap.timeline({ paused: true });
tl.to("#box", { keyframes: { "0%": { opacity: 0, _auto: 1 }, "50%": { opacity: 0.5, ease: "power2.in" }, "100%": { opacity: 1, _auto: 1 }, easeEach: "power1.inOut" }, duration: 1, ease: "power3.out" }, 0.2);
`;
// Window [0.2, 1.2]; drag the last keyframe (abs 1.2) out to abs 2.2 → [0.2, 2.2].
// abs 0.2/0.7/2.2 over the new 2.0s window → 0 / 25 / 100.
const RESIZE_REMAP = [
{ from: 0, to: 0 },
{ from: 50, to: 25 },
{ from: 100, to: 100 },
];
describe("resizeKeyframedTweenInScript: preserves author intent (acorn + recast)", () => {
for (const [label, resize] of [
["acorn", resizeKeyframedTweenAcorn],
["recast", resizeKeyframedTweenRecast],
] as const) {
it(`${label}: re-keys + grows the window, keeping _auto / ease / easeEach / outer ease`, () => {
const id = acornId(RESIZE_KF_SCRIPT);
const out = resize(RESIZE_KF_SCRIPT, id, 0.2, 2, RESIZE_REMAP);
expect(out).not.toBe(RESIZE_KF_SCRIPT);
const shape = shapeOf(out);
expect(shape.duration).toBe(2);
expect(parseGsapScript(out).animations[0]!.position).toBeCloseTo(0.2, 5);
// Outer tween ease + keyframes-object easeEach survive.
expect(shape.ease).toBe("power3.out");
expect(shape.keyframes?.easeEach).toBe("power1.inOut");
const kfs = shape.keyframes?.keyframes ?? [];
expect(kfs.map((k) => k.percentage)).toEqual([0, 25, 100]);
// _auto endpoints preserved (parsed back as an _auto property).
expect(kfs.find((k) => k.percentage === 0)!.properties).toEqual({ opacity: 0, _auto: 1 });
expect(kfs.find((k) => k.percentage === 100)!.properties).toEqual({ opacity: 1, _auto: 1 });
// Per-keyframe ease on the interior keyframe survives the re-key.
const interior = kfs.find((k) => k.percentage === 25)!;
expect(interior.properties).toEqual({ opacity: 0.5 });
expect(interior.ease).toBe("power2.in");
});
it(`${label}: no-ops on unknown id`, () => {
expect(resize(RESIZE_KF_SCRIPT, "bad-id", 0.2, 2, RESIZE_REMAP)).toBe(RESIZE_KF_SCRIPT);
});
}
it("parity: both writers reparse to the same model", () => {
const id = acornId(RESIZE_KF_SCRIPT);
expect(modelOf(resizeKeyframedTweenAcorn(RESIZE_KF_SCRIPT, id, 0.2, 2, RESIZE_REMAP))).toEqual(
modelOf(resizeKeyframedTweenRecast(RESIZE_KF_SCRIPT, id, 0.2, 2, RESIZE_REMAP)),
);
});
});
// ── addAnimationWithKeyframesToScript parity (recast vs acorn) ───────────────
// WS-3.C add path: both writers insert a new keyframed tl.to() call. The
// inserted statement's authored model (selector, keyframes, duration, ease,
+100
View File
@@ -667,6 +667,10 @@ const PERCENTAGE_KEY_RE = /^(\d+(?:\.\d+)?)%$/;
// treated as the same keyframe (merge), not a new insert.
const PCT_TOLERANCE = 2;
// Below this (tween-%) a retime resolves onto its own source keyframe → skip the
// write. Mirrors the drag layer's NOOP_EPSILON so a deliberate 1% retime commits.
const MOVE_NOOP_EPSILON_PCT = 0.05;
function percentageFromKey(key: string): number {
const m = PERCENTAGE_KEY_RE.exec(key);
return m ? Number.parseFloat(m[1] ?? "0") : Number.NaN;
@@ -1191,6 +1195,102 @@ export function removeKeyframeFromScript(
return ms.toString();
}
/**
* Retime a keyframe: move the keyframe at `fromPercentage` to `toPercentage`,
* PRESERVING its properties and per-keyframe ease (the Studio "Move to Playhead"
* gesture). Re-sorts keyframes by percentage. If a keyframe already exists at
* `toPercentage`, it is overwritten by the moved one (no duplicate). No-op when
* the animation/keyframe isn't found, the tween has no object-form keyframes, or
* the move resolves onto the same keyframe.
*/
export function moveKeyframeInScript(
script: string,
animationId: string,
fromPercentage: number,
toPercentage: number,
): string {
const located = locateWithKeyframes(script, animationId);
if (!located) return script;
const { kfNode } = located;
const match = findKfPropByPct(kfNode, fromPercentage);
if (!match) return script;
// No-op ONLY for a negligible move (matches the drag's NOOP_EPSILON). The old
// `collision.prop === match.prop` guard dropped EVERY sub-PCT_TOLERANCE (2%)
// retime, because findKfPropByPct resolves the destination back onto the
// from-keyframe — so a deliberate 1% drag committed nothing.
if (Math.abs(fromPercentage - toPercentage) < MOVE_NOOP_EPSILON_PCT) return script;
// A destination keyframe is only a real collision (overwrite) when it's a
// DIFFERENT keyframe; resolving back onto the from-keyframe is not.
const dest = findKfPropByPct(kfNode, toPercentage);
const collision = dest && dest.prop !== match.prop ? dest : null;
// Rebuild the keyframes object: drop the moved keyframe (and any keyframe at
// the destination it overwrites), re-key the moved record to toPercentage,
// then re-sort. recordToCode round-trips properties + per-keyframe ease + _auto.
const entries: Array<{ pct: number; record: Record<string, number | string> }> = [];
for (const prop of percentagePropsOf(kfNode)) {
if (prop === match.prop) continue;
if (collision && prop === collision.prop) continue;
const pct = percentageFromKey(propKeyName(prop) ?? "");
if (Number.isNaN(pct)) continue;
entries.push({ pct, record: valueNodeToRecord(prop.value, script) });
}
entries.push({ pct: toPercentage, record: valueNodeToRecord(match.prop.value, script) });
entries.sort((a, b) => a.pct - b.pct);
const body = entries
.map((e) => `${JSON.stringify(`${e.pct}%`)}: ${recordToCode(e.record)}`)
.join(", ");
const ms = new MagicString(script);
ms.overwrite(kfNode.start, kfNode.end, `{ ${body} }`);
return ms.toString();
}
/**
* Resize a keyframed tween's window (boundary drag-to-retime): set the tween's
* `position` (trailing position arg) + `duration`, and RE-KEY each existing
* keyframe to its new percentage via `pctRemap` (each `{ from, to }` matches an
* existing keyframe by its current tween-% and re-keys it to `to`).
*
* Unlike replace-with-keyframes (which rebuilds the keyframes object from a plain
* array and loses author intent), this re-keys the percentage KEY in place and
* leaves every value node, each keyframe's `_auto` + per-keyframe `ease`, the
* keyframes-object `easeEach`, and the OUTER tween `ease` byte-for-byte verbatim.
* No-op when the animation/keyframes can't be located.
*/
export function resizeKeyframedTweenInScript(
script: string,
animationId: string,
newPosition: number,
newDuration: number,
pctRemap: ReadonlyArray<{ from: number; to: number }>,
): string {
const located = locateWithKeyframes(script, animationId);
if (!located) return script;
const { target, kfNode } = located;
// Resolve every re-key against the ORIGINAL AST first (offsets stay stable),
// then splice — distinct key nodes, so the overwrites never overlap. A Set
// guards the degenerate case where two remaps resolve to the same key.
const edits: Array<{ keyNode: Node; to: number }> = [];
const seen = new Set<Node>();
for (const { from, to } of pctRemap) {
const match = findKfPropByPct(kfNode, from);
if (!match || seen.has(match.prop.key)) continue;
seen.add(match.prop.key);
edits.push({ keyNode: match.prop.key, to });
}
const ms = new MagicString(script);
for (const { keyNode, to } of edits) {
ms.overwrite(keyNode.start, keyNode.end, JSON.stringify(`${to}%`));
}
overwritePosition(ms, target.call, newPosition);
upsertProp(ms, target.call.varsArg, "duration", newDuration);
return ms.toString();
}
export function removePropertyFromAnimation(
script: string,
animationId: string,
@@ -450,6 +450,159 @@ tl.to("#box", { opacity: 1, duration: 1 }, 0);
expect(fp.opacity).toBe(0); // untouched
});
// Object-form keyframes — exercises the move-keyframe (retime) route.
const KEYFRAME_COMP = `<!DOCTYPE html><html><body data-duration="3">
<div id="box" data-start="0" data-duration="3"></div>
<script data-hyperframes-gsap>
const tl = gsap.timeline();
tl.to("#box", { keyframes: { "0%": { x: 0 }, "50%": { x: 100, opacity: 0.5, ease: "power2.in" }, "100%": { x: 200 } }, duration: 1.5 }, 0);
</script>
</body></html>`;
it("move-keyframe retimes a keyframe, preserving its value + ease", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "kf.html", KEYFRAME_COMP);
const app = new Hono();
registerFileRoutes(app, createAdapter(projectDir));
const anim = await getFirstAnimation(app, "kf.html");
const res = await app.request("http://localhost/projects/demo/gsap-mutations/kf.html", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "move-keyframe",
animationId: anim.id,
fromPercentage: 50,
toPercentage: 75,
}),
});
const result = (await res.json()) as {
ok: boolean;
changed: boolean;
parsed: {
animations: Array<{
keyframes?: {
keyframes: Array<{
percentage: number;
properties: Record<string, number | string>;
ease?: string;
}>;
};
}>;
};
};
expect(res.status).toBe(200);
expect(result.ok).toBe(true);
expect(result.changed).toBe(true);
const kfs = result.parsed.animations[0].keyframes?.keyframes ?? [];
expect(kfs.map((k) => k.percentage)).toEqual([0, 75, 100]);
const moved = kfs.find((k) => k.percentage === 75)!;
expect(moved.properties).toEqual({ x: 100, opacity: 0.5 });
expect(moved.ease).toBe("power2.in");
});
it("move-keyframe rejects non-finite percentages before writing source", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "kf.html", KEYFRAME_COMP);
const app = new Hono();
registerFileRoutes(app, createAdapter(projectDir));
const anim = await getFirstAnimation(app, "kf.html");
const before = readFileSync(join(projectDir, "kf.html"), "utf-8");
const res = await app.request("http://localhost/projects/demo/gsap-mutations/kf.html", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "move-keyframe",
animationId: anim.id,
fromPercentage: 50,
toPercentage: Number.NaN,
}),
});
expect(res.status).toBe(400);
expect(readFileSync(join(projectDir, "kf.html"), "utf-8")).toBe(before);
});
it("resize-keyframed-tween grows the window + re-keys, preserving value + ease", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "kf.html", KEYFRAME_COMP);
const app = new Hono();
registerFileRoutes(app, createAdapter(projectDir));
const anim = await getFirstAnimation(app, "kf.html");
// Window [0, 1.5]; drag the last keyframe (abs 1.5) out to abs 3 → [0, 3].
// abs 0/0.75/3 over the new 3s window → 0 / 25 / 100.
const res = await app.request("http://localhost/projects/demo/gsap-mutations/kf.html", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "resize-keyframed-tween",
animationId: anim.id,
position: 0,
duration: 3,
pctRemap: [
{ from: 0, to: 0 },
{ from: 50, to: 25 },
{ from: 100, to: 100 },
],
}),
});
const result = (await res.json()) as {
ok: boolean;
changed: boolean;
parsed: {
animations: Array<{
duration?: number;
keyframes?: {
keyframes: Array<{
percentage: number;
properties: Record<string, number | string>;
ease?: string;
}>;
};
}>;
};
};
expect(res.status).toBe(200);
expect(result.ok).toBe(true);
expect(result.changed).toBe(true);
expect(result.parsed.animations[0].duration).toBe(3);
const kfs = result.parsed.animations[0].keyframes?.keyframes ?? [];
expect(kfs.map((k) => k.percentage)).toEqual([0, 25, 100]);
const interior = kfs.find((k) => k.percentage === 25)!;
expect(interior.properties).toEqual({ x: 100, opacity: 0.5 });
expect(interior.ease).toBe("power2.in");
});
it("resize-keyframed-tween rejects non-finite numbers before writing source", async () => {
const projectDir = createProjectDir();
writeHtml(projectDir, "kf.html", KEYFRAME_COMP);
const app = new Hono();
registerFileRoutes(app, createAdapter(projectDir));
const anim = await getFirstAnimation(app, "kf.html");
const before = readFileSync(join(projectDir, "kf.html"), "utf-8");
const res = await app.request("http://localhost/projects/demo/gsap-mutations/kf.html", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "resize-keyframed-tween",
animationId: anim.id,
position: 0,
duration: Number.NaN,
pctRemap: [{ from: 0, to: 0 }],
}),
});
expect(res.status).toBe(400);
expect(readFileSync(join(projectDir, "kf.html"), "utf-8")).toBe(before);
});
it("remove-from-property returns 400 for a non-fromTo animation", async () => {
const projectDir = createProjectDir();
const TO_COMP = `<!DOCTYPE html><html><body><script data-hyperframes-gsap>
@@ -37,6 +37,8 @@ import {
removeAnimationFromScript,
addKeyframeToScript,
removeKeyframeFromScript,
moveKeyframeInScript,
resizeKeyframedTweenInScript,
updateKeyframeInScript,
convertToKeyframesFromScript,
removeAllKeyframesFromScript,
@@ -624,6 +626,22 @@ type GsapMutationRequest =
backfillDefaults?: Record<string, number | string>;
}
| { type: "remove-keyframe"; animationId: string; percentage: number }
| {
type: "move-keyframe";
animationId: string;
fromPercentage: number;
toPercentage: number;
}
| {
// Boundary drag-to-retime: grow/shift a keyframed tween's window and re-key
// its existing keyframes in place (preserves _auto / per-keyframe ease /
// easeEach / outer ease, unlike the array-rebuild replace-with-keyframes).
type: "resize-keyframed-tween";
animationId: string;
position: number;
duration: number;
pctRemap: Array<{ from: number; to: number }>;
}
| {
type: "update-keyframe";
animationId: string;
@@ -778,6 +796,8 @@ const HOLD_SYNC_MUTATION_TYPES = new Set<string>([
"add-keyframe",
"update-keyframe",
"remove-keyframe",
"move-keyframe",
"resize-keyframed-tween",
"remove-all-keyframes",
"add-with-keyframes",
"replace-with-keyframes",
@@ -945,6 +965,23 @@ function executeGsapMutationAcorn(
case "remove-keyframe": {
return removeKeyframeFromScript(block.scriptText, body.animationId, body.percentage);
}
case "move-keyframe": {
return moveKeyframeInScript(
block.scriptText,
body.animationId,
body.fromPercentage,
body.toPercentage,
);
}
case "resize-keyframed-tween": {
return resizeKeyframedTweenInScript(
block.scriptText,
body.animationId,
body.position,
body.duration,
body.pctRemap,
);
}
case "update-keyframe": {
return updateKeyframeInScript(
block.scriptText,
@@ -1103,6 +1140,8 @@ async function executeGsapMutationRecast(
removeAnimationFromScript,
addKeyframeToScript,
removeKeyframeFromScript,
moveKeyframeInScript,
resizeKeyframedTweenInScript,
updateKeyframeInScript,
convertToKeyframesInScript,
removeAllKeyframesFromScript,
@@ -1256,6 +1295,23 @@ async function executeGsapMutationRecast(
case "remove-keyframe": {
return removeKeyframeFromScript(block.scriptText, body.animationId, body.percentage);
}
case "move-keyframe": {
return moveKeyframeInScript(
block.scriptText,
body.animationId,
body.fromPercentage,
body.toPercentage,
);
}
case "resize-keyframed-tween": {
return resizeKeyframedTweenInScript(
block.scriptText,
body.animationId,
body.position,
body.duration,
body.pctRemap,
);
}
case "update-keyframe": {
return updateKeyframeInScript(
block.scriptText,
@@ -1,4 +1,4 @@
import { useState, useMemo, type ReactNode } from "react";
import { useState, useMemo, useCallback, type ReactNode } from "react";
import { NLELayout } from "./nle/NLELayout";
import { CaptionOverlay } from "../captions/components/CaptionOverlay";
import { CaptionTimeline } from "../captions/components/CaptionTimeline";
@@ -18,6 +18,9 @@ import {
} from "./editor/manualEditingAvailability";
import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
import { useDomEditActionsContext, useDomEditSelectionContext } from "../contexts/DomEditContext";
import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
import { resolveClipTimingBasis } from "../hooks/useGsapTweenCache";
import { resolveKeyframeRetime } from "./editor/keyframeRetime";
import { TimelineEditProvider } from "../contexts/TimelineEditContext";
import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
import { readStudioUiPreferences } from "../utils/studioUiPreferences";
@@ -130,6 +133,9 @@ export function StudioPreviewArea({
handleDomBoxSizeCommit,
handleDomRotationCommit,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapUpdateMeta,
handleGsapAddKeyframe,
handleGsapConvertToKeyframes,
@@ -149,6 +155,23 @@ export function StudioPreviewArea({
};
});
// Resolve a timeline-diamond callback's clip-% to the keyframe's anim id + its
// tween-relative percentage (shared by the delete/move keyframe callbacks): the
// diamond reports a clip-% but the script ops key on the tween-%. Prefers the
// anim in the keyframe's property group, falling back to the first keyframed one.
const resolveKeyframeTarget = useCallback(
(pct: number): { animId: string; tweenPct: number } | null => {
const cached = usePlayerStore.getState().keyframeCache.get(domEditSelection?.id ?? "");
const kf = cached?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2);
const group = kf?.propertyGroup;
const anim =
(group ? selectedGsapAnimations.find((a) => a.propertyGroup === group) : undefined) ??
selectedGsapAnimations.find((a) => a.keyframes);
return anim ? { animId: anim.id, tweenPct: kf?.tweenPercentage ?? pct } : null;
},
[domEditSelection?.id, selectedGsapAnimations],
);
// fallow-ignore-next-line complexity
const timelineEditCallbacks = useMemo(
() => ({
@@ -166,17 +189,61 @@ export function StudioPreviewArea({
if (!anim) return;
handleGsapRemoveAllKeyframes(anim.id);
},
// fallow-ignore-next-line complexity
onDeleteKeyframe: (_elId: string, pct: number) => {
const cacheKey = domEditSelection?.id ?? "";
const cached = usePlayerStore.getState().keyframeCache.get(cacheKey);
const kf = cached?.keyframes.find((k) => Math.abs(k.percentage - pct) < 0.2);
const group = kf?.propertyGroup;
const anim =
(group ? selectedGsapAnimations.find((a) => a.propertyGroup === group) : undefined) ??
selectedGsapAnimations.find((a) => a.keyframes);
if (!anim) return;
handleGsapRemoveKeyframe(anim.id, kf?.tweenPercentage ?? pct);
const target = resolveKeyframeTarget(pct);
if (target) handleGsapRemoveKeyframe(target.animId, target.tweenPct);
},
// Retime the keyframe to the playhead, preserving its value + ease.
onMoveKeyframeToPlayhead: (_elId: string, pct: number) => {
const target = resolveKeyframeTarget(pct);
if (target) handleGsapMoveKeyframeToPlayhead(target.animId, target.tweenPct);
},
// Drag-to-retime. The diamond reports clip-%s; resolveKeyframeTarget gives
// the dragged keyframe's anim + tween-%. We convert the clip-% drop to an
// absolute time (via the clip's timing basis) and let resolveKeyframeRetime
// decide: a drop inside the tween window is a plain move (re-key tween-%); a
// drop past the boundary (last keyframe past the end, first before the start)
// resizes the tween — position/duration grow so the dragged keyframe lands at
// the drop while every other keyframe keeps its absolute time (value+ease too).
onMoveKeyframe: (_elId: string, fromClipPct: number, toClipPct: number) => {
const target = resolveKeyframeTarget(fromClipPct);
const sel = domEditSelection;
if (!target || !sel) return;
const anim = selectedGsapAnimations.find((a) => a.id === target.animId);
const tweenStart = anim ? resolveTweenStart(anim) : null;
if (!anim || tweenStart === null) return;
const tweenDuration = anim.duration ?? resolveTweenDuration(anim);
const sourceFile = sel.sourceFile || activeCompPath || "index.html";
const { elements, domClipChildren } = usePlayerStore.getState();
const { elStart, elDuration } = resolveClipTimingBasis(
sel.id ?? "",
sourceFile,
elements,
domClipChildren,
);
const dropAbsTime = elStart + (toClipPct / 100) * elDuration;
const decision = resolveKeyframeRetime({
keyframes: anim.keyframes?.keyframes ?? [],
draggedTweenPct: target.tweenPct,
tweenStart,
tweenDuration,
dropAbsTime,
});
if (decision.kind === "move" && decision.toTweenPct != null) {
handleGsapMoveKeyframe(target.animId, target.tweenPct, decision.toTweenPct);
} else if (
decision.kind === "resize" &&
decision.pctRemap &&
decision.position != null &&
decision.duration != null
) {
handleGsapResizeKeyframedTween(
target.animId,
decision.position,
decision.duration,
decision.pctRemap,
);
}
},
onChangeKeyframeEase: (_elId: string, _pct: number, ease: string) => {
for (const anim of selectedGsapAnimations) {
@@ -213,15 +280,19 @@ export function StudioPreviewArea({
handleRazorSplit,
handleRazorSplitAll,
handleGsapRemoveAllKeyframes,
domEditSelection?.id,
resolveKeyframeTarget,
selectedGsapAnimations,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapUpdateMeta,
handleGsapAddKeyframe,
handleGsapConvertToKeyframes,
buildDomSelectionForTimelineElement,
projectId,
activeCompPath,
domEditSelection,
],
);
@@ -72,6 +72,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
selectedGsapAnimations,
handleGsapRemoveKeyframe,
handleGsapRemoveAllKeyframes,
handleGsapMoveKeyframeToPlayhead,
} = useDomEditContext();
const { rect, geometry, geometryResolved, visibleInPreview, home, pScale } = useMotionPathData(
iframeRef,
@@ -490,6 +491,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({
onClose={() => setKfMenu(null)}
onDelete={(_elId, pct) => animId && handleGsapRemoveKeyframe(animId, pct)}
onDeleteAll={() => animId && handleGsapRemoveAllKeyframes(animId)}
onMoveToPlayhead={(_elId, pct) => animId && handleGsapMoveKeyframeToPlayhead(animId, pct)}
/>
)}
</>
@@ -0,0 +1,195 @@
import { describe, expect, it } from "vitest";
import {
resolveKeyframeDrag,
previewClipPct,
clampToNeighbors,
KEYFRAME_DRAG_THRESHOLD_PX,
} from "./keyframeDrag";
// Three keyframes at clip-% 20 / 40 / 60. The dragged one (index 1) is bounded
// by its neighbours at 20 and 60; first/last are bounded only by the clip.
const CLIP_PCTS = [20, 40, 60];
describe("resolveKeyframeDrag — click vs drag threshold", () => {
const base = {
clipWidthPx: 200,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
};
it("treats sub-threshold movement as a click", () => {
const r = resolveKeyframeDrag({
...base,
pointerDownX: 100,
pointerUpX: 100 + (KEYFRAME_DRAG_THRESHOLD_PX - 1),
});
expect(r.kind).toBe("click");
});
it("treats movement at/over the threshold as a drag", () => {
const r = resolveKeyframeDrag({
...base,
pointerDownX: 100,
pointerUpX: 100 + KEYFRAME_DRAG_THRESHOLD_PX + 1,
});
expect(r.kind).toBe("move");
});
it("guards a zero-width clip (no division blowup) → click", () => {
const r = resolveKeyframeDrag({ ...base, clipWidthPx: 0, pointerDownX: 0, pointerUpX: 50 });
expect(r.kind).toBe("click");
});
it("no-ops a past-threshold drag that resolves to the source percentage", () => {
// Over the px threshold, but on a huge clip the 5px maps to ~0.00125 clip%
// away — under the noop epsilon, so don't commit a churn write.
const r = resolveKeyframeDrag({
...base,
clipWidthPx: 1_000_000,
pointerDownX: 80,
pointerUpX: 80 + KEYFRAME_DRAG_THRESHOLD_PX + 1,
});
expect(r.kind).toBe("noop");
});
});
describe("resolveKeyframeDrag — pixel delta → clip%", () => {
// 200px wide clip → 2px per clip-%. Dragged diamond at clip 40%, pointer-down
// anchored at its pixel position (80px) for a clean delta.
const base = {
clipWidthPx: 200,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
pointerDownX: 80,
};
it("maps a rightward drag to clip-%", () => {
// +20px → +10 clip% → clip 50% (within [20, 60]).
const r = resolveKeyframeDrag({ ...base, pointerUpX: 100 });
expect(r.kind).toBe("move");
expect(r.toClipPct).toBeCloseTo(50, 5);
});
it("maps a leftward drag", () => {
// -20px → -10 clip% → clip 30%.
const r = resolveKeyframeDrag({ ...base, pointerUpX: 60 });
expect(r.toClipPct).toBeCloseTo(30, 5);
});
});
describe("resolveKeyframeDrag — neighbour + clip clamp", () => {
const base = { clipWidthPx: 200, pointerDownX: 80 };
it("an interior keyframe cannot pass its right neighbour", () => {
// Drag the middle (clip 40, index 1) far right → clamps just inside 60.
const r = resolveKeyframeDrag({
...base,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
pointerUpX: 5000,
});
expect(r.toClipPct).toBeLessThan(60);
expect(r.toClipPct).toBeGreaterThan(59); // epsilon inside, not equal/crossed
});
it("an interior keyframe cannot pass its left neighbour", () => {
const r = resolveKeyframeDrag({
...base,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
pointerUpX: -5000,
});
expect(r.toClipPct).toBeGreaterThan(20);
expect(r.toClipPct).toBeLessThan(21);
});
it("the first keyframe is free to the clip start (0%) but bounded by the 2nd", () => {
// Index 0 dragged left past 0 → clamps to 0.
const left = resolveKeyframeDrag({
...base,
draggedClipPct: 20,
draggedIndex: 0,
sortedClipPcts: CLIP_PCTS,
pointerUpX: -5000,
});
expect(left.toClipPct).toBe(0);
// Dragged right past the 2nd keyframe (40) → clamps just inside it.
const right = resolveKeyframeDrag({
...base,
draggedClipPct: 20,
draggedIndex: 0,
sortedClipPcts: CLIP_PCTS,
pointerUpX: 5000,
});
expect(right.toClipPct).toBeLessThan(40);
expect(right.toClipPct).toBeGreaterThan(39);
});
it("the last keyframe is free to the clip end (100%) but bounded by the 2nd-to-last", () => {
const right = resolveKeyframeDrag({
...base,
draggedClipPct: 60,
draggedIndex: 2,
sortedClipPcts: CLIP_PCTS,
pointerUpX: 5000,
});
expect(right.toClipPct).toBe(100);
const left = resolveKeyframeDrag({
...base,
draggedClipPct: 60,
draggedIndex: 2,
sortedClipPcts: CLIP_PCTS,
pointerUpX: -5000,
});
expect(left.toClipPct).toBeGreaterThan(40);
expect(left.toClipPct).toBeLessThan(41);
});
it("a lone keyframe moves freely across the whole clip", () => {
const r = resolveKeyframeDrag({
...base,
draggedClipPct: 50,
draggedIndex: 0,
sortedClipPcts: [50],
pointerUpX: 5000,
});
expect(r.toClipPct).toBe(100);
});
});
describe("clampToNeighbors", () => {
it("pins to the midpoint when neighbours are tighter than 2·epsilon", () => {
// Neighbours at 10 and 10.5 → window [10.5, 10] inverts → midpoint 10.25.
expect(clampToNeighbors(50, [10, 10.2, 10.5], 1)).toBeCloseTo(10.25, 5);
});
});
describe("previewClipPct", () => {
it("follows the pointer in clip-% and clamps to neighbours", () => {
expect(
previewClipPct({
pointerDownX: 80,
pointerMoveX: 100,
clipWidthPx: 200,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
}),
).toBeCloseTo(50, 5);
// Far right → clamps just inside the right neighbour (60), not the clip edge.
expect(
previewClipPct({
pointerDownX: 80,
pointerMoveX: 5000,
clipWidthPx: 200,
draggedClipPct: 40,
draggedIndex: 1,
sortedClipPcts: CLIP_PCTS,
}),
).toBeLessThan(60);
});
});
@@ -0,0 +1,105 @@
/**
* Pure math for the timeline keyframe-diamond drag-to-retime gesture. Kept free
* of React/store so the gesture handler stays a thin orchestrator and the
* click-vs-drag + neighbor clamp are unit-testable in isolation.
*
* The diamond is positioned by clip-relative % (same basis it's drawn with), so
* this layer works entirely in clip-%: it converts the pointer pixel delta to a
* clip-% drop and clamps it between the dragged keyframe's neighbours (and the
* clip bounds). The clip-%→tween-% conversion and the move-vs-resize decision
* happen in the studio handler (it has the tween window + clip timing this layer
* deliberately doesn't), see `keyframeRetime.ts`.
*/
/** Screen-px the pointer must travel before a press counts as a drag (else click). */
export const KEYFRAME_DRAG_THRESHOLD_PX = 4;
/** Clip-% movement below this is treated as no change (drop == original). */
const NOOP_EPSILON_PCT = 0.1;
/** Gap (clip-%) kept between a dragged interior keyframe and each neighbour so it
* can't equal/cross them (which would reorder the keyframes). */
const NEIGHBOR_EPSILON_PCT = 0.5;
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
/**
* Clamp a dragged keyframe's clip-% strictly between its immediate neighbours
* (with a small epsilon so it can't equal/cross them) and to the clip bounds.
*
* - Interior keyframe → bounded by both neighbours.
* - First keyframe (index 0) → left bound is the clip start (0%), so it's free to
* travel left toward/past the tween start (a boundary RESIZE the handler owns).
* - Last keyframe → right bound is the clip end (100%), free to travel right.
* - Lone keyframe → free across the whole clip [0, 100].
*/
export function clampToNeighbors(
clipPct: number,
sortedClipPcts: ReadonlyArray<number>,
draggedIndex: number,
): number {
const left =
draggedIndex > 0 ? (sortedClipPcts[draggedIndex - 1] ?? 0) + NEIGHBOR_EPSILON_PCT : 0;
const right =
draggedIndex < sortedClipPcts.length - 1
? (sortedClipPcts[draggedIndex + 1] ?? 100) - NEIGHBOR_EPSILON_PCT
: 100;
// Degenerate window (neighbours closer than 2·epsilon): pin to the midpoint so
// the result stays ordered between them.
if (left > right) return (left + right) / 2;
return clamp(clipPct, left, right);
}
export interface KeyframeDragResult {
/** `click`: under the drag threshold → seek. `noop`: moved but resolved onto
* the original keyframe → skip the commit. `move`: commit the retime. */
kind: "click" | "noop" | "move";
/** Clip-relative drop position, neighbour- and clip-clamped (only on `move`). */
toClipPct?: number;
}
/**
* Decide whether a diamond press was a click or a drag, and for a drag compute
* the neighbour-clamped clip-% drop position.
*
* - `draggedClipPct`: the dragged diamond's own clip-relative percentage.
* - `draggedIndex` / `sortedClipPcts`: index of the dragged keyframe within the
* clip's keyframes sorted by clip-%, used for the neighbour clamp.
*/
export function resolveKeyframeDrag(opts: {
pointerDownX: number;
pointerUpX: number;
clipWidthPx: number;
draggedClipPct: number;
draggedIndex: number;
sortedClipPcts: ReadonlyArray<number>;
}): KeyframeDragResult {
const dx = opts.pointerUpX - opts.pointerDownX;
if (Math.abs(dx) < KEYFRAME_DRAG_THRESHOLD_PX || opts.clipWidthPx <= 0) {
return { kind: "click" };
}
const rawClipPct = opts.draggedClipPct + (dx / opts.clipWidthPx) * 100;
const toClipPct = clampToNeighbors(rawClipPct, opts.sortedClipPcts, opts.draggedIndex);
if (Math.abs(toClipPct - opts.draggedClipPct) < NOOP_EPSILON_PCT) return { kind: "noop" };
return { kind: "move", toClipPct };
}
/**
* Live drag preview: the dragged diamond's clip-% as it follows the pointer,
* neighbour- and clip-clamped to match where the commit will land. Visual only —
* no runtime/GSAP hold (the #1763 flake).
*/
export function previewClipPct(opts: {
pointerDownX: number;
pointerMoveX: number;
clipWidthPx: number;
draggedClipPct: number;
draggedIndex: number;
sortedClipPcts: ReadonlyArray<number>;
}): number {
if (opts.clipWidthPx <= 0) return opts.draggedClipPct;
const dx = opts.pointerMoveX - opts.pointerDownX;
return clampToNeighbors(
opts.draggedClipPct + (dx / opts.clipWidthPx) * 100,
opts.sortedClipPcts,
opts.draggedIndex,
);
}
@@ -0,0 +1,140 @@
import { describe, expect, it } from "vitest";
import { resolveKeyframeRetime, type RetimeKeyframe } from "./keyframeRetime";
// Tween window [2, 6] (start 2s, duration 4s). Keyframes at tween-% 0/50/100 →
// absolute times 2 / 4 / 6. First + last carry an ease to prove it's preserved.
const KEYFRAMES: RetimeKeyframe[] = [
{ percentage: 0, properties: { x: 0 }, ease: "power1.out" },
{ percentage: 50, properties: { x: 50 } },
{ percentage: 100, properties: { x: 100 }, ease: "power2.in" },
];
const WINDOW = { tweenStart: 2, tweenDuration: 4 };
describe("resolveKeyframeRetime — move (within the tween window)", () => {
it("re-keys an interior keyframe to the tween-% of the drop", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: KEYFRAMES,
draggedTweenPct: 50,
dropAbsTime: 3, // (3-2)/4 = 25%
});
expect(r.kind).toBe("move");
expect(r.toTweenPct).toBeCloseTo(25, 5);
});
it("no-ops a drop that resolves onto the source keyframe", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: KEYFRAMES,
draggedTweenPct: 50,
dropAbsTime: 4, // exactly 50%
});
expect(r.kind).toBe("noop");
});
it("moves a flat (keyframe-less) tween without needing the keyframes array", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: [],
draggedTweenPct: 100,
dropAbsTime: 5, // (5-2)/4 = 75%
});
expect(r.kind).toBe("move");
expect(r.toTweenPct).toBeCloseTo(75, 5);
});
});
describe("resolveKeyframeRetime — resize (past the tween boundary)", () => {
it("extends the LAST keyframe past the end, keeping others' absolute times", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: KEYFRAMES,
draggedTweenPct: 100,
dropAbsTime: 8, // past end (6) → grow duration
});
expect(r.kind).toBe("resize");
expect(r.position).toBeCloseTo(2, 5); // start unchanged
expect(r.duration).toBeCloseTo(6, 5); // 8 - 2
// abs 2/4/8 over the new [2,8] window → 0 / 33.3 / 100. pctRemap carries each
// existing keyframe's old→new tween-%; the commit re-keys in place (value +
// ease + _auto preserved by round-tripping the source node, not re-emitted here).
expect(r.pctRemap).toEqual([
{ from: 0, to: 0 },
{ from: 50, to: 33.3 },
{ from: 100, to: 100 },
]);
});
it("extends the FIRST keyframe before the start, shifting position earlier", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: KEYFRAMES,
draggedTweenPct: 0,
dropAbsTime: 0.5, // before start (2) → move position back + grow duration
});
expect(r.kind).toBe("resize");
expect(r.position).toBeCloseTo(0.5, 5);
expect(r.duration).toBeCloseTo(5.5, 5); // 6 - 0.5
// abs 0.5/4/6 over [0.5,6] → 0 / 63.6 / 100.
expect(r.pctRemap).toEqual([
{ from: 0, to: 0 },
{ from: 50, to: 63.6 },
{ from: 100, to: 100 },
]);
});
});
describe("resolveKeyframeRetime — single keyframe (both first and last)", () => {
const lone: RetimeKeyframe[] = [{ percentage: 100, properties: { x: 9 } }];
it("resizes right past the end", () => {
const r = resolveKeyframeRetime({
...WINDOW, // lone keyframe sits at abs 6
keyframes: lone,
draggedTweenPct: 100,
dropAbsTime: 9,
});
expect(r.kind).toBe("resize");
expect(r.position).toBeCloseTo(2, 5);
expect(r.duration).toBeCloseTo(7, 5);
expect(r.pctRemap).toEqual([{ from: 100, to: 100 }]);
});
it("resizes left before the start", () => {
const r = resolveKeyframeRetime({
...WINDOW,
keyframes: lone,
draggedTweenPct: 100,
dropAbsTime: 0.5,
});
expect(r.kind).toBe("resize");
expect(r.position).toBeCloseTo(0.5, 5);
expect(r.duration).toBeCloseTo(5.5, 5);
expect(r.pctRemap).toEqual([{ from: 100, to: 0 }]);
});
});
describe("resolveKeyframeRetime — guards", () => {
it("no-ops a zero-duration tween", () => {
expect(
resolveKeyframeRetime({
tweenStart: 2,
tweenDuration: 0,
keyframes: KEYFRAMES,
draggedTweenPct: 50,
dropAbsTime: 3,
}).kind,
).toBe("noop");
});
it("no-ops a boundary drop on a flat tween (nothing to remap)", () => {
expect(
resolveKeyframeRetime({
...WINDOW,
keyframes: [],
draggedTweenPct: 100,
dropAbsTime: 8,
}).kind,
).toBe("noop");
});
});
@@ -0,0 +1,121 @@
/**
* Pure move-vs-resize decision + absolute-time remap for keyframe drag-to-retime.
*
* Keyframes live inside the ANIMATION's window (tween position + duration), which
* is usually shorter than the clip. Dragging a keyframe is one of:
* - MOVE: the drop stays within `[tweenStart, tweenEnd]` → re-key the tween-%.
* - RESIZE: the drop crosses the tween boundary (the LAST keyframe past the end,
* or the FIRST before the start, but still inside the clip — the gesture layer
* already clamped to neighbours + clip). The tween's window grows so the
* dragged keyframe lands exactly where dropped; every OTHER keyframe keeps its
* ABSOLUTE time (its tween-% remaps onto the new, longer window). Value + ease
* are preserved per keyframe.
*
* 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.
*/
export interface RetimeKeyframe {
/** Tween-relative percentage (the writer/runtime key on this). */
percentage: number;
properties: Record<string, number | string>;
ease?: string;
}
/** One existing keyframe's old→new tween-% under a resize remap. */
export interface KeyframePctRemap {
/** The existing keyframe's current tween-relative %. */
from: number;
/** Its new tween-relative % on the resized window. */
to: number;
}
export interface KeyframeRetimeResult {
kind: "noop" | "move" | "resize";
/** MOVE: tween-relative drop position. */
toTweenPct?: number;
/** RESIZE: new tween position (absolute seconds). */
position?: number;
/** RESIZE: new tween duration (seconds). */
duration?: number;
/**
* RESIZE: each existing keyframe's old→new tween-%. The commit re-keys each
* keyframe IN PLACE (round-tripping its value node), so `_auto`, per-keyframe
* `ease`, `easeEach`, and the outer tween `ease` all survive — unlike rebuilding
* a fresh keyframes array.
*/
pctRemap?: KeyframePctRemap[];
}
/** Below this (tween-%) a move resolves onto the source keyframe → skip the write. */
const NOOP_EPSILON_PCT = 0.1;
/** Slack (seconds) for the within-tween boundary test. */
const EPSILON_TIME = 1e-4;
const round3 = (n: number) => Math.round(n * 1000) / 1000;
const round1 = (n: number) => Math.round(n * 10) / 10; // 0.1% precision
const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
/**
* Decide move vs resize for a dragged keyframe and, for resize, return the new
* tween window + remapped keyframes.
*
* - `keyframes`: the tween's keyframes (tween-relative %, with value + ease).
* - `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).
*/
export function resolveKeyframeRetime(opts: {
keyframes: ReadonlyArray<RetimeKeyframe>;
draggedTweenPct: number;
tweenStart: number;
tweenDuration: number;
dropAbsTime: number;
}): KeyframeRetimeResult {
const { keyframes, draggedTweenPct, tweenStart, tweenDuration, dropAbsTime } = opts;
if (tweenDuration <= 0) return { kind: "noop" };
const tweenEnd = tweenStart + tweenDuration;
// Within the tween window → plain move (re-key the tween-%). This branch never
// touches the keyframes array, so it still works for synthesized flat tweens.
if (dropAbsTime >= tweenStart - EPSILON_TIME && dropAbsTime <= tweenEnd + EPSILON_TIME) {
const toTweenPct = clamp(((dropAbsTime - tweenStart) / tweenDuration) * 100, 0, 100);
if (Math.abs(toTweenPct - draggedTweenPct) < NOOP_EPSILON_PCT) return { kind: "noop" };
return { kind: "move", toTweenPct };
}
// Boundary resize needs the real keyframes to remap; a flat tween has none here.
if (keyframes.length === 0) return { kind: "noop" };
const newStart = Math.min(dropAbsTime, tweenStart);
const newEnd = Math.max(dropAbsTime, tweenEnd);
const newDuration = Math.max(0.01, newEnd - newStart);
// The dragged keyframe is the one whose tween-% is closest to draggedTweenPct.
let draggedIdx = 0;
let best = Infinity;
keyframes.forEach((kf, i) => {
const d = Math.abs(kf.percentage - draggedTweenPct);
if (d < best) {
best = d;
draggedIdx = i;
}
});
// Map each existing keyframe to its new tween-% on the grown window, preserving
// its absolute time (the dragged one lands at the drop). Carry only the old→new
// percentages; the commit re-keys in place so value + ease + _auto + easeEach
// 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: round1(((absTime - newStart) / newDuration) * 100) };
});
return {
kind: "resize",
position: round3(newStart),
duration: round3(newDuration),
pctRemap,
};
}
@@ -54,6 +54,9 @@ export interface DomEditActionsValue extends Pick<
| "handleGsapAddKeyframe"
| "handleGsapAddKeyframeBatch"
| "handleGsapRemoveKeyframe"
| "handleGsapMoveKeyframeToPlayhead"
| "handleGsapMoveKeyframe"
| "handleGsapResizeKeyframedTween"
| "handleGsapConvertToKeyframes"
| "handleGsapRemoveAllKeyframes"
| "handleResetSelectedElementKeyframes"
@@ -169,6 +172,9 @@ export function DomEditProvider({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -247,6 +253,9 @@ export function DomEditProvider({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -311,6 +320,9 @@ export function DomEditProvider({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -39,6 +39,8 @@ export function TimelineEditProvider({
value.onDeleteKeyframe,
value.onDeleteAllKeyframes,
value.onChangeKeyframeEase,
value.onMoveKeyframeToPlayhead,
value.onMoveKeyframe,
value.onToggleKeyframeAtPlayhead,
],
);
@@ -201,6 +201,8 @@ export function useDomEditSession({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
setArcPath,
@@ -356,6 +358,9 @@ export function useDomEditSession({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -393,6 +398,8 @@ export function useDomEditSession({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
@@ -553,6 +560,9 @@ export function useDomEditSession({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -87,6 +87,19 @@ export interface UseDomEditWiringParams {
properties: Record<string, number | string>,
) => Promise<void>;
removeKeyframe: (sel: DomEditSelection, animId: string, percentage: number) => void;
moveKeyframe: (
sel: DomEditSelection,
animId: string,
fromPercentage: number,
toPercentage: number,
) => void;
resizeKeyframedTween: (
sel: DomEditSelection,
animId: string,
position: number,
duration: number,
pctRemap: Array<{ from: number; to: number }>,
) => void;
convertToKeyframes: (
sel: DomEditSelection,
animId: string,
@@ -131,6 +144,8 @@ export function useDomEditWiring({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
@@ -224,6 +239,8 @@ export function useDomEditWiring({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
@@ -0,0 +1,101 @@
// @vitest-environment happy-dom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
// Tell React this is an act-capable environment so act(...) flushes effects.
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { useGsapKeyframeOps } from "./useGsapKeyframeOps";
type HookApi = ReturnType<typeof useGsapKeyframeOps>;
let cleanup: (() => void) | null = null;
afterEach(() => {
cleanup?.();
cleanup = null;
});
const selection: DomEditSelection = { id: "box", selector: "#box" } as DomEditSelection;
function renderKeyframeOps(over: {
commitMutation: (...args: unknown[]) => Promise<unknown>;
trackGsapSaveFailure: (...args: unknown[]) => void;
}) {
const captured: { api: HookApi | null } = { api: null };
function Probe() {
captured.api = useGsapKeyframeOps({
activeCompPath: "index.html",
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test doubles
commitMutation: over.commitMutation as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test doubles
commitMutationSafely: (() => {}) as any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- test doubles
trackGsapSaveFailure: over.trackGsapSaveFailure as any,
sdkSession: null,
sdkDeps: null,
});
return null;
}
const container = document.createElement("div");
const root = createRoot(container);
act(() => {
root.render(<Probe />);
});
cleanup = () => act(() => root.unmount());
if (!captured.api) throw new Error("hook did not initialize");
return captured.api;
}
describe("useGsapKeyframeOps — resizeKeyframedTween", () => {
it("issues a resize-keyframed-tween mutation with the remap + window", async () => {
const commitMutation = vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => ({
ok: true,
}));
const trackGsapSaveFailure = vi.fn<(...args: unknown[]) => void>();
const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure });
const pctRemap = [
{ from: 0, to: 0 },
{ from: 100, to: 100 },
];
await act(async () => {
api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, pctRemap);
});
expect(commitMutation).toHaveBeenCalledTimes(1);
const [sel, mutation] = commitMutation.mock.calls[0]!;
expect(sel).toBe(selection);
expect(mutation).toEqual({
type: "resize-keyframed-tween",
animationId: "box-to-0-opacity",
position: 0.2,
duration: 2,
pctRemap,
});
expect(trackGsapSaveFailure).not.toHaveBeenCalled();
});
it("routes a rejected commit to trackGsapSaveFailure (no unhandled rejection)", async () => {
const error = new Error("network down");
const commitMutation = vi.fn<(...args: unknown[]) => Promise<unknown>>(async () => {
throw error;
});
const trackGsapSaveFailure = vi.fn<(...args: unknown[]) => void>();
const api = renderKeyframeOps({ commitMutation, trackGsapSaveFailure });
await act(async () => {
api.resizeKeyframedTween(selection, "box-to-0-opacity", 0.2, 2, [{ from: 100, to: 100 }]);
// let the rejected commit promise settle inside act
await Promise.resolve();
});
expect(trackGsapSaveFailure).toHaveBeenCalledTimes(1);
const [errArg, selArg, mutationArg, labelArg] = trackGsapSaveFailure.mock.calls[0]!;
expect(errArg).toBe(error);
expect(selArg).toBe(selection);
expect((mutationArg as { type: string }).type).toBe("resize-keyframed-tween");
expect(labelArg).toBe("Retime keyframe (resize tween)");
});
});
@@ -205,6 +205,56 @@ export function useGsapKeyframeOps({
[activeCompPath, commitMutation, trackGsapSaveFailure, sdkSession, sdkDeps],
);
const moveKeyframe = useCallback(
(
selection: DomEditSelection,
animationId: string,
fromPercentage: number,
toPercentage: number,
) => {
const mutation = { type: "move-keyframe", animationId, fromPercentage, toPercentage };
// No SDK persist helper exists for retime — server path only. The post-commit
// updateKeyframeCacheFromParsed re-keys the diamond from the fresh parse, so no
// optimistic cache write is needed (mapping the tween-% to clip-% here would
// duplicate that math). softReload mirrors remove-keyframe.
void commitMutation(selection, mutation, {
label: `Move keyframe to ${toPercentage}%`,
softReload: true,
}).catch((error) => {
trackGsapSaveFailure(error, selection, mutation, `Move keyframe to ${toPercentage}%`);
});
},
[commitMutation, trackGsapSaveFailure],
);
const resizeKeyframedTween = useCallback(
(
selection: DomEditSelection,
animationId: string,
position: number,
duration: number,
pctRemap: Array<{ from: number; to: number }>,
) => {
const mutation = {
type: "resize-keyframed-tween",
animationId,
position,
duration,
pctRemap,
};
// Boundary drag-to-retime: the server re-keys keyframes in place + grows the
// tween window, preserving _auto / per-keyframe ease / easeEach / outer ease.
// softReload re-keys the diamonds from the fresh parse (mirrors moveKeyframe).
void commitMutation(selection, mutation, {
label: "Retime keyframe (resize tween)",
softReload: true,
}).catch((error) => {
trackGsapSaveFailure(error, selection, mutation, "Retime keyframe (resize tween)");
});
},
[commitMutation, trackGsapSaveFailure],
);
const convertToKeyframes = useCallback(
async (
selection: DomEditSelection,
@@ -276,6 +326,8 @@ export function useGsapKeyframeOps({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
commitKeyframeAtTime,
@@ -1,6 +1,8 @@
import { useCallback, useRef } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditing";
import { usePlayerStore } from "../player";
import { computeCurrentPercentage } from "./gsapDragCommit";
import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { trackStudioEvent } from "../utils/studioTelemetry";
@@ -25,6 +27,8 @@ export function useGsapSelectionHandlers({
addKeyframe,
addKeyframeBatch,
removeKeyframe,
moveKeyframe,
resizeKeyframedTween,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
@@ -73,6 +77,19 @@ export function useGsapSelectionHandlers({
properties: Record<string, number | string>,
) => Promise<void>;
removeKeyframe: (sel: DomEditSelection, animId: string, percentage: number) => void;
moveKeyframe: (
sel: DomEditSelection,
animId: string,
fromPercentage: number,
toPercentage: number,
) => void;
resizeKeyframedTween: (
sel: DomEditSelection,
animId: string,
position: number,
duration: number,
pctRemap: Array<{ from: number; to: number }>,
) => void;
convertToKeyframes: (
sel: DomEditSelection,
animId: string,
@@ -82,7 +99,7 @@ export function useGsapSelectionHandlers({
removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
handleDomManualEditsReset: (sel: DomEditSelection) => void;
selectedGsapAnimations: { id: string; keyframes?: unknown }[];
selectedGsapAnimations: GsapAnimation[];
}) {
const lastSelectionRef = useRef<DomEditSelection | null>(null);
if (domEditSelection) lastSelectionRef.current = domEditSelection;
@@ -233,6 +250,57 @@ export function useGsapSelectionHandlers({
[domEditSelection, removeKeyframe],
);
const handleGsapMoveKeyframeToPlayhead = useCallback(
(animId: string, fromPercentage: number, selectionOverride?: DomEditSelection | null) => {
const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
// Retime the keyframe to the playhead, preserving its value + ease. The
// playhead's tween-relative percentage is the move target.
const anim = selectedGsapAnimations.find((a) => a.id === animId);
const toPercentage = computeCurrentPercentage(sel, anim);
trackStudioEvent("keyframe", { action: "move_to_playhead" });
moveKeyframe(sel, animId, fromPercentage, toPercentage);
},
[domEditSelection, selectedGsapAnimations, moveKeyframe],
);
const handleGsapMoveKeyframe = useCallback(
(
animId: string,
fromPercentage: number,
toPercentage: number,
selectionOverride?: DomEditSelection | null,
) => {
const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
// Atomic retime: preserves the keyframe's value + per-keyframe ease. Both
// percentages are tween-relative (the drag handler converts the drop
// position before calling). No optimistic runtime hold — the soft-reload
// re-keys the diamond from source.
trackStudioEvent("keyframe", { action: "retime" });
moveKeyframe(sel, animId, fromPercentage, toPercentage);
},
[domEditSelection, moveKeyframe],
);
const handleGsapResizeKeyframedTween = useCallback(
(
animId: string,
position: number,
duration: number,
pctRemap: Array<{ from: number; to: number }>,
selectionOverride?: DomEditSelection | null,
) => {
const sel = selectionOverride ?? domEditSelection ?? lastSelectionRef.current;
if (!sel) return;
// Boundary drag-to-retime: grows/shifts the tween window + re-keys keyframes
// in place. Distinct telemetry action so resize is separable from in-window move.
trackStudioEvent("keyframe", { action: "retime_resize" });
resizeKeyframedTween(sel, animId, position, duration, pctRemap);
},
[domEditSelection, resizeKeyframedTween],
);
const handleGsapConvertToKeyframes = useCallback(
(animId: string, resolvedFromValues?: Record<string, number | string>, duration?: number) => {
if (!domEditSelection) return Promise.resolve();
@@ -280,6 +348,9 @@ export function useGsapSelectionHandlers({
handleGsapAddKeyframe,
handleGsapAddKeyframeBatch,
handleGsapRemoveKeyframe,
handleGsapMoveKeyframeToPlayhead,
handleGsapMoveKeyframe,
handleGsapResizeKeyframedTween,
handleGsapConvertToKeyframes,
handleGsapRemoveAllKeyframes,
handleResetSelectedElementKeyframes,
@@ -128,7 +128,7 @@ export async function fetchParsedAnimations(
* Fall back to the sub-comp HOST's bounds, resolved via domClipChildren (the host's
* data-composition-src is stripped in the rendered DOM, so we can't query it).
*/
function resolveClipTimingBasis(
export function resolveClipTimingBasis(
elementId: string,
sourceFile: string,
elements: ReadonlyArray<{
@@ -18,6 +18,8 @@ interface KeyframeDiamondContextMenuProps {
onDeleteAll: (elementId: string) => void;
onChangeEase?: (elementId: string, percentage: number, ease: string) => void;
onCopyProperties?: (elementId: string, percentage: number) => void;
/** Retime the keyframe to the current playhead, preserving its value + ease. */
onMoveToPlayhead?: (elementId: string, fromPercentage: number) => void;
}
export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMenu({
@@ -25,11 +27,12 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe
onClose,
onDelete,
onDeleteAll,
onMoveToPlayhead,
}: KeyframeDiamondContextMenuProps) {
const menuRef = useContextMenuDismiss(onClose);
const menuWidth = 200;
const menuHeight = 70;
const menuHeight = onMoveToPlayhead ? 100 : 70;
const overflowY = state.y + menuHeight - window.innerHeight;
const adjustedX = state.x + menuWidth > window.innerWidth ? state.x - menuWidth : state.x;
const adjustedY = overflowY > 0 ? state.y - overflowY - 8 : state.y;
@@ -40,12 +43,28 @@ export const KeyframeDiamondContextMenu = memo(function KeyframeDiamondContextMe
className="fixed z-50 bg-neutral-900 border border-neutral-700 rounded-md shadow-lg py-1 min-w-[180px]"
style={{ left: adjustedX, top: adjustedY }}
>
{onMoveToPlayhead && (
<button
type="button"
className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-neutral-200 hover:bg-neutral-800 cursor-pointer text-left"
onClick={() => {
// Pass clip-% — resolveKeyframeTarget keys the cache lookup on clip-%
// and returns the tween-% for the mutation. Passing tween-% here would
// miss the lookup on any tween whose window is shorter than the clip.
onMoveToPlayhead(state.elementId, state.percentage);
onClose();
}}
>
Move to Playhead
</button>
)}
{/* Delete */}
<button
type="button"
className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-red-400 hover:bg-neutral-800 cursor-pointer text-left"
onClick={() => {
onDelete(state.elementId, state.tweenPercentage ?? state.percentage);
onDelete(state.elementId, state.percentage);
onClose();
}}
>
@@ -86,6 +86,8 @@ export const Timeline = memo(function Timeline({
onDeleteKeyframe,
onDeleteAllKeyframes,
onChangeKeyframeEase,
onMoveKeyframeToPlayhead,
onMoveKeyframe,
} = useResolvedTimelineEditCallbacks({
onMoveElement: onMoveElementOverride,
onResizeElement: onResizeElementOverride,
@@ -479,6 +481,7 @@ export const Timeline = memo(function Timeline({
onShiftClickKeyframe={(elId, pct) => {
toggleSelectedKeyframe(`${elId}:${pct}`);
}}
onMoveKeyframe={onMoveKeyframe}
onContextMenuKeyframe={(e, elId, pct) => {
const el = expandedElements.find((x) => (x.key ?? x.id) === elId);
if (el) {
@@ -556,6 +559,11 @@ export const Timeline = memo(function Timeline({
onDelete={(elId, pct) => onDeleteKeyframe?.(elId, pct)}
onDeleteAll={(elId) => onDeleteAllKeyframes?.(elId)}
onChangeEase={(elId, pct, ease) => onChangeKeyframeEase?.(elId, pct, ease)}
onMoveToPlayhead={
onMoveKeyframeToPlayhead
? (elId, pct) => onMoveKeyframeToPlayhead(elId, pct)
: undefined
}
onCopyProperties={(elId, pct) => {
const kfData = keyframeCache.get(elId);
const kf = kfData?.keyframes.find((k) => k.percentage === pct);
@@ -92,6 +92,11 @@ interface TimelineCanvasProps {
onClickKeyframe?: (element: TimelineElement, percentage: number) => void;
onShiftClickKeyframe?: (elementId: string, percentage: number) => void;
onContextMenuKeyframe?: (e: React.MouseEvent, elementId: string, percentage: number) => void;
onMoveKeyframe?: (
elementId: string,
fromClipPercentage: number,
toClipPercentage: number,
) => void;
onContextMenuClip?: (e: React.MouseEvent, element: TimelineElement) => void;
beatAnalysis?: MusicBeatAnalysis | null;
}
@@ -139,6 +144,7 @@ export const TimelineCanvas = memo(function TimelineCanvas({
onClickKeyframe,
onShiftClickKeyframe,
onContextMenuKeyframe,
onMoveKeyframe,
onContextMenuClip,
beatAnalysis,
}: TimelineCanvasProps) {
@@ -439,6 +445,7 @@ export const TimelineCanvas = memo(function TimelineCanvas({
onClickKeyframe={(pct) => onClickKeyframe?.(previewElement, pct)}
onShiftClickKeyframe={onShiftClickKeyframe}
onContextMenuKeyframe={onContextMenuKeyframe}
onMoveKeyframe={onMoveKeyframe}
/>
)}
</TimelineClip>
@@ -1,8 +1,15 @@
import { memo } from "react";
import { memo, useRef, useState } from "react";
import { BEAT_BAND_H } from "./BeatStrip";
import {
KEYFRAME_DRAG_THRESHOLD_PX,
previewClipPct,
resolveKeyframeDrag,
} from "../../components/editor/keyframeDrag";
interface KeyframeEntry {
percentage: number;
/** Tween-relative percentage (the retime mutation keys on this, not clip %). */
tweenPercentage?: number;
properties: Record<string, number | string>;
ease?: string;
}
@@ -29,6 +36,15 @@ interface TimelineClipDiamondsProps {
onClickKeyframe?: (percentage: number) => void;
onShiftClickKeyframe?: (elementId: string, percentage: number) => void;
onContextMenuKeyframe?: (e: React.MouseEvent, elementId: string, percentage: number) => void;
/** Drag-to-retime: move a keyframe to a new time, preserving its value + ease.
* Both percentages are clip-relative: `fromClipPercentage` identifies the
* dragged keyframe, `toClipPercentage` is the neighbour-clamped drop position.
* The handler decides move (within the tween) vs resize (past its boundary). */
onMoveKeyframe?: (
elementId: string,
fromClipPercentage: number,
toClipPercentage: number,
) => void;
}
const DIAMOND_RATIO = 0.8;
@@ -39,6 +55,13 @@ const DIAMOND_RATIO = 0.8;
const KF_MIN_PCT = -5;
const KF_MAX_PCT = 105;
type DragState = {
kfKey: string;
startX: number;
fromClipPct: number;
moved: boolean;
};
export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
keyframesData,
clipWidthPx,
@@ -52,7 +75,15 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
onClickKeyframe,
onShiftClickKeyframe,
onContextMenuKeyframe,
onMoveKeyframe,
}: TimelineClipDiamondsProps) {
// Hooks must run before the early return below.
const dragRef = useRef<DragState | null>(null);
// Visual-only preview of the dragged diamond's clip-% — no runtime/GSAP hold
// (that optimistic hold was the #1763 flake). The atomic move-keyframe commit
// on drop re-keys the diamond from source.
const [preview, setPreview] = useState<{ kfKey: string; clipPct: number } | null>(null);
if (clipWidthPx < 20) return null;
// When the beat strip occupies the top band, shrink the diamonds and center
@@ -63,17 +94,12 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
const sorted = keyframesData.keyframes
.filter((kf) => kf.percentage >= KF_MIN_PCT && kf.percentage <= KF_MAX_PCT)
.sort((a, b) => a.percentage - b.percentage);
// Clip-%s of the sorted keyframes — the neighbour clamp (preview + drop) needs
// the whole row to bound the dragged diamond between its immediate siblings.
const sortedClipPcts = sorted.map((k) => k.percentage);
const baseColor = isSelected ? accentColor : "#a3a3a3";
const baseOpacity = isSelected ? 0.4 : 0.25;
const handleClick = (e: React.MouseEvent, pct: number) => {
e.stopPropagation();
if (e.shiftKey) {
onShiftClickKeyframe?.(elementId, pct);
} else {
onClickKeyframe?.(pct);
}
};
const canDrag = isSelected && !!onMoveKeyframe;
return (
<div className="absolute inset-0" style={{ zIndex: 3, pointerEvents: "none" }}>
@@ -102,17 +128,80 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
})}
{sorted.map((kf, i) => {
const kfKey = `${elementId}:${kf.percentage}`;
// While dragging this diamond, render it at the live preview clip-%.
const renderPct = preview?.kfKey === kfKey ? preview.clipPct : kf.percentage;
// Center the diamond ON its keyframe %: left = (% · width) − half so the
// diamond's midpoint sits exactly at the percentage. At 0% the midpoint
// is the clip's left edge (the diamond's left half overflows, which the
// overflow-visible clip shows) — NOT shifted fully inside. No clamp, or
// boundary keyframes (0% / 100%) would render off-center.
const leftPx = (kf.percentage / 100) * clipWidthPx - half;
const kfKey = `${elementId}:${kf.percentage}`;
// is the clip's left edge (the left half overflows, which the
// overflow-visible clip shows) — NOT shifted fully inside.
const leftPx = (renderPct / 100) * clipWidthPx - half;
const isKfSelected = selectedKeyframes.has(kfKey);
const atPlayhead = isSelected && Math.abs(kf.percentage - currentPercentage) < 0.5;
const isHighlighted = isKfSelected || atPlayhead;
const color = isHighlighted ? accentColor : "#a3a3a3";
const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {
if (e.button !== 0) return;
e.stopPropagation();
if (canDrag) {
e.currentTarget.setPointerCapture?.(e.pointerId);
dragRef.current = {
kfKey,
startX: e.clientX,
fromClipPct: kf.percentage,
moved: false,
};
}
};
const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {
const d = dragRef.current;
if (!d || d.kfKey !== kfKey) return;
if (!d.moved && Math.abs(e.clientX - d.startX) >= KEYFRAME_DRAG_THRESHOLD_PX) {
d.moved = true;
}
if (d.moved) {
setPreview({
kfKey,
clipPct: previewClipPct({
pointerDownX: d.startX,
pointerMoveX: e.clientX,
clipWidthPx,
draggedClipPct: d.fromClipPct,
draggedIndex: i,
sortedClipPcts,
}),
});
}
};
const onPointerUp = (e: React.PointerEvent<HTMLButtonElement>) => {
const d = dragRef.current;
// No drag armed (canDrag false / non-primary press) → treat as a click.
if (!d || d.kfKey !== kfKey) {
if (e.shiftKey) onShiftClickKeyframe?.(elementId, kf.percentage);
else onClickKeyframe?.(kf.percentage);
return;
}
e.stopPropagation();
dragRef.current = null;
setPreview(null);
e.currentTarget.releasePointerCapture?.(e.pointerId);
const res = resolveKeyframeDrag({
pointerDownX: d.startX,
pointerUpX: e.clientX,
clipWidthPx,
draggedClipPct: d.fromClipPct,
draggedIndex: i,
sortedClipPcts,
});
if (res.kind === "click") {
if (e.shiftKey) onShiftClickKeyframe?.(elementId, kf.percentage);
else onClickKeyframe?.(kf.percentage);
} else if (res.kind === "move" && res.toClipPct != null) {
onMoveKeyframe?.(elementId, d.fromClipPct, res.toClipPct);
}
};
return (
<button
key={`${i}-${kf.percentage}`}
@@ -128,10 +217,13 @@ export const TimelineClipDiamonds = memo(function TimelineClipDiamonds({
pointerEvents: "auto",
background: "none",
border: "none",
cursor: "pointer",
cursor: canDrag ? "ew-resize" : "pointer",
padding: 0,
touchAction: "none",
}}
onClick={(e) => handleClick(e, kf.percentage)}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -39,5 +39,11 @@ export interface TimelineEditCallbacks {
onDeleteKeyframe?: (elementId: string, percentage: number) => void;
onDeleteAllKeyframes?: (elementId: string) => void;
onChangeKeyframeEase?: (elementId: string, percentage: number, ease: string) => void;
onMoveKeyframeToPlayhead?: (elementId: string, percentage: number) => void;
onMoveKeyframe?: (
elementId: string,
fromClipPercentage: number,
toClipPercentage: number,
) => void;
onToggleKeyframeAtPlayhead?: (element: TimelineElement) => void;
}