🎥 Make videos programmatically with React
`@remotion/studio`: Add canvas asset drop insertion (#8026)
Jonny Burger45f5399687f4
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsindex 12f86139f4..ae1f2ec64e 100644--- a/packages/studio-server/src/helpers/resolve-composition-component.ts+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -8,6 +8,7 @@ import type {File,FunctionDeclaration,ImportDeclaration,+ ImportSpecifier,JSXAttribute,JSXElement,VariableDeclaration,@@ -17,7 +18,11 @@ import type {namedTypes} from 'ast-types';import * as recast from 'recast';import {formatFileContent} from '../codemods/format-file-content';import {parseAst, serializeAst} from '../codemods/parse-ast';-import {ensureNamedImport} from './imports';+import {+ ensureNamedImport,+ getImportedName,+ insertImportDeclaration,+} from './imports';type SourceLocation = {line: number;@@ -728,6 +733,38 @@ const createNumberAttribute = ();};+const createPositionAbsoluteStyleAttribute = (): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier('style'),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.objectExpression([+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('position'),+ recast.types.builders.stringLiteral('absolute'),+ ),+ ]),+ ),+ );+};++const createStaticFileSrcAttribute = ({+ staticFileLocalName,+ src,+}: {+ staticFileLocalName: string;+ src: string;+}): namedTypes.JSXAttribute => {+ return recast.types.builders.jsxAttribute(+ recast.types.builders.jsxIdentifier('src'),+ recast.types.builders.jsxExpressionContainer(+ recast.types.builders.callExpression(+ recast.types.builders.identifier(staticFileLocalName),+ [recast.types.builders.stringLiteral(src)],+ ),+ ),+ );+};+const createSolidElement = ({localName,width,@@ -743,17 +780,38 @@ const createSolidElement = ({[createNumberAttribute('width', width),createNumberAttribute('height', height),- recast.types.builders.jsxAttribute(- recast.types.builders.jsxIdentifier('style'),- recast.types.builders.jsxExpressionContainer(- recast.types.builders.objectExpression([- recast.types.builders.objectProperty(- recast.types.builders.identifier('position'),- recast.types.builders.stringLiteral('absolute'),- ),- ]),- ),- ),+ createPositionAbsoluteStyleAttribute(),+ ],+ true,+ ),+ null,+ [],+ );+};++const createAssetElement = ({+ localName,+ staticFileLocalName,+ src,+ dimensions,+}: {+ localName: string;+ staticFileLocalName: string;+ src: string;+ dimensions: {width: number; height: number} | null;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(localName),+ [+ createStaticFileSrcAttribute({staticFileLocalName, src}),+ createPositionAbsoluteStyleAttribute(),+ ...(dimensions+ ? [+ createNumberAttribute('width', dimensions.width),+ createNumberAttribute('height', dimensions.height),+ ]+ : []),],true,),@@ -915,6 +973,141 @@ const ensureSolidImport = (ast: File) => {});};+const getImportDeclarations = ({+ ast,+ sourcePath,+}: {+ ast: File;+ sourcePath: string;+}) => {+ return ast.program.body.filter(+ (node): node is ImportDeclaration =>+ node.type === 'ImportDeclaration' &&+ node.source.type === 'StringLiteral' &&+ node.source.value === sourcePath,+ );+};++const importDeclarationHasNamespaceSpecifier = (+ importDeclaration: ImportDeclaration,+) => {+ return importDeclaration.specifiers?.some(+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',+ );+};++const hasOfficialLocalImport = ({+ ast,+ importedName,+ sourcePath,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+}) => {+ return getImportDeclarations({ast, sourcePath}).some((importDeclaration) => {+ return importDeclaration.specifiers?.some((specifier) => {+ return (+ specifier.type === 'ImportSpecifier' &&+ getImportedName(specifier) === importedName &&+ (specifier.local?.name ?? importedName) === importedName+ );+ });+ });+};++const addOfficialNamedImport = ({+ ast,+ importedName,+ sourcePath,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+}) => {+ const existingImport = getImportDeclarations({ast, sourcePath}).find(+ (candidate) => !importDeclarationHasNamespaceSpecifier(candidate),+ );+ const importSpecifier = recast.types.builders.importSpecifier(+ recast.types.builders.identifier(importedName),+ ) as unknown as ImportSpecifier;++ if (existingImport) {+ existingImport.specifiers = [+ ...(existingImport.specifiers ?? []),+ importSpecifier,+ ];+ return;+ }++ const importDeclaration = recast.types.builders.importDeclaration(+ [importSpecifier as never],+ recast.types.builders.stringLiteral(sourcePath),+ ) as unknown as ImportDeclaration;+ insertImportDeclaration(ast, importDeclaration);+};++const ensureOfficialNamedImport = ({+ ast,+ importedName,+ sourcePath,+ label,+}: {+ ast: File;+ importedName: string;+ sourcePath: string;+ label: string;+}) => {+ if (hasOfficialLocalImport({ast, importedName, sourcePath})) {+ return importedName;+ }++ if (hasTopLevelBinding({ast, name: importedName})) {+ throw new Error(+ `Cannot add ${label} because ${importedName} is already defined`,+ );+ }++ addOfficialNamedImport({ast, importedName, sourcePath});+ return importedName;+};++const ensureStaticFileImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'staticFile',+ sourcePath: 'remotion',+ label: 'staticFile()',+ });+};++const ensureImgImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Img',+ sourcePath: 'remotion',+ label: '<Img>',+ });+};++const ensureVideoImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Video',+ sourcePath: '@remotion/media',+ label: '<Video>',+ });+};++const ensureGifImport = (ast: File) => {+ return ensureOfficialNamedImport({+ ast,+ importedName: 'Gif',+ sourcePath: '@remotion/gif',+ label: '<Gif>',+ });+};+const addElementToComponentRoot = ({ast,exportName,@@ -956,7 +1149,7 @@ const addElementToComponentRoot = ({CANVAS_ROOT_ELEMENTS.includes(rootNode.openingElement.name.name)) {throw new Error(- `Cannot insert a <Solid> into a composition whose root element is <${rootNode.openingElement.name.name}>`,+ `Cannot insert a JSX element into a composition whose root element is <${rootNode.openingElement.name.name}>`,);}@@ -1239,6 +1432,23 @@ const createInsertableJsxElement = ({});}+ if (element.type === 'asset') {+ const staticFileLocalName = ensureStaticFileImport(ast);+ const localName =+ element.assetType === 'image'+ ? ensureImgImport(ast)+ : element.assetType === 'video'+ ? ensureVideoImport(ast)+ : ensureGifImport(ast);++ return createAssetElement({+ localName,+ staticFileLocalName,+ src: element.src,+ dimensions: element.dimensions,+ });+ }+throw new Error('Unsupported element type');};diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.tsindex fc5ffbcbf5..1e403f1dca 100644--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts@@ -26,7 +26,23 @@ const validateElement = (element: InsertableCompositionElement) => {if (element.type === 'solid') {validateDimension('width', element.width);validateDimension('height', element.height);+ return;}++ if (element.type === 'asset') {+ if (!element.src || element.src.includes('\\')) {+ throw new Error('Asset path must be a static file path');+ }++ if (element.dimensions) {+ validateDimension('width', element.dimensions.width);+ validateDimension('height', element.dimensions.height);+ }++ return;+ }++ throw new Error('Unsupported element type');};const getElementLabel = (element: InsertableCompositionElement) => {@@ -34,6 +50,20 @@ const getElementLabel = (element: InsertableCompositionElement) => {return '<Solid>';}+ if (element.type === 'asset') {+ if (element.assetType === 'image') {+ return '<Img>';+ }++ if (element.assetType === 'video') {+ return '<Video>';+ }++ if (element.assetType === 'gif') {+ return '<Gif>';+ }+ }+throw new Error('Unsupported element type');};diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsindex 06d7cb0137..43fb3c9f2a 100644--- a/packages/studio-server/src/test/resolve-composition-component.test.ts+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -657,3 +657,160 @@ test('inserts a Solid into an empty component returning null', async () => {await fs.rm(tempDir, {recursive: true, force: true});}});++test('inserts an Img asset into the resolved composition component', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ "import {AbsoluteFill} from 'remotion';",+ '',+ 'export const MyComp: React.FC = () => {',+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',+ '};',+ '',+ ].join('\n'),+ );++ const result = await insertJsxElementIntoComposition({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ element: {+ type: 'asset',+ assetType: 'image',+ src: 'image.png',+ dimensions: {+ width: 800,+ height: 600,+ },+ },+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ });++ expect(result.output).toContain(+ "import { AbsoluteFill, staticFile, Img } from 'remotion';",+ );+ expect(result.output).toContain('<Img');+ expect(result.output).toContain("src={staticFile('image.png')}");+ expect(result.output).toContain('width={800}');+ expect(result.output).toContain('height={600}');+ expect(result.output).toContain("position: 'absolute'");+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('rejects inserting a Video asset if Video is already defined', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ "import {AbsoluteFill} from 'remotion';",+ '',+ 'export const Video = () => null;',+ '',+ 'export const MyComp: React.FC = () => {',+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',+ '};',+ '',+ ].join('\n'),+ );++ await expect(+ insertJsxElementIntoComposition({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ element: {+ type: 'asset',+ assetType: 'video',+ src: 'clip.mp4',+ dimensions: null,+ },+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ }),+ ).rejects.toThrow('Cannot add <Video> because Video is already defined');+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('inserts a Gif asset into the resolved composition component', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ "import {AbsoluteFill} from 'remotion';",+ '',+ 'export const MyComp: React.FC = () => {',+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',+ '};',+ '',+ ].join('\n'),+ );++ const result = await insertJsxElementIntoComposition({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ element: {+ type: 'asset',+ assetType: 'gif',+ src: 'animation.gif',+ dimensions: {+ width: 320,+ height: 180,+ },+ },+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ });++ expect(result.output).toContain("import { Gif } from '@remotion/gif';");+ expect(result.output).toContain(+ "import { AbsoluteFill, staticFile } from 'remotion';",+ );+ expect(result.output).toContain('<Gif');+ expect(result.output).toContain("src={staticFile('animation.gif')}");+ expect(result.output).toContain('width={320}');+ expect(result.output).toContain('height={180}');+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 562c767e86..b4e0a4a043 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -491,11 +491,21 @@ export type DuplicateJsxNodeResponse =stack: string;};-export type InsertableCompositionElement = {- type: 'solid';- width: number;- height: number;-};+export type InsertableCompositionElement =+ | {+ type: 'solid';+ width: number;+ height: number;+ }+ | {+ type: 'asset';+ assetType: 'image' | 'video' | 'gif';+ src: string;+ dimensions: {+ width: number;+ height: number;+ } | null;+ };export type InsertJsxElementRequest = {compositionFile: string;diff --git a/packages/studio/src/components/AssetSelector.tsx b/packages/studio/src/components/AssetSelector.tsxindex 972395b584..654fc4b3cd 100644--- a/packages/studio/src/components/AssetSelector.tsx+++ b/packages/studio/src/components/AssetSelector.tsx@@ -110,6 +110,24 @@ export const AssetSelector: React.FC<{return [assetPath, file.name].filter(Boolean).join('/');};+ const differentExistingFile = Array.from(files).find((file) => {+ const filePath = makePath(file);+ return staticFiles.some(+ (staticFile) =>+ staticFile.name === filePath &&+ staticFile.sizeInBytes !== file.size,+ );+ });+ if (differentExistingFile) {+ showNotification(+ `File with name ${makePath(+ differentExistingFile,+ )} already exists and is different`,+ 4000,+ );+ return;+ }+for (const file of files) {const body = await file.arrayBuffer();await writeStaticFile({@@ -129,7 +147,7 @@ export const AssetSelector: React.FC<{setDropLocation(null);}},- [dropLocation],+ [dropLocation, staticFiles],);return (diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 8e2fefecb9..244624218d 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -1,4 +1,5 @@import type {Size} from '@remotion/player';+import type {InsertableCompositionElement} from '@remotion/studio-shared';import React, {useCallback,useContext,@@ -9,13 +10,19 @@ 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 {applyZoomAroundFocalPoint,getEffectiveTranslation,} from '../helpers/get-effective-translation';+import {useCachedCompositionComponentInfo} from '../helpers/open-in-editor';import {MAX_ZOOM,MIN_ZOOM,@@ -26,12 +33,15 @@ 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 {SPACING_UNIT} from './layout';+import {showNotification} from './Notifications/NotificationCenter';import {VideoPreview} from './Preview';import {ResetZoomButton} from './ResetZoomButton';+import {useResolvedStack} from './Timeline/use-resolved-stack';const getContainerStyle = (editorZoomGestures: boolean,@@ -52,12 +62,99 @@ 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;clientY: number;};+const isFileDragEvent = (event: DragEvent): boolean => {+ return Array.from(event.dataTransfer?.types ?? []).includes('Files');+};++const isDragEventInsideCanvas = (event: DragEvent): boolean => {+ const {current} = canvasRef;+ if (!current) {+ return false;+ }++ const targetIsNode = event.target instanceof Node;+ if (targetIsNode && current.contains(event.target as Node)) {+ return true;+ }++ const rect = current.getBoundingClientRect();+ return (+ event.clientX >= rect.left &&+ event.clientX <= rect.right &&+ event.clientY >= rect.top &&+ event.clientY <= rect.bottom+ );+};+export const Canvas: React.FC<{readonly canvasContent: CanvasContent;readonly size: Size;@@ -79,11 +176,43 @@ export const Canvas: React.FC<{const config = Internals.useUnsafeVideoConfig();const areRulersVisible = useIsRulerVisible();const {editorShowGuides} = useContext(EditorShowGuidesContext);+ const {compositions} = useContext(Internals.CompositionManager);+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const [isAddingAsset, setIsAddingAsset] = useState(false);const [assetResolution, setAssetResolution] = useState<AssetMetadata | null>(null,);+ const currentCompositionId =+ canvasContent.type === 'composition' ? canvasContent.compositionId : null;+ const currentComposition = useMemo(() => {+ if (currentCompositionId === null) {+ return null;+ }++ return (+ compositions.find(+ (composition) => composition.id === currentCompositionId,+ ) ?? null+ );+ }, [compositions, currentCompositionId]);+ const resolvedCompositionLocation = useResolvedStack(+ currentComposition?.stack ?? null,+ );+ const compositionFile = resolvedCompositionLocation?.source ?? null;+ const compositionComponentInfo = useCachedCompositionComponentInfo({+ compositionFile,+ compositionId: currentCompositionId,+ });+ const canDropAssets =+ previewServerState.type === 'connected' &&+ !window.remotion_isReadOnlyStudio &&+ compositionComponentInfo?.canAddSequence === true &&+ currentCompositionId !== null &&+ compositionFile !== null &&+ !isAddingAsset;+const contentDimensions = useMemo(() => {if ((canvasContent.type === 'asset' ||@@ -534,6 +663,173 @@ export const Canvas: React.FC<{fetchMetadata();}, [fetchMetadata]);+ const onDragOver = useCallback(+ (event: DragEvent) => {+ if (+ !canDropAssets ||+ !isFileDragEvent(event) ||+ !isDragEventInsideCanvas(event)+ ) {+ return;+ }++ event.preventDefault();+ if (event.dataTransfer) {+ event.dataTransfer.dropEffect = 'copy';+ }+ },+ [canDropAssets],+ );++ const onDrop = useCallback(+ async (event: DragEvent) => {+ if (+ !canDropAssets ||+ compositionFile === null ||+ currentCompositionId === null ||+ !isFileDragEvent(event) ||+ !isDragEventInsideCanvas(event)+ ) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();++ const files = Array.from(event.dataTransfer?.files ?? []);+ 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;+ }++ 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,+ );+ } finally {+ setIsAddingAsset(false);+ }+ },+ [canDropAssets, compositionFile, currentCompositionId],+ );++ useEffect(() => {+ if (!canDropAssets) {+ return;+ }++ document.addEventListener('dragover', onDragOver, {capture: true});+ document.addEventListener('drop', onDrop, {capture: true});++ return () => {+ document.removeEventListener('dragover', onDragOver, {capture: true});+ document.removeEventListener('drop', onDrop, {capture: true});+ };+ }, [canDropAssets, onDragOver, onDrop]);+return (<><div ref={canvasRef} style={getContainerStyle(editorZoomGestures)}>diff --git a/packages/studio/src/helpers/detect-file-type.ts b/packages/studio/src/helpers/detect-file-type.tsnew file mode 100644index 0000000000..7f624ab3c0--- /dev/null+++ b/packages/studio/src/helpers/detect-file-type.ts@@ -0,0 +1,437 @@+export type FileDimensions = {+ readonly width: number;+ readonly height: number;+};++const webmPattern = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]);++export const matchesPattern = (pattern: Uint8Array) => {+ return (data: Uint8Array) => {+ return pattern.every((value, index) => data[index] === value);+ };+};++export const isRiffAvi = (data: Uint8Array) => {+ const riffPattern = new Uint8Array([0x52, 0x49, 0x46, 0x46]);+ if (!matchesPattern(riffPattern)(data.subarray(0, 4))) {+ return false;+ }++ const fileType = data.subarray(8, 12);+ const aviPattern = new Uint8Array([0x41, 0x56, 0x49, 0x20]);+ return matchesPattern(aviPattern)(fileType);+};++export const isRiffWave = (data: Uint8Array) => {+ const riffPattern = new Uint8Array([0x52, 0x49, 0x46, 0x46]);+ if (!matchesPattern(riffPattern)(data.subarray(0, 4))) {+ return false;+ }++ const fileType = data.subarray(8, 12);+ const wavePattern = new Uint8Array([0x57, 0x41, 0x56, 0x45]);+ return matchesPattern(wavePattern)(fileType);+};++export const isWebm = (data: Uint8Array) => {+ return matchesPattern(webmPattern)(data.subarray(0, 4));+};++export const isIsoBaseMedia = (data: Uint8Array) => {+ const isoBaseMediaMp4Pattern = new TextEncoder().encode('ftyp');++ return matchesPattern(isoBaseMediaMp4Pattern)(data.subarray(4, 8));+};++export const isTransportStream = (data: Uint8Array) => {+ return data[0] === 0x47 && data[188] === 0x47;+};++export const isMp3 = (data: Uint8Array) => {+ const mpegPattern = new Uint8Array([0xff, 0xf3]);+ const mpegPattern2 = new Uint8Array([0xff, 0xfb]);+ const id3v4Pattern = new Uint8Array([0x49, 0x44, 0x33, 4]);+ const id3v3Pattern = new Uint8Array([0x49, 0x44, 0x33, 3]);+ const id3v2Pattern = new Uint8Array([0x49, 0x44, 0x33, 2]);++ const subarray = data.subarray(0, 4);+ return (+ matchesPattern(mpegPattern)(subarray) ||+ matchesPattern(mpegPattern2)(subarray) ||+ matchesPattern(id3v4Pattern)(subarray) ||+ matchesPattern(id3v3Pattern)(subarray) ||+ matchesPattern(id3v2Pattern)(subarray)+ );+};++export const isAac = (data: Uint8Array) => {+ const aacPattern = new Uint8Array([0xff, 0xf1]);++ return matchesPattern(aacPattern)(data.subarray(0, 2));+};++export const isFlac = (data: Uint8Array) => {+ const flacPattern = new Uint8Array([0x66, 0x4c, 0x61, 0x43]);++ return matchesPattern(flacPattern)(data.subarray(0, 4));+};++export const isM3u = (data: Uint8Array) => {+ return new TextDecoder('utf-8').decode(data.slice(0, 7)) === '#EXTM3U';+};++const getPngDimensions = (pngData: Uint8Array): FileDimensions | null => {+ if (pngData.length < 24) {+ return null;+ }++ const view = new DataView(pngData.buffer, pngData.byteOffset);+ const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];+ for (let i = 0; i < 8; i++) {+ if (pngData[i] !== pngSignature[i]) {+ return null;+ }+ }++ return {+ width: view.getUint32(16, false),+ height: view.getUint32(20, false),+ };+};++const isPng = (data: Uint8Array): PngType | null => {+ const pngPattern = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);++ if (matchesPattern(pngPattern)(data.subarray(0, 4))) {+ const png = getPngDimensions(data);+ return {dimensions: png, type: 'png'};+ }++ return null;+};++const getJpegDimensions = (data: Uint8Array): FileDimensions | null => {+ let offset = 0;++ const readUint16BE = (o: number): number => {+ return (data[o] << 8) | data[o + 1];+ };++ if (readUint16BE(offset) !== 0xffd8) {+ return null;+ }++ offset += 2;++ while (offset < data.length) {+ if (data[offset] === 0xff) {+ const marker = data[offset + 1];+ if (marker === 0xc0 || marker === 0xc2) {+ const height = readUint16BE(offset + 5);+ const width = readUint16BE(offset + 7);+ return {width, height};+ }++ const length = readUint16BE(offset + 2);+ offset += length + 2;+ } else {+ offset++;+ }+ }++ return null;+};++const isJpeg = (data: Uint8Array): JpegType | null => {+ const jpegPattern = new Uint8Array([0xff, 0xd8]);++ const jpeg = matchesPattern(jpegPattern)(data.subarray(0, 2));+ if (!jpeg) {+ return null;+ }++ const dim = getJpegDimensions(data);+ return {dimensions: dim, type: 'jpeg'};+};++const getGifDimensions = (data: Uint8Array) => {+ const view = new DataView(data.buffer, data.byteOffset);++ const width = view.getUint16(6, true);+ const height = view.getUint16(8, true);++ return {width, height};+};++const isGif = (data: Uint8Array): GifType | null => {+ const gifPattern = new Uint8Array([0x47, 0x49, 0x46, 0x38]);++ if (matchesPattern(gifPattern)(data.subarray(0, 4))) {+ return {type: 'gif', dimensions: getGifDimensions(data)};+ }++ return null;+};++const getWebPDimensions = (bytes: Uint8Array): FileDimensions | null => {+ if (bytes.length < 30) {+ return null;+ }++ if (+ bytes[0] !== 0x52 ||+ bytes[1] !== 0x49 ||+ bytes[2] !== 0x46 ||+ bytes[3] !== 0x46 ||+ bytes[8] !== 0x57 ||+ bytes[9] !== 0x45 ||+ bytes[10] !== 0x42 ||+ bytes[11] !== 0x50+ ) {+ return null;+ }++ if (bytes[12] === 0x56 && bytes[13] === 0x50 && bytes[14] === 0x38) {+ if (bytes[15] === 0x20) {+ return {+ width: bytes[26] | ((bytes[27] << 8) & 0x3fff),+ height: bytes[28] | ((bytes[29] << 8) & 0x3fff),+ };+ }+ }++ if (+ bytes[12] === 0x56 &&+ bytes[13] === 0x50 &&+ bytes[14] === 0x38 &&+ bytes[15] === 0x4c+ ) {+ return {+ width: 1 + (bytes[21] | ((bytes[22] & 0x3f) << 8)),+ height:+ 1 ++ (((bytes[22] & 0xc0) >> 6) |+ (bytes[23] << 2) |+ ((bytes[24] & 0x0f) << 10)),+ };+ }++ if (+ bytes[12] === 0x56 &&+ bytes[13] === 0x50 &&+ bytes[14] === 0x38 &&+ bytes[15] === 0x58+ ) {+ return {+ width: 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)),+ height: 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)),+ };+ }++ return null;+};++const isWebp = (data: Uint8Array): WebpType | null => {+ const webpPattern = new Uint8Array([0x52, 0x49, 0x46, 0x46]);++ if (matchesPattern(webpPattern)(data.subarray(0, 4))) {+ return {+ type: 'webp',+ dimensions: getWebPDimensions(data),+ };+ }++ return null;+};++const getBmpDimensions = (bmpData: Uint8Array): FileDimensions | null => {+ if (bmpData.length < 26) {+ return null;+ }++ const view = new DataView(bmpData.buffer, bmpData.byteOffset);++ return {+ width: view.getUint32(18, true),+ height: Math.abs(view.getInt32(22, true)),+ };+};++const isBmp = (data: Uint8Array): BmpType | null => {+ const bmpPattern = new Uint8Array([0x42, 0x4d]);++ if (matchesPattern(bmpPattern)(data.subarray(0, 2))) {+ const bmp = getBmpDimensions(data);+ return {dimensions: bmp, type: 'bmp'};+ }++ return null;+};++const isPdf = (data: Uint8Array): PdfType | null => {+ if (data.length < 4) {+ return null;+ }++ const pdfPattern = new Uint8Array([0x25, 0x50, 0x44, 0x46]);++ return matchesPattern(pdfPattern)(data.subarray(0, 4)) ? {type: 'pdf'} : null;+};++export type RiffType = {+ type: 'riff';+};++export type WebmType = {+ type: 'webm';+};++export type IsoBaseMediaType = {+ type: 'iso-base-media';+};++export type TransportStreamType = {+ type: 'transport-stream';+};++export type Mp3Type = {+ type: 'mp3';+};++export type AacType = {+ type: 'aac';+};++export type WavType = {+ type: 'wav';+};++export type GifType = {+ type: 'gif';+ dimensions: FileDimensions;+};++export type FlacType = {+ type: 'flac';+};++export type M3uType = {+ type: 'm3u';+};++export type PngType = {+ type: 'png';+ dimensions: FileDimensions | null;+};++export type JpegType = {+ type: 'jpeg';+ dimensions: FileDimensions | null;+};++export type WebpType = {+ type: 'webp';+ dimensions: FileDimensions | null;+};++export type BmpType = {+ type: 'bmp';+ dimensions: FileDimensions | null;+};++export type PdfType = {+ type: 'pdf';+};++export type UnknownType = {+ type: 'unknown';+};++export type FileType =+ | JpegType+ | WebpType+ | RiffType+ | WebmType+ | WavType+ | PdfType+ | AacType+ | IsoBaseMediaType+ | TransportStreamType+ | Mp3Type+ | GifType+ | PngType+ | BmpType+ | AacType+ | FlacType+ | M3uType+ | UnknownType;++export const detectFileType = (data: Uint8Array): FileType => {+ if (isRiffWave(data)) {+ return {type: 'wav'};+ }++ if (isRiffAvi(data)) {+ return {type: 'riff'};+ }++ if (isAac(data)) {+ return {type: 'aac'};+ }++ if (isFlac(data)) {+ return {type: 'flac'};+ }++ if (isM3u(data)) {+ return {type: 'm3u'};+ }++ const webp = isWebp(data);+ if (webp) {+ return webp;+ }++ if (isWebm(data)) {+ return {type: 'webm'};+ }++ if (isIsoBaseMedia(data)) {+ return {type: 'iso-base-media'};+ }++ if (isTransportStream(data)) {+ return {type: 'transport-stream'};+ }++ if (isMp3(data)) {+ return {type: 'mp3'};+ }++ const gif = isGif(data);+ if (gif) {+ return gif;+ }++ const png = isPng(data);+ if (png) {+ return png;+ }++ const pdf = isPdf(data);+ if (pdf) {+ return pdf;+ }++ const bmp = isBmp(data);+ if (bmp) {+ return bmp;+ }++ const jpeg = isJpeg(data);+ if (jpeg) {+ return jpeg;+ }++ return {type: 'unknown'};+};diff --git a/packages/studio/src/test/detect-file-type.test.ts b/packages/studio/src/test/detect-file-type.test.tsnew file mode 100644index 0000000000..22beb0a59e--- /dev/null+++ b/packages/studio/src/test/detect-file-type.test.ts@@ -0,0 +1,47 @@+import {expect, test} from 'bun:test';+import {detectFileType} from '../helpers/detect-file-type';++test('detects PNG dimensions', () => {+ const png = new Uint8Array(24);+ png.set([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10], 0);+ png.set([0, 0, 0, 13], 8);+ png.set([0x49, 0x48, 0x44, 0x52], 12);+ png.set([0, 0, 7, 128], 16);+ png.set([0, 0, 4, 56], 20);++ expect(detectFileType(png)).toEqual({+ type: 'png',+ dimensions: {+ width: 1920,+ height: 1080,+ },+ });+});++test('detects GIF dimensions', () => {+ const gif = new Uint8Array([+ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x20, 0x03, 0x58, 0x02,+ ]);++ expect(detectFileType(gif)).toEqual({+ type: 'gif',+ dimensions: {+ width: 800,+ height: 600,+ },+ });+});++test('detects iso base media and WebM files as videos', () => {+ const mp4 = new Uint8Array([0, 0, 0, 24, 0x66, 0x74, 0x79, 0x70]);+ const webm = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]);++ expect(detectFileType(mp4)).toEqual({type: 'iso-base-media'});+ expect(detectFileType(webm)).toEqual({type: 'webm'});+});++test('returns unknown for unsupported signatures', () => {+ expect(detectFileType(new Uint8Array([1, 2, 3, 4]))).toEqual({+ type: 'unknown',+ });+});