🎥 Make videos programmatically with React
`@remotion/drag-and-drop`: Add Install in Studio interface (#9576)
Jonny Burger06f2fd70c591
diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsxindex f886ab9b0a..b5ece36317 100644--- a/packages/docs/src/components/Elements/ElementPage.tsx+++ b/packages/docs/src/components/Elements/ElementPage.tsx@@ -27,76 +27,12 @@ type ElementPageProps = {readonly sourceCode?: string;};-type ElementInstallTarget = {- type: 'remotion-studio';- projectName: string | null;- port: number | null;- lastFocusedAt: number | null;- canInstall: boolean;- activeCompositionId: string | null;- readOnly: boolean;-};-type InstallStatus =| {type: 'idle'}| {type: 'installing'}| {type: 'success'; message: string; studioUrl: string}| {type: 'error'; message: string};-const probePorts = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009];-const focusedStudioMaxAge = 5 * 60 * 1000;--const fetchWithTimeout = async (url: string, options: RequestInit = {}) => {- const controller = new AbortController();- const timeout = window.setTimeout(() => controller.abort(), 700);- try {- return await fetch(url, {...options, signal: controller.signal});- } finally {- window.clearTimeout(timeout);- }-};--const findBestInstallTarget = async (): Promise<- (ElementInstallTarget & {origin: string}) | null-> => {- const targets = await Promise.all(- probePorts.map(async (port) => {- const origin = `http://localhost:${port}`;- try {- const response = await fetchWithTimeout(- `${origin}/api/element-install-target`,- );- if (!response.ok) {- return null;- }-- const target = (await response.json()) as ElementInstallTarget;- if (target.type !== 'remotion-studio') {- return null;- }-- return {...target, origin};- } catch {- return null;- }- }),- );-- const now = Date.now();- const installableTargets = targets.filter(- (target): target is ElementInstallTarget & {origin: string} =>- target !== null &&- target.canInstall &&- target.lastFocusedAt !== null &&- now - target.lastFocusedAt < focusedStudioMaxAge,- );-- return (- installableTargets.sort((a, b) => b.lastFocusedAt! - a.lastFocusedAt!)[0] ??- null- );-};-export const ElementPage: React.FC<ElementPageProps> = ({children,definition,@@ -159,56 +95,23 @@ export const ElementPage: React.FC<ElementPageProps> = ({}setInstallStatus({type: 'installing'});- try {- const target = await findBestInstallTarget();- if (target === null) {- setInstallStatus({- type: 'error',- message:- 'Focus the Remotion Studio you want to install into, then click again.',- });- return;- }-- const response = await fetchWithTimeout(- `${target.origin}/api/request-element-install`,- {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({- mimeType: dragData.mimeType,- payload: dragData.payload,- }),- },- );- const result = (await response.json()) as- | {success: true; status: 'sent'}- | {success: false; reason: string};-- if (!response.ok || !result.success) {- setInstallStatus({- type: 'error',- message:- 'success' in result && result.success === false- ? result.reason- : 'Could not send Element to Remotion Studio.',- });- return;- }-- setInstallStatus({- type: 'success',- message: `Sent to ${target.projectName ?? 'Remotion Studio'}${- target.activeCompositionId ? ` / ${target.activeCompositionId}` : ''- }. Confirm the install in Studio.`,- studioUrl: target.origin,- });- } catch (err) {+ const result = await DragAndDropInternals.installInStudio(dragData);+ if (!result.success) {setInstallStatus({type: 'error',- message: err instanceof Error ? err.message : String(err),+ message: result.reason,});+ return;}++ const {target} = result;+ setInstallStatus({+ type: 'success',+ message: `Sent to ${target.projectName ?? 'Remotion Studio'}${+ target.activeCompositionId ? ` / ${target.activeCompositionId}` : ''+ }. Confirm the install in Studio.`,+ studioUrl: target.origin,+ });}, [dragData]);const PreviewComponent = useMemo(() => {diff --git a/packages/drag-and-drop/README.md b/packages/drag-and-drop/README.mdindex 788df85a2d..74c61d6eae 100644--- a/packages/drag-and-drop/README.md+++ b/packages/drag-and-drop/README.md@@ -1,6 +1,6 @@# `@remotion/drag-and-drop`-Internal drag-and-drop helpers for Remotion.+Internal drag-and-drop and Studio installation helpers for Remotion.This package is published for use by other Remotion packages and has no publicAPI.diff --git a/packages/drag-and-drop/package.json b/packages/drag-and-drop/package.jsonindex 14f2089823..ce6e9607ce 100644--- a/packages/drag-and-drop/package.json+++ b/packages/drag-and-drop/package.json@@ -1,7 +1,7 @@{"name": "@remotion/drag-and-drop","version": "4.0.498",- "description": "Internal drag-and-drop helpers for Remotion",+ "description": "Internal drag-and-drop and Studio installation helpers for Remotion","main": "dist/index.cjs","types": "dist/index.d.ts","module": "dist/esm/index.mjs",diff --git a/packages/drag-and-drop/src/index.ts b/packages/drag-and-drop/src/index.tsindex 71d3846c62..f3a493405e 100644--- a/packages/drag-and-drop/src/index.ts+++ b/packages/drag-and-drop/src/index.ts@@ -9,6 +9,7 @@ import {getElementComponentNameFromSourceCode,makeElementFileNameFromSlug,} from './element-drag-data';+import {installInStudio} from './install-in-studio';export type {AssetDragData} from './asset-drag-data';export type {@@ -44,6 +45,10 @@ export type {export type {EffectDragData} from './effect-drag-data';export type {ElementDragData} from './element-drag-data';export type {SfxDragData} from './sfx-drag-data';+export type {+ InstallInStudioResult,+ StudioInstallTarget,+} from './install-in-studio';export const DragAndDropInternals = {areComponentProps,@@ -51,6 +56,7 @@ export const DragAndDropInternals = {getElementComponentNameFromSourceCode,isComponentIdentifier,isComponentImportPath,+ installInStudio,makeDragData,makeElementFileNameFromSlug,parseDragData,diff --git a/packages/drag-and-drop/src/install-in-studio.ts b/packages/drag-and-drop/src/install-in-studio.tsnew file mode 100644index 0000000000..56379b6ed3--- /dev/null+++ b/packages/drag-and-drop/src/install-in-studio.ts@@ -0,0 +1,188 @@+import type {SerializedDragData} from './drag-data';+import {isRecord} from './validation';++export type StudioInstallTarget = {+ readonly type: 'remotion-studio';+ readonly projectName: string | null;+ readonly port: number | null;+ readonly lastFocusedAt: number | null;+ readonly canInstall: boolean;+ readonly activeCompositionId: string | null;+ readonly readOnly: boolean;+ readonly origin: string;+};++export type InstallInStudioResult =+ | {+ readonly success: true;+ readonly target: StudioInstallTarget;+ }+ | {+ readonly success: false;+ readonly reason: string;+ };++const probePorts = [3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009];+const focusedStudioMaxAge = 5 * 60 * 1000;++type InstallInStudioDependencies = {+ readonly fetchFn: Fetcher;+ readonly now: () => number;+ readonly ports: readonly number[];+};++type Fetcher = (+ input: string | URL | Request,+ options?: RequestInit,+) => Promise<Response>;++const fetchWithTimeout = async ({+ fetchFn,+ options = {},+ url,+}: {+ readonly fetchFn: Fetcher;+ readonly options?: RequestInit;+ readonly url: string;+}) => {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 700);+ try {+ return await fetchFn(url, {...options, signal: controller.signal});+ } finally {+ clearTimeout(timeout);+ }+};++const isNullableString = (value: unknown): value is string | null => {+ return value === null || typeof value === 'string';+};++const isStudioInstallTarget = (+ value: unknown,+): value is Omit<StudioInstallTarget, 'origin'> => {+ if (!isRecord(value)) {+ return false;+ }++ return (+ value.type === 'remotion-studio' &&+ isNullableString(value.projectName) &&+ (value.port === null ||+ (typeof value.port === 'number' && Number.isFinite(value.port))) &&+ (value.lastFocusedAt === null ||+ (typeof value.lastFocusedAt === 'number' &&+ Number.isFinite(value.lastFocusedAt))) &&+ typeof value.canInstall === 'boolean' &&+ isNullableString(value.activeCompositionId) &&+ typeof value.readOnly === 'boolean'+ );+};++const findBestStudioInstallTarget = async ({+ fetchFn,+ now,+ ports,+}: InstallInStudioDependencies): Promise<StudioInstallTarget | null> => {+ const targets = await Promise.all(+ ports.map(async (port): Promise<StudioInstallTarget | null> => {+ const origin = `http://localhost:${port}`;+ try {+ const response = await fetchWithTimeout({+ fetchFn,+ url: `${origin}/api/element-install-target`,+ });+ if (!response.ok) {+ return null;+ }++ const target: unknown = await response.json();+ if (!isStudioInstallTarget(target)) {+ return null;+ }++ return {...target, origin};+ } catch {+ return null;+ }+ }),+ );++ const currentTime = now();+ const installableTargets = targets.filter(+ (target): target is StudioInstallTarget =>+ target !== null &&+ target.canInstall &&+ target.lastFocusedAt !== null &&+ currentTime - target.lastFocusedAt < focusedStudioMaxAge,+ );++ return (+ installableTargets.sort((a, b) => b.lastFocusedAt! - a.lastFocusedAt!)[0] ??+ null+ );+};++export const installInStudioWithDependencies = async (+ dragData: SerializedDragData,+ dependencies: InstallInStudioDependencies,+): Promise<InstallInStudioResult> => {+ const target = await findBestStudioInstallTarget(dependencies);+ if (target === null) {+ return {+ success: false,+ reason:+ 'Focus the Remotion Studio you want to install into, then click again.',+ };+ }++ try {+ const response = await fetchWithTimeout({+ fetchFn: dependencies.fetchFn,+ url: `${target.origin}/api/request-element-install`,+ options: {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({+ mimeType: dragData.mimeType,+ payload: dragData.payload,+ }),+ },+ });+ const result: unknown = await response.json();++ if (+ !response.ok ||+ !isRecord(result) ||+ result.success !== true ||+ result.status !== 'sent'+ ) {+ return {+ success: false,+ reason:+ isRecord(result) &&+ result.success === false &&+ typeof result.reason === 'string'+ ? result.reason+ : 'Could not send payload to Remotion Studio.',+ };+ }++ return {success: true, target};+ } catch (error) {+ return {+ success: false,+ reason: error instanceof Error ? error.message : String(error),+ };+ }+};++export const installInStudio = (+ dragData: SerializedDragData,+): Promise<InstallInStudioResult> => {+ return installInStudioWithDependencies(dragData, {+ fetchFn: fetch,+ now: Date.now,+ ports: probePorts,+ });+};diff --git a/packages/drag-and-drop/src/test/install-in-studio.test.ts b/packages/drag-and-drop/src/test/install-in-studio.test.tsnew file mode 100644index 0000000000..4d028a46eb--- /dev/null+++ b/packages/drag-and-drop/src/test/install-in-studio.test.ts@@ -0,0 +1,129 @@+import {expect, test} from 'bun:test';+import {installInStudioWithDependencies} from '../install-in-studio';++const dragData = {+ mimeType: 'application/vnd.remotion.drag+json;v=1;type=element;duration=90',+ payload: '{"type":"remotion-element"}',+ data: {type: 'not-sent'},+};++const target = ({+ lastFocusedAt,+ projectName,+}: {+ lastFocusedAt: number;+ projectName: string;+}) => ({+ type: 'remotion-studio' as const,+ projectName,+ port: 3000,+ lastFocusedAt,+ canInstall: true,+ activeCompositionId: 'Main',+ readOnly: false,+});++const jsonResponse = (value: unknown, status = 200) => {+ return new Response(JSON.stringify(value), {+ headers: {'Content-Type': 'application/json'},+ status,+ });+};++test('installs into the most recently focused Studio', async () => {+ const requests: Array<{url: string; options?: RequestInit}> = [];+ const fetchFn = (input: string | URL | Request, options?: RequestInit) => {+ const url = String(input);+ requests.push({url, options});++ if (url === 'http://localhost:3000/api/element-install-target') {+ return Promise.resolve(+ jsonResponse(+ target({lastFocusedAt: 900_000, projectName: 'Older project'}),+ ),+ );+ }++ if (url === 'http://localhost:3001/api/element-install-target') {+ return Promise.resolve(+ jsonResponse(+ target({lastFocusedAt: 950_000, projectName: 'Newest project'}),+ ),+ );+ }++ if (url === 'http://localhost:3001/api/request-element-install') {+ return Promise.resolve(jsonResponse({success: true, status: 'sent'}));+ }++ return Promise.resolve(new Response(null, {status: 404}));+ };++ const result = await installInStudioWithDependencies(dragData, {+ fetchFn,+ now: () => 1_000_000,+ ports: [3000, 3001],+ });++ expect(result).toEqual({+ success: true,+ target: {+ ...target({lastFocusedAt: 950_000, projectName: 'Newest project'}),+ origin: 'http://localhost:3001',+ },+ });+ expect(requests.at(-1)).toEqual({+ url: 'http://localhost:3001/api/request-element-install',+ options: {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({+ mimeType: dragData.mimeType,+ payload: dragData.payload,+ }),+ signal: expect.any(AbortSignal),+ },+ });+});++test('returns an actionable error if no focused Studio is available', async () => {+ const fetchFn = () => Promise.resolve(new Response(null, {status: 404}));++ const result = await installInStudioWithDependencies(dragData, {+ fetchFn,+ now: () => 1_000_000,+ ports: [3000],+ });++ expect(result).toEqual({+ success: false,+ reason:+ 'Focus the Remotion Studio you want to install into, then click again.',+ });+});++test('returns the error from Studio if installation is rejected', async () => {+ const fetchFn = (input: string | URL | Request) => {+ const url = String(input);+ if (url.endsWith('/api/element-install-target')) {+ return Promise.resolve(+ jsonResponse(target({lastFocusedAt: 950_000, projectName: 'Project'})),+ );+ }++ return Promise.resolve(+ jsonResponse({success: false, reason: 'No active composition'}, 409),+ );+ };++ const result = await installInStudioWithDependencies(dragData, {+ fetchFn,+ now: () => 1_000_000,+ ports: [3000],+ });++ expect(result).toEqual({+ success: false,+ reason: 'No active composition',+ });+});