Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-codemods`: Split JSX without Prettier

Jonny Burger6171ee865b3a
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 21e307f160..37ac4df0a6 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -319,7 +319,6 @@ const getElementInstallPlanForProject = async ({
compositionFile: destination.compositionFile,
compositionId: destination.compositionId,
environment: makeInMemoryInsertJsxElementCodemodEnvironment({
- formatFile: formatCodemodFile,
project,
svgMarkupToJsx,
}),
@@ -1368,7 +1367,6 @@ export const createBrowserStudioOperations = ({
nodePath,
sequenceKeys,
splitFrame,
- formatFile: formatCodemodFile,
});
const nodePathMutation = controller.applyMutation({
fileName: absolutePath,
@@ -1904,7 +1902,6 @@ export const createBrowserStudioOperations = ({
project: getProject(),
});
const result = await insertJsxElementIntoProjectWithNodePathRemappings({
- formatFile: formatCodemodFile,
project,
request,
svgMarkupToJsx,
@@ -2048,7 +2045,6 @@ export const createBrowserStudioOperations = ({
const durationInFrames = request.element.durationInFrames ?? null;
const insertion =
await insertJsxElementIntoProjectWithNodePathRemappings({
- formatFile: formatCodemodFile,
project,
request: {
compositionFile: request.compositionFile,
diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.ts
index 4899ccdde7..6db3dfef16 100644
--- a/packages/studio-codemods/src/insert-jsx-element.ts
+++ b/packages/studio-codemods/src/insert-jsx-element.ts
@@ -31,6 +31,11 @@ import {
captureJsxNodePaths,
getNodePathRemappings,
} from './get-node-path-remappings';
+import {
+ getIndentationUnit,
+ indentInsertedJsx,
+ printInsertedJsx,
+} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {
ensureNamedImport,
@@ -51,7 +56,9 @@ export type InsertJsxElementCodemodEnvironment = {
dirname: (fileName: string) => string;
extname: (fileName: string) => string;
fileExists: (fileName: string) => boolean;
- 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}>;
@@ -129,7 +136,7 @@ export const makeInMemoryInsertJsxElementCodemodEnvironment = ({
project,
svgMarkupToJsx,
}: {
- formatFile: InsertJsxElementCodemodEnvironment['formatFile'];
+ formatFile?: InsertJsxElementCodemodEnvironment['formatFile'];
project: {files: Record<string, string>; rootDir: string};
svgMarkupToJsx: InsertJsxElementCodemodEnvironment['svgMarkupToJsx'];
}): InsertJsxElementCodemodEnvironment => {
@@ -2082,31 +2089,6 @@ const getLineIndent = (input: string, offset: number) => {
return input.slice(lineStart, offset).match(/^\s*/)?.[0] ?? '';
};
-const getIndentationUnit = (
- input: string,
- prettierConfigOverride: Record<string, unknown> | null,
-) => {
- if (/^\t+/m.test(input)) {
- return '\t';
- }
-
- const indentation = input.match(/^([ ]+)\S/m)?.[1].length;
- if (indentation) {
- return ' '.repeat(indentation > 1 ? indentation : 2);
- }
-
- if (prettierConfigOverride?.useTabs === true) {
- return '\t';
- }
-
- const tabWidth = prettierConfigOverride?.tabWidth;
- return ' '.repeat(
- typeof tabWidth === 'number' && Number.isInteger(tabWidth) && tabWidth > 0
- ? tabWidth
- : 2,
- );
-};
-
const renderImportSpecifier = (
specifier: NonNullable<ImportDeclaration['specifiers']>[number],
) => {
@@ -2495,174 +2477,6 @@ const getSolidInsertionSource = ({
].join(endOfLine);
};
-const indentInsertedJsx = ({
- indent,
- insertion,
-}: {
- indent: string;
- insertion: string;
-}) => {
- return insertion
- .split(/\r?\n/)
- .map((line) => `${indent}${line}`)
- .join(insertion.includes('\r\n') ? '\r\n' : '\n');
-};
-
-const printInsertedJsx = ({
- element,
- input,
- prettierConfigOverride,
-}: {
- element: namedTypes.JSXElement | namedTypes.JSXFragment;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
-}): string => {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- const unit = getIndentationUnit(input, prettierConfigOverride);
- const printWidth = prettierConfigOverride?.printWidth;
- const configuredTabWidth = prettierConfigOverride?.tabWidth;
- const tabWidth =
- typeof configuredTabWidth === 'number' &&
- Number.isInteger(configuredTabWidth) &&
- configuredTabWidth > 0
- ? configuredTabWidth
- : 2;
- recast.types.visit(element, {
- visitObjectProperty(path) {
- const {node} = path;
- if (
- !node.computed &&
- node.key.type === 'StringLiteral' &&
- identifierRegex.test(node.key.value)
- ) {
- node.key = recast.types.builders.identifier(node.key.value);
- }
-
- this.traverse(path);
- return undefined;
- },
- });
- const printNode = (node: namedTypes.Node) => {
- return recast.prettyPrint(node, {
- objectCurlySpacing: prettierConfigOverride?.bracketSpacing !== false,
- quote: prettierConfigOverride?.singleQuote === true ? 'single' : 'double',
- tabWidth,
- useTabs: false,
- wrapColumn: typeof printWidth === 'number' ? printWidth : 80,
- }).code;
- };
-
- const normalizeIndentation = (code: string) => {
- return code
- .split(/\r?\n/)
- .map((line) => {
- const spaces = line.match(/^ */)?.[0].length ?? 0;
- const indentationLevels = Math.floor(spaces / tabWidth);
- const remainingSpaces = spaces % tabWidth;
- return `${unit.repeat(indentationLevels)}${' '.repeat(remainingSpaces)}${line.slice(spaces)}`;
- })
- .join(endOfLine);
- };
-
- const printOpeningElement = (opening: namedTypes.JSXOpeningElement) => {
- const name = printNode(opening.name);
- const attributes = (opening.attributes ?? []).map((attribute) => {
- if (
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.value?.type === 'StringLiteral'
- ) {
- return `${attribute.name.name}=${JSON.stringify(attribute.value.value)}`;
- }
-
- return normalizeIndentation(printNode(attribute));
- });
- const suffix = opening.selfClosing ? ' />' : '>';
- const singleLine = `<${name}${attributes.length === 0 ? '' : ` ${attributes.join(' ')}`}${suffix}`;
- if (
- !attributes.some((attribute) => attribute.includes(endOfLine)) &&
- singleLine.length <= (typeof printWidth === 'number' ? printWidth : 80)
- ) {
- return singleLine;
- }
-
- return [
- `<${name}`,
- ...attributes.map((attribute) =>
- indentInsertedJsx({indent: unit, insertion: attribute}),
- ),
- opening.selfClosing ? '/>' : '>',
- ].join(endOfLine);
- };
-
- const printElement = (
- node: namedTypes.JSXElement | namedTypes.JSXFragment,
- ): string => {
- if (node.type === 'JSXFragment') {
- const fragmentChildren = (node.children ?? []).flatMap((child) => {
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
- return [printElement(child)];
- }
-
- if (child.type === 'JSXText' && child.value.trim() === '') {
- return [];
- }
-
- return [normalizeIndentation(printNode(child))];
- });
- return [
- '<>',
- ...fragmentChildren.map((child) =>
- indentInsertedJsx({indent: unit, insertion: child}),
- ),
- '</>',
- ].join(endOfLine);
- }
-
- const opening = printOpeningElement(node.openingElement);
- if (node.openingElement.selfClosing) {
- return opening;
- }
-
- const closing = node.closingElement
- ? normalizeIndentation(printNode(node.closingElement))
- : '';
- const children = node.children ?? [];
- if (
- children.length === 1 &&
- children[0].type === 'JSXText' &&
- !children[0].value.includes('\n')
- ) {
- return `${opening}${children[0].value}${closing}`;
- }
-
- const printedChildren = children.flatMap((child) => {
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
- return [printElement(child)];
- }
-
- if (child.type === 'JSXText' && child.value.trim() === '') {
- return [];
- }
-
- return [normalizeIndentation(printNode(child))];
- });
- if (printedChildren.length === 0) {
- return `${opening}${closing}`;
- }
-
- return [
- opening,
- ...printedChildren.map((child) =>
- indentInsertedJsx({indent: unit, insertion: child}),
- ),
- closing,
- ].join(endOfLine);
- };
-
- return printElement(element);
-};
-
const getInsertionSource = ({
element,
elementToInsert,
@@ -3465,7 +3279,7 @@ export const insertJsxElementIntoProjectWithNodePathRemappings = async <
}: {
project: Project;
request: InsertJsxElementRequest;
- formatFile: InsertJsxElementCodemodEnvironment['formatFile'];
+ formatFile?: InsertJsxElementCodemodEnvironment['formatFile'];
svgMarkupToJsx: InsertJsxElementCodemodEnvironment['svgMarkupToJsx'];
wrapInSequence: {
dimensions: {width: number; height: number} | null;
diff --git a/packages/studio-codemods/src/print-jsx.ts b/packages/studio-codemods/src/print-jsx.ts
new file mode 100644
index 0000000000..6f9a4fe7a0
--- /dev/null
+++ b/packages/studio-codemods/src/print-jsx.ts
@@ -0,0 +1,197 @@
+import type {namedTypes} from 'ast-types';
+import * as recast from 'recast';
+
+const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
+
+export const getIndentationUnit = (
+ input: string,
+ prettierConfigOverride: Record<string, unknown> | null,
+) => {
+ if (/^\t+/m.test(input)) {
+ return '\t';
+ }
+
+ const indentation = input.match(/^([ ]+)\S/m)?.[1].length;
+ if (indentation) {
+ return ' '.repeat(indentation > 1 ? indentation : 2);
+ }
+
+ if (prettierConfigOverride?.useTabs === true) {
+ return '\t';
+ }
+
+ const tabWidth = prettierConfigOverride?.tabWidth;
+ return ' '.repeat(
+ typeof tabWidth === 'number' && Number.isInteger(tabWidth) && tabWidth > 0
+ ? tabWidth
+ : 2,
+ );
+};
+
+export const indentInsertedJsx = ({
+ indent,
+ insertion,
+}: {
+ indent: string;
+ insertion: string;
+}) => {
+ return insertion
+ .split(/\r?\n/)
+ .map((line) => `${indent}${line}`)
+ .join(insertion.includes('\r\n') ? '\r\n' : '\n');
+};
+
+export const printInsertedJsx = ({
+ element,
+ input,
+ prettierConfigOverride,
+}: {
+ element: namedTypes.JSXElement | namedTypes.JSXFragment;
+ input: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+}): string => {
+ const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const unit = getIndentationUnit(input, prettierConfigOverride);
+ const printWidth = prettierConfigOverride?.printWidth;
+ const configuredTabWidth = prettierConfigOverride?.tabWidth;
+ const tabWidth =
+ typeof configuredTabWidth === 'number' &&
+ Number.isInteger(configuredTabWidth) &&
+ configuredTabWidth > 0
+ ? configuredTabWidth
+ : 2;
+ recast.types.visit(element, {
+ visitObjectProperty(path) {
+ const {node} = path;
+ if (
+ !node.computed &&
+ node.key.type === 'StringLiteral' &&
+ identifierRegex.test(node.key.value)
+ ) {
+ node.key = recast.types.builders.identifier(node.key.value);
+ }
+
+ this.traverse(path);
+ return undefined;
+ },
+ });
+ const printNode = (node: namedTypes.Node) => {
+ return recast.prettyPrint(node, {
+ objectCurlySpacing: prettierConfigOverride?.bracketSpacing !== false,
+ quote: prettierConfigOverride?.singleQuote === true ? 'single' : 'double',
+ tabWidth,
+ useTabs: false,
+ wrapColumn: typeof printWidth === 'number' ? printWidth : 80,
+ }).code;
+ };
+
+ const normalizeIndentation = (code: string) => {
+ return code
+ .split(/\r?\n/)
+ .map((line) => {
+ const spaces = line.match(/^ */)?.[0].length ?? 0;
+ const indentationLevels = Math.floor(spaces / tabWidth);
+ const remainingSpaces = spaces % tabWidth;
+ return `${unit.repeat(indentationLevels)}${' '.repeat(remainingSpaces)}${line.slice(spaces)}`;
+ })
+ .join(endOfLine);
+ };
+
+ const printOpeningElement = (opening: namedTypes.JSXOpeningElement) => {
+ const name = printNode(opening.name);
+ const attributes = (opening.attributes ?? []).map((attribute) => {
+ if (
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.value?.type === 'StringLiteral'
+ ) {
+ return `${attribute.name.name}=${JSON.stringify(attribute.value.value)}`;
+ }
+
+ return normalizeIndentation(printNode(attribute));
+ });
+ const suffix = opening.selfClosing ? ' />' : '>';
+ const singleLine = `<${name}${attributes.length === 0 ? '' : ` ${attributes.join(' ')}`}${suffix}`;
+ if (
+ !attributes.some((attribute) => attribute.includes(endOfLine)) &&
+ singleLine.length <= (typeof printWidth === 'number' ? printWidth : 80)
+ ) {
+ return singleLine;
+ }
+
+ return [
+ `<${name}`,
+ ...attributes.map((attribute) =>
+ indentInsertedJsx({indent: unit, insertion: attribute}),
+ ),
+ opening.selfClosing ? '/>' : '>',
+ ].join(endOfLine);
+ };
+
+ const printElement = (
+ node: namedTypes.JSXElement | namedTypes.JSXFragment,
+ ): string => {
+ if (node.type === 'JSXFragment') {
+ const fragmentChildren = (node.children ?? []).flatMap((child) => {
+ if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
+ return [printElement(child)];
+ }
+
+ if (child.type === 'JSXText' && child.value.trim() === '') {
+ return [];
+ }
+
+ return [normalizeIndentation(printNode(child))];
+ });
+ return [
+ '<>',
+ ...fragmentChildren.map((child) =>
+ indentInsertedJsx({indent: unit, insertion: child}),
+ ),
+ '</>',
+ ].join(endOfLine);
+ }
+
+ const opening = printOpeningElement(node.openingElement);
+ if (node.openingElement.selfClosing) {
+ return opening;
+ }
+
+ const closing = node.closingElement
+ ? normalizeIndentation(printNode(node.closingElement))
+ : '';
+ const children = node.children ?? [];
+ if (
+ children.length === 1 &&
+ children[0].type === 'JSXText' &&
+ !children[0].value.includes('\n')
+ ) {
+ return `${opening}${children[0].value}${closing}`;
+ }
+
+ const printedChildren = children.flatMap((child) => {
+ if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
+ return [printElement(child)];
+ }
+
+ if (child.type === 'JSXText' && child.value.trim() === '') {
+ return [];
+ }
+
+ return [normalizeIndentation(printNode(child))];
+ });
+ if (printedChildren.length === 0) {
+ return `${opening}${closing}`;
+ }
+
+ return [
+ opening,
+ ...printedChildren.map((child) =>
+ indentInsertedJsx({indent: unit, insertion: child}),
+ ),
+ closing,
+ ].join(endOfLine);
+ };
+
+ return printElement(element);
+};
diff --git a/packages/studio-codemods/src/split-jsx-sequence.ts b/packages/studio-codemods/src/split-jsx-sequence.ts
index c29185acb4..7ac687ef86 100644
--- a/packages/studio-codemods/src/split-jsx-sequence.ts
+++ b/packages/studio-codemods/src/split-jsx-sequence.ts
@@ -15,6 +15,7 @@ import {
hasSequenceTimingTraits,
type SequenceNodePathRemapping,
} from '@remotion/studio-shared';
+import type {namedTypes as AstNamedTypes} from 'ast-types';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {
@@ -25,11 +26,9 @@ import {
captureJsxNodePaths,
getNodePathRemappings,
} from './get-node-path-remappings';
-import {
- parseAst,
- parseAstForReadOnly,
- serializeAst,
-} from './sequence-props/parse-ast';
+import {printInsertedJsx} from './print-jsx';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
const {builders: b, namedTypes} = recast.types;
@@ -330,19 +329,74 @@ const insertAfter = (
return false;
};
-export const splitJsxSequence = async ({
+const indentContinuationLines = ({
+ indent,
+ source,
+}: {
+ indent: string;
+ source: string;
+}) => {
+ const endOfLine = source.includes('\r\n') ? '\r\n' : '\n';
+ return source.split(/\r?\n/).join(`${endOfLine}${indent}`);
+};
+
+const getSplitSourceEdit = ({
+ input,
+ left,
+ prettierConfigOverride,
+ right,
+ wrapInFragment,
+}: {
+ input: string;
+ left: JSXElement;
+ prettierConfigOverride: Record<string, unknown> | null;
+ right: JSXElement;
+ wrapInFragment: boolean;
+}) => {
+ if (!left.loc) {
+ throw new Error('Cannot split a JSX sequence without a source location');
+ }
+
+ const start = recastLocToOffset(input, left.loc.start);
+ const end = recastLocToOffset(input, left.loc.end);
+ const lineStart = input.lastIndexOf('\n', start - 1) + 1;
+ const beforeElement = input.slice(lineStart, start);
+ const lineIndent = beforeElement.match(/^\s*/)?.[0] ?? '';
+ const isOnlyElementOnLine = beforeElement.trim() === '';
+ const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const formattingConfig = prettierConfigOverride ?? null;
+ const print = (element: JSXElement | JSXFragment) =>
+ indentContinuationLines({
+ indent: lineIndent,
+ source: printInsertedJsx({
+ element: element as unknown as
+ | AstNamedTypes.JSXElement
+ | AstNamedTypes.JSXFragment,
+ input,
+ prettierConfigOverride: formattingConfig,
+ }),
+ });
+ const replacement = wrapInFragment
+ ? print(makeFragment(left, right))
+ : `${print(left)}${isOnlyElementOnLine ? `${endOfLine}${lineIndent}` : ' '}${print(right)}`;
+
+ return {end, replacement, start};
+};
+
+export const splitJsxSequence = ({
input,
nodePath,
sequenceKeys,
splitFrame,
- formatFile,
prettierConfigOverride,
}: {
input: string;
nodePath: SequenceNodePath;
sequenceKeys: string[];
splitFrame: number;
- 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}>;
@@ -425,29 +479,38 @@ export const splitJsxSequence = async ({
throw new Error('Cannot split JSX sequence with no parent');
}
+ const isJsxChild =
+ namedTypes.JSXElement.check(parentPath.node) ||
+ namedTypes.JSXFragment.check(parentPath.node);
if (!insertAfter(parentPath.node, jsxElement, right)) {
jsxPath.replace(makeFragment(jsxElement, right));
}
- const finalFile = serializeAst(ast);
- const {output, formatted} = await formatFile({
- contents: finalFile,
+ const sourceEdit = getSplitSourceEdit({
+ input,
+ left: jsxElement,
prettierConfigOverride: prettierConfigOverride ?? null,
+ right,
+ wrapInFragment: !isJsxChild,
});
+ const output =
+ input.slice(0, sourceEdit.start) +
+ sourceEdit.replacement +
+ input.slice(sourceEdit.end);
const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
});
- return {
+ return Promise.resolve({
output,
- formatted,
+ formatted: true,
nodeLabel: getJsxElementTagLabel(jsxElement),
logLine:
jsxElement.openingElement.loc?.start.line ??
jsxElement.loc?.start.line ??
1,
nodePathRemappings,
- };
+ });
};
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index 9a4c8a84c3..e283f904a6 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -1,6 +1,5 @@
import {splitJsxSequence as splitJsxSequenceCodemod} from '@remotion/studio-codemods';
import type {SequenceNodePath} from 'remotion';
-import {formatFileContent} from './format-file-content';
export const splitJsxSequence = ({
input,
@@ -20,10 +19,5 @@ export const splitJsxSequence = ({
nodePath,
sequenceKeys,
splitFrame,
- formatFile: ({contents, prettierConfigOverride: override}) =>
- formatFileContent({
- input: contents,
- prettierConfigOverride: override,
- }),
prettierConfigOverride,
});
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index b5f37c56a0..278ffb1f1a 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -14,7 +14,6 @@ import type {
SequenceNodePathRemapping,
} from '@remotion/studio-shared';
import type {SequenceNodePath} from 'remotion';
-import {formatFileContent} from '../codemods/format-file-content';
import {svgMarkupToJsx} from './svg-to-jsx';
const makeCodemodEnvironment = (
@@ -24,8 +23,6 @@ const makeCodemodEnvironment = (
extname: path.extname,
fileExists: (fileName) =>
fs.existsSync(fileName) && fs.statSync(fileName).isFile(),
- formatFile: ({contents, prettierConfigOverride}) =>
- formatFileContent({input: contents, prettierConfigOverride}),
isAbsolute: path.isAbsolute,
join: path.join,
pathSeparator: path.sep,
diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.ts
index f80a484463..981dc4ac84 100644
--- a/packages/studio-server/src/preview-server/routes/insert-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts
@@ -19,7 +19,6 @@ import {
normalizeElementSourceForComparison,
validateElementInstallPosition,
} from './element-install-plan';
-import {warnAboutPrettierOnce} from './log-updates/log-update';
import {
getCodemodTimingPrefix,
withSourceFileWriteQueue,
@@ -288,10 +287,6 @@ export const insertElementHandler: ApiHandler<
{indent: false, logLevel},
`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${plan.componentName}>`,
);
- if (!inserted.formatted) {
- warnAboutPrettierOnce(logLevel);
- }
-
printUndoHint(logLevel);
return {success: true, nodePathMutation};
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index 0fb6135ce4..cf9c7f472e 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -18,7 +18,6 @@ import {
pushToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
-import {warnAboutPrettierOnce} from './log-updates/log-update';
import {
getCodemodTimingPrefix,
withSourceFileWriteQueue,
@@ -248,7 +247,6 @@ export const insertJsxElementHandler: ApiHandler<
source,
oldContents,
output,
- formatted,
insertedNodePath,
logLine,
nodePathRemappings,
@@ -305,13 +303,9 @@ export const insertJsxElementHandler: ApiHandler<
{indent: false, logLevel},
`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Added ${elementLabel}`,
);
- if (!formatted) {
- warnAboutPrettierOnce(logLevel);
- }
-
RenderInternals.Log.verbose(
{indent: false, logLevel},
- `[insert-jsx-element] Wrote ${source}${formatted ? ' (formatted)' : ''}`,
+ `[insert-jsx-element] Wrote ${source}`,
);
printUndoHint(logLevel);
diff --git a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
index 93995bfdea..a9f5fc3963 100644
--- a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts
@@ -15,7 +15,6 @@ import {
pushToUndoStack,
suppressUndoStackInvalidation,
} from '../undo-stack';
-import {warnAboutPrettierOnce} from './log-updates/log-update';
import {
getCodemodTimingPrefix,
withSourceFileWriteQueue,
@@ -43,7 +42,7 @@ export const splitJsxSequenceHandler: ApiHandler<
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, formatted, nodeLabel, logLine, nodePathRemappings} =
+ const {output, nodeLabel, logLine, nodePathRemappings} =
await splitJsxSequence({
input: fileContents,
nodePath,
@@ -91,15 +90,9 @@ export const splitJsxSequenceHandler: ApiHandler<
`${locationLabel}`,
)} Split ${nodeLabel}`,
);
- if (!formatted) {
- warnAboutPrettierOnce(logLevel);
- }
-
RenderInternals.Log.verbose(
{indent: false, logLevel},
- `[split-jsx-sequence] Wrote ${fileRelativeToRoot}${
- formatted ? ' (formatted)' : ''
- }`,
+ `[split-jsx-sequence] Wrote ${fileRelativeToRoot}`,
);
printUndoHint(logLevel);
diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.ts
index fe04f23ce1..7438f302ec 100644
--- a/packages/studio-server/src/test/split-jsx-sequence.test.ts
+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts
@@ -2,6 +2,7 @@ import {expect, test} from 'bun:test';
import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';
+import {splitJsxSequence as splitJsxSequenceCodemod} from '@remotion/studio-codemods';
import {splitJsxSequence} from '../codemods/split-jsx-sequence';
import {
createFileWatcherRegistry,
@@ -113,6 +114,75 @@ test('splitJsxSequence splits finite duration and trimBefore', async () => {
);
});
+test('splitJsxSequence preserves surrounding formatting without calling Prettier', async () => {
+ const input = `const deliberatelyUnformatted = {value : true}
+
+export const Comp = () => {
+ return (
+ <>
+ <Sequence
+ name="clip"
+ from={0}
+ durationInFrames={50}
+ >
+ <div>Child</div>
+ </Sequence>
+ <Keep prop = {1}/>
+ </>
+ )
+}
+`;
+ let formatCalls = 0;
+ const {output} = await splitJsxSequenceCodemod({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Sequence'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ formatFile: () => {
+ formatCalls++;
+ throw new Error('Prettier should not be called when splitting a clip');
+ },
+ });
+
+ expect(formatCalls).toBe(0);
+ expect(output).toStartWith(
+ 'const deliberatelyUnformatted = {value : true}\n',
+ );
+ expect(output).toContain(
+ '<Sequence name="clip" from={0} durationInFrames={30}>\n',
+ );
+ expect(output).toContain(
+ '<Sequence name="clip" from={30} durationInFrames={20} trimBefore={30}>\n',
+ );
+ expect(output).toContain(' <Keep prop = {1}/>');
+ expect(output).toEndWith(' )\n}\n');
+});
+
+test('splitJsxSequence formats a split component root as a fragment', async () => {
+ const input = `export const Comp = () => <Sequence from={0} durationInFrames={50}><span>Hi</span></Sequence>;
+
+const keep = { value : true }
+`;
+ const {output} = await splitJsxSequenceCodemod({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Sequence'),
+ sequenceKeys: sequenceTimingKeys,
+ splitFrame: 30,
+ });
+
+ expect(output).toBe(`export const Comp = () => <>
+ <Sequence from={0} durationInFrames={30}>
+ <span>Hi</span>
+ </Sequence>
+ <Sequence from={30} durationInFrames={20} trimBefore={30}>
+ <span>Hi</span>
+ </Sequence>
+</>;
+
+const keep = { value : true }
+`);
+});
+
test('splitJsxSequence splits a video with a negative from', async () => {
const output = await split(
'<Video src="video.mov" from={-2644} trimBefore={272} />',