Skip to content

🎥 Make videos programmatically with React

`@remotion/codemods`: Speed up edits by reusing parsed source

JonnyBurger6a0beba624a2
diff --git a/packages/codemods/src/effect-operations.ts b/packages/codemods/src/effect-operations.ts
index b988309073..f9b529a560 100644
--- a/packages/codemods/src/effect-operations.ts
+++ b/packages/codemods/src/effect-operations.ts
@@ -1000,32 +1000,21 @@ const makeEffectPropExpression = ({
return makeClipboardParamExpression({param: update.effectParam, localNames});
};
-export const updateEffectPropsAst = ({
+const applyEffectPropUpdate = ({
+ ast,
effectIndex,
- input,
- prettierConfigOverride,
schema,
sequenceNodePath,
update,
+ jsx,
}: {
+ ast: File;
effectIndex: number;
- input: string;
- prettierConfigOverride?: Record<string, unknown> | null;
schema: InteractivitySchema;
sequenceNodePath: SequenceNodePath;
update: EffectPropUpdate;
-}): {
- serialized: string;
- oldValueString: string;
- newValueString: string;
- logLine: number;
- effectCallee: string;
- removedProps: PropDelta[];
-} => {
- const ast = parseAst(input);
- const snapshots = captureEffectSourceSnapshots(ast);
- const jsx = getJsx({action: 'update', ast, sequenceNodePath});
- trackOpeningElement({jsx, snapshots});
+ jsx: JSXOpeningElement;
+}) => {
const attr = findEffectsAttr(jsx.attributes);
if (!attr) {
throw new Error('Could not find effects on the target JSX element');
@@ -1045,7 +1034,7 @@ export const updateEffectPropsAst = ({
if (call.arguments.length === 0) {
if (isDefault) {
return {
- serialized: input,
+ changed: false,
oldValueString: '',
newValueString: JSON.stringify(update.defaultValue),
logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
@@ -1109,12 +1098,7 @@ export const updateEffectPropsAst = ({
}
return {
- serialized: getEffectSourceOutput({
- ast,
- input,
- prettierConfigOverride: prettierConfigOverride ?? null,
- snapshots,
- }),
+ changed: true,
oldValueString,
newValueString,
logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,
@@ -1123,6 +1107,46 @@ export const updateEffectPropsAst = ({
};
};
+export const updateEffectPropsAst = ({
+ effectIndex,
+ input,
+ prettierConfigOverride,
+ schema,
+ sequenceNodePath,
+ update,
+}: {
+ effectIndex: number;
+ input: string;
+ prettierConfigOverride?: Record<string, unknown> | null;
+ schema: InteractivitySchema;
+ sequenceNodePath: SequenceNodePath;
+ update: EffectPropUpdate;
+}) => {
+ const ast = parseAst(input);
+ const snapshots = captureEffectSourceSnapshots(ast);
+ const jsx = getJsx({action: 'update', ast, sequenceNodePath});
+ trackOpeningElement({jsx, snapshots});
+ const {changed, ...result} = applyEffectPropUpdate({
+ ast,
+ effectIndex,
+ schema,
+ sequenceNodePath,
+ update,
+ jsx,
+ });
+ return {
+ ...result,
+ serialized: changed
+ ? getEffectSourceOutput({
+ ast,
+ input,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ snapshots,
+ })
+ : input,
+ };
+};
+
export const updateEffectProps = ({
effectIndex,
input,
@@ -1164,3 +1188,103 @@ export const updateEffectProps = ({
removedProps,
};
});
+
+export const batchUpdateEffectProps = async ({
+ effectIndex,
+ input,
+ schema,
+ sequenceNodePath,
+ updates,
+}: {
+ effectIndex: number;
+ input: string;
+ schema: InteractivitySchema;
+ sequenceNodePath: SequenceNodePath;
+ updates: EffectPropUpdate[];
+}): Promise<UpdateEffectPropsResult[]> => {
+ const results: UpdateEffectPropsResult[] = [];
+ let output = input;
+ // Keyframes may rewrite the enclosing function and imports. Keep their
+ // existing source-edit path; static batches only replace one opening tag.
+ const canBatch =
+ updates.length > 1 &&
+ updates.every(
+ (update) =>
+ !isEffectParamUpdate(update) || update.effectParam.type === 'static',
+ );
+ const ast = canBatch ? parseAst(input) : null;
+ const snapshots = ast ? captureEffectSourceSnapshots(ast) : null;
+ let jsx = ast ? getJsx({action: 'update', ast, sequenceNodePath}) : null;
+ for (let index = 0; index < updates.length; index++) {
+ if (!ast || !snapshots || !jsx) {
+ const edit = await updateEffectProps({
+ input: output,
+ sequenceNodePath,
+ effectIndex,
+ update: updates[index],
+ schema,
+ });
+ output = edit.output;
+ results.push(edit);
+ continue;
+ }
+
+ trackOpeningElement({jsx, snapshots});
+ const {changed, ...result} = applyEffectPropUpdate({
+ ast,
+ effectIndex,
+ schema,
+ sequenceNodePath,
+ update: updates[index],
+ jsx,
+ });
+ const previousOutput = output;
+ output = changed
+ ? getEffectSourceOutput({
+ ast,
+ input: output,
+ prettierConfigOverride: null,
+ snapshots,
+ })
+ : output;
+ results.push({output, formatted: true, ...result});
+ if (!changed || index === updates.length - 1) {
+ continue;
+ }
+
+ // Refresh only the edited tag so subsequent results retain the exact
+ // intermediate source spelling and line numbers. Padding preserves the
+ // absolute locations used by the source-edit printer without reparsing
+ // the rest of the file.
+ const start = recastLocToOffset(previousOutput, jsx.loc!.start);
+ const end =
+ recastLocToOffset(previousOutput, jsx.loc!.end) +
+ output.length -
+ previousOutput.length;
+ const {line, column} = jsx.loc!.start;
+ const padding = '\n'.repeat(line - 1) + ' '.repeat(column);
+ const closing = jsx.selfClosing ? '' : `</${recast.print(jsx.name).code}>`;
+ try {
+ const fragment = parseAst(
+ `${padding}${output.slice(start, end)}${closing}`,
+ );
+ const statement = fragment.program.body[0];
+ if (
+ statement?.type !== 'ExpressionStatement' ||
+ statement.expression.type !== 'JSXElement'
+ ) {
+ throw new Error('Expected a JSX fragment');
+ }
+
+ jsx = statement.expression.openingElement;
+ snapshots.openingElementLocations.clear();
+ snapshots.originalAttributeSources.clear();
+ } catch {
+ // Context-dependent expressions such as yield or super cannot be
+ // parsed on their own. Finish those updates in their full context.
+ jsx = null;
+ }
+ }
+
+ return results;
+};
diff --git a/packages/codemods/src/effect-references.ts b/packages/codemods/src/effect-references.ts
index 07e24b7e4c..b961cc1513 100644
--- a/packages/codemods/src/effect-references.ts
+++ b/packages/codemods/src/effect-references.ts
@@ -2,8 +2,8 @@ import type {CodemodProject} from './codemod-project';
import {findProjectFile} from './internals';
import {type NodeReference} from './node-references';
import {findJsxElementAtNodePath} from './sequence-props';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {findEffectsAttr} from './sequence-props/can-update-effect-props';
-import {parseAst} from './sequence-props/parse-ast';
export type EffectReference = NodeReference & {effectIndex: number};
@@ -16,7 +16,7 @@ export const getEffectSource = ({
}) => {
const filePath = findProjectFile({project, filePath: node.filePath});
const input = project.files[filePath];
- const ast = parseAst(input);
+ const {ast} = getReadOnlySourceSnapshot(input);
const jsx = findJsxElementAtNodePath(ast, node.nodePath);
if (!jsx) {
throw new Error('Could not find the JSX node');
diff --git a/packages/codemods/src/folder-editing.ts b/packages/codemods/src/folder-editing.ts
index b780e54659..7af0afc924 100644
--- a/packages/codemods/src/folder-editing.ts
+++ b/packages/codemods/src/folder-editing.ts
@@ -21,6 +21,7 @@ import {
getCompositionIdFromJSXElement,
getFolderNameFromJSXElement,
} from './registration-source-edits';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {parseAst} from './sequence-props/parse-ast';
import {applySourceEdits} from './source-edits';
@@ -117,8 +118,8 @@ export const getRegistrationInsertionResult = ({
| CompositionTreeItem
| {type: 'last-child'; folder: FolderReference | null};
}): CodemodInsertionResult => {
- const before = captureJsxNodePaths(parseAst(input));
- const nextAst = parseAst(output);
+ const before = captureJsxNodePaths(getReadOnlySourceSnapshot(input).ast);
+ const {ast: nextAst} = getReadOnlySourceSnapshot(output);
const after = captureJsxNodePaths(nextAst);
let element: JSXElement;
if (inserted.type === 'last-child') {
diff --git a/packages/codemods/src/get-node-path-remappings.ts b/packages/codemods/src/get-node-path-remappings.ts
index 07ca8e0cf0..641e7450c3 100644
--- a/packages/codemods/src/get-node-path-remappings.ts
+++ b/packages/codemods/src/get-node-path-remappings.ts
@@ -5,17 +5,20 @@ import type {SequenceNodePath} from 'remotion';
import {getNodePathForRecastPath} from './sequence-props';
import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
-export type CapturedJsxNodePath = {
+type JsxNodeWithPath = {
node: JSXOpeningElement;
nodePath: SequenceNodePath;
- jsxName: string;
- signature: string;
// The opening element of the closest enclosing JSX element, if any.
parentNode: JSXOpeningElement | null;
};
-export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
- const captured: CapturedJsxNodePath[] = [];
+export type CapturedJsxNodePath = JsxNodeWithPath & {
+ jsxName: string;
+ signature: string;
+};
+
+export const getJsxNodesWithPaths = (ast: File): JsxNodeWithPath[] => {
+ const captured: JsxNodeWithPath[] = [];
recast.visit(ast, {
visitJSXOpeningElement(path) {
let parentNode: JSXOpeningElement | null = null;
@@ -33,8 +36,6 @@ export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
captured.push({
node: path.node as JSXOpeningElement,
nodePath: getNodePathForRecastPath(path, ast),
- jsxName: recast.prettyPrint(path.node.name).code,
- signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
parentNode,
});
return this.traverse(path);
@@ -44,6 +45,14 @@ export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
return captured;
};
+export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {
+ return getJsxNodesWithPaths(ast).map((entry) => ({
+ ...entry,
+ jsxName: recast.prettyPrint(entry.node.name).code,
+ signature: recast.prettyPrint(entry.node).code,
+ }));
+};
+
// The opening elements of a JSX element and its descendants. Relies on the
// captured nodes being in document order, so parents precede their children.
export const collectJsxSubtree = (
diff --git a/packages/codemods/src/get-nodes.ts b/packages/codemods/src/get-nodes.ts
index 36c0f3a00b..96028d26fd 100644
--- a/packages/codemods/src/get-nodes.ts
+++ b/packages/codemods/src/get-nodes.ts
@@ -1,7 +1,7 @@
import * as recast from 'recast';
import type {JsxComponentIdentity, SequenceNodePath} from 'remotion';
import type {CodemodProject} from './codemod-project';
-import {captureJsxNodePaths} from './get-node-path-remappings';
+import {getJsxNodesWithPaths} from './get-node-path-remappings';
import {findProjectFile} from './internals';
import type {NodeReference} from './node-references';
import {recastLocToOffset} from './recast-loc-to-offset';
@@ -27,7 +27,7 @@ export const getNodes = ({
const resolvedFilePath = findProjectFile({project, filePath});
const input = project.files[resolvedFilePath];
const {ast} = getReadOnlySourceSnapshot(input);
- const captured = captureJsxNodePaths(ast);
+ const captured = getJsxNodesWithPaths(ast);
const nodePathByNode = new Map(
captured.map(({node, nodePath}) => [node, nodePath]),
);
diff --git a/packages/codemods/src/node-references.ts b/packages/codemods/src/node-references.ts
index e15ff9d5da..672057e743 100644
--- a/packages/codemods/src/node-references.ts
+++ b/packages/codemods/src/node-references.ts
@@ -1,13 +1,14 @@
import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
+import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import type {CodemodProject, CodemodResult} from './codemod-project';
import {getCodemodResult} from './codemod-project';
import {
- captureJsxNodePaths,
+ getJsxNodesWithPaths,
type CapturedJsxNodePath,
} from './get-node-path-remappings';
import {findProjectFile} from './internals';
-import {parseAst} from './sequence-props/parse-ast';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
export type NodeReference = {
filePath: string;
@@ -90,15 +91,18 @@ export const getUnchangedStructureRemappings = ({
input: string;
output: string;
}): NodeSourceEdit['nodePathRemappings'] => {
- const before = captureJsxNodePaths(parseAst(input));
- const after = captureJsxNodePaths(parseAst(output));
+ const before = getJsxNodesWithPaths(getReadOnlySourceSnapshot(input).ast);
+ const after = getJsxNodesWithPaths(getReadOnlySourceSnapshot(output).ast);
if (before.length !== after.length) {
throw new Error('The edit unexpectedly changed the JSX structure');
}
return before.flatMap((node, index) => {
const next = after[index];
- return isUnchangedNode(node, next)
+ const unchanged =
+ JSON.stringify(node.nodePath) === JSON.stringify(next.nodePath) &&
+ recast.prettyPrint(node.node).code === recast.prettyPrint(next.node).code;
+ return unchanged
? []
: [{oldNodePath: node.nodePath, newNodePath: next.nodePath}];
});
diff --git a/packages/codemods/src/precompose-jsx-nodes.ts b/packages/codemods/src/precompose-jsx-nodes.ts
index e04ff2adc6..807980b1b1 100644
--- a/packages/codemods/src/precompose-jsx-nodes.ts
+++ b/packages/codemods/src/precompose-jsx-nodes.ts
@@ -30,6 +30,7 @@ import {
import {getStyleablePrecompositionRoot} from './precompose-styleable-root';
import {captureJsxAttributeSources, printJsxOpeningElement} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {ensureNamedImport, getImportedName} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
import {
@@ -1519,8 +1520,8 @@ const getRegistrationPathChanges = ({
after: string;
compositionId: string;
}) => {
- const original = captureJsxNodePaths(parseAst(before));
- const updated = captureJsxNodePaths(parseAst(after));
+ const original = captureJsxNodePaths(getReadOnlySourceSnapshot(before).ast);
+ const updated = captureJsxNodePaths(getReadOnlySourceSnapshot(after).ast);
const inserted = updated.filter(({node: {attributes}}) => {
return (
attributes.some(
diff --git a/packages/codemods/src/recast-loc-to-offset.ts b/packages/codemods/src/recast-loc-to-offset.ts
index bd4f82bfe7..b10a1bdf02 100644
--- a/packages/codemods/src/recast-loc-to-offset.ts
+++ b/packages/codemods/src/recast-loc-to-offset.ts
@@ -1,14 +1,34 @@
const RECAST_TAB_WIDTH = 4;
+const lineStartsBySource = new Map<string, number[]>();
+const maximumCachedSources = 8;
// Recast normalizes every line ending, removes zero-width indentation, and
-// expands tabs in leading whitespace before parsing. Walk the parsed location
-// and original source together so the offset remains platform-independent.
+// expands tabs in leading whitespace before parsing. Index line starts once
+// per source, then walk the requested line to map its normalized column.
export const recastLocToOffset = (
input: string,
loc: {line: number; column: number},
): number => {
- let sourceOffset = 0;
- let line = 1;
+ let lineStarts = lineStartsBySource.get(input);
+ if (!lineStarts) {
+ lineStarts = [0];
+ for (const match of input.matchAll(/\r\n|[\r\n\u2028\u2029]/g)) {
+ lineStarts.push(match.index + match[0].length);
+ }
+ }
+
+ lineStartsBySource.delete(input);
+ lineStartsBySource.set(input, lineStarts);
+ if (lineStartsBySource.size > maximumCachedSources) {
+ lineStartsBySource.delete(lineStartsBySource.keys().next().value!);
+ }
+
+ let sourceOffset = lineStarts[loc.line - 1];
+ if (sourceOffset === undefined) {
+ return input.length;
+ }
+
+ let {line} = loc;
let column = 0;
let isLeadingWhitespace = true;
diff --git a/packages/codemods/src/split-sequences.ts b/packages/codemods/src/split-sequences.ts
index 8b5aaa7dc4..e5abdb23c6 100644
--- a/packages/codemods/src/split-sequences.ts
+++ b/packages/codemods/src/split-sequences.ts
@@ -2,7 +2,7 @@ import type {VideoConfigValues} from 'remotion';
import type {CodemodProject} from './codemod-project';
import type {DuplicateNodesResult} from './duplicate-nodes';
import {getNodeProps} from './get-node-props';
-import {getNodes} from './get-nodes';
+import {getNodes, type CodemodNode} from './get-nodes';
import {findProjectFile} from './internals';
import {
getNodeEditResult,
@@ -30,13 +30,22 @@ export const splitSequences = async <Project extends CodemodProject>({
}
const groups = new Map<string, typeof splits>();
+ const nodesByFile = new Map<string, Map<string, CodemodNode>>();
for (const split of splits) {
const filePath = findProjectFile({project, filePath: split.node.filePath});
if (split.sequenceKeys === undefined) {
- const target = getNodes({project, filePath}).find(
- (node) =>
- JSON.stringify(node.nodePath) === JSON.stringify(split.node.nodePath),
- );
+ let nodesByPath = nodesByFile.get(filePath);
+ if (!nodesByPath) {
+ nodesByPath = new Map(
+ getNodes({project, filePath}).map((node) => [
+ JSON.stringify(node.nodePath),
+ node,
+ ]),
+ );
+ nodesByFile.set(filePath, nodesByPath);
+ }
+
+ const target = nodesByPath.get(JSON.stringify(split.node.nodePath));
if (
!target?.componentIdentity ||
!/^dev\.remotion\.(remotion\.(Sequence|Video|OffthreadVideo|Audio|experimental_Video|experimental_Audio|Interactive\.[A-Za-z]+)|media\.(Video|Audio))$/.test(
diff --git a/packages/codemods/src/test/precompose-jsx-nodes.test.ts b/packages/codemods/src/test/precompose-jsx-nodes.test.ts
index 240357fdd5..75fef50547 100644
--- a/packages/codemods/src/test/precompose-jsx-nodes.test.ts
+++ b/packages/codemods/src/test/precompose-jsx-nodes.test.ts
@@ -233,14 +233,19 @@ export const Video = () => {
node.tagName === sequenceTag &&
getStaticPropValue(project, node, 'name') === 'Presenter',
)!;
- const result = precomposeJsxNodes({
+ const request = {
project,
nodes: [selected],
compositionFile,
compositionId: 'Main',
metadata,
existingCompositionIds: ['Main'],
+ };
+ expect(canPrecomposeJsxNodes(request)).toEqual({
+ canPrecompose: true,
+ reason: null,
});
+ const result = precomposeJsxNodes(request);
const after = applyCodemodChanges(project, result.changes);
expect(after.files[filePath]).toContain(
`<${sequenceTag} name="Presenter" durationInFrames={147} trimBefore={369} premountFor={fps} ${extraProps}>\n <Presenter />\n </${sequenceTag}>`,
diff --git a/packages/codemods/src/test/precompose-styleable-roots.test.ts b/packages/codemods/src/test/precompose-styleable-roots.test.ts
index 0c3dd07eb7..7d7635d447 100644
--- a/packages/codemods/src/test/precompose-styleable-roots.test.ts
+++ b/packages/codemods/src/test/precompose-styleable-roots.test.ts
@@ -34,14 +34,19 @@ const precomposeSource = (
) => {
const project = makeProject(source);
const nodes = getNodes({project, filePath}).filter(select);
- const result = precomposeJsxNodes({
+ const request = {
project,
nodes,
compositionFile,
compositionId: 'Main',
metadata,
existingCompositionIds: ['Main'],
+ };
+ expect(canPrecomposeJsxNodes(request)).toEqual({
+ canPrecompose: true,
+ reason: null,
});
+ const result = precomposeJsxNodes(request);
return {
project,
nodes,
diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.ts
index 68f15aaa32..16b1c51fce 100644
--- a/packages/codemods/src/test/public-editing.test.ts
+++ b/packages/codemods/src/test/public-editing.test.ts
@@ -471,9 +471,9 @@ test('add, duplicate, reorder, edit, animate, and delete effects', async () => {
const second = await addEffect({
project: afterFirst,
node: first.insertedEffect,
- importName: 'brightness',
- importPath: '@remotion/effects/brightness',
- props: {amount: 1},
+ importName: 'tint',
+ importPath: '@remotion/effects/tint',
+ props: {color: 'red', opacity: 1},
});
const afterSecond = applyCodemodChanges(afterFirst, second.changes);
const duplicate = await duplicateEffects({
@@ -493,15 +493,44 @@ test('add, duplicate, reorder, edit, animate, and delete effects', async () => {
const edited = await updateEffectProps({
project: afterReorder,
effect: reordered.updatedEffect,
- props: {amount: 2},
+ updates: [
+ {key: 'opacity', value: 0.5, defaultValue: 1},
+ {key: 'color', value: 'blue', defaultValue: 'black'},
+ {key: 'opacity', value: 0.75, defaultValue: 1},
+ ],
});
+ expect(
+ edited.results.map(({oldValueString, newValueString}) => ({
+ oldValueString,
+ newValueString,
+ })),
+ ).toEqual([
+ {oldValueString: '1', newValueString: '0.5'},
+ {oldValueString: "'red'", newValueString: '"blue"'},
+ {oldValueString: '0.5', newValueString: '0.75'},
+ ]);
+ for (const [index, result] of edited.results.entries()) {
+ const previousSource =
+ index === 0
+ ? afterReorder.files[filePath]
+ : edited.results[index - 1].output;
+ expect(result.logLine).toBe(
+ previousSource.slice(0, previousSource.indexOf('tint(')).split('\n')
+ .length,
+ );
+ }
+
+ expect(edited.results[0].output).toContain('opacity: 0.5');
+ expect(edited.results[1].output).toContain("color: 'blue'");
+ expect(edited.results[2].output).toContain('opacity: 0.75');
+ expect(edited.results[2].output).toBe(getChangedContents(edited, filePath));
const afterEdit = applyCodemodChanges(afterReorder, edited.changes);
const animated = await updateEffectKeyframes({
project: afterEdit,
effect: edited.updatedEffect,
updates: [
- {key: 'amount', operation: {type: 'add', frame: 0, value: 1}},
- {key: 'amount', operation: {type: 'add', frame: 30, value: 2}},
+ {key: 'opacity', operation: {type: 'add', frame: 0, value: 0}},
+ {key: 'opacity', operation: {type: 'add', frame: 30, value: 1}},
],
});
const afterAnimation = applyCodemodChanges(afterEdit, animated.changes);
@@ -509,12 +538,12 @@ test('add, duplicate, reorder, edit, animate, and delete effects', async () => {
project: afterAnimation,
node: animated.updatedEffect,
keys: [],
- effectKeys: [['amount'], ['radius'], ['radius'], ['amount']],
+ effectKeys: [['opacity'], ['radius'], ['radius'], ['opacity']],
}).effects;
expect(status[0]).toMatchObject({
canUpdate: true,
- callee: 'brightness',
- props: {amount: {status: 'keyframed'}},
+ callee: 'tint',
+ props: {opacity: {status: 'keyframed'}},
});
const deleted = await deleteEffects({
project: afterAnimation,
diff --git a/packages/codemods/src/update-effect-props.ts b/packages/codemods/src/update-effect-props.ts
index 47dae63cf0..76f47edc15 100644
--- a/packages/codemods/src/update-effect-props.ts
+++ b/packages/codemods/src/update-effect-props.ts
@@ -2,9 +2,8 @@ import type {InteractivitySchema} from 'remotion';
import type {CodemodProject} from './codemod-project';
import type {CodemodValue} from './codemod-value';
import {
- updateEffectProps as updateEffectPropsInSource,
+ batchUpdateEffectProps,
type EffectPropUpdate,
- type UpdateEffectPropsResult,
} from './effect-operations';
import {type EffectReference, getEffectSource} from './effect-references';
import {getNodeProps} from './get-node-props';
@@ -63,8 +62,6 @@ export const updateEffectProps = async <Project extends CodemodProject>({
throw new Error(`Cannot update effect: ${status?.reason ?? 'not-found'}`);
}
- let output = input;
- const results: UpdateEffectPropsResult[] = [];
for (const update of propUpdates) {
const {key} = update;
if (!/^[A-Za-z_$][\w$]*$/.test(key)) {
@@ -74,18 +71,17 @@ export const updateEffectProps = async <Project extends CodemodProject>({
if (!updates && status.props[key]?.status === 'computed') {
throw new Error(`Cannot update computed effect prop "${key}"`);
}
-
- const edit = await updateEffectPropsInSource({
- input: output,
- sequenceNodePath: effect.nodePath,
- effectIndex: effect.effectIndex,
- update,
- schema,
- });
- output = edit.output;
- results.push(edit);
}
+ const results = await batchUpdateEffectProps({
+ input,
+ sequenceNodePath: effect.nodePath,
+ effectIndex: effect.effectIndex,
+ updates: propUpdates,
+ schema,
+ });
+ const {output} = results[results.length - 1];
+
const result = getNodeEditResult({
project,
edits: [
diff --git a/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts b/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
index 4c114ad96f..18e446bec0 100644
--- a/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
+++ b/packages/studio/src/components/Timeline/use-resolved-stack-react-to-change.ts
@@ -50,9 +50,13 @@ export const useResolveStackAndReactToChange = (
resolvedLocationRef.current = resolvedLocation;
const getStackRef = useRef(getStack);
getStackRef.current = getStack;
+ const previousSequenceIdentity = useRef(sequenceIdentity);
useEffect(() => {
- const newStack = getStackRef.current();
+ const identityChanged =
+ previousSequenceIdentity.current !== sequenceIdentity;
+ previousSequenceIdentity.current = sequenceIdentity;
+ const newStack = getStack();
setStackState((current) => {
if (newStack === current.stack) {
return current;
@@ -60,12 +64,12 @@ export const useResolveStackAndReactToChange = (
return {
stack: newStack,
- // A different identity means a different selected sequence. Its existing
- // node path mapping is still preferred.
- preferMappedNodePath: true,
+ // Registration can publish its new stack after the refresh event.
+ // Only a different sequence should retain its existing node path.
+ preferMappedNodePath: identityChanged,
};
});
- }, [sequenceIdentity]);
+ }, [getStack, sequenceIdentity]);
useEffect(() => {
if (fastRefreshes === 0) {
diff --git a/packages/studio/src/test/source-subscription-churn.test.tsx b/packages/studio/src/test/source-subscription-churn.test.tsx
index 0eef9f9691..c38741513c 100644
--- a/packages/studio/src/test/source-subscription-churn.test.tsx
+++ b/packages/studio/src/test/source-subscription-churn.test.tsx
@@ -3,7 +3,7 @@ import {readFileSync} from 'node:fs';
import {CodemodsInternals} from '@remotion/codemods';
import type {SubscribeToSequencePropsBatchRequest} from '@remotion/studio-shared';
import {act, render, waitFor} from '@testing-library/react';
-import {useContext, type ContextType} from 'react';
+import {useContext, useState, type ContextType} from 'react';
import {
Internals,
Sequence,
@@ -19,6 +19,7 @@ import {StudioServerConnectionCtx} from '../helpers/client-id';
const fileName = __filename;
const source = readFileSync(fileName, 'utf8').split('\ntest(')[0];
+let sourceLineOffset = 0;
// Supply the source locations normally injected by the Studio bundler. The
// subscription parser reads the same JSX that React mounts below.
@@ -29,7 +30,8 @@ const sourceProps = (name: string) => {
[Internals.REMOTION_INTERNAL_STACK_PROP]: Internals.makeOriginalSourceStack(
{
fileName,
- lineNumber: source.slice(0, opening).split('\n').length,
+ lineNumber:
+ source.slice(0, opening).split('\n').length + sourceLineOffset,
columnNumber: 0,
},
),
@@ -83,6 +85,17 @@ test('parent previews keep source subscriptions stable while mounted instances e
const subscriptions: ReturnType<
typeof CodemodsInternals.computeSequencePropsSubscriptionFromContent
>[] = [];
+ let subscriptionSource = source;
+ let refreshFixture: () => void = () => {
+ throw new Error('Fixture has not mounted');
+ };
+
+ const RefreshableFixture = () => {
+ const [, setRevision] = useState(0);
+ refreshFixture = () => setRevision((revision) => revision + 1);
+ return <Fixture />;
+ };
+
const setters: {
current: ContextType<typeof Internals.VisualModeSettersContext> | null;
} = {current: null};
@@ -106,7 +119,7 @@ test('parent previews keep source subscriptions stable while mounted instances e
) as SubscribeToSequencePropsBatchRequest;
const results = body.requests.map((request) =>
CodemodsInternals.computeSequencePropsSubscriptionFromContent({
- fileContents: source,
+ fileContents: subscriptionSource,
absolutePath: fileName,
line: request.line,
preferredNodePath: request.nodePath,
@@ -208,7 +221,7 @@ test('parent previews keep source subscriptions stable while mounted instances e
subscribeToEvent: () => () => undefined,
}}
>
- <Fixture />
+ <RefreshableFixture />
<Subscriptions />
</StudioServerConnectionCtx.Provider>
</ExpandedTracksProvider>
@@ -298,12 +311,23 @@ test('parent previews keep source subscriptions stable while mounted instances e
Number(rendered.getByTestId('B').parentElement!.style.opacity),
).toBeCloseTo(30 / 398, 5);
expect(requests).toEqual(initialRequests);
+
+ // Registration can publish a shifted source stack without another refresh
+ // event. Updating that stack must still refresh source props.
+ sourceLineOffset = 2;
+ subscriptionSource = `\n\n${source}`;
+ act(() => refreshFixture());
+ await waitFor(() =>
+ expect(rendered!.getByTestId('A').textContent).toBe('180'),
+ );
+ expect(rendered.getByTestId('B').textContent).toBe('200');
} finally {
await act(async () => {
rendered?.unmount();
await Promise.resolve();
});
globalThis.fetch = previousFetch;
+ sourceLineOffset = 0;
}
// Verify that unsubscribe traffic is actually observed by the test.
@@ -311,5 +335,5 @@ test('parent previews keep source subscriptions stable while mounted instances e
requests.filter(
(endpoint) => endpoint === '/api/unsubscribe-from-sequence-props',
),
- ).toHaveLength(4);
+ ).toHaveLength(subscriptions.filter((result) => result.success).length);
});