🎥 Make videos programmatically with React
save props mutex
Jonny Burgerb04836a8ead3
diff --git a/packages/studio-server/src/preview-server/routes/save-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-effect-props.tsindex 088488bf2a..82f93e319f 100644--- a/packages/studio-server/src/preview-server/routes/save-effect-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-effect-props.ts@@ -21,11 +21,12 @@ import {findJsxElementAtNodePath} from './can-update-sequence-props';import {formatEffectPropChange} from './log-updates/format-effect-prop-change';import {logEffectUpdate} from './log-updates/log-effect-update';import {normalizeQuotes} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';export const saveEffectPropsHandler: ApiHandler<SaveEffectPropsRequest,SaveEffectPropsResponse-> = async ({+> = ({input: {fileName,sequenceNodePath,@@ -37,106 +38,108 @@ export const saveEffectPropsHandler: ApiHandler<},remotionRoot,logLevel,-}) => {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[save-effect-props] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}"`,- );- const absolutePath = path.resolve(remotionRoot, fileName);- const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);- if (fileRelativeToRoot.startsWith('..')) {- throw new Error('Cannot modify a file outside the project');- }+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[save-effect-props] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}"`,+ );+ const absolutePath = path.resolve(remotionRoot, fileName);+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);+ if (fileRelativeToRoot.startsWith('..')) {+ throw new Error('Cannot modify a file outside the project');+ }- const fileContents = readFileSync(absolutePath, 'utf-8');+ const fileContents = readFileSync(absolutePath, 'utf-8');- const parsedDefault = defaultValue !== null ? JSON.parse(defaultValue) : null;+ const parsedDefault =+ defaultValue !== null ? JSON.parse(defaultValue) : null;- const {output, oldValueString, formatted, logLine, effectCallee} =- await updateEffectProps({- input: fileContents,- sequenceNodePath: sequenceNodePath.nodePath,- effectIndex,- update: {- key,- value: JSON.parse(value),- defaultValue: parsedDefault,- },- });+ const {output, oldValueString, formatted, logLine, effectCallee} =+ await updateEffectProps({+ input: fileContents,+ sequenceNodePath: sequenceNodePath.nodePath,+ effectIndex,+ update: {+ key,+ value: JSON.parse(value),+ defaultValue: parsedDefault,+ },+ });- const defaultValueString =- parsedDefault !== null ? JSON.stringify(parsedDefault) : null;+ const defaultValueString =+ parsedDefault !== null ? JSON.stringify(parsedDefault) : null;- const normalizedOld = normalizeQuotes(oldValueString);- const normalizedNew = normalizeQuotes(value);- const normalizedDefault =- defaultValueString !== null ? normalizeQuotes(defaultValueString) : null;+ const normalizedOld = normalizeQuotes(oldValueString);+ const normalizedNew = normalizeQuotes(value);+ const normalizedDefault =+ defaultValueString !== null ? normalizeQuotes(defaultValueString) : null;- const undoPropChange = formatEffectPropChange({- effectName: effectCallee,- key,- oldValueString: normalizedNew,- newValueString: normalizedOld,- defaultValueString: normalizedDefault,- removedProps: [],- addedProps: [],- });- const redoPropChange = formatEffectPropChange({- effectName: effectCallee,- key,- oldValueString: normalizedOld,- newValueString: normalizedNew,- defaultValueString: normalizedDefault,- removedProps: [],- addedProps: [],- });+ const undoPropChange = formatEffectPropChange({+ effectName: effectCallee,+ key,+ oldValueString: normalizedNew,+ newValueString: normalizedOld,+ defaultValueString: normalizedDefault,+ removedProps: [],+ addedProps: [],+ });+ const redoPropChange = formatEffectPropChange({+ effectName: effectCallee,+ key,+ oldValueString: normalizedOld,+ newValueString: normalizedNew,+ defaultValueString: normalizedDefault,+ removedProps: [],+ addedProps: [],+ });- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ ${undoPropChange}`,- redoMessage: `↪️ ${redoPropChange}`,- },- entryType: 'effect-props',- suppressHmrOnFileRestore: true,- });- suppressUndoStackInvalidation(absolutePath);- suppressBundlerUpdateForFile(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'effect-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output);- logEffectUpdate({- fileRelativeToRoot,- line: logLine,- effectName: effectCallee,- propKey: key,- oldValueString,- newValueString: value,- defaultValueString,- formatted,- logLevel,- removedProps: [],- addedProps: [],- });+ logEffectUpdate({+ fileRelativeToRoot,+ line: logLine,+ effectName: effectCallee,+ propKey: key,+ oldValueString,+ newValueString: value,+ defaultValueString,+ formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });- printUndoHint(logLevel);+ printUndoHint(logLevel);- const ast = parseAst(readFileSync(absolutePath, 'utf-8'));- const jsx = findJsxElementAtNodePath(ast, sequenceNodePath.nodePath);- if (!jsx) {- return {- canUpdate: false,- effectIndex,- reason: 'not-found',- };- }+ const ast = parseAst(readFileSync(absolutePath, 'utf-8'));+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath.nodePath);+ if (!jsx) {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-found',+ };+ }- return computeEffectPropStatus({- jsx,- effectIndex,- keys: getAllSchemaKeys(schema),+ return computeEffectPropStatus({+ jsx,+ effectIndex,+ keys: getAllSchemaKeys(schema),+ });});-};diff --git a/packages/studio-server/src/preview-server/routes/save-props-mutex.ts b/packages/studio-server/src/preview-server/routes/save-props-mutex.tsnew file mode 100644index 0000000000..2c9cc0aa41--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/save-props-mutex.ts@@ -0,0 +1,11 @@+let chain: Promise<unknown> = Promise.resolve();++export const withSavePropsLock = <T>(fn: () => Promise<T>): Promise<T> => {+ const run = () => fn();+ const next = chain.then(run, run);+ chain = next.then(+ () => undefined,+ () => undefined,+ );+ return next;+};diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex 738c20661c..498d7862c1 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -19,107 +19,111 @@ import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeSequencePropsOnlyStatus} from './can-update-sequence-props';import {formatPropChange} from './log-updates/format-prop-change';import {logUpdate, normalizeQuotes} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';export const saveSequencePropsHandler: ApiHandler<SaveSequencePropsRequest,SaveSequencePropsResponse-> = async ({+> = ({input: {fileName, nodePath, key, value, defaultValue, schema},remotionRoot,logLevel,-}) => {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[save-sequence-props] Received request for fileName="${fileName}" key="${key}"`,- );- const absolutePath = path.resolve(remotionRoot, fileName);- const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);- if (fileRelativeToRoot.startsWith('..')) {- throw new Error('Cannot modify a file outside the project');- }+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[save-sequence-props] Received request for fileName="${fileName}" key="${key}"`,+ );+ const absolutePath = path.resolve(remotionRoot, fileName);+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);+ if (fileRelativeToRoot.startsWith('..')) {+ throw new Error('Cannot modify a file outside the project');+ }- const fileContents = readFileSync(absolutePath, 'utf-8');+ const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, oldValueStrings, formatted, logLine, removedProps} =- await updateSequenceProps({- input: fileContents,- nodePath: nodePath.nodePath,- updates: [- {- key,- value: JSON.parse(value),- defaultValue: defaultValue !== null ? JSON.parse(defaultValue) : null,- },- ],- schema: NoReactInternals.sequenceSchema,- });- const oldValueString = oldValueStrings[0];+ const {output, oldValueStrings, formatted, logLine, removedProps} =+ await updateSequenceProps({+ input: fileContents,+ nodePath: nodePath.nodePath,+ updates: [+ {+ key,+ value: JSON.parse(value),+ defaultValue:+ defaultValue !== null ? JSON.parse(defaultValue) : null,+ },+ ],+ schema: NoReactInternals.sequenceSchema,+ });+ const oldValueString = oldValueStrings[0];- const newValueString = JSON.stringify(JSON.parse(value));- const parsedDefault = defaultValue !== null ? JSON.parse(defaultValue) : null;- const defaultValueString =- parsedDefault !== null ? JSON.stringify(parsedDefault) : null;+ const newValueString = JSON.stringify(JSON.parse(value));+ const parsedDefault =+ defaultValue !== null ? JSON.parse(defaultValue) : null;+ const defaultValueString =+ parsedDefault !== null ? JSON.stringify(parsedDefault) : null;- const normalizedOld = normalizeQuotes(oldValueString);- const normalizedNew = normalizeQuotes(newValueString);- const normalizedDefault =- defaultValueString !== null ? normalizeQuotes(defaultValueString) : null;+ const normalizedOld = normalizeQuotes(oldValueString);+ const normalizedNew = normalizeQuotes(newValueString);+ const normalizedDefault =+ defaultValueString !== null ? normalizeQuotes(defaultValueString) : null;- const undoPropChange = formatPropChange({- key,- oldValueString: normalizedNew,- newValueString: normalizedOld,- defaultValueString: normalizedDefault,- removedProps: [],- addedProps: removedProps,- });- const redoPropChange = formatPropChange({- key,- oldValueString: normalizedOld,- newValueString: normalizedNew,- defaultValueString: normalizedDefault,- removedProps,- addedProps: [],- });+ const undoPropChange = formatPropChange({+ key,+ oldValueString: normalizedNew,+ newValueString: normalizedOld,+ defaultValueString: normalizedDefault,+ removedProps: [],+ addedProps: removedProps,+ });+ const redoPropChange = formatPropChange({+ key,+ oldValueString: normalizedOld,+ newValueString: normalizedNew,+ defaultValueString: normalizedDefault,+ removedProps,+ addedProps: [],+ });- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ ${undoPropChange}`,- redoMessage: `↪️ ${redoPropChange}`,- },- entryType: 'sequence-props',- suppressHmrOnFileRestore: true,- });- suppressUndoStackInvalidation(absolutePath);- suppressBundlerUpdateForFile(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'sequence-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output);- logUpdate({- fileRelativeToRoot,- line: logLine,- key,- oldValueString,- newValueString,- defaultValueString,- formatted,- logLevel,- removedProps,- addedProps: [],- });+ logUpdate({+ fileRelativeToRoot,+ line: logLine,+ key,+ oldValueString,+ newValueString,+ defaultValueString,+ formatted,+ logLevel,+ removedProps,+ addedProps: [],+ });- printUndoHint(logLevel);+ printUndoHint(logLevel);- const newStatus = computeSequencePropsOnlyStatus({- fileName,- keys: getAllSchemaKeys(schema),- nodePath: nodePath.nodePath,- remotionRoot,- });+ const newStatus = computeSequencePropsOnlyStatus({+ fileName,+ keys: getAllSchemaKeys(schema),+ nodePath: nodePath.nodePath,+ remotionRoot,+ });- return newStatus;-};+ return newStatus;+ });diff --git a/packages/studio/src/components/Timeline/TimelineEffectFieldRow.tsx b/packages/studio/src/components/Timeline/TimelineEffectFieldRow.tsxindex df63b2a15e..c4fbacf5ca 100644--- a/packages/studio/src/components/Timeline/TimelineEffectFieldRow.tsx+++ b/packages/studio/src/components/Timeline/TimelineEffectFieldRow.tsx@@ -1,17 +1,13 @@import {optimisticUpdateForEffectCodeValues} from '@remotion/studio-shared';import React, {useCallback, useContext, useMemo} from 'react';-import type {- CanUpdateEffectPropsResponse,- CanUpdateSequencePropsResponse,- SequencePropsSubscriptionKey,-} from 'remotion';+import type {SequencePropsSubscriptionKey} from 'remotion';import {Internals} from 'remotion';import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-source-map';import type {EffectSchemaFieldInfo} from '../../helpers/timeline-layout';import {EXPANDED_SECTION_PADDING_RIGHT} from '../../helpers/timeline-layout';import {callApi} from '../call-api';-import {showNotification} from '../Notifications/NotificationCenter';import {Padder} from './Padder';+import {enqueueSavePropChange} from './save-prop-queue';import {TimelineFieldValue, UnsupportedStatus} from './TimelineSchemaField';const fieldRowBase: React.CSSProperties = {@@ -110,64 +106,48 @@ const Value: React.FC<{return Promise.resolve();}- let previousUpdate: CanUpdateSequencePropsResponse | undefined;-- setCodeValues(nodePath, (prev) => {- previousUpdate = prev;- return optimisticUpdateForEffectCodeValues({- previous: prev,- effectIndex: field.effectIndex,- fieldKey: field.key,- value,- schema: field.effectSchema,- });- });-- return callApi('/api/save-effect-props', {- fileName: validatedLocation.source,- sequenceNodePath: nodePath,- effectIndex: field.effectIndex,- key: field.key,- value: stringifiedValue,- defaultValue,- schema: field.effectSchema,- })- .then((data: CanUpdateEffectPropsResponse) => {- setCodeValues(nodePath, (prev) => {- if (!prev.canUpdate) {- return prev;- }-- const idx = prev.effects.findIndex(- (e) => e.effectIndex === field.effectIndex,- );- if (idx === -1) {- return {- ...prev,- effects: [...prev.effects, data],- };- }-- const next = [...prev.effects];- next[idx] = data;- return {...prev, effects: next};- });- })- .catch((err) => {- setCodeValues(nodePath, (current) => {- if (previousUpdate) {- return previousUpdate;- }-- return current;- });- showNotification(- `Could not save effect prop: ${- err instanceof Error ? err.message : String(err)- }`,- 4000,+ return enqueueSavePropChange({+ nodePath,+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticUpdateForEffectCodeValues({+ previous: prev,+ effectIndex: field.effectIndex,+ fieldKey: field.key,+ value,+ schema: field.effectSchema,+ }),+ apiCall: () =>+ callApi('/api/save-effect-props', {+ fileName: validatedLocation.source,+ sequenceNodePath: nodePath,+ effectIndex: field.effectIndex,+ key: field.key,+ value: stringifiedValue,+ defaultValue,+ schema: field.effectSchema,+ }),+ mergeServerResponse: (prev, data) => {+ if (!prev.canUpdate) {+ return prev;+ }++ const idx = prev.effects.findIndex(+ (e) => e.effectIndex === field.effectIndex,);- });+ if (idx === -1) {+ return {+ ...prev,+ effects: [...prev.effects, data],+ };+ }++ const nextEffects = [...prev.effects];+ nextEffects[idx] = data;+ return {...prev, effects: nextEffects};+ },+ errorLabel: 'Could not save effect prop',+ });},[field.effectIndex,diff --git a/packages/studio/src/components/Timeline/save-prop-queue.ts b/packages/studio/src/components/Timeline/save-prop-queue.tsnew file mode 100644index 0000000000..85ec316081--- /dev/null+++ b/packages/studio/src/components/Timeline/save-prop-queue.ts@@ -0,0 +1,119 @@+import type {+ CanUpdateSequencePropsResponse,+ SequencePropsSubscriptionKey,+} from 'remotion';+import {Internals} from 'remotion';+import {showNotification} from '../Notifications/NotificationCenter';++type SetCodeValues = (+ nodePath: SequencePropsSubscriptionKey,+ values: (+ prev: CanUpdateSequencePropsResponse,+ ) => CanUpdateSequencePropsResponse,+) => void;++type QueueState = {+ chain: Promise<unknown>;+ cancelled: boolean;+ committed: CanUpdateSequencePropsResponse | null;+};++const queues = new Map<string, QueueState>();++const getQueue = (nodePath: SequencePropsSubscriptionKey): QueueState => {+ const key = Internals.makeSequencePropsSubscriptionKey(nodePath);+ let q = queues.get(key);+ if (!q) {+ q = {chain: Promise.resolve(), cancelled: false, committed: null};+ queues.set(key, q);+ }++ return q;+};++const dropQueue = (+ nodePath: SequencePropsSubscriptionKey,+ q: QueueState,+): void => {+ const key = Internals.makeSequencePropsSubscriptionKey(nodePath);+ if (queues.get(key) === q) {+ queues.delete(key);+ }+};++export type EnqueueSaveOptions<TResponse> = {+ nodePath: SequencePropsSubscriptionKey;+ setCodeValues: SetCodeValues;+ applyOptimistic: (+ prev: CanUpdateSequencePropsResponse,+ ) => CanUpdateSequencePropsResponse;+ apiCall: () => Promise<TResponse>;+ mergeServerResponse: (+ prev: CanUpdateSequencePropsResponse,+ response: TResponse,+ ) => CanUpdateSequencePropsResponse;+ errorLabel: string;+};++export const enqueueSavePropChange = <TResponse>({+ nodePath,+ setCodeValues,+ applyOptimistic,+ apiCall,+ mergeServerResponse,+ errorLabel,+}: EnqueueSaveOptions<TResponse>): Promise<void> => {+ const q = getQueue(nodePath);++ if (q.cancelled) {+ return Promise.resolve();+ }++ setCodeValues(nodePath, (prev) => {+ if (q.committed === null) {+ q.committed = prev;+ }++ return applyOptimistic(prev);+ });++ const myQueue = q;+ const next = myQueue.chain.then(async () => {+ if (myQueue.cancelled) {+ return;+ }++ try {+ const response = await apiCall();+ if (myQueue.cancelled) {+ return;+ }++ setCodeValues(nodePath, (prev) => mergeServerResponse(prev, response));+ myQueue.committed = mergeServerResponse(+ myQueue.committed as CanUpdateSequencePropsResponse,+ response,+ );++ // If nothing more is queued, reset baseline so the next round starts fresh.+ if (myQueue.chain === next) {+ dropQueue(nodePath, myQueue);+ }+ } catch (err) {+ myQueue.cancelled = true;+ const committed = myQueue.committed;+ if (committed !== null) {+ setCodeValues(nodePath, () => committed);+ }++ dropQueue(nodePath, myQueue);+ showNotification(+ `${errorLabel}: ${err instanceof Error ? err.message : String(err)}`,+ 4000,+ );+ }+ });++ myQueue.chain = next;+ return next;+};diff --git a/packages/studio/src/components/Timeline/save-sequence-prop.ts b/packages/studio/src/components/Timeline/save-sequence-prop.tsindex 8d0867285d..f16019480c 100644--- a/packages/studio/src/components/Timeline/save-sequence-prop.ts+++ b/packages/studio/src/components/Timeline/save-sequence-prop.ts@@ -5,7 +5,7 @@ import type {SequenceSchema,} from 'remotion';import {callApi} from '../call-api';-import {showNotification} from '../Notifications/NotificationCenter';+import {enqueueSavePropChange} from './save-prop-queue';type SetCodeValues = (nodePath: SequencePropsSubscriptionKey,@@ -31,52 +31,36 @@ export const saveSequenceProp = ({schema: SequenceSchema;setCodeValues: SetCodeValues;}): Promise<void> => {- let previousUpdate: CanUpdateSequencePropsResponse | undefined;-- setCodeValues(nodePath, (prev) => {- previousUpdate = prev;- return optimisticUpdateForCodeValues({- previous: prev,- fieldKey,- value,- schema,- });- });-- return callApi('/api/save-sequence-props', {- fileName,+ return enqueueSavePropChange({nodePath,- key: fieldKey,- value: JSON.stringify(value),- defaultValue,- schema,- })- .then((data) => {- setCodeValues(nodePath, (prev) => {- if (!data.canUpdate) {- return data;- }+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticUpdateForCodeValues({+ previous: prev,+ fieldKey,+ value,+ schema,+ }),+ apiCall: () =>+ callApi('/api/save-sequence-props', {+ fileName,+ nodePath,+ key: fieldKey,+ value: JSON.stringify(value),+ defaultValue,+ schema,+ }),+ mergeServerResponse: (prev, data) => {+ if (!data.canUpdate) {+ return data;+ }- return {- canUpdate: true,- props: data.props,- effects: prev.canUpdate ? prev.effects : [],- };- });- })- .catch((err) => {- setCodeValues(nodePath, (current) => {- if (previousUpdate) {- return previousUpdate;- }-- return current;- });- showNotification(- `Could not save sequence prop: ${- err instanceof Error ? err.message : String(err)- }`,- 4000,- );- });+ return {+ canUpdate: true,+ props: data.props,+ effects: prev.canUpdate ? prev.effects : [],+ };+ },+ errorLabel: 'Could not save sequence prop',+ });};