Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Support copying keyframed effects

JonnyBurgera7f4ac35920d
diff --git a/packages/example/src/EffectCopyTestbed/Source.tsx b/packages/example/src/EffectCopyTestbed/Source.tsx
new file mode 100644
index 0000000000..f7a3bd29a0
--- /dev/null
+++ b/packages/example/src/EffectCopyTestbed/Source.tsx
@@ -0,0 +1,36 @@
+import {blur} from '@remotion/effects/blur';
+import {brightness} from '@remotion/effects/brightness';
+import React from 'react';
+import {
+ AbsoluteFill,
+ Easing,
+ interpolate,
+ Solid,
+ useCurrentFrame,
+} from 'remotion';
+import {label} from './label';
+
+export const EffectCopySource: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill style={{backgroundColor: '#111827'}}>
+ <Solid
+ width={1080}
+ height={1080}
+ color="#60a5fa"
+ effects={[
+ brightness({
+ amount: interpolate(frame, [0, 100], [-0.25, 0.65], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ easing: Easing.linear,
+ }),
+ }),
+ blur({radius: 10}),
+ ]}
+ />
+ <div style={label}>Copy this keyframed effects group</div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/EffectCopyTestbed/Target.tsx b/packages/example/src/EffectCopyTestbed/Target.tsx
new file mode 100644
index 0000000000..0c38ded9a5
--- /dev/null
+++ b/packages/example/src/EffectCopyTestbed/Target.tsx
@@ -0,0 +1,12 @@
+import React from 'react';
+import {AbsoluteFill, Solid} from 'remotion';
+import {label} from './label';
+
+export const EffectCopyTarget: React.FC = () => {
+ return (
+ <AbsoluteFill style={{backgroundColor: '#111827'}}>
+ <Solid width={1080} height={1080} color="#f97316" />
+ <div style={label}>Paste effects onto this Solid</div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/EffectCopyTestbed/index.ts b/packages/example/src/EffectCopyTestbed/index.ts
new file mode 100644
index 0000000000..2cd39c56fc
--- /dev/null
+++ b/packages/example/src/EffectCopyTestbed/index.ts
@@ -0,0 +1,2 @@
+export {EffectCopySource} from './Source';
+export {EffectCopyTarget} from './Target';
diff --git a/packages/example/src/EffectCopyTestbed/label.ts b/packages/example/src/EffectCopyTestbed/label.ts
new file mode 100644
index 0000000000..55efbda6ea
--- /dev/null
+++ b/packages/example/src/EffectCopyTestbed/label.ts
@@ -0,0 +1,12 @@
+import type React from 'react';
+
+export const label: React.CSSProperties = {
+ position: 'absolute',
+ left: 48,
+ bottom: 48,
+ fontFamily: 'monospace',
+ fontSize: 34,
+ fontWeight: 700,
+ color: 'white',
+ textShadow: '0 3px 16px rgba(0, 0, 0, 0.45)',
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 4f75b34540..4e9ebfe146 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -30,6 +30,7 @@ import {
} from './DiscriminatedUnionSchemaTest';
import {DynamicDuration, dynamicDurationSchema} from './DynamicDuration';
import {EasingVisualizer} from './EasingVisualizer/EasingVisualizer';
+import {EffectCopySource, EffectCopyTarget} from './EffectCopyTestbed';
import {EmojiTestbed} from './Emoji';
import {ErrorOnFrame10} from './ErrorOnFrame10';
import {ExperimentalControlsShowcase} from './ExperimentalControls';
@@ -375,6 +376,22 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={60}
/>
+ <Composition
+ id="effect-copy-source"
+ component={EffectCopySource}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
+ <Composition
+ id="effect-copy-target"
+ component={EffectCopyTarget}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
</Folder>
<Folder name="dynamic-parameters">
<Composition
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.ts
index a7c63fe75f..37ce6e5ef2 100644
--- a/packages/studio-server/src/codemods/paste-effects.ts
+++ b/packages/studio-server/src/codemods/paste-effects.ts
@@ -1,21 +1,43 @@
-import type {ArrayExpression, CallExpression, JSXAttribute} from '@babel/types';
import type {
+ ArrayExpression,
+ CallExpression,
+ File,
+ JSXAttribute,
+ ObjectExpression,
+ ObjectProperty,
+} from '@babel/types';
+import type {
+ EffectClipboardKeyframedParam,
+ EffectClipboardParam,
EffectClipboardPasteType,
EffectClipboardSnapshot,
} from '@remotion/studio-shared';
+import type {ExpressionKind} 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 {ensureNamedImport} from '../helpers/imports';
import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {
- assertValidEffect,
- ensureEffectImport,
- makeConfigObjectExpression,
-} from './add-effect';
+import {assertValidEffect, ensureEffectImport} from './add-effect';
import {formatFileContent} from './format-file-content';
import {parseAst, serializeAst} from './parse-ast';
import {findEffectsAttr} from './update-effect-props/update-effect-props';
+import {
+ ensureUseCurrentFrameHook,
+ findEnclosingFunctionPath,
+} from './update-keyframes/ensure-imports-and-frame-hook';
+import {parseValueExpression} from './update-nested-prop';
const b = recast.types.builders;
+const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
+
+type RemotionImportName =
+ | 'Easing'
+ | 'interpolate'
+ | 'interpolateColors'
+ | 'useCurrentFrame';
+
+type RemotionLocalNames = Partial<Record<RemotionImportName, string>>;
const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
@@ -41,12 +63,221 @@ const makeEffectsArray = (calls: CallExpression[]): ArrayExpression => {
return b.arrayExpression(calls as never) as unknown as ArrayExpression;
};
+const isNonLinearEasing = (
+ easing: EffectClipboardKeyframedParam['easing'][number],
+) => easing !== 'linear';
+
+const keyframedParamNeedsEasingImport = (
+ param: EffectClipboardKeyframedParam,
+) => {
+ return (
+ param.interpolationFunction === 'interpolate' &&
+ param.easing.some(isNonLinearEasing)
+ );
+};
+
+const getRequiredRemotionImports = (
+ effects: EffectClipboardSnapshot[],
+): Set<RemotionImportName> => {
+ const requiredImports = new Set<RemotionImportName>();
+
+ for (const effect of effects) {
+ for (const param of Object.values(effect.params)) {
+ if (param.type !== 'keyframed') {
+ continue;
+ }
+
+ requiredImports.add('useCurrentFrame');
+ requiredImports.add(param.interpolationFunction);
+ if (keyframedParamNeedsEasingImport(param)) {
+ requiredImports.add('Easing');
+ }
+ }
+ }
+
+ return requiredImports;
+};
+
+const ensureRemotionImportLocalNames = ({
+ ast,
+ requiredImports,
+}: {
+ ast: File;
+ requiredImports: Set<RemotionImportName>;
+}): RemotionLocalNames => {
+ const localNames: RemotionLocalNames = {};
+ for (const importedName of requiredImports) {
+ localNames[importedName] = ensureNamedImport({
+ ast,
+ importedName,
+ sourcePath: 'remotion',
+ localName: importedName,
+ });
+ }
+
+ return localNames;
+};
+
+const makeEasingExpression = ({
+ easing,
+ easingLocalName,
+}: {
+ easing: EffectClipboardKeyframedParam['easing'][number];
+ easingLocalName: string;
+}): ExpressionKind => {
+ if (easing === 'linear') {
+ return b.memberExpression(
+ b.identifier(easingLocalName),
+ b.identifier('linear'),
+ ) as ExpressionKind;
+ }
+
+ return b.callExpression(
+ b.memberExpression(b.identifier(easingLocalName), b.identifier('bezier')),
+ easing.map((value) => parseValueExpression(value)) as never,
+ ) as ExpressionKind;
+};
+
+const makeKeyframedOptions = ({
+ param,
+ remotionLocalNames,
+}: {
+ param: EffectClipboardKeyframedParam;
+ remotionLocalNames: RemotionLocalNames;
+}): ObjectExpression | null => {
+ const properties: ObjectProperty[] = [];
+
+ if (param.interpolationFunction === 'interpolate') {
+ if (param.clamping.left !== 'extend') {
+ properties.push(
+ b.objectProperty(
+ b.identifier('extrapolateLeft'),
+ b.stringLiteral(param.clamping.left),
+ ) as ObjectProperty,
+ );
+ }
+
+ if (param.clamping.right !== 'extend') {
+ properties.push(
+ b.objectProperty(
+ b.identifier('extrapolateRight'),
+ b.stringLiteral(param.clamping.right),
+ ) as ObjectProperty,
+ );
+ }
+
+ if (keyframedParamNeedsEasingImport(param)) {
+ const easingLocalName = remotionLocalNames.Easing ?? 'Easing';
+ properties.push(
+ b.objectProperty(
+ b.identifier('easing'),
+ b.arrayExpression(
+ param.easing.map((easing) =>
+ makeEasingExpression({easing, easingLocalName}),
+ ) as never,
+ ),
+ ) as ObjectProperty,
+ );
+ }
+ }
+
+ if (param.posterize !== undefined) {
+ properties.push(
+ b.objectProperty(
+ b.identifier('posterize'),
+ parseValueExpression(param.posterize) as never,
+ ) as ObjectProperty,
+ );
+ }
+
+ if (properties.length === 0) {
+ return null;
+ }
+
+ return b.objectExpression(properties as never) as ObjectExpression;
+};
+
+const makeKeyframedExpression = ({
+ param,
+ remotionLocalNames,
+}: {
+ param: EffectClipboardKeyframedParam;
+ remotionLocalNames: RemotionLocalNames;
+}): ExpressionKind => {
+ const expectedEasingCount = Math.max(0, param.keyframes.length - 1);
+ if (param.easing.length !== expectedEasingCount) {
+ throw new Error('Cannot paste keyframed effect: invalid easing metadata');
+ }
+
+ const calleeName =
+ remotionLocalNames[param.interpolationFunction] ??
+ param.interpolationFunction;
+ const args: ExpressionKind[] = [
+ b.identifier('frame') as ExpressionKind,
+ b.arrayExpression(
+ param.keyframes.map((keyframe) =>
+ parseValueExpression(keyframe.frame),
+ ) as never,
+ ) as ExpressionKind,
+ b.arrayExpression(
+ param.keyframes.map((keyframe) =>
+ parseValueExpression(keyframe.value),
+ ) as never,
+ ) as ExpressionKind,
+ ];
+ const options = makeKeyframedOptions({param, remotionLocalNames});
+ if (options) {
+ args.push(options as ExpressionKind);
+ }
+
+ return b.callExpression(
+ b.identifier(calleeName),
+ args as never,
+ ) as ExpressionKind;
+};
+
+const makeParamExpression = ({
+ param,
+ remotionLocalNames,
+}: {
+ param: EffectClipboardParam;
+ remotionLocalNames: RemotionLocalNames;
+}): ExpressionKind => {
+ if (param.type === 'static') {
+ return parseValueExpression(param.value);
+ }
+
+ return makeKeyframedExpression({param, remotionLocalNames});
+};
+
+const makeParamsObjectExpression = ({
+ params,
+ remotionLocalNames,
+}: {
+ params: EffectClipboardSnapshot['params'];
+ remotionLocalNames: RemotionLocalNames;
+}): ObjectExpression => {
+ return b.objectExpression(
+ Object.entries(params).map(([key, param]) => {
+ const keyNode = identifierRegex.test(key)
+ ? b.identifier(key)
+ : b.stringLiteral(key);
+ return b.objectProperty(
+ keyNode as never,
+ makeParamExpression({param, remotionLocalNames}) as never,
+ ) as ObjectProperty;
+ }) as never,
+ ) as ObjectExpression;
+};
+
const makeEffectCall = ({
ast,
effect,
+ remotionLocalNames,
}: {
ast: ReturnType<typeof parseAst>;
effect: EffectClipboardSnapshot;
+ remotionLocalNames: RemotionLocalNames;
}): CallExpression => {
assertValidEffect({
effectName: effect.callee,
@@ -59,7 +290,10 @@ const makeEffectCall = ({
});
return b.callExpression(b.identifier(localName), [
- makeConfigObjectExpression(effect.params) as never,
+ makeParamsObjectExpression({
+ params: effect.params,
+ remotionLocalNames,
+ }) as never,
]) as unknown as CallExpression;
};
@@ -95,14 +329,32 @@ export const pasteEffects = async ({
readonly logLine: number;
}> => {
const ast = parseAst(input);
+ const targetJsxPath = getAstNodePath(ast, targetSequenceNodePath);
const targetJsx = findJsxElementAtNodePath(ast, targetSequenceNodePath);
- if (!targetJsx) {
+ if (!targetJsx || !targetJsxPath) {
throw new Error(
'Could not find a JSX element at the specified location to paste effects',
);
}
- const effectCalls = effects.map((effect) => makeEffectCall({ast, effect}));
+ const requiredRemotionImports = getRequiredRemotionImports(effects);
+ const remotionLocalNames = ensureRemotionImportLocalNames({
+ ast,
+ requiredImports: requiredRemotionImports,
+ });
+ if (requiredRemotionImports.has('useCurrentFrame')) {
+ const fnPath = findEnclosingFunctionPath(targetJsxPath);
+ if (fnPath) {
+ ensureUseCurrentFrameHook(
+ fnPath,
+ remotionLocalNames.useCurrentFrame ?? 'useCurrentFrame',
+ );
+ }
+ }
+
+ const effectCalls = effects.map((effect) =>
+ makeEffectCall({ast, effect, remotionLocalNames}),
+ );
const effectLabels = effects.map((effect) => `${effect.callee}()`);
const existingAttr = findEffectsAttr(targetJsx.attributes ?? []);
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
index f674897cb5..3974e5ca2b 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
@@ -45,9 +45,13 @@ export const ensureRemotionImports = (
ensureNamedImports({ast, importedNames: names, sourcePath: 'remotion'});
};
-const componentBodyHasFrameDeclaration = (
- body: FunctionNode['body'],
-): boolean => {
+const componentBodyHasFrameDeclaration = ({
+ body,
+ hookName,
+}: {
+ body: FunctionNode['body'];
+ hookName: string;
+}): boolean => {
if (!n.BlockStatement.check(body)) {
return false;
}
@@ -68,7 +72,7 @@ const componentBodyHasFrameDeclaration = (
decl.init &&
decl.init.type === 'CallExpression' &&
decl.init.callee.type === 'Identifier' &&
- decl.init.callee.name === 'useCurrentFrame'
+ decl.init.callee.name === hookName
) {
return true;
}
@@ -80,6 +84,7 @@ const componentBodyHasFrameDeclaration = (
export const ensureUseCurrentFrameHook = (
functionPath: recast.types.NodePath,
+ hookName = 'useCurrentFrame',
): void => {
const fn = functionPath.value as FunctionNode;
@@ -92,7 +97,7 @@ export const ensureUseCurrentFrameHook = (
]) as unknown as FunctionNode['body'];
}
- if (componentBodyHasFrameDeclaration(fn.body)) {
+ if (componentBodyHasFrameDeclaration({body: fn.body, hookName})) {
return;
}
@@ -103,7 +108,7 @@ export const ensureUseCurrentFrameHook = (
const frameDecl = b.variableDeclaration('const', [
b.variableDeclarator(
b.identifier('frame'),
- b.callExpression(b.identifier('useCurrentFrame'), []),
+ b.callExpression(b.identifier(hookName), []),
),
]);
diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.ts
index 6ab543d576..fc600c5a9c 100644
--- a/packages/studio-server/src/test/paste-effects.test.ts
+++ b/packages/studio-server/src/test/paste-effects.test.ts
@@ -22,6 +22,17 @@ const makeNodePath = (input: string, line: number) => ({
effectKeys: [],
});
+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;
+};
+
test('pasteEffects appends a copied effect to a target sequence', async () => {
const input = buildInput(`<>
<HtmlInCanvas effects={[blur({radius: 5})]} />
@@ -37,7 +48,7 @@ test('pasteEffects appends a copied effect to a target sequence', async () => {
{
callee: 'tint',
importPath: '@remotion/effects/tint',
- params: {color: 'red'},
+ params: {color: {type: 'static', value: 'red'}},
},
],
});
@@ -62,12 +73,12 @@ test('pasteEffects replaces existing effects with all copied effects', async ()
{
callee: 'tint',
importPath: '@remotion/effects/tint',
- params: {color: 'red'},
+ params: {color: {type: 'static', value: 'red'}},
},
{
callee: 'blur',
importPath: '@remotion/effects/blur',
- params: {radius: 10},
+ params: {radius: {type: 'static', value: 10}},
},
],
});
@@ -93,7 +104,7 @@ test('pasteEffects can paste after the source sequence no longer exists', async
{
callee: 'tint',
importPath: '@remotion/effects/tint',
- params: {amount: 0.8},
+ params: {amount: {type: 'static', value: 0.8}},
},
],
});
@@ -120,7 +131,7 @@ test('pasteEffects inserts imports for copied effects', async () => {
{
callee: 'tint',
importPath: '@remotion/effects/tint',
- params: {color: 'red'},
+ params: {color: {type: 'static', value: 'red'}},
},
],
});
@@ -144,7 +155,7 @@ test('pasteEffects does not duplicate an existing copied effect import', async (
{
callee: 'tint',
importPath: '@remotion/effects/tint',
- params: {color: 'red'},
+ params: {color: {type: 'static', value: 'red'}},
},
],
});
@@ -153,3 +164,137 @@ test('pasteEffects does not duplicate an existing copied effect import', async (
output.match(/import \{tint\} from '@remotion\/effects\/tint';/g)?.length,
).toBe(1);
});
+
+test('pasteEffects appends a keyframed effect and inserts frame dependencies', async () => {
+ const input = `import {HtmlInCanvas} from '@remotion/html-in-canvas';
+
+export const Comp = () => {
+ return (
+ <HtmlInCanvas />
+ );
+};
+`;
+ const target = makeNodePath(input, getLine(input, '<HtmlInCanvas'));
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0},
+ {frame: 100, value: 1},
+ ],
+ easing: [[0.1, 0.2, 0.3, 0.4]],
+ clamping: {left: 'clamp', right: 'wrap'},
+ posterize: 2,
+ },
+ },
+ },
+ ],
+ });
+
+ expect(output).toContain(
+ "import {brightness} from '@remotion/effects/brightness';",
+ );
+ expect(output).toContain('useCurrentFrame');
+ expect(output).toContain('interpolate');
+ expect(output).toContain('Easing');
+ expect(output).toContain('const frame = useCurrentFrame();');
+ expect(output).toContain('amount: interpolate(frame, [0, 100], [0, 1], {');
+ expect(output).toContain("extrapolateLeft: 'clamp'");
+ expect(output).toContain("extrapolateRight: 'wrap'");
+ expect(output).toContain('easing: [Easing.bezier(0.1, 0.2, 0.3, 0.4)]');
+ expect(output).toContain('posterize: 2');
+});
+
+test('pasteEffects uses aliased Remotion imports for keyframed effects', async () => {
+ const input = `import {HtmlInCanvas} from '@remotion/html-in-canvas';
+import {interpolate as i, useCurrentFrame as useFrame} from 'remotion';
+
+export const Comp = () => {
+ return (
+ <HtmlInCanvas />
+ );
+};
+`;
+ const target = makeNodePath(input, getLine(input, '<HtmlInCanvas'));
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0},
+ {frame: 100, value: 1},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'extend', right: 'extend'},
+ },
+ },
+ },
+ ],
+ });
+
+ expect(output).toContain('const frame = useFrame();');
+ expect(output).toContain('amount: i(frame, [0, 100], [0, 1])');
+});
+
+test('pasteEffects replaces existing effects with mixed static and keyframed params', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas effects={[tint({color: "blue"})]} />
+ </>`);
+ const target = makeNodePath(input, 9);
+
+ const {output, effectLabels} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-replacing',
+ effects: [
+ {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {
+ color: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolateColors',
+ keyframes: [
+ {frame: 0, value: 'red'},
+ {frame: 100, value: 'green'},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'clamp', right: 'clamp'},
+ posterize: 5,
+ },
+ amount: {type: 'static', value: 0.7},
+ },
+ },
+ ],
+ });
+
+ expect(effectLabels).toEqual(['tint()']);
+ expect(output).toContain(
+ "color: interpolateColors(frame, [0, 100], ['red', 'green'], {",
+ );
+ expect(output).toContain('posterize: 5');
+ expect(output).toContain('amount: 0.7');
+ expect(output).not.toMatch(/color: ['"]blue['"]/);
+});
diff --git a/packages/studio-shared/src/effect-clipboard-data.ts b/packages/studio-shared/src/effect-clipboard-data.ts
index 79b66e88a1..c208f03c59 100644
--- a/packages/studio-shared/src/effect-clipboard-data.ts
+++ b/packages/studio-shared/src/effect-clipboard-data.ts
@@ -1,14 +1,54 @@
export type EffectClipboardPasteType = 'effects-additive' | 'effects-replacing';
+export type EffectClipboardStaticParam = {
+ readonly type: 'static';
+ readonly value: unknown;
+};
+
+export type EffectClipboardInterpolationFunction =
+ | 'interpolate'
+ | 'interpolateColors';
+
+export type EffectClipboardKeyframe = {
+ readonly frame: number;
+ readonly value: unknown;
+};
+
+export type EffectClipboardEasing = 'linear' | [number, number, number, number];
+
+export type EffectClipboardExtrapolateType =
+ | 'extend'
+ | 'identity'
+ | 'clamp'
+ | 'wrap';
+
+export type EffectClipboardClamping = {
+ readonly left: EffectClipboardExtrapolateType;
+ readonly right: EffectClipboardExtrapolateType;
+};
+
+export type EffectClipboardKeyframedParam = {
+ readonly type: 'keyframed';
+ readonly interpolationFunction: EffectClipboardInterpolationFunction;
+ readonly keyframes: EffectClipboardKeyframe[];
+ readonly easing: EffectClipboardEasing[];
+ readonly clamping: EffectClipboardClamping;
+ readonly posterize?: number;
+};
+
+export type EffectClipboardParam =
+ | EffectClipboardStaticParam
+ | EffectClipboardKeyframedParam;
+
export type EffectClipboardSnapshot = {
readonly callee: string;
readonly importPath: string;
- readonly params: Record<string, unknown>;
+ readonly params: Record<string, EffectClipboardParam>;
};
export type EffectClipboardData = {
readonly type: EffectClipboardPasteType;
- readonly version: 2;
+ readonly version: 3;
readonly remotionClipboard: 'effects';
readonly effects: EffectClipboardSnapshot[];
};
@@ -17,7 +57,70 @@ const isRecord = (value: unknown): value is Record<string, unknown> => {
return typeof value === 'object' && value !== null && !Array.isArray(value);
};
-const isEffectClipboardSnapshot = (
+const extrapolateTypes = new Set(['extend', 'identity', 'clamp', 'wrap']);
+
+const isFiniteNumber = (value: unknown): value is number => {
+ return typeof value === 'number' && Number.isFinite(value);
+};
+
+const isEasing = (value: unknown): value is EffectClipboardEasing => {
+ return (
+ value === 'linear' ||
+ (Array.isArray(value) &&
+ value.length === 4 &&
+ value.every((item) => isFiniteNumber(item)))
+ );
+};
+
+const isKeyframe = (value: unknown): value is EffectClipboardKeyframe => {
+ return isRecord(value) && isFiniteNumber(value.frame) && 'value' in value;
+};
+
+const isClamping = (value: unknown): value is EffectClipboardClamping => {
+ return (
+ isRecord(value) &&
+ typeof value.left === 'string' &&
+ extrapolateTypes.has(value.left) &&
+ typeof value.right === 'string' &&
+ extrapolateTypes.has(value.right)
+ );
+};
+
+const isEffectClipboardParam = (
+ value: unknown,
+): value is EffectClipboardParam => {
+ if (!isRecord(value)) {
+ return false;
+ }
+
+ if (value.type === 'static') {
+ return 'value' in value;
+ }
+
+ if (value.type !== 'keyframed') {
+ return false;
+ }
+
+ const posterize = value.posterize;
+ const easingLength =
+ Array.isArray(value.keyframes) && value.keyframes.length > 0
+ ? value.keyframes.length - 1
+ : null;
+ return (
+ (value.interpolationFunction === 'interpolate' ||
+ value.interpolationFunction === 'interpolateColors') &&
+ Array.isArray(value.keyframes) &&
+ value.keyframes.length > 0 &&
+ value.keyframes.every(isKeyframe) &&
+ Array.isArray(value.easing) &&
+ value.easing.length === easingLength &&
+ value.easing.every(isEasing) &&
+ isClamping(value.clamping) &&
+ (posterize === undefined || (isFiniteNumber(posterize) && posterize > 0))
+ );
+};
+
+const isEffectClipboardSnapshotV3 = (
value: unknown,
): value is EffectClipboardSnapshot => {
if (!isRecord(value)) {
@@ -27,10 +130,41 @@ const isEffectClipboardSnapshot = (
return (
typeof value.callee === 'string' &&
typeof value.importPath === 'string' &&
- isRecord(value.params)
+ isRecord(value.params) &&
+ Object.values(value.params).every(isEffectClipboardParam)
);
};
+const normalizeV2Snapshot = (
+ value: unknown,
+): EffectClipboardSnapshot | null => {
+ if (!isRecord(value)) {
+ return null;
+ }
+
+ if (
+ typeof value.callee !== 'string' ||
+ typeof value.importPath !== 'string' ||
+ !isRecord(value.params)
+ ) {
+ return null;
+ }
+
+ const params: Record<string, EffectClipboardParam> = {};
+ for (const [key, paramValue] of Object.entries(value.params)) {
+ params[key] = {
+ type: 'static',
+ value: paramValue,
+ };
+ }
+
+ return {
+ callee: value.callee,
+ importPath: value.importPath,
+ params,
+ };
+};
+
export const parseEffectClipboardData = (
value: string,
): EffectClipboardData | null => {
@@ -42,20 +176,29 @@ export const parseEffectClipboardData = (
if (
parsed.remotionClipboard !== 'effects' ||
- parsed.version !== 2 ||
(parsed.type !== 'effects-additive' &&
parsed.type !== 'effects-replacing') ||
- !Array.isArray(parsed.effects) ||
- !parsed.effects.every(isEffectClipboardSnapshot)
+ !Array.isArray(parsed.effects)
) {
return null;
}
+ const effects =
+ parsed.version === 2
+ ? parsed.effects.map(normalizeV2Snapshot)
+ : parsed.version === 3 &&
+ parsed.effects.every(isEffectClipboardSnapshotV3)
+ ? parsed.effects
+ : null;
+ if (!effects || effects.some((effect) => effect === null)) {
+ return null;
+ }
+
return {
type: parsed.type,
- version: 2,
+ version: 3,
remotionClipboard: 'effects',
- effects: parsed.effects,
+ effects: effects as EffectClipboardSnapshot[],
};
} catch {
return null;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 4562d1ed0d..c8425dd554 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -79,9 +79,17 @@ export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';
export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';
export {
parseEffectClipboardData,
+ type EffectClipboardClamping,
type EffectClipboardData,
+ type EffectClipboardEasing,
+ type EffectClipboardExtrapolateType,
+ type EffectClipboardInterpolationFunction,
+ type EffectClipboardKeyframe,
+ type EffectClipboardKeyframedParam,
+ type EffectClipboardParam,
type EffectClipboardPasteType,
type EffectClipboardSnapshot,
+ type EffectClipboardStaticParam,
} from './effect-clipboard-data';
export {
EFFECT_DRAG_MIME_TYPE,
diff --git a/packages/studio-shared/src/test/effect-clipboard-data.test.ts b/packages/studio-shared/src/test/effect-clipboard-data.test.ts
new file mode 100644
index 0000000000..7f0baf3a90
--- /dev/null
+++ b/packages/studio-shared/src/test/effect-clipboard-data.test.ts
@@ -0,0 +1,116 @@
+import {expect, test} from 'bun:test';
+import {parseEffectClipboardData} from '../effect-clipboard-data';
+
+test('parseEffectClipboardData accepts keyframed v3 effect payloads', () => {
+ const parsed = parseEffectClipboardData(
+ JSON.stringify({
+ type: 'effects-additive',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0},
+ {frame: 100, value: 1},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'clamp', right: 'clamp'},
+ },
+ },
+ },
+ ],
+ }),
+ );
+
+ expect(parsed).toEqual({
+ type: 'effects-additive',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 0},
+ {frame: 100, value: 1},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'clamp', right: 'clamp'},
+ },
+ },
+ },
+ ],
+ });
+});
+
+test('parseEffectClipboardData normalizes old v2 static effect payloads', () => {
+ const parsed = parseEffectClipboardData(
+ JSON.stringify({
+ type: 'effects-replacing',
+ version: 2,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {radius: 10},
+ },
+ ],
+ }),
+ );
+
+ expect(parsed).toEqual({
+ type: 'effects-replacing',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {
+ radius: {
+ type: 'static',
+ value: 10,
+ },
+ },
+ },
+ ],
+ });
+});
+
+test('parseEffectClipboardData rejects malformed keyframed payloads', () => {
+ expect(
+ parseEffectClipboardData(
+ JSON.stringify({
+ type: 'effects-additive',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {
+ amount: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [{frame: 0, value: 0}],
+ easing: ['linear'],
+ clamping: {left: 'clamp', right: 'clamp'},
+ },
+ },
+ },
+ ],
+ }),
+ ),
+ ).toBe(null);
+});
diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
index 6372cf0882..79f75b30ae 100644
--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
@@ -1,6 +1,7 @@
import {
parseEffectClipboardData,
type EffectClipboardData,
+ type EffectClipboardParam,
type EffectClipboardPasteType,
type EffectClipboardSnapshot,
} from '@remotion/studio-shared';
@@ -125,15 +126,31 @@ const effectStatusToSnapshot = (
return null;
}
- const params: Record<string, unknown> = {};
+ const params: Record<string, EffectClipboardParam> = {};
for (const [key, prop] of Object.entries(effect.props)) {
- if (prop.status !== 'static') {
+ if (prop.status === 'computed') {
return null;
}
- if (prop.codeValue !== undefined) {
- params[key] = prop.codeValue;
+ if (prop.status === 'static') {
+ if (prop.codeValue !== undefined) {
+ params[key] = {
+ type: 'static',
+ value: prop.codeValue,
+ };
+ }
+
+ continue;
}
+
+ params[key] = {
+ type: 'keyframed',
+ interpolationFunction: prop.interpolationFunction,
+ keyframes: prop.keyframes,
+ easing: prop.easing,
+ clamping: prop.clamping,
+ ...(prop.posterize === undefined ? {} : {posterize: prop.posterize}),
+ };
}
return {
@@ -258,7 +275,7 @@ export const TimelineClipboardKeybindings: React.FC = () => {
.writeText(
makeClipboardText({
type,
- version: 2,
+ version: 3,
remotionClipboard: 'effects',
effects: snapshots as EffectClipboardSnapshot[],
}),
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 54bd764e09..fa38944888 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -145,7 +145,7 @@ test('pasting effects treats effect selections on one sequence as one target', (
} satisfies PasteEffectsTarget);
});
-test('copying a keyframed effect is blocked', () => {
+test('copying a keyframed effect creates a structured snapshot', () => {
const effectNodePathInfo = makeNodePathInfo(
['body', 0],
['effects', '0'],
@@ -168,7 +168,10 @@ test('copying a keyframed effect is blocked', () => {
status: 'keyframed',
codeValue: 10,
interpolationFunction: 'interpolate',
- keyframes: [{frame: 0, value: 10}],
+ keyframes: [
+ {frame: 0, value: 10},
+ {frame: 100, value: 20},
+ ],
easing: ['linear'],
clamping: {left: 'clamp', right: 'clamp'},
posterize: undefined,
@@ -188,7 +191,24 @@ test('copying a keyframed effect is blocked', () => {
},
codeValues,
}),
- ).toBe(null);
+ ).toEqual([
+ {
+ callee: 'effect',
+ importPath: '@remotion/effect',
+ params: {
+ intensity: {
+ type: 'keyframed',
+ interpolationFunction: 'interpolate',
+ keyframes: [
+ {frame: 0, value: 10},
+ {frame: 100, value: 20},
+ ],
+ easing: ['linear'],
+ clamping: {left: 'clamp', right: 'clamp'},
+ },
+ },
+ },
+ ]);
});
test('Timeline top drag should not be enabled', () => {