🎥 Make videos programmatically with React
Add asset panel drag import
Cursor Agent0ea6de517688
diff --git a/packages/studio-shared/src/asset-drag-data.ts b/packages/studio-shared/src/asset-drag-data.tsnew file mode 100644index 0000000000..a67c331039--- /dev/null+++ b/packages/studio-shared/src/asset-drag-data.ts@@ -0,0 +1,44 @@+export const ASSET_DRAG_MIME_TYPE = 'application/vnd.remotion.asset+json';++export type AssetDragData = {+ type: 'remotion-asset';+ version: 1;+ assetPath: string;+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+};++export const makeAssetDragData = (assetPath: string): AssetDragData => {+ return {+ type: 'remotion-asset',+ version: 1,+ assetPath,+ };+};++export const parseAssetDragData = (value: string): AssetDragData | null => {+ try {+ const parsed: unknown = JSON.parse(value);+ if (!isRecord(parsed)) {+ return null;+ }++ if (parsed.type !== 'remotion-asset' || parsed.version !== 1) {+ return null;+ }++ if (typeof parsed.assetPath !== 'string' || parsed.assetPath.length === 0) {+ return null;+ }++ return {+ type: 'remotion-asset',+ version: 1,+ assetPath: parsed.assetPath,+ };+ } catch {+ return null;+ }+};diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex bb8ab28186..f2c646c996 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -85,6 +85,12 @@ export {type KeyframeSettings,} from './api-requests';export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';+export {+ ASSET_DRAG_MIME_TYPE,+ makeAssetDragData,+ parseAssetDragData,+ type AssetDragData,+} from './asset-drag-data';export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';export {parseEffectClipboardData,diff --git a/packages/studio-shared/src/test/asset-drag-data.test.ts b/packages/studio-shared/src/test/asset-drag-data.test.tsnew file mode 100644index 0000000000..4775289818--- /dev/null+++ b/packages/studio-shared/src/test/asset-drag-data.test.ts@@ -0,0 +1,35 @@+import {expect, test} from 'bun:test';+import {makeAssetDragData, parseAssetDragData} from '../asset-drag-data';++test('parses asset drag data', () => {+ expect(+ parseAssetDragData(JSON.stringify(makeAssetDragData('nested/image.png'))),+ ).toEqual({+ type: 'remotion-asset',+ version: 1,+ assetPath: 'nested/image.png',+ });+});++test('rejects invalid asset drag data', () => {+ expect(parseAssetDragData('')).toBe(null);+ expect(parseAssetDragData('{')).toBe(null);+ expect(+ parseAssetDragData(+ JSON.stringify({+ type: 'remotion-asset',+ version: 2,+ assetPath: 'image.png',+ }),+ ),+ ).toBe(null);+ expect(+ parseAssetDragData(+ JSON.stringify({+ type: 'remotion-asset',+ version: 1,+ assetPath: '',+ }),+ ),+ ).toBe(null);+});diff --git a/packages/studio/src/components/AssetSelectorItem.tsx b/packages/studio/src/components/AssetSelectorItem.tsxindex e9e3b1fbec..ec420bb77f 100644--- a/packages/studio/src/components/AssetSelectorItem.tsx+++ b/packages/studio/src/components/AssetSelectorItem.tsx@@ -1,3 +1,4 @@+import {ASSET_DRAG_MIME_TYPE, makeAssetDragData} from '@remotion/studio-shared';import React, {useCallback,useContext,@@ -27,6 +28,7 @@ import {ClipboardIcon} from '../icons/clipboard';import {FileIcon} from '../icons/file';import {CollapsedFolderIcon, ExpandedFolderIcon} from '../icons/folder';import {SidebarContext} from '../state/sidebar';+import {getAssetElementFromPath} from './import-assets';import type {RenderInlineAction} from './InlineAction';import {InlineAction} from './InlineAction';import {Row, Spacing} from './layout';@@ -279,6 +281,10 @@ const AssetSelectorItem: React.FC<{return false;}, [canvasContent, relativePath]);+ const canDragAsset = useMemo(() => {+ return !readOnlyStudio && getAssetElementFromPath(relativePath) !== null;+ }, [readOnlyStudio, relativePath]);+const onPointerLeave = useCallback(() => {setHovered(false);}, []);@@ -306,6 +312,22 @@ const AssetSelectorItem: React.FC<{setSidebarCollapsedState,]);+ const onDragStart: React.DragEventHandler<HTMLDivElement> = useCallback(+ (e) => {+ if (!canDragAsset) {+ e.preventDefault();+ return;+ }++ e.dataTransfer.effectAllowed = 'copy';+ e.dataTransfer.setData(+ ASSET_DRAG_MIME_TYPE,+ JSON.stringify(makeAssetDragData(relativePath)),+ );+ },+ [canDragAsset, relativePath],+ );+const style: React.CSSProperties = useMemo(() => {return {...itemStyle,@@ -317,9 +339,10 @@ const AssetSelectorItem: React.FC<{: selected? SELECTED_BACKGROUND: 'transparent',+ cursor: canDragAsset ? 'grab' : 'default',paddingLeft: 12 + level * 8,};- }, [hovered, level, selected]);+ }, [canDragAsset, hovered, level, selected]);const label = useMemo(() => {return {@@ -378,6 +401,8 @@ const AssetSelectorItem: React.FC<{onPointerEnter={onPointerEnter}onPointerLeave={onPointerLeave}onClick={onClick}+ draggable={canDragAsset}+ onDragStart={onDragStart}tabIndex={tabIndex}title={item.name}>diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 868aff9c7b..b56d168311 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -1,4 +1,8 @@import type {Size} from '@remotion/player';+import {+ ASSET_DRAG_MIME_TYPE,+ parseAssetDragData,+} from '@remotion/studio-shared';import React, {useCallback,useContext,@@ -31,7 +35,7 @@ import {EditorZoomGesturesContext} from '../state/editor-zoom-gestures';import EditorGuides from './EditorGuides';import {EditorRulers} from './EditorRuler';import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';-import {importAssets} from './import-assets';+import {importAssets, insertExistingAssets} from './import-assets';import {SPACING_UNIT} from './layout';import {VideoPreview} from './Preview';import {ResetZoomButton} from './ResetZoomButton';@@ -66,6 +70,21 @@ const isFileDragEvent = (event: DragEvent): boolean => {return Array.from(event.dataTransfer?.types ?? []).includes('Files');};+const isAssetDragEvent = (event: DragEvent): boolean => {+ return Array.from(event.dataTransfer?.types ?? []).includes(+ ASSET_DRAG_MIME_TYPE,+ );+};++const getAssetDragPath = (event: DragEvent): string | null => {+ const value = event.dataTransfer?.getData(ASSET_DRAG_MIME_TYPE);+ if (!value) {+ return null;+ }++ return parseAssetDragData(value)?.assetPath ?? null;+};+const isDragEventInsideCanvas = (event: DragEvent): boolean => {const {current} = canvasRef;if (!current) {@@ -598,7 +617,7 @@ export const Canvas: React.FC<{(event: DragEvent) => {if (!canDropAssets ||- !isFileDragEvent(event) ||+ (!isFileDragEvent(event) && !isAssetDragEvent(event)) ||!isDragEventInsideCanvas(event)) {return;@@ -618,7 +637,7 @@ export const Canvas: React.FC<{!canDropAssets ||compositionFile === null ||currentCompositionId === null ||- !isFileDragEvent(event) ||+ (!isFileDragEvent(event) && !isAssetDragEvent(event)) ||!isDragEventInsideCanvas(event)) {return;@@ -627,18 +646,31 @@ export const Canvas: React.FC<{event.preventDefault();event.stopPropagation();- const files = Array.from(event.dataTransfer?.files ?? []);- if (files.length === 0) {- return;- }-setIsAddingAsset(true);try {- await importAssets({- files,- compositionFile,- compositionId: currentCompositionId,- });+ if (isFileDragEvent(event)) {+ const files = Array.from(event.dataTransfer?.files ?? []);+ if (files.length === 0) {+ return;+ }++ await importAssets({+ files,+ compositionFile,+ compositionId: currentCompositionId,+ });+ } else {+ const assetPath = getAssetDragPath(event);+ if (assetPath === null) {+ return;+ }++ await insertExistingAssets({+ assetPaths: [assetPath],+ compositionFile,+ compositionId: currentCompositionId,+ });+ }} finally {setIsAddingAsset(false);}diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex 49f9896a24..5e1e377d86 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -66,6 +66,57 @@ export const getAssetElement = ({return null;};+export const getAssetElementFromPath = (+ assetPath: string,+): InsertableCompositionElement | null => {+ if (!assetPath || assetPath.includes('\\')) {+ return null;+ }++ const extension = assetPath.split('.').pop()?.toLowerCase();+ if (!extension || extension === assetPath.toLowerCase()) {+ return null;+ }++ if (['png', 'jpg', 'jpeg', 'webp', 'bmp'].includes(extension)) {+ return {+ type: 'asset',+ assetType: 'image',+ src: assetPath,+ dimensions: null,+ };+ }++ if (extension === 'gif') {+ return {+ type: 'asset',+ assetType: 'gif',+ src: assetPath,+ dimensions: null,+ };+ }++ if (['mp4', 'm4v', 'mov', 'avi', 'webm', 'ts', 'm2ts'].includes(extension)) {+ return {+ type: 'asset',+ assetType: 'video',+ src: assetPath,+ dimensions: null,+ };+ }++ if (['wav', 'mp3', 'aac', 'flac'].includes(extension)) {+ return {+ type: 'asset',+ assetType: 'audio',+ src: assetPath,+ dimensions: null,+ };+ }++ return null;+};+const getAssetLabel = (element: InsertableCompositionElement) => {if (element.type !== 'asset') {throw new Error('Expected asset element');@@ -120,6 +171,54 @@ export const pickFilesToImport = (): Promise<File[]> => {});};+const notifyInsertedAssets = (insertedLabels: string[]) => {+ 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,+ );+ }+};++const notifyUnsupportedFiles = (unsupportedFiles: string[]) => {+ 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,+ );+ }+};++const insertAssetElement = async ({+ compositionFile,+ compositionId,+ element,+}: {+ compositionFile: string;+ compositionId: string;+ element: InsertableCompositionElement;+}) => {+ const result = await callApi('/api/insert-jsx-element', {+ compositionFile,+ compositionId,+ element,+ });++ if (!result.success) {+ showNotification(result.reason, 4000);+ return false;+ }++ return true;+};+export const importAssets = async ({compositionFile,compositionId,@@ -191,15 +290,14 @@ export const importAssets = async ({addedStaticFiles.push(file.name);}- const result = await callApi('/api/insert-jsx-element', {+ const inserted = await insertAssetElement({compositionFile,compositionId,element,});- if (!result.success) {+ if (!inserted) {notifyAddedStaticFiles();- showNotification(result.reason, 4000);return;}@@ -207,27 +305,57 @@ export const importAssets = async ({}notifyAddedStaticFiles();+ notifyInsertedAssets(insertedLabels);+ notifyUnsupportedFiles(unsupportedFiles);+ } catch (error) {+ showNotification(+ `Could not add asset: ${+ error instanceof Error ? error.message : String(error)+ }`,+ 4000,+ );+ }+};- 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,- );- }+export const insertExistingAssets = async ({+ assetPaths,+ compositionFile,+ compositionId,+}: {+ assetPaths: string[];+ compositionFile: string;+ compositionId: string;+}) => {+ if (assetPaths.length === 0) {+ return;+ }- 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,- );+ const insertedLabels: string[] = [];+ const unsupportedFiles: string[] = [];++ try {+ for (const assetPath of assetPaths) {+ const element = getAssetElementFromPath(assetPath);+ if (element === null) {+ unsupportedFiles.push(assetPath);+ continue;+ }++ const inserted = await insertAssetElement({+ compositionFile,+ compositionId,+ element,+ });++ if (!inserted) {+ return;+ }++ insertedLabels.push(getAssetLabel(element));}++ notifyInsertedAssets(insertedLabels);+ notifyUnsupportedFiles(unsupportedFiles);} catch (error) {showNotification(`Could not add asset: ${diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.tsindex 4951cac57a..923553e2db 100644--- a/packages/studio/src/test/import-assets.test.ts+++ b/packages/studio/src/test/import-assets.test.ts@@ -1,5 +1,8 @@import {expect, test} from 'bun:test';-import {getAssetElement} from '../components/import-assets';+import {+ getAssetElement,+ getAssetElementFromPath,+} from '../components/import-assets';test('maps audio file types to Audio assets', () => {for (const type of ['wav', 'mp3', 'aac', 'flac'] as const) {@@ -25,3 +28,36 @@ test('does not map M3U playlists to Audio assets', () => {}),).toBe(null);});++test('maps existing static file paths to insertable assets', () => {+ expect(getAssetElementFromPath('nested/photo.JPG')).toEqual({+ type: 'asset',+ assetType: 'image',+ src: 'nested/photo.JPG',+ dimensions: null,+ });+ expect(getAssetElementFromPath('movie.webm')).toEqual({+ type: 'asset',+ assetType: 'video',+ src: 'movie.webm',+ dimensions: null,+ });+ expect(getAssetElementFromPath('audio.flac')).toEqual({+ type: 'asset',+ assetType: 'audio',+ src: 'audio.flac',+ dimensions: null,+ });+ expect(getAssetElementFromPath('animation.gif')).toEqual({+ type: 'asset',+ assetType: 'gif',+ src: 'animation.gif',+ dimensions: null,+ });+});++test('does not map unsupported existing static file paths', () => {+ expect(getAssetElementFromPath('data.json')).toBe(null);+ expect(getAssetElementFromPath('asset-without-extension')).toBe(null);+ expect(getAssetElementFromPath('nested\\photo.png')).toBe(null);+});