Skip to content

🎥 Make videos programmatically with React

Share Studio codemod source edit helpers

Jonny Burger94317a63ea47
diff --git a/packages/studio-codemods/src/composition-source-edits.ts b/packages/studio-codemods/src/composition-source-edits.ts
index e61740e03b..f6b42b8093 100644
--- a/packages/studio-codemods/src/composition-source-edits.ts
+++ b/packages/studio-codemods/src/composition-source-edits.ts
@@ -4,17 +4,18 @@ import {namedTypes} from 'ast-types';
import * as recast from 'recast';
import {getNodeSourceEdit} from './delete-jsx-node';
import {getCompositionId} from './duplicate-composition';
-import {
- applySourceEdits,
- getInsertImportSourceEdits,
- getInsertionRootSourceEdit,
- type SourceEdit,
-} from './insert-jsx-element';
+import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {applyCodemod, type Change} from './recast-mods';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type SourceEdit,
+} from './source-edits';
export const editCompositionInSource = ({
input,
@@ -30,11 +31,7 @@ export const editCompositionInSource = ({
const edits: SourceEdit[] = [];
let changesMade: Change[] = [];
if (codeMod.type === 'new-composition') {
- const snapshots = ast.program.body.flatMap((statement) =>
- statement.type === 'ImportDeclaration'
- ? [{declaration: statement, specifiers: [...statement.specifiers]}]
- : [],
- );
+ const snapshots = captureImportSnapshots(ast);
const result = applyCodemod({file: ast, codeMod});
changesMade = result.changesMade;
const {newAst} = result;
diff --git a/packages/studio-codemods/src/duplicate-composition.ts b/packages/studio-codemods/src/duplicate-composition.ts
index 95225359e9..f02a13a46d 100644
--- a/packages/studio-codemods/src/duplicate-composition.ts
+++ b/packages/studio-codemods/src/duplicate-composition.ts
@@ -7,16 +7,17 @@ import type {
} from '@babel/types';
import type {RecastCodemod} from '@remotion/studio-shared';
import * as recast from 'recast';
-import {
- applySourceEdits,
- getInsertImportSourceEdits,
- getInsertionRootSourceEdit,
- type SourceEdit,
-} from './insert-jsx-element';
+import {getInsertionRootSourceEdit} from './insert-jsx-element';
import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {ensureNamedImport} from './sequence-props/imports';
import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type SourceEdit,
+} from './source-edits';
const b = recast.types.builders;
@@ -219,11 +220,7 @@ export const duplicateCompositionInSource = ({
const ast = parseAst(input);
const changesMade: {description: string}[] = [];
const edits: SourceEdit[] = [];
- const snapshots = ast.program.body.flatMap((statement) =>
- statement.type === 'ImportDeclaration'
- ? [{declaration: statement, specifiers: [...statement.specifiers]}]
- : [],
- );
+ const snapshots = captureImportSnapshots(ast);
recast.types.visit(ast, {
visitJSXElement(astPath) {
diff --git a/packages/studio-codemods/src/function-source-edits.ts b/packages/studio-codemods/src/function-source-edits.ts
new file mode 100644
index 0000000000..90927094d4
--- /dev/null
+++ b/packages/studio-codemods/src/function-source-edits.ts
@@ -0,0 +1,266 @@
+import type {
+ BlockStatement,
+ File,
+ Function as BabelFunction,
+ Statement,
+} from '@babel/types';
+import type {namedTypes} from 'ast-types';
+import * as recast from 'recast';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {
+ getNodeEndIncludingSameLineComments,
+ type SourceEdit,
+} from './source-edits';
+import {
+ getEndOfLine,
+ getLineIndent,
+ indentContinuationLines,
+} from './source-style';
+
+export type FunctionNode = BabelFunction;
+
+export type FunctionSourceSnapshot = {
+ body: FunctionNode['body'];
+ functionNode: FunctionNode;
+ statements: Statement[] | null;
+};
+
+const isFunctionNode = (node: unknown): node is FunctionNode => {
+ return (
+ recast.types.namedTypes.FunctionDeclaration.check(node) ||
+ recast.types.namedTypes.FunctionExpression.check(node) ||
+ recast.types.namedTypes.ArrowFunctionExpression.check(node) ||
+ recast.types.namedTypes.ObjectMethod.check(node) ||
+ recast.types.namedTypes.ClassMethod.check(node) ||
+ recast.types.namedTypes.ClassPrivateMethod.check(node)
+ );
+};
+
+export const captureFunctionSourceSnapshots = (
+ ast: File,
+): FunctionSourceSnapshot[] => {
+ const snapshots: FunctionSourceSnapshot[] = [];
+ recast.types.visit(ast, {
+ visitFunction(path) {
+ if (!isFunctionNode(path.node)) {
+ this.traverse(path);
+ return undefined;
+ }
+
+ const functionNode = path.node;
+ snapshots.push({
+ body: functionNode.body,
+ functionNode,
+ statements:
+ functionNode.body.type === 'BlockStatement'
+ ? [...functionNode.body.body]
+ : null,
+ });
+ this.traverse(path);
+ return undefined;
+ },
+ });
+
+ return snapshots;
+};
+
+const getBodySourceRange = ({
+ body,
+ functionNode,
+ input,
+}: {
+ body: FunctionNode['body'];
+ functionNode: FunctionNode;
+ input: string;
+}): {end: number; start: number} | null => {
+ if (!body.loc) {
+ return null;
+ }
+
+ const bodyStart = recastLocToOffset(input, body.loc.start);
+ let start = bodyStart;
+ let end = recastLocToOffset(input, body.loc.end);
+ const leadingCommentStarts = (body.leadingComments ?? []).flatMap((comment) =>
+ comment.loc && recastLocToOffset(input, comment.loc.end) <= bodyStart
+ ? [recastLocToOffset(input, comment.loc.start)]
+ : [],
+ );
+ if (leadingCommentStarts.length > 0) {
+ start = Math.min(...leadingCommentStarts);
+ }
+
+ const extra = body.extra as
+ | {
+ parenthesized: boolean | null | undefined;
+ parenStart: number | null | undefined;
+ }
+ | null
+ | undefined;
+ if (extra?.parenthesized && typeof extra.parenStart === 'number') {
+ if (!functionNode.loc) {
+ return null;
+ }
+
+ start = Math.min(start, extra.parenStart);
+ end = recastLocToOffset(input, functionNode.loc.end);
+ }
+
+ return {end, start};
+};
+
+export const getFunctionSourceEditsForPrependedStatements = ({
+ indentationUnit,
+ input,
+ printNode,
+ reprintBlockBodies,
+ snapshots,
+}: {
+ indentationUnit: string;
+ input: string;
+ printNode: (node: namedTypes.Node) => string;
+ reprintBlockBodies: ReadonlySet<BlockStatement>;
+ snapshots: FunctionSourceSnapshot[];
+}): {coveredRanges: {end: number; start: number}[]; edits: SourceEdit[]} => {
+ const coveredRanges: {end: number; start: number}[] = [];
+ const edits: SourceEdit[] = [];
+ const endOfLine = getEndOfLine(input);
+
+ for (const snapshot of snapshots) {
+ const {body: originalBody, functionNode, statements} = snapshot;
+ const shouldReprintBody =
+ functionNode.body !== originalBody ||
+ (originalBody.type === 'BlockStatement' &&
+ reprintBlockBodies.has(originalBody));
+ if (shouldReprintBody) {
+ const range = getBodySourceRange({
+ body: originalBody,
+ functionNode,
+ input,
+ });
+ if (!range) {
+ continue;
+ }
+
+ edits.push({
+ ...range,
+ replacement: indentContinuationLines({
+ indent: getLineIndent({input, offset: range.start}),
+ input,
+ printed: printNode(functionNode.body as unknown as namedTypes.Node),
+ }),
+ });
+ coveredRanges.push(range);
+ continue;
+ }
+
+ if (originalBody.type !== 'BlockStatement' || statements === null) {
+ continue;
+ }
+
+ const originalStatements = new Set(statements);
+ const insertedStatements = originalBody.body.filter(
+ (statement) => !originalStatements.has(statement),
+ );
+ const unchangedStatements = originalBody.body.slice(
+ insertedStatements.length,
+ );
+ const onlyPrependedStatementsChanged =
+ originalBody.body
+ .slice(0, insertedStatements.length)
+ .every((statement) => !originalStatements.has(statement)) &&
+ unchangedStatements.length === statements.length &&
+ unchangedStatements.every(
+ (statement, index) => statement === statements[index],
+ );
+ if (!onlyPrependedStatementsChanged) {
+ throw new Error(
+ 'Function source edits only support prepended statements unless the block body is explicitly reprinted',
+ );
+ }
+
+ if (insertedStatements.length === 0 || !originalBody.loc) {
+ continue;
+ }
+
+ const blockStart = recastLocToOffset(input, originalBody.loc.start);
+ const blockEnd = recastLocToOffset(input, originalBody.loc.end);
+ const openingBrace = input.indexOf('{', blockStart);
+ if (openingBrace === -1 || openingBrace >= blockEnd) {
+ continue;
+ }
+
+ const firstOriginalStatement = statements[0];
+ const firstOriginalOffset = firstOriginalStatement?.loc
+ ? recastLocToOffset(input, firstOriginalStatement.loc.start)
+ : null;
+ const lastDirective = originalBody.directives?.at(-1);
+ const insertionStart = lastDirective
+ ? (getNodeEndIncludingSameLineComments({
+ input,
+ node: lastDirective,
+ }) ?? openingBrace + 1)
+ : openingBrace + 1;
+ const leadingCommentOffsets = (
+ firstOriginalStatement?.leadingComments ?? []
+ ).flatMap((comment) =>
+ comment.loc ? [recastLocToOffset(input, comment.loc.start)] : [],
+ );
+ const firstKnownContentOffset = [
+ ...(firstOriginalOffset === null ? [] : [firstOriginalOffset]),
+ ...leadingCommentOffsets,
+ ].reduce<number | null>(
+ (earliest, candidate) =>
+ candidate < insertionStart
+ ? earliest
+ : Math.min(earliest ?? candidate, candidate),
+ null,
+ );
+ const gapToKnownContent = input.slice(
+ insertionStart,
+ firstKnownContentOffset ?? blockEnd,
+ );
+ const immediateContentIndex = gapToKnownContent.search(/\S/);
+ const firstContentOffset =
+ immediateContentIndex === -1
+ ? firstKnownContentOffset
+ : insertionStart + immediateContentIndex;
+ const gap =
+ firstContentOffset === null
+ ? ''
+ : input.slice(insertionStart, firstContentOffset);
+ const originalStartsOnNewLine = /\r?\n/.test(gap);
+ const contentIsClosingBrace =
+ firstContentOffset !== null && input[firstContentOffset] === '}';
+ const statementIndent =
+ firstContentOffset !== null &&
+ originalStartsOnNewLine &&
+ !contentIsClosingBrace
+ ? getLineIndent({input, offset: firstContentOffset})
+ : `${getLineIndent({input, offset: blockStart})}${indentationUnit}`;
+ const printedStatements = insertedStatements
+ .map((statement) => printNode(statement as unknown as namedTypes.Node))
+ .join(`${endOfLine}${statementIndent}`);
+ edits.push({
+ end: originalStartsOnNewLine
+ ? insertionStart
+ : (firstContentOffset ?? insertionStart),
+ replacement: originalStartsOnNewLine
+ ? `${endOfLine}${statementIndent}${printedStatements}`
+ : `${endOfLine}${statementIndent}${printedStatements}${endOfLine}${statementIndent}`,
+ start: insertionStart,
+ });
+ }
+
+ return {
+ coveredRanges,
+ edits: edits.filter(
+ (edit) =>
+ !coveredRanges.some(
+ (range) =>
+ edit.start >= range.start &&
+ edit.end <= range.end &&
+ (edit.start !== range.start || edit.end !== range.end),
+ ),
+ ),
+ };
+};
diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.ts
index be33aaaa80..e128f60653 100644
--- a/packages/studio-codemods/src/insert-jsx-element.ts
+++ b/packages/studio-codemods/src/insert-jsx-element.ts
@@ -31,11 +31,7 @@ import {
captureJsxNodePaths,
getNodePathRemappings,
} from './get-node-path-remappings';
-import {
- getIndentationUnit,
- indentInsertedJsx,
- printInsertedJsx,
-} from './print-jsx';
+import {indentInsertedJsx, printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {
ensureNamedImport,
@@ -43,6 +39,13 @@ import {
insertImportDeclaration,
} from './sequence-props/imports';
import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type SourceEdit,
+} from './source-edits';
+import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
import {stripParenthesizedExtra} from './strip-parenthesized-extra';
import {parseValueExpression} from './update-nested-prop';
@@ -173,17 +176,6 @@ type SourceLocation = {
column: number;
};
-export type SourceEdit = {
- end: number;
- replacement: string;
- start: number;
-};
-
-type ImportSnapshot = {
- declaration: ImportDeclaration;
- specifiers: NonNullable<ImportDeclaration['specifiers']>;
-};
-
type NodeWithLocation = {
loc?: {
start: {
@@ -2098,319 +2090,6 @@ const getNullComponentRoot = (
: null;
};
-const getLineIndent = (input: string, offset: number) => {
- const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
- return input.slice(lineStart, offset).match(/^\s*/)?.[0] ?? '';
-};
-
-const renderImportSpecifier = (
- specifier: NonNullable<ImportDeclaration['specifiers']>[number],
-) => {
- if (specifier.type === 'ImportDefaultSpecifier') {
- return specifier.local.name;
- }
-
- if (specifier.type === 'ImportNamespaceSpecifier') {
- return `* as ${specifier.local.name}`;
- }
-
- const importedName = getImportedName(specifier);
- const localName = specifier.local?.name ?? importedName;
- const rendered =
- importedName === localName
- ? importedName
- : `${importedName} as ${localName}`;
- return specifier.importKind === 'type' ? `type ${rendered}` : rendered;
-};
-
-const renderImportDeclaration = ({
- bracketSpacing,
- declaration,
- quote,
- semicolon,
-}: {
- bracketSpacing: boolean;
- declaration: ImportDeclaration;
- quote: '"' | "'";
- semicolon: string;
-}) => {
- const specifiers = declaration.specifiers ?? [];
- const defaultSpecifier = specifiers.find(
- (specifier) => specifier.type === 'ImportDefaultSpecifier',
- );
- const namespaceSpecifier = specifiers.find(
- (specifier) => specifier.type === 'ImportNamespaceSpecifier',
- );
- const namedSpecifiers = specifiers.filter(
- (specifier) => specifier.type === 'ImportSpecifier',
- );
- const parts = [
- ...(defaultSpecifier ? [renderImportSpecifier(defaultSpecifier)] : []),
- ...(namespaceSpecifier ? [renderImportSpecifier(namespaceSpecifier)] : []),
- ...(namedSpecifiers.length
- ? [
- `{${bracketSpacing ? ' ' : ''}${namedSpecifiers
- .map(renderImportSpecifier)
- .join(', ')}${bracketSpacing ? ' ' : ''}}`,
- ]
- : []),
- ];
- const source =
- quote === '"'
- ? JSON.stringify(declaration.source.value)
- : `'${declaration.source.value.replaceAll("'", "\\'")}'`;
- return `import ${parts.join(', ')} from ${source}${semicolon}`;
-};
-
-const getImportBracketSpacing = ({
- declaration,
- input,
- prettierConfigOverride,
-}: {
- declaration: ImportDeclaration | null;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
-}) => {
- if (declaration?.loc) {
- const source = input.slice(
- recastLocToOffset(input, declaration.loc.start),
- recastLocToOffset(input, declaration.loc.end),
- );
- const openingBrace = source.indexOf('{');
- const closingBrace = source.lastIndexOf('}');
- if (openingBrace !== -1 && closingBrace > openingBrace) {
- return (
- /\s/.test(source[openingBrace + 1]) &&
- /\s/.test(source[closingBrace - 1])
- );
- }
- }
-
- return prettierConfigOverride?.bracketSpacing !== false;
-};
-
-export const getInsertImportSourceEdits = ({
- ast,
- input,
- prettierConfigOverride,
- snapshots,
-}: {
- ast: File;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
- snapshots: ImportSnapshot[];
-}): SourceEdit[] => {
- const edits: SourceEdit[] = [];
- const snapshotByDeclaration = new Map(
- snapshots.map((snapshot) => [snapshot.declaration, snapshot]),
- );
- const importWithNamedSpecifiers =
- snapshots.find((snapshot) =>
- snapshot.specifiers.some(
- (specifier) => specifier.type === 'ImportSpecifier',
- ),
- )?.declaration ?? null;
- const fallbackBracketSpacing = getImportBracketSpacing({
- declaration: importWithNamedSpecifiers,
- input,
- prettierConfigOverride,
- });
- const newDeclarations: ImportDeclaration[] = [];
-
- for (const statement of ast.program.body) {
- if (statement.type !== 'ImportDeclaration') {
- continue;
- }
-
- const snapshot = snapshotByDeclaration.get(statement);
- if (!snapshot) {
- newDeclarations.push(statement);
- continue;
- }
-
- const addedSpecifiers = (statement.specifiers ?? []).filter(
- (specifier) => !snapshot.specifiers.includes(specifier),
- );
- if (addedSpecifiers.length === 0) {
- continue;
- }
-
- if (
- addedSpecifiers.every(
- (specifier) => specifier.type === 'ImportDefaultSpecifier',
- ) &&
- statement.loc
- ) {
- const importStart = recastLocToOffset(input, statement.loc.start);
- const importPrefix = input.slice(importStart).match(/^import\s+/)?.[0];
- if (!importPrefix) {
- throw new Error('Could not locate the import prefix to update');
- }
-
- const offset = importStart + importPrefix.length;
- edits.push({
- end: offset,
- replacement: `${addedSpecifiers.map(renderImportSpecifier).join(', ')}, `,
- start: offset,
- });
- continue;
- }
-
- if (
- addedSpecifiers.some((specifier) => specifier.type !== 'ImportSpecifier')
- ) {
- if (!statement.loc) {
- throw new Error('Could not locate the import to update');
- }
-
- const fullImportStart = recastLocToOffset(input, statement.loc.start);
- const fullImportEnd = recastLocToOffset(input, statement.loc.end);
- const fullImport = input.slice(fullImportStart, fullImportEnd);
- edits.push({
- end: fullImportEnd,
- replacement: renderImportDeclaration({
- bracketSpacing: getImportBracketSpacing({
- declaration: statement,
- input,
- prettierConfigOverride,
- }),
- declaration: statement,
- quote: fullImport.includes('"') ? '"' : "'",
- semicolon: fullImport.trimEnd().endsWith(';') ? ';' : '',
- }),
- start: fullImportStart,
- });
- continue;
- }
-
- const rendered = addedSpecifiers.map(renderImportSpecifier).join(', ');
- const lastNamedSpecifier = snapshot.specifiers.findLast(
- (specifier) => specifier.type === 'ImportSpecifier',
- );
- if (lastNamedSpecifier?.loc) {
- const offset = recastLocToOffset(input, lastNamedSpecifier.loc.end);
- edits.push({
- end: offset,
- replacement: `, ${rendered}`,
- start: offset,
- });
- continue;
- }
-
- const defaultSpecifier = snapshot.specifiers.find(
- (specifier) => specifier.type === 'ImportDefaultSpecifier',
- );
- if (defaultSpecifier?.loc) {
- const offset = recastLocToOffset(input, defaultSpecifier.loc.end);
- edits.push({
- end: offset,
- replacement: `, {${fallbackBracketSpacing ? ' ' : ''}${rendered}${fallbackBracketSpacing ? ' ' : ''}}`,
- start: offset,
- });
- continue;
- }
-
- if (!statement.loc) {
- throw new Error('Could not locate the import to update');
- }
-
- const start = recastLocToOffset(input, statement.loc.start);
- const end = recastLocToOffset(input, statement.loc.end);
- const original = input.slice(start, end);
- edits.push({
- end,
- replacement: renderImportDeclaration({
- bracketSpacing: fallbackBracketSpacing,
- declaration: statement,
- quote: original.includes('"') ? '"' : "'",
- semicolon: original.trimEnd().endsWith(';') ? ';' : '',
- }),
- start,
- });
- }
-
- if (newDeclarations.length > 0) {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- const firstImport = snapshots[0]?.declaration;
- const firstImportSource = firstImport?.source.loc
- ? input.slice(
- recastLocToOffset(input, firstImport.source.loc.start),
- recastLocToOffset(input, firstImport.source.loc.end),
- )
- : null;
- const quote = firstImportSource?.startsWith('"')
- ? ('"' as const)
- : firstImportSource?.startsWith("'") ||
- prettierConfigOverride?.singleQuote === true
- ? ("'" as const)
- : ('"' as const);
- const semicolon = firstImport?.loc
- ? input
- .slice(
- recastLocToOffset(input, firstImport.loc.start),
- recastLocToOffset(input, firstImport.loc.end),
- )
- .trimEnd()
- .endsWith(';')
- ? ';'
- : ''
- : (() => {
- const styleNode =
- ast.program.directives.at(-1) ?? ast.program.body.at(-1);
- if (!styleNode?.loc) {
- return ';';
- }
-
- return input
- .slice(
- recastLocToOffset(input, styleNode.loc.start),
- recastLocToOffset(input, styleNode.loc.end),
- )
- .trimEnd()
- .endsWith(';')
- ? ';'
- : '';
- })();
- const rendered = newDeclarations
- .map((declaration) =>
- renderImportDeclaration({
- bracketSpacing: fallbackBracketSpacing,
- declaration,
- quote,
- semicolon,
- }),
- )
- .join(endOfLine);
- if (firstImport?.loc) {
- const offset = recastLocToOffset(input, firstImport.loc.start);
- edits.push({
- end: offset,
- replacement: `${rendered}${endOfLine}`,
- start: offset,
- });
- } else {
- const lastDirective = ast.program.directives.at(-1);
- const insertionAnchor = lastDirective ?? ast.program.interpreter;
- if (insertionAnchor?.loc) {
- const offset = recastLocToOffset(input, insertionAnchor.loc.end);
- edits.push({
- end: offset,
- replacement: `${endOfLine}${rendered}`,
- start: offset,
- });
- } else {
- edits.push({
- end: 0,
- replacement: `${rendered}${endOfLine}`,
- start: 0,
- });
- }
- }
- }
-
- return edits;
-};
-
const indentExistingJsx = ({
indent,
original,
@@ -2429,7 +2108,7 @@ const indentExistingJsx = ({
return `${indent}${line.startsWith(originalIndent) ? line.slice(originalIndent.length) : line.trimStart()}`;
})
- .join(original.includes('\r\n') ? '\r\n' : '\n');
+ .join(getEndOfLine(original));
};
const getJsxIdentifierName = (element: namedTypes.JSXElement) => {
@@ -2478,7 +2157,7 @@ const getSolidInsertionSource = ({
} | null;
width: number;
}) => {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const endOfLine = getEndOfLine(input);
const unit = getIndentationUnit(input, prettierConfigOverride);
const solid = [
`<${getJsxIdentifierName(element)}`,
@@ -2578,7 +2257,7 @@ export const getInsertionRootSourceEdit = ({
prettierConfigOverride: Record<string, unknown> | null;
root: namedTypes.JSXElement | namedTypes.JSXFragment | null;
}): SourceEdit => {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const endOfLine = getEndOfLine(input);
const unit = getIndentationUnit(input, prettierConfigOverride);
if (nullRoot) {
@@ -2588,7 +2267,7 @@ export const getInsertionRootSourceEdit = ({
const nullStart = recastLocToOffset(input, nullRoot.loc.start);
const nullEnd = recastLocToOffset(input, nullRoot.loc.end);
- const nullIndent = getLineIndent(input, nullStart);
+ const nullIndent = getLineIndent({input, offset: nullStart});
return {
end: nullEnd,
replacement: [
@@ -2622,7 +2301,7 @@ export const getInsertionRootSourceEdit = ({
root.openingElement.loc.start,
);
const openingEnd = recastLocToOffset(input, root.openingElement.loc.end);
- const openingIndent = getLineIndent(input, openingStart);
+ const openingIndent = getLineIndent({input, offset: openingStart});
return {
start: openingStart,
end: openingEnd,
@@ -2639,7 +2318,10 @@ export const getInsertionRootSourceEdit = ({
const beforeClosing = input.slice(lineStart, closingStart);
const closingIndent = /^\s*$/.test(beforeClosing)
? beforeClosing
- : getLineIndent(input, recastLocToOffset(input, root.loc.start));
+ : getLineIndent({
+ input,
+ offset: recastLocToOffset(input, root.loc.start),
+ });
if (/^\s*$/.test(beforeClosing) && lineStart > 0) {
return {
end: closingStart,
@@ -2663,7 +2345,7 @@ export const getInsertionRootSourceEdit = ({
const start = recastLocToOffset(input, root.loc.start);
const end = recastLocToOffset(input, root.loc.end);
- const indent = getLineIndent(input, start);
+ const indent = getLineIndent({input, offset: start});
const original = input.slice(start, end);
const existingRoot = indentExistingJsx({
indent: `${indent}${unit}`,
@@ -2683,29 +2365,6 @@ export const getInsertionRootSourceEdit = ({
};
};
-export const applySourceEdits = ({
- edits,
- input,
-}: {
- edits: SourceEdit[];
- input: string;
-}) => {
- const sorted = edits.slice().sort((left, right) => right.start - left.start);
- let output = input;
- let previousStart = input.length + 1;
- for (const edit of sorted) {
- if (edit.end > previousStart) {
- throw new Error('Overlapping JSX insertion source ranges');
- }
-
- output =
- output.slice(0, edit.start) + edit.replacement + output.slice(edit.end);
- previousStart = edit.start;
- }
-
- return output;
-};
-
const canAddSequenceToComponent = ({
ast,
exportName,
@@ -3219,17 +2878,7 @@ export const insertJsxElementIntoComposition = async ({
const nullRootBeforeInsertion = componentDeclaration
? getNullComponentRoot(componentDeclaration)
: null;
- const importSnapshots: ImportSnapshot[] = ast.program.body.flatMap(
- (statement) =>
- statement.type === 'ImportDeclaration'
- ? [
- {
- declaration: statement,
- specifiers: [...(statement.specifiers ?? [])],
- },
- ]
- : [],
- );
+ const importSnapshots = captureImportSnapshots(ast);
if (
element.type === 'composition' &&
element.compositionId === compositionId
diff --git a/packages/studio-codemods/src/print-jsx.ts b/packages/studio-codemods/src/print-jsx.ts
index e47a62e689..35916ef71a 100644
--- a/packages/studio-codemods/src/print-jsx.ts
+++ b/packages/studio-codemods/src/print-jsx.ts
@@ -1,5 +1,10 @@
import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
+import {
+ getIndentationUnit,
+ getObjectCurlySpacing,
+ getPreferredQuote,
+} from './source-style';
const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
@@ -30,67 +35,6 @@ const escapeJsxStringAttribute = (value: string) => {
});
};
-export const getPreferredQuote = (
- input: string,
- prettierConfigOverride: Record<string, unknown> | null,
-) => {
- if (typeof prettierConfigOverride?.singleQuote === 'boolean') {
- return prettierConfigOverride.singleQuote ? 'single' : 'double';
- }
-
- const importQuote =
- input.match(/\bfrom\s+(['"])/)?.[1] ??
- input.match(/^\s*import\s+(['"])/m)?.[1];
- if (importQuote) {
- return importQuote === "'" ? 'single' : 'double';
- }
-
- const singleQuotedStrings = input.match(/'(?:\\.|[^'\\])*'/g)?.length ?? 0;
- const doubleQuotedStrings = input.match(/"(?:\\.|[^"\\])*"/g)?.length ?? 0;
- return singleQuotedStrings > doubleQuotedStrings ? 'single' : 'double';
-};
-
-export const getObjectCurlySpacing = (
- input: string,
- prettierConfigOverride: Record<string, unknown> | null,
-) => {
- if (typeof prettierConfigOverride?.bracketSpacing === 'boolean') {
- return prettierConfigOverride.bracketSpacing;
- }
-
- const namedImport = input.match(/\bimport\s*{([^}\n]*)}/);
- if (namedImport) {
- return /^\s/.test(namedImport[1]) && /\s$/.test(namedImport[1]);
- }
-
- return true;
-};
-
-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,
diff --git a/packages/studio-codemods/src/recast-loc-to-offset.ts b/packages/studio-codemods/src/recast-loc-to-offset.ts
index ed1b4e7d0d..0a6aef72a0 100644
--- a/packages/studio-codemods/src/recast-loc-to-offset.ts
+++ b/packages/studio-codemods/src/recast-loc-to-offset.ts
@@ -14,7 +14,9 @@ export const recastLocToOffset = (
const line = lines[loc.line - 1];
let column = 0;
- for (let i = 0; i < line.length; i++) {
+ const firstSourceCharacter =
+ loc.line === 1 && line.startsWith('\uFEFF') ? 1 : 0;
+ for (let i = firstSourceCharacter; i < line.length; i++) {
if (column >= loc.column) {
return offset + i;
}
diff --git a/packages/studio-codemods/src/source-edits.ts b/packages/studio-codemods/src/source-edits.ts
new file mode 100644
index 0000000000..f9d760c1a5
--- /dev/null
+++ b/packages/studio-codemods/src/source-edits.ts
@@ -0,0 +1,451 @@
+import type {File, ImportDeclaration, Node} from '@babel/types';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {getImportedName} from './sequence-props/imports';
+import {getEndOfLine, getPreferredQuote} from './source-style';
+
+export type SourceEdit = {
+ end: number;
+ replacement: string;
+ start: number;
+};
+
+export type ImportSnapshot = {
+ declaration: ImportDeclaration;
+ specifiers: NonNullable<ImportDeclaration['specifiers']>;
+};
+
+export const getNodeEndIncludingSameLineComments = ({
+ input,
+ node,
+}: {
+ input: string;
+ node: Node;
+}): number | null => {
+ if (!node.loc) {
+ return null;
+ }
+
+ const nodeEnd = recastLocToOffset(input, node.loc.end);
+ return (node.trailingComments ?? []).reduce((end, comment) => {
+ if (
+ !comment.loc ||
+ comment.loc.start.line !== node.loc?.end.line ||
+ recastLocToOffset(input, comment.loc.start) < nodeEnd
+ ) {
+ return end;
+ }
+
+ return Math.max(end, recastLocToOffset(input, comment.loc.end));
+ }, nodeEnd);
+};
+
+const getLeadingFileHeaderEnd = ({
+ ast,
+ input,
+ minimumOffset,
+}: {
+ ast: File;
+ input: string;
+ minimumOffset: number;
+}): number | null => {
+ const firstOriginalStatement = ast.program.body
+ .flatMap((statement) =>
+ statement.loc
+ ? [
+ {
+ statement,
+ start: recastLocToOffset(input, statement.loc.start),
+ },
+ ]
+ : [],
+ )
+ .sort((left, right) => left.start - right.start)[0]?.statement;
+ const leadingComments = firstOriginalStatement?.leadingComments ?? [];
+ const lastHeaderCommentIndex = leadingComments.findLastIndex((comment) =>
+ /(?:@ts-(?:no)?check\b|@flow\b|@jsx\b|@license\b|@generated\b|copyright\b|eslint-disable(?!-(?:next-)?line\b)\b|\/\s*<(?:reference|amd-module|amd-dependency)\b)/i.test(
+ comment.value,
+ ),
+ );
+ if (lastHeaderCommentIndex === -1) {
+ return null;
+ }
+
+ return leadingComments
+ .slice(0, lastHeaderCommentIndex + 1)
+ .reduce<number | null>((latestEnd, comment) => {
+ if (!comment.loc) {
+ return latestEnd;
+ }
+
+ const commentStart = recastLocToOffset(input, comment.loc.start);
+ if (commentStart < minimumOffset) {
+ return latestEnd;
+ }
+
+ return Math.max(
+ latestEnd ?? minimumOffset,
+ recastLocToOffset(input, comment.loc.end),
+ );
+ }, null);
+};
+
+export const captureImportSnapshots = (ast: File): ImportSnapshot[] =>
+ ast.program.body.flatMap((statement) =>
+ statement.type === 'ImportDeclaration'
+ ? [
+ {
+ declaration: statement,
+ specifiers: [...(statement.specifiers ?? [])],
+ },
+ ]
+ : [],
+ );
+
+const renderImportSpecifier = (
+ specifier: NonNullable<ImportDeclaration['specifiers']>[number],
+) => {
+ if (specifier.type === 'ImportDefaultSpecifier') {
+ return specifier.local.name;
+ }
+
+ if (specifier.type === 'ImportNamespaceSpecifier') {
+ return `* as ${specifier.local.name}`;
+ }
+
+ const importedName = getImportedName(specifier);
+ const localName = specifier.local?.name ?? importedName;
+ const rendered =
+ importedName === localName
+ ? importedName
+ : `${importedName} as ${localName}`;
+ return specifier.importKind === 'type' ? `type ${rendered}` : rendered;
+};
+
+const renderImportDeclaration = ({
+ bracketSpacing,
+ declaration,
+ quote,
+ semicolon,
+}: {
+ bracketSpacing: boolean;
+ declaration: ImportDeclaration;
+ quote: '"' | "'";
+ semicolon: string;
+}) => {
+ const specifiers = declaration.specifiers ?? [];
+ const defaultSpecifier = specifiers.find(
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
+ );
+ const namespaceSpecifier = specifiers.find(
+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',
+ );
+ const namedSpecifiers = specifiers.filter(
+ (specifier) => specifier.type === 'ImportSpecifier',
+ );
+ const parts = [
+ ...(defaultSpecifier ? [renderImportSpecifier(defaultSpecifier)] : []),
+ ...(namespaceSpecifier ? [renderImportSpecifier(namespaceSpecifier)] : []),
+ ...(namedSpecifiers.length
+ ? [
+ `{${bracketSpacing ? ' ' : ''}${namedSpecifiers
+ .map(renderImportSpecifier)
+ .join(', ')}${bracketSpacing ? ' ' : ''}}`,
+ ]
+ : []),
+ ];
+ const source =
+ quote === '"'
+ ? JSON.stringify(declaration.source.value)
+ : `'${declaration.source.value.replaceAll("'", "\\'")}'`;
+ return `import ${parts.join(', ')} from ${source}${semicolon}`;
+};
+
+const getImportBracketSpacing = ({
+ declaration,
+ input,
+ prettierConfigOverride,
+}: {
+ declaration: ImportDeclaration | null;
+ input: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+}) => {
+ if (declaration?.loc) {
+ const source = input.slice(
+ recastLocToOffset(input, declaration.loc.start),
+ recastLocToOffset(input, declaration.loc.end),
+ );
+ const openingBrace = source.indexOf('{');
+ const closingBrace = source.lastIndexOf('}');
+ if (openingBrace !== -1 && closingBrace > openingBrace) {
+ return (
+ /\s/.test(source[openingBrace + 1]) &&
+ /\s/.test(source[closingBrace - 1])
+ );
+ }
+ }
+
+ return prettierConfigOverride?.bracketSpacing !== false;
+};
+
+export const getInsertImportSourceEdits = ({
+ ast,
+ input,
+ prettierConfigOverride,
+ snapshots,
+}: {
+ ast: File;
+ input: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ snapshots: ImportSnapshot[];
+}): SourceEdit[] => {
+ const edits: SourceEdit[] = [];
+ const snapshotByDeclaration = new Map(
+ snapshots.map((snapshot) => [snapshot.declaration, snapshot]),
+ );
+ const importWithNamedSpecifiers =
+ snapshots.find((snapshot) =>
+ snapshot.specifiers.some(
+ (specifier) => specifier.type === 'ImportSpecifier',
+ ),
+ )?.declaration ?? null;
+ const fallbackBracketSpacing = getImportBracketSpacing({
+ declaration: importWithNamedSpecifiers,
+ input,
+ prettierConfigOverride,
+ });
+ const newDeclarations: ImportDeclaration[] = [];
+
+ for (const statement of ast.program.body) {
+ if (statement.type !== 'ImportDeclaration') {
+ continue;
+ }
+
+ const snapshot = snapshotByDeclaration.get(statement);
+ if (!snapshot) {
+ newDeclarations.push(statement);
+ continue;
+ }
+
+ const addedSpecifiers = (statement.specifiers ?? []).filter(
+ (specifier) => !snapshot.specifiers.includes(specifier),
+ );
+ if (addedSpecifiers.length === 0) {
+ continue;
+ }
+
+ if (
+ addedSpecifiers.every(
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
+ ) &&
+ statement.loc
+ ) {
+ const importStart = recastLocToOffset(input, statement.loc.start);
+ const importPrefix = input.slice(importStart).match(/^import\s+/)?.[0];
+ if (!importPrefix) {
+ throw new Error('Could not locate the import prefix to update');
+ }
+
+ const offset = importStart + importPrefix.length;
+ edits.push({
+ end: offset,
+ replacement: `${addedSpecifiers.map(renderImportSpecifier).join(', ')}, `,
+ start: offset,
+ });
+ continue;
+ }
+
+ if (
+ addedSpecifiers.some((specifier) => specifier.type !== 'ImportSpecifier')
+ ) {
+ if (!statement.loc) {
+ throw new Error('Could not locate the import to update');
+ }
+
+ const fullImportStart = recastLocToOffset(input, statement.loc.start);
+ const fullImportEnd = recastLocToOffset(input, statement.loc.end);
+ const fullImport = input.slice(fullImportStart, fullImportEnd);
+ edits.push({
+ end: fullImportEnd,
+ replacement: renderImportDeclaration({
+ bracketSpacing: getImportBracketSpacing({
+ declaration: statement,
+ input,
+ prettierConfigOverride,
+ }),
+ declaration: statement,
+ quote: fullImport.includes('"') ? '"' : "'",
+ semicolon: fullImport.trimEnd().endsWith(';') ? ';' : '',
+ }),
+ start: fullImportStart,
+ });
+ continue;
+ }
+
+ const rendered = addedSpecifiers.map(renderImportSpecifier).join(', ');
+ const lastNamedSpecifier = snapshot.specifiers.findLast(
+ (specifier) => specifier.type === 'ImportSpecifier',
+ );
+ if (lastNamedSpecifier?.loc) {
+ const offset = recastLocToOffset(input, lastNamedSpecifier.loc.end);
+ edits.push({
+ end: offset,
+ replacement: `, ${rendered}`,
+ start: offset,
+ });
+ continue;
+ }
+
+ const defaultSpecifier = snapshot.specifiers.find(
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
+ );
+ if (defaultSpecifier?.loc) {
+ const offset = recastLocToOffset(input, defaultSpecifier.loc.end);
+ edits.push({
+ end: offset,
+ replacement: `, {${fallbackBracketSpacing ? ' ' : ''}${rendered}${fallbackBracketSpacing ? ' ' : ''}}`,
+ start: offset,
+ });
+ continue;
+ }
+
+ if (!statement.loc) {
+ throw new Error('Could not locate the import to update');
+ }
+
+ const start = recastLocToOffset(input, statement.loc.start);
+ const end = recastLocToOffset(input, statement.loc.end);
+ const original = input.slice(start, end);
+ edits.push({
+ end,
+ replacement: renderImportDeclaration({
+ bracketSpacing: fallbackBracketSpacing,
+ declaration: statement,
+ quote: original.includes('"') ? '"' : "'",
+ semicolon: original.trimEnd().endsWith(';') ? ';' : '',
+ }),
+ start,
+ });
+ }
+
+ if (newDeclarations.length > 0) {
+ const endOfLine = getEndOfLine(input);
+ const firstImport = snapshots[0]?.declaration;
+ const firstImportSource = firstImport?.source.loc
+ ? input.slice(
+ recastLocToOffset(input, firstImport.source.loc.start),
+ recastLocToOffset(input, firstImport.source.loc.end),
+ )
+ : null;
+ const quote = firstImportSource?.startsWith('"')
+ ? ('"' as const)
+ : firstImportSource?.startsWith("'") ||
+ getPreferredQuote(input, prettierConfigOverride) === 'single'
+ ? ("'" as const)
+ : ('"' as const);
+ const semicolon = firstImport?.loc
+ ? input
+ .slice(
+ recastLocToOffset(input, firstImport.loc.start),
+ recastLocToOffset(input, firstImport.loc.end),
+ )
+ .trimEnd()
+ .endsWith(';')
+ ? ';'
+ : ''
+ : (() => {
+ const styleNode =
+ ast.program.directives.at(-1) ?? ast.program.body.at(-1);
+ if (!styleNode?.loc) {
+ return ';';
+ }
+
+ return input
+ .slice(
+ recastLocToOffset(input, styleNode.loc.start),
+ recastLocToOffset(input, styleNode.loc.end),
+ )
+ .trimEnd()
+ .endsWith(';')
+ ? ';'
+ : '';
+ })();
+ const rendered = newDeclarations
+ .map((declaration) =>
+ renderImportDeclaration({
+ bracketSpacing: fallbackBracketSpacing,
+ declaration,
+ quote,
+ semicolon,
+ }),
+ )
+ .join(endOfLine);
+ if (firstImport?.loc) {
+ const offset = recastLocToOffset(input, firstImport.loc.start);
+ edits.push({
+ end: offset,
+ replacement: `${rendered}${endOfLine}`,
+ start: offset,
+ });
+ } else {
+ const lastDirective = ast.program.directives.at(-1);
+ const insertionAnchor = lastDirective ?? ast.program.interpreter;
+ const byteOrderMarkOffset = input.startsWith('\uFEFF') ? 1 : 0;
+ const anchorEnd = insertionAnchor
+ ? getNodeEndIncludingSameLineComments({
+ input,
+ node: insertionAnchor,
+ })
+ : null;
+ const minimumOffset = anchorEnd ?? byteOrderMarkOffset;
+ const fileHeaderEnd = getLeadingFileHeaderEnd({
+ ast,
+ input,
+ minimumOffset,
+ });
+ const offset = fileHeaderEnd ?? anchorEnd ?? byteOrderMarkOffset;
+ if (fileHeaderEnd !== null || anchorEnd !== null) {
+ const suffix = input.slice(offset);
+ const nextContentIndex = suffix.search(/\S/);
+ const needsTrailingEndOfLine =
+ nextContentIndex !== -1 &&
+ !suffix.slice(0, nextContentIndex).includes('\n');
+ edits.push({
+ end: needsTrailingEndOfLine ? offset + nextContentIndex : offset,
+ replacement: `${endOfLine}${rendered}${needsTrailingEndOfLine ? endOfLine : ''}`,
+ start: offset,
+ });
+ } else {
+ edits.push({
+ end: offset,
+ replacement: `${rendered}${endOfLine}`,
+ start: offset,
+ });
+ }
+ }
+ }
+
+ return edits;
+};
+
+export const applySourceEdits = ({
+ edits,
+ input,
+}: {
+ edits: SourceEdit[];
+ input: string;
+}) => {
+ const sorted = edits.slice().sort((left, right) => right.start - left.start);
+ let output = input;
+ let previousStart = input.length + 1;
+ for (const edit of sorted) {
+ if (edit.end > previousStart) {
+ throw new Error('Overlapping source edit ranges');
+ }
+
+ output =
+ output.slice(0, edit.start) + edit.replacement + output.slice(edit.end);
+ previousStart = edit.start;
+ }
+
+ return output;
+};
diff --git a/packages/studio-codemods/src/source-style.ts b/packages/studio-codemods/src/source-style.ts
new file mode 100644
index 0000000000..1946c9f942
--- /dev/null
+++ b/packages/studio-codemods/src/source-style.ts
@@ -0,0 +1,210 @@
+import type {namedTypes} from 'ast-types';
+import * as recast from 'recast';
+
+export type SourceFormattingConfig = {
+ bracketSpacing: boolean;
+ endOfLine: '\n' | '\r\n';
+ indentationUnit: string;
+ printWidth: number;
+ quote: 'single' | 'double';
+ semi: boolean;
+ singleQuote: boolean;
+ tabWidth: number;
+ useTabs: boolean;
+};
+
+export const getPreferredQuote = (
+ input: string,
+ prettierConfigOverride: Record<string, unknown> | null,
+): 'single' | 'double' => {
+ if (typeof prettierConfigOverride?.singleQuote === 'boolean') {
+ return prettierConfigOverride.singleQuote ? 'single' : 'double';
+ }
+
+ const importQuote =
+ input.match(/\bfrom\s+(['"])/)?.[1] ??
+ input.match(/^\s*import\s+(['"])/m)?.[1];
+ if (importQuote) {
+ return importQuote === "'" ? 'single' : 'double';
+ }
+
+ const singleQuotedStrings = input.match(/'(?:\\.|[^'\\])*'/g)?.length ?? 0;
+ const doubleQuotedStrings = input.match(/"(?:\\.|[^"\\])*"/g)?.length ?? 0;
+ return singleQuotedStrings > doubleQuotedStrings ? 'single' : 'double';
+};
+
+export const getObjectCurlySpacing = (
+ input: string,
+ prettierConfigOverride: Record<string, unknown> | null,
+): boolean => {
+ if (typeof prettierConfigOverride?.bracketSpacing === 'boolean') {
+ return prettierConfigOverride.bracketSpacing;
+ }
+
+ const namedImport = input.match(/\bimport\s*{([^}\n]*)}/);
+ if (namedImport) {
+ return /^\s/.test(namedImport[1]) && /\s$/.test(namedImport[1]);
+ }
+
+ return true;
+};
+
+export const getIndentationUnit = (
+ input: string,
+ prettierConfigOverride: Record<string, unknown> | null,
+): string => {
+ 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 getEndOfLine = (input: string): '\n' | '\r\n' => {
+ return input.includes('\r\n') ? '\r\n' : '\n';
+};
+
+export const getLineIndent = ({
+ input,
+ offset,
+}: {
+ input: string;
+ offset: number;
+}): string => {
+ const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
+ return input.slice(lineStart, offset).match(/^\s*/)?.[0] ?? '';
+};
+
+export const getSourceFormattingConfig = ({
+ input,
+ prettierConfigOverride,
+}: {
+ input: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+}): SourceFormattingConfig => {
+ const indentationUnit = getIndentationUnit(input, prettierConfigOverride);
+ const configuredPrintWidth = prettierConfigOverride?.printWidth;
+ const configuredTabWidth = prettierConfigOverride?.tabWidth;
+ const quote = getPreferredQuote(input, prettierConfigOverride);
+
+ return {
+ bracketSpacing: getObjectCurlySpacing(input, prettierConfigOverride),
+ endOfLine: getEndOfLine(input),
+ indentationUnit,
+ printWidth:
+ typeof configuredPrintWidth === 'number' ? configuredPrintWidth : 80,
+ quote,
+ semi:
+ typeof prettierConfigOverride?.semi === 'boolean'
+ ? prettierConfigOverride.semi
+ : /;[ \t]*(?:\r?\n|$)/.test(input),
+ singleQuote: quote === 'single',
+ tabWidth:
+ typeof configuredTabWidth === 'number' &&
+ Number.isInteger(configuredTabWidth) &&
+ configuredTabWidth > 0
+ ? configuredTabWidth
+ : indentationUnit === '\t'
+ ? 2
+ : indentationUnit.length,
+ useTabs: indentationUnit === '\t',
+ };
+};
+
+export const normalizePrintedIndentation = ({
+ endOfLine,
+ indentationUnit,
+ printed,
+ tabWidth,
+}: {
+ endOfLine: '\n' | '\r\n';
+ indentationUnit: string;
+ printed: string;
+ tabWidth: number;
+}): string => {
+ return printed
+ .split(/\r?\n/)
+ .map((line) => {
+ const spaces = line.match(/^ */)?.[0].length ?? 0;
+ const indentationLevels = Math.floor(spaces / tabWidth);
+ const remainingSpaces = spaces % tabWidth;
+ return `${indentationUnit.repeat(indentationLevels)}${' '.repeat(remainingSpaces)}${line.slice(spaces)}`;
+ })
+ .join(endOfLine);
+};
+
+export const indentContinuationLines = ({
+ indent,
+ input,
+ printed,
+}: {
+ indent: string;
+ input: string;
+ printed: string;
+}): string => {
+ return printed.split(/\r?\n/).join(`${getEndOfLine(input)}${indent}`);
+};
+
+export const indentContinuationLinesAtOffset = ({
+ input,
+ offset,
+ printed,
+}: {
+ input: string;
+ offset: number;
+ printed: string;
+}): string => {
+ return indentContinuationLines({
+ indent: getLineIndent({input, offset}),
+ input,
+ printed,
+ });
+};
+
+export const printNodeWithSourceStyle = ({
+ input,
+ node,
+ prettierConfigOverride,
+ wrapColumn,
+}: {
+ input: string;
+ node: namedTypes.Node;
+ prettierConfigOverride: Record<string, unknown> | null;
+ wrapColumn: number | null;
+}): string => {
+ const formattingConfig = getSourceFormattingConfig({
+ input,
+ prettierConfigOverride,
+ });
+ const printed = recast.prettyPrint(node, {
+ objectCurlySpacing: formattingConfig.bracketSpacing,
+ quote: formattingConfig.quote,
+ tabWidth: formattingConfig.tabWidth,
+ useTabs: false,
+ ...(wrapColumn === null ? {} : {wrapColumn}),
+ }).code;
+ const withSemicolonStyle = formattingConfig.semi
+ ? printed
+ : printed.replace(/;(?=\r?\n|$)/g, '');
+
+ return normalizePrintedIndentation({
+ endOfLine: formattingConfig.endOfLine,
+ indentationUnit: formattingConfig.indentationUnit,
+ printed: withSemicolonStyle,
+ tabWidth: formattingConfig.tabWidth,
+ });
+};
diff --git a/packages/studio-codemods/src/split-jsx-sequence.ts b/packages/studio-codemods/src/split-jsx-sequence.ts
index f43fee1ae3..e213dc0f54 100644
--- a/packages/studio-codemods/src/split-jsx-sequence.ts
+++ b/packages/studio-codemods/src/split-jsx-sequence.ts
@@ -29,6 +29,11 @@ import {
import {printInsertedJsx} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {parseAst, parseAstForReadOnly} from './sequence-props/parse-ast';
+import {
+ getEndOfLine,
+ getLineIndent,
+ indentContinuationLines,
+} from './source-style';
const {builders: b, namedTypes} = recast.types;
@@ -334,17 +339,6 @@ const insertAfter = (
return false;
};
-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,
@@ -366,14 +360,15 @@ const getSplitSourceEdit = ({
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 lineIndent = getLineIndent({input, offset: start});
const isOnlyElementOnLine = beforeElement.trim() === '';
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const endOfLine = getEndOfLine(input);
const formattingConfig = prettierConfigOverride ?? null;
const print = (element: JSXElement | JSXFragment) =>
indentContinuationLines({
indent: lineIndent,
- source: printInsertedJsx({
+ input,
+ printed: printInsertedJsx({
element: element as unknown as
| AstNamedTypes.JSXElement
| AstNamedTypes.JSXFragment,
diff --git a/packages/studio-codemods/src/test/function-source-edits.test.ts b/packages/studio-codemods/src/test/function-source-edits.test.ts
new file mode 100644
index 0000000000..c479c54866
--- /dev/null
+++ b/packages/studio-codemods/src/test/function-source-edits.test.ts
@@ -0,0 +1,68 @@
+import {expect, test} from 'bun:test';
+import type {BlockStatement, Statement} from '@babel/types';
+import * as recast from 'recast';
+import {
+ captureFunctionSourceSnapshots,
+ getFunctionSourceEditsForPrependedStatements,
+} from '../function-source-edits';
+import {parseAst} from '../sequence-props/parse-ast';
+
+const b = recast.types.builders;
+
+test('rejects inserted statements outside the leading prefix', () => {
+ const input = `export const C = () => {
+ first();
+};
+`;
+ const ast = parseAst(input);
+ const snapshots = captureFunctionSourceSnapshots(ast);
+ const body = snapshots[0]?.functionNode.body;
+ if (body?.type !== 'BlockStatement') {
+ throw new Error('Expected a block-bodied function');
+ }
+
+ body.body.push(
+ b.expressionStatement(
+ b.callExpression(b.identifier('second'), []),
+ ) as unknown as Statement,
+ );
+
+ expect(() =>
+ getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: ' ',
+ input,
+ printNode: (node) => recast.prettyPrint(node).code,
+ reprintBlockBodies: new Set(),
+ snapshots,
+ }),
+ ).toThrow('Function source edits only support prepended statements');
+});
+
+test('filters edits nested inside a reprinted function body', () => {
+ const input = `export const C = () => items.map(() => <span />);
+`;
+ const ast = parseAst(input);
+ const snapshots = captureFunctionSourceSnapshots(ast);
+ for (const {functionNode} of snapshots) {
+ if (functionNode.body.type === 'BlockStatement') {
+ throw new Error('Expected expression-bodied functions');
+ }
+
+ functionNode.body = b.blockStatement([
+ b.returnStatement(
+ functionNode.body as Parameters<typeof b.returnStatement>[0],
+ ),
+ ]) as unknown as BlockStatement;
+ }
+
+ const {coveredRanges, edits} = getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: ' ',
+ input,
+ printNode: (node) => recast.prettyPrint(node).code,
+ reprintBlockBodies: new Set(),
+ snapshots,
+ });
+
+ expect(coveredRanges).toHaveLength(2);
+ expect(edits).toHaveLength(1);
+});
diff --git a/packages/studio-codemods/src/test/source-edits.test.ts b/packages/studio-codemods/src/test/source-edits.test.ts
new file mode 100644
index 0000000000..879b0a7479
--- /dev/null
+++ b/packages/studio-codemods/src/test/source-edits.test.ts
@@ -0,0 +1,70 @@
+import {expect, test} from 'bun:test';
+import {ensureNamedImports} from '../sequence-props/imports';
+import {parseAst} from '../sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+} from '../source-edits';
+
+const addImport = (input: string) => {
+ const ast = parseAst(input);
+ const snapshots = captureImportSnapshots(ast);
+ ensureNamedImports({
+ ast,
+ importedNames: new Set(['added']),
+ sourcePath: 'pkg',
+ });
+
+ return applySourceEdits({
+ input,
+ edits: getInsertImportSourceEdits({
+ ast,
+ input,
+ prettierConfigOverride: null,
+ snapshots,
+ }),
+ });
+};
+
+test('keeps byte order marks and file pragmas before new imports', () => {
+ expect(
+ addImport("\uFEFF// @ts-nocheck\nconst value = 'single quote'\n"),
+ ).toBe(
+ "\uFEFF// @ts-nocheck\nimport { added } from 'pkg'\nconst value = 'single quote'\n",
+ );
+});
+
+test('keeps TypeScript triple-slash directives before new imports', () => {
+ expect(addImport('/// <reference types="bun" />\nconst value = 1;\n')).toBe(
+ '/// <reference types="bun" />\nimport { added } from "pkg";\nconst value = 1;\n',
+ );
+});
+
+test('keeps next-line lint comments attached to their statement', () => {
+ expect(
+ addImport("// eslint-disable-next-line no-console\nconsole.log('value')\n"),
+ ).toBe(
+ "import { added } from 'pkg'\n// eslint-disable-next-line no-console\nconsole.log('value')\n",
+ );
+});
+
+test('keeps file-level lint comments before new imports', () => {
+ expect(addImport("/* eslint-disable no-console */\nconsole.log('value')\n"))
+ .toBe(`/* eslint-disable no-console */
+import { added } from 'pkg'
+console.log('value')
+`);
+});
+
+test('reports overlapping generic source edits', () => {
+ expect(() =>
+ applySourceEdits({
+ input: 'source',
+ edits: [
+ {start: 0, end: 3, replacement: 'a'},
+ {start: 2, end: 4, replacement: 'b'},
+ ],
+ }),
+ ).toThrow('Overlapping source edit ranges');
+});
diff --git a/packages/studio-codemods/src/test/source-style.test.ts b/packages/studio-codemods/src/test/source-style.test.ts
new file mode 100644
index 0000000000..8a11f657ac
--- /dev/null
+++ b/packages/studio-codemods/src/test/source-style.test.ts
@@ -0,0 +1,62 @@
+import {expect, test} from 'bun:test';
+import * as recast from 'recast';
+import {
+ getEndOfLine,
+ getLineIndent,
+ getSourceFormattingConfig,
+ indentContinuationLinesAtOffset,
+ printNodeWithSourceStyle,
+} from '../source-style';
+
+test('infers formatting choices from source', () => {
+ const input = "import {thing} from 'pkg'\r\n\r\n\tconst value = 1\r\n";
+
+ expect(
+ getSourceFormattingConfig({input, prettierConfigOverride: null}),
+ ).toEqual({
+ bracketSpacing: false,
+ endOfLine: '\r\n',
+ indentationUnit: '\t',
+ printWidth: 80,
+ quote: 'single',
+ semi: false,
+ singleQuote: true,
+ tabWidth: 2,
+ useTabs: true,
+ });
+});
+
+test('indents continuation lines using the surrounding source', () => {
+ const input = 'const value = (\r\n\tfirst\r\n);\r\n';
+ const offset = input.indexOf('first');
+
+ expect(getEndOfLine(input)).toBe('\r\n');
+ expect(getLineIndent({input, offset})).toBe('\t');
+ expect(
+ indentContinuationLinesAtOffset({
+ input,
+ offset,
+ printed: 'first\nsecond',
+ }),
+ ).toBe('first\r\n\tsecond');
+});
+
+test('prints nodes with inferred quote, semicolon, indentation, and EOL styles', () => {
+ const b = recast.types.builders;
+ const body = b.blockStatement([
+ b.variableDeclaration('const', [
+ b.variableDeclarator(b.identifier('value'), b.stringLiteral('hello')),
+ ]),
+ b.returnStatement(b.identifier('value')),
+ ]);
+ const input = "if (ready) {\r\n\tconst existing = 'value'\r\n}\r\n";
+
+ expect(
+ printNodeWithSourceStyle({
+ input,
+ node: body,
+ prettierConfigOverride: null,
+ wrapColumn: null,
+ }),
+ ).toBe("{\r\n\tconst value = 'hello'\r\n\treturn value\r\n}");
+});
diff --git a/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts b/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts
index 5d064c2a87..2fcfddd856 100644
--- a/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts
+++ b/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts
@@ -393,3 +393,254 @@ export const Example = () => {
);
expect(() => parseAst(output)).not.toThrow();
});
+
+test('keyframe hook expansion preserves trailing block comments', async () => {
+ const input = `export const C = () => (
+ <div style={{opacity: 1}} />
+ /* Keep this comment. */
+);
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 2),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(() => parseAst(output)).not.toThrow();
+ expect(output).toBe(`import { interpolate, useCurrentFrame } from "remotion";
+export const C = () => {
+ const frame = useCurrentFrame();
+ return (
+ <div
+ style={{
+ opacity: interpolate(frame, [8], [1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp"
+ })
+ }} />
+ /* Keep this comment. */
+ );
+};
+`);
+});
+
+test('keyframe hook expansion preserves trailing line comments', async () => {
+ const input = `export const C = () => (
+ <div style={{opacity: 1}} /> // Keep this comment.
+);
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 2),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(() => parseAst(output)).not.toThrow();
+ expect(output).toBe(`import { interpolate, useCurrentFrame } from "remotion";
+export const C = () => {
+ const frame = useCurrentFrame();
+ return (
+ // Keep this comment.
+ <div
+ style={{
+ opacity: interpolate(frame, [8], [1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp"
+ })
+ }} />
+ );
+};
+`);
+});
+
+test('keyframe hook expansion preserves leading expression comments', async () => {
+ const input = `export const C = () => /* Keep this comment. */ <div style={{opacity: 1}} />;
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 1),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(() => parseAst(output)).not.toThrow();
+ expect(output).toBe(`import { interpolate, useCurrentFrame } from "remotion";
+export const C = () => {
+ const frame = useCurrentFrame();
+ return (
+ /* Keep this comment. */ <div
+ style={{
+ opacity: interpolate(frame, [8], [1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp"
+ })
+ }} />
+ );
+};
+`);
+});
+
+test('compact block reprints preserve leading comments', async () => {
+ const input = `export const C = () => /* Keep this comment. */ { return <div style={{opacity: 1}} />; };
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 1),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(() => parseAst(output)).not.toThrow();
+ expect(output).toBe(`import { interpolate, useCurrentFrame } from "remotion";
+export const C = () => /* Keep this comment. */ {
+ const frame = useCurrentFrame();
+ return (
+ <div
+ style={{
+ opacity: interpolate(frame, [8], [1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp"
+ })
+ }} />
+ );
+};
+`);
+});
+
+test('new keyframe imports stay after inline directive comments', async () => {
+ const input = `'use client'; // Keep this on the directive.
+export const C = () => <div style={{opacity: 1}} />;
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 2),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(output).toStartWith(
+ `'use client'; // Keep this on the directive.\nimport `,
+ );
+});
+
+test('new keyframe imports stay after file pragmas', async () => {
+ const input = `// @ts-nocheck
+export const C = () => <div style={{opacity: 1}} />;
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 2),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(output).toStartWith('// @ts-nocheck\nimport ');
+});
+
+test('new keyframe imports separate same-line block pragmas', async () => {
+ const input = `/* @ts-nocheck */ export const C = () => <div style={{opacity: 1}} />;
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 1),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(() => parseAst(output)).not.toThrow();
+ expect(output).toBe(`/* @ts-nocheck */
+import { interpolate, useCurrentFrame } from "remotion";
+export const C = () => {
+ const frame = useCurrentFrame();
+ return (
+ <div
+ style={{
+ opacity: interpolate(frame, [8], [1], {
+ extrapolateLeft: "clamp",
+ extrapolateRight: "clamp"
+ })
+ }} />
+ );
+};
+`);
+});
+
+test('new keyframe imports stay after shebangs and file pragmas', async () => {
+ const input = `#!/usr/bin/env bun
+// @ts-nocheck
+export const C = () => <div style={{opacity: 1}} />;
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 3),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(output).toStartWith('#!/usr/bin/env bun\n// @ts-nocheck\nimport ');
+});
+
+test('frame hooks stay after inline function directive comments', async () => {
+ const input = `export const C = () => {
+ 'use strict'; // Keep this on the directive.
+ return <div style={{opacity: 1}} />;
+};
+`;
+ const {output} = await updateSequenceKeyframes({
+ input,
+ nodePath: getNodePathAtLine(input, 3),
+ updates: [
+ {
+ key: 'style.opacity',
+ operation: {type: 'add', frame: 8, value: 1},
+ },
+ ],
+ videoConfigValues: null,
+ });
+
+ expect(output).toContain(
+ ` 'use strict'; // Keep this on the directive.\n const frame`,
+ );
+});
diff --git a/packages/studio-codemods/src/test/update-sequence-props.test.ts b/packages/studio-codemods/src/test/update-sequence-props.test.ts
index 122ea8aa24..82140587c5 100644
--- a/packages/studio-codemods/src/test/update-sequence-props.test.ts
+++ b/packages/studio-codemods/src/test/update-sequence-props.test.ts
@@ -269,7 +269,7 @@ export const Example = () => {
parseAst(output);
});
-test('indents a compact frame hook after directives and before comments', () => {
+test('preserves inline directive comments before compact frame hooks', () => {
const input = `import {Interactive} from "remotion"
export const C = () => { "use strict"; /* keep */ return <Interactive.Div opacity={1} /> }
`;
@@ -315,9 +315,9 @@ export const C = () => { "use strict"; /* keep */ return <Interactive.Div opacit
expect(output)
.toBe(`import {Interactive, useCurrentFrame, interpolate} from "remotion"
-export const C = () => { "use strict";
+export const C = () => { "use strict"; /* keep */
const frame = useCurrentFrame()
- /* keep */ return <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])} /> }
+ return <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])} /> }
`);
parseAst(output);
});
@@ -366,6 +366,50 @@ export const C = () => { return <Interactive.Div
parseAst(output);
});
+test('indents a multiline opening element inside a compact object method', () => {
+ const input = `import {Interactive} from "remotion"
+const object = {render() { return <Interactive.Div opacity={1} /> }}
+`;
+ const ast = parseAst(input);
+ let nodePath = null;
+ recast.types.visit(ast, {
+ visitJSXOpeningElement(path) {
+ nodePath = getNodePathForRecastPath(path, ast);
+ return false;
+ },
+ });
+ if (!nodePath) {
+ throw new Error('Could not find the Interactive.Div');
+ }
+
+ const {output} = updateMultipleSequenceProps({
+ input,
+ changes: [
+ {
+ nodePath,
+ updates: [
+ {
+ key: 'name',
+ value:
+ 'A deliberately long sequence name that makes this opening element wrap onto multiple lines',
+ defaultValue: null,
+ },
+ ],
+ schema: NoReactInternals.sequenceSchema,
+ videoConfigValues: null,
+ },
+ ],
+ });
+
+ expect(output).toBe(`import {Interactive} from "remotion"
+const object = {render() { return <Interactive.Div
+ opacity={1}
+ name={"A deliberately long sequence name that makes this opening element wrap onto multiple lines"}
+ /> }}
+`);
+ parseAst(output);
+});
+
test('infers single quotes for a new import', () => {
const input = `const unrelated = 'single quote'
diff --git a/packages/studio-codemods/src/update-keyframes.ts b/packages/studio-codemods/src/update-keyframes.ts
index c35b4d067b..5cef5fa10c 100644
--- a/packages/studio-codemods/src/update-keyframes.ts
+++ b/packages/studio-codemods/src/update-keyframes.ts
@@ -4,8 +4,6 @@ import type {
CallExpression,
Expression,
File,
- FunctionDeclaration,
- FunctionExpression,
JSXAttribute,
JSXElement,
JSXExpressionContainer,
@@ -14,7 +12,6 @@ import type {
JSXSpreadAttribute,
ObjectExpression,
ObjectProperty,
- ArrowFunctionExpression,
StringLiteral,
} from '@babel/types';
import {
@@ -45,16 +42,12 @@ import {
findEnclosingFunctionPath,
} from './ensure-imports-and-frame-hook';
import {
- applySourceEdits,
- getInsertImportSourceEdits,
- type SourceEdit,
-} from './insert-jsx-element';
-import {
- getIndentationUnit,
- getObjectCurlySpacing,
- getPreferredQuote,
- printJsxOpeningElement,
-} from './print-jsx';
+ captureFunctionSourceSnapshots,
+ getFunctionSourceEditsForPrependedStatements,
+ type FunctionNode,
+ type FunctionSourceSnapshot,
+} from './function-source-edits';
+import {printJsxOpeningElement} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {
extractStaticValue,
@@ -77,104 +70,24 @@ import {
getVideoConfigIdentifierValues,
type VideoConfigIdentifierValues,
} from './sequence-props/video-config-values';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type ImportSnapshot,
+ type SourceEdit,
+} from './source-edits';
+import {
+ getEndOfLine,
+ getSourceFormattingConfig,
+ indentContinuationLinesAtOffset,
+ printNodeWithSourceStyle,
+ type SourceFormattingConfig,
+} from './source-style';
import {parseValueExpression} from './update-nested-prop';
const b = recast.types.builders;
-type FunctionNode =
- | FunctionDeclaration
- | FunctionExpression
- | ArrowFunctionExpression;
-
-const getSourceFormattingConfig = ({
- input,
- prettierConfigOverride,
-}: {
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
-}): Record<string, unknown> => {
- const indentationUnit = getIndentationUnit(input, prettierConfigOverride);
- return {
- ...prettierConfigOverride,
- bracketSpacing: getObjectCurlySpacing(input, prettierConfigOverride),
- printWidth: prettierConfigOverride?.printWidth ?? 80,
- singleQuote: getPreferredQuote(input, prettierConfigOverride) === 'single',
- tabWidth:
- prettierConfigOverride?.tabWidth ??
- (indentationUnit === '\t' ? 2 : indentationUnit.length),
- };
-};
-
-const indentContinuationLines = ({
- input,
- offset,
- printed,
-}: {
- input: string;
- offset: number;
- printed: string;
-}) => {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
- const lineIndent = input.slice(lineStart, offset).match(/^\s*/)?.[0] ?? '';
- return printed.split(/\r?\n/).join(`${endOfLine}${lineIndent}`);
-};
-
-const printBlockStatementWithSourceStyle = ({
- body,
- input,
- prettierConfigOverride,
-}: {
- body: BlockStatement;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
-}) => {
- const formattingConfig = getSourceFormattingConfig({
- input,
- prettierConfigOverride,
- });
- const configuredTabWidth = formattingConfig.tabWidth;
- const tabWidth =
- typeof configuredTabWidth === 'number' &&
- Number.isInteger(configuredTabWidth) &&
- configuredTabWidth > 0
- ? configuredTabWidth
- : 2;
- const indentationUnit = getIndentationUnit(input, formattingConfig);
- let printed = recast.prettyPrint(body, {
- objectCurlySpacing: formattingConfig.bracketSpacing !== false,
- quote: formattingConfig.singleQuote === true ? 'single' : 'double',
- tabWidth,
- useTabs: false,
- wrapColumn:
- typeof formattingConfig.printWidth === 'number'
- ? formattingConfig.printWidth
- : 80,
- }).code;
- printed = printed
- .split('\n')
- .map((line) => {
- const spaces = line.match(/^ */)?.[0].length ?? 0;
- const levels = Math.floor(spaces / tabWidth);
- const remainder = spaces % tabWidth;
- return `${indentationUnit.repeat(levels)}${' '.repeat(remainder)}${line.slice(spaces)}`;
- })
- .join(input.includes('\r\n') ? '\r\n' : '\n');
- printed = printed.replace(
- /(const frame = useCurrentFrame\(\);?\r?\n)(?:[ \t]*\r?\n)+/,
- '$1',
- );
- const shouldUseSemicolons =
- typeof formattingConfig.semi === 'boolean'
- ? formattingConfig.semi
- : /;\s*(?:\r?\n|$)/.test(input);
- if (!shouldUseSemicolons) {
- printed = printed.replace(/;(?=\r?$)/gm, '');
- }
-
- return printed;
-};
-
const getOpeningElementSourceEdit = ({
input,
openingElement,
@@ -199,7 +112,7 @@ const getOpeningElementSourceEdit = ({
return {
start,
end: recastLocToOffset(input, openingElement.loc.end),
- replacement: indentContinuationLines({
+ replacement: indentContinuationLinesAtOffset({
input,
offset: start,
printed: removeBlankLinesFromUpdatedOpeningElementObjects({
@@ -210,237 +123,93 @@ const getOpeningElementSourceEdit = ({
};
};
-const getFrameHookSourceEdit = ({
- body,
+const getKeyframeFunctionSourceEdits = ({
+ formattingConfig,
+ functionSnapshots,
input,
- originalStatements,
- prettierConfigOverride,
-}: {
- body: BlockStatement;
- input: string;
- originalStatements: BlockStatement['body'];
- prettierConfigOverride: Record<string, unknown> | null;
-}): SourceEdit | null => {
- if (body.body.length === originalStatements.length) {
- return null;
- }
-
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- const firstStatement = originalStatements[0];
- const statementTerminator = firstStatement?.loc
- ? input
- .slice(
- recastLocToOffset(input, firstStatement.loc.start),
- recastLocToOffset(input, firstStatement.loc.end),
- )
- .trimEnd()
- .endsWith(';')
- ? ';'
- : ''
- : /;\s*(?:\r?\n|$)/.test(input)
- ? ';'
- : '';
- const declaration = `const frame = useCurrentFrame()${statementTerminator}`;
-
- if (!body.loc) {
- return null;
- }
-
- const bodyStart = recastLocToOffset(input, body.loc.start);
- const lineStart = input.lastIndexOf('\n', bodyStart - 1) + 1;
- const functionIndent =
- input.slice(lineStart, bodyStart).match(/^\s*/)?.[0] ?? '';
- const firstStatementStart = firstStatement?.loc
- ? recastLocToOffset(input, firstStatement.loc.start)
- : null;
- const lastDirective = body.directives?.at(-1);
- const insertionOffset = lastDirective?.loc
- ? recastLocToOffset(input, lastDirective.loc.end)
- : bodyStart + 1;
- const leadingCommentOffsets = (firstStatement?.leadingComments ?? []).flatMap(
- (comment) =>
- comment.loc ? [recastLocToOffset(input, comment.loc.start)] : [],
- );
- const firstContentOffset = [
- ...(firstStatementStart === null ? [] : [firstStatementStart]),
- ...leadingCommentOffsets,
- ].reduce<number | null>(
- (earliest, candidate) =>
- candidate < insertionOffset
- ? earliest
- : Math.min(earliest ?? candidate, candidate),
- null,
- );
- const gapToKnownContent =
- firstContentOffset === null
- ? ''
- : input.slice(insertionOffset, firstContentOffset);
- const unexpectedContentIndex = gapToKnownContent.search(/\S/);
- const contentOffset =
- unexpectedContentIndex === -1
- ? firstContentOffset
- : insertionOffset + unexpectedContentIndex;
- const gap =
- contentOffset === null ? '' : input.slice(insertionOffset, contentOffset);
- const originalStartsOnNewLine = /\r?\n/.test(gap);
- const statementIndent =
- contentOffset !== null && originalStartsOnNewLine
- ? (input
- .slice(input.lastIndexOf('\n', contentOffset - 1) + 1, contentOffset)
- .match(/^\s*/)?.[0] ?? '')
- : `${functionIndent}${getIndentationUnit(input, prettierConfigOverride)}`;
- return {
- start: insertionOffset,
- end: originalStartsOnNewLine
- ? insertionOffset
- : (contentOffset ?? insertionOffset),
- replacement: originalStartsOnNewLine
- ? `${endOfLine}${statementIndent}${declaration}`
- : `${endOfLine}${statementIndent}${declaration}${endOfLine}${statementIndent}`,
- };
-};
-
-const getBlockStatementSourceEdit = ({
- body,
- input,
- prettierConfigOverride,
-}: {
- body: BlockStatement;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
-}): SourceEdit | null => {
- if (!body.loc) {
- return null;
- }
-
- const start = recastLocToOffset(input, body.loc.start);
- return {
- start,
- end: recastLocToOffset(input, body.loc.end),
- replacement: indentContinuationLines({
- input,
- offset: start,
- printed: printBlockStatementWithSourceStyle({
- body,
- input,
- prettierConfigOverride,
- }),
- }),
- };
-};
-
-const openingElementStartsInCompactFunctionBody = ({
- body,
+ jsxPath,
+ needsFrameHook,
openingElement,
}: {
- body: BlockStatement;
- openingElement: JSXOpeningElement;
-}) =>
- body.loc !== null &&
- body.loc !== undefined &&
- openingElement.loc !== null &&
- openingElement.loc !== undefined &&
- body.loc.start.line === openingElement.loc.start.line;
-
-const getExpressionBodySourceEdit = ({
- body,
- input,
- originalBody,
- prettierConfigOverride,
-}: {
- body: BlockStatement;
+ formattingConfig: SourceFormattingConfig;
+ functionSnapshots: FunctionSourceSnapshot[];
input: string;
- originalBody: Expression;
- prettierConfigOverride: Record<string, unknown> | null;
-}): SourceEdit | null => {
- if (!originalBody.loc) {
- return null;
- }
-
- const printed = printBlockStatementWithSourceStyle({
- body,
- input,
- prettierConfigOverride,
- });
-
- const bodyStart = recastLocToOffset(input, originalBody.loc.start);
- let start = bodyStart;
- let end = recastLocToOffset(input, originalBody.loc.end);
- const extra = originalBody.extra as
- | {
- parenthesized: boolean | null | undefined;
- parenStart: number | null | undefined;
- }
- | null
- | undefined;
- if (
- extra?.parenthesized === true &&
- typeof extra.parenStart === 'number' &&
- extra.parenStart < bodyStart
- ) {
- const openingParentheses = input
- .slice(extra.parenStart, bodyStart)
- .split('')
- .filter((character) => character === '(').length;
- let closingParentheses = 0;
- let cursor = end;
- while (cursor < input.length && closingParentheses < openingParentheses) {
- const character = input[cursor];
- if (/\s/.test(character)) {
- cursor++;
- continue;
- }
-
- if (character !== ')') {
- break;
- }
-
- closingParentheses++;
- cursor++;
+ jsxPath: recast.types.NodePath;
+ needsFrameHook: boolean;
+ openingElement: JSXOpeningElement;
+}) => {
+ const reprintBlockBodies = new Set<BlockStatement>();
+ const fnPath = findEnclosingFunctionPath(jsxPath);
+ if (fnPath) {
+ const functionNode = fnPath.value as FunctionNode;
+ const snapshot = functionSnapshots.find(
+ (candidate) => candidate.functionNode === functionNode,
+ );
+ if (
+ snapshot?.body.type === 'BlockStatement' &&
+ snapshot.body.loc &&
+ openingElement.loc &&
+ snapshot.body.loc.start.line === openingElement.loc.start.line
+ ) {
+ reprintBlockBodies.add(snapshot.body);
}
- if (closingParentheses === openingParentheses) {
- start = extra.parenStart;
- end = cursor;
+ if (needsFrameHook) {
+ ensureUseCurrentFrameHook(fnPath);
}
}
- return {
- start,
- end,
- replacement: indentContinuationLines({input, offset: start, printed}),
- };
+ return getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: formattingConfig.indentationUnit,
+ input,
+ printNode: (node) =>
+ printNodeWithSourceStyle({
+ input,
+ node,
+ prettierConfigOverride: formattingConfig,
+ wrapColumn: formattingConfig.printWidth,
+ }).replace(
+ /(const frame = useCurrentFrame\(\);?\r?\n)(?:[ \t]*\r?\n)+/,
+ '$1',
+ ),
+ reprintBlockBodies,
+ snapshots: functionSnapshots,
+ });
};
const getKeyframeSourceOutput = ({
ast,
+ functionSourceCoveredRanges,
+ functionSourceEdits,
input,
openingElement,
- functionSourceEdit,
importSnapshots,
prettierConfigOverride,
propertyNames,
}: {
ast: File;
+ functionSourceCoveredRanges: {end: number; start: number}[];
+ functionSourceEdits: SourceEdit[];
input: string;
- openingElement: JSXOpeningElement | null;
- functionSourceEdit: SourceEdit | null;
- importSnapshots: {
- declaration: Extract<
- File['program']['body'][number],
- {type: 'ImportDeclaration'}
- >;
- specifiers: NonNullable<
- Extract<
- File['program']['body'][number],
- {type: 'ImportDeclaration'}
- >['specifiers']
- >;
- }[];
+ openingElement: JSXOpeningElement;
+ importSnapshots: ImportSnapshot[];
prettierConfigOverride: Record<string, unknown> | null;
propertyNames: string[];
-}) =>
- applySourceEdits({
+}) => {
+ const openingStart = openingElement.loc
+ ? recastLocToOffset(input, openingElement.loc.start)
+ : null;
+ const openingEnd = openingElement.loc
+ ? recastLocToOffset(input, openingElement.loc.end)
+ : null;
+ const openingElementIsCovered =
+ openingStart !== null &&
+ openingEnd !== null &&
+ functionSourceCoveredRanges.some(
+ (range) => openingStart >= range.start && openingEnd <= range.end,
+ );
+
+ return applySourceEdits({
input,
edits: [
...getInsertImportSourceEdits({
@@ -449,8 +218,8 @@ const getKeyframeSourceOutput = ({
prettierConfigOverride,
snapshots: importSnapshots,
}),
- ...(functionSourceEdit ? [functionSourceEdit] : []),
- ...(openingElement
+ ...functionSourceEdits,
+ ...(!openingElementIsCovered
? [
getOpeningElementSourceEdit({
input,
@@ -462,6 +231,7 @@ const getKeyframeSourceOutput = ({
: []),
],
});
+};
const getObjectPropertyNameFromUpdateKey = (key: string): string => {
const dotIndex = key.indexOf('.');
@@ -496,7 +266,7 @@ const removeBlankLinesFromUpdatedOpeningElementObjects = ({
return input;
}
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const endOfLine = getEndOfLine(input);
const lines = input.split(/\r?\n/);
const linesToRemove = new Set<number>();
@@ -2207,16 +1977,8 @@ export const updateSequenceKeyframesAst = ({
input,
prettierConfigOverride: prettierConfigOverride ?? null,
});
- const importSnapshots = ast.program.body.flatMap((statement) =>
- statement.type === 'ImportDeclaration'
- ? [
- {
- declaration: statement,
- specifiers: [...(statement.specifiers ?? [])],
- },
- ]
- : [],
- );
+ const functionSnapshots = captureFunctionSourceSnapshots(ast);
+ const importSnapshots = captureImportSnapshots(ast);
const videoConfigIdentifierValues = getVideoConfigIdentifierValues({
ast,
videoConfigValues,
@@ -2290,51 +2052,17 @@ export const updateSequenceKeyframesAst = ({
}
}
- let functionSourceEdit: SourceEdit | null = null;
- let openingElementForSourceEdit: JSXOpeningElement | null = node;
- const fnPath = findEnclosingFunctionPath(jsxPath);
- if (fnPath) {
- const fn = fnPath.value as FunctionNode;
- const originalBody = fn.body;
- const originalStatements =
- originalBody.type === 'BlockStatement' ? [...originalBody.body] : null;
- if (needsFrameHook) {
- ensureUseCurrentFrameHook(fnPath);
- }
-
- if (
- originalBody.type === 'BlockStatement' &&
- fn.body.type === 'BlockStatement' &&
- openingElementStartsInCompactFunctionBody({
- body: originalBody,
- openingElement: node,
- })
- ) {
- functionSourceEdit = getBlockStatementSourceEdit({
- body: fn.body,
- input,
- prettierConfigOverride: formattingConfig,
- });
- openingElementForSourceEdit = null;
- } else if (needsFrameHook) {
- if (originalStatements && fn.body.type === 'BlockStatement') {
- functionSourceEdit = getFrameHookSourceEdit({
- body: fn.body as BlockStatement,
- input,
- originalStatements,
- prettierConfigOverride: formattingConfig,
- });
- } else if (fn.body.type === 'BlockStatement') {
- functionSourceEdit = getExpressionBodySourceEdit({
- body: fn.body,
- input,
- originalBody: originalBody as Expression,
- prettierConfigOverride: formattingConfig,
- });
- openingElementForSourceEdit = null;
- }
- }
- }
+ const {
+ coveredRanges: functionSourceCoveredRanges,
+ edits: functionSourceEdits,
+ } = getKeyframeFunctionSourceEdits({
+ formattingConfig,
+ functionSnapshots,
+ input,
+ jsxPath,
+ needsFrameHook,
+ openingElement: node,
+ });
ensureRemotionImports(ast, requiredImports);
@@ -2348,9 +2076,10 @@ export const updateSequenceKeyframesAst = ({
return {
serialized: getKeyframeSourceOutput({
ast,
+ functionSourceCoveredRanges,
+ functionSourceEdits,
input,
- openingElement: openingElementForSourceEdit,
- functionSourceEdit,
+ openingElement: node,
importSnapshots,
prettierConfigOverride: formattingConfig,
propertyNames: updates.map((update) =>
@@ -2443,16 +2172,8 @@ export const updateEffectKeyframesAst = ({
input,
prettierConfigOverride: prettierConfigOverride ?? null,
});
- const importSnapshots = ast.program.body.flatMap((statement) =>
- statement.type === 'ImportDeclaration'
- ? [
- {
- declaration: statement,
- specifiers: [...(statement.specifiers ?? [])],
- },
- ]
- : [],
- );
+ const functionSnapshots = captureFunctionSourceSnapshots(ast);
+ const importSnapshots = captureImportSnapshots(ast);
const videoConfigIdentifierValues = getVideoConfigIdentifierValues({
ast,
videoConfigValues,
@@ -2533,51 +2254,17 @@ export const updateEffectKeyframesAst = ({
}
}
- let functionSourceEdit: SourceEdit | null = null;
- let openingElementForSourceEdit: JSXOpeningElement | null = jsx;
- const fnPath = findEnclosingFunctionPath(jsxPath);
- if (fnPath) {
- const fn = fnPath.value as FunctionNode;
- const originalBody = fn.body;
- const originalStatements =
- originalBody.type === 'BlockStatement' ? [...originalBody.body] : null;
- if (needsFrameHook) {
- ensureUseCurrentFrameHook(fnPath);
- }
-
- if (
- originalBody.type === 'BlockStatement' &&
- fn.body.type === 'BlockStatement' &&
- openingElementStartsInCompactFunctionBody({
- body: originalBody,
- openingElement: jsx,
- })
- ) {
- functionSourceEdit = getBlockStatementSourceEdit({
- body: fn.body,
- input,
- prettierConfigOverride: formattingConfig,
- });
- openingElementForSourceEdit = null;
- } else if (needsFrameHook) {
- if (originalStatements && fn.body.type === 'BlockStatement') {
- functionSourceEdit = getFrameHookSourceEdit({
- body: fn.body as BlockStatement,
- input,
- originalStatements,
- prettierConfigOverride: formattingConfig,
- });
- } else if (fn.body.type === 'BlockStatement') {
- functionSourceEdit = getExpressionBodySourceEdit({
- body: fn.body,
- input,
- originalBody: originalBody as Expression,
- prettierConfigOverride: formattingConfig,
- });
- openingElementForSourceEdit = null;
- }
- }
- }
+ const {
+ coveredRanges: functionSourceCoveredRanges,
+ edits: functionSourceEdits,
+ } = getKeyframeFunctionSourceEdits({
+ formattingConfig,
+ functionSnapshots,
+ input,
+ jsxPath,
+ needsFrameHook,
+ openingElement: jsx,
+ });
ensureRemotionImports(ast, requiredImports);
@@ -2591,9 +2278,10 @@ export const updateEffectKeyframesAst = ({
return {
serialized: getKeyframeSourceOutput({
ast,
+ functionSourceCoveredRanges,
+ functionSourceEdits,
input,
- openingElement: openingElementForSourceEdit,
- functionSourceEdit,
+ openingElement: jsx,
importSnapshots,
prettierConfigOverride: formattingConfig,
propertyNames: updates.map((update) => update.key),
diff --git a/packages/studio-codemods/src/update-sequence-props.ts b/packages/studio-codemods/src/update-sequence-props.ts
index ac2bff619f..ebf620452c 100644
--- a/packages/studio-codemods/src/update-sequence-props.ts
+++ b/packages/studio-codemods/src/update-sequence-props.ts
@@ -1,7 +1,4 @@
import type {
- ArrowFunctionExpression,
- FunctionDeclaration,
- FunctionExpression,
JSXAttribute,
JSXElement,
JSXExpressionContainer,
@@ -27,17 +24,11 @@ import type {
} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {
- applySourceEdits,
- getInsertImportSourceEdits,
- type SourceEdit,
-} from './insert-jsx-element';
-import {
- getIndentationUnit,
- getObjectCurlySpacing,
- getPreferredQuote,
- printInsertedJsx,
- printJsxOpeningElement,
-} from './print-jsx';
+ captureFunctionSourceSnapshots,
+ getFunctionSourceEditsForPrependedStatements,
+ type FunctionNode,
+} from './function-source-edits';
+import {printInsertedJsx, printJsxOpeningElement} from './print-jsx';
import {recastLocToOffset} from './recast-loc-to-offset';
import {
findNodePathForJsxElement,
@@ -66,6 +57,21 @@ import {
getVideoConfigIdentifierValues,
type VideoConfigIdentifierValues,
} from './sequence-props/video-config-values';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getInsertImportSourceEdits,
+ type SourceEdit,
+} from './source-edits';
+import {
+ getEndOfLine,
+ getIndentationUnit,
+ getLineIndent,
+ getObjectCurlySpacing,
+ getPreferredQuote,
+ indentContinuationLines,
+ printNodeWithSourceStyle,
+} from './source-style';
import {parseValueExpression, updateNestedProp} from './update-nested-prop';
const b = recast.types.builders;
@@ -198,11 +204,6 @@ type JSXElementLike = NonNullable<
>;
type JSXOpeningElementLike = JSXElementLike['openingElement'];
-type FunctionNode =
- | FunctionDeclaration
- | FunctionExpression
- | ArrowFunctionExpression;
-
const isFunctionNode = (value: unknown): value is FunctionNode => {
return (
recast.types.namedTypes.FunctionDeclaration.check(value) ||
@@ -1262,247 +1263,6 @@ export const updateSequencePropsAst = ({
};
};
-type FunctionSourceSnapshot = {
- body: FunctionNode['body'];
- functionNode: FunctionNode;
- statements: Statement[] | null;
-};
-
-const getLineIndent = (input: string, offset: number) => {
- const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
- return input.slice(lineStart, offset).match(/^\s*/)?.[0] ?? '';
-};
-
-const printNodeWithSourceStyle = ({
- input,
- node,
- prettierConfigOverride,
-}: {
- input: string;
- node: AstNamedTypes.Node;
- prettierConfigOverride: Record<string, unknown> | null;
-}) => {
- const configuredTabWidth = prettierConfigOverride?.tabWidth;
- const tabWidth =
- typeof configuredTabWidth === 'number' &&
- Number.isInteger(configuredTabWidth) &&
- configuredTabWidth > 0
- ? configuredTabWidth
- : 2;
- const unit = getIndentationUnit(input, prettierConfigOverride);
- const shouldUseSemicolons =
- typeof prettierConfigOverride?.semi === 'boolean'
- ? prettierConfigOverride.semi
- : /;[ \t]*(?:\r?\n|$)/.test(input);
- const printed = recast.prettyPrint(node, {
- objectCurlySpacing: getObjectCurlySpacing(input, prettierConfigOverride),
- quote: getPreferredQuote(input, prettierConfigOverride),
- tabWidth,
- useTabs: false,
- }).code;
- const withSemicolonStyle = shouldUseSemicolons
- ? printed
- : printed.replace(/;(?=\r?\n|$)/g, '');
-
- return withSemicolonStyle
- .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(input.includes('\r\n') ? '\r\n' : '\n');
-};
-
-const indentContinuationLines = ({
- indent,
- input,
- printed,
-}: {
- indent: string;
- input: string;
- printed: string;
-}) => {
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- return printed.split(/\r?\n/).join(`${endOfLine}${indent}`);
-};
-
-const getFunctionSourceSnapshots = (ast: File) => {
- const snapshots: FunctionSourceSnapshot[] = [];
- recast.types.visit(ast, {
- visitFunction(path) {
- const functionNode = path.node as FunctionNode;
- snapshots.push({
- body: functionNode.body,
- functionNode,
- statements:
- functionNode.body.type === 'BlockStatement'
- ? [...functionNode.body.body]
- : null,
- });
- this.traverse(path);
- return undefined;
- },
- });
- return snapshots;
-};
-
-const getFunctionSourceEdits = ({
- input,
- prettierConfigOverride,
- snapshots,
-}: {
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
- snapshots: FunctionSourceSnapshot[];
-}): {coveredRanges: {start: number; end: number}[]; edits: SourceEdit[]} => {
- const coveredRanges: {start: number; end: number}[] = [];
- const edits: SourceEdit[] = [];
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
- const unit = getIndentationUnit(input, prettierConfigOverride);
-
- for (const snapshot of snapshots) {
- const {body: originalBody, functionNode, statements} = snapshot;
- if (functionNode.body !== originalBody) {
- if (!originalBody.loc) {
- continue;
- }
-
- const bodyStart = recastLocToOffset(input, originalBody.loc.start);
- let start = bodyStart;
- let end = recastLocToOffset(input, originalBody.loc.end);
- const parenthesisStart = originalBody.extra?.parenthesized
- ? originalBody.extra.parenStart
- : null;
- if (typeof parenthesisStart === 'number') {
- const parenthesisCount = input
- .slice(parenthesisStart, bodyStart)
- .split('')
- .filter((character) => character === '(').length;
- let parenthesisEnd = end;
- let consumedParentheses = 0;
- while (consumedParentheses < parenthesisCount) {
- while (/\s/.test(input[parenthesisEnd] ?? '')) {
- parenthesisEnd++;
- }
-
- if (input[parenthesisEnd] !== ')') {
- break;
- }
-
- parenthesisEnd++;
- consumedParentheses++;
- }
-
- if (parenthesisCount > 0 && consumedParentheses === parenthesisCount) {
- start = parenthesisStart;
- end = parenthesisEnd;
- }
- }
-
- const printed = printNodeWithSourceStyle({
- input,
- node: functionNode.body as unknown as AstNamedTypes.Node,
- prettierConfigOverride,
- });
- edits.push({
- start,
- end,
- replacement: indentContinuationLines({
- indent: getLineIndent(input, start),
- input,
- printed,
- }),
- });
- coveredRanges.push({start, end});
- continue;
- }
-
- if (originalBody.type !== 'BlockStatement' || statements === null) {
- continue;
- }
-
- const originalStatements = new Set(statements);
- const insertedStatements = originalBody.body.filter(
- (statement) => !originalStatements.has(statement),
- );
- if (insertedStatements.length === 0 || !originalBody.loc) {
- continue;
- }
-
- const blockStart = recastLocToOffset(input, originalBody.loc.start);
- const openingBrace = input.indexOf('{', blockStart);
- if (openingBrace === -1) {
- continue;
- }
-
- const firstOriginalStatement = statements[0];
- const firstOriginalOffset = firstOriginalStatement?.loc
- ? recastLocToOffset(input, firstOriginalStatement.loc.start)
- : null;
- const lastDirective = originalBody.directives?.at(-1);
- const insertionStart = lastDirective?.loc
- ? recastLocToOffset(input, lastDirective.loc.end)
- : openingBrace + 1;
- const leadingCommentOffsets = (
- firstOriginalStatement?.leadingComments ?? []
- ).flatMap((comment) =>
- comment.loc ? [recastLocToOffset(input, comment.loc.start)] : [],
- );
- const firstContentOffset = [
- ...(firstOriginalOffset === null ? [] : [firstOriginalOffset]),
- ...leadingCommentOffsets,
- ].reduce<number | null>(
- (earliest, candidate) =>
- candidate < insertionStart
- ? earliest
- : Math.min(earliest ?? candidate, candidate),
- null,
- );
- const gap =
- firstContentOffset === null
- ? ''
- : input.slice(insertionStart, firstContentOffset);
- const originalStartsOnNewLine = /\r?\n/.test(gap);
- const statementIndent =
- firstContentOffset !== null && originalStartsOnNewLine
- ? getLineIndent(input, firstContentOffset)
- : `${getLineIndent(input, blockStart)}${unit}`;
- const printedStatements = insertedStatements
- .map((statement) =>
- printNodeWithSourceStyle({
- input,
- node: statement as unknown as AstNamedTypes.Node,
- prettierConfigOverride,
- }),
- )
- .join(`${endOfLine}${statementIndent}`);
- edits.push({
- start: insertionStart,
- end: originalStartsOnNewLine
- ? insertionStart
- : (firstContentOffset ?? insertionStart),
- replacement: originalStartsOnNewLine
- ? `${endOfLine}${statementIndent}${printedStatements}`
- : `${endOfLine}${statementIndent}${printedStatements}${endOfLine}${statementIndent}`,
- });
- }
-
- return {
- coveredRanges,
- edits: edits.filter(
- (edit) =>
- !coveredRanges.some(
- (range) =>
- edit.start >= range.start &&
- edit.end <= range.end &&
- (edit.start !== range.start || edit.end !== range.end),
- ),
- ),
- };
-};
-
const getProgramStatementSourceEdits = ({
ast,
input,
@@ -1536,7 +1296,7 @@ const getProgramStatementSourceEdits = ({
}
const originalStatements = new Set(originalBody);
- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';
+ const endOfLine = getEndOfLine(input);
for (let index = 0; index < ast.program.body.length; index++) {
const statement = ast.program.body[index];
if (
@@ -1564,6 +1324,7 @@ const getProgramStatementSourceEdits = ({
input,
node: candidate as unknown as AstNamedTypes.Node,
prettierConfigOverride,
+ wrapColumn: null,
}),
)
.join(`${endOfLine}${endOfLine}`);
@@ -1614,17 +1375,8 @@ export const updateMultipleSequenceProps = ({
...(prettierConfig ?? {}),
};
const originalProgramBody = [...ast.program.body];
- const importSnapshots = ast.program.body.flatMap((statement) =>
- statement.type === 'ImportDeclaration'
- ? [
- {
- declaration: statement,
- specifiers: [...statement.specifiers],
- },
- ]
- : [],
- );
- const functionSnapshots = getFunctionSourceSnapshots(ast);
+ const importSnapshots = captureImportSnapshots(ast);
+ const functionSnapshots = captureFunctionSourceSnapshots(ast);
const getJsxSourceIndent = (offset: number) => {
const lineStart = input.lastIndexOf('\n', offset - 1) + 1;
const startsInsideSameLineFunctionBlock = functionSnapshots.some(
@@ -1642,7 +1394,7 @@ export const updateMultipleSequenceProps = ({
);
},
);
- const lineIndent = getLineIndent(input, offset);
+ const lineIndent = getLineIndent({input, offset});
return startsInsideSameLineFunctionBlock
? `${lineIndent}${getIndentationUnit(input, prettierConfig)}`
: lineIndent;
@@ -1715,11 +1467,20 @@ export const updateMultipleSequenceProps = ({
return {...result, newNodePath};
});
- const {coveredRanges, edits: functionEdits} = getFunctionSourceEdits({
- input,
- prettierConfigOverride: prettierConfig,
- snapshots: functionSnapshots,
- });
+ const {coveredRanges, edits: functionEdits} =
+ getFunctionSourceEditsForPrependedStatements({
+ indentationUnit: getIndentationUnit(input, prettierConfig),
+ input,
+ printNode: (node) =>
+ printNodeWithSourceStyle({
+ input,
+ node,
+ prettierConfigOverride: prettierConfig,
+ wrapColumn: null,
+ }),
+ reprintBlockBodies: new Set(),
+ snapshots: functionSnapshots,
+ });
const isCoveredByFunctionEdit = (start: number, end: number) =>
coveredRanges.some((range) => start >= range.start && end <= range.end);
const elementEdits: SourceEdit[] = [];
@@ -1807,6 +1568,7 @@ export const updateMultipleSequenceProps = ({
input,
node: snapshot.declaration as unknown as AstNamedTypes.Node,
prettierConfigOverride: prettierConfig,
+ wrapColumn: null,
}),
},
];