Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(sdk): ws-3c — addWithKeyframes + replaceWithKeyframes SDK ops (acorn writer) (#1572)
Vance Ingalls418f198b3391
diff --git a/packages/core/src/parsers/gsapWriter.parity.test.ts b/packages/core/src/parsers/gsapWriter.parity.test.tsindex 2a478bb0a5..1cc605622e 100644--- a/packages/core/src/parsers/gsapWriter.parity.test.ts+++ b/packages/core/src/parsers/gsapWriter.parity.test.ts@@ -22,6 +22,7 @@ import {addKeyframeToScript as addKeyframeRecast,removeKeyframeFromScript as removeKeyframeRecast,addAnimationWithKeyframesToScript as addWithKfRecast,+ removeAnimationFromScript as removeAnimRecast,shiftPositionsInScript as shiftRecast,scalePositionsInScript as scaleRecast,type SplitAnimationsOptions,@@ -44,6 +45,7 @@ import {addKeyframeToScript as addKeyframeAcorn,removeKeyframeFromScript as removeKeyframeAcorn,addAnimationWithKeyframesToScript as addWithKfAcorn,+ removeAnimationFromScript as removeAnimAcorn,shiftPositionsInScript as shiftAcorn,scalePositionsInScript as scaleAcorn,} from "./gsapWriterAcorn.js";@@ -917,6 +919,132 @@ describe("parity: addAnimationWithKeyframesToScript (recast vs acorn)", () => {const recast = addWithKfRecast(ADD_WITH_KF_BASE, "#card", 1.5, 2.25, kfs, "none").script;expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));});++ // WS-3.C: auto-endpoint markers must round-trip through both writers.+ it("_auto endpoint: 0% and 100% carry the _auto marker", () => {+ const kfs = [+ { percentage: 0, properties: { x: 0, opacity: 1 }, auto: true },+ { percentage: 50, properties: { x: 100, opacity: 0.5 } },+ { percentage: 100, properties: { x: 200, opacity: 0 }, auto: true },+ ];+ const acorn = addWithKfAcorn(ADD_WITH_KF_BASE, "#hero", 0, 1, kfs).script;+ const recast = addWithKfRecast(ADD_WITH_KF_BASE, "#hero", 0, 1, kfs).script;+ expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));+ });++ it("_auto endpoint: only 0% carries auto marker", () => {+ const kfs = [+ { percentage: 0, properties: { opacity: 1 }, auto: true },+ { percentage: 100, properties: { opacity: 0 } },+ ];+ const acorn = addWithKfAcorn(ADD_WITH_KF_BASE, "#el", 2, 0.5, kfs).script;+ const recast = addWithKfRecast(ADD_WITH_KF_BASE, "#el", 2, 0.5, kfs).script;+ expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));+ });++ it("returns a stable new animation ID that is non-empty", () => {+ const kfs = [+ { percentage: 0, properties: { opacity: 0 } },+ { percentage: 100, properties: { opacity: 1 } },+ ];+ const acornResult = addWithKfAcorn(ADD_WITH_KF_BASE, "#box", 0, 1, kfs);+ const recastResult = addWithKfRecast(ADD_WITH_KF_BASE, "#box", 0, 1, kfs);+ expect(acornResult.id).not.toBe("");+ expect(recastResult.id).not.toBe("");+ // The IDs are position-derived and may differ between writers due to+ // formatting differences, but both must be non-empty valid strings.+ expect(typeof acornResult.id).toBe("string");+ expect(typeof recastResult.id).toBe("string");+ });+});++// ── replaceWithKeyframes parity (remove + addWithKeyframes, recast vs acorn) ──+// WS-3.C replace path: both writers remove the existing tween by animationId,+// then insert the replacement keyframed tween. The animation model of the+// resulting script's last animation must match.++const REPLACE_WITH_KF_BASE = `\+const tl = gsap.timeline({ paused: true });+tl.to("#box", { x: 100, opacity: 1, duration: 0.5 }, 1);+`;++function replaceWithKfRecast(+ script: string,+ animId: string,+ selector: string,+ pos: number,+ dur: number,+ kfs: Array<{+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+ }>,+ ease?: string,+): string {+ const removed = removeAnimRecast(script, animId);+ return addWithKfRecast(removed, selector, pos, dur, kfs, ease).script;+}++function replaceWithKfAcorn(+ script: string,+ animId: string,+ selector: string,+ pos: number,+ dur: number,+ kfs: Array<{+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+ }>,+ ease?: string,+): string {+ const removed = removeAnimAcorn(script, animId);+ return addWithKfAcorn(removed, selector, pos, dur, kfs, ease).script;+}++describe("parity: replaceWithKeyframes (remove + addWithKeyframes, recast vs acorn)", () => {+ it("replaces the only tween: resulting animation model matches", () => {+ const id = acornId(REPLACE_WITH_KF_BASE);+ const kfs = [+ { percentage: 0, properties: { x: 0, opacity: 0 } },+ { percentage: 100, properties: { x: 200, opacity: 1 } },+ ];+ const acorn = replaceWithKfAcorn(REPLACE_WITH_KF_BASE, id, "#box", 0.5, 1.5, kfs);+ const recast = replaceWithKfRecast(REPLACE_WITH_KF_BASE, id, "#box", 0.5, 1.5, kfs);+ expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));+ });++ it("replaces the first tween in a two-tween script, preserving the other", () => {+ const TWO_TWEEN = `\+const tl = gsap.timeline({ paused: true });+tl.to("#box", { x: 100, duration: 0.5 }, 0);+tl.to("#circle", { y: 200, duration: 1 }, 1);+`;+ const id = acornId(TWO_TWEEN);+ const kfs = [+ { percentage: 0, properties: { x: 0 } },+ { percentage: 100, properties: { x: 300 } },+ ];+ const acorn = replaceWithKfAcorn(TWO_TWEEN, id, "#box", 0, 0.75, kfs);+ const recast = replaceWithKfRecast(TWO_TWEEN, id, "#box", 0, 0.75, kfs);+ // The second tween (#circle) must survive unchanged.+ expect(modelOf(acorn)).toHaveLength(2);+ expect(modelOf(recast)).toHaveLength(2);+ expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));+ });++ it("replaces with _auto endpoint markers", () => {+ const id = acornId(REPLACE_WITH_KF_BASE);+ const kfs = [+ { percentage: 0, properties: { opacity: 1 }, auto: true },+ { percentage: 100, properties: { opacity: 0 }, auto: true },+ ];+ const acorn = replaceWithKfAcorn(REPLACE_WITH_KF_BASE, id, "#box", 1, 2, kfs);+ const recast = replaceWithKfRecast(REPLACE_WITH_KF_BASE, id, "#box", 1, 2, kfs);+ expect(lastModelOf(acorn)).toEqual(lastModelOf(recast));+ });});// ── shiftPositionsInScript / scalePositionsInScript (timeline clip move/resize) ──diff --git a/packages/core/src/parsers/gsapWriterAcorn.ts b/packages/core/src/parsers/gsapWriterAcorn.tsindex cfd459cc77..bf855cae64 100644--- a/packages/core/src/parsers/gsapWriterAcorn.ts+++ b/packages/core/src/parsers/gsapWriterAcorn.ts@@ -1128,12 +1128,14 @@ function buildKeyframeObjectCode(percentage: number;properties: Record<string, number | string>;ease?: string;+ auto?: boolean;}>,easeEach?: string,): string {const entries = keyframes.map((kf) => {const props = Object.entries(kf.properties).map(([k, v]) => `${safeKey(k)}: ${valueToCode(v)}`);if (kf.ease) props.push(`ease: ${JSON.stringify(kf.ease)}`);+ if (kf.auto) props.push(`_auto: 1`);return `${JSON.stringify(`${kf.percentage}%`)}: { ${props.join(", ")} }`;});if (easeEach) entries.push(`easeEach: ${JSON.stringify(easeEach)}`);@@ -1210,6 +1212,7 @@ export function addAnimationWithKeyframesToScript(percentage: number;properties: Record<string, number | string>;ease?: string;+ auto?: boolean;}>,ease?: string,): { script: string; id: string } {diff --git a/packages/sdk/src/engine/mutate.ts b/packages/sdk/src/engine/mutate.tsindex 17f82ee69d..5d9c3be10f 100644--- a/packages/sdk/src/engine/mutate.ts+++ b/packages/sdk/src/engine/mutate.ts@@ -55,6 +55,7 @@ import { parseGsapScriptAcornForWrite } from "@hyperframes/core/gsap-parser-acorimport type { GsapAnimation } from "@hyperframes/core/gsap-parser";import {addAnimationToScript,+ addAnimationWithKeyframesToScript,updateAnimationInScript,removeAnimationFromScript,removePropertyFromAnimation,@@ -228,11 +229,24 @@ function applyArcPathOp(parsed: ParsedDocument, op: EditOp): MutationResult | un}}+function applyGsapWithKeyframesOp(parsed: ParsedDocument, op: EditOp): MutationResult | undefined {+ switch (op.type) {+ case "addWithKeyframes":+ return handleAddWithKeyframes(parsed, op);+ case "replaceWithKeyframes":+ return handleReplaceWithKeyframes(parsed, op);+ default:+ return undefined;+ }+}+function applyGsapOp(parsed: ParsedDocument, op: EditOp): MutationResult | undefined {const kf = applyGsapKeyframeOp(parsed, op);if (kf !== undefined) return kf;const arc = applyArcPathOp(parsed, op);if (arc !== undefined) return arc;+ const wkf = applyGsapWithKeyframesOp(parsed, op);+ if (wkf !== undefined) return wkf;switch (op.type) {case "addGsapTween":return handleAddGsapTween(parsed, op.target, op.tween);@@ -942,6 +956,51 @@ function cascadeRemoveAnimations(script: string, id: HfId): string {}}+// ─── addWithKeyframes / replaceWithKeyframes handlers ────────────────────────++function handleAddWithKeyframes(+ parsed: ParsedDocument,+ op: Extract<EditOp, { type: "addWithKeyframes" }>,+): MutationResult {+ const script = getGsapScript(parsed.document);+ if (!script) throw new Error("No GSAP script block found in the composition.");+ const { script: newScript, id: animationId } = addAnimationWithKeyframesToScript(+ script,+ op.targetSelector,+ op.position,+ op.duration,+ op.keyframes,+ op.ease,+ );+ if (!animationId) return EMPTY;+ setGsapScript(parsed.document, newScript);+ return { ...gsapScriptChange(script, newScript), meta: { animationId } };+}++function handleReplaceWithKeyframes(+ parsed: ParsedDocument,+ op: Extract<EditOp, { type: "replaceWithKeyframes" }>,+): MutationResult {+ const script = getGsapScript(parsed.document);+ if (!script) throw new Error("No GSAP script block found in the composition.");+ // Step 1: remove the existing tween. Position-derived IDs renumber, so the+ // inverse patch restores the full GSAP script rather than trying to re-insert+ // by ID (handled by the coarse gsapScriptChange patch pair).+ const afterRemove = removeAnimationFromScript(script, op.animationId);+ // Step 2: insert the replacement keyframed tween.+ const { script: newScript, id: animationId } = addAnimationWithKeyframesToScript(+ afterRemove,+ op.targetSelector,+ op.position,+ op.duration,+ op.keyframes,+ op.ease,+ );+ if (!animationId) return EMPTY;+ setGsapScript(parsed.document, newScript);+ return { ...gsapScriptChange(script, newScript), meta: { animationId } };+}+// ─── setClassStyle handler ────────────────────────────────────────────────────function handleSetClassStyle(@@ -1496,6 +1555,29 @@ export function validateOp(parsed: ParsedDocument, op: EditOp): CanResult {case "deleteAllForSelector":case "removeLabel":return gsapScriptMissing(parsed) ?? CAN_OK;+ case "addWithKeyframes":+ return (+ gsapScriptMissing(parsed) ??+ (op.keyframes.length === 0+ ? canErr(+ "E_INVALID_ARGS",+ "addWithKeyframes requires at least one keyframe.",+ "An empty keyframe list would create an animation with no keyframes.",+ )+ : CAN_OK)+ );+ case "replaceWithKeyframes":+ return (+ gsapScriptMissing(parsed) ??+ gsapAnimationMissing(parsed, op.animationId) ??+ (op.keyframes.length === 0+ ? canErr(+ "E_INVALID_ARGS",+ "replaceWithKeyframes requires at least one keyframe.",+ "An empty keyframe list would create an animation with no keyframes.",+ )+ : CAN_OK)+ );case "unrollDynamicAnimations":return (gsapScriptMissing(parsed) ??diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.tsindex 7be2adf808..5446b86a8b 100644--- a/packages/sdk/src/types.ts+++ b/packages/sdk/src/types.ts@@ -189,6 +189,40 @@ export type EditOp =keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;easeEach?: string;}>;+ }+ | {+ /** Insert a new keyframed tween for targetSelector at the given position/duration. */+ type: "addWithKeyframes";+ targetSelector: string;+ position: number;+ duration: number;+ keyframes: Array<{+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+ }>;+ ease?: string;+ }+ | {+ /**+ * Replace an existing tween (by animationId) with a new keyframed tween.+ * Equivalent to removeGsapTween + addWithKeyframes in one atomic op.+ * Position-derived tween IDs renumber after the remove; callers must+ * re-parse to discover the new ID.+ */+ type: "replaceWithKeyframes";+ animationId: string;+ targetSelector: string;+ position: number;+ duration: number;+ keyframes: Array<{+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+ }>;+ ease?: string;};export interface ElasticHold {diff --git a/packages/studio/src/hooks/useGsapAnimationOps.ts b/packages/studio/src/hooks/useGsapAnimationOps.tsindex 701576e018..390db74ffc 100644--- a/packages/studio/src/hooks/useGsapAnimationOps.ts+++ b/packages/studio/src/hooks/useGsapAnimationOps.ts@@ -5,6 +5,8 @@ import { roundTo3 } from "../utils/rounding";import {sdkGsapTweenPersist,sdkGsapDeleteAllForSelectorPersist,+ sdkAddWithKeyframesPersist,+ sdkReplaceWithKeyframesPersist,type CutoverDeps,} from "../utils/sdkCutover";import {@@ -181,10 +183,104 @@ export function useGsapAnimationOps({[activeCompPath, commitMutation, projectIdRef, showToast, sdkSession, sdkDeps],);+ type KeyframeEntry = {+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+ };++ const addWithKeyframes = useCallback(+ async (+ selection: DomEditSelection,+ targetSelector: string,+ position: number,+ duration: number,+ keyframes: KeyframeEntry[],+ ease?: string,+ label = "Add animation with keyframes",+ ) => {+ if (sdkSession && sdkDeps) {+ const targetPath = selection.sourceFile || activeCompPath || "index.html";+ const handled = await sdkAddWithKeyframesPersist(+ targetPath,+ targetSelector,+ position,+ duration,+ keyframes,+ ease,+ sdkSession,+ sdkDeps,+ { label },+ );+ if (handled) return;+ }+ void commitMutation(+ selection,+ {+ type: "add-with-keyframes",+ targetSelector,+ position,+ duration,+ keyframes,+ ...(ease ? { ease } : {}),+ },+ { label, softReload: true },+ );+ },+ [commitMutation, activeCompPath, sdkSession, sdkDeps],+ );++ const replaceWithKeyframes = useCallback(+ async (+ selection: DomEditSelection,+ animationId: string,+ targetSelector: string,+ position: number,+ duration: number,+ keyframes: KeyframeEntry[],+ ease?: string,+ label = "Replace animation with keyframes",+ ) => {+ if (sdkSession && sdkDeps) {+ const targetPath = selection.sourceFile || activeCompPath || "index.html";+ const handled = await sdkReplaceWithKeyframesPersist(+ targetPath,+ animationId,+ targetSelector,+ position,+ duration,+ keyframes,+ ease,+ sdkSession,+ sdkDeps,+ { label },+ );+ if (handled) return;+ }+ void commitMutation(+ selection,+ {+ type: "replace-with-keyframes",+ animationId,+ targetSelector,+ position,+ duration,+ keyframes,+ ...(ease ? { ease } : {}),+ },+ { label, softReload: true },+ );+ },+ [commitMutation, activeCompPath, sdkSession, sdkDeps],+ );+return {updateGsapMeta,deleteGsapAnimation,deleteAllForSelector,addGsapAnimation,+ addWithKeyframes,+ replaceWithKeyframes,};}diff --git a/packages/studio/src/utils/sdkCutover.ts b/packages/studio/src/utils/sdkCutover.tsindex b7c1081190..77c48c010e 100644--- a/packages/studio/src/utils/sdkCutover.ts+++ b/packages/studio/src/utils/sdkCutover.ts@@ -435,6 +435,86 @@ export function sdkGsapConvertToKeyframesPersist();}+type KeyframeSpec = {+ percentage: number;+ properties: Record<string, number | string>;+ ease?: string;+ auto?: boolean;+};++type KeyframesPayload = {+ targetSelector: string;+ position: number;+ duration: number;+ keyframes: KeyframeSpec[];+ ease?: string;+};++/** Shared inner dispatch for addWithKeyframes / replaceWithKeyframes ops. */+function dispatchWithKeyframes(+ s: Composition,+ payload: KeyframesPayload,+ animationId?: string,+): void {+ if (animationId !== undefined) {+ s.dispatch({ type: "replaceWithKeyframes", animationId, ...payload });+ } else {+ s.dispatch({ type: "addWithKeyframes", ...payload });+ }+}++export function sdkAddWithKeyframesPersist(+ targetPath: string,+ targetSelector: string,+ position: number,+ duration: number,+ keyframes: KeyframeSpec[],+ ease: string | undefined,+ sdkSession: Composition | null | undefined,+ deps: CutoverDeps,+ options?: CutoverOptions,+): Promise<boolean> {+ const payload: KeyframesPayload = {+ targetSelector,+ position,+ duration,+ keyframes,+ ...(ease ? { ease } : {}),+ };+ return dispatchGsapOpAndPersist(targetPath, sdkSession, deps, options, (s) =>+ dispatchWithKeyframes(s, payload),+ );+}++export function sdkReplaceWithKeyframesPersist(+ targetPath: string,+ animationId: string,+ targetSelector: string,+ position: number,+ duration: number,+ keyframes: KeyframeSpec[],+ ease: string | undefined,+ sdkSession: Composition | null | undefined,+ deps: CutoverDeps,+ options?: CutoverOptions,+): Promise<boolean> {+ const payload: KeyframesPayload = {+ targetSelector,+ position,+ duration,+ keyframes,+ ...(ease ? { ease } : {}),+ };+ return dispatchGsapOpAndPersist(+ targetPath,+ sdkSession,+ deps,+ options,+ (s) => dispatchWithKeyframes(s, payload, animationId),+ { animationId, opLabel: "replaceWithKeyframes" },+ );+}+export async function sdkDeletePersist(hfId: string,originalContent: string,