🎥 Make videos programmatically with React
@remotion/studio-codemods: Remove Prettier from default props updates
Jonny Burger6f61b0b9feac
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 65e448ed7b..a3ecc97f50 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -11,7 +11,6 @@ import {getCanUpdateDefaultPropsForProject,getCompositionComponentInfo,getCompositionFile,- formatInlineContentWithFormatter,getFolderFile,getRootFileForProject,insertJsxElementIntoProjectWithNodePathRemappings,@@ -32,7 +31,6 @@ import {updateEffectKeyframes,updateSequenceKeyframes,type EffectKeyframeUpdate,- type FormatInline,type SequenceKeyframeUpdate,} from '@remotion/studio-codemods';import {@@ -90,25 +88,6 @@ const formatCodemodFile = async ({contents}: {contents: string}) => ({}),});-const formatInline: FormatInline = ({inlineContent, linePrefix, endOfLine}) =>- formatInlineContentWithFormatter({- inlineContent,- linePrefix,- endOfLine,- prettierConfig: {- bracketSpacing: false,- parser: 'typescript',- singleQuote: true,- tabWidth: 2,- useTabs: false,- },- format: (source, options) =>- format(source, {- ...options,- plugins: [prettierPluginTypescript, prettierPluginEstree],- }),- });-const getStructuredError = (error: unknown) => ({success: false as const,reason: error instanceof Error ? error.message : String(error),@@ -1863,7 +1842,6 @@ export const createBrowserStudioOperations = ({compositionId,newDefaultProps: JSON.parse(defaultProps),enumPaths,- formatInline,});controller.applyMutation({undoRedoNavigation: null,diff --git a/packages/studio-codemods/src/update-default-props.ts b/packages/studio-codemods/src/update-default-props.tsindex 7413794110..523fde09c2 100644--- a/packages/studio-codemods/src/update-default-props.ts+++ b/packages/studio-codemods/src/update-default-props.ts@@ -2,6 +2,12 @@ import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';import * as recast from 'recast';import {recastLocToOffset} from './recast-loc-to-offset';import {parseAst} from './sequence-props/parse-ast';+import {+ getSourceFormattingConfig,+ normalizePrintedIndentation,+} from './source-style';++const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;export type FormatInline = (options: {inlineContent: string;@@ -88,18 +94,20 @@ export const formatInlineContentWithFormatter = async ({return {formatted: indentedProps, didFormat: true};};+/* eslint-disable require-await -- Keep the formatter-era Promise API. */export const updateDefaultProps = async ({input,compositionId,newDefaultProps,enumPaths,- formatInline,}: {input: string;compositionId: string;newDefaultProps: Record<string, unknown>;enumPaths: EnumPath[];- formatInline: FormatInline;+ // Kept optional for compatibility with callers from before source-aware+ // printing replaced the inline formatter.+ formatInline?: FormatInline;}): Promise<{output: string; formatted: boolean}> => {const ast = parseAst(input);const stringified = stringifyDefaultProps({@@ -231,13 +239,119 @@ export const updateDefaultProps = async ({// linePrefix includes the JSX container opening braceconst lineStart = input.lastIndexOf('\n', replaceStart) + 1;const linePrefix = input.substring(lineStart, replaceStart + 1);+ const previousValue = input.slice(replaceStart + 1, replaceEnd - 1).trim();+ const inlineObjectSpacing = previousValue.match(+ /\{([\t ]*)(?=(?:["'][^"']+["']|[$A-Z_a-z][$\w]*)[\t ]*:)/,+ )?.[1];+ const bracketSpacing = previousValue.startsWith('{ ')+ ? true+ : previousValue.startsWith('{') &&+ !previousValue.startsWith('{\n') &&+ !previousValue.startsWith('{\r\n')+ ? false+ : inlineObjectSpacing === undefined+ ? null+ : inlineObjectSpacing.length > 0;+ const formattingConfig = getSourceFormattingConfig({+ input,+ prettierConfigOverride: bracketSpacing === null ? null : {bracketSpacing},+ });+ const valueAst = parseAst(`__defaultProps = ${stringified}`);+ const statement = valueAst.program.body[0];+ if (+ statement?.type !== 'ExpressionStatement' ||+ statement.expression.type !== 'AssignmentExpression'+ ) {+ throw new Error('Could not parse the updated defaultProps value');+ }++ const expression = statement.expression.right;+ recast.types.visit(expression, {+ 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);+ }- const {formatted, didFormat} = await formatInline({- inlineContent: stringified,- linePrefix,- endOfLine: 'auto',+ this.traverse(path);+ },});+ const printExpression = ({+ trailingComma,+ wrapColumn,+ }: {+ trailingComma: boolean;+ wrapColumn: number;+ }) => {+ const printed = recast.prettyPrint(expression, {+ objectCurlySpacing: formattingConfig.bracketSpacing,+ quote: formattingConfig.quote,+ tabWidth: formattingConfig.tabWidth,+ trailingComma,+ useTabs: false,+ wrapColumn,+ }).code;++ return normalizePrintedIndentation({+ endOfLine: formattingConfig.endOfLine,+ indentationUnit: formattingConfig.indentationUnit,+ printed,+ tabWidth: formattingConfig.tabWidth,+ });+ };++ const compactLines = printExpression({+ trailingComma: false,+ wrapColumn: Number.POSITIVE_INFINITY,+ })+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ const compact = compactLines.reduce((result, line) => {+ if (result.length === 0) {+ return line;+ }++ const omitSeparator =+ !formattingConfig.bracketSpacing &&+ (result.endsWith('{') || line.startsWith('}'));+ return `${result}${omitSeparator ? '' : ' '}${line}`;+ }, '');+ const columnOffset = [...linePrefix].reduce(+ (column, character) =>+ character === '\t' ? column + formattingConfig.tabWidth : column + 1,+ 0,+ );+ const compactWidth = [...compact].reduce(+ (column, character) =>+ character === '\t' ? column + formattingConfig.tabWidth : column + 1,+ 0,+ );+ const baseIndent = linePrefix.match(/^([\t ]*)/)?.[1] ?? '';+ const effectivePrintWidth = Math.max(+ formattingConfig.printWidth - columnOffset,+ 20,+ );+ const multiline = printExpression({+ trailingComma: true,+ wrapColumn: effectivePrintWidth,+ })+ .split(/\r?\n/)+ .filter((line) => line.trim().length > 0)+ .map((line, index) =>+ index === 0 || line.length === 0 ? line : baseIndent + line,+ )+ .join(formattingConfig.endOfLine);+ const formatted =+ columnOffset + compactWidth + 1 <= formattingConfig.printWidth+ ? compact+ : multiline;+// Replace the JSX expression container in the original inputconst output =input.substring(0, replaceStart) +@@ -246,8 +360,9 @@ export const updateDefaultProps = async ({'}' +input.substring(replaceEnd);- return {output, formatted: didFormat};+ return {output, formatted: true};};+/* eslint-enable require-await *//** Line of the matching `<Composition>` / `<Still>` opening tag (for log links). */export const getCompositionDefaultPropsLine = ({diff --git a/packages/studio-server/src/codemods/format-inline-content.ts b/packages/studio-server/src/codemods/format-inline-content.tsdeleted file mode 100644index d1eb1640c1..0000000000--- a/packages/studio-server/src/codemods/format-inline-content.ts+++ /dev/null@@ -1,58 +0,0 @@-import {formatInlineContentWithFormatter} from '@remotion/studio-codemods';--// eslint-disable-next-line @typescript-eslint/consistent-type-imports-type PrettierType = typeof import('prettier');--/**- * Instead of running prettier on the entire file (which is slow),- * format only a small snippet of inline content (e.g. stringified defaultProps).- *- * @param inlineContent - The raw content to format (e.g. stringified props)- * @param linePrefix - Everything from the start of the line to where- * inlineContent will appear (used to calculate column offset and indentation)- * @param endOfLine - Prettier endOfLine option- */-export const formatInlineContent = async ({- inlineContent,- linePrefix,- endOfLine,- prettierConfigOverride,-}: {- inlineContent: string;- linePrefix: string;- endOfLine: 'auto' | 'lf';- prettierConfigOverride?: Record<string, unknown> | null;-}): Promise<{formatted: string; didFormat: boolean}> => {- let prettier: PrettierType | null = null;-- try {- prettier = await import('prettier');- } catch {- return {formatted: inlineContent, didFormat: false};- }-- const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;-- let prettierConfig: Record<string, unknown> | null;- if (prettierConfigOverride !== undefined && prettierConfigOverride !== null) {- prettierConfig = prettierConfigOverride;- } else {- const configFilePath = await resolveConfigFile();- if (!configFilePath) {- return {formatted: inlineContent, didFormat: false};- }-- prettierConfig = await resolveConfig(configFilePath);- if (!prettierConfig) {- return {formatted: inlineContent, didFormat: false};- }- }-- return formatInlineContentWithFormatter({- inlineContent,- linePrefix,- endOfLine,- prettierConfig,- format: (source, options) => format(source, {...options, plugins: []}),- });-};diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.tsindex c4fc7dc263..eaaead7d3f 100644--- a/packages/studio-server/src/codemods/update-default-props.ts+++ b/packages/studio-server/src/codemods/update-default-props.ts@@ -1,30 +1,4 @@-import {- updateDefaultProps as updateDefaultPropsCodemod,- type FormatInline,+export {+ getCompositionDefaultPropsLine,+ updateDefaultProps,} from '@remotion/studio-codemods';-import type {EnumPath} from '@remotion/studio-shared';-import {formatInlineContent} from './format-inline-content';--export {getCompositionDefaultPropsLine} from '@remotion/studio-codemods';--const formatInline: FormatInline = ({inlineContent, linePrefix, endOfLine}) =>- formatInlineContent({inlineContent, linePrefix, endOfLine});--export const updateDefaultProps = ({- input,- compositionId,- newDefaultProps,- enumPaths,-}: {- input: string;- compositionId: string;- newDefaultProps: Record<string, unknown>;- enumPaths: EnumPath[];-}): Promise<{output: string; formatted: boolean}> =>- updateDefaultPropsCodemod({- input,- compositionId,- newDefaultProps,- enumPaths,- formatInline,- });diff --git a/packages/studio-server/src/preview-server/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.tsindex 7152c37c7e..dc96376a7a 100644--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts@@ -19,7 +19,6 @@ import {} from '../undo-stack';import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {checkIfTypeScriptFile} from './can-update-default-props';-import {warnAboutPrettierOnce} from './log-updates/log-update';import {getCodemodTimingPrefix,withSourceFileWriteQueue,@@ -52,7 +51,7 @@ export const updateDefaultPropsHandler: ApiHandler<input: fileContents,compositionId,});- const {output, formatted} = await updateDefaultProps({+ const {output} = await updateDefaultProps({compositionId,input: fileContents,newDefaultProps: JSON.parse(defaultProps),@@ -92,9 +91,6 @@ export const updateDefaultPropsHandler: ApiHandler<{indent: false, logLevel},`${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(`${locationLabel}`)} Updated default props for "${compositionId}"`,);- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }printUndoHint(logLevel);diff --git a/packages/studio-server/src/test/update-default-props.test.ts b/packages/studio-server/src/test/update-default-props.test.tsindex 9c63efdf63..c2cb4196b4 100644--- a/packages/studio-server/src/test/update-default-props.test.ts+++ b/packages/studio-server/src/test/update-default-props.test.ts@@ -1,13 +1,13 @@import {expect, test} from 'bun:test';import {readFileSync} from 'node:fs';import path from 'node:path';+import {parseAst} from '../codemods/parse-ast';import {getCompositionDefaultPropsLine,updateDefaultProps,} from '../codemods/update-default-props';-import {prettify} from './test-utils';-test('Should be able to update default props', async () => {+test('updates default props without changing surrounding source', async () => {const file = readFileSync(path.join(__dirname, 'snapshots', 'root-before.tsx'),'utf-8',@@ -24,7 +24,7 @@ test('Should be able to update default props', async () => {enumPaths: [],});- expect(await prettify(output)).toBe(await prettify(expected));+ expect(output).toBe(expected);});test('getCompositionDefaultPropsLine returns the opening tag line (ast-types visitor must traverse)', () => {@@ -41,7 +41,7 @@ test('getCompositionDefaultPropsLine returns the opening tag line (ast-types vis).toBe(27);});-test('Should be able to update default props', async () => {+test('replaces multiline default props with a compact value', async () => {const file = readFileSync(path.join(__dirname, 'snapshots', 'problematic.tsx'),'utf-8',@@ -58,5 +58,120 @@ test('Should be able to update default props', async () => {enumPaths: [],});- expect(await prettify(output)).toBe(await prettify(expected));+ expect(output).toBe(expected);+});++test('formats multiline default props without calling the compatibility formatter', async () => {+ const input = `import {Composition} from 'remotion'++const untouched = {keep:"this spacing"}++export const Root=()=>(+ <Composition+ id='Comp'+ defaultProps={{old : "value"}}+ />+)+`;+ let formatCalls = 0;++ const {output, formatted} = await updateDefaultProps({+ input,+ compositionId: 'Comp',+ newDefaultProps: {+ title: 'Hello',+ publishedAt: 'remotion-date:2026-07-29T00:00:00.000Z',+ audio: 'remotion-file:my%20folder/audio%20%231.wav',+ mode: 'fast',+ },+ enumPaths: [['mode']],+ formatInline: () => {+ formatCalls++;+ throw new Error('Prettier must not be called');+ },+ });++ expect(formatted).toBe(true);+ expect(formatCalls).toBe(0);+ expect(output).toBe(`import {Composition} from 'remotion'++const untouched = {keep:"this spacing"}++export const Root=()=>(+ <Composition+ id='Comp'+ defaultProps={{+ title: 'Hello',+ publishedAt: new Date('2026-07-29T00:00:00.000Z'),+ audio: staticFile('my folder/audio #1.wav'),+ mode: 'fast' as const,+ }}+ />+)+`);+});++test('preserves CRLF, spaces, double quotes, and bracket spacing', async () => {+ const input = [+ 'import { Composition } from "remotion"',+ '',+ 'const untouched = {keep:"this spacing"}',+ '',+ 'export const Root = () => (',+ ' <Composition',+ ' id="Comp"',+ ' defaultProps={{ old: "value" }}',+ ' />',+ ')',+ '',+ ].join('\r\n');++ const {output} = await updateDefaultProps({+ input,+ compositionId: 'Comp',+ newDefaultProps: {title: 'Hello'},+ enumPaths: [],+ });++ expect(output).toBe(+ input.replace(+ 'defaultProps={{ old: "value" }}',+ 'defaultProps={{ title: "Hello" }}',+ ),+ );+});++test('formats nested arrays and keeps non-identifier keys quoted', async () => {+ const input = `export const Root = () => (+ <Composition id="Comp" defaultProps={{ old: true }} />+)+`;++ const {output} = await updateDefaultProps({+ input,+ compositionId: 'Comp',+ newDefaultProps: {+ items: [+ {mode: 'fast', label: 'hello'},+ {mode: 'slow', label: 'world'},+ ],+ 'dash-key': true,+ },+ enumPaths: [['items', '[]', 'mode']],+ });++ expect(output).toBe(`export const Root = () => (+ <Composition id="Comp" defaultProps={{+ items: [{+ mode: "fast" as const,+ label: "hello",+ }, {+ mode: "slow" as const,+ label: "world",+ }],+ "dash-key": true,+ }} />+)+`);+ expect(() => parseAst(output)).not.toThrow();});