🎥 Make videos programmatically with React
unsubscribe from file watcher if closing websocket connection
Jonny Burger683dc8fcd48e
diff --git a/packages/cli/src/editor/components/EditorContexts.tsx b/packages/cli/src/editor/components/EditorContexts.tsxindex 509c94d13e..524eda76ae 100644--- a/packages/cli/src/editor/components/EditorContexts.tsx+++ b/packages/cli/src/editor/components/EditorContexts.tsx@@ -5,6 +5,7 @@ import type {SetMediaVolumeContextValue,} from 'remotion';import {Internals} from 'remotion';+import {PreviewServerConnection} from '../helpers/client-id';import {CheckerboardContext,loadCheckerboardOption,@@ -118,44 +119,46 @@ export const EditorContexts: React.FC<{}, [modalContextType]);return (- <RenderQueueContextProvider>- <KeybindingContextProvider>- <RichTimelineContext.Provider value={richTimelineCtx}>- <CheckerboardContext.Provider value={checkerboardCtx}>- <PreviewSizeProvider>- <ModalsContext.Provider value={modalsContext}>- <Internals.MediaVolumeContext.Provider- value={mediaVolumeContextValue}- >- <Internals.SetMediaVolumeContext.Provider- value={setMediaVolumeContextValue}+ <PreviewServerConnection>+ <RenderQueueContextProvider>+ <KeybindingContextProvider>+ <RichTimelineContext.Provider value={richTimelineCtx}>+ <CheckerboardContext.Provider value={checkerboardCtx}>+ <PreviewSizeProvider>+ <ModalsContext.Provider value={modalsContext}>+ <Internals.MediaVolumeContext.Provider+ value={mediaVolumeContextValue}>- <PlayerInternals.PlayerEventEmitterContext.Provider- value={emitter}+ <Internals.SetMediaVolumeContext.Provider+ value={setMediaVolumeContextValue}>- <SidebarContextProvider>- <FolderContextProvider>- <HighestZIndexProvider>- <TimelineInOutContext.Provider- value={timelineInOutContextValue}- >- <SetTimelineInOutContext.Provider- value={setTimelineInOutContextValue}+ <PlayerInternals.PlayerEventEmitterContext.Provider+ value={emitter}+ >+ <SidebarContextProvider>+ <FolderContextProvider>+ <HighestZIndexProvider>+ <TimelineInOutContext.Provider+ value={timelineInOutContextValue}>- {children}- </SetTimelineInOutContext.Provider>- </TimelineInOutContext.Provider>- </HighestZIndexProvider>- </FolderContextProvider>- </SidebarContextProvider>- </PlayerInternals.PlayerEventEmitterContext.Provider>- </Internals.SetMediaVolumeContext.Provider>- </Internals.MediaVolumeContext.Provider>- </ModalsContext.Provider>- </PreviewSizeProvider>- </CheckerboardContext.Provider>- </RichTimelineContext.Provider>- </KeybindingContextProvider>- </RenderQueueContextProvider>+ <SetTimelineInOutContext.Provider+ value={setTimelineInOutContextValue}+ >+ {children}+ </SetTimelineInOutContext.Provider>+ </TimelineInOutContext.Provider>+ </HighestZIndexProvider>+ </FolderContextProvider>+ </SidebarContextProvider>+ </PlayerInternals.PlayerEventEmitterContext.Provider>+ </Internals.SetMediaVolumeContext.Provider>+ </Internals.MediaVolumeContext.Provider>+ </ModalsContext.Provider>+ </PreviewSizeProvider>+ </CheckerboardContext.Provider>+ </RichTimelineContext.Provider>+ </KeybindingContextProvider>+ </RenderQueueContextProvider>+ </PreviewServerConnection>);};diff --git a/packages/cli/src/editor/components/Notifications/ServerDisconnected.tsx b/packages/cli/src/editor/components/Notifications/ServerDisconnected.tsxindex 1aaf667f89..0e6fca14ba 100644--- a/packages/cli/src/editor/components/Notifications/ServerDisconnected.tsx+++ b/packages/cli/src/editor/components/Notifications/ServerDisconnected.tsx@@ -1,4 +1,5 @@-import React, {createRef, useImperativeHandle, useState} from 'react';+import React, {createRef, useContext} from 'react';+import {PreviewServerConnectionCtx} from '../../helpers/client-id';const container: React.CSSProperties = {position: 'fixed',@@ -42,24 +43,9 @@ window.addEventListener('beforeunload', () => {});export const ServerDisconnected: React.FC = () => {- const [serverDisconnected, setServerDisconnected] = useState(false);+ const ctx = useContext(PreviewServerConnectionCtx);- useImperativeHandle(- serverDisconnectedRef,- () => {- return {- setServerDisconnected: () => {- setServerDisconnected(true);- },- setServerConnected: () => {- setServerDisconnected(false);- },- };- },- []- );-- if (!serverDisconnected) {+ if (ctx.type !== 'disconnected') {return null;}diff --git a/packages/cli/src/editor/components/RenderQueue/actions.ts b/packages/cli/src/editor/components/RenderQueue/actions.tsindex e444928114..765af6a95c 100644--- a/packages/cli/src/editor/components/RenderQueue/actions.ts+++ b/packages/cli/src/editor/components/RenderQueue/actions.ts@@ -95,16 +95,27 @@ export const addVideoRenderJob = ({});};-export const unsubscribeFromFileExistenceWatcher = ({file}: {file: string}) => {- return callApi('/api/unsubscribe-from-file-existence', {file});+export const unsubscribeFromFileExistenceWatcher = ({+ file,+ clientId,+}: {+ file: string;+ clientId: string;+}) => {+ return callApi('/api/unsubscribe-from-file-existence', {file, clientId});};export const subscribeToFileExistenceWatcher = async ({file,+ clientId,}: {file: string;+ clientId: string;}): Promise<boolean> => {- const {exists} = await callApi('/api/subscribe-to-file-existence', {file});+ const {exists} = await callApi('/api/subscribe-to-file-existence', {+ file,+ clientId,+ });return exists;};diff --git a/packages/cli/src/editor/helpers/client-id.tsx b/packages/cli/src/editor/helpers/client-id.tsxnew file mode 100644index 0000000000..40b852b05d--- /dev/null+++ b/packages/cli/src/editor/helpers/client-id.tsx@@ -0,0 +1,49 @@+import React, {createRef, useImperativeHandle} from 'react';++type PreviewServerState =+ | {+ type: 'init';+ }+ | {+ type: 'connected';+ clientId: string;+ }+ | {+ type: 'disconnected';+ };++export const PreviewServerConnectionCtx =+ React.createContext<PreviewServerState>({+ type: 'init',+ });++export const previewServerConnectionRef = createRef<{+ set: (jobs: PreviewServerState) => void;+}>();++export const PreviewServerConnection: React.FC<{+ children: React.ReactNode;+ type: 'editor';+}> = ({children}) => {+ const [state, setState] = React.useState<PreviewServerState>({+ type: 'init',+ });++ useImperativeHandle(+ previewServerConnectionRef,+ () => {+ return {+ set: (newState) => {+ setState(newState);+ },+ };+ },+ []+ );++ return (+ <PreviewServerConnectionCtx.Provider value={state}>+ {children}+ </PreviewServerConnectionCtx.Provider>+ );+};diff --git a/packages/cli/src/editor/helpers/use-file-existence.ts b/packages/cli/src/editor/helpers/use-file-existence.tsindex 3d2aeb407c..74e41fe789 100644--- a/packages/cli/src/editor/helpers/use-file-existence.ts+++ b/packages/cli/src/editor/helpers/use-file-existence.ts@@ -1,27 +1,39 @@-import {useEffect, useRef, useState} from 'react';+import {useContext, useEffect, useRef, useState} from 'react';import {subscribeToEvent} from '../../event-source';import type {EventSourceEvent} from '../../event-source-events';import {subscribeToFileExistenceWatcher,unsubscribeFromFileExistenceWatcher,} from '../components/RenderQueue/actions';+import {PreviewServerConnectionCtx} from './client-id';export const useFileExistence = (outName: string) => {const [exists, setExists] = useState(false);++ const state = useContext(PreviewServerConnectionCtx);+ const clientId = state.type === 'connected' ? state.clientId : undefined;+const currentOutName = useRef('');currentOutName.current = outName;useEffect(() => {- subscribeToFileExistenceWatcher({file: outName}).then((_exists) => {+ if (!clientId) {+ return;+ }++ subscribeToFileExistenceWatcher({+ file: outName,+ clientId,+ }).then((_exists) => {if (currentOutName.current === outName) {setExists(_exists);}});return () => {- unsubscribeFromFileExistenceWatcher({file: outName});+ unsubscribeFromFileExistenceWatcher({file: outName, clientId});};- }, [outName]);+ }, [clientId, outName]);useEffect(() => {const listener = (event: EventSourceEvent) => {diff --git a/packages/cli/src/event-source-events.ts b/packages/cli/src/event-source-events.tsindex 1d49b5df46..2fbe6d3279 100644--- a/packages/cli/src/event-source-events.ts+++ b/packages/cli/src/event-source-events.ts@@ -7,6 +7,7 @@ export type EventSourceEvent =}| {type: 'init';+ clientId: string;}| {type: 'new-env-variables';diff --git a/packages/cli/src/event-source.ts b/packages/cli/src/event-source.tsindex 3b5e794877..bd33d839f1 100644--- a/packages/cli/src/event-source.ts+++ b/packages/cli/src/event-source.ts@@ -1,6 +1,6 @@import {notificationCenter} from './editor/components/Notifications/NotificationCenter';-import {serverDisconnectedRef} from './editor/components/Notifications/ServerDisconnected';import {renderJobsRef} from './editor/components/RenderQueue/context';+import {previewServerConnectionRef} from './editor/helpers/client-id';import type {EventSourceEvent} from './event-source-events';let source: EventSource | null = null;@@ -35,6 +35,13 @@ export const openEventSource = () => {window.location.reload();}+ if (newEvent.type === 'init') {+ previewServerConnectionRef.current?.set({+ type: 'connected',+ clientId: newEvent.clientId,+ });+ }+if (newEvent.type === 'render-queue-updated') {renderJobsRef.current?.updateRenderJobs(newEvent.queue);}@@ -56,13 +63,11 @@ export const openEventSource = () => {});source.addEventListener('open', () => {- serverDisconnectedRef.current?.setServerConnected();-(source as EventSource).addEventListener('error',() => {+ previewServerConnectionRef.current?.set({type: 'disconnected'});// Display an error message that the preview server has disconnected.- serverDisconnectedRef.current?.setServerDisconnected();source?.close();// Retry laterdiff --git a/packages/cli/src/preview-server/file-existence-watchers.ts b/packages/cli/src/preview-server/file-existence-watchers.tsindex 48c295ccd9..7b00176167 100644--- a/packages/cli/src/preview-server/file-existence-watchers.ts+++ b/packages/cli/src/preview-server/file-existence-watchers.ts@@ -2,14 +2,16 @@ import path from 'path';import {installFileWatcher} from '../file-watcher';import {waitForLiveEventsListener} from './live-events';-const fileExistenceWatchers: Record<string, () => void> = {};+const fileExistenceWatchers: Record<string, Record<string, () => void>> = {};export const subscribeToFileExistenceWatchers = ({file: relativeFile,remotionRoot,+ clientId,}: {file: string;remotionRoot: string;+ clientId: string;}): {exists: boolean} => {const file = path.resolve(remotionRoot, relativeFile);@@ -37,7 +39,11 @@ export const subscribeToFileExistenceWatchers = ({}},});- fileExistenceWatchers[file] = unwatch;+ if (!fileExistenceWatchers[clientId]) {+ fileExistenceWatchers[clientId] = {};+ }++ fileExistenceWatchers[clientId][file] = unwatch;return {exists};};@@ -45,11 +51,29 @@ export const subscribeToFileExistenceWatchers = ({export const unsubscribeFromFileExistenceWatchers = ({file,remotionRoot,+ clientId,}: {file: string;remotionRoot: string;+ clientId: string;}) => {const actualPath = path.resolve(remotionRoot, file);- fileExistenceWatchers[actualPath]?.();- delete fileExistenceWatchers[actualPath];+ if (!fileExistenceWatchers[clientId]) {+ return;+ }++ fileExistenceWatchers[clientId][actualPath]?.();+ delete fileExistenceWatchers[clientId][actualPath];+};++export const unsubscribeClientFileExistenceWatchers = (clientId: string) => {+ if (!fileExistenceWatchers[clientId]) {+ return;+ }++ Object.values(fileExistenceWatchers[clientId]).forEach((unwatch) => {+ unwatch();+ });++ delete fileExistenceWatchers[clientId];};diff --git a/packages/cli/src/preview-server/live-events.ts b/packages/cli/src/preview-server/live-events.tsindex 79980adbed..70f4df1a35 100644--- a/packages/cli/src/preview-server/live-events.ts+++ b/packages/cli/src/preview-server/live-events.ts@@ -1,5 +1,6 @@import type {IncomingMessage, OutgoingHttpHeaders, ServerResponse} from 'http';import type {EventSourceEvent} from '../event-source-events';+import {unsubscribeClientFileExistenceWatchers} from './file-existence-watchers';type Client = {id: string;@@ -31,9 +32,8 @@ export const makeLiveEventsRouter = (): LiveEventsServer => {return;}- response.write(serializeMessage({type: 'init'}));-const clientId = String(Math.random());+ response.write(serializeMessage({type: 'init', clientId}));const newClient = {id: clientId,@@ -42,6 +42,7 @@ export const makeLiveEventsRouter = (): LiveEventsServer => {clients.push(newClient);request.on('close', () => {+ unsubscribeClientFileExistenceWatchers(clientId);clients = clients.filter((client) => client.id !== clientId);});};diff --git a/packages/cli/src/preview-server/render-queue/job.ts b/packages/cli/src/preview-server/render-queue/job.tsindex ea02730ae3..c7aca83310 100644--- a/packages/cli/src/preview-server/render-queue/job.ts+++ b/packages/cli/src/preview-server/render-queue/job.ts@@ -90,6 +90,7 @@ export type OpenInFileExplorerRequest = {export type SubscribeToFileExistenceRequest = {file: string;+ clientId: string;};export type SubscribeToFileExistenceResponse = {@@ -98,4 +99,5 @@ export type SubscribeToFileExistenceResponse = {export type UnsubscribeFromFileExistenceRequest = {file: string;+ clientId: string;};diff --git a/packages/cli/src/preview-server/routes/subscribe-to-file-existence.ts b/packages/cli/src/preview-server/routes/subscribe-to-file-existence.tsindex 1d2e75e73d..22b4349b39 100644--- a/packages/cli/src/preview-server/routes/subscribe-to-file-existence.ts+++ b/packages/cli/src/preview-server/routes/subscribe-to-file-existence.ts@@ -8,11 +8,11 @@ import type {export const subscribeToFileExistence: ApiHandler<SubscribeToFileExistenceRequest,SubscribeToFileExistenceResponse-> = ({input: {file}, remotionRoot}) => {- // TODO: What if the user reloads the page? The file watcher doesn't get cleared+> = ({input: {file, clientId}, remotionRoot}) => {const {exists} = subscribeToFileExistenceWatchers({file,remotionRoot,+ clientId,});return Promise.resolve({exists});diff --git a/packages/cli/src/preview-server/routes/unsubscribe-from-file-existence.ts b/packages/cli/src/preview-server/routes/unsubscribe-from-file-existence.tsindex 58dee9fbc1..c39a22dd88 100644--- a/packages/cli/src/preview-server/routes/unsubscribe-from-file-existence.ts+++ b/packages/cli/src/preview-server/routes/unsubscribe-from-file-existence.ts@@ -6,6 +6,10 @@ export const unsubscribeFromFileExistence: ApiHandler<UnsubscribeFromFileExistenceRequest,undefined> = ({input, remotionRoot}) => {- unsubscribeFromFileExistenceWatchers({file: input.file, remotionRoot});+ unsubscribeFromFileExistenceWatchers({+ file: input.file,+ clientId: input.clientId,+ remotionRoot,+ });return Promise.resolve(undefined);};diff --git a/packages/cli/src/previewEntry.tsx b/packages/cli/src/previewEntry.tsxindex 894b68b97d..7fdc9b5fcf 100644--- a/packages/cli/src/previewEntry.tsx+++ b/packages/cli/src/previewEntry.tsx@@ -1,4 +1,5 @@import type {render} from 'react-dom';+import {createPortal} from 'react-dom';import ReactDOM from 'react-dom/client';// eslint-disable-next-line no-restricted-importsimport {Internals} from 'remotion';@@ -20,6 +21,10 @@ const content = (<Internals.RemotionRoot numberOfAudioTags={window.remotion_numberOfAudioTags}><EditorContexts><Editor />+ {createPortal(+ <ServerDisconnected />,+ getServerDisconnectedDomElement() as HTMLElement+ )}</EditorContexts></Internals.RemotionRoot>);@@ -28,18 +33,11 @@ if (ReactDOM.createRoot) {ReactDOM.createRoot(Internals.getPreviewDomElement() as HTMLElement).render(content);- ReactDOM.createRoot(getServerDisconnectedDomElement() as HTMLElement).render(- <ServerDisconnected />- );} else {(ReactDOM as unknown as {render: typeof render}).render(content,Internals.getPreviewDomElement());- (ReactDOM as unknown as {render: typeof render}).render(- <ServerDisconnected />,- getServerDisconnectedDomElement()- );}openEventSource();