Skip to content

🎥 Make videos programmatically with React

`@remotion/drag-and-drop`: Add drag-and-drop payload package (#9532)

Jonny Burger1636821b7f8f
diff --git a/bun.lock b/bun.lock
index e3a329f997..b7e960f0a7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -491,6 +491,7 @@
"@remotion/convert": "workspace:*",
"@remotion/design": "workspace:*",
"@remotion/docusaurus-plugin": "workspace:*",
+ "@remotion/drag-and-drop": "workspace:*",
"@remotion/effects": "workspace:*",
"@remotion/elevenlabs": "workspace:*",
"@remotion/enable-scss": "workspace:*",
@@ -607,6 +608,15 @@
"eslint": "catalog:",
},
},
+ "packages/drag-and-drop": {
+ "name": "@remotion/drag-and-drop",
+ "version": "4.0.497",
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:",
+ },
+ },
"packages/effects": {
"name": "@remotion/effects",
"version": "4.0.498",
@@ -739,6 +749,7 @@
"@remotion/captions": "workspace:*",
"@remotion/cli": "workspace:*",
"@remotion/cloudrun": "workspace:*",
+ "@remotion/drag-and-drop": "workspace:*",
"@remotion/effects": "workspace:*",
"@remotion/enable-scss": "workspace:*",
"@remotion/eslint-config-flat": "workspace:*",
@@ -1644,6 +1655,7 @@
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@remotion/canvas-capture": "workspace:*",
+ "@remotion/drag-and-drop": "workspace:*",
"@remotion/media-utils": "workspace:*",
"@remotion/player": "workspace:*",
"@remotion/renderer": "workspace:*",
@@ -1678,6 +1690,7 @@
"@babel/parser": "7.24.1",
"@babel/types": "7.24.0",
"@remotion/bundler": "workspace:*",
+ "@remotion/drag-and-drop": "workspace:*",
"@remotion/renderer": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"@svgr/core": "8.1.0",
@@ -1704,6 +1717,7 @@
"name": "@remotion/studio-shared",
"version": "4.0.498",
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"remotion": "workspace:*",
},
"devDependencies": {
@@ -4053,6 +4067,8 @@
"@remotion/docusaurus-plugin": ["@remotion/docusaurus-plugin@workspace:packages/docusaurus-plugin"],
+ "@remotion/drag-and-drop": ["@remotion/drag-and-drop@workspace:packages/drag-and-drop"],
+
"@remotion/effects": ["@remotion/effects@workspace:packages/effects"],
"@remotion/elevenlabs": ["@remotion/elevenlabs@workspace:packages/elevenlabs"],
diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.ts
index 39d421fa3f..460f34ea01 100644
--- a/packages/cli/src/list-of-remotion-packages.ts
+++ b/packages/cli/src/list-of-remotion-packages.ts
@@ -94,6 +94,7 @@ export const listOfRemotionPackages = [
'@remotion/remotion-media',
'@remotion/web-renderer',
'@remotion/design',
+ '@remotion/drag-and-drop',
'@remotion/light-leaks',
'@remotion/rough-notation',
'@remotion/starburst',
diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.ts
index 39d421fa3f..460f34ea01 100644
--- a/packages/create-video/src/list-of-remotion-packages.ts
+++ b/packages/create-video/src/list-of-remotion-packages.ts
@@ -94,6 +94,7 @@ export const listOfRemotionPackages = [
'@remotion/remotion-media',
'@remotion/web-renderer',
'@remotion/design',
+ '@remotion/drag-and-drop',
'@remotion/light-leaks',
'@remotion/rough-notation',
'@remotion/starburst',
diff --git a/packages/docs/components/effects-demos/effect-drag-data.ts b/packages/docs/components/effects-demos/effect-drag-data.ts
index 7d6ff34593..ea24568bed 100644
--- a/packages/docs/components/effects-demos/effect-drag-data.ts
+++ b/packages/docs/components/effects-demos/effect-drag-data.ts
@@ -1,7 +1,7 @@
-import {
- EFFECT_DRAG_MIME_TYPE,
- type EffectDragData,
-} from '@remotion/studio-shared';
+import type {
+ ConstructedDragData,
+ EffectDragData,
+} from '@remotion/drag-and-drop';
const FX_ICON_PATH =
'M4.405 4.48C4.575 3.82 4.865 3.325 5.275 2.995C5.695 2.665 6.25 2.5 6.94 2.5H9.235V4.06H7.045C6.555 4.06 6.235 4.3 6.085 4.78L5.83 5.68H7.975V7.255H5.395L3.805 13H2.02L3.625 7.255H1.96V5.68H4.075L4.405 4.48ZM8.57102 9.085L6.87602 5.68H8.79602L9.86102 7.99L11.991 5.68H14.331L10.686 9.415L12.426 13H10.491L9.35102 10.585L7.02602 13H4.68602L8.57102 9.085Z';
@@ -35,38 +35,15 @@ const makeEffectDragImage = () => {
return wrapper;
};
-export const makeEffectDragData = ({
- effectName,
- effectImportPath,
- effectConfig,
-}: {
- readonly effectName: string;
- readonly effectImportPath: string;
- readonly effectConfig: Record<string, unknown>;
-}): EffectDragData => {
- return {
- type: 'remotion-effect',
- version: 1,
- effect: {
- name: effectName,
- importPath: effectImportPath,
- config: effectConfig,
- },
- };
-};
-
export const setEffectDragData = ({
dataTransfer,
dragData,
}: {
readonly dataTransfer: DataTransfer;
- readonly dragData: EffectDragData;
+ readonly dragData: ConstructedDragData<EffectDragData>;
}) => {
- const serialized = JSON.stringify(dragData);
dataTransfer.effectAllowed = 'copy';
- dataTransfer.setData(EFFECT_DRAG_MIME_TYPE, serialized);
- dataTransfer.setData('application/json', serialized);
- dataTransfer.setData('text/plain', serialized);
+ dataTransfer.setData(dragData.mimeType, dragData.payload);
};
export const setEffectDragImage = (dataTransfer: DataTransfer) => {
diff --git a/packages/docs/components/effects-demos/index.tsx b/packages/docs/components/effects-demos/index.tsx
index 35a1b8db57..bbb91fa83a 100644
--- a/packages/docs/components/effects-demos/index.tsx
+++ b/packages/docs/components/effects-demos/index.tsx
@@ -1,13 +1,9 @@
import {useColorMode} from '@docusaurus/theme-common';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import {Player} from '@remotion/player';
import React, {useCallback, useMemo, useState} from 'react';
import {AbsoluteFill} from 'remotion';
-import controlStyles from '../demos/styles.module.css';
-import {
- makeEffectDragData,
- setEffectDragData,
- setEffectDragImage,
-} from './effect-drag-data';
+import {setEffectDragData, setEffectDragImage} from './effect-drag-data';
import {
fillSchemaDefaults,
getActiveSchemaFields,
@@ -15,6 +11,7 @@ import {
} from './get-default-props-from-schema';
import {effectsDemos} from './registry';
import {SchemaControl} from './schema-control';
+import controlStyles from '../demos/styles.module.css';
import styles from './styles.module.css';
export const EffectsDemo: React.FC<{
@@ -52,10 +49,11 @@ export const EffectsDemo: React.FC<{
}, [initialState]);
const dragData = useMemo(() => {
- return makeEffectDragData({
- effectName: demo.effectName,
- effectImportPath: demo.effectImportPath,
- effectConfig: state,
+ return DragAndDropInternals.makeDragData({
+ type: 'effect',
+ name: demo.effectName,
+ importPath: demo.effectImportPath,
+ config: state,
});
}, [demo.effectImportPath, demo.effectName, state]);
diff --git a/packages/docs/components/sfx-demos/sfx-drag-data.ts b/packages/docs/components/sfx-demos/sfx-drag-data.ts
index 1aa60f5853..f108001b3b 100644
--- a/packages/docs/components/sfx-demos/sfx-drag-data.ts
+++ b/packages/docs/components/sfx-demos/sfx-drag-data.ts
@@ -1,21 +1,4 @@
-import {SFX_DRAG_MIME_TYPE, type SfxDragData} from '@remotion/studio-shared';
-
-export const makeSfxDragData = ({
- name,
- url,
-}: {
- readonly name: string;
- readonly url: string;
-}): SfxDragData => {
- return {
- type: 'remotion-sfx',
- version: 1,
- sfx: {
- name,
- url,
- },
- };
-};
+import type {ConstructedDragData, SfxDragData} from '@remotion/drag-and-drop';
export const getSfxNameFromUrl = (src: string): string => {
try {
@@ -36,11 +19,8 @@ export const setSfxDragData = ({
dragData,
}: {
readonly dataTransfer: DataTransfer;
- readonly dragData: SfxDragData;
+ readonly dragData: ConstructedDragData<SfxDragData>;
}) => {
- const serialized = JSON.stringify(dragData);
dataTransfer.effectAllowed = 'copy';
- dataTransfer.setData(SFX_DRAG_MIME_TYPE, serialized);
- dataTransfer.setData('application/json', serialized);
- dataTransfer.setData('text/plain', serialized);
+ dataTransfer.setData(dragData.mimeType, dragData.payload);
};
diff --git a/packages/docs/components/shapes/shape-component-drag-data.ts b/packages/docs/components/shapes/shape-component-drag-data.ts
index db41b0289c..a41871b966 100644
--- a/packages/docs/components/shapes/shape-component-drag-data.ts
+++ b/packages/docs/components/shapes/shape-component-drag-data.ts
@@ -1,9 +1,9 @@
import {
- COMPONENT_DRAG_MIME_TYPE,
- makeComponentDragData,
+ DragAndDropInternals,
type ComponentDragData,
type ComponentProp,
-} from '@remotion/studio-shared';
+ type ConstructedDragData,
+} from '@remotion/drag-and-drop';
import {getShapeDragInfo} from './shape-drag-info';
import type {ShapeName} from './shapes-info';
@@ -155,7 +155,7 @@ const makeShapeComponentDragData = ({
}: {
readonly shape: ShapeName;
readonly props: ComponentProp[];
-}): ComponentDragData => {
+}): ConstructedDragData<ComponentDragData> => {
const component = {
componentName: shape,
importName: shape,
@@ -164,7 +164,8 @@ const makeShapeComponentDragData = ({
} satisfies ComponentDragData['component'];
const shapeInfo = getShapeDragInfo(component);
- return makeComponentDragData({
+ return DragAndDropInternals.makeDragData({
+ type: 'component',
...component,
dimensions: shapeInfo
? {width: shapeInfo.width, height: shapeInfo.height}
@@ -174,7 +175,7 @@ const makeShapeComponentDragData = ({
export const makeDefaultShapeComponentDragData = (
shape: ShapeName,
-): ComponentDragData => {
+): ConstructedDragData<ComponentDragData> => {
return makeShapeComponentDragData({
shape,
props: [...shapeDefaultProps[shape]],
@@ -193,7 +194,7 @@ export const makeShapeComponentDragDataFromDemoState = ({
}: {
readonly demoId: string;
readonly state: Record<string, unknown>;
-}): ComponentDragData | null => {
+}): ConstructedDragData<ComponentDragData> | null => {
const shape = shapeNameByDemoId[demoId];
if (!shape) {
return null;
@@ -234,14 +235,11 @@ export const setComponentDragData = ({
dragImage,
}: {
readonly dataTransfer: DataTransfer;
- readonly dragData: ComponentDragData;
+ readonly dragData: ConstructedDragData<ComponentDragData>;
readonly dragImage?: Element | null;
}) => {
- const serialized = JSON.stringify(dragData);
dataTransfer.effectAllowed = 'copy';
- dataTransfer.setData(COMPONENT_DRAG_MIME_TYPE, serialized);
- dataTransfer.setData('application/json', serialized);
- dataTransfer.setData('text/plain', serialized);
+ dataTransfer.setData(dragData.mimeType, dragData.payload);
if (dragImage) {
const rect = dragImage.getBoundingClientRect();
diff --git a/packages/docs/components/shapes/shape-drag-info.ts b/packages/docs/components/shapes/shape-drag-info.ts
index 9e6e198ce2..a02f14e73b 100644
--- a/packages/docs/components/shapes/shape-drag-info.ts
+++ b/packages/docs/components/shapes/shape-drag-info.ts
@@ -1,3 +1,4 @@
+import type {ComponentDragData} from '@remotion/drag-and-drop';
import {
makeArrow,
makeCallout,
@@ -11,7 +12,6 @@ import {
makeStar,
makeTriangle,
} from '@remotion/shapes';
-import type {ComponentDragData} from '@remotion/studio-shared';
import {shapeNames, type ShapeName} from './shapes-info';
export type ShapeDragInfo = {
diff --git a/packages/docs/components/shapes/shape-drag-preview.tsx b/packages/docs/components/shapes/shape-drag-preview.tsx
index fe1b3ae9ad..f0d66fc2de 100644
--- a/packages/docs/components/shapes/shape-drag-preview.tsx
+++ b/packages/docs/components/shapes/shape-drag-preview.tsx
@@ -1,15 +1,18 @@
-import type {ComponentDragData} from '@remotion/studio-shared';
+import type {
+ ComponentDragData,
+ ConstructedDragData,
+} from '@remotion/drag-and-drop';
import React from 'react';
import {getShapeDragInfo} from './shape-drag-info';
export const ShapeDragPreview = React.forwardRef<
SVGSVGElement,
{
- readonly dragData: ComponentDragData;
+ readonly dragData: ConstructedDragData<ComponentDragData>;
readonly size: number;
}
>(({dragData, size}, ref) => {
- const shapeInfo = getShapeDragInfo(dragData.component);
+ const shapeInfo = getShapeDragInfo(dragData.data.component);
if (shapeInfo === null) {
return null;
}
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index c09af8ba15..4521052d40 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -1,10 +1,10 @@
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import {
EFFECT_CATALOG,
getEffectCatalogCategories,
getEffectDocumentationPath,
getEffectPreviewAlt,
getEffectPreviewSource,
- makeEffectDragDataFromCatalogItem,
type EffectCatalogItem,
} from '@remotion/studio-shared';
import React from 'react';
@@ -34,7 +34,10 @@ const previewImage: React.CSSProperties = {
const EffectCard: React.FC<{
readonly effect: EffectCatalogItem;
}> = ({effect}) => {
- const dragData = makeEffectDragDataFromCatalogItem(effect);
+ const dragData = DragAndDropInternals.makeDragData({
+ type: 'effect',
+ ...effect.effect,
+ });
return (
<TOCItem
diff --git a/packages/docs/docs/sfx/PlayButton.tsx b/packages/docs/docs/sfx/PlayButton.tsx
index c2b6c9b0d2..8518c8fa81 100644
--- a/packages/docs/docs/sfx/PlayButton.tsx
+++ b/packages/docs/docs/sfx/PlayButton.tsx
@@ -1,8 +1,8 @@
import {Button} from '@remotion/design';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {
getSfxNameFromUrl,
- makeSfxDragData,
setSfxDragData,
} from '../../components/sfx-demos/sfx-drag-data';
import {sfxWaveforms} from '../../components/sfx-demos/sfx-waveforms';
@@ -159,7 +159,8 @@ const setDragDataForSfx = ({
}) => {
setSfxDragData({
dataTransfer,
- dragData: makeSfxDragData({
+ dragData: DragAndDropInternals.makeDragData({
+ type: 'sfx',
name,
url: src,
}),
diff --git a/packages/docs/docs/shapes/table-of-contents.tsx b/packages/docs/docs/shapes/table-of-contents.tsx
index a5cd427003..90698f7305 100644
--- a/packages/docs/docs/shapes/table-of-contents.tsx
+++ b/packages/docs/docs/shapes/table-of-contents.tsx
@@ -42,7 +42,7 @@ const shapeThumbnail: React.CSSProperties = {
const ShapeDragPreview = React.forwardRef<SVGSVGElement, {shape: ShapeName}>(
({shape}, ref) => {
const dragData = makeDefaultShapeComponentDragData(shape);
- const shapeInfo = getShapeDragInfo(dragData.component);
+ const shapeInfo = getShapeDragInfo(dragData.data.component);
if (shapeInfo === null) {
throw new Error(`Could not get shape info for ${shape}`);
}
diff --git a/packages/docs/package.json b/packages/docs/package.json
index 280549428d..f806192a01 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -22,6 +22,7 @@
"render-element-previews": "bun run render-element-previews.ts"
},
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"@aws-sdk/s3-request-presigner": "catalog:",
"@babel/parser": "7.24.1",
"@babel/plugin-transform-modules-commonjs": "7.27.1",
diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsx
index 7f879a1e0b..f886ab9b0a 100644
--- a/packages/docs/src/components/Elements/ElementPage.tsx
+++ b/packages/docs/src/components/Elements/ElementPage.tsx
@@ -1,7 +1,7 @@
import {
- makeElementDragData,
+ DragAndDropInternals,
type ComponentDimensions,
-} from '@remotion/studio-shared';
+} from '@remotion/drag-and-drop';
import React, {
useCallback,
useId,
@@ -134,16 +134,19 @@ export const ElementPage: React.FC<ElementPageProps> = ({
}
: null;
- return makeElementDragData({
+ return DragAndDropInternals.makeDragData({
+ type: 'element',
dependencies,
dimensions,
displayName,
+ durationInFrames,
slug,
sourceCode,
});
}, [
dependencies,
displayName,
+ durationInFrames,
elementHeight,
elementWidth,
slug,
@@ -172,7 +175,10 @@ export const ElementPage: React.FC<ElementPageProps> = ({
{
method: 'POST',
headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({element: dragData.element}),
+ body: JSON.stringify({
+ mimeType: dragData.mimeType,
+ payload: dragData.payload,
+ }),
},
);
const result = (await response.json()) as
diff --git a/packages/docs/src/components/Elements/element-drag-data.ts b/packages/docs/src/components/Elements/element-drag-data.ts
index b3d4d10a2b..00d4bf3256 100644
--- a/packages/docs/src/components/Elements/element-drag-data.ts
+++ b/packages/docs/src/components/Elements/element-drag-data.ts
@@ -1,7 +1,4 @@
-import {
- ELEMENT_DRAG_MIME_TYPE,
- type ElementDragData,
-} from '@remotion/studio-shared';
+import type {ConstructedDragData} from '@remotion/drag-and-drop';
const ELEMENT_ICON_PATH =
'M3 3.5C3 2.67157 3.67157 2 4.5 2H11.5C12.3284 2 13 2.67157 13 3.5V12.5C13 13.3284 12.3284 14 11.5 14H4.5C3.67157 14 3 13.3284 3 12.5V3.5ZM4.5 3.5V6H11.5V3.5H4.5ZM11.5 7.5H4.5V12.5H11.5V7.5Z';
@@ -40,13 +37,10 @@ export const setElementDragData = ({
dragData,
}: {
readonly dataTransfer: DataTransfer;
- readonly dragData: ElementDragData;
+ readonly dragData: ConstructedDragData;
}) => {
- const serialized = JSON.stringify(dragData);
dataTransfer.effectAllowed = 'copy';
- dataTransfer.setData(ELEMENT_DRAG_MIME_TYPE, serialized);
- dataTransfer.setData('application/json', serialized);
- dataTransfer.setData('text/plain', serialized);
+ dataTransfer.setData(dragData.mimeType, dragData.payload);
};
export const setElementDragImage = (dataTransfer: DataTransfer) => {
diff --git a/packages/docs/src/test/shape-component-drag-data.test.ts b/packages/docs/src/test/shape-component-drag-data.test.ts
index 18bac46a9c..3e47db6054 100644
--- a/packages/docs/src/test/shape-component-drag-data.test.ts
+++ b/packages/docs/src/test/shape-component-drag-data.test.ts
@@ -9,9 +9,9 @@ test('embeds dimensions into default shape drag data', () => {
for (const shape of shapeNames) {
const dragData = makeDefaultShapeComponentDragData(shape);
- expect(dragData.component.dimensions).toBeDefined();
- expect(dragData.component.dimensions?.width).toBeGreaterThan(0);
- expect(dragData.component.dimensions?.height).toBeGreaterThan(0);
+ expect(dragData.data.component.dimensions).toBeDefined();
+ expect(dragData.data.component.dimensions?.width).toBeGreaterThan(0);
+ expect(dragData.data.component.dimensions?.height).toBeGreaterThan(0);
}
});
@@ -21,6 +21,6 @@ test('embeds dimensions from shape demo state', () => {
state: {height: 200, aspectRatio: 1.2},
});
- expect(dragData?.component.dimensions?.width).toBeCloseTo(240);
- expect(dragData?.component.dimensions?.height).toBe(200);
+ expect(dragData?.data.component.dimensions?.width).toBeCloseTo(240);
+ expect(dragData?.data.component.dimensions?.height).toBe(200);
});
diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.json
index 3e79b82ca7..9055bfb119 100644
--- a/packages/docs/tsconfig.json
+++ b/packages/docs/tsconfig.json
@@ -25,6 +25,7 @@
"references": [
{"path": "../player"},
{"path": "../core"},
+ {"path": "../drag-and-drop"},
{"path": "../media-utils"},
{"path": "../browser-studio"},
{"path": "../docusaurus-plugin"},
diff --git a/packages/drag-and-drop/.npmignore b/packages/drag-and-drop/.npmignore
new file mode 100644
index 0000000000..b01c0f0056
--- /dev/null
+++ b/packages/drag-and-drop/.npmignore
@@ -0,0 +1,10 @@
+dist/test/**
+src
+eslint.config.mjs
+tsconfig.tsbuildinfo
+*.tgz
+.turbo
+tsconfig.json
+.prettierrc.js
+bundle.ts
+dist/cjs/test/
diff --git a/packages/drag-and-drop/README.md b/packages/drag-and-drop/README.md
new file mode 100644
index 0000000000..788df85a2d
--- /dev/null
+++ b/packages/drag-and-drop/README.md
@@ -0,0 +1,6 @@
+# `@remotion/drag-and-drop`
+
+Internal drag-and-drop helpers for Remotion.
+
+This package is published for use by other Remotion packages and has no public
+API.
diff --git a/packages/drag-and-drop/bundle.ts b/packages/drag-and-drop/bundle.ts
new file mode 100644
index 0000000000..03974d7308
--- /dev/null
+++ b/packages/drag-and-drop/bundle.ts
@@ -0,0 +1,51 @@
+import path from 'path';
+import {build} from 'bun';
+
+if (process.env.NODE_ENV !== 'production') {
+ throw new Error('This script must be run using NODE_ENV=production');
+}
+
+const external = [
+ 'remotion',
+ 'remotion/no-react',
+ 'react',
+ 'react/jsx-runtime',
+ 'react/jsx-dev-runtime',
+ 'react-dom',
+];
+
+console.time('Generated.');
+const esmOutput = await build({
+ entrypoints: ['src/index.ts'],
+ naming: '[name].mjs',
+ external,
+});
+const cjsOutput = await build({
+ entrypoints: ['src/index.ts'],
+ naming: '[name].cjs',
+ format: 'cjs',
+ external,
+});
+
+for (const output of [esmOutput, cjsOutput]) {
+ if (!output.success) {
+ console.log(output.logs.join('\n'));
+ process.exit(1);
+ }
+}
+
+for (const file of esmOutput.outputs) {
+ const str = await file.text();
+ const out = path.join('dist', 'esm', file.path);
+
+ await Bun.write(out, str);
+}
+
+for (const file of cjsOutput.outputs) {
+ const str = await file.text();
+ const out = path.join('dist', file.path);
+
+ await Bun.write(out, str);
+}
+
+console.timeEnd('Generated.');
diff --git a/packages/drag-and-drop/eslint.config.mjs b/packages/drag-and-drop/eslint.config.mjs
new file mode 100644
index 0000000000..04fd4fac11
--- /dev/null
+++ b/packages/drag-and-drop/eslint.config.mjs
@@ -0,0 +1,7 @@
+import {remotionFlatConfig} from '@remotion/eslint-config-internal';
+
+const config = remotionFlatConfig({react: false});
+
+export default {
+ ...config,
+};
diff --git a/packages/drag-and-drop/package.json b/packages/drag-and-drop/package.json
new file mode 100644
index 0000000000..db6a172527
--- /dev/null
+++ b/packages/drag-and-drop/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@remotion/drag-and-drop",
+ "version": "4.0.497",
+ "description": "Internal drag-and-drop helpers for Remotion",
+ "main": "dist/index.cjs",
+ "types": "dist/index.d.ts",
+ "module": "dist/esm/index.mjs",
+ "repository": {
+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/drag-and-drop"
+ },
+ "type": "module",
+ "scripts": {
+ "test": "bun test src/test",
+ "formatting": "oxfmt src --check",
+ "format": "oxfmt src",
+ "lint": "eslint src",
+ "watch": "tsgo -w",
+ "make": "tsgo && bun --env-file=../.env.bundle bundle.ts"
+ },
+ "author": "Jonny Burger <[email protected]>",
+ "contributors": [],
+ "license": "Remotion License",
+ "bugs": {
+ "url": "https://github.com/remotion-dev/remotion/issues"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "require": "./dist/index.cjs",
+ "module": "./dist/esm/index.mjs",
+ "import": "./dist/esm/index.mjs"
+ },
+ "./package.json": "./package.json"
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "eslint": "catalog:",
+ "@typescript/native-preview": "catalog:"
+ },
+ "keywords": [
+ "remotion",
+ "drag-and-drop"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/drag-and-drop/src/asset-drag-data.ts b/packages/drag-and-drop/src/asset-drag-data.ts
new file mode 100644
index 0000000000..81076329dd
--- /dev/null
+++ b/packages/drag-and-drop/src/asset-drag-data.ts
@@ -0,0 +1,34 @@
+import {isRecord} from './validation';
+
+export type AssetDragData = {
+ type: 'remotion-asset';
+ version: 1;
+ assetPath: string;
+};
+
+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) ||
+ parsed.type !== 'remotion-asset' ||
+ parsed.version !== 1 ||
+ typeof parsed.assetPath !== 'string' ||
+ parsed.assetPath.length === 0
+ ) {
+ return null;
+ }
+
+ return makeAssetDragData(parsed.assetPath);
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/studio-shared/src/component-drag-data.ts b/packages/drag-and-drop/src/component-drag-data.ts
similarity index 81%
rename from packages/studio-shared/src/component-drag-data.ts
rename to packages/drag-and-drop/src/component-drag-data.ts
index 27cc41083b..e68dcf129d 100644
--- a/packages/studio-shared/src/component-drag-data.ts
+++ b/packages/drag-and-drop/src/component-drag-data.ts
@@ -1,4 +1,4 @@
-export {COMPONENT_DRAG_MIME_TYPE} from './drag-mime-types';
+import {isRecord} from './validation';
export type ComponentProp = {
name: string;
@@ -22,10 +22,6 @@ export type ComponentDragData = {
};
};
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-};
-
export const isComponentIdentifier = (value: unknown): value is string => {
return typeof value === 'string' && /^[A-Z_$][A-Za-z0-9_$]*$/.test(value);
};
@@ -51,11 +47,7 @@ export const isComponentPropName = (value: unknown): value is string => {
};
export const isComponentProp = (value: unknown): value is ComponentProp => {
- if (!isRecord(value)) {
- return false;
- }
-
- if (!isComponentPropName(value.name)) {
+ if (!isRecord(value) || !isComponentPropName(value.name)) {
return false;
}
@@ -131,15 +123,12 @@ export const parseComponentDragData = (
): ComponentDragData | null => {
try {
const parsed: unknown = JSON.parse(value);
- if (!isRecord(parsed)) {
- return null;
- }
-
- if (parsed.type !== 'remotion-component' || parsed.version !== 1) {
- return null;
- }
-
- if (!isRecord(parsed.component)) {
+ if (
+ !isRecord(parsed) ||
+ parsed.type !== 'remotion-component' ||
+ parsed.version !== 1 ||
+ !isRecord(parsed.component)
+ ) {
return null;
}
@@ -155,17 +144,13 @@ export const parseComponentDragData = (
return null;
}
- return {
- type: 'remotion-component',
- version: 1,
- component: {
- componentName,
- ...(dimensions ? {dimensions} : {}),
- importName,
- importPath,
- props,
- },
- };
+ return makeComponentDragData({
+ componentName,
+ dimensions: dimensions ?? null,
+ importName,
+ importPath,
+ props,
+ });
} catch {
return null;
}
diff --git a/packages/drag-and-drop/src/composition-drag-data.ts b/packages/drag-and-drop/src/composition-drag-data.ts
new file mode 100644
index 0000000000..9e514dafa1
--- /dev/null
+++ b/packages/drag-and-drop/src/composition-drag-data.ts
@@ -0,0 +1,72 @@
+import {isRecord} from './validation';
+
+export type CompositionDragData = {
+ type: 'remotion-composition';
+ version: 1;
+ compositionId: string;
+ compositionFile: string | null;
+};
+
+const isCompositionId = (value: unknown): value is string => {
+ return (
+ typeof value === 'string' &&
+ value.length > 0 &&
+ value.length < 500 &&
+ /^([a-zA-Z0-9-\u4E00-\u9FFF])+$/.test(value)
+ );
+};
+
+const isCompositionFile = (value: unknown): value is string | null => {
+ if (value === null) {
+ return true;
+ }
+
+ return (
+ typeof value === 'string' &&
+ value.length > 0 &&
+ value.length < 2000 &&
+ !value.includes('\0') &&
+ !value.includes('\\') &&
+ !value.startsWith('/') &&
+ !value.split('/').includes('..')
+ );
+};
+
+export const makeCompositionDragData = ({
+ compositionFile,
+ compositionId,
+}: {
+ compositionFile: string | null;
+ compositionId: string;
+}): CompositionDragData => {
+ return {
+ type: 'remotion-composition',
+ version: 1,
+ compositionFile,
+ compositionId,
+ };
+};
+
+export const parseCompositionDragData = (
+ value: string,
+): CompositionDragData | null => {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (
+ !isRecord(parsed) ||
+ parsed.type !== 'remotion-composition' ||
+ parsed.version !== 1 ||
+ !isCompositionId(parsed.compositionId) ||
+ !isCompositionFile(parsed.compositionFile)
+ ) {
+ return null;
+ }
+
+ return makeCompositionDragData({
+ compositionFile: parsed.compositionFile,
+ compositionId: parsed.compositionId,
+ });
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/drag-and-drop/src/drag-data.ts b/packages/drag-and-drop/src/drag-data.ts
new file mode 100644
index 0000000000..6a7b818add
--- /dev/null
+++ b/packages/drag-and-drop/src/drag-data.ts
@@ -0,0 +1,376 @@
+import {
+ makeAssetDragData,
+ parseAssetDragData,
+ type AssetDragData,
+} from './asset-drag-data';
+import {
+ makeComponentDragData,
+ parseComponentDragData,
+ type ComponentDimensions,
+ type ComponentDragData,
+ type ComponentProp,
+} from './component-drag-data';
+import {
+ makeCompositionDragData,
+ parseCompositionDragData,
+ type CompositionDragData,
+} from './composition-drag-data';
+import {
+ getDragPreviewMetadata,
+ makeDragMimeType,
+ parseDragMimeType,
+ type AssetDragPreviewMetadata,
+ type ComponentDragPreviewMetadata,
+ type CompositionDragPreviewMetadata,
+ type DragPreviewMetadata,
+ type EffectDragPreviewMetadata,
+ type ElementDragPreviewMetadata,
+ type SfxDragPreviewMetadata,
+} from './drag-preview-metadata';
+import {
+ makeEffectDragData,
+ parseEffectDragData,
+ type EffectDragData,
+} from './effect-drag-data';
+import {
+ makeElementDragData,
+ parseElementDragData,
+ type ElementDragData,
+} from './element-drag-data';
+import {
+ makeSfxDragData,
+ parseSfxDragData,
+ type SfxDragData,
+} from './sfx-drag-data';
+
+export type MakeAssetDragDataInput = {
+ readonly type: 'asset';
+ readonly assetPath: string;
+ readonly width: number | null;
+ readonly height: number | null;
+ readonly durationInSeconds: number | null;
+};
+
+export type MakeComponentDragDataInput = {
+ readonly type: 'component';
+ readonly componentName: string;
+ readonly dimensions?: ComponentDimensions | null;
+ readonly importName: string;
+ readonly importPath: string;
+ readonly props: ComponentProp[];
+};
+
+export type MakeCompositionDragDataInput = {
+ readonly type: 'composition';
+ readonly compositionFile: string | null;
+ readonly compositionId: string;
+ readonly width: number | null;
+ readonly height: number | null;
+ readonly durationInFrames: number | null;
+};
+
+export type MakeEffectDragDataInput = EffectDragData['effect'] & {
+ readonly type: 'effect';
+};
+
+export type MakeElementDragDataInput = ElementDragData['element'] & {
+ readonly type: 'element';
+ readonly durationInFrames: number;
+};
+
+export type MakeSfxDragDataInput = SfxDragData['sfx'] & {
+ readonly type: 'sfx';
+};
+
+export type MakeDragDataInput =
+ | MakeAssetDragDataInput
+ | MakeComponentDragDataInput
+ | MakeCompositionDragDataInput
+ | MakeEffectDragDataInput
+ | MakeElementDragDataInput
+ | MakeSfxDragDataInput;
+
+export type ConstructedDragData<
+ TData extends RemotionDragData = RemotionDragData,
+> = {
+ readonly mimeType: string;
+ readonly payload: string;
+ readonly data: TData;
+};
+
+export type SerializedDragData = Pick<
+ ConstructedDragData,
+ 'mimeType' | 'payload'
+>;
+
+export type DragDataTransfer = {
+ readonly types: ArrayLike<string>;
+ readonly getData: (mimeType: string) => string;
+};
+
+export type RemotionDragData =
+ | AssetDragData
+ | ComponentDragData
+ | CompositionDragData
+ | EffectDragData
+ | ElementDragData
+ | SfxDragData;
+
+export type ParsedDragData =
+ | {
+ readonly type: 'asset';
+ readonly data: AssetDragData;
+ readonly preview: AssetDragPreviewMetadata;
+ }
+ | {
+ readonly type: 'component';
+ readonly data: ComponentDragData;
+ readonly preview: ComponentDragPreviewMetadata;
+ }
+ | {
+ readonly type: 'composition';
+ readonly data: CompositionDragData;
+ readonly preview: CompositionDragPreviewMetadata;
+ }
+ | {
+ readonly type: 'effect';
+ readonly data: EffectDragData;
+ readonly preview: EffectDragPreviewMetadata;
+ }
+ | {
+ readonly type: 'element';
+ readonly data: ElementDragData;
+ readonly preview: ElementDragPreviewMetadata;
+ }
+ | {
+ readonly type: 'sfx';
+ readonly data: SfxDragData;
+ readonly preview: SfxDragPreviewMetadata;
+ };
+
+const construct = <TData extends RemotionDragData>(
+ data: TData,
+ preview: DragPreviewMetadata,
+): ConstructedDragData<TData> => {
+ return {
+ mimeType: makeDragMimeType(preview),
+ payload: JSON.stringify(data),
+ data,
+ };
+};
+
+const makeCompositionPreview = (
+ input: MakeCompositionDragDataInput,
+): CompositionDragPreviewMetadata => {
+ if (
+ input.width === undefined ||
+ input.height === undefined ||
+ input.durationInFrames === undefined
+ ) {
+ throw new TypeError(
+ 'width, height, and durationInFrames must be set to a value or null',
+ );
+ }
+
+ if ((input.width === null) !== (input.height === null)) {
+ throw new TypeError(
+ 'width and height must either both be numbers or both be null',
+ );
+ }
+
+ return {
+ type: input.type,
+ width: input.width ?? undefined,
+ height: input.height ?? undefined,
+ durationInFrames: input.durationInFrames ?? undefined,
+ };
+};
+
+const makeAssetPreview = (
+ input: MakeAssetDragDataInput,
+): AssetDragPreviewMetadata => {
+ if (
+ input.width === undefined ||
+ input.height === undefined ||
+ input.durationInSeconds === undefined
+ ) {
+ throw new TypeError(
+ 'width, height, and durationInSeconds must be set to a value or null',
+ );
+ }
+
+ if ((input.width === null) !== (input.height === null)) {
+ throw new TypeError(
+ 'width and height must either both be numbers or both be null',
+ );
+ }
+
+ return {
+ type: input.type,
+ width: input.width ?? undefined,
+ height: input.height ?? undefined,
+ durationInSeconds: input.durationInSeconds ?? undefined,
+ };
+};
+
+type MakeDragData = {
+ (input: MakeAssetDragDataInput): ConstructedDragData<AssetDragData>;
+ (input: MakeComponentDragDataInput): ConstructedDragData<ComponentDragData>;
+ (
+ input: MakeCompositionDragDataInput,
+ ): ConstructedDragData<CompositionDragData>;
+ (input: MakeEffectDragDataInput): ConstructedDragData<EffectDragData>;
+ (input: MakeElementDragDataInput): ConstructedDragData<ElementDragData>;
+ (input: MakeSfxDragDataInput): ConstructedDragData<SfxDragData>;
+ (input: MakeDragDataInput): ConstructedDragData;
+};
+
+export const makeDragData = ((
+ input: MakeDragDataInput,
+): ConstructedDragData => {
+ switch (input.type) {
+ case 'asset':
+ return construct(
+ makeAssetDragData(input.assetPath),
+ makeAssetPreview(input),
+ );
+ case 'component':
+ return construct(
+ makeComponentDragData({
+ componentName: input.componentName,
+ dimensions: input.dimensions,
+ importName: input.importName,
+ importPath: input.importPath,
+ props: input.props,
+ }),
+ {
+ type: input.type,
+ ...(input.dimensions ?? {}),
+ },
+ );
+ case 'composition':
+ return construct(
+ makeCompositionDragData({
+ compositionFile: input.compositionFile,
+ compositionId: input.compositionId,
+ }),
+ makeCompositionPreview(input),
+ );
+ case 'effect':
+ return construct(
+ makeEffectDragData({
+ name: input.name,
+ importPath: input.importPath,
+ config: input.config,
+ }),
+ {type: input.type},
+ );
+ case 'element':
+ return construct(
+ makeElementDragData({
+ dependencies: input.dependencies,
+ dimensions: input.dimensions,
+ displayName: input.displayName,
+ slug: input.slug,
+ sourceCode: input.sourceCode,
+ }),
+ {
+ type: input.type,
+ ...(input.dimensions ?? {}),
+ durationInFrames: input.durationInFrames,
+ },
+ );
+ case 'sfx':
+ return construct(makeSfxDragData({name: input.name, url: input.url}), {
+ type: input.type,
+ });
+ default:
+ throw new TypeError('Unknown drag data type');
+ }
+}) as MakeDragData;
+
+const dimensionsMatch = (
+ preview: ComponentDragPreviewMetadata | ElementDragPreviewMetadata,
+ dimensions: ComponentDimensions | null | undefined,
+) => {
+ if (dimensions === null || dimensions === undefined) {
+ return preview.width === undefined && preview.height === undefined;
+ }
+
+ return (
+ preview.width === dimensions.width && preview.height === dimensions.height
+ );
+};
+
+export const parseDragData = (
+ source: SerializedDragData | DragDataTransfer,
+): ParsedDragData | null => {
+ const {mimeType, payload} =
+ 'types' in source
+ ? (() => {
+ const candidate = getDragPreviewMetadata(source.types);
+ if (candidate === null) {
+ return {mimeType: '', payload: ''};
+ }
+
+ return {
+ mimeType: candidate.mimeType,
+ payload: source.getData(candidate.mimeType),
+ };
+ })()
+ : source;
+ const preview = parseDragMimeType(mimeType);
+ if (preview === null) {
+ return null;
+ }
+
+ switch (preview.type) {
+ case 'asset': {
+ const data = parseAssetDragData(payload);
+
+ return data === null ? null : {type: preview.type, data, preview};
+ }
+
+ case 'component': {
+ const data = parseComponentDragData(payload);
+ if (
+ data === null ||
+ !dimensionsMatch(preview, data.component.dimensions)
+ ) {
+ return null;
+ }
+
+ return {type: preview.type, data, preview};
+ }
+
+ case 'composition': {
+ const data = parseCompositionDragData(payload);
+
+ return data === null ? null : {type: preview.type, data, preview};
+ }
+
+ case 'effect': {
+ const data = parseEffectDragData(payload);
+
+ return data === null ? null : {type: preview.type, data, preview};
+ }
+
+ case 'element': {
+ const data = parseElementDragData(payload);
+ if (!data || !dimensionsMatch(preview, data.element.dimensions)) {
+ return null;
+ }
+
+ return {type: preview.type, data, preview};
+ }
+
+ case 'sfx': {
+ const data = parseSfxDragData(payload);
+
+ return data === null ? null : {type: preview.type, data, preview};
+ }
+
+ default:
+ return null;
+ }
+};
diff --git a/packages/drag-and-drop/src/drag-preview-metadata.ts b/packages/drag-and-drop/src/drag-preview-metadata.ts
new file mode 100644
index 0000000000..d010d2c818
--- /dev/null
+++ b/packages/drag-and-drop/src/drag-preview-metadata.ts
@@ -0,0 +1,312 @@
+export const REMOTION_DRAG_MIME_TYPE = 'application/vnd.remotion.drag+json';
+const DRAG_MIME_VERSION = 1;
+const MAX_MIME_TYPE_LENGTH = 512;
+const MAX_DIMENSION = 100_000;
+const MAX_DURATION_IN_FRAMES = 100_000_000;
+const MAX_DURATION_IN_SECONDS = 31_536_000;
+
+type Dimensions = {
+ readonly width?: number;
+ readonly height?: number;
+};
+
+export type AssetDragPreviewMetadata = Dimensions & {
+ readonly type: 'asset';
+ readonly durationInSeconds?: number;
+};
+
+export type ComponentDragPreviewMetadata = Dimensions & {
+ readonly type: 'component';
+};
+
+export type CompositionDragPreviewMetadata = Dimensions & {
+ readonly type: 'composition';
+ readonly durationInFrames?: number;
+};
+
+export type EffectDragPreviewMetadata = {
+ readonly type: 'effect';
+};
+
+export type ElementDragPreviewMetadata = Dimensions & {
+ readonly type: 'element';
+ readonly durationInFrames: number;
+};
+
+export type SfxDragPreviewMetadata = {
+ readonly type: 'sfx';
+};
+
+export type DragPreviewMetadata =
+ | AssetDragPreviewMetadata
+ | ComponentDragPreviewMetadata
+ | CompositionDragPreviewMetadata
+ | EffectDragPreviewMetadata
+ | ElementDragPreviewMetadata
+ | SfxDragPreviewMetadata;
+
+export type DragPreviewMetadataWithMimeType = DragPreviewMetadata & {
+ readonly mimeType: string;
+};
+
+const isBoundedInteger = (value: number, max: number) => {
+ return Number.isInteger(value) && value > 0 && value <= max;
+};
+
+const isBoundedNumber = (value: number, max: number) => {
+ return Number.isFinite(value) && value > 0 && value <= max;
+};
+
+const assertDimensions = (metadata: DragPreviewMetadata) => {
+ if (!('width' in metadata) && !('height' in metadata)) {
+ return;
+ }
+
+ const {height, width} = metadata as Dimensions;
+ if (width === undefined && height === undefined) {
+ return;
+ }
+
+ if (width === undefined || height === undefined) {
+ throw new TypeError(
+ 'width and height must either both be set or both be omitted',
+ );
+ }
+
+ if (
+ !isBoundedNumber(width, MAX_DIMENSION) ||
+ !isBoundedNumber(height, MAX_DIMENSION)
+ ) {
+ throw new TypeError(
+ `width and height must be numbers between 0 and ${MAX_DIMENSION}`,
+ );
+ }
+};
+
+const assertDuration = (metadata: DragPreviewMetadata) => {
+ if (
+ metadata.type === 'asset' &&
+ metadata.durationInSeconds !== undefined &&
+ (!Number.isFinite(metadata.durationInSeconds) ||
+ metadata.durationInSeconds <= 0 ||
+ metadata.durationInSeconds > MAX_DURATION_IN_SECONDS)
+ ) {
+ throw new TypeError(
+ `durationInSeconds must be between 0 and ${MAX_DURATION_IN_SECONDS}`,
+ );
+ }
+
+ if (
+ metadata.type === 'composition' &&
+ metadata.durationInFrames !== undefined &&
+ !isBoundedInteger(metadata.durationInFrames, MAX_DURATION_IN_FRAMES)
+ ) {
+ throw new TypeError(
+ `durationInFrames must be an integer between 1 and ${MAX_DURATION_IN_FRAMES}`,
+ );
+ }
+
+ if (
+ metadata.type === 'element' &&
+ !isBoundedInteger(metadata.durationInFrames, MAX_DURATION_IN_FRAMES)
+ ) {
+ throw new TypeError(
+ `durationInFrames must be an integer between 1 and ${MAX_DURATION_IN_FRAMES}`,
+ );
+ }
+};
+
+const getDuration = (metadata: DragPreviewMetadata) => {
+ if (metadata.type === 'asset') {
+ return metadata.durationInSeconds;
+ }
+
+ if (metadata.type === 'composition' || metadata.type === 'element') {
+ return metadata.durationInFrames;
+ }
+
+ return undefined;
+};
+
+export const makeDragMimeType = (metadata: DragPreviewMetadata): string => {
+ assertDimensions(metadata);
+ assertDuration(metadata);
+
+ const segments = [
+ REMOTION_DRAG_MIME_TYPE,
+ `v=${DRAG_MIME_VERSION}`,
+ `type=${metadata.type}`,
+ ];
+
+ if ('width' in metadata && metadata.width !== undefined) {
+ segments.push(`width=${metadata.width}`, `height=${metadata.height}`);
+ }
+
+ const duration = getDuration(metadata);
+ if (duration !== undefined) {
+ segments.push(`duration=${duration}`);
+ }
+
+ return segments.join(';');
+};
+
+const parsePositiveInteger = (value: string, max: number): number | null => {
+ if (!/^[1-9]\d*$/.test(value)) {
+ return null;
+ }
+
+ const parsed = Number(value);
+ return isBoundedInteger(parsed, max) ? parsed : null;
+};
+
+const parsePositiveNumber = (value: string, max: number): number | null => {
+ if (!/^(?:[1-9]\d*|0\.\d+|[1-9]\d*\.\d+)$/.test(value)) {
+ return null;
+ }
+
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed > 0 && parsed <= max ? parsed : null;
+};
+
+export const parseDragMimeType = (
+ mimeType: string,
+): DragPreviewMetadata | null => {
+ if (
+ mimeType.length > MAX_MIME_TYPE_LENGTH ||
+ !mimeType.startsWith(`${REMOTION_DRAG_MIME_TYPE};`)
+ ) {
+ return null;
+ }
+
+ const segments = mimeType.split(';');
+ if (segments.shift() !== REMOTION_DRAG_MIME_TYPE) {
+ return null;
+ }
+
+ const values = new Map<string, string>();
+ for (const segment of segments) {
+ const separator = segment.indexOf('=');
+ if (separator === -1) {
+ return null;
+ }
+
+ const key = segment.slice(0, separator);
+ const value = segment.slice(separator + 1);
+ if (
+ !['v', 'type', 'width', 'height', 'duration'].includes(key) ||
+ value === '' ||
+ values.has(key)
+ ) {
+ return null;
+ }
+
+ values.set(key, value);
+ }
+
+ if (values.get('v') !== String(DRAG_MIME_VERSION)) {
+ return null;
+ }
+
+ const type = values.get('type');
+ if (
+ type !== 'asset' &&
+ type !== 'component' &&
+ type !== 'composition' &&
+ type !== 'effect' &&
+ type !== 'element' &&
+ type !== 'sfx'
+ ) {
+ return null;
+ }
+
+ const widthValue = values.get('width');
+ const heightValue = values.get('height');
+ if ((widthValue === undefined) !== (heightValue === undefined)) {
+ return null;
+ }
+
+ if (
+ (type === 'effect' || type === 'sfx') &&
+ (widthValue !== undefined || values.has('duration'))
+ ) {
+ return null;
+ }
+
+ const width =
+ widthValue === undefined
+ ? undefined
+ : parsePositiveNumber(widthValue, MAX_DIMENSION);
+ const height =
+ heightValue === undefined
+ ? undefined
+ : parsePositiveNumber(heightValue, MAX_DIMENSION);
+ if (width === null || height === null) {
+ return null;
+ }
+
+ const durationValue = values.get('duration');
+ if (
+ durationValue !== undefined &&
+ type !== 'asset' &&
+ type !== 'composition' &&
+ type !== 'element'
+ ) {
+ return null;
+ }
+
+ const duration =
+ durationValue === undefined
+ ? undefined
+ : type === 'asset'
+ ? parsePositiveNumber(durationValue, MAX_DURATION_IN_SECONDS)
+ : parsePositiveInteger(durationValue, MAX_DURATION_IN_FRAMES);
+ if (duration === null) {
+ return null;
+ }
+
+ const dimensions =
+ width === undefined ? {} : {width, height: height as number};
+ if (type === 'asset') {
+ return {
+ type,
+ ...dimensions,
+ ...(duration === undefined ? {} : {durationInSeconds: duration}),
+ };
+ }
+
+ if (type === 'element') {
+ if (duration === undefined) {
+ return null;
+ }
+
+ return {
+ type,
+ ...dimensions,
+ durationInFrames: duration,
+ };
+ }
+
+ if (type === 'composition') {
+ return {
+ type,
+ ...dimensions,
+ ...(duration === undefined ? {} : {durationInFrames: duration}),
+ };
+ }
+
+ return {type, ...dimensions};
+};
+
+export const getDragPreviewMetadata = (
+ mimeTypes: ArrayLike<string>,
+): DragPreviewMetadataWithMimeType | null => {
+ for (let index = 0; index < mimeTypes.length; index++) {
+ const mimeType = mimeTypes[index];
+ const parsed = parseDragMimeType(mimeType);
+ if (parsed !== null) {
+ return {...parsed, mimeType};
+ }
+ }
+
+ return null;
+};
diff --git a/packages/studio-shared/src/effect-drag-data.ts b/packages/drag-and-drop/src/effect-drag-data.ts
similarity index 51%
rename from packages/studio-shared/src/effect-drag-data.ts
rename to packages/drag-and-drop/src/effect-drag-data.ts
index d8854f4fb9..910e89178c 100644
--- a/packages/studio-shared/src/effect-drag-data.ts
+++ b/packages/drag-and-drop/src/effect-drag-data.ts
@@ -1,4 +1,4 @@
-export {EFFECT_DRAG_MIME_TYPE} from './drag-mime-types';
+import {isRecord} from './validation';
export type EffectDragData = {
type: 'remotion-effect';
@@ -10,22 +10,25 @@ export type EffectDragData = {
};
};
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
+export const makeEffectDragData = (
+ effect: EffectDragData['effect'],
+): EffectDragData => {
+ return {
+ type: 'remotion-effect',
+ version: 1,
+ effect,
+ };
};
export const parseEffectDragData = (value: string): EffectDragData | null => {
try {
const parsed: unknown = JSON.parse(value);
- if (!isRecord(parsed)) {
- return null;
- }
-
- if (parsed.type !== 'remotion-effect' || parsed.version !== 1) {
- return null;
- }
-
- if (!isRecord(parsed.effect)) {
+ if (
+ !isRecord(parsed) ||
+ parsed.type !== 'remotion-effect' ||
+ parsed.version !== 1 ||
+ !isRecord(parsed.effect)
+ ) {
return null;
}
@@ -38,15 +41,7 @@ export const parseEffectDragData = (value: string): EffectDragData | null => {
return null;
}
- return {
- type: 'remotion-effect',
- version: 1,
- effect: {
- name,
- importPath,
- config,
- },
- };
+ return makeEffectDragData({name, importPath, config});
} catch {
return null;
}
diff --git a/packages/studio-shared/src/element-drag-data.ts b/packages/drag-and-drop/src/element-drag-data.ts
similarity index 69%
rename from packages/studio-shared/src/element-drag-data.ts
rename to packages/drag-and-drop/src/element-drag-data.ts
index 9544f969df..f45915484d 100644
--- a/packages/studio-shared/src/element-drag-data.ts
+++ b/packages/drag-and-drop/src/element-drag-data.ts
@@ -2,9 +2,7 @@ import {
isComponentIdentifier,
type ComponentDimensions,
} from './component-drag-data';
-import {isValidPackageName} from './package-name';
-
-export {ELEMENT_DRAG_MIME_TYPE} from './drag-mime-types';
+import {isRecord, isValidPackageName} from './validation';
export type ElementDragData = {
type: 'remotion-element';
@@ -18,10 +16,6 @@ export type ElementDragData = {
};
};
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-};
-
export const isLowercaseElementFileName = (value: unknown): value is string => {
return (
typeof value === 'string' &&
@@ -62,59 +56,21 @@ export const makeElementFileNameFromSlug = (slug: string) => {
return isLowercaseElementFileName(fileName) ? fileName : null;
};
-const isDisplayName = (value: unknown): value is string => {
- return typeof value === 'string' && value.length > 0 && value.length < 120;
-};
-
-const isSourceCode = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value.trim().length > 0 &&
- value.length < 200000
- );
-};
-
-const isDependencies = (value: unknown): value is string[] => {
- return (
- Array.isArray(value) &&
- value.length <= 100 &&
- value.every(
- (dependency) =>
- typeof dependency === 'string' && isValidPackageName(dependency),
- )
- );
-};
-
-const isDimensions = (value: unknown): value is ComponentDimensions => {
- if (!isRecord(value)) {
- return false;
- }
-
- return (
- typeof value.width === 'number' &&
- Number.isFinite(value.width) &&
- value.width > 0 &&
- typeof value.height === 'number' &&
- Number.isFinite(value.height) &&
- value.height > 0
- );
-};
-
export const getElementComponentNameFromSourceCode = (sourceCode: string) => {
const componentNames = Array.from(
sourceCode.matchAll(
/export\s+(?:const|function)\s+([A-Z_$][A-Za-z0-9_$]*)\b/g,
),
).map((match) => match[1]);
-
const uniqueComponentNames = Array.from(new Set(componentNames));
if (uniqueComponentNames.length !== 1) {
return null;
}
- const [componentName] = uniqueComponentNames;
- return isComponentIdentifier(componentName) ? componentName : null;
+ return isComponentIdentifier(uniqueComponentNames[0])
+ ? uniqueComponentNames[0]
+ : null;
};
export const makeElementDragData = ({
@@ -137,31 +93,49 @@ export const makeElementDragData = ({
};
};
+const isDimensions = (value: unknown): value is ComponentDimensions => {
+ return (
+ isRecord(value) &&
+ typeof value.width === 'number' &&
+ Number.isFinite(value.width) &&
+ value.width > 0 &&
+ typeof value.height === 'number' &&
+ Number.isFinite(value.height) &&
+ value.height > 0
+ );
+};
+
export const parseElementDragData = (value: string): ElementDragData | null => {
try {
const parsed: unknown = JSON.parse(value);
- if (!isRecord(parsed)) {
- return null;
- }
-
- if (parsed.type !== 'remotion-element' || parsed.version !== 1) {
- return null;
- }
-
- if (!isRecord(parsed.element)) {
+ if (
+ !isRecord(parsed) ||
+ parsed.type !== 'remotion-element' ||
+ parsed.version !== 1 ||
+ !isRecord(parsed.element)
+ ) {
return null;
}
const {dependencies, dimensions, displayName, slug, sourceCode} =
parsed.element;
-
if (
!isSlug(slug) ||
- !isDisplayName(displayName) ||
- !isSourceCode(sourceCode) ||
+ typeof displayName !== 'string' ||
+ displayName.length === 0 ||
+ displayName.length >= 120 ||
+ typeof sourceCode !== 'string' ||
+ sourceCode.trim().length === 0 ||
+ sourceCode.length >= 200000 ||
getElementComponentNameFromSourceCode(sourceCode) === null ||
makeElementFileNameFromSlug(slug) === null ||
- (dependencies !== undefined && !isDependencies(dependencies)) ||
+ (dependencies !== undefined &&
+ (!Array.isArray(dependencies) ||
+ dependencies.length > 100 ||
+ !dependencies.every(
+ (dependency) =>
+ typeof dependency === 'string' && isValidPackageName(dependency),
+ ))) ||
(dimensions !== undefined &&
dimensions !== null &&
!isDimensions(dimensions))
diff --git a/packages/drag-and-drop/src/index.ts b/packages/drag-and-drop/src/index.ts
new file mode 100644
index 0000000000..71d3846c62
--- /dev/null
+++ b/packages/drag-and-drop/src/index.ts
@@ -0,0 +1,57 @@
+import {
+ areComponentProps,
+ isComponentIdentifier,
+ isComponentImportPath,
+} from './component-drag-data';
+import {makeDragData, parseDragData} from './drag-data';
+import {getDragPreviewMetadata} from './drag-preview-metadata';
+import {
+ getElementComponentNameFromSourceCode,
+ makeElementFileNameFromSlug,
+} from './element-drag-data';
+
+export type {AssetDragData} from './asset-drag-data';
+export type {
+ ComponentDimensions,
+ ComponentDragData,
+ ComponentProp,
+} from './component-drag-data';
+export type {CompositionDragData} from './composition-drag-data';
+export type {
+ ConstructedDragData,
+ DragDataTransfer,
+ MakeAssetDragDataInput,
+ MakeComponentDragDataInput,
+ MakeCompositionDragDataInput,
+ MakeDragDataInput,
+ MakeEffectDragDataInput,
+ MakeElementDragDataInput,
+ MakeSfxDragDataInput,
+ ParsedDragData,
+ RemotionDragData,
+ SerializedDragData,
+} from './drag-data';
+export type {
+ AssetDragPreviewMetadata,
+ ComponentDragPreviewMetadata,
+ CompositionDragPreviewMetadata,
+ DragPreviewMetadata,
+ DragPreviewMetadataWithMimeType,
+ EffectDragPreviewMetadata,
+ ElementDragPreviewMetadata,
+ SfxDragPreviewMetadata,
+} from './drag-preview-metadata';
+export type {EffectDragData} from './effect-drag-data';
+export type {ElementDragData} from './element-drag-data';
+export type {SfxDragData} from './sfx-drag-data';
+
+export const DragAndDropInternals = {
+ areComponentProps,
+ getDragPreviewMetadata,
+ getElementComponentNameFromSourceCode,
+ isComponentIdentifier,
+ isComponentImportPath,
+ makeDragData,
+ makeElementFileNameFromSlug,
+ parseDragData,
+};
diff --git a/packages/drag-and-drop/src/sfx-drag-data.ts b/packages/drag-and-drop/src/sfx-drag-data.ts
new file mode 100644
index 0000000000..c5ed8aeffc
--- /dev/null
+++ b/packages/drag-and-drop/src/sfx-drag-data.ts
@@ -0,0 +1,49 @@
+import {isRecord, isUrl} from './validation';
+
+export type SfxDragData = {
+ type: 'remotion-sfx';
+ version: 1;
+ sfx: {
+ name: string;
+ url: string;
+ };
+};
+
+export const makeSfxDragData = ({
+ name,
+ url,
+}: SfxDragData['sfx']): SfxDragData => {
+ return {
+ type: 'remotion-sfx',
+ version: 1,
+ sfx: {name, url},
+ };
+};
+
+export const parseSfxDragData = (value: string): SfxDragData | null => {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (
+ !isRecord(parsed) ||
+ parsed.type !== 'remotion-sfx' ||
+ parsed.version !== 1 ||
+ !isRecord(parsed.sfx)
+ ) {
+ return null;
+ }
+
+ const {name, url} = parsed.sfx;
+ if (
+ typeof name !== 'string' ||
+ name.length === 0 ||
+ typeof url !== 'string' ||
+ !isUrl(url)
+ ) {
+ return null;
+ }
+
+ return makeSfxDragData({name, url});
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/drag-and-drop/src/test/drag-data.test.ts b/packages/drag-and-drop/src/test/drag-data.test.ts
new file mode 100644
index 0000000000..1a7c988aa6
--- /dev/null
+++ b/packages/drag-and-drop/src/test/drag-data.test.ts
@@ -0,0 +1,241 @@
+import {expect, test} from 'bun:test';
+import {
+ DragAndDropInternals,
+ type MakeCompositionDragDataInput,
+ type MakeDragDataInput,
+ type MakeElementDragDataInput,
+ type MakeAssetDragDataInput,
+} from '../index';
+
+const inputs: MakeDragDataInput[] = [
+ {
+ type: 'asset',
+ assetPath: 'nested/image.png',
+ width: 1920,
+ height: 1080,
+ durationInSeconds: 5,
+ },
+ {
+ type: 'component',
+ componentName: 'Circle',
+ dimensions: {width: 200, height: 200},
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [{name: 'radius', value: 100}],
+ },
+ {
+ type: 'composition',
+ compositionFile: 'src/Root.tsx',
+ compositionId: 'MyVideo',
+ width: 1920,
+ height: 1080,
+ durationInFrames: 150,
+ },
+ {
+ type: 'effect',
+ name: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ config: {brightness: 1.2},
+ },
+ {
+ type: 'element',
+ dependencies: ['@remotion/google-fonts'],
+ slug: 'overlays/lower-third',
+ displayName: 'Lower Third',
+ sourceCode: 'export const LowerThird = () => null;',
+ dimensions: {width: 900, height: 260},
+ durationInFrames: 90,
+ },
+ {
+ type: 'sfx',
+ name: 'Whip',
+ url: 'https://remotion.media/whip.wav',
+ },
+];
+
+test('constructs and parses all drag data families', () => {
+ for (const input of inputs) {
+ const constructed = DragAndDropInternals.makeDragData(input);
+ const parsed = DragAndDropInternals.parseDragData(constructed);
+
+ expect(parsed?.type).toBe(input.type);
+ expect(constructed.mimeType).toStartWith(
+ 'application/vnd.remotion.drag+json;v=1;type=',
+ );
+ expect(JSON.parse(constructed.payload)).toBeObject();
+ }
+});
+
+test('puts preview metadata in the same MIME type as the payload', () => {
+ const constructed = DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: 'src/Root.tsx',
+ compositionId: 'MyVideo',
+ width: 1920,
+ height: 1080,
+ durationInFrames: 150,
+ });
+
+ expect(constructed.mimeType).toBe(
+ 'application/vnd.remotion.drag+json;v=1;type=composition;width=1920;height=1080;duration=150',
+ );
+ expect(
+ DragAndDropInternals.getDragPreviewMetadata([
+ 'text/plain',
+ constructed.mimeType,
+ ]),
+ ).toEqual({
+ type: 'composition',
+ mimeType: constructed.mimeType,
+ width: 1920,
+ height: 1080,
+ durationInFrames: 150,
+ });
+ expect(DragAndDropInternals.parseDragData(constructed)).toEqual({
+ type: 'composition',
+ data: {
+ type: 'remotion-composition',
+ version: 1,
+ compositionFile: 'src/Root.tsx',
+ compositionId: 'MyVideo',
+ },
+ preview: {
+ type: 'composition',
+ width: 1920,
+ height: 1080,
+ durationInFrames: 150,
+ },
+ });
+});
+
+test('accepts explicit null composition metadata', () => {
+ const constructed = DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: null,
+ compositionId: 'UnresolvedVideo',
+ width: null,
+ height: null,
+ durationInFrames: null,
+ });
+
+ expect(constructed.mimeType).toBe(
+ 'application/vnd.remotion.drag+json;v=1;type=composition',
+ );
+ expect(DragAndDropInternals.parseDragData(constructed)?.preview).toEqual({
+ type: 'composition',
+ });
+ expect(() =>
+ DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: null,
+ compositionId: 'MissingMetadata',
+ } as MakeCompositionDragDataInput),
+ ).toThrow('must be set to a value or null');
+ expect(() =>
+ DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: null,
+ compositionId: 'PartiallyResolvedDimensions',
+ width: 1920,
+ height: null,
+ durationInFrames: null,
+ }),
+ ).toThrow('must either both be numbers or both be null');
+});
+
+test('requires asset metadata and accepts explicit null values', () => {
+ const constructed = DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: 'unresolved.png',
+ width: null,
+ height: null,
+ durationInSeconds: null,
+ });
+
+ expect(constructed.mimeType).toBe(
+ 'application/vnd.remotion.drag+json;v=1;type=asset',
+ );
+ expect(DragAndDropInternals.parseDragData(constructed)?.preview).toEqual({
+ type: 'asset',
+ });
+ expect(() =>
+ DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: 'missing-metadata.png',
+ } as MakeAssetDragDataInput),
+ ).toThrow('must be set to a value or null');
+ expect(() =>
+ DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: 'partially-resolved.png',
+ width: 1920,
+ height: null,
+ durationInSeconds: null,
+ }),
+ ).toThrow('must either both be numbers or both be null');
+});
+
+test('requires a duration for element drags', () => {
+ const constructed = DragAndDropInternals.makeDragData({
+ type: 'element',
+ dependencies: [],
+ slug: 'titles/lower-third',
+ displayName: 'Lower Third',
+ sourceCode: 'export const LowerThird = () => null;',
+ dimensions: null,
+ durationInFrames: 90,
+ });
+
+ expect(constructed.mimeType).toContain(';duration=90');
+ expect(
+ DragAndDropInternals.parseDragData({
+ mimeType: 'application/vnd.remotion.drag+json;v=1;type=element',
+ payload: constructed.payload,
+ }),
+ ).toBe(null);
+ expect(() =>
+ DragAndDropInternals.makeDragData({
+ type: 'element',
+ dependencies: [],
+ slug: 'titles/lower-third',
+ displayName: 'Lower Third',
+ sourceCode: 'export const LowerThird = () => null;',
+ dimensions: null,
+ } as unknown as MakeElementDragDataInput),
+ ).toThrow('durationInFrames must be an integer');
+});
+
+test('rejects malformed and mismatched drag data', () => {
+ expect(
+ DragAndDropInternals.parseDragData({
+ mimeType:
+ 'application/vnd.remotion.drag+json;v=1;type=component;width=10;height=10',
+ payload: JSON.stringify({
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName: 'Circle',
+ dimensions: {width: 20, height: 20},
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ },
+ }),
+ }),
+ ).toBe(null);
+
+ const invalidMimeTypes = [
+ 'application/vnd.remotion.drag+json;v=2;type=composition',
+ 'application/vnd.remotion.drag+json;v=1;type=unknown',
+ 'application/vnd.remotion.drag+json;v=1;type=element;width=1920',
+ 'application/vnd.remotion.drag+json;v=1;type=effect;duration=10',
+ 'application/vnd.remotion.drag+json;v=1;type=composition;secret=value',
+ ];
+
+ for (const mimeType of invalidMimeTypes) {
+ expect(DragAndDropInternals.getDragPreviewMetadata([mimeType])).toBe(null);
+ expect(DragAndDropInternals.parseDragData({mimeType, payload: '{}'})).toBe(
+ null,
+ );
+ }
+});
diff --git a/packages/drag-and-drop/src/validation.ts b/packages/drag-and-drop/src/validation.ts
new file mode 100644
index 0000000000..a7ddf29885
--- /dev/null
+++ b/packages/drag-and-drop/src/validation.ts
@@ -0,0 +1,97 @@
+export const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+};
+
+export const isUrl = (value: string): boolean => {
+ try {
+ const parsed = new URL(value);
+ return parsed.href.length > 0;
+ } catch {
+ return false;
+ }
+};
+
+const nodeBuiltinPackages = new Set([
+ 'assert',
+ 'async_hooks',
+ 'buffer',
+ 'child_process',
+ 'cluster',
+ 'console',
+ 'constants',
+ 'crypto',
+ 'dgram',
+ 'diagnostics_channel',
+ 'dns',
+ 'domain',
+ 'events',
+ 'fs',
+ 'http',
+ 'http2',
+ 'https',
+ 'inspector',
+ 'module',
+ 'net',
+ 'os',
+ 'path',
+ 'perf_hooks',
+ 'process',
+ 'punycode',
+ 'querystring',
+ 'readline',
+ 'repl',
+ 'sea',
+ 'sqlite',
+ 'stream',
+ 'string_decoder',
+ 'sys',
+ 'test',
+ 'timers',
+ 'tls',
+ 'trace_events',
+ 'tty',
+ 'url',
+ 'util',
+ 'v8',
+ 'vm',
+ 'wasi',
+ 'worker_threads',
+ 'zlib',
+]);
+
+const scopedPackagePattern = /^(?:@([^/]+?)\/)?([^/]+?)$/;
+const reservedPackageNames = new Set(['node_modules', 'favicon.ico']);
+
+export const isValidPackageName = (packageName: string): boolean => {
+ if (
+ packageName.length === 0 ||
+ packageName.length > 214 ||
+ packageName.startsWith('.') ||
+ packageName.startsWith('_') ||
+ packageName.startsWith('-') ||
+ packageName.trim() !== packageName ||
+ packageName.toLowerCase() !== packageName ||
+ reservedPackageNames.has(packageName) ||
+ nodeBuiltinPackages.has(packageName) ||
+ /[~'!()*]/.test(packageName.split('/').at(-1) ?? '')
+ ) {
+ return false;
+ }
+
+ if (encodeURIComponent(packageName) === packageName) {
+ return true;
+ }
+
+ const match = packageName.match(scopedPackagePattern);
+ if (!match) {
+ return false;
+ }
+
+ const [, scope, name] = match;
+ return (
+ scope !== undefined &&
+ name !== undefined &&
+ encodeURIComponent(scope) === scope &&
+ encodeURIComponent(name) === name
+ );
+};
diff --git a/packages/drag-and-drop/tsconfig.json b/packages/drag-and-drop/tsconfig.json
new file mode 100644
index 0000000000..e5c5f5163c
--- /dev/null
+++ b/packages/drag-and-drop/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "skipLibCheck": true,
+ "target": "ES2022",
+ "module": "es2020",
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "emitDeclarationOnly": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/example/package.json b/packages/example/package.json
index c664f673de..979df203aa 100644
--- a/packages/example/package.json
+++ b/packages/example/package.json
@@ -31,6 +31,7 @@
"render-transparent": "remotion render --image-format=png --pixel-format=yuva420p --codec=vp8 react-svg out/video.webm"
},
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"@mdx-js/loader": "2.3.0",
"@mdx-js/react": "2.3.0",
"@mediabunny/ac3": "catalog:",
diff --git a/packages/example/src/DragAndDrop/index.tsx b/packages/example/src/DragAndDrop/index.tsx
new file mode 100644
index 0000000000..7e6f3532d1
--- /dev/null
+++ b/packages/example/src/DragAndDrop/index.tsx
@@ -0,0 +1,63 @@
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
+import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+const payloads = [
+ DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: 'images/logo.png',
+ width: null,
+ height: null,
+ durationInSeconds: null,
+ }),
+ DragAndDropInternals.makeDragData({
+ type: 'component',
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [{name: 'radius', value: 100}],
+ }),
+ DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionId: 'MyVideo',
+ compositionFile: 'src/Root.tsx',
+ width: null,
+ height: null,
+ durationInFrames: null,
+ }),
+ DragAndDropInternals.makeDragData({
+ type: 'effect',
+ name: 'brightness',
+ importPath: '@remotion/effects/brightness',
+ config: {brightness: 1.2},
+ }),
+ DragAndDropInternals.makeDragData({
+ type: 'element',
+ dependencies: [],
+ slug: 'titles/lower-third',
+ displayName: 'Lower Third',
+ sourceCode: 'export const LowerThird = () => null;',
+ dimensions: {width: 900, height: 260},
+ durationInFrames: 90,
+ }),
+ DragAndDropInternals.makeDragData({
+ type: 'sfx',
+ name: 'Whip',
+ url: 'https://remotion.media/whip.wav',
+ }),
+];
+
+export const DragAndDropExample: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: '#0b0b0f',
+ color: 'white',
+ fontFamily: 'monospace',
+ padding: 40,
+ }}
+ >
+ <pre>{JSON.stringify(payloads, null, 2)}</pre>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 742a71737e..41bd341f6a 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -38,6 +38,7 @@ import {
DiscriminatedUnionSchemaTest,
discriminatedUnionRootSchema,
} from './DiscriminatedUnionSchemaTest';
+import {DragAndDropExample} from './DragAndDrop';
import {DynamicDuration, dynamicDurationSchema} from './DynamicDuration';
import {EasingVisualizer} from './EasingVisualizer/EasingVisualizer';
import {EffectCopySource, EffectCopyTarget} from './EffectCopyTestbed';
@@ -2780,6 +2781,14 @@ export const Index: React.FC = () => {
/>
</Folder>
<ChangingTrimBeforeValue />
+ <Composition
+ id="drag-and-drop-payloads"
+ component={DragAndDropExample}
+ width={1280}
+ height={720}
+ fps={30}
+ durationInFrames={30}
+ />
<Composition
id="browser-test"
component={BrowserTest}
diff --git a/packages/example/tsconfig.json b/packages/example/tsconfig.json
index 7a6eebe69f..f39db93212 100644
--- a/packages/example/tsconfig.json
+++ b/packages/example/tsconfig.json
@@ -42,6 +42,7 @@
{"path": "../media-parser"},
{"path": "../webcodecs"},
{"path": "../whisper-web"},
+ {"path": "../drag-and-drop"},
{"path": "../light-leaks"},
{"path": "../starburst"},
{"path": "../sfx"},
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index f513a76090..214d1bc277 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -23,6 +23,7 @@
"access": "public"
},
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"@babel/types": "7.24.0",
"@babel/parser": "7.24.1",
"@svgr/core": "8.1.0",
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 0bd21eb8f4..ddd98e34e2 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -16,9 +16,9 @@ import type {
ObjectProperty,
VariableDeclaration,
} from '@babel/types';
+import type {ComponentProp} from '@remotion/drag-and-drop';
import {
isUrl,
- type ComponentProp,
type InsertableCompositionElement,
type InsertableCompositionElementPosition,
} from '@remotion/studio-shared';
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index 69b1a030fe..a82a5a2239 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -1,9 +1,8 @@
import {existsSync, readFileSync} from 'node:fs';
import path from 'node:path';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import {RenderInternals} from '@remotion/renderer';
import {
- getElementComponentNameFromSourceCode,
- makeElementFileNameFromSlug,
type InsertElementRequest,
type InsertElementResponse,
type InsertableCompositionElementPosition,
@@ -89,7 +88,7 @@ const validateDimensions = (
};
const validateElement = (element: InsertElementRequest['element']) => {
- if (makeElementFileNameFromSlug(element.slug) === null) {
+ if (DragAndDropInternals.makeElementFileNameFromSlug(element.slug) === null) {
throw new Error(
'Element slug must produce a safe lowercase .tsx file name',
);
@@ -103,7 +102,11 @@ const validateElement = (element: InsertElementRequest['element']) => {
throw new Error('Unsupported Element source code');
}
- if (getElementComponentNameFromSourceCode(element.sourceCode) === null) {
+ if (
+ DragAndDropInternals.getElementComponentNameFromSourceCode(
+ element.sourceCode,
+ ) === null
+ ) {
throw new Error('Element source must export exactly one named component');
}
@@ -129,9 +132,10 @@ export const insertElementHandler: ApiHandler<
throw new Error('from must be a non-negative integer');
}
- const componentName = getElementComponentNameFromSourceCode(
- element.sourceCode,
- );
+ const componentName =
+ DragAndDropInternals.getElementComponentNameFromSourceCode(
+ element.sourceCode,
+ );
if (componentName === null) {
throw new Error(
'Element source must export exactly one named component',
@@ -154,7 +158,8 @@ export const insertElementHandler: ApiHandler<
);
}
- const derivedElementFileName = makeElementFileNameFromSlug(element.slug);
+ const derivedElementFileName =
+ DragAndDropInternals.makeElementFileNameFromSlug(element.slug);
if (derivedElementFileName === null) {
throw new Error(
'Element slug must produce a safe lowercase .tsx file name',
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.ts
index 2c7677ae23..6e9c06f531 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
@@ -1,9 +1,7 @@
import path from 'node:path';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import {RenderInternals} from '@remotion/renderer';
import {
- areComponentProps,
- isComponentIdentifier,
- isComponentImportPath,
isUrl,
type InsertJsxElementRequest,
type InsertJsxElementResponse,
@@ -120,19 +118,19 @@ const validateElement = (
}
if (element.type === 'component') {
- if (!isComponentIdentifier(element.componentName)) {
+ if (!DragAndDropInternals.isComponentIdentifier(element.componentName)) {
throw new Error('Unsupported component name');
}
- if (!isComponentIdentifier(element.importName)) {
+ if (!DragAndDropInternals.isComponentIdentifier(element.importName)) {
throw new Error('Unsupported component import name');
}
- if (!isComponentImportPath(element.importPath)) {
+ if (!DragAndDropInternals.isComponentImportPath(element.importPath)) {
throw new Error('Unsupported component import path');
}
- if (!areComponentProps(element.props)) {
+ if (!DragAndDropInternals.areComponentProps(element.props)) {
throw new Error('Unsupported component props');
}
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index 0a6057b0a2..3271937315 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -4,6 +4,7 @@ import type {IncomingMessage, ServerResponse} from 'node:http';
import path, {join} from 'node:path';
import {URLSearchParams} from 'node:url';
import {BundlerInternals} from '@remotion/bundler';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import type {LogLevel} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
import type {
@@ -14,7 +15,7 @@ import type {
RenderJob,
StudioRuntimeConfig,
} from '@remotion/studio-shared';
-import {getProjectName, parseElementDragData} from '@remotion/studio-shared';
+import {getProjectName} from '@remotion/studio-shared';
import {focusBrowserTab} from './better-opn';
import {getCompletedClientRenders} from './client-render-queue';
import {getFileSource} from './helpers/get-file-source';
@@ -206,15 +207,16 @@ const handleRequestElementInstall = async ({
try {
const body = await parseRequestBody(request);
- const parsed = parseElementDragData(
- JSON.stringify({
- type: 'remotion-element',
- version: 1,
- element: (body as {element?: unknown}).element,
- }),
- );
+ const {mimeType, payload} = body as {
+ mimeType?: unknown;
+ payload?: unknown;
+ };
+ const parsed =
+ typeof mimeType === 'string' && typeof payload === 'string'
+ ? DragAndDropInternals.parseDragData({mimeType, payload})
+ : null;
- if (parsed === null) {
+ if (parsed?.type !== 'element') {
response.writeHead(400);
response.end(
JSON.stringify({success: false, reason: 'Invalid Element payload'}),
@@ -255,7 +257,7 @@ const handleRequestElementInstall = async ({
createdAt: Date.now(),
compositionFile: target.compositionFile,
compositionId: target.compositionId,
- element: parsed.element,
+ element: parsed.data.element,
position: null,
};
diff --git a/packages/studio-server/tsconfig.json b/packages/studio-server/tsconfig.json
index 4d86dc110f..ec8b7b5a74 100644
--- a/packages/studio-server/tsconfig.json
+++ b/packages/studio-server/tsconfig.json
@@ -15,6 +15,9 @@
{
"path": "../core"
},
+ {
+ "path": "../drag-and-drop"
+ },
{
"path": "../media-utils"
},
diff --git a/packages/studio-shared/package.json b/packages/studio-shared/package.json
index 50c1411e9d..ea1bc83c18 100644
--- a/packages/studio-shared/package.json
+++ b/packages/studio-shared/package.json
@@ -20,6 +20,7 @@
"url": "https://github.com/remotion-dev/remotion/issues"
},
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"remotion": "workspace:*"
},
"devDependencies": {
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 27fbf301ae..ffbe5ce8c7 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -1,3 +1,4 @@
+import type {ComponentProp, ElementDragData} from '@remotion/drag-and-drop';
import type {
AudioCodec,
ChromeMode,
@@ -26,13 +27,11 @@ import type {
VideoConfigValues,
} from 'remotion';
import type {RecastCodemod, VisualControlChange} from './codemods';
-import type {ComponentProp} from './component-drag-data';
import type {
EffectClipboardParam,
EffectClipboardPasteType,
EffectClipboardSnapshot,
} from './effect-clipboard-data';
-import type {ElementDragData} from './element-drag-data';
import type {PackageManager} from './package-manager';
import type {ProjectInfo} from './project-info';
import type {
diff --git a/packages/studio-shared/src/asset-drag-data.ts b/packages/studio-shared/src/asset-drag-data.ts
deleted file mode 100644
index 47127a5427..0000000000
--- a/packages/studio-shared/src/asset-drag-data.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-export {ASSET_DRAG_MIME_TYPE} from './drag-mime-types';
-
-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/composition-drag-data.ts b/packages/studio-shared/src/composition-drag-data.ts
index b4b23abd17..bdaa2e32dd 100644
--- a/packages/studio-shared/src/composition-drag-data.ts
+++ b/packages/studio-shared/src/composition-drag-data.ts
@@ -1,62 +1,6 @@
+import type {CompositionDragData} from '@remotion/drag-and-drop';
import type {SymbolicatedStackFrame} from './stack-types';
-export {COMPOSITION_DRAG_MIME_TYPE} from './drag-mime-types';
-
-export type CompositionDragData = {
- type: 'remotion-composition';
- version: 1;
- compositionId: string;
- compositionFile: string | null;
-};
-
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-};
-
-const isCompositionId = (value: unknown): value is string => {
- return (
- typeof value === 'string' &&
- value.length > 0 &&
- value.length < 500 &&
- /^([a-zA-Z0-9-\u4E00-\u9FFF])+$/.test(value)
- );
-};
-
-const hasParentDirectorySegment = (value: string) => {
- return value.split('/').includes('..');
-};
-
-const isCompositionFile = (value: unknown): value is string | null => {
- if (value === null) {
- return true;
- }
-
- return (
- typeof value === 'string' &&
- value.length > 0 &&
- value.length < 2000 &&
- !value.includes('\0') &&
- !value.includes('\\') &&
- !value.startsWith('/') &&
- !hasParentDirectorySegment(value)
- );
-};
-
-export const makeCompositionDragData = ({
- compositionFile,
- compositionId,
-}: {
- compositionFile: string | null;
- compositionId: string;
-}): CompositionDragData => {
- return {
- type: 'remotion-composition',
- version: 1,
- compositionFile,
- compositionId,
- };
-};
-
export const compositionDragDataToSymbolicatedStack = (
dragData: CompositionDragData,
): SymbolicatedStackFrame | null => {
@@ -72,32 +16,3 @@ export const compositionDragDataToSymbolicatedStack = (
originalScriptCode: null,
};
};
-
-export const parseCompositionDragData = (
- value: string,
-): CompositionDragData | null => {
- try {
- const parsed: unknown = JSON.parse(value);
- if (!isRecord(parsed)) {
- return null;
- }
-
- if (parsed.type !== 'remotion-composition' || parsed.version !== 1) {
- return null;
- }
-
- if (
- !isCompositionId(parsed.compositionId) ||
- !isCompositionFile(parsed.compositionFile)
- ) {
- return null;
- }
-
- return makeCompositionDragData({
- compositionFile: parsed.compositionFile,
- compositionId: parsed.compositionId,
- });
- } catch {
- return null;
- }
-};
diff --git a/packages/studio-shared/src/drag-mime-types.ts b/packages/studio-shared/src/drag-mime-types.ts
deleted file mode 100644
index 3b6c2c58df..0000000000
--- a/packages/studio-shared/src/drag-mime-types.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export const ASSET_DRAG_MIME_TYPE = 'application/vnd.remotion.asset+json';
-export const COMPONENT_DRAG_MIME_TYPE =
- 'application/vnd.remotion.component+json';
-export const COMPOSITION_DRAG_MIME_TYPE =
- 'application/vnd.remotion.composition+json';
-export const EFFECT_DRAG_MIME_TYPE = 'application/vnd.remotion.effect+json';
-export const ELEMENT_DRAG_MIME_TYPE = 'application/vnd.remotion.element+json';
-export const SFX_DRAG_MIME_TYPE = 'application/vnd.remotion.sfx+json';
-
-export const REMOTION_DRAG_MIME_TYPES = [
- ASSET_DRAG_MIME_TYPE,
- COMPONENT_DRAG_MIME_TYPE,
- COMPOSITION_DRAG_MIME_TYPE,
- EFFECT_DRAG_MIME_TYPE,
- ELEMENT_DRAG_MIME_TYPE,
- SFX_DRAG_MIME_TYPE,
-] as const;
-
-export type RemotionDragMimeType = (typeof REMOTION_DRAG_MIME_TYPES)[number];
-
-export const isRemotionDragMimeType = (
- type: string,
-): type is RemotionDragMimeType => {
- return REMOTION_DRAG_MIME_TYPES.some((mimeType) => mimeType === type);
-};
diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.ts
index 8f629da039..18618d4089 100644
--- a/packages/studio-shared/src/effect-catalog.ts
+++ b/packages/studio-shared/src/effect-catalog.ts
@@ -1,4 +1,4 @@
-import type {EffectDragData} from './effect-drag-data';
+import type {EffectDragData} from '@remotion/drag-and-drop';
export type EffectCatalogItem = {
readonly id: string;
@@ -44,16 +44,6 @@ export const getEffectPreviewAlt = (item: EffectCatalogItem) => {
return `${effectName} effect preview`;
};
-export const makeEffectDragDataFromCatalogItem = (
- item: EffectCatalogItem,
-): EffectDragData => {
- return {
- type: 'remotion-effect',
- version: 1,
- effect: item.effect,
- };
-};
-
export const getEffectCatalogCategories = (
items: readonly EffectCatalogItem[],
): readonly EffectCatalogCategory[] => {
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index aa481cba2a..b23210009e 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -118,31 +118,8 @@ export {
type AddSequenceKeyframe,
type KeyframeSettings,
} from './api-requests';
-export {
- ASSET_DRAG_MIME_TYPE,
- makeAssetDragData,
- parseAssetDragData,
- type AssetDragData,
-} from './asset-drag-data';
export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';
-export {
- COMPONENT_DRAG_MIME_TYPE,
- areComponentProps,
- isComponentIdentifier,
- isComponentImportPath,
- makeComponentDragData,
- parseComponentDragData,
- type ComponentDimensions,
- type ComponentDragData,
- type ComponentProp,
-} from './component-drag-data';
-export {
- COMPOSITION_DRAG_MIME_TYPE,
- compositionDragDataToSymbolicatedStack,
- makeCompositionDragData,
- parseCompositionDragData,
- type CompositionDragData,
-} from './composition-drag-data';
+export {compositionDragDataToSymbolicatedStack} from './composition-drag-data';
export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';
export {
detectFileType,
@@ -151,11 +128,6 @@ export {
type FileType,
type ImageFileType,
} from './detect-file-type';
-export {
- REMOTION_DRAG_MIME_TYPES,
- isRemotionDragMimeType,
- type RemotionDragMimeType,
-} from './drag-mime-types';
export {
parseEasingClipboardData,
parseEasingClipboardDataResult,
@@ -169,7 +141,6 @@ export {
getEffectDocumentationPath,
getEffectPreviewAlt,
getEffectPreviewSource,
- makeEffectDragDataFromCatalogItem,
type EffectCatalogCategory,
type EffectCatalogItem,
} from './effect-catalog';
@@ -193,20 +164,6 @@ export {
type EffectPropClipboardData,
type EffectPropClipboardDataParseResult,
} from './effect-clipboard-data';
-export {
- EFFECT_DRAG_MIME_TYPE,
- parseEffectDragData,
- type EffectDragData,
-} from './effect-drag-data';
-export {
- ELEMENT_DRAG_MIME_TYPE,
- getElementComponentNameFromSourceCode,
- isLowercaseElementFileName,
- makeElementDragData,
- makeElementFileNameFromSlug,
- parseElementDragData,
- type ElementDragData,
-} from './element-drag-data';
export {EventSourceEvent} from './event-source-event';
export {formatBytes} from './format-bytes';
export {getAllSchemaKeys, getAssetSchemaKeys} from './get-all-keys';
@@ -311,11 +268,6 @@ export type {
SchemaFieldInfo,
SequenceControls,
} from './schema-field-info';
-export {
- SFX_DRAG_MIME_TYPE,
- parseSfxDragData,
- type SfxDragData,
-} from './sfx-drag-data';
export {
ScriptLine,
SomeStackFrame,
diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.ts
index fcbe236ac4..10bbc38b0d 100644
--- a/packages/studio-shared/src/package-info.ts
+++ b/packages/studio-shared/src/package-info.ts
@@ -93,6 +93,7 @@ export const packages = [
'remotion-media',
'web-renderer',
'design',
+ 'drag-and-drop',
'light-leaks',
'rough-notation',
'starburst',
@@ -236,6 +237,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {
'remotion-media': null,
'web-renderer': 'Render videos in the browser',
design: 'Design system',
+ 'drag-and-drop': 'Construct and parse drag-and-drop payloads for Remotion',
'light-leaks': 'Light leak effects for Remotion',
'rough-notation': 'Rough annotation primitives for Remotion',
'player-a11y': 'Internal accessibility wrapper around @remotion/player',
@@ -339,6 +341,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {
'remotion-media': false,
'web-renderer': false,
design: false,
+ 'drag-and-drop': true,
'light-leaks': true,
'rough-notation': true,
starburst: true,
@@ -445,6 +448,7 @@ export const apiDocs: {[key in Pkgs]: string | null} = {
media: 'https://remotion.dev/docs/media',
'web-renderer': 'https://www.remotion.dev/docs/web-renderer/',
design: 'https://www.remotion.dev/design',
+ 'drag-and-drop': 'https://www.remotion.dev/docs/drag-and-drop',
'light-leaks': 'https://www.remotion.dev/docs/light-leaks',
'rough-notation': 'https://www.remotion.dev/docs/rough-notation',
starburst: 'https://www.remotion.dev/docs/starburst',
diff --git a/packages/studio-shared/src/sfx-drag-data.ts b/packages/studio-shared/src/sfx-drag-data.ts
deleted file mode 100644
index 6c6b0e06ba..0000000000
--- a/packages/studio-shared/src/sfx-drag-data.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import {isUrl} from './url';
-
-export {SFX_DRAG_MIME_TYPE} from './drag-mime-types';
-
-export type SfxDragData = {
- type: 'remotion-sfx';
- version: 1;
- sfx: {
- name: string;
- url: string;
- };
-};
-
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-};
-
-export const parseSfxDragData = (value: string): SfxDragData | null => {
- try {
- const parsed: unknown = JSON.parse(value);
- if (!isRecord(parsed)) {
- return null;
- }
-
- if (parsed.type !== 'remotion-sfx' || parsed.version !== 1) {
- return null;
- }
-
- if (!isRecord(parsed.sfx)) {
- return null;
- }
-
- const {name, url} = parsed.sfx;
- if (
- typeof name !== 'string' ||
- name.length === 0 ||
- typeof url !== 'string' ||
- !isUrl(url)
- ) {
- return null;
- }
-
- return {
- type: 'remotion-sfx',
- version: 1,
- sfx: {
- name,
- url,
- },
- };
- } catch {
- return null;
- }
-};
diff --git a/packages/studio-shared/src/test/asset-drag-data.test.ts b/packages/studio-shared/src/test/asset-drag-data.test.ts
index 4775289818..b0ab8a137c 100644
--- a/packages/studio-shared/src/test/asset-drag-data.test.ts
+++ b/packages/studio-shared/src/test/asset-drag-data.test.ts
@@ -1,5 +1,28 @@
import {expect, test} from 'bun:test';
-import {makeAssetDragData, parseAssetDragData} from '../asset-drag-data';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
+
+const assetMimeType = DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: 'asset',
+ width: null,
+ height: null,
+ durationInSeconds: null,
+}).mimeType;
+const makeAssetDragData = (assetPath: string) =>
+ DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath,
+ width: null,
+ height: null,
+ durationInSeconds: null,
+ }).data;
+const parseAssetDragData = (payload: string) => {
+ const parsed = DragAndDropInternals.parseDragData({
+ mimeType: assetMimeType,
+ payload,
+ });
+ return parsed?.type === 'asset' ? parsed.data : null;
+};
test('parses asset drag data', () => {
expect(
diff --git a/packages/studio-shared/src/test/component-drag-data.test.ts b/packages/studio-shared/src/test/component-drag-data.test.ts
index 5caa1d6c1d..e0a3a6d7fe 100644
--- a/packages/studio-shared/src/test/component-drag-data.test.ts
+++ b/packages/studio-shared/src/test/component-drag-data.test.ts
@@ -1,8 +1,39 @@
import {expect, test} from 'bun:test';
import {
- makeComponentDragData,
- parseComponentDragData,
-} from '../component-drag-data';
+ DragAndDropInternals,
+ type MakeComponentDragDataInput,
+} from '@remotion/drag-and-drop';
+
+const makeComponentDragData = (
+ input: Omit<MakeComponentDragDataInput, 'type'>,
+) => DragAndDropInternals.makeDragData({type: 'component', ...input}).data;
+const parseComponentDragData = (payload: string) => {
+ let dimensions: MakeComponentDragDataInput['dimensions'];
+ try {
+ const candidate = JSON.parse(payload)?.component?.dimensions;
+ if (
+ typeof candidate?.width === 'number' &&
+ candidate.width > 0 &&
+ typeof candidate?.height === 'number' &&
+ candidate.height > 0
+ ) {
+ dimensions = candidate;
+ }
+ } catch {
+ // The unified parser handles the malformed payload below.
+ }
+
+ const {mimeType} = DragAndDropInternals.makeDragData({
+ type: 'component',
+ componentName: 'Test',
+ dimensions,
+ importName: 'Test',
+ importPath: 'test',
+ props: [],
+ });
+ const parsed = DragAndDropInternals.parseDragData({mimeType, payload});
+ return parsed?.type === 'component' ? parsed.data : null;
+};
test('parses component drag data', () => {
expect(
diff --git a/packages/studio-shared/src/test/composition-drag-data.test.ts b/packages/studio-shared/src/test/composition-drag-data.test.ts
index dc4619c6e3..f2fd7dcaef 100644
--- a/packages/studio-shared/src/test/composition-drag-data.test.ts
+++ b/packages/studio-shared/src/test/composition-drag-data.test.ts
@@ -1,9 +1,37 @@
import {expect, test} from 'bun:test';
-import {
- compositionDragDataToSymbolicatedStack,
- makeCompositionDragData,
- parseCompositionDragData,
-} from '../composition-drag-data';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
+import {compositionDragDataToSymbolicatedStack} from '../composition-drag-data';
+
+const compositionMimeType = DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: null,
+ compositionId: 'Test',
+ width: null,
+ height: null,
+ durationInFrames: null,
+}).mimeType;
+const makeCompositionDragData = ({
+ compositionFile,
+ compositionId,
+}: {
+ compositionFile: string | null;
+ compositionId: string;
+}) =>
+ DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile,
+ compositionId,
+ width: null,
+ height: null,
+ durationInFrames: null,
+ }).data;
+const parseCompositionDragData = (payload: string) => {
+ const parsed = DragAndDropInternals.parseDragData({
+ mimeType: compositionMimeType,
+ payload,
+ });
+ return parsed?.type === 'composition' ? parsed.data : null;
+};
test('parses composition drag data', () => {
expect(
diff --git a/packages/studio-shared/src/test/element-drag-data.test.ts b/packages/studio-shared/src/test/element-drag-data.test.ts
index c067a51209..74e1cb610a 100644
--- a/packages/studio-shared/src/test/element-drag-data.test.ts
+++ b/packages/studio-shared/src/test/element-drag-data.test.ts
@@ -1,9 +1,5 @@
import {expect, test} from 'bun:test';
-import {
- makeElementDragData,
- makeElementFileNameFromSlug,
- parseElementDragData,
-} from '../element-drag-data';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
const validElement = {
dependencies: ['@remotion/google-fonts'],
@@ -12,6 +8,47 @@ const validElement = {
sourceCode: 'export const LowerThird = () => null;',
dimensions: {width: 900, height: 260},
};
+const makeElementDragData = (
+ element:
+ | typeof validElement
+ | {
+ dependencies: string[];
+ slug: string;
+ displayName: string;
+ sourceCode: string;
+ dimensions: null;
+ },
+) =>
+ DragAndDropInternals.makeDragData({
+ type: 'element',
+ ...element,
+ durationInFrames: 120,
+ }).data;
+const parseElementDragData = (payload: string) => {
+ let dimensions: (typeof validElement)['dimensions'] | null = null;
+ try {
+ const candidate = JSON.parse(payload)?.element?.dimensions;
+ if (
+ typeof candidate?.width === 'number' &&
+ candidate.width > 0 &&
+ typeof candidate?.height === 'number' &&
+ candidate.height > 0
+ ) {
+ dimensions = candidate;
+ }
+ } catch {
+ // The unified parser handles the malformed payload below.
+ }
+
+ const {mimeType} = DragAndDropInternals.makeDragData({
+ type: 'element',
+ ...validElement,
+ dimensions,
+ durationInFrames: 120,
+ });
+ const parsed = DragAndDropInternals.parseDragData({mimeType, payload});
+ return parsed?.type === 'element' ? parsed.data : null;
+};
test('parses element drag data', () => {
expect(
@@ -55,11 +92,15 @@ test('accepts element drag data with null dimensions', () => {
});
test('derives element file name from slug', () => {
- expect(makeElementFileNameFromSlug('overlays/lower-third')).toBe(
- 'lower-third.element.tsx',
+ expect(
+ DragAndDropInternals.makeElementFileNameFromSlug('overlays/lower-third'),
+ ).toBe('lower-third.element.tsx');
+ expect(DragAndDropInternals.makeElementFileNameFromSlug('LowerThird')).toBe(
+ null,
);
- expect(makeElementFileNameFromSlug('LowerThird')).toBe(null);
- expect(makeElementFileNameFromSlug('overlays/../lower-third')).toBe(null);
+ expect(
+ DragAndDropInternals.makeElementFileNameFromSlug('overlays/../lower-third'),
+ ).toBe(null);
});
test('rejects invalid element drag data', () => {
diff --git a/packages/studio-shared/src/test/sfx-drag-data.test.ts b/packages/studio-shared/src/test/sfx-drag-data.test.ts
index 463c88a2a2..5e1f3ab36a 100644
--- a/packages/studio-shared/src/test/sfx-drag-data.test.ts
+++ b/packages/studio-shared/src/test/sfx-drag-data.test.ts
@@ -1,7 +1,20 @@
import {expect, test} from 'bun:test';
-import {parseSfxDragData, type SfxDragData} from '../sfx-drag-data';
+import {DragAndDropInternals, type SfxDragData} from '@remotion/drag-and-drop';
import {isUrl} from '../url';
+const sfxMimeType = DragAndDropInternals.makeDragData({
+ type: 'sfx',
+ name: 'Test',
+ url: 'https://remotion.media/test.wav',
+}).mimeType;
+const parseSfxDragData = (payload: string) => {
+ const parsed = DragAndDropInternals.parseDragData({
+ mimeType: sfxMimeType,
+ payload,
+ });
+ return parsed?.type === 'sfx' ? parsed.data : null;
+};
+
const validSfxDragData: SfxDragData = {
type: 'remotion-sfx',
version: 1,
diff --git a/packages/studio-shared/tsconfig.json b/packages/studio-shared/tsconfig.json
index ba4199362d..f17fb8c42a 100644
--- a/packages/studio-shared/tsconfig.json
+++ b/packages/studio-shared/tsconfig.json
@@ -8,6 +8,9 @@
},
"include": ["src"],
"references": [
+ {
+ "path": "../drag-and-drop"
+ },
{
"path": "../renderer"
}
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 0f776a26e8..d309805276 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -24,6 +24,7 @@
"react-dom": ">=16.8.0"
},
"dependencies": {
+ "@remotion/drag-and-drop": "workspace:*",
"semver": "7.5.3",
"remotion": "workspace:*",
"@remotion/canvas-capture": "workspace:*",
diff --git a/packages/studio/src/components/AssetSelectorItem.tsx b/packages/studio/src/components/AssetSelectorItem.tsx
index 96203498d0..aa083beaf5 100644
--- a/packages/studio/src/components/AssetSelectorItem.tsx
+++ b/packages/studio/src/components/AssetSelectorItem.tsx
@@ -1,4 +1,4 @@
-import {ASSET_DRAG_MIME_TYPE, makeAssetDragData} from '@remotion/studio-shared';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import React, {
useCallback,
useContext,
@@ -7,7 +7,7 @@ import React, {
useRef,
useState,
} from 'react';
-import {Internals, type StaticFile} from 'remotion';
+import {Internals, staticFile, type StaticFile} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {deleteStaticFile} from '../api/delete-static-file';
import {StudioServerConnectionCtx} from '../helpers/client-id';
@@ -32,6 +32,8 @@ import {pushUrl} from '../helpers/url-state';
import useAssetDragEvents, {
isFileDragEvent,
} from '../helpers/use-asset-drag-events';
+import {getCachedImageMetadata} from '../helpers/use-image-metadata';
+import {getCachedMediaMetadata} from '../helpers/use-media-metadata';
import {ClipboardIcon} from '../icons/clipboard';
import {CollapsedFolderIcon, ExpandedFolderIcon} from '../icons/folder';
import {ModalsContext} from '../state/modals';
@@ -355,12 +357,39 @@ const AssetSelectorItem: React.FC<{
setIsDragging(true);
e.dataTransfer.effectAllowed = 'copy';
- e.dataTransfer.setData(
- ASSET_DRAG_MIME_TYPE,
- JSON.stringify(makeAssetDragData(relativePath)),
- );
+ const src = staticFile(relativePath);
+ const imageMetadata =
+ previewFileType === 'image' ? getCachedImageMetadata(src) : null;
+ const mediaMetadata =
+ previewFileType === 'audio' || previewFileType === 'video'
+ ? getCachedMediaMetadata(src)
+ : null;
+ const width = imageMetadata?.width ?? mediaMetadata?.width ?? null;
+ const height = imageMetadata?.height ?? mediaMetadata?.height ?? null;
+ const hasDimensions =
+ width !== null &&
+ height !== null &&
+ Number.isInteger(width) &&
+ Number.isInteger(height) &&
+ width > 0 &&
+ height > 0;
+ const durationInSeconds =
+ mediaMetadata?.duration !== undefined &&
+ Number.isFinite(mediaMetadata.duration) &&
+ mediaMetadata.duration > 0
+ ? mediaMetadata.duration
+ : null;
+
+ const dragData = DragAndDropInternals.makeDragData({
+ type: 'asset',
+ assetPath: relativePath,
+ width: hasDimensions ? width : null,
+ height: hasDimensions ? height : null,
+ durationInSeconds,
+ });
+ e.dataTransfer.setData(dragData.mimeType, dragData.payload);
},
- [canDragAsset, relativePath],
+ [canDragAsset, previewFileType, relativePath],
);
const onDragEnd: React.DragEventHandler<HTMLDivElement> = useCallback(() => {
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index 62c179a5c9..da6a2b0866 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1,3 +1,4 @@
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
import type {Size} from '@remotion/player';
import type {ElementInstallRequest} from '@remotion/studio-shared';
import React, {
@@ -15,13 +16,18 @@ import {StudioServerConnectionCtx} from '../helpers/client-id';
import {getClipboardFigmaHtml} from '../helpers/clipboard-figma';
import {getClipboardImageFiles} from '../helpers/clipboard-images';
import {getClipboardSvgMarkup} from '../helpers/clipboard-svg';
-import {BACKGROUND} from '../helpers/colors';
+import {
+ BACKGROUND,
+ BORDER_TIMELINE_DROP_BLUE,
+ TIMELINE_DROP_BLUE_ALPHA_16,
+} from '../helpers/colors';
import type {AssetMetadata} from '../helpers/get-asset-metadata';
import {getAssetMetadata} from '../helpers/get-asset-metadata';
import {
applyZoomAroundFocalPoint,
getCenterPointWhileScrolling,
getEffectiveTranslation,
+ getUnboundedCenterPointWhileScrolling,
} from '../helpers/get-effective-translation';
import {getMissingPackages} from '../helpers/install-required-package';
import {useCachedCompositionComponentInfo} from '../helpers/open-in-editor';
@@ -38,8 +44,14 @@ import {
} from '../helpers/use-keybinding';
import {canvasRef} from '../state/canvas-ref';
import {EditorShowGuidesContext} from '../state/editor-guides';
+import {EditorSnappingContext} from '../state/editor-snapping';
import {EditorZoomGesturesContext} from '../state/editor-zoom-gestures';
import {callApi} from './call-api';
+import {
+ getCompositionDropPreviewBox,
+ snapCompositionDropPosition,
+ type CompositionDropPreview,
+} from './composition-drop-preview';
import {useConfirmationDialog} from './ConfirmationDialog';
import {isSupportedDropEvent} from './drop-handler-data';
import EditorGuides from './EditorGuides';
@@ -160,6 +172,7 @@ const getDropPosition = ({
clientX,
clientY,
contentDimensions,
+ unbounded,
previewSize,
size,
}: {
@@ -167,6 +180,7 @@ const getDropPosition = ({
clientX: number;
clientY: number;
contentDimensions: {width: number; height: number} | 'none' | null;
+ unbounded: boolean;
previewSize: PreviewSize;
size: Size;
}): InsertElementDropPosition | null => {
@@ -181,7 +195,10 @@ const getDropPosition = ({
compositionWidth: contentDimensions.width,
previewSize: previewSize.size,
});
- const {centerX, centerY} = getCenterPointWhileScrolling({
+ const getCenterPoint = unbounded
+ ? getUnboundedCenterPointWhileScrolling
+ : getCenterPointWhileScrolling;
+ const {centerX, centerY} = getCenterPoint({
size,
clientX,
clientY,
@@ -237,6 +254,7 @@ export const Canvas: React.FC<{
const config = Internals.useUnsafeVideoConfig();
const areRulersVisible = useIsRulerVisible();
const {editorShowGuides} = useContext(EditorShowGuidesContext);
+ const {editorSnapping} = useContext(EditorSnappingContext);
const {compositions} = useContext(Internals.CompositionManager);
const {previewServerState, subscribeToEvent} = useContext(
StudioServerConnectionCtx,
@@ -246,6 +264,8 @@ export const Canvas: React.FC<{
? previewServerState.clientId
: null;
const [isAddingAsset, setIsAddingAsset] = useState(false);
+ const [compositionDropPreview, setCompositionDropPreview] =
+ useState<CompositionDropPreview | null>(null);
const [installingElementName, setInstallingElementName] = useState<
string | null
>(null);
@@ -942,10 +962,12 @@ export const Canvas: React.FC<{
const onDragOver = useCallback(
(event: DragEvent) => {
if (!isSupportedDropEvent(event) || !isDragEventInsideCanvas(event)) {
+ setCompositionDropPreview(null);
return;
}
if (!canDropAssets && !cannotAddSequence) {
+ setCompositionDropPreview(null);
return;
}
@@ -953,12 +975,117 @@ export const Canvas: React.FC<{
if (event.dataTransfer) {
event.dataTransfer.dropEffect = canDropAssets ? 'copy' : 'none';
}
+
+ if (
+ !canDropAssets ||
+ contentDimensions === null ||
+ contentDimensions === 'none'
+ ) {
+ setCompositionDropPreview(null);
+ return;
+ }
+
+ const metadata = DragAndDropInternals.getDragPreviewMetadata(
+ event.dataTransfer?.types ?? [],
+ );
+ if (
+ metadata?.type !== 'composition' ||
+ metadata.width === undefined ||
+ metadata.height === undefined
+ ) {
+ setCompositionDropPreview(null);
+ return;
+ }
+
+ let dropPosition = getDropPosition({
+ addFitPadding,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ contentDimensions,
+ unbounded: true,
+ previewSize,
+ size,
+ });
+ if (dropPosition === null) {
+ setCompositionDropPreview(null);
+ return;
+ }
+
+ const compositionDimensions = {
+ width: metadata.width,
+ height: metadata.height,
+ };
+ if (editorSnapping && !event.metaKey && !event.ctrlKey) {
+ dropPosition = snapCompositionDropPosition({
+ compositionDimensions,
+ destinationDimensions: contentDimensions,
+ dropPosition,
+ scale: calculateCanvasScale({
+ addFitPadding,
+ canvasSize: size,
+ compositionHeight: contentDimensions.height,
+ compositionWidth: contentDimensions.width,
+ previewSize: previewSize.size,
+ }),
+ });
+ }
+
+ setCompositionDropPreview((currentPreview) => {
+ if (
+ currentPreview?.compositionDimensions.width ===
+ compositionDimensions.width &&
+ currentPreview.compositionDimensions.height ===
+ compositionDimensions.height &&
+ currentPreview.dropPosition.centerX === dropPosition.centerX &&
+ currentPreview.dropPosition.centerY === dropPosition.centerY
+ ) {
+ return currentPreview;
+ }
+
+ return {
+ compositionDimensions,
+ dropPosition,
+ };
+ });
},
- [canDropAssets, cannotAddSequence],
+ [
+ addFitPadding,
+ canDropAssets,
+ cannotAddSequence,
+ contentDimensions,
+ editorSnapping,
+ previewSize,
+ size,
+ ],
);
+ const onDragLeave = useCallback((event: DragEvent) => {
+ const canvas = canvasRef.current;
+ if (canvas !== null) {
+ const rect = canvas.getBoundingClientRect();
+ if (
+ (event.clientX >= rect.left &&
+ event.clientX <= rect.right &&
+ event.clientY >= rect.top &&
+ event.clientY <= rect.bottom) ||
+ (event.relatedTarget instanceof Node &&
+ canvas.contains(event.relatedTarget))
+ ) {
+ return;
+ }
+ }
+
+ setCompositionDropPreview(null);
+ }, []);
+
+ const onDragEnd = useCallback(() => {
+ setCompositionDropPreview(null);
+ }, []);
+
const onDrop = useCallback(
async (event: DragEvent) => {
+ setCompositionDropPreview(null);
+
if (!isSupportedDropEvent(event) || !isDragEventInsideCanvas(event)) {
return;
}
@@ -995,14 +1122,46 @@ export const Canvas: React.FC<{
setIsAddingAsset(true);
try {
- const dropPosition = getDropPosition({
+ const metadata = DragAndDropInternals.getDragPreviewMetadata(
+ event.dataTransfer?.types ?? [],
+ );
+ const isComposition = metadata?.type === 'composition';
+ let dropPosition = getDropPosition({
addFitPadding,
clientX: event.clientX,
clientY: event.clientY,
contentDimensions,
+ unbounded: isComposition,
previewSize,
size,
});
+ if (
+ dropPosition !== null &&
+ isComposition &&
+ metadata.width !== undefined &&
+ metadata.height !== undefined &&
+ contentDimensions !== null &&
+ contentDimensions !== 'none' &&
+ editorSnapping &&
+ !event.metaKey &&
+ !event.ctrlKey
+ ) {
+ dropPosition = snapCompositionDropPosition({
+ compositionDimensions: {
+ width: metadata.width,
+ height: metadata.height,
+ },
+ destinationDimensions: contentDimensions,
+ dropPosition,
+ scale: calculateCanvasScale({
+ addFitPadding,
+ canvasSize: size,
+ compositionHeight: contentDimensions.height,
+ compositionWidth: contentDimensions.width,
+ previewSize: previewSize.size,
+ }),
+ });
+ }
await handleDrop({
chooseSvgImportMode,
@@ -1028,6 +1187,7 @@ export const Canvas: React.FC<{
config,
contentDimensions,
currentCompositionId,
+ editorSnapping,
previewSize,
size,
],
@@ -1142,13 +1302,17 @@ export const Canvas: React.FC<{
useEffect(() => {
document.addEventListener('dragover', onDragOver, {capture: true});
+ document.addEventListener('dragleave', onDragLeave, {capture: true});
+ document.addEventListener('dragend', onDragEnd, {capture: true});
document.addEventListener('drop', onDrop, {capture: true});
return () => {
document.removeEventListener('dragover', onDragOver, {capture: true});
+ document.removeEventListener('dragleave', onDragLeave, {capture: true});
+ document.removeEventListener('dragend', onDragEnd, {capture: true});
document.removeEventListener('drop', onDrop, {capture: true});
};
- }, [onDragOver, onDrop]);
+ }, [onDragEnd, onDragLeave, onDragOver, onDrop]);
useEffect(() => {
if (
@@ -1163,6 +1327,34 @@ export const Canvas: React.FC<{
return () => document.removeEventListener('paste', onPaste);
}, [canDropAssets, keybindings.isHighestContext, onPaste]);
+ const compositionDropPreviewStyle =
+ useMemo((): React.CSSProperties | null => {
+ if (
+ compositionDropPreview === null ||
+ contentDimensions === null ||
+ contentDimensions === 'none'
+ ) {
+ return null;
+ }
+
+ const box = getCompositionDropPreviewBox({
+ canvasSize: size,
+ destinationDimensions: contentDimensions,
+ preview: compositionDropPreview,
+ previewSize,
+ });
+
+ return {
+ ...box,
+ position: 'absolute',
+ boxSizing: 'border-box',
+ border: BORDER_TIMELINE_DROP_BLUE,
+ backgroundColor: TIMELINE_DROP_BLUE_ALPHA_16,
+ pointerEvents: 'none',
+ zIndex: 1,
+ };
+ }, [compositionDropPreview, contentDimensions, previewSize, size]);
+
return (
<>
<div ref={canvasRef} style={getContainerStyle(editorZoomGestures)}>
@@ -1175,6 +1367,13 @@ export const Canvas: React.FC<{
onRetryAssetMetadata={fetchMetadata}
/>
) : null}
+ {compositionDropPreviewStyle === null ? null : (
+ <div
+ className="css-reset"
+ data-testid="composition-drop-preview"
+ style={compositionDropPreviewStyle}
+ />
+ )}
{isFit ? null : (
<div style={resetZoom} className="css-reset">
<ResetZoomButton onClick={onReset} />
diff --git a/packages/studio/src/components/CompositionSelector.tsx b/packages/studio/src/components/CompositionSelector.tsx
index 884034bbba..21a0023c5d 100644
--- a/packages/studio/src/components/CompositionSelector.tsx
+++ b/packages/studio/src/components/CompositionSelector.tsx
@@ -1,8 +1,5 @@
-import {
- COMPOSITION_DRAG_MIME_TYPE,
- compositionDragDataToSymbolicatedStack,
- parseCompositionDragData,
-} from '@remotion/studio-shared';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
+import {compositionDragDataToSymbolicatedStack} from '@remotion/studio-shared';
import React, {
useCallback,
useContext,
@@ -273,9 +270,8 @@ export const CompositionSelector: React.FC = () => {
(event: React.DragEvent<HTMLElement>) => {
if (
window.remotion_isReadOnlyStudio ||
- !Array.from(event.dataTransfer.types).includes(
- COMPOSITION_DRAG_MIME_TYPE,
- )
+ DragAndDropInternals.getDragPreviewMetadata(event.dataTransfer.types)
+ ?.type !== 'composition'
) {
stopCompositionListAutoScroll();
return;
@@ -301,7 +297,8 @@ export const CompositionSelector: React.FC = () => {
const onRootDragOver = useCallback((event: React.DragEvent<HTMLElement>) => {
if (
window.remotion_isReadOnlyStudio ||
- !Array.from(event.dataTransfer.types).includes(COMPOSITION_DRAG_MIME_TYPE)
+ DragAndDropInternals.getDragPreviewMetadata(event.dataTransfer.types)
+ ?.type !== 'composition'
) {
return;
}
@@ -333,26 +330,27 @@ export const CompositionSelector: React.FC = () => {
return;
}
- const raw = event.dataTransfer.getData(COMPOSITION_DRAG_MIME_TYPE);
- const parsed = raw ? parseCompositionDragData(raw) : null;
- if (parsed === null) {
+ const parsed = DragAndDropInternals.parseDragData(event.dataTransfer);
+ if (parsed?.type !== 'composition') {
return;
}
+ const compositionDragData = parsed.data;
+
event.preventDefault();
event.stopPropagation();
stopCompositionListAutoScroll();
setRootDragHovered(false);
const composition = compositions.find(
- (c) => c.id === parsed.compositionId,
+ (c) => c.id === compositionDragData.compositionId,
);
if (!composition || composition.folderName === null) {
return;
}
const notification = showNotification(
- `Moving ${parsed.compositionId}...`,
+ `Moving ${compositionDragData.compositionId}...`,
null,
);
const controller = new AbortController();
@@ -361,18 +359,19 @@ export const CompositionSelector: React.FC = () => {
const result = await applyCodemod({
codemod: {
type: 'move-composition-to-folder',
- idToMove: parsed.compositionId,
+ idToMove: compositionDragData.compositionId,
folderName: null,
parentName: null,
},
dryRun: false,
signal: controller.signal,
- symbolicatedStack: compositionDragDataToSymbolicatedStack(parsed),
+ symbolicatedStack:
+ compositionDragDataToSymbolicatedStack(compositionDragData),
});
notification.replaceContent(
result.success
- ? `Moved ${parsed.compositionId} outside of folder`
+ ? `Moved ${compositionDragData.compositionId} outside of folder`
: result.reason,
result.success ? 2000 : 4000,
);
diff --git a/packages/studio/src/components/CompositionSelectorItem.tsx b/packages/studio/src/components/CompositionSelectorItem.tsx
index 025940ee04..2b33bf0d28 100644
--- a/packages/studio/src/components/CompositionSelectorItem.tsx
+++ b/packages/studio/src/components/CompositionSelectorItem.tsx
@@ -1,9 +1,5 @@
-import {
- COMPOSITION_DRAG_MIME_TYPE,
- compositionDragDataToSymbolicatedStack,
- makeCompositionDragData,
- parseCompositionDragData,
-} from '@remotion/studio-shared';
+import {DragAndDropInternals} from '@remotion/drag-and-drop';
+import {compositionDragDataToSymbolicatedStack} from '@remotion/studio-shared';
import type {DragEvent, KeyboardEvent, MouseEvent} from 'react';
import React, {
useCallback,
@@ -233,15 +229,15 @@ export const CompositionSelectorItem: React.FC<{
setIsDragging(true);
event.dataTransfer.effectAllowed = 'copyMove';
- event.dataTransfer.setData(
- COMPOSITION_DRAG_MIME_TYPE,
- JSON.stringify(
- makeCompositionDragData({
- compositionFile: resolvedLocation?.source ?? null,
- compositionId: item.composition.id,
- }),
- ),
- );
+ const dragData = DragAndDropInternals.makeDragData({
+ type: 'composition',
+ compositionFile: resolvedLocation?.source ?? null,
+ compositionId: item.composition.id,
+ width: item.composition.width ?? null,
+ height: item.composition.height ?? null,
+ durationInFrames: item.composition.durationInFrames ?? null,
+ });
+ event.dataTransfer.setData(dragData.mimeType, dragData.payload);
},
[item, resolvedLocation?.source],
);
@@ -254,9 +250,8 @@ export const CompositionSelectorItem: React.FC<{
if (
item.type !== 'folder' ||
window.remotion_isReadOnlyStudio ||
- !Array.from(event.dataTransfer.types).includes(
- COMPOSITION_DRAG_MIME_TYPE,
- )
+ DragAndDropInternals.getDragPreviewMetadata(event.dataTransfer.types)
+ ?.type !== 'composition'
) {
return;
}
@@ -279,9 +274,8 @@ export const CompositionSelectorItem: React.FC<{
if (
item.type !== 'folder' ||
window.remotion_isReadOnlyStudio ||
- !Array.from(event.dataTransfer.types).includes(
- COMPOSITION_DRAG_MIME_TYPE,
- )
+ DragAndDropInternals.getDragPreviewMetadata(event.dataTransfer.types)
+ ?.type !== 'composition'
) {
return;
}
@@ -300,12 +294,13 @@ export const CompositionSelectorItem: React.FC<{
return;
}
- const raw = event.dataTransfer.getData(COMPOSITION_DRAG_MIME_TYPE);
- const parsed = raw ? parseCompositionDragData(raw) : null;
- if (parsed === null) {
+ const parsed = DragAndDropInternals.parseDragData(event.dataTransfer);
+ if (parsed?.type !== 'composition') {
return;
}
+ const compositionDragData = parsed.data;
+
event.preventDefault();
event.stopPropagation();
clearRootDragHover();
@@ -314,7 +309,7 @@ export const CompositionSelectorItem: React.FC<{
const isAlreadyDirectChild = item.items.some((child) => {
return (
child.type === 'composition' &&
- child.composition.id === parsed.compositionId
+ child.composition.id === compositionDragData.compositionId
);
});
if (isAlreadyDirectChild) {
@@ -326,7 +321,7 @@ export const CompositionSelectorItem: React.FC<{
parentName: item.parentName,
});
const notification = showNotification(
- `Moving ${parsed.compositionId}...`,
+ `Moving ${compositionDragData.compositionId}...`,
null,
);
const controller = new AbortController();
@@ -335,18 +330,19 @@ export const CompositionSelectorItem: React.FC<{
const result = await applyCodemod({
codemod: {
type: 'move-composition-to-folder',
- idToMove: parsed.compositionId,
+ idToMove: compositionDragData.compositionId,
folderName: item.folderName,
parentName: item.parentName,
},
dryRun: false,
signal: controller.signal,
- symbolicatedStack: compositionDragDataToSymbolicatedStack(parsed),
+ symbolicatedStack:
+ compositionDragDataToSymbolicatedStack(compositionDragData),
});
notification.replaceContent(
result.success
- ? `Moved ${parsed.compositionId} to ${folderId}`
+ ? `Moved ${compositionDragData.compositionId} to ${folderId}`
: result.reason,
result.success ? 2000 : 4000,
);
diff --git a/packages/studio/src/components/composition-drop-preview.ts b/packages/studio/src/components/composition-drop-preview.ts
new file mode 100644
index 0000000000..295978216f
--- /dev/null
+++ b/packages/studio/src/components/composition-drop-preview.ts
@@ -0,0 +1,116 @@
+import type {PreviewSize} from 'remotion';
+import {calculateStudioScale} from '../helpers/studio-fit-padding';
+import {
+ getCompositionPositionForDrop,
+ type InsertElementDropPosition,
+} from './import-assets';
+import type {SelectedOutline} from './selected-outline-geometry';
+import {
+ findSelectedOutlineSnap,
+ getSelectedOutlineSnapTargets,
+} from './selected-outline-snap';
+
+type Dimensions = {
+ readonly width: number;
+ readonly height: number;
+};
+
+type CanvasSize = {
+ readonly width: number;
+ readonly height: number;
+};
+
+export type CompositionDropPreview = {
+ readonly compositionDimensions: Dimensions;
+ readonly dropPosition: InsertElementDropPosition;
+};
+
+export type CompositionDropPreviewBox = {
+ readonly left: number;
+ readonly top: number;
+ readonly width: number;
+ readonly height: number;
+};
+
+export const snapCompositionDropPosition = ({
+ compositionDimensions,
+ destinationDimensions,
+ dropPosition,
+ scale,
+}: {
+ readonly compositionDimensions: Dimensions;
+ readonly destinationDimensions: Dimensions;
+ readonly dropPosition: InsertElementDropPosition;
+ readonly scale: number;
+}): InsertElementDropPosition => {
+ const left = dropPosition.centerX - compositionDimensions.width / 2;
+ const top = dropPosition.centerY - compositionDimensions.height / 2;
+ const right = left + compositionDimensions.width;
+ const bottom = top + compositionDimensions.height;
+ const outline: SelectedOutline = {
+ key: 'composition-drop-preview',
+ dimensions: compositionDimensions,
+ points: [
+ {x: left * scale, y: top * scale},
+ {x: right * scale, y: top * scale},
+ {x: right * scale, y: bottom * scale},
+ {x: left * scale, y: bottom * scale},
+ ],
+ };
+ const snap = findSelectedOutlineSnap({
+ allowX: true,
+ allowY: true,
+ deltaX: 0,
+ deltaY: 0,
+ outlines: [outline],
+ scale,
+ targets: getSelectedOutlineSnapTargets({
+ compositionHeight: destinationDimensions.height,
+ compositionWidth: destinationDimensions.width,
+ guides: [],
+ }),
+ });
+
+ return {
+ centerX: dropPosition.centerX + (snap.snapOffsetX ?? 0),
+ centerY: dropPosition.centerY + (snap.snapOffsetY ?? 0),
+ };
+};
+
+export const getCompositionDropPreviewBox = ({
+ canvasSize,
+ destinationDimensions,
+ preview,
+ previewSize,
+}: {
+ readonly canvasSize: CanvasSize;
+ readonly destinationDimensions: Dimensions;
+ readonly preview: CompositionDropPreview;
+ readonly previewSize: PreviewSize;
+}): CompositionDropPreviewBox => {
+ const scale = calculateStudioScale({
+ canvasSize,
+ compositionHeight: destinationDimensions.height,
+ compositionWidth: destinationDimensions.width,
+ previewSize: previewSize.size,
+ });
+ const position = getCompositionPositionForDrop({
+ compositionDimensions: preview.compositionDimensions,
+ dropPosition: preview.dropPosition,
+ });
+ const contentLeft =
+ canvasSize.width / 2 -
+ (destinationDimensions.width * scale) / 2 -
+ previewSize.translation.x;
+ const contentTop =
+ canvasSize.height / 2 -
+ (destinationDimensions.height * scale) / 2 -
+ previewSize.translation.y;
+
+ return {
+ left: contentLeft + (position?.x ?? 0) * scale,
+ top: contentTop + (position?.y ?? 0) * scale,
+ width: preview.compositionDimensions.width * scale,
+ height: preview.compositionDimensions.height * scale,
+ };
+};
diff --git a/packages/studio/src/components/drop-handler-data.ts b/packages/studio/src/components/drop-handler-data.ts
index 97d99b5946..2d3698e673 100644
--- a/packages/studio/src/components/drop-handler-data.ts
+++ b/packages/studio/src/components/drop-handler-data.ts
@@ -1,50 +1,43 @@
import {
- ASSET_DRAG_MIME_TYPE,
- COMPONENT_DRAG_MIME_TYPE,
- COMPOSITION_DRAG_MIME_TYPE,
- ELEMENT_DRAG_MIME_TYPE,
- parseAssetDragData,
- parseComponentDragData,
- parseCompositionDragData,
- parseSfxDragData,
- SFX_DRAG_MIME_TYPE,
+ DragAndDropInternals,
type ComponentDragData,
type CompositionDragData,
-} from '@remotion/studio-shared';
+ type DragPreviewMetadata,
+} from '@remotion/drag-and-drop';
import {hasRemoteAssetDragData} from '../helpers/remote-asset-drag';
export const isFileDragEvent = (event: DragEvent): boolean => {
return Array.from(event.dataTransfer?.types ?? []).includes('Files');
};
-export const isAssetDragEvent = (event: DragEvent): boolean => {
- return Array.from(event.dataTransfer?.types ?? []).includes(
- ASSET_DRAG_MIME_TYPE,
+const isRemotionDragEvent = (
+ event: DragEvent,
+ type: DragPreviewMetadata['type'],
+) => {
+ return (
+ DragAndDropInternals.getDragPreviewMetadata(event.dataTransfer?.types ?? [])
+ ?.type === type
);
};
-export const isComponentDragEvent = (event: DragEvent): boolean => {
- return Array.from(event.dataTransfer?.types ?? []).includes(
- COMPONENT_DRAG_MIME_TYPE,
- );
+export const isAssetDragEvent = (event: DragEvent) => {
+ return isRemotionDragEvent(event, 'asset');
};
-export const isCompositionDragEvent = (event: DragEvent): boolean => {
- return Array.from(event.dataTransfer?.types ?? []).includes(
- COMPOSITION_DRAG_MIME_TYPE,
- );
+export const isComponentDragEvent = (event: DragEvent) => {
+ return isRemotionDragEvent(event, 'component');
};
-export const isElementDragEvent = (event: DragEvent): boolean => {
- return Array.from(event.dataTransfer?.types ?? []).includes(
- ELEMENT_DRAG_MIME_TYPE,
- );
+export const isCompositionDragEvent = (event: DragEvent) => {
+ return isRemotionDragEvent(event, 'composition');
};
-export const isSfxDragEvent = (event: DragEvent): boolean => {
- return Array.from(event.dataTransfer?.types ?? []).includes(
- SFX_DRAG_MIME_TYPE,
- );
+export const isElementDragEvent = (event: DragEvent) => {
+ return isRemotionDragEvent(event, 'element');
+};
+
+export const isSfxDragEvent = (event: DragEvent) => {
+ return isRemotionDragEvent(event, 'sfx');
};
export const isRemoteAssetDragEvent = (event: DragEvent): boolean => {
@@ -72,64 +65,33 @@ export const isSupportedDropEvent = (event: DragEvent): boolean => {
};
export 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 parsed = event.dataTransfer
+ ? DragAndDropInternals.parseDragData(event.dataTransfer)
+ : null;
+ return parsed?.type === 'asset' ? parsed.data.assetPath : null;
};
export const getCompositionDragData = (
event: DragEvent,
): CompositionDragData | null => {
- const value = event.dataTransfer?.getData(COMPOSITION_DRAG_MIME_TYPE);
- if (!value) {
- return null;
- }
-
- return parseCompositionDragData(value);
+ const parsed = event.dataTransfer
+ ? DragAndDropInternals.parseDragData(event.dataTransfer)
+ : null;
+ return parsed?.type === 'composition' ? parsed.data : null;
};
export const getComponentDragData = (
event: DragEvent,
): ComponentDragData | null => {
- for (const type of [
- COMPONENT_DRAG_MIME_TYPE,
- 'application/json',
- 'text/plain',
- ]) {
- const value = event.dataTransfer?.getData(type);
- if (!value) {
- continue;
- }
-
- const parsed = parseComponentDragData(value);
- if (parsed) {
- return parsed;
- }
- }
-
- return null;
+ const parsed = event.dataTransfer
+ ? DragAndDropInternals.parseDragData(event.dataTransfer)
+ : null;
+ return parsed?.type === 'component' ? parsed.data : null;
};
export const getSfxDragUrl = (event: DragEvent): string | null => {
- const {dataTransfer} = event;
- if (!dataTransfer) {
- return null;
- }
-
- for (const type of [SFX_DRAG_MIME_TYPE, 'application/json', 'text/plain']) {
- const value = dataTransfer.getData(type);
- if (!value) {
- continue;
- }
-
- const parsed = parseSfxDragData(value);
- if (parsed) {
- return parsed.sfx.url;
- }
- }
-
- return null;
+ const parsed = event.dataTransfer
+ ? DragAndDropInternals.parseDragData(event.dataTransfer)
+ : null;
+ return parsed?.type === 'sfx' ? parsed.data.sfx.url : null;
};
diff --git a/packages/studio/src/components/effect-drag-and-drop.ts b/packages/studio/src/components/effect-drag-and-drop.ts
index a82d1ab675..58540f41a8 100644
--- a/packages/studio/src/components/effect-drag-and-drop.ts
+++ b/packages/studio/src/components/effect-drag-and-drop.ts
@@ -1,97 +1,29 @@
import {
- ASSET_DRAG_MIME_TYPE,
- COMPOSITION_DRAG_MIME_TYPE,
- COMPONENT_DRAG_MIME_TYPE,
- EFFECT_DRAG_MIME_TYPE,
- ELEMENT_DRAG_MIME_TYPE,
- getRequiredPackageForEffectImportPath,
- isRemotionDragMimeType,
- parseEffectDragData,
- SFX_DRAG_MIME_TYPE,
+ DragAndDropInternals,
type EffectDragData,
- type RemotionDragMimeType,
-} from '@remotion/studio-shared';
+} from '@remotion/drag-and-drop';
+import {getRequiredPackageForEffectImportPath} from '@remotion/studio-shared';
import type {SequencePropsSubscriptionKey} from 'remotion';
import {installRequiredPackages} from '../helpers/install-required-package';
import {callApi} from './call-api';
import {showNotification} from './Notifications/NotificationCenter';
export const hasEffectDragType = (dataTransfer: DataTransfer) => {
- const types = Array.from(dataTransfer.types);
- const hasExplicitEffectType = types.includes(EFFECT_DRAG_MIME_TYPE);
- if (
- !hasExplicitEffectType &&
- (hasNonEffectRemotionDragType(dataTransfer) ||
- hasNonRemotionImportableAssetDragType(dataTransfer))
- ) {
- return false;
- }
-
- return types.some(
- (type) => type === EFFECT_DRAG_MIME_TYPE || isGenericDragType(type),
+ return (
+ DragAndDropInternals.getDragPreviewMetadata(dataTransfer.types)?.type ===
+ 'effect'
);
};
export const hasExplicitEffectDragType = (dataTransfer: DataTransfer) => {
- return Array.from(dataTransfer.types).includes(EFFECT_DRAG_MIME_TYPE);
-};
-
-const isGenericDragType = (type: string) => {
- return type === 'application/json' || type === 'text/plain';
-};
-
-const isNonEffectRemotionDragType = (mimeType: RemotionDragMimeType) => {
- switch (mimeType) {
- case EFFECT_DRAG_MIME_TYPE:
- return false;
- case ASSET_DRAG_MIME_TYPE:
- case COMPOSITION_DRAG_MIME_TYPE:
- case COMPONENT_DRAG_MIME_TYPE:
- case ELEMENT_DRAG_MIME_TYPE:
- case SFX_DRAG_MIME_TYPE:
- return true;
- default:
- mimeType satisfies never;
- throw new Error(`Unhandled Remotion drag MIME type: ${mimeType}`);
- }
-};
-
-const hasNonEffectRemotionDragType = (dataTransfer: DataTransfer) => {
- return Array.from(dataTransfer.types).some((type) => {
- if (!isRemotionDragMimeType(type)) {
- return false;
- }
-
- return isNonEffectRemotionDragType(type);
- });
-};
-
-const hasNonRemotionImportableAssetDragType = (dataTransfer: DataTransfer) => {
- return Array.from(dataTransfer.types).some((type) => {
- return type === 'Files' || type === 'text/uri-list' || type === 'text/html';
- });
+ return hasEffectDragType(dataTransfer);
};
export const getEffectDragData = (
dataTransfer: DataTransfer,
): EffectDragData | null => {
- for (const type of [
- EFFECT_DRAG_MIME_TYPE,
- 'application/json',
- 'text/plain',
- ]) {
- const value = dataTransfer.getData(type);
- if (!value) {
- continue;
- }
-
- const parsed = parseEffectDragData(value);
- if (parsed) {
- return parsed;
- }
- }
-
- return null;
+ const parsed = DragAndDropInternals.parseDragData(dataTransfer);
+ return parsed?.type === 'effect' ? parsed.data : null;
};
export const addEffectFromDragData = ({
diff --git a/packages/studio/src/components/element-drag-and-drop.ts b/packages/studio/src/components/element-drag-and-drop.ts
index c98550ebd5..901c2b0508 100644
--- a/packages/studio/src/components/element-drag-and-drop.ts
+++ b/packages/studio/src/components/element-drag-and-drop.ts
@@ -1,11 +1,13 @@
import {
- ELEMENT_DRAG_MIME_TYPE,
- parseElementDragData,
+ DragAndDropInternals,
type ElementDragData,
-} from '@remotion/studio-shared';
+} from '@remotion/drag-and-drop';
export const hasElementDragType = (dataTransfer: DataTransfer | null) => {
- return Array.from(dataTransfer?.types ?? []).includes(ELEMENT_DRAG_MIME_TYPE);
+ return (
+ DragAndDropInternals.getDragPreviewMetadata(dataTransfer?.types ?? [])
+ ?.type === 'element'
+ );
};
export const getElementDragData = (
@@ -15,21 +17,6 @@ export const getElementDragData = (
return null;
}
- for (const type of [
- ELEMENT_DRAG_MIME_TYPE,
- 'application/json',
- 'text/plain',
- ]) {
- const raw = dataTransfer.getData(type);
- if (!raw) {
- continue;
- }
-
- const parsed = parseElementDragData(raw);
- if (parsed) {
- return parsed;
- }
- }
-
- return null;
+ const parsed = DragAndDropInternals.parseDragData(dataTransfer);
+ return parsed?.type === 'element' ? parsed.data : null;
};
diff --git a/packages/studio/src/components/handle-drop.ts b/packages/studio/src/components/handle-drop.ts
index 79fd0e1b98..26b55e6cd4 100644
--- a/packages/studio/src/components/handle-drop.ts
+++ b/packages/studio/src/components/handle-drop.ts
@@ -113,7 +113,6 @@ export const handleDrop = async ({
composition,
compositionFile,
compositionId,
- destinationDimensions,
dropPosition,
from,
});
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index b5d94c3203..1b9f712a01 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -1,12 +1,14 @@
+import {
+ type ComponentDragData,
+ type CompositionDragData,
+ type ComponentProp,
+ type ElementDragData,
+} from '@remotion/drag-and-drop';
import {
detectFileType,
getRequiredPackageForInsertableElement,
isUrl,
- type ComponentDragData,
- type ComponentProp,
- type CompositionDragData,
type DownloadRemoteAssetResponse,
- type ElementDragData,
type FileType,
type InsertableCompositionElement,
type InsertableCompositionElementPosition,
@@ -299,22 +301,11 @@ export const getElementPositionForDrop = ({
export const getCompositionPositionForDrop = ({
compositionDimensions,
- destinationDimensions,
dropPosition,
}: {
compositionDimensions: Dimensions;
- destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
}): InsertableCompositionElementPosition | null => {
- // No translation makes an equal-sized composition fill the destination.
- if (
- destinationDimensions !== null &&
- compositionDimensions.width === destinationDimensions.width &&
- compositionDimensions.height === destinationDimensions.height
- ) {
- return null;
- }
-
return getCenteredPosition({
dimensions: compositionDimensions,
dropPosition,
@@ -1246,14 +1237,12 @@ export const insertComposition = async ({
composition,
compositionFile,
compositionId,
- destinationDimensions,
dropPosition,
from,
}: {
composition: CompositionDragData;
compositionFile: string;
compositionId: string;
- destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
from: number | null;
}) => {
@@ -1295,7 +1284,6 @@ export const insertComposition = async ({
serializeResolvedPropsForSourceCode(calculated.props),
position: getCompositionPositionForDrop({
compositionDimensions: dimensions,
- destinationDimensions,
dropPosition,
}),
},
diff --git a/packages/studio/src/helpers/get-effective-translation.ts b/packages/studio/src/helpers/get-effective-translation.ts
index 8749e9af14..a820c8a049 100644
--- a/packages/studio/src/helpers/get-effective-translation.ts
+++ b/packages/studio/src/helpers/get-effective-translation.ts
@@ -81,7 +81,7 @@ export const getEffectiveTranslation = ({
};
};
-export const getCenterPointWhileScrolling = ({
+export const getUnboundedCenterPointWhileScrolling = ({
size,
clientX,
clientY,
@@ -106,18 +106,20 @@ export const getCenterPointWhileScrolling = ({
const contentTopPoint =
size.height / 2 - (compositionHeight * scale) / 2 - translation.y;
- const offsetFromVideoLeft = Math.min(
- compositionWidth,
- Math.max(0, (mouseLeft - contentLeftPoint) / scale),
- );
- const offsetFromVideoTop = Math.min(
- compositionHeight,
- Math.max(0, (mouseTop - contentTopPoint) / scale),
- );
+ return {
+ centerX: (mouseLeft - contentLeftPoint) / scale,
+ centerY: (mouseTop - contentTopPoint) / scale,
+ };
+};
+
+export const getCenterPointWhileScrolling = (
+ options: Parameters<typeof getUnboundedCenterPointWhileScrolling>[0],
+) => {
+ const {centerX, centerY} = getUnboundedCenterPointWhileScrolling(options);
return {
- centerX: offsetFromVideoLeft,
- centerY: offsetFromVideoTop,
+ centerX: Math.min(options.compositionWidth, Math.max(0, centerX)),
+ centerY: Math.min(options.compositionHeight, Math.max(0, centerY)),
};
};
diff --git a/packages/studio/src/helpers/use-image-metadata.ts b/packages/studio/src/helpers/use-image-metadata.ts
index 5520aead7b..a59db8ba40 100644
--- a/packages/studio/src/helpers/use-image-metadata.ts
+++ b/packages/studio/src/helpers/use-image-metadata.ts
@@ -14,6 +14,10 @@ export type ImageMetadata = {
const cache = new Map<string, ImageMetadata>();
const pendingRequests = new Map<string, Promise<ImageMetadata | null>>();
+export const getCachedImageMetadata = (src: string) => {
+ return cache.get(src) ?? null;
+};
+
const formatImageType = (fileType: ImageFileType['type']) => {
if (fileType === 'webp') {
return 'WebP';
@@ -84,11 +88,11 @@ export const getImageMetadata = (
export const useImageMetadata = (src: string | null): ImageMetadata | null => {
const [imageMetadata, setImageMetadata] = useState<ImageMetadata | null>(
- src ? (cache.get(src) ?? null) : null,
+ src ? getCachedImageMetadata(src) : null,
);
useEffect(() => {
- const cached = src ? (cache.get(src) ?? null) : null;
+ const cached = src ? getCachedImageMetadata(src) : null;
setImageMetadata(cached);
if (!src || cached) {
diff --git a/packages/studio/src/helpers/use-media-metadata.ts b/packages/studio/src/helpers/use-media-metadata.ts
index 16db137bb3..f874da2a5c 100644
--- a/packages/studio/src/helpers/use-media-metadata.ts
+++ b/packages/studio/src/helpers/use-media-metadata.ts
@@ -21,6 +21,10 @@ export type MediaMetadata = {
const cache = new Map<string, MediaMetadata>();
const pendingRequests = new Map<string, Promise<MediaMetadata | null>>();
+export const getCachedMediaMetadata = (src: string) => {
+ return cache.get(src) ?? null;
+};
+
const safeCall = async <T>(fn: () => Promise<T>): Promise<T | null> => {
try {
return await fn();
@@ -155,11 +159,11 @@ export const getMediaMetadata = (
export const useMediaMetadata = (src: string | null): MediaMetadata | null => {
const [mediaMetadata, setMediaMetadata] = useState<MediaMetadata | null>(
- src ? (cache.get(src) ?? null) : null,
+ src ? getCachedMediaMetadata(src) : null,
);
useEffect(() => {
- const cached = src ? (cache.get(src) ?? null) : null;
+ const cached = src ? getCachedMediaMetadata(src) : null;
setMediaMetadata(cached);
if (!src || cached) {
diff --git a/packages/studio/src/test/composition-drop-preview.test.ts b/packages/studio/src/test/composition-drop-preview.test.ts
new file mode 100644
index 0000000000..f511e69475
--- /dev/null
+++ b/packages/studio/src/test/composition-drop-preview.test.ts
@@ -0,0 +1,102 @@
+import {expect, test} from 'bun:test';
+import {
+ getCompositionDropPreviewBox,
+ snapCompositionDropPosition,
+} from '../components/composition-drop-preview';
+import {getUnboundedCenterPointWhileScrolling} from '../helpers/get-effective-translation';
+
+const canvasSize = {
+ width: 992,
+ height: 572,
+ left: 0,
+ top: 0,
+};
+const destinationDimensions = {width: 1920, height: 1080};
+const previewSize = {
+ size: 'auto' as const,
+ translation: {x: 0, y: 0},
+};
+
+test('centers a composition drop preview under the pointer', () => {
+ expect(
+ getCompositionDropPreviewBox({
+ canvasSize,
+ destinationDimensions,
+ previewSize,
+ preview: {
+ compositionDimensions: {width: 640, height: 360},
+ dropPosition: {centerX: 960, centerY: 540},
+ },
+ }),
+ ).toEqual({
+ left: 336,
+ top: 196,
+ width: 320,
+ height: 180,
+ });
+});
+
+test('previews an equal-sized composition at the drop position', () => {
+ expect(
+ getCompositionDropPreviewBox({
+ canvasSize,
+ destinationDimensions,
+ previewSize: {
+ size: 'auto',
+ translation: {x: 20, y: -10},
+ },
+ preview: {
+ compositionDimensions: destinationDimensions,
+ dropPosition: {centerX: 200, centerY: 300},
+ },
+ }),
+ ).toEqual({
+ left: -384,
+ top: -94,
+ width: 960,
+ height: 540,
+ });
+});
+
+test('does not clamp drop coordinates to the destination', () => {
+ expect(
+ getUnboundedCenterPointWhileScrolling({
+ size: {
+ width: 1000,
+ height: 600,
+ left: 100,
+ top: 50,
+ windowSize: {width: 1000, height: 600},
+ refresh: () => undefined,
+ },
+ clientX: 100,
+ clientY: 50,
+ compositionWidth: 1920,
+ compositionHeight: 1080,
+ scale: 0.5,
+ translation: {x: 0, y: 0},
+ }),
+ ).toEqual({centerX: -40, centerY: -60});
+});
+
+test('snaps the dragged right edge to the destination left edge', () => {
+ expect(
+ snapCompositionDropPosition({
+ compositionDimensions: {width: 640, height: 360},
+ destinationDimensions,
+ dropPosition: {centerX: -315, centerY: 540},
+ scale: 1,
+ }),
+ ).toEqual({centerX: -320, centerY: 540});
+});
+
+test('snaps the dragged left edge to the destination right edge', () => {
+ expect(
+ snapCompositionDropPosition({
+ compositionDimensions: {width: 640, height: 360},
+ destinationDimensions,
+ dropPosition: {centerX: 2235, centerY: 540},
+ scale: 1,
+ }),
+ ).toEqual({centerX: 2240, centerY: 540});
+});
diff --git a/packages/studio/src/test/effect-drag-and-drop.test.ts b/packages/studio/src/test/effect-drag-and-drop.test.ts
index 61d86cfc33..4a0bc70fab 100644
--- a/packages/studio/src/test/effect-drag-and-drop.test.ts
+++ b/packages/studio/src/test/effect-drag-and-drop.test.ts
@@ -1,81 +1,76 @@
import {expect, test} from 'bun:test';
import {
- ASSET_DRAG_MIME_TYPE,
- COMPOSITION_DRAG_MIME_TYPE,
- COMPONENT_DRAG_MIME_TYPE,
- EFFECT_DRAG_MIME_TYPE,
- ELEMENT_DRAG_MIME_TYPE,
- SFX_DRAG_MIME_TYPE,
- type EffectDragData,
- type RemotionDragMimeType,
-} from '@remotion/studio-shared';
+ DragAndDropInternals,
+ type MakeDragDataInput,
+} from '@remotion/drag-and-drop';
import {
getEffectDragData,
hasEffectDragType,
} from '../components/effect-drag-and-drop';
-const effectDragData: EffectDragData = {
- type: 'remotion-effect',
- version: 1,
- effect: {
- name: 'Opacity',
- importPath: '@remotion/effects',
- config: {},
- },
-};
-
-const makeDataTransfer = ({
- types,
- data,
-}: {
- readonly types: string[];
- readonly data?: Record<string, string>;
-}): DataTransfer => {
+const makeDataTransfer = (
+ constructed: ReturnType<typeof DragAndDropInternals.makeDragData>,
+): DataTransfer => {
return {
- types,
- getData: (type: string) => data?.[type] ?? '',
+ types: [constructed.mimeType],
+ getData: (type: string) =>
+ type === constructed.mimeType ? constructed.payload : '',
} as unknown as DataTransfer;
};
-test('detects explicit effect drags', () => {
- expect(
- hasEffectDragType(
- makeDataTransfer({
- types: [EFFECT_DRAG_MIME_TYPE, 'application/json', 'text/plain'],
- }),
- ),
- ).toBe(true);
-});
-
-test('keeps generic effect drag fallback', () => {
- const serialized = JSON.stringify(effectDragData);
- const dataTransfer = makeDataTransfer({
- types: ['application/json', 'text/plain'],
- data: {
- 'application/json': serialized,
- 'text/plain': serialized,
- },
+test('detects and parses effect drags', () => {
+ const effect = DragAndDropInternals.makeDragData({
+ type: 'effect',
+ name: 'Opacity',
+ importPath: '@remotion/effects',
+ config: {},
});
+ const dataTransfer = makeDataTransfer(effect);
expect(hasEffectDragType(dataTransfer)).toBe(true);
- expect(getEffectDragData(dataTransfer)).toEqual(effectDragData);
+ expect(getEffectDragData(dataTransfer)).toEqual(effect.data);
});
-const nonEffectRemotionDragMimeTypes = [
- ['asset', ASSET_DRAG_MIME_TYPE],
- ['component', COMPONENT_DRAG_MIME_TYPE],
- ['composition', COMPOSITION_DRAG_MIME_TYPE],
- ['element', ELEMENT_DRAG_MIME_TYPE],
- ['sfx', SFX_DRAG_MIME_TYPE],
-] satisfies readonly (readonly [string, RemotionDragMimeType])[];
+const nonEffectInputs: MakeDragDataInput[] = [
+ {
+ type: 'asset',
+ assetPath: 'image.png',
+ width: null,
+ height: null,
+ durationInSeconds: null,
+ },
+ {
+ type: 'component',
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ },
+ {
+ type: 'composition',
+ compositionFile: null,
+ compositionId: 'Comp',
+ width: null,
+ height: null,
+ durationInFrames: null,
+ },
+ {
+ type: 'element',
+ dependencies: [],
+ dimensions: null,
+ displayName: 'Element',
+ durationInFrames: 30,
+ slug: 'element',
+ sourceCode: 'export const Element = () => null;',
+ },
+ {type: 'sfx', name: 'SFX', url: 'https://remotion.media/sfx.wav'},
+];
-for (const [label, mimeType] of nonEffectRemotionDragMimeTypes) {
- test(`does not treat ${label} imports as effect drags`, () => {
+for (const input of nonEffectInputs) {
+ test(`does not treat ${input.type} drags as effect drags`, () => {
expect(
hasEffectDragType(
- makeDataTransfer({
- types: [mimeType, 'application/json', 'text/plain'],
- }),
+ makeDataTransfer(DragAndDropInternals.makeDragData(input)),
),
).toBe(false);
});
@@ -83,10 +78,8 @@ for (const [label, mimeType] of nonEffectRemotionDragMimeTypes) {
test('does not treat remote asset imports as effect drags', () => {
expect(
- hasEffectDragType(
- makeDataTransfer({
- types: ['text/uri-list', 'text/plain'],
- }),
- ),
+ hasEffectDragType({
+ types: ['text/uri-list', 'text/plain'],
+ } as unknown as DataTransfer),
).toBe(false);
});
diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.ts
index 2af88617e0..6b469481c0 100644
--- a/packages/studio/src/test/import-assets.test.ts
+++ b/packages/studio/src/test/import-assets.test.ts
@@ -258,21 +258,19 @@ test('does not position Elements without a drop position', () => {
).toBe(null);
});
-test('aligns a composition with matching destination dimensions', () => {
+test('centers a composition with matching destination dimensions', () => {
expect(
getCompositionPositionForDrop({
compositionDimensions: {width: 1920, height: 1080},
- destinationDimensions: {width: 1920, height: 1080},
dropPosition: {centerX: 400, centerY: 300},
}),
- ).toBe(null);
+ ).toEqual({x: -560, y: -240});
});
test('centers a composition with different destination dimensions', () => {
expect(
getCompositionPositionForDrop({
compositionDimensions: {width: 1280, height: 720},
- destinationDimensions: {width: 1920, height: 1080},
dropPosition: {centerX: 400, centerY: 300},
}),
).toEqual({x: -240, y: -60});
diff --git a/packages/studio/tsconfig.json b/packages/studio/tsconfig.json
index d46897976a..4172579da8 100644
--- a/packages/studio/tsconfig.json
+++ b/packages/studio/tsconfig.json
@@ -18,6 +18,9 @@
{
"path": "../media-utils"
},
+ {
+ "path": "../drag-and-drop"
+ },
{
"path": "../studio-shared"
},
diff --git a/tsconfig.json b/tsconfig.json
index 549db0aab6..9a0b7fe62f 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -261,6 +261,9 @@
{
"path": "./packages/canvas-capture"
},
+ {
+ "path": "./packages/drag-and-drop"
+ },
{
"path": "./packages/light-leaks"
},