Skip to content

🎥 Make videos programmatically with React

Support pasting images from clipboard (#9322)

Jonny Burger7146709d64c2
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index e0449dc259..aa3aee5642 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -23,7 +23,9 @@ import React, {
} from 'react';
import type {CanvasContent} from 'remotion';
import {Internals, watchStaticFile, type PreviewSize} from 'remotion';
+import {getStaticFiles} from '../api/get-static-files';
import {StudioServerConnectionCtx} from '../helpers/client-id';
+import {getClipboardImageFiles} from '../helpers/clipboard-images';
import {BACKGROUND} from '../helpers/colors';
import type {AssetMetadata} from '../helpers/get-asset-metadata';
import {getAssetMetadata} from '../helpers/get-asset-metadata';
@@ -44,7 +46,10 @@ import {
smoothenZoom,
unsmoothenZoom,
} from '../helpers/smooth-zoom';
-import {useKeybinding} from '../helpers/use-keybinding';
+import {
+ areKeyboardShortcutsDisabled,
+ useKeybinding,
+} from '../helpers/use-keybinding';
import {canvasRef} from '../state/canvas-ref';
import {EditorShowGuidesContext} from '../state/editor-guides';
import {EditorZoomGesturesContext} from '../state/editor-zoom-gestures';
@@ -1193,6 +1198,54 @@ export const Canvas: React.FC<{
],
);
+ const onPaste = useCallback(
+ async (event: ClipboardEvent) => {
+ const {activeElement} = document;
+ if (
+ !canDropAssets ||
+ compositionFile === null ||
+ currentCompositionId === null ||
+ event.clipboardData === null ||
+ activeElement instanceof HTMLInputElement ||
+ activeElement instanceof HTMLTextAreaElement ||
+ (activeElement instanceof HTMLElement &&
+ activeElement.isContentEditable)
+ ) {
+ return;
+ }
+
+ const files = getClipboardImageFiles({
+ clipboardData: event.clipboardData,
+ existingFileNames: getStaticFiles().map((file) => file.name),
+ });
+ if (files.length === 0) {
+ return;
+ }
+
+ event.preventDefault();
+ setIsAddingAsset(true);
+ try {
+ await importAssets({
+ files,
+ compositionFile,
+ compositionId: currentCompositionId,
+ destinationDimensions:
+ contentDimensions === 'none' ? null : contentDimensions,
+ dropPosition:
+ contentDimensions === null || contentDimensions === 'none'
+ ? null
+ : {
+ centerX: contentDimensions.width / 2,
+ centerY: contentDimensions.height / 2,
+ },
+ });
+ } finally {
+ setIsAddingAsset(false);
+ }
+ },
+ [canDropAssets, compositionFile, contentDimensions, currentCompositionId],
+ );
+
useEffect(() => {
document.addEventListener('dragover', onDragOver, {capture: true});
document.addEventListener('drop', onDrop, {capture: true});
@@ -1203,6 +1256,19 @@ export const Canvas: React.FC<{
};
}, [onDragOver, onDrop]);
+ useEffect(() => {
+ if (
+ !canDropAssets ||
+ !keybindings.isHighestContext ||
+ areKeyboardShortcutsDisabled()
+ ) {
+ return;
+ }
+
+ document.addEventListener('paste', onPaste);
+ return () => document.removeEventListener('paste', onPaste);
+ }, [canDropAssets, keybindings.isHighestContext, onPaste]);
+
return (
<>
<div ref={canvasRef} style={getContainerStyle(editorZoomGestures)}>
diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
index 5c93d66f7a..69d5b160f4 100644
--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
@@ -25,6 +25,7 @@ import {
type TSequence,
} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
+import {hasClipboardImage} from '../../helpers/clipboard-images';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
import {
areKeyboardShortcutsDisabled,
@@ -932,7 +933,11 @@ export const TimelineClipboardKeybindings: React.FC = () => {
}
const {selectedItems} = currentSelection.current;
- if (selectedItems.length === 0 || e.clipboardData === null) {
+ if (
+ selectedItems.length === 0 ||
+ e.clipboardData === null ||
+ hasClipboardImage(e.clipboardData)
+ ) {
return;
}
diff --git a/packages/studio/src/helpers/clipboard-images.ts b/packages/studio/src/helpers/clipboard-images.ts
new file mode 100644
index 0000000000..517818e21a
--- /dev/null
+++ b/packages/studio/src/helpers/clipboard-images.ts
@@ -0,0 +1,113 @@
+const getClipboardFiles = (clipboardData: DataTransfer): File[] => {
+ const imageItems = Array.from(clipboardData.items).filter(
+ (item) => item.kind === 'file' && item.type.startsWith('image/'),
+ );
+
+ if (imageItems.length > 0) {
+ const files = imageItems
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => file !== null);
+ if (files.length > 0) {
+ return files;
+ }
+ }
+
+ return Array.from(clipboardData.files).filter((file) =>
+ file.type.startsWith('image/'),
+ );
+};
+
+export const hasClipboardImage = (clipboardData: DataTransfer): boolean => {
+ return (
+ Array.from(clipboardData.items).some(
+ (item) => item.kind === 'file' && item.type.startsWith('image/'),
+ ) ||
+ Array.from(clipboardData.files).some((file) =>
+ file.type.startsWith('image/'),
+ )
+ );
+};
+
+const getExtensionForMimeType = (mimeType: string): string => {
+ switch (mimeType) {
+ case 'image/jpeg':
+ return 'jpg';
+ case 'image/svg+xml':
+ return 'svg';
+ default:
+ return mimeType.startsWith('image/')
+ ? mimeType.slice('image/'.length)
+ : 'png';
+ }
+};
+
+const getNameParts = ({
+ fileName,
+ mimeType,
+}: {
+ fileName: string;
+ mimeType: string;
+}): {base: string; extension: string} => {
+ const trimmedName = fileName.trim();
+ const lastDot = trimmedName.lastIndexOf('.');
+ if (lastDot > 0 && lastDot < trimmedName.length - 1) {
+ return {
+ base: trimmedName.slice(0, lastDot),
+ extension: trimmedName.slice(lastDot + 1),
+ };
+ }
+
+ return {
+ base: 'pasted-image',
+ extension: getExtensionForMimeType(mimeType),
+ };
+};
+
+export const getUniqueClipboardImageName = ({
+ existingFileNames,
+ fileName,
+ mimeType,
+}: {
+ existingFileNames: Set<string>;
+ fileName: string;
+ mimeType: string;
+}): string => {
+ const {base, extension} = getNameParts({fileName, mimeType});
+ let candidate = `${base}.${extension}`;
+ let suffix = 1;
+
+ while (existingFileNames.has(candidate)) {
+ candidate = `${base}-${suffix}.${extension}`;
+ suffix++;
+ }
+
+ return candidate;
+};
+
+export const getClipboardImageFiles = ({
+ clipboardData,
+ existingFileNames,
+}: {
+ clipboardData: DataTransfer;
+ existingFileNames: string[];
+}): File[] => {
+ const usedNames = new Set(existingFileNames);
+
+ return getClipboardFiles(clipboardData).map((file) => {
+ const candidate = getUniqueClipboardImageName({
+ existingFileNames: usedNames,
+ fileName: file.name ?? '',
+ mimeType: file.type,
+ });
+
+ usedNames.add(candidate);
+ if (candidate === file.name) {
+ return file;
+ }
+
+ return new File([file.slice()], candidate, {
+ type: file.type,
+ lastModified: file.lastModified,
+ });
+ });
+};
diff --git a/packages/studio/src/test/clipboard-images.test.ts b/packages/studio/src/test/clipboard-images.test.ts
new file mode 100644
index 0000000000..56fbcd3c42
--- /dev/null
+++ b/packages/studio/src/test/clipboard-images.test.ts
@@ -0,0 +1,69 @@
+import {expect, test} from 'bun:test';
+import {
+ getClipboardImageFiles,
+ getUniqueClipboardImageName,
+ hasClipboardImage,
+} from '../helpers/clipboard-images';
+
+const makeClipboardData = (files: File[]): DataTransfer => {
+ return {
+ files,
+ items: [],
+ } as unknown as DataTransfer;
+};
+
+test('gets images from clipboard items', () => {
+ const image = new File(['image'], 'image.png', {type: 'image/png'});
+ const clipboardData = {
+ files: [],
+ items: [
+ {
+ kind: 'file',
+ type: 'image/png',
+ getAsFile: () => image,
+ },
+ ],
+ } as unknown as DataTransfer;
+
+ expect(hasClipboardImage(clipboardData)).toBe(true);
+ expect(
+ getClipboardImageFiles({clipboardData, existingFileNames: []}),
+ ).toEqual([image]);
+});
+
+test('gets images from clipboard files and ignores other files', () => {
+ const image = new File(['image'], 'image.png', {type: 'image/png'});
+ const text = new File(['text'], 'notes.txt', {type: 'text/plain'});
+ const clipboardData = makeClipboardData([image, text]);
+
+ expect(hasClipboardImage(clipboardData)).toBe(true);
+ expect(
+ getClipboardImageFiles({clipboardData, existingFileNames: []}),
+ ).toEqual([image]);
+});
+
+test('gives unnamed and duplicate clipboard images unique names', () => {
+ expect(
+ getUniqueClipboardImageName({
+ existingFileNames: new Set(['pasted-image.png']),
+ fileName: '',
+ mimeType: 'image/png',
+ }),
+ ).toBe('pasted-image-1.png');
+ expect(
+ getUniqueClipboardImageName({
+ existingFileNames: new Set(['image.png', 'image-1.png']),
+ fileName: 'image.png',
+ mimeType: 'image/png',
+ }),
+ ).toBe('image-2.png');
+});
+
+test('uses an extension matching the clipboard MIME type', () => {
+ const jpeg = new File(['image'], '', {type: 'image/jpeg'});
+ const clipboardData = makeClipboardData([jpeg]);
+
+ expect(
+ getClipboardImageFiles({clipboardData, existingFileNames: []})[0]?.name,
+ ).toBe('pasted-image.jpg');
+});