Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/studio`: Cut selected effects (#9113)

Igor Samokhovetsdb16db871b36
diff --git a/packages/docs/docs/studio/shortcuts.mdx b/packages/docs/docs/studio/shortcuts.mdx
index 9765124db6..b488c366b3 100644
--- a/packages/docs/docs/studio/shortcuts.mdx
+++ b/packages/docs/docs/studio/shortcuts.mdx
@@ -313,6 +313,14 @@ Pause and return to where playback started
</td>
<td>Copy selected effects or effect prop values</td>
</tr>
+ <tr>
+ <td>
+ <kbd>⌘/Ctrl</kbd>
+ <div style={{width: 2, display: 'inline-block'}} />
+ <kbd>X</kbd>
+ </td>
+ <td>Cut selected effects</td>
+ </tr>
<tr>
<td>
<kbd>⌘/Ctrl</kbd>
diff --git a/packages/studio-server/src/codemods/paste-effects.ts b/packages/studio-server/src/codemods/paste-effects.ts
index b040d49760..e864a1927d 100644
--- a/packages/studio-server/src/codemods/paste-effects.ts
+++ b/packages/studio-server/src/codemods/paste-effects.ts
@@ -119,6 +119,7 @@ export const pasteEffects = async ({
targetSequenceNodePath,
type,
effects,
+ insertAtIndices,
prettierConfigOverride,
}: {
readonly input: string;
@@ -126,6 +127,7 @@ export const pasteEffects = async ({
readonly targetSequenceNodePath: SequenceNodePath;
readonly type: EffectClipboardPasteType;
readonly effects: EffectClipboardSnapshot[];
+ readonly insertAtIndices: number[] | null;
readonly prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
readonly output: string;
@@ -164,6 +166,17 @@ export const pasteEffects = async ({
const existingAttr = findEffectsAttr(targetJsx.attributes ?? []);
+ if (insertAtIndices !== null) {
+ if (
+ type !== 'effects-additive' ||
+ insertAtIndices.length !== effectCalls.length ||
+ new Set(insertAtIndices).size !== insertAtIndices.length ||
+ insertAtIndices.some((index) => !Number.isInteger(index) || index < 0)
+ ) {
+ throw new Error('Cannot paste effects: invalid insertion indices');
+ }
+ }
+
if (type === 'effects-replacing') {
if (existingAttr) {
removeEffectsAttr(targetJsx.attributes, existingAttr);
@@ -172,14 +185,41 @@ export const pasteEffects = async ({
if (effectCalls.length > 0) {
targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
}
- } else if (existingAttr) {
- getEffectsArray(existingAttr).elements.push(
- ...(effectCalls as ArrayExpression['elements']),
- );
- } else if (effectCalls.length > 0) {
- targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
- } else {
+ } else if (effectCalls.length === 0) {
throw new Error('Cannot paste effects: no effects were copied');
+ } else if (insertAtIndices === null) {
+ if (existingAttr) {
+ getEffectsArray(existingAttr).elements.push(
+ ...(effectCalls as ArrayExpression['elements']),
+ );
+ } else {
+ targetJsx.attributes.push(makeEffectsAttr(makeEffectsArray(effectCalls)));
+ }
+ } else {
+ const elements = existingAttr
+ ? getEffectsArray(existingAttr).elements
+ : ([] as ArrayExpression['elements']);
+ const indexedCalls = effectCalls
+ .map((effect, index) => ({
+ effect,
+ index: insertAtIndices[index] as number,
+ }))
+ .sort((left, right) => left.index - right.index);
+ for (const indexedCall of indexedCalls) {
+ elements.splice(
+ Math.min(indexedCall.index, elements.length),
+ 0,
+ indexedCall.effect,
+ );
+ }
+
+ if (!existingAttr) {
+ targetJsx.attributes.push(
+ makeEffectsAttr(
+ b.arrayExpression(elements as never) as ArrayExpression,
+ ),
+ );
+ }
}
const finalFile = serializeAst(ast);
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 fce1570419..562e7c039a 100644
--- a/packages/studio-server/src/preview-server/routes/paste-effects.ts
+++ b/packages/studio-server/src/preview-server/routes/paste-effects.ts
@@ -30,7 +30,14 @@ export const pasteEffectsHandler: ApiHandler<
PasteEffectsRequest,
PasteEffectsResponse
> = ({
- input: {targetFileName, targetSequenceNodePath, type, effects, clientId},
+ input: {
+ targetFileName,
+ targetSequenceNodePath,
+ type,
+ effects,
+ clientId,
+ insertAtIndices,
+ },
remotionRoot,
logLevel,
}) => {
@@ -58,6 +65,7 @@ export const pasteEffectsHandler: ApiHandler<
targetSequenceNodePath: targetSequenceNodePath.nodePath,
type,
effects,
+ insertAtIndices,
});
const effectDescription = getPastedEffectDescription(effectLabels);
diff --git a/packages/studio-server/src/test/paste-effects.test.ts b/packages/studio-server/src/test/paste-effects.test.ts
index 4bef20dbca..3c5ec9ac2b 100644
--- a/packages/studio-server/src/test/paste-effects.test.ts
+++ b/packages/studio-server/src/test/paste-effects.test.ts
@@ -44,6 +44,7 @@ test('pasteEffects appends a copied effect to a target sequence', async () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -58,6 +59,116 @@ test('pasteEffects appends a copied effect to a target sequence', async () => {
expect(output).toMatch(/tint\(\{\s*color: ['"]red['"],?\s*\}\)/);
});
+test('pasteEffects inserts a cut effect at its original index', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas effects={[blur({radius: 5})]} />
+ </>`);
+ const target = makeNodePath(input, 9);
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ insertAtIndices: [0],
+ effects: [
+ {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: {type: 'static', value: 'red'}},
+ },
+ ],
+ });
+
+ expect(output.indexOf('tint({')).toBeLessThan(output.indexOf('blur({'));
+});
+
+test('pasteEffects restores noncontiguous effects in index order', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas effects={[blur({radius: 5}), tint({color: "blue"})]} />
+ </>`);
+ const target = makeNodePath(input, 9);
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ insertAtIndices: [3, 0],
+ effects: [
+ {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: {type: 'static', value: 'green'}},
+ },
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {radius: {type: 'static', value: 10}},
+ },
+ ],
+ });
+
+ const effects = output.slice(output.indexOf('effects={['));
+ expect(effects.indexOf('radius: 10')).toBeLessThan(
+ effects.indexOf('radius: 5'),
+ );
+ expect(effects.indexOf("color: 'blue'")).toBeLessThan(
+ effects.indexOf("color: 'green'"),
+ );
+});
+
+test('pasteEffects inserts by index when the target has no effects prop', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas />
+ </>`);
+ const target = makeNodePath(input, 9);
+
+ const {output} = await pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ insertAtIndices: [4],
+ effects: [
+ {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {radius: {type: 'static', value: 10}},
+ },
+ ],
+ });
+
+ expect(output).toContain('effects={[');
+ expect(output).toContain('blur({');
+ expect(output).toContain('radius: 10');
+});
+
+test('pasteEffects rejects invalid insertion indices', async () => {
+ const input = buildInput(`<>
+ <HtmlInCanvas effects={[blur({radius: 5})]} />
+ </>`);
+ const target = makeNodePath(input, 9);
+ const effect = {
+ callee: 'tint',
+ importPath: '@remotion/effects/tint',
+ params: {color: {type: 'static' as const, value: 'red'}},
+ };
+
+ for (const insertAtIndices of [[], [-1], [0.5]]) {
+ await expect(
+ pasteEffects({
+ input,
+ targetFileName: 'Comp.tsx',
+ targetSequenceNodePath: target.nodePath,
+ type: 'effects-additive',
+ insertAtIndices,
+ effects: [effect],
+ }),
+ ).rejects.toThrow('invalid insertion indices');
+ }
+});
+
test('pasteEffects replaces existing effects with all copied effects', async () => {
const input = buildInput(`<>
<HtmlInCanvas effects={[tint({color: "blue"})]} />
@@ -69,6 +180,7 @@ test('pasteEffects replaces existing effects with all copied effects', async ()
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-replacing',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -100,6 +212,7 @@ test('pasteEffects can paste after the source sequence no longer exists', async
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -127,6 +240,7 @@ test('pasteEffects inserts imports for copied effects', async () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -151,6 +265,7 @@ test('pasteEffects does not duplicate an existing copied effect import', async (
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -181,6 +296,7 @@ export const Comp = () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'brightness',
@@ -234,6 +350,7 @@ export const Comp = () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'brightness',
@@ -290,6 +407,7 @@ export const Comp = () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-additive',
+ insertAtIndices: null,
effects: [
{
callee: 'brightness',
@@ -325,6 +443,7 @@ test('pasteEffects replaces existing effects with mixed static and keyframed par
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-replacing',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
@@ -369,6 +488,7 @@ test('pasteEffects supports interpolated rotate keyframed params', async () => {
targetFileName: 'Comp.tsx',
targetSequenceNodePath: target.nodePath,
type: 'effects-replacing',
+ insertAtIndices: null,
effects: [
{
callee: 'tint',
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index eeeec10573..d51ace828c 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -622,6 +622,7 @@ export type PasteEffectsRequest = {
type: EffectClipboardPasteType;
effects: EffectClipboardSnapshot[];
clientId: string;
+ insertAtIndices: number[] | null;
};
export type PasteEffectsResponse =
diff --git a/packages/studio/src/components/KeyboardShortcutsExplainer.tsx b/packages/studio/src/components/KeyboardShortcutsExplainer.tsx
index 6f14b0ee66..37732685a4 100644
--- a/packages/studio/src/components/KeyboardShortcutsExplainer.tsx
+++ b/packages/studio/src/components/KeyboardShortcutsExplainer.tsx
@@ -386,6 +386,14 @@ export const KeyboardShortcutsExplainer: React.FC = () => {
</div>
<div style={right}>Copy effects / values</div>
</Row>
+ <Row align="center">
+ <div style={left}>
+ <kbd style={key}>{cmdOrCtrlCharacter}</kbd>
+ <Spacing x={0.3} />
+ <kbd style={key}>X</kbd>
+ </div>
+ <div style={right}>Cut effects</div>
+ </Row>
<Row align="center">
<div style={left}>
<kbd style={key}>{cmdOrCtrlCharacter}</kbd>
diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
index d194480b86..35965723b4 100644
--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
@@ -24,9 +24,22 @@ import {
} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
-import {useKeybinding} from '../../helpers/use-keybinding';
+import {
+ areKeyboardShortcutsDisabled,
+ useKeybinding,
+} from '../../helpers/use-keybinding';
import {callApi} from '../call-api';
+import {useConfirmationDialog} from '../ConfirmationDialog';
import {showNotification} from '../Notifications/NotificationCenter';
+import {
+ deleteSelectedTimelineItems,
+ getTimelineSelectionAfterDeletingItems,
+} from './delete-selected-timeline-item';
+import {
+ readClipboardTextAndEffectsEnvelope,
+ writeEffectsClipboardEnvelope,
+ type EffectsClipboardEnvelope,
+} from './effects-clipboard';
import {findTrackForNodePathInfo} from './find-track-for-node-path-info';
import {saveEffectProp} from './save-effect-prop';
import {
@@ -296,6 +309,129 @@ export const getSnapshotsFromSelection = ({
return snapshots;
};
+export type EffectClipboardDataFromSelections =
+ | {
+ readonly type: 'valid';
+ readonly payload: EffectClipboardData;
+ }
+ | {
+ readonly type: 'none';
+ }
+ | {
+ readonly type: 'mixed';
+ }
+ | {
+ readonly type: 'uncopyable';
+ };
+
+export const getEffectClipboardDataFromSelections = ({
+ selectedItems,
+ propStatuses,
+}: {
+ selectedItems: readonly TimelineSelection[];
+ propStatuses: PropStatuses;
+}): EffectClipboardDataFromSelections => {
+ const firstSelection = selectedItems[0];
+ const type = firstSelection ? getCopyType(firstSelection) : null;
+ if (type === null) {
+ return {type: 'none'};
+ }
+
+ if (selectedItems.some((selection) => getCopyType(selection) !== type)) {
+ return {type: 'mixed'};
+ }
+
+ const snapshots = selectedItems.flatMap((selection) => {
+ const itemSnapshots = getSnapshotsFromSelection({
+ selection,
+ propStatuses,
+ });
+ return itemSnapshots ?? [null];
+ });
+ if (snapshots.some((snapshot) => snapshot === null)) {
+ return {type: 'uncopyable'};
+ }
+
+ return {
+ type: 'valid',
+ payload: {
+ type,
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: snapshots as EffectClipboardSnapshot[],
+ },
+ };
+};
+
+export const getEffectsClipboardEnvelopeFromSelections = ({
+ selectedItems,
+ payload,
+}: {
+ selectedItems: readonly TimelineSelection[];
+ payload: EffectClipboardData;
+}): EffectsClipboardEnvelope => {
+ if (
+ payload.type !== 'effects-additive' ||
+ selectedItems.some((selection) => selection.type !== 'sequence-effect')
+ ) {
+ return {
+ envelopeVersion: 1,
+ payload,
+ sourceIdentity: null,
+ originalEffectIndices: [],
+ };
+ }
+
+ const effectSelections = selectedItems as readonly Extract<
+ TimelineSelection,
+ {type: 'sequence-effect'}
+ >[];
+ const firstSelection = effectSelections[0];
+ if (!firstSelection || effectSelections.length !== payload.effects.length) {
+ return {
+ envelopeVersion: 1,
+ payload,
+ sourceIdentity: null,
+ originalEffectIndices: [],
+ };
+ }
+
+ const sourceIdentity = makeTargetKey(
+ firstSelection.nodePathInfo.sequenceSubscriptionKey,
+ );
+ if (
+ effectSelections.some(
+ (selection) =>
+ makeTargetKey(selection.nodePathInfo.sequenceSubscriptionKey) !==
+ sourceIdentity,
+ )
+ ) {
+ return {
+ envelopeVersion: 1,
+ payload,
+ sourceIdentity: null,
+ originalEffectIndices: [],
+ };
+ }
+
+ const indexedEffects = effectSelections
+ .map((selection, index) => ({
+ effectIndex: selection.i,
+ effect: payload.effects[index] as EffectClipboardSnapshot,
+ }))
+ .sort((a, b) => a.effectIndex - b.effectIndex);
+
+ return {
+ envelopeVersion: 1,
+ payload: {
+ ...payload,
+ effects: indexedEffects.map(({effect}) => effect),
+ },
+ sourceIdentity,
+ originalEffectIndices: indexedEffects.map(({effectIndex}) => effectIndex),
+ };
+};
+
export const getEffectPropClipboardDataFromSelection = ({
selection,
propStatuses,
@@ -497,6 +633,7 @@ export const TimelineClipboardKeybindings: React.FC = () => {
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
+ const confirm = useConfirmationDialog();
useEffect(() => {
if (!canSelect || previewServerState.type !== 'connected') {
@@ -595,16 +732,15 @@ export const TimelineClipboardKeybindings: React.FC = () => {
return;
}
- const firstSelection = selectedItems[0];
- const type = firstSelection ? getCopyType(firstSelection) : null;
-
- if (type === null) {
+ const effectClipboardData = getEffectClipboardDataFromSelections({
+ selectedItems,
+ propStatuses,
+ });
+ if (effectClipboardData.type === 'none') {
return;
}
- if (
- selectedItems.some((selection) => getCopyType(selection) !== type)
- ) {
+ if (effectClipboardData.type === 'mixed') {
e.preventDefault();
showNotification(
'Cannot copy individual effects together with all effects',
@@ -613,14 +749,7 @@ export const TimelineClipboardKeybindings: React.FC = () => {
return;
}
- const snapshots = selectedItems.flatMap((selection) => {
- const itemSnapshots = getSnapshotsFromSelection({
- selection,
- propStatuses,
- });
- return itemSnapshots ?? [null];
- });
- if (snapshots.some((snapshot) => snapshot === null)) {
+ if (effectClipboardData.type === 'uncopyable') {
e.preventDefault();
showNotification(
'Cannot copy effects because one of them contains values that cannot be copied',
@@ -631,17 +760,10 @@ export const TimelineClipboardKeybindings: React.FC = () => {
e.preventDefault();
navigator.clipboard
- .writeText(
- makeClipboardText({
- type,
- version: 3,
- remotionClipboard: 'effects',
- effects: snapshots as EffectClipboardSnapshot[],
- }),
- )
+ .writeText(makeClipboardText(effectClipboardData.payload))
.then(() => {
showNotification(
- snapshots.length === 1
+ effectClipboardData.payload.effects.length === 1
? 'Copied effect to clipboard'
: 'Copied effects to clipboard',
1000,
@@ -660,232 +782,330 @@ export const TimelineClipboardKeybindings: React.FC = () => {
keepRegisteredWhenNotHighestContext: false,
});
- const paste = keybindings.registerKeybinding({
+ const cut = keybindings.registerKeybinding({
event: 'keydown',
- key: 'v',
+ key: 'x',
callback: (e) => {
- const {selectedItems} = currentSelection.current;
+ const {selectedItems, clearSelection, selectItems} =
+ currentSelection.current;
if (selectedItems.length === 0) {
return;
}
- navigator.clipboard
- .readText()
- .then((text) => {
- const propStatuses = propStatusesRef.current;
- const sequences = sequencesRef.current;
- const easingResult = parseEasingClipboardDataResult(text);
- if (easingResult.status !== 'invalid') {
- e.preventDefault();
- if (easingResult.status === 'unsupported-version') {
- showNotification(
- 'Cannot paste easing copied from a different Remotion Studio version',
- 4000,
- );
- return;
- }
-
- const easingSelections = getEasingSelections(selectedItems);
- if (
- easingSelections.length === 0 ||
- easingSelections.length !== selectedItems.length
- ) {
- showNotification('Select an easing to paste onto', 3000);
- return;
- }
-
- const updatePromise = updateSelectedTimelineEasings({
- selections: easingSelections,
- sequences,
- overrideIdsToNodePaths: overrideIdToNodePathMappings,
- propStatuses,
- setPropStatuses,
- clientId,
- easing: easingResult.data.easing,
- });
+ const effectClipboardData = getEffectClipboardDataFromSelections({
+ selectedItems,
+ propStatuses: propStatusesRef.current,
+ });
+ if (effectClipboardData.type === 'none') {
+ return;
+ }
- if (updatePromise === null) {
- showNotification(
- 'Cannot paste onto an easing that cannot be updated',
- 3000,
- );
- return;
- }
+ e.preventDefault();
+ if (effectClipboardData.type === 'mixed') {
+ showNotification(
+ 'Cannot cut individual effects together with all effects',
+ 3000,
+ );
+ return;
+ }
- return updatePromise
- .then(() => {
- showNotification(
- easingSelections.length === 1
- ? 'Pasted easing'
- : 'Pasted easing to selected segments',
- 2000,
- );
- })
- .catch((err) => {
- showNotification(
- `Could not paste easing: ${(err as Error).message}`,
- 3000,
- );
- });
- }
+ if (effectClipboardData.type === 'uncopyable') {
+ showNotification(
+ 'Cannot cut effects because one of them contains values that cannot be copied',
+ 3000,
+ );
+ return;
+ }
- const effectPropResult = parseEffectPropClipboardDataResult(text);
- if (effectPropResult.status !== 'invalid') {
- e.preventDefault();
- if (effectPropResult.status === 'unsupported-version') {
- showNotification(
- 'Cannot paste effect prop copied from a different Remotion Studio version',
- 4000,
- );
+ const envelope = getEffectsClipboardEnvelopeFromSelections({
+ selectedItems,
+ payload: effectClipboardData.payload,
+ });
+ const propStatuses = propStatusesRef.current;
+ writeEffectsClipboardEnvelope(envelope)
+ .then(() => {
+ const deletePromise = deleteSelectedTimelineItems({
+ selections: selectedItems,
+ sequences: sequencesRef.current,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ setPropStatuses,
+ clientId,
+ confirm,
+ });
+ return deletePromise?.then((deleted) => {
+ if (!deleted) {
return;
}
- const effectPropTarget = getPasteEffectPropTarget({
- selectedItems,
- payload: effectPropResult.data,
+ const nextSelection = getTimelineSelectionAfterDeletingItems({
+ selections: selectedItems,
propStatuses,
- sequences,
- overrideIdsToNodePaths: overrideIdToNodePathMappings,
});
-
- if (effectPropTarget.type !== 'valid') {
- switch (effectPropTarget.type) {
- case 'multiple':
- showNotification(
- 'Select one target effect prop or effect to paste onto',
- 3000,
- );
- return;
- case 'none':
- showNotification(
- 'Select a matching effect prop or effect to paste onto',
- 3000,
- );
- return;
- case 'unsupported':
- showNotification(
- 'This sequence does not support effects',
- 3000,
- );
- return;
- case 'effect-type-mismatch':
- showNotification(
- 'Select an effect of the same type to paste this prop',
- 3000,
- );
- return;
- case 'prop-mismatch':
- showNotification(
- 'Select the same effect prop, or an effect with that prop',
- 3000,
- );
- return;
- case 'uncopyable':
- showNotification(
- 'Cannot paste onto an effect prop that cannot be updated',
- 3000,
- );
- return;
- default:
- throw new Error(
- `Unexpected paste target: ${effectPropTarget satisfies never}`,
- );
- }
+ if (nextSelection.length === 0) {
+ clearSelection();
+ } else {
+ selectItems(nextSelection);
}
+ });
+ })
+ .catch((err) => {
+ showNotification(
+ `Could not cut effects: ${(err as Error).message}`,
+ 2000,
+ );
+ });
+ },
+ commandCtrlKey: true,
+ preventDefault: false,
+ triggerIfInputFieldFocused: false,
+ keepRegisteredWhenNotHighestContext: false,
+ });
- return saveEffectProp({
- fileName: effectPropTarget.fileName,
- nodePath: effectPropTarget.nodePath,
- effectIndex: effectPropTarget.effectIndex,
- fieldKey: effectPropTarget.fieldKey,
- ...(effectPropResult.data.param.type === 'static'
- ? {
- type: 'value' as const,
- value: effectPropResult.data.param.value,
- }
- : {
- type: 'effect-param' as const,
- effectParam: effectPropResult.data.param,
- }),
- defaultValue: effectPropTarget.defaultValue,
- schema: effectPropTarget.schema,
- setPropStatuses,
- clientId,
- }).then(() => {
- showNotification('Pasted effect prop', 2000);
- });
+ const handlePaste = (e: ClipboardEvent) => {
+ const {activeElement} = document;
+ if (
+ activeElement instanceof HTMLInputElement ||
+ activeElement instanceof HTMLTextAreaElement
+ ) {
+ return;
+ }
+
+ const {selectedItems} = currentSelection.current;
+ if (selectedItems.length === 0 || e.clipboardData === null) {
+ return;
+ }
+
+ e.preventDefault();
+ const {text, envelope} = readClipboardTextAndEffectsEnvelope(
+ e.clipboardData,
+ );
+ Promise.resolve()
+ .then(() => {
+ const propStatuses = propStatusesRef.current;
+ const sequences = sequencesRef.current;
+ const easingResult = parseEasingClipboardDataResult(text);
+ if (easingResult.status !== 'invalid') {
+ e.preventDefault();
+ if (easingResult.status === 'unsupported-version') {
+ showNotification(
+ 'Cannot paste easing copied from a different Remotion Studio version',
+ 4000,
+ );
+ return;
}
- const result = parseEffectClipboardDataResult(text);
- if (result.status === 'invalid') {
+ const easingSelections = getEasingSelections(selectedItems);
+ if (
+ easingSelections.length === 0 ||
+ easingSelections.length !== selectedItems.length
+ ) {
+ showNotification('Select an easing to paste onto', 3000);
return;
}
- e.preventDefault();
+ const updatePromise = updateSelectedTimelineEasings({
+ selections: easingSelections,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ propStatuses,
+ setPropStatuses,
+ clientId,
+ easing: easingResult.data.easing,
+ });
- if (result.status === 'unsupported-version') {
+ if (updatePromise === null) {
showNotification(
- 'Cannot paste effects copied from a different Remotion Studio version',
- 4000,
+ 'Cannot paste onto an easing that cannot be updated',
+ 3000,
);
return;
}
- const {data: payload} = result;
- const target = getPasteEffectsTarget(selectedItems);
- if (target.type === 'multiple') {
+ return updatePromise
+ .then(() => {
+ showNotification(
+ easingSelections.length === 1
+ ? 'Pasted easing'
+ : 'Pasted easing to selected segments',
+ 2000,
+ );
+ })
+ .catch((err) => {
+ showNotification(
+ `Could not paste easing: ${(err as Error).message}`,
+ 3000,
+ );
+ });
+ }
+
+ const effectPropResult = parseEffectPropClipboardDataResult(text);
+ if (effectPropResult.status !== 'invalid') {
+ e.preventDefault();
+ if (effectPropResult.status === 'unsupported-version') {
showNotification(
- 'Select one target sequence to paste effects',
- 3000,
+ 'Cannot paste effect prop copied from a different Remotion Studio version',
+ 4000,
);
return;
}
- if (target.type === 'none') {
- showNotification('Select a sequence to paste effects onto', 3000);
- return;
- }
+ const effectPropTarget = getPasteEffectPropTarget({
+ selectedItems,
+ payload: effectPropResult.data,
+ propStatuses,
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ });
- if (target.type === 'unsupported') {
- showNotification('This sequence does not support effects', 3000);
- return;
+ if (effectPropTarget.type !== 'valid') {
+ switch (effectPropTarget.type) {
+ case 'multiple':
+ showNotification(
+ 'Select one target effect prop or effect to paste onto',
+ 3000,
+ );
+ return;
+ case 'none':
+ showNotification(
+ 'Select a matching effect prop or effect to paste onto',
+ 3000,
+ );
+ return;
+ case 'unsupported':
+ showNotification(
+ 'This sequence does not support effects',
+ 3000,
+ );
+ return;
+ case 'effect-type-mismatch':
+ showNotification(
+ 'Select an effect of the same type to paste this prop',
+ 3000,
+ );
+ return;
+ case 'prop-mismatch':
+ showNotification(
+ 'Select the same effect prop, or an effect with that prop',
+ 3000,
+ );
+ return;
+ case 'uncopyable':
+ showNotification(
+ 'Cannot paste onto an effect prop that cannot be updated',
+ 3000,
+ );
+ return;
+ default:
+ throw new Error(
+ `Unexpected paste target: ${effectPropTarget satisfies never}`,
+ );
+ }
}
- const {sequenceSubscriptionKey: targetSequenceNodePath} =
- target.nodePathInfo;
- return callApi('/api/paste-effects', {
- targetFileName: targetSequenceNodePath.absolutePath,
- targetSequenceNodePath,
- type: payload.type,
- effects: payload.effects,
+ return saveEffectProp({
+ fileName: effectPropTarget.fileName,
+ nodePath: effectPropTarget.nodePath,
+ effectIndex: effectPropTarget.effectIndex,
+ fieldKey: effectPropTarget.fieldKey,
+ ...(effectPropResult.data.param.type === 'static'
+ ? {
+ type: 'value' as const,
+ value: effectPropResult.data.param.value,
+ }
+ : {
+ type: 'effect-param' as const,
+ effectParam: effectPropResult.data.param,
+ }),
+ defaultValue: effectPropTarget.defaultValue,
+ schema: effectPropTarget.schema,
+ setPropStatuses,
clientId,
- }).then((pasteResult) => {
- if (pasteResult.success) {
- showNotification('Pasted effects', 2000);
- } else {
- showNotification(pasteResult.reason, 4000);
- }
+ }).then(() => {
+ showNotification('Pasted effect prop', 2000);
});
- })
- .catch((err) => {
+ }
+
+ const result =
+ envelope === null
+ ? parseEffectClipboardDataResult(text)
+ : {status: 'valid' as const, data: envelope.payload};
+ if (result.status === 'invalid') {
+ return;
+ }
+
+ e.preventDefault();
+
+ if (result.status === 'unsupported-version') {
showNotification(
- `Could not paste effects: ${(err as Error).message}`,
+ 'Cannot paste effects copied from a different Remotion Studio version',
+ 4000,
+ );
+ return;
+ }
+
+ const {data: payload} = result;
+ const target = getPasteEffectsTarget(selectedItems);
+ if (target.type === 'multiple') {
+ showNotification(
+ 'Select one target sequence to paste effects',
3000,
);
+ return;
+ }
+
+ if (target.type === 'none') {
+ showNotification('Select a sequence to paste effects onto', 3000);
+ return;
+ }
+
+ if (target.type === 'unsupported') {
+ showNotification('This sequence does not support effects', 3000);
+ return;
+ }
+
+ const {sequenceSubscriptionKey: targetSequenceNodePath} =
+ target.nodePathInfo;
+ const insertAtIndices =
+ envelope?.sourceIdentity === makeTargetKey(targetSequenceNodePath)
+ ? envelope.originalEffectIndices
+ : null;
+ return callApi('/api/paste-effects', {
+ targetFileName: targetSequenceNodePath.absolutePath,
+ targetSequenceNodePath,
+ type: payload.type,
+ effects: payload.effects,
+ clientId,
+ insertAtIndices,
+ }).then((pasteResult) => {
+ if (pasteResult.success) {
+ showNotification('Pasted effects', 2000);
+ } else {
+ showNotification(pasteResult.reason, 4000);
+ }
});
- },
- commandCtrlKey: true,
- preventDefault: false,
- triggerIfInputFieldFocused: false,
- keepRegisteredWhenNotHighestContext: false,
- });
+ })
+ .catch((err) => {
+ showNotification(
+ `Could not paste effects: ${(err as Error).message}`,
+ 3000,
+ );
+ });
+ };
+
+ // Reading ClipboardEvent data avoids the permission prompt caused by
+ // navigator.clipboard.read().
+ if (keybindings.isHighestContext && !areKeyboardShortcutsDisabled()) {
+ document.addEventListener('paste', handlePaste);
+ }
return () => {
copy.unregister();
- paste.unregister();
+ cut.unregister();
+ document.removeEventListener('paste', handlePaste);
};
}, [
canSelect,
+ confirm,
currentSelection,
keybindings,
overrideIdToNodePathMappings,
diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
index 2c776a8df2..a72352ef0b 100644
--- a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
@@ -134,15 +134,15 @@ const deleteEffects = (
: 'Removed effects from source files',
2000,
);
- } else {
- showNotification(result.reason, 4000);
+ return true;
}
- return true;
+ showNotification(result.reason, 4000);
+ return false;
})
.catch((err) => {
showNotification((err as Error).message, 4000);
- return true;
+ return false;
});
};
diff --git a/packages/studio/src/components/Timeline/effects-clipboard.ts b/packages/studio/src/components/Timeline/effects-clipboard.ts
new file mode 100644
index 0000000000..9080db6e96
--- /dev/null
+++ b/packages/studio/src/components/Timeline/effects-clipboard.ts
@@ -0,0 +1,105 @@
+import {
+ parseEffectClipboardDataResult,
+ type EffectClipboardData,
+} from '@remotion/studio-shared';
+
+const attribute = 'data-remotion-effects-clipboard';
+
+export type EffectsClipboardEnvelope = {
+ readonly envelopeVersion: 1;
+ readonly payload: EffectClipboardData;
+ readonly sourceIdentity: string | null;
+ readonly originalEffectIndices: number[];
+};
+
+const getClipboardLabel = (effects: number): string =>
+ effects === 1 ? 'Remotion effect' : `${effects} Remotion effects`;
+
+export const makeEffectsClipboardHtml = (
+ envelope: EffectsClipboardEnvelope,
+): string =>
+ `<span ${attribute}="${encodeURIComponent(JSON.stringify(envelope))}">${getClipboardLabel(envelope.payload.effects.length)}</span>`;
+
+export const parseEffectsClipboardHtml = (
+ html: string,
+): EffectsClipboardEnvelope | null => {
+ const match = html.match(new RegExp(`${attribute}=["']([^"']+)["']`, 'i'));
+ if (!match?.[1]) {
+ return null;
+ }
+
+ try {
+ const candidate = JSON.parse(decodeURIComponent(match[1])) as Record<
+ string,
+ unknown
+ >;
+ if (
+ candidate.envelopeVersion !== 1 ||
+ (candidate.sourceIdentity !== null &&
+ typeof candidate.sourceIdentity !== 'string') ||
+ !Array.isArray(candidate.originalEffectIndices) ||
+ !candidate.originalEffectIndices.every(
+ (index) => Number.isInteger(index) && index >= 0,
+ )
+ ) {
+ return null;
+ }
+
+ const result = parseEffectClipboardDataResult(
+ JSON.stringify(candidate.payload),
+ );
+ if (result.status !== 'valid') {
+ return null;
+ }
+
+ const originalEffectIndices = candidate.originalEffectIndices as number[];
+ const sourceIdentity = candidate.sourceIdentity as string | null;
+ if (
+ (sourceIdentity === null && originalEffectIndices.length !== 0) ||
+ (sourceIdentity !== null &&
+ (originalEffectIndices.length !== result.data.effects.length ||
+ new Set(originalEffectIndices).size !== originalEffectIndices.length))
+ ) {
+ return null;
+ }
+
+ return {
+ envelopeVersion: 1,
+ payload: result.data,
+ sourceIdentity,
+ originalEffectIndices,
+ };
+ } catch {
+ return null;
+ }
+};
+
+export const writeEffectsClipboardEnvelope = async (
+ envelope: EffectsClipboardEnvelope,
+): Promise<void> => {
+ const label = getClipboardLabel(envelope.payload.effects.length);
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ 'text/html': new Blob([makeEffectsClipboardHtml(envelope)], {
+ type: 'text/html',
+ }),
+ 'text/plain': new Blob([label], {type: 'text/plain'}),
+ }),
+ ]);
+};
+
+export const readClipboardTextAndEffectsEnvelope = (
+ clipboardData: DataTransfer,
+): {
+ readonly text: string;
+ readonly envelope: EffectsClipboardEnvelope | null;
+} => {
+ const html = clipboardData.types.includes('text/html')
+ ? clipboardData.getData('text/html')
+ : '';
+
+ return {
+ text: clipboardData.getData('text/plain'),
+ envelope: html === '' ? null : parseEffectsClipboardHtml(html),
+ };
+};
diff --git a/packages/studio/src/test/effects-clipboard.test.ts b/packages/studio/src/test/effects-clipboard.test.ts
new file mode 100644
index 0000000000..b1746707f0
--- /dev/null
+++ b/packages/studio/src/test/effects-clipboard.test.ts
@@ -0,0 +1,73 @@
+import {expect, test} from 'bun:test';
+import type {EffectClipboardData} from '@remotion/studio-shared';
+import {
+ makeEffectsClipboardHtml,
+ parseEffectsClipboardHtml,
+ readClipboardTextAndEffectsEnvelope,
+ type EffectsClipboardEnvelope,
+} from '../components/Timeline/effects-clipboard';
+
+const payload: EffectClipboardData = {
+ type: 'effects-additive',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [
+ {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {amount: {type: 'static', value: 1}},
+ },
+ ],
+};
+
+const envelope: EffectsClipboardEnvelope = {
+ envelopeVersion: 1,
+ payload,
+ sourceIdentity: 'source',
+ originalEffectIndices: [0],
+};
+
+test('effect clipboard data round-trips through marked HTML', () => {
+ const html = makeEffectsClipboardHtml(envelope);
+ expect(html).toContain('>Remotion effect</span>');
+ expect(html).not.toContain(JSON.stringify(payload));
+ expect(parseEffectsClipboardHtml(html)).toEqual(envelope);
+});
+
+test('effect clipboard data is read from a native paste event', () => {
+ const html = makeEffectsClipboardHtml(envelope);
+ const clipboardData = {
+ types: ['text/html', 'text/plain'],
+ getData: (type: string) =>
+ type === 'text/html' ? html : 'Remotion effect',
+ } as unknown as DataTransfer;
+
+ expect(readClipboardTextAndEffectsEnvelope(clipboardData)).toEqual({
+ text: 'Remotion effect',
+ envelope,
+ });
+});
+
+test('effect clipboard HTML rejects invalid envelope data', () => {
+ const makeInvalidHtml = (candidate: unknown) =>
+ `<span data-remotion-effects-clipboard="${encodeURIComponent(JSON.stringify(candidate))}">Remotion effect</span>`;
+ const invalidCandidates = [
+ {...envelope, envelopeVersion: 2},
+ {...envelope, originalEffectIndices: []},
+ {...envelope, originalEffectIndices: [-1]},
+ {...envelope, originalEffectIndices: [0.5]},
+ {...envelope, sourceIdentity: null},
+ {...envelope, payload: {...payload, version: 2}},
+ ];
+
+ for (const candidate of invalidCandidates) {
+ expect(parseEffectsClipboardHtml(makeInvalidHtml(candidate))).toBe(null);
+ }
+
+ expect(
+ parseEffectsClipboardHtml(
+ '<span data-remotion-effects-clipboard="%E0%A4%A">Remotion effect</span>',
+ ),
+ ).toBe(null);
+ expect(parseEffectsClipboardHtml('<span>Remotion effect</span>')).toBe(null);
+});
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 48f4e86dd1..4628bea4bd 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -72,6 +72,7 @@ import {getTimelinePropResetTargets} from '../components/Timeline/reset-selected
import {shouldSubscribeToSequenceProps} from '../components/Timeline/should-subscribe-to-sequence-props';
import {
getEasingClipboardDataFromSelection,
+ getEffectsClipboardEnvelopeFromSelections,
getEffectPropClipboardDataFromSelection,
getPasteEffectPropTarget,
getPasteEffectsTarget,
@@ -631,6 +632,38 @@ test('copying a keyframed effect creates a structured snapshot', () => {
]);
});
+test('cut effect clipboard metadata preserves source order', () => {
+ const nodePathInfo = makeNodePathInfo(['body', 0], ['effects', '0'], true, [
+ ['0'],
+ ]);
+ const blur = {
+ callee: 'blur',
+ importPath: '@remotion/effects/blur',
+ params: {},
+ };
+ const brightness = {
+ callee: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ params: {},
+ };
+ const envelope = getEffectsClipboardEnvelopeFromSelections({
+ selectedItems: [
+ {type: 'sequence-effect', nodePathInfo, i: 1},
+ {type: 'sequence-effect', nodePathInfo, i: 0},
+ ],
+ payload: {
+ type: 'effects-additive',
+ version: 3,
+ remotionClipboard: 'effects',
+ effects: [blur, brightness],
+ },
+ });
+
+ expect(envelope.sourceIdentity).not.toBe(null);
+ expect(envelope.originalEffectIndices).toEqual([0, 1]);
+ expect(envelope.payload.effects).toEqual([brightness, blur]);
+});
+
test('copying a selected effect prop creates an effect prop payload', () => {
const effectPropNodePathInfo = makeNodePathInfo(
['body', 0],