🎥 Make videos programmatically with React
`@remotion/studio`: Request element install targets on demand (#9025)
Jonny Burger84d8caeef224
diff --git a/packages/studio-server/src/preview-server/element-install-state.ts b/packages/studio-server/src/preview-server/element-install-state.tsindex 883e2948c0..50f39cf19c 100644--- a/packages/studio-server/src/preview-server/element-install-state.ts+++ b/packages/studio-server/src/preview-server/element-install-state.ts@@ -1,6 +1,7 @@export const ELEMENT_INSTALL_TARGET_MAX_AGE = 5000;export type ElementInstallTarget = {+ requestId: string | null;clientId: string;compositionFile: string | null;compositionId: string | null;@@ -32,7 +33,7 @@ export const updateElementInstallTarget = (});};-export const getElementInstallTarget = () => {+export const getElementInstallTarget = (requestId: string | null) => {const now = Date.now();let bestTarget: ElementInstallTarget | null = null;@@ -42,6 +43,10 @@ export const getElementInstallTarget = () => {continue;}+ if (requestId !== null && currentTarget.requestId !== requestId) {+ continue;+ }+if (bestTarget === null || compareTargets(currentTarget, bestTarget) > 0) {bestTarget = currentTarget;}diff --git a/packages/studio-server/src/preview-server/routes/update-element-install-target.ts b/packages/studio-server/src/preview-server/routes/update-element-install-target.tsindex 7cafc2d9ab..3106e75688 100644--- a/packages/studio-server/src/preview-server/routes/update-element-install-target.ts+++ b/packages/studio-server/src/preview-server/routes/update-element-install-target.ts@@ -17,6 +17,10 @@ export const updateElementInstallTargetHandler: ApiHandler<throw new Error('Invalid client ID');}+ if (input.requestId !== null && typeof input.requestId !== 'string') {+ throw new Error('Invalid request ID');+ }+if (!isFiniteTimestamp(input.lastFocusedAt)) {throw new Error('Invalid focus timestamp');}diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex b07aebb69e..ef22fc9a69 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -38,6 +38,7 @@ import {reloadPreviouslySuppressedFiles} from './preview-server/watch-ignore-neximport type {RemotionConfigResponse} from './remotion-config-response';const loggedStaticFileHints = new Set<string>();const ELEMENT_INSTALL_FOCUS_MAX_AGE = 5 * 60 * 1000;+const ELEMENT_INSTALL_TARGET_RESPONSE_WAIT = 250;const static404 = (response: ServerResponse): Promise<void> => {response.writeHead(404);@@ -124,11 +125,13 @@ const handleElementInstallOptions = ({};const handleElementInstallTarget = ({+ liveEventsServer,request,response,remotionRoot,gitSource,}: {+ liveEventsServer: LiveEventsServer;request: IncomingMessage;response: ServerResponse;remotionRoot: string;@@ -142,30 +145,42 @@ const handleElementInstallTarget = ({return Promise.resolve();}- const target = getElementInstallTarget();- const now = Date.now();- const targetIsLive =- target !== null && now - target.updatedAt < ELEMENT_INSTALL_TARGET_MAX_AGE;- const host = request.headers.host ?? null;- const port = host?.split(':').at(-1) ?? null;- setElementInstallCorsHeaders({request, response});- response.writeHead(200, {'Content-Type': 'application/json'});- response.end(- JSON.stringify({- type: 'remotion-studio',- projectName: getProjectName({- basename: path.basename,- gitSource,- resolvedRemotionRoot: remotionRoot,- }),- port: port === null ? null : Number(port),- lastFocusedAt: target?.lastFocusedAt ?? null,- canInstall: target !== null && target.canInstall && targetIsLive,- activeCompositionId: target?.compositionId ?? null,- readOnly: target?.readOnly ?? false,- }),- );- return Promise.resolve();+ const requestId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;++ liveEventsServer.sendEventToClient({+ type: 'request-element-install-target',+ requestId,+ });++ return new Promise<void>((resolve) => {+ setTimeout(() => {+ const target = getElementInstallTarget(requestId);+ const now = Date.now();+ const targetIsLive =+ target !== null &&+ now - target.updatedAt < ELEMENT_INSTALL_TARGET_MAX_AGE;+ const host = request.headers.host ?? null;+ const port = host?.split(':').at(-1) ?? null;+ setElementInstallCorsHeaders({request, response});+ response.writeHead(200, {'Content-Type': 'application/json'});+ response.end(+ JSON.stringify({+ type: 'remotion-studio',+ projectName: getProjectName({+ basename: path.basename,+ gitSource,+ resolvedRemotionRoot: remotionRoot,+ }),+ port: port === null ? null : Number(port),+ lastFocusedAt: target?.lastFocusedAt ?? null,+ canInstall: target !== null && target.canInstall && targetIsLive,+ activeCompositionId: target?.compositionId ?? null,+ readOnly: target?.readOnly ?? false,+ }),+ );+ resolve();+ }, ELEMENT_INSTALL_TARGET_RESPONSE_WAIT);+ });};const handleRequestElementInstall = async ({@@ -206,7 +221,7 @@ const handleRequestElementInstall = async ({return;}- const target = getElementInstallTarget();+ const target = getElementInstallTarget(null);const now = Date.now();const targetIsLive =target !== null &&@@ -641,6 +656,7 @@ export const handleRoutes = ({if (url.pathname === '/api/element-install-target') {return handleElementInstallTarget({+ liveEventsServer,request,response,remotionRoot,diff --git a/packages/studio-server/src/test/element-install-state.test.ts b/packages/studio-server/src/test/element-install-state.test.tsindex 38a96d594d..aaa48b8239 100644--- a/packages/studio-server/src/test/element-install-state.test.ts+++ b/packages/studio-server/src/test/element-install-state.test.ts@@ -9,6 +9,7 @@ test('uses the most recently focused Studio target even when older tabs keep updclearElementInstallStateForTests();updateElementInstallTarget({+ requestId: null,clientId: 'older-tab',compositionFile: '/project/src/older.tsx',compositionId: 'older-composition',@@ -17,6 +18,7 @@ test('uses the most recently focused Studio target even when older tabs keep updreadOnly: false,});updateElementInstallTarget({+ requestId: null,clientId: 'focused-tab',compositionFile: '/project/src/focused.tsx',compositionId: 'focused-composition',@@ -25,6 +27,7 @@ test('uses the most recently focused Studio target even when older tabs keep updreadOnly: false,});updateElementInstallTarget({+ requestId: null,clientId: 'older-tab',compositionFile: '/project/src/older.tsx',compositionId: 'older-composition',@@ -33,13 +36,14 @@ test('uses the most recently focused Studio target even when older tabs keep updreadOnly: false,});- expect(getElementInstallTarget()?.clientId).toBe('focused-tab');+ expect(getElementInstallTarget(null)?.clientId).toBe('focused-tab');});test('falls back to update recency when focus timestamps match', async () => {clearElementInstallStateForTests();updateElementInstallTarget({+ requestId: null,clientId: 'first-tab',compositionFile: '/project/src/first.tsx',compositionId: 'first-composition',@@ -51,6 +55,7 @@ test('falls back to update recency when focus timestamps match', async () => {await new Promise((resolve) => setTimeout(resolve, 2));updateElementInstallTarget({+ requestId: null,clientId: 'second-tab',compositionFile: '/project/src/second.tsx',compositionId: 'second-composition',@@ -59,5 +64,33 @@ test('falls back to update recency when focus timestamps match', async () => {readOnly: false,});- expect(getElementInstallTarget()?.clientId).toBe('second-tab');+ expect(getElementInstallTarget(null)?.clientId).toBe('second-tab');+});++test('can select a target for a specific request', () => {+ clearElementInstallStateForTests();++ updateElementInstallTarget({+ requestId: 'first-request',+ clientId: 'first-tab',+ compositionFile: '/project/src/first.tsx',+ compositionId: 'first-composition',+ canInstall: true,+ lastFocusedAt: 1000,+ readOnly: false,+ });+ updateElementInstallTarget({+ requestId: 'second-request',+ clientId: 'second-tab',+ compositionFile: '/project/src/second.tsx',+ compositionId: 'second-composition',+ canInstall: true,+ lastFocusedAt: 2000,+ readOnly: false,+ });++ expect(getElementInstallTarget('first-request')?.clientId).toBe('first-tab');+ expect(getElementInstallTarget('second-request')?.clientId).toBe(+ 'second-tab',+ );});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 6bbe0c1b80..52ccbd9612 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -768,6 +768,7 @@ export type ElementInstallRequest = {};export type UpdateElementInstallTargetRequest = {+ requestId: string | null;clientId: string;compositionFile: string | null;compositionId: string | null;diff --git a/packages/studio-shared/src/event-source-event.ts b/packages/studio-shared/src/event-source-event.tsindex da33df0197..f95e94c194 100644--- a/packages/studio-shared/src/event-source-event.ts+++ b/packages/studio-shared/src/event-source-event.ts@@ -76,6 +76,10 @@ export type EventSourceEvent =undoFile: string | null;redoFile: string | null;}+ | {+ type: 'request-element-install-target';+ requestId: string;+ }| {type: 'element-install-request';request: ElementInstallRequest;diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 352ed517f6..bc384c8658 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -811,39 +811,33 @@ export const Canvas: React.FC<{fetchMetadata();}, [fetchMetadata]);- const updateElementInstallTarget = useCallback(() => {- if (previewServerClientId === null) {- return;- }-- callApi('/api/update-element-install-target', {- clientId: previewServerClientId,- compositionFile: canInstallElements ? compositionFile : null,- compositionId: canInstallElements ? currentCompositionId : null,- canInstall: canInstallElements,- lastFocusedAt: lastFocusedAtRef.current,- readOnly: window.remotion_isReadOnlyStudio,- }).catch(() => undefined);- }, [- canInstallElements,- compositionFile,- currentCompositionId,- previewServerClientId,- ]);-- useEffect(() => {- updateElementInstallTarget();- const interval = window.setInterval(updateElementInstallTarget, 2000);+ const updateElementInstallTarget = useCallback(+ (requestId: string) => {+ if (previewServerClientId === null) {+ return;+ }- return () => {- window.clearInterval(interval);- };- }, [updateElementInstallTarget]);+ callApi('/api/update-element-install-target', {+ requestId,+ clientId: previewServerClientId,+ compositionFile: canInstallElements ? compositionFile : null,+ compositionId: canInstallElements ? currentCompositionId : null,+ canInstall: canInstallElements,+ lastFocusedAt: lastFocusedAtRef.current,+ readOnly: window.remotion_isReadOnlyStudio,+ }).catch(() => undefined);+ },+ [+ canInstallElements,+ compositionFile,+ currentCompositionId,+ previewServerClientId,+ ],+ );useEffect(() => {const markFocused = () => {lastFocusedAtRef.current = Date.now();- updateElementInstallTarget();};window.addEventListener('focus', markFocused);@@ -853,7 +847,17 @@ export const Canvas: React.FC<{window.removeEventListener('focus', markFocused);document.removeEventListener('pointerdown', markFocused, {capture: true});};- }, [updateElementInstallTarget]);+ }, []);++ useEffect(() => {+ return subscribeToEvent('request-element-install-target', (event) => {+ if (event.type !== 'request-element-install-target') {+ return;+ }++ updateElementInstallTarget(event.requestId);+ });+ }, [subscribeToEvent, updateElementInstallTarget]);useEffect(() => {if (installingElementName === null) {