🎥 Make videos programmatically with React
Place dropped Studio assets at cursor
Jonny Burgerd8501775afe4
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsindex 0e5b7da7dd..0fbabb5438 100644--- a/packages/studio-server/src/helpers/resolve-composition-component.ts+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -16,6 +16,7 @@ import type {import {isUrl,type ComponentProp,+ type InsertableCompositionElementPosition,type InsertableCompositionElement,} from '@remotion/studio-shared';import type {namedTypes} from 'ast-types';@@ -759,16 +760,32 @@ const createBooleanAttribute = ();};-const createPositionAbsoluteStyleAttribute = (): namedTypes.JSXAttribute => {+const formatTranslateValue = ({x, y}: InsertableCompositionElementPosition) =>+ `${x}px ${y}px`;++const createPositionAbsoluteStyleAttribute = (+ position: InsertableCompositionElementPosition | null,+): namedTypes.JSXAttribute => {+ const properties = [+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('position'),+ recast.types.builders.stringLiteral('absolute'),+ ),+ ];++ if (position) {+ properties.push(+ recast.types.builders.objectProperty(+ recast.types.builders.identifier('translate'),+ recast.types.builders.stringLiteral(formatTranslateValue(position)),+ ),+ );+ }+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'),- ),- ]),+ recast.types.builders.objectExpression(properties),),);};@@ -817,10 +834,12 @@ const createSolidElement = ({localName,width,height,+ position,}: {localName: string;width: number;height: number;+ position: InsertableCompositionElementPosition | null;}): namedTypes.JSXElement => {return recast.types.builders.jsxElement(recast.types.builders.jsxOpeningElement(@@ -828,7 +847,7 @@ const createSolidElement = ({[createNumberAttribute('width', width),createNumberAttribute('height', height),- createPositionAbsoluteStyleAttribute(),+ createPositionAbsoluteStyleAttribute(position),],true,),@@ -840,16 +859,18 @@ const createSolidElement = ({const createComponentElement = ({localName,props,+ position,}: {localName: string;props: ComponentProp[];+ position: InsertableCompositionElementPosition | null;}): namedTypes.JSXElement => {return recast.types.builders.jsxElement(recast.types.builders.jsxOpeningElement(recast.types.builders.jsxIdentifier(localName),[...props.map(createComponentProp),- createPositionAbsoluteStyleAttribute(),+ createPositionAbsoluteStyleAttribute(position),],true,),@@ -864,12 +885,14 @@ const createAssetElement = ({staticFileLocalName,src,dimensions,+ position,}: {addPositionStyle: boolean;localName: string;staticFileLocalName: string | null;src: string;dimensions: {width: number; height: number} | null;+ position: InsertableCompositionElementPosition | null;}): namedTypes.JSXElement => {return recast.types.builders.jsxElement(recast.types.builders.jsxOpeningElement(@@ -878,7 +901,9 @@ const createAssetElement = ({staticFileLocalName === null? createStringSrcAttribute(src): createStaticFileSrcAttribute({staticFileLocalName, src}),- ...(addPositionStyle ? [createPositionAbsoluteStyleAttribute()] : []),+ ...(addPositionStyle+ ? [createPositionAbsoluteStyleAttribute(position)]+ : []),...(dimensions? [createNumberAttribute('width', dimensions.width),@@ -1572,6 +1597,7 @@ const createInsertableJsxElement = ({localName: solidLocalName,width: element.width,height: element.height,+ position: element.position,});}@@ -1586,6 +1612,7 @@ const createInsertableJsxElement = ({return createComponentElement({localName: componentLocalName,props: element.props,+ position: element.position,});}@@ -1615,6 +1642,7 @@ const createInsertableJsxElement = ({staticFileLocalName,src: element.src,dimensions: element.dimensions,+ position: element.position,});}diff --git a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts b/packages/studio-server/src/preview-server/routes/download-remote-asset.tsindex 31962f4898..2a8c7e58fb 100644--- a/packages/studio-server/src/preview-server/routes/download-remote-asset.ts+++ b/packages/studio-server/src/preview-server/routes/download-remote-asset.ts@@ -339,6 +339,7 @@ export const downloadRemoteAssetHandler: ApiHandler<src: assetPath,srcType: 'static',dimensions: fileType.dimensions,+ position: null,};return {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 a0e1399c1b..06e767c602 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@@ -6,6 +6,7 @@ import {isUrl,type InsertJsxElementRequest,type InsertJsxElementResponse,+ type InsertableCompositionElementPosition,type InsertableCompositionElement,} from '@remotion/studio-shared';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';@@ -26,7 +27,21 @@ const validateDimension = (name: string, value: number) => {}};+const validatePosition = (+ position: InsertableCompositionElementPosition | null,+) => {+ if (position === null) {+ return;+ }++ if (!Number.isFinite(position.x) || !Number.isFinite(position.y)) {+ throw new Error('Position must be finite');+ }+};+const validateElement = (element: InsertableCompositionElement) => {+ validatePosition(element.position);+if (element.type === 'solid') {validateDimension('width', element.width);validateDimension('height', element.height);diff --git a/packages/studio-server/src/test/download-remote-asset.test.ts b/packages/studio-server/src/test/download-remote-asset.test.tsindex 9766f15e6c..fe0dd59714 100644--- a/packages/studio-server/src/test/download-remote-asset.test.ts+++ b/packages/studio-server/src/test/download-remote-asset.test.ts@@ -92,6 +92,7 @@ test('follows validated redirects for remote assets', async () => {height: 600,width: 800,},+ position: null,src: 'raw-link.gif',srcType: 'static',type: 'asset',diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsindex e7b29b5b1d..4d399a9479 100644--- a/packages/studio-server/src/test/resolve-composition-component.test.ts+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -523,6 +523,7 @@ test('inserts a Solid into the resolved composition component', async () => {type: 'solid',width: 1280,height: 720,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -540,6 +541,55 @@ test('inserts a Solid into the resolved composition component', async () => {}});+test('inserts a Solid with a translate style', 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: 'solid',+ width: 1280,+ height: 720,+ position: {+ x: 120,+ y: 80.5,+ },+ },+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ });++ expect(result.output).toContain("position: 'absolute'");+ expect(result.output).toContain("translate: '120px 80.5px'");+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});+test('inserts an aliased Solid import if Solid is already defined', async () => {const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));try {@@ -576,6 +626,7 @@ test('inserts an aliased Solid import if Solid is already defined', async () =>type: 'solid',width: 1920,height: 1080,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -619,6 +670,7 @@ test('inserts a Solid into an empty component returning null', async () => {type: 'solid',width: 640,height: 360,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -649,6 +701,7 @@ test('inserts a Solid into an empty component returning null', async () => {type: 'solid',width: 320,height: 180,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -697,6 +750,7 @@ test('inserts an Img asset into the resolved composition component', async () =>width: 800,height: 600,},+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -714,6 +768,60 @@ test('inserts an Img asset into the resolved composition component', async () =>}});+test('inserts an Img asset with a translate style', 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',+ srcType: 'static',+ dimensions: {+ width: 800,+ height: 600,+ },+ position: {+ x: 100,+ y: 150,+ },+ },+ prettierConfigOverride: {singleQuote: true, useTabs: true},+ });++ expect(result.output).toContain("src={staticFile('image.png')}");+ expect(result.output).toContain("translate: '100px 150px'");+ } 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 {@@ -753,6 +861,7 @@ test('rejects inserting a Video asset if Video is already defined', async () =>src: 'clip.mp4',srcType: 'static',dimensions: null,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},}),@@ -801,6 +910,7 @@ test('inserts a Gif asset into the resolved composition component', async () =>width: 320,height: 180,},+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -854,6 +964,7 @@ test('inserts an Audio asset into the resolved composition component', async ()src: 'audio.mp3',srcType: 'static',dimensions: null,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -906,6 +1017,7 @@ test('inserts a remote audio asset with a literal URL', async () => {src: 'https://example.com/whip.wav',srcType: 'remote',dimensions: null,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});@@ -961,6 +1073,7 @@ test('rejects inserting an Audio asset if Audio is already defined', async () =>src: 'audio.mp3',srcType: 'static',dimensions: null,+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},}),@@ -1010,6 +1123,7 @@ test('inserts a component into the resolved composition component', async () =>{name: 'dataShapeIndex', value: 1},{name: 'debug', value: false},],+ position: null,},prettierConfigOverride: {singleQuote: true, useTabs: true},});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex d8bb0514ce..4a4262ead4 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -625,6 +625,7 @@ export type InsertableCompositionElement =type: 'solid';width: number;height: number;+ position: InsertableCompositionElementPosition | null;}| {type: 'component';@@ -632,6 +633,7 @@ export type InsertableCompositionElement =importName: string;importPath: string;props: ComponentProp[];+ position: InsertableCompositionElementPosition | null;}| {type: 'asset';@@ -642,8 +644,14 @@ export type InsertableCompositionElement =width: number;height: number;} | null;+ position: InsertableCompositionElementPosition | null;};+export type InsertableCompositionElementPosition = {+ x: number;+ y: number;+};+export type InsertJsxElementRequest = {compositionFile: string;compositionId: string;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 661aa03a8d..8b16762ba4 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -40,6 +40,7 @@ export {InsertJsxElementRequest,InsertJsxElementResponse,InsertableCompositionElement,+ InsertableCompositionElementPosition,InstallPackageRequest,InstallPackageResponse,LogStudioErrorRequest,diff --git a/packages/studio-shared/src/test/required-package.test.ts b/packages/studio-shared/src/test/required-package.test.tsindex c3be2652e4..e9dae73447 100644--- a/packages/studio-shared/src/test/required-package.test.ts+++ b/packages/studio-shared/src/test/required-package.test.ts@@ -10,6 +10,7 @@ test('gets required package for insertable elements', () => {type: 'solid',width: 1920,height: 1080,+ position: null,}),).toBe(null);expect(@@ -19,6 +20,7 @@ test('gets required package for insertable elements', () => {src: 'image.png',srcType: 'static',dimensions: null,+ position: null,}),).toBe(null);expect(@@ -28,6 +30,7 @@ test('gets required package for insertable elements', () => {src: 'video.mp4',srcType: 'static',dimensions: null,+ position: null,}),).toBe('@remotion/media');expect(@@ -37,6 +40,7 @@ test('gets required package for insertable elements', () => {src: 'audio.mp3',srcType: 'static',dimensions: null,+ position: null,}),).toBe('@remotion/media');expect(@@ -46,6 +50,7 @@ test('gets required package for insertable elements', () => {src: 'animation.gif',srcType: 'static',dimensions: null,+ position: null,}),).toBe('@remotion/gif');expect(@@ -55,6 +60,7 @@ test('gets required package for insertable elements', () => {importName: 'Circle',importPath: '@remotion/shapes',props: [],+ position: null,}),).toBe('@remotion/shapes');expect(@@ -64,6 +70,7 @@ test('gets required package for insertable elements', () => {importName: 'Sequence',importPath: 'remotion',props: [],+ position: null,}),).toBe(null);});diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 28fd8a49be..5dcd837b81 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -17,13 +17,14 @@ import React, {useState,} from 'react';import type {CanvasContent} from 'remotion';-import {Internals, watchStaticFile} from 'remotion';+import {Internals, watchStaticFile, type PreviewSize} from 'remotion';import {StudioServerConnectionCtx} from '../helpers/client-id';import {BACKGROUND} from '../helpers/colors';import type {AssetMetadata} from '../helpers/get-asset-metadata';import {getAssetMetadata} from '../helpers/get-asset-metadata';import {applyZoomAroundFocalPoint,+ getCenterPointWhileScrolling,getEffectiveTranslation,} from '../helpers/get-effective-translation';import {useCachedCompositionComponentInfo} from '../helpers/open-in-editor';@@ -51,6 +52,7 @@ import {insertComponent,insertExistingAssets,insertRemoteAudio,+ type InsertElementDropPosition,} from './import-assets';import {SPACING_UNIT} from './layout';import {VideoPreview} from './Preview';@@ -164,6 +166,42 @@ const getSfxDragUrl = (event: DragEvent): string | null => {return null;};+const getDropPosition = ({+ clientX,+ clientY,+ contentDimensions,+ previewSize,+ size,+}: {+ clientX: number;+ clientY: number;+ contentDimensions: {width: number; height: number} | 'none' | null;+ previewSize: PreviewSize;+ size: Size;+}): InsertElementDropPosition | null => {+ if (contentDimensions === null || contentDimensions === 'none') {+ return null;+ }++ const scale = Internals.calculateScale({+ canvasSize: size,+ compositionHeight: contentDimensions.height,+ compositionWidth: contentDimensions.width,+ previewSize: previewSize.size,+ });+ const {centerX, centerY} = getCenterPointWhileScrolling({+ size,+ clientX,+ clientY,+ compositionWidth: contentDimensions.width,+ compositionHeight: contentDimensions.height,+ scale,+ translation: previewSize.translation,+ });++ return {centerX, centerY};+};+const isDragEventInsideCanvas = (event: DragEvent): boolean => {const {current} = canvasRef;if (!current) {@@ -743,6 +781,14 @@ export const Canvas: React.FC<{setIsAddingAsset(true);try {+ const dropPosition = getDropPosition({+ clientX: event.clientX,+ clientY: event.clientY,+ contentDimensions,+ previewSize,+ size,+ });+if (isFileDragEvent(event)) {const files = Array.from(event.dataTransfer?.files ?? []);if (files.length === 0) {@@ -753,6 +799,7 @@ export const Canvas: React.FC<{files,compositionFile,compositionId: currentCompositionId,+ dropPosition,});} else if (isAssetDragEvent(event)) {const assetPath = getAssetDragPath(event);@@ -764,6 +811,7 @@ export const Canvas: React.FC<{assetPaths: [assetPath],compositionFile,compositionId: currentCompositionId,+ dropPosition,});} else if (isSfxDragEvent(event)) {const url = getSfxDragUrl(event);@@ -783,6 +831,7 @@ export const Canvas: React.FC<{component: componentDragData.component,compositionFile,compositionId: currentCompositionId,+ dropPosition,});return;}@@ -796,13 +845,21 @@ export const Canvas: React.FC<{url,compositionFile,compositionId: currentCompositionId,+ dropPosition,});}} finally {setIsAddingAsset(false);}},- [canDropAssets, compositionFile, currentCompositionId],+ [+ canDropAssets,+ compositionFile,+ contentDimensions,+ currentCompositionId,+ previewSize,+ size,+ ],);useEffect(() => {diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsxindex b370ece5e0..b3980c18a5 100644--- a/packages/studio/src/components/Timeline/Timeline.tsx+++ b/packages/studio/src/components/Timeline/Timeline.tsx@@ -119,6 +119,7 @@ const TimelineContextMenuArea: React.FC<{type: 'solid',width: videoConfig.width,height: videoConfig.height,+ position: null,},});@@ -155,6 +156,7 @@ const TimelineContextMenuArea: React.FC<{files,compositionFile,compositionId: currentCompositionId,+ dropPosition: null,});} finally {setIsAddingAsset(false);diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex e614ce4789..4736d418e8 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -1,25 +1,40 @@+import {getVideoMetadata} from '@remotion/media-utils';import {detectFileType,getRequiredPackageForInsertableElement,isUrl,type ComponentDragData,+ type ComponentProp,type DownloadRemoteAssetResponse,type FileType,type InsertableCompositionElement,+ type InsertableCompositionElementPosition,} from '@remotion/studio-shared';+import {staticFile} from 'remotion';import {getStaticFiles} from '../api/get-static-files';import {writeStaticFile} from '../api/write-static-file';import {installRequiredPackages} from '../helpers/install-required-package';+import type {Dimensions} from '../helpers/is-current-selected-still';import {callApi} from './call-api';import {showNotification} from './Notifications/NotificationCenter';+export type InsertElementDropPosition = {+ readonly centerX: number;+ readonly centerY: number;+};++type InsertableAssetElement = Extract<+ InsertableCompositionElement,+ {type: 'asset'}+>;+export const getAssetElement = ({fileType,src,}: {fileType: FileType;src: string;-}): InsertableCompositionElement | null => {+}): InsertableAssetElement | null => {if (fileType.type === 'png' ||fileType.type === 'jpeg' ||@@ -32,6 +47,7 @@ export const getAssetElement = ({src,srcType: 'static',dimensions: fileType.dimensions,+ position: null,};}@@ -42,6 +58,7 @@ export const getAssetElement = ({src,srcType: 'static',dimensions: fileType.dimensions,+ position: null,};}@@ -57,6 +74,7 @@ export const getAssetElement = ({src,srcType: 'static',dimensions: null,+ position: null,};}@@ -72,6 +90,7 @@ export const getAssetElement = ({src,srcType: 'static',dimensions: null,+ position: null,};}@@ -80,7 +99,7 @@ export const getAssetElement = ({export const getAssetElementFromPath = (assetPath: string,-): InsertableCompositionElement | null => {+): InsertableAssetElement | null => {if (!assetPath || assetPath.includes('\\')) {return null;}@@ -97,6 +116,7 @@ export const getAssetElementFromPath = (src: assetPath,srcType: 'static',dimensions: null,+ position: null,};}@@ -107,6 +127,7 @@ export const getAssetElementFromPath = (src: assetPath,srcType: 'static',dimensions: null,+ position: null,};}@@ -117,6 +138,7 @@ export const getAssetElementFromPath = (src: assetPath,srcType: 'static',dimensions: null,+ position: null,};}@@ -127,6 +149,7 @@ export const getAssetElementFromPath = (src: assetPath,srcType: 'static',dimensions: null,+ position: null,};}@@ -161,6 +184,181 @@ const getComponentLabel = (component: ComponentDragData['component']) => {return `<${component.componentName}>`;};+const getCenteredPosition = ({+ dimensions,+ dropPosition,+}: {+ dimensions: Dimensions | null;+ dropPosition: InsertElementDropPosition | null;+}): InsertableCompositionElementPosition | null => {+ if (dropPosition === null) {+ return null;+ }++ if (dimensions === null) {+ return {+ x: dropPosition.centerX,+ y: dropPosition.centerY,+ };+ }++ return {+ x: dropPosition.centerX - dimensions.width / 2,+ y: dropPosition.centerY - dimensions.height / 2,+ };+};++const getComponentPropNumber = (props: ComponentProp[], name: string) => {+ const prop = props.find((p) => p.name === name);+ return typeof prop?.value === 'number' ? prop.value : null;+};++const getComponentDimensions = (+ component: ComponentDragData['component'],+): Dimensions | null => {+ const width = getComponentPropNumber(component.props, 'width');+ const height = getComponentPropNumber(component.props, 'height');+ if (width !== null && height !== null) {+ return {width, height};+ }++ const radius = getComponentPropNumber(component.props, 'radius');+ if (radius !== null) {+ return {width: radius * 2, height: radius * 2};+ }++ return null;+};++const getImageDimensions = ({+ revokeObjectUrl,+ src,+}: {+ revokeObjectUrl: boolean;+ src: string;+}): Promise<Dimensions> => {+ return new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => {+ if (revokeObjectUrl) {+ URL.revokeObjectURL(src);+ }++ resolve({width: image.naturalWidth, height: image.naturalHeight});+ };++ image.onerror = () => {+ if (revokeObjectUrl) {+ URL.revokeObjectURL(src);+ }++ reject(new Error('Failed to load image dimensions'));+ };++ image.src = src;+ });+};++const getVideoDimensions = async (src: string): Promise<Dimensions> => {+ const metadata = await getVideoMetadata(src);+ return {width: metadata.width, height: metadata.height};+};++const getFileDimensions = async ({+ file,+ fileType,+}: {+ file: File;+ fileType: FileType;+}): Promise<Dimensions | null> => {+ if (+ fileType.type === 'wav' ||+ fileType.type === 'mp3' ||+ fileType.type === 'aac' ||+ fileType.type === 'flac'+ ) {+ return null;+ }++ if (+ fileType.type === 'png' ||+ fileType.type === 'jpeg' ||+ fileType.type === 'webp' ||+ fileType.type === 'bmp' ||+ fileType.type === 'gif'+ ) {+ if (fileType.dimensions) {+ return fileType.dimensions;+ }++ const objectUrl = URL.createObjectURL(file);+ return getImageDimensions({revokeObjectUrl: true, src: objectUrl});+ }++ if (+ fileType.type === 'riff' ||+ fileType.type === 'webm' ||+ fileType.type === 'iso-base-media' ||+ fileType.type === 'transport-stream'+ ) {+ const objectUrl = URL.createObjectURL(file);+ try {+ return await getVideoDimensions(objectUrl);+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+ }++ return null;+};++const getStaticAssetDimensions = (+ assetPath: string,+): Dimensions | Promise<Dimensions> | null => {+ const extension = assetPath.split('.').pop()?.toLowerCase();+ const src = staticFile(assetPath);++ if (+ extension &&+ ['png', 'jpg', 'jpeg', 'webp', 'bmp', 'gif'].includes(extension)+ ) {+ return getImageDimensions({revokeObjectUrl: false, src});+ }++ if (+ extension &&+ ['mp4', 'm4v', 'mov', 'avi', 'webm', 'ts', 'm2ts'].includes(extension)+ ) {+ return getVideoDimensions(src);+ }++ return null;+};++const getFileDimensionsOrNull = async ({+ file,+ fileType,+}: {+ file: File;+ fileType: FileType;+}): Promise<Dimensions | null> => {+ try {+ return await getFileDimensions({file, fileType});+ } catch {+ return null;+ }+};++const getStaticAssetDimensionsOrNull = async (+ assetPath: string,+): Promise<Dimensions | null> => {+ try {+ return await getStaticAssetDimensions(assetPath);+ } catch {+ return null;+ }+};+export const pickFilesToImport = (): Promise<File[]> => {return new Promise((resolve) => {const input = document.createElement('input');@@ -242,7 +440,7 @@ const insertAssetElement = async ({return true;};-const downloadRemoteAsset = async (+const downloadRemoteAsset = (url: string,): Promise<DownloadRemoteAssetResponse> => {return callApi('/api/download-remote-asset', {url});@@ -251,10 +449,12 @@ const downloadRemoteAsset = async (export const importAssets = async ({compositionFile,compositionId,+ dropPosition,files,}: {compositionFile: string;compositionId: string;+ dropPosition: InsertElementDropPosition | null;files: File[];}) => {if (files.length === 0) {@@ -264,8 +464,9 @@ export const importAssets = async ({const staticFiles = getStaticFiles();const differentExistingFile = files.find((file) => {return staticFiles.some(- (staticFile) =>- staticFile.name === file.name && staticFile.sizeInBytes !== file.size,+ (existingStaticFile) =>+ existingStaticFile.name === file.name &&+ existingStaticFile.sizeInBytes !== file.size,);});if (differentExistingFile) {@@ -307,8 +508,9 @@ export const importAssets = async ({}const alreadyExists = staticFiles.some(- (staticFile) =>- staticFile.name === file.name && staticFile.sizeInBytes === file.size,+ (existingStaticFile) =>+ existingStaticFile.name === file.name &&+ existingStaticFile.sizeInBytes === file.size,);if (!alreadyExists) {@@ -319,10 +521,19 @@ export const importAssets = async ({addedStaticFiles.push(file.name);}+ const dimensions = await getFileDimensionsOrNull({file, fileType});+const inserted = await insertAssetElement({compositionFile,compositionId,- element,+ element: {+ ...element,+ dimensions: element.dimensions ?? dimensions,+ position: getCenteredPosition({+ dimensions,+ dropPosition,+ }),+ },});if (!inserted) {@@ -349,10 +560,12 @@ export const importAssets = async ({export const importRemoteAsset = async ({compositionFile,compositionId,+ dropPosition,url,}: {compositionFile: string;compositionId: string;+ dropPosition: InsertElementDropPosition | null;url: string;}) => {try {@@ -362,10 +575,21 @@ export const importRemoteAsset = async ({showNotification(`Created ${assetPath} in public folder`, 3000);}+ if (element.type !== 'asset') {+ showNotification('Cannot add remote asset: Unsupported asset type', 3000);+ return;+ }+const inserted = await insertAssetElement({compositionFile,compositionId,- element,+ element: {+ ...element,+ position: getCenteredPosition({+ dimensions: element.dimensions,+ dropPosition,+ }),+ },});if (!inserted) {@@ -403,6 +627,7 @@ export const insertRemoteAudio = async ({src: url,srcType: 'remote',dimensions: null,+ position: null,};try {@@ -431,10 +656,12 @@ export const insertExistingAssets = async ({assetPaths,compositionFile,compositionId,+ dropPosition,}: {assetPaths: string[];compositionFile: string;compositionId: string;+ dropPosition: InsertElementDropPosition | null;}) => {if (assetPaths.length === 0) {return;@@ -451,10 +678,19 @@ export const insertExistingAssets = async ({continue;}+ const dimensions = await getStaticAssetDimensionsOrNull(assetPath);+const inserted = await insertAssetElement({compositionFile,compositionId,- element,+ element: {+ ...element,+ dimensions: element.dimensions ?? dimensions,+ position: getCenteredPosition({+ dimensions,+ dropPosition,+ }),+ },});if (!inserted) {@@ -480,10 +716,12 @@ export const insertComponent = async ({component,compositionFile,compositionId,+ dropPosition,}: {component: ComponentDragData['component'];compositionFile: string;compositionId: string;+ dropPosition: InsertElementDropPosition | null;}) => {try {const inserted = await insertAssetElement({@@ -495,6 +733,10 @@ export const insertComponent = async ({importName: component.importName,importPath: component.importPath,props: component.props,+ position: getCenteredPosition({+ dimensions: getComponentDimensions(component),+ dropPosition,+ }),},});diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.tsindex c7c3f38674..864c9b0c27 100644--- a/packages/studio/src/test/import-assets.test.ts+++ b/packages/studio/src/test/import-assets.test.ts@@ -17,6 +17,7 @@ test('maps audio file types to Audio assets', () => {src: `sound.${type}`,srcType: 'static',dimensions: null,+ position: null,});}});@@ -37,6 +38,7 @@ test('maps existing static file paths to insertable assets', () => {src: 'nested/photo.JPG',srcType: 'static',dimensions: null,+ position: null,});expect(getAssetElementFromPath('movie.webm')).toEqual({type: 'asset',@@ -44,6 +46,7 @@ test('maps existing static file paths to insertable assets', () => {src: 'movie.webm',srcType: 'static',dimensions: null,+ position: null,});expect(getAssetElementFromPath('audio.flac')).toEqual({type: 'asset',@@ -51,6 +54,7 @@ test('maps existing static file paths to insertable assets', () => {src: 'audio.flac',srcType: 'static',dimensions: null,+ position: null,});expect(getAssetElementFromPath('animation.gif')).toEqual({type: 'asset',@@ -58,6 +62,7 @@ test('maps existing static file paths to insertable assets', () => {src: 'animation.gif',srcType: 'static',dimensions: null,+ position: null,});});