Skip to content

🎥 Make videos programmatically with React

`@remotion/codemods`: Preserve cached reads and conditional registrations

Jonny Burger8ce12fd0d0fd
diff --git a/packages/codemods/src/get-jsx-node-props.ts b/packages/codemods/src/get-jsx-node-props.ts
index 66ccbec76c..e36d63925b 100644
--- a/packages/codemods/src/get-jsx-node-props.ts
+++ b/packages/codemods/src/get-jsx-node-props.ts
@@ -10,8 +10,8 @@ import {
computeSequencePropsStatusFromContent,
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 GetJsxNodePropsOptions = {
project: CodemodProject;
@@ -40,7 +40,7 @@ export const getJsxNodeProps = ({
const filePath = findProjectFile({project, filePath: node.filePath});
let effects = effectKeys;
if (effects === undefined) {
- const ast = parseAst(project.files[filePath]);
+ const {ast} = getReadOnlySourceSnapshot(project.files[filePath]);
const jsx = findJsxElementAtNodePath(ast, node.nodePath);
const attr = jsx ? findEffectsAttr(jsx.attributes) : null;
const array =
diff --git a/packages/codemods/src/get-jsx-nodes.ts b/packages/codemods/src/get-jsx-nodes.ts
index 144f0a3f13..6aacf47cc7 100644
--- a/packages/codemods/src/get-jsx-nodes.ts
+++ b/packages/codemods/src/get-jsx-nodes.ts
@@ -5,8 +5,8 @@ import {captureJsxNodePaths} from './get-node-path-remappings';
import {findProjectFile} from './internals';
import type {JsxNodeReference} from './node-references';
import {recastLocToOffset} from './recast-loc-to-offset';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {getJsxComponentIdentity} from './sequence-props/jsx-component-identity';
-import {parseAst} from './sequence-props/parse-ast';
export type JsxNode = JsxNodeReference & {
tagName: string;
@@ -25,7 +25,7 @@ export const getJsxNodes = ({
}: GetJsxNodesOptions): JsxNode[] => {
const resolvedFilePath = findProjectFile({project, filePath});
const input = project.files[resolvedFilePath];
- const ast = parseAst(input);
+ const {ast} = getReadOnlySourceSnapshot(input);
return captureJsxNodePaths(ast).map(({node, nodePath}) => {
const offset = node.loc ? recastLocToOffset(input, node.loc.start) : null;
return {
diff --git a/packages/codemods/src/get-node-path-remappings.ts b/packages/codemods/src/get-node-path-remappings.ts
index 11e585de19..3d11cf9235 100644
--- a/packages/codemods/src/get-node-path-remappings.ts
+++ b/packages/codemods/src/get-node-path-remappings.ts
@@ -3,7 +3,7 @@ import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {getNodePathForRecastPath} from './sequence-props';
-import {parseAst} from './sequence-props/parse-ast';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
export type CapturedJsxNodePath = {
node: JSXOpeningElement;
@@ -47,7 +47,7 @@ export const getNodePathRemappings = ({
},
});
- const finalAst = parseAst(output);
+ const {ast: finalAst} = getReadOnlySourceSnapshot(output);
const finalNodePaths: SequenceNodePath[] = [];
recast.visit(finalAst, {
visitJSXOpeningElement(path) {
diff --git a/packages/codemods/src/registration-source-edits.ts b/packages/codemods/src/registration-source-edits.ts
index e2263c33a7..e55e9b1838 100644
--- a/packages/codemods/src/registration-source-edits.ts
+++ b/packages/codemods/src/registration-source-edits.ts
@@ -214,9 +214,9 @@ export const getRegistrationInsertionSourceEdit = ({
return false;
},
});
- if (roots.length !== 1) {
+ if (roots.length === 0) {
throw new Error(
- 'Adding registrations requires a single JSX return in the registration component',
+ 'Adding registrations requires a JSX return in the registration component',
);
}
diff --git a/packages/codemods/src/sequence-props-snapshot.ts b/packages/codemods/src/sequence-props-snapshot.ts
new file mode 100644
index 0000000000..87b928f39d
--- /dev/null
+++ b/packages/codemods/src/sequence-props-snapshot.ts
@@ -0,0 +1,37 @@
+import type {File} from '@babel/types';
+import {parseAst} from './sequence-props/parse-ast';
+import type {VideoConfigIdentifierValues} from './sequence-props/video-config-values';
+
+type SourceSnapshot = {
+ ast: File;
+ videoConfigIdentifierValues: Map<string, VideoConfigIdentifierValues>;
+};
+
+// Public reads share immutable source snapshots, including across the awaits in
+// Studio's read/edit/write/status workflow. Content keys make external writes,
+// caption edits, keyframe edits, and retained project versions independent.
+const snapshots = new Map<string, SourceSnapshot>();
+const maximumSnapshots = 8;
+
+export const getReadOnlySourceSnapshot = (input: string): SourceSnapshot => {
+ const snapshot = snapshots.get(input) ?? {
+ ast: parseAst(input),
+ videoConfigIdentifierValues: new Map<string, VideoConfigIdentifierValues>(),
+ };
+ // Refresh recency without retaining an unbounded number of edited versions.
+ snapshots.delete(input);
+ snapshots.set(input, snapshot);
+ if (snapshots.size > maximumSnapshots) {
+ snapshots.delete(snapshots.keys().next().value!);
+ }
+
+ return snapshot;
+};
+
+// A mutating edit takes exclusive ownership. Never leave its AST available to a
+// read of the old source, even when the edit throws after partially mutating it.
+export const takeSourceSnapshotForEdit = (input: string): File => {
+ const snapshot = snapshots.get(input);
+ snapshots.delete(input);
+ return snapshot?.ast ?? parseAst(input);
+};
diff --git a/packages/codemods/src/sequence-props.ts b/packages/codemods/src/sequence-props.ts
index 024cdd461a..6a37accd1b 100644
--- a/packages/codemods/src/sequence-props.ts
+++ b/packages/codemods/src/sequence-props.ts
@@ -6,6 +6,7 @@ import type {
JSXElement,
JSXOpeningElement,
NewExpression,
+ Node,
ObjectExpression,
ObjectProperty,
TSAsExpression,
@@ -14,7 +15,6 @@ import type {
import type {SubscribeToSequencePropsResponse} from '@remotion/studio-shared';
import {LINEAR_KEYFRAME_EASING} from '@remotion/studio-shared/keyframe-easing-presets';
import {isKeyframeInterpolationFunction} from '@remotion/studio-shared/keyframe-interpolation-function';
-import type {NodePath} from 'ast-types';
import * as recast from 'recast';
import type {
CanUpdateSequencePropsResponseTrue,
@@ -28,6 +28,7 @@ import type {
VideoConfigValues,
} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
+import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {computeEffectPropStatus} from './sequence-props/can-update-effect-props';
import {getCssShorthandForLonghand} from './sequence-props/css-shorthand-properties';
import {getAstNodePath} from './sequence-props/get-ast-node-path';
@@ -38,7 +39,6 @@ import {
JsxElementIdentityMismatchError,
} from './sequence-props/jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
-import {parseAst} from './sequence-props/parse-ast';
import {parseBorderRadiusShorthand} from './sequence-props/parse-border-radius-shorthand';
import {parseKeyframeEasingExpression} from './sequence-props/parse-keyframe-easing-expression';
import {parseVideoConfigNumericExpression} from './sequence-props/video-config-numeric-expression';
@@ -514,45 +514,399 @@ const getInterpolationMetadata = (
};
};
-const isUseCurrentFrameCall = (node: Expression): boolean => {
+const getRemotionImportNames = ({
+ ast,
+ importedName,
+}: {
+ ast: File;
+ importedName: string;
+}): {direct: Set<string>; namespaces: Set<string>} => {
+ const direct = new Set<string>();
+ const namespaces = new Set<string>();
+ for (const statement of ast.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.value !== 'remotion'
+ ) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ ((specifier.imported.type === 'Identifier' &&
+ specifier.imported.name === importedName) ||
+ (specifier.imported.type === 'StringLiteral' &&
+ specifier.imported.value === importedName))
+ ) {
+ direct.add(specifier.local?.name ?? importedName);
+ }
+
+ if (specifier.type === 'ImportNamespaceSpecifier') {
+ namespaces.add(specifier.local.name);
+ }
+ }
+ }
+
+ return {direct, namespaces};
+};
+
+const isUseCurrentFrameCall = (node: Expression, ast: File): boolean => {
+ if (node.type !== 'CallExpression' || node.arguments.length !== 0) {
+ return false;
+ }
+
+ const imports = getRemotionImportNames({
+ ast,
+ importedName: 'useCurrentFrame',
+ });
+ if (node.callee.type === 'Identifier') {
+ return imports.direct.has(node.callee.name);
+ }
+
return (
- node.type === 'CallExpression' &&
- node.callee.type === 'Identifier' &&
- node.callee.name === 'useCurrentFrame' &&
- node.arguments.length === 0
+ node.callee.type === 'MemberExpression' &&
+ !node.callee.computed &&
+ node.callee.object.type === 'Identifier' &&
+ node.callee.property.type === 'Identifier' &&
+ imports.namespaces.has(node.callee.object.name) &&
+ node.callee.property.name === 'useCurrentFrame'
);
};
-const isCurrentFrameIdentifier = (node: Expression, ast: File): boolean => {
+const findNodePath = (
+ ast: File,
+ target: Node,
+): recast.types.NodePath | null => {
+ let found: recast.types.NodePath | null = null;
+ recast.types.visit(ast, {
+ visitNode(p) {
+ if (p.node === target) {
+ found = p as unknown as recast.types.NodePath;
+ return false;
+ }
+
+ return this.traverse(p);
+ },
+ });
+
+ return found;
+};
+
+const getJsxNumericAttribute = ({
+ openingElement,
+ name,
+ defaultValue,
+ videoConfigValues,
+}: {
+ openingElement: JSXOpeningElement;
+ name: string;
+ defaultValue: number;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): number | null => {
+ if (
+ openingElement.attributes.some(
+ (attribute) => attribute.type === 'JSXSpreadAttribute',
+ )
+ ) {
+ return null;
+ }
+
+ for (let index = openingElement.attributes.length - 1; index >= 0; index--) {
+ const attribute = openingElement.attributes[index];
+ if (
+ attribute.type !== 'JSXAttribute' ||
+ attribute.name.type !== 'JSXIdentifier' ||
+ attribute.name.name !== name
+ ) {
+ continue;
+ }
+
+ if (
+ attribute.value?.type !== 'JSXExpressionContainer' ||
+ attribute.value.expression.type === 'JSXEmptyExpression'
+ ) {
+ return null;
+ }
+
+ return (
+ parseVideoConfigNumericExpression({
+ node: attribute.value.expression,
+ videoConfigValues,
+ })?.value ?? null
+ );
+ }
+
+ return defaultValue;
+};
+
+const getFrameDisplayOffsetAdjustmentBetweenPaths = ({
+ startPath,
+ endPath,
+ videoConfigValues,
+}: {
+ startPath: recast.types.NodePath;
+ endPath: recast.types.NodePath;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): {
+ readonly adjustment: number;
+ readonly hasEnclosingElement: boolean;
+} | null => {
+ let current: recast.types.NodePath | null = startPath;
+ let hasSeenControlledElement = false;
+ let hasEnclosingElement = false;
+ let adjustment = 0;
+ while (current && current.value !== endPath.value) {
+ const currentNode = current.value as Node;
+ if (
+ currentNode.type === 'FunctionDeclaration' ||
+ currentNode.type === 'FunctionExpression' ||
+ currentNode.type === 'ArrowFunctionExpression'
+ ) {
+ return null;
+ }
+
+ if (currentNode.type === 'JSXElement') {
+ if (!hasSeenControlledElement) {
+ hasSeenControlledElement = true;
+ } else {
+ hasEnclosingElement = true;
+ // Sequence-backed built-ins and userland components can both shift
+ // their children, so the prop names are the semantic boundary.
+ const from = getJsxNumericAttribute({
+ openingElement: currentNode.openingElement,
+ name: 'from',
+ defaultValue: 0,
+ videoConfigValues,
+ });
+ const trimBefore = getJsxNumericAttribute({
+ openingElement: currentNode.openingElement,
+ name: 'trimBefore',
+ defaultValue: 0,
+ videoConfigValues,
+ });
+ if (from === null || trimBefore === null) {
+ return null;
+ }
+
+ adjustment -= from - trimBefore;
+ }
+ }
+
+ current = current.parentPath;
+ }
+
+ return current ? {adjustment, hasEnclosingElement} : null;
+};
+
+const getDefaultFrameDisplayOffsetAdjustment = ({
+ jsxPath,
+ videoConfigValues,
+}: {
+ jsxPath: recast.types.NodePath;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): number | null => {
+ let functionPath: recast.types.NodePath | null = jsxPath.parentPath;
+ while (functionPath) {
+ const node = functionPath.value as Node;
+ if (
+ node.type === 'FunctionDeclaration' ||
+ node.type === 'FunctionExpression' ||
+ node.type === 'ArrowFunctionExpression'
+ ) {
+ break;
+ }
+
+ functionPath = functionPath.parentPath;
+ }
+
+ if (!functionPath) {
+ // Module-level JSX still has editable static props. There is no local
+ // frame clock to adjust; keyframe insertion validates its own hook scope.
+ return 0;
+ }
+
+ const result = getFrameDisplayOffsetAdjustmentBetweenPaths({
+ startPath: jsxPath,
+ endPath: functionPath,
+ videoConfigValues,
+ });
+ return result?.adjustment ?? null;
+};
+
+type ResolvedCurrentFrameExpression = {
+ readonly bindingScopePath: recast.types.NodePath;
+ readonly offset: number;
+};
+
+const resolveCurrentFrameExpression = ({
+ node,
+ ast,
+ seenDeclarations,
+}: {
+ node: Expression;
+ ast: File;
+ seenDeclarations: Set<object>;
+}): ResolvedCurrentFrameExpression | null => {
if (node.type === 'TSAsExpression') {
- return isCurrentFrameIdentifier(node.expression as Expression, ast);
+ return resolveCurrentFrameExpression({
+ node: node.expression as Expression,
+ ast,
+ seenDeclarations,
+ });
+ }
+
+ if (
+ node.type === 'BinaryExpression' &&
+ (node.operator === '+' || node.operator === '-')
+ ) {
+ const rightValue = getNumericValue(node.right as Expression);
+ if (rightValue !== null && Number.isFinite(rightValue)) {
+ const resolvedLeft = resolveCurrentFrameExpression({
+ node: node.left as Expression,
+ ast,
+ seenDeclarations,
+ });
+ if (resolvedLeft !== null) {
+ return {
+ ...resolvedLeft,
+ offset:
+ resolvedLeft.offset +
+ (node.operator === '+' ? rightValue : -rightValue),
+ };
+ }
+ }
+
+ if (node.operator === '+') {
+ const leftValue = getNumericValue(node.left as Expression);
+ if (leftValue !== null && Number.isFinite(leftValue)) {
+ const resolvedRight = resolveCurrentFrameExpression({
+ node: node.right as Expression,
+ ast,
+ seenDeclarations,
+ });
+ if (resolvedRight !== null) {
+ return {
+ ...resolvedRight,
+ offset: resolvedRight.offset + leftValue,
+ };
+ }
+ }
+ }
+
+ return null;
}
if (node.type !== 'Identifier') {
- return false;
+ return null;
}
- let hasUseCurrentFrameDeclaration = false;
- let hasOtherDeclaration = false;
+ const nodePath = findNodePath(ast, node);
+ const bindingScope = nodePath?.scope?.lookup(node.name);
+ if (!nodePath || !bindingScope) {
+ return null;
+ }
- recast.types.visit(ast, {
+ let matchingDeclarations = 0;
+ let matchingDeclaration: object | null = null;
+ let initializer: Expression | null = null;
+ let isConstDeclaration = false;
+ recast.types.visit(bindingScope.path, {
visitVariableDeclarator(p) {
const {id, init} = p.node;
- if (id.type !== 'Identifier' || id.name !== node.name) {
+ if (
+ id.type !== 'Identifier' ||
+ id.name !== node.name ||
+ p.scope.lookup(node.name)?.path.node !== bindingScope.path.node
+ ) {
return this.traverse(p);
}
- if (init && isUseCurrentFrameCall(init as Expression)) {
- hasUseCurrentFrameDeclaration = true;
- } else {
- hasOtherDeclaration = true;
+ matchingDeclarations++;
+ const declaration = p.parentPath.node;
+ if (init) {
+ matchingDeclaration = p.node;
+ initializer = init as Expression;
+ isConstDeclaration =
+ declaration.type === 'VariableDeclaration' &&
+ declaration.kind === 'const';
}
return false;
},
});
- return hasUseCurrentFrameDeclaration && !hasOtherDeclaration;
+ if (
+ matchingDeclarations !== 1 ||
+ matchingDeclaration === null ||
+ initializer === null ||
+ seenDeclarations.has(matchingDeclaration)
+ ) {
+ return null;
+ }
+
+ if (isUseCurrentFrameCall(initializer, ast)) {
+ return {bindingScopePath: bindingScope.path, offset: 0};
+ }
+
+ if (!isConstDeclaration) {
+ return null;
+ }
+
+ const nextSeenDeclarations = new Set(seenDeclarations);
+ nextSeenDeclarations.add(matchingDeclaration);
+ return resolveCurrentFrameExpression({
+ node: initializer,
+ ast,
+ seenDeclarations: nextSeenDeclarations,
+ });
+};
+
+const getCurrentFrameDisplayOffsetAdjustment = ({
+ node,
+ ast,
+ videoConfigValues,
+}: {
+ node: Expression;
+ ast: File;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): {
+ readonly adjustment: number;
+ readonly hasEnclosingElement: boolean;
+} | null => {
+ if (node.type === 'TSAsExpression') {
+ return getCurrentFrameDisplayOffsetAdjustment({
+ node: node.expression as Expression,
+ ast,
+ videoConfigValues,
+ });
+ }
+
+ const nodePath = findNodePath(ast, node);
+ const resolved = resolveCurrentFrameExpression({
+ node,
+ ast,
+ seenDeclarations: new Set(),
+ });
+ if (!nodePath || resolved === null) {
+ return null;
+ }
+
+ const frameDisplayOffset = getFrameDisplayOffsetAdjustmentBetweenPaths({
+ startPath: nodePath,
+ endPath: resolved.bindingScopePath,
+ videoConfigValues,
+ });
+ if (frameDisplayOffset === null) {
+ return null;
+ }
+
+ return {
+ ...frameDisplayOffset,
+ // interpolate(frame + offset, [keyframe], ...) reaches the keyframe at
+ // composition frame `keyframe - offset`.
+ adjustment: frameDisplayOffset.adjustment - resolved.offset,
+ };
};
const getInterpolationKeyframes = (
@@ -567,6 +921,7 @@ const getInterpolationKeyframes = (
posterize: PropPosterize;
output: PropOutput;
interpolationFunction: PropInterpolationFunction;
+ keyframeDisplayOffsetAdjustment: number | null;
}
| undefined => {
if (node.type === 'TSAsExpression') {
@@ -624,7 +979,6 @@ const getInterpolationKeyframes = (
if (
!frameArg ||
frameArg.type === 'SpreadElement' ||
- !isCurrentFrameIdentifier(frameArg as Expression, ast) ||
!inputArg ||
!outputArg ||
inputArg.type !== 'ArrayExpression' ||
@@ -633,6 +987,15 @@ const getInterpolationKeyframes = (
return undefined;
}
+ const frameDisplayOffset = getCurrentFrameDisplayOffsetAdjustment({
+ node: frameArg as Expression,
+ ast,
+ videoConfigValues,
+ });
+ if (frameDisplayOffset === null) {
+ return undefined;
+ }
+
if (inputArg.elements.length !== outputArg.elements.length) {
return undefined;
}
@@ -685,6 +1048,9 @@ const getInterpolationKeyframes = (
clamping: metadata.clamping,
posterize: metadata.posterize,
output: metadata.output,
+ keyframeDisplayOffsetAdjustment: frameDisplayOffset.hasEnclosingElement
+ ? frameDisplayOffset.adjustment
+ : null,
};
};
@@ -700,8 +1066,9 @@ export const getComputedStatus = (
return {
status: 'keyframed',
- keyframeDisplayOffsetAdjustment: null,
interpolationFunction: interpolation.interpolationFunction,
+ keyframeDisplayOffsetAdjustment:
+ interpolation.keyframeDisplayOffsetAdjustment,
keyframes: interpolation.keyframes,
easing: interpolation.easing,
clamping: interpolation.clamping,
@@ -807,7 +1174,7 @@ export const getNodePathForRecastPath = (
export const findJsxElementPathAtNodePath = (
ast: File,
nodePath: SequenceNodePath,
-): NodePath | null => {
+) => {
const current = getAstNodePath(ast, nodePath);
if (!current) {
return null;
@@ -828,20 +1195,22 @@ export const findJsxElementAtNodePath = (
return current ? (current.value as unknown as JSXOpeningElement) : null;
};
+const getJsxElementNodeFromJsxPath = (
+ jsxPath: recast.types.NodePath,
+): JSXElement | null => {
+ if (recast.types.namedTypes.JSXElement.check(jsxPath.parentPath?.value)) {
+ return jsxPath.parentPath.value as unknown as JSXElement;
+ }
+
+ return null;
+};
+
export const findJsxElementNodeAtNodePath = (
ast: File,
nodePath: SequenceNodePath,
): JSXElement | null => {
const current = findJsxElementPathAtNodePath(ast, nodePath);
- if (!current) {
- return null;
- }
-
- if (recast.types.namedTypes.JSXElement.check(current.parentPath?.value)) {
- return current.parentPath.value as unknown as JSXElement;
- }
-
- return null;
+ return current ? getJsxElementNodeFromJsxPath(current) : null;
};
export type StaticJsxTextContent =
@@ -946,32 +1315,123 @@ export const findNodePathForJsxElement = (
return foundPath;
};
+const RECAST_TAB_WIDTH = 4;
+
+const sourceColumnToRecastColumn = ({
+ sourceLine,
+ column,
+}: {
+ sourceLine: string | undefined;
+ column: number;
+}) => {
+ if (sourceLine === undefined) {
+ return column;
+ }
+
+ let recastColumn = 0;
+ for (let index = 0; index < column; index++) {
+ if (sourceLine[index] === '\t') {
+ recastColumn += RECAST_TAB_WIDTH - (recastColumn % RECAST_TAB_WIDTH);
+ } else {
+ recastColumn++;
+ }
+ }
+
+ return recastColumn;
+};
+
export const lineColumnToNodePath = (
ast: File,
targetLine: number,
+ targetColumn?: number,
+ fileContents?: string,
): SequenceNodePath | null => {
- let foundPath: SequenceNodePath | null = null;
+ const lineMatches: SequenceNodePath[] = [];
+ const exactMatches: SequenceNodePath[] = [];
+ const recastTargetColumn =
+ targetColumn === undefined || fileContents === undefined
+ ? targetColumn
+ : sourceColumnToRecastColumn({
+ sourceLine: fileContents.split('\n')[targetLine - 1],
+ column: targetColumn,
+ });
recast.types.visit(ast, {
visitJSXOpeningElement(p) {
const {node} = p;
if (node.loc && node.loc.start.line === targetLine) {
- foundPath = getNodePathForRecastPath(p, ast);
- return false;
+ const nodePath = getNodePathForRecastPath(p, ast);
+ lineMatches.push(nodePath);
+ if (node.loc.start.column === recastTargetColumn) {
+ exactMatches.push(nodePath);
+ }
}
return this.traverse(p);
},
});
- return foundPath;
+ if (exactMatches.length === 1) {
+ return exactMatches[0];
+ }
+
+ 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],
+ );
};
const PIXEL_VALUE_REGEX = /^-?\d+(\.\d+)?px$/;
const isSupportedTranslateValue = (value: string): boolean => {
const parts = value.split(/\s+/);
- if (parts.length === 1 || parts.length === 2) {
+ if (parts.length >= 1 && parts.length <= 3) {
return parts.every((part) => PIXEL_VALUE_REGEX.test(part));
}
@@ -1354,7 +1814,7 @@ const computeSequenceOnlyPropsRecord = ({
const dotIndex = key.indexOf('.');
if (dotIndex !== -1) {
- filteredProps[key] = getNestedPropStatus({
+ const status = getNestedPropStatus({
jsxElement,
ast,
parentKey: key.slice(0, dotIndex),
@@ -1363,6 +1823,19 @@ const computeSequenceOnlyPropsRecord = ({
allowSpecialValues: assetKeys.includes(key),
lastSpreadIndex,
});
+ filteredProps[key] =
+ key === 'style.translate' &&
+ ((status.status === 'static' &&
+ typeof status.codeValue === 'string' &&
+ status.codeValue.includes('%')) ||
+ (status.status === 'keyframed' &&
+ status.keyframes.some(
+ (keyframe) =>
+ typeof keyframe.value === 'string' &&
+ keyframe.value.includes('%'),
+ )))
+ ? computedStatus()
+ : status;
} else if (key in allProps) {
filteredProps[key] = allProps[key];
} else if (lastSpreadIndex !== -1) {
@@ -1376,33 +1849,28 @@ 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 => {
- const ast = parseAst(fileContents);
- const videoConfigIdentifierValues = getVideoConfigIdentifierValues({
- ast,
- videoConfigValues,
- });
-
- const jsxElementNode = findJsxElementNodeAtNodePath(ast, nodePath);
+ const jsxPath = findJsxElementPathAtNodePath(ast, nodePath);
+ const jsxElementNode = jsxPath ? getJsxElementNodeFromJsxPath(jsxPath) : null;
const jsxElement = jsxElementNode?.openingElement ?? null;
- if (!jsxElement || !jsxElementNode) {
+ if (!jsxPath || !jsxElement || !jsxElementNode) {
throw new JsxElementNotFoundAtLocationError();
}
@@ -1429,14 +1897,109 @@ export const computeSequencePropsStatusFromContent = ({
effects,
videoConfigValues: videoConfigIdentifierValues,
});
+ const defaultKeyframeDisplayOffsetAdjustment =
+ getDefaultFrameDisplayOffsetAdjustment({
+ jsxPath,
+ videoConfigValues: videoConfigIdentifierValues,
+ });
+ const addDefaultKeyframeDisplayOffsetAdjustment = (
+ status: CanUpdateSequencePropStatus,
+ ): CanUpdateSequencePropStatus => {
+ if (status.status !== 'static') {
+ return status;
+ }
+
+ if (defaultKeyframeDisplayOffsetAdjustment === null) {
+ return computedStatus();
+ }
+
+ if (defaultKeyframeDisplayOffsetAdjustment === 0) {
+ return status;
+ }
+
+ return {
+ ...status,
+ keyframeDisplayOffsetAdjustment: defaultKeyframeDisplayOffsetAdjustment,
+ };
+ };
return {
canUpdate: true as const,
- props: filteredProps,
- effects: effectsStatuses,
+ props: Object.fromEntries(
+ Object.entries(filteredProps).map(([key, status]) => [
+ key,
+ addDefaultKeyframeDisplayOffsetAdjustment(status),
+ ]),
+ ),
+ effects: effectsStatuses.map((effectStatus) =>
+ effectStatus.canUpdate
+ ? {
+ ...effectStatus,
+ props: Object.fromEntries(
+ Object.entries(effectStatus.props).map(([key, status]) => [
+ key,
+ addDefaultKeyframeDisplayOffsetAdjustment(status),
+ ]),
+ ),
+ }
+ : effectStatus,
+ ),
};
};
+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 = getReadOnlySourceSnapshot(fileContents);
+ const {ast} = cachedAst;
+ const videoConfigCacheKey = JSON.stringify(videoConfigValues);
+ let videoConfigIdentifierValues =
+ cachedAst.videoConfigIdentifierValues.get(videoConfigCacheKey);
+ if (videoConfigIdentifierValues === undefined) {
+ videoConfigIdentifierValues = getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ });
+ }
+
+ // A source snapshot may outlive many composition metadata changes. Bound
+ // derived values as well, retaining the configurations most recently read.
+ cachedAst.videoConfigIdentifierValues.delete(videoConfigCacheKey);
+ cachedAst.videoConfigIdentifierValues.set(
+ videoConfigCacheKey,
+ videoConfigIdentifierValues,
+ );
+ if (cachedAst.videoConfigIdentifierValues.size > 8) {
+ cachedAst.videoConfigIdentifierValues.delete(
+ cachedAst.videoConfigIdentifierValues.keys().next().value!,
+ );
+ }
+
+ return computeSequencePropsStatusFromAstAndIdentifiers({
+ ast,
+ nodePath,
+ componentIdentity,
+ keys,
+ assetKeys,
+ effects,
+ videoConfigIdentifierValues,
+ });
+};
+
export const computeSequencePropsSubscriptionFromContent = ({
fileContents,
absolutePath,
@@ -1495,7 +2058,7 @@ export const computeSequencePropsSubscriptionFromContent = ({
}
try {
- const ast = parseAst(fileContents);
+ const {ast} = getReadOnlySourceSnapshot(fileContents);
const resolvedNodePath = lineColumnToNodePath(ast, line);
if (!resolvedNodePath) {
return {
diff --git a/packages/codemods/src/update-jsx-node-props.ts b/packages/codemods/src/update-jsx-node-props.ts
index 31afa77d4a..84f22eab37 100644
--- a/packages/codemods/src/update-jsx-node-props.ts
+++ b/packages/codemods/src/update-jsx-node-props.ts
@@ -13,7 +13,7 @@ import {
type JsxNodeReference,
type NodeSourceEdit,
} from './node-references';
-import {parseAst} from './sequence-props/parse-ast';
+import {takeSourceSnapshotForEdit} from './sequence-props-snapshot';
import {
updateMultipleSequenceProps,
type SequencePropUpdate,
@@ -67,56 +67,57 @@ export const updateMultipleJsxNodeProps = <Project extends CodemodProject>({
const results: SequencePropsNodeUpdateResult[] = [];
for (const [filePath, group] of groups) {
const input = project.files[filePath];
- const ast = parseAst(input);
+ const fileChanges = group.map(({change}) => {
+ const updates =
+ change.updates ??
+ Object.entries(change.props).map(([key, value]) => ({
+ key,
+ value,
+ defaultValue: null,
+ }));
+ if (updates.length === 0) {
+ throw new Error('Expected at least one prop to update');
+ }
+
+ const keys = updates.map(({key}) => key);
+ const status = change.updates
+ ? null
+ : getJsxNodeProps({
+ project,
+ node: change.node,
+ keys,
+ videoConfig: change.videoConfig,
+ });
+ for (const key of keys) {
+ if (
+ !key ||
+ key.split('.').some((part) => !part) ||
+ key.split('.').length > 2
+ ) {
+ throw new Error(
+ 'Prop keys must be names or one-level nested paths such as style.opacity',
+ );
+ }
+
+ if (status?.props[key]?.status === 'computed') {
+ throw new Error(`Cannot update computed prop "${key}"`);
+ }
+ }
+
+ return {
+ nodePath: change.node.nodePath,
+ updates,
+ schema: change.schema ?? {},
+ videoConfigValues: change.videoConfig ?? null,
+ };
+ });
+ const ast = takeSourceSnapshotForEdit(input);
const captured = captureJsxNodePaths(ast);
const edit = updateMultipleSequenceProps({
input,
ast,
prettierConfigOverride,
- changes: group.map(({change}) => {
- const updates =
- change.updates ??
- Object.entries(change.props).map(([key, value]) => ({
- key,
- value,
- defaultValue: null,
- }));
- if (updates.length === 0) {
- throw new Error('Expected at least one prop to update');
- }
-
- const keys = updates.map(({key}) => key);
- const status = change.updates
- ? null
- : getJsxNodeProps({
- project,
- node: change.node,
- keys,
- videoConfig: change.videoConfig,
- });
- for (const key of keys) {
- if (
- !key ||
- key.split('.').some((part) => !part) ||
- key.split('.').length > 2
- ) {
- throw new Error(
- 'Prop keys must be names or one-level nested paths such as style.opacity',
- );
- }
-
- if (status?.props[key]?.status === 'computed') {
- throw new Error(`Cannot update computed prop "${key}"`);
- }
- }
-
- return {
- nodePath: change.node.nodePath,
- updates,
- schema: change.schema ?? {},
- videoConfigValues: change.videoConfig ?? null,
- };
- }),
+ changes: fileChanges,
});
const {nodePathRemappings} = getNodePathRemappings({
ast: edit.ast,
diff --git a/packages/codemods/src/update-keyframes.ts b/packages/codemods/src/update-keyframes.ts
index c5467d2ebb..d8886b7645 100644
--- a/packages/codemods/src/update-keyframes.ts
+++ b/packages/codemods/src/update-keyframes.ts
@@ -145,6 +145,12 @@ const getKeyframeFunctionSourceEdits = ({
}) => {
const reprintBlockBodies = new Set<BlockStatement>();
const fnPath = findEnclosingFunctionPath(jsxPath);
+ if (needsFrameHook && !fnPath) {
+ throw new Error(
+ 'Cannot add keyframes outside a component function because useCurrentFrame() needs a function scope',
+ );
+ }
+
if (fnPath) {
const functionNode = fnPath.value as FunctionNode;
const snapshot = functionSnapshots.find(
diff --git a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
index 6474074a4d..28eba7208b 100644
--- a/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
+++ b/packages/docs/docs/codemods/add-canvas-capture-composition.mdx
@@ -6,7 +6,7 @@ crumb: '@remotion/codemods'
# addCanvasCaptureComposition()<AvailableFrom v="4.0.528" />
-Creates an interactive Canvas Capture component and registers it in the project. Both files are returned in one result.
+Creates an interactive Canvas Capture component and registers it in the project. Both files are returned in one result. Use [`addComposition()`](/docs/codemods/add-composition) when the component implementation already exists.
:::warning
@@ -53,11 +53,11 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project
### compositionFile
-The project file containing the registration component.
+The existing project file containing the registration component. The same [registration-root requirements and import support](/docs/codemods/add-composition#compositionfile) as [`addComposition()`](/docs/codemods/add-composition) apply.
### compositionId
-The new composition ID. Must contain only letters, numbers, or hyphens and be unused in the registration file.
+The new composition ID. Must contain only ASCII letters, numbers, CJK characters, or hyphens and be unused in the registration file.
### component
@@ -73,7 +73,7 @@ The named component export, beginning with an uppercase letter, `_`, or `$`.
#### importPath
-The module specifier to use in the registration file, such as `./Capture`.
+The module specifier to use in the registration file, such as `./Capture`. It must resolve to `component.filePath`; the path is not derived automatically.
### metadata
@@ -117,7 +117,11 @@ The updated project. Unchanged files and extra project fields are preserved.
### changes
-An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+Two `{filePath, previousContents, nextContents}` entries: the modified registration file and the created component file. The new component's `previousContents` is `null`. Save both changes to persist the operation; the video asset is not created or copied.
+
+## Errors
+
+Throws if the component file already exists, the registration target cannot be resolved, the capture has no usable cursor movements, or an option is invalid. Failed operations leave the input project unchanged.
## Compatibility
diff --git a/packages/docs/docs/codemods/add-composition.mdx b/packages/docs/docs/codemods/add-composition.mdx
index ca9ffb8964..3f56d1982b 100644
--- a/packages/docs/docs/codemods/add-composition.mdx
+++ b/packages/docs/docs/codemods/add-composition.mdx
@@ -30,7 +30,7 @@ const result = addComposition({
console.log(result);
```
-Adds the registration and required imports. The component implementation must already exist. Use a file containing one registration component.
+Adds the registration and required imports to `compositionFile` only. It does not create a component file: the component implementation must already exist. To generate and register a Canvas Capture component together, use [`addCanvasCaptureComposition()`](/docs/codemods/add-canvas-capture-composition).
## Options
@@ -42,9 +42,11 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project
The project file containing the composition registrations. Registration edits support [`<Composition>`](/docs/composition), [`<Still>`](/docs/still), and [`<Folder>`](/docs/folder) with static IDs or folder names. Aliased and namespace imports from `remotion` are supported.
+When `folder` is omitted, the file must have one component containing registrations, or a single JSX component if no registrations exist yet. The first JSX return in the selected component is used; returns in nested functions are ignored.
+
### compositionId
-The new composition ID. Must contain only letters, numbers, or hyphens and be unused in this file.
+The new composition ID. Must contain only ASCII letters, numbers, CJK characters, or hyphens and be unused in this file.
### component
@@ -52,7 +54,7 @@ The component to register.
#### importName
-The named component export.
+The named component export, beginning with an uppercase letter, `_`, or `$`.
#### importPath
@@ -92,7 +94,7 @@ The updated project. Unchanged files and extra project fields are preserved.
### changes
-An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.
+An array containing the registration file's `{filePath, previousContents, nextContents}` change. No component-file change is returned.
## Errors
diff --git a/packages/docs/docs/codemods/duplicate-composition.mdx b/packages/docs/docs/codemods/duplicate-composition.mdx
index ac7bcd3e18..595f6f6f22 100644
--- a/packages/docs/docs/codemods/duplicate-composition.mdx
+++ b/packages/docs/docs/codemods/duplicate-composition.mdx
@@ -50,7 +50,7 @@ The static ID of the composition to edit.
### newId
-The new ID, containing only letters, numbers, or hyphens. It must be unused in this file.
+The new ID, containing only ASCII letters, numbers, CJK characters, or hyphens. It must be unused in this file.
### metadata?
diff --git a/packages/docs/docs/codemods/get-jsx-node-props.mdx b/packages/docs/docs/codemods/get-jsx-node-props.mdx
index 461199573f..5cf97b5d51 100644
--- a/packages/docs/docs/codemods/get-jsx-node-props.mdx
+++ b/packages/docs/docs/codemods/get-jsx-node-props.mdx
@@ -47,11 +47,11 @@ The JSX props to inspect. Use `children` for static text or a one-level path suc
### effectKeys?
-An array of prop-name arrays indexed by effect position. By default, inline effect calls and their explicit configuration keys are discovered from source.
+An array of prop-name arrays indexed by effect position. By default, inline effect calls and their explicit configuration keys are discovered from source. Pass `[]` to skip effect inspection.
### assetKeys?
-Prop names for which [`staticFile()`](/docs/staticfile) calls and `new Date()` expressions should be read as serialized asset and date values. Defaults to `[]`; these expressions are otherwise treated as computed.
+Names from `keys` for which [`staticFile()`](/docs/staticfile) calls and `new Date()` expressions should be read as serialized asset and date values. Defaults to `[]`; these expressions are otherwise treated as computed.
### componentIdentity?
diff --git a/packages/docs/docs/codemods/index.mdx b/packages/docs/docs/codemods/index.mdx
index ead0d0c8c4..b013906f4f 100644
--- a/packages/docs/docs/codemods/index.mdx
+++ b/packages/docs/docs/codemods/index.mdx
@@ -131,9 +131,9 @@ JSX, effect, and keyframe mutations return these mappings in addition to the sha
## Supported edits
-Code must be valid JavaScript or TypeScript with supported JSX structures. Prop inspection distinguishes static values, recognized keyframes, and computed expressions. The package does not evaluate arbitrary JavaScript. Prop updates reject computed values; setting a recognized keyframed prop replaces it with a static value.
+Code must be valid JavaScript or TypeScript with supported JSX structures. Prop inspection distinguishes static values, recognized keyframes, and computed expressions. The package does not evaluate arbitrary JavaScript. The `props` form of prop updates rejects computed values; [structured `updates`](/docs/codemods/update-jsx-node-props#updates) permit explicit replacement. Setting a recognized keyframed prop to a static value replaces its animation.
-Registration edits use explicit composition files and static IDs. They support the original `Composition`, `Still`, and `Folder` import names. Component insertion and resolution support additional import patterns, as documented on their pages.
+Registration edits use explicit composition files and static IDs. They support `Composition`, `Still`, and `Folder` from `remotion`, including aliased and namespace imports. Component insertion and resolution support additional import patterns, as documented on their pages.
`CodemodValue` represents serializable strings, numbers, booleans, `null`, arrays, and objects. Strings are values, not executable expressions. [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props) also accepts `undefined` to remove a property.
diff --git a/packages/docs/docs/codemods/rename-composition.mdx b/packages/docs/docs/codemods/rename-composition.mdx
index 281db74ceb..5ac18ecba4 100644
--- a/packages/docs/docs/codemods/rename-composition.mdx
+++ b/packages/docs/docs/codemods/rename-composition.mdx
@@ -47,7 +47,7 @@ The static ID of the composition to edit.
### newId
-The new ID, containing only letters, numbers, or hyphens. It must be unused in this file.
+The new ID, containing only ASCII letters, numbers, CJK characters, or hyphens. It must be unused in this file.
## Return value
diff --git a/packages/docs/docs/codemods/update-effect-keyframes.mdx b/packages/docs/docs/codemods/update-effect-keyframes.mdx
index 4beaacba50..3a999c7b24 100644
--- a/packages/docs/docs/codemods/update-effect-keyframes.mdx
+++ b/packages/docs/docs/codemods/update-effect-keyframes.mdx
@@ -34,6 +34,8 @@ console.log(result);
The effect must be a call in an inline effects array with a supported configuration. Required interpolation imports and frame hooks are added. Frame coordinates belong to the interpolation expression's local frame clock.
+Creating an animation that needs a new [`useCurrentFrame()`](/docs/use-current-frame) hook requires an enclosing function. Existing supported interpolation expressions can be edited outside functions. Static effect prop edits outside functions remain supported by [`updateEffectProps()`](/docs/codemods/update-effect-props).
+
## Options
### project
diff --git a/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx b/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx
index 6889e58bb6..6f4430c507 100644
--- a/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx
+++ b/packages/docs/docs/codemods/update-jsx-node-keyframes.mdx
@@ -34,6 +34,8 @@ console.log(result);
Adds the required interpolation imports and frame hook. Supports recognized inline interpolation expressions; unsupported dynamic expressions throw. Frame coordinates belong to the interpolation expression's local frame clock.
+Creating an animation that needs a new [`useCurrentFrame()`](/docs/use-current-frame) hook requires an enclosing function. Existing supported interpolation expressions can be edited outside functions. Static prop edits outside functions remain supported by [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props).
+
## Options
### project
diff --git a/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx
index 52c712df77..2b99187185 100644
--- a/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx
+++ b/packages/docs/docs/codemods/update-multiple-jsx-node-props.mdx
@@ -46,13 +46,13 @@ A non-empty array of node edits.
The [`JsxNodeReference`](/docs/codemods#node-references) to edit, containing `filePath` and `nodePath`.
-#### props
+#### props?
-A record of prop values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes a prop. Supply either `props` or `updates` for each edit.
+A non-empty record of prop values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes a prop. Only one level of nested keys is supported. Computed props, including values potentially overridden by a spread, are rejected. Supply exactly one of `props` or `updates` for each edit.
-#### updates
+#### updates?
-Structured [`SequencePropUpdate`](/docs/codemods/update-jsx-node-props#updates) entries for edits that need default values, enum handling, or other update metadata. Supply this instead of `props`.
+A non-empty array of [structured prop updates](/docs/codemods/update-jsx-node-props#updates) for edits that need default values or other update metadata. This form permits explicitly replacing computed prop values. Supply this instead of `props`.
#### schema?
diff --git a/packages/docs/docs/codemods/update-visual-controls.mdx b/packages/docs/docs/codemods/update-visual-controls.mdx
index 100c9c1c66..90b2c0efc6 100644
--- a/packages/docs/docs/codemods/update-visual-controls.mdx
+++ b/packages/docs/docs/codemods/update-visual-controls.mdx
@@ -43,7 +43,7 @@ An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project
### filePath
-The project source file containing the `visualControl()` calls.
+The project source file containing the `visualControl()` calls. Calls must use this name directly; aliased imports and namespace calls are not matched.
### changes
@@ -77,7 +77,11 @@ An array of `{filePath, previousContents, nextContents}` file changes. A `null`
### updatedControls
-An array of `{id, line}` entries for the requested changes that matched a call. `line` is the call's one-based source line. A matched call can be reported even if its value was already equal to the requested value.
+An array of `{id, line}` entries for the requested changes that matched a call. `line` is the call's one-based source line. Multiple matching calls produce separate entries. A matched call can be reported even if its value was already equal to the requested value.
+
+## Errors
+
+Throws if a `visualControl()` call has a dynamic identifier, a matched change contains invalid serialized JSON, or the source cannot be parsed. Failed operations leave the input project unchanged.
## Compatibility
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 4824e274c9..85dc305de0 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
@@ -13,6 +13,11 @@ import type {
TSAsExpression,
UnaryExpression,
} from '@babel/types';
+import {
+ CodemodsInternals,
+ getJsxNodeProps,
+ getJsxNodes,
+} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {SubscribeToSequencePropsResponse} from '@remotion/studio-shared';
import {
@@ -29,32 +34,20 @@ import type {
JsxComponentIdentity,
LogLevel,
SequenceNodePath,
- VideoConfigNumericExpression,
VideoConfigValues,
} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
-import {parseAst} from '../../codemods/parse-ast';
-import {getCssShorthandForLonghand} from '../../helpers/css-shorthand-properties';
import {getAstNodePath} from '../../helpers/get-ast-node-path';
import {toImportAgnosticNodePath} from '../../helpers/import-agnostic-node-path';
-import {parseBorderRadiusShorthand} from '../../helpers/parse-border-radius-shorthand';
import {parseKeyframeEasingExpression} from '../../helpers/parse-keyframe-easing-expression';
import {
FileOutsideProjectError,
resolveFileInsideProject,
} from '../../helpers/resolve-file-inside-project';
import {parseVideoConfigNumericExpression} from '../../helpers/video-config-numeric-expression';
-import {
- getVideoConfigIdentifierValues,
- type VideoConfigIdentifierValues,
-} from '../../helpers/video-config-values';
-import {
- getJsxComponentIdentity,
- jsxComponentIdentitiesMatch,
- JsxElementIdentityMismatchError,
-} from '../jsx-component-identity';
+import {type VideoConfigIdentifierValues} from '../../helpers/video-config-values';
+import {JsxElementIdentityMismatchError} from '../jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from '../jsx-element-not-found-at-location-error';
-import {computeEffectPropStatus} from './can-update-effect-props';
type CanUpdatePropStatus = CanUpdateSequencePropStatus;
type KeyframedPropStatus = Extract<CanUpdatePropStatus, {status: 'keyframed'}>;
@@ -65,48 +58,6 @@ type PropPosterize = KeyframedPropStatus['posterize'];
type PropOutput = KeyframedPropStatus['output'];
type PropInterpolationFunction = KeyframedPropStatus['interpolationFunction'];
-// A file write synchronously notifies every sequence subscription. Status
-// computation is read-only, so all subscribers can share one parsed snapshot
-// until the notification burst has finished.
-let cachedSequencePropsStatusAst: {
- fileContents: string;
- ast: File;
- videoConfigIdentifierValues: Map<string, VideoConfigIdentifierValues>;
-} | null = null;
-
-const getCachedSequencePropsStatusAst = (fileContents: string) => {
- if (cachedSequencePropsStatusAst?.fileContents !== fileContents) {
- const snapshot = {
- fileContents,
- ast: parseAst(fileContents),
- videoConfigIdentifierValues: new Map<
- string,
- VideoConfigIdentifierValues
- >(),
- };
- cachedSequencePropsStatusAst = snapshot;
- queueMicrotask(() => {
- if (cachedSequencePropsStatusAst === snapshot) {
- cachedSequencePropsStatusAst = null;
- }
- });
- }
-
- return cachedSequencePropsStatusAst;
-};
-
-const staticStatus = (
- codeValue: unknown,
- numericExpression: VideoConfigNumericExpression | null,
-): CanUpdatePropStatus => ({
- status: 'static',
- keyframeDisplayOffsetAdjustment: null,
- codeValue,
- ...(numericExpression === null || numericExpression.type === 'literal'
- ? {}
- : {numericExpression}),
-});
-
const computedStatus = (): CanUpdatePropStatus => ({
status: 'computed',
});
@@ -883,39 +834,6 @@ const getFrameDisplayOffsetAdjustmentBetweenPaths = ({
return current ? {adjustment, hasEnclosingElement} : null;
};
-const getDefaultFrameDisplayOffsetAdjustment = ({
- jsxPath,
- videoConfigValues,
-}: {
- jsxPath: recast.types.NodePath;
- videoConfigValues: VideoConfigIdentifierValues;
-}): number | null => {
- let functionPath: recast.types.NodePath | null = jsxPath.parentPath;
- while (functionPath) {
- const node = functionPath.value as Node;
- if (
- node.type === 'FunctionDeclaration' ||
- node.type === 'FunctionExpression' ||
- node.type === 'ArrowFunctionExpression'
- ) {
- break;
- }
-
- functionPath = functionPath.parentPath;
- }
-
- if (!functionPath) {
- return null;
- }
-
- const result = getFrameDisplayOffsetAdjustmentBetweenPaths({
- startPath: jsxPath,
- endPath: functionPath,
- videoConfigValues,
- });
- return result?.adjustment ?? null;
-};
-
type ResolvedCurrentFrameExpression = {
readonly bindingScopePath: recast.types.NodePath;
readonly offset: number;
@@ -1114,79 +1032,6 @@ export const getComputedStatus = (
};
};
-const getPropsStatus = (
- jsxElement: JSXOpeningElement,
- ast: File,
- videoConfigValues: VideoConfigIdentifierValues,
- assetKeys: string[],
-): Record<string, CanUpdatePropStatus> => {
- const props: Record<string, CanUpdatePropStatus> = {};
-
- for (const attr of jsxElement.attributes) {
- if (attr.type === 'JSXSpreadAttribute') {
- // The spread may override every prop written before it
- for (const key of Object.keys(props)) {
- props[key] = computedStatus();
- }
-
- continue;
- }
-
- if (attr.name.type === 'JSXNamespacedName') {
- continue;
- }
-
- const {name} = attr.name;
- if (typeof name !== 'string') {
- continue;
- }
-
- const {value} = attr as JSXAttribute;
-
- if (!value) {
- props[name] = staticStatus(true, null);
- continue;
- }
-
- if (value.type === 'StringLiteral') {
- props[name] = staticStatus((value as {value: string}).value, null);
- continue;
- }
-
- if (value.type === 'JSXExpressionContainer') {
- const {expression} = value;
- const staticValueOptions = {
- allowSpecialValues: assetKeys.includes(name),
- };
- if (expression.type === 'JSXEmptyExpression') {
- props[name] = computedStatus();
- continue;
- }
-
- if (!isStaticValue(expression, staticValueOptions)) {
- const numericExpression = parseVideoConfigNumericExpression({
- node: expression,
- videoConfigValues,
- });
- props[name] = numericExpression
- ? staticStatus(numericExpression.value, numericExpression)
- : getComputedStatus(expression, ast, videoConfigValues);
- continue;
- }
-
- props[name] = staticStatus(
- extractStaticValue(expression, staticValueOptions),
- null,
- );
- continue;
- }
-
- props[name] = computedStatus();
- }
-
- return props;
-};
-
export const getNodePathForRecastPath = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
recastPath: any,
@@ -1479,528 +1324,20 @@ export const resolveSequencePropsNodePathsFromFilename = ({
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 => {
- const parts = value.split(/\s+/);
- if (parts.length >= 1 && parts.length <= 3) {
- return parts.every((part) => PIXEL_VALUE_REGEX.test(part));
- }
-
- return false;
-};
-
-const validateStyleValue = (childKey: string, value: unknown): boolean => {
- if (childKey === 'translate' && typeof value === 'string') {
- return isSupportedTranslateValue(value);
- }
-
- return true;
-};
-
-const getObjectPropertyName = (property: ObjectProperty): string | null => {
- if (property.key.type === 'Identifier') {
- return property.key.name;
- }
-
- if (property.key.type === 'StringLiteral') {
- return property.key.value;
- }
-
- return null;
-};
-
-const BORDER_RADIUS_SHORTHAND = 'borderRadius';
-const BORDER_RADIUS_LONGHANDS = [
- 'borderTopLeftRadius',
- 'borderTopRightRadius',
- 'borderBottomRightRadius',
- 'borderBottomLeftRadius',
-] as const;
-const BORDER_RADIUS_PROPERTIES = new Set<string>([
- BORDER_RADIUS_SHORTHAND,
- ...BORDER_RADIUS_LONGHANDS,
-]);
-
-const hasMixedBorderRadiusRepresentation = (
- jsxElement: JSXOpeningElement,
-): boolean => {
- const style = jsxElement.attributes.find(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type !== 'JSXNamespacedName' &&
- attribute.name.name === 'style',
- );
- if (
- !style ||
- style.type !== 'JSXAttribute' ||
- style.value?.type !== 'JSXExpressionContainer' ||
- style.value.expression.type !== 'ObjectExpression'
- ) {
- return false;
- }
-
- let hasShorthand = false;
- let hasLonghand = false;
- for (const property of style.value.expression.properties) {
- if (property.type !== 'ObjectProperty') {
- continue;
- }
-
- const name = getObjectPropertyName(property);
- hasShorthand ||= name === BORDER_RADIUS_SHORTHAND;
- hasLonghand ||= BORDER_RADIUS_LONGHANDS.some(
- (longhand) => longhand === name,
- );
- }
-
- return hasShorthand && hasLonghand;
-};
-
-const getUniformBorderRadius = (value: unknown): number | null => {
- const parsed = parseBorderRadiusShorthand(value);
- if (!parsed) {
- return null;
- }
-
- const values = Object.values(parsed);
- return values.every((radius) => radius === values[0]) ? values[0] : null;
-};
-
-const getBorderRadiusShorthandStatus = ({
- propValue,
- ast,
- videoConfigValues,
-}: {
- propValue: Expression;
- ast: File;
- videoConfigValues: VideoConfigIdentifierValues;
-}): CanUpdatePropStatus => {
- if (isStaticValue(propValue)) {
- const uniform = getUniformBorderRadius(extractStaticValue(propValue));
- return uniform === null ? computedStatus() : staticStatus(uniform, null);
- }
-
- const numericExpression = parseVideoConfigNumericExpression({
- node: propValue,
- videoConfigValues,
- });
- if (numericExpression !== null && numericExpression.value >= 0) {
- return staticStatus(numericExpression.value, numericExpression);
- }
-
- const computed = getComputedStatus(propValue, ast, videoConfigValues);
- if (
- computed.status === 'keyframed' &&
- computed.interpolationFunction === 'interpolate' &&
- computed.keyframes.every(
- (keyframe) =>
- typeof keyframe.value === 'number' &&
- Number.isFinite(keyframe.value) &&
- keyframe.value >= 0,
- )
- ) {
- return computed;
- }
-
- return computedStatus();
-};
-
-const getNestedPropStatus = ({
- jsxElement,
- ast,
- parentKey,
- childKey,
- videoConfigValues,
- allowSpecialValues,
- lastSpreadIndex,
-}: {
- jsxElement: JSXOpeningElement;
- ast: File;
- parentKey: string;
- childKey: string;
- videoConfigValues: VideoConfigIdentifierValues;
- allowSpecialValues: boolean;
- lastSpreadIndex: number;
-}): CanUpdatePropStatus => {
- const attrIndex = jsxElement.attributes.findIndex(
- (a) =>
- a.type !== 'JSXSpreadAttribute' &&
- a.name.type !== 'JSXNamespacedName' &&
- a.name.name === parentKey,
- );
- const attr =
- attrIndex === -1
- ? undefined
- : (jsxElement.attributes[attrIndex] as JSXAttribute);
-
- if (attrIndex !== -1 && attrIndex < lastSpreadIndex) {
- // A later spread may replace the whole parent object
- return computedStatus();
- }
-
- if (!attr) {
- if (lastSpreadIndex !== -1) {
- // The spread may provide the parent object
- return computedStatus();
- }
-
- // Parent attribute doesn't exist, nested prop can be added
- return staticStatus(undefined, null);
- }
-
- if (!attr.value) {
- return staticStatus(undefined, null);
- }
-
- if (attr.value.type !== 'JSXExpressionContainer') {
- return computedStatus();
- }
-
- const {expression} = attr.value;
- if (
- expression.type === 'JSXEmptyExpression' ||
- expression.type !== 'ObjectExpression'
- ) {
- // Parent is not an object literal (e.g. style={myStyles})
- return computedStatus();
- }
-
- const objExpr = expression as ObjectExpression;
- const cssShorthand = getCssShorthandForLonghand({
- parentKey,
- longhand: childKey,
- });
- if (
- cssShorthand &&
- objExpr.properties.some((property) => {
- if (property.type !== 'ObjectProperty') {
- return false;
- }
-
- const propertyName = getObjectPropertyName(property);
- return (
- propertyName !== null &&
- cssShorthand.isUnsupportedProperty(propertyName)
- );
- })
- ) {
- return computedStatus();
- }
-
- let prop: ObjectProperty | undefined;
- for (let index = objExpr.properties.length - 1; index >= 0; index--) {
- const candidate = objExpr.properties[index];
- if (candidate.type === 'SpreadElement') {
- return computedStatus();
- }
-
- if (
- candidate.type === 'ObjectProperty' &&
- (getObjectPropertyName(candidate) === childKey ||
- getObjectPropertyName(candidate) === cssShorthand?.shorthand)
- ) {
- prop = candidate;
- break;
- }
- }
-
- if (
- prop &&
- cssShorthand &&
- getObjectPropertyName(prop) === cssShorthand.shorthand
- ) {
- const shorthandValue = prop.value as Expression;
- if (!isStaticValue(shorthandValue, {allowSpecialValues: false})) {
- return computedStatus();
- }
-
- const staticShorthandValue = extractStaticValue(shorthandValue, {
- allowSpecialValues: false,
- });
- const parsed = cssShorthand.parse(staticShorthandValue);
- return parsed ? staticStatus(parsed[childKey], null) : computedStatus();
- }
-
- if (!prop) {
- // Property not set in the object, can be added
- return staticStatus(undefined, null);
- }
-
- const propValue = prop.value as Expression;
- if (parentKey === 'style' && childKey === BORDER_RADIUS_SHORTHAND) {
- return getBorderRadiusShorthandStatus({
- propValue,
- ast,
- videoConfigValues,
- });
- }
-
- const staticValueOptions = {allowSpecialValues};
- if (!isStaticValue(propValue, staticValueOptions)) {
- const numericExpression = parseVideoConfigNumericExpression({
- node: propValue,
- videoConfigValues,
- });
- return numericExpression
- ? staticStatus(numericExpression.value, numericExpression)
- : getComputedStatus(propValue, ast, videoConfigValues);
- }
-
- const propStatus = extractStaticValue(propValue, staticValueOptions);
- if (!validateStyleValue(childKey, propStatus)) {
- return computedStatus();
- }
-
- return staticStatus(propStatus, null);
-};
-
-const computeEffectsForJsx = ({
- ast,
- jsxElement,
- effects,
- videoConfigValues,
-}: {
- ast: File;
- jsxElement: JSXOpeningElement;
- effects: string[][];
- videoConfigValues: VideoConfigIdentifierValues;
-}) => {
- return effects.map((effect, effectIndex) =>
- computeEffectPropStatus({
- ast,
- jsx: jsxElement,
- effectIndex,
- keys: effect,
- videoConfigValues,
- }),
- );
-};
-
-const computeSequenceOnlyPropsRecord = ({
- jsxElement,
- jsxElementNode,
- ast,
- keys,
- assetKeys,
- videoConfigValues,
-}: {
- jsxElement: JSXOpeningElement;
- jsxElementNode: JSXElement;
- ast: File;
- keys: string[];
- assetKeys: string[];
- videoConfigValues: VideoConfigIdentifierValues;
-}): Record<string, CanUpdatePropStatus> => {
- // A JSX spread attribute ({...props}) is invisible to the parser and may
- // set or override every prop that is not explicitly written after it.
- // Affected props are treated as computed so the runtime values pass
- // through untouched and Visual Mode does not offer to edit them.
- // Attributes written after the last spread win at runtime and can be
- // parsed as usual.
- const lastSpreadIndex = jsxElement.attributes.reduce(
- (highest, attr, index) =>
- attr.type === 'JSXSpreadAttribute' ? index : highest,
- -1,
- );
- const allProps = getPropsStatus(
- jsxElement,
- ast,
- videoConfigValues,
- assetKeys,
- );
- const filteredProps: Record<string, CanUpdatePropStatus> = {};
- const mixedBorderRadius = hasMixedBorderRadiusRepresentation(jsxElement);
- for (const key of keys) {
- if (
- mixedBorderRadius &&
- key.startsWith('style.') &&
- BORDER_RADIUS_PROPERTIES.has(key.slice('style.'.length))
- ) {
- filteredProps[key] = computedStatus();
- continue;
- }
-
- if (key === 'children') {
- const childrenAttrIndex = jsxElement.attributes.findIndex(
- (attr) =>
- attr.type === 'JSXAttribute' &&
- attr.name.type === 'JSXIdentifier' &&
- attr.name.name === 'children',
- );
- if (childrenAttrIndex !== -1 && childrenAttrIndex < lastSpreadIndex) {
- // A later spread may override the children attribute
- filteredProps[key] = computedStatus();
- continue;
- }
-
- const staticChildrenAttribute = getStaticJsxChildrenAttribute(jsxElement);
- if (staticChildrenAttribute) {
- filteredProps[key] = staticStatus(staticChildrenAttribute.value, null);
- continue;
- }
-
- if (hasJsxChildrenAttribute(jsxElement)) {
- filteredProps[key] = computedStatus();
- continue;
- }
-
- // JSX element children are compiled after any spread and win over
- // it. Only if the element body is empty may the spread provide the
- // children.
- const hasMeaningfulJsxChildren = jsxElementNode.children.some(
- (candidate) =>
- !(candidate.type === 'JSXText' && candidate.value.trim() === ''),
- );
- if (!hasMeaningfulJsxChildren && lastSpreadIndex !== -1) {
- filteredProps[key] = computedStatus();
- continue;
- }
-
- const staticTextContent = getStaticJsxTextContent(jsxElementNode);
- filteredProps[key] = staticTextContent
- ? staticStatus(staticTextContent.value, null)
- : computedStatus();
- continue;
- }
-
- const dotIndex = key.indexOf('.');
- if (dotIndex !== -1) {
- const status = getNestedPropStatus({
- jsxElement,
- ast,
- parentKey: key.slice(0, dotIndex),
- childKey: key.slice(dotIndex + 1),
- videoConfigValues,
- allowSpecialValues: assetKeys.includes(key),
- lastSpreadIndex,
- });
- filteredProps[key] =
- key === 'style.translate' &&
- ((status.status === 'static' &&
- typeof status.codeValue === 'string' &&
- status.codeValue.includes('%')) ||
- (status.status === 'keyframed' &&
- status.keyframes.some(
- (keyframe) =>
- typeof keyframe.value === 'string' &&
- keyframe.value.includes('%'),
- )))
- ? computedStatus()
- : status;
- } else if (key in allProps) {
- filteredProps[key] = allProps[key];
- } else if (lastSpreadIndex !== -1) {
- // The spread may provide this prop
- filteredProps[key] = computedStatus();
- } else {
- filteredProps[key] = staticStatus(undefined, null);
- }
- }
-
- return filteredProps;
-};
-
-const computeSequencePropsStatusFromAstAndIdentifiers = ({
- ast,
- nodePath,
- componentIdentity,
- keys,
- assetKeys,
- effects,
- videoConfigIdentifierValues,
-}: {
- ast: File;
- nodePath: SequenceNodePath;
- componentIdentity: JsxComponentIdentity | null;
- keys: string[];
- assetKeys: string[];
- effects: string[][];
- videoConfigIdentifierValues: VideoConfigIdentifierValues;
-}): CanUpdateSequencePropsResponseTrue => {
- const jsxPath = findJsxElementPathAtNodePath(ast, nodePath);
- const jsxElementNode = jsxPath ? getJsxElementNodeFromJsxPath(jsxPath) : null;
- const jsxElement = jsxElementNode?.openingElement ?? null;
-
- if (!jsxPath || !jsxElement || !jsxElementNode) {
- throw new JsxElementNotFoundAtLocationError();
- }
-
- if (
- !jsxComponentIdentitiesMatch({
- expected: componentIdentity,
- actual: getJsxComponentIdentity({ast, jsxElement}),
- })
- ) {
- throw new JsxElementIdentityMismatchError();
- }
-
- const filteredProps = computeSequenceOnlyPropsRecord({
- jsxElement,
- jsxElementNode,
- ast,
- keys,
- assetKeys,
- videoConfigValues: videoConfigIdentifierValues,
+ const nodes = getJsxNodes({
+ project: {rootDir: remotionRoot, files: {[absolutePath]: fileContents}},
+ filePath: absolutePath,
});
- const effectsStatuses = computeEffectsForJsx({
- ast,
- jsxElement,
- effects,
- videoConfigValues: videoConfigIdentifierValues,
+ return targets.map(({line, column}) => {
+ const lineMatches = nodes.filter((node) => node.location?.line === line);
+ const exactMatches = lineMatches.filter(
+ (node) => node.location?.column === column,
+ );
+ return (
+ (exactMatches.length === 1 ? exactMatches[0] : lineMatches.at(-1))
+ ?.nodePath ?? null
+ );
});
- const defaultKeyframeDisplayOffsetAdjustment =
- getDefaultFrameDisplayOffsetAdjustment({
- jsxPath,
- videoConfigValues: videoConfigIdentifierValues,
- });
- const addDefaultKeyframeDisplayOffsetAdjustment = (
- status: CanUpdateSequencePropStatus,
- ): CanUpdateSequencePropStatus => {
- if (status.status !== 'static') {
- return status;
- }
-
- if (defaultKeyframeDisplayOffsetAdjustment === null) {
- return computedStatus();
- }
-
- if (defaultKeyframeDisplayOffsetAdjustment === 0) {
- return status;
- }
-
- return {
- ...status,
- keyframeDisplayOffsetAdjustment: defaultKeyframeDisplayOffsetAdjustment,
- };
- };
-
- return {
- canUpdate: true as const,
- props: Object.fromEntries(
- Object.entries(filteredProps).map(([key, status]) => [
- key,
- addDefaultKeyframeDisplayOffsetAdjustment(status),
- ]),
- ),
- effects: effectsStatuses.map((effectStatus) =>
- effectStatus.canUpdate
- ? {
- ...effectStatus,
- props: Object.fromEntries(
- Object.entries(effectStatus.props).map(([key, status]) => [
- key,
- addDefaultKeyframeDisplayOffsetAdjustment(status),
- ]),
- ),
- }
- : effectStatus,
- ),
- };
};
export const computeSequencePropsStatusFromContent = ({
@@ -2020,31 +1357,27 @@ export const computeSequencePropsStatusFromContent = ({
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,
+ try {
+ return getJsxNodeProps({
+ project: {rootDir: '/', files: {'source.tsx': fileContents}},
+ node: {filePath: 'source.tsx', nodePath},
+ componentIdentity,
+ keys,
+ assetKeys,
+ effectKeys: effects,
+ videoConfig: videoConfigValues ?? undefined,
});
- cachedAst.videoConfigIdentifierValues.set(
- videoConfigCacheKey,
- videoConfigIdentifierValues,
- );
- }
+ } catch (error) {
+ if (error instanceof CodemodsInternals.JsxElementIdentityMismatchError) {
+ throw new JsxElementIdentityMismatchError();
+ }
- return computeSequencePropsStatusFromAstAndIdentifiers({
- ast,
- nodePath,
- componentIdentity,
- keys,
- assetKeys,
- effects,
- videoConfigIdentifierValues,
- });
+ if (error instanceof CodemodsInternals.JsxElementNotFoundAtLocationError) {
+ throw new JsxElementNotFoundAtLocationError();
+ }
+
+ throw error;
+ }
};
export const computeSequencePropsStatus = ({
@@ -2114,15 +1447,11 @@ export const computeSequencePropsStatusFromFilenameByLocation = ({
action: 'read',
});
- const fileContents = readFileSync(absolutePath, 'utf-8');
- const {ast} = getCachedSequencePropsStatusAst(fileContents);
-
- const resolvedNodePath = lineColumnToNodePath(
- ast,
- line,
- column,
- fileContents,
- );
+ const [resolvedNodePath] = resolveSequencePropsNodePathsFromFilename({
+ fileName,
+ targets: [{line, column}],
+ remotionRoot,
+ });
if (!resolvedNodePath) {
return {
status: {