Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/studio`: Speed up sequence prop editing (#10482)

Jonny Burger8886283a140c
diff --git a/packages/studio-codemods/bundle.ts b/packages/studio-codemods/bundle.ts
index 9f211bbc9d..c2396781ac 100644
--- a/packages/studio-codemods/bundle.ts
+++ b/packages/studio-codemods/bundle.ts
@@ -5,7 +5,7 @@ if (process.env.NODE_ENV !== 'production') {
throw new Error('This script must be run using NODE_ENV=production');
}
-const external = ['@remotion/studio-shared'];
+const external = ['@remotion/studio-shared', 'recast'];
console.time('Generated.');
const esmOutput = await build({
diff --git a/packages/studio-codemods/src/test/update-sequence-props.test.ts b/packages/studio-codemods/src/test/update-sequence-props.test.ts
new file mode 100644
index 0000000000..ff88bdc49b
--- /dev/null
+++ b/packages/studio-codemods/src/test/update-sequence-props.test.ts
@@ -0,0 +1,57 @@
+import {expect, test} from 'bun:test';
+import * as recast from 'recast';
+import {NoReactInternals} from 'remotion/no-react';
+import {getNodePathForRecastPath} from '../sequence-props';
+import {parseAst} from '../sequence-props/parse-ast';
+import {updateMultipleSequenceProps} from '../update-sequence-props';
+
+test('patches an opening element without reprinting its siblings', () => {
+ const input = `export const Example = () => {
+ return (
+ <div>
+ <Interactive.Div name="First" />
+ <Interactive.Div name="Second" />
+ <Interactive.Div name="Third" />
+ </div>
+ );
+};
+`;
+ const ast = parseAst(input);
+ let nodePath = null;
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(path) {
+ if (path.node.loc?.start.line === 5) {
+ nodePath = getNodePathForRecastPath(path, ast);
+ return false;
+ }
+
+ return this.traverse(path);
+ },
+ });
+ if (!nodePath) {
+ throw new Error('Could not find the second Interactive.Div');
+ }
+
+ const {output} = updateMultipleSequenceProps({
+ input,
+ changes: [
+ {
+ nodePath,
+ updates: [{key: 'hidden', value: true, defaultValue: false}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ });
+
+ expect(output).toBe(`export const Example = () => {
+ return (
+ <div>
+ <Interactive.Div name="First" />
+ <Interactive.Div name="Second" hidden />
+ <Interactive.Div name="Third" />
+ </div>
+ );
+};
+`);
+});
diff --git a/packages/studio-codemods/src/update-sequence-props.ts b/packages/studio-codemods/src/update-sequence-props.ts
index 0e99c74762..f61c7fde8d 100644
--- a/packages/studio-codemods/src/update-sequence-props.ts
+++ b/packages/studio-codemods/src/update-sequence-props.ts
@@ -110,6 +110,12 @@ export type SequencePropsNodeUpdateResult = {
export type UpdateMultipleSequencePropsResult = {
output: string;
results: SequencePropsNodeUpdateResult[];
+ ast: File;
+ openingElementRanges: Array<{
+ start: number;
+ end: number;
+ selfClosing: boolean;
+ }> | null;
};
const removeVariantKey = ({
@@ -1245,11 +1251,26 @@ export const updateSequencePropsAst = ({
export const updateMultipleSequenceProps = ({
input,
changes,
+ ast: providedAst,
}: {
input: string;
changes: SequencePropsNodeUpdate[];
+ ast?: File;
}): UpdateMultipleSequencePropsResult => {
- const ast = parseAst(input);
+ const ast = providedAst ?? parseAst(input);
+ const canPatchOpeningElements = changes.every(({updates}) =>
+ updates.every(
+ (update) =>
+ update.key !== 'children' &&
+ update.key !== 'style.fontFamily' &&
+ !update.googleFont &&
+ !update.clipboardParam &&
+ !(
+ typeof update.value === 'string' &&
+ update.value.startsWith(NoReactInternals.FILE_TOKEN)
+ ),
+ ),
+ );
const resolvedChanges = changes.map(
({nodePath, updates, schema, videoConfigValues}) => {
const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
@@ -1262,6 +1283,14 @@ export const updateMultipleSequenceProps = ({
return {jsxElement, updates, schema, videoConfigValues};
},
);
+ const openingElementLocations = canPatchOpeningElements
+ ? new Map(
+ resolvedChanges.map(({jsxElement}) => [
+ jsxElement.openingElement,
+ jsxElement.openingElement.loc,
+ ]),
+ )
+ : null;
const clipboardParamLocalNames = prepareClipboardParamSourceEdits({
ast,
changes: resolvedChanges,
@@ -1298,9 +1327,81 @@ export const updateMultipleSequenceProps = ({
return {...result, newNodePath};
});
+ const sourceLines = input.split('\n');
+ const lineOffsets: number[] = [];
+ let offset = 0;
+ for (const line of sourceLines) {
+ lineOffsets.push(offset);
+ offset += line.length + 1;
+ }
+
+ const replacements = openingElementLocations
+ ? [...openingElementLocations].map(([openingElement, location]) => {
+ if (!location) {
+ return null;
+ }
+
+ const getOffset = ({line, column}: {line: number; column: number}) => {
+ const sourceLine = sourceLines[line - 1];
+ if (sourceLine === undefined) {
+ return null;
+ }
+
+ let sourceColumn = 0;
+ let recastColumn = 0;
+ while (sourceColumn < sourceLine.length && recastColumn < column) {
+ recastColumn +=
+ sourceLine[sourceColumn] === '\t' ? 4 - (recastColumn % 4) : 1;
+ sourceColumn++;
+ }
+
+ return lineOffsets[line - 1] + sourceColumn;
+ };
+
+ const start = getOffset(location.start);
+ const end = getOffset(location.end);
+ if (start === null || end === null) {
+ return null;
+ }
+
+ return {
+ start,
+ end,
+ replacement: recast.print(openingElement).code,
+ selfClosing: openingElement.selfClosing ?? false,
+ };
+ })
+ : null;
+ let output = input;
+ let openingElementRanges: UpdateMultipleSequencePropsResult['openingElementRanges'] =
+ null;
+ if (replacements?.every((replacement) => replacement !== null)) {
+ const replacementsByStart = replacements.sort(
+ (first, second) => first.start - second.start,
+ );
+ let shift = 0;
+ openingElementRanges = replacementsByStart.map((replacement) => {
+ const start = replacement.start + shift;
+ const end = start + replacement.replacement.length;
+ shift +=
+ replacement.replacement.length - (replacement.end - replacement.start);
+ return {start, end, selfClosing: replacement.selfClosing};
+ });
+
+ for (const replacement of [...replacementsByStart].reverse()) {
+ output =
+ output.slice(0, replacement.start) +
+ replacement.replacement +
+ output.slice(replacement.end);
+ }
+ } else {
+ output = serializeAst(ast);
+ }
return {
- output: serializeAst(ast),
+ output,
results,
+ ast,
+ openingElementRanges,
};
};
diff --git a/packages/studio-server/src/codemods/format-inline-content.ts b/packages/studio-server/src/codemods/format-inline-content.ts
index be239c6bcf..89444a0ceb 100644
--- a/packages/studio-server/src/codemods/format-inline-content.ts
+++ b/packages/studio-server/src/codemods/format-inline-content.ts
@@ -18,10 +18,12 @@ export const formatInlineContent = async ({
inlineContent,
linePrefix,
endOfLine,
+ prettierConfigOverride,
}: {
inlineContent: string;
linePrefix: string;
endOfLine: 'auto' | 'lf';
+ prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{formatted: string; didFormat: boolean}> => {
let prettier: PrettierType | null = null;
@@ -33,14 +35,19 @@ export const formatInlineContent = async ({
const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
- const configFilePath = await resolveConfigFile();
- if (!configFilePath) {
- return {formatted: inlineContent, didFormat: false};
- }
+ let prettierConfig: Record<string, unknown> | null;
+ if (prettierConfigOverride !== undefined && prettierConfigOverride !== null) {
+ prettierConfig = prettierConfigOverride;
+ } else {
+ const configFilePath = await resolveConfigFile();
+ if (!configFilePath) {
+ return {formatted: inlineContent, didFormat: false};
+ }
- const prettierConfig = await resolveConfig(configFilePath);
- if (!prettierConfig) {
- return {formatted: inlineContent, didFormat: false};
+ prettierConfig = await resolveConfig(configFilePath);
+ if (!prettierConfig) {
+ return {formatted: inlineContent, didFormat: false};
+ }
}
const tabWidth = (prettierConfig.tabWidth as number) ?? 2;
@@ -72,13 +79,18 @@ export const formatInlineContent = async ({
// Extract the formatted value from the wrapper
const withoutSemicolon = formattedWrapped.replace(/;\s*$/, '');
+ const wrappedInParentheses = withoutSemicolon.startsWith(
+ `${wrapperPrefix}(\n`,
+ );
let formattedProps: string;
- if (withoutSemicolon.startsWith(wrapperPrefix)) {
+ if (withoutSemicolon.startsWith(wrapperPrefix) && !wrappedInParentheses) {
formattedProps = withoutSemicolon.slice(wrapperPrefix.length);
} else {
// Prettier broke the line after `=` β€” extract and dedent one level
- const lines = withoutSemicolon.split('\n').slice(1);
+ const lines = withoutSemicolon
+ .split('\n')
+ .slice(1, wrappedInParentheses ? -1 : undefined);
const useTabs = prettierConfig.useTabs as boolean;
const oneIndent = useTabs ? '\t' : ' '.repeat(tabWidth);
formattedProps = lines
diff --git a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
index 69054c708b..7434dd4750 100644
--- a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
+++ b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
@@ -1,3 +1,4 @@
+import type {File} from '@babel/types';
import {
type RemovedProp,
type SequencePropsNodeUpdate,
@@ -12,6 +13,7 @@ import type {
VideoConfigValues,
} from 'remotion';
import {formatFileContent} from '../format-file-content';
+import {formatInlineContent} from '../format-inline-content';
export {
type RemovedProp,
@@ -27,6 +29,7 @@ type UpdateMultipleSequencePropsResult = {
output: string;
formatted: boolean;
results: SequencePropsNodeUpdateResult[];
+ ast: File;
};
type UpdateSequencePropsResult = {
@@ -41,19 +44,74 @@ export const updateMultipleSequenceProps = async ({
input,
changes,
prettierConfigOverride,
+ ast: providedAst,
}: {
input: string;
changes: SequencePropsNodeUpdate[];
prettierConfigOverride: PrettierConfigOverride;
+ ast?: File;
}): Promise<UpdateMultipleSequencePropsResult> => {
- const {output: unformattedOutput, results} =
- updateMultipleSequencePropsUnformatted({input, changes});
+ const {
+ output: unformattedOutput,
+ results,
+ ast,
+ openingElementRanges,
+ } = updateMultipleSequencePropsUnformatted({
+ input,
+ changes,
+ ast: providedAst,
+ });
+ if (unformattedOutput === input) {
+ return {output: input, formatted: true, results, ast};
+ }
+
+ if (openingElementRanges?.length === 1) {
+ const [range] = openingElementRanges;
+ const openingElement = unformattedOutput.slice(range.start, range.end);
+ const formattableOpeningElement = range.selfClosing
+ ? openingElement
+ : openingElement.slice(0, -1) + ' />';
+ const lineStart = unformattedOutput.lastIndexOf('\n', range.start) + 1;
+ const linePrefix = unformattedOutput.slice(lineStart, range.start);
+ const {formatted: formattedOpeningElement, didFormat} =
+ await formatInlineContent({
+ inlineContent: formattableOpeningElement,
+ linePrefix,
+ endOfLine: 'lf',
+ prettierConfigOverride,
+ });
+ let finalOpeningElement = formattedOpeningElement;
+ if (!range.selfClosing) {
+ const slashIndex = finalOpeningElement.lastIndexOf('/>');
+ if (slashIndex !== finalOpeningElement.length - 2) {
+ throw new Error('Could not format JSX opening element');
+ }
+
+ const lastLineStart = finalOpeningElement.lastIndexOf('\n') + 1;
+ const beforeSlash = finalOpeningElement.slice(lastLineStart, slashIndex);
+ finalOpeningElement =
+ beforeSlash.trim().length === 0
+ ? finalOpeningElement.slice(0, slashIndex) + '>'
+ : finalOpeningElement.slice(0, slashIndex).trimEnd() + '>';
+ }
+
+ return {
+ output:
+ unformattedOutput.slice(0, range.start) +
+ finalOpeningElement +
+ unformattedOutput.slice(range.end),
+ formatted: didFormat,
+ results,
+ ast,
+ };
+ }
+
const {output, formatted} = await formatFileContent({
input: unformattedOutput,
prettierConfigOverride,
});
- return {output, formatted, results};
+ return {output, formatted, results, ast};
};
export const updateSequenceProps = async ({
diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
index 53b07ee2b7..16f3f49ad5 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -72,6 +72,51 @@ let cachedSequencePropsStatusAst: {
videoConfigIdentifierValues: Map<string, VideoConfigIdentifierValues>;
} | null = null;
+// A subsequent save can consume the last read-only snapshot if the file has
+// not changed. The save mutates the AST, so it must only be reused once.
+let reusableSequencePropsStatusAst: {
+ fileContents: string;
+ ast: File;
+} | null = null;
+
+const getCachedSequencePropsStatusAst = (fileContents: string) => {
+ if (cachedSequencePropsStatusAst?.fileContents !== fileContents) {
+ const snapshot = {
+ fileContents,
+ ast: parseAst(fileContents),
+ videoConfigIdentifierValues: new Map<
+ string,
+ VideoConfigIdentifierValues
+ >(),
+ };
+ cachedSequencePropsStatusAst = snapshot;
+ reusableSequencePropsStatusAst = snapshot;
+ queueMicrotask(() => {
+ if (cachedSequencePropsStatusAst === snapshot) {
+ cachedSequencePropsStatusAst = null;
+ }
+ });
+ }
+
+ return cachedSequencePropsStatusAst;
+};
+
+export const takeCachedSequencePropsStatusAst = (
+ fileContents: string,
+): File | null => {
+ if (reusableSequencePropsStatusAst?.fileContents !== fileContents) {
+ return null;
+ }
+
+ const {ast} = reusableSequencePropsStatusAst;
+ reusableSequencePropsStatusAst = null;
+ if (cachedSequencePropsStatusAst?.ast === ast) {
+ cachedSequencePropsStatusAst = null;
+ }
+
+ return ast;
+};
+
const staticStatus = (
codeValue: unknown,
numericExpression: VideoConfigNumericExpression | null,
@@ -923,15 +968,12 @@ export const findNodePathForJsxElement = (
const RECAST_TAB_WIDTH = 4;
const sourceColumnToRecastColumn = ({
- fileContents,
- line,
+ sourceLine,
column,
}: {
- fileContents: string;
- line: number;
+ sourceLine: string | undefined;
column: number;
}) => {
- const sourceLine = fileContents.split('\n')[line - 1];
if (sourceLine === undefined) {
return column;
}
@@ -960,8 +1002,7 @@ export const lineColumnToNodePath = (
targetColumn === undefined || fileContents === undefined
? targetColumn
: sourceColumnToRecastColumn({
- fileContents,
- line: targetLine,
+ sourceLine: fileContents.split('\n')[targetLine - 1],
column: targetColumn,
});
@@ -987,6 +1028,74 @@ export const lineColumnToNodePath = (
return lineMatches.at(-1) ?? null;
};
+export const lineColumnsToNodePaths = ({
+ ast,
+ targets,
+ fileContents,
+}: {
+ ast: File;
+ targets: {line: number; column: number}[];
+ fileContents: string;
+}): (SequenceNodePath | null)[] => {
+ const sourceLines = fileContents.split('\n');
+ const targetIndicesByLine = new Map<number, number[]>();
+ const recastTargetColumns = targets.map(({line, column}, index) => {
+ const indices = targetIndicesByLine.get(line) ?? [];
+ indices.push(index);
+ targetIndicesByLine.set(line, indices);
+ return sourceColumnToRecastColumn({
+ sourceLine: sourceLines[line - 1],
+ column,
+ });
+ });
+ const lineMatches: (SequenceNodePath | null)[] = targets.map(() => null);
+ const exactMatches: (SequenceNodePath | null)[] = targets.map(() => null);
+ const exactMatchCounts = targets.map(() => 0);
+
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(p) {
+ const {node} = p;
+ const line = node.loc?.start.line;
+ const targetIndices = line ? targetIndicesByLine.get(line) : undefined;
+ if (targetIndices) {
+ const nodePath = getNodePathForRecastPath(p, ast);
+ for (const index of targetIndices) {
+ lineMatches[index] = nodePath;
+ if (node.loc?.start.column === recastTargetColumns[index]) {
+ exactMatches[index] = nodePath;
+ exactMatchCounts[index]++;
+ }
+ }
+ }
+
+ return this.traverse(p);
+ },
+ });
+
+ return targets.map((_, index) =>
+ exactMatchCounts[index] === 1 ? exactMatches[index] : lineMatches[index],
+ );
+};
+
+export const resolveSequencePropsNodePathsFromFilename = ({
+ fileName,
+ targets,
+ remotionRoot,
+}: {
+ fileName: string;
+ targets: {line: number; column: number}[];
+ remotionRoot: string;
+}) => {
+ const {absolutePath} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'read',
+ });
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const {ast} = getCachedSequencePropsStatusAst(fileContents);
+ return lineColumnsToNodePaths({ast, targets, fileContents});
+};
+
const PIXEL_VALUE_REGEX = /^-?\d+(\.\d+)?px$/;
const isSupportedTranslateValue = (value: string): boolean => {
@@ -1337,58 +1446,23 @@ const computeSequenceOnlyPropsRecord = ({
return filteredProps;
};
-export const computeSequencePropsStatusFromContent = ({
- fileContents,
+const computeSequencePropsStatusFromAstAndIdentifiers = ({
+ ast,
nodePath,
componentIdentity,
keys,
- assetKeys = [],
+ assetKeys,
effects,
- videoConfigValues,
+ videoConfigIdentifierValues,
}: {
- fileContents: string;
+ ast: File;
nodePath: SequenceNodePath;
componentIdentity: JsxComponentIdentity | null;
keys: string[];
- assetKeys?: string[];
+ assetKeys: string[];
effects: string[][];
- videoConfigValues: VideoConfigValues | null;
+ videoConfigIdentifierValues: VideoConfigIdentifierValues;
}): CanUpdateSequencePropsResponseTrue => {
- if (cachedSequencePropsStatusAst?.fileContents !== fileContents) {
- cachedSequencePropsStatusAst = null;
- const snapshot = {
- fileContents,
- ast: parseAst(fileContents),
- videoConfigIdentifierValues: new Map<
- string,
- VideoConfigIdentifierValues
- >(),
- };
- cachedSequencePropsStatusAst = snapshot;
- queueMicrotask(() => {
- if (cachedSequencePropsStatusAst === snapshot) {
- cachedSequencePropsStatusAst = null;
- }
- });
- }
-
- const {ast} = cachedSequencePropsStatusAst;
- const videoConfigCacheKey = JSON.stringify(videoConfigValues);
- let videoConfigIdentifierValues =
- cachedSequencePropsStatusAst.videoConfigIdentifierValues.get(
- videoConfigCacheKey,
- );
- if (videoConfigIdentifierValues === undefined) {
- videoConfigIdentifierValues = getVideoConfigIdentifierValues({
- ast,
- videoConfigValues,
- });
- cachedSequencePropsStatusAst.videoConfigIdentifierValues.set(
- videoConfigCacheKey,
- videoConfigIdentifierValues,
- );
- }
-
const jsxElementNode = findJsxElementNodeAtNodePath(ast, nodePath);
const jsxElement = jsxElementNode?.openingElement ?? null;
@@ -1427,6 +1501,81 @@ export const computeSequencePropsStatusFromContent = ({
};
};
+export const computeSequencePropsStatusFromAst = ({
+ ast,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys = [],
+ effects,
+ videoConfigValues,
+}: {
+ ast: File;
+ nodePath: SequenceNodePath;
+ componentIdentity: JsxComponentIdentity | null;
+ keys: string[];
+ assetKeys?: string[];
+ effects: string[][];
+ videoConfigValues: VideoConfigValues | null;
+}): CanUpdateSequencePropsResponseTrue => {
+ return computeSequencePropsStatusFromAstAndIdentifiers({
+ ast,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys,
+ effects,
+ videoConfigIdentifierValues: getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ }),
+ });
+};
+
+export const computeSequencePropsStatusFromContent = ({
+ fileContents,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys = [],
+ effects,
+ videoConfigValues,
+}: {
+ fileContents: string;
+ nodePath: SequenceNodePath;
+ componentIdentity: JsxComponentIdentity | null;
+ keys: string[];
+ assetKeys?: string[];
+ effects: string[][];
+ videoConfigValues: VideoConfigValues | null;
+}): CanUpdateSequencePropsResponseTrue => {
+ const cachedAst = getCachedSequencePropsStatusAst(fileContents);
+ const {ast} = cachedAst;
+ const videoConfigCacheKey = JSON.stringify(videoConfigValues);
+ let videoConfigIdentifierValues =
+ cachedAst.videoConfigIdentifierValues.get(videoConfigCacheKey);
+ if (videoConfigIdentifierValues === undefined) {
+ videoConfigIdentifierValues = getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ });
+ cachedAst.videoConfigIdentifierValues.set(
+ videoConfigCacheKey,
+ videoConfigIdentifierValues,
+ );
+ }
+
+ return computeSequencePropsStatusFromAstAndIdentifiers({
+ ast,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys,
+ effects,
+ videoConfigIdentifierValues,
+ });
+};
+
export const computeSequencePropsStatus = ({
fileName,
nodePath,
@@ -1495,7 +1644,7 @@ export const computeSequencePropsStatusFromFilenameByLocation = ({
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const ast = parseAst(fileContents);
+ const {ast} = getCachedSequencePropsStatusAst(fileContents);
const resolvedNodePath = lineColumnToNodePath(
ast,
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.ts
index e42388df2c..d1f102e3c8 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
@@ -1,4 +1,5 @@
import {readFileSync} from 'node:fs';
+import type {File} from '@babel/types';
import {RenderInternals} from '@remotion/renderer';
import type {
AddSequenceKeyframe,
@@ -31,7 +32,11 @@ import {
suppressUndoStackInvalidation,
} from '../undo-stack';
import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';
-import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';
+import {
+ computeSequencePropsStatusFromAst,
+ computeSequencePropsStatusFromContent,
+ takeCachedSequencePropsStatusAst,
+} from './can-update-sequence-props';
import {logEffectUpdate} from './log-updates/log-effect-update';
import {logUpdate} from './log-updates/log-update';
import {withSourceFileWriteQueue} from './source-file-write-queue';
@@ -353,6 +358,7 @@ export const saveSequencePropsHandler: ApiHandler<
const snapshots: SequencePropUndoSnapshot[] = [];
const outputByPath = new Map<string, string>();
+ const statusAstByPath = new Map<string, File>();
const resultByIndex = new Map<number, SequencePropEditResult>();
const updatedNodePaths = new Map<string, SequenceNodePath>();
const sequenceKeyframeLogs: SequenceKeyframeLog[] = [];
@@ -362,6 +368,11 @@ export const saveSequencePropsHandler: ApiHandler<
for (const [absolutePath, group] of editGroups) {
const fileContents = readFileSync(absolutePath, 'utf-8');
let output = fileContents;
+ const cachedStatusAst =
+ group.edits.length > 0
+ ? takeCachedSequencePropsStatusAst(fileContents)
+ : null;
+ let sequencePropsAst: File | null = null;
let firstLogLine = Number.POSITIVE_INFINITY;
if (group.edits.length > 0) {
@@ -369,12 +380,15 @@ export const saveSequencePropsHandler: ApiHandler<
output: sequencePropsOutput,
formatted,
results: updateResults,
+ ast,
} = await updateMultipleSequenceProps({
input: output,
changes: group.edits.map(convertSequencePropEditToCodemodChange),
prettierConfigOverride: null,
+ ast: cachedStatusAst ?? undefined,
});
output = sequencePropsOutput;
+ sequencePropsAst = ast;
const firstUpdate = updateResults[0];
if (firstUpdate) {
firstLogLine = Math.min(firstLogLine, firstUpdate.logLine);
@@ -576,6 +590,16 @@ export const saveSequencePropsHandler: ApiHandler<
}
}
+ if (
+ sequencePropsAst &&
+ group.captionPatches.length === 0 &&
+ group.addedKeyframes.length === 0 &&
+ group.movedSequenceKeyframes.length === 0 &&
+ group.effectKeyframes.length === 0
+ ) {
+ statusAstByPath.set(absolutePath, sequencePropsAst);
+ }
+
outputByPath.set(absolutePath, output);
snapshots.push({
filePath: absolutePath,
@@ -706,8 +730,7 @@ export const saveSequencePropsHandler: ApiHandler<
throw new Error('Could not compute sequence prop edit status');
}
- const newStatus = computeSequencePropsStatusFromContent({
- fileContents: output,
+ const statusInput = {
keys: getAllSchemaKeys(target.schema),
assetKeys: getAssetSchemaKeys(target.schema),
nodePath:
@@ -717,7 +740,17 @@ export const saveSequencePropsHandler: ApiHandler<
componentIdentity: null,
effects: [],
videoConfigValues: target.nodePath.videoConfigValues,
- });
+ };
+ const statusAst = statusAstByPath.get(absolutePath);
+ const newStatus = statusAst
+ ? computeSequencePropsStatusFromAst({
+ ...statusInput,
+ ast: statusAst,
+ })
+ : computeSequencePropsStatusFromContent({
+ ...statusInput,
+ fileContents: output,
+ });
return {
fileName: target.fileName,
diff --git a/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts b/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts
index 20118f874e..40b115cefb 100644
--- a/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/subscribe-to-sequence-props.ts
@@ -1,43 +1,83 @@
import type {
- SubscribeToSequencePropsRequest,
- SubscribeToSequencePropsResponse,
+ SubscribeToSequencePropsBatchRequest,
+ SubscribeToSequencePropsBatchResponse,
} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
import type {ApiHandler} from '../api-types';
import {subscribeToSequencePropsWatchers} from '../sequence-props-watchers';
+import {resolveSequencePropsNodePathsFromFilename} from './can-update-sequence-props';
export const subscribeToSequenceProps: ApiHandler<
- SubscribeToSequencePropsRequest,
- SubscribeToSequencePropsResponse
-> = ({
- input: {
- fileName,
- line,
- column,
- nodePath,
- componentIdentity,
- keys,
- assetKeys = [],
- effects,
- clientId,
- videoConfigValues,
- },
- remotionRoot,
- logLevel,
-}) => {
- const result = subscribeToSequencePropsWatchers({
- fileName,
- line,
- column,
- nodePath,
- componentIdentity,
- keys,
- assetKeys,
- effects,
- remotionRoot,
- clientId,
- videoConfigValues,
- logLevel,
- });
+ SubscribeToSequencePropsBatchRequest,
+ SubscribeToSequencePropsBatchResponse
+> = ({input, remotionRoot, logLevel}) => {
+ const requests = input.requests ?? [input];
+ const unresolvedByFile = new Map<
+ string,
+ {index: number; line: number; column: number}[]
+ >();
+ for (const [index, request] of requests.entries()) {
+ if (request.nodePath !== null) {
+ continue;
+ }
+
+ const unresolved = unresolvedByFile.get(request.fileName) ?? [];
+ unresolved.push({index, line: request.line, column: request.column});
+ unresolvedByFile.set(request.fileName, unresolved);
+ }
- return Promise.resolve(result);
+ const resolvedNodePaths = new Map<number, SequenceNodePath>();
+ for (const [fileName, unresolved] of unresolvedByFile) {
+ try {
+ const nodePaths = resolveSequencePropsNodePathsFromFilename({
+ fileName,
+ targets: unresolved,
+ remotionRoot,
+ });
+ for (const [index, nodePath] of nodePaths.entries()) {
+ if (nodePath) {
+ resolvedNodePaths.set(unresolved[index].index, nodePath);
+ }
+ }
+ } catch {
+ // Let each subscription produce its usual not-found response.
+ }
+ }
+
+ const results = requests.map(
+ (
+ {
+ fileName,
+ line,
+ column,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys = [],
+ effects,
+ clientId,
+ videoConfigValues,
+ },
+ index,
+ ) =>
+ subscribeToSequencePropsWatchers({
+ fileName,
+ line,
+ column,
+ nodePath,
+ resolvedNodePath: resolvedNodePaths.get(index),
+ componentIdentity,
+ keys,
+ assetKeys,
+ effects,
+ remotionRoot,
+ clientId,
+ videoConfigValues,
+ logLevel,
+ }),
+ );
+ return Promise.resolve({
+ ...results[0],
+ results,
+ });
};
diff --git a/packages/studio-server/src/preview-server/sequence-props-watchers.ts b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
index ebca41556c..a3ee65cad7 100644
--- a/packages/studio-server/src/preview-server/sequence-props-watchers.ts
+++ b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
@@ -49,6 +49,7 @@ const getSequencePropsStatus = ({
line,
column,
preferredNodePath,
+ resolvedNodePath,
componentIdentity,
keys,
assetKeys,
@@ -61,6 +62,7 @@ const getSequencePropsStatus = ({
line: number;
column: number;
preferredNodePath: SequenceNodePath | null;
+ resolvedNodePath: SequenceNodePath | null;
componentIdentity: JsxComponentIdentity | null;
keys: string[];
assetKeys: string[];
@@ -147,6 +149,40 @@ const getSequencePropsStatus = ({
}
}
+ if (resolvedNodePath) {
+ try {
+ return {
+ status: computeSequencePropsStatus({
+ fileName,
+ nodePath: resolvedNodePath,
+ componentIdentity,
+ keys,
+ assetKeys,
+ effects,
+ remotionRoot,
+ videoConfigValues,
+ }),
+ nodePath: {
+ absolutePath: path.resolve(remotionRoot, fileName),
+ nodePath: resolvedNodePath,
+ sequenceKeys: keys,
+ effectKeys: effects,
+ videoConfigValues,
+ },
+ success: true,
+ };
+ } catch (error) {
+ if (
+ !(
+ error instanceof JsxElementIdentityMismatchError ||
+ error instanceof JsxElementNotFoundAtLocationError
+ )
+ ) {
+ throw error;
+ }
+ }
+ }
+
const status = computeSequencePropsStatusFromFilenameByLocation({
fileName,
line,
@@ -168,6 +204,7 @@ export const subscribeToSequencePropsWatchers = ({
line,
column,
nodePath: preferredNodePath,
+ resolvedNodePath = null,
componentIdentity,
keys,
assetKeys,
@@ -181,6 +218,7 @@ export const subscribeToSequencePropsWatchers = ({
line: number;
column: number;
nodePath: SequenceNodePath | null;
+ resolvedNodePath?: SequenceNodePath | null;
componentIdentity: JsxComponentIdentity | null;
keys: string[];
assetKeys: string[];
@@ -195,6 +233,7 @@ export const subscribeToSequencePropsWatchers = ({
line,
column,
preferredNodePath,
+ resolvedNodePath,
componentIdentity,
keys,
assetKeys,
diff --git a/packages/studio-server/src/test/compute-sequence-props-status.test.ts b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
index f9059bd703..7621913110 100644
--- a/packages/studio-server/src/test/compute-sequence-props-status.test.ts
+++ b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
@@ -10,6 +10,7 @@ import {
computeSequencePropsStatusFromContent,
computeSequencePropsStatusFromFilenameByLocation,
lineColumnToNodePath,
+ lineColumnsToNodePaths,
} from '../preview-server/routes/can-update-sequence-props';
const getNodePath = (filePath: string, line: number) => {
@@ -129,6 +130,26 @@ export const Fallback = () => <><Sequence name="First" /><Sequence name="Fallbac
}
});
+test('lineColumnsToNodePaths matches individual location resolution', () => {
+ const input = `export const Example = () => (
+ <div><span /><span><strong /></span></div>
+);`;
+ const ast = parseAst(input);
+ const targets = [
+ getSourceLocation(input, '<div>'),
+ getSourceLocation(input, '<span />'),
+ getSourceLocation(input, '<span><strong'),
+ getSourceLocation(input, '<strong'),
+ {...getSourceLocation(input, '<strong'), column: 999},
+ ];
+
+ expect(lineColumnsToNodePaths({ast, targets, fileContents: input})).toEqual(
+ targets.map(({line, column}) =>
+ lineColumnToNodePath(ast, line, column, input),
+ ),
+ );
+});
+
test('computeSequencePropsStatus should ignore source locations outside the project', () => {
const remotionRoot = mkdtempSync(
path.join(tmpdir(), 'remotion-jsx-location-'),
diff --git a/packages/studio-server/src/test/delete-jsx-node.test.ts b/packages/studio-server/src/test/delete-jsx-node.test.ts
index 00915f4e01..bc62f72527 100644
--- a/packages/studio-server/src/test/delete-jsx-node.test.ts
+++ b/packages/studio-server/src/test/delete-jsx-node.test.ts
@@ -2,7 +2,10 @@ import {expect, test} from 'bun:test';
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
-import type {EventSourceEvent} from '@remotion/studio-shared';
+import type {
+ EventSourceEvent,
+ SubscribeToSequencePropsRequest,
+} from '@remotion/studio-shared';
import {deleteJsxNode, deleteJsxNodes} from '../codemods/delete-jsx-node';
import {
createFileWatcherRegistry,
@@ -204,29 +207,34 @@ test('deleting a JSX node broadcasts node path mutations for all clients', async
};
try {
- for (const line of [6, 7, 8]) {
- const result = await subscribeToSequenceProps({
- ...apiHandlerContext,
- input: {
- assetKeys: [],
- clientId,
- column: 0,
- componentIdentity: 'dev.remotion.remotion.Interactive.Div',
- effects: [],
- fileName,
- keys: ['name'],
- line,
- nodePath: lineColumnToNodePath(interactiveSiblings, line),
- videoConfigValues: {
- durationInFrames: 100,
- fps: 30,
- height: 1080,
- width: 1920,
- },
+ const requests: SubscribeToSequencePropsRequest[] = [6, 7, 8].map(
+ (line) => ({
+ assetKeys: [],
+ clientId,
+ column: 0,
+ componentIdentity: 'dev.remotion.remotion.Interactive.Div',
+ effects: [],
+ fileName,
+ keys: ['name'],
+ line,
+ nodePath: lineColumnToNodePath(interactiveSiblings, line),
+ videoConfigValues: {
+ durationInFrames: 100,
+ fps: 30,
+ height: 1080,
+ width: 1920,
},
- });
- expect(result.success).toBe(true);
- }
+ }),
+ );
+ const subscription = await subscribeToSequenceProps({
+ ...apiHandlerContext,
+ input: {
+ ...requests[0],
+ requests,
+ },
+ });
+ expect(subscription.success).toBe(true);
+ expect(subscription.results.every((result) => result.success)).toBe(true);
const response = await deleteJsxNodeHandler({
...apiHandlerContext,
diff --git a/packages/studio-server/src/test/subscribe-to-sequence-props.test.ts b/packages/studio-server/src/test/subscribe-to-sequence-props.test.ts
new file mode 100644
index 0000000000..520187d47e
--- /dev/null
+++ b/packages/studio-server/src/test/subscribe-to-sequence-props.test.ts
@@ -0,0 +1,130 @@
+import {expect, test} from 'bun:test';
+import {mkdtempSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import {basename, join} from 'node:path';
+import type {SubscribeToSequencePropsRequest} from '@remotion/studio-shared';
+import {
+ createFileWatcherRegistry,
+ setFileWatcherRegistry,
+} from '../file-watcher';
+import {subscribeToSequenceProps} from '../preview-server/routes/subscribe-to-sequence-props';
+import {unsubscribeClientSequencePropsWatchers} from '../preview-server/sequence-props-watchers';
+import {lineColumnToNodePath} from './test-utils';
+
+test('resolves batched sequence prop subscriptions through the handler', async () => {
+ const firstInput = `import {Interactive} from 'remotion';
+
+export const First = () => {
+ return (
+ <>
+ <Interactive.Div name="One" />
+ <Interactive.Div name="Two" />
+ </>
+ );
+};
+`;
+ const secondInput = `import {Interactive} from 'remotion';
+
+export const Second = () => {
+ return <Interactive.Div name="Three" />;
+};
+`;
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const remotionRoot = mkdtempSync(join(tmpdir(), 'remotion-subscriptions-'));
+ const uniqueSuffix = basename(remotionRoot);
+ const firstFileName = `First-${uniqueSuffix}.tsx`;
+ const secondFileName = `Second-${uniqueSuffix}.tsx`;
+ const clientId = `subscription-test-${uniqueSuffix}`;
+ writeFileSync(join(remotionRoot, firstFileName), firstInput);
+ writeFileSync(join(remotionRoot, secondFileName), secondInput);
+ const videoConfigValues = {
+ durationInFrames: 100,
+ fps: 30,
+ height: 1080,
+ width: 1920,
+ };
+ const requestBase = {
+ column: 0,
+ componentIdentity: 'dev.remotion.remotion.Interactive.Div',
+ keys: ['name'],
+ assetKeys: [],
+ effects: [],
+ clientId,
+ videoConfigValues,
+ } satisfies Omit<
+ SubscribeToSequencePropsRequest,
+ 'fileName' | 'line' | 'nodePath'
+ >;
+ const requests: SubscribeToSequencePropsRequest[] = [
+ {
+ ...requestBase,
+ fileName: firstFileName,
+ line: 6,
+ nodePath: null,
+ },
+ {
+ ...requestBase,
+ fileName: firstFileName,
+ line: 7,
+ nodePath: null,
+ },
+ {
+ ...requestBase,
+ fileName: secondFileName,
+ line: 4,
+ nodePath: null,
+ },
+ {
+ ...requestBase,
+ fileName: secondFileName,
+ line: 4,
+ nodePath: lineColumnToNodePath(secondInput, 4),
+ },
+ ];
+
+ try {
+ const response = await subscribeToSequenceProps({
+ binariesDirectory: null,
+ configFile: null,
+ entryPoint: join(remotionRoot, firstFileName),
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+ input: {...requests[0], requests},
+ logLevel: 'error',
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: remotionRoot,
+ remotionRoot,
+ request: {} as never,
+ response: {} as never,
+ });
+ const expectedNodePaths = [
+ lineColumnToNodePath(firstInput, 6),
+ lineColumnToNodePath(firstInput, 7),
+ lineColumnToNodePath(secondInput, 4),
+ lineColumnToNodePath(secondInput, 4),
+ ];
+ const expectedNames = ['One', 'Two', 'Three', 'Three'];
+ expect(response.results).toHaveLength(requests.length);
+ for (const [index, result] of response.results.entries()) {
+ if (!result.success) {
+ throw new Error(`Subscription ${index} failed`);
+ }
+
+ expect(result.nodePath.nodePath).toEqual(expectedNodePaths[index]);
+ expect(result.status.props.name).toEqual({
+ status: 'static',
+ codeValue: expectedNames[index],
+ });
+ }
+ } finally {
+ unsubscribeClientSequencePropsWatchers(clientId);
+ cleanupFileWatcher();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.ts
index 7dc926d249..346e700c21 100644
--- a/packages/studio-server/src/test/update-sequence-props.test.ts
+++ b/packages/studio-server/src/test/update-sequence-props.test.ts
@@ -1,9 +1,14 @@
import {expect, test} from 'bun:test';
+import * as recast from 'recast';
import {NoReactInternals} from 'remotion/no-react';
import {
updateMultipleSequenceProps,
updateSequenceProps,
} from '../codemods/update-sequence-props/update-sequence-props';
+import {
+ computeSequencePropsStatusFromContent,
+ takeCachedSequencePropsStatusAst,
+} from '../preview-server/routes/can-update-sequence-props';
import {lineColumnToNodePath} from './test-utils';
const lightLeakInput = `import {LightLeak} from '@remotion/light-leaks';
@@ -582,6 +587,128 @@ test('updateMultipleSequenceProps should update multiple nodes in one format pas
expect(output.split('\n')[8]).toContain('durationInFrames={120}');
});
+test('updateMultipleSequenceProps should not format a no-op edit', async () => {
+ const unformattedInput = lightLeakInput.replace(
+ '\t\t<AbsoluteFill',
+ ' <AbsoluteFill',
+ );
+ const {output, formatted} = await updateMultipleSequenceProps({
+ input: unformattedInput,
+ changes: [
+ {
+ nodePath: lineColumnToNodePath(unformattedInput, 8),
+ updates: [{key: 'hueShift', value: 30, defaultValue: null}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ prettierConfigOverride: null,
+ });
+
+ expect(output).toBe(unformattedInput);
+ expect(formatted).toBe(true);
+});
+
+test('updateMultipleSequenceProps should only format the edited opening element', async () => {
+ const input = `const unrelated = {keep: "double quotes"};
+
+export const Example = () => {
+ return <Interactive.Div name = "Example">Text</Interactive.Div>;
+};
+`;
+ const {output, formatted} = await updateMultipleSequenceProps({
+ input,
+ changes: [
+ {
+ nodePath: lineColumnToNodePath(input, 4),
+ updates: [{key: 'hidden', value: true, defaultValue: false}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+
+ expect(output).toBe(`const unrelated = {keep: "double quotes"};
+
+export const Example = () => {
+ return <Interactive.Div name="Example" hidden>Text</Interactive.Div>;
+};
+`);
+ expect(formatted).toBe(true);
+});
+
+test('updateMultipleSequenceProps formats a multiline non-self-closing opening element', async () => {
+ const input = `export const Example = () => {
+ return (
+ <Interactive.Div
+ name="Example"
+ style={{height: 8, scale: 1, width: 8}}
+ >
+ Text
+ </Interactive.Div>
+ );
+};
+`;
+ const {output, formatted} = await updateMultipleSequenceProps({
+ input,
+ changes: [
+ {
+ nodePath: lineColumnToNodePath(input, 3),
+ updates: [{key: 'style.scale', value: 1.353, defaultValue: null}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+
+ expect(output).toBe(`export const Example = () => {
+ return (
+ <Interactive.Div name="Example" style={{ height: 8, scale: 1.353, width: 8 }}>
+ Text
+ </Interactive.Div>
+ );
+};
+`);
+ expect(formatted).toBe(true);
+});
+
+test('updateMultipleSequenceProps reuses the status AST across the shared Recast runtime', async () => {
+ const nodePath = lineColumnToNodePath(lightLeakInput, 8);
+ computeSequencePropsStatusFromContent({
+ fileContents: lightLeakInput,
+ nodePath,
+ componentIdentity: null,
+ keys: ['hueShift'],
+ effects: [],
+ videoConfigValues: null,
+ });
+ expect(takeCachedSequencePropsStatusAst(`${lightLeakInput}\n`)).toBeNull();
+ const cachedAst = takeCachedSequencePropsStatusAst(lightLeakInput);
+ if (!cachedAst) {
+ throw new Error('Expected the status AST to be reusable');
+ }
+
+ const {ast} = await updateMultipleSequenceProps({
+ input: lightLeakInput,
+ changes: [
+ {
+ nodePath,
+ updates: [{key: 'hueShift', value: 90, defaultValue: null}],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ prettierConfigOverride: null,
+ ast: cachedAst,
+ });
+
+ expect(ast).toBe(cachedAst);
+ expect(() => recast.print(ast).code).not.toThrow();
+ expect(takeCachedSequencePropsStatusAst(lightLeakInput)).toBeNull();
+});
+
test('updateSequenceProps should update JSX text children', async () => {
const input = `import React from 'react';
import {Interactive} from 'remotion';
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index f5e9ae44f8..edb3c2c851 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -348,6 +348,16 @@ export type SubscribeToSequencePropsResponse =
status: CanUpdateSequencePropsResponseFalse;
};
+export type SubscribeToSequencePropsBatchRequest =
+ SubscribeToSequencePropsRequest & {
+ requests?: SubscribeToSequencePropsRequest[];
+ };
+
+export type SubscribeToSequencePropsBatchResponse =
+ SubscribeToSequencePropsResponse & {
+ results: SubscribeToSequencePropsResponse[];
+ };
+
export type UnsubscribeFromSequencePropsRequest = {
fileName: string;
nodePath: SequencePropsSubscriptionKey;
@@ -1186,8 +1196,8 @@ export type ApiRoutes = {
undefined
>;
'/api/subscribe-to-sequence-props': ReqAndRes<
- SubscribeToSequencePropsRequest,
- SubscribeToSequencePropsResponse
+ SubscribeToSequencePropsBatchRequest,
+ SubscribeToSequencePropsBatchResponse
>;
'/api/unsubscribe-from-sequence-props': ReqAndRes<
UnsubscribeFromSequencePropsRequest,
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 6add72af06..ca8a8a9947 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -124,6 +124,8 @@ export {
SubscribeToDefaultPropsResponse,
SubscribeToFileExistenceRequest,
SubscribeToFileExistenceResponse,
+ SubscribeToSequencePropsBatchRequest,
+ SubscribeToSequencePropsBatchResponse,
SubscribeToSequencePropsRequest,
SubscribeToSequencePropsResponse,
UndoRequest,
diff --git a/packages/studio/src/components/sequence-props-api.ts b/packages/studio/src/components/sequence-props-api.ts
index c742f79002..486786d64c 100644
--- a/packages/studio/src/components/sequence-props-api.ts
+++ b/packages/studio/src/components/sequence-props-api.ts
@@ -1,6 +1,7 @@
import type {
SaveSequencePropsRequest,
SaveSequencePropsResponse,
+ SubscribeToSequencePropsBatchResponse,
SubscribeToSequencePropsRequest,
SubscribeToSequencePropsResponse,
UnsubscribeFromSequencePropsRequest,
@@ -8,6 +9,61 @@ import type {
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {callApi} from './call-api';
+type PendingSequencePropsSubscription = {
+ request: SubscribeToSequencePropsRequest;
+ resolve: (response: SubscribeToSequencePropsResponse) => void;
+ reject: (error: unknown) => void;
+};
+
+let pendingSequencePropsSubscriptions: PendingSequencePropsSubscription[] = [];
+let sequencePropsSubscriptionTimer: ReturnType<typeof setTimeout> | null = null;
+
+const flushSequencePropsSubscriptions = () => {
+ sequencePropsSubscriptionTimer = null;
+ const pending = pendingSequencePropsSubscriptions;
+ pendingSequencePropsSubscriptions = [];
+ const firstRequest = pending[0].request;
+
+ callApi('/api/subscribe-to-sequence-props', {
+ ...firstRequest,
+ requests: pending.map(({request}) => request),
+ }).then(
+ (response: SubscribeToSequencePropsBatchResponse) => {
+ if (!Array.isArray(response.results)) {
+ pending[0].resolve(response as SubscribeToSequencePropsResponse);
+ const error = new Error(
+ 'Legacy single subscription response received for a batched request',
+ );
+ for (const item of pending.slice(1)) {
+ item.reject(error);
+ }
+
+ return;
+ }
+
+ if (response.results.length !== pending.length) {
+ const error = new Error(
+ `Expected ${pending.length} sequence prop subscription results, got ${response.results.length}`,
+ );
+ for (const item of pending) {
+ item.reject(error);
+ }
+
+ return;
+ }
+
+ for (let index = 0; index < pending.length; index++) {
+ pending[index].resolve(response.results[index]);
+ }
+ },
+ (error) => {
+ for (const item of pending) {
+ item.reject(error);
+ }
+ },
+ );
+};
+
export const saveSequenceProps = (
request: SaveSequencePropsRequest,
): Promise<SaveSequencePropsResponse> => {
@@ -21,9 +77,19 @@ export const subscribeToSequenceProps = (
request: SubscribeToSequencePropsRequest,
): Promise<SubscribeToSequencePropsResponse> => {
const browserStudioOperations = getBrowserStudioOperations();
- return browserStudioOperations
- ? browserStudioOperations.subscribeToSequenceProps(request)
- : callApi('/api/subscribe-to-sequence-props', request);
+ if (browserStudioOperations) {
+ return browserStudioOperations.subscribeToSequenceProps(request);
+ }
+
+ return new Promise((resolve, reject) => {
+ pendingSequencePropsSubscriptions.push({request, resolve, reject});
+ if (sequencePropsSubscriptionTimer === null) {
+ sequencePropsSubscriptionTimer = setTimeout(
+ flushSequencePropsSubscriptions,
+ 0,
+ );
+ }
+ });
};
export const unsubscribeFromSequenceProps = (
diff --git a/packages/studio/src/test/browser-studio-sequence-props.test.ts b/packages/studio/src/test/browser-studio-sequence-props.test.ts
index 04eda25b27..d9276119be 100644
--- a/packages/studio/src/test/browser-studio-sequence-props.test.ts
+++ b/packages/studio/src/test/browser-studio-sequence-props.test.ts
@@ -123,3 +123,152 @@ test('routes sequence prop operations through Browser Studio', async () => {
'unsubscribe:browser-studio:src/Composition.tsx',
]);
});
+
+test('batches server sequence prop subscriptions into one request', async () => {
+ const previousFetch = globalThis.fetch;
+ const calls: unknown[] = [];
+ globalThis.fetch = ((_input, init) => {
+ const body = JSON.parse(String(init?.body));
+ calls.push(body);
+
+ return Promise.resolve({
+ json: () =>
+ Promise.resolve({
+ success: true,
+ data: {
+ results: body.requests.map((request: {line: number}) => ({
+ success: true,
+ nodePath: {
+ absolutePath: '/project/src/Composition.tsx',
+ nodePath: ['program', 'body', request.line],
+ sequenceKeys: ['from'],
+ effectKeys: [],
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ },
+ status: {
+ canUpdate: true,
+ props: {from: {status: 'static', codeValue: request.line}},
+ effects: [],
+ },
+ })),
+ },
+ }),
+ } as Response);
+ }) as typeof fetch;
+
+ const subscribe = (line: number) =>
+ subscribeToSequenceProps({
+ fileName: 'src/Composition.tsx',
+ line,
+ column: 0,
+ nodePath: null,
+ componentIdentity: 'dev.remotion.remotion.Sequence',
+ keys: ['from'],
+ assetKeys: [],
+ effects: [],
+ clientId: 'studio',
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ });
+
+ try {
+ const results = await Promise.all(
+ Array.from({length: 1000}, (_, index) => subscribe(index + 2)),
+ );
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ requests: Array.from({length: 1000}, (_, index) => ({line: index + 2})),
+ });
+ const first = results[0];
+ const last = results.at(-1);
+ expect(first.success && first.status.props.from).toEqual({
+ status: 'static',
+ codeValue: 2,
+ });
+ expect(last?.success && last.status.props.from).toEqual({
+ status: 'static',
+ codeValue: 1001,
+ });
+ } finally {
+ globalThis.fetch = previousFetch;
+ }
+});
+
+test('handles a legacy single-subscription response to a batched request', async () => {
+ const previousFetch = globalThis.fetch;
+ const nodePath = {
+ absolutePath: '/project/src/Composition.tsx',
+ nodePath: ['program', 'body', 2],
+ sequenceKeys: ['from'],
+ effectKeys: [],
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ };
+ globalThis.fetch = (() =>
+ Promise.resolve({
+ json: () =>
+ Promise.resolve({
+ success: true,
+ data: {
+ success: true,
+ nodePath,
+ status: {
+ canUpdate: true,
+ props: {from: {status: 'static', codeValue: 10}},
+ effects: [],
+ },
+ },
+ }),
+ } as Response)) as unknown as typeof fetch;
+
+ const subscribe = (line: number) =>
+ subscribeToSequenceProps({
+ fileName: 'src/Composition.tsx',
+ line,
+ column: 0,
+ nodePath: null,
+ componentIdentity: 'dev.remotion.remotion.Sequence',
+ keys: ['from'],
+ assetKeys: [],
+ effects: [],
+ clientId: 'studio',
+ videoConfigValues: nodePath.videoConfigValues,
+ });
+
+ try {
+ const results = await Promise.allSettled([subscribe(2), subscribe(3)]);
+ expect(results[0]).toEqual({
+ status: 'fulfilled',
+ value: {
+ success: true,
+ nodePath,
+ status: {
+ canUpdate: true,
+ props: {from: {status: 'static', codeValue: 10}},
+ effects: [],
+ },
+ },
+ });
+ expect(results[1]).toEqual({
+ status: 'rejected',
+ reason: new Error(
+ 'Legacy single subscription response received for a batched request',
+ ),
+ });
+ } finally {
+ globalThis.fetch = previousFetch;
+ }
+});