🎥 Make videos programmatically with React
Fix Basic Captions insertion formatting
JonnyBurger04034202a838
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 10f92c7027..4b7ffc6194 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -443,10 +443,10 @@ registerRoot(Root);`,expect(currentProject.files['/project/src/basic-captions.element.tsx']).toBe(basicCaptionsElementSource,);- expect(currentProject.files[fileName]).toContain(+ expect(currentProject.files[fileName].replace(/\s+/g, ' ')).toContain('<BasicCaptions captions={[',);- expect(currentProject.files[fileName]).toContain('"text": " Hello"');+ expect(currentProject.files[fileName]).toContain("text: ' Hello'");expect(events).toContainEqual({type: 'sequence-node-paths-remapped',mutation: captionsResult.nodePathMutation,@@ -507,12 +507,12 @@ registerRoot(Root);`,currentProject.files['/project/src/basic-captions-2.element.tsx'],).toBeUndefined();expect(- currentProject.files[fileName].match(/<BasicCaptions captions/g),+ currentProject.files[fileName].match(/<BasicCaptions\b/g),).toHaveLength(2);expect((await operations.undo()).success).toBe(true);expect(currentProject.files[localElementPath]).toBe(customizedSource);expect(- currentProject.files[fileName].match(/<BasicCaptions captions/g),+ currentProject.files[fileName].match(/<BasicCaptions\b/g),).toHaveLength(1);expect((await operations.undo()).success).toBe(true);expect(currentProject.files[fileName]).toBe(initialSource);diff --git a/packages/codemods/src/insert-basic-captions.ts b/packages/codemods/src/insert-basic-captions.tsindex f2d0b87c5a..74dccbe33b 100644--- a/packages/codemods/src/insert-basic-captions.ts+++ b/packages/codemods/src/insert-basic-captions.ts@@ -22,6 +22,7 @@ import {getEndOfLine,getIndentationUnit,getLineIndent,+ getSourceFormattingConfig,indentContinuationLines,} from './source-style';@@ -141,7 +142,81 @@ export const insertBasicCaptions = ({copiedAttributes.push(`premountFor={${premountFor}}`);}- const elementSource = `<${captionsLocalName} captions={${JSON.stringify(captions, null, 2)}} ${copiedAttributes.join(' ')} />`;+ const formattingConfig = getSourceFormattingConfig({+ input,+ prettierConfigOverride,+ });+ const trailingComma =+ prettierConfigOverride?.trailingComma !== 'none' &&+ prettierConfigOverride?.trailingComma !== false;+ const singleLineElement = `<${captionsLocalName} captions={[]}${copiedAttributes.length === 0 ? '' : ` ${copiedAttributes.join(' ')}`} />`;+ const captionLines = captions.flatMap((caption, captionIndex) => {+ const doubleQuotedText = JSON.stringify(caption.text);+ const singleQuotedText = `'${doubleQuotedText+ .slice(1, -1)+ .replaceAll('\\"', '"')+ .replaceAll("'", "\\'")}'`;+ const singleQuotes = caption.text.match(/'/g)?.length ?? 0;+ const doubleQuotes = caption.text.match(/"/g)?.length ?? 0;+ const text =+ singleQuotes === doubleQuotes+ ? formattingConfig.quote === 'single'+ ? singleQuotedText+ : doubleQuotedText+ : singleQuotes < doubleQuotes+ ? singleQuotedText+ : doubleQuotedText;+ const properties = [+ `text: ${text}`,+ `startMs: ${JSON.stringify(caption.startMs)}`,+ `endMs: ${JSON.stringify(caption.endMs)}`,+ `timestampMs: ${JSON.stringify(caption.timestampMs)}`,+ `confidence: ${JSON.stringify(caption.confidence)}`,+ ...(caption.pageBreakAfter === undefined+ ? []+ : [`pageBreakAfter: ${caption.pageBreakAfter}`]),+ ];+ return [+ '{',+ ...properties.map((property, propertyIndex) =>+ indentInsertedJsx({+ indent: formattingConfig.indentationUnit,+ insertion: `${property}${+ propertyIndex < properties.length - 1 || trailingComma ? ',' : ''+ }`,+ }),+ ),+ `}${captionIndex < captions.length - 1 || trailingComma ? ',' : ''}`,+ ].map((line) =>+ indentInsertedJsx({+ indent: formattingConfig.indentationUnit,+ insertion: line,+ }),+ );+ });+ const multilineElementLines = [+ `<${captionsLocalName}`,+ 'captions={[',+ ...captionLines,+ ']}',+ ...copiedAttributes,+ '/>',+ ];+ const elementSource =+ captions.length === 0 &&+ !singleLineElement.includes('\n') &&+ singleLineElement.length <= formattingConfig.printWidth+ ? singleLineElement+ : multilineElementLines+ .map((line, index) =>+ index === 0 || index === multilineElementLines.length - 1+ ? line+ : indentInsertedJsx({+ indent: formattingConfig.indentationUnit,+ insertion: line,+ }),+ )+ .join(formattingConfig.endOfLine);const parsedElement = parseAst(`const element = (${elementSource});`).program.body[0];if (diff --git a/packages/codemods/src/test/insert-basic-captions.test.ts b/packages/codemods/src/test/insert-basic-captions.test.tsnew file mode 100644index 0000000000..fba9758db4--- /dev/null+++ b/packages/codemods/src/test/insert-basic-captions.test.ts@@ -0,0 +1,126 @@+import {expect, test} from 'bun:test';+import {insertBasicCaptions} from '../insert-basic-captions';+import {lineContainingToNodePath} from './node-path-test-utils';++const captions = [+ {+ text: 'Here',+ startMs: 1440,+ endMs: 1620,+ timestampMs: 1530,+ confidence: null,+ },+ {+ text: ' are',+ startMs: 1620,+ endMs: 1820,+ timestampMs: 1720,+ confidence: null,+ },+];++test('inserts captions with save-stable defaults without formatting existing source', () => {+ const input = `import { Video } from "@remotion/media";++const untouched = {keep : "this spacing"};++export const Comp = () => (+ <>+ <Video src="video.mp4" />+ </>+);+`;+ const {output} = insertBasicCaptions({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ captions,+ durationInFrames: 177.45,+ premountFor: 30,+ });++ expect(output).toBe(`import { BasicCaptions } from "./basic-captions.element";+import { Video } from "@remotion/media";++const untouched = {keep : "this spacing"};++export const Comp = () => (+ <>+ <Video src="video.mp4" />+ <BasicCaptions+ captions={[+ {+ text: "Here",+ startMs: 1440,+ endMs: 1620,+ timestampMs: 1530,+ confidence: null,+ },+ {+ text: " are",+ startMs: 1620,+ endMs: 1820,+ timestampMs: 1720,+ confidence: null,+ },+ ]}+ durationInFrames={177.45}+ premountFor={30}+ />+ </>+);+`);+});++test('uses the source whitespace and configured trailing comma style', () => {+ const input = [+ "import {Video} from '@remotion/media'",+ '',+ 'export const Comp = () => (',+ '\t<>',+ '\t\t<Video src="video.mp4" />',+ '\t</>',+ ')',+ '',+ ].join('\r\n');+ const {output} = insertBasicCaptions({+ input,+ nodePath: lineContainingToNodePath(input, '<Video'),+ captions: [+ {+ ...captions[0],+ text: "Jonny's video",+ pageBreakAfter: true,+ },+ ],+ durationInFrames: 90,+ premountFor: null,+ prettierConfigOverride: {trailingComma: 'none'},+ });++ expect(output).toBe(+ [+ "import {BasicCaptions} from './basic-captions.element'",+ "import {Video} from '@remotion/media'",+ '',+ 'export const Comp = () => (',+ '\t<>',+ '\t\t<Video src="video.mp4" />',+ '\t\t<BasicCaptions',+ '\t\t\tcaptions={[',+ '\t\t\t\t{',+ '\t\t\t\t\ttext: "Jonny\'s video",',+ '\t\t\t\t\tstartMs: 1440,',+ '\t\t\t\t\tendMs: 1620,',+ '\t\t\t\t\ttimestampMs: 1530,',+ '\t\t\t\t\tconfidence: null,',+ '\t\t\t\t\tpageBreakAfter: true',+ '\t\t\t\t}',+ '\t\t\t]}',+ '\t\t\tdurationInFrames={90}',+ '\t\t/>',+ '\t</>',+ ')',+ '',+ ].join('\r\n'),+ );+});diff --git a/packages/studio-server/src/test/insert-basic-captions.test.ts b/packages/studio-server/src/test/insert-basic-captions.test.tsindex 9ef77d8794..638aa3eb6b 100644--- a/packages/studio-server/src/test/insert-basic-captions.test.ts+++ b/packages/studio-server/src/test/insert-basic-captions.test.ts@@ -112,7 +112,7 @@ export const Comp = () => (readdirSync(remotionRoot).filter((file) => file.endsWith('.element.tsx')),).toEqual(['basic-captions.element.tsx']);expect(written.match(/<BasicCaptions/g)).toHaveLength(2);- expect(written).toContain('"text": " Hello"');+ expect(written).toContain("text: ' Hello'");expect(written.replace(/\s+/g, ' ')).toContain('<BasicCaptions captions={[',);@@ -148,7 +148,7 @@ export const Comp = () => <Audio src="voice.mp3" />;`;expect(output).toContain('<>');expect(output).toContain('<Audio src="voice.mp3" />');- expect(output).toContain('<BasicCaptions captions={[');+ expect(output.replace(/\s+/g, ' ')).toContain('<BasicCaptions captions={[');expect(output).toContain('durationInFrames={30}');});@@ -197,6 +197,6 @@ export const Comp = () => <Audio src="voice.mp3" />;`;premountFor: 30,importPath: localElement.importPath,});- expect(second.output.match(/<BasicCaptions captions/g)).toHaveLength(2);+ expect(second.output.match(/<BasicCaptions\b/g)).toHaveLength(2);expect(second.output.match(/import \{BasicCaptions\}/g)).toHaveLength(1);});