Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Snapshot copied effects

Jonny Burgerbcfa06cb6fbe
diff --git a/packages/core/src/SequenceManager.tsx b/packages/core/src/SequenceManager.tsx
index 248676035b..6302647a81 100644
--- a/packages/core/src/SequenceManager.tsx
+++ b/packages/core/src/SequenceManager.tsx
@@ -64,6 +64,7 @@ export type VisualModeSetters = {
export type CanUpdateEffectPropsResponseTrue = {
canUpdate: true;
callee: string;
+ importPath: string | null;
effectIndex: number;
props: Record<string, CanUpdateSequencePropStatus>;
};
diff --git a/packages/studio-server/src/codemods/add-effect.ts b/packages/studio-server/src/codemods/add-effect.ts
index 29c154766c..ee215b77a6 100644
--- a/packages/studio-server/src/codemods/add-effect.ts
+++ b/packages/studio-server/src/codemods/add-effect.ts
@@ -24,7 +24,7 @@ const b = recast.types.builders;
const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
-const assertValidEffect = ({
+export const assertValidEffect = ({
effectName,
effectImportPath,
}: {
@@ -156,7 +156,7 @@ const getAvailableLocalName = ({
throw new Error(`Cannot find a local name for ${effectName}`);
};
-const ensureEffectImport = ({
+export const ensureEffectImport = ({
ast,
effectName,
effectImportPath,
@@ -238,7 +238,7 @@ const makeEffectsAttr = (array: ArrayExpression): JSXAttribute => {
) as unknown as JSXAttribute;
};
-const makeConfigObjectExpression = (
+export const makeConfigObjectExpression = (
config: Record<string, unknown>,
): ObjectExpression => {
return b.objectExpression(
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.ts
index 8c39393564..a7c63fe75f 100644
--- a/packages/studio-server/src/codemods/paste-effects.ts
+++ b/packages/studio-server/src/codemods/paste-effects.ts
@@ -1,37 +1,30 @@
-import type {
- ArrayExpression,
- CallExpression,
- Expression,
- JSXAttribute,
-} from '@babel/types';
+import type {ArrayExpression, CallExpression, JSXAttribute} from '@babel/types';
import type {
EffectClipboardPasteType,
- EffectClipboardSource,
+ EffectClipboardSnapshot,
} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
+import {
+ assertValidEffect,
+ ensureEffectImport,
+ makeConfigObjectExpression,
+} from './add-effect';
import {formatFileContent} from './format-file-content';
import {parseAst, serializeAst} from './parse-ast';
-import {
- enumerateEffectArrayElements,
- findEffectCallExpression,
- findEffectsAttr,
-} from './update-effect-props/update-effect-props';
+import {findEffectsAttr} from './update-effect-props/update-effect-props';
const b = recast.types.builders;
-const getEffectsArray = (
- attr: JSXAttribute,
- action: 'read' | 'append',
-): ArrayExpression => {
+const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
- throw new Error(`Cannot ${action} effects: effects prop is not an array`);
+ throw new Error('Cannot append effects: effects prop is not an array');
}
- const expr = attr.value.expression as Expression;
+ const expr = attr.value.expression;
if (expr.type !== 'ArrayExpression') {
- throw new Error(`Cannot ${action} effects: effects prop is not an array`);
+ throw new Error('Cannot append effects: effects prop is not an array');
}
return expr;
@@ -48,88 +41,26 @@ const makeEffectsArray = (calls: CallExpression[]): ArrayExpression => {
return b.arrayExpression(calls as never) as unknown as ArrayExpression;
};
-const cloneCallExpression = (call: CallExpression): CallExpression => {
- const {code} = recast.print(call);
- const ast = parseAst(`const __remotionEffect = ${code};`);
- const stmt = ast.program.body[0];
- if (
- stmt.type !== 'VariableDeclaration' ||
- stmt.declarations[0]?.init?.type !== 'CallExpression'
- ) {
- throw new Error('Cannot paste effects: failed to clone effect expression');
- }
-
- return stmt.declarations[0].init as CallExpression;
-};
-
-const getSourceEffects = ({
- source,
- targetFileName,
+const makeEffectCall = ({
ast,
+ effect,
}: {
- readonly source: EffectClipboardSource;
- readonly targetFileName: string;
- readonly ast: ReturnType<typeof parseAst>;
-}): {calls: CallExpression[]; labels: string[]} => {
- if (source.fileName !== targetFileName) {
- throw new Error(
- 'Cannot paste effects from a different source file yet. Paste between sequences in the same file to preserve keyframes and referenced values.',
- );
- }
-
- const jsx = findJsxElementAtNodePath(
+ ast: ReturnType<typeof parseAst>;
+ effect: EffectClipboardSnapshot;
+}): CallExpression => {
+ assertValidEffect({
+ effectName: effect.callee,
+ effectImportPath: effect.importPath,
+ });
+ const localName = ensureEffectImport({
ast,
- source.sequenceNodePath.nodePath as SequenceNodePath,
- );
- if (!jsx) {
- throw new Error(
- 'Could not find a JSX element at the specified location to copy effects',
- );
- }
-
- const attr = findEffectsAttr(jsx.attributes ?? []);
- if (!attr) {
- if (source.type === 'all-effects') {
- return {calls: [], labels: []};
- }
-
- throw new Error('Could not find effects on the source JSX element');
- }
-
- if (source.type === 'single-effect') {
- const found = findEffectCallExpression({
- attr,
- effectIndex: source.effectIndex,
- });
- if (found.kind === 'error') {
- throw new Error(
- `Cannot paste source effect at index ${source.effectIndex}: ${found.reason}`,
- );
- }
-
- return {
- calls: [cloneCallExpression(found.call)],
- labels: [`${found.callee}()`],
- };
- }
-
- const effectsArray = getEffectsArray(attr, 'read');
- const elements = enumerateEffectArrayElements(effectsArray);
- const calls: CallExpression[] = [];
- const labels: string[] = [];
-
- for (const [index, effect] of elements.entries()) {
- if (effect.kind !== 'call') {
- throw new Error(
- `Cannot paste source effect at index ${index}: ${effect.reason}`,
- );
- }
-
- calls.push(cloneCallExpression(effect.node));
- labels.push(`${effect.callee}()`);
- }
+ effectName: effect.callee,
+ effectImportPath: effect.importPath,
+ });
- return {calls, labels};
+ return b.callExpression(b.identifier(localName), [
+ makeConfigObjectExpression(effect.params) as never,
+ ]) as unknown as CallExpression;
};
const removeEffectsAttr = (
@@ -146,17 +77,16 @@ const removeEffectsAttr = (
export const pasteEffects = async ({
input,
- targetFileName,
targetSequenceNodePath,
type,
- sources,
+ effects,
prettierConfigOverride,
}: {
readonly input: string;
readonly targetFileName: string;
readonly targetSequenceNodePath: SequenceNodePath;
readonly type: EffectClipboardPasteType;
- readonly sources: EffectClipboardSource[];
+ readonly effects: EffectClipboardSnapshot[];
readonly prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
readonly output: string;
@@ -165,12 +95,6 @@ export const pasteEffects = async ({
readonly logLine: number;
}> => {
const ast = parseAst(input);
- const copied = sources.map((source) =>
- getSourceEffects({source, targetFileName, ast}),
- );
- const effectCalls = copied.flatMap((item) => item.calls);
- const effectLabels = copied.flatMap((item) => item.labels);
-
const targetJsx = findJsxElementAtNodePath(ast, targetSequenceNodePath);
if (!targetJsx) {
throw new Error(
@@ -178,6 +102,9 @@ export const pasteEffects = async ({
);
}
+ const effectCalls = effects.map((effect) => makeEffectCall({ast, effect}));
+ const effectLabels = effects.map((effect) => `${effect.callee}()`);
+
const existingAttr = findEffectsAttr(targetJsx.attributes ?? []);
if (type === 'effects-replacing') {
@@ -189,7 +116,7 @@ export const pasteEffects = async ({
targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
}
} else if (existingAttr) {
- getEffectsArray(existingAttr, 'append').elements.push(
+ getEffectsArray(existingAttr).elements.push(
...(effectCalls as ArrayExpression['elements']),
);
} else if (effectCalls.length > 0) {
diff --git a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
index fd933ad261..2bd5f44910 100644
--- a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
+++ b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts
@@ -127,6 +127,7 @@ export const addEffectKeyframeHandler: ApiHandler<
}
return computeEffectPropStatus({
+ ast,
jsx,
effectIndex,
keys: getAllSchemaKeys(schema),
diff --git a/packages/studio-server/src/preview-server/routes/can-update-effect-props.ts b/packages/studio-server/src/preview-server/routes/can-update-effect-props.ts
index 5f3a0318a9..b883cee6bd 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-effect-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-effect-props.ts
@@ -2,6 +2,7 @@ import {readFileSync} from 'node:fs';
import type {
CallExpression,
Expression,
+ File,
JSXAttribute,
JSXOpeningElement,
ObjectExpression,
@@ -55,6 +56,89 @@ const getEffectsArrayElements = (
return enumerateEffectArrayElements(expr);
};
+const getImportedName = (specifier: {
+ readonly imported?: {
+ readonly type: string;
+ readonly name?: string;
+ readonly value?: string;
+ };
+}) => {
+ if (!specifier.imported) {
+ return null;
+ }
+
+ if (specifier.imported.type === 'Identifier') {
+ return specifier.imported.name ?? null;
+ }
+
+ return specifier.imported.value ?? null;
+};
+
+const resolveEffectImport = ({
+ ast,
+ call,
+ fallbackCallee,
+}: {
+ ast: File;
+ call: CallExpression;
+ fallbackCallee: string;
+}): {callee: string; importPath: string | null} => {
+ const {callee} = call;
+
+ if (callee.type === 'Identifier') {
+ const localName = callee.name;
+ for (const node of ast.program.body) {
+ if (node.type !== 'ImportDeclaration') {
+ continue;
+ }
+
+ const matchingSpecifier = node.specifiers?.find((specifier) => {
+ return (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.local?.name === localName
+ );
+ });
+
+ if (matchingSpecifier?.type === 'ImportSpecifier') {
+ return {
+ callee: getImportedName(matchingSpecifier) ?? fallbackCallee,
+ importPath: String(node.source.value),
+ };
+ }
+ }
+ }
+
+ if (
+ callee.type === 'MemberExpression' &&
+ callee.object.type === 'Identifier' &&
+ callee.property.type === 'Identifier' &&
+ !callee.computed
+ ) {
+ const namespaceName = callee.object.name;
+ for (const node of ast.program.body) {
+ if (node.type !== 'ImportDeclaration') {
+ continue;
+ }
+
+ const matchingSpecifier = node.specifiers?.find((specifier) => {
+ return (
+ specifier.type === 'ImportNamespaceSpecifier' &&
+ specifier.local?.name === namespaceName
+ );
+ });
+
+ if (matchingSpecifier) {
+ return {
+ callee: callee.property.name,
+ importPath: String(node.source.value),
+ };
+ }
+ }
+ }
+
+ return {callee: fallbackCallee, importPath: null};
+};
+
const getPropsFromObjectExpression = ({
objExpr,
keys,
@@ -94,10 +178,12 @@ const getPropsFromObjectExpression = ({
};
export const computeEffectPropStatus = ({
+ ast,
jsx,
effectIndex,
keys,
}: {
+ ast: File;
jsx: JSXOpeningElement;
effectIndex: number;
keys: string[];
@@ -131,6 +217,11 @@ export const computeEffectPropStatus = ({
}
const call: CallExpression = target.node;
+ const effectImport = resolveEffectImport({
+ ast,
+ call,
+ fallbackCallee: target.callee,
+ });
if (call.arguments.length === 0) {
const emptyProps: Record<string, CanUpdateSequencePropStatus> = {};
for (const key of keys) {
@@ -139,7 +230,8 @@ export const computeEffectPropStatus = ({
return {
canUpdate: true,
- callee: target.callee,
+ callee: effectImport.callee,
+ importPath: effectImport.importPath,
effectIndex,
props: emptyProps,
};
@@ -162,7 +254,8 @@ export const computeEffectPropStatus = ({
return {
canUpdate: true,
effectIndex,
- callee: target.callee,
+ callee: effectImport.callee,
+ importPath: effectImport.importPath,
props: resolvedProps,
};
};
@@ -190,6 +283,7 @@ export const computeEffectPropsStatusesFromContent = ({
return effects.map((effect, effectIndex) =>
computeEffectPropStatus({
+ ast,
jsx,
effectIndex,
keys: keysFor(effect),
diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
index 150000d5b9..9f1bfad58d 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -699,14 +699,17 @@ const getNestedPropStatus = (
};
const computeEffectsForJsx = ({
+ ast,
jsxElement,
effects,
}: {
+ ast: File;
jsxElement: JSXOpeningElement;
effects: string[][];
}) => {
return effects.map((effect, effectIndex) =>
computeEffectPropStatus({
+ ast,
jsx: jsxElement,
effectIndex,
keys: effect,
@@ -761,7 +764,7 @@ export const computeSequencePropsStatusFromContent = ({
}
const filteredProps = computeSequenceOnlyPropsRecord({jsxElement, keys});
- const effectsStatuses = computeEffectsForJsx({jsxElement, effects});
+ const effectsStatuses = computeEffectsForJsx({ast, jsxElement, effects});
return {
canUpdate: true as const,
diff --git a/packages/studio-server/src/preview-server/routes/delete-keyframes.ts b/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
index 6a0e7ff281..cf4765c5a1 100644
--- a/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
+++ b/packages/studio-server/src/preview-server/routes/delete-keyframes.ts
@@ -364,6 +364,7 @@ export const deleteKeyframes = async ({
}
return computeEffectPropStatus({
+ ast,
jsx,
effectIndex: keyframe.effectIndex,
keys: getAllSchemaKeys(keyframe.schema),
diff --git a/packages/studio-server/src/preview-server/routes/paste-effects.ts b/packages/studio-server/src/preview-server/routes/paste-effects.ts
index 46e7f5a48b..03167c17fb 100644
--- a/packages/studio-server/src/preview-server/routes/paste-effects.ts
+++ b/packages/studio-server/src/preview-server/routes/paste-effects.ts
@@ -29,18 +29,18 @@ export const pasteEffectsHandler: ApiHandler<
PasteEffectsRequest,
PasteEffectsResponse
> = async ({
- input: {targetFileName, targetSequenceNodePath, type, sources, clientId},
+ input: {targetFileName, targetSequenceNodePath, type, effects, clientId},
remotionRoot,
logLevel,
}) => {
try {
- if (sources.length === 0) {
+ if (effects.length === 0 && type !== 'effects-replacing') {
throw new Error('No effects were specified for pasting');
}
RenderInternals.Log.trace(
{indent: false, logLevel},
- `[paste-effects] Received request to paste ${sources.length} effect source${sources.length === 1 ? '' : 's'} into fileName="${targetFileName}"`,
+ `[paste-effects] Received request to paste ${effects.length} effect${effects.length === 1 ? '' : 's'} into fileName="${targetFileName}"`,
);
const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
@@ -55,7 +55,7 @@ export const pasteEffectsHandler: ApiHandler<
targetFileName,
targetSequenceNodePath: targetSequenceNodePath.nodePath,
type,
- sources,
+ effects,
});
const effectDescription = getPastedEffectDescription(effectLabels);
diff --git a/packages/studio-server/src/preview-server/routes/save-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
index 3b3a93bb50..386aa43049 100644
--- a/packages/studio-server/src/preview-server/routes/save-effect-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-effect-props.ts
@@ -151,6 +151,7 @@ export const saveEffectPropsHandler: ApiHandler<
}
return computeEffectPropStatus({
+ ast,
jsx,
effectIndex,
keys: getAllSchemaKeys(schema),
diff --git a/packages/studio-server/src/test/compute-effect-props-status.test.ts b/packages/studio-server/src/test/compute-effect-props-status.test.ts
index c8fb3e7a9e..761cfba4c5 100644
--- a/packages/studio-server/src/test/compute-effect-props-status.test.ts
+++ b/packages/studio-server/src/test/compute-effect-props-status.test.ts
@@ -25,13 +25,15 @@ const findJsx = (input: string) => {
throw new Error('JSX not found');
}
- return jsx;
+ return {ast, jsx};
};
test('computeEffectPropStatus reports static props as canUpdate=true with codeValue', () => {
const input = buildInput('[tint({color: "red", opacity: 0.5})]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['color', 'opacity'],
});
@@ -43,12 +45,15 @@ test('computeEffectPropStatus reports static props as canUpdate=true with codeVa
expect(result.props.color).toEqual({canUpdate: true, codeValue: 'red'});
expect(result.props.opacity).toEqual({canUpdate: true, codeValue: 0.5});
+ expect(result.importPath).toBe('@remotion/effects/tint');
});
test('computeEffectPropStatus reports computed props', () => {
const input = buildInput('[tint({color: getColor(), opacity: 0.5})]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['color', 'opacity'],
});
@@ -66,8 +71,10 @@ test('computeEffectPropStatus reports keyframes for inline interpolated effect p
const input = buildInput(
'[tint({amount: interpolate(frame, [0, 100], [0.2, 0.8])})]',
);
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['amount'],
});
@@ -93,8 +100,10 @@ test('computeEffectPropStatus reports keyframes for inline interpolated effect p
test('computeEffectPropStatus reports unset props as undefined codeValue', () => {
const input = buildInput('[tint({color: "red"})]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['color', 'opacity'],
});
@@ -110,8 +119,10 @@ test('computeEffectPropStatus reports unset props as undefined codeValue', () =>
test('computeEffectPropStatus flags non-call expressions', () => {
const input = buildInput('[someEffect, tint({color: "red"})]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['color'],
});
@@ -126,8 +137,10 @@ test('computeEffectPropStatus flags non-call expressions', () => {
test('computeEffectPropStatus flags out-of-range effect indices', () => {
const input = buildInput('[tint({color: "red"})]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 5,
keys: ['color'],
});
@@ -142,8 +155,10 @@ test('computeEffectPropStatus flags out-of-range effect indices', () => {
test('computeEffectPropStatus treats non-object first arg as computed', () => {
const input = buildInput('[tint(getParams())]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['color'],
});
@@ -158,8 +173,10 @@ test('computeEffectPropStatus treats non-object first arg as computed', () => {
test('computeEffectPropStatus treats zero-arg effect as editable with undefined props', () => {
const input = buildInput('[tint()]');
+ const {ast, jsx} = findJsx(input);
const result = computeEffectPropStatus({
- jsx: findJsx(input),
+ ast,
+ jsx,
effectIndex: 0,
keys: ['amount'],
});
diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.ts
index 6313a1b530..b58c7c4202 100644
--- a/packages/studio-server/src/test/paste-effects.test.ts
+++ b/packages/studio-server/src/test/paste-effects.test.ts
@@ -10,8 +10,8 @@ import {tint} from '@remotion/effects/tint';
import {interpolate, useCurrentFrame} from 'remotion';
export const Comp = () => {
-\tconst frame = useCurrentFrame();
-\treturn ${jsx};
+ const frame = useCurrentFrame();
+ return ${jsx};
};
`;
@@ -24,50 +24,50 @@ const makeNodePath = (input: string, line: number) => ({
test('pasteEffects appends a copied effect to a target sequence', async () => {
const input = buildInput(`<>
-\t\t<HtmlInCanvas effects={[tint({color: "red"})]} />
-\t\t<HtmlInCanvas effects={[blur({radius: 5})]} />
-\t</>`);
- const source = makeNodePath(input, 9);
- const target = makeNodePath(input, 10);
+ <HtmlInCanvas effects={[blur({radius: 5})]} />
+ </>`);
+ const target = makeNodePath(input, 9);
const {output, effectLabels} = await pasteEffects({
input,
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
- sources: [
+ effects: [
{
- type: 'single-effect',
- fileName: 'Comp.tsx',
- sequenceNodePath: source,
- effectIndex: 0,
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: 'red'},
},
],
});
expect(effectLabels).toEqual(['tint()']);
expect(output).toContain('blur({radius: 5})');
- expect(output).toMatch(/tint\(\{color: ['"]red['"]\}\)/);
+ expect(output).toMatch(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/);
});
test('pasteEffects replaces existing effects with all copied effects', async () => {
const input = buildInput(`<>
-\t\t<HtmlInCanvas effects={[tint({color: "red"}), blur({radius: 10})]} />
-\t\t<HtmlInCanvas effects={[tint({color: "blue"})]} />
-\t</>`);
- const source = makeNodePath(input, 9);
- const target = makeNodePath(input, 10);
+ <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',
- sources: [
+ effects: [
{
- type: 'all-effects',
- fileName: 'Comp.tsx',
- sequenceNodePath: source,
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: 'red'},
+ },
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {radius: 10},
},
],
});
@@ -78,58 +78,53 @@ test('pasteEffects replaces existing effects with all copied effects', async ()
expect(output).not.toMatch(/color: ['"]blue['"]/);
});
-test('pasteEffects preserves inline effect keyframes in the same file', async () => {
+test('pasteEffects can paste after the source sequence no longer exists', async () => {
const input = buildInput(`<>
-\t\t<HtmlInCanvas
-\t\t\teffects={[tint({amount: interpolate(frame, [0, 20], [0.2, 0.8])})]}
-\t\t/>
-\t\t<HtmlInCanvas />
-\t</>`);
- const source = makeNodePath(input, 9);
- const target = makeNodePath(input, 12);
+ <HtmlInCanvas />
+ </>`);
+ const target = makeNodePath(input, 9);
const {output} = await pasteEffects({
input,
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
- sources: [
+ effects: [
{
- type: 'single-effect',
- fileName: 'Comp.tsx',
- sequenceNodePath: source,
- effectIndex: 0,
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {amount: 0.8},
},
],
});
- expect(output).toContain(
- 'tint({amount: interpolate(frame, [0, 20], [0.2, 0.8])})',
- );
+ expect(output).toMatch(/tint\(\{\s*amount: 0.8,?\s*\}\)/);
});
-test('pasteEffects rejects cross-file pastes to avoid broken keyframe references', async () => {
+test('pasteEffects inserts imports for copied effects', async () => {
const input = buildInput(`<>
-\t\t<HtmlInCanvas effects={[tint({color: "red"})]} />
-\t\t<HtmlInCanvas />
-\t</>`);
- const source = makeNodePath(input, 9);
- const target = makeNodePath(input, 10);
+ <HtmlInCanvas />
+ </>`);
+ const inputWithoutTintImport = input.replace(
+ "import {tint} from '@remotion/effects/tint';\n",
+ '',
+ );
+ const target = makeNodePath(inputWithoutTintImport, 8);
+
+ const {output} = await pasteEffects({
+ input: inputWithoutTintImport,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ effects: [
+ {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: 'red'},
+ },
+ ],
+ });
- await expect(
- pasteEffects({
- input,
- targetFileName: 'Comp.tsx',
- targetSequenceNodePath: target.nodePath,
- type: 'effects-additive',
- sources: [
- {
- type: 'single-effect',
- fileName: 'Other.tsx',
- sequenceNodePath: source,
- effectIndex: 0,
- },
- ],
- }),
- ).rejects.toThrow(/different source file/);
+ expect(output).toContain("import {tint} from '@remotion/effects/tint';");
+ expect(output).toMatch(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/);
});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 2729b97ee6..562c767e86 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -24,7 +24,7 @@ import type {
import type {RecastCodemod, VisualControlChange} from './codemods';
import type {
EffectClipboardPasteType,
- EffectClipboardSource,
+ EffectClipboardSnapshot,
} from './effect-clipboard-data';
import type {PackageManager} from './package-manager';
import type {ProjectInfo} from './project-info';
@@ -443,7 +443,7 @@ export type PasteEffectsRequest = {
targetFileName: string;
targetSequenceNodePath: SequencePropsSubscriptionKey;
type: EffectClipboardPasteType;
- sources: EffectClipboardSource[];
+ effects: EffectClipboardSnapshot[];
clientId: string;
};
diff --git a/packages/studio-shared/src/effect-clipboard-data.ts b/packages/studio-shared/src/effect-clipboard-data.ts
index 66bdd9844c..07f4049da3 100644
--- a/packages/studio-shared/src/effect-clipboard-data.ts
+++ b/packages/studio-shared/src/effect-clipboard-data.ts
@@ -1,88 +1,36 @@
-import type {SequencePropsSubscriptionKey} from 'remotion';
-
export const EFFECT_CLIPBOARD_MIME_TYPE =
'application/vnd.remotion.effects-clipboard+json';
export type EffectClipboardPasteType = 'effects-additive' | 'effects-replacing';
-export type EffectClipboardSource = {
- readonly fileName: string;
- readonly sequenceNodePath: SequencePropsSubscriptionKey;
-} & (
- | {
- readonly type: 'single-effect';
- readonly effectIndex: number;
- }
- | {
- readonly type: 'all-effects';
- }
-);
+export type EffectClipboardSnapshot = {
+ readonly callee: string;
+ readonly importPath: string;
+ readonly params: Record<string, unknown>;
+};
export type EffectClipboardData = {
readonly type: EffectClipboardPasteType;
- readonly version: 1;
+ readonly version: 2;
readonly remotionClipboard: 'effects';
- readonly sources: EffectClipboardSource[];
+ readonly effects: EffectClipboardSnapshot[];
};
const isRecord = (value: unknown): value is Record<string, unknown> => {
return typeof value === 'object' && value !== null && !Array.isArray(value);
};
-const isStringArray = (value: unknown): value is string[] => {
- return (
- Array.isArray(value) && value.every((item) => typeof item === 'string')
- );
-};
-
-const isStringArrayArray = (value: unknown): value is string[][] => {
- return Array.isArray(value) && value.every(isStringArray);
-};
-
-const isSequenceNodePath = (
- value: unknown,
-): value is SequencePropsSubscriptionKey => {
- if (!isRecord(value)) {
- return false;
- }
-
- if (
- typeof value.absolutePath !== 'string' ||
- !Array.isArray(value.nodePath) ||
- !isStringArray(value.sequenceKeys) ||
- !isStringArrayArray(value.effectKeys)
- ) {
- return false;
- }
-
- return value.nodePath.every(
- (item) => typeof item === 'string' || typeof item === 'number',
- );
-};
-
-const isEffectClipboardSource = (
+const isEffectClipboardSnapshot = (
value: unknown,
-): value is EffectClipboardSource => {
+): value is EffectClipboardSnapshot => {
if (!isRecord(value)) {
return false;
}
- if (
- typeof value.fileName !== 'string' ||
- !isSequenceNodePath(value.sequenceNodePath)
- ) {
- return false;
- }
-
- if (value.type === 'all-effects') {
- return true;
- }
-
return (
- value.type === 'single-effect' &&
- typeof value.effectIndex === 'number' &&
- Number.isInteger(value.effectIndex) &&
- value.effectIndex >= 0
+ typeof value.callee === 'string' &&
+ typeof value.importPath === 'string' &&
+ isRecord(value.params)
);
};
@@ -97,20 +45,20 @@ export const parseEffectClipboardData = (
if (
parsed.remotionClipboard !== 'effects' ||
- parsed.version !== 1 ||
+ parsed.version !== 2 ||
(parsed.type !== 'effects-additive' &&
parsed.type !== 'effects-replacing') ||
- !Array.isArray(parsed.sources) ||
- !parsed.sources.every(isEffectClipboardSource)
+ !Array.isArray(parsed.effects) ||
+ !parsed.effects.every(isEffectClipboardSnapshot)
) {
return null;
}
return {
type: parsed.type,
- version: 1,
+ version: 2,
remotionClipboard: 'effects',
- sources: parsed.sources,
+ effects: parsed.effects,
};
} catch {
return null;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index b7dae5318b..0b30ecc2e2 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -82,7 +82,7 @@ export {
parseEffectClipboardData,
type EffectClipboardData,
type EffectClipboardPasteType,
- type EffectClipboardSource,
+ type EffectClipboardSnapshot,
} from './effect-clipboard-data';
export {
EFFECT_DRAG_MIME_TYPE,
diff --git a/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts b/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
index 79c4a2d5cb..832371987c 100644
--- a/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
+++ b/packages/studio-shared/src/test/optimistic-add-keyframe.test.ts
@@ -90,6 +90,7 @@ test('optimisticAddEffectKeyframe appends a keyframe on the target effect', () =
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {
canUpdate: false,
@@ -142,6 +143,7 @@ test('optimisticAddEffectKeyframe converts a static prop to a single keyframe',
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {
canUpdate: true,
diff --git a/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts b/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts
index d92a354d15..7684f2e77e 100644
--- a/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts
+++ b/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts
@@ -177,6 +177,7 @@ test('optimisticDeleteEffectKeyframe removes the matching keyframe on the target
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {
canUpdate: false,
@@ -229,6 +230,7 @@ test('optimisticDeleteEffectKeyframe converts the last keyframe on the target ef
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {
canUpdate: false,
@@ -292,6 +294,7 @@ test('optimisticDeleteEffectKeyframes deletes multiple keyframes in one pass', (
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {
canUpdate: false,
diff --git a/packages/studio-shared/src/test/optimistic-update-for-effect-code-values.test.ts b/packages/studio-shared/src/test/optimistic-update-for-effect-code-values.test.ts
index 207f86165d..8e5e2d95ad 100644
--- a/packages/studio-shared/src/test/optimistic-update-for-effect-code-values.test.ts
+++ b/packages/studio-shared/src/test/optimistic-update-for-effect-code-values.test.ts
@@ -15,6 +15,7 @@ test('optimisticUpdateForEffectCodeValues updates the matching effect prop', ()
opacity: {canUpdate: true, codeValue: 0.5},
},
callee: 'tint',
+ importPath: null,
},
],
};
@@ -84,6 +85,7 @@ test('optimisticUpdateForEffectCodeValues applies when effect props are unset (z
canUpdate: true,
effectIndex: 0,
callee: 'tint',
+ importPath: null,
props: {
amount: {canUpdate: true, codeValue: undefined},
},
diff --git a/packages/studio-shared/src/test/schema-field-info.test.ts b/packages/studio-shared/src/test/schema-field-info.test.ts
index 1b5a907e7e..1d5b88cb8e 100644
--- a/packages/studio-shared/src/test/schema-field-info.test.ts
+++ b/packages/studio-shared/src/test/schema-field-info.test.ts
@@ -58,6 +58,7 @@ test('getEffectFieldsToShow uses the active enum variant', () => {
{
canUpdate: true,
callee: 'halftone',
+ importPath: null,
effectIndex: 0,
props: {
colorMode: {canUpdate: true, codeValue: 'source'},
diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
index ed0127acac..0fb49d1508 100644
--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
@@ -1,11 +1,11 @@
import {
parseEffectClipboardData,
type EffectClipboardData,
- type EffectClipboardSource,
+ type EffectClipboardSnapshot,
} from '@remotion/studio-shared';
import type React from 'react';
import {useContext, useEffect} from 'react';
-import type {SequencePropsSubscriptionKey} from 'remotion';
+import {Internals, type SequencePropsSubscriptionKey} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {useKeybinding} from '../../helpers/use-keybinding';
import {callApi} from '../call-api';
@@ -28,31 +28,6 @@ const makeTargetKey = (nodePath: SequencePropsSubscriptionKey): string => {
});
};
-const sourceFromSelection = (
- selection: TimelineSelection,
-): EffectClipboardSource | null => {
- if (selection.type === 'sequence-effect') {
- const {sequenceSubscriptionKey} = selection.nodePathInfo;
- return {
- type: 'single-effect',
- fileName: sequenceSubscriptionKey.absolutePath,
- sequenceNodePath: sequenceSubscriptionKey,
- effectIndex: selection.i,
- };
- }
-
- if (selection.type === 'sequence-all-effects') {
- const {sequenceSubscriptionKey} = selection.nodePathInfo;
- return {
- type: 'all-effects',
- fileName: sequenceSubscriptionKey.absolutePath,
- sequenceNodePath: sequenceSubscriptionKey,
- };
- }
-
- return null;
-};
-
const getTargetSequenceNodePath = (
selection: TimelineSelection,
): SequencePropsSubscriptionKey | null => {
@@ -67,11 +42,106 @@ const getTargetSequenceNodePath = (
return null;
};
+type CopyableEffectStatus = {
+ readonly canUpdate: true;
+ readonly callee: string;
+ readonly importPath: string | null;
+ readonly props: Record<
+ string,
+ | {
+ readonly canUpdate: true;
+ readonly codeValue?: unknown;
+ }
+ | {
+ readonly canUpdate: false;
+ }
+ >;
+};
+
+const effectStatusToSnapshot = (
+ effect: CopyableEffectStatus,
+): EffectClipboardSnapshot | null => {
+ if (effect.importPath === null) {
+ return null;
+ }
+
+ const params: Record<string, unknown> = {};
+ for (const [key, prop] of Object.entries(effect.props)) {
+ if (!prop.canUpdate) {
+ return null;
+ }
+
+ if (prop.codeValue !== undefined) {
+ params[key] = prop.codeValue;
+ }
+ }
+
+ return {
+ callee: effect.callee,
+ importPath: effect.importPath,
+ params,
+ };
+};
+
+const getSnapshotsFromSelection = ({
+ selection,
+ codeValues,
+}: {
+ selection: TimelineSelection;
+ codeValues: React.ContextType<
+ typeof Internals.VisualModeCodeValuesContext
+ >['codeValues'];
+}): EffectClipboardSnapshot[] | null => {
+ if (
+ selection.type !== 'sequence-effect' &&
+ selection.type !== 'sequence-all-effects'
+ ) {
+ return null;
+ }
+
+ const {sequenceSubscriptionKey} = selection.nodePathInfo;
+ const sequenceStatus =
+ codeValues[
+ Internals.makeSequencePropsSubscriptionKey(sequenceSubscriptionKey)
+ ];
+ if (!sequenceStatus || !sequenceStatus.canUpdate) {
+ return null;
+ }
+
+ const effects =
+ selection.type === 'sequence-effect'
+ ? sequenceStatus.effects.filter(
+ (effect) => effect.effectIndex === selection.i,
+ )
+ : sequenceStatus.effects;
+
+ if (selection.type === 'sequence-effect' && effects.length !== 1) {
+ return null;
+ }
+
+ const snapshots: EffectClipboardSnapshot[] = [];
+ for (const effect of effects) {
+ if (!effect.canUpdate) {
+ return null;
+ }
+
+ const snapshot = effectStatusToSnapshot(effect);
+ if (snapshot === null) {
+ return null;
+ }
+
+ snapshots.push(snapshot);
+ }
+
+ return snapshots;
+};
+
export const TimelineClipboardKeybindings: React.FC = () => {
const keybindings = useKeybinding();
const {previewServerState} = useContext(StudioServerConnectionCtx);
const {canSelect} = useTimelineSelection();
const currentSelection = useCurrentTimelineSelectionStateAsRef();
+ const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);
useEffect(() => {
if (!canSelect || previewServerState.type !== 'connected') {
@@ -89,11 +159,6 @@ export const TimelineClipboardKeybindings: React.FC = () => {
return;
}
- const sources = selectedItems.map(sourceFromSelection);
- if (sources.some((source) => source === null)) {
- return;
- }
-
const firstSelection = selectedItems[0];
const type =
firstSelection?.type === 'sequence-effect'
@@ -106,19 +171,35 @@ export const TimelineClipboardKeybindings: React.FC = () => {
return;
}
+ const snapshots = selectedItems.flatMap((selection) => {
+ const itemSnapshots = getSnapshotsFromSelection({
+ selection,
+ codeValues,
+ });
+ return itemSnapshots ?? [null];
+ });
+ if (snapshots.some((snapshot) => snapshot === null)) {
+ e.preventDefault();
+ showNotification(
+ 'Cannot copy effects because one of them contains values that cannot be copied',
+ 3000,
+ );
+ return;
+ }
+
e.preventDefault();
navigator.clipboard
.writeText(
makeClipboardText({
type,
- version: 1,
+ version: 2,
remotionClipboard: 'effects',
- sources: sources as EffectClipboardSource[],
+ effects: snapshots as EffectClipboardSnapshot[],
}),
)
.then(() => {
showNotification(
- sources.length === 1
+ snapshots.length === 1
? 'Copied effect to clipboard'
: 'Copied effects to clipboard',
1000,
@@ -184,7 +265,7 @@ export const TimelineClipboardKeybindings: React.FC = () => {
targetFileName: targetSequenceNodePath.absolutePath,
targetSequenceNodePath,
type: payload.type,
- sources: payload.sources,
+ effects: payload.effects,
clientId,
}).then((result) => {
if (result.success) {
@@ -211,7 +292,13 @@ export const TimelineClipboardKeybindings: React.FC = () => {
copy.unregister();
paste.unregister();
};
- }, [canSelect, currentSelection, keybindings, previewServerState]);
+ }, [
+ canSelect,
+ codeValues,
+ currentSelection,
+ keybindings,
+ previewServerState,
+ ]);
return null;
};
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index b5f291b24d..6670a55ebe 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -351,6 +351,7 @@ test('Backspace reset targets selected effect props', () => {
{
canUpdate: true,
callee: 'effect',
+ importPath: null,
effectIndex: 0,
props: {
intensity: {canUpdate: true, codeValue: 10},