🎥 Make videos programmatically with React
`@remotion/browser-studio`: Support keyframe operations (#10623)
Jonny Burgera1ef7f0b6b72
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 9ba810a043..fa25f42d14 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -21,14 +21,20 @@ import {splitJsxSequence as splitJsxSequenceCodemod,splitVideoFromAudio as splitVideoFromAudioCodemod,updateDefaultProps as updateDefaultPropsCodemod,+ updateEffectKeyframes,+ updateSequenceKeyframes,+ type EffectKeyframeUpdate,type FormatInline,+ type SequenceKeyframeUpdate,} from '@remotion/studio-codemods';import {StudioProtocolInternals,type StudioElementPayload,} from '@remotion/studio-protocol';import {+ getAllSchemaKeys,getRequiredPackageForInsertableElement,+ type BrowserStudioKeyframeOperations,type BrowserStudioOperations,type ElementInstallExpectedFileState,type EventSourceEvent,@@ -42,6 +48,11 @@ import {import * as prettierPluginEstree from 'prettier/plugins/estree';import * as prettierPluginTypescript from 'prettier/plugins/typescript';import {format} from 'prettier/standalone';+import type {+ InteractivitySchema,+ SequenceNodePath,+ SequencePropsSubscriptionKey,+} from 'remotion';import {createBrowserStudioProjectController} from './browser-studio-project-controller';import {makeBrowserStudioProjectArchive} from './download-project';import {saveSequencePropsInProject} from './save-sequence-props';@@ -112,6 +123,31 @@ type ResolveElementDependencies = (dependencies: readonly {name: string; version: string | null}[],) => Promise<Record<string, string>>;+type SequenceKeyframeMutation = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ schema: InteractivitySchema;+ updates: SequenceKeyframeUpdate[];+};++type EffectKeyframeMutation = {+ fileName: string;+ sequenceNodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ schema: InteractivitySchema;+ updates: EffectKeyframeUpdate[];+};++type AppliedSequenceKeyframeMutation = SequenceKeyframeMutation & {+ absolutePath: string;+ updatedNodePath: SequenceNodePath;+};++type AppliedEffectKeyframeMutation = EffectKeyframeMutation & {+ absolutePath: string;+ updatedSequenceNodePath: SequenceNodePath;+};+const getEffectChain = (result: SuccessfulSequencePropsSubscription) =>result.status.effects.map((effect) => (effect.canUpdate ? effect.callee : false))@@ -388,6 +424,211 @@ export const createBrowserStudioOperations = ({},});+ const mutateKeyframesInProject = async ({+ project,+ sequenceMutations,+ effectMutations,+ }: {+ project: VirtualProject;+ sequenceMutations: SequenceKeyframeMutation[];+ effectMutations: EffectKeyframeMutation[];+ }) => {+ if (sequenceMutations.length === 0 && effectMutations.length === 0) {+ throw new Error('No keyframe changes were specified');+ }++ const mergeUpdates = <T extends SequenceKeyframeUpdate>(updates: T[]) => {+ const merged: T[] = [];+ for (const update of updates) {+ const existingMove = merged.find(+ (candidate) =>+ candidate.key === update.key &&+ candidate.operation.type === 'move' &&+ update.operation.type === 'move',+ );+ if (+ existingMove?.operation.type === 'move' &&+ update.operation.type === 'move'+ ) {+ existingMove.operation.moves.push(...update.operation.moves);+ } else {+ merged.push(update);+ }+ }++ return merged;+ };++ const mergedSequenceMutations = [+ ...sequenceMutations+ .reduce((groups, mutation) => {+ const key = `${mutation.fileName}:${JSON.stringify(mutation.nodePath.nodePath)}`;+ const existing = groups.get(key);+ if (existing) {+ existing.updates.push(...mutation.updates);+ } else {+ groups.set(key, {...mutation, updates: [...mutation.updates]});+ }++ return groups;+ }, new Map<string, SequenceKeyframeMutation>())+ .values(),+ ].map((mutation) => ({+ ...mutation,+ updates: mergeUpdates(mutation.updates),+ }));+ const mergedEffectMutations = [+ ...effectMutations+ .reduce((groups, mutation) => {+ const key = `${mutation.fileName}:${JSON.stringify(mutation.sequenceNodePath.nodePath)}:${mutation.effectIndex}`;+ const existing = groups.get(key);+ if (existing) {+ existing.updates.push(...mutation.updates);+ } else {+ groups.set(key, {...mutation, updates: [...mutation.updates]});+ }++ return groups;+ }, new Map<string, EffectKeyframeMutation>())+ .values(),+ ].map((mutation) => ({+ ...mutation,+ updates: mergeUpdates(mutation.updates),+ }));++ const files = {...project.files};+ const appliedSequenceMutations: AppliedSequenceKeyframeMutation[] = [];+ const appliedEffectMutations: AppliedEffectKeyframeMutation[] = [];++ for (const mutation of mergedSequenceMutations) {+ const absolutePath = findProjectFile({+ filePath: mutation.fileName,+ project,+ });+ const result = await updateSequenceKeyframes({+ input: files[absolutePath],+ nodePath: mutation.nodePath.nodePath,+ updates: mutation.updates,+ schema: mutation.schema,+ videoConfigValues: mutation.nodePath.videoConfigValues,+ formatFile: formatCodemodFile,+ });+ files[absolutePath] = result.output;+ appliedSequenceMutations.push({+ ...mutation,+ absolutePath,+ updatedNodePath: result.updatedNodePath,+ });+ }++ for (const mutation of mergedEffectMutations) {+ const absolutePath = findProjectFile({+ filePath: mutation.fileName,+ project,+ });+ const result = await updateEffectKeyframes({+ input: files[absolutePath],+ sequenceNodePath: mutation.sequenceNodePath.nodePath,+ effectIndex: mutation.effectIndex,+ updates: mutation.updates,+ schema: mutation.schema,+ videoConfigValues: mutation.sequenceNodePath.videoConfigValues,+ formatFile: formatCodemodFile,+ });+ files[absolutePath] = result.output;+ appliedEffectMutations.push({+ ...mutation,+ absolutePath,+ updatedSequenceNodePath: result.updatedSequenceNodePath,+ });+ }++ return {+ project: {...project, files},+ appliedSequenceMutations,+ appliedEffectMutations,+ };+ };++ const commitKeyframeMutations = async ({+ label,+ sequenceMutations,+ effectMutations,+ }: {+ label: string;+ sequenceMutations: SequenceKeyframeMutation[];+ effectMutations: EffectKeyframeMutation[];+ }) => {+ const project = getProject();+ const result = await mutateKeyframesInProject({+ project,+ sequenceMutations,+ effectMutations,+ });+ controller.applyMutation({+ fileName: label,+ mutate: () => result.project,+ nodePathMutationFiles: null,+ });+ return result;+ };++ const getSequenceKeyframeResponse = ({+ mutation,+ project,+ }: {+ mutation: AppliedSequenceKeyframeMutation;+ project: VirtualProject;+ }) => {+ const status = computeSequencePropsStatusFromContent({+ fileContents: project.files[mutation.absolutePath],+ nodePath: mutation.updatedNodePath,+ componentIdentity: null,+ keys: getAllSchemaKeys(mutation.schema),+ effects: [],+ videoConfigValues: mutation.nodePath.videoConfigValues,+ });+ const nodePath = {+ ...mutation.nodePath,+ absolutePath: mutation.absolutePath,+ nodePath: mutation.updatedNodePath,+ };++ return {+ canUpdate: true as const,+ props: status.props,+ results: [{fileName: mutation.fileName, nodePath, props: status.props}],+ };+ };++ const getEffectKeyframeResponse = ({+ mutation,+ project,+ }: {+ mutation: AppliedEffectKeyframeMutation;+ project: VirtualProject;+ }) => {+ const effects = Array.from({length: mutation.effectIndex + 1}, (_, index) =>+ index === mutation.effectIndex ? getAllSchemaKeys(mutation.schema) : [],+ );+ const status = computeSequencePropsStatusFromContent({+ fileContents: project.files[mutation.absolutePath],+ nodePath: mutation.updatedSequenceNodePath,+ componentIdentity: null,+ keys: [],+ effects,+ videoConfigValues: mutation.sequenceNodePath.videoConfigValues,+ });++ return (+ status.effects[mutation.effectIndex] ?? {+ canUpdate: false as const,+ effectIndex: mutation.effectIndex,+ reason: 'not-found' as const,+ }+ );+ };+const getDefaultPropsStatus = (compositionId: string) =>getCanUpdateDefaultPropsForProject({compositionId,@@ -747,6 +988,252 @@ export const createBrowserStudioOperations = ({}};+ const keyframes: BrowserStudioKeyframeOperations = {+ addSequenceKeyframe: async (request) => {+ const result = await commitKeyframeMutations({+ label: `${request.key} keyframe`,+ sequenceMutations: [+ {+ fileName: request.fileName,+ nodePath: request.nodePath,+ schema: request.schema,+ updates: [+ {+ key: request.key,+ operation: {+ type: 'add',+ frame: request.frame,+ value: JSON.parse(request.value),+ },+ },+ ],+ },+ ],+ effectMutations: [],+ });+ const mutation = result.appliedSequenceMutations[0];+ if (!mutation) {+ throw new Error('Could not add sequence keyframe');+ }++ return getSequenceKeyframeResponse({mutation, project: result.project});+ },+ addEffectKeyframe: async (request) => {+ const result = await commitKeyframeMutations({+ label: `${request.key} effect keyframe`,+ sequenceMutations: [],+ effectMutations: [+ {+ fileName: request.fileName,+ sequenceNodePath: request.sequenceNodePath,+ effectIndex: request.effectIndex,+ schema: request.schema,+ updates: [+ {+ key: request.key,+ operation: {+ type: 'add',+ frame: request.frame,+ value: JSON.parse(request.value),+ },+ },+ ],+ },+ ],+ });+ const mutation = result.appliedEffectMutations[0];+ if (!mutation) {+ throw new Error('Could not add effect keyframe');+ }++ return getEffectKeyframeResponse({mutation, project: result.project});+ },+ addKeyframes: async ({sequenceKeyframes, effectKeyframes}) => {+ await commitKeyframeMutations({+ label: `${sequenceKeyframes.length + effectKeyframes.length} keyframes`,+ sequenceMutations: sequenceKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'add',+ frame: keyframe.frame,+ value: JSON.parse(keyframe.value),+ },+ },+ ],+ })),+ effectMutations: effectKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.sequenceNodePath,+ effectIndex: keyframe.effectIndex,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'add',+ frame: keyframe.frame,+ value: JSON.parse(keyframe.value),+ },+ },+ ],+ })),+ });+ return {success: true};+ },+ deleteKeyframes: async ({sequenceKeyframes, effectKeyframes}) => {+ await commitKeyframeMutations({+ label: `${sequenceKeyframes.length + effectKeyframes.length} keyframes`,+ sequenceMutations: sequenceKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'remove',+ frame: keyframe.frame,+ valueWhenLastKeyframeDeleted:+ keyframe.valueWhenLastKeyframeDeleted ?? null,+ },+ },+ ],+ })),+ effectMutations: effectKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.sequenceNodePath,+ effectIndex: keyframe.effectIndex,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'remove',+ frame: keyframe.frame,+ valueWhenLastKeyframeDeleted:+ keyframe.valueWhenLastKeyframeDeleted ?? null,+ },+ },+ ],+ })),+ });+ return {success: true};+ },+ moveKeyframes: async ({sequenceKeyframes, effectKeyframes}) => {+ await commitKeyframeMutations({+ label: `${sequenceKeyframes.length + effectKeyframes.length} keyframes`,+ sequenceMutations: sequenceKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'move',+ moves: [+ {+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ },+ ],+ },+ },+ ],+ })),+ effectMutations: effectKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.sequenceNodePath,+ effectIndex: keyframe.effectIndex,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'move',+ moves: [+ {+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ },+ ],+ },+ },+ ],+ })),+ });+ return {success: true};+ },+ updateSequenceKeyframeSettings: async (request) => {+ const result = await commitKeyframeMutations({+ label: `${request.key} keyframe settings`,+ sequenceMutations: [+ {+ fileName: request.fileName,+ nodePath: request.nodePath,+ schema: request.schema,+ updates: [{key: request.key, operation: request.settings}],+ },+ ],+ effectMutations: [],+ });+ const mutation = result.appliedSequenceMutations[0];+ if (!mutation) {+ throw new Error('Could not update sequence keyframe settings');+ }++ return getSequenceKeyframeResponse({mutation, project: result.project});+ },+ updateEffectKeyframeSettings: async (request) => {+ const result = await commitKeyframeMutations({+ label: `${request.key} effect keyframe settings`,+ sequenceMutations: [],+ effectMutations: [+ {+ fileName: request.fileName,+ sequenceNodePath: request.sequenceNodePath,+ effectIndex: request.effectIndex,+ schema: request.schema,+ updates: [{key: request.key, operation: request.settings}],+ },+ ],+ });+ const mutation = result.appliedEffectMutations[0];+ if (!mutation) {+ throw new Error('Could not update effect keyframe settings');+ }++ return getEffectKeyframeResponse({mutation, project: result.project});+ },+ batchUpdateKeyframeSettings: async ({+ sequenceKeyframes,+ effectKeyframes,+ }) => {+ await commitKeyframeMutations({+ label: `${sequenceKeyframes.length + effectKeyframes.length} keyframe settings`,+ sequenceMutations: sequenceKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [{key: keyframe.key, operation: keyframe.settings}],+ })),+ effectMutations: effectKeyframes.map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.sequenceNodePath,+ effectIndex: keyframe.effectIndex,+ schema: keyframe.schema,+ updates: [{key: keyframe.key, operation: keyframe.settings}],+ })),+ });+ return {success: true};+ },+ };+const duplicateComposition: BrowserStudioOperations['duplicateComposition'] =async ({codemod, dryRun}) => {try {@@ -1100,6 +1587,7 @@ export const createBrowserStudioOperations = ({},insertJsxElement,insertSolid: insertJsxElement,+ keyframes,prepareElementInstall: async (request) => {try {const plan = await getElementInstallPlanForProject({@@ -1124,29 +1612,105 @@ export const createBrowserStudioOperations = ({redo: controller.redo,renameStaticFile: controller.renameStaticFile,reorderSequence,- saveSequenceProps: (request) => {- try {- let response: Awaited<- ReturnType<BrowserStudioOperations['saveSequenceProps']>- > | null = null;- const firstTarget = request.edits[0] ?? request.captionPatches?.[0];- controller.applyMutation({- fileName: firstTarget?.fileName ?? 'Sequence props',- nodePathMutationFiles: null,- mutate: (project) => {- const result = saveSequencePropsInProject({project, request});- response = result.response;- return result.project;+ saveSequenceProps: async (request) => {+ const project = getProject();+ const hasPropChanges =+ request.edits.length > 0 || (request.captionPatches?.length ?? 0) > 0;+ const propResult = hasPropChanges+ ? saveSequencePropsInProject({project, request})+ : null;+ const sequenceMutations: SequenceKeyframeMutation[] = [+ ...(request.addedKeyframes ?? []).map((keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'add' as const,+ frame: keyframe.frame,+ value: JSON.parse(keyframe.value),+ },+ },+ ],+ })),+ ...(request.movedKeyframes?.sequenceKeyframes ?? []).map(+ (keyframe) => ({+ fileName: keyframe.fileName,+ nodePath: keyframe.nodePath,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'move' as const,+ moves: [+ {+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ },+ ],+ },+ },+ ],+ }),+ ),+ ];+ const effectMutations: EffectKeyframeMutation[] = (+ request.movedKeyframes?.effectKeyframes ?? []+ ).map((keyframe) => ({+ fileName: keyframe.fileName,+ sequenceNodePath: keyframe.sequenceNodePath,+ effectIndex: keyframe.effectIndex,+ schema: keyframe.schema,+ updates: [+ {+ key: keyframe.key,+ operation: {+ type: 'move',+ moves: [+ {+ fromFrame: keyframe.fromFrame,+ toFrame: keyframe.toFrame,+ },+ ],+ },},- });- if (response === null) {- throw new Error('Could not save sequence props');- }+ ],+ }));+ const keyframeResult =+ sequenceMutations.length > 0 || effectMutations.length > 0+ ? await mutateKeyframesInProject({+ project: propResult?.project ?? project,+ sequenceMutations,+ effectMutations,+ })+ : null;+ if (propResult === null && keyframeResult === null) {+ throw new Error('No sequence prop edits to save');+ }- return Promise.resolve(response);- } catch (error) {- return Promise.reject(error);+ const firstTarget = request.edits[0] ?? request.captionPatches?.[0];+ controller.applyMutation({+ fileName:+ firstTarget?.fileName ??+ sequenceMutations[0]?.fileName ??+ 'Keyframes',+ nodePathMutationFiles: null,+ mutate: () => keyframeResult?.project ?? propResult!.project,+ });+ if (propResult) {+ return propResult.response;}++ const firstSequenceMutation = keyframeResult?.appliedSequenceMutations[0];+ return firstSequenceMutation && keyframeResult+ ? getSequenceKeyframeResponse({+ mutation: firstSequenceMutation,+ project: keyframeResult.project,+ })+ : {canUpdate: true, props: {}, results: []};},resetHistory: () => {controller.resetHistory();diff --git a/packages/browser-studio/src/save-sequence-props.ts b/packages/browser-studio/src/save-sequence-props.tsindex 18cd138b66..dd849cc082 100644--- a/packages/browser-studio/src/save-sequence-props.ts+++ b/packages/browser-studio/src/save-sequence-props.ts@@ -25,14 +25,6 @@ const parseSequencePropEditValue = (return JSON.parse(value.serialized);};-const hasKeyframeChanges = (request: SaveSequencePropsRequest) => {- return (- (request.addedKeyframes?.length ?? 0) > 0 ||- (request.movedKeyframes?.sequenceKeyframes.length ?? 0) > 0 ||- (request.movedKeyframes?.effectKeyframes.length ?? 0) > 0- );-};-type FileMutation = {edits: SaveSequencePropEdit[];captionPatches: NonNullable<SaveSequencePropsRequest['captionPatches']>;@@ -73,12 +65,6 @@ export const saveSequencePropsInProject = ({project: VirtualProject;response: SaveSequencePropsResponse;} => {- if (hasKeyframeChanges(request)) {- throw new Error(- 'Browser Studio does not support saving sequence keyframes yet',- );- }-if (request.edits.length === 0 &&(request.captionPatches?.length ?? 0) === 0diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 9b9d8d5b43..a0616ff5d6 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1,6 +1,8 @@import {expect, test} from 'bun:test';import {createElementPayload} from '@remotion/studio-protocol';import type {EventSourceEvent} from '@remotion/studio-shared';+import type {InteractivitySchema} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';import {createBrowserStudioOperations,insertSolidIntoProject,@@ -823,6 +825,217 @@ const makeOperationsForProject = (project: VirtualProject) => {return {operations, getProject: () => currentProject};};+test('edits sequence and effect keyframes in the virtual project', async () => {+ const fileName = '/project/src/Comp.tsx';+ const initialContents = `import {tint} from '@remotion/effects/tint';+import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';++export const Comp = () => {+ const frame = useCurrentFrame();+ return (+ <AbsoluteFill+ style={{opacity: interpolate(frame, [0, 20], [0, 1])}}+ effects={[tint({amount: interpolate(frame, [0, 20], [0.2, 0.8])})]}+ />+ );+};+`;+ const effectSchema = {+ amount: {type: 'number', default: 0, hiddenFromList: false},+ } satisfies InteractivitySchema;+ const {operations, getProject} = makeOperationsForProject({+ rootDir: '/project',+ entryPoint: fileName,+ files: {[fileName]: initialContents},+ });+ const subscription = await operations.subscribeToSequenceProps({+ fileName: 'src/Comp.tsx',+ line: 7,+ column: 2,+ nodePath: null,+ componentIdentity: null,+ keys: ['style.opacity'],+ assetKeys: [],+ effects: [['amount']],+ clientId: 'browser-studio',+ videoConfigValues: {+ durationInFrames: 60,+ fps: 30,+ height: 720,+ width: 1280,+ },+ });+ if (!subscription.success || !operations.keyframes) {+ throw new Error('Expected Browser Studio keyframe capability');+ }++ const failedContents = getProject().files[fileName];+ await expect(+ operations.keyframes.moveKeyframes({+ sequenceKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ fromFrame: 99,+ toFrame: 10,+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [],+ clientId: 'browser-studio',+ }),+ ).rejects.toThrow('Cannot move keyframe at frame 99: not found');+ expect(getProject().files[fileName]).toBe(failedContents);++ const sequenceResult = await operations.keyframes.addSequenceKeyframe({+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ frame: 5,+ value: '0.25',+ schema: NoReactInternals.sequenceSchema,+ clientId: 'browser-studio',+ });+ expect(sequenceResult.canUpdate).toBe(true);+ expect(getProject().files[fileName]).toContain(+ 'opacity: interpolate(frame, [0, 5, 20], [0, 0.25, 1])',+ );+ const beforeQueuedSave = getProject().files[fileName];+ await operations.saveSequenceProps({+ edits: [],+ captionPatches: [],+ addedKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ frame: 8,+ value: '0.4',+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ movedKeyframes: null,+ clientId: 'browser-studio',+ undoLabel: 'Remove opacity keyframe',+ redoLabel: 'Add opacity keyframe',+ });+ expect(getProject().files[fileName]).toContain(+ 'opacity: interpolate(frame, [0, 5, 8, 20], [0, 0.25, 0.4, 1])',+ );+ expect(await operations.undo()).toMatchObject({success: true});+ expect(getProject().files[fileName]).toBe(beforeQueuedSave);++ const effectResult = await operations.keyframes.addEffectKeyframe({+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ key: 'amount',+ frame: 10,+ value: '0.5',+ schema: effectSchema,+ clientId: 'browser-studio',+ });+ expect(effectResult).toMatchObject({canUpdate: true, effectIndex: 0});+ expect(getProject().files[fileName]).toContain(+ 'amount: interpolate(frame, [0, 10, 20], [0.2, 0.5, 0.8])',+ );++ await operations.keyframes.moveKeyframes({+ sequenceKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ fromFrame: 5,+ toFrame: 6,+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ key: 'amount',+ fromFrame: 10,+ toFrame: 12,+ schema: effectSchema,+ },+ ],+ clientId: 'browser-studio',+ });+ expect(getProject().files[fileName]).toContain('[0, 6, 20], [0, 0.25, 1]');+ expect(getProject().files[fileName]).toContain(+ '[0, 12, 20], [0.2, 0.5, 0.8]',+ );++ await operations.keyframes.batchUpdateKeyframeSettings({+ sequenceKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ settings: {+ type: 'easing',+ segmentIndex: 0,+ easing: {type: 'bezier', x1: 0.42, y1: 0, x2: 1, y2: 1},+ },+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ key: 'amount',+ settings: {+ type: 'easing',+ segmentIndex: 0,+ easing: {type: 'bezier', x1: 0, y1: 0, x2: 0.58, y2: 1},+ },+ schema: effectSchema,+ },+ ],+ clientId: 'browser-studio',+ });+ expect(getProject().files[fileName]).toContain(+ 'Easing.bezier(0.42, 0, 1, 1)',+ );+ expect(getProject().files[fileName]).toContain(+ 'Easing.bezier(0, 0, 0.58, 1)',+ );++ const beforeDelete = getProject().files[fileName];+ await operations.keyframes.deleteKeyframes({+ sequenceKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ nodePath: subscription.nodePath,+ key: 'style.opacity',+ frame: 6,+ schema: NoReactInternals.sequenceSchema,+ },+ ],+ effectKeyframes: [+ {+ fileName: 'src/Comp.tsx',+ sequenceNodePath: subscription.nodePath,+ effectIndex: 0,+ key: 'amount',+ frame: 12,+ schema: effectSchema,+ },+ ],+ clientId: 'browser-studio',+ });+ expect(getProject().files[fileName]).not.toContain('[0, 6, 20]');+ expect(getProject().files[fileName]).not.toContain('[0, 12, 20]');+ expect(await operations.undo()).toMatchObject({success: true});+ expect(getProject().files[fileName]).toBe(beforeDelete);+});+test('renames a composition by resolving the file from the composition id', async () => {const {operations, getProject} = makeOperationsForProject(createBlankTemplateProject(),diff --git a/packages/studio-codemods/src/ensure-imports-and-frame-hook.ts b/packages/studio-codemods/src/ensure-imports-and-frame-hook.tsnew file mode 100644index 0000000000..59a1f0d907--- /dev/null+++ b/packages/studio-codemods/src/ensure-imports-and-frame-hook.ts@@ -0,0 +1,116 @@+import type {+ ArrowFunctionExpression,+ File,+ FunctionDeclaration,+ FunctionExpression,+} from '@babel/types';+import * as recast from 'recast';+import {ensureNamedImports} from './sequence-props/imports';++const b = recast.types.builders;+const n = recast.types.namedTypes;++type FunctionNode =+ | FunctionDeclaration+ | FunctionExpression+ | ArrowFunctionExpression;++const isFunctionNode = (value: unknown): value is FunctionNode => {+ return (+ n.FunctionDeclaration.check(value) ||+ n.FunctionExpression.check(value) ||+ n.ArrowFunctionExpression.check(value)+ );+};++export const findEnclosingFunctionPath = (+ path: recast.types.NodePath,+): recast.types.NodePath | null => {+ let current: recast.types.NodePath | null = path.parentPath;+ while (current) {+ if (isFunctionNode(current.value)) {+ return current;+ }++ current = current.parentPath;+ }++ return null;+};++export const ensureRemotionImports = (+ ast: File,+ names: ReadonlySet<string>,+) => {+ ensureNamedImports({ast, importedNames: names, sourcePath: 'remotion'});+};++const componentBodyHasFrameDeclaration = ({+ body,+ hookName,+}: {+ body: FunctionNode['body'];+ hookName: string;+}): boolean => {+ if (!n.BlockStatement.check(body)) {+ return false;+ }++ for (const stmt of body.body) {+ if (stmt.type !== 'VariableDeclaration') {+ continue;+ }++ for (const decl of stmt.declarations) {+ if (decl.type !== 'VariableDeclarator') {+ continue;+ }++ if (+ decl.id.type === 'Identifier' &&+ decl.id.name === 'frame' &&+ decl.init &&+ decl.init.type === 'CallExpression' &&+ decl.init.callee.type === 'Identifier' &&+ decl.init.callee.name === hookName+ ) {+ return true;+ }+ }+ }++ return false;+};++export const ensureUseCurrentFrameHook = (+ functionPath: recast.types.NodePath,+ hookName = 'useCurrentFrame',+): void => {+ const fn = functionPath.value as FunctionNode;++ if (!n.BlockStatement.check(fn.body)) {+ // Arrow function with expression body: wrap the expression in a block so+ // we can prepend the hook call before returning the original expression.+ const expression = fn.body;+ fn.body = b.blockStatement([+ b.returnStatement(expression as Parameters<typeof b.returnStatement>[0]),+ ]) as unknown as FunctionNode['body'];+ }++ if (componentBodyHasFrameDeclaration({body: fn.body, hookName})) {+ return;+ }++ const block = fn.body as Extract<+ FunctionNode['body'],+ {type: 'BlockStatement'}+ >;+ const frameDecl = b.variableDeclaration('const', [+ b.variableDeclarator(+ b.identifier('frame'),+ b.callExpression(b.identifier(hookName), []),+ ),+ ]);++ block.body.unshift(frameDecl as unknown as (typeof block.body)[number]);+};diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex 6a793ea736..5c23c62d69 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -20,6 +20,11 @@ export {getJsxElementTagLabel,} from './delete-jsx-node';export {duplicateCompositionInSource} from './duplicate-composition';+export {+ ensureRemotionImports,+ ensureUseCurrentFrameHook,+ findEnclosingFunctionPath,+} from './ensure-imports-and-frame-hook';export {findSearchPosition} from './find-search-position';export {parseAndApplyCodemod} from './parse-and-apply-codemod';export {@@ -54,6 +59,17 @@ export {type FormatInline,} from './update-default-props';export {updateInlineCaptionPatches} from './update-inline-caption-patches';+export {+ type EffectKeyframeUpdate,+ type FormatKeyframesFile,+ type IntroducedKeyframeIdentifiers,+ type KeyframeOperation,+ type SequenceKeyframeUpdate,+ updateEffectKeyframes,+ updateEffectKeyframesAst,+ updateSequenceKeyframes,+ updateSequenceKeyframesAst,+} from './update-keyframes';export {type RemovedProp,type SequencePropsNodeUpdate,diff --git a/packages/studio-codemods/src/sequence-props/can-update-effect-props.ts b/packages/studio-codemods/src/sequence-props/can-update-effect-props.tsindex 5d8b05a4b4..48065da3bb 100644--- a/packages/studio-codemods/src/sequence-props/can-update-effect-props.ts+++ b/packages/studio-codemods/src/sequence-props/can-update-effect-props.ts@@ -37,8 +37,10 @@ const staticStatus = (codeValue: unknown): CanUpdateSequencePropStatus => ({codeValue,});-const findEffectsAttr = (jsx: JSXOpeningElement): JSXAttribute | null => {- for (const attr of jsx.attributes) {+export const findEffectsAttr = (+ attributes: JSXOpeningElement['attributes'],+): JSXAttribute | null => {+ for (const attr of attributes) {if (attr.type !== 'JSXAttribute') {continue;}@@ -51,6 +53,37 @@ const findEffectsAttr = (jsx: JSXOpeningElement): JSXAttribute | null => {return null;};+export const findEffectCallExpression = ({+ attr,+ effectIndex,+}: {+ attr: JSXAttribute;+ effectIndex: number;+}):+ | {kind: 'ok'; call: CallExpression; callee: string}+ | {kind: 'error'; reason: 'not-found' | 'not-call-expression'} => {+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {+ return {kind: 'error', reason: 'not-call-expression'};+ }++ const expr = attr.value.expression as Expression;+ if (expr.type !== 'ArrayExpression') {+ return {kind: 'error', reason: 'not-call-expression'};+ }++ const elements = enumerateEffectArrayElements(expr);+ if (effectIndex < 0 || effectIndex >= elements.length) {+ return {kind: 'error', reason: 'not-found'};+ }++ const target = elements[effectIndex];+ if (target.kind !== 'call') {+ return {kind: 'error', reason: 'not-call-expression'};+ }++ return {kind: 'ok', call: target.node, callee: target.callee};+};+const getEffectsArrayElements = (attr: JSXAttribute | null,): EffectArrayElement[] | null => {@@ -218,7 +251,7 @@ export const computeEffectPropStatus = ({keys: string[];videoConfigValues: VideoConfigIdentifierValues;}): CanUpdateEffectPropsResponse => {- const attr = findEffectsAttr(jsx);+ const attr = findEffectsAttr(jsx.attributes);const elements = getEffectsArrayElements(attr);if (!elements) {diff --git a/packages/studio-codemods/src/update-keyframes.ts b/packages/studio-codemods/src/update-keyframes.tsnew file mode 100644index 0000000000..58b98a54f7--- /dev/null+++ b/packages/studio-codemods/src/update-keyframes.ts@@ -0,0 +1,2150 @@+/* eslint-disable @typescript-eslint/no-use-before-define */+import type {+ CallExpression,+ Expression,+ JSXAttribute,+ JSXElement,+ JSXExpressionContainer,+ JSXFragment,+ JSXSpreadAttribute,+ ObjectExpression,+ ObjectProperty,+ StringLiteral,+} from '@babel/types';+import {+ getKeyframeInterpolationFunction,+ getKeyframeInterpolationFunctionForSchemaField,+ HOLD_KEYFRAME_EASING,+ isKeyframeInterpolationFunction,+ isSchemaFieldHoldOnly,+ isSchemaFieldKeyframable,+ LINEAR_KEYFRAME_EASING,+ type KeyframeInterpolationFunction,+} from '@remotion/studio-shared';+import type {ExpressionKind, SpreadElementKind} from 'ast-types/lib/gen/kinds';+import * as recast from 'recast';+import type {+ CanUpdateSequencePropStatus,+ ExtrapolateType,+ InteractivitySchema,+ InteractivitySchemaField,+ InterpolateOutputOption,+ SequenceNodePath,+ VideoConfigNumericExpression,+ VideoConfigValues,+} from 'remotion';+import {+ ensureRemotionImports,+ ensureUseCurrentFrameHook,+ findEnclosingFunctionPath,+} from './ensure-imports-and-frame-hook';+import {+ extractStaticValue,+ findJsxElementAtNodePath,+ findNodePathForJsxElement,+ isStaticValue,+} from './sequence-props';+import {+ findEffectCallExpression,+ findEffectsAttr,+} from './sequence-props/can-update-effect-props';+import {getAstNodePath} from './sequence-props/get-ast-node-path';+import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseKeyframeEasingExpression} from './sequence-props/parse-keyframe-easing-expression';+import {+ parseVideoConfigNumericExpression,+ updateVideoConfigNumericExpression,+} from './sequence-props/video-config-numeric-expression';+import {+ getVideoConfigIdentifierValues,+ type VideoConfigIdentifierValues,+} from './sequence-props/video-config-values';+import {parseValueExpression} from './update-nested-prop';++const b = recast.types.builders;++const getObjectPropertyNameFromUpdateKey = (key: string): string => {+ const dotIndex = key.indexOf('.');+ return dotIndex === -1 ? key : key.slice(dotIndex + 1);+};++const lineStartsWithPropertyName = ({+ line,+ propertyName,+}: {+ line: string;+ propertyName: string;+}) => {+ const trimmed = line.trimStart();+ return (+ trimmed.startsWith(`${propertyName}:`) ||+ trimmed.startsWith(`'${propertyName}':`) ||+ trimmed.startsWith(`"${propertyName}":`)+ );+};++const getIndent = (line: string) => line.match(/^[ \t]*/)?.[0] ?? '';++const removeBlankLinesFromObjectsWithProperties = ({+ input,+ propertyNames,+}: {+ input: string;+ propertyNames: string[];+}) => {+ if (propertyNames.length === 0) {+ return input;+ }++ const lines = input.split('\n');+ const linesToRemove = new Set<number>();++ for (let i = 0; i < lines.length; i++) {+ const propertyName = propertyNames.find((name) =>+ lineStartsWithPropertyName({line: lines[i], propertyName: name}),+ );+ if (!propertyName) {+ continue;+ }++ const propertyIndentLength = getIndent(lines[i]).length;+ let objectStart = i;+ for (let j = i - 1; j >= 0; j--) {+ const trimmed = lines[j].trim();+ if (+ trimmed.endsWith('{') &&+ getIndent(lines[j]).length < propertyIndentLength+ ) {+ objectStart = j;+ break;+ }+ }++ let objectEnd = i;+ for (let j = i + 1; j < lines.length; j++) {+ const trimmed = lines[j].trim();+ if (+ trimmed.startsWith('}') &&+ getIndent(lines[j]).length < propertyIndentLength+ ) {+ objectEnd = j;+ break;+ }+ }++ for (let j = objectStart + 1; j < objectEnd; j++) {+ if (lines[j].trim() === '') {+ linesToRemove.add(j);+ }+ }+ }++ if (linesToRemove.size === 0) {+ return input;+ }++ return lines.filter((_, index) => !linesToRemove.has(index)).join('\n');+};++type KeyframeEasing = Extract<+ CanUpdateSequencePropStatus,+ {status: 'keyframed'}+>['easing'][number];++export type KeyframeOperation =+ | {+ type: 'add';+ frame: number;+ value: unknown;+ }+ | {+ type: 'remove';+ frame: number;+ valueWhenLastKeyframeDeleted: unknown | null;+ }+ | {+ type: 'settings';+ clamping:+ | {+ left: ExtrapolateType;+ right: ExtrapolateType;+ }+ | undefined;+ posterize: number | undefined;+ output: InterpolateOutputOption | undefined;+ }+ | {+ type: 'easing';+ segmentIndex: number;+ easing: KeyframeEasing;+ }+ | {+ type: 'move';+ moves: {+ fromFrame: number;+ toFrame: number;+ }[];+ };++export type SequenceKeyframeUpdate = {+ key: string;+ operation: KeyframeOperation;+};++export type EffectKeyframeUpdate = {+ key: string;+ operation: KeyframeOperation;+};++export type FormatKeyframesFile = (input: {+ contents: string;+ prettierConfigOverride: Record<string, unknown> | null;+}) => Promise<{output: string; formatted: boolean}>;++type WritableProp = {+ expression: Expression;+ setExpression: (expression: ExpressionKind) => void;+ remove: () => void;+};++type MissingPropInitialValue = {+ value: unknown;+};++type InterpolateKeyframe = {+ frame: number;+ frameExpression: ExpressionKind;+ frameNumericExpression: VideoConfigNumericExpression;+ originalFrame: number;+ output: ExpressionKind;+ value: unknown;+};++type InterpolateExpression = {+ callee: ExpressionKind;+ input: ExpressionKind | SpreadElementKind;+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ keyframes: InterpolateKeyframe[];+};++const getSupportedCallArgument = (+ arg: CallExpression['arguments'][number] | undefined,+): ExpressionKind | SpreadElementKind | null => {+ if (+ arg === undefined ||+ arg.type === 'ArgumentPlaceholder' ||+ arg.type === 'JSXNamespacedName'+ ) {+ return null;+ }++ return arg as unknown as ExpressionKind | SpreadElementKind;+};++const getInterpolationExpression = (+ node: Expression,+ videoConfigValues: VideoConfigIdentifierValues,+): InterpolateExpression | null => {+ if (node.type === 'TSAsExpression') {+ return getInterpolationExpression(+ node.expression as Expression,+ videoConfigValues,+ );+ }++ if (+ node.type !== 'CallExpression' ||+ node.callee.type !== 'Identifier' ||+ !isKeyframeInterpolationFunction(node.callee.name)+ ) {+ return null;+ }++ const frameArg = getSupportedCallArgument(node.arguments[0]);+ const inputArg = node.arguments[1];+ const outputArg = node.arguments[2];+ if (+ !frameArg ||+ !inputArg ||+ !outputArg ||+ inputArg.type !== 'ArrayExpression' ||+ outputArg.type !== 'ArrayExpression' ||+ inputArg.elements.length !== outputArg.elements.length+ ) {+ return null;+ }++ const keyframes: InterpolateKeyframe[] = [];+ for (let i = 0; i < inputArg.elements.length; i++) {+ const inputElement = inputArg.elements[i];+ const outputElement = outputArg.elements[i];+ if (+ !inputElement ||+ !outputElement ||+ inputElement.type === 'SpreadElement' ||+ outputElement.type === 'SpreadElement'+ ) {+ return null;+ }++ const frameExpression = parseVideoConfigNumericExpression({+ node: inputElement,+ videoConfigValues,+ });+ if (frameExpression === null || !isStaticValue(outputElement)) {+ return null;+ }++ keyframes.push({+ frame: frameExpression.value,+ frameExpression: inputElement as ExpressionKind,+ frameNumericExpression: frameExpression,+ originalFrame: frameExpression.value,+ output: outputElement as ExpressionKind,+ value: extractStaticValue(outputElement),+ });+ }++ if (keyframes.length === 0) {+ return null;+ }++ const extraArgs: (ExpressionKind | SpreadElementKind)[] = [];+ for (const arg of node.arguments.slice(3)) {+ const supportedArg = getSupportedCallArgument(arg);+ if (!supportedArg) {+ return null;+ }++ extraArgs.push(supportedArg);+ }++ return {+ callee: node.callee as unknown as ExpressionKind,+ input: frameArg,+ extraArgs,+ keyframes,+ };+};++const getInterpolationCalleeForValues = ({+ schema,+ key,+ staticValue,+ newValue,+}: {+ schema: InteractivitySchema | null;+ key: string;+ staticValue: unknown;+ newValue: unknown;+}): ExpressionKind => {+ return b.identifier(+ getKeyframeInterpolationFunction({+ schema,+ key,+ staticValue,+ newValue,+ }),+ );+};++const createFrameExpression = (frame: number): ExpressionKind => {+ return parseValueExpression(frame);+};++const createClampOptionsExpression = ({+ defaultOutput,+}: {+ defaultOutput: InterpolateOutputOption | null;+}): ExpressionKind => {+ const properties = [+ b.objectProperty(b.identifier('extrapolateLeft'), b.stringLiteral('clamp')),+ b.objectProperty(+ b.identifier('extrapolateRight'),+ b.stringLiteral('clamp'),+ ),+ ];++ if (defaultOutput !== null && defaultOutput !== 'linear') {+ properties.push(+ b.objectProperty(b.identifier('output'), b.stringLiteral(defaultOutput)),+ );+ }++ return b.objectExpression(properties) as ExpressionKind;+};++const createEmptyOptionsExpression = (): ObjectExpression =>+ b.objectExpression([]) as ObjectExpression;++const findObjectOptionProperty = (+ options: ObjectExpression,+ propertyName: string,+): {propIndex: number; prop: ObjectProperty | undefined} => {+ const propIndex = options.properties.findIndex(+ (prop) =>+ prop.type === 'ObjectProperty' &&+ !prop.computed &&+ ((prop.key.type === 'Identifier' && prop.key.name === propertyName) ||+ (prop.key.type === 'StringLiteral' && prop.key.value === propertyName)),+ );++ return {+ propIndex,+ prop:+ propIndex === -1+ ? undefined+ : (options.properties[propIndex] as ObjectProperty),+ };+};++const setOptionsProperty = ({+ options,+ propertyName,+ value,+}: {+ options: ObjectExpression;+ propertyName: string;+ value: ExpressionKind | null;+}) => {+ const {propIndex, prop} = findObjectOptionProperty(options, propertyName);+ if (value === null) {+ if (propIndex !== -1) {+ options.properties.splice(propIndex, 1);+ }++ return;+ }++ if (prop) {+ prop.value = value as ObjectProperty['value'];+ return;+ }++ options.properties.push(+ b.objectProperty(b.identifier(propertyName), value) as ObjectProperty,+ );+};++const isLinearEasing = (easing: KeyframeEasing) => easing.type === 'linear';++const getKeyframeEasing = (node: Expression): KeyframeEasing | null =>+ parseKeyframeEasingExpression(node);++const getKeyframeEasingArray = ({+ easingNode,+ segmentCount,+}: {+ easingNode: Expression;+ segmentCount: number;+}): KeyframeEasing[] | null => {+ if (segmentCount === 0) {+ return [];+ }++ if (easingNode.type === 'TSAsExpression') {+ return getKeyframeEasingArray({+ easingNode: easingNode.expression as Expression,+ segmentCount,+ });+ }++ if (easingNode.type === 'ArrayExpression') {+ if (easingNode.elements.length > segmentCount) {+ return null;+ }++ const parsed = easingNode.elements.map((element) => {+ if (!element || element.type === 'SpreadElement') {+ return null;+ }++ return getKeyframeEasing(element as Expression);+ });++ if (parsed.some((value) => value === null)) {+ return null;+ }++ const easingArray = parsed as KeyframeEasing[];+ while (easingArray.length < segmentCount) {+ easingArray.push(LINEAR_KEYFRAME_EASING);+ }++ return easingArray;+ }++ const easing = getKeyframeEasing(easingNode);+ if (!easing) {+ return null;+ }++ return new Array(segmentCount).fill(easing);+};++const getExistingEasingArray = ({+ options,+ segmentCount,+}: {+ options: ObjectExpression;+ segmentCount: number;+}): KeyframeEasing[] => {+ const {prop} = findObjectOptionProperty(options, 'easing');+ if (!prop) {+ return Array.from({length: segmentCount}, () => ({type: 'linear'}));+ }++ const easing = getKeyframeEasingArray({+ easingNode: prop.value as Expression,+ segmentCount,+ });+ if (!easing) {+ throw new Error('Cannot update easing: easing must be inline');+ }++ return easing;+};++const getExistingEasingArrayOrNull = ({+ options,+ segmentCount,+}: {+ options: ObjectExpression;+ segmentCount: number;+}): KeyframeEasing[] | null => {+ const {prop} = findObjectOptionProperty(options, 'easing');+ if (!prop) {+ return null;+ }++ return getExistingEasingArray({options, segmentCount});+};++const createEasingExpression = (easing: KeyframeEasing): ExpressionKind => {+ switch (easing.type) {+ case 'linear':+ return b.memberExpression(+ b.identifier('Easing'),+ b.identifier('linear'),+ ) as ExpressionKind;+ case 'step1':+ return b.memberExpression(+ b.identifier('Easing'),+ b.identifier('step1'),+ ) as ExpressionKind;+ case 'spring':+ return b.callExpression(+ b.memberExpression(b.identifier('Easing'), b.identifier('spring')),+ [+ b.objectExpression([+ b.objectProperty(+ b.identifier('damping'),+ parseValueExpression(easing.damping),+ ),+ b.objectProperty(+ b.identifier('mass'),+ parseValueExpression(easing.mass),+ ),+ b.objectProperty(+ b.identifier('stiffness'),+ parseValueExpression(easing.stiffness),+ ),+ ...(easing.allowTail === null+ ? []+ : [+ b.objectProperty(+ b.identifier('allowTail'),+ b.booleanLiteral(easing.allowTail),+ ),+ ]),+ ...(easing.durationRestThreshold === null+ ? []+ : [+ b.objectProperty(+ b.identifier('durationRestThreshold'),+ parseValueExpression(easing.durationRestThreshold),+ ),+ ]),+ b.objectProperty(+ b.identifier('overshootClamping'),+ b.booleanLiteral(easing.overshootClamping),+ ),+ ]),+ ] as never,+ ) as ExpressionKind;+ case 'bezier':+ return b.callExpression(+ b.memberExpression(b.identifier('Easing'), b.identifier('bezier')),+ [easing.x1, easing.y1, easing.x2, easing.y2].map((value) =>+ parseValueExpression(value),+ ) as never,+ ) as ExpressionKind;+ default:+ throw new Error(+ `Unsupported easing: ${JSON.stringify(easing satisfies never)}`,+ );+ }+};++const createEasingArrayExpression = (+ easing: KeyframeEasing[],+): ExpressionKind =>+ b.arrayExpression(+ easing.map((easingValue) => createEasingExpression(easingValue)) as never,+ ) as ExpressionKind;++const setEasingOption = ({+ options,+ easing,+}: {+ options: ObjectExpression;+ easing: KeyframeEasing[];+}): boolean => {+ const hasNonLinearEasing = easing.some(+ (easingValue) => !isLinearEasing(easingValue),+ );+ setOptionsProperty({+ options,+ propertyName: 'easing',+ value: hasNonLinearEasing ? createEasingArrayExpression(easing) : null,+ });+ return hasNonLinearEasing;+};++const getExtraArgsWithOptions = ({+ extraArgs,+ options,+}: {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ options: ObjectExpression;+}): (ExpressionKind | SpreadElementKind)[] => {+ return options.properties.length === 0+ ? extraArgs.slice(1)+ : [options as ExpressionKind, ...extraArgs.slice(1)];+};++const getInlineOptionsFromExtraArgs = (+ extraArgs: (ExpressionKind | SpreadElementKind)[],+): ObjectExpression | null => {+ const existingOptions = extraArgs[0];+ if (!existingOptions || existingOptions.type !== 'ObjectExpression') {+ return null;+ }++ return existingOptions as ObjectExpression;+};++const normalizeEasingAfterAddingKeyframe = ({+ extraArgs,+ previousSegmentCount,+ nextSegmentCount,+ insertedKeyframeIndex,+ nextKeyframeCount,+ defaultEasing,+}: {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ previousSegmentCount: number;+ nextSegmentCount: number;+ insertedKeyframeIndex: number;+ nextKeyframeCount: number;+ defaultEasing: KeyframeEasing;+}): {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ needsEasingImport: boolean;+} => {+ const options =+ getInlineOptionsFromExtraArgs(extraArgs) ??+ (extraArgs.length === 0 ? createEmptyOptionsExpression() : null);+ if (!options) {+ return {extraArgs, needsEasingImport: false};+ }++ const easing =+ getExistingEasingArrayOrNull({+ options,+ segmentCount: previousSegmentCount,+ }) ?? Array.from({length: previousSegmentCount}, () => defaultEasing);++ if (easing.length < nextSegmentCount) {+ const isSplittingExistingSegment =+ insertedKeyframeIndex > 0 &&+ insertedKeyframeIndex < nextKeyframeCount - 1;+ const easingIndexToDuplicate =+ isSplittingExistingSegment && easing.length > 0+ ? Math.min(insertedKeyframeIndex - 1, easing.length - 1)+ : null;+ easing.splice(+ insertedKeyframeIndex,+ 0,+ easingIndexToDuplicate === null+ ? defaultEasing+ : easing[easingIndexToDuplicate],+ );+ }++ while (easing.length < nextSegmentCount) {+ easing.push(defaultEasing);+ }++ const needsEasingImport = setEasingOption({options, easing});+ return {+ extraArgs: getExtraArgsWithOptions({extraArgs, options}),+ needsEasingImport,+ };+};++const getEasingIndexToRemove = ({+ removedKeyframeIndex,+ keyframeCountBeforeRemoval,+}: {+ removedKeyframeIndex: number;+ keyframeCountBeforeRemoval: number;+}) => {+ if (removedKeyframeIndex === 0) {+ return 0;+ }++ if (removedKeyframeIndex === keyframeCountBeforeRemoval - 1) {+ return removedKeyframeIndex - 1;+ }++ return removedKeyframeIndex;+};++const normalizeEasingAfterRemovingKeyframe = ({+ extraArgs,+ previousSegmentCount,+ nextSegmentCount,+ removedKeyframeIndex,+}: {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ previousSegmentCount: number;+ nextSegmentCount: number;+ removedKeyframeIndex: number;+}): {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ needsEasingImport: boolean;+} => {+ const options = getInlineOptionsFromExtraArgs(extraArgs);+ if (!options) {+ return {extraArgs, needsEasingImport: false};+ }++ const easing = getExistingEasingArrayOrNull({+ options,+ segmentCount: previousSegmentCount,+ });+ if (easing === null) {+ return {extraArgs, needsEasingImport: false};+ }++ if (easing.length > 0) {+ const easingIndexToRemove = getEasingIndexToRemove({+ removedKeyframeIndex,+ keyframeCountBeforeRemoval: previousSegmentCount + 1,+ });+ easing.splice(easingIndexToRemove, 1);+ }++ while (easing.length > nextSegmentCount) {+ easing.pop();+ }++ while (easing.length < nextSegmentCount) {+ easing.push(LINEAR_KEYFRAME_EASING);+ }++ return {+ extraArgs: getExtraArgsWithOptions({extraArgs, options}),+ needsEasingImport: setEasingOption({options, easing}),+ };+};++const normalizeEasingAfterRemovingKeyframes = ({+ extraArgs,+ previousSegmentCount,+ nextSegmentCount,+ removedKeyframeIndexes,+}: {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ previousSegmentCount: number;+ nextSegmentCount: number;+ removedKeyframeIndexes: number[];+}): {+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ needsEasingImport: boolean;+} => {+ const options = getInlineOptionsFromExtraArgs(extraArgs);+ if (!options) {+ return {extraArgs, needsEasingImport: false};+ }++ const easing = getExistingEasingArrayOrNull({+ options,+ segmentCount: previousSegmentCount,+ });+ if (easing === null) {+ return {extraArgs, needsEasingImport: false};+ }++ for (const {removedKeyframeIndex, keyframeCountBeforeRemoval} of [+ ...removedKeyframeIndexes,+ ]+ .sort((first, second) => second - first)+ .map((keyframeIndex, index) => ({+ removedKeyframeIndex: keyframeIndex,+ keyframeCountBeforeRemoval: previousSegmentCount + 1 - index,+ }))) {+ if (easing.length === 0) {+ break;+ }++ const easingIndexToRemove = getEasingIndexToRemove({+ removedKeyframeIndex,+ keyframeCountBeforeRemoval,+ });+ easing.splice(easingIndexToRemove, 1);+ }++ while (easing.length > nextSegmentCount) {+ easing.pop();+ }++ while (easing.length < nextSegmentCount) {+ easing.push(LINEAR_KEYFRAME_EASING);+ }++ return {+ extraArgs: getExtraArgsWithOptions({extraArgs, options}),+ needsEasingImport: setEasingOption({options, easing}),+ };+};++const validatePosterize = (posterize: number | undefined) => {+ if (posterize === undefined) {+ return;+ }++ if (!Number.isFinite(posterize) || posterize <= 0) {+ throw new Error('Cannot update keyframe settings: posterize must be > 0');+ }+};++const validateOutput = (output: InterpolateOutputOption | undefined) => {+ if (+ output === undefined ||+ output === 'linear' ||+ output === 'perceptual-scale'+ ) {+ return;+ }++ throw new Error(+ 'Cannot update keyframe settings: output must be "linear" or "perceptual-scale"',+ );+};++const updateKeyframeSettings = ({+ expression,+ clamping,+ posterize,+ output,+ videoConfigValues,+}: {+ expression: Expression;+ clamping:+ | {+ left: ExtrapolateType;+ right: ExtrapolateType;+ }+ | undefined;+ posterize: number | undefined;+ output: InterpolateOutputOption | undefined;+ videoConfigValues: VideoConfigIdentifierValues;+}): ExpressionKind => {+ validatePosterize(posterize);+ validateOutput(output);++ const existing = getInterpolationExpression(expression, videoConfigValues);+ if (!existing) {+ throw new Error('Cannot update keyframe settings on non-keyframed value');+ }++ const calleeName =+ existing.callee.type === 'Identifier' ? existing.callee.name : null;+ const isColorInterpolation = calleeName === 'interpolateColors';+ const extraArgs = [...existing.extraArgs];+ const existingOptions = extraArgs[0];+ if (existingOptions && existingOptions.type !== 'ObjectExpression') {+ throw new Error('Cannot update keyframe settings: options must be inline');+ }++ const options =+ existingOptions?.type === 'ObjectExpression'+ ? (existingOptions as ObjectExpression)+ : createEmptyOptionsExpression();++ if (isColorInterpolation) {+ setOptionsProperty({options, propertyName: 'extrapolateLeft', value: null});+ setOptionsProperty({+ options,+ propertyName: 'extrapolateRight',+ value: null,+ });+ setOptionsProperty({options, propertyName: 'output', value: null});+ } else if (clamping) {+ setOptionsProperty({+ options,+ propertyName: 'extrapolateLeft',+ value: b.stringLiteral(clamping.left),+ });+ setOptionsProperty({+ options,+ propertyName: 'extrapolateRight',+ value: b.stringLiteral(clamping.right),+ });+ }++ if (!isColorInterpolation && output !== undefined) {+ setOptionsProperty({+ options,+ propertyName: 'output',+ value: output === 'linear' ? null : b.stringLiteral(output),+ });+ }++ setOptionsProperty({+ options,+ propertyName: 'posterize',+ value: posterize === undefined ? null : b.numericLiteral(posterize),+ });++ const nextExtraArgs =+ options.properties.length === 0+ ? extraArgs.slice(1)+ : [options as ExpressionKind, ...extraArgs.slice(1)];++ return createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: nextExtraArgs,+ keyframes: existing.keyframes,+ });+};++const updateKeyframeEasing = ({+ expression,+ segmentIndex,+ easing,+ videoConfigValues,+}: {+ expression: Expression;+ segmentIndex: number;+ easing: KeyframeEasing;+ videoConfigValues: VideoConfigIdentifierValues;+}): {expression: ExpressionKind; needsEasingImport: boolean} => {+ const existing = getInterpolationExpression(expression, videoConfigValues);+ if (!existing) {+ throw new Error('Cannot update easing on non-keyframed value');+ }++ const segmentCount = Math.max(0, existing.keyframes.length - 1);+ if (+ !Number.isInteger(segmentIndex) ||+ segmentIndex < 0 ||+ segmentIndex >= segmentCount+ ) {+ throw new Error('Cannot update easing: segment index out of range');+ }++ const extraArgs = [...existing.extraArgs];+ const existingOptions = extraArgs[0];+ if (existingOptions && existingOptions.type !== 'ObjectExpression') {+ throw new Error('Cannot update easing: options must be inline');+ }++ const options =+ existingOptions?.type === 'ObjectExpression'+ ? (existingOptions as ObjectExpression)+ : createEmptyOptionsExpression();+ const nextEasing = getExistingEasingArray({options, segmentCount});+ nextEasing[segmentIndex] = easing;+ const hasNonLinearEasing = nextEasing.some(+ (easingValue) => !isLinearEasing(easingValue),+ );++ setOptionsProperty({+ options,+ propertyName: 'easing',+ value: hasNonLinearEasing ? createEasingArrayExpression(nextEasing) : null,+ });++ const nextExtraArgs =+ options.properties.length === 0+ ? extraArgs.slice(1)+ : [options as ExpressionKind, ...extraArgs.slice(1)];++ return {+ expression: createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: nextExtraArgs,+ keyframes: existing.keyframes,+ }),+ needsEasingImport: hasNonLinearEasing,+ };+};++const createInterpolateExpression = ({+ callee,+ input,+ extraArgs,+ keyframes,+}: {+ callee: ExpressionKind;+ input: ExpressionKind | SpreadElementKind;+ extraArgs: (ExpressionKind | SpreadElementKind)[];+ keyframes: InterpolateKeyframe[];+}): ExpressionKind => {+ const sortedKeyframes = [...keyframes].sort(+ (first, second) => first.frame - second.frame,+ );+ return b.callExpression(callee, [+ input,+ b.arrayExpression(+ sortedKeyframes.map((keyframe) =>+ keyframe.frame === keyframe.originalFrame+ ? keyframe.frameExpression+ : updateVideoConfigNumericExpression({+ expression: keyframe.frameNumericExpression,+ value: keyframe.frame,+ }),+ ),+ ),+ b.arrayExpression(sortedKeyframes.map((keyframe) => keyframe.output)),+ ...extraArgs,+ ]) as ExpressionKind;+};++export type IntroducedKeyframeIdentifiers = {+ calleeName: KeyframeInterpolationFunction | null;+ needsFrameHook: boolean;+ needsEasingImport: boolean;+};++const noIntroducedIdentifiers: IntroducedKeyframeIdentifiers = {+ calleeName: null,+ needsFrameHook: false,+ needsEasingImport: false,+};++const addKeyframe = ({+ expression,+ key,+ frame,+ value,+ schema,+ videoConfigValues,+}: {+ expression: Expression;+ key: string;+ frame: number;+ value: unknown;+ schema: InteractivitySchema | null;+ videoConfigValues: VideoConfigIdentifierValues;+}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {+ if (!isSchemaFieldKeyframable({schema, key})) {+ throw new Error(`Cannot add keyframe: "${key}" is not keyframable`);+ }++ const existing = getInterpolationExpression(expression, videoConfigValues);+ const newOutput = parseValueExpression(value);++ if (existing) {+ const defaultEasing = isSchemaFieldHoldOnly({schema, key})+ ? HOLD_KEYFRAME_EASING+ : LINEAR_KEYFRAME_EASING;+ const existingCalleeName =+ existing.callee.type === 'Identifier'+ ? (existing.callee.name as KeyframeInterpolationFunction)+ : 'interpolate';+ const schemaCalleeName = getKeyframeInterpolationFunctionForSchemaField({+ schema,+ key,+ });+ const nextCalleeName = schemaCalleeName ?? existingCalleeName;+ const existingIndex = existing.keyframes.findIndex(+ (keyframe) => keyframe.frame === frame,+ );+ const nextKeyframes: InterpolateKeyframe[] =+ existingIndex === -1+ ? [+ ...existing.keyframes,+ {+ frame,+ frameExpression: createFrameExpression(frame),+ frameNumericExpression: {type: 'literal', value: frame},+ originalFrame: frame,+ output: newOutput,+ value,+ },+ ]+ : existing.keyframes.map((keyframe, index) =>+ index === existingIndex+ ? {...keyframe, output: newOutput, value}+ : keyframe,+ );+ const normalizedEasing =+ existingIndex === -1+ ? normalizeEasingAfterAddingKeyframe({+ extraArgs: existing.extraArgs,+ previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),+ nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),+ insertedKeyframeIndex: [...nextKeyframes]+ .sort((first, second) => first.frame - second.frame)+ .findIndex((keyframe) => keyframe.frame === frame),+ nextKeyframeCount: nextKeyframes.length,+ defaultEasing,+ })+ : {extraArgs: existing.extraArgs, needsEasingImport: false};++ return {+ expression: createInterpolateExpression({+ callee: b.identifier(nextCalleeName),+ input: existing.input,+ extraArgs: normalizedEasing.extraArgs,+ keyframes: nextKeyframes,+ }),+ introduced: {+ calleeName:+ schemaCalleeName && schemaCalleeName !== existingCalleeName+ ? schemaCalleeName+ : null,+ needsFrameHook: false,+ needsEasingImport: normalizedEasing.needsEasingImport,+ },+ };+ }++ const staticNumericExpression = parseVideoConfigNumericExpression({+ node: expression,+ videoConfigValues,+ });+ if (!isStaticValue(expression) && staticNumericExpression === null) {+ throw new Error('Cannot add keyframe to computed expression');+ }++ const staticValue =+ staticNumericExpression?.value ?? extractStaticValue(expression);+ const keyframes: InterpolateKeyframe[] = [+ {+ frame,+ frameExpression: createFrameExpression(frame),+ frameNumericExpression: {type: 'literal', value: frame},+ originalFrame: frame,+ output: newOutput,+ value,+ },+ ];++ const callee = getInterpolationCalleeForValues({+ schema,+ key,+ staticValue,+ newValue: value,+ });+ const extraArgs =+ callee.type === 'Identifier' && callee.name === 'interpolateColors'+ ? []+ : [+ createClampOptionsExpression({+ defaultOutput: getDefaultKeyframeOutput({schema, key}),+ }),+ ];++ return {+ expression: createInterpolateExpression({+ callee,+ input: b.identifier('frame'),+ extraArgs,+ keyframes,+ }),+ introduced: {+ calleeName:+ callee.type === 'Identifier'+ ? (callee.name as KeyframeInterpolationFunction)+ : null,+ needsFrameHook: true,+ needsEasingImport: false,+ },+ };+};++const removeKeyframe = ({+ expression,+ frame,+ videoConfigValues,+ valueWhenLastKeyframeDeleted,+}: {+ expression: Expression;+ frame: number;+ videoConfigValues: VideoConfigIdentifierValues;+ valueWhenLastKeyframeDeleted: unknown | null;+}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {+ const existing = getInterpolationExpression(expression, videoConfigValues);+ if (!existing) {+ throw new Error('Cannot remove keyframe from non-interpolated expression');+ }++ const keyframeIndex = existing.keyframes.findIndex(+ (keyframe) => keyframe.frame === frame,+ );+ if (keyframeIndex === -1) {+ throw new Error(`Cannot remove keyframe at frame ${frame}: not found`);+ }++ const nextKeyframes = existing.keyframes.filter(+ (_keyframe, index) => index !== keyframeIndex,+ );++ if (nextKeyframes.length === 0) {+ return {+ expression:+ valueWhenLastKeyframeDeleted === null+ ? existing.keyframes[keyframeIndex].output+ : parseValueExpression(valueWhenLastKeyframeDeleted),+ introduced: noIntroducedIdentifiers,+ };+ }++ const normalizedEasing = normalizeEasingAfterRemovingKeyframe({+ extraArgs: existing.extraArgs,+ previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),+ nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),+ removedKeyframeIndex: keyframeIndex,+ });++ return {+ expression: createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: normalizedEasing.extraArgs,+ keyframes: nextKeyframes,+ }),+ introduced: {+ ...noIntroducedIdentifiers,+ needsEasingImport: normalizedEasing.needsEasingImport,+ },+ };+};++const moveKeyframes = ({+ expression,+ moves,+ videoConfigValues,+}: {+ expression: Expression;+ moves: {+ fromFrame: number;+ toFrame: number;+ }[];+ videoConfigValues: VideoConfigIdentifierValues;+}): ExpressionKind => {+ const existing = getInterpolationExpression(expression, videoConfigValues);+ if (!existing) {+ throw new Error('Cannot move keyframe in non-interpolated expression');+ }++ const moveMap = new Map<number, number>();+ for (const move of moves) {+ if (move.fromFrame === move.toFrame) {+ continue;+ }++ if (moveMap.has(move.fromFrame)) {+ throw new Error(`Cannot move keyframe at frame ${move.fromFrame} twice`);+ }++ moveMap.set(move.fromFrame, move.toFrame);+ }++ if (moveMap.size === 0) {+ return expression as ExpressionKind;+ }++ const frames = new Set(existing.keyframes.map((keyframe) => keyframe.frame));+ for (const fromFrame of moveMap.keys()) {+ if (!frames.has(fromFrame)) {+ throw new Error(`Cannot move keyframe at frame ${fromFrame}: not found`);+ }+ }++ const movedFromFrames = new Set(moveMap.keys());+ const movedToFrames = new Set(moveMap.values());+ const removedKeyframeIndexes: number[] = [];+ const nextKeyframes = existing.keyframes.flatMap((keyframe, index) => {+ const movedFrame = moveMap.get(keyframe.frame);+ if (movedFrame !== undefined) {+ return [{...keyframe, frame: movedFrame}];+ }++ if (+ movedToFrames.has(keyframe.frame) &&+ !movedFromFrames.has(keyframe.frame)+ ) {+ removedKeyframeIndexes.push(index);+ return [];+ }++ return [keyframe];+ });++ const nextFrames = new Set<number>();+ for (const keyframe of nextKeyframes) {+ if (nextFrames.has(keyframe.frame)) {+ throw new Error(+ `Cannot move keyframe to frame ${keyframe.frame}: frame already exists`,+ );+ }++ nextFrames.add(keyframe.frame);+ }++ const normalizedEasing = normalizeEasingAfterRemovingKeyframes({+ extraArgs: existing.extraArgs,+ previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),+ nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),+ removedKeyframeIndexes,+ });++ return createInterpolateExpression({+ callee: existing.callee,+ input: existing.input,+ extraArgs: normalizedEasing.extraArgs,+ keyframes: nextKeyframes,+ });+};++const applyKeyframeOperation = ({+ expression,+ key,+ operation,+ schema,+ videoConfigValues,+}: {+ expression: Expression;+ key: string;+ operation: KeyframeOperation;+ schema: InteractivitySchema | null;+ videoConfigValues: VideoConfigIdentifierValues;+}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {+ if (operation.type === 'add') {+ return addKeyframe({+ expression,+ key,+ frame: operation.frame,+ value: operation.value,+ schema,+ videoConfigValues,+ });+ }++ if (operation.type === 'settings') {+ return {+ expression: updateKeyframeSettings({+ expression,+ clamping: operation.clamping,+ posterize: operation.posterize,+ output: operation.output,+ videoConfigValues,+ }),+ introduced: noIntroducedIdentifiers,+ };+ }++ if (operation.type === 'easing') {+ if (+ isSchemaFieldHoldOnly({schema, key}) &&+ operation.easing.type !== 'step1'+ ) {+ throw new Error(+ `Cannot update easing: "${key}" only supports Easing.step1`,+ );+ }++ const updated = updateKeyframeEasing({+ expression,+ segmentIndex: operation.segmentIndex,+ easing: operation.easing,+ videoConfigValues,+ });+ return {+ expression: updated.expression,+ introduced: {+ ...noIntroducedIdentifiers,+ needsEasingImport: updated.needsEasingImport,+ },+ };+ }++ if (operation.type === 'move') {+ return {+ expression: moveKeyframes({+ expression,+ moves: operation.moves,+ videoConfigValues,+ }),+ introduced: noIntroducedIdentifiers,+ };+ }++ return removeKeyframe({+ expression,+ frame: operation.frame,+ videoConfigValues,+ valueWhenLastKeyframeDeleted: operation.valueWhenLastKeyframeDeleted,+ });+};++const getExpressionFromJsxAttribute = (+ attr: JSXAttribute,+): Expression | null => {+ if (!attr.value) {+ return b.booleanLiteral(true) as Expression;+ }++ if (attr.value.type === 'StringLiteral') {+ return attr.value as unknown as Expression;+ }++ if (attr.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ const {expression} = attr.value;+ if (expression.type === 'JSXEmptyExpression') {+ return null;+ }++ return expression as Expression;+};++const findJsxAttribute = (+ attributes: (JSXAttribute | JSXSpreadAttribute)[],+ name: string,+): {attrIndex: number; attr: JSXAttribute | undefined} => {+ const attrIndex = attributes.findIndex((candidate) => {+ if (candidate.type === 'JSXSpreadAttribute') {+ return false;+ }++ if (candidate.name.type === 'JSXNamespacedName') {+ return false;+ }++ return candidate.name.name === name;+ });++ const foundAttr = attrIndex === -1 ? undefined : attributes[attrIndex];+ return {+ attrIndex,+ attr:+ foundAttr && foundAttr.type === 'JSXAttribute'+ ? (foundAttr as JSXAttribute)+ : undefined,+ };+};++const findObjectProperty = (+ objExpr: ObjectExpression,+ propertyName: string,+): {propIndex: number; prop: ObjectProperty | undefined} => {+ const propIndex = objExpr.properties.findIndex(+ (prop) =>+ prop.type === 'ObjectProperty' &&+ ((prop.key.type === 'Identifier' && prop.key.name === propertyName) ||+ (prop.key.type === 'StringLiteral' && prop.key.value === propertyName)),+ );++ return {+ propIndex,+ prop:+ propIndex === -1+ ? undefined+ : (objExpr.properties[propIndex] as ObjectProperty),+ };+};++const findFieldInSchema = (+ schema: InteractivitySchema,+ key: string,+): InteractivitySchemaField | undefined => {+ if (key in schema) {+ return schema[key];+ }++ for (const field of Object.values(schema)) {+ if (field.type !== 'enum') {+ continue;+ }++ for (const variant of Object.values(field.variants)) {+ const found = findFieldInSchema(variant, key);+ if (found) {+ return found;+ }+ }+ }++ return undefined;+};++const getDefaultKeyframeOutput = ({+ schema,+ key,+}: {+ schema: InteractivitySchema | null;+ key: string;+}): InterpolateOutputOption | null => {+ const field = schema ? findFieldInSchema(schema, key) : undefined;+ if (+ (field?.type === 'number' || field?.type === 'scale') &&+ field.defaultKeyframeOutput !== undefined+ ) {+ return field.defaultKeyframeOutput;+ }++ return key === 'style.scale' ? 'perceptual-scale' : null;+};++const getInitialValueForMissingProp = ({+ schema,+ key,+ newValue,+}: {+ schema: InteractivitySchema | null;+ key: string;+ newValue: unknown;+}): unknown => {+ const field = schema ? findFieldInSchema(schema, key) : undefined;+ if (field && field.type !== 'hidden' && field.default !== undefined) {+ return field.default;+ }++ return newValue;+};++const shouldRemovePropAfterKeyframeOperation = ({+ expression,+ key,+ operation,+ schema,+ videoConfigValues,+}: {+ expression: Expression;+ key: string;+ operation: KeyframeOperation;+ schema: InteractivitySchema | null;+ videoConfigValues: VideoConfigIdentifierValues;+}) => {+ if (operation.type !== 'remove' || !schema) {+ return false;+ }++ const existing = getInterpolationExpression(expression, videoConfigValues);+ if (!existing || existing.keyframes.length !== 1) {+ return false;+ }++ const field = findFieldInSchema(schema, key);+ if (!field || field.type === 'hidden' || field.default === undefined) {+ return false;+ }++ const valueAfterRemoval =+ operation.valueWhenLastKeyframeDeleted === null+ ? existing.keyframes[0].value+ : operation.valueWhenLastKeyframeDeleted;++ return JSON.stringify(valueAfterRemoval) === JSON.stringify(field.default);+};++const getObjectExpression = (attr: JSXAttribute): ObjectExpression | null => {+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ if (attr.value.expression.type !== 'ObjectExpression') {+ return null;+ }++ return attr.value.expression as ObjectExpression;+};++const createJsxExpressionAttribute = (+ key: string,+ expression: ExpressionKind,+): JSXAttribute => {+ return b.jsxAttribute(+ b.jsxIdentifier(key),+ b.jsxExpressionContainer(expression),+ ) as JSXAttribute;+};++const createObjectProperty = (key: string, value: ExpressionKind) =>+ b.objectProperty(b.identifier(key), value);++const createObjectExpressionAttribute = ({+ parentKey,+ childKey,+ expression,+}: {+ parentKey: string;+ childKey: string;+ expression: ExpressionKind;+}): JSXAttribute => {+ return createJsxExpressionAttribute(+ parentKey,+ b.objectExpression([+ createObjectProperty(childKey, expression),+ ]) as ExpressionKind,+ );+};++const createMissingPropExpression = (+ missingPropInitialValue: MissingPropInitialValue,+): Expression => {+ return parseValueExpression(missingPropInitialValue.value) as Expression;+};++const getSequenceWritableProp = ({+ attributes,+ key,+ missingPropInitialValue,+}: {+ attributes: (JSXAttribute | JSXSpreadAttribute)[];+ key: string;+ missingPropInitialValue: MissingPropInitialValue | null;+}): WritableProp => {+ const dotIndex = key.indexOf('.');+ if (dotIndex === -1) {+ const {attrIndex, attr: topLevelAttr} = findJsxAttribute(attributes, key);+ if (!topLevelAttr) {+ if (missingPropInitialValue) {+ return {+ expression: createMissingPropExpression(missingPropInitialValue),+ setExpression: (nextExpression) => {+ attributes.push(createJsxExpressionAttribute(key, nextExpression));+ },+ remove: () => undefined,+ };+ }++ throw new Error(`Cannot update keyframes: "${key}" is not set`);+ }++ const expression = getExpressionFromJsxAttribute(topLevelAttr);+ if (!expression) {+ throw new Error(`Cannot update keyframes: "${key}" is computed`);+ }++ return {+ expression,+ setExpression: (nextExpression) => {+ topLevelAttr.value = b.jsxExpressionContainer(nextExpression) as+ | JSXElement+ | JSXExpressionContainer+ | JSXFragment+ | StringLiteral+ | null+ | undefined;+ },+ remove: () => {+ attributes.splice(attrIndex, 1);+ },+ };+ }++ const parentKey = key.slice(0, dotIndex);+ const childKey = key.slice(dotIndex + 1);+ const {attrIndex: parentAttrIndex, attr: parentAttr} = findJsxAttribute(+ attributes,+ parentKey,+ );+ if (!parentAttr) {+ if (missingPropInitialValue) {+ return {+ expression: createMissingPropExpression(missingPropInitialValue),+ setExpression: (nextExpression) => {+ attributes.push(+ createObjectExpressionAttribute({+ parentKey,+ childKey,+ expression: nextExpression,+ }),+ );+ },+ remove: () => undefined,+ };+ }++ throw new Error(`Cannot update keyframes: "${parentKey}" is not set`);+ }++ const objExpr = getObjectExpression(parentAttr);+ if (!objExpr) {+ throw new Error(`Cannot update keyframes: "${parentKey}" is computed`);+ }++ const {propIndex, prop} = findObjectProperty(objExpr, childKey);+ if (!prop) {+ if (missingPropInitialValue) {+ return {+ expression: createMissingPropExpression(missingPropInitialValue),+ setExpression: (nextExpression) => {+ objExpr.properties.push(+ createObjectProperty(childKey, nextExpression) as ObjectProperty,+ );+ },+ remove: () => undefined,+ };+ }++ throw new Error(`Cannot update keyframes: "${key}" is not set`);+ }++ return {+ expression: prop.value as Expression,+ setExpression: (nextExpression) => {+ prop.value = nextExpression as ObjectProperty['value'];+ },+ remove: () => {+ objExpr.properties.splice(propIndex, 1);+ if (objExpr.properties.length === 0) {+ attributes.splice(parentAttrIndex, 1);+ }+ },+ };+};++const getEffectWritableProp = ({+ objExpr,+ key,+ missingPropInitialValue,+}: {+ objExpr: ObjectExpression;+ key: string;+ missingPropInitialValue: MissingPropInitialValue | null;+}): WritableProp => {+ const {propIndex, prop} = findObjectProperty(objExpr, key);+ if (!prop) {+ if (missingPropInitialValue) {+ return {+ expression: createMissingPropExpression(missingPropInitialValue),+ setExpression: (nextExpression) => {+ objExpr.properties.push(+ createObjectProperty(key, nextExpression) as ObjectProperty,+ );+ },+ remove: () => undefined,+ };+ }++ throw new Error(`Cannot update keyframes: "${key}" is not set`);+ }++ return {+ expression: prop.value as Expression,+ setExpression: (nextExpression) => {+ prop.value = nextExpression as ObjectProperty['value'];+ },+ remove: () => {+ objExpr.properties.splice(propIndex, 1);+ },+ };+};++const getEffectPropsObjectExpression = (+ call: CallExpression,+): ObjectExpression => {+ if (call.arguments.length === 0) {+ const objExpr = b.objectExpression([]) as ObjectExpression;+ call.arguments.push(objExpr);+ return objExpr;+ }++ if (call.arguments[0].type !== 'ObjectExpression') {+ throw new Error('Cannot update effect keyframe: computed');+ }++ return call.arguments[0] as ObjectExpression;+};++export const updateSequenceKeyframesAst = ({+ input,+ nodePath,+ updates,+ schema,+ videoConfigValues,+}: {+ input: string;+ nodePath: SequenceNodePath;+ updates: SequenceKeyframeUpdate[];+ schema?: InteractivitySchema;+ videoConfigValues: VideoConfigValues | null;+}): {+ serialized: string;+ oldValueStrings: string[];+ newValueStrings: string[];+ logLine: number;+ updatedNodePath: SequenceNodePath;+} => {+ const ast = parseAst(input);+ const videoConfigIdentifierValues = getVideoConfigIdentifierValues({+ ast,+ videoConfigValues,+ });+ const jsxPath = getAstNodePath(ast, nodePath);+ const node = findJsxElementAtNodePath(ast, nodePath);+ if (!node || !jsxPath) {+ throw new Error(+ 'Could not find a JSX element at the specified location to update keyframes',+ );+ }++ if (!node.attributes) {+ node.attributes = [];+ }++ const requiredImports = new Set<string>();+ let needsFrameHook = false;++ const oldValueStrings: string[] = [];+ const newValueStrings: string[] = [];+ for (const update of updates) {+ const prop = getSequenceWritableProp({+ attributes: node.attributes,+ key: update.key,+ missingPropInitialValue:+ update.operation.type === 'add'+ ? {+ value: getInitialValueForMissingProp({+ schema: schema ?? null,+ key: update.key,+ newValue: update.operation.value,+ }),+ }+ : null,+ });+ oldValueStrings.push(recast.print(prop.expression).code);+ const {expression: nextExpression, introduced} = applyKeyframeOperation({+ expression: prop.expression,+ key: update.key,+ operation: update.operation,+ schema: schema ?? null,+ videoConfigValues: videoConfigIdentifierValues,+ });+ newValueStrings.push(recast.print(nextExpression).code);+ if (+ shouldRemovePropAfterKeyframeOperation({+ expression: prop.expression,+ key: update.key,+ operation: update.operation,+ schema: schema ?? null,+ videoConfigValues: videoConfigIdentifierValues,+ })+ ) {+ prop.remove();+ } else {+ prop.setExpression(nextExpression);+ }++ if (introduced.calleeName) {+ requiredImports.add(introduced.calleeName);+ }++ if (introduced.needsFrameHook) {+ requiredImports.add('useCurrentFrame');+ needsFrameHook = true;+ }++ if (introduced.needsEasingImport) {+ requiredImports.add('Easing');+ }+ }++ if (needsFrameHook) {+ const fnPath = findEnclosingFunctionPath(jsxPath);+ if (fnPath) {+ ensureUseCurrentFrameHook(fnPath);+ }+ }++ ensureRemotionImports(ast, requiredImports);++ const updatedNodePath = findNodePathForJsxElement(ast, node);+ if (!updatedNodePath) {+ throw new Error(+ 'Could not find updated JSX element location after updating keyframes',+ );+ }++ return {+ serialized: serializeAst(ast),+ oldValueStrings,+ newValueStrings,+ logLine: node.loc?.start.line ?? 1,+ updatedNodePath,+ };+};++export const updateSequenceKeyframes = async ({+ input,+ nodePath,+ updates,+ schema,+ formatFile,+ prettierConfigOverride,+ videoConfigValues,+}: {+ input: string;+ nodePath: SequenceNodePath;+ updates: SequenceKeyframeUpdate[];+ schema?: InteractivitySchema;+ formatFile: FormatKeyframesFile;+ prettierConfigOverride?: Record<string, unknown> | null;+ videoConfigValues: VideoConfigValues | null;+}): Promise<{+ output: string;+ formatted: boolean;+ oldValueStrings: string[];+ newValueStrings: string[];+ logLine: number;+ updatedNodePath: SequenceNodePath;+}> => {+ const {+ serialized,+ oldValueStrings,+ newValueStrings,+ logLine,+ updatedNodePath,+ } = updateSequenceKeyframesAst({+ input,+ nodePath,+ updates,+ schema,+ videoConfigValues,+ });+ const {output, formatted} = await formatFile({+ contents: serialized,+ prettierConfigOverride: prettierConfigOverride ?? null,+ });+ const outputWithoutInsertedBlankLines =+ removeBlankLinesFromObjectsWithProperties({+ input: output,+ propertyNames: updates.map((update) =>+ getObjectPropertyNameFromUpdateKey(update.key),+ ),+ });++ return {+ output: outputWithoutInsertedBlankLines,+ formatted,+ oldValueStrings,+ newValueStrings,+ logLine,+ updatedNodePath,+ };+};++export const updateEffectKeyframesAst = ({+ input,+ sequenceNodePath,+ effectIndex,+ updates,+ schema,+ videoConfigValues,+}: {+ input: string;+ sequenceNodePath: SequenceNodePath;+ effectIndex: number;+ updates: EffectKeyframeUpdate[];+ schema?: InteractivitySchema;+ videoConfigValues: VideoConfigValues | null;+}): {+ serialized: string;+ oldValueStrings: string[];+ newValueStrings: string[];+ logLine: number;+ effectCallee: string;+ updatedSequenceNodePath: SequenceNodePath;+} => {+ const ast = parseAst(input);+ const videoConfigIdentifierValues = getVideoConfigIdentifierValues({+ ast,+ videoConfigValues,+ });+ const jsxPath = getAstNodePath(ast, sequenceNodePath);+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);+ if (!jsx || !jsxPath) {+ throw new Error(+ 'Could not find a JSX element at the specified location to update effect keyframes',+ );+ }++ const attr = findEffectsAttr(jsx.attributes ?? []);+ if (!attr) {+ throw new Error('Could not find effects on the target JSX element');+ }++ const found = findEffectCallExpression({attr, effectIndex});+ if (found.kind === 'error') {+ throw new Error(`Cannot update effect keyframe: ${found.reason}`);+ }++ const {call, callee: effectCallee} = found;+ const objExpr = getEffectPropsObjectExpression(call);+ const oldValueStrings: string[] = [];+ const newValueStrings: string[] = [];+ const requiredImports = new Set<string>();+ let needsFrameHook = false;+ for (const update of updates) {+ const prop = getEffectWritableProp({+ objExpr,+ key: update.key,+ missingPropInitialValue:+ update.operation.type === 'add'+ ? {+ value: getInitialValueForMissingProp({+ schema: schema ?? null,+ key: update.key,+ newValue: update.operation.value,+ }),+ }+ : null,+ });+ oldValueStrings.push(recast.print(prop.expression).code);+ const {expression: nextExpression, introduced} = applyKeyframeOperation({+ expression: prop.expression,+ key: update.key,+ operation: update.operation,+ schema: schema ?? null,+ videoConfigValues: videoConfigIdentifierValues,+ });+ newValueStrings.push(recast.print(nextExpression).code);+ if (+ shouldRemovePropAfterKeyframeOperation({+ expression: prop.expression,+ key: update.key,+ operation: update.operation,+ schema: schema ?? null,+ videoConfigValues: videoConfigIdentifierValues,+ })+ ) {+ prop.remove();+ } else {+ prop.setExpression(nextExpression);+ }++ if (introduced.calleeName) {+ requiredImports.add(introduced.calleeName);+ }++ if (introduced.needsFrameHook) {+ requiredImports.add('useCurrentFrame');+ needsFrameHook = true;+ }++ if (introduced.needsEasingImport) {+ requiredImports.add('Easing');+ }+ }++ if (needsFrameHook) {+ const fnPath = findEnclosingFunctionPath(jsxPath);+ if (fnPath) {+ ensureUseCurrentFrameHook(fnPath);+ }+ }++ ensureRemotionImports(ast, requiredImports);++ const updatedSequenceNodePath = findNodePathForJsxElement(ast, jsx);+ if (!updatedSequenceNodePath) {+ throw new Error(+ 'Could not find updated JSX element location after updating effect keyframes',+ );+ }++ return {+ serialized: serializeAst(ast),+ oldValueStrings,+ newValueStrings,+ logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,+ effectCallee,+ updatedSequenceNodePath,+ };+};++export const updateEffectKeyframes = async ({+ input,+ sequenceNodePath,+ effectIndex,+ updates,+ schema,+ formatFile,+ prettierConfigOverride,+ videoConfigValues,+}: {+ input: string;+ sequenceNodePath: SequenceNodePath;+ effectIndex: number;+ updates: EffectKeyframeUpdate[];+ schema?: InteractivitySchema;+ formatFile: FormatKeyframesFile;+ prettierConfigOverride?: Record<string, unknown> | null;+ videoConfigValues: VideoConfigValues | null;+}): Promise<{+ output: string;+ formatted: boolean;+ oldValueStrings: string[];+ newValueStrings: string[];+ logLine: number;+ effectCallee: string;+ updatedSequenceNodePath: SequenceNodePath;+}> => {+ const {+ serialized,+ oldValueStrings,+ newValueStrings,+ logLine,+ effectCallee,+ updatedSequenceNodePath,+ } = updateEffectKeyframesAst({+ input,+ sequenceNodePath,+ effectIndex,+ updates,+ schema,+ videoConfigValues,+ });+ const {output, formatted} = await formatFile({+ contents: serialized,+ prettierConfigOverride: prettierConfigOverride ?? null,+ });+ const outputWithoutInsertedBlankLines =+ removeBlankLinesFromObjectsWithProperties({+ input: output,+ propertyNames: updates.map((update) => update.key),+ });++ return {+ output: outputWithoutInsertedBlankLines,+ formatted,+ oldValueStrings,+ newValueStrings,+ logLine,+ effectCallee,+ updatedSequenceNodePath,+ };+};diff --git a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.tsindex 3974e5ca2b..14959b842f 100644--- a/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts+++ b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts@@ -1,116 +1,5 @@-import type {- ArrowFunctionExpression,- File,- FunctionDeclaration,- FunctionExpression,-} from '@babel/types';-import * as recast from 'recast';-import {ensureNamedImports} from '../../helpers/imports';--const b = recast.types.builders;-const n = recast.types.namedTypes;--type FunctionNode =- | FunctionDeclaration- | FunctionExpression- | ArrowFunctionExpression;--const isFunctionNode = (value: unknown): value is FunctionNode => {- return (- n.FunctionDeclaration.check(value) ||- n.FunctionExpression.check(value) ||- n.ArrowFunctionExpression.check(value)- );-};--export const findEnclosingFunctionPath = (- path: recast.types.NodePath,-): recast.types.NodePath | null => {- let current: recast.types.NodePath | null = path.parentPath;- while (current) {- if (isFunctionNode(current.value)) {- return current;- }-- current = current.parentPath;- }-- return null;-};--export const ensureRemotionImports = (- ast: File,- names: ReadonlySet<string>,-) => {- ensureNamedImports({ast, importedNames: names, sourcePath: 'remotion'});-};--const componentBodyHasFrameDeclaration = ({- body,- hookName,-}: {- body: FunctionNode['body'];- hookName: string;-}): boolean => {- if (!n.BlockStatement.check(body)) {- return false;- }-- for (const stmt of body.body) {- if (stmt.type !== 'VariableDeclaration') {- continue;- }-- for (const decl of stmt.declarations) {- if (decl.type !== 'VariableDeclarator') {- continue;- }-- if (- decl.id.type === 'Identifier' &&- decl.id.name === 'frame' &&- decl.init &&- decl.init.type === 'CallExpression' &&- decl.init.callee.type === 'Identifier' &&- decl.init.callee.name === hookName- ) {- return true;- }- }- }-- return false;-};--export const ensureUseCurrentFrameHook = (- functionPath: recast.types.NodePath,- hookName = 'useCurrentFrame',-): void => {- const fn = functionPath.value as FunctionNode;-- if (!n.BlockStatement.check(fn.body)) {- // Arrow function with expression body: wrap the expression in a block so- // we can prepend the hook call before returning the original expression.- const expression = fn.body;- fn.body = b.blockStatement([- b.returnStatement(expression as Parameters<typeof b.returnStatement>[0]),- ]) as unknown as FunctionNode['body'];- }-- if (componentBodyHasFrameDeclaration({body: fn.body, hookName})) {- return;- }-- const block = fn.body as Extract<- FunctionNode['body'],- {type: 'BlockStatement'}- >;- const frameDecl = b.variableDeclaration('const', [- b.variableDeclarator(- b.identifier('frame'),- b.callExpression(b.identifier(hookName), []),- ),- ]);-- block.body.unshift(frameDecl as unknown as (typeof block.body)[number]);-};+export {+ ensureRemotionImports,+ ensureUseCurrentFrameHook,+ findEnclosingFunctionPath,+} from '@remotion/studio-codemods';diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex 83a234a136..865535ed43 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -1,2141 +1,42 @@-import type {- CallExpression,- Expression,- JSXAttribute,- JSXElement,- JSXExpressionContainer,- JSXFragment,- JSXSpreadAttribute,- ObjectExpression,- ObjectProperty,- StringLiteral,-} from '@babel/types';import {- getKeyframeInterpolationFunction,- getKeyframeInterpolationFunctionForSchemaField,- HOLD_KEYFRAME_EASING,- isKeyframeInterpolationFunction,- isSchemaFieldHoldOnly,- isSchemaFieldKeyframable,- LINEAR_KEYFRAME_EASING,- type KeyframeInterpolationFunction,-} from '@remotion/studio-shared';-import type {ExpressionKind, SpreadElementKind} from 'ast-types/lib/gen/kinds';-import * as recast from 'recast';-import type {- CanUpdateSequencePropStatus,- ExtrapolateType,- InteractivitySchema,- InteractivitySchemaField,- InterpolateOutputOption,- SequenceNodePath,- VideoConfigNumericExpression,- VideoConfigValues,-} from 'remotion';-import {getAstNodePath} from '../../helpers/get-ast-node-path';-import {parseKeyframeEasingExpression} from '../../helpers/parse-keyframe-easing-expression';-import {- parseVideoConfigNumericExpression,- updateVideoConfigNumericExpression,-} from '../../helpers/video-config-numeric-expression';-import {- getVideoConfigIdentifierValues,- type VideoConfigIdentifierValues,-} from '../../helpers/video-config-values';-import {- extractStaticValue,- findJsxElementAtNodePath,- findNodePathForJsxElement,- isStaticValue,-} from '../../preview-server/routes/can-update-sequence-props';+ updateEffectKeyframes as updateEffectKeyframesCodemod,+ updateSequenceKeyframes as updateSequenceKeyframesCodemod,+} from '@remotion/studio-codemods';import {formatFileContent} from '../format-file-content';-import {parseAst, serializeAst} from '../parse-ast';-import {- findEffectCallExpression,- findEffectsAttr,-} from '../update-effect-props/update-effect-props';-import {parseValueExpression} from '../update-nested-prop';-import {- ensureRemotionImports,- ensureUseCurrentFrameHook,- findEnclosingFunctionPath,-} from './ensure-imports-and-frame-hook';--const b = recast.types.builders;--const getObjectPropertyNameFromUpdateKey = (key: string): string => {- const dotIndex = key.indexOf('.');- return dotIndex === -1 ? key : key.slice(dotIndex + 1);-};--const lineStartsWithPropertyName = ({- line,- propertyName,-}: {- line: string;- propertyName: string;-}) => {- const trimmed = line.trimStart();- return (- trimmed.startsWith(`${propertyName}:`) ||- trimmed.startsWith(`'${propertyName}':`) ||- trimmed.startsWith(`"${propertyName}":`)- );-};--const getIndent = (line: string) => line.match(/^[ \t]*/)?.[0] ?? '';--const removeBlankLinesFromObjectsWithProperties = ({- input,- propertyNames,-}: {- input: string;- propertyNames: string[];-}) => {- if (propertyNames.length === 0) {- return input;- }-- const lines = input.split('\n');- const linesToRemove = new Set<number>();-- for (let i = 0; i < lines.length; i++) {- const propertyName = propertyNames.find((name) =>- lineStartsWithPropertyName({line: lines[i], propertyName: name}),- );- if (!propertyName) {- continue;- }-- const propertyIndentLength = getIndent(lines[i]).length;- let objectStart = i;- for (let j = i - 1; j >= 0; j--) {- const trimmed = lines[j].trim();- if (- trimmed.endsWith('{') &&- getIndent(lines[j]).length < propertyIndentLength- ) {- objectStart = j;- break;- }- }-- let objectEnd = i;- for (let j = i + 1; j < lines.length; j++) {- const trimmed = lines[j].trim();- if (- trimmed.startsWith('}') &&- getIndent(lines[j]).length < propertyIndentLength- ) {- objectEnd = j;- break;- }- }-- for (let j = objectStart + 1; j < objectEnd; j++) {- if (lines[j].trim() === '') {- linesToRemove.add(j);- }- }- }-- if (linesToRemove.size === 0) {- return input;- }-- return lines.filter((_, index) => !linesToRemove.has(index)).join('\n');-};--type KeyframeEasing = Extract<- CanUpdateSequencePropStatus,- {status: 'keyframed'}->['easing'][number];--export type KeyframeOperation =- | {- type: 'add';- frame: number;- value: unknown;- }- | {- type: 'remove';- frame: number;- valueWhenLastKeyframeDeleted: unknown | null;- }- | {- type: 'settings';- clamping:- | {- left: ExtrapolateType;- right: ExtrapolateType;- }- | undefined;- posterize: number | undefined;- output: InterpolateOutputOption | undefined;- }- | {- type: 'easing';- segmentIndex: number;- easing: KeyframeEasing;- }- | {- type: 'move';- moves: {- fromFrame: number;- toFrame: number;- }[];- };--export type SequenceKeyframeUpdate = {- key: string;- operation: KeyframeOperation;-};--export type EffectKeyframeUpdate = {- key: string;- operation: KeyframeOperation;-};--type WritableProp = {- expression: Expression;- setExpression: (expression: ExpressionKind) => void;- remove: () => void;-};--type MissingPropInitialValue = {- value: unknown;-};--type InterpolateKeyframe = {- frame: number;- frameExpression: ExpressionKind;- frameNumericExpression: VideoConfigNumericExpression;- originalFrame: number;- output: ExpressionKind;- value: unknown;-};--type InterpolateExpression = {- callee: ExpressionKind;- input: ExpressionKind | SpreadElementKind;- extraArgs: (ExpressionKind | SpreadElementKind)[];- keyframes: InterpolateKeyframe[];-};--const getSupportedCallArgument = (- arg: CallExpression['arguments'][number] | undefined,-): ExpressionKind | SpreadElementKind | null => {- if (- arg === undefined ||- arg.type === 'ArgumentPlaceholder' ||- arg.type === 'JSXNamespacedName'- ) {- return null;- }-- return arg as unknown as ExpressionKind | SpreadElementKind;-};--const getInterpolationExpression = (- node: Expression,- videoConfigValues: VideoConfigIdentifierValues,-): InterpolateExpression | null => {- if (node.type === 'TSAsExpression') {- return getInterpolationExpression(- node.expression as Expression,- videoConfigValues,- );- }-- if (- node.type !== 'CallExpression' ||- node.callee.type !== 'Identifier' ||- !isKeyframeInterpolationFunction(node.callee.name)- ) {- return null;- }-- const frameArg = getSupportedCallArgument(node.arguments[0]);- const inputArg = node.arguments[1];- const outputArg = node.arguments[2];- if (- !frameArg ||- !inputArg ||- !outputArg ||- inputArg.type !== 'ArrayExpression' ||- outputArg.type !== 'ArrayExpression' ||- inputArg.elements.length !== outputArg.elements.length- ) {- return null;- }-- const keyframes: InterpolateKeyframe[] = [];- for (let i = 0; i < inputArg.elements.length; i++) {- const inputElement = inputArg.elements[i];- const outputElement = outputArg.elements[i];- if (- !inputElement ||- !outputElement ||- inputElement.type === 'SpreadElement' ||- outputElement.type === 'SpreadElement'- ) {- return null;- }-- const frameExpression = parseVideoConfigNumericExpression({- node: inputElement,- videoConfigValues,- });- if (frameExpression === null || !isStaticValue(outputElement)) {- return null;- }-- keyframes.push({- frame: frameExpression.value,- frameExpression: inputElement as ExpressionKind,- frameNumericExpression: frameExpression,- originalFrame: frameExpression.value,- output: outputElement as ExpressionKind,- value: extractStaticValue(outputElement),- });- }-- if (keyframes.length === 0) {- return null;- }-- const extraArgs: (ExpressionKind | SpreadElementKind)[] = [];- for (const arg of node.arguments.slice(3)) {- const supportedArg = getSupportedCallArgument(arg);- if (!supportedArg) {- return null;- }-- extraArgs.push(supportedArg);- }-- return {- callee: node.callee as unknown as ExpressionKind,- input: frameArg,- extraArgs,- keyframes,- };-};--const getInterpolationCalleeForValues = ({- schema,- key,- staticValue,- newValue,-}: {- schema: InteractivitySchema | null;- key: string;- staticValue: unknown;- newValue: unknown;-}): ExpressionKind => {- return b.identifier(- getKeyframeInterpolationFunction({- schema,- key,- staticValue,- newValue,- }),- );-};--const createFrameExpression = (frame: number): ExpressionKind => {- return parseValueExpression(frame);-};--const createClampOptionsExpression = ({- defaultOutput,-}: {- defaultOutput: InterpolateOutputOption | null;-}): ExpressionKind => {- const properties = [- b.objectProperty(b.identifier('extrapolateLeft'), b.stringLiteral('clamp')),- b.objectProperty(- b.identifier('extrapolateRight'),- b.stringLiteral('clamp'),- ),- ];-- if (defaultOutput !== null && defaultOutput !== 'linear') {- properties.push(- b.objectProperty(b.identifier('output'), b.stringLiteral(defaultOutput)),- );- }-- return b.objectExpression(properties) as ExpressionKind;-};--const createEmptyOptionsExpression = (): ObjectExpression =>- b.objectExpression([]) as ObjectExpression;--const findObjectOptionProperty = (- options: ObjectExpression,- propertyName: string,-): {propIndex: number; prop: ObjectProperty | undefined} => {- const propIndex = options.properties.findIndex(- (prop) =>- prop.type === 'ObjectProperty' &&- !prop.computed &&- ((prop.key.type === 'Identifier' && prop.key.name === propertyName) ||- (prop.key.type === 'StringLiteral' && prop.key.value === propertyName)),- );-- return {- propIndex,- prop:- propIndex === -1- ? undefined- : (options.properties[propIndex] as ObjectProperty),- };-};--const setOptionsProperty = ({- options,- propertyName,- value,-}: {- options: ObjectExpression;- propertyName: string;- value: ExpressionKind | null;-}) => {- const {propIndex, prop} = findObjectOptionProperty(options, propertyName);- if (value === null) {- if (propIndex !== -1) {- options.properties.splice(propIndex, 1);- }-- return;- }-- if (prop) {- prop.value = value as ObjectProperty['value'];- return;- }-- options.properties.push(- b.objectProperty(b.identifier(propertyName), value) as ObjectProperty,- );-};--const isLinearEasing = (easing: KeyframeEasing) => easing.type === 'linear';--const getKeyframeEasing = (node: Expression): KeyframeEasing | null =>- parseKeyframeEasingExpression(node);--const getKeyframeEasingArray = ({- easingNode,- segmentCount,-}: {- easingNode: Expression;- segmentCount: number;-}): KeyframeEasing[] | null => {- if (segmentCount === 0) {- return [];- }-- if (easingNode.type === 'TSAsExpression') {- return getKeyframeEasingArray({- easingNode: easingNode.expression as Expression,- segmentCount,- });- }-- if (easingNode.type === 'ArrayExpression') {- if (easingNode.elements.length > segmentCount) {- return null;- }-- const parsed = easingNode.elements.map((element) => {- if (!element || element.type === 'SpreadElement') {- return null;- }-- return getKeyframeEasing(element as Expression);- });-- if (parsed.some((value) => value === null)) {- return null;- }-- const easingArray = parsed as KeyframeEasing[];- while (easingArray.length < segmentCount) {- easingArray.push(LINEAR_KEYFRAME_EASING);- }-- return easingArray;- }-- const easing = getKeyframeEasing(easingNode);- if (!easing) {- return null;- }-- return new Array(segmentCount).fill(easing);-};--const getExistingEasingArray = ({- options,- segmentCount,-}: {- options: ObjectExpression;- segmentCount: number;-}): KeyframeEasing[] => {- const {prop} = findObjectOptionProperty(options, 'easing');- if (!prop) {- return Array.from({length: segmentCount}, () => ({type: 'linear'}));- }-- const easing = getKeyframeEasingArray({- easingNode: prop.value as Expression,- segmentCount,- });- if (!easing) {- throw new Error('Cannot update easing: easing must be inline');- }-- return easing;-};--const getExistingEasingArrayOrNull = ({- options,- segmentCount,-}: {- options: ObjectExpression;- segmentCount: number;-}): KeyframeEasing[] | null => {- const {prop} = findObjectOptionProperty(options, 'easing');- if (!prop) {- return null;- }-- return getExistingEasingArray({options, segmentCount});-};--const createEasingExpression = (easing: KeyframeEasing): ExpressionKind => {- switch (easing.type) {- case 'linear':- return b.memberExpression(- b.identifier('Easing'),- b.identifier('linear'),- ) as ExpressionKind;- case 'step1':- return b.memberExpression(- b.identifier('Easing'),- b.identifier('step1'),- ) as ExpressionKind;- case 'spring':- return b.callExpression(- b.memberExpression(b.identifier('Easing'), b.identifier('spring')),- [- b.objectExpression([- b.objectProperty(- b.identifier('damping'),- parseValueExpression(easing.damping),- ),- b.objectProperty(- b.identifier('mass'),- parseValueExpression(easing.mass),- ),- b.objectProperty(- b.identifier('stiffness'),- parseValueExpression(easing.stiffness),- ),- ...(easing.allowTail === null- ? []- : [- b.objectProperty(- b.identifier('allowTail'),- b.booleanLiteral(easing.allowTail),- ),- ]),- ...(easing.durationRestThreshold === null- ? []- : [- b.objectProperty(- b.identifier('durationRestThreshold'),- parseValueExpression(easing.durationRestThreshold),- ),- ]),- b.objectProperty(- b.identifier('overshootClamping'),- b.booleanLiteral(easing.overshootClamping),- ),- ]),- ] as never,- ) as ExpressionKind;- case 'bezier':- return b.callExpression(- b.memberExpression(b.identifier('Easing'), b.identifier('bezier')),- [easing.x1, easing.y1, easing.x2, easing.y2].map((value) =>- parseValueExpression(value),- ) as never,- ) as ExpressionKind;- default:- throw new Error(- `Unsupported easing: ${JSON.stringify(easing satisfies never)}`,- );- }-};--const createEasingArrayExpression = (- easing: KeyframeEasing[],-): ExpressionKind =>- b.arrayExpression(- easing.map((easingValue) => createEasingExpression(easingValue)) as never,- ) as ExpressionKind;--const setEasingOption = ({- options,- easing,-}: {- options: ObjectExpression;- easing: KeyframeEasing[];-}): boolean => {- const hasNonLinearEasing = easing.some(- (easingValue) => !isLinearEasing(easingValue),- );- setOptionsProperty({- options,- propertyName: 'easing',- value: hasNonLinearEasing ? createEasingArrayExpression(easing) : null,- });- return hasNonLinearEasing;-};--const getExtraArgsWithOptions = ({- extraArgs,- options,-}: {- extraArgs: (ExpressionKind | SpreadElementKind)[];- options: ObjectExpression;-}): (ExpressionKind | SpreadElementKind)[] => {- return options.properties.length === 0- ? extraArgs.slice(1)- : [options as ExpressionKind, ...extraArgs.slice(1)];-};--const getInlineOptionsFromExtraArgs = (- extraArgs: (ExpressionKind | SpreadElementKind)[],-): ObjectExpression | null => {- const existingOptions = extraArgs[0];- if (!existingOptions || existingOptions.type !== 'ObjectExpression') {- return null;- }-- return existingOptions as ObjectExpression;-};--const normalizeEasingAfterAddingKeyframe = ({- extraArgs,- previousSegmentCount,- nextSegmentCount,- insertedKeyframeIndex,- nextKeyframeCount,- defaultEasing,-}: {- extraArgs: (ExpressionKind | SpreadElementKind)[];- previousSegmentCount: number;- nextSegmentCount: number;- insertedKeyframeIndex: number;- nextKeyframeCount: number;- defaultEasing: KeyframeEasing;-}): {- extraArgs: (ExpressionKind | SpreadElementKind)[];- needsEasingImport: boolean;-} => {- const options =- getInlineOptionsFromExtraArgs(extraArgs) ??- (extraArgs.length === 0 ? createEmptyOptionsExpression() : null);- if (!options) {- return {extraArgs, needsEasingImport: false};- }-- const easing =- getExistingEasingArrayOrNull({- options,- segmentCount: previousSegmentCount,- }) ?? Array.from({length: previousSegmentCount}, () => defaultEasing);-- if (easing.length < nextSegmentCount) {- const isSplittingExistingSegment =- insertedKeyframeIndex > 0 &&- insertedKeyframeIndex < nextKeyframeCount - 1;- const easingIndexToDuplicate =- isSplittingExistingSegment && easing.length > 0- ? Math.min(insertedKeyframeIndex - 1, easing.length - 1)- : null;- easing.splice(- insertedKeyframeIndex,- 0,- easingIndexToDuplicate === null- ? defaultEasing- : easing[easingIndexToDuplicate],- );- }-- while (easing.length < nextSegmentCount) {- easing.push(defaultEasing);- }-- const needsEasingImport = setEasingOption({options, easing});- return {- extraArgs: getExtraArgsWithOptions({extraArgs, options}),- needsEasingImport,- };-};--const getEasingIndexToRemove = ({- removedKeyframeIndex,- keyframeCountBeforeRemoval,-}: {- removedKeyframeIndex: number;- keyframeCountBeforeRemoval: number;-}) => {- if (removedKeyframeIndex === 0) {- return 0;- }-- if (removedKeyframeIndex === keyframeCountBeforeRemoval - 1) {- return removedKeyframeIndex - 1;- }-- return removedKeyframeIndex;-};--const normalizeEasingAfterRemovingKeyframe = ({- extraArgs,- previousSegmentCount,- nextSegmentCount,- removedKeyframeIndex,-}: {- extraArgs: (ExpressionKind | SpreadElementKind)[];- previousSegmentCount: number;- nextSegmentCount: number;- removedKeyframeIndex: number;-}): {- extraArgs: (ExpressionKind | SpreadElementKind)[];- needsEasingImport: boolean;-} => {- const options = getInlineOptionsFromExtraArgs(extraArgs);- if (!options) {- return {extraArgs, needsEasingImport: false};- }-- const easing = getExistingEasingArrayOrNull({- options,- segmentCount: previousSegmentCount,- });- if (easing === null) {- return {extraArgs, needsEasingImport: false};- }-- if (easing.length > 0) {- const easingIndexToRemove = getEasingIndexToRemove({- removedKeyframeIndex,- keyframeCountBeforeRemoval: previousSegmentCount + 1,- });- easing.splice(easingIndexToRemove, 1);- }-- while (easing.length > nextSegmentCount) {- easing.pop();- }-- while (easing.length < nextSegmentCount) {- easing.push(LINEAR_KEYFRAME_EASING);- }-- return {- extraArgs: getExtraArgsWithOptions({extraArgs, options}),- needsEasingImport: setEasingOption({options, easing}),- };-};--const normalizeEasingAfterRemovingKeyframes = ({- extraArgs,- previousSegmentCount,- nextSegmentCount,- removedKeyframeIndexes,-}: {- extraArgs: (ExpressionKind | SpreadElementKind)[];- previousSegmentCount: number;- nextSegmentCount: number;- removedKeyframeIndexes: number[];-}): {- extraArgs: (ExpressionKind | SpreadElementKind)[];- needsEasingImport: boolean;-} => {- const options = getInlineOptionsFromExtraArgs(extraArgs);- if (!options) {- return {extraArgs, needsEasingImport: false};- }-- const easing = getExistingEasingArrayOrNull({- options,- segmentCount: previousSegmentCount,- });- if (easing === null) {- return {extraArgs, needsEasingImport: false};- }-- for (const {removedKeyframeIndex, keyframeCountBeforeRemoval} of [- ...removedKeyframeIndexes,- ]- .sort((first, second) => second - first)- .map((keyframeIndex, index) => ({- removedKeyframeIndex: keyframeIndex,- keyframeCountBeforeRemoval: previousSegmentCount + 1 - index,- }))) {- if (easing.length === 0) {- break;- }-- const easingIndexToRemove = getEasingIndexToRemove({- removedKeyframeIndex,- keyframeCountBeforeRemoval,- });- easing.splice(easingIndexToRemove, 1);- }-- while (easing.length > nextSegmentCount) {- easing.pop();- }-- while (easing.length < nextSegmentCount) {- easing.push(LINEAR_KEYFRAME_EASING);- }-- return {- extraArgs: getExtraArgsWithOptions({extraArgs, options}),- needsEasingImport: setEasingOption({options, easing}),- };-};--const validatePosterize = (posterize: number | undefined) => {- if (posterize === undefined) {- return;- }-- if (!Number.isFinite(posterize) || posterize <= 0) {- throw new Error('Cannot update keyframe settings: posterize must be > 0');- }-};--const validateOutput = (output: InterpolateOutputOption | undefined) => {- if (- output === undefined ||- output === 'linear' ||- output === 'perceptual-scale'- ) {- return;- }-- throw new Error(- 'Cannot update keyframe settings: output must be "linear" or "perceptual-scale"',- );-};--const updateKeyframeSettings = ({- expression,- clamping,- posterize,- output,- videoConfigValues,-}: {- expression: Expression;- clamping:- | {- left: ExtrapolateType;- right: ExtrapolateType;- }- | undefined;- posterize: number | undefined;- output: InterpolateOutputOption | undefined;- videoConfigValues: VideoConfigIdentifierValues;-}): ExpressionKind => {- validatePosterize(posterize);- validateOutput(output);-- const existing = getInterpolationExpression(expression, videoConfigValues);- if (!existing) {- throw new Error('Cannot update keyframe settings on non-keyframed value');- }-- const calleeName =- existing.callee.type === 'Identifier' ? existing.callee.name : null;- const isColorInterpolation = calleeName === 'interpolateColors';- const extraArgs = [...existing.extraArgs];- const existingOptions = extraArgs[0];- if (existingOptions && existingOptions.type !== 'ObjectExpression') {- throw new Error('Cannot update keyframe settings: options must be inline');- }-- const options =- existingOptions?.type === 'ObjectExpression'- ? (existingOptions as ObjectExpression)- : createEmptyOptionsExpression();-- if (isColorInterpolation) {- setOptionsProperty({options, propertyName: 'extrapolateLeft', value: null});- setOptionsProperty({- options,- propertyName: 'extrapolateRight',- value: null,- });- setOptionsProperty({options, propertyName: 'output', value: null});- } else if (clamping) {- setOptionsProperty({- options,- propertyName: 'extrapolateLeft',- value: b.stringLiteral(clamping.left),- });- setOptionsProperty({- options,- propertyName: 'extrapolateRight',- value: b.stringLiteral(clamping.right),- });- }-- if (!isColorInterpolation && output !== undefined) {- setOptionsProperty({- options,- propertyName: 'output',- value: output === 'linear' ? null : b.stringLiteral(output),- });- }-- setOptionsProperty({- options,- propertyName: 'posterize',- value: posterize === undefined ? null : b.numericLiteral(posterize),- });-- const nextExtraArgs =- options.properties.length === 0- ? extraArgs.slice(1)- : [options as ExpressionKind, ...extraArgs.slice(1)];-- return createInterpolateExpression({- callee: existing.callee,- input: existing.input,- extraArgs: nextExtraArgs,- keyframes: existing.keyframes,- });-};--const updateKeyframeEasing = ({- expression,- segmentIndex,- easing,- videoConfigValues,-}: {- expression: Expression;- segmentIndex: number;- easing: KeyframeEasing;- videoConfigValues: VideoConfigIdentifierValues;-}): {expression: ExpressionKind; needsEasingImport: boolean} => {- const existing = getInterpolationExpression(expression, videoConfigValues);- if (!existing) {- throw new Error('Cannot update easing on non-keyframed value');- }-- const segmentCount = Math.max(0, existing.keyframes.length - 1);- if (- !Number.isInteger(segmentIndex) ||- segmentIndex < 0 ||- segmentIndex >= segmentCount- ) {- throw new Error('Cannot update easing: segment index out of range');- }-- const extraArgs = [...existing.extraArgs];- const existingOptions = extraArgs[0];- if (existingOptions && existingOptions.type !== 'ObjectExpression') {- throw new Error('Cannot update easing: options must be inline');- }-- const options =- existingOptions?.type === 'ObjectExpression'- ? (existingOptions as ObjectExpression)- : createEmptyOptionsExpression();- const nextEasing = getExistingEasingArray({options, segmentCount});- nextEasing[segmentIndex] = easing;- const hasNonLinearEasing = nextEasing.some(- (easingValue) => !isLinearEasing(easingValue),- );-- setOptionsProperty({- options,- propertyName: 'easing',- value: hasNonLinearEasing ? createEasingArrayExpression(nextEasing) : null,- });-- const nextExtraArgs =- options.properties.length === 0- ? extraArgs.slice(1)- : [options as ExpressionKind, ...extraArgs.slice(1)];-- return {- expression: createInterpolateExpression({- callee: existing.callee,- input: existing.input,- extraArgs: nextExtraArgs,- keyframes: existing.keyframes,- }),- needsEasingImport: hasNonLinearEasing,- };-};-const createInterpolateExpression = ({- callee,- input,- extraArgs,- keyframes,-}: {- callee: ExpressionKind;- input: ExpressionKind | SpreadElementKind;- extraArgs: (ExpressionKind | SpreadElementKind)[];- keyframes: InterpolateKeyframe[];-}): ExpressionKind => {- const sortedKeyframes = [...keyframes].sort(- (first, second) => first.frame - second.frame,- );- return b.callExpression(callee, [- input,- b.arrayExpression(- sortedKeyframes.map((keyframe) =>- keyframe.frame === keyframe.originalFrame- ? keyframe.frameExpression- : updateVideoConfigNumericExpression({- expression: keyframe.frameNumericExpression,- value: keyframe.frame,- }),- ),- ),- b.arrayExpression(sortedKeyframes.map((keyframe) => keyframe.output)),- ...extraArgs,- ]) as ExpressionKind;-};--export type IntroducedKeyframeIdentifiers = {- calleeName: KeyframeInterpolationFunction | null;- needsFrameHook: boolean;- needsEasingImport: boolean;-};--const noIntroducedIdentifiers: IntroducedKeyframeIdentifiers = {- calleeName: null,- needsFrameHook: false,- needsEasingImport: false,-};--const addKeyframe = ({- expression,- key,- frame,- value,- schema,- videoConfigValues,-}: {- expression: Expression;- key: string;- frame: number;- value: unknown;- schema: InteractivitySchema | null;- videoConfigValues: VideoConfigIdentifierValues;-}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {- if (!isSchemaFieldKeyframable({schema, key})) {- throw new Error(`Cannot add keyframe: "${key}" is not keyframable`);- }-- const existing = getInterpolationExpression(expression, videoConfigValues);- const newOutput = parseValueExpression(value);-- if (existing) {- const defaultEasing = isSchemaFieldHoldOnly({schema, key})- ? HOLD_KEYFRAME_EASING- : LINEAR_KEYFRAME_EASING;- const existingCalleeName =- existing.callee.type === 'Identifier'- ? (existing.callee.name as KeyframeInterpolationFunction)- : 'interpolate';- const schemaCalleeName = getKeyframeInterpolationFunctionForSchemaField({- schema,- key,- });- const nextCalleeName = schemaCalleeName ?? existingCalleeName;- const existingIndex = existing.keyframes.findIndex(- (keyframe) => keyframe.frame === frame,- );- const nextKeyframes: InterpolateKeyframe[] =- existingIndex === -1- ? [- ...existing.keyframes,- {- frame,- frameExpression: createFrameExpression(frame),- frameNumericExpression: {type: 'literal', value: frame},- originalFrame: frame,- output: newOutput,- value,- },- ]- : existing.keyframes.map((keyframe, index) =>- index === existingIndex- ? {...keyframe, output: newOutput, value}- : keyframe,- );- const normalizedEasing =- existingIndex === -1- ? normalizeEasingAfterAddingKeyframe({- extraArgs: existing.extraArgs,- previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),- nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),- insertedKeyframeIndex: [...nextKeyframes]- .sort((first, second) => first.frame - second.frame)- .findIndex((keyframe) => keyframe.frame === frame),- nextKeyframeCount: nextKeyframes.length,- defaultEasing,- })- : {extraArgs: existing.extraArgs, needsEasingImport: false};-- return {- expression: createInterpolateExpression({- callee: b.identifier(nextCalleeName),- input: existing.input,- extraArgs: normalizedEasing.extraArgs,- keyframes: nextKeyframes,- }),- introduced: {- calleeName:- schemaCalleeName && schemaCalleeName !== existingCalleeName- ? schemaCalleeName- : null,- needsFrameHook: false,- needsEasingImport: normalizedEasing.needsEasingImport,- },- };- }-- const staticNumericExpression = parseVideoConfigNumericExpression({- node: expression,- videoConfigValues,- });- if (!isStaticValue(expression) && staticNumericExpression === null) {- throw new Error('Cannot add keyframe to computed expression');- }-- const staticValue =- staticNumericExpression?.value ?? extractStaticValue(expression);- const keyframes: InterpolateKeyframe[] = [- {- frame,- frameExpression: createFrameExpression(frame),- frameNumericExpression: {type: 'literal', value: frame},- originalFrame: frame,- output: newOutput,- value,- },- ];-- const callee = getInterpolationCalleeForValues({- schema,- key,- staticValue,- newValue: value,- });- const extraArgs =- callee.type === 'Identifier' && callee.name === 'interpolateColors'- ? []- : [- createClampOptionsExpression({- defaultOutput: getDefaultKeyframeOutput({schema, key}),- }),- ];-- return {- expression: createInterpolateExpression({- callee,- input: b.identifier('frame'),- extraArgs,- keyframes,- }),- introduced: {- calleeName:- callee.type === 'Identifier'- ? (callee.name as KeyframeInterpolationFunction)- : null,- needsFrameHook: true,- needsEasingImport: false,- },- };-};--const removeKeyframe = ({- expression,- frame,- videoConfigValues,- valueWhenLastKeyframeDeleted,-}: {- expression: Expression;- frame: number;- videoConfigValues: VideoConfigIdentifierValues;- valueWhenLastKeyframeDeleted: unknown | null;-}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {- const existing = getInterpolationExpression(expression, videoConfigValues);- if (!existing) {- throw new Error('Cannot remove keyframe from non-interpolated expression');- }-- const keyframeIndex = existing.keyframes.findIndex(- (keyframe) => keyframe.frame === frame,- );- if (keyframeIndex === -1) {- throw new Error(`Cannot remove keyframe at frame ${frame}: not found`);- }-- const nextKeyframes = existing.keyframes.filter(- (_keyframe, index) => index !== keyframeIndex,- );-- if (nextKeyframes.length === 0) {- return {- expression:- valueWhenLastKeyframeDeleted === null- ? existing.keyframes[keyframeIndex].output- : parseValueExpression(valueWhenLastKeyframeDeleted),- introduced: noIntroducedIdentifiers,- };- }-- const normalizedEasing = normalizeEasingAfterRemovingKeyframe({- extraArgs: existing.extraArgs,- previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),- nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),- removedKeyframeIndex: keyframeIndex,- });-- return {- expression: createInterpolateExpression({- callee: existing.callee,- input: existing.input,- extraArgs: normalizedEasing.extraArgs,- keyframes: nextKeyframes,- }),- introduced: {- ...noIntroducedIdentifiers,- needsEasingImport: normalizedEasing.needsEasingImport,- },- };-};--const moveKeyframes = ({- expression,- moves,- videoConfigValues,-}: {- expression: Expression;- moves: {- fromFrame: number;- toFrame: number;- }[];- videoConfigValues: VideoConfigIdentifierValues;-}): ExpressionKind => {- const existing = getInterpolationExpression(expression, videoConfigValues);- if (!existing) {- throw new Error('Cannot move keyframe in non-interpolated expression');- }-- const moveMap = new Map<number, number>();- for (const move of moves) {- if (move.fromFrame === move.toFrame) {- continue;- }-- if (moveMap.has(move.fromFrame)) {- throw new Error(`Cannot move keyframe at frame ${move.fromFrame} twice`);- }-- moveMap.set(move.fromFrame, move.toFrame);- }-- if (moveMap.size === 0) {- return expression as ExpressionKind;- }-- const frames = new Set(existing.keyframes.map((keyframe) => keyframe.frame));- for (const fromFrame of moveMap.keys()) {- if (!frames.has(fromFrame)) {- throw new Error(`Cannot move keyframe at frame ${fromFrame}: not found`);- }- }-- const movedFromFrames = new Set(moveMap.keys());- const movedToFrames = new Set(moveMap.values());- const removedKeyframeIndexes: number[] = [];- const nextKeyframes = existing.keyframes.flatMap((keyframe, index) => {- const movedFrame = moveMap.get(keyframe.frame);- if (movedFrame !== undefined) {- return [{...keyframe, frame: movedFrame}];- }-- if (- movedToFrames.has(keyframe.frame) &&- !movedFromFrames.has(keyframe.frame)- ) {- removedKeyframeIndexes.push(index);- return [];- }-- return [keyframe];- });-- const nextFrames = new Set<number>();- for (const keyframe of nextKeyframes) {- if (nextFrames.has(keyframe.frame)) {- throw new Error(- `Cannot move keyframe to frame ${keyframe.frame}: frame already exists`,- );- }-- nextFrames.add(keyframe.frame);- }-- const normalizedEasing = normalizeEasingAfterRemovingKeyframes({- extraArgs: existing.extraArgs,- previousSegmentCount: Math.max(existing.keyframes.length - 1, 0),- nextSegmentCount: Math.max(nextKeyframes.length - 1, 0),- removedKeyframeIndexes,- });-- return createInterpolateExpression({- callee: existing.callee,- input: existing.input,- extraArgs: normalizedEasing.extraArgs,- keyframes: nextKeyframes,- });-};--const applyKeyframeOperation = ({- expression,- key,- operation,- schema,- videoConfigValues,-}: {- expression: Expression;- key: string;- operation: KeyframeOperation;- schema: InteractivitySchema | null;- videoConfigValues: VideoConfigIdentifierValues;-}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {- if (operation.type === 'add') {- return addKeyframe({- expression,- key,- frame: operation.frame,- value: operation.value,- schema,- videoConfigValues,- });- }-- if (operation.type === 'settings') {- return {- expression: updateKeyframeSettings({- expression,- clamping: operation.clamping,- posterize: operation.posterize,- output: operation.output,- videoConfigValues,- }),- introduced: noIntroducedIdentifiers,- };- }-- if (operation.type === 'easing') {- if (- isSchemaFieldHoldOnly({schema, key}) &&- operation.easing.type !== 'step1'- ) {- throw new Error(- `Cannot update easing: "${key}" only supports Easing.step1`,- );- }-- const updated = updateKeyframeEasing({- expression,- segmentIndex: operation.segmentIndex,- easing: operation.easing,- videoConfigValues,- });- return {- expression: updated.expression,- introduced: {- ...noIntroducedIdentifiers,- needsEasingImport: updated.needsEasingImport,- },- };- }-- if (operation.type === 'move') {- return {- expression: moveKeyframes({- expression,- moves: operation.moves,- videoConfigValues,- }),- introduced: noIntroducedIdentifiers,- };- }-- return removeKeyframe({- expression,- frame: operation.frame,- videoConfigValues,- valueWhenLastKeyframeDeleted: operation.valueWhenLastKeyframeDeleted,- });-};--const getExpressionFromJsxAttribute = (- attr: JSXAttribute,-): Expression | null => {- if (!attr.value) {- return b.booleanLiteral(true) as Expression;- }-- if (attr.value.type === 'StringLiteral') {- return attr.value as unknown as Expression;- }-- if (attr.value.type !== 'JSXExpressionContainer') {- return null;- }-- const {expression} = attr.value;- if (expression.type === 'JSXEmptyExpression') {- return null;- }-- return expression as Expression;-};--const findJsxAttribute = (- attributes: (JSXAttribute | JSXSpreadAttribute)[],- name: string,-): {attrIndex: number; attr: JSXAttribute | undefined} => {- const attrIndex = attributes.findIndex((candidate) => {- if (candidate.type === 'JSXSpreadAttribute') {- return false;- }-- if (candidate.name.type === 'JSXNamespacedName') {- return false;- }-- return candidate.name.name === name;- });-- const foundAttr = attrIndex === -1 ? undefined : attributes[attrIndex];- return {- attrIndex,- attr:- foundAttr && foundAttr.type === 'JSXAttribute'- ? (foundAttr as JSXAttribute)- : undefined,- };-};--const findObjectProperty = (- objExpr: ObjectExpression,- propertyName: string,-): {propIndex: number; prop: ObjectProperty | undefined} => {- const propIndex = objExpr.properties.findIndex(- (prop) =>- prop.type === 'ObjectProperty' &&- ((prop.key.type === 'Identifier' && prop.key.name === propertyName) ||- (prop.key.type === 'StringLiteral' && prop.key.value === propertyName)),- );-- return {- propIndex,- prop:- propIndex === -1- ? undefined- : (objExpr.properties[propIndex] as ObjectProperty),- };-};--const findFieldInSchema = (- schema: InteractivitySchema,- key: string,-): InteractivitySchemaField | undefined => {- if (key in schema) {- return schema[key];- }-- for (const field of Object.values(schema)) {- if (field.type !== 'enum') {- continue;- }-- for (const variant of Object.values(field.variants)) {- const found = findFieldInSchema(variant, key);- if (found) {- return found;- }- }- }-- return undefined;-};--const getDefaultKeyframeOutput = ({- schema,- key,-}: {- schema: InteractivitySchema | null;- key: string;-}): InterpolateOutputOption | null => {- const field = schema ? findFieldInSchema(schema, key) : undefined;- if (- (field?.type === 'number' || field?.type === 'scale') &&- field.defaultKeyframeOutput !== undefined- ) {- return field.defaultKeyframeOutput;- }-- return key === 'style.scale' ? 'perceptual-scale' : null;-};--const getInitialValueForMissingProp = ({- schema,- key,- newValue,-}: {- schema: InteractivitySchema | null;- key: string;- newValue: unknown;-}): unknown => {- const field = schema ? findFieldInSchema(schema, key) : undefined;- if (field && field.type !== 'hidden' && field.default !== undefined) {- return field.default;- }-- return newValue;-};--const shouldRemovePropAfterKeyframeOperation = ({- expression,- key,- operation,- schema,- videoConfigValues,-}: {- expression: Expression;- key: string;- operation: KeyframeOperation;- schema: InteractivitySchema | null;- videoConfigValues: VideoConfigIdentifierValues;-}) => {- if (operation.type !== 'remove' || !schema) {- return false;- }-- const existing = getInterpolationExpression(expression, videoConfigValues);- if (!existing || existing.keyframes.length !== 1) {- return false;- }-- const field = findFieldInSchema(schema, key);- if (!field || field.type === 'hidden' || field.default === undefined) {- return false;- }-- const valueAfterRemoval =- operation.valueWhenLastKeyframeDeleted === null- ? existing.keyframes[0].value- : operation.valueWhenLastKeyframeDeleted;-- return JSON.stringify(valueAfterRemoval) === JSON.stringify(field.default);-};--const getObjectExpression = (attr: JSXAttribute): ObjectExpression | null => {- if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {- return null;- }-- if (attr.value.expression.type !== 'ObjectExpression') {- return null;- }-- return attr.value.expression as ObjectExpression;-};--const createJsxExpressionAttribute = (- key: string,- expression: ExpressionKind,-): JSXAttribute => {- return b.jsxAttribute(- b.jsxIdentifier(key),- b.jsxExpressionContainer(expression),- ) as JSXAttribute;-};--const createObjectProperty = (key: string, value: ExpressionKind) =>- b.objectProperty(b.identifier(key), value);--const createObjectExpressionAttribute = ({- parentKey,- childKey,- expression,-}: {- parentKey: string;- childKey: string;- expression: ExpressionKind;-}): JSXAttribute => {- return createJsxExpressionAttribute(- parentKey,- b.objectExpression([- createObjectProperty(childKey, expression),- ]) as ExpressionKind,- );-};--const createMissingPropExpression = (- missingPropInitialValue: MissingPropInitialValue,-): Expression => {- return parseValueExpression(missingPropInitialValue.value) as Expression;-};--const getSequenceWritableProp = ({- attributes,- key,- missingPropInitialValue,-}: {- attributes: (JSXAttribute | JSXSpreadAttribute)[];- key: string;- missingPropInitialValue: MissingPropInitialValue | null;-}): WritableProp => {- const dotIndex = key.indexOf('.');- if (dotIndex === -1) {- const {attrIndex, attr: topLevelAttr} = findJsxAttribute(attributes, key);- if (!topLevelAttr) {- if (missingPropInitialValue) {- return {- expression: createMissingPropExpression(missingPropInitialValue),- setExpression: (nextExpression) => {- attributes.push(createJsxExpressionAttribute(key, nextExpression));- },- remove: () => undefined,- };- }-- throw new Error(`Cannot update keyframes: "${key}" is not set`);- }-- const expression = getExpressionFromJsxAttribute(topLevelAttr);- if (!expression) {- throw new Error(`Cannot update keyframes: "${key}" is computed`);- }-- return {- expression,- setExpression: (nextExpression) => {- topLevelAttr.value = b.jsxExpressionContainer(nextExpression) as- | JSXElement- | JSXExpressionContainer- | JSXFragment- | StringLiteral- | null- | undefined;- },- remove: () => {- attributes.splice(attrIndex, 1);- },- };- }-- const parentKey = key.slice(0, dotIndex);- const childKey = key.slice(dotIndex + 1);- const {attrIndex: parentAttrIndex, attr: parentAttr} = findJsxAttribute(- attributes,- parentKey,- );- if (!parentAttr) {- if (missingPropInitialValue) {- return {- expression: createMissingPropExpression(missingPropInitialValue),- setExpression: (nextExpression) => {- attributes.push(- createObjectExpressionAttribute({- parentKey,- childKey,- expression: nextExpression,- }),- );- },- remove: () => undefined,- };- }-- throw new Error(`Cannot update keyframes: "${parentKey}" is not set`);- }-- const objExpr = getObjectExpression(parentAttr);- if (!objExpr) {- throw new Error(`Cannot update keyframes: "${parentKey}" is computed`);- }-- const {propIndex, prop} = findObjectProperty(objExpr, childKey);- if (!prop) {- if (missingPropInitialValue) {- return {- expression: createMissingPropExpression(missingPropInitialValue),- setExpression: (nextExpression) => {- objExpr.properties.push(- createObjectProperty(childKey, nextExpression) as ObjectProperty,- );- },- remove: () => undefined,- };- }-- throw new Error(`Cannot update keyframes: "${key}" is not set`);- }-- return {- expression: prop.value as Expression,- setExpression: (nextExpression) => {- prop.value = nextExpression as ObjectProperty['value'];- },- remove: () => {- objExpr.properties.splice(propIndex, 1);- if (objExpr.properties.length === 0) {- attributes.splice(parentAttrIndex, 1);- }- },- };-};--const getEffectWritableProp = ({- objExpr,- key,- missingPropInitialValue,-}: {- objExpr: ObjectExpression;- key: string;- missingPropInitialValue: MissingPropInitialValue | null;-}): WritableProp => {- const {propIndex, prop} = findObjectProperty(objExpr, key);- if (!prop) {- if (missingPropInitialValue) {- return {- expression: createMissingPropExpression(missingPropInitialValue),- setExpression: (nextExpression) => {- objExpr.properties.push(- createObjectProperty(key, nextExpression) as ObjectProperty,- );- },- remove: () => undefined,- };- }-- throw new Error(`Cannot update keyframes: "${key}" is not set`);- }-- return {- expression: prop.value as Expression,- setExpression: (nextExpression) => {- prop.value = nextExpression as ObjectProperty['value'];- },- remove: () => {- objExpr.properties.splice(propIndex, 1);- },- };-};--const getEffectPropsObjectExpression = (- call: CallExpression,-): ObjectExpression => {- if (call.arguments.length === 0) {- const objExpr = b.objectExpression([]) as ObjectExpression;- call.arguments.push(objExpr);- return objExpr;- }-- if (call.arguments[0].type !== 'ObjectExpression') {- throw new Error('Cannot update effect keyframe: computed');- }-- return call.arguments[0] as ObjectExpression;-};--export const updateSequenceKeyframesAst = ({- input,- nodePath,- updates,- schema,- videoConfigValues,-}: {- input: string;- nodePath: SequenceNodePath;- updates: SequenceKeyframeUpdate[];- schema?: InteractivitySchema;- videoConfigValues: VideoConfigValues | null;-}): {- serialized: string;- oldValueStrings: string[];- newValueStrings: string[];- logLine: number;- updatedNodePath: SequenceNodePath;-} => {- const ast = parseAst(input);- const videoConfigIdentifierValues = getVideoConfigIdentifierValues({- ast,- videoConfigValues,- });- const jsxPath = getAstNodePath(ast, nodePath);- const node = findJsxElementAtNodePath(ast, nodePath);- if (!node || !jsxPath) {- throw new Error(- 'Could not find a JSX element at the specified location to update keyframes',- );- }-- if (!node.attributes) {- node.attributes = [];- }-- const requiredImports = new Set<string>();- let needsFrameHook = false;-- const oldValueStrings: string[] = [];- const newValueStrings: string[] = [];- for (const update of updates) {- const prop = getSequenceWritableProp({- attributes: node.attributes,- key: update.key,- missingPropInitialValue:- update.operation.type === 'add'- ? {- value: getInitialValueForMissingProp({- schema: schema ?? null,- key: update.key,- newValue: update.operation.value,- }),- }- : null,- });- oldValueStrings.push(recast.print(prop.expression).code);- const {expression: nextExpression, introduced} = applyKeyframeOperation({- expression: prop.expression,- key: update.key,- operation: update.operation,- schema: schema ?? null,- videoConfigValues: videoConfigIdentifierValues,- });- newValueStrings.push(recast.print(nextExpression).code);- if (- shouldRemovePropAfterKeyframeOperation({- expression: prop.expression,- key: update.key,- operation: update.operation,- schema: schema ?? null,- videoConfigValues: videoConfigIdentifierValues,- })- ) {- prop.remove();- } else {- prop.setExpression(nextExpression);- }-- if (introduced.calleeName) {- requiredImports.add(introduced.calleeName);- }-- if (introduced.needsFrameHook) {- requiredImports.add('useCurrentFrame');- needsFrameHook = true;- }-- if (introduced.needsEasingImport) {- requiredImports.add('Easing');- }- }-- if (needsFrameHook) {- const fnPath = findEnclosingFunctionPath(jsxPath);- if (fnPath) {- ensureUseCurrentFrameHook(fnPath);- }- }-- ensureRemotionImports(ast, requiredImports);-- const updatedNodePath = findNodePathForJsxElement(ast, node);- if (!updatedNodePath) {- throw new Error(- 'Could not find updated JSX element location after updating keyframes',- );- }-- return {- serialized: serializeAst(ast),- oldValueStrings,- newValueStrings,- logLine: node.loc?.start.line ?? 1,- updatedNodePath,- };-};--export const updateSequenceKeyframes = async ({- input,- nodePath,- updates,- schema,+export {+ type EffectKeyframeUpdate,+ type IntroducedKeyframeIdentifiers,+ type KeyframeOperation,+ type SequenceKeyframeUpdate,+ updateEffectKeyframesAst,+ updateSequenceKeyframesAst,+} from '@remotion/studio-codemods';++type UpdateSequenceKeyframesInput = Omit<+ Parameters<typeof updateSequenceKeyframesCodemod>[0],+ 'formatFile'+>;++type UpdateEffectKeyframesInput = Omit<+ Parameters<typeof updateEffectKeyframesCodemod>[0],+ 'formatFile'+>;++const formatKeyframesFile = ({+ contents,prettierConfigOverride,- videoConfigValues,}: {- input: string;- nodePath: SequenceNodePath;- updates: SequenceKeyframeUpdate[];- schema?: InteractivitySchema;- prettierConfigOverride?: Record<string, unknown> | null;- videoConfigValues: VideoConfigValues | null;-}): Promise<{- output: string;- formatted: boolean;- oldValueStrings: string[];- newValueStrings: string[];- logLine: number;- updatedNodePath: SequenceNodePath;-}> => {- const {- serialized,- oldValueStrings,- newValueStrings,- logLine,- updatedNodePath,- } = updateSequenceKeyframesAst({- input,- nodePath,- updates,- schema,- videoConfigValues,- });- const {output, formatted} = await formatFileContent({- input: serialized,+ contents: string;+ prettierConfigOverride: Record<string, unknown> | null;+}) =>+ formatFileContent({+ input: contents,prettierConfigOverride,});- const outputWithoutInsertedBlankLines =- removeBlankLinesFromObjectsWithProperties({- input: output,- propertyNames: updates.map((update) =>- getObjectPropertyNameFromUpdateKey(update.key),- ),- });-- return {- output: outputWithoutInsertedBlankLines,- formatted,- oldValueStrings,- newValueStrings,- logLine,- updatedNodePath,- };-};-export const updateEffectKeyframesAst = ({- input,- sequenceNodePath,- effectIndex,- updates,- schema,- videoConfigValues,-}: {- input: string;- sequenceNodePath: SequenceNodePath;- effectIndex: number;- updates: EffectKeyframeUpdate[];- schema?: InteractivitySchema;- videoConfigValues: VideoConfigValues | null;-}): {- serialized: string;- oldValueStrings: string[];- newValueStrings: string[];- logLine: number;- effectCallee: string;- updatedSequenceNodePath: SequenceNodePath;-} => {- const ast = parseAst(input);- const videoConfigIdentifierValues = getVideoConfigIdentifierValues({- ast,- videoConfigValues,- });- const jsxPath = getAstNodePath(ast, sequenceNodePath);- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);- if (!jsx || !jsxPath) {- throw new Error(- 'Could not find a JSX element at the specified location to update effect keyframes',- );- }-- const attr = findEffectsAttr(jsx.attributes ?? []);- if (!attr) {- throw new Error('Could not find effects on the target JSX element');- }-- const found = findEffectCallExpression({attr, effectIndex});- if (found.kind === 'error') {- throw new Error(`Cannot update effect keyframe: ${found.reason}`);- }-- const {call, callee: effectCallee} = found;- const objExpr = getEffectPropsObjectExpression(call);- const oldValueStrings: string[] = [];- const newValueStrings: string[] = [];- const requiredImports = new Set<string>();- let needsFrameHook = false;- for (const update of updates) {- const prop = getEffectWritableProp({- objExpr,- key: update.key,- missingPropInitialValue:- update.operation.type === 'add'- ? {- value: getInitialValueForMissingProp({- schema: schema ?? null,- key: update.key,- newValue: update.operation.value,- }),- }- : null,- });- oldValueStrings.push(recast.print(prop.expression).code);- const {expression: nextExpression, introduced} = applyKeyframeOperation({- expression: prop.expression,- key: update.key,- operation: update.operation,- schema: schema ?? null,- videoConfigValues: videoConfigIdentifierValues,- });- newValueStrings.push(recast.print(nextExpression).code);- if (- shouldRemovePropAfterKeyframeOperation({- expression: prop.expression,- key: update.key,- operation: update.operation,- schema: schema ?? null,- videoConfigValues: videoConfigIdentifierValues,- })- ) {- prop.remove();- } else {- prop.setExpression(nextExpression);- }-- if (introduced.calleeName) {- requiredImports.add(introduced.calleeName);- }-- if (introduced.needsFrameHook) {- requiredImports.add('useCurrentFrame');- needsFrameHook = true;- }-- if (introduced.needsEasingImport) {- requiredImports.add('Easing');- }- }-- if (needsFrameHook) {- const fnPath = findEnclosingFunctionPath(jsxPath);- if (fnPath) {- ensureUseCurrentFrameHook(fnPath);- }- }-- ensureRemotionImports(ast, requiredImports);-- const updatedSequenceNodePath = findNodePathForJsxElement(ast, jsx);- if (!updatedSequenceNodePath) {- throw new Error(- 'Could not find updated JSX element location after updating effect keyframes',- );- }-- return {- serialized: serializeAst(ast),- oldValueStrings,- newValueStrings,- logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,- effectCallee,- updatedSequenceNodePath,- };-};--export const updateEffectKeyframes = async ({- input,- sequenceNodePath,- effectIndex,- updates,- schema,- prettierConfigOverride,- videoConfigValues,-}: {- input: string;- sequenceNodePath: SequenceNodePath;- effectIndex: number;- updates: EffectKeyframeUpdate[];- schema?: InteractivitySchema;- prettierConfigOverride?: Record<string, unknown> | null;- videoConfigValues: VideoConfigValues | null;-}): Promise<{- output: string;- formatted: boolean;- oldValueStrings: string[];- newValueStrings: string[];- logLine: number;- effectCallee: string;- updatedSequenceNodePath: SequenceNodePath;-}> => {- const {- serialized,- oldValueStrings,- newValueStrings,- logLine,- effectCallee,- updatedSequenceNodePath,- } = updateEffectKeyframesAst({- input,- sequenceNodePath,- effectIndex,- updates,- schema,- videoConfigValues,- });- const {output, formatted} = await formatFileContent({- input: serialized,- prettierConfigOverride,- });- const outputWithoutInsertedBlankLines =- removeBlankLinesFromObjectsWithProperties({- input: output,- propertyNames: updates.map((update) => update.key),- });+export const updateSequenceKeyframes = (input: UpdateSequenceKeyframesInput) =>+ updateSequenceKeyframesCodemod({...input, formatFile: formatKeyframesFile});- return {- output: outputWithoutInsertedBlankLines,- formatted,- oldValueStrings,- newValueStrings,- logLine,- effectCallee,- updatedSequenceNodePath,- };-};+export const updateEffectKeyframes = (input: UpdateEffectKeyframesInput) =>+ updateEffectKeyframesCodemod({...input, formatFile: formatKeyframesFile});diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex de89a7c6e7..036d5c96ee 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -1,11 +1,21 @@import type {ElementDragData} from '@remotion/studio-protocol';import type {+ AddEffectKeyframeRequest,+ AddEffectKeyframeResponse,+ AddKeyframesRequest,+ AddKeyframesResponse,+ AddSequenceKeyframeRequest,+ AddSequenceKeyframeResponse,ApplyCodemodRequest,ApplyCodemodResponse,+ BatchUpdateKeyframeSettingsRequest,+ BatchUpdateKeyframeSettingsResponse,CompositionComponentInfoRequest,CompositionComponentInfoResponse,DeleteJsxNodeRequest,DeleteJsxNodeResponse,+ DeleteKeyframesRequest,+ DeleteKeyframesResponse,DeleteStaticFileRequest,DeleteStaticFileResponse,FindInFileRequest,@@ -14,6 +24,8 @@ import type {InsertJsxElementResponse,InsertElementRequest,InsertElementResponse,+ MoveKeyframesRequest,+ MoveKeyframesResponse,PrepareElementInstallRequest,PrepareElementInstallResponse,RedoResponse,@@ -37,6 +49,10 @@ import type {UnsubscribeFromSequencePropsRequest,UpdateDefaultPropsRequest,UpdateDefaultPropsResponse,+ UpdateEffectKeyframeSettingsRequest,+ UpdateEffectKeyframeSettingsResponse,+ UpdateSequenceKeyframeSettingsRequest,+ UpdateSequenceKeyframeSettingsResponse,} from './api-requests';import type {RecastCodemod} from './codemods';import type {EventSourceEvent} from './event-source-event';@@ -62,6 +78,31 @@ export type DuplicateCompositionResponse =stack: string;};+export type BrowserStudioKeyframeOperations = {+ addEffectKeyframe: (+ request: AddEffectKeyframeRequest,+ ) => Promise<AddEffectKeyframeResponse>;+ addKeyframes: (request: AddKeyframesRequest) => Promise<AddKeyframesResponse>;+ addSequenceKeyframe: (+ request: AddSequenceKeyframeRequest,+ ) => Promise<AddSequenceKeyframeResponse>;+ batchUpdateKeyframeSettings: (+ request: BatchUpdateKeyframeSettingsRequest,+ ) => Promise<BatchUpdateKeyframeSettingsResponse>;+ deleteKeyframes: (+ request: DeleteKeyframesRequest,+ ) => Promise<DeleteKeyframesResponse>;+ moveKeyframes: (+ request: MoveKeyframesRequest,+ ) => Promise<MoveKeyframesResponse>;+ updateEffectKeyframeSettings: (+ request: UpdateEffectKeyframeSettingsRequest,+ ) => Promise<UpdateEffectKeyframeSettingsResponse>;+ updateSequenceKeyframeSettings: (+ request: UpdateSequenceKeyframeSettingsRequest,+ ) => Promise<UpdateSequenceKeyframeSettingsResponse>;+};+export type BrowserStudioOperations = {consumeInitialElement: () => {element: ElementDragData['element'];@@ -96,6 +137,8 @@ export type BrowserStudioOperations = {insertJsxElement: (request: InsertJsxElementRequest,) => Promise<InsertJsxElementResponse>;+ /** Optional for compatibility with older Browser Studio hosts. */+ keyframes?: BrowserStudioKeyframeOperations;prepareElementInstall: (request: PrepareElementInstallRequest,) => Promise<PrepareElementInstallResponse>;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex b4e851b157..4d85f85645 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -156,6 +156,7 @@ export {type KeyframeSettings,} from './api-requests';export type {+ BrowserStudioKeyframeOperations,BrowserStudioOperations,DuplicateCompositionRequest,DuplicateCompositionResponse,diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsxindex 27ec7a923c..27d4554de1 100644--- a/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx+++ b/packages/studio/src/components/Timeline/TimelineKeyframeControls.tsx@@ -11,6 +11,7 @@ import type {SequencePropsSubscriptionKey,} from 'remotion';import {Internals, useVideoConfig} from 'remotion';+import {canUseKeyframeOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {BLUE, LIGHT_GRAY, LIGHT_TEXT, WHITE} from '../../helpers/colors';import type {@@ -598,6 +599,7 @@ export const TimelineKeyframeControls: React.FC<{});const canAddKeyframe = keyframable;const canToggleKeyframe =+ canUseKeyframeOperations() &&propStatus.status !== 'computed' &&(hasKeyframeAtCurrentFrame || canAddKeyframe);diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsxindex 104e832101..606d1abb76 100644--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx@@ -18,6 +18,7 @@ import {type GetEffectDragOverrides,type PropStatuses,} from 'remotion';+import {canUseKeyframeOperations} from '../../helpers/browser-studio-operations';import {StudioServerConnectionCtx} from '../../helpers/client-id';import {BACKGROUND,@@ -1164,6 +1165,7 @@ export const TimelineSelectionProvider: React.FC<{isStudioSelectionEnabled() &&(previewServerState.type === 'connected' ||window.remotion_isReadOnlyStudio);+ const keyframeOperationsAvailable = canUseKeyframeOperations();const [selectedItems, setSelectedItems] = useState<readonly TimelineSelection[]>([]);@@ -1195,8 +1197,10 @@ export const TimelineSelectionProvider: React.FC<{const canSelectItem = useCallback((item: TimelineSelection) =>canSelect &&- (!window.remotion_isReadOnlyStudio || item.type === 'sequence'),- [canSelect],+ (!window.remotion_isReadOnlyStudio ||+ keyframeOperationsAvailable ||+ item.type === 'sequence'),+ [canSelect, keyframeOperationsAvailable],);const getCurrentAvailableSelectionState = useCallback(diff --git a/packages/studio/src/components/Timeline/call-add-keyframe.ts b/packages/studio/src/components/Timeline/call-add-keyframe.tsindex 050edb57d2..32006b0ab5 100644--- a/packages/studio/src/components/Timeline/call-add-keyframe.ts+++ b/packages/studio/src/components/Timeline/call-add-keyframe.ts@@ -1,8 +1,12 @@import {optimisticAddEffectKeyframe,optimisticAddSequenceKeyframe,+ type AddEffectKeyframeRequest,+ type AddKeyframesRequest,+ type AddSequenceKeyframeRequest,} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';import {callApi} from '../call-api';import {applyEffectResponseToPropStatuses} from './apply-effect-response-to-prop-statuses';import {enqueueSavePropChange} from './save-prop-queue';@@ -21,6 +25,39 @@ export type AddEffectKeyframeChange = AddSequenceKeyframeChange & {effectIndex: number;};+const addSequenceKeyframe = (request: AddSequenceKeyframeRequest) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/add-sequence-keyframe', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.addSequenceKeyframe(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};++const addEffectKeyframe = (request: AddEffectKeyframeRequest) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/add-effect-keyframe', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.addEffectKeyframe(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};++const addKeyframes = (request: AddKeyframesRequest) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/add-keyframes', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.addKeyframes(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};+const groupByNodePath = <T extends {nodePath: SequencePropsSubscriptionKey}>(keyframes: T[],): T[][] => {@@ -66,7 +103,7 @@ export const callAddSequenceKeyframe = ({schema,}),apiCall: () =>- callApi('/api/add-sequence-keyframe', {+ addSequenceKeyframe({fileName,nodePath,key: fieldKey,@@ -137,7 +174,7 @@ export const callAddKeyframes = ({);}- return callApi('/api/add-keyframes', {+ return addKeyframes({sequenceKeyframes: sequenceKeyframes.map((keyframe) => ({fileName: keyframe.fileName,nodePath: keyframe.nodePath,@@ -195,7 +232,7 @@ export const callAddEffectKeyframe = ({applyServerResponse: (prev, response) =>applyEffectResponseToPropStatuses({previous: prev, response}),apiCall: () =>- callApi('/api/add-effect-keyframe', {+ addEffectKeyframe({fileName,sequenceNodePath: nodePath,effectIndex,diff --git a/packages/studio/src/components/Timeline/call-delete-keyframe.ts b/packages/studio/src/components/Timeline/call-delete-keyframe.tsindex f0c0b20e47..407bd80762 100644--- a/packages/studio/src/components/Timeline/call-delete-keyframe.ts+++ b/packages/studio/src/components/Timeline/call-delete-keyframe.ts@@ -3,8 +3,10 @@ import {optimisticDeleteEffectKeyframes,optimisticDeleteSequenceKeyframe,optimisticDeleteSequenceKeyframes,+ type DeleteKeyframesRequest,} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';import {callApi} from '../call-api';import {enqueueSavePropChange} from './save-prop-queue';import type {SetPropStatuses} from './save-sequence-prop';@@ -22,6 +24,17 @@ export type DeleteEffectKeyframeChange = DeleteSequenceKeyframeChange & {effectIndex: number;};+const deleteKeyframes = (request: DeleteKeyframesRequest) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/delete-keyframes', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.deleteKeyframes(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};+const groupByNodePath = <T extends {nodePath: SequencePropsSubscriptionKey}>(keyframes: T[],): T[][] => {@@ -63,7 +76,7 @@ export const callDeleteSequenceKeyframe = ({frame: sourceFrame,}),apiCall: () =>- callApi('/api/delete-keyframes', {+ deleteKeyframes({sequenceKeyframes: [{fileName,@@ -110,7 +123,7 @@ export const callDeleteEffectKeyframe = ({frame: sourceFrame,}),apiCall: () =>- callApi('/api/delete-keyframes', {+ deleteKeyframes({sequenceKeyframes: [],effectKeyframes: [{@@ -180,7 +193,7 @@ export const callDeleteKeyframes = ({);}- return callApi('/api/delete-keyframes', {+ return deleteKeyframes({sequenceKeyframes: sequenceKeyframes.map((keyframe) => ({fileName: keyframe.fileName,nodePath: keyframe.nodePath,diff --git a/packages/studio/src/components/Timeline/call-move-keyframe.ts b/packages/studio/src/components/Timeline/call-move-keyframe.tsindex eebd813bc2..d29724bb8e 100644--- a/packages/studio/src/components/Timeline/call-move-keyframe.ts+++ b/packages/studio/src/components/Timeline/call-move-keyframe.ts@@ -1,12 +1,14 @@import {optimisticMoveEffectKeyframes,optimisticMoveSequenceKeyframes,+ type MoveKeyframesRequest,} from '@remotion/studio-shared';import type {CanUpdateSequencePropStatus,InteractivitySchema,SequencePropsSubscriptionKey,} from 'remotion';+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';import {callApi} from '../call-api';import type {SetPropStatuses} from './save-sequence-prop';@@ -24,6 +26,17 @@ export type MoveEffectKeyframeChange = MoveSequenceKeyframeChange & {effectIndex: number;};+const moveKeyframes = (request: MoveKeyframesRequest) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/move-keyframes', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.moveKeyframes(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};+const groupByNodePath = <T extends {nodePath: SequencePropsSubscriptionKey}>(keyframes: T[],): T[][] => {@@ -180,7 +193,7 @@ export const callMoveKeyframes = ({setPropStatuses,});- return callApi('/api/move-keyframes', {+ return moveKeyframes({sequenceKeyframes: sequenceKeyframes.map((keyframe) => ({fileName: keyframe.fileName,nodePath: keyframe.nodePath,diff --git a/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts b/packages/studio/src/components/Timeline/call-update-keyframe-settings.tsindex bbe105c8e3..d06ee77824 100644--- a/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts+++ b/packages/studio/src/components/Timeline/call-update-keyframe-settings.ts@@ -1,15 +1,58 @@import {optimisticUpdateEffectKeyframeSettings,optimisticUpdateSequenceKeyframeSettings,+ type BatchUpdateKeyframeSettingsRequest,type KeyframeSettings,+ type UpdateEffectKeyframeSettingsRequest,+ type UpdateSequenceKeyframeSettingsRequest,} from '@remotion/studio-shared';import type {SequencePropsSubscriptionKey, InteractivitySchema} from 'remotion';+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';import {callApi} from '../call-api';import {showNotification} from '../Notifications/NotificationCenter';import {applyEffectResponseToPropStatuses} from './apply-effect-response-to-prop-statuses';import {enqueueSavePropChange} from './save-prop-queue';import type {SetPropStatuses} from './save-sequence-prop';+const updateSequenceKeyframeSettings = (+ request: UpdateSequenceKeyframeSettingsRequest,+) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/update-sequence-keyframe-settings', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.updateSequenceKeyframeSettings(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};++const updateEffectKeyframeSettings = (+ request: UpdateEffectKeyframeSettingsRequest,+) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/update-effect-keyframe-settings', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.updateEffectKeyframeSettings(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};++const batchUpdateKeyframeSettings = (+ request: BatchUpdateKeyframeSettingsRequest,+) => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (!browserStudioOperations) {+ return callApi('/api/batch-update-keyframe-settings', request);+ }++ return browserStudioOperations.keyframes+ ? browserStudioOperations.keyframes.batchUpdateKeyframeSettings(request)+ : Promise.reject(new Error('Keyframe editing is unavailable'));+};+export const callUpdateSequenceKeyframeSettings = ({fileName,nodePath,@@ -37,7 +80,7 @@ export const callUpdateSequenceKeyframeSettings = ({settings,}),apiCall: () =>- callApi('/api/update-sequence-keyframe-settings', {+ updateSequenceKeyframeSettings({fileName,nodePath,key: fieldKey,@@ -81,7 +124,7 @@ export const callUpdateEffectKeyframeSettings = ({applyServerResponse: (prev, response) =>applyEffectResponseToPropStatuses({previous: prev, response}),apiCall: () =>- callApi('/api/update-effect-keyframe-settings', {+ updateEffectKeyframeSettings({fileName,sequenceNodePath: nodePath,effectIndex,@@ -138,7 +181,7 @@ export const callBatchUpdateKeyframeSettings = ({);}- return callApi('/api/batch-update-keyframe-settings', {+ return batchUpdateKeyframeSettings({sequenceKeyframes: sequenceKeyframes.map((update) => ({fileName: update.fileName,nodePath: update.nodePath,diff --git a/packages/studio/src/helpers/browser-studio-operations.ts b/packages/studio/src/helpers/browser-studio-operations.tsindex 5d4e04a428..bf2415b236 100644--- a/packages/studio/src/helpers/browser-studio-operations.ts+++ b/packages/studio/src/helpers/browser-studio-operations.ts@@ -13,3 +13,10 @@ export const getBrowserStudioOperations =return window.remotion_browserStudio ?? null;};++export const getBrowserStudioKeyframeOperations = () =>+ getBrowserStudioOperations()?.keyframes ?? null;++export const canUseKeyframeOperations = () =>+ !window.remotion_isReadOnlyStudio ||+ getBrowserStudioKeyframeOperations() !== null;