🎥 Make videos programmatically with React
@remotion/studio: Copy and paste sequence effects
JonnyBurger12d20b08fb09
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.tsnew file mode 100644index 0000000000..8c39393564--- /dev/null+++ b/packages/studio-server/src/codemods/paste-effects.ts@@ -0,0 +1,213 @@+import type {+ ArrayExpression,+ CallExpression,+ Expression,+ JSXAttribute,+} from '@babel/types';+import type {+ EffectClipboardPasteType,+ EffectClipboardSource,+} 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 {formatFileContent} from './format-file-content';+import {parseAst, serializeAst} from './parse-ast';+import {+ enumerateEffectArrayElements,+ findEffectCallExpression,+ findEffectsAttr,+} from './update-effect-props/update-effect-props';++const b = recast.types.builders;++const getEffectsArray = (+ attr: JSXAttribute,+ action: 'read' | 'append',+): ArrayExpression => {+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {+ throw new Error(`Cannot ${action} effects: effects prop is not an array`);+ }++ const expr = attr.value.expression as Expression;+ if (expr.type !== 'ArrayExpression') {+ throw new Error(`Cannot ${action} effects: effects prop is not an array`);+ }++ return expr;+};++const makeEffectsAttr = (array: ArrayExpression): JSXAttribute => {+ return b.jsxAttribute(+ b.jsxIdentifier('effects'),+ b.jsxExpressionContainer(array as never),+ ) as unknown as JSXAttribute;+};++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,+ ast,+}: {+ 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,+ 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}()`);+ }++ return {calls, labels};+};++const removeEffectsAttr = (+ attributes: NonNullable<+ ReturnType<typeof findJsxElementAtNodePath>+ >['attributes'],+ attr: JSXAttribute,+) => {+ const index = attributes.indexOf(attr);+ if (index !== -1) {+ attributes.splice(index, 1);+ }+};++export const pasteEffects = async ({+ input,+ targetFileName,+ targetSequenceNodePath,+ type,+ sources,+ prettierConfigOverride,+}: {+ readonly input: string;+ readonly targetFileName: string;+ readonly targetSequenceNodePath: SequenceNodePath;+ readonly type: EffectClipboardPasteType;+ readonly sources: EffectClipboardSource[];+ readonly prettierConfigOverride?: Record<string, unknown> | null;+}): Promise<{+ readonly output: string;+ readonly formatted: boolean;+ readonly effectLabels: string[];+ 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(+ 'Could not find a JSX element at the specified location to paste effects',+ );+ }++ const existingAttr = findEffectsAttr(targetJsx.attributes ?? []);++ if (type === 'effects-replacing') {+ if (existingAttr) {+ removeEffectsAttr(targetJsx.attributes, existingAttr);+ }++ if (effectCalls.length > 0) {+ targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));+ }+ } else if (existingAttr) {+ getEffectsArray(existingAttr, 'append').elements.push(+ ...(effectCalls as ArrayExpression['elements']),+ );+ } else if (effectCalls.length > 0) {+ targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));+ } else {+ throw new Error('Cannot paste effects: no effects were copied');+ }++ const finalFile = serializeAst(ast);+ const {output, formatted} = await formatFileContent({+ input: finalFile,+ prettierConfigOverride,+ });++ return {+ output,+ formatted,+ effectLabels,+ logLine: targetJsx.loc?.start.line ?? 1,+ };+};diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 60b2f5c52e..0169066bf6 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -17,6 +17,7 @@ import {insertJsxElementHandler} from './routes/insert-jsx-element';import {handleInstallPackage} from './routes/install-dependency';import {openInEditorHandler} from './routes/open-in-editor';import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';+import {pasteEffectsHandler} from './routes/paste-effects';import {projectInfoHandler} from './routes/project-info';import {redoHandler} from './routes/redo';import {registerClientRenderHandler} from './routes/register-client-render';@@ -67,6 +68,7 @@ export const allApiRoutes: {'/api/add-sequence-keyframe': addSequenceKeyframeHandler,'/api/add-effect-keyframe': addEffectKeyframeHandler,'/api/delete-effect': deleteEffectHandler,+ '/api/paste-effects': pasteEffectsHandler,'/api/delete-jsx-node': deleteJsxNodeHandler,'/api/duplicate-jsx-node': duplicateJsxNodeHandler,'/api/update-available': handleUpdate,diff --git a/packages/studio-server/src/preview-server/routes/paste-effects.ts b/packages/studio-server/src/preview-server/routes/paste-effects.tsnew file mode 100644index 0000000000..46e7f5a48b--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/paste-effects.ts@@ -0,0 +1,110 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ PasteEffectsRequest,+ PasteEffectsResponse,+} from '@remotion/studio-shared';+import {pasteEffects} from '../../codemods/paste-effects';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {formatLogFileLocation} from '../format-log-file-location';+import {+ printUndoHint,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {attrName} from './log-updates/formatting';+import {warnAboutPrettierOnce} from './log-updates/log-update';++const getPastedEffectDescription = (effectLabels: string[]): string => {+ if (effectLabels.length === 1) {+ return effectLabels[0];+ }++ return `${effectLabels.length} effects`;+};++export const pasteEffectsHandler: ApiHandler<+ PasteEffectsRequest,+ PasteEffectsResponse+> = async ({+ input: {targetFileName, targetSequenceNodePath, type, sources, clientId},+ remotionRoot,+ logLevel,+}) => {+ try {+ if (sources.length === 0) {+ 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}"`,+ );++ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: targetFileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabels, logLine} = await pasteEffects({+ input: fileContents,+ targetFileName,+ targetSequenceNodePath: targetSequenceNodePath.nodePath,+ type,+ sources,+ });++ const effectDescription = getPastedEffectDescription(effectLabels);++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Pasting of ${effectDescription}`,+ redoMessage: `↪️ Pasting of ${effectDescription}`,+ },+ entryType: 'paste-effects',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);++ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Pasted ${attrName(effectDescription)}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[paste-effects] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );++ printUndoHint(logLevel);++ return {+ success: true,+ };+ } catch (err) {+ return {+ success: false,+ reason: (err as Error).message,+ stack: (err as Error).stack as string,+ };+ }+};diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsindex 1abde54fd8..2008086e1e 100644--- a/packages/studio-server/src/preview-server/undo-stack.ts+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -24,6 +24,7 @@ type UndoEntryType =| 'keyframe-delete'| 'add-effect'| 'delete-effect'+ | 'paste-effects'| 'reorder-effect'| 'delete-jsx-node'| 'duplicate-jsx-node'@@ -56,6 +57,7 @@ type UndoEntry = {| {entryType: 'keyframe-delete'}| {entryType: 'add-effect'}| {entryType: 'delete-effect'}+ | {entryType: 'paste-effects'}| {entryType: 'reorder-effect'}| {entryType: 'delete-jsx-node'}| {entryType: 'duplicate-jsx-node'}diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.tsnew file mode 100644index 0000000000..6313a1b530--- /dev/null+++ b/packages/studio-server/src/test/paste-effects.test.ts@@ -0,0 +1,135 @@+import {expect, test} from 'bun:test';+import {pasteEffects} from '../codemods/paste-effects';+import {lineColumnToNodePath} from './test-utils';++const buildInput = (+ jsx: string,+) => `import {HtmlInCanvas} from '@remotion/html-in-canvas';+import {blur} from '@remotion/effects/blur';+import {tint} from '@remotion/effects/tint';+import {interpolate, useCurrentFrame} from 'remotion';++export const Comp = () => {+\tconst frame = useCurrentFrame();+\treturn ${jsx};+};+`;++const makeNodePath = (input: string, line: number) => ({+ absolutePath: 'Comp.tsx',+ nodePath: lineColumnToNodePath(input, line),+ sequenceKeys: [],+ effectKeys: [],+});++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);++ const {output, effectLabels} = await pasteEffects({+ input,+ targetFileName: 'Comp.tsx',+ targetSequenceNodePath: target.nodePath,+ type: 'effects-additive',+ sources: [+ {+ type: 'single-effect',+ fileName: 'Comp.tsx',+ sequenceNodePath: source,+ effectIndex: 0,+ },+ ],+ });++ expect(effectLabels).toEqual(['tint()']);+ expect(output).toContain('blur({radius: 5})');+ expect(output).toMatch(/tint\(\{color: ['"]red['"]\}\)/);+});++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);++ const {output, effectLabels} = await pasteEffects({+ input,+ targetFileName: 'Comp.tsx',+ targetSequenceNodePath: target.nodePath,+ type: 'effects-replacing',+ sources: [+ {+ type: 'all-effects',+ fileName: 'Comp.tsx',+ sequenceNodePath: source,+ },+ ],+ });++ expect(effectLabels).toEqual(['tint()', 'blur()']);+ expect(output).toMatch(/color: ['"]red['"]/);+ expect(output).toContain('radius: 10');+ expect(output).not.toMatch(/color: ['"]blue['"]/);+});++test('pasteEffects preserves inline effect keyframes in the same file', 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);++ const {output} = await pasteEffects({+ input,+ targetFileName: 'Comp.tsx',+ targetSequenceNodePath: target.nodePath,+ type: 'effects-additive',+ sources: [+ {+ type: 'single-effect',+ fileName: 'Comp.tsx',+ sequenceNodePath: source,+ effectIndex: 0,+ },+ ],+ });++ expect(output).toContain(+ 'tint({amount: interpolate(frame, [0, 20], [0.2, 0.8])})',+ );+});++test('pasteEffects rejects cross-file pastes to avoid broken keyframe references', 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);++ 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/);+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 359c9faa59..2729b97ee6 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -22,6 +22,10 @@ import type {SequenceSchema,} from 'remotion';import type {RecastCodemod, VisualControlChange} from './codemods';+import type {+ EffectClipboardPasteType,+ EffectClipboardSource,+} from './effect-clipboard-data';import type {PackageManager} from './package-manager';import type {ProjectInfo} from './project-info';import type {@@ -435,6 +439,24 @@ export type DeleteEffectResponse =stack: string;};+export type PasteEffectsRequest = {+ targetFileName: string;+ targetSequenceNodePath: SequencePropsSubscriptionKey;+ type: EffectClipboardPasteType;+ sources: EffectClipboardSource[];+ clientId: string;+};++export type PasteEffectsResponse =+ | {+ success: true;+ }+ | {+ success: false;+ reason: string;+ stack: string;+ };+export type DeleteJsxNodeRequestItem = {fileName: string;nodePath: SequenceNodePath;@@ -600,6 +622,7 @@ export type ApiRoutes = {AddEffectKeyframeResponse>;'/api/delete-effect': ReqAndRes<DeleteEffectRequest, DeleteEffectResponse>;+ '/api/paste-effects': ReqAndRes<PasteEffectsRequest, PasteEffectsResponse>;'/api/delete-jsx-node': ReqAndRes<DeleteJsxNodeRequest,DeleteJsxNodeResponsediff --git a/packages/studio-shared/src/effect-clipboard-data.ts b/packages/studio-shared/src/effect-clipboard-data.tsnew file mode 100644index 0000000000..66bdd9844c--- /dev/null+++ b/packages/studio-shared/src/effect-clipboard-data.ts@@ -0,0 +1,118 @@+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 EffectClipboardData = {+ readonly type: EffectClipboardPasteType;+ readonly version: 1;+ readonly remotionClipboard: 'effects';+ readonly sources: EffectClipboardSource[];+};++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 = (+ value: unknown,+): value is EffectClipboardSource => {+ 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+ );+};++export const parseEffectClipboardData = (+ value: string,+): EffectClipboardData | null => {+ try {+ const parsed: unknown = JSON.parse(value);+ if (!isRecord(parsed)) {+ return null;+ }++ if (+ parsed.remotionClipboard !== 'effects' ||+ parsed.version !== 1 ||+ (parsed.type !== 'effects-additive' &&+ parsed.type !== 'effects-replacing') ||+ !Array.isArray(parsed.sources) ||+ !parsed.sources.every(isEffectClipboardSource)+ ) {+ return null;+ }++ return {+ type: parsed.type,+ version: 1,+ remotionClipboard: 'effects',+ sources: parsed.sources,+ };+ } catch {+ return null;+ }+};diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 06d689c909..b7dae5318b 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -1,9 +1,9 @@export {splitAnsi, stripAnsi} from './ansi';export {- AddEffectRequest,- AddEffectResponse,AddEffectKeyframeRequest,AddEffectKeyframeResponse,+ AddEffectRequest,+ AddEffectResponse,AddRenderRequest,AddSequenceKeyframeRequest,AddSequenceKeyframeResponse,@@ -33,14 +33,16 @@ export {DeleteStaticFileResponse,DuplicateJsxNodeRequest,DuplicateJsxNodeResponse,- InstallPackageRequest,- InstallPackageResponse,- InsertableCompositionElement,InsertJsxElementRequest,InsertJsxElementResponse,+ InsertableCompositionElement,+ InstallPackageRequest,+ InstallPackageResponse,OpenInEditorRequest,OpenInEditorResponse,OpenInFileExplorerRequest,+ PasteEffectsRequest,+ PasteEffectsResponse,ProjectInfoRequest,ProjectInfoResponse,RedoRequest,@@ -75,6 +77,13 @@ export {} from './api-requests';export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';+export {+ EFFECT_CLIPBOARD_MIME_TYPE,+ parseEffectClipboardData,+ type EffectClipboardData,+ type EffectClipboardPasteType,+ type EffectClipboardSource,+} from './effect-clipboard-data';export {EFFECT_DRAG_MIME_TYPE,parseEffectDragData,diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsxnew file mode 100644index 0000000000..ed0127acac--- /dev/null+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx@@ -0,0 +1,217 @@+import {+ parseEffectClipboardData,+ type EffectClipboardData,+ type EffectClipboardSource,+} from '@remotion/studio-shared';+import type React from 'react';+import {useContext, useEffect} from 'react';+import type {SequencePropsSubscriptionKey} from 'remotion';+import {StudioServerConnectionCtx} from '../../helpers/client-id';+import {useKeybinding} from '../../helpers/use-keybinding';+import {callApi} from '../call-api';+import {showNotification} from '../Notifications/NotificationCenter';+import {+ useCurrentTimelineSelectionStateAsRef,+ useTimelineSelection,+ type TimelineSelection,+} from './TimelineSelection';++const makeClipboardText = (payload: EffectClipboardData) =>+ JSON.stringify(payload);++const makeTargetKey = (nodePath: SequencePropsSubscriptionKey): string => {+ return JSON.stringify({+ absolutePath: nodePath.absolutePath,+ nodePath: nodePath.nodePath,+ sequenceKeys: nodePath.sequenceKeys,+ effectKeys: nodePath.effectKeys,+ });+};++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 => {+ if (+ selection.type === 'sequence' ||+ selection.type === 'sequence-effect' ||+ selection.type === 'sequence-all-effects'+ ) {+ return selection.nodePathInfo.sequenceSubscriptionKey;+ }++ return null;+};++export const TimelineClipboardKeybindings: React.FC = () => {+ const keybindings = useKeybinding();+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const {canSelect} = useTimelineSelection();+ const currentSelection = useCurrentTimelineSelectionStateAsRef();++ useEffect(() => {+ if (!canSelect || previewServerState.type !== 'connected') {+ return;+ }++ const {clientId} = previewServerState;++ const copy = keybindings.registerKeybinding({+ event: 'keydown',+ key: 'c',+ callback: (e) => {+ const {selectedItems} = currentSelection.current;+ if (selectedItems.length === 0) {+ return;+ }++ const sources = selectedItems.map(sourceFromSelection);+ if (sources.some((source) => source === null)) {+ return;+ }++ const firstSelection = selectedItems[0];+ const type =+ firstSelection?.type === 'sequence-effect'+ ? 'effects-additive'+ : firstSelection?.type === 'sequence-all-effects'+ ? 'effects-replacing'+ : null;++ if (type === null) {+ return;+ }++ e.preventDefault();+ navigator.clipboard+ .writeText(+ makeClipboardText({+ type,+ version: 1,+ remotionClipboard: 'effects',+ sources: sources as EffectClipboardSource[],+ }),+ )+ .then(() => {+ showNotification(+ sources.length === 1+ ? 'Copied effect to clipboard'+ : 'Copied effects to clipboard',+ 1000,+ );+ })+ .catch((err) => {+ showNotification(+ `Could not copy effects: ${(err as Error).message}`,+ 2000,+ );+ });+ },+ commandCtrlKey: true,+ preventDefault: false,+ triggerIfInputFieldFocused: false,+ keepRegisteredWhenNotHighestContext: false,+ });++ const paste = keybindings.registerKeybinding({+ event: 'keydown',+ key: 'v',+ callback: (e) => {+ const {selectedItems} = currentSelection.current;+ if (selectedItems.length === 0) {+ return;+ }++ navigator.clipboard+ .readText()+ .then((text) => {+ const payload = parseEffectClipboardData(text);+ if (payload === null) {+ return;+ }++ e.preventDefault();++ const targetNodePaths = selectedItems+ .map(getTargetSequenceNodePath)+ .filter(+ (nodePath): nodePath is SequencePropsSubscriptionKey =>+ nodePath !== null,+ );+ const uniqueTargetKeys = new Set(+ targetNodePaths.map(makeTargetKey),+ );++ if (uniqueTargetKeys.size !== 1) {+ showNotification(+ 'Select one target sequence to paste effects',+ 3000,+ );+ return;+ }++ const [targetSequenceNodePath] = targetNodePaths;+ if (!targetSequenceNodePath) {+ showNotification('Select a sequence to paste effects onto', 3000);+ return;+ }++ return callApi('/api/paste-effects', {+ targetFileName: targetSequenceNodePath.absolutePath,+ targetSequenceNodePath,+ type: payload.type,+ sources: payload.sources,+ clientId,+ }).then((result) => {+ if (result.success) {+ showNotification('Pasted effects', 2000);+ } else {+ showNotification(result.reason, 4000);+ }+ });+ })+ .catch((err) => {+ showNotification(+ `Could not paste effects: ${(err as Error).message}`,+ 3000,+ );+ });+ },+ commandCtrlKey: true,+ preventDefault: false,+ triggerIfInputFieldFocused: false,+ keepRegisteredWhenNotHighestContext: false,+ });++ return () => {+ copy.unregister();+ paste.unregister();+ };+ }, [canSelect, currentSelection, keybindings, previewServerState]);++ return null;+};diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsxindex 02eb1bb842..f0c47fb722 100644--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx@@ -17,6 +17,7 @@ import type {import {TIMELINE_PADDING} from '../../helpers/timeline-layout';import {timelineNodePathInfoToKey} from '../../helpers/timeline-node-path-key';import {useKeybinding} from '../../helpers/use-keybinding';+import {TimelineClipboardKeybindings} from './TimelineClipboardKeybindings';import {TimelineDeleteKeybindings} from './TimelineDeleteKeybindings';export const TIMELINE_SELECTED_BACKGROUND = '#3B3F42';@@ -579,6 +580,7 @@ export const TimelineSelectionProvider: React.FC<{<CurrentTimelineSelectionContext.Provider value={currentSelection}><TimelineSelectionContext.Provider value={value}>{children}+ <TimelineClipboardKeybindings /><TimelineDeleteKeybindings /></TimelineSelectionContext.Provider></CurrentTimelineSelectionContext.Provider>