Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add asset import to timeline context menu

Jonny Burger865db5042388
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 244624218d..868aff9c7b 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1,5 +1,4 @@
import type {Size} from '@remotion/player';
-import type {InsertableCompositionElement} from '@remotion/studio-shared';
import React, {
useCallback,
useContext,
@@ -10,12 +9,8 @@ import React, {
} from 'react';
import type {CanvasContent} from 'remotion';
import {Internals, watchStaticFile} from 'remotion';
-import {getStaticFiles} from '../api/get-static-files';
-import {writeStaticFile} from '../api/write-static-file';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {BACKGROUND} from '../helpers/colors';
-import {detectFileType} from '../helpers/detect-file-type';
-import type {FileType} from '../helpers/detect-file-type';
import type {AssetMetadata} from '../helpers/get-asset-metadata';
import {getAssetMetadata} from '../helpers/get-asset-metadata';
import {
@@ -33,12 +28,11 @@ import {useKeybinding} from '../helpers/use-keybinding';
import {canvasRef} from '../state/canvas-ref';
import {EditorShowGuidesContext} from '../state/editor-guides';
import {EditorZoomGesturesContext} from '../state/editor-zoom-gestures';
-import {callApi} from './call-api';
import EditorGuides from './EditorGuides';
import {EditorRulers} from './EditorRuler';
import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
+import {importAssets} from './import-assets';
import {SPACING_UNIT} from './layout';
-import {showNotification} from './Notifications/NotificationCenter';
import {VideoPreview} from './Preview';
import {ResetZoomButton} from './ResetZoomButton';
import {useResolvedStack} from './Timeline/use-resolved-stack';
@@ -62,69 +56,6 @@ const resetZoom: React.CSSProperties = {
const ZOOM_PX_FACTOR = 0.003;
-const getAssetElement = ({
- fileType,
- src,
-}: {
- fileType: FileType;
- src: string;
-}): InsertableCompositionElement | null => {
- if (
- fileType.type === 'png' ||
- fileType.type === 'jpeg' ||
- fileType.type === 'webp' ||
- fileType.type === 'bmp'
- ) {
- return {
- type: 'asset',
- assetType: 'image',
- src,
- dimensions: fileType.dimensions,
- };
- }
-
- if (fileType.type === 'gif') {
- return {
- type: 'asset',
- assetType: 'gif',
- src,
- dimensions: fileType.dimensions,
- };
- }
-
- if (
- fileType.type === 'riff' ||
- fileType.type === 'webm' ||
- fileType.type === 'iso-base-media' ||
- fileType.type === 'transport-stream'
- ) {
- return {
- type: 'asset',
- assetType: 'video',
- src,
- dimensions: null,
- };
- }
-
- return null;
-};
-
-const getAssetLabel = (element: InsertableCompositionElement) => {
- if (element.type !== 'asset') {
- throw new Error('Expected asset element');
- }
-
- if (element.assetType === 'image') {
- return '<Img>';
- }
-
- if (element.assetType === 'video') {
- return '<Video>';
- }
-
- return '<Gif>';
-};
-
type WebKitGestureEvent = UIEvent & {
scale: number;
clientX: number;
@@ -701,114 +632,13 @@ export const Canvas: React.FC<{
return;
}
- const staticFiles = getStaticFiles();
- const differentExistingFile = files.find((file) => {
- return staticFiles.some(
- (staticFile) =>
- staticFile.name === file.name &&
- staticFile.sizeInBytes !== file.size,
- );
- });
- if (differentExistingFile) {
- showNotification(
- `File with name ${differentExistingFile.name} already exists and is different`,
- 4000,
- );
- return;
- }
-
setIsAddingAsset(true);
- const insertedLabels: string[] = [];
- const addedStaticFiles: string[] = [];
- const unsupportedFiles: string[] = [];
- const notifyAddedStaticFiles = () => {
- if (addedStaticFiles.length === 1) {
- showNotification(
- `Created ${addedStaticFiles[0]} in public folder`,
- 3000,
- );
- } else if (addedStaticFiles.length > 1) {
- showNotification(
- `Added ${addedStaticFiles.length} files to public folder`,
- 3000,
- );
- }
-
- addedStaticFiles.length = 0;
- };
-
try {
- for (const file of files) {
- const contents = await file.arrayBuffer();
- const fileType = detectFileType(new Uint8Array(contents));
- const element = getAssetElement({
- fileType,
- src: file.name,
- });
-
- if (element === null) {
- unsupportedFiles.push(file.name);
- continue;
- }
-
- const alreadyExists = staticFiles.some(
- (staticFile) =>
- staticFile.name === file.name &&
- staticFile.sizeInBytes === file.size,
- );
-
- if (!alreadyExists) {
- await writeStaticFile({
- contents,
- filePath: file.name,
- });
- addedStaticFiles.push(file.name);
- }
-
- const result = await callApi('/api/insert-jsx-element', {
- compositionFile,
- compositionId: currentCompositionId,
- element,
- });
-
- if (!result.success) {
- notifyAddedStaticFiles();
- showNotification(result.reason, 4000);
- return;
- }
-
- insertedLabels.push(getAssetLabel(element));
- }
-
- notifyAddedStaticFiles();
-
- if (insertedLabels.length === 1) {
- showNotification(`Added ${insertedLabels[0]} to source file`, 2000);
- } else if (insertedLabels.length > 1) {
- showNotification(
- `Added ${insertedLabels.length} assets to source file`,
- 2000,
- );
- }
-
- if (unsupportedFiles.length === 1) {
- showNotification(
- `Cannot add ${unsupportedFiles[0]}: Unsupported file type`,
- 3000,
- );
- } else if (unsupportedFiles.length > 1) {
- showNotification(
- `Skipped ${unsupportedFiles.length} unsupported files`,
- 3000,
- );
- }
- } catch (error) {
- showNotification(
- `Could not add asset: ${
- error instanceof Error ? error.message : String(error)
- }`,
- 4000,
- );
+ await importAssets({
+ files,
+ compositionFile,
+ compositionId: currentCompositionId,
+ });
} finally {
setIsAddingAsset(false);
}
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 371e95622d..dad2415133 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -8,6 +8,7 @@ import {useIsStill} from '../../helpers/is-current-selected-still';
import {useCachedCompositionComponentInfo} from '../../helpers/open-in-editor';
import {callApi} from '../call-api';
import {ContextMenu} from '../ContextMenu';
+import {importAssets, pickFilesToImport} from '../import-assets';
import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';
import type {ComboboxValue} from '../NewComposition/ComboBox';
import {showNotification} from '../Notifications/NotificationCenter';
@@ -60,6 +61,8 @@ const TimelineClearSelectionArea: React.FC<{
);
const videoConfig = Internals.useUnsafeVideoConfig();
const [isAddingSolid, setIsAddingSolid] = useState(false);
+ const [isAddingAsset, setIsAddingAsset] = useState(false);
+ const {previewServerState} = useContext(StudioServerConnectionCtx);
const currentCompositionId =
canvasContent?.type === 'composition' ? canvasContent.compositionId : null;
@@ -104,6 +107,14 @@ const TimelineClearSelectionArea: React.FC<{
videoConfig !== null &&
!isAddingSolid;
+ const canInsertAsset =
+ previewServerState.type === 'connected' &&
+ !window.remotion_isReadOnlyStudio &&
+ compositionComponentInfo?.canAddSequence === true &&
+ currentCompositionId !== null &&
+ compositionFile !== null &&
+ !isAddingAsset;
+
const insertSolid = useCallback(async () => {
if (
!canInsertSolid ||
@@ -139,6 +150,32 @@ const TimelineClearSelectionArea: React.FC<{
}
}, [canInsertSolid, compositionFile, currentCompositionId, videoConfig]);
+ const insertAsset = useCallback(async () => {
+ if (
+ !canInsertAsset ||
+ currentCompositionId === null ||
+ compositionFile === null
+ ) {
+ return;
+ }
+
+ const files = await pickFilesToImport();
+ if (files.length === 0) {
+ return;
+ }
+
+ setIsAddingAsset(true);
+ try {
+ await importAssets({
+ files,
+ compositionFile,
+ compositionId: currentCompositionId,
+ });
+ } finally {
+ setIsAddingAsset(false);
+ }
+ }, [canInsertAsset, compositionFile, currentCompositionId]);
+
const contextMenuItems = useMemo((): ComboboxValue[] => {
return [
{
@@ -153,8 +190,20 @@ const TimelineClearSelectionArea: React.FC<{
quickSwitcherLabel: null,
disabled: !canInsertSolid,
},
+ {
+ type: 'item',
+ id: 'insert-asset',
+ label: 'Add asset',
+ value: 'insert-asset',
+ onClick: insertAsset,
+ keyHint: null,
+ leftItem: null,
+ subMenu: null,
+ quickSwitcherLabel: null,
+ disabled: !canInsertAsset,
+ },
];
- }, [insertSolid, canInsertSolid]);
+ }, [insertSolid, canInsertSolid, insertAsset, canInsertAsset]);
return (
<ContextMenu
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
new file mode 100644
index 0000000000..5b955a5f04
--- /dev/null
+++ b/packages/studio/src/components/import-assets.ts
@@ -0,0 +1,217 @@
+import type {InsertableCompositionElement} from '@remotion/studio-shared';
+import {getStaticFiles} from '../api/get-static-files';
+import {writeStaticFile} from '../api/write-static-file';
+import {detectFileType, type FileType} from '../helpers/detect-file-type';
+import {callApi} from './call-api';
+import {showNotification} from './Notifications/NotificationCenter';
+
+const getAssetElement = ({
+ fileType,
+ src,
+}: {
+ fileType: FileType;
+ src: string;
+}): InsertableCompositionElement | null => {
+ if (
+ fileType.type === 'png' ||
+ fileType.type === 'jpeg' ||
+ fileType.type === 'webp' ||
+ fileType.type === 'bmp'
+ ) {
+ return {
+ type: 'asset',
+ assetType: 'image',
+ src,
+ dimensions: fileType.dimensions,
+ };
+ }
+
+ if (fileType.type === 'gif') {
+ return {
+ type: 'asset',
+ assetType: 'gif',
+ src,
+ dimensions: fileType.dimensions,
+ };
+ }
+
+ if (
+ fileType.type === 'riff' ||
+ fileType.type === 'webm' ||
+ fileType.type === 'iso-base-media' ||
+ fileType.type === 'transport-stream'
+ ) {
+ return {
+ type: 'asset',
+ assetType: 'video',
+ src,
+ dimensions: null,
+ };
+ }
+
+ return null;
+};
+
+const getAssetLabel = (element: InsertableCompositionElement) => {
+ if (element.type !== 'asset') {
+ throw new Error('Expected asset element');
+ }
+
+ if (element.assetType === 'image') {
+ return '<Img>';
+ }
+
+ if (element.assetType === 'video') {
+ return '<Video>';
+ }
+
+ return '<Gif>';
+};
+
+export const pickFilesToImport = (): Promise<File[]> => {
+ return new Promise((resolve) => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.multiple = true;
+ input.style.display = 'none';
+
+ let didResolve = false;
+ const resolveOnce = (files: File[]) => {
+ if (didResolve) {
+ return;
+ }
+
+ didResolve = true;
+ input.removeEventListener('change', onChange);
+ input.removeEventListener('cancel', onCancel);
+ input.remove();
+ resolve(files);
+ };
+
+ const onChange = () => resolveOnce(Array.from(input.files ?? []));
+ const onCancel = () => resolveOnce([]);
+
+ input.addEventListener('change', onChange);
+ input.addEventListener('cancel', onCancel);
+ document.body.appendChild(input);
+ input.click();
+ });
+};
+
+export const importAssets = async ({
+ compositionFile,
+ compositionId,
+ files,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ files: File[];
+}) => {
+ if (files.length === 0) {
+ return;
+ }
+
+ const staticFiles = getStaticFiles();
+ const differentExistingFile = files.find((file) => {
+ return staticFiles.some(
+ (staticFile) =>
+ staticFile.name === file.name && staticFile.sizeInBytes !== file.size,
+ );
+ });
+ if (differentExistingFile) {
+ showNotification(
+ `File with name ${differentExistingFile.name} already exists and is different`,
+ 4000,
+ );
+ return;
+ }
+
+ const insertedLabels: string[] = [];
+ const addedStaticFiles: string[] = [];
+ const unsupportedFiles: string[] = [];
+ const notifyAddedStaticFiles = () => {
+ if (addedStaticFiles.length === 1) {
+ showNotification(`Created ${addedStaticFiles[0]} in public folder`, 3000);
+ } else if (addedStaticFiles.length > 1) {
+ showNotification(
+ `Added ${addedStaticFiles.length} files to public folder`,
+ 3000,
+ );
+ }
+
+ addedStaticFiles.length = 0;
+ };
+
+ try {
+ for (const file of files) {
+ const contents = await file.arrayBuffer();
+ const fileType = detectFileType(new Uint8Array(contents));
+ const element = getAssetElement({
+ fileType,
+ src: file.name,
+ });
+
+ if (element === null) {
+ unsupportedFiles.push(file.name);
+ continue;
+ }
+
+ const alreadyExists = staticFiles.some(
+ (staticFile) =>
+ staticFile.name === file.name && staticFile.sizeInBytes === file.size,
+ );
+
+ if (!alreadyExists) {
+ await writeStaticFile({
+ contents,
+ filePath: file.name,
+ });
+ addedStaticFiles.push(file.name);
+ }
+
+ const result = await callApi('/api/insert-jsx-element', {
+ compositionFile,
+ compositionId,
+ element,
+ });
+
+ if (!result.success) {
+ notifyAddedStaticFiles();
+ showNotification(result.reason, 4000);
+ return;
+ }
+
+ insertedLabels.push(getAssetLabel(element));
+ }
+
+ notifyAddedStaticFiles();
+
+ if (insertedLabels.length === 1) {
+ showNotification(`Added ${insertedLabels[0]} to source file`, 2000);
+ } else if (insertedLabels.length > 1) {
+ showNotification(
+ `Added ${insertedLabels.length} assets to source file`,
+ 2000,
+ );
+ }
+
+ if (unsupportedFiles.length === 1) {
+ showNotification(
+ `Cannot add ${unsupportedFiles[0]}: Unsupported file type`,
+ 3000,
+ );
+ } else if (unsupportedFiles.length > 1) {
+ showNotification(
+ `Skipped ${unsupportedFiles.length} unsupported files`,
+ 3000,
+ );
+ }
+ } catch (error) {
+ showNotification(
+ `Could not add asset: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 4000,
+ );
+ }
+};