🎥 Make videos programmatically with React
Fix codemod indentation and preserve unchanged JSX attributes
Jonny Burgerd8f6cefd324d
diff --git a/packages/codemods/src/print-jsx.ts b/packages/codemods/src/print-jsx.tsindex 3d0045cbb9..d388937d15 100644--- a/packages/codemods/src/print-jsx.ts+++ b/packages/codemods/src/print-jsx.ts@@ -1,14 +1,30 @@+import type {JSXElement, JSXOpeningElement} from '@babel/types';import type {namedTypes} from 'ast-types';import * as recast from 'recast';import {recastLocToOffset} from './recast-loc-to-offset';import {- getIndentationUnit,- getObjectCurlySpacing,- getPreferredQuote,+ getSourceFormattingConfig,+ normalizePrintedIndentation,} from './source-style';const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;+export const captureJsxAttributeSources = (+ node: JSXElement | JSXOpeningElement,+): Map<object, string> => {+ const sources = new Map<object, string>();+ recast.types.visit(node, {+ visitJSXOpeningElement(path) {+ for (const attribute of path.node.attributes ?? []) {+ sources.set(attribute, recast.print(attribute).code);+ }++ this.traverse(path);+ },+ });+ return sources;+};+const escapeJsxStringAttribute = (value: string) => {return value.replace(/[&"<>{}\t\r\n]/g, (character) => {switch (character) {@@ -45,7 +61,7 @@ export const indentInsertedJsx = ({}) => {return insertion.split(/\r?\n/)- .map((line) => `${indent}${line}`)+ .map((line) => (line.length === 0 ? line : `${indent}${line}`)).join(insertion.includes('\r\n') ? '\r\n' : '\n');};@@ -60,44 +76,44 @@ export const printInsertedJsx = ({originalAttributeSources?: ReadonlyMap<object, string>;prettierConfigOverride: Record<string, unknown> | null;}): string => {- const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';- const unit = getIndentationUnit(input, prettierConfigOverride);- const printWidth = prettierConfigOverride?.printWidth;- const configuredTabWidth = prettierConfigOverride?.tabWidth;- const tabWidth =- typeof configuredTabWidth === 'number' &&- Number.isInteger(configuredTabWidth) &&- configuredTabWidth > 0- ? configuredTabWidth- : 2;- recast.types.visit(element, {- visitObjectProperty(path) {- const {node} = path;- if (- !node.computed &&- node.key.type === 'StringLiteral' &&- identifierRegex.test(node.key.value)- ) {- node.key = recast.types.builders.identifier(node.key.value);- }-- this.traverse(path);- return undefined;- },+ const formattingConfig = getSourceFormattingConfig({+ input,+ prettierConfigOverride,});- const printNode = (node: namedTypes.Node, wrapColumn: number) => {+ const {+ endOfLine,+ indentationUnit: unit,+ printWidth,+ tabWidth,+ } = formattingConfig;+ const printNode = (printableNode: namedTypes.Node, wrapColumn: number) => {+ recast.types.visit(printableNode, {+ visitObjectProperty(path) {+ const {node} = path;+ if (+ !node.computed &&+ node.key.type === 'StringLiteral' &&+ identifierRegex.test(node.key.value)+ ) {+ node.key = recast.types.builders.identifier(node.key.value);+ }++ this.traverse(path);+ return undefined;+ },+ });// The generic printer drops comments inside empty JSX expressions.if (- node.type === 'JSXExpressionContainer' &&- (node as namedTypes.JSXExpressionContainer).expression.type ===+ printableNode.type === 'JSXExpressionContainer' &&+ (printableNode as namedTypes.JSXExpressionContainer).expression.type ==='JSXEmptyExpression') {- return recast.print(node).code;+ return recast.print(printableNode).code;}- return recast.prettyPrint(node, {- objectCurlySpacing: prettierConfigOverride?.bracketSpacing !== false,- quote: prettierConfigOverride?.singleQuote === true ? 'single' : 'double',+ return recast.prettyPrint(printableNode, {+ objectCurlySpacing: formattingConfig.bracketSpacing,+ quote: formattingConfig.quote,tabWidth,useTabs: false,wrapColumn,@@ -105,21 +121,16 @@ export const printInsertedJsx = ({};const normalizeIndentation = (code: string) => {- return code- .split(/\r?\n/)- .map((line) => {- const spaces = line.match(/^ */)?.[0].length ?? 0;- const indentationLevels = Math.floor(spaces / tabWidth);- const remainingSpaces = spaces % tabWidth;- return `${unit.repeat(indentationLevels)}${' '.repeat(remainingSpaces)}${line.slice(spaces)}`;- })- .join(endOfLine);+ return normalizePrintedIndentation({+ endOfLine,+ indentationUnit: unit,+ printed: code,+ tabWidth,+ });};const printOpeningElement = (opening: namedTypes.JSXOpeningElement) => {- const effectivePrintWidth =- typeof printWidth === 'number' ? printWidth : 80;- const name = printNode(opening.name, effectivePrintWidth);+ const name = printNode(opening.name, printWidth);const attributes = (opening.attributes ?? []).map((attribute) => {const originalAttributeSource = originalAttributeSources?.get(attribute);if (@@ -164,16 +175,15 @@ export const printInsertedJsx = ({const unwrapped = normalizeIndentation(printNode(attribute, Number.POSITIVE_INFINITY),);- return !unwrapped.includes(endOfLine) &&- unwrapped.length <= effectivePrintWidth+ return !unwrapped.includes(endOfLine) && unwrapped.length <= printWidth? unwrapped- : normalizeIndentation(printNode(attribute, effectivePrintWidth));+ : normalizeIndentation(printNode(attribute, printWidth));});const suffix = opening.selfClosing ? ' />' : '>';const singleLine = `<${name}${attributes.length === 0 ? '' : ` ${attributes.join(' ')}`}${suffix}`;if (!attributes.some((attribute) => attribute.includes(endOfLine)) &&- singleLine.length <= effectivePrintWidth+ singleLine.length <= printWidth) {return singleLine;}@@ -200,11 +210,7 @@ export const printInsertedJsx = ({return [];}- return [- normalizeIndentation(- printNode(child, typeof printWidth === 'number' ? printWidth : 80),- ),- ];+ return [normalizeIndentation(printNode(child, printWidth))];});return ['<>',@@ -221,12 +227,7 @@ export const printInsertedJsx = ({}const closing = node.closingElement- ? normalizeIndentation(- printNode(- node.closingElement,- typeof printWidth === 'number' ? printWidth : 80,- ),- )+ ? normalizeIndentation(printNode(node.closingElement, printWidth)): '';const children = node.children ?? [];if (@@ -243,10 +244,7 @@ export const printInsertedJsx = ({children[0].expression.type === 'StringLiteral') {return `${opening}${normalizeIndentation(- printNode(- children[0],- typeof printWidth === 'number' ? printWidth : 80,- ),+ printNode(children[0], printWidth),)}${closing}`;}@@ -259,11 +257,7 @@ export const printInsertedJsx = ({return [];}- return [- normalizeIndentation(- printNode(child, typeof printWidth === 'number' ? printWidth : 80),- ),- ];+ return [normalizeIndentation(printNode(child, printWidth))];});if (printedChildren.length === 0) {return `${opening}${closing}`;@@ -306,12 +300,7 @@ export const printJsxOpeningElement = ({element: printableElement,input,originalAttributeSources,- prettierConfigOverride: {- bracketSpacing: getObjectCurlySpacing(input, prettierConfigOverride),- singleQuote:- getPreferredQuote(input, prettierConfigOverride) === 'single',- ...prettierConfigOverride,- },+ prettierConfigOverride,});if (wasSelfClosing) {return printed;diff --git a/packages/codemods/src/source-style.ts b/packages/codemods/src/source-style.tsindex 1946c9f942..5afd30898c 100644--- a/packages/codemods/src/source-style.ts+++ b/packages/codemods/src/source-style.ts@@ -53,13 +53,45 @@ export const getIndentationUnit = (input: string,prettierConfigOverride: Record<string, unknown> | null,): string => {- if (/^\t+/m.test(input)) {+ let tabIndentedLines = 0;+ let spaceIndentedLines = 0;+ let previousIndent = '';+ const widths = new Map<number, number>();+ for (const line of input.split(/\r?\n/)) {+ const match = line.match(/^([\t ]*)(\S.*)$/);+ // Comment decoration and blank lines are not indentation levels.+ if (!match || /^(?:\/[/*]|\*)/.test(match[2])) {+ continue;+ }++ const indent = match[1];+ if (indent.includes('\t')) {+ tabIndentedLines++;+ } else if (indent.length > 0) {+ spaceIndentedLines++;+ }++ if (!indent.includes('\t') && !previousIndent.includes('\t')) {+ const difference = Math.abs(indent.length - previousIndent.length);+ if (difference > 0) {+ widths.set(difference, (widths.get(difference) ?? 0) + 1);+ }+ }++ previousIndent = indent;+ }++ if (tabIndentedLines > spaceIndentedLines) {return '\t';}- const indentation = input.match(/^([ ]+)\S/m)?.[1].length;- if (indentation) {- return ' '.repeat(indentation > 1 ? indentation : 2);+ // Prefer the most common change in depth, then the smaller width on ties.+ // The first indented line may be several levels deep or a continuation.+ const indentation = [...widths].sort(+ ([widthA, countA], [widthB, countB]) => countB - countA || widthA - widthB,+ )[0]?.[0];+ if (indentation !== undefined) {+ return ' '.repeat(indentation);}if (prettierConfigOverride?.useTabs === true) {@@ -156,7 +188,12 @@ export const indentContinuationLines = ({input: string;printed: string;}): string => {- return printed.split(/\r?\n/).join(`${getEndOfLine(input)}${indent}`);+ return printed+ .split(/\r?\n/)+ .map((line, index) =>+ index === 0 || line.length === 0 ? line : `${indent}${line}`,+ )+ .join(getEndOfLine(input));};export const indentContinuationLinesAtOffset = ({diff --git a/packages/codemods/src/test/formatting.test.ts b/packages/codemods/src/test/formatting.test.tsnew file mode 100644index 0000000000..a0328ea374--- /dev/null+++ b/packages/codemods/src/test/formatting.test.ts@@ -0,0 +1,85 @@+import {expect, test} from 'bun:test';+import {+ getJsxNodes,+ updateJsxNodeKeyframes,+ updateJsxNodeProps,+} from '../index';++for (const indentation of ['\t', ' ', ' ']) {+ for (const endOfLine of ['\n', '\r\n']) {+ test(`prop and keyframe edits preserve formatting with ${JSON.stringify({indentation, endOfLine})}`, async () => {+ const format = (source: string) =>+ source.replaceAll('\t', indentation).replaceAll('\n', endOfLine);+ const input = format(`/**+ * A composition with a header and a render prop.+ */+import {AbsoluteFill} from 'remotion';++const unrelated = {keep:"this spacing"};++export const Video = () => {+ return (+ <AbsoluteFill+ style={{+ opacity: 0.5,+ }}+ render={() => (+ <section>+ {/* Keep the callback and its indentation. */}++ <span />+ </section>+ )}+ />+ );+};+`);+ const filePath = 'src/Video.tsx';+ const project = {rootDir: '/', files: {[filePath]: input}};+ const [node] = getJsxNodes({project, filePath});+ const changed = updateJsxNodeProps({+ project,+ node,+ props: {title: 'Hello'},+ });+ const expected = input.replace(+ format('\t\t/>'),+ format("\t\t\ttitle={'Hello'}\n\t\t/>"),+ );+ expect(changed.project.files[filePath]).toBe(expected);++ const repeated = updateJsxNodeProps({+ project: changed.project,+ node: changed.updatedNode,+ props: {title: 'Hello'},+ });+ expect(repeated.project.files[filePath]).toBe(expected);++ const animated = await updateJsxNodeKeyframes({+ project: repeated.project,+ node: repeated.updatedNode,+ updates: [+ {key: 'style.opacity', operation: {type: 'add', frame: 0, value: 0}},+ ],+ });+ expect(animated.project.files[filePath]).toBe(+ expected+ .replace(+ '{AbsoluteFill}',+ '{AbsoluteFill, interpolate, useCurrentFrame}',+ )+ .replace(+ format('\treturn ('),+ format('\tconst frame = useCurrentFrame();\n\treturn ('),+ )+ .replace(+ format('\t\t\t\topacity: 0.5,'),+ format(` opacity: interpolate(frame, [0], [0], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp'+ })`),+ ),+ );+ });+ }+}diff --git a/packages/codemods/src/test/source-style.test.ts b/packages/codemods/src/test/source-style.test.tsindex 8a11f657ac..92eebce681 100644--- a/packages/codemods/src/test/source-style.test.ts+++ b/packages/codemods/src/test/source-style.test.ts@@ -2,12 +2,43 @@ import {expect, test} from 'bun:test';import * as recast from 'recast';import {getEndOfLine,+ getIndentationUnit,getLineIndent,getSourceFormattingConfig,indentContinuationLinesAtOffset,printNodeWithSourceStyle,} from '../source-style';+test.each([+ [+ 'a header comment',+ '/**\n * Comment\n */\nconst f = () => {\n return 1;\n};',+ ' ',+ ],+ [+ 'a deeply indented first line',+ 'const f = () => (\n <div>\n <span />\n </div>\n);',+ ' ',+ ],+ [+ 'an aligned continuation',+ 'const value = call(\n argument);\nconst f = () => {\n if (value) {\n return 1;\n }\n};',+ ' ',+ ],+ [+ 'a tab in a comment',+ '// Example:\n\t// indented comment\nconst f = () => {\n return 1;\n};',+ ' ',+ ],+ [+ 'a stray tab-indented line',+ 'const f = () => {\n\tconst a = 1;\n if (a) {\n return a;\n }\n};',+ ' ',+ ],+])('infers indentation despite %s', (_name, input, expected) => {+ expect(getIndentationUnit(input, null)).toBe(expected);+});+test('infers formatting choices from source', () => {const input = "import {thing} from 'pkg'\r\n\r\n\tconst value = 1\r\n";diff --git a/packages/codemods/src/test/update-keyframes-formatting.test.ts b/packages/codemods/src/test/update-keyframes-formatting.test.tsindex 5f4ed5a8d3..b3f2edaed9 100644--- a/packages/codemods/src/test/update-keyframes-formatting.test.ts+++ b/packages/codemods/src/test/update-keyframes-formatting.test.ts@@ -77,7 +77,7 @@ export const Example = () => {extrapolateRight: 'clamp'})}}- data-label={label}+ data-label = {label}/></AbsoluteFill>)diff --git a/packages/codemods/src/test/update-sequence-props.test.ts b/packages/codemods/src/test/update-sequence-props.test.tsindex 4dcc461a24..5649f18a3a 100644--- a/packages/codemods/src/test/update-sequence-props.test.ts+++ b/packages/codemods/src/test/update-sequence-props.test.ts@@ -56,7 +56,7 @@ test('patches an opening element without reprinting its siblings', () => {`);});-test('formats the patched opening element and preserves unrelated formatting', () => {+test('preserves existing attribute formatting when patching an opening element', () => {const input = `const unrelated = {keep:"this spacing"};export const Example = () => {@@ -101,7 +101,7 @@ export const Example = () => {export const Example = () => {return (- <Interactive.Div name="Example" hidden>+ <Interactive.Div name = "Example" hidden>Text</Interactive.Div>);diff --git a/packages/codemods/src/update-keyframes.ts b/packages/codemods/src/update-keyframes.tsindex 5c57ee5121..c5467d2ebb 100644--- a/packages/codemods/src/update-keyframes.ts+++ b/packages/codemods/src/update-keyframes.ts@@ -49,7 +49,7 @@ import {type FunctionNode,type FunctionSourceSnapshot,} from './function-source-edits';-import {printJsxOpeningElement} from './print-jsx';+import {captureJsxAttributeSources, printJsxOpeningElement} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';import {extractStaticValue,@@ -91,11 +91,13 @@ import {parseValueExpression} from './update-nested-prop';const b = recast.types.builders;const getOpeningElementSourceEdit = ({+ originalAttributeSources,input,openingElement,prettierConfigOverride,propertyNames,}: {+ originalAttributeSources: ReadonlyMap<object, string>;input: string;openingElement: JSXOpeningElement;prettierConfigOverride: Record<string, unknown> | null;@@ -107,6 +109,7 @@ const getOpeningElementSourceEdit = ({const start = recastLocToOffset(input, openingElement.loc.start);const printed = printJsxOpeningElement({+ originalAttributeSources,openingElement: openingElement as never,input,prettierConfigOverride,@@ -180,6 +183,7 @@ const getKeyframeFunctionSourceEdits = ({};const getKeyframeSourceOutput = ({+ originalAttributeSources,ast,functionSourceCoveredRanges,functionSourceEdits,@@ -189,6 +193,7 @@ const getKeyframeSourceOutput = ({prettierConfigOverride,propertyNames,}: {+ originalAttributeSources: ReadonlyMap<object, string>;ast: File;functionSourceCoveredRanges: {end: number; start: number}[];functionSourceEdits: SourceEdit[];@@ -224,6 +229,7 @@ const getKeyframeSourceOutput = ({...(!openingElementIsCovered? [getOpeningElementSourceEdit({+ originalAttributeSources,input,openingElement,prettierConfigOverride,@@ -2036,6 +2042,8 @@ export const updateSequenceKeyframesAst = ({node.attributes = [];}+ const originalAttributeSources = captureJsxAttributeSources(node);+const requiredImports = new Set<string>();let needsFrameHook = false;@@ -2116,6 +2124,7 @@ export const updateSequenceKeyframesAst = ({return {serialized: getKeyframeSourceOutput({+ originalAttributeSources,ast,functionSourceCoveredRanges,functionSourceEdits,@@ -2228,6 +2237,7 @@ export const updateEffectKeyframesAst = ({}const attr = findEffectsAttr(jsx.attributes ?? []);+ const originalAttributeSources = captureJsxAttributeSources(jsx);if (!attr) {throw new Error('Could not find effects on the target JSX element');}@@ -2318,6 +2328,7 @@ export const updateEffectKeyframesAst = ({return {serialized: getKeyframeSourceOutput({+ originalAttributeSources,ast,functionSourceCoveredRanges,functionSourceEdits,diff --git a/packages/codemods/src/update-sequence-props.ts b/packages/codemods/src/update-sequence-props.tsindex ebf620452c..1368736f70 100644--- a/packages/codemods/src/update-sequence-props.ts+++ b/packages/codemods/src/update-sequence-props.ts@@ -28,7 +28,11 @@ import {getFunctionSourceEditsForPrependedStatements,type FunctionNode,} from './function-source-edits';-import {printInsertedJsx, printJsxOpeningElement} from './print-jsx';+import {+ captureJsxAttributeSources,+ printInsertedJsx,+ printJsxOpeningElement,+} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';import {findNodePathForJsxElement,@@ -1417,6 +1421,11 @@ export const updateMultipleSequenceProps = ({updates.some((update) => update.key === 'children') ? [jsxElement] : [],),);+ const originalAttributeSources = new Map(+ resolvedChanges.flatMap(({jsxElement}) => [+ ...captureJsxAttributeSources(jsxElement),+ ]),+ );const openingElementLocations = new Map(resolvedChanges.flatMap(({jsxElement}) =>elementsWithChildrenUpdates.has(jsxElement)@@ -1507,6 +1516,7 @@ export const updateMultipleSequenceProps = ({indent: getJsxSourceIndent(start),input,printed: printJsxOpeningElement({+ originalAttributeSources,openingElement:openingElement as unknown as AstNamedTypes.JSXOpeningElement,input,@@ -1539,6 +1549,7 @@ export const updateMultipleSequenceProps = ({indent: getJsxSourceIndent(start),input,printed: printInsertedJsx({+ originalAttributeSources,element: element as unknown as AstNamedTypes.JSXElement,input,prettierConfigOverride: jsxFormattingConfig,