Skip to content

🎥 Make videos programmatically with React

remotion.dev/convert: Allow to drag output files (#10221)

Jonny Burgeref810db783af
diff --git a/bun.lock b/bun.lock
index 54f649d1af..32c011cce6 100644
--- a/bun.lock
+++ b/bun.lock
@@ -377,9 +377,12 @@
"tailwindcss-animate": "1.0.7",
},
"devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
"@remix-run/dev": "2.17.4",
"@remotion/eslint-config-internal": "workspace:*",
"@tailwindcss/postcss": "4.2.0",
+ "@testing-library/dom": "10.4.0",
+ "@testing-library/react": "16.1.0",
"@types/dom-webcodecs": "catalog:",
"eslint": "catalog:",
"postcss": "8.5.23",
diff --git a/packages/convert/app/components/ConvertProgress.tsx b/packages/convert/app/components/ConvertProgress.tsx
index 151297e220..f92d5f3a02 100644
--- a/packages/convert/app/components/ConvertProgress.tsx
+++ b/packages/convert/app/components/ConvertProgress.tsx
@@ -24,6 +24,7 @@ export const ConvertProgress: React.FC<{
readonly bars: number[];
readonly startTime?: number;
readonly completedTime?: number;
+ readonly draggableFile: File | null;
}> = ({
state,
newName,
@@ -33,6 +34,7 @@ export const ConvertProgress: React.FC<{
duration,
startTime,
completedTime,
+ draggableFile,
}) => {
const progress = done ? 1 : state.overallProgress;
@@ -51,6 +53,7 @@ export const ConvertProgress: React.FC<{
userRotation={0}
mirrorHorizontal={false}
mirrorVertical={false}
+ draggableFile={done ? draggableFile : null}
/>
{duration ? (
<>
diff --git a/packages/convert/app/components/ConvertUi.tsx b/packages/convert/app/components/ConvertUi.tsx
index 3162e0dc64..40b7aa8ebb 100644
--- a/packages/convert/app/components/ConvertUi.tsx
+++ b/packages/convert/app/components/ConvertUi.tsx
@@ -23,6 +23,7 @@ import {
isConvertEnabledByDefault,
isVideoOnlySection,
} from '~/lib/default-ui';
+import {canOfferFileDrag} from '~/lib/file-drag';
import {getNewName} from '~/lib/generate-new-name';
import {
getActualAudioOperation,
@@ -266,8 +267,14 @@ const ConvertUI = ({
const run = async () => {
const filename = getNewName(name, format);
- const {getBlob, stream, getWrittenByteCount, close} =
- await makeWebFsTarget(filename);
+ const {
+ getBlob,
+ stream,
+ getWrittenByteCount,
+ getFileSize,
+ isFileSystemBacked,
+ close,
+ } = await makeWebFsTarget(filename, format.mimeType);
const output = new Output({
format,
@@ -443,14 +450,39 @@ const ConvertUI = ({
await conversion.execute();
- close();
+ await close();
+ progress.bytesWritten = getWrittenByteCount();
+
+ let outputFilePromise: Promise<File> | null = null;
+ const download = () => {
+ if (outputFilePromise === null) {
+ outputFilePromise = getBlob().catch((error) => {
+ outputFilePromise = null;
+ throw error;
+ });
+ }
+
+ return outputFilePromise;
+ };
+
+ let draggableFile: File | null = null;
+ if (
+ canOfferFileDrag({
+ fileSize: getFileSize(),
+ isFileSystemBacked,
+ })
+ ) {
+ try {
+ draggableFile = await download();
+ } catch {
+ draggableFile = null;
+ }
+ }
setState({
type: 'done',
- download: async () => {
- const blob = await getBlob();
- return blob;
- },
+ download,
+ draggableFile,
state: progress,
startTime,
completedTime: Date.now(),
@@ -556,6 +588,7 @@ const ConvertUI = ({
<ConvertProgress
state={state.state}
newName={state.newName}
+ draggableFile={null}
done={false}
duration={durationInSeconds}
isReencoding={
@@ -584,6 +617,7 @@ const ConvertUI = ({
done
state={state.state}
newName={state.newName}
+ draggableFile={state.draggableFile}
duration={durationInSeconds}
isReencoding={
supportedConfigs !== null &&
diff --git a/packages/convert/app/components/DragOverOverlay.tsx b/packages/convert/app/components/DragOverOverlay.tsx
index 0a5ce50a87..1a90cc86dd 100644
--- a/packages/convert/app/components/DragOverOverlay.tsx
+++ b/packages/convert/app/components/DragOverOverlay.tsx
@@ -6,7 +6,7 @@ export const DragOverOverlay: React.FC<{
return (
<div
data-active={String(active)}
- className="inset-0 absolute bg-slate-50 pointer-events-none flex justify-center items-center font-brand flex-col transition-opacity opacity-0 data-[active=true]:opacity-100"
+ className="inset-0 fixed bg-slate-50 pointer-events-none flex justify-center items-center font-brand flex-col transition-opacity opacity-0 data-[active=true]:opacity-100"
>
<h2 className="text-2xl font-medium">Drop a video</h2>
<div className="h-1" />
diff --git a/packages/convert/app/components/ReplaceVideo.tsx b/packages/convert/app/components/ReplaceVideo.tsx
index 476180001e..8ce74a946d 100644
--- a/packages/convert/app/components/ReplaceVideo.tsx
+++ b/packages/convert/app/components/ReplaceVideo.tsx
@@ -1,5 +1,6 @@
import React, {useCallback, useEffect, useState} from 'react';
import type {Source} from '~/lib/convert-state';
+import {CONVERTED_OUTPUT_DRAG_TYPE} from '~/lib/file-drag';
import {DragOverOverlay} from './DragOverOverlay';
import {Button} from './ui/button';
import {
@@ -10,6 +11,12 @@ import {
DialogTitle,
} from './ui/dialog';
+const isConvertedOutputDrag = (dataTransfer: DataTransfer | null) => {
+ return dataTransfer
+ ? Array.from(dataTransfer.types).includes(CONVERTED_OUTPUT_DRAG_TYPE)
+ : false;
+};
+
export const ReplaceVideo: React.FC<{
readonly src: Source | null;
readonly setSrc: React.Dispatch<React.SetStateAction<Source | null>>;
@@ -23,6 +30,11 @@ export const ReplaceVideo: React.FC<{
}
const onDragOver = (e: DragEvent) => {
+ if (isConvertedOutputDrag(e.dataTransfer)) {
+ setDragging(false);
+ return;
+ }
+
e.preventDefault();
setDragging(src !== null);
};
@@ -34,6 +46,10 @@ export const ReplaceVideo: React.FC<{
const onDrop = (e: DragEvent) => {
setDragging(false);
e.preventDefault();
+ if (isConvertedOutputDrag(e.dataTransfer)) {
+ return;
+ }
+
const file = e.dataTransfer?.files[0];
if (file) {
if (src === null) {
diff --git a/packages/convert/app/components/VideoThumbnail.tsx b/packages/convert/app/components/VideoThumbnail.tsx
index bc94f7e3bd..34802bb57a 100644
--- a/packages/convert/app/components/VideoThumbnail.tsx
+++ b/packages/convert/app/components/VideoThumbnail.tsx
@@ -1,6 +1,13 @@
import clsx from 'clsx';
import {FastAverageColor} from 'fast-average-color';
-import React, {useCallback, useImperativeHandle, useRef, useState} from 'react';
+import React, {
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from 'react';
+import {setFileDragData} from '~/lib/file-drag';
import {useIsNarrow} from '~/lib/is-narrow';
export const THUMBNAIL_HEIGHT = Math.round((350 / 16) * 9);
@@ -12,6 +19,7 @@ type Props = {
readonly mirrorHorizontal: boolean;
readonly mirrorVertical: boolean;
readonly initialReveal: boolean;
+ readonly draggableFile?: File | null;
};
export type VideoThumbnailRef = {
@@ -34,6 +42,7 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
mirrorHorizontal,
mirrorVertical,
initialReveal,
+ draggableFile = null,
},
forwardedRef,
) => {
@@ -44,6 +53,22 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
const [reveal, setReveal] = useState(initialReveal);
const [drawn, setDrawn] = useState(false);
const [needsRotation, setNeedsRotation] = useState(false);
+ const [dragObjectUrl, setDragObjectUrl] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!draggableFile) {
+ setDragObjectUrl(null);
+ return;
+ }
+
+ try {
+ const objectUrl = URL.createObjectURL(draggableFile);
+ setDragObjectUrl(objectUrl);
+ return () => URL.revokeObjectURL(objectUrl);
+ } catch {
+ setDragObjectUrl(null);
+ }
+ }, [draggableFile]);
const onChangeListeners = useRef<(() => void)[]>([]);
@@ -116,12 +141,33 @@ const VideoThumbnailRefForward: React.ForwardRefRenderFunction<
? THUMBNAIL_HEIGHT / dimensions.width
: 1;
+ const canDrag = draggableFile !== null && dragObjectUrl !== null;
+ const onDragStart = useCallback(
+ (event: React.DragEvent<HTMLDivElement>) => {
+ if (
+ !draggableFile ||
+ !dragObjectUrl ||
+ !setFileDragData({
+ dataTransfer: event.dataTransfer,
+ file: draggableFile,
+ objectUrl: dragObjectUrl,
+ })
+ ) {
+ event.preventDefault();
+ }
+ },
+ [dragObjectUrl, draggableFile],
+ );
+
return (
<div
className={clsx(
isNarrow && smallThumbOnMobile ? 'border-r-2' : 'border-b-2',
'border-black overflow-hidden bg-slate-100',
+ canDrag && 'cursor-grab active:cursor-grabbing',
)}
+ draggable={canDrag || undefined}
+ onDragStart={canDrag ? onDragStart : undefined}
// +2 to account for border
style={{height: THUMBNAIL_HEIGHT * scale + 2}}
>
diff --git a/packages/convert/app/lib/convert-state.ts b/packages/convert/app/lib/convert-state.ts
index a6b79ddd10..4ae7e1404e 100644
--- a/packages/convert/app/lib/convert-state.ts
+++ b/packages/convert/app/lib/convert-state.ts
@@ -24,6 +24,7 @@ export type ConvertState =
| {
type: 'done';
download: () => Promise<File>;
+ draggableFile: File | null;
state: ConvertProgressType;
startTime: number;
completedTime: number;
diff --git a/packages/convert/app/lib/file-drag.ts b/packages/convert/app/lib/file-drag.ts
new file mode 100644
index 0000000000..6899344699
--- /dev/null
+++ b/packages/convert/app/lib/file-drag.ts
@@ -0,0 +1,84 @@
+// Browser Blob and file-drag implementations have different upper bounds.
+// Stay at the lowest broadly established desktop limit instead of advertising a
+// drag that may fail only after the user has left the page.
+export const MAXIMUM_SAFE_FILE_DRAG_SIZE = 500 * 1024 * 1024;
+export const CONVERTED_OUTPUT_DRAG_TYPE =
+ 'application/x-remotion-converted-output';
+
+export const isFileDragEligible = ({
+ fileSize,
+ isFileSystemBacked,
+}: {
+ readonly fileSize: number;
+ readonly isFileSystemBacked: boolean;
+}) => {
+ return (
+ isFileSystemBacked &&
+ fileSize > 0 &&
+ fileSize <= MAXIMUM_SAFE_FILE_DRAG_SIZE
+ );
+};
+
+export const canOfferFileDrag = ({
+ fileSize,
+ isFileSystemBacked,
+}: {
+ readonly fileSize: number;
+ readonly isFileSystemBacked: boolean;
+}) => {
+ if (!isFileDragEligible({fileSize, isFileSystemBacked})) {
+ return false;
+ }
+
+ if (
+ typeof window === 'undefined' ||
+ typeof DataTransfer === 'undefined' ||
+ typeof File === 'undefined' ||
+ typeof URL.createObjectURL !== 'function' ||
+ navigator.maxTouchPoints > 0 ||
+ !window.matchMedia('(any-pointer: fine)').matches
+ ) {
+ return false;
+ }
+
+ try {
+ const dataTransfer = new DataTransfer();
+ const item = dataTransfer.items.add(
+ new File([], 'remotion-file-drag-probe'),
+ );
+ return item !== null && dataTransfer.files.length === 1;
+ } catch {
+ return false;
+ }
+};
+
+export const setFileDragData = ({
+ dataTransfer,
+ file,
+ objectUrl,
+}: {
+ readonly dataTransfer: DataTransfer;
+ readonly file: File;
+ readonly objectUrl: string;
+}) => {
+ try {
+ dataTransfer.clearData();
+ dataTransfer.effectAllowed = 'copy';
+ const item = dataTransfer.items.add(file);
+ if (item === null) {
+ return false;
+ }
+
+ // Chromium uses this non-standard type when the drag crosses a browser
+ // window or leaves the browser. Other browsers safely ignore it and use
+ // the standards-based File item above.
+ dataTransfer.setData(
+ 'DownloadURL',
+ `${file.type || 'application/octet-stream'}:${file.name}:${objectUrl}`,
+ );
+ dataTransfer.setData(CONVERTED_OUTPUT_DRAG_TYPE, '1');
+ return true;
+ } catch {
+ return false;
+ }
+};
diff --git a/packages/convert/app/lib/web-fs-target.ts b/packages/convert/app/lib/web-fs-target.ts
index ab26fe07d6..b2524af032 100644
--- a/packages/convert/app/lib/web-fs-target.ts
+++ b/packages/convert/app/lib/web-fs-target.ts
@@ -26,7 +26,7 @@ const canUseCreateWritable = async (): Promise<boolean> => {
}
};
-const makeWebFsTargetWithFs = async (filename: string) => {
+const makeWebFsTargetWithFs = async (filename: string, mimeType: string) => {
const directoryHandle = await navigator.storage.getDirectory();
const actualFilename = `__remotion_convert:${filename}`;
@@ -46,12 +46,14 @@ const makeWebFsTargetWithFs = async (filename: string) => {
const writable = await fileHandle.createWritable();
let written = 0;
+ let size = 0;
const writableStream = new WritableStream({
async write(chunk: StreamTargetChunk) {
await writable.seek(chunk.position);
await writable.write(chunk);
written += chunk.data.byteLength;
+ size = Math.max(size, chunk.position + chunk.data.byteLength);
},
});
@@ -60,18 +62,23 @@ const makeWebFsTargetWithFs = async (filename: string) => {
create: true,
});
const newFile = await newHandle.getFile();
- return newFile;
+ return new File([newFile], filename, {
+ lastModified: newFile.lastModified,
+ type: mimeType,
+ });
};
return {
stream: writableStream,
getBlob,
getWrittenByteCount: () => written,
+ getFileSize: () => size,
+ isFileSystemBacked: true,
close: () => writable.close(),
};
};
-const makeWebFsTargetInMemory = (filename: string) => {
+const makeWebFsTargetInMemory = (filename: string, mimeType: string) => {
let buffer = new Uint8Array(1024 * 1024);
let length = 0;
let written = 0;
@@ -106,8 +113,9 @@ const makeWebFsTargetInMemory = (filename: string) => {
const getBlob = (): Promise<File> =>
Promise.resolve(
- new File([buffer.slice(0, length)], filename, {
+ new File([buffer.subarray(0, length)], filename, {
lastModified: Date.now(),
+ type: mimeType,
}),
);
@@ -115,15 +123,17 @@ const makeWebFsTargetInMemory = (filename: string) => {
stream: writableStream,
getBlob,
getWrittenByteCount: () => written,
+ getFileSize: () => length,
+ isFileSystemBacked: false,
close: () => {},
};
};
-export const makeWebFsTarget = async (filename: string) => {
+export const makeWebFsTarget = async (filename: string, mimeType: string) => {
const canUse = await canUseCreateWritable();
if (canUse) {
- return makeWebFsTargetWithFs(filename);
+ return makeWebFsTargetWithFs(filename, mimeType);
}
- return makeWebFsTargetInMemory(filename);
+ return makeWebFsTargetInMemory(filename, mimeType);
};
diff --git a/packages/convert/bunfig.toml b/packages/convert/bunfig.toml
new file mode 100644
index 0000000000..d20eff30d4
--- /dev/null
+++ b/packages/convert/bunfig.toml
@@ -0,0 +1,2 @@
+[test]
+preload = "./happydom.ts"
diff --git a/packages/convert/happydom.ts b/packages/convert/happydom.ts
new file mode 100644
index 0000000000..7d4076c191
--- /dev/null
+++ b/packages/convert/happydom.ts
@@ -0,0 +1,3 @@
+import {GlobalRegistrator} from '@happy-dom/global-registrator';
+
+GlobalRegistrator.register();
diff --git a/packages/convert/package.json b/packages/convert/package.json
index 810aecbf74..d3f11ecb99 100644
--- a/packages/convert/package.json
+++ b/packages/convert/package.json
@@ -58,9 +58,12 @@
"tailwindcss-animate": "1.0.7"
},
"devDependencies": {
+ "@happy-dom/global-registrator": "14.5.1",
"@remix-run/dev": "2.17.4",
"@remotion/eslint-config-internal": "workspace:*",
"@tailwindcss/postcss": "4.2.0",
+ "@testing-library/dom": "10.4.0",
+ "@testing-library/react": "16.1.0",
"@types/dom-webcodecs": "catalog:",
"eslint": "catalog:",
"postcss": "8.5.23",
diff --git a/packages/convert/test/file-drag.test.tsx b/packages/convert/test/file-drag.test.tsx
new file mode 100644
index 0000000000..bbabbe327a
--- /dev/null
+++ b/packages/convert/test/file-drag.test.tsx
@@ -0,0 +1,176 @@
+import {afterEach, expect, test} from 'bun:test';
+import {cleanup, fireEvent, render, waitFor} from '@testing-library/react';
+import {ConvertProgress} from '../app/components/ConvertProgress';
+import {ReplaceVideo} from '../app/components/ReplaceVideo';
+import {
+ canOfferFileDrag,
+ CONVERTED_OUTPUT_DRAG_TYPE,
+ MAXIMUM_SAFE_FILE_DRAG_SIZE,
+ isFileDragEligible,
+} from '../app/lib/file-drag';
+import {TitleProvider} from '../app/lib/title-context';
+
+afterEach(() => {
+ cleanup();
+});
+
+test('offers the completed thumbnail as a file drag without adding UI', async () => {
+ const originalCreateObjectUrl = URL.createObjectURL;
+ const originalRevokeObjectUrl = URL.revokeObjectURL;
+ const revokedUrls: string[] = [];
+ URL.createObjectURL = () => 'blob:converted-output';
+ URL.revokeObjectURL = (url) => revokedUrls.push(url);
+
+ const file = new File(['converted contents'], 'converted.mp4', {
+ type: 'video/mp4',
+ });
+ const addedFiles: File[] = [];
+ const dragData = new Map<string, string>();
+ const dataTransfer = {
+ clearData: () => dragData.clear(),
+ effectAllowed: 'none',
+ get files() {
+ return addedFiles;
+ },
+ items: {
+ add: (addedFile: File) => {
+ addedFiles.push(addedFile);
+ return {} as DataTransferItem;
+ },
+ },
+ setData: (type: string, value: string) => dragData.set(type, value),
+ get types() {
+ return [...dragData.keys()];
+ },
+ } as unknown as DataTransfer;
+
+ try {
+ const rendered = render(
+ <TitleProvider routeAction={{type: 'generic-convert'}}>
+ <ConvertProgress
+ bars={[]}
+ done
+ draggableFile={file}
+ duration={1}
+ isReencoding
+ newName={file.name}
+ state={{
+ bytesWritten: file.size,
+ hasVideo: true,
+ millisecondsWritten: 1000,
+ overallProgress: 1,
+ }}
+ />
+ <ReplaceVideo src={{type: 'file', file}} setSrc={() => undefined} />
+ </TitleProvider>,
+ );
+
+ const thumbnail = await waitFor(() => {
+ const element = rendered.container.querySelector('[draggable="true"]');
+ expect(element).not.toBeNull();
+ return element as HTMLElement;
+ });
+
+ expect(thumbnail.textContent).toBe('');
+ fireEvent.dragStart(thumbnail, {dataTransfer});
+
+ expect(addedFiles).toEqual([file]);
+ expect(dragData.get('DownloadURL')).toBe(
+ 'video/mp4:converted.mp4:blob:converted-output',
+ );
+ expect(dragData.get(CONVERTED_OUTPUT_DRAG_TYPE)).toBe('1');
+
+ fireEvent.dragOver(document, {dataTransfer});
+ const overlay = rendered.getByText('Drop a video').parentElement;
+ expect(overlay?.dataset.active).toBe('false');
+ expect(overlay?.classList.contains('fixed')).toBe(true);
+ expect(overlay?.classList.contains('absolute')).toBe(false);
+
+ fireEvent.drop(document, {dataTransfer});
+ expect(rendered.queryByText('Replace video?')).toBeNull();
+
+ fireEvent.dragOver(document, {
+ dataTransfer: {
+ files: [file],
+ types: ['Files'],
+ },
+ });
+ await waitFor(() => expect(overlay?.dataset.active).toBe('true'));
+
+ rendered.unmount();
+ expect(revokedUrls).toEqual(['blob:converted-output']);
+ } finally {
+ URL.createObjectURL = originalCreateObjectUrl;
+ URL.revokeObjectURL = originalRevokeObjectUrl;
+ }
+});
+
+test('does not advertise unsafe outputs as file drags', () => {
+ expect(
+ isFileDragEligible({
+ fileSize: MAXIMUM_SAFE_FILE_DRAG_SIZE,
+ isFileSystemBacked: true,
+ }),
+ ).toBe(true);
+ expect(
+ isFileDragEligible({
+ fileSize: MAXIMUM_SAFE_FILE_DRAG_SIZE + 1,
+ isFileSystemBacked: true,
+ }),
+ ).toBe(false);
+ expect(
+ isFileDragEligible({
+ fileSize: 1,
+ isFileSystemBacked: false,
+ }),
+ ).toBe(false);
+
+ const rendered = render(
+ <TitleProvider routeAction={{type: 'generic-convert'}}>
+ <ConvertProgress
+ bars={[]}
+ done
+ draggableFile={null}
+ duration={1}
+ isReencoding
+ newName="converted.mp4"
+ state={{
+ bytesWritten: 1,
+ hasVideo: true,
+ millisecondsWritten: 1000,
+ overallProgress: 1,
+ }}
+ />
+ </TitleProvider>,
+ );
+
+ expect(rendered.getByText('converted.mp4')).not.toBeNull();
+ expect(rendered.container.querySelector('[draggable]')).toBeNull();
+});
+
+test('does not offer file dragging on touch-capable devices', () => {
+ const maxTouchPoints = Object.getOwnPropertyDescriptor(
+ navigator,
+ 'maxTouchPoints',
+ );
+
+ Object.defineProperty(navigator, 'maxTouchPoints', {
+ configurable: true,
+ value: 1,
+ });
+
+ try {
+ expect(
+ canOfferFileDrag({
+ fileSize: 1,
+ isFileSystemBacked: true,
+ }),
+ ).toBe(false);
+ } finally {
+ if (maxTouchPoints) {
+ Object.defineProperty(navigator, 'maxTouchPoints', maxTouchPoints);
+ } else {
+ delete (navigator as {maxTouchPoints?: number}).maxTouchPoints;
+ }
+ }
+});