Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Save JSX duplication without Prettier

Jonny Burger102c6ed91ee5
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index e1b9527d6e..3e892006b6 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -1353,7 +1353,6 @@ export const createBrowserStudioOperations = ({
result: await duplicateJsxNodesCodemod({
input: project.files[fileName],
nodePaths,
- formatFile: formatCodemodFile,
}),
})),
);
diff --git a/packages/studio-codemods/src/duplicate-jsx-node.ts b/packages/studio-codemods/src/duplicate-jsx-node.ts
index 2f3c2fd458..f176d6ef16 100644
--- a/packages/studio-codemods/src/duplicate-jsx-node.ts
+++ b/packages/studio-codemods/src/duplicate-jsx-node.ts
@@ -10,11 +10,21 @@ import {
captureJsxNodePaths,
getNodePathRemappings,
} from './get-node-path-remappings';
+import {indentInsertedJsx} from './print-jsx';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
import {
- parseAst,
- parseAstForReadOnly,
- serializeAst,
-} from './sequence-props/parse-ast';
+ applySourceEdits,
+ getJsxElementSourceForInsertion,
+ getJsxStringAttributeValueSourceEdit,
+ type SourceEdit,
+} from './source-edits';
+import {
+ getEndOfLine,
+ getIndentationUnit,
+ getLineIndent,
+ indentContinuationLines,
+} from './source-style';
const makeFragment = (first: JSXElement, second: JSXElement): JSXFragment => ({
type: 'JSXFragment',
@@ -161,19 +171,159 @@ export const duplicateJsxElementAtPath = (
jsxPath.replace(makeFragment(jsxNode, clone));
};
-export const duplicateJsxNodes = async ({
+const getDuplicatedJsxSource = ({
+ element,
+ input,
+}: {
+ element: JSXElement;
+ input: string;
+}) => {
+ if (!element.loc) {
+ throw new Error('Cannot duplicate a JSX element without a source location');
+ }
+
+ const start = recastLocToOffset(input, element.loc.start);
+ const end = recastLocToOffset(input, element.loc.end);
+ let source = input.slice(start, end);
+ const nameAttribute = element.openingElement.attributes.find(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'name' &&
+ (attribute.value?.type === 'StringLiteral' ||
+ (attribute.value?.type === 'JSXExpressionContainer' &&
+ attribute.value.expression.type === 'StringLiteral')),
+ );
+
+ if (nameAttribute?.type === 'JSXAttribute') {
+ const value =
+ nameAttribute.value?.type === 'JSXExpressionContainer'
+ ? nameAttribute.value.expression
+ : nameAttribute.value;
+ if (value?.type !== 'StringLiteral') {
+ throw new Error('Expected the JSX name attribute to be a string');
+ }
+
+ const edit = getJsxStringAttributeValueSourceEdit({
+ attribute: nameAttribute,
+ input,
+ newValue: `${value.value}-copy`,
+ });
+ source =
+ source.slice(0, edit.start - start) +
+ edit.replacement +
+ source.slice(edit.end - start);
+ }
+
+ const originalIndent = getLineIndent({input, offset: start});
+ return source
+ .split(/\r?\n/)
+ .map((line, index) => {
+ if (index === 0) {
+ return line;
+ }
+
+ return line.startsWith(originalIndent)
+ ? line.slice(originalIndent.length)
+ : line.trimStart();
+ })
+ .join(getEndOfLine(input));
+};
+
+const getDuplicateSourceEdit = ({
+ input,
+ jsxPath,
+}: {
+ input: string;
+ jsxPath: recast.types.NodePath;
+}): SourceEdit => {
+ const element = jsxPath.node as JSXElement;
+ if (!element.loc) {
+ throw new Error('Cannot duplicate a JSX element without a source location');
+ }
+
+ const start = recastLocToOffset(input, element.loc.start);
+ const end = recastLocToOffset(input, element.loc.end);
+ const parentNode = jsxPath.parentPath?.node;
+ if (!parentNode) {
+ throw new Error('Cannot duplicate JSX element with no parent');
+ }
+
+ const duplicatedSource = getDuplicatedJsxSource({element, input});
+ const indent = getLineIndent({input, offset: start});
+ const endOfLine = getEndOfLine(input);
+ const lineEnd = input.indexOf('\n', end);
+ const sourceAfterElement = input.slice(
+ end,
+ lineEnd === -1 ? input.length : lineEnd,
+ );
+
+ if (parentNode.type === 'JSXElement' || parentNode.type === 'JSXFragment') {
+ const isStandalone = sourceAfterElement.trim() === '';
+ const lineStart = input.lastIndexOf('\n', start - 1) + 1;
+ const whitespaceBeforeElement =
+ input.slice(lineStart, start).match(/[\t ]*$/)?.[0] ?? '';
+ const insertion = isStandalone
+ ? `${endOfLine}${indentInsertedJsx({
+ indent,
+ insertion: duplicatedSource,
+ })}`
+ : `${whitespaceBeforeElement}${indentContinuationLines({
+ indent,
+ input,
+ printed: duplicatedSource,
+ })}`;
+
+ return {end, replacement: insertion, start: end};
+ }
+
+ const arrayProperty = getArrayProperty(parentNode);
+ const parent = parentNode as unknown as Record<string, unknown>;
+ const isArrayChild =
+ arrayProperty !== null &&
+ (parent[arrayProperty] as unknown[]).includes(element);
+ if (isArrayChild) {
+ const isStandalone =
+ sourceAfterElement.trim() === '' || sourceAfterElement.trim() === ',';
+ const insertion = isStandalone
+ ? `,${endOfLine}${indentInsertedJsx({
+ indent,
+ insertion: duplicatedSource,
+ })}`
+ : `, ${indentContinuationLines({
+ indent,
+ input,
+ printed: duplicatedSource,
+ })}`;
+ return {end, replacement: insertion, start: end};
+ }
+
+ const originalSource = getJsxElementSourceForInsertion({element, input});
+ const unit = getIndentationUnit(input, null);
+ const fragment = [
+ '<>',
+ indentInsertedJsx({indent: unit, insertion: originalSource}),
+ indentInsertedJsx({indent: unit, insertion: duplicatedSource}),
+ '</>',
+ ].join(endOfLine);
+
+ return {
+ end,
+ replacement: indentContinuationLines({
+ indent,
+ input,
+ printed: fragment,
+ }),
+ start,
+ };
+};
+
+export const duplicateJsxNodes = ({
input,
nodePaths,
- formatFile,
- prettierConfigOverride,
}: {
input: string;
nodePaths: SequenceNodePath[];
- formatFile: (input: {
- contents: string;
- prettierConfigOverride: Record<string, unknown> | null;
- }) => Promise<{output: string; formatted: boolean}>;
- prettierConfigOverride?: Record<string, unknown> | null;
}): Promise<{
output: string;
formatted: boolean;
@@ -201,61 +351,26 @@ export const duplicateJsxNodes = async ({
1,
};
});
+ const sourceEdits = targets.map(({jsxPath}) =>
+ getDuplicateSourceEdit({input, jsxPath}),
+ );
for (const target of targets) {
duplicateJsxElementAtPath(target.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: targets.map((target) => target.nodeLabel),
logLines: targets.map((target) => target.logLine),
nodePathRemappings,
- };
-};
-
-export const duplicateJsxNode = async ({
- input,
- nodePath,
- formatFile,
- prettierConfigOverride,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- formatFile: (input: {
- contents: string;
- prettierConfigOverride: Record<string, unknown> | null;
- }) => Promise<{output: string; formatted: boolean}>;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- nodeLabel: string;
- logLine: number;
- nodePathRemappings: SequenceNodePathRemapping[];
-}> => {
- const {nodeLabels, logLines, ...result} = await duplicateJsxNodes({
- input,
- nodePaths: [nodePath],
- formatFile,
- prettierConfigOverride,
});
-
- return {
- ...result,
- nodeLabel: nodeLabels[0],
- logLine: logLines[0],
- };
};
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index d68bba28e9..a6e0daaa4a 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -23,7 +23,6 @@ export {
export {duplicateCompositionInSource} from './duplicate-composition';
export {
duplicateJsxElementAtPath,
- duplicateJsxNode,
duplicateJsxNodes,
} from './duplicate-jsx-node';
export {
diff --git a/packages/studio-server/src/codemods/duplicate-jsx-node.ts b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
deleted file mode 100644
index 825a370207..0000000000
--- a/packages/studio-server/src/codemods/duplicate-jsx-node.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import {
- duplicateJsxElementAtPath,
- duplicateJsxNode as duplicateJsxNodeCodemod,
- duplicateJsxNodes as duplicateJsxNodesCodemod,
-} from '@remotion/studio-codemods';
-import type {SequenceNodePath} from 'remotion';
-import {formatFileContent} from './format-file-content';
-
-export {duplicateJsxElementAtPath};
-
-export const duplicateJsxNode = ({
- input,
- nodePath,
- prettierConfigOverride,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- prettierConfigOverride?: Record<string, unknown> | null;
-}) =>
- duplicateJsxNodeCodemod({
- input,
- nodePath,
- formatFile: ({contents, prettierConfigOverride: override}) =>
- formatFileContent({
- input: contents,
- prettierConfigOverride: override,
- }),
- prettierConfigOverride,
- });
-
-export const duplicateJsxNodes = ({
- input,
- nodePaths,
- prettierConfigOverride,
-}: {
- input: string;
- nodePaths: SequenceNodePath[];
- prettierConfigOverride?: Record<string, unknown> | null;
-}) =>
- duplicateJsxNodesCodemod({
- input,
- nodePaths,
- formatFile: ({contents, prettierConfigOverride: override}) =>
- formatFileContent({
- input: contents,
- prettierConfigOverride: override,
- }),
- prettierConfigOverride,
- });
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
index 01a9719024..de86996c7e 100644
--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
@@ -1,10 +1,10 @@
import {readFileSync} from 'node:fs';
import {RenderInternals} from '@remotion/renderer';
+import {duplicateJsxNodes} from '@remotion/studio-codemods';
import type {
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse,
} from '@remotion/studio-shared';
-import {duplicateJsxNodes} from '../../codemods/duplicate-jsx-node';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -15,7 +15,6 @@ import {
pushTransactionToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
-import {warnAboutPrettierOnce} from './log-updates/log-update';
import {
getCodemodTimingPrefix,
withSourceFileWriteQueue,
@@ -51,7 +50,7 @@ export const duplicateJsxNodeHandler: ApiHandler<
action: 'modify',
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, nodeLabels, logLines, nodePathRemappings} =
+ const {output, nodeLabels, logLines, nodePathRemappings} =
await duplicateJsxNodes({
input: fileContents,
nodePaths: fileItems.map((item) => item.nodePath),
@@ -61,7 +60,6 @@ export const duplicateJsxNodeHandler: ApiHandler<
absolutePath,
fileRelativeToRoot,
fileContents,
- formatted,
logLine: Math.min(...logLines),
nodeLabels,
nodePathRemappings,
@@ -122,13 +120,10 @@ export const duplicateJsxNodeHandler: ApiHandler<
{indent: false, logLevel},
`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${fileDescription}`,
);
- if (!update.formatted) {
- warnAboutPrettierOnce(logLevel);
- }
RenderInternals.Log.verbose(
{indent: false, logLevel},
- `[duplicate-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,
+ `[duplicate-jsx-node] Wrote ${update.fileRelativeToRoot}`,
);
}
diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
index 8061130309..407897285f 100644
--- a/packages/studio-server/src/test/duplicate-jsx-node.test.ts
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -1,8 +1,5 @@
import {expect, test} from 'bun:test';
-import {
- duplicateJsxNode,
- duplicateJsxNodes,
-} from '../codemods/duplicate-jsx-node';
+import {duplicateJsxNodes} from '@remotion/studio-codemods';
import {lineColumnToNodePath, lineContainingToNodePath} from './test-utils';
const sample = `import React from 'react';
@@ -17,10 +14,10 @@ export const X: React.FC = () => {
};
`;
-test('duplicateJsxNode inserts a sibling JSX element', async () => {
- const {output} = await duplicateJsxNode({
+test('duplicateJsxNodes inserts a sibling JSX element', async () => {
+ const {output} = await duplicateJsxNodes({
input: sample,
- nodePath: lineColumnToNodePath(sample, 7),
+ nodePaths: [lineColumnToNodePath(sample, 7)],
});
const divOpens = output.match(/<div/g);
@@ -28,7 +25,7 @@ test('duplicateJsxNode inserts a sibling JSX element', async () => {
expect(output).toContain('<AbsoluteFill>');
});
-test('duplicateJsxNode remaps following JSX siblings', async () => {
+test('duplicateJsxNodes remaps following JSX siblings', async () => {
const input = `export const X = () => (
<div>
<span name="duplicate" />
@@ -36,9 +33,9 @@ test('duplicateJsxNode remaps following JSX siblings', async () => {
</div>
);
`;
- const {output, nodePathRemappings} = await duplicateJsxNode({
+ const {output, nodePathRemappings} = await duplicateJsxNodes({
input,
- nodePath: lineContainingToNodePath(input, 'name="duplicate"'),
+ nodePaths: [lineContainingToNodePath(input, 'name="duplicate"')],
});
expect(nodePathRemappings).toEqual([
@@ -83,15 +80,21 @@ export const X: React.FC = () => {
};
`;
-test('duplicateJsxNode wraps sole return JSX in a fragment with two elements', async () => {
- const {output} = await duplicateJsxNode({
+test('duplicateJsxNodes wraps sole return JSX in a fragment with two elements', async () => {
+ const {output} = await duplicateJsxNodes({
input: onlyReturn,
- nodePath: lineColumnToNodePath(onlyReturn, 4),
+ nodePaths: [lineColumnToNodePath(onlyReturn, 4)],
});
- expect(output).toMatch(/return\s*\(?\s*</);
- const divOpens = output.match(/<div/g);
- expect(divOpens?.length).toBe(2);
+ expect(output).toBe(`import React from 'react';
+
+export const X: React.FC = () => {
+ return <>
+ <div />
+ <div />
+ </>;
+};
+`);
});
const mapCase = `import React from 'react';
@@ -107,12 +110,105 @@ export const X: React.FC = () => {
};
`;
-test('duplicateJsxNode duplicates JSX inside map callback', async () => {
- const {output} = await duplicateJsxNode({
+test('duplicateJsxNodes duplicates JSX inside map callback', async () => {
+ const {output} = await duplicateJsxNodes({
input: mapCase,
- nodePath: lineColumnToNodePath(mapCase, 7),
+ nodePaths: [lineColumnToNodePath(mapCase, 7)],
});
const divOpens = output.match(/<div/g);
expect(divOpens?.length).toBe(2);
});
+
+test('duplicateJsxNodes preserves surrounding source formatting', async () => {
+ const input = `export const X=()=>(
+ <div data={{value:1}}>
+ <span name='first' data-value = {1}/>
+ <span name='untouched'/>
+ </div>
+)
+`;
+ const {output} = await duplicateJsxNodes({
+ input,
+ nodePaths: [lineContainingToNodePath(input, "name='first'")],
+ });
+
+ expect(output).toBe(`export const X=()=>(
+ <div data={{value:1}}>
+ <span name='first' data-value = {1}/>
+ <span name='first-copy' data-value = {1}/>
+ <span name='untouched'/>
+ </div>
+)
+`);
+});
+
+test('duplicateJsxNodes preserves CRLF line endings', async () => {
+ const input = [
+ 'export const X = () => (',
+ ' <div>',
+ ' <span name="first" />',
+ ' </div>',
+ ');',
+ '',
+ ].join('\r\n');
+ const {output} = await duplicateJsxNodes({
+ input,
+ nodePaths: [lineContainingToNodePath(input, 'name="first"')],
+ });
+
+ expect(output).toBe(
+ [
+ 'export const X = () => (',
+ ' <div>',
+ ' <span name="first" />',
+ ' <span name="first-copy" />',
+ ' </div>',
+ ');',
+ '',
+ ].join('\r\n'),
+ );
+});
+
+test('duplicateJsxNodes preserves inline JSX spacing', async () => {
+ const input =
+ 'export const X = () => <div><Keep /> <Copy name="item" /><Keep /></div>;\n';
+ const {output} = await duplicateJsxNodes({
+ input,
+ nodePaths: [lineContainingToNodePath(input, '<Copy name="item"')],
+ });
+
+ expect(output).toBe(
+ 'export const X = () => <div><Keep /> <Copy name="item" /> <Copy name="item-copy" /><Keep /></div>;\n',
+ );
+});
+
+test('duplicateJsxNodes preserves multiline JSX formatting', async () => {
+ const input = `export const X = () => (
+ <div>
+ <Item
+ name={'item'}
+ value = {{nested:true}}
+ />
+ </div>
+);
+`;
+ const {output} = await duplicateJsxNodes({
+ input,
+ nodePaths: [lineContainingToNodePath(input, '<Item')],
+ });
+
+ expect(output).toBe(`export const X = () => (
+ <div>
+ <Item
+ name={'item'}
+ value = {{nested:true}}
+ />
+ <Item
+ name={'item-copy'}
+ value = {{nested:true}}
+ />
+ </div>
+);
+`);
+});