Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Delete sequences optimistically

Jonny Burger6a1b64af863a
diff --git a/packages/bundler/src/watch-ignore-next-change-plugin.ts b/packages/bundler/src/watch-ignore-next-change-plugin.ts
index ee0860d537..21ed259c8e 100644
--- a/packages/bundler/src/watch-ignore-next-change-plugin.ts
+++ b/packages/bundler/src/watch-ignore-next-change-plugin.ts
@@ -66,6 +66,7 @@ type TraceLogFn = (...args: Parameters<typeof console.log>) => void;
export class WatchIgnoreNextChangePlugin {
private filesToIgnore = new Set<string>();
+ private filesRequiringRebuild = new Set<string>();
private dirsToIgnore = new Set<string>();
private snapshotFileTimestamps = new Map<string, TimeInfoEntry>();
private snapshotDirTimestamps = new Map<string, TimeInfoEntry>();
@@ -78,6 +79,10 @@ export class WatchIgnoreNextChangePlugin {
}
ignoreNextChange(file: string): void {
+ if (this.filesRequiringRebuild.has(file)) {
+ return;
+ }
+
this.filesToIgnore.add(file);
const dir = path.dirname(file);
this.dirsToIgnore.add(dir);
@@ -111,6 +116,11 @@ export class WatchIgnoreNextChangePlugin {
this.trace('[WatchIgnoreNextChange] Registered ignore for', file);
}
+ requireRebuild(file: string): void {
+ this.unignoreNextChange(file);
+ this.filesRequiringRebuild.add(file);
+ }
+
unignoreNextChange(file: string): void {
this.filesToIgnore.delete(file);
const dir = path.dirname(file);
@@ -197,6 +207,16 @@ export class WatchIgnoreNextChangePlugin {
changedFiles,
removedFiles,
) => {
+ // A rebuild-required write wins over subsequent suppressed writes in
+ // the same watcher batch. Release it only when the watcher sees it.
+ for (const file of changedFiles ?? []) {
+ self.filesRequiringRebuild.delete(file);
+ }
+
+ for (const file of removedFiles ?? []) {
+ self.filesRequiringRebuild.delete(file);
+ }
+
const hasIgnoredFiles = self.filesToIgnore.size > 0;
const suppressedFiles: string[] = [];
const suppressedDirs: string[] = [];
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 799757d281..49b8b9595c 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -145,6 +145,10 @@ import {
makeMediaResourceManager,
MEDIABUNNY_DURATION_VALUE_KEY,
} from './media-resource-manager.js';
+import {
+ OptimisticSequenceDeletion,
+ usePendingSequenceDeletions,
+} from './optimistic-sequence-deletion.js';
import {playbackLogging} from './playback-logging.js';
import {portalNode, setPortalNodeCurrentScale} from './portal-node.js';
import {PrefetchProvider} from './prefetch-state.js';
@@ -345,6 +349,8 @@ const compositionSelectorRef = createRef<{
// Mark them as Internals so use don't assume this is public
// API and are less likely to use it
export const Internals = {
+ OptimisticSequenceDeletion,
+ usePendingSequenceDeletions,
CommittedMetadataProvider,
withCommittedMetadata,
DefaultPremountContext,
diff --git a/packages/core/src/optimistic-sequence-deletion.ts b/packages/core/src/optimistic-sequence-deletion.ts
new file mode 100644
index 0000000000..7a98f15b66
--- /dev/null
+++ b/packages/core/src/optimistic-sequence-deletion.ts
@@ -0,0 +1,139 @@
+import {isValidElement, type ReactNode} from 'react';
+import type {SequenceNodePath} from './SequenceManager.js';
+import {useRemotionEnvironment} from './use-remotion-environment.js';
+import {useSyncExternalStore} from './use-sync-external-store.js';
+
+type Node = {absolutePath: string; nodePath: SequenceNodePath};
+type Deletion = {id: number; revision: number; deleted: boolean};
+const deletions = new Map<string, Deletion>();
+const stackToNode = new Map<string, string>();
+const listeners = new Set<() => void>();
+const empty = new Set<string>();
+let snapshot: ReadonlySet<string> = empty;
+
+const keyForNode = (node: Node) =>
+ JSON.stringify([node.absolutePath, node.nodePath]);
+
+const publish = (force = false) => {
+ const next = new Set(
+ [...deletions].filter(([, value]) => value.deleted).map(([key]) => key),
+ );
+ if (
+ !force &&
+ next.size === snapshot.size &&
+ [...next].every((key) => snapshot.has(key))
+ ) {
+ return;
+ }
+
+ snapshot = next.size === 0 ? empty : next;
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+export const usePendingSequenceDeletions = () => {
+ const environment = useRemotionEnvironment();
+ const value = useSyncExternalStore(
+ subscribe,
+ () => snapshot,
+ () => empty,
+ );
+ return environment.isStudio && !environment.isRendering ? value : empty;
+};
+
+export const OptimisticSequenceDeletion = {
+ register: (stack: string | null, node: Node | null) => {
+ if (stack === null || node === null) {
+ return;
+ }
+
+ const key = keyForNode(node);
+ if (stackToNode.get(stack) === key) {
+ return;
+ }
+
+ stackToNode.set(stack, key);
+ if (snapshot.size > 0) {
+ publish(true);
+ }
+ },
+ isDeleted: (node: Node | null, pending: ReadonlySet<string>) =>
+ node !== null && pending.has(keyForNode(node)),
+ isElementDeleted: (element: ReactNode, pending: ReadonlySet<string>) => {
+ if (
+ !isValidElement<{_remotionInternalStack: string | undefined}>(element)
+ ) {
+ return false;
+ }
+
+ const stack = element.props._remotionInternalStack;
+ const key = stack === undefined ? undefined : stackToNode.get(stack);
+ return key !== undefined && pending.has(key);
+ },
+ set: (nodes: readonly Node[], revision: number, deleted: boolean) => {
+ for (const node of nodes) {
+ const key = keyForNode(node);
+ const previous = deletions.get(key);
+ if (previous && previous.revision > revision) {
+ continue;
+ }
+
+ deletions.set(key, {id: revision, revision, deleted});
+ }
+
+ publish();
+ },
+ rollback: (nodes: readonly Node[], revision: number) => {
+ for (const node of nodes) {
+ const key = keyForNode(node);
+ if (deletions.get(key)?.revision === revision) {
+ deletions.delete(key);
+ }
+ }
+
+ publish();
+ },
+ // Undo/redo can only update deletions still represented by the loaded tree.
+ // Once source remapping retires them, restoration is handled by HMR.
+ restore: (nodes: readonly Node[], revision: number, deleted: boolean) => {
+ for (const node of nodes) {
+ const key = keyForNode(node);
+ const previous = deletions.get(key);
+ if (previous && previous.revision <= revision) {
+ deletions.set(key, {...previous, revision, deleted});
+ }
+ }
+
+ publish();
+ },
+ prepareRetirement: (nodes: readonly Node[], dispatchedRevision: number) => {
+ const captured = nodes.map((node) => {
+ const key = keyForNode(node);
+ return {key, id: deletions.get(key)?.id};
+ });
+ return () => {
+ let changed = false;
+ for (const {key, id} of captured) {
+ if (
+ id !== undefined &&
+ id <= dispatchedRevision &&
+ deletions.get(key)?.id === id
+ ) {
+ changed = deletions.delete(key) || changed;
+ }
+ }
+
+ if (changed) {
+ publish();
+ }
+ };
+ },
+};
diff --git a/packages/core/src/series/index.tsx b/packages/core/src/series/index.tsx
index 9663fc4cc2..ebcdf68730 100644
--- a/packages/core/src/series/index.tsx
+++ b/packages/core/src/series/index.tsx
@@ -14,6 +14,10 @@ import {
sequenceSchemaDefaultLayoutNone,
type InteractivitySchema,
} from '../interactivity-schema.js';
+import {
+ OptimisticSequenceDeletion,
+ usePendingSequenceDeletions,
+} from '../optimistic-sequence-deletion.js';
import type {LayoutAndStyle, SequenceProps} from '../Sequence.js';
import {SequenceWithoutSchema} from '../Sequence.js';
import {TrackWithoutSchema} from '../Track.js';
@@ -154,8 +158,12 @@ const validateSeriesSequenceProps = ({
};
const SeriesInner: FC<SeriesProps> = (props) => {
+ const pendingDeletions = usePendingSequenceDeletions();
const childrenValue = useMemo(() => {
- const flattenedChildren = flattenChildren(props.children);
+ const flattenedChildren = flattenChildren(props.children).filter(
+ (child) =>
+ !OptimisticSequenceDeletion.isElementDeleted(child, pendingDeletions),
+ );
const renderChildren = (i: number, startFrame: number): React.ReactNode => {
if (i === flattenedChildren.length) {
return null;
@@ -259,7 +267,7 @@ const SeriesInner: FC<SeriesProps> = (props) => {
};
return renderChildren(0, 0);
- }, [props.children]);
+ }, [props.children, pendingDeletions]);
return (
<TrackWithoutSchema
diff --git a/packages/core/src/with-interactivity-schema.ts b/packages/core/src/with-interactivity-schema.ts
index 842aeb6163..cdf50b5434 100644
--- a/packages/core/src/with-interactivity-schema.ts
+++ b/packages/core/src/with-interactivity-schema.ts
@@ -25,6 +25,10 @@ import {
extendSchemaWithSequenceName,
type InteractivitySchema,
} from './interactivity-schema.js';
+import {
+ OptimisticSequenceDeletion,
+ usePendingSequenceDeletions,
+} from './optimistic-sequence-deletion.js';
import {createRuntimeValueStore} from './runtime-value-store.js';
import {OverrideIdsToNodePathsGettersContext} from './sequence-node-path.js';
import {
@@ -229,6 +233,7 @@ export const withInteractivitySchema = <
} = props as Props & {readonly _remotionInternalStack?: string};
const cleanProps = propsWithoutInternalStack as Props;
const env = useRemotionEnvironment();
+ const pendingDeletions = usePendingSequenceDeletions();
const canUseRemotionHooks = useContext(CanUseRemotionHooks);
const disableInteractivity = useContext(DisableInteractivityContext);
const enableInteractivity = useContext(EnableInteractivityContext);
@@ -385,6 +390,13 @@ export const withInteractivitySchema = <
videoConfigValues,
]);
+ // Keep source identities available to parents that inspect their children
+ // before rendering them (Series and TransitionSeries).
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ useLayoutEffect(() => {
+ OptimisticSequenceDeletion.register(internalStack ?? null, nodePath);
+ }, [internalStack, nodePath]);
+
// 3. Apply drag/code overrides on top of the runtime values.
// eslint-disable-next-line react-hooks/rules-of-hooks
const {merged: valuesDotNotation, propsToDelete} = useMemo(() => {
@@ -425,6 +437,10 @@ export const withInteractivitySchema = <
propsToDelete,
});
+ if (OptimisticSequenceDeletion.isDeleted(nodePath, pendingDeletions)) {
+ return null;
+ }
+
return React.createElement(Component, {
...mergedProps,
controls,
diff --git a/packages/studio-server/src/file-watcher.ts b/packages/studio-server/src/file-watcher.ts
index 89cc6157cb..0abecd6f4e 100644
--- a/packages/studio-server/src/file-watcher.ts
+++ b/packages/studio-server/src/file-watcher.ts
@@ -1,4 +1,5 @@
import fs, {readFileSync, writeFileSync} from 'node:fs';
+import {prepareBundlerForFileWrite} from './preview-server/watch-ignore-next-change';
export type FileChangeMetadata = {
skipSequencePropsUpdate: boolean;
@@ -173,6 +174,7 @@ export const createFileWatcherRegistry = (): FileWatcherRegistry => {
originatorClientId,
metadata,
}: WriteFileAndNotifyFileWatchersOptions) => {
+ prepareBundlerForFileWrite(file);
writeFileSync(file, content);
const shared = sharedWatchers.get(getRegistryKey(file, false));
diff --git a/packages/studio-server/src/preview-server/routes/redo.ts b/packages/studio-server/src/preview-server/routes/redo.ts
index 9240b75b2e..9e69684413 100644
--- a/packages/studio-server/src/preview-server/routes/redo.ts
+++ b/packages/studio-server/src/preview-server/routes/redo.ts
@@ -1,7 +1,8 @@
import type {RedoRequest, RedoResponse} from '@remotion/studio-shared';
import type {ApiHandler} from '../api-types';
import {popRedo} from '../undo-stack';
+import {withSourceFileWriteQueue} from './source-file-write-queue';
export const redoHandler: ApiHandler<RedoRequest, RedoResponse> = () => {
- return Promise.resolve(popRedo());
+ return withSourceFileWriteQueue(() => popRedo());
};
diff --git a/packages/studio-server/src/preview-server/routes/source-file-write-queue.ts b/packages/studio-server/src/preview-server/routes/source-file-write-queue.ts
index 14a9391130..c0a0e391c8 100644
--- a/packages/studio-server/src/preview-server/routes/source-file-write-queue.ts
+++ b/packages/studio-server/src/preview-server/routes/source-file-write-queue.ts
@@ -12,7 +12,7 @@ export const getCodemodTimingPrefix = (logLevel: LogLevel) => {
};
export const withSourceFileWriteQueue = <T>(
- fn: () => Promise<T>,
+ fn: () => Promise<T> | T,
): Promise<T> => {
const run = () => codemodStartTime.run(Date.now(), fn);
const next = chain.then(run, run);
diff --git a/packages/studio-server/src/preview-server/routes/undo.ts b/packages/studio-server/src/preview-server/routes/undo.ts
index 78e7562ccb..7f18f4b6f3 100644
--- a/packages/studio-server/src/preview-server/routes/undo.ts
+++ b/packages/studio-server/src/preview-server/routes/undo.ts
@@ -1,7 +1,8 @@
import type {UndoRequest, UndoResponse} from '@remotion/studio-shared';
import type {ApiHandler} from '../api-types';
import {popUndo} from '../undo-stack';
+import {withSourceFileWriteQueue} from './source-file-write-queue';
export const undoHandler: ApiHandler<UndoRequest, UndoResponse> = () => {
- return Promise.resolve(popUndo());
+ return withSourceFileWriteQueue(() => popUndo());
};
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index f35e53d6ac..49d8273612 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -16,7 +16,10 @@ import {
import {formatLogFileLocation} from './format-log-file-location';
import {waitForLiveEventsListener} from './live-events';
import {broadcastSequenceNodePathMutation} from './sequence-node-path-mutation';
-import {suppressBundlerUpdateForFile} from './watch-ignore-next-change';
+import {
+ prepareBundlerForFileWrite,
+ suppressBundlerUpdateForFile,
+} from './watch-ignore-next-change';
export interface UndoEntryDescription {
undoMessage: string;
@@ -484,6 +487,7 @@ export function popUndo(): UndoResponse {
}
if (snapshot.oldContents === null) {
+ prepareBundlerForFileWrite(snapshot.filePath);
rmSync(snapshot.filePath, {force: true});
} else {
writeFileAndNotifyFileWatchers({
diff --git a/packages/studio-server/src/preview-server/watch-ignore-next-change.ts b/packages/studio-server/src/preview-server/watch-ignore-next-change.ts
index 1b5af70d91..0b6e63bd0b 100644
--- a/packages/studio-server/src/preview-server/watch-ignore-next-change.ts
+++ b/packages/studio-server/src/preview-server/watch-ignore-next-change.ts
@@ -1,16 +1,29 @@
import {promises as fs} from 'node:fs';
import type {WatchIgnoreNextChangePlugin} from '@remotion/bundler';
+const pendingSuppressedWrites = new Set<string>();
+
let currentPlugin: WatchIgnoreNextChangePlugin | null = null;
export const setWatchIgnoreNextChangePlugin = (
plugin: WatchIgnoreNextChangePlugin,
): void => {
currentPlugin = plugin;
+ pendingSuppressedWrites.clear();
};
export const suppressBundlerUpdateForFile = (absolutePath: string): void => {
- currentPlugin?.ignoreNextChange(absolutePath);
+ pendingSuppressedWrites.add(absolutePath);
+};
+
+// Consume the intent for this write, rather than letting an earlier suppressed
+// write swallow a subsequent structural change in the watcher's aggregated event.
+export const prepareBundlerForFileWrite = (absolutePath: string): void => {
+ if (pendingSuppressedWrites.delete(absolutePath)) {
+ currentPlugin?.ignoreNextChange(absolutePath);
+ } else {
+ currentPlugin?.requireRebuild(absolutePath);
+ }
};
export const invalidatePreviouslySuppressedFiles =
diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
index 58683fa1ab..079b4810d0 100644
--- a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts
@@ -1,6 +1,7 @@
import type {OverrideIdToNodePaths, PropStatuses, TSequence} from 'remotion';
import {canUseEffectOperations} from '../../helpers/browser-studio-operations';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
+import {getSourceMutationRevision} from '../../helpers/source-mutation-queue';
import type {ConfirmationDialogFunction} from '../ConfirmationDialog-types';
import {deleteNodes} from '../delete-nodes-api';
import {deleteEffects as deleteEffectsApi} from '../effect-operations-api';
@@ -53,7 +54,7 @@ export const deleteSequencesFromSource = async (
return false;
}
- return deleteNodes({
+ const deletion = deleteNodes({
nodes: nodePathInfos.map((nodePathInfo) => {
const nodePath = nodePathInfo.sequenceSubscriptionKey;
@@ -62,13 +63,15 @@ export const deleteSequencesFromSource = async (
nodePath: nodePath.nodePath,
};
}),
- })
+ });
+ const revision = getSourceMutationRevision();
+ return deletion
.then((result) => {
if (!result.success) {
showNotification(result.reason, 4000);
}
- return result.success;
+ return result.success && revision === getSourceMutationRevision();
})
.catch((err) => {
showNotification((err as Error).message, 4000);
diff --git a/packages/studio/src/components/Timeline/save-prop-queue.ts b/packages/studio/src/components/Timeline/save-prop-queue.ts
index ccc8ba7c6c..eef6a7a6ac 100644
--- a/packages/studio/src/components/Timeline/save-prop-queue.ts
+++ b/packages/studio/src/components/Timeline/save-prop-queue.ts
@@ -3,6 +3,7 @@ import type {
SequencePropsSubscriptionKey,
} from 'remotion';
import {Internals} from 'remotion';
+import {getSourceMutationRevision} from '../../helpers/source-mutation-queue';
import {showNotification} from '../Notifications/NotificationCenter';
type SetPropStatuses = (
@@ -73,20 +74,18 @@ export const enqueueSavePropChange = <TResponse>({
});
const myQueue = q;
- const next = myQueue.chain.then(async () => {
- if (myQueue.cancelled) {
- return;
- }
-
+ const request = new Promise<TResponse>((resolve) => resolve(apiCall()));
+ const revision = getSourceMutationRevision();
+ const next = Promise.resolve().then(async () => {
try {
- const response = await apiCall();
+ const response = await request;
if (myQueue.cancelled) {
return;
}
// If nothing more is queued, reset baseline so the next round starts fresh.
if (myQueue.chain === next) {
- if (applyServerResponse) {
+ if (applyServerResponse && revision === getSourceMutationRevision()) {
setPropStatuses(nodePath, (prev) =>
applyServerResponse(prev, response),
);
diff --git a/packages/studio/src/components/UndoRedoButtons.tsx b/packages/studio/src/components/UndoRedoButtons.tsx
index 54027d5734..adb368617b 100644
--- a/packages/studio/src/components/UndoRedoButtons.tsx
+++ b/packages/studio/src/components/UndoRedoButtons.tsx
@@ -1,14 +1,9 @@
import type {EventSourceEvent} from '@remotion/studio-shared';
-import React, {
- useCallback,
- useContext,
- useEffect,
- useRef,
- useState,
-} from 'react';
+import React, {useCallback, useContext, useEffect, useState} from 'react';
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {WHITE_ALPHA_80} from '../helpers/colors';
+import {getSourceMutationRevision} from '../helpers/source-mutation-queue';
import {pushUrl} from '../helpers/url-state';
import {
areKeyboardShortcutsDisabled,
@@ -35,8 +30,6 @@ export const UndoRedoButtons: React.FC = () => {
const [redoFile, setRedoFile] = useState<string | null>(null);
const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
const keybindings = useKeybinding();
- const undoInFlight = useRef(false);
- const redoInFlight = useRef(false);
useEffect(() => {
const unsub = subscribeToEvent(
@@ -55,50 +48,44 @@ export const UndoRedoButtons: React.FC = () => {
}, [subscribeToEvent]);
const onUndo = useCallback(() => {
- if (undoInFlight.current) {
- return;
- }
-
- undoInFlight.current = true;
const browserStudioOperations = getBrowserStudioOperations();
const promise = browserStudioOperations
? browserStudioOperations.undo()
: callApi('/api/undo', {});
+ const revision = getSourceMutationRevision();
promise
.then((response) => {
- if (response.success && response.route !== null) {
+ if (
+ revision === getSourceMutationRevision() &&
+ response.success &&
+ response.route !== null
+ ) {
pushUrl(response.route);
}
})
.catch(() => {
// Ignore errors
- })
- .finally(() => {
- undoInFlight.current = false;
});
}, []);
const onRedo = useCallback(() => {
- if (redoInFlight.current) {
- return;
- }
-
- redoInFlight.current = true;
const browserStudioOperations = getBrowserStudioOperations();
const promise = browserStudioOperations
? browserStudioOperations.redo()
: callApi('/api/redo', {});
+ const revision = getSourceMutationRevision();
promise
.then((response) => {
- if (response.success && response.route !== null) {
+ if (
+ revision === getSourceMutationRevision() &&
+ response.success &&
+ response.route !== null
+ ) {
pushUrl(response.route);
}
})
.catch(() => {
// Ignore errors
- })
- .finally(() => {
- redoInFlight.current = false;
});
}, []);
@@ -109,9 +96,7 @@ export const UndoRedoButtons: React.FC = () => {
event: 'keydown',
action: 'undo',
callback: () => {
- if (undoFile) {
- onUndo();
- }
+ onUndo();
},
preventDefault: true,
triggerIfInputFieldFocused: false,
@@ -122,9 +107,7 @@ export const UndoRedoButtons: React.FC = () => {
event: 'keydown',
action: 'redo',
callback: () => {
- if (redoFile) {
- onRedo();
- }
+ onRedo();
},
preventDefault: true,
triggerIfInputFieldFocused: false,
@@ -135,7 +118,7 @@ export const UndoRedoButtons: React.FC = () => {
undo.unregister();
redo.unregister();
};
- }, [keybindings, onRedo, onUndo, redoFile, undoFile]);
+ }, [keybindings, onRedo, onUndo]);
const undoShortcut = useKeyboardShortcutLabel('undo');
const redoShortcut = useKeyboardShortcutLabel('redo');
diff --git a/packages/studio/src/components/call-api.ts b/packages/studio/src/components/call-api.ts
index 3862fd5791..f06d625fae 100644
--- a/packages/studio/src/components/call-api.ts
+++ b/packages/studio/src/components/call-api.ts
@@ -1,7 +1,9 @@
import type {ApiRoutes} from '@remotion/studio-shared';
+import {enqueueStudioSourceMutation} from '../helpers/enqueue-studio-source-mutation';
import {queueSequenceNodePathMutationFromApiResponse} from '../helpers/sequence-node-path-mutations';
+import {sourceMutationEndpoints} from '../helpers/source-mutation-endpoints';
-export const callApi = <Endpoint extends keyof ApiRoutes>(
+const callApiImmediately = <Endpoint extends keyof ApiRoutes>(
endpoint: Endpoint,
body: ApiRoutes[Endpoint]['Request'],
signal?: AbortSignal,
@@ -35,3 +37,17 @@ export const callApi = <Endpoint extends keyof ApiRoutes>(
});
});
};
+
+export const callApi = <Endpoint extends keyof ApiRoutes>(
+ endpoint: Endpoint,
+ body: ApiRoutes[Endpoint]['Request'],
+ signal?: AbortSignal,
+): Promise<ApiRoutes[Endpoint]['Response']> => {
+ if (!sourceMutationEndpoints.has(endpoint)) {
+ return callApiImmediately(endpoint, body, signal);
+ }
+
+ return enqueueStudioSourceMutation(endpoint, body, () =>
+ callApiImmediately(endpoint, body, signal),
+ );
+};
diff --git a/packages/studio/src/helpers/browser-studio-operations.ts b/packages/studio/src/helpers/browser-studio-operations.ts
index 13fb42008e..24e11eb833 100644
--- a/packages/studio/src/helpers/browser-studio-operations.ts
+++ b/packages/studio/src/helpers/browser-studio-operations.ts
@@ -1,4 +1,53 @@
-import type {BrowserStudioOperations} from '@remotion/studio-shared';
+import type {ApiRoutes, BrowserStudioOperations} from '@remotion/studio-shared';
+import {enqueueStudioSourceMutation} from './enqueue-studio-source-mutation';
+import {sourceMutationEndpoints} from './source-mutation-endpoints';
+
+const queuedOperations = new WeakMap<object, object>();
+
+const withMutationQueue = <T extends object>(operations: T): T => {
+ const existing = queuedOperations.get(operations);
+ if (existing) {
+ return existing as T;
+ }
+
+ const methods = new Map<string, {original: unknown; queued: unknown}>();
+ const wrapped = new Proxy(operations, {
+ get(target, property, receiver) {
+ const value = Reflect.get(target, property, receiver);
+ if (property === 'effects' || property === 'keyframes') {
+ return value ? withMutationQueue(value) : value;
+ }
+
+ if (typeof property !== 'string' || typeof value !== 'function') {
+ return value;
+ }
+
+ const cached = methods.get(property);
+ if (cached?.original === value) {
+ return cached.queued;
+ }
+
+ const name =
+ property === 'deleteEffects'
+ ? 'deleteEffect'
+ : property === 'duplicateEffects'
+ ? 'duplicateEffect'
+ : property;
+ const endpoint =
+ `/api/${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}` as keyof ApiRoutes;
+ const queued = sourceMutationEndpoints.has(endpoint)
+ ? (...args: unknown[]) =>
+ enqueueStudioSourceMutation(endpoint, args[0], () =>
+ value.apply(target, args),
+ )
+ : value.bind(target);
+ methods.set(property, {original: value, queued});
+ return queued;
+ },
+ });
+ queuedOperations.set(operations, wrapped);
+ return wrapped;
+};
// Browser Studio may be hosted by a different studio-shared version, so this
// handshake intentionally has no shared runtime import.
@@ -11,7 +60,9 @@ export const getBrowserStudioOperations =
return null;
}
- return window.remotion_browserStudio ?? null;
+ return window.remotion_browserStudio
+ ? withMutationQueue(window.remotion_browserStudio)
+ : null;
};
export const getBrowserStudioKeyframeOperations = () =>
diff --git a/packages/studio/src/helpers/enqueue-studio-source-mutation.ts b/packages/studio/src/helpers/enqueue-studio-source-mutation.ts
new file mode 100644
index 0000000000..c3dd9052c7
--- /dev/null
+++ b/packages/studio/src/helpers/enqueue-studio-source-mutation.ts
@@ -0,0 +1,102 @@
+import type {
+ ApiRoutes,
+ DeleteNodesRequest,
+ SequenceNodePathMutation,
+} from '@remotion/studio-shared';
+import {Internals} from 'remotion';
+import {queueSequenceNodePathMutationFromApiResponse} from './sequence-node-path-mutations';
+import {enqueueSourceMutation} from './source-mutation-queue';
+
+export const enqueueStudioSourceMutation = <T>(
+ endpoint: keyof ApiRoutes,
+ body: unknown,
+ run: () => Promise<T>,
+): Promise<T> => {
+ const nodes =
+ endpoint === '/api/delete-nodes'
+ ? (body as DeleteNodesRequest).nodes.map((node) => ({
+ absolutePath: node.fileName,
+ nodePath: node.nodePath,
+ }))
+ : [];
+
+ return enqueueSourceMutation(
+ async (operation) => {
+ try {
+ const result = await run();
+ queueSequenceNodePathMutationFromApiResponse(result);
+ if (typeof result !== 'object' || result === null) {
+ return result;
+ }
+
+ if ('success' in result && result.success === false) {
+ Internals.OptimisticSequenceDeletion.rollback(
+ nodes,
+ operation.revision,
+ );
+ return result;
+ }
+
+ if (
+ (endpoint === '/api/undo' || endpoint === '/api/redo') &&
+ 'nodePathMutation' in result &&
+ result.nodePathMutation
+ ) {
+ const mutation = result.nodePathMutation as SequenceNodePathMutation;
+ for (const file of mutation.files) {
+ for (const remapping of file.remappings) {
+ if (
+ remapping.oldNodePath === null &&
+ remapping.newNodePath !== null
+ ) {
+ Internals.OptimisticSequenceDeletion.restore(
+ [
+ {
+ absolutePath: file.absolutePath,
+ nodePath: remapping.newNodePath,
+ },
+ ],
+ operation.revision,
+ false,
+ );
+ } else if (
+ remapping.newNodePath === null &&
+ remapping.oldNodePath !== null
+ ) {
+ Internals.OptimisticSequenceDeletion.restore(
+ [
+ {
+ absolutePath: file.absolutePath,
+ nodePath: remapping.oldNodePath,
+ },
+ ],
+ operation.revision,
+ true,
+ );
+ }
+ }
+ }
+ }
+
+ // A successful delete only acknowledges persistence. Reapplying its
+ // optimistic state here could overwrite a newer undo intent.
+ return result;
+ } catch (error) {
+ Internals.OptimisticSequenceDeletion.rollback(
+ nodes,
+ operation.revision,
+ );
+ throw error;
+ }
+ },
+ (operation) => {
+ if (nodes.length > 0) {
+ Internals.OptimisticSequenceDeletion.set(
+ nodes,
+ operation.revision,
+ true,
+ );
+ }
+ },
+ );
+};
diff --git a/packages/studio/src/helpers/sequence-node-path-mutations.ts b/packages/studio/src/helpers/sequence-node-path-mutations.ts
index 64ecc7a516..7b6eb7e239 100644
--- a/packages/studio/src/helpers/sequence-node-path-mutations.ts
+++ b/packages/studio/src/helpers/sequence-node-path-mutations.ts
@@ -1,7 +1,10 @@
import type {SequenceNodePathMutation} from '@remotion/studio-shared';
+import {Internals} from 'remotion';
import {requestInsertedElementSelection} from './inserted-element-selection';
+import {getLastDispatchedSourceMutationRevision} from './source-mutation-queue';
const pendingMutations: SequenceNodePathMutation[] = [];
+const pendingDeletionRetirements: Array<() => void> = [];
const seenMutationIds = new Set<string>();
export const queueSequenceNodePathMutation = (
@@ -13,6 +16,23 @@ export const queueSequenceNodePathMutation = (
seenMutationIds.add(mutation.mutationId);
pendingMutations.push(mutation);
+ pendingDeletionRetirements.push(
+ Internals.OptimisticSequenceDeletion.prepareRetirement(
+ mutation.files.flatMap((file) =>
+ file.remappings.flatMap((remapping) =>
+ remapping.oldNodePath === null
+ ? []
+ : [
+ {
+ absolutePath: file.absolutePath,
+ nodePath: remapping.oldNodePath,
+ },
+ ],
+ ),
+ ),
+ getLastDispatchedSourceMutationRevision(),
+ ),
+ );
if (mutation.timelineSelection !== null) {
requestInsertedElementSelection({
@@ -51,4 +71,10 @@ export const queueSequenceNodePathMutationFromApiResponse = (
};
export const takePendingSequenceNodePathMutations =
- (): SequenceNodePathMutation[] => pendingMutations.splice(0);
+ (): SequenceNodePathMutation[] => {
+ for (const retire of pendingDeletionRetirements.splice(0)) {
+ retire();
+ }
+
+ return pendingMutations.splice(0);
+ };
diff --git a/packages/studio/src/helpers/source-mutation-endpoints.ts b/packages/studio/src/helpers/source-mutation-endpoints.ts
new file mode 100644
index 0000000000..212358441a
--- /dev/null
+++ b/packages/studio/src/helpers/source-mutation-endpoints.ts
@@ -0,0 +1,49 @@
+import type {ApiRoutes} from '@remotion/studio-shared';
+
+// Source mutations share one command stream with undo/redo. Reads and long-running
+// asset processing must remain independent of this queue.
+export const sourceMutationEndpoints: ReadonlySet<keyof ApiRoutes> = new Set([
+ '/api/add-composition',
+ '/api/add-effect',
+ '/api/add-effect-keyframe',
+ '/api/add-folder',
+ '/api/add-keyframes',
+ '/api/add-sequence-keyframe',
+ '/api/apply-visual-control-change',
+ '/api/batch-update-keyframe-settings',
+ '/api/delete-composition',
+ '/api/delete-effect',
+ '/api/delete-keyframes',
+ '/api/delete-nodes',
+ '/api/duplicate-composition',
+ '/api/duplicate-effect',
+ '/api/duplicate-nodes',
+ '/api/insert-composition-element',
+ '/api/insert-element',
+ '/api/insert-basic-captions',
+ '/api/replace-video-source',
+ '/api/invalidate-bundle',
+ '/api/move-composition',
+ '/api/move-folder',
+ '/api/move-keyframes',
+ '/api/paste-effects',
+ '/api/precompose-jsx-nodes',
+ '/api/prepare-element-install',
+ '/api/redo',
+ '/api/rename-composition',
+ '/api/rename-folder',
+ '/api/reorder-effect',
+ '/api/reorder-sequence',
+ '/api/save-effect-props',
+ '/api/save-multiple-effect-props',
+ '/api/save-sequence-props',
+ '/api/split-sequences',
+ '/api/split-video-from-audio',
+ '/api/undo',
+ '/api/unwrap-folder',
+ '/api/update-composition-metadata',
+ '/api/update-default-props',
+ '/api/update-effect-keyframe-settings',
+ '/api/update-sequence-keyframe-settings',
+ '/api/wrap-node',
+]);
diff --git a/packages/studio/src/helpers/source-mutation-queue.ts b/packages/studio/src/helpers/source-mutation-queue.ts
new file mode 100644
index 0000000000..4e3c674572
--- /dev/null
+++ b/packages/studio/src/helpers/source-mutation-queue.ts
@@ -0,0 +1,31 @@
+export type SourceMutationOperation = {
+ readonly id: string;
+ readonly revision: number;
+};
+
+let revision = 0;
+let lastDispatchedRevision = 0;
+let chain: Promise<unknown> = Promise.resolve();
+
+export const getSourceMutationRevision = () => revision;
+export const getLastDispatchedSourceMutationRevision = () =>
+ lastDispatchedRevision;
+
+// Reserve the revision synchronously, in user action order. A response may finish
+// after a newer intent was queued, even though persistence runs serially.
+export const enqueueSourceMutation = <T>(
+ run: (operation: SourceMutationOperation) => Promise<T>,
+ onQueued: ((operation: SourceMutationOperation) => void) | null = null,
+): Promise<T> => {
+ const operation = {id: `source-operation-${++revision}`, revision};
+ const next = chain.then(() => {
+ lastDispatchedRevision = operation.revision;
+ return run(operation);
+ });
+ chain = next.then(
+ () => undefined,
+ () => undefined,
+ );
+ onQueued?.(operation);
+ return next;
+};
diff --git a/packages/transitions/src/TransitionSeries.tsx b/packages/transitions/src/TransitionSeries.tsx
index 8b484dfda3..9511923dcc 100644
--- a/packages/transitions/src/TransitionSeries.tsx
+++ b/packages/transitions/src/TransitionSeries.tsx
@@ -244,9 +244,16 @@ const TransitionSeriesChildren: FC<{readonly children: React.ReactNode}> = ({
const prevImageRef = useRef<ImageMap>({});
const nextImageRef = useRef<ImageMap>({});
+ const pendingDeletions = Internals.usePendingSequenceDeletions();
const flattedChildren = useMemo(() => {
- return flattenChildren(children);
- }, [children]);
+ return flattenChildren(children).filter(
+ (child) =>
+ !Internals.OptimisticSequenceDeletion.isElementDeleted(
+ child,
+ pendingDeletions,
+ ),
+ );
+ }, [children, pendingDeletions]);
const hasOverlay = flattedChildren.some(
(child) => React.isValidElement(child) && child.type === SeriesOverlay,
);