🎥 Make videos programmatically with React
Remove Prettier from sequence and keyframe mutations
Jonny Burger939cd341566e
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 13c91567b6..61ba75eb06 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -587,7 +587,6 @@ export const createBrowserStudioOperations = ({updates: mutation.updates,schema: mutation.schema,videoConfigValues: mutation.nodePath.videoConfigValues,- formatFile: formatCodemodFile,});files[absolutePath] = result.output;appliedSequenceMutations.push({@@ -609,7 +608,6 @@ export const createBrowserStudioOperations = ({updates: mutation.updates,schema: mutation.schema,videoConfigValues: mutation.sequenceNodePath.videoConfigValues,- formatFile: formatCodemodFile,});files[absolutePath] = result.output;appliedEffectMutations.push({diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex bdf01c69fa..fbbdf1f9d7 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -670,7 +670,7 @@ export const Root = () => <Composition id="MyComp" component={Component} duratioredoLabel: 'Reapply property paste',});expect(currentProject.files[fileName]).toContain(- 'rotate: interpolate(frame, [0, 30], ["0deg", "90deg"])',+ "rotate: interpolate(frame, [0, 30], ['0deg', '90deg'])",);expect(await operations.undo()).toEqual({success: true,diff --git a/packages/studio-codemods/src/insert-jsx-element.ts b/packages/studio-codemods/src/insert-jsx-element.tsindex e5b104efef..be33aaaa80 100644--- a/packages/studio-codemods/src/insert-jsx-element.ts+++ b/packages/studio-codemods/src/insert-jsx-element.ts@@ -2354,7 +2354,23 @@ export const getInsertImportSourceEdits = ({.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({@@ -2373,7 +2389,22 @@ export const getInsertImportSourceEdits = ({start: offset,});} else {- edits.push({end: 0, replacement: `${rendered}${endOfLine}`, start: 0});+ 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,+ });+ }}}diff --git a/packages/studio-codemods/src/print-jsx.ts b/packages/studio-codemods/src/print-jsx.tsindex 39679a4402..e47a62e689 100644--- a/packages/studio-codemods/src/print-jsx.ts+++ b/packages/studio-codemods/src/print-jsx.ts@@ -3,6 +3,69 @@ import * as recast from 'recast';const identifierRegex = /^[A-Za-z_$][0-9A-Za-z_$]*$/;+const escapeJsxStringAttribute = (value: string) => {+ return value.replace(/[&"<>{}\t\r\n]/g, (character) => {+ switch (character) {+ case '&':+ return '&';+ case '"':+ return '"';+ case '<':+ return '<';+ case '>':+ return '>';+ case '{':+ return '{';+ case '}':+ return '}';+ case '\t':+ return '	';+ case '\r':+ return ' ';+ case '\n':+ return ' ';+ default:+ throw new Error(`Unexpected JSX attribute character: ${character}`);+ }+ });+};++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,@@ -75,7 +138,7 @@ export const printInsertedJsx = ({return undefined;},});- const printNode = (node: namedTypes.Node) => {+ const printNode = (node: namedTypes.Node, wrapColumn: number) => {// The generic printer drops comments inside empty JSX expressions.if (node.type === 'JSXExpressionContainer' &&@@ -90,7 +153,7 @@ export const printInsertedJsx = ({quote: prettierConfigOverride?.singleQuote === true ? 'single' : 'double',tabWidth,useTabs: false,- wrapColumn: typeof printWidth === 'number' ? printWidth : 80,+ wrapColumn,}).code;};@@ -107,23 +170,31 @@ export const printInsertedJsx = ({};const printOpeningElement = (opening: namedTypes.JSXOpeningElement) => {- const name = printNode(opening.name);+ const effectivePrintWidth =+ typeof printWidth === 'number' ? printWidth : 80;+ const name = printNode(opening.name, effectivePrintWidth);const attributes = (opening.attributes ?? []).map((attribute) => {if (attribute.type === 'JSXAttribute' &&attribute.name.type === 'JSXIdentifier' &&attribute.value?.type === 'StringLiteral') {- return `${attribute.name.name}=${JSON.stringify(attribute.value.value)}`;+ return `${attribute.name.name}="${escapeJsxStringAttribute(attribute.value.value)}"`;}- return normalizeIndentation(printNode(attribute));+ const unwrapped = normalizeIndentation(+ printNode(attribute, Number.POSITIVE_INFINITY),+ );+ return !unwrapped.includes(endOfLine) &&+ unwrapped.length <= effectivePrintWidth+ ? unwrapped+ : normalizeIndentation(printNode(attribute, effectivePrintWidth));});const suffix = opening.selfClosing ? ' />' : '>';const singleLine = `<${name}${attributes.length === 0 ? '' : ` ${attributes.join(' ')}`}${suffix}`;if (!attributes.some((attribute) => attribute.includes(endOfLine)) &&- singleLine.length <= (typeof printWidth === 'number' ? printWidth : 80)+ singleLine.length <= effectivePrintWidth) {return singleLine;}@@ -150,7 +221,11 @@ export const printInsertedJsx = ({return [];}- return [normalizeIndentation(printNode(child))];+ return [+ normalizeIndentation(+ printNode(child, typeof printWidth === 'number' ? printWidth : 80),+ ),+ ];});return ['<>',@@ -167,7 +242,12 @@ export const printInsertedJsx = ({}const closing = node.closingElement- ? normalizeIndentation(printNode(node.closingElement))+ ? normalizeIndentation(+ printNode(+ node.closingElement,+ typeof printWidth === 'number' ? printWidth : 80,+ ),+ ): '';const children = node.children ?? [];if (@@ -178,6 +258,19 @@ export const printInsertedJsx = ({return `${opening}${children[0].value}${closing}`;}+ if (+ children.length === 1 &&+ children[0].type === 'JSXExpressionContainer' &&+ children[0].expression.type === 'StringLiteral'+ ) {+ return `${opening}${normalizeIndentation(+ printNode(+ children[0],+ typeof printWidth === 'number' ? printWidth : 80,+ ),+ )}${closing}`;+ }+const printedChildren = children.flatMap((child) => {if (child.type === 'JSXElement' || child.type === 'JSXFragment') {return [printElement(child)];@@ -187,7 +280,11 @@ export const printInsertedJsx = ({return [];}- return [normalizeIndentation(printNode(child))];+ return [+ normalizeIndentation(+ printNode(child, typeof printWidth === 'number' ? printWidth : 80),+ ),+ ];});if (printedChildren.length === 0) {return `${opening}${closing}`;@@ -204,3 +301,48 @@ export const printInsertedJsx = ({return printElement(element);};++export const printJsxOpeningElement = ({+ openingElement,+ input,+ prettierConfigOverride,+}: {+ openingElement: namedTypes.JSXOpeningElement;+ input: string;+ prettierConfigOverride: Record<string, unknown> | null;+}): string => {+ const wasSelfClosing = openingElement.selfClosing ?? false;+ const printableOpeningElement = {+ ...openingElement,+ selfClosing: true,+ };+ const printableElement = recast.types.builders.jsxElement(+ printableOpeningElement,+ null,+ [],+ );+ const printed = printInsertedJsx({+ element: printableElement,+ input,+ prettierConfigOverride: {+ bracketSpacing: getObjectCurlySpacing(input, prettierConfigOverride),+ singleQuote:+ getPreferredQuote(input, prettierConfigOverride) === 'single',+ ...prettierConfigOverride,+ },+ });+ if (wasSelfClosing) {+ return printed;+ }++ if (!printed.endsWith('/>')) {+ throw new Error('Expected a printed self-closing JSX element');+ }++ const slashIndex = printed.length - 2;+ const lastLineStart = printed.lastIndexOf('\n') + 1;+ const beforeSlash = printed.slice(lastLineStart, slashIndex);+ return beforeSlash.trim().length === 0+ ? `${printed.slice(0, slashIndex)}>`+ : `${printed.slice(0, slashIndex).trimEnd()}>`;+};diff --git a/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts b/packages/studio-codemods/src/test/update-keyframes-formatting.test.tsnew file mode 100644index 0000000000..5d064c2a87--- /dev/null+++ b/packages/studio-codemods/src/test/update-keyframes-formatting.test.ts@@ -0,0 +1,395 @@+import {expect, test} from 'bun:test';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import {getNodePathForRecastPath} from '../sequence-props';+import {parseAst} from '../sequence-props/parse-ast';+import {+ updateEffectKeyframes,+ updateSequenceKeyframes,+} from '../update-keyframes';++const getNodePathAtLine = (input: string, line: number): SequenceNodePath => {+ const ast = parseAst(input);+ let nodePath: SequenceNodePath | null = null;+ recast.types.visit(ast, {+ visitJSXOpeningElement(path) {+ if (path.node.loc?.start.line === line) {+ nodePath = getNodePathForRecastPath(path, ast);+ return false;+ }++ return this.traverse(path);+ },+ });+ if (!nodePath) {+ throw new Error(`Could not find a JSX element on line ${line}`);+ }++ return nodePath;+};++test('sequence keyframes preserve source style without calling Prettier', async () => {+ const input = `import {AbsoluteFill} from 'remotion'++// Keep this deliberately non-Prettier code untouched.+const unrelated = {keep:"this spacing"}++export const Example = () => {+ const label = "untouched"+ return (+ <AbsoluteFill>+ <div style = {{opacity: 0.5}} data-label = {label}/>+ </AbsoluteFill>+ )+}+`;+ const {formatted, output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 10),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 12, value: 0.75},+ },+ ],+ videoConfigValues: null,+ formatFile: () => {+ throw new Error('The compatibility formatter must not be called');+ },+ });++ expect(formatted).toBe(true);+ expect(output)+ .toBe(`import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion'++// Keep this deliberately non-Prettier code untouched.+const unrelated = {keep:"this spacing"}++export const Example = () => {+ const frame = useCurrentFrame()+ const label = "untouched"+ return (+ <AbsoluteFill>+ <div+ style={{+ opacity: interpolate(frame, [12], [0.75], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp'+ })+ }}+ data-label={label}+ />+ </AbsoluteFill>+ )+}+`);+});++test('effect keyframes only format the edited opening element', async () => {+ const input = `import {AbsoluteFill,interpolate,useCurrentFrame} from "remotion";+import {blur} from "@remotion/effects/blur";++const unrelated = {keep:'this spacing'};++export const Example = () => {+ const frame=useCurrentFrame();+ return (+ <AbsoluteFill effects = {[blur({radius:interpolate(frame,[0,20],[1,3])})]}>+ Keep me+ </AbsoluteFill>+ );+};+`;+ const {formatted, output} = await updateEffectKeyframes({+ input,+ sequenceNodePath: getNodePathAtLine(input, 9),+ effectIndex: 0,+ updates: [+ {+ key: 'radius',+ operation: {type: 'add', frame: 10, value: 2},+ },+ ],+ videoConfigValues: null,+ formatFile: () => {+ throw new Error('The compatibility formatter must not be called');+ },+ });++ expect(formatted).toBe(true);+ expect(output)+ .toBe(`import {AbsoluteFill,interpolate,useCurrentFrame} from "remotion";+import {blur} from "@remotion/effects/blur";++const unrelated = {keep:'this spacing'};++export const Example = () => {+ const frame=useCurrentFrame();+ return (+ <AbsoluteFill+ effects={[blur({+ radius: interpolate(frame, [0, 10, 20], [1, 2, 3])+ })]}+ >+ Keep me+ </AbsoluteFill>+ );+};+`);+});++test('sequence keyframes preserve blank lines in unrelated objects', async () => {+ const input = `import {interpolate, useCurrentFrame} from 'remotion';++const unrelated = {+ opacity: 0.4,++ nested: true,+};++export const Example = () => {+ const frame = useCurrentFrame();+ return (+ <div+ style={{+ opacity: interpolate(frame, [0], [0.5]),++ transform: 'none',+ }} />+ );+};+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 12),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 10, value: 0.75},+ },+ ],+ videoConfigValues: null,+ });++ expect(output).toContain(`const unrelated = {+ opacity: 0.4,++ nested: true,+};`);+ expect(output).toContain(+ "opacity: interpolate(frame, [0, 10], [0.5, 0.75]),\n transform: 'none'",+ );+});++test('new keyframe imports stay after directives', async () => {+ const input = `'use client'++const unrelated = true++export const Example = () => (+ <div style={{opacity:0.5}} />+)+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 6),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 8, value: 1},+ },+ ],+ videoConfigValues: null,+ });++ expect(output).toBe(`'use client'+import { interpolate, useCurrentFrame } from 'remotion'++const unrelated = true++export const Example = () => {+ const frame = useCurrentFrame()+ return (+ <div+ style={{+ opacity: interpolate(frame, [8], [1], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp'+ })+ }} />+ )+}+`);+});++test('frame hooks stay before comments attached to the first statement', async () => {+ const input = `import {AbsoluteFill} from 'remotion';++export const Example = () => {+ 'use strict';+ // Keep this comment attached to the return.+ return (+ <AbsoluteFill style={{opacity: 0.5}} />+ );+};+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 7),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 8, value: 1},+ },+ ],+ videoConfigValues: null,+ });++ expect(output)+ .toBe(`import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';++export const Example = () => {+ 'use strict';+ const frame = useCurrentFrame();+ // Keep this comment attached to the return.+ return (+ <AbsoluteFill+ style={{+ opacity: interpolate(frame, [8], [1], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp'+ })+ }}+ />+ );+};+`);+});++test('frame hooks separate comments immediately after the opening brace', async () => {+ const input = `import {AbsoluteFill} from 'remotion';++export const Example = () => {/* Explain the return. */+ return (+ <AbsoluteFill style={{opacity: 0.5}} />+ );+};+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 5),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 8, value: 1},+ },+ ],+ videoConfigValues: null,+ });++ expect(output)+ .toBe(`import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';++export const Example = () => {+ const frame = useCurrentFrame();+ /* Explain the return. */+ return (+ <AbsoluteFill+ style={{+ opacity: interpolate(frame, [8], [1], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp'+ })+ }}+ />+ );+};+`);+});++test('frame hooks reformat compact function blocks', async () => {+ const input = `export const C = () => { 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(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"+ })+ }} />+ )+}+`);+});++test('existing keyframes get source-aware indentation in compact blocks', async () => {+ const input = `import {interpolate, useCurrentFrame} from 'remotion';+export const C = () => { const frame = useCurrentFrame(); return <div style={{opacity: interpolate(frame, [0], [0.5])}} /> }+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 2),+ updates: [+ {+ key: 'style.opacity',+ operation: {type: 'add', frame: 8, value: 1},+ },+ ],+ videoConfigValues: null,+ });++ expect(output).toBe(`import {interpolate, useCurrentFrame} from 'remotion';+export const C = () => {+ const frame = useCurrentFrame();+ return (+ <div+ style={{+ opacity: interpolate(frame, [0, 8], [0.5, 1])+ }} />+ );+}+`);+});++test('keyframe mutations preserve JSX string attribute values', async () => {+ const input = `import {interpolate, useCurrentFrame} from 'remotion';++export const Example = () => {+ const frame = useCurrentFrame();+ return <div title=""" opacity={interpolate(frame, [0], [0.5])} />;+};+`;+ const {output} = await updateSequenceKeyframes({+ input,+ nodePath: getNodePathAtLine(input, 5),+ updates: [+ {+ key: 'opacity',+ operation: {type: 'add', frame: 10, value: 0.75},+ },+ ],+ videoConfigValues: null,+ });++ expect(output).toContain('title="""');+ expect(output).toContain(+ 'opacity={interpolate(frame, [0, 10], [0.5, 0.75])}',+ );+ expect(() => parseAst(output)).not.toThrow();+});diff --git a/packages/studio-codemods/src/test/update-sequence-props.test.ts b/packages/studio-codemods/src/test/update-sequence-props.test.tsindex 4f3bd29cae..122ea8aa24 100644--- a/packages/studio-codemods/src/test/update-sequence-props.test.ts+++ b/packages/studio-codemods/src/test/update-sequence-props.test.ts@@ -56,6 +56,436 @@ test('patches an opening element without reprinting its siblings', () => {`);});+test('formats the patched opening element and preserves unrelated formatting', () => {+ const input = `const unrelated = {keep:"this spacing"};++export const Example = () => {+ return (+ <Interactive.Div+ name = "Example"+ >+ Text+ </Interactive.Div>+ );+};+`;+ const ast = parseAst(input);+ let nodePath = null;+ recast.types.visit(ast, {+ visitJSXOpeningElement(path) {+ if (path.node.loc?.start.line === 5) {+ nodePath = getNodePathForRecastPath(path, ast);+ return false;+ }++ return this.traverse(path);+ },+ });+ if (!nodePath) {+ throw new Error('Could not find the Interactive.Div');+ }++ const {output} = updateMultipleSequenceProps({+ input,+ changes: [+ {+ nodePath,+ updates: [{key: 'hidden', value: true, defaultValue: false}],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ });++ expect(output).toBe(`const unrelated = {keep:"this spacing"};++export const Example = () => {+ return (+ <Interactive.Div name="Example" hidden>+ Text+ </Interactive.Div>+ );+};+`);+});++test('preserves JSX string attribute values while patching another prop', () => {+ const input = `export const Example = () => (+ <div title="" &" />+);+`;+ 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 div');+ }++ const {output} = updateMultipleSequenceProps({+ input,+ changes: [+ {+ nodePath,+ updates: [{key: 'hidden', value: true, defaultValue: false}],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ });++ expect(output).toBe(`export const Example = () => (+ <div title="" &" hidden />+);+`);+ expect(() => parseAst(output)).not.toThrow();+});++test('inserts a source-styled import for a local asset without formatting the file', () => {+ const input = `"use client";++import {Video} from "@remotion/media"++const unrelated = {keep:"spacing"}++export const Example = () => {+ return <Video src="https://example.com/old.mp4" />+}+`;+ 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 Video');+ }++ const {output} = updateMultipleSequenceProps({+ input,+ changes: [+ {+ nodePath,+ updates: [+ {+ key: 'src',+ value: 'remotion-file:folder/new%20video.mp4',+ defaultValue: null,+ },+ ],+ schema: {+ src: {+ type: 'asset',+ default: undefined,+ keyframable: false,+ },+ },+ videoConfigValues: null,+ },+ ],+ });++ expect(output).toBe(`"use client";++import {staticFile} from "remotion"+import {Video} from "@remotion/media"++const unrelated = {keep:"spacing"}++export const Example = () => {+ return <Video src={staticFile("folder/new video.mp4")} />+}+`);+ parseAst(output);+});++test('inserts keyframe dependencies without formatting unrelated source', () => {+ const input = `"use client"++import {Interactive} from "remotion"++const unrelated = {keep:"spacing"}++export const Example = () => <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: 'opacity',+ value: 1,+ defaultValue: null,+ clipboardParam: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 1},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ ],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ });++ expect(output).toBe(`"use client"++import {Interactive, useCurrentFrame, interpolate} from "remotion"++const unrelated = {keep:"spacing"}++export const Example = () => {+ const frame = useCurrentFrame()+ return <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])} />+}+`);+ parseAst(output);+});++test('indents a compact frame hook after directives and before comments', () => {+ const input = `import {Interactive} from "remotion"+export const C = () => { "use strict"; /* keep */ 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: 'opacity',+ value: 1,+ defaultValue: null,+ clipboardParam: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 1},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ ],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ });++ expect(output)+ .toBe(`import {Interactive, useCurrentFrame, interpolate} from "remotion"+export const C = () => { "use strict";+ const frame = useCurrentFrame()+ /* keep */ return <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])} /> }+`);+ parseAst(output);+});++test('indents a multiline opening element inside a compact function body', () => {+ const input = `import {Interactive} from "remotion"+export const C = () => { 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"+export const C = () => { 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'++export const Example = () => <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 div');+ }++ const {output} = updateMultipleSequenceProps({+ input,+ changes: [+ {+ nodePath,+ updates: [+ {+ key: 'opacity',+ value: 1,+ defaultValue: null,+ clipboardParam: {+ type: 'keyframed',+ interpolationFunction: 'interpolate',+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 1},+ ],+ easing: [{type: 'linear'}],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ ],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ });++ expect(output).toStartWith(+ "import { useCurrentFrame, interpolate } from 'remotion'\n",+ );+ parseAst(output);+});++test('does not overlap nested function edits for batched keyframed props', () => {+ const input = `import {Interactive} from "remotion"++export const Example = () => (+ <Interactive.Div opacity={1}>+ {[1].map(() => <Interactive.Div opacity={1} />)}+ </Interactive.Div>+)+`;+ const ast = parseAst(input);+ const nodePaths: ReturnType<typeof getNodePathForRecastPath>[] = [];+ recast.types.visit(ast, {+ visitJSXOpeningElement(path) {+ nodePaths.push(getNodePathForRecastPath(path, ast));+ return this.traverse(path);+ },+ });+ if (nodePaths.length !== 2) {+ throw new Error(+ `Expected 2 Interactive.Div nodes, got ${nodePaths.length}`,+ );+ }++ const clipboardParam = {+ type: 'keyframed' as const,+ interpolationFunction: 'interpolate' as const,+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 1},+ ],+ easing: [{type: 'linear' as const}],+ clamping: {left: 'extend' as const, right: 'extend' as const},+ };+ const {output} = updateMultipleSequenceProps({+ input,+ changes: nodePaths.map((nodePath) => ({+ nodePath,+ updates: [+ {+ key: 'opacity',+ value: 1,+ defaultValue: null,+ clipboardParam,+ },+ ],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ })),+ });++ expect(output)+ .toBe(`import {Interactive, useCurrentFrame, interpolate} from "remotion"++export const Example = () => {+ const frame = useCurrentFrame()++ return (+ <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])}>+ {[1].map(() => {+ const frame = useCurrentFrame()+ return <Interactive.Div opacity={interpolate(frame, [0, 30], [0, 1])} />+ })}+ </Interactive.Div>+ )+}+`);+ parseAst(output);+});+test('preserves multiplication by a numeric constant', () => {const input = `import {Sequence} from 'remotion';diff --git a/packages/studio-codemods/src/update-keyframes.ts b/packages/studio-codemods/src/update-keyframes.tsindex 58b98a54f7..c35b4d067b 100644--- a/packages/studio-codemods/src/update-keyframes.ts+++ b/packages/studio-codemods/src/update-keyframes.ts@@ -1,14 +1,20 @@/* eslint-disable @typescript-eslint/no-use-before-define */import type {+ BlockStatement,CallExpression,Expression,+ File,+ FunctionDeclaration,+ FunctionExpression,JSXAttribute,JSXElement,JSXExpressionContainer,JSXFragment,+ JSXOpeningElement,JSXSpreadAttribute,ObjectExpression,ObjectProperty,+ ArrowFunctionExpression,StringLiteral,} from '@babel/types';import {@@ -38,6 +44,18 @@ import {ensureUseCurrentFrameHook,findEnclosingFunctionPath,} from './ensure-imports-and-frame-hook';+import {+ applySourceEdits,+ getInsertImportSourceEdits,+ type SourceEdit,+} from './insert-jsx-element';+import {+ getIndentationUnit,+ getObjectCurlySpacing,+ getPreferredQuote,+ printJsxOpeningElement,+} from './print-jsx';+import {recastLocToOffset} from './recast-loc-to-offset';import {extractStaticValue,findJsxElementAtNodePath,@@ -49,7 +67,7 @@ import {findEffectsAttr,} from './sequence-props/can-update-effect-props';import {getAstNodePath} from './sequence-props/get-ast-node-path';-import {parseAst, serializeAst} from './sequence-props/parse-ast';+import {parseAst} from './sequence-props/parse-ast';import {parseKeyframeEasingExpression} from './sequence-props/parse-keyframe-easing-expression';import {parseVideoConfigNumericExpression,@@ -63,6 +81,388 @@ 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,+ prettierConfigOverride,+ propertyNames,+}: {+ input: string;+ openingElement: JSXOpeningElement;+ prettierConfigOverride: Record<string, unknown> | null;+ propertyNames: string[];+}): SourceEdit => {+ if (!openingElement.loc) {+ throw new Error('Cannot update keyframes without a JSX source location');+ }++ const start = recastLocToOffset(input, openingElement.loc.start);+ const printed = printJsxOpeningElement({+ openingElement: openingElement as never,+ input,+ prettierConfigOverride,+ });+ return {+ start,+ end: recastLocToOffset(input, openingElement.loc.end),+ replacement: indentContinuationLines({+ input,+ offset: start,+ printed: removeBlankLinesFromUpdatedOpeningElementObjects({+ input: printed,+ propertyNames,+ }),+ }),+ };+};++const getFrameHookSourceEdit = ({+ body,+ 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,+ 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;+ 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++;+ }++ if (closingParentheses === openingParentheses) {+ start = extra.parenStart;+ end = cursor;+ }+ }++ return {+ start,+ end,+ replacement: indentContinuationLines({input, offset: start, printed}),+ };+};++const getKeyframeSourceOutput = ({+ ast,+ input,+ openingElement,+ functionSourceEdit,+ importSnapshots,+ prettierConfigOverride,+ propertyNames,+}: {+ ast: File;+ 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']+ >;+ }[];+ prettierConfigOverride: Record<string, unknown> | null;+ propertyNames: string[];+}) =>+ applySourceEdits({+ input,+ edits: [+ ...getInsertImportSourceEdits({+ ast,+ input,+ prettierConfigOverride,+ snapshots: importSnapshots,+ }),+ ...(functionSourceEdit ? [functionSourceEdit] : []),+ ...(openingElement+ ? [+ getOpeningElementSourceEdit({+ input,+ openingElement,+ prettierConfigOverride,+ propertyNames,+ }),+ ]+ : []),+ ],+ });+const getObjectPropertyNameFromUpdateKey = (key: string): string => {const dotIndex = key.indexOf('.');return dotIndex === -1 ? key : key.slice(dotIndex + 1);@@ -85,7 +485,7 @@ const lineStartsWithPropertyName = ({const getIndent = (line: string) => line.match(/^[ \t]*/)?.[0] ?? '';-const removeBlankLinesFromObjectsWithProperties = ({+const removeBlankLinesFromUpdatedOpeningElementObjects = ({input,propertyNames,}: {@@ -96,7 +496,8 @@ const removeBlankLinesFromObjectsWithProperties = ({return input;}- const lines = input.split('\n');+ const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';+ const lines = input.split(/\r?\n/);const linesToRemove = new Set<number>();for (let i = 0; i < lines.length; i++) {@@ -143,7 +544,7 @@ const removeBlankLinesFromObjectsWithProperties = ({return input;}- return lines.filter((_, index) => !linesToRemove.has(index)).join('\n');+ return lines.filter((_, index) => !linesToRemove.has(index)).join(endOfLine);};type KeyframeEasing = Extract<@@ -1785,12 +2186,14 @@ export const updateSequenceKeyframesAst = ({nodePath,updates,schema,+ prettierConfigOverride,videoConfigValues,}: {input: string;nodePath: SequenceNodePath;updates: SequenceKeyframeUpdate[];schema?: InteractivitySchema;+ prettierConfigOverride?: Record<string, unknown> | null;videoConfigValues: VideoConfigValues | null;}): {serialized: string;@@ -1800,6 +2203,20 @@ export const updateSequenceKeyframesAst = ({updatedNodePath: SequenceNodePath;} => {const ast = parseAst(input);+ const formattingConfig = getSourceFormattingConfig({+ input,+ prettierConfigOverride: prettierConfigOverride ?? null,+ });+ const importSnapshots = ast.program.body.flatMap((statement) =>+ statement.type === 'ImportDeclaration'+ ? [+ {+ declaration: statement,+ specifiers: [...(statement.specifiers ?? [])],+ },+ ]+ : [],+ );const videoConfigIdentifierValues = getVideoConfigIdentifierValues({ast,videoConfigValues,@@ -1873,11 +2290,50 @@ export const updateSequenceKeyframesAst = ({}}- if (needsFrameHook) {- const fnPath = findEnclosingFunctionPath(jsxPath);- if (fnPath) {+ 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;+ }+ }}ensureRemotionImports(ast, requiredImports);@@ -1890,7 +2346,17 @@ export const updateSequenceKeyframesAst = ({}return {- serialized: serializeAst(ast),+ serialized: getKeyframeSourceOutput({+ ast,+ input,+ openingElement: openingElementForSourceEdit,+ functionSourceEdit,+ importSnapshots,+ prettierConfigOverride: formattingConfig,+ propertyNames: updates.map((update) =>+ getObjectPropertyNameFromUpdateKey(update.key),+ ),+ }),oldValueStrings,newValueStrings,logLine: node.loc?.start.line ?? 1,@@ -1898,12 +2364,11 @@ export const updateSequenceKeyframesAst = ({};};-export const updateSequenceKeyframes = async ({+export const updateSequenceKeyframes = ({input,nodePath,updates,schema,- formatFile,prettierConfigOverride,videoConfigValues,}: {@@ -1911,7 +2376,9 @@ export const updateSequenceKeyframes = async ({nodePath: SequenceNodePath;updates: SequenceKeyframeUpdate[];schema?: InteractivitySchema;- formatFile: FormatKeyframesFile;+ // Kept optional for compatibility with callers from before source edits+ // replaced the full-file formatting pass.+ formatFile?: FormatKeyframesFile;prettierConfigOverride?: Record<string, unknown> | null;videoConfigValues: VideoConfigValues | null;}): Promise<{@@ -1921,41 +2388,31 @@ export const updateSequenceKeyframes = async ({newValueStrings: string[];logLine: number;updatedNodePath: SequenceNodePath;-}> => {- const {- serialized,- oldValueStrings,- newValueStrings,- logLine,- updatedNodePath,- } = updateSequenceKeyframesAst({- input,- nodePath,- updates,- schema,- videoConfigValues,- });- const {output, formatted} = await formatFile({- contents: serialized,- prettierConfigOverride: prettierConfigOverride ?? null,- });- const outputWithoutInsertedBlankLines =- removeBlankLinesFromObjectsWithProperties({- input: output,- propertyNames: updates.map((update) =>- getObjectPropertyNameFromUpdateKey(update.key),- ),+}> =>+ Promise.resolve().then(() => {+ const {+ serialized,+ oldValueStrings,+ newValueStrings,+ logLine,+ updatedNodePath,+ } = updateSequenceKeyframesAst({+ input,+ nodePath,+ updates,+ schema,+ prettierConfigOverride,+ videoConfigValues,});-- return {- output: outputWithoutInsertedBlankLines,- formatted,- oldValueStrings,- newValueStrings,- logLine,- updatedNodePath,- };-};+ return {+ output: serialized,+ formatted: true,+ oldValueStrings,+ newValueStrings,+ logLine,+ updatedNodePath,+ };+ });export const updateEffectKeyframesAst = ({input,@@ -1963,6 +2420,7 @@ export const updateEffectKeyframesAst = ({effectIndex,updates,schema,+ prettierConfigOverride,videoConfigValues,}: {input: string;@@ -1970,6 +2428,7 @@ export const updateEffectKeyframesAst = ({effectIndex: number;updates: EffectKeyframeUpdate[];schema?: InteractivitySchema;+ prettierConfigOverride?: Record<string, unknown> | null;videoConfigValues: VideoConfigValues | null;}): {serialized: string;@@ -1980,6 +2439,20 @@ export const updateEffectKeyframesAst = ({updatedSequenceNodePath: SequenceNodePath;} => {const ast = parseAst(input);+ const formattingConfig = getSourceFormattingConfig({+ input,+ prettierConfigOverride: prettierConfigOverride ?? null,+ });+ const importSnapshots = ast.program.body.flatMap((statement) =>+ statement.type === 'ImportDeclaration'+ ? [+ {+ declaration: statement,+ specifiers: [...(statement.specifiers ?? [])],+ },+ ]+ : [],+ );const videoConfigIdentifierValues = getVideoConfigIdentifierValues({ast,videoConfigValues,@@ -2060,11 +2533,50 @@ export const updateEffectKeyframesAst = ({}}- if (needsFrameHook) {- const fnPath = findEnclosingFunctionPath(jsxPath);- if (fnPath) {+ 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;+ }+ }}ensureRemotionImports(ast, requiredImports);@@ -2077,7 +2589,15 @@ export const updateEffectKeyframesAst = ({}return {- serialized: serializeAst(ast),+ serialized: getKeyframeSourceOutput({+ ast,+ input,+ openingElement: openingElementForSourceEdit,+ functionSourceEdit,+ importSnapshots,+ prettierConfigOverride: formattingConfig,+ propertyNames: updates.map((update) => update.key),+ }),oldValueStrings,newValueStrings,logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,@@ -2086,13 +2606,12 @@ export const updateEffectKeyframesAst = ({};};-export const updateEffectKeyframes = async ({+export const updateEffectKeyframes = ({input,sequenceNodePath,effectIndex,updates,schema,- formatFile,prettierConfigOverride,videoConfigValues,}: {@@ -2101,7 +2620,9 @@ export const updateEffectKeyframes = async ({effectIndex: number;updates: EffectKeyframeUpdate[];schema?: InteractivitySchema;- formatFile: FormatKeyframesFile;+ // Kept optional for compatibility with callers from before source edits+ // replaced the full-file formatting pass.+ formatFile?: FormatKeyframesFile;prettierConfigOverride?: Record<string, unknown> | null;videoConfigValues: VideoConfigValues | null;}): Promise<{@@ -2112,39 +2633,31 @@ export const updateEffectKeyframes = async ({logLine: number;effectCallee: string;updatedSequenceNodePath: SequenceNodePath;-}> => {- const {- serialized,- oldValueStrings,- newValueStrings,- logLine,- effectCallee,- updatedSequenceNodePath,- } = updateEffectKeyframesAst({- input,- sequenceNodePath,- effectIndex,- updates,- schema,- videoConfigValues,- });- const {output, formatted} = await formatFile({- contents: serialized,- prettierConfigOverride: prettierConfigOverride ?? null,- });- const outputWithoutInsertedBlankLines =- removeBlankLinesFromObjectsWithProperties({- input: output,- propertyNames: updates.map((update) => update.key),+}> =>+ Promise.resolve().then(() => {+ const {+ serialized,+ oldValueStrings,+ newValueStrings,+ logLine,+ effectCallee,+ updatedSequenceNodePath,+ } = updateEffectKeyframesAst({+ input,+ sequenceNodePath,+ effectIndex,+ updates,+ schema,+ prettierConfigOverride,+ videoConfigValues,});-- return {- output: outputWithoutInsertedBlankLines,- formatted,- oldValueStrings,- newValueStrings,- logLine,- effectCallee,- updatedSequenceNodePath,- };-};+ return {+ output: serialized,+ formatted: true,+ oldValueStrings,+ newValueStrings,+ logLine,+ effectCallee,+ updatedSequenceNodePath,+ };+ });diff --git a/packages/studio-codemods/src/update-sequence-props.ts b/packages/studio-codemods/src/update-sequence-props.tsindex f61c7fde8d..ac2bff619f 100644--- a/packages/studio-codemods/src/update-sequence-props.ts+++ b/packages/studio-codemods/src/update-sequence-props.ts@@ -17,6 +17,7 @@ import type {EffectClipboardParam,GoogleFontSourceEdit,} from '@remotion/studio-shared';+import type {namedTypes as AstNamedTypes} from 'ast-types';import type {ExpressionKind} from 'ast-types/lib/gen/kinds';import * as recast from 'recast';import type {@@ -25,6 +26,19 @@ import type {VideoConfigValues,} 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';+import {recastLocToOffset} from './recast-loc-to-offset';import {findNodePathForJsxElement,findJsxElementNodeAtNodePath,@@ -1248,29 +1262,392 @@ 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,+ originalBody,+ prettierConfigOverride,+}: {+ ast: File;+ input: string;+ originalBody: Statement[];+ prettierConfigOverride: Record<string, unknown> | null;+}): SourceEdit[] => {+ const edits: SourceEdit[] = [];+ const currentStatements = new Set(ast.program.body);+ for (const statement of originalBody) {+ if (currentStatements.has(statement) || !statement.loc) {+ continue;+ }++ const leadingCommentStarts = (statement.leadingComments ?? []).flatMap(+ (comment) =>+ comment.loc ? [recastLocToOffset(input, comment.loc.start)] : [],+ );+ edits.push({+ start: Math.min(+ recastLocToOffset(input, statement.loc.start),+ ...leadingCommentStarts,+ ),+ end: recastLocToOffset(input, statement.loc.end),+ replacement: '',+ });+ }++ const originalStatements = new Set(originalBody);+ const endOfLine = input.includes('\r\n') ? '\r\n' : '\n';+ for (let index = 0; index < ast.program.body.length; index++) {+ const statement = ast.program.body[index];+ if (+ originalStatements.has(statement) ||+ statement.type === 'ImportDeclaration'+ ) {+ continue;+ }++ const inserted: Statement[] = [statement];+ while (+ index + 1 < ast.program.body.length &&+ !originalStatements.has(ast.program.body[index + 1]) &&+ ast.program.body[index + 1].type !== 'ImportDeclaration'+ ) {+ inserted.push(ast.program.body[++index]);+ }++ const nextOriginal = ast.program.body+ .slice(index + 1)+ .find((candidate) => originalStatements.has(candidate) && candidate.loc);+ const printed = inserted+ .map((candidate) =>+ printNodeWithSourceStyle({+ input,+ node: candidate as unknown as AstNamedTypes.Node,+ prettierConfigOverride,+ }),+ )+ .join(`${endOfLine}${endOfLine}`);+ if (nextOriginal?.loc) {+ const nextOffset = recastLocToOffset(input, nextOriginal.loc.start);+ edits.push({+ start: nextOffset,+ end: nextOffset,+ replacement: `${printed}${endOfLine}${endOfLine}`,+ });+ continue;+ }++ const previousOriginal = ast.program.body+ .slice(0, index - inserted.length + 1)+ .findLast(+ (candidate) => originalStatements.has(candidate) && candidate.loc,+ );+ const offset = previousOriginal?.loc+ ? recastLocToOffset(input, previousOriginal.loc.end)+ : input.length;+ edits.push({+ start: offset,+ end: offset,+ replacement: `${endOfLine}${endOfLine}${printed}`,+ });+ }++ return edits;+};+export const updateMultipleSequenceProps = ({input,changes,ast: providedAst,+ prettierConfigOverride,}: {input: string;changes: SequencePropsNodeUpdate[];ast?: File;+ prettierConfigOverride?: Record<string, unknown> | null;}): UpdateMultipleSequencePropsResult => {const ast = providedAst ?? parseAst(input);- const canPatchOpeningElements = changes.every(({updates}) =>- updates.every(- (update) =>- update.key !== 'children' &&- update.key !== 'style.fontFamily' &&- !update.googleFont &&- !update.clipboardParam &&- !(- typeof update.value === 'string' &&- update.value.startsWith(NoReactInternals.FILE_TOKEN)- ),- ),+ const prettierConfig = prettierConfigOverride ?? null;+ const jsxFormattingConfig = {+ bracketSpacing: getObjectCurlySpacing(input, prettierConfig),+ singleQuote: getPreferredQuote(input, prettierConfig) === 'single',+ ...(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 getJsxSourceIndent = (offset: number) => {+ const lineStart = input.lastIndexOf('\n', offset - 1) + 1;+ const startsInsideSameLineFunctionBlock = functionSnapshots.some(+ ({body}) => {+ if (body.type !== 'BlockStatement' || !body.loc) {+ return false;+ }++ const blockStart = recastLocToOffset(input, body.loc.start);+ const blockEnd = recastLocToOffset(input, body.loc.end);+ return (+ blockStart < offset &&+ offset < blockEnd &&+ input.lastIndexOf('\n', blockStart - 1) + 1 === lineStart+ );+ },+ );+ const lineIndent = getLineIndent(input, offset);+ return startsInsideSameLineFunctionBlock+ ? `${lineIndent}${getIndentationUnit(input, prettierConfig)}`+ : lineIndent;+ };+const resolvedChanges = changes.map(({nodePath, updates, schema, videoConfigValues}) => {const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);@@ -1283,14 +1660,25 @@ export const updateMultipleSequenceProps = ({return {jsxElement, updates, schema, videoConfigValues};},);- const openingElementLocations = canPatchOpeningElements- ? new Map(- resolvedChanges.map(({jsxElement}) => [- jsxElement.openingElement,- jsxElement.openingElement.loc,- ]),- )- : null;+ const elementsWithChildrenUpdates = new Set(+ resolvedChanges.flatMap(({jsxElement, updates}) =>+ updates.some((update) => update.key === 'children') ? [jsxElement] : [],+ ),+ );+ const openingElementLocations = new Map(+ resolvedChanges.flatMap(({jsxElement}) =>+ elementsWithChildrenUpdates.has(jsxElement)+ ? []+ : [[jsxElement.openingElement, jsxElement.openingElement.loc] as const],+ ),+ );+ const elementLocations = new Map(+ resolvedChanges.flatMap(({jsxElement}) =>+ elementsWithChildrenUpdates.has(jsxElement)+ ? [[jsxElement, jsxElement.loc] as const]+ : [],+ ),+ );const clipboardParamLocalNames = prepareClipboardParamSourceEdits({ast,changes: resolvedChanges,@@ -1327,81 +1715,136 @@ export const updateMultipleSequenceProps = ({return {...result, newNodePath};});- const sourceLines = input.split('\n');- const lineOffsets: number[] = [];- let offset = 0;- for (const line of sourceLines) {- lineOffsets.push(offset);- offset += line.length + 1;- }+ const {coveredRanges, edits: functionEdits} = getFunctionSourceEdits({+ input,+ prettierConfigOverride: prettierConfig,+ snapshots: functionSnapshots,+ });+ const isCoveredByFunctionEdit = (start: number, end: number) =>+ coveredRanges.some((range) => start >= range.start && end <= range.end);+ const elementEdits: SourceEdit[] = [];+ for (const [openingElement, location] of openingElementLocations) {+ if (!location) {+ continue;+ }- const replacements = openingElementLocations- ? [...openingElementLocations].map(([openingElement, location]) => {- if (!location) {- return null;- }+ const start = recastLocToOffset(input, location.start);+ const end = recastLocToOffset(input, location.end);+ if (isCoveredByFunctionEdit(start, end)) {+ continue;+ }- const getOffset = ({line, column}: {line: number; column: number}) => {- const sourceLine = sourceLines[line - 1];- if (sourceLine === undefined) {- return null;- }+ const original = input.slice(start, end);+ if (recast.print(openingElement).code === original) {+ continue;+ }- let sourceColumn = 0;- let recastColumn = 0;- while (sourceColumn < sourceLine.length && recastColumn < column) {- recastColumn +=- sourceLine[sourceColumn] === '\t' ? 4 - (recastColumn % 4) : 1;- sourceColumn++;- }+ elementEdits.push({+ start,+ end,+ replacement: indentContinuationLines({+ indent: getJsxSourceIndent(start),+ input,+ printed: printJsxOpeningElement({+ openingElement:+ openingElement as unknown as AstNamedTypes.JSXOpeningElement,+ input,+ prettierConfigOverride: jsxFormattingConfig,+ }),+ }),+ });+ }- return lineOffsets[line - 1] + sourceColumn;- };+ for (const [element, location] of elementLocations) {+ if (!location) {+ continue;+ }- const start = getOffset(location.start);- const end = getOffset(location.end);- if (start === null || end === null) {- return null;- }+ const start = recastLocToOffset(input, location.start);+ const end = recastLocToOffset(input, location.end);+ if (isCoveredByFunctionEdit(start, end)) {+ continue;+ }- return {- start,- end,- replacement: recast.print(openingElement).code,- selfClosing: openingElement.selfClosing ?? false,- };- })- : null;- let output = input;- let openingElementRanges: UpdateMultipleSequencePropsResult['openingElementRanges'] =- null;- if (replacements?.every((replacement) => replacement !== null)) {- const replacementsByStart = replacements.sort(- (first, second) => first.start - second.start,- );- let shift = 0;- openingElementRanges = replacementsByStart.map((replacement) => {- const start = replacement.start + shift;- const end = start + replacement.replacement.length;- shift +=- replacement.replacement.length - (replacement.end - replacement.start);- return {start, end, selfClosing: replacement.selfClosing};+ const original = input.slice(start, end);+ if (recast.print(element).code === original) {+ continue;+ }++ elementEdits.push({+ start,+ end,+ replacement: indentContinuationLines({+ indent: getJsxSourceIndent(start),+ input,+ printed: printInsertedJsx({+ element: element as unknown as AstNamedTypes.JSXElement,+ input,+ prettierConfigOverride: jsxFormattingConfig,+ }),+ }),});+ }- for (const replacement of [...replacementsByStart].reverse()) {- output =- output.slice(0, replacement.start) +- replacement.replacement +- output.slice(replacement.end);+ const modifiedImportEdits = importSnapshots.flatMap((snapshot) => {+ if (+ !ast.program.body.includes(snapshot.declaration) ||+ !snapshot.declaration.loc ||+ snapshot.specifiers.every((specifier) =>+ snapshot.declaration.specifiers.includes(specifier),+ )+ ) {+ return [];}- } else {- output = serializeAst(ast);- }++ const start = recastLocToOffset(input, snapshot.declaration.loc.start);+ const end = recastLocToOffset(input, snapshot.declaration.loc.end);+ return [+ {+ start,+ end,+ replacement: printNodeWithSourceStyle({+ input,+ node: snapshot.declaration as unknown as AstNamedTypes.Node,+ prettierConfigOverride: prettierConfig,+ }),+ },+ ];+ });+ const insertedImportEdits = getInsertImportSourceEdits({+ ast,+ input,+ prettierConfigOverride: jsxFormattingConfig,+ snapshots: importSnapshots,+ });+ const importEdits = [+ ...modifiedImportEdits,+ ...insertedImportEdits.filter((edit) =>+ modifiedImportEdits.every(+ (modified) => edit.end <= modified.start || edit.start >= modified.end,+ ),+ ),+ ];+ const programStatementEdits = getProgramStatementSourceEdits({+ ast,+ input,+ originalBody: originalProgramBody,+ prettierConfigOverride: prettierConfig,+ });+ const output = applySourceEdits({+ input,+ edits: [+ ...programStatementEdits,+ ...importEdits,+ ...functionEdits,+ ...elementEdits,+ ],+ });return {output,results,ast,- openingElementRanges,+ openingElementRanges: null,};};diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex 865535ed43..8e865022ab 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -2,7 +2,6 @@ import {updateEffectKeyframes as updateEffectKeyframesCodemod,updateSequenceKeyframes as updateSequenceKeyframesCodemod,} from '@remotion/studio-codemods';-import {formatFileContent} from '../format-file-content';export {type EffectKeyframeUpdate,@@ -23,20 +22,8 @@ type UpdateEffectKeyframesInput = Omit<'formatFile'>;-const formatKeyframesFile = ({- contents,- prettierConfigOverride,-}: {- contents: string;- prettierConfigOverride: Record<string, unknown> | null;-}) =>- formatFileContent({- input: contents,- prettierConfigOverride,- });-export const updateSequenceKeyframes = (input: UpdateSequenceKeyframesInput) =>- updateSequenceKeyframesCodemod({...input, formatFile: formatKeyframesFile});+ updateSequenceKeyframesCodemod(input);export const updateEffectKeyframes = (input: UpdateEffectKeyframesInput) =>- updateEffectKeyframesCodemod({...input, formatFile: formatKeyframesFile});+ updateEffectKeyframesCodemod(input);diff --git a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.tsindex 7434dd4750..5e781acfaf 100644--- a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts+++ b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts@@ -4,7 +4,7 @@ import {type SequencePropsNodeUpdate,type SequencePropsNodeUpdateResult,type SequencePropUpdate,- updateMultipleSequenceProps as updateMultipleSequencePropsUnformatted,+ updateMultipleSequenceProps as updateMultipleSequencePropsCodemod,updateSequencePropsAst,} from '@remotion/studio-codemods';import type {@@ -12,8 +12,6 @@ import type {SequenceNodePath,VideoConfigValues,} from 'remotion';-import {formatFileContent} from '../format-file-content';-import {formatInlineContent} from '../format-inline-content';export {type RemovedProp,@@ -40,7 +38,7 @@ type UpdateSequencePropsResult = {removedProps: RemovedProp[];};-export const updateMultipleSequenceProps = async ({+export const updateMultipleSequenceProps = ({input,changes,prettierConfigOverride,@@ -51,67 +49,16 @@ export const updateMultipleSequenceProps = async ({prettierConfigOverride: PrettierConfigOverride;ast?: File;}): Promise<UpdateMultipleSequencePropsResult> => {- const {- output: unformattedOutput,- results,- ast,- openingElementRanges,- } = updateMultipleSequencePropsUnformatted({- input,- changes,- ast: providedAst,- });- if (unformattedOutput === input) {- return {output: input, formatted: true, results, ast};- }-- if (openingElementRanges?.length === 1) {- const [range] = openingElementRanges;- const openingElement = unformattedOutput.slice(range.start, range.end);- const formattableOpeningElement = range.selfClosing- ? openingElement- : openingElement.slice(0, -1) + ' />';- const lineStart = unformattedOutput.lastIndexOf('\n', range.start) + 1;- const linePrefix = unformattedOutput.slice(lineStart, range.start);- const {formatted: formattedOpeningElement, didFormat} =- await formatInlineContent({- inlineContent: formattableOpeningElement,- linePrefix,- endOfLine: 'lf',- prettierConfigOverride,- });- let finalOpeningElement = formattedOpeningElement;- if (!range.selfClosing) {- const slashIndex = finalOpeningElement.lastIndexOf('/>');- if (slashIndex !== finalOpeningElement.length - 2) {- throw new Error('Could not format JSX opening element');- }-- const lastLineStart = finalOpeningElement.lastIndexOf('\n') + 1;- const beforeSlash = finalOpeningElement.slice(lastLineStart, slashIndex);- finalOpeningElement =- beforeSlash.trim().length === 0- ? finalOpeningElement.slice(0, slashIndex) + '>'- : finalOpeningElement.slice(0, slashIndex).trimEnd() + '>';- }-- return {- output:- unformattedOutput.slice(0, range.start) +- finalOpeningElement +- unformattedOutput.slice(range.end),- formatted: didFormat,- results,- ast,- };- }+ return Promise.resolve().then(() => {+ const {output, results, ast} = updateMultipleSequencePropsCodemod({+ input,+ changes,+ ast: providedAst,+ prettierConfigOverride,+ });- const {output, formatted} = await formatFileContent({- input: unformattedOutput,- prettierConfigOverride,+ return {output, formatted: true, results, ast};});-- return {output, formatted, results, ast};};export const updateSequenceProps = async ({@@ -129,18 +76,21 @@ export const updateSequenceProps = async ({prettierConfigOverride: PrettierConfigOverride;videoConfigValues: VideoConfigValues | null;}): Promise<UpdateSequencePropsResult> => {- const {serialized, oldValueStrings, logLine, removedProps} =- updateSequencePropsAst({- input,- nodePath,- updates,- schema,- videoConfigValues,- });- const {output, formatted} = await formatFileContent({- input: serialized,+ const {output, results} = await updateMultipleSequenceProps({+ input,+ changes: [{nodePath, updates, schema, videoConfigValues}],prettierConfigOverride,});+ const result = results[0];+ if (!result) {+ throw new Error('Expected sequence prop update result');+ }- return {output, oldValueStrings, formatted, logLine, removedProps};+ return {+ output,+ oldValueStrings: result.oldValueStrings,+ formatted: true,+ logLine: result.logLine,+ removedProps: result.removedProps,+ };};diff --git a/packages/studio-server/src/test/code-shift.test.ts b/packages/studio-server/src/test/code-shift.test.tsindex 91517fe8ce..2636065058 100644--- a/packages/studio-server/src/test/code-shift.test.ts+++ b/packages/studio-server/src/test/code-shift.test.ts@@ -12,7 +12,21 @@ export const Component = () => {};`;-test('Should add style.scale to a Video component and format with prettier', async () => {+const expectedOutput = `import {Video} from '@remotion/media';++const src = 'https://remotion.media/video.mp4';++export const Component = () => {+ return <Video+ src={src}+ style={{+ scale: 2+ }}+ />;+};+`;++test('Should add style.scale without changing the existing indentation style', async () => {const {output, oldValueStrings, formatted} = await updateSequenceProps({videoConfigValues: null,input: componentInput,@@ -29,24 +43,10 @@ test('Should add style.scale to a Video component and format with prettier', asyexpect(oldValueString).toBe('');expect(formatted).toBe(true);- expect(output).toBe(`import {Video} from '@remotion/media';--const src = 'https://remotion.media/video.mp4';--export const Component = () => {-\treturn (-\t\t<Video-\t\t\tsrc={src}-\t\t\tstyle={{-\t\t\t\tscale: 2,-\t\t\t}}-\t\t/>-\t);-};-`);+ expect(output).toBe(expectedOutput);});-test('Should resolve prettier config if override is null', async () => {+test('Should infer source formatting if the config override is null', async () => {const {output, formatted} = await updateSequenceProps({videoConfigValues: null,input: componentInput,@@ -57,6 +57,5 @@ test('Should resolve prettier config if override is null', async () => {});expect(formatted).toBe(true);- expect(output).toContain('\treturn (');- expect(output).toContain('style={{');+ expect(output).toBe(expectedOutput);});diff --git a/packages/studio-server/src/test/update-keyframes-imports.test.ts b/packages/studio-server/src/test/update-keyframes-imports.test.tsindex 496ab54e41..1f3eabd1b7 100644--- a/packages/studio-server/src/test/update-keyframes-imports.test.ts+++ b/packages/studio-server/src/test/update-keyframes-imports.test.ts@@ -61,8 +61,8 @@ export const Example: React.FC = () => {);expect(serialized).toContain('const frame = useCurrentFrame();');expect(serialized).toContain('interpolate(frame, [30], [1], {');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");});test('adds interpolateColors import (not interpolate) for color conversion', () => {@@ -138,8 +138,8 @@ export const Example: React.FC = () => {expect(serialized).toContain('interpolate');expect(serialized).not.toContain('interpolateColors');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");expect(serialized).toContain('useCurrentFrame');expect(serialized).toContain('const frame = useCurrentFrame();');});@@ -424,8 +424,8 @@ export const Example: React.FC = () => (expect(serialized).toContain('const frame = useCurrentFrame();');expect(serialized).toContain('return');expect(serialized).toContain('interpolate(frame, [20], [1], {');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");});test('does not add a duplicate frame hook when user already has one with a different intermediate statement', () => {@@ -487,8 +487,8 @@ export const Comp = () => {);expect(serialized).toContain('const frame = useCurrentFrame();');expect(serialized).toContain('interpolate(frame, [100], [1], {');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");});test('effect keyframe remove does not modify imports or insert a frame hook', () => {diff --git a/packages/studio-server/src/test/update-keyframes.test.ts b/packages/studio-server/src/test/update-keyframes.test.tsindex 23245ee379..ef74dcd017 100644--- a/packages/studio-server/src/test/update-keyframes.test.ts+++ b/packages/studio-server/src/test/update-keyframes.test.ts@@ -1493,7 +1493,7 @@ test('updateSequenceKeyframes keeps an interpolation when one keyframe remains',});expect(oldValueStrings).toEqual(['interpolate(frame, [0, 100], [2, 4])']);- expect(output).toContain('style={{scale: interpolate(frame, [100], [4])}}');+ expect(output).toContain('scale: interpolate(frame, [100], [4])');});test('updateSequenceKeyframes removes the adjacent easing segment when deleting keyframes', async () => {@@ -1595,7 +1595,7 @@ test('updateSequenceKeyframes moves overlapping selected keyframes together', as'interpolate(frame, [50, 80, 100], [2, 3, 4])',]);expect(output).toContain(- 'style={{scale: interpolate(frame, [50, 80, 100], [2, 3, 4])}}',+ 'scale: interpolate(frame, [50, 80, 100], [2, 3, 4])',);});@@ -1627,7 +1627,7 @@ test('updateSequenceKeyframes resorts keyframes when moving past an adjacent key'interpolate(frame, [50, 75, 100], [3, 2, 4])',]);expect(output).toContain(- 'style={{scale: interpolate(frame, [50, 75, 100], [3, 2, 4])}}',+ 'scale: interpolate(frame, [50, 75, 100], [3, 2, 4])',);});@@ -1693,7 +1693,7 @@ test('updateSequenceKeyframes allows moving keyframes outside the sequence range'interpolate(frame, [-15, 50, 140], [2, 3, 4])',]);expect(output).toContain(- 'style={{scale: interpolate(frame, [-15, 50, 140], [2, 3, 4])}}',+ 'scale: interpolate(frame, [-15, 50, 140], [2, 3, 4])',);});@@ -1721,7 +1721,7 @@ test('updateSequenceKeyframes converts the last keyframe to a static value', asyexpect(oldValueStrings).toEqual(['interpolate(frame, [12], [320])']);expect(newValueStrings).toEqual(['320']);- expect(output).toContain('style={{scale: 320}}');+ expect(output).toContain('scale: 320');const status = computeSequencePropsStatusFromContent({videoConfigValues: null,fileContents: output,@@ -1788,7 +1788,7 @@ test('updateSequenceKeyframes preserves the playhead value when all keyframes ar})),});- expect(output).toContain('style={{scale: 3}}');+ expect(output).toContain('scale: 3');}});@@ -1838,8 +1838,8 @@ test('updateEffectKeyframes converts a static value to a clamped interpolation',expect(oldValueStrings).toEqual(['0.2']);expect(serialized).toContain('amount: interpolate(frame, [40], [0.6], {');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");expect(serialized).not.toContain('perceptual-scale');});@@ -1862,7 +1862,7 @@ test('updateEffectKeyframes uses the schema keyframe output default', () => {});expect(serialized).toContain('scale: interpolate(frame, [40], [2], {');- expect(serialized).toContain('output: "perceptual-scale"');+ expect(serialized).toContain("output: 'perceptual-scale'");});test('updateEffectKeyframes adds a missing prop before keyframing it', () => {@@ -1887,8 +1887,8 @@ test('updateEffectKeyframes adds a missing prop before keyframing it', () => {expect(serialized).toContain('useCurrentFrame');expect(serialized).toContain('const frame = useCurrentFrame();');expect(serialized).toContain('phase: interpolate(frame, [30], [90], {');- expect(serialized).toContain('extrapolateLeft: "clamp"');- expect(serialized).toContain('extrapolateRight: "clamp"');+ expect(serialized).toContain("extrapolateLeft: 'clamp'");+ expect(serialized).toContain("extrapolateRight: 'clamp'");});test('updateEffectKeyframes adds props to a zero-argument effect', () => {diff --git a/packages/studio-server/src/test/update-sequence-props.test.ts b/packages/studio-server/src/test/update-sequence-props.test.tsindex 346e700c21..689621064d 100644--- a/packages/studio-server/src/test/update-sequence-props.test.ts+++ b/packages/studio-server/src/test/update-sequence-props.test.ts@@ -587,6 +587,26 @@ test('updateMultipleSequenceProps should update multiple nodes in one format pasexpect(output.split('\n')[8]).toContain('durationInFrames={120}');});+test('updateMultipleSequenceProps rejects instead of throwing synchronously', async () => {+ const promise = updateMultipleSequenceProps({+ input: lightLeakInput,+ changes: [+ {+ nodePath: ['program', 'body', 999],+ updates: [{key: 'hueShift', value: 90, defaultValue: null}],+ schema: NoReactInternals.sequenceSchema,+ videoConfigValues: null,+ },+ ],+ prettierConfigOverride: null,+ });++ expect(promise).toBeInstanceOf(Promise);+ await expect(promise).rejects.toThrow(+ 'Could not find a JSX element at the specified line to update',+ );+});+test('updateMultipleSequenceProps should not format a no-op edit', async () => {const unformattedInput = lightLeakInput.replace('\t\t<AbsoluteFill',@@ -638,7 +658,32 @@ export const Example = () => {expect(formatted).toBe(true);});-test('updateMultipleSequenceProps formats a multiline non-self-closing opening element', async () => {+test('updateSequenceProps preserves non-Prettier source around the edited element', async () => {+ const input = `const unrelated = {keep:"this spacing"};++export const Example = () => {+ return <Interactive.Div name = "Example">Text</Interactive.Div>;+};+`;+ const {output, formatted} = await updateSequenceProps({+ input,+ nodePath: lineColumnToNodePath(input, 4),+ updates: [{key: 'hidden', value: true, defaultValue: false}],+ schema: NoReactInternals.sequenceSchema,+ prettierConfigOverride: null,+ videoConfigValues: null,+ });++ expect(output).toBe(`const unrelated = {keep:"this spacing"};++export const Example = () => {+ return <Interactive.Div name="Example" hidden>Text</Interactive.Div>;+};+`);+ expect(formatted).toBe(true);+});++test('updateMultipleSequenceProps formats a multiline non-self-closing opening element without Prettier', async () => {const input = `export const Example = () => {return (<Interactive.Div@@ -665,7 +710,14 @@ test('updateMultipleSequenceProps formats a multiline non-self-closing opening eexpect(output).toBe(`export const Example = () => {return (- <Interactive.Div name="Example" style={{ height: 8, scale: 1.353, width: 8 }}>+ <Interactive.Div+ name="Example"+ style={{+ height: 8,+ scale: 1.353,+ width: 8+ }}+ >Text</Interactive.Div>);