Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-server`: Auto-add interpolate import and useCurrentFrame hook on keyframe add (#7856)

Jonny Burger6b50e6b95964
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.ts
new file mode 100644
index 0000000000..f9843b13ee
--- /dev/null
+++ b/packages/studio-server/src/codemods/update-keyframes/ensure-imports-and-frame-hook.ts
@@ -0,0 +1,178 @@
+import type {
+ ArrowFunctionExpression,
+ File,
+ FunctionDeclaration,
+ FunctionExpression,
+ ImportDeclaration,
+ ImportSpecifier,
+} from '@babel/types';
+import * as recast from 'recast';
+
+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;
+};
+
+const findRemotionImport = (ast: File): ImportDeclaration | null => {
+ for (const stmt of ast.program.body) {
+ if (
+ stmt.type === 'ImportDeclaration' &&
+ stmt.source.type === 'StringLiteral' &&
+ stmt.source.value === 'remotion'
+ ) {
+ return stmt;
+ }
+ }
+
+ return null;
+};
+
+const insertImportDeclaration = (
+ ast: File,
+ importDecl: ImportDeclaration,
+): void => {
+ const {body} = ast.program;
+ let lastImportIndex = -1;
+ for (let i = 0; i < body.length; i++) {
+ if (body[i].type === 'ImportDeclaration') {
+ lastImportIndex = i;
+ }
+ }
+
+ body.splice(lastImportIndex + 1, 0, importDecl);
+};
+
+export const ensureRemotionImports = (
+ ast: File,
+ names: ReadonlySet<string>,
+): void => {
+ if (names.size === 0) {
+ return;
+ }
+
+ let remotionImport = findRemotionImport(ast);
+ if (!remotionImport) {
+ remotionImport = b.importDeclaration(
+ [],
+ b.stringLiteral('remotion'),
+ ) as unknown as ImportDeclaration;
+ insertImportDeclaration(ast, remotionImport);
+ }
+
+ const existingNames = new Set<string>();
+ for (const specifier of remotionImport.specifiers ?? []) {
+ if (specifier.type !== 'ImportSpecifier') {
+ continue;
+ }
+
+ const {imported} = specifier as ImportSpecifier;
+ if (imported.type === 'Identifier') {
+ existingNames.add(imported.name);
+ } else if (imported.type === 'StringLiteral') {
+ existingNames.add(imported.value);
+ }
+ }
+
+ for (const name of names) {
+ if (existingNames.has(name)) {
+ continue;
+ }
+
+ remotionImport.specifiers = remotionImport.specifiers ?? [];
+ remotionImport.specifiers.push(
+ b.importSpecifier(b.identifier(name)) as unknown as ImportSpecifier,
+ );
+ existingNames.add(name);
+ }
+};
+
+const componentBodyHasFrameDeclaration = (
+ body: FunctionNode['body'],
+): 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 === 'useCurrentFrame'
+ ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+};
+
+export const ensureUseCurrentFrameHook = (
+ functionPath: recast.types.NodePath,
+): 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(fn.body)) {
+ 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('useCurrentFrame'), []),
+ ),
+ ]);
+
+ block.body.unshift(frameDecl as unknown as (typeof block.body)[number]);
+};
diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
index 5fcaf00d02..08522b3c57 100644
--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts
@@ -13,6 +13,7 @@ import type {
import type {ExpressionKind, SpreadElementKind} from 'ast-types/lib/gen/kinds';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
+import {getAstNodePath} from '../../helpers/get-ast-node-path';
import {
extractStaticValue,
findJsxElementAtNodePath,
@@ -25,6 +26,11 @@ import {
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;
@@ -220,6 +226,16 @@ const createInterpolateExpression = ({
]) as ExpressionKind;
};
+export type IntroducedKeyframeIdentifiers = {
+ calleeName: 'interpolate' | 'interpolateColors' | null;
+ needsFrameHook: boolean;
+};
+
+const noIntroducedIdentifiers: IntroducedKeyframeIdentifiers = {
+ calleeName: null,
+ needsFrameHook: false,
+};
+
const addKeyframe = ({
expression,
frame,
@@ -228,7 +244,7 @@ const addKeyframe = ({
expression: Expression;
frame: number;
value: unknown;
-}): ExpressionKind => {
+}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {
const existing = getInterpolationExpression(expression);
const newOutput = parseValueExpression(value);
@@ -245,12 +261,15 @@ const addKeyframe = ({
: keyframe,
);
- return createInterpolateExpression({
- callee: existing.callee,
- input: existing.input,
- extraArgs: existing.extraArgs,
- keyframes: nextKeyframes,
- });
+ return {
+ expression: createInterpolateExpression({
+ callee: existing.callee,
+ input: existing.input,
+ extraArgs: existing.extraArgs,
+ keyframes: nextKeyframes,
+ }),
+ introduced: noIntroducedIdentifiers,
+ };
}
if (!isStaticValue(expression)) {
@@ -267,15 +286,26 @@ const addKeyframe = ({
{frame, output: newOutput, value},
];
- return createInterpolateExpression({
- callee: getInterpolationCalleeForValues({
- staticValue,
- newValue: value,
- }),
- input: b.identifier('frame'),
- extraArgs: [],
- keyframes,
+ const callee = getInterpolationCalleeForValues({
+ staticValue,
+ newValue: value,
});
+
+ return {
+ expression: createInterpolateExpression({
+ callee,
+ input: b.identifier('frame'),
+ extraArgs: [],
+ keyframes,
+ }),
+ introduced: {
+ calleeName:
+ callee.type === 'Identifier'
+ ? (callee.name as 'interpolate' | 'interpolateColors')
+ : null,
+ needsFrameHook: true,
+ },
+ };
};
const removeKeyframe = ({
@@ -315,7 +345,7 @@ const applyKeyframeOperation = ({
}: {
expression: Expression;
operation: KeyframeOperation;
-}): ExpressionKind => {
+}): {expression: ExpressionKind; introduced: IntroducedKeyframeIdentifiers} => {
if (operation.type === 'add') {
return addKeyframe({
expression,
@@ -324,7 +354,10 @@ const applyKeyframeOperation = ({
});
}
- return removeKeyframe({expression, frame: operation.frame});
+ return {
+ expression: removeKeyframe({expression, frame: operation.frame}),
+ introduced: noIntroducedIdentifiers,
+ };
};
const getExpressionFromJsxAttribute = (
@@ -481,8 +514,9 @@ export const updateSequenceKeyframesAst = ({
logLine: number;
} => {
const ast = parseAst(input);
+ const jsxPath = getAstNodePath(ast, nodePath);
const node = findJsxElementAtNodePath(ast, nodePath);
- if (!node) {
+ if (!node || !jsxPath) {
throw new Error(
'Could not find a JSX element at the specified location to update keyframes',
);
@@ -492,6 +526,9 @@ export const updateSequenceKeyframesAst = ({
node.attributes = [];
}
+ const requiredImports = new Set<string>();
+ let needsFrameHook = false;
+
const oldValueStrings: string[] = [];
const newValueStrings: string[] = [];
for (const update of updates) {
@@ -500,14 +537,32 @@ export const updateSequenceKeyframesAst = ({
key: update.key,
});
oldValueStrings.push(recast.print(prop.expression).code);
- const nextExpression = applyKeyframeOperation({
+ const {expression: nextExpression, introduced} = applyKeyframeOperation({
expression: prop.expression,
operation: update.operation,
});
newValueStrings.push(recast.print(nextExpression).code);
prop.setExpression(nextExpression);
+
+ if (introduced.calleeName) {
+ requiredImports.add(introduced.calleeName);
+ }
+
+ if (introduced.needsFrameHook) {
+ requiredImports.add('useCurrentFrame');
+ needsFrameHook = true;
+ }
+ }
+
+ if (needsFrameHook) {
+ const fnPath = findEnclosingFunctionPath(jsxPath);
+ if (fnPath) {
+ ensureUseCurrentFrameHook(fnPath);
+ }
}
+ ensureRemotionImports(ast, requiredImports);
+
return {
serialized: serializeAst(ast),
oldValueStrings,
@@ -565,8 +620,9 @@ export const updateEffectKeyframesAst = ({
effectCallee: string;
} => {
const ast = parseAst(input);
+ const jsxPath = getAstNodePath(ast, sequenceNodePath);
const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
- if (!jsx) {
+ if (!jsx || !jsxPath) {
throw new Error(
'Could not find a JSX element at the specified location to update effect keyframes',
);
@@ -593,6 +649,8 @@ export const updateEffectKeyframesAst = ({
const objExpr = call.arguments[0] as ObjectExpression;
const oldValueStrings: string[] = [];
const newValueStrings: string[] = [];
+ const requiredImports = new Set<string>();
+ let needsFrameHook = false;
for (const update of updates) {
const {prop} = findObjectProperty(objExpr, update.key);
if (!prop) {
@@ -600,14 +658,32 @@ export const updateEffectKeyframesAst = ({
}
oldValueStrings.push(recast.print(prop.value).code);
- const nextExpression = applyKeyframeOperation({
+ const {expression: nextExpression, introduced} = applyKeyframeOperation({
expression: prop.value as Expression,
operation: update.operation,
});
newValueStrings.push(recast.print(nextExpression).code);
prop.value = nextExpression as ObjectProperty['value'];
+
+ if (introduced.calleeName) {
+ requiredImports.add(introduced.calleeName);
+ }
+
+ if (introduced.needsFrameHook) {
+ requiredImports.add('useCurrentFrame');
+ needsFrameHook = true;
+ }
}
+ if (needsFrameHook) {
+ const fnPath = findEnclosingFunctionPath(jsxPath);
+ if (fnPath) {
+ ensureUseCurrentFrameHook(fnPath);
+ }
+ }
+
+ ensureRemotionImports(ast, requiredImports);
+
return {
serialized: serializeAst(ast),
oldValueStrings,
diff --git a/packages/studio-server/src/test/update-keyframes-imports.test.ts b/packages/studio-server/src/test/update-keyframes-imports.test.ts
new file mode 100644
index 0000000000..88966c5af5
--- /dev/null
+++ b/packages/studio-server/src/test/update-keyframes-imports.test.ts
@@ -0,0 +1,485 @@
+import {expect, test} from 'bun:test';
+import {
+ updateEffectKeyframesAst,
+ updateSequenceKeyframesAst,
+} from '../codemods/update-keyframes/update-keyframes';
+import {lineColumnToNodePath} from './test-utils';
+
+const getLine = (input: string, needle: string): number => {
+ const lineIndex = input
+ .split('\n')
+ .findIndex((line) => line.includes(needle));
+ if (lineIndex === -1) {
+ throw new Error(`Could not find line containing ${needle}`);
+ }
+
+ return lineIndex + 1;
+};
+
+// ---------------------------------------------------------------------------
+// Sequence: imports
+// ---------------------------------------------------------------------------
+
+test('adds missing interpolate and useCurrentFrame imports when converting static prop', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 30, value: 1}},
+ ],
+ });
+
+ expect(serialized).toMatch(
+ /import\s*\{[^}]*\bAbsoluteFill\b[^}]*\binterpolate\b[^}]*\buseCurrentFrame\b[^}]*\}\s*from\s*['"]remotion['"]/,
+ );
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+ expect(serialized).toContain('interpolate(frame, [0, 30], [0.5, 1])');
+});
+
+test('adds interpolateColors import (not interpolate) for color conversion', () => {
+ const input = `import React from 'react';
+import {Solid} from 'remotion';
+
+export const Example: React.FC = () => {
+\treturn <Solid color={'red'} width={100} height={100} />;
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, '<Solid')),
+ updates: [
+ {key: 'color', operation: {type: 'add', frame: 50, value: 'blue'}},
+ ],
+ });
+
+ expect(serialized).toContain('interpolateColors');
+ expect(serialized).not.toContain('{interpolate,');
+ expect(serialized).toContain('useCurrentFrame');
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+});
+
+test('creates a new remotion import when one is missing entirely', () => {
+ const input = `import React from 'react';
+
+export const Example = () => {
+\treturn <div style={{opacity: 0.5}} />;
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, '<div')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 20, value: 1}},
+ ],
+ });
+
+ expect(serialized).toMatch(
+ /import\s*\{[^}]*\binterpolate\b[^}]*\buseCurrentFrame\b[^}]*\}\s*from\s*['"]remotion['"]/,
+ );
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+});
+
+test('does not duplicate an existing interpolate import', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';
+
+export const Example: React.FC = () => {
+\tconst frame = useCurrentFrame();
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 25, value: 1}},
+ ],
+ });
+
+ const matches = serialized.match(/from 'remotion'/g) ?? [];
+ expect(matches.length).toBe(1);
+ const interpolateMatches = serialized.match(/\binterpolate\b/g) ?? [];
+ // once in import, once in the new expression
+ expect(interpolateMatches.length).toBe(2);
+});
+
+test('does not add useCurrentFrame import or frame hook when extending an existing interpolation', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, interpolate} from 'remotion';
+
+const f = 10;
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: interpolate(f, [0, 100], [0, 1])}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 50, value: 0.5}},
+ ],
+ });
+
+ expect(serialized).not.toContain('useCurrentFrame');
+ expect(serialized).toContain('interpolate(f, [0, 50, 100], [0, 0.5, 1])');
+});
+
+test('does not add useCurrentFrame import or frame hook when removing a keyframe', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, interpolate} from 'remotion';
+
+const f = 10;
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: interpolate(f, [0, 50, 100], [0, 0.5, 1])}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [{key: 'style.opacity', operation: {type: 'remove', frame: 50}}],
+ });
+
+ expect(serialized).not.toContain('useCurrentFrame');
+});
+
+test('adds useCurrentFrame to existing remotion import that already has other specifiers', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, Sequence} from 'remotion';
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<Sequence>
+\t\t\t\t<div style={{opacity: 0.5}} />
+\t\t\t</Sequence>
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 20, value: 1}},
+ ],
+ });
+
+ expect(serialized).toMatch(
+ /import\s*\{[^}]*\bAbsoluteFill\b[^}]*\bSequence\b[^}]*\binterpolate\b[^}]*\buseCurrentFrame\b[^}]*\}\s*from\s*'remotion'/,
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Sequence: frame hook insertion
+// ---------------------------------------------------------------------------
+
+test('inserts const frame = useCurrentFrame() at the top of the component', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Example: React.FC = () => {
+\tconst x = 5;
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 30, value: 1}},
+ ],
+ });
+
+ const frameIdx = serialized.indexOf('const frame = useCurrentFrame()');
+ const xIdx = serialized.indexOf('const x = 5');
+ expect(frameIdx).toBeGreaterThan(-1);
+ expect(frameIdx).toBeLessThan(xIdx);
+});
+
+test('does not duplicate the frame hook if it already exists', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, useCurrentFrame} from 'remotion';
+
+export const Example: React.FC = () => {
+\tconst frame = useCurrentFrame();
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 30, value: 1}},
+ ],
+ });
+
+ const matches = serialized.match(/const frame = useCurrentFrame\(\)/g) ?? [];
+ expect(matches.length).toBe(1);
+});
+
+test('inserts frame hook in function declaration component', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export function Example() {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+}
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 25, value: 1}},
+ ],
+ });
+
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+ expect(serialized).toMatch(
+ /function Example\(\)\s*\{\s*const frame = useCurrentFrame/,
+ );
+});
+
+test('inserts frame hook into the innermost enclosing function, not an outer one', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Outer: React.FC = () => {
+\tconst Inner: React.FC = () => {
+\t\treturn <div style={{opacity: 0.5}} />;
+\t};
+
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<Inner />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 30, value: 1}},
+ ],
+ });
+
+ expect(serialized).toMatch(
+ /Inner:\s*React\.FC\s*=\s*\(\)\s*=>\s*\{\s*const frame = useCurrentFrame\(\);/,
+ );
+ // Outer function body should not have a hook prepended
+ expect(serialized).not.toMatch(
+ /Outer:\s*React\.FC\s*=\s*\(\)\s*=>\s*\{\s*const frame = useCurrentFrame/,
+ );
+});
+
+test('converts an arrow function with expression body to a block when inserting the hook', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Example: React.FC = () => (
+\t<AbsoluteFill>
+\t\t<div style={{opacity: 0.5}} />
+\t</AbsoluteFill>
+);
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 20, value: 1}},
+ ],
+ });
+
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+ expect(serialized).toContain('return');
+ expect(serialized).toContain('interpolate(frame, [0, 20], [0.5, 1])');
+});
+
+test('does not add a duplicate frame hook when user already has one with a different intermediate statement', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, useCurrentFrame} from 'remotion';
+
+export const Example: React.FC = () => {
+\tconst other = 1;
+\tconst frame = useCurrentFrame();
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 20, value: 1}},
+ ],
+ });
+
+ const matches = serialized.match(/const frame = useCurrentFrame\(\)/g) ?? [];
+ expect(matches.length).toBe(1);
+});
+
+// ---------------------------------------------------------------------------
+// Effect imports & frame hook
+// ---------------------------------------------------------------------------
+
+test('effect keyframe add inserts imports and frame hook when needed', () => {
+ const input = `import {tint} from '@remotion/effects/tint';
+import {HtmlInCanvas} from '@remotion/html-in-canvas';
+
+export const Comp = () => {
+\treturn (
+\t\t<HtmlInCanvas effects={[tint({amount: 0.5})]}>
+\t\t\thi
+\t\t</HtmlInCanvas>
+\t);
+};
+`;
+ const {serialized} = updateEffectKeyframesAst({
+ input,
+ sequenceNodePath: lineColumnToNodePath(
+ input,
+ getLine(input, '<HtmlInCanvas'),
+ ),
+ effectIndex: 0,
+ updates: [{key: 'amount', operation: {type: 'add', frame: 100, value: 1}}],
+ });
+
+ expect(serialized).toMatch(
+ /import\s*\{[^}]*\binterpolate\b[^}]*\buseCurrentFrame\b[^}]*\}\s*from\s*['"]remotion['"]/,
+ );
+ expect(serialized).toContain('const frame = useCurrentFrame();');
+ expect(serialized).toContain('interpolate(frame, [0, 100], [0.5, 1])');
+});
+
+test('effect keyframe remove does not modify imports or insert a frame hook', () => {
+ const input = `import {tint} from '@remotion/effects/tint';
+import {HtmlInCanvas} from '@remotion/html-in-canvas';
+import {interpolate, useCurrentFrame} from 'remotion';
+
+export const Comp = () => {
+\tconst frame = useCurrentFrame();
+\treturn (
+\t\t<HtmlInCanvas
+\t\t\teffects={[tint({amount: interpolate(frame, [0, 50, 100], [0.2, 0.5, 0.8])})]}
+\t\t>
+\t\t\thi
+\t\t</HtmlInCanvas>
+\t);
+};
+`;
+ const before = (input.match(/const frame = useCurrentFrame/g) ?? []).length;
+ const {serialized} = updateEffectKeyframesAst({
+ input,
+ sequenceNodePath: lineColumnToNodePath(
+ input,
+ getLine(input, '<HtmlInCanvas'),
+ ),
+ effectIndex: 0,
+ updates: [{key: 'amount', operation: {type: 'remove', frame: 50}}],
+ });
+ const after = (serialized.match(/const frame = useCurrentFrame/g) ?? [])
+ .length;
+
+ expect(after).toBe(before);
+});
+
+test('effect keyframe extension of existing interpolation does not add useCurrentFrame', () => {
+ const input = `import {tint} from '@remotion/effects/tint';
+import {HtmlInCanvas} from '@remotion/html-in-canvas';
+import {interpolate} from 'remotion';
+
+const f = 0;
+
+export const Comp = () => {
+\treturn (
+\t\t<HtmlInCanvas
+\t\t\teffects={[tint({amount: interpolate(f, [0, 100], [0.2, 0.8])})]}
+\t\t>
+\t\t\thi
+\t\t</HtmlInCanvas>
+\t);
+};
+`;
+ const {serialized} = updateEffectKeyframesAst({
+ input,
+ sequenceNodePath: lineColumnToNodePath(
+ input,
+ getLine(input, '<HtmlInCanvas'),
+ ),
+ effectIndex: 0,
+ updates: [{key: 'amount', operation: {type: 'add', frame: 50, value: 0.5}}],
+ });
+
+ expect(serialized).not.toContain('useCurrentFrame');
+ expect(serialized).toContain('interpolate(f, [0, 50, 100], [0.2, 0.5, 0.8])');
+});
+
+test('multiple updates only add imports/hook once', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const Example: React.FC = () => {
+\treturn (
+\t\t<AbsoluteFill>
+\t\t\t<div style={{opacity: 0.5, scale: 1}} />
+\t\t</AbsoluteFill>
+\t);
+};
+`;
+ const {serialized} = updateSequenceKeyframesAst({
+ input,
+ nodePath: lineColumnToNodePath(input, getLine(input, 'opacity')),
+ updates: [
+ {key: 'style.opacity', operation: {type: 'add', frame: 20, value: 1}},
+ {key: 'style.scale', operation: {type: 'add', frame: 30, value: 2}},
+ ],
+ });
+
+ const matches = serialized.match(/const frame = useCurrentFrame\(\)/g) ?? [];
+ expect(matches.length).toBe(1);
+ const imports = serialized.match(/from 'remotion'/g) ?? [];
+ expect(imports.length).toBe(1);
+ const interpolateImport =
+ serialized.match(/import\s*\{[^}]*\binterpolate\b[^}]*\}/g) ?? [];
+ expect(interpolateImport.length).toBe(1);
+});