🎥 Make videos programmatically with React
`@remotion/studio`: Copy properties between components (#10361)
Jonny Burger06d42a533cf4
diff --git a/packages/browser-studio/src/save-sequence-props.ts b/packages/browser-studio/src/save-sequence-props.tsindex 5b1b9224ee..18cd138b66 100644--- a/packages/browser-studio/src/save-sequence-props.ts+++ b/packages/browser-studio/src/save-sequence-props.ts@@ -12,6 +12,7 @@ import type {SaveSequencePropsResult,} from '@remotion/studio-shared';import {getAllSchemaKeys, getAssetSchemaKeys} from '@remotion/studio-shared';+import type {SequenceNodePath} from 'remotion';import type {VirtualProject} from './types';const parseSequencePropEditValue = (@@ -103,6 +104,7 @@ export const saveSequencePropsInProject = ({}const nextFiles = {...project.files};+ const updatedNodePaths = new Map<string, SequenceNodePath>();for (const [absolutePath, mutation] of mutations) {let output = project.files[absolutePath];if (output === undefined) {@@ -122,12 +124,27 @@ export const saveSequencePropsInProject = ({edit.sourceEdit?.type === 'google-font'? edit.sourceEdit.font: null,+ clipboardParam:+ edit.sourceEdit?.type === 'clipboard-param'+ ? edit.sourceEdit.param+ : null,},],schema: edit.schema,videoConfigValues: edit.nodePath.videoConfigValues,}));- output = updateMultipleSequenceProps({input: output, changes}).output;+ const updateResult = updateMultipleSequenceProps({+ input: output,+ changes,+ });+ output = updateResult.output;+ for (const [index, result] of updateResult.results.entries()) {+ const edit = mutation.edits[index];+ updatedNodePaths.set(+ `${absolutePath}:${JSON.stringify(edit.nodePath.nodePath)}`,+ result.newNodePath,+ );+ }}for (const captionPatch of mutation.captionPatches) {@@ -152,7 +169,10 @@ export const saveSequencePropsInProject = ({fileContents: nextFiles[absolutePath],keys: getAllSchemaKeys(target.schema),assetKeys: getAssetSchemaKeys(target.schema),- nodePath: target.nodePath.nodePath,+ nodePath:+ updatedNodePaths.get(+ `${absolutePath}:${JSON.stringify(target.nodePath.nodePath)}`,+ ) ?? target.nodePath.nodePath,componentIdentity: null,effects: [],videoConfigValues: target.nodePath.videoConfigValues,diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 38a5288720..9282503350 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -492,6 +492,47 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio});expect(currentProject.files[fileName]).toContain('from={15}');+ await operations.saveSequenceProps({+ edits: [+ {+ fileName: request.fileName,+ nodePath: subscription.nodePath,+ key: 'style.rotate',+ value: {type: 'undefined'},+ defaultValue: JSON.stringify('0deg'),+ schema: {+ 'style.rotate': {type: 'rotation-css', default: '0deg'},+ },+ sourceEdit: {+ type: 'clipboard-param',+ param: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0deg'},+ {frame: 30, value: '90deg'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ },+ ],+ addedKeyframes: null,+ movedKeyframes: null,+ clientId: request.clientId,+ undoLabel: 'Paste property',+ redoLabel: 'Reapply property paste',+ });+ expect(currentProject.files[fileName]).toContain(+ 'rotate: interpolate(frame, [0, 30], ["0deg", "90deg"])',+ );+ expect(await operations.undo()).toEqual({+ success: true,+ nodePathMutation: null,+ });+ expect(currentProject.files[fileName]).not.toContain('style={{rotate:');+currentProject = {...currentProject,files: {diff --git a/packages/example/e2e/effect-keyframes.test.mts b/packages/example/e2e/effect-keyframes.test.mtsindex 11a009244f..192a60bf5a 100644--- a/packages/example/e2e/effect-keyframes.test.mts+++ b/packages/example/e2e/effect-keyframes.test.mts@@ -156,6 +156,12 @@ test.describe('effect keyframes', () => {{timeout: 30_000},);+ const timelineExpansionLabel = page+ .getByText('Timeline expansion', {exact: true})+ .last();+ const timelineExpansionRow = timelineExpansionLabel+ .locator('..')+ .locator('..');const opacityRow = page.getByText('Opacity', {exact: true});await expect(async () => {await page@@ -165,13 +171,17 @@ test.describe('effect keyframes', () => {await expect(opacityRow).toHaveCount(1, {timeout: 1_000});}).toPass({timeout: 15_000});await expect(- page.locator('button[aria-label="Expand track properties"]'),+ timelineExpansionRow.getByRole('button', {+ name: 'Expand track properties',+ }),).toBeVisible();await opacityRow.click();await expect(- page.locator('button[aria-label="Collapse track properties"]'),+ timelineExpansionRow.getByRole('button', {+ name: 'Collapse track properties',+ }),).toBeVisible();await expect(opacityRow).toHaveCount(2);diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mtsindex 1f33ca975b..87594b7431 100644--- a/packages/example/e2e/studio.test.mts+++ b/packages/example/e2e/studio.test.mts@@ -133,6 +133,55 @@ test.describe('visual mode', () => {expect(scrollTopAfter).toBeGreaterThan(0);});+ test('should copy a keyframed property between component types', async ({+ context,+ page,+ }) => {+ await context.grantPermissions(['clipboard-read', 'clipboard-write'], {+ origin: STUDIO_URL,+ });+ await page.goto(`${STUDIO_URL}/effect-keyframe-e2e`);+ await page.bringToFront();+ await page.evaluate(() => navigator.clipboard.writeText(''));+ const sourceRow = page.locator(+ '[data-timeline-marquee-item][title="Copy rotation source"]',+ );+ const targetRow = page.locator(+ '[data-timeline-marquee-item][title="Copy rotation target"]',+ );+ await expect(sourceRow).toBeVisible({timeout: 15_000});+ await page+ .getByTitle('Copy rotation source', {exact: true})+ .first()+ .click({button: 'right'});+ await page.getByRole('button', {name: 'Rotate', exact: true}).click();+ await page.keyboard.press('ControlOrMeta+c');++ await page+ .getByTitle('Copy rotation target', {exact: true})+ .first()+ .click({button: 'right'});+ await page.getByRole('button', {name: 'Rotate', exact: true}).click();+ await page.keyboard.press('ControlOrMeta+v');++ await expect+ .poll(() => {+ const source = fs.readFileSync(effectKeyframeE2eFile, 'utf-8');+ const targetNameIndex = source.indexOf('name="Copy rotation target"');+ const tagStart = source.lastIndexOf('<AbsoluteFill', targetNameIndex);+ const tagEnd = source.indexOf('/>', targetNameIndex);+ return source.slice(tagStart, tagEnd + 2);+ })+ .toContain("rotate: interpolate(frame, [0, 30], ['0deg', '90deg'])");++ await page.getByRole('button', {name: /^Undo/}).click();+ await expect+ .poll(() => fs.readFileSync(effectKeyframeE2eFile, 'utf-8'))+ .toContain(+ '<AbsoluteFill name="Copy rotation target" style={{rotate: \'0deg\'}} />',+ );+ });+test('should keep canvas item context menus open', async ({page}) => {await page.goto(`${STUDIO_URL}/AnimatedBarChart`);await expect(diff --git a/packages/example/src/EffectKeyframeE2e.tsx b/packages/example/src/EffectKeyframeE2e.tsxindex b6169c2ead..1731168cd7 100644--- a/packages/example/src/EffectKeyframeE2e.tsx+++ b/packages/example/src/EffectKeyframeE2e.tsx@@ -1,12 +1,26 @@import {wave} from '@remotion/effects/wave';+import {Video} from '@remotion/media';import React from 'react';-import {AbsoluteFill, interpolate, Solid, useCurrentFrame} from 'remotion';+import {+ AbsoluteFill,+ interpolate,+ Solid,+ staticFile,+ useCurrentFrame,+} from 'remotion';export const EffectKeyframeE2e: React.FC = () => {const frame = useCurrentFrame();return (<AbsoluteFill>+ <Video+ name="Copy rotation source"+ src={staticFile('framer.webm')}+ durationInFrames={90}+ style={{rotate: interpolate(frame, [0, 30], ['0deg', '90deg'])}}+ />+ <AbsoluteFill name="Copy rotation target" style={{rotate: '0deg'}} /><Solidname="Scale precision"width={1080}diff --git a/packages/studio-codemods/src/sequence-props/clipboard-param-expression.ts b/packages/studio-codemods/src/sequence-props/clipboard-param-expression.tsnew file mode 100644index 0000000000..cf3abbed17--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/clipboard-param-expression.ts@@ -0,0 +1,246 @@+import type {File, ObjectExpression, ObjectProperty} from '@babel/types';+import type {+ EffectClipboardKeyframedParam,+ EffectClipboardParam,+} from '@remotion/studio-shared';+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';+import * as recast from 'recast';+import {parseValueExpression} from '../update-nested-prop';+import {ensureNamedImport} from './imports';++const b = recast.types.builders;++export type ClipboardParamRemotionImportName =+ | 'Easing'+ | 'interpolate'+ | 'interpolateColors'+ | 'useCurrentFrame';++export type ClipboardParamRemotionLocalNames = Partial<+ Record<ClipboardParamRemotionImportName, string>+>;++export const getRequiredRemotionImportsForClipboardParams = (+ params: Iterable<EffectClipboardParam>,+): Set<ClipboardParamRemotionImportName> => {+ const requiredImports = new Set<ClipboardParamRemotionImportName>();+ for (const param of params) {+ if (param.type !== 'keyframed') {+ continue;+ }++ requiredImports.add('useCurrentFrame');+ requiredImports.add(param.interpolationFunction);+ if (param.easing.some((easing) => easing.type !== 'linear')) {+ requiredImports.add('Easing');+ }+ }++ return requiredImports;+};++export const ensureClipboardParamRemotionImports = ({+ ast,+ requiredImports,+}: {+ ast: File;+ requiredImports: Set<ClipboardParamRemotionImportName>;+}): ClipboardParamRemotionLocalNames => {+ const localNames: ClipboardParamRemotionLocalNames = {};+ 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 => {+ switch (easing.type) {+ case 'linear':+ return b.memberExpression(+ b.identifier(easingLocalName),+ b.identifier('linear'),+ ) as ExpressionKind;+ case 'step1':+ return b.memberExpression(+ b.identifier(easingLocalName),+ b.identifier('step1'),+ ) as ExpressionKind;+ case 'spring':+ return b.callExpression(+ b.memberExpression(+ b.identifier(easingLocalName),+ b.identifier('spring'),+ ),+ [+ b.objectExpression([+ b.objectProperty(+ b.identifier('damping'),+ parseValueExpression(easing.damping),+ ),+ b.objectProperty(+ b.identifier('mass'),+ parseValueExpression(easing.mass),+ ),+ b.objectProperty(+ b.identifier('stiffness'),+ parseValueExpression(easing.stiffness),+ ),+ ...(easing.allowTail === null+ ? []+ : [+ b.objectProperty(+ b.identifier('allowTail'),+ b.booleanLiteral(easing.allowTail),+ ),+ ]),+ ...(easing.durationRestThreshold === null+ ? []+ : [+ b.objectProperty(+ b.identifier('durationRestThreshold'),+ parseValueExpression(easing.durationRestThreshold),+ ),+ ]),+ b.objectProperty(+ b.identifier('overshootClamping'),+ b.booleanLiteral(easing.overshootClamping),+ ),+ ]),+ ] as never,+ ) as ExpressionKind;+ case 'bezier':+ return b.callExpression(+ b.memberExpression(+ b.identifier(easingLocalName),+ b.identifier('bezier'),+ ),+ [easing.x1, easing.y1, easing.x2, easing.y2].map((value) =>+ parseValueExpression(value),+ ) as never,+ ) as ExpressionKind;+ default:+ throw new Error(+ `Unsupported easing: ${JSON.stringify(easing satisfies never)}`,+ );+ }+};++const makeOptionsExpression = ({+ param,+ localNames,+}: {+ param: EffectClipboardKeyframedParam;+ localNames: ClipboardParamRemotionLocalNames;+}): ObjectExpression | null => {+ const properties: ObjectProperty[] = [];+ if (param.interpolationFunction !== 'interpolateColors') {+ 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 (param.output === 'perceptual-scale') {+ properties.push(+ b.objectProperty(+ b.identifier('output'),+ b.stringLiteral(param.output),+ ) as ObjectProperty,+ );+ }+ }++ if (param.easing.some((easing) => easing.type !== 'linear')) {+ properties.push(+ b.objectProperty(+ b.identifier('easing'),+ b.arrayExpression(+ param.easing.map((easing) =>+ makeEasingExpression({+ easing,+ easingLocalName: localNames.Easing ?? 'Easing',+ }),+ ) as never,+ ),+ ) as ObjectProperty,+ );+ }++ if (param.posterize !== undefined) {+ properties.push(+ b.objectProperty(+ b.identifier('posterize'),+ parseValueExpression(param.posterize) as never,+ ) as ObjectProperty,+ );+ }++ return properties.length === 0+ ? null+ : (b.objectExpression(properties as never) as ObjectExpression);+};++export const makeClipboardParamExpression = ({+ param,+ localNames,+}: {+ param: EffectClipboardParam;+ localNames: ClipboardParamRemotionLocalNames;+}): ExpressionKind => {+ if (param.type === 'static') {+ return parseValueExpression(param.value);+ }++ if (param.easing.length !== Math.max(0, param.keyframes.length - 1)) {+ throw new Error('Cannot paste property: invalid easing metadata');+ }++ 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 = makeOptionsExpression({param, localNames});+ if (options) {+ args.push(options as ExpressionKind);+ }++ return b.callExpression(+ b.identifier(+ localNames[param.interpolationFunction] ?? param.interpolationFunction,+ ),+ args as never,+ ) as ExpressionKind;+};diff --git a/packages/studio-codemods/src/update-sequence-props.ts b/packages/studio-codemods/src/update-sequence-props.tsindex a4a5c69b71..0e99c74762 100644--- a/packages/studio-codemods/src/update-sequence-props.ts+++ b/packages/studio-codemods/src/update-sequence-props.ts@@ -1,4 +1,7 @@import type {+ ArrowFunctionExpression,+ FunctionDeclaration,+ FunctionExpression,JSXAttribute,JSXElement,JSXExpressionContainer,@@ -10,7 +13,10 @@ import type {File,Statement,} from '@babel/types';-import type {GoogleFontSourceEdit} from '@remotion/studio-shared';+import type {+ EffectClipboardParam,+ GoogleFontSourceEdit,+} from '@remotion/studio-shared';import type {ExpressionKind} from 'ast-types/lib/gen/kinds';import * as recast from 'recast';import type {@@ -20,11 +26,18 @@ import type {} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {+ findNodePathForJsxElement,findJsxElementNodeAtNodePath,getStaticJsxChildrenAttribute,getStaticJsxTextContent,hasJsxChildrenAttribute,} from './sequence-props';+import {+ ensureClipboardParamRemotionImports,+ getRequiredRemotionImportsForClipboardParams,+ makeClipboardParamExpression,+ type ClipboardParamRemotionLocalNames,+} from './sequence-props/clipboard-param-expression';import {getCssShorthandsForUpdates,type CssShorthandProperty,@@ -48,6 +61,7 @@ export type SequencePropUpdate = {value: unknown;defaultValue: unknown | null;googleFont?: GoogleFontSourceEdit | null;+ clipboardParam?: EffectClipboardParam | null;};const ensureImportsForUpdates = ({@@ -90,6 +104,7 @@ export type SequencePropsNodeUpdateResult = {oldValueStrings: string[];logLine: number;removedProps: RemovedProp[];+ newNodePath: SequenceNodePath;};export type UpdateMultipleSequencePropsResult = {@@ -163,6 +178,131 @@ type JSXElementLike = NonNullable<>;type JSXOpeningElementLike = JSXElementLike['openingElement'];+type FunctionNode =+ | FunctionDeclaration+ | FunctionExpression+ | ArrowFunctionExpression;++const isFunctionNode = (value: unknown): value is FunctionNode => {+ return (+ recast.types.namedTypes.FunctionDeclaration.check(value) ||+ recast.types.namedTypes.FunctionExpression.check(value) ||+ recast.types.namedTypes.ArrowFunctionExpression.check(value)+ );+};++const ensureUseCurrentFrameHook = ({+ ast,+ jsxElement,+ hookName,+}: {+ ast: File;+ jsxElement: JSXElementLike;+ hookName: string;+}) => {+ let functionPath: recast.types.NodePath | null = null;+ recast.types.visit(ast, {+ visitJSXElement(path) {+ if (path.node !== jsxElement) {+ return this.traverse(path);+ }++ let current: recast.types.NodePath | null = path.parentPath;+ while (current) {+ if (isFunctionNode(current.value)) {+ functionPath = current;+ return false;+ }++ current = current.parentPath;+ }++ return false;+ },+ });++ const enclosingFunctionPath = functionPath as recast.types.NodePath | null;+ if (enclosingFunctionPath === null) {+ return;+ }++ const fn = enclosingFunctionPath.value as FunctionNode;+ if (!recast.types.namedTypes.BlockStatement.check(fn.body)) {+ fn.body = b.blockStatement([+ b.returnStatement(fn.body as Parameters<typeof b.returnStatement>[0]),+ ]) as unknown as FunctionNode['body'];+ }++ const block = fn.body as Extract<+ FunctionNode['body'],+ {type: 'BlockStatement'}+ >;+ const hasFrame = block.body.some((statement) => {+ return (+ statement.type === 'VariableDeclaration' &&+ statement.declarations.some(+ (declaration) =>+ declaration.type === 'VariableDeclarator' &&+ declaration.id.type === 'Identifier' &&+ declaration.id.name === 'frame' &&+ declaration.init?.type === 'CallExpression' &&+ declaration.init.callee.type === 'Identifier' &&+ declaration.init.callee.name === hookName,+ )+ );+ });+ if (hasFrame) {+ return;+ }++ block.body.unshift(+ b.variableDeclaration('const', [+ b.variableDeclarator(+ b.identifier('frame'),+ b.callExpression(b.identifier(hookName), []),+ ),+ ]) as unknown as (typeof block.body)[number],+ );+};++const prepareClipboardParamSourceEdits = ({+ ast,+ changes,+}: {+ ast: File;+ changes: {+ readonly jsxElement: JSXElementLike;+ readonly updates: SequencePropUpdate[];+ }[];+}): ClipboardParamRemotionLocalNames => {+ const params = changes.flatMap(({updates}) =>+ updates.flatMap((update) =>+ update.clipboardParam ? [update.clipboardParam] : [],+ ),+ );+ const requiredImports = getRequiredRemotionImportsForClipboardParams(params);+ const localNames = ensureClipboardParamRemotionImports({+ ast,+ requiredImports,+ });++ if (requiredImports.has('useCurrentFrame')) {+ for (const {jsxElement, updates} of changes) {+ if (+ updates.some((update) => update.clipboardParam?.type === 'keyframed')+ ) {+ ensureUseCurrentFrameHook({+ ast,+ jsxElement,+ hookName: localNames.useCurrentFrame ?? 'useCurrentFrame',+ });+ }+ }+ }++ return localNames;+};+const escapeJsxText = (value: string): string => {return value.replace(/&/g, '&')@@ -842,11 +982,13 @@ const updateSequencePropsNode = ({updates,schema,videoConfigValues,+ clipboardParamLocalNames,}: {jsxElement: JSXElementLike;updates: SequencePropUpdate[];schema: InteractivitySchema;videoConfigValues: VideoConfigIdentifierValues;+ clipboardParamLocalNames: ClipboardParamRemotionLocalNames;}): {oldValueStrings: string[];logLine: number;@@ -871,10 +1013,19 @@ const updateSequencePropsNode = ({const createValueExpression = ({existing,value,+ clipboardParam,}: {existing: Expression | null;value: unknown;+ clipboardParam: EffectClipboardParam | null | undefined;}) => {+ if (clipboardParam) {+ return makeClipboardParamExpression({+ param: clipboardParam,+ localNames: clipboardParamLocalNames,+ });+ }+if (existing === null || typeof value !== 'number') {return parseValueExpression(value);}@@ -892,7 +1043,7 @@ const updateSequencePropsNode = ({: updateVideoConfigNumericExpression({expression, value});};- for (const {key, value, defaultValue} of updates) {+ for (const {key, value, defaultValue, clipboardParam} of updates) {let oldValueString = '';if (key === 'children') {@@ -902,9 +1053,10 @@ const updateSequencePropsNode = ({}const isDefault =- (defaultValue === null && value === undefined) ||- (defaultValue !== null &&- JSON.stringify(value) === JSON.stringify(defaultValue));+ !clipboardParam &&+ ((defaultValue === null && value === undefined) ||+ (defaultValue !== null &&+ JSON.stringify(value) === JSON.stringify(defaultValue)));const dotIndex = key.indexOf('.');const isNested = dotIndex !== -1;@@ -920,7 +1072,7 @@ const updateSequencePropsNode = ({defaultValue,isDefault,createValueExpression: (existing) =>- createValueExpression({existing, value}),+ createValueExpression({existing, value, clipboardParam}),});} else {const attrIndex = node.attributes?.findIndex((a) => {@@ -968,10 +1120,13 @@ const updateSequencePropsNode = ({const parsed = createValueExpression({existing: existingExpression,value,+ clipboardParam,});const newValue =- value === true ? null : b.jsxExpressionContainer(parsed);+ value === true && !clipboardParam+ ? null+ : b.jsxExpressionContainer(parsed);if (!attr || attr.type === 'JSXSpreadAttribute') {const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);@@ -1064,11 +1219,17 @@ export const updateSequencePropsAst = ({);}+ const clipboardParamLocalNames = prepareClipboardParamSourceEdits({+ ast,+ changes: [{jsxElement, updates}],+ });+const {oldValueStrings, logLine, removedProps} = updateSequencePropsNode({jsxElement,updates,schema,videoConfigValues: videoConfigIdentifierValues,+ clipboardParamLocalNames,});ensureImportsForUpdates({ast, updates});applyGoogleFontSourceEdits({ast, updates});@@ -1089,8 +1250,7 @@ export const updateMultipleSequenceProps = ({changes: SequencePropsNodeUpdate[];}): UpdateMultipleSequencePropsResult => {const ast = parseAst(input);- const allUpdates: SequencePropUpdate[] = [];- const results = changes.map(+ const resolvedChanges = changes.map(({nodePath, updates, schema, videoConfigValues}) => {const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);if (!jsxElement) {@@ -1099,20 +1259,45 @@ export const updateMultipleSequenceProps = ({);}+ return {jsxElement, updates, schema, videoConfigValues};+ },+ );+ const clipboardParamLocalNames = prepareClipboardParamSourceEdits({+ ast,+ changes: resolvedChanges,+ });+ const allUpdates: SequencePropUpdate[] = [];+ const updateResults = resolvedChanges.map(+ ({jsxElement, updates, schema, videoConfigValues}) => {allUpdates.push(...updates);- return updateSequencePropsNode({+ return {jsxElement,- updates,- schema,- videoConfigValues: getVideoConfigIdentifierValues({- ast,- videoConfigValues,+ result: updateSequencePropsNode({+ jsxElement,+ updates,+ schema,+ videoConfigValues: getVideoConfigIdentifierValues({+ ast,+ videoConfigValues,+ }),+ clipboardParamLocalNames,}),- });+ };},);ensureImportsForUpdates({ast, updates: allUpdates});applyGoogleFontSourceEdits({ast, updates: allUpdates});+ const results = updateResults.map(({jsxElement, result}) => {+ const newNodePath = findNodePathForJsxElement(+ ast,+ jsxElement.openingElement,+ );+ if (!newNodePath) {+ throw new Error('Could not determine the updated JSX element path');+ }++ return {...result, newNodePath};+ });return {output: serializeAst(ast),diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex bf0fc32fd6..e42388df2c 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -11,6 +11,7 @@ import type {SaveSequencePropsResult,} from '@remotion/studio-shared';import {getAllSchemaKeys, getAssetSchemaKeys} from '@remotion/studio-shared';+import type {SequenceNodePath} from 'remotion';import {updateInlineCaptionPatches} from '../../codemods/update-inline-caption-patches';import {updateEffectKeyframes,@@ -83,6 +84,25 @@ const stringifySequencePropEditValue = (value: unknown): string => {return JSON.stringify(value);};+const stringifySequencePropSourceEdit = (+ sourceEdit: SaveSequencePropEdit['sourceEdit'],+ fallbackValue: unknown,+): string => {+ if (sourceEdit?.type !== 'clipboard-param') {+ return stringifySequencePropEditValue(fallbackValue);+ }++ if (sourceEdit.param.type === 'static') {+ return stringifySequencePropEditValue(sourceEdit.param.value);+ }++ return `${sourceEdit.param.interpolationFunction}(frame, ${JSON.stringify(+ sourceEdit.param.keyframes.map((keyframe) => keyframe.frame),+ )}, ${JSON.stringify(+ sourceEdit.param.keyframes.map((keyframe) => keyframe.value),+ )})`;+};+type SequencePropUndoSnapshot = {filePath: string;oldContents: string;@@ -95,6 +115,7 @@ type SequencePropEditResult = {logLine: number;removedProps: RemovedProp[];formatted: boolean;+ newNodePath: SequenceNodePath;};type SequenceKeyframeLog = {@@ -151,6 +172,10 @@ export const convertSequencePropEditToCodemodChange = (defaultValue: edit.defaultValue,googleFont:edit.sourceEdit?.type === 'google-font' ? edit.sourceEdit.font : null,+ clipboardParam:+ edit.sourceEdit?.type === 'clipboard-param'+ ? edit.sourceEdit.param+ : null,},],schema: edit.schema,@@ -236,7 +261,10 @@ export const saveSequencePropsHandler: ApiHandler<nodePath: edit.nodePath,key: edit.key,value: parsedValue,- valueString: stringifySequencePropEditValue(parsedValue),+ valueString: stringifySequencePropSourceEdit(+ edit.sourceEdit,+ parsedValue,+ ),defaultValue: parsedDefaultValue,defaultValueString:parsedDefaultValue !== null@@ -326,6 +354,7 @@ export const saveSequencePropsHandler: ApiHandler<const snapshots: SequencePropUndoSnapshot[] = [];const outputByPath = new Map<string, string>();const resultByIndex = new Map<number, SequencePropEditResult>();+ const updatedNodePaths = new Map<string, SequenceNodePath>();const sequenceKeyframeLogs: SequenceKeyframeLog[] = [];const captionPatchLogs: CaptionPatchLog[] = [];const effectKeyframeLogs: EffectKeyframeLog[] = [];@@ -358,7 +387,12 @@ export const saveSequencePropsHandler: ApiHandler<logLine: result.logLine,removedProps: result.removedProps,formatted,+ newNodePath: result.newNodePath,});+ updatedNodePaths.set(+ `${absolutePath}:${JSON.stringify(edit.nodePath.nodePath)}`,+ result.newNodePath,+ );}}@@ -676,7 +710,10 @@ export const saveSequencePropsHandler: ApiHandler<fileContents: output,keys: getAllSchemaKeys(target.schema),assetKeys: getAssetSchemaKeys(target.schema),- nodePath: target.nodePath.nodePath,+ nodePath:+ updatedNodePaths.get(+ `${absolutePath}:${JSON.stringify(target.nodePath.nodePath)}`,+ ) ?? target.nodePath.nodePath,componentIdentity: null,effects: [],videoConfigValues: target.nodePath.videoConfigValues,diff --git a/packages/studio-server/src/test/save-sequence-props.test.ts b/packages/studio-server/src/test/save-sequence-props.test.tsindex d1c499da0f..45d262a722 100644--- a/packages/studio-server/src/test/save-sequence-props.test.ts+++ b/packages/studio-server/src/test/save-sequence-props.test.ts@@ -76,6 +76,107 @@ test('saveSequenceProps does not suppress HMR for Google Font source edits', ()).toBe(false);});+test('saveSequenceProps pastes a keyframed property into source', async () => {+ clearUndoStackForTests();+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ addNewClientListener: () => () => undefined,+ closeConnections: () => Promise.resolve(),+ router: () => Promise.resolve(),+ sendEventToClient: () => undefined,+ sendEventToClientId: () => true,+ });+ const dir = mkdtempSync(join(tmpdir(), 'remotion-save-sequence-props-'));+ const fileName = 'Comp.tsx';+ const filePath = join(dir, fileName);+ const input = `import {AbsoluteFill} from 'remotion';++export const Comp = () => {+ return <AbsoluteFill style={{rotate: '0deg'}} />;+};+`;+ const nodePath = {+ absolutePath: fileName,+ nodePath: lineColumnToNodePath(input, 4),+ sequenceKeys: ['style.rotate'],+ effectKeys: [],+ videoConfigValues: null,+ };++ try {+ writeFileSync(filePath, input);+ await saveSequencePropsHandler({+ input: {+ edits: [+ {+ fileName,+ nodePath,+ key: 'style.rotate',+ value: {type: 'undefined'},+ defaultValue: JSON.stringify('0deg'),+ schema: NoReactInternals.sequenceSchema,+ sourceEdit: {+ type: 'clipboard-param',+ param: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0deg'},+ {frame: 30, value: '90deg'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ },+ ],+ addedKeyframes: null,+ movedKeyframes: null,+ clientId: 'test-client',+ undoLabel: 'Paste property',+ redoLabel: 'Reapply property paste',+ },+ entryPoint: '',+ remotionRoot: dir,+ request: {} as never,+ response: {} as never,+ logLevel: 'error',+ methods: {+ addJob: () => undefined,+ cancelJob: () => undefined,+ removeJob: () => undefined,+ },+ publicDir: '',+ binariesDirectory: null,+ configFile: null,+ getDefaultCodingAgent: () => null,+ getDefaultEditor: () => null,+ });++ const output = readFileSync(filePath, 'utf-8');+ expect(output).toMatch(+ /import \{[^}]*\binterpolate\b[^}]*\} from 'remotion';/,+ );+ expect(output).toMatch(+ /import \{[^}]*\buseCurrentFrame\b[^}]*\} from 'remotion';/,+ );+ expect(output).toContain('const frame = useCurrentFrame();');+ expect(output).toContain(+ "rotate: interpolate(frame, [0, 30], ['0deg', '90deg'])",+ );+ expect(getUndoStack()).toHaveLength(1);+ expect(popUndo()).toEqual({success: true, nodePathMutation: null});+ expect(readFileSync(filePath, 'utf-8')).toBe(input);+ } finally {+ clearUndoStackForTests();+ cleanupLiveEvents();+ cleanupFileWatcher();+ rmSync(dir, {force: true, recursive: true});+ }+});+test('saveSequenceProps forwards element schemas to the codemod', () => {const change = convertSequencePropEditToCodemodChange({nodePath: {@@ -100,6 +201,7 @@ test('saveSequenceProps forwards element schemas to the codemod', () => {value: 7,defaultValue: 5,googleFont: null,+ clipboardParam: null,},],schema: starSchema,diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex cface76f1f..a68e7b46ef 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -356,10 +356,15 @@ export type GoogleFontSourceEdit = {subsets: string[];};-export type SaveSequencePropSourceEdit = {- type: 'google-font';- font: GoogleFontSourceEdit;-};+export type SaveSequencePropSourceEdit =+ | {+ type: 'google-font';+ font: GoogleFontSourceEdit;+ }+ | {+ type: 'clipboard-param';+ param: EffectClipboardParam;+ };export type SaveSequencePropEdit = {fileName: string;diff --git a/packages/studio-shared/src/effect-clipboard-data.ts b/packages/studio-shared/src/effect-clipboard-data.tsindex 7955395262..21aa4dd482 100644--- a/packages/studio-shared/src/effect-clipboard-data.ts+++ b/packages/studio-shared/src/effect-clipboard-data.ts@@ -148,7 +148,9 @@ const normalizeEasing = (};};-const normalizeParam = (param: EffectClipboardParam): EffectClipboardParam => {+export const normalizeEffectClipboardParam = (+ param: EffectClipboardParam,+): EffectClipboardParam => {if (param.type === 'static') {return param;}@@ -167,7 +169,7 @@ const normalizeSnapshot = (params: Object.fromEntries(Object.entries(snapshot.params).map(([key, param]) => [key,- normalizeParam(param),+ normalizeEffectClipboardParam(param),]),),};@@ -187,7 +189,7 @@ const isClamping = (value: unknown): value is EffectClipboardClamping => {);};-const isEffectClipboardParam = (+export const isEffectClipboardParam = (value: unknown,): value is EffectClipboardParam => {if (!isRecord(value)) {@@ -360,7 +362,7 @@ export const parseEffectPropClipboardDataResult = (importPath: parsed.effect.importPath,},key: parsed.key,- param: normalizeParam(parsed.param),+ param: normalizeEffectClipboardParam(parsed.param),},};} catch {diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 31bfa6a6f1..eba3ffc333 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -212,6 +212,12 @@ export {type EffectPropClipboardData,type EffectPropClipboardDataParseResult,} from './effect-clipboard-data';+export {+ parseSequencePropClipboardData,+ parseSequencePropClipboardDataResult,+ type SequencePropClipboardData,+ type SequencePropClipboardDataParseResult,+} from './sequence-prop-clipboard-data';export {EventSourceEvent} from './event-source-event';export {formatBytes} from './format-bytes';export {getAllSchemaKeys, getAssetSchemaKeys} from './get-all-keys';diff --git a/packages/studio-shared/src/sequence-prop-clipboard-data.ts b/packages/studio-shared/src/sequence-prop-clipboard-data.tsnew file mode 100644index 0000000000..86d00d0275--- /dev/null+++ b/packages/studio-shared/src/sequence-prop-clipboard-data.ts@@ -0,0 +1,78 @@+import type {EffectClipboardParam} from './effect-clipboard-data';+import {+ isEffectClipboardParam,+ normalizeEffectClipboardParam,+} from './effect-clipboard-data';+import type {KeyframeClipboardFieldType} from './keyframe-clipboard-data';+import {isKeyframeClipboardFieldType} from './keyframe-clipboard-data';++export type SequencePropClipboardData = {+ readonly type: 'sequence-prop';+ readonly version: 1;+ readonly remotionClipboard: 'sequence-prop';+ readonly key: string;+ readonly fieldType: KeyframeClipboardFieldType;+ readonly param: EffectClipboardParam;+};++export type SequencePropClipboardDataParseResult =+ | {+ readonly status: 'valid';+ readonly data: SequencePropClipboardData;+ }+ | {+ readonly status: 'unsupported-version';+ readonly version: unknown;+ }+ | {+ readonly status: 'invalid';+ };++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+};++export const parseSequencePropClipboardDataResult = (+ value: string,+): SequencePropClipboardDataParseResult => {+ try {+ const parsed: unknown = JSON.parse(value);+ if (!isRecord(parsed) || parsed.remotionClipboard !== 'sequence-prop') {+ return {status: 'invalid'};+ }++ if (parsed.version !== 1) {+ return {status: 'unsupported-version', version: parsed.version};+ }++ if (+ parsed.type !== 'sequence-prop' ||+ typeof parsed.key !== 'string' ||+ !isKeyframeClipboardFieldType(parsed.fieldType) ||+ !isEffectClipboardParam(parsed.param)+ ) {+ return {status: 'invalid'};+ }++ return {+ status: 'valid',+ data: {+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: parsed.key,+ fieldType: parsed.fieldType,+ param: normalizeEffectClipboardParam(parsed.param),+ },+ };+ } catch {+ return {status: 'invalid'};+ }+};++export const parseSequencePropClipboardData = (+ value: string,+): SequencePropClipboardData | null => {+ const result = parseSequencePropClipboardDataResult(value);+ return result.status === 'valid' ? result.data : null;+};diff --git a/packages/studio-shared/src/test/sequence-prop-clipboard-data.test.ts b/packages/studio-shared/src/test/sequence-prop-clipboard-data.test.tsnew file mode 100644index 0000000000..f4d136aa0b--- /dev/null+++ b/packages/studio-shared/src/test/sequence-prop-clipboard-data.test.ts@@ -0,0 +1,83 @@+import {expect, test} from 'bun:test';+import {+ parseSequencePropClipboardData,+ parseSequencePropClipboardDataResult,+} from '../sequence-prop-clipboard-data';++test('parses static and keyframed sequence prop clipboard data', () => {+ expect(+ parseSequencePropClipboardData(+ JSON.stringify({+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: 'style.rotate',+ fieldType: 'rotation-css',+ param: {type: 'static', value: '45deg'},+ }),+ ),+ ).toEqual({+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: 'style.rotate',+ fieldType: 'rotation-css',+ param: {type: 'static', value: '45deg'},+ });++ expect(+ parseSequencePropClipboardData(+ JSON.stringify({+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: 'style.rotate',+ fieldType: 'rotation-css',+ param: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0deg'},+ {frame: 30, value: '90deg'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ }),+ )?.param,+ ).toEqual({+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0deg'},+ {frame: 30, value: '90deg'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ });+});++test('rejects incompatible and unsupported sequence prop clipboard data', () => {+ expect(+ parseSequencePropClipboardData(+ JSON.stringify({+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: 'style.rotate',+ fieldType: 'boolean',+ param: {type: 'static', value: true},+ }),+ ),+ ).toBe(null);++ expect(+ parseSequencePropClipboardDataResult(+ JSON.stringify({+ type: 'sequence-prop',+ version: 2,+ remotionClipboard: 'sequence-prop',+ }),+ ),+ ).toEqual({status: 'unsupported-version', version: 2});+});diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsxindex fd11721536..eb3370fb76 100644--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx@@ -1,17 +1,17 @@import {- isKeyframeInterpolationFunction,parseKeyframeClipboardDataResult,parseEasingClipboardDataResult,parseEffectClipboardDataResult,parseEffectPropClipboardDataResult,+ parseSequencePropClipboardDataResult,type EasingClipboardData,type EffectClipboardData,- type EffectClipboardInterpolationFunction,type EffectClipboardParam,type EffectClipboardPasteType,type EffectClipboardSnapshot,type EffectPropClipboardData,type KeyframeClipboardData,+ type SequencePropClipboardData,} from '@remotion/studio-shared';import type React from 'react';import {useContext, useEffect} from 'react';@@ -58,6 +58,12 @@ import {getPasteKeyframeTarget,} from './keyframe-clipboard';import {saveMultipleEffectProps} from './save-effect-prop';+import {saveSequenceProps} from './save-sequence-prop';+import {+ getPasteSequencePropTarget,+ getSequencePropClipboardDataFromSelection,+ propStatusToClipboardParam,+} from './sequence-prop-clipboard';import {useCurrentTimelineSelectionStateAsRef,useTimelineSelection,@@ -75,7 +81,8 @@ const makeClipboardText = (| EffectClipboardData| EffectPropClipboardData| EasingClipboardData- | KeyframeClipboardData,+ | KeyframeClipboardData+ | SequencePropClipboardData,) => JSON.stringify(payload);const makeTargetKey = (nodePath: SequencePropsSubscriptionKey): string => {@@ -210,47 +217,6 @@ type CopyableEffectStatus = React.ContextType<: never: never;-const isClipboardInterpolationFunction = (- value: string,-): value is EffectClipboardInterpolationFunction => {- return isKeyframeInterpolationFunction(value);-};--const effectPropStatusToClipboardParam = (- prop: CopyableEffectStatus['props'][string],-): EffectClipboardParam | null => {- if (prop.status === 'computed') {- return null;- }-- if (prop.status === 'static') {- if (prop.codeValue === undefined) {- return null;- }-- return {- type: 'static',- value: prop.codeValue,- };- }-- if (!isClipboardInterpolationFunction(prop.interpolationFunction)) {- return null;- }-- return {- type: 'keyframed',- interpolationFunction: prop.interpolationFunction,- keyframes: prop.keyframes,- easing: prop.easing,- clamping: prop.clamping,- ...(prop.output === undefined || prop.output === 'linear'- ? {}- : {output: prop.output}),- ...(prop.posterize === undefined ? {} : {posterize: prop.posterize}),- };-};-const effectStatusToSnapshot = (effect: CopyableEffectStatus,): EffectClipboardSnapshot | null => {@@ -264,7 +230,7 @@ const effectStatusToSnapshot = (continue;}- const param = effectPropStatusToClipboardParam(prop);+ const param = propStatusToClipboardParam(prop);if (param === null) {return null;}@@ -488,7 +454,7 @@ export const getEffectPropClipboardDataFromSelection = ({return null;}- const param = effectPropStatusToClipboardParam(prop);+ const param = propStatusToClipboardParam(prop);if (param === null) {return null;}@@ -792,6 +758,46 @@ export const TimelineClipboardKeybindings: React.FC = () => {return;}+ if (+ selectedItems.some((selection) => selection.type === 'sequence-prop')+ ) {+ e.preventDefault();+ if (+ selectedItems.length !== 1 ||+ selectedItems[0]?.type !== 'sequence-prop'+ ) {+ showNotification('Select one property to copy its value', 3000);+ return;+ }++ const payload = getSequencePropClipboardDataFromSelection({+ selection: selectedItems[0],+ propStatuses,+ sequences,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ });+ if (payload === null) {+ showNotification(+ 'Cannot copy property because its value cannot be copied',+ 3000,+ );+ return;+ }++ navigator.clipboard+ .writeText(makeClipboardText(payload))+ .then(() => {+ showNotification('Copied property value', 1000);+ })+ .catch((err) => {+ showNotification(+ `Could not copy property: ${(err as Error).message}`,+ 2000,+ );+ });+ return;+ }+if (selectedItems.some((selection) => selection.type === 'sequence-effect-prop',@@ -1166,6 +1172,97 @@ export const TimelineClipboardKeybindings: React.FC = () => {});}+ const sequencePropResult = parseSequencePropClipboardDataResult(text);+ if (sequencePropResult.status !== 'invalid') {+ e.preventDefault();+ if (sequencePropResult.status === 'unsupported-version') {+ showNotification(+ 'Cannot paste property copied from a different Remotion Studio version',+ 4000,+ );+ return;+ }++ const sequencePropTarget = getPasteSequencePropTarget({+ selectedItems,+ payload: sequencePropResult.data,+ propStatuses,+ sequences,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ });+ if (sequencePropTarget.type !== 'valid') {+ switch (sequencePropTarget.type) {+ case 'none':+ showNotification(+ 'Select a property or sequence to paste onto',+ 3000,+ );+ return;+ case 'prop-mismatch':+ showNotification(+ 'Select the same property to paste this value',+ 3000,+ );+ return;+ case 'uncopyable':+ showNotification(+ 'Cannot paste onto a property that cannot be updated',+ 3000,+ );+ return;+ case 'incompatible':+ showNotification(+ 'The copied value is not compatible with this property',+ 3000,+ );+ return;+ default:+ throw new Error(+ `Unexpected paste target: ${sequencePropTarget satisfies never}`,+ );+ }+ }++ const {param} = sequencePropResult.data;+ return saveSequenceProps({+ changes: sequencePropTarget.targets.map((pasteTarget) => ({+ fileName: pasteTarget.fileName,+ nodePath: pasteTarget.nodePath,+ fieldKey: pasteTarget.fieldKey,+ value: param.type === 'static' ? param.value : undefined,+ defaultValue: pasteTarget.defaultValue,+ schema: pasteTarget.schema,+ ...(param.type === 'keyframed'+ ? {+ sourceEdit: {+ type: 'clipboard-param' as const,+ param,+ },+ }+ : {}),+ })),+ addedKeyframes: null,+ movedKeyframes: null,+ setPropStatuses,+ clientId,+ undoLabel:+ sequencePropTarget.targets.length > 1+ ? 'Paste property onto selected sequences'+ : 'Paste property',+ redoLabel:+ sequencePropTarget.targets.length > 1+ ? 'Reapply property paste onto selected sequences'+ : 'Reapply property paste',+ }).then(() => {+ showNotification(+ sequencePropTarget.targets.length > 1+ ? 'Pasted property onto selected sequences'+ : 'Pasted property',+ 2000,+ );+ });+ }+const effectPropResult = parseEffectPropClipboardDataResult(text);if (effectPropResult.status !== 'invalid') {e.preventDefault();diff --git a/packages/studio/src/components/Timeline/keyframe-clipboard.ts b/packages/studio/src/components/Timeline/keyframe-clipboard.tsindex 7c241b6ee4..bd4fc55ede 100644--- a/packages/studio/src/components/Timeline/keyframe-clipboard.ts+++ b/packages/studio/src/components/Timeline/keyframe-clipboard.ts@@ -344,7 +344,7 @@ export type PasteKeyframeTarget =readonly type: 'none' | 'multiple' | 'uncopyable' | 'incompatible';};-const isKeyframeValueCompatible = ({+export const isKeyframeValueCompatible = ({value,fieldType,}: {diff --git a/packages/studio/src/components/Timeline/save-sequence-prop.ts b/packages/studio/src/components/Timeline/save-sequence-prop.tsindex 75d761ee3e..8cd844e3ce 100644--- a/packages/studio/src/components/Timeline/save-sequence-prop.ts+++ b/packages/studio/src/components/Timeline/save-sequence-prop.ts@@ -140,13 +140,15 @@ export const saveSequenceProps = ({nodePath: change.nodePath,setPropStatuses,applyOptimistic: (prev) =>- optimisticUpdateForPropStatuses({- previous: prev,- fieldKey: change.fieldKey,- value: change.value,- defaultValue: change.defaultValue,- schema: change.schema,- }),+ change.sourceEdit?.type === 'clipboard-param'+ ? prev+ : optimisticUpdateForPropStatuses({+ previous: prev,+ fieldKey: change.fieldKey,+ value: change.value,+ defaultValue: change.defaultValue,+ schema: change.schema,+ }),apiCall: () =>saveSequencePropsApi({edits: [@@ -189,6 +191,10 @@ export const saveSequenceProps = ({}for (const change of changes) {+ if (change.sourceEdit?.type === 'clipboard-param') {+ continue;+ }+setPropStatuses(change.nodePath, (prev) =>optimisticUpdateForPropStatuses({previous: prev,diff --git a/packages/studio/src/components/Timeline/sequence-prop-clipboard.ts b/packages/studio/src/components/Timeline/sequence-prop-clipboard.tsnew file mode 100644index 0000000000..80c9c7a8b5--- /dev/null+++ b/packages/studio/src/components/Timeline/sequence-prop-clipboard.ts@@ -0,0 +1,242 @@+import {+ isKeyframeClipboardFieldType,+ isKeyframeInterpolationFunction,+ type EffectClipboardParam,+ type SequencePropClipboardData,+} from '@remotion/studio-shared';+import {+ Internals,+ type CanUpdateSequencePropStatus,+ type InteractivitySchema,+ type OverrideIdToNodePaths,+ type PropStatuses,+ type SequencePropsSubscriptionKey,+ type TSequence,+} from 'remotion';+import {findTrackForNodePathInfo} from './find-track-for-node-path-info';+import {isKeyframeValueCompatible} from './keyframe-clipboard';+import type {TimelineSelection} from './TimelineSelection';++export const propStatusToClipboardParam = (+ prop: CanUpdateSequencePropStatus,+): EffectClipboardParam | null => {+ if (prop.status === 'computed') {+ return null;+ }++ if (prop.status === 'static') {+ if (prop.codeValue === undefined) {+ return null;+ }++ return {type: 'static', value: prop.codeValue};+ }++ if (!isKeyframeInterpolationFunction(prop.interpolationFunction)) {+ return null;+ }++ return {+ type: 'keyframed',+ interpolationFunction: prop.interpolationFunction,+ keyframes: prop.keyframes,+ easing: prop.easing,+ clamping: prop.clamping,+ ...(prop.output === undefined || prop.output === 'linear'+ ? {}+ : {output: prop.output}),+ ...(prop.posterize === undefined ? {} : {posterize: prop.posterize}),+ };+};++export const getSequencePropClipboardDataFromSelection = ({+ selection,+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+}: {+ readonly selection: TimelineSelection;+ readonly propStatuses: PropStatuses;+ readonly sequences: TSequence[];+ readonly overrideIdsToNodePaths: OverrideIdToNodePaths;+}): SequencePropClipboardData | null => {+ if (selection.type !== 'sequence-prop') {+ return null;+ }++ const track = findTrackForNodePathInfo({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo: selection.nodePathInfo,+ });+ if (!track?.sequence.controls) {+ return null;+ }++ const field = Internals.getFlatSchemaWithAllKeys(+ track.sequence.controls.schema,+ )[selection.key];+ if (!field || !isKeyframeClipboardFieldType(field.type)) {+ return null;+ }++ const propStatus = Internals.getPropStatusesCtx(+ propStatuses,+ track.nodePathInfo?.sequenceSubscriptionKey ??+ selection.nodePathInfo.sequenceSubscriptionKey,+ )?.[selection.key];+ if (!propStatus) {+ return null;+ }++ const param = propStatusToClipboardParam(propStatus);+ if (param === null) {+ return null;+ }++ return {+ type: 'sequence-prop',+ version: 1,+ remotionClipboard: 'sequence-prop',+ key: selection.key,+ fieldType: field.type,+ param,+ };+};++type PasteSequencePropEditTarget = {+ readonly fileName: string;+ readonly nodePath: SequencePropsSubscriptionKey;+ readonly fieldKey: string;+ readonly defaultValue: string | null;+ readonly schema: InteractivitySchema;+};++export type PasteSequencePropTarget =+ | {+ readonly type: 'valid';+ readonly targets: PasteSequencePropEditTarget[];+ }+ | {+ readonly type: 'none' | 'prop-mismatch' | 'uncopyable' | 'incompatible';+ };++const getPasteTargetForSelection = ({+ selection,+ payload,+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+}: {+ readonly selection: TimelineSelection;+ readonly payload: SequencePropClipboardData;+ readonly propStatuses: PropStatuses;+ readonly sequences: TSequence[];+ readonly overrideIdsToNodePaths: OverrideIdToNodePaths;+}):+ | {type: 'valid'; target: PasteSequencePropEditTarget}+ | Exclude<PasteSequencePropTarget, {type: 'valid'}> => {+ if (selection.type !== 'sequence-prop' && selection.type !== 'sequence') {+ return {type: 'none'};+ }++ const fieldKey =+ selection.type === 'sequence-prop' ? selection.key : payload.key;+ if (fieldKey !== payload.key) {+ return {type: 'prop-mismatch'};+ }++ const track = findTrackForNodePathInfo({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo: selection.nodePathInfo,+ });+ if (!track?.sequence.controls || !track.nodePathInfo) {+ return {type: 'uncopyable'};+ }++ const {schema} = track.sequence.controls;+ const field = Internals.getFlatSchemaWithAllKeys(schema)[fieldKey];+ if (!field || field.type !== payload.fieldType) {+ return {type: 'incompatible'};+ }++ const nodePath = track.nodePathInfo.sequenceSubscriptionKey;+ const propStatus = Internals.getPropStatusesCtx(propStatuses, nodePath)?.[+ fieldKey+ ];+ if (!propStatus || propStatus.status === 'computed') {+ return {type: 'uncopyable'};+ }++ const values =+ payload.param.type === 'static'+ ? [payload.param.value]+ : payload.param.keyframes.map((keyframe) => keyframe.value);+ if (+ values.some(+ (value) =>+ !isKeyframeValueCompatible({value, fieldType: payload.fieldType}),+ )+ ) {+ return {type: 'incompatible'};+ }++ return {+ type: 'valid',+ target: {+ fileName: nodePath.absolutePath,+ nodePath,+ fieldKey,+ defaultValue:+ field.default === undefined ? null : JSON.stringify(field.default),+ schema,+ },+ };+};++export const getPasteSequencePropTarget = ({+ selectedItems,+ payload,+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+}: {+ readonly selectedItems: readonly TimelineSelection[];+ readonly payload: SequencePropClipboardData;+ readonly propStatuses: PropStatuses;+ readonly sequences: TSequence[];+ readonly overrideIdsToNodePaths: OverrideIdToNodePaths;+}): PasteSequencePropTarget => {+ if (selectedItems.length === 0) {+ return {type: 'none'};+ }++ const targets: PasteSequencePropEditTarget[] = [];+ for (const selection of selectedItems) {+ const result = getPasteTargetForSelection({+ selection,+ payload,+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+ });+ if (result.type !== 'valid') {+ return result;+ }++ targets.push(result.target);+ }++ return {+ type: 'valid',+ targets: [+ ...new Map(+ targets.map((target) => [+ Internals.makeSequencePropsSubscriptionKey(target.nodePath),+ target,+ ]),+ ).values(),+ ],+ };+};diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.tsindex 1498475db7..eef0c94737 100644--- a/packages/studio/src/test/timeline-selection.test.ts+++ b/packages/studio/src/test/timeline-selection.test.ts@@ -90,6 +90,10 @@ import {type PasteKeyframeTarget,} from '../components/Timeline/keyframe-clipboard';import {getTimelinePropResetTargets} from '../components/Timeline/reset-selected-timeline-props';+import {+ getPasteSequencePropTarget,+ getSequencePropClipboardDataFromSelection,+} from '../components/Timeline/sequence-prop-clipboard';import {shouldSubscribeToSequenceProps} from '../components/Timeline/should-subscribe-to-sequence-props';import {parseCssRotationToEuler} from '../components/Timeline/timeline-rotation-utils';import {@@ -1002,6 +1006,90 @@ test('pasting keyframes onto a sequence targets the copied property', () => {});});+test('copies a keyframed sequence prop between components with matching schemas', () => {+ const sourceNodePathInfo = makeNodePathInfo(+ ['body', 0],+ ['controls', 'style.rotate'],+ );+ const targetNodePathInfo = makeNodePathInfo(['body', 1], []);+ const sourceNodePath = sourceNodePathInfo.sequenceSubscriptionKey;+ const targetNodePath = targetNodePathInfo.sequenceSubscriptionKey;+ const schema = {+ 'style.rotate': {+ type: 'rotation-css',+ default: '0deg',+ },+ } satisfies InteractivitySchema;+ const propStatuses = {+ [Internals.makeSequencePropsSubscriptionKey(sourceNodePath)]: {+ canUpdate: true,+ props: {+ 'style.rotate': {+ status: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: '0deg'},+ {frame: 30, value: '90deg'},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ posterize: undefined,+ output: undefined,+ },+ },+ effects: [],+ },+ [Internals.makeSequencePropsSubscriptionKey(targetNodePath)]: {+ canUpdate: true,+ props: {+ 'style.rotate': {status: 'static', codeValue: undefined},+ },+ effects: [],+ },+ } satisfies PropStatuses;+ const sequences = [+ makeTimelineSequence({schema, overrideId: 'video'}),+ makeTimelineSequence({schema, overrideId: 'absolute-fill'}),+ ];+ const overrideIdsToNodePaths = {+ video: sourceNodePath,+ 'absolute-fill': targetNodePath,+ };+ const payload = getSequencePropClipboardDataFromSelection({+ selection: {+ type: 'sequence-prop',+ nodePathInfo: sourceNodePathInfo,+ key: 'style.rotate',+ },+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+ });++ expect(payload).toMatchObject({+ type: 'sequence-prop',+ key: 'style.rotate',+ fieldType: 'rotation-css',+ param: {type: 'keyframed'},+ });+ if (payload === null) {+ throw new Error('Expected a sequence prop clipboard payload');+ }++ expect(+ getPasteSequencePropTarget({+ selectedItems: [{type: 'sequence', nodePathInfo: targetNodePathInfo}],+ payload,+ propStatuses,+ sequences,+ overrideIdsToNodePaths,+ }),+ ).toMatchObject({+ type: 'valid',+ targets: [{nodePath: targetNodePath, fieldKey: 'style.rotate'}],+ });+});+test('copying selected keyframes requires one property', () => {const opacityNodePathInfo = makeNodePathInfo(['body', 0],