π₯ Make videos programmatically with React
`@remotion/studio`: Share subscription if many sequences have the same stack (#7279)
Jonny Burger1151724dcd03
diff --git a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts b/packages/studio/src/components/Timeline/sequence-props-subscription-store.tsnew file mode 100644index 0000000000..05df6263a8--- /dev/null+++ b/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts@@ -0,0 +1,222 @@+import type {EventSourceEvent, SequenceNodePath} from '@remotion/studio-shared';+import {Internals, type CanUpdateSequencePropStatus} from 'remotion';+import type {SequenceSchema} from 'remotion';+import {callApi} from '../call-api';++export type SequencePropsSnapshot = {+ nodePath: SequenceNodePath | null;+ jsxInMapCallback: boolean;+ props: Record<string, CanUpdateSequencePropStatus> | null;+};++const INITIAL_SNAPSHOT: SequencePropsSnapshot = {+ nodePath: null,+ jsxInMapCallback: false,+ props: null,+};++type SubscribeToEvent = (+ type: EventSourceEvent['type'],+ listener: (event: EventSourceEvent) => void,+) => () => void;++type Entry = {+ clientId: string;+ fileName: string;+ refCount: number;+ snapshot: SequencePropsSnapshot;+ listeners: Set<(s: SequencePropsSnapshot) => void>;+ tornDown: boolean;+};++const entries = new Map<string, Entry>();+let globalUnsubscribe: (() => void) | null = null;++const makeKey = (fileName: string, line: number, column: number): string =>+ `${fileName}|${line}|${column}`;++const nodePathsEqual = (+ a: SequenceNodePath | null,+ b: SequenceNodePath | null,+): boolean => {+ if (!a || !b) {+ return false;+ }++ return JSON.stringify(a) === JSON.stringify(b);+};++const notify = (entry: Entry) => {+ for (const listener of entry.listeners) {+ listener(entry.snapshot);+ }+};++const handleEvent = (event: EventSourceEvent) => {+ if (event.type !== 'sequence-props-updated') {+ return;+ }++ for (const entry of entries.values()) {+ if (entry.fileName !== event.fileName) {+ continue;+ }++ if (!nodePathsEqual(entry.snapshot.nodePath, event.nodePath)) {+ continue;+ }++ if (event.result.canUpdate) {+ entry.snapshot = {+ nodePath: entry.snapshot.nodePath,+ jsxInMapCallback: event.result.jsxInMapCallback,+ props: event.result.props,+ };+ } else {+ entry.snapshot = {+ nodePath: entry.snapshot.nodePath,+ jsxInMapCallback: false,+ props: null,+ };+ }++ notify(entry);+ }+};++const ensureGlobalListener = (subscribeToEvent: SubscribeToEvent) => {+ if (globalUnsubscribe) {+ return;+ }++ globalUnsubscribe = subscribeToEvent('sequence-props-updated', handleEvent);+};++const teardownGlobalListenerIfEmpty = () => {+ if (entries.size > 0) {+ return;+ }++ if (globalUnsubscribe) {+ globalUnsubscribe();+ globalUnsubscribe = null;+ }+};++const fireUnsubscribe = (+ fileName: string,+ nodePath: SequenceNodePath,+ clientId: string,+) => {+ callApi('/api/unsubscribe-from-sequence-props', {+ fileName,+ nodePath,+ clientId,+ }).catch(() => {+ // Ignore unsubscribe errors+ });+};++export const acquireSequencePropsSubscription = ({+ clientId,+ fileName,+ line,+ column,+ schema,+ subscribeToEvent,+ onChange,+}: {+ clientId: string;+ fileName: string;+ line: number;+ column: number;+ schema: SequenceSchema;+ subscribeToEvent: SubscribeToEvent;+ onChange: (snapshot: SequencePropsSnapshot) => void;+}): (() => void) => {+ const key = makeKey(fileName, line, column);+ let entry = entries.get(key);++ if (!entry) {+ const newEntry: Entry = {+ clientId,+ fileName,+ refCount: 0,+ snapshot: INITIAL_SNAPSHOT,+ listeners: new Set(),+ tornDown: false,+ };+ entries.set(key, newEntry);+ ensureGlobalListener(subscribeToEvent);++ callApi('/api/subscribe-to-sequence-props', {+ fileName,+ line,+ column,+ schema,+ clientId,+ })+ .then((result) => {+ if (newEntry.tornDown) {+ if (result.canUpdate) {+ fireUnsubscribe(fileName, result.nodePath, clientId);+ }++ return;+ }++ if (result.canUpdate) {+ newEntry.snapshot = {+ nodePath: result.nodePath,+ jsxInMapCallback: result.jsxInMapCallback,+ props: result.props,+ };+ } else {+ newEntry.snapshot = INITIAL_SNAPSHOT;+ }++ notify(newEntry);+ })+ .catch((err) => {+ if (newEntry.tornDown) {+ return;+ }++ Internals.Log.error(err);+ newEntry.snapshot = INITIAL_SNAPSHOT;+ notify(newEntry);+ });++ entry = newEntry;+ }++ entry.refCount += 1;+ entry.listeners.add(onChange);+ onChange(entry.snapshot);++ let released = false;+ return () => {+ if (released) {+ return;+ }++ released = true;+ const e = entry as Entry;+ e.listeners.delete(onChange);+ e.refCount -= 1;++ if (e.refCount > 0) {+ return;+ }++ e.tornDown = true;+ const resolvedNodePath = e.snapshot.nodePath;+ entries.delete(key);++ if (resolvedNodePath) {+ fireUnsubscribe(e.fileName, resolvedNodePath, e.clientId);+ }++ teardownGlobalListenerIfEmpty();+ };+};diff --git a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts b/packages/studio/src/components/Timeline/use-sequence-props-subscription.tsindex a1672442dc..1a7600c765 100644--- a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts+++ b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts@@ -1,4 +1,4 @@-import type {EventSourceEvent, SequenceNodePath} from '@remotion/studio-shared';+import type {SequenceNodePath} from '@remotion/studio-shared';import {useCallback,useContext,@@ -11,7 +11,15 @@ import {Internals, type CanUpdateSequencePropStatus} from 'remotion';import type {TSequence} from 'remotion';import type {OriginalPosition} from '../../error-overlay/react-overlay/utils/get-source-map';import {StudioServerConnectionCtx} from '../../helpers/client-id';-import {callApi} from '../call-api';+import {+ acquireSequencePropsSubscription,+ type SequencePropsSnapshot,+} from './sequence-props-subscription-store';++const EMPTY_STATE = {+ nodePath: null as SequenceNodePath | null,+ jsxInMapCallback: false,+};export const useSequencePropsSubscription = (sequence: TSequence,@@ -56,32 +64,10 @@ export const useSequencePropsSubscription = (};}, [originalLocation]);- const locationSource = validatedLocation?.source ?? null;- const locationLine = validatedLocation?.line ?? null;- const locationColumn = validatedLocation?.column ?? null;-- const currentLocationSource = useRef(locationSource);- currentLocationSource.current = locationSource;- const currentLocationLine = useRef(locationLine);- currentLocationLine.current = locationLine;- const currentLocationColumn = useRef(locationColumn);- currentLocationColumn.current = locationColumn;-- const nodePathRef = useRef<SequenceNodePath | null>(null);- const [subscriptionState, setSubscriptionState] = useState<{- nodePath: SequenceNodePath | null;- jsxInMapCallback: boolean;- }>({nodePath: null, jsxInMapCallback: false});+ const [subscriptionState, setSubscriptionState] =+ useState<typeof EMPTY_STATE>(EMPTY_STATE);const isMountedRef = useRef(true);- const updateSubscriptionState = useCallback(- (next: {nodePath: SequenceNodePath | null; jsxInMapCallback: boolean}) => {- nodePathRef.current = next.nodePath;- setSubscriptionState(next);- },- [],- );-useEffect(() => {isMountedRef.current = true;return () => {@@ -89,10 +75,15 @@ export const useSequencePropsSubscription = (};}, []);+ const schema = sequence.controls?.schema;+ const locationSource = validatedLocation?.source ?? null;+ const locationLine = validatedLocation?.line ?? null;+ const locationColumn = validatedLocation?.column ?? null;+useEffect(() => {if (!visualModeEnabled) {setPropStatusesForSequence(null);- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});+ setSubscriptionState(EMPTY_STATE);return;}@@ -100,130 +91,49 @@ export const useSequencePropsSubscription = (!clientId ||!locationSource ||!locationLine ||- locationColumn === null+ locationColumn === null ||+ !schema) {setPropStatusesForSequence(null);- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});+ setSubscriptionState(EMPTY_STATE);return;}- const schema = sequence.controls?.schema;- if (!schema) {- setPropStatusesForSequence(null);- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});- return;- }+ const onChange = (snapshot: SequencePropsSnapshot) => {+ setSubscriptionState({+ nodePath: snapshot.nodePath,+ jsxInMapCallback: snapshot.jsxInMapCallback,+ });+ setPropStatusesForSequence(snapshot.props);+ };- callApi('/api/subscribe-to-sequence-props', {+ const release = acquireSequencePropsSubscription({+ clientId,fileName: locationSource,line: locationLine,column: locationColumn,schema,- clientId,- })- .then((result) => {- if (- currentLocationSource.current !== locationSource ||- currentLocationLine.current !== locationLine ||- currentLocationColumn.current !== locationColumn- ) {- return;- }-- if (result.canUpdate) {- updateSubscriptionState({- nodePath: result.nodePath,- jsxInMapCallback: result.jsxInMapCallback,- });- setPropStatusesForSequence(result.props);- } else {- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});- setPropStatusesForSequence(null);- }- })- .catch((err) => {- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});- Internals.Log.error(err);- setPropStatusesForSequence(null);- });+ subscribeToEvent,+ onChange,+ });return () => {- const currentNodePath = nodePathRef.current;+ release();// Only clear props on true unmount, not on re-subscribe due to- // line number changes β avoids flicker while re-subscribing.+ // location changes β avoids flicker while re-subscribing.if (!isMountedRef.current) {setPropStatusesForSequence(null);}-- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});- if (currentNodePath) {- callApi('/api/unsubscribe-from-sequence-props', {- fileName: locationSource,- nodePath: currentNodePath,- clientId,- }).catch(() => {- // Ignore unsubscribe errors- });- }};}, [clientId,locationColumn,locationLine,locationSource,- sequence.controls?.schema,+ schema,setPropStatusesForSequence,- updateSubscriptionState,- visualModeEnabled,- ]);-- useEffect(() => {- if (!visualModeEnabled) {- return;- }-- if (!locationSource || !locationLine || locationColumn === null) {- return;- }-- const listener = (event: EventSourceEvent) => {- if (event.type !== 'sequence-props-updated') {- return;- }-- if (- event.fileName !== currentLocationSource.current ||- !nodePathRef.current ||- JSON.stringify(event.nodePath) !== JSON.stringify(nodePathRef.current)- ) {- return;- }-- if (event.result.canUpdate) {- const {jsxInMapCallback: nextJsxInMapCallback, props} = event.result;- setSubscriptionState((prev) => ({- nodePath: prev.nodePath,- jsxInMapCallback: nextJsxInMapCallback,- }));- setPropStatusesForSequence(props);- } else {- setPropStatusesForSequence(null);- updateSubscriptionState({nodePath: null, jsxInMapCallback: false});- }- };-- const unsub = subscribeToEvent('sequence-props-updated', listener);- return () => {- unsub();- };- }, [- visualModeEnabled,- locationSource,- locationLine,- locationColumn,subscribeToEvent,- setPropStatusesForSequence,- updateSubscriptionState,+ visualModeEnabled,]);return subscriptionState;