🎥 Make videos programmatically with React
`@remotion/studio-codemods`: Delete JSX without Prettier
JonnyBurger2881fbdbfe25
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex f3e1b56597..918667846c 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1227,7 +1227,6 @@ export const createBrowserStudioOperations = ({result: await deleteJsxNodes({input: project.files[fileName],nodePaths,- formatFile: formatCodemodFile,}),})),);diff --git a/packages/studio-codemods/src/delete-jsx-node.ts b/packages/studio-codemods/src/delete-jsx-node.tsindex 1a50114379..fd69707763 100644--- a/packages/studio-codemods/src/delete-jsx-node.ts+++ b/packages/studio-codemods/src/delete-jsx-node.ts@@ -30,8 +30,9 @@ import {captureJsxNodePaths,getNodePathRemappings,} from './get-node-path-remappings';+import {recastLocToOffset} from './recast-loc-to-offset';import {getAstNodePath} from './sequence-props/get-ast-node-path';-import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseAst} from './sequence-props/parse-ast';const {builders: b, namedTypes} = recast.types;@@ -411,15 +412,126 @@ export const deleteJsxElementAtPath = (jsxPath.replace(b.nullLiteral());};-export const deleteJsxNodes = async ({+type SourceEdit = {+ end: number;+ replacement: string;+ start: number;+};++const getNodeSourceEdit = ({+ input,+ jsxPath,+}: {+ input: string;+ jsxPath: recast.types.NodePath;+}): SourceEdit => {+ const node = jsxPath.node as JSXElement;+ if (!node.loc) {+ throw new Error('Cannot delete a JSX element without a source location');+ }++ const start = recastLocToOffset(input, node.loc.start);+ const end = recastLocToOffset(input, node.loc.end);+ const parentNode = jsxPath.parentPath?.node;+ const isJsxChild =+ parentNode !== undefined &&+ (namedTypes.JSXElement.check(parentNode) ||+ namedTypes.JSXFragment.check(parentNode));++ if (!isJsxChild) {+ const {extra} = node as JSXElement & {+ extra?: {parenthesized?: boolean};+ };+ if (extra?.parenthesized) {+ let openingParenthesis = start - 1;+ while (openingParenthesis >= 0 && /\s/.test(input[openingParenthesis])) {+ openingParenthesis--;+ }++ let closingParenthesis = end;+ while (+ closingParenthesis < input.length &&+ /\s/.test(input[closingParenthesis])+ ) {+ closingParenthesis++;+ }++ if (+ input[openingParenthesis] === '(' &&+ input[closingParenthesis] === ')'+ ) {+ return {+ end: closingParenthesis + 1,+ replacement: 'null',+ start: openingParenthesis,+ };+ }+ }++ return {end, replacement: 'null', start};+ }++ const lineStart = input.lastIndexOf('\n', start - 1) + 1;+ const nextLineStart = input.indexOf('\n', end);+ const lineEnd = nextLineStart === -1 ? input.length : nextLineStart;+ const beforeNode = input.slice(lineStart, start);+ const afterNode = input.slice(end, lineEnd);++ if (beforeNode.trim() === '' && afterNode.trim() === '') {+ return {+ end: nextLineStart === -1 ? input.length : nextLineStart + 1,+ replacement: '',+ start: lineStart,+ };+ }++ return {end, replacement: '', start};+};++const applySourceEdits = ({+ edits,+ input,+}: {+ edits: SourceEdit[];+ input: string;+}): string => {+ const sorted = edits+ .slice()+ .sort((left, right) => left.start - right.start || right.end - left.end);+ const nonOverlapping: SourceEdit[] = [];++ for (const edit of sorted) {+ const previous = nonOverlapping[nonOverlapping.length - 1];+ if (previous && edit.start < previous.end) {+ if (edit.end <= previous.end) {+ continue;+ }++ throw new Error('Overlapping JSX deletion source ranges');+ }++ nonOverlapping.push(edit);+ }++ let output = input;+ for (let i = nonOverlapping.length - 1; i >= 0; i--) {+ const edit = nonOverlapping[i];+ output =+ output.slice(0, edit.start) + edit.replacement + output.slice(edit.end);+ }++ return output;+};++export const deleteJsxNodes = ({input,nodePaths,- formatFile,- prettierConfigOverride,}: {input: string;nodePaths: SequenceNodePath[];- formatFile: (input: {+ // Kept optional for compatibility with callers from before source edits+ // replaced the full-file formatting pass.+ formatFile?: (input: {contents: string;prettierConfigOverride: Record<string, unknown> | null;}) => Promise<{output: string; formatted: boolean}>;@@ -460,39 +572,39 @@ export const deleteJsxNodes = async ({};});+ const sourceEdits = pathsToDelete.map(({jsxPath}) =>+ getNodeSourceEdit({input, jsxPath}),+ );+for (const {jsxPath} of pathsToDelete) {deleteJsxElementAtPath(jsxPath);}- const finalFile = serializeAst(ast);- const {output, formatted} = await formatFile({- contents: finalFile,- prettierConfigOverride: prettierConfigOverride ?? null,- });+ const output = applySourceEdits({edits: sourceEdits, input});const {nodePathRemappings} = getNodePathRemappings({ast,captured: capturedNodePaths,output,});- return {+ return Promise.resolve({output,- formatted,+ formatted: true,nodeLabels: pathsToDelete.map(({nodeLabel}) => nodeLabel),logLines: pathsToDelete.map(({logLine}) => logLine),nodePathRemappings,- };+ });};export const deleteJsxNode = async ({input,nodePath,- formatFile,- prettierConfigOverride,}: {input: string;nodePath: SequenceNodePath;- formatFile: (input: {+ // Kept optional for compatibility with callers from before source edits+ // replaced the full-file formatting pass.+ formatFile?: (input: {contents: string;prettierConfigOverride: Record<string, unknown> | null;}) => Promise<{output: string; formatted: boolean}>;@@ -506,8 +618,6 @@ export const deleteJsxNode = async ({const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({input,nodePaths: [nodePath],- formatFile,- prettierConfigOverride,});return {diff --git a/packages/studio-codemods/src/recast-loc-to-offset.ts b/packages/studio-codemods/src/recast-loc-to-offset.tsnew file mode 100644index 0000000000..ed1b4e7d0d--- /dev/null+++ b/packages/studio-codemods/src/recast-loc-to-offset.ts@@ -0,0 +1,27 @@+const RECAST_TAB_WIDTH = 4;++// Recast expands tabs before parsing, so its columns cannot be used as+// character offsets in the original source.+export const recastLocToOffset = (+ input: string,+ loc: {line: number; column: number},+): number => {+ const lines = input.split('\n');+ let offset = 0;+ for (let i = 0; i < loc.line - 1; i++) {+ offset += lines[i].length + 1;+ }++ const line = lines[loc.line - 1];+ let column = 0;+ for (let i = 0; i < line.length; i++) {+ if (column >= loc.column) {+ return offset + i;+ }++ column +=+ line[i] === '\t' ? RECAST_TAB_WIDTH - (column % RECAST_TAB_WIDTH) : 1;+ }++ return offset + line.length;+};diff --git a/packages/studio-codemods/src/update-default-props.ts b/packages/studio-codemods/src/update-default-props.tsindex a9ee95207f..7413794110 100644--- a/packages/studio-codemods/src/update-default-props.ts+++ b/packages/studio-codemods/src/update-default-props.ts@@ -1,5 +1,6 @@import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';import * as recast from 'recast';+import {recastLocToOffset} from './recast-loc-to-offset';import {parseAst} from './sequence-props/parse-ast';export type FormatInline = (options: {@@ -87,35 +88,6 @@ export const formatInlineContentWithFormatter = async ({return {formatted: indentedProps, didFormat: true};};-// Recast uses tabWidth=4 for column counting, so columns don't-// correspond to character indices when tabs are present.-// This converts a recast loc (line/column) to a character offset.-const RECAST_TAB_WIDTH = 4;--const recastLocToOffset = (- input: string,- loc: {line: number; column: number},-): number => {- const lines = input.split('\n');- let offset = 0;- for (let i = 0; i < loc.line - 1; i++) {- offset += lines[i].length + 1;- }-- // Convert recast's tab-expanded column to character index- const line = lines[loc.line - 1];- let col = 0;- for (let i = 0; i < line.length; i++) {- if (col >= loc.column) {- return offset + i;- }-- col += line[i] === '\t' ? RECAST_TAB_WIDTH : 1;- }-- return offset + line.length;-};-export const updateDefaultProps = async ({input,compositionId,diff --git a/packages/studio-server/src/codemods/delete-jsx-node.ts b/packages/studio-server/src/codemods/delete-jsx-node.tsindex 6154defab2..3306bc8b6a 100644--- a/packages/studio-server/src/codemods/delete-jsx-node.ts+++ b/packages/studio-server/src/codemods/delete-jsx-node.ts@@ -6,7 +6,6 @@ import {getJsxElementTagLabel,} from '@remotion/studio-codemods';import type {SequenceNodePath} from 'remotion';-import {formatFileContent} from './format-file-content';export {deleteJsxElementAtPath,@@ -17,45 +16,23 @@ export {export const deleteJsxNodes = ({input,nodePaths,- onFormatFile,- prettierConfigOverride,}: {input: string;nodePaths: SequenceNodePath[];- onFormatFile: ((stage: 'start' | 'complete') => void) | null;- prettierConfigOverride?: Record<string, unknown> | null;}) =>deleteJsxNodesCodemod({input,nodePaths,- formatFile: async ({contents, prettierConfigOverride: override}) => {- onFormatFile?.('start');- const result = await formatFileContent({- input: contents,- prettierConfigOverride: override,- });- onFormatFile?.('complete');- return result;- },- prettierConfigOverride,});export const deleteJsxNode = ({input,nodePath,- prettierConfigOverride,}: {input: string;nodePath: SequenceNodePath;- prettierConfigOverride?: Record<string, unknown> | null;}) =>deleteJsxNodeCodemod({input,nodePath,- formatFile: ({contents, prettierConfigOverride: override}) =>- formatFileContent({- input: contents,- prettierConfigOverride: override,- }),- prettierConfigOverride,});diff --git a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts b/packages/studio-server/src/preview-server/routes/delete-jsx-node.tsindex 94b16f06e8..385b2c7fcc 100644--- a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts@@ -16,7 +16,6 @@ import {pushToUndoStack,suppressUndoStackInvalidation,} from '../undo-stack';-import {warnAboutPrettierOnce} from './log-updates/log-update';import {getCodemodTimingPrefix,withSourceFileWriteQueue,@@ -68,17 +67,10 @@ export const deleteJsxNodeHandler: ApiHandler<const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, nodeLabels, logLines, nodePathRemappings} =+ const {output, nodeLabels, logLines, nodePathRemappings} =await deleteJsxNodes({input: fileContents,nodePaths: fileItems.map((item) => item.nodePath),- onFormatFile: (stage) => {- logHmrTiming({- detail: `file=${fileRelativeToRoot}`,- logLevel,- stage: `source-file-format-${stage}`,- });- },});return {@@ -86,7 +78,6 @@ export const deleteJsxNodeHandler: ApiHandler<fileRelativeToRoot,fileContents,output,- formatted,nodeLabels,nodePathRemappings,logLine: Math.min(...logLines),@@ -153,13 +144,9 @@ export const deleteJsxNodeHandler: ApiHandler<{indent: false, logLevel},`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Deleted ${deletedNodeDescription}`,);- if (!update.formatted) {- warnAboutPrettierOnce(logLevel);- }-RenderInternals.Log.verbose({indent: false, logLevel},- `[delete-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ `[delete-jsx-node] Wrote ${update.fileRelativeToRoot}`,);}diff --git a/packages/studio-server/src/test/delete-jsx-node.test.ts b/packages/studio-server/src/test/delete-jsx-node.test.tsindex 0b9e0b5a1d..75c96f6610 100644--- a/packages/studio-server/src/test/delete-jsx-node.test.ts+++ b/packages/studio-server/src/test/delete-jsx-node.test.ts@@ -20,7 +20,7 @@ import {popRedo,popUndo,} from '../preview-server/undo-stack';-import {lineColumnToNodePath} from './test-utils';+import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';const sample = `import React from 'react';import {AbsoluteFill} from 'remotion';@@ -139,7 +139,6 @@ test('deleteJsxNodes removes multiple JSX children in one transform', async () =lineColumnToNodePath(multipleSiblings, 7),lineColumnToNodePath(multipleSiblings, 8),],- onFormatFile: null,});expect(output).not.toContain('<div');@@ -149,6 +148,164 @@ test('deleteJsxNodes removes multiple JSX children in one transform', async () =expect(logLines).toEqual([7, 8]);});+test('deleteJsxNodes preserves source formatting and removes standalone JSX lines', async () => {+ const cases = [+ {+ input: `export const Comp = () => {+ return (+ <div>+ <Keep />+ <RemoveOne />+ <RemoveTwo />+ <Keep />+ </div>+ );+};+`,+ markers: ['<RemoveOne', '<RemoveTwo'],+ expected: `export const Comp = () => {+ return (+ <div>+ <Keep />+ <Keep />+ </div>+ );+};+`,+ },+ {+ input: `export const Comp = () => {+ return (+ <div>+ <Remove />+ </div>+ )+}+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => {+ return (+ <div>+ </div>+ )+}+`,+ },+ {+ input: `export const Comp = () => {+ return [1].map((item) => (+ <Remove key={item} />+ ));+};+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => {+ return [1].map((item) => null);+};+`,+ },+ {+ input: `const AnimatedBar = () => {+ return (+ <Remove />+ );+};+`,+ markers: ['<Remove'],+ expected: `const AnimatedBar = () => {+ return null;+};+`,+ },+ {+ input: `const AnimatedBar = () => {+ return (+ // Keep this explanation.+ <Remove />+ );+};+`,+ markers: ['<Remove'],+ expected: `const AnimatedBar = () => {+ return (+ // Keep this explanation.+ null+ );+};+`,+ },+ {+ input: `export const Comp = () => <div><Keep /><Remove /><Keep /></div>;+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => <div><Keep /><Keep /></div>;+`,+ },+ {+ input:+ 'export const Comp = () => <div><Keep />\t<Remove /><Keep /></div>;\n',+ markers: ['<Remove'],+ expected: 'export const Comp = () => <div><Keep />\t<Keep /></div>;\n',+ },+ {+ input: `export const Comp = () => (+ <div>+ <Remove /> {/* keep this comment */}+ </div>+);+`,+ markers: ['<Remove'],+ expected: `export const Comp = () => (+ <div>+ {/* keep this comment */}+ </div>+);+`,+ },+ {+ input: `export const Comp = () => {+ return (+ <div>+ <RemoveParent>+ <RemoveChild />+ </RemoveParent>+ <Keep />+ </div>+ );+};+`,+ markers: ['<RemoveParent', '<RemoveChild'],+ expected: `export const Comp = () => {+ return (+ <div>+ <Keep />+ </div>+ );+};+`,+ },+ {+ input:+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t\t<Remove />\r\n\t\t</div>\r\n\t);\r\n};\r\n',+ markers: ['<Remove'],+ expected:+ 'export const Comp = () => {\r\n\treturn (\r\n\t\t<div>\r\n\t\t</div>\r\n\t);\r\n};\r\n',+ },+ ] as const;++ for (const item of cases) {+ const {output, formatted} = await deleteJsxNodes({+ input: item.input,+ nodePaths: item.markers.map((marker) =>+ lineContainingToNodePath(item.input, marker),+ ),+ });++ expect(output).toBe(item.expected);+ expect(formatted).toBe(true);+ }+});+const interactiveSiblings = `import {Interactive} from 'remotion';export const X = () => {@@ -162,6 +319,18 @@ export const X = () => {};`;+const interactiveSiblingsAfterDelete = `import {Interactive} from 'remotion';++export const X = () => {+ return (+ <div>+ <Interactive.Div name="Title" />+ <Interactive.Div name="Chart" />+ </div>+ );+};+`;+test('deleting a JSX node broadcasts node path mutations for all clients', async () => {clearUndoStackForTests();const cleanupFileWatcher = setFileWatcherRegistry(@@ -255,6 +424,7 @@ test('deleting a JSX node broadcasts node path mutations for all clients', asyncawait Promise.resolve();const output = readFileSync(filePath, 'utf-8');+ expect(output).toBe(interactiveSiblingsAfterDelete);expect(output).not.toContain('Eyebrow');expect(output).toContain('name="Title"');expect(output).toContain('name="Chart"');diff --git a/packages/studio-server/src/test/test-utils.ts b/packages/studio-server/src/test/test-utils.tsindex ac0f9fd897..81d01cdbea 100644--- a/packages/studio-server/src/test/test-utils.ts+++ b/packages/studio-server/src/test/test-utils.ts@@ -43,12 +43,20 @@ export const lineContainingToNodePath = (input: string,search: string,): SequenceNodePath => {- const line = input- .split('\n')- .findIndex((sourceLine) => sourceLine.includes(search));+ const sourceLines = input.split('\n');+ const line = sourceLines.findIndex((sourceLine) =>+ sourceLine.includes(search),+ );if (line === -1) {throw new Error(`Could not find ${JSON.stringify(search)} in source`);}- return lineColumnToNodePath(input, line + 1);+ const ast = parseAst(input);+ const column = sourceLines[line].indexOf(search);+ const result = _lineColumnToNodePath(ast, line + 1, column, input);+ if (!result) {+ throw new Error(`No JSX element found for ${JSON.stringify(search)}`);+ }++ return result;};