Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-server`: Resolve JSX elements by column (#9872)

Jonny Burgere4a2ebc93fc4
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 20f2d16588..a99a3a6259 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
@@ -908,25 +908,71 @@ export const findNodePathForJsxElement = (
return foundPath;
};
+const RECAST_TAB_WIDTH = 4;
+
+const sourceColumnToRecastColumn = ({
+ fileContents,
+ line,
+ column,
+}: {
+ fileContents: string;
+ line: number;
+ column: number;
+}) => {
+ const sourceLine = fileContents.split('\n')[line - 1];
+ 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({
+ fileContents,
+ line: targetLine,
+ 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;
};
const PIXEL_VALUE_REGEX = /^-?\d+(\.\d+)?px$/;
@@ -1377,9 +1423,10 @@ export const computeSequencePropsStatus = ({
});
};
-export const computeSequencePropsStatusFromFilenameByLine = ({
+export const computeSequencePropsStatusFromFilenameByLocation = ({
fileName,
line,
+ column,
componentIdentity,
keys,
assetKeys = [],
@@ -1390,6 +1437,7 @@ export const computeSequencePropsStatusFromFilenameByLine = ({
}: {
fileName: string;
line: number;
+ column: number;
componentIdentity: JsxComponentIdentity | null;
keys: string[];
assetKeys?: string[];
@@ -1408,7 +1456,12 @@ export const computeSequencePropsStatusFromFilenameByLine = ({
const fileContents = readFileSync(absolutePath, 'utf-8');
const ast = parseAst(fileContents);
- const resolvedNodePath = lineColumnToNodePath(ast, line);
+ const resolvedNodePath = lineColumnToNodePath(
+ ast,
+ line,
+ column,
+ fileContents,
+ );
if (!resolvedNodePath) {
return {
status: {
@@ -1440,6 +1493,19 @@ export const computeSequencePropsStatusFromFilenameByLine = ({
success: true,
};
} catch (err) {
+ if (
+ err instanceof JsxElementIdentityMismatchError ||
+ err instanceof JsxElementNotFoundAtLocationError
+ ) {
+ return {
+ status: {
+ canUpdate: false as const,
+ reason: 'not-found',
+ },
+ success: false,
+ };
+ }
+
RenderInternals.Log.error({indent: false, logLevel}, err);
return {
status: {
diff --git a/packages/studio-server/src/preview-server/sequence-props-watchers.ts b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
index 66f69ab26c..45f928182c 100644
--- a/packages/studio-server/src/preview-server/sequence-props-watchers.ts
+++ b/packages/studio-server/src/preview-server/sequence-props-watchers.ts
@@ -18,7 +18,7 @@ import {getCachedNodePath, setCachedNodePath} from './node-path-cache';
import {
computeSequencePropsStatus,
computeSequencePropsStatusFromContent,
- computeSequencePropsStatusFromFilenameByLine,
+ computeSequencePropsStatusFromFilenameByLocation,
} from './routes/can-update-sequence-props';
type WatcherInfo = {
@@ -143,9 +143,10 @@ const getSequencePropsStatus = ({
}
}
- const status = computeSequencePropsStatusFromFilenameByLine({
+ const status = computeSequencePropsStatusFromFilenameByLocation({
fileName,
line,
+ column,
componentIdentity,
keys,
assetKeys,
diff --git a/packages/studio-server/src/test/compute-sequence-props-status.test.ts b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
index dc5f6f83b3..3c28268253 100644
--- a/packages/studio-server/src/test/compute-sequence-props-status.test.ts
+++ b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
@@ -1,5 +1,6 @@
import {expect, test} from 'bun:test';
-import {readFileSync} from 'node:fs';
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
import path from 'node:path';
import {NoReactInternals} from 'remotion/no-react';
import {parseAst} from '../codemods/parse-ast';
@@ -7,6 +8,7 @@ import {JsxElementIdentityMismatchError} from '../preview-server/jsx-component-i
import {
computeSequencePropsStatus,
computeSequencePropsStatusFromContent,
+ computeSequencePropsStatusFromFilenameByLocation,
lineColumnToNodePath,
} from '../preview-server/routes/can-update-sequence-props';
@@ -38,6 +40,95 @@ const videoConfigValues = {
width: 1920,
};
+const getSourceLocation = (source: string, search: string) => {
+ const index = source.indexOf(search);
+ if (index === -1) {
+ throw new Error(`Could not find ${search}`);
+ }
+
+ const linesBeforeMatch = source.slice(0, index).split('\n');
+ return {
+ line: linesBeforeMatch.length,
+ column: linesBeforeMatch.at(-1)?.length ?? 0,
+ };
+};
+
+test('computeSequencePropsStatus should distinguish JSX elements on the same line', () => {
+ const input = `import React from 'react';
+import {AbsoluteFill, Sequence} from 'remotion';
+
+export const Example: React.FC = () => {
+ return <AbsoluteFill><Sequence name="Hook" durationInFrames={150}><HeroScene /></Sequence><Sequence name="Create" from={150} durationInFrames={150}><CreateScene /></Sequence></AbsoluteFill>;
+};
+
+export const Fallback = () => <><Sequence name="First" /><Sequence name="Fallback" from={300} /></>;
+`;
+ const remotionRoot = mkdtempSync(
+ path.join(tmpdir(), 'remotion-jsx-location-'),
+ );
+ const fileName = 'Example.tsx';
+ writeFileSync(path.join(remotionRoot, fileName), input);
+
+ try {
+ const getStatus = (search: string, columnOffset = 0) => {
+ const location = getSourceLocation(input, search);
+
+ return computeSequencePropsStatusFromFilenameByLocation({
+ fileName,
+ line: location.line,
+ column: location.column + columnOffset,
+ componentIdentity: 'dev.remotion.remotion.Sequence',
+ keys: ['name', 'from'],
+ effects: [],
+ remotionRoot,
+ logLevel: 'info',
+ videoConfigValues,
+ });
+ };
+
+ const hook = getStatus('<Sequence name="Hook"');
+ expect(hook.success).toBe(true);
+ if (!hook.success) {
+ throw new Error('Expected the Hook sequence to be found');
+ }
+
+ expect(hook.status.props.name).toEqual({
+ status: 'static',
+ codeValue: 'Hook',
+ });
+
+ const create = getStatus('<Sequence name="Create"');
+ expect(create.success).toBe(true);
+ if (!create.success) {
+ throw new Error('Expected the Create sequence to be found');
+ }
+
+ expect(create.status.props).toMatchObject({
+ name: {status: 'static', codeValue: 'Create'},
+ from: {status: 'static', codeValue: 150},
+ });
+
+ const child = getStatus('<HeroScene');
+ expect(child).toEqual({
+ success: false,
+ status: {canUpdate: false, reason: 'not-found'},
+ });
+
+ const fallback = getStatus('<Sequence name="Fallback"', 1);
+ expect(fallback.success).toBe(true);
+ if (!fallback.success) {
+ throw new Error('Expected the line fallback to find the last sequence');
+ }
+
+ expect(fallback.status.props).toMatchObject({
+ name: {status: 'static', codeValue: 'Fallback'},
+ from: {status: 'static', codeValue: 300},
+ });
+ } finally {
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
test('computeSequencePropsStatus should treat staticFile() asset props as static', () => {
const input = `import {Img, staticFile} from 'remotion';