Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/browser-studio`: Save composition `defaultProps` to source (#10593)

Jonny Burger257bc7516c49
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index a00def713b..b09d7c802f 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -7,6 +7,7 @@ import {
getCanUpdateDefaultPropsForProject,
getCompositionComponentInfo,
getCompositionFile,
+ formatInlineContentWithFormatter,
getFolderFile,
getRootFileForProject,
insertJsxElementIntoProjectWithNodePathRemappings,
@@ -18,6 +19,8 @@ import {
simpleDiff,
splitJsxSequence as splitJsxSequenceCodemod,
splitVideoFromAudio as splitVideoFromAudioCodemod,
+ updateDefaultProps as updateDefaultPropsCodemod,
+ type FormatInline,
} from '@remotion/studio-codemods';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
import {
@@ -60,6 +63,25 @@ const formatCodemodFile = async ({contents}: {contents: string}) => ({
}),
});
+const formatInline: FormatInline = ({inlineContent, linePrefix, endOfLine}) =>
+ formatInlineContentWithFormatter({
+ inlineContent,
+ linePrefix,
+ endOfLine,
+ prettierConfig: {
+ bracketSpacing: false,
+ parser: 'typescript',
+ singleQuote: true,
+ tabWidth: 2,
+ useTabs: false,
+ },
+ format: (source, options) =>
+ format(source, {
+ ...options,
+ plugins: [prettierPluginTypescript, prettierPluginEstree],
+ }),
+ });
+
export {
insertSolidIntoProject,
insertSolidIntoProjectWithNodePathRemappings,
@@ -718,6 +740,45 @@ export const createBrowserStudioOperations = ({
}
};
+ const updateDefaultProps: BrowserStudioOperations['updateDefaultProps'] =
+ async ({compositionId, defaultProps, enumPaths}) => {
+ try {
+ const project = getProject();
+ const compositionFile = getCompositionFile({compositionId, project});
+ if (compositionFile === null) {
+ throw new Error(`Could not find composition "${compositionId}"`);
+ }
+
+ const absolutePath = findProjectFile({
+ filePath: compositionFile,
+ project,
+ });
+ const {output} = await updateDefaultPropsCodemod({
+ input: project.files[absolutePath],
+ compositionId,
+ newDefaultProps: JSON.parse(defaultProps),
+ enumPaths,
+ formatInline,
+ });
+ controller.applyMutation({
+ fileName: absolutePath,
+ nodePathMutationFiles: null,
+ mutate: () => ({
+ ...project,
+ files: {...project.files, [absolutePath]: output},
+ }),
+ });
+
+ return {success: true};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error && error.stack ? error.stack : '',
+ };
+ }
+ };
+
const splitVideoFromAudio: BrowserStudioOperations['splitVideoFromAudio'] =
async ({fileName, nodePath}) => {
try {
@@ -1089,6 +1150,7 @@ export const createBrowserStudioOperations = ({
return Promise.resolve(undefined);
},
+ updateDefaultProps,
writeStaticFile: controller.writeStaticFile,
};
};
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 324e2e5583..3f2a5352e1 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -1036,6 +1036,140 @@ export const Root = () => {
);
});
+test('updates default props in the virtual project', async () => {
+ const fileName = '/project/src/Root.tsx';
+ const {operations, getProject} = makeOperationsForProject({
+ rootDir: '/project',
+ entryPoint: '/project/src/index.ts',
+ files: {
+ '/project/src/index.ts': `import {registerRoot} from 'remotion';
+import {Root} from './Root';
+registerRoot(Root);
+`,
+ [fileName]: `import {Composition} from 'remotion';
+
+const MyComponent = (props: {title: string; count: number}) => null;
+
+export const Root = () => {
+ return (
+ <Composition
+ id="MyComp"
+ component={MyComponent}
+ durationInFrames={60}
+ fps={30}
+ width={1280}
+ height={720}
+ defaultProps={{title: 'Hello', count: 1}}
+ />
+ );
+};
+`,
+ },
+ });
+ const events: EventSourceEvent[] = [];
+ operations.subscribeToEvent((event) => events.push(event));
+ await operations.subscribeToDefaultProps({
+ clientId: 'browser-studio',
+ compositionId: 'MyComp',
+ });
+
+ const result = await operations.updateDefaultProps({
+ compositionId: 'MyComp',
+ defaultProps: JSON.stringify({title: 'Updated', count: 2}),
+ enumPaths: [],
+ });
+ expect(result).toEqual({success: true});
+ expect(getProject().files[fileName]).toContain(
+ `defaultProps={{title: 'Updated', count: 2}}`,
+ );
+ expect(
+ events.some((event) => event.type === 'default-props-updatable-changed'),
+ ).toBe(true);
+
+ const undoResult = await operations.undo();
+ expect(undoResult.success).toBe(true);
+ expect(getProject().files[fileName]).toContain(
+ `defaultProps={{title: 'Hello', count: 1}}`,
+ );
+
+ const missingDefaultProps = await operations.updateDefaultProps({
+ compositionId: 'Unknown',
+ defaultProps: JSON.stringify({}),
+ enumPaths: [],
+ });
+ expect(missingDefaultProps).toEqual({
+ success: false,
+ reason: 'Could not find composition "Unknown"',
+ stack: expect.any(String),
+ });
+});
+
+test('formats wrapped default props with spaces', async () => {
+ const fileName = '/project/src/Root.tsx';
+ const {operations, getProject} = makeOperationsForProject({
+ rootDir: '/project',
+ entryPoint: '/project/src/index.ts',
+ files: {
+ '/project/src/index.ts': `import {registerRoot} from 'remotion';
+import {Root} from './Root';
+registerRoot(Root);
+`,
+ [fileName]: `import {Composition} from 'remotion';
+
+const MyComponent = () => null;
+
+export const Root = () => (
+ <Composition
+ id="MyComp"
+ component={MyComponent}
+ durationInFrames={60}
+ fps={30}
+ width={1280}
+ height={720}
+ defaultProps={{title: 'Before'}}
+ />
+);
+`,
+ },
+ });
+
+ const result = await operations.updateDefaultProps({
+ compositionId: 'MyComp',
+ defaultProps: JSON.stringify({
+ title: 'A sufficiently long title to wrap the default props object',
+ count: 2,
+ }),
+ enumPaths: [],
+ });
+
+ expect(result).toEqual({success: true});
+ expect(getProject().files[fileName]).toContain(`defaultProps={{
+ title: 'A sufficiently long title to wrap the default props object',
+ count: 2,
+ }}`);
+ expect(getProject().files[fileName]).not.toContain('\t');
+});
+
+test('reports a structured error when a composition has no defaultProps', async () => {
+ const {operations, getProject} = makeOperationsForProject(
+ createBlankTemplateProject(),
+ );
+ const initialFiles = {...getProject().files};
+
+ const result = await operations.updateDefaultProps({
+ compositionId: 'MyComp',
+ defaultProps: JSON.stringify({title: 'Hello'}),
+ enumPaths: [],
+ });
+ expect(result).toEqual({
+ success: false,
+ reason:
+ 'No `defaultProps` prop found in the <Composition/> tag with the ID "MyComp".',
+ stack: expect.any(String),
+ });
+ expect(getProject().files).toEqual(initialFiles);
+});
+
test('reports structured failures for unsupported codemods', async () => {
const {operations, getProject} = makeOperationsForProject(
createBlankTemplateProject(),
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index ceef856c41..038d0695c3 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -46,6 +46,12 @@ export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-no
export {simpleDiff} from './simple-diff';
export {splitJsxSequence} from './split-jsx-sequence';
export {splitVideoFromAudio} from './split-video-from-audio';
+export {
+ formatInlineContentWithFormatter,
+ getCompositionDefaultPropsLine,
+ updateDefaultProps,
+ type FormatInline,
+} from './update-default-props';
export {updateInlineCaptionPatches} from './update-inline-caption-patches';
export {
type RemovedProp,
diff --git a/packages/studio-codemods/src/update-default-props.ts b/packages/studio-codemods/src/update-default-props.ts
new file mode 100644
index 0000000000..a9ee95207f
--- /dev/null
+++ b/packages/studio-codemods/src/update-default-props.ts
@@ -0,0 +1,350 @@
+import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import {parseAst} from './sequence-props/parse-ast';
+
+export type FormatInline = (options: {
+ inlineContent: string;
+ linePrefix: string;
+ endOfLine: 'auto' | 'lf';
+}) => Promise<{formatted: string; didFormat: boolean}>;
+
+/**
+ * Instead of running prettier on the entire file (which is slow),
+ * format only a small snippet of inline content (e.g. stringified defaultProps).
+ *
+ * We wrap the content in `const __x__ = CONTENT;` and adjust printWidth
+ * so prettier makes the same line-breaking decisions as if the content
+ * were at its actual column position in the file.
+ */
+export const formatInlineContentWithFormatter = async ({
+ inlineContent,
+ linePrefix,
+ endOfLine,
+ prettierConfig,
+ format,
+}: {
+ inlineContent: string;
+ linePrefix: string;
+ endOfLine: 'auto' | 'lf';
+ prettierConfig: Record<string, unknown>;
+ format: (source: string, options: Record<string, unknown>) => Promise<string>;
+}): Promise<{formatted: string; didFormat: boolean}> => {
+ const tabWidth = (prettierConfig.tabWidth as number) ?? 2;
+ const baseIndent = linePrefix.match(/^(\s*)/)?.[1] ?? '';
+
+ // Calculate visual column offset (tabs expand to tabWidth columns)
+ const columnOffset = [...linePrefix].reduce(
+ (col, ch) => (ch === '\t' ? col + tabWidth : col + 1),
+ 0,
+ );
+
+ // Adjust printWidth so the wrapper prefix occupies the same visual
+ // width as the actual file prefix, ensuring identical line breaks.
+ const configPrintWidth = (prettierConfig.printWidth as number) ?? 80;
+ const wrapperPrefix = 'const __x__ = ';
+ const effectivePrintWidth = Math.max(
+ configPrintWidth - columnOffset + wrapperPrefix.length,
+ 20,
+ );
+
+ const wrappedSource = `${wrapperPrefix}${inlineContent};\n`;
+ const formattedWrapped = await format(wrappedSource, {
+ ...prettierConfig,
+ printWidth: effectivePrintWidth,
+ filepath: 'test.tsx',
+ endOfLine,
+ });
+
+ // Extract the formatted value from the wrapper
+ const withoutSemicolon = formattedWrapped.replace(/;\s*$/, '');
+ const wrappedInParentheses = withoutSemicolon.startsWith(
+ `${wrapperPrefix}(\n`,
+ );
+ let formattedProps: string;
+
+ if (withoutSemicolon.startsWith(wrapperPrefix) && !wrappedInParentheses) {
+ formattedProps = withoutSemicolon.slice(wrapperPrefix.length);
+ } else {
+ // Prettier broke the line after `=` β€” extract and dedent one level
+ const lines = withoutSemicolon
+ .split('\n')
+ .slice(1, wrappedInParentheses ? -1 : undefined);
+ const useTabs = prettierConfig.useTabs as boolean;
+ const oneIndent = useTabs ? '\t' : ' '.repeat(tabWidth);
+ formattedProps = lines
+ .map((l) => (l.startsWith(oneIndent) ? l.slice(oneIndent.length) : l))
+ .join('\n');
+ }
+
+ // Add base indentation to all lines except the first
+ const indentedProps = formattedProps
+ .split('\n')
+ .map((line, i) =>
+ i === 0 ? line : line.length > 0 ? baseIndent + line : line,
+ )
+ .join('\n');
+
+ return {formatted: indentedProps, didFormat: true};
+};
+
+// Recast uses tabWidth=4 for column counting, so columns don't
+// correspond to character indices when tabs are present.
+// This converts a recast loc (line/column) to a character offset.
+const RECAST_TAB_WIDTH = 4;
+
+const recastLocToOffset = (
+ input: string,
+ loc: {line: number; column: number},
+): number => {
+ const lines = input.split('\n');
+ let offset = 0;
+ for (let i = 0; i < loc.line - 1; i++) {
+ offset += lines[i].length + 1;
+ }
+
+ // Convert recast's tab-expanded column to character index
+ const line = lines[loc.line - 1];
+ let col = 0;
+ for (let i = 0; i < line.length; i++) {
+ if (col >= loc.column) {
+ return offset + i;
+ }
+
+ col += line[i] === '\t' ? RECAST_TAB_WIDTH : 1;
+ }
+
+ return offset + line.length;
+};
+
+export const updateDefaultProps = async ({
+ input,
+ compositionId,
+ newDefaultProps,
+ enumPaths,
+ formatInline,
+}: {
+ input: string;
+ compositionId: string;
+ newDefaultProps: Record<string, unknown>;
+ enumPaths: EnumPath[];
+ formatInline: FormatInline;
+}): Promise<{output: string; formatted: boolean}> => {
+ const ast = parseAst(input);
+ const stringified = stringifyDefaultProps({
+ props: newDefaultProps,
+ enumPaths,
+ });
+
+ let replaceStart: number | undefined;
+ let replaceEnd: number | undefined;
+
+ recast.types.visit(ast, {
+ visitJSXElement(path) {
+ const {openingElement} = path.node;
+ // 1: ensure its the element we're looking for
+ const openingName = openingElement.name;
+ if (
+ openingName.type !== 'JSXIdentifier' &&
+ openingName.type !== 'JSXNamespacedName'
+ ) {
+ this.traverse(path); // Continue traversing the AST
+ return;
+ }
+
+ if (openingName.name !== 'Composition' && openingName.name !== 'Still') {
+ this.traverse(path); // Continue traversing the AST
+ return;
+ }
+
+ if (
+ !openingElement.attributes?.some((attr) => {
+ if (attr.type === 'JSXSpreadAttribute') {
+ return;
+ }
+
+ if (!attr.value) {
+ return;
+ }
+
+ if (attr.value.type === 'JSXElement') {
+ return;
+ }
+
+ if (attr.value.type === 'JSXExpressionContainer') {
+ return;
+ }
+
+ if (attr.value.type === 'JSXFragment') {
+ return;
+ }
+
+ return attr.name.name === 'id' && attr.value.value === compositionId;
+ })
+ ) {
+ this.traverse(path); // Continue traversing the AST
+ return;
+ }
+
+ // 2: Find the defaultProps attribute and handle related errors
+ const defaultPropsAttr = openingElement.attributes.find((attr) => {
+ if (attr.type === 'JSXSpreadAttribute') {
+ this.traverse(path); // Continue traversing the AST
+ return;
+ }
+
+ return attr.name.name === 'defaultProps';
+ });
+
+ if (!defaultPropsAttr) {
+ throw new Error(
+ `No \`defaultProps\` prop found in the <Composition/> tag with the ID "${compositionId}".`,
+ );
+ }
+
+ if (defaultPropsAttr.type === 'JSXSpreadAttribute') {
+ this.traverse(path); // Continue traversing the AST
+ return;
+ }
+
+ // 3: ensure only hardcoded values are provided
+ if (
+ !defaultPropsAttr.value ||
+ defaultPropsAttr.value.type === 'JSXElement' ||
+ defaultPropsAttr.value.type === 'JSXText' ||
+ defaultPropsAttr.value.type === 'StringLiteral' ||
+ defaultPropsAttr.value.type === 'NumericLiteral' ||
+ defaultPropsAttr.value.type === 'BigIntLiteral' ||
+ defaultPropsAttr.value.type === 'DecimalLiteral' ||
+ defaultPropsAttr.value.type === 'NullLiteral' ||
+ defaultPropsAttr.value.type === 'BooleanLiteral' ||
+ defaultPropsAttr.value.type === 'RegExpLiteral' ||
+ defaultPropsAttr.value.type === 'JSXFragment' ||
+ defaultPropsAttr.value.type === 'Literal'
+ ) {
+ throw new Error(
+ `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag, but it is a ${defaultPropsAttr.value?.type}".`,
+ );
+ }
+
+ const defaultPropsValue = defaultPropsAttr.value.expression;
+ if (
+ defaultPropsValue.type !== 'ObjectExpression' &&
+ defaultPropsValue.type !== 'TSAsExpression'
+ ) {
+ throw new Error(
+ `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag with the ID "${compositionId}".`,
+ );
+ }
+
+ // Capture source positions for direct string replacement
+ // instead of modifying the AST and serializing (avoids recast artifacts)
+ const valueLoc = defaultPropsAttr.value.loc;
+ if (!valueLoc) {
+ throw new Error('Could not determine source location of defaultProps');
+ }
+
+ replaceStart = recastLocToOffset(input, valueLoc.start);
+ replaceEnd = recastLocToOffset(input, valueLoc.end);
+
+ this.traverse(path); // Continue traversing the AST
+ },
+ });
+
+ if (replaceStart === undefined || replaceEnd === undefined) {
+ throw new Error(
+ `Could not find defaultProps for composition "${compositionId}"`,
+ );
+ }
+
+ // linePrefix includes the JSX container opening brace
+ const lineStart = input.lastIndexOf('\n', replaceStart) + 1;
+ const linePrefix = input.substring(lineStart, replaceStart + 1);
+
+ const {formatted, didFormat} = await formatInline({
+ inlineContent: stringified,
+ linePrefix,
+ endOfLine: 'auto',
+ });
+
+ // Replace the JSX expression container in the original input
+ const output =
+ input.substring(0, replaceStart) +
+ '{' +
+ formatted +
+ '}' +
+ input.substring(replaceEnd);
+
+ return {output, formatted: didFormat};
+};
+
+/** Line of the matching `<Composition>` / `<Still>` opening tag (for log links). */
+export const getCompositionDefaultPropsLine = ({
+ input,
+ compositionId,
+}: {
+ input: string;
+ compositionId: string;
+}): number => {
+ const ast = parseAst(input);
+ let line = 1;
+ let found = false;
+
+ recast.types.visit(ast, {
+ visitJSXElement(path) {
+ if (found) {
+ this.traverse(path);
+ return;
+ }
+
+ const {openingElement} = path.node;
+ const openingName = openingElement.name;
+ if (
+ openingName.type !== 'JSXIdentifier' &&
+ openingName.type !== 'JSXNamespacedName'
+ ) {
+ this.traverse(path);
+ return;
+ }
+
+ if (openingName.name !== 'Composition' && openingName.name !== 'Still') {
+ this.traverse(path);
+ return;
+ }
+
+ if (
+ !openingElement.attributes?.some((attr) => {
+ if (attr.type === 'JSXSpreadAttribute') {
+ return;
+ }
+
+ if (!attr.value) {
+ return;
+ }
+
+ if (attr.value.type === 'JSXElement') {
+ return;
+ }
+
+ if (attr.value.type === 'JSXExpressionContainer') {
+ return;
+ }
+
+ if (attr.value.type === 'JSXFragment') {
+ return;
+ }
+
+ return attr.name.name === 'id' && attr.value.value === compositionId;
+ })
+ ) {
+ this.traverse(path);
+ return;
+ }
+
+ found = true;
+ line = openingElement.loc?.start.line ?? path.node.loc?.start.line ?? 1;
+ this.traverse(path);
+ },
+ });
+
+ return line;
+};
diff --git a/packages/studio-server/src/codemods/format-inline-content.ts b/packages/studio-server/src/codemods/format-inline-content.ts
index 89444a0ceb..d1eb1640c1 100644
--- a/packages/studio-server/src/codemods/format-inline-content.ts
+++ b/packages/studio-server/src/codemods/format-inline-content.ts
@@ -1,3 +1,5 @@
+import {formatInlineContentWithFormatter} from '@remotion/studio-codemods';
+
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
type PrettierType = typeof import('prettier');
@@ -9,10 +11,6 @@ type PrettierType = typeof import('prettier');
* @param linePrefix - Everything from the start of the line to where
* inlineContent will appear (used to calculate column offset and indentation)
* @param endOfLine - Prettier endOfLine option
- *
- * We wrap the content in `const __x__ = CONTENT;` and adjust printWidth
- * so prettier makes the same line-breaking decisions as if the content
- * were at its actual column position in the file.
*/
export const formatInlineContent = async ({
inlineContent,
@@ -50,61 +48,11 @@ export const formatInlineContent = async ({
}
}
- const tabWidth = (prettierConfig.tabWidth as number) ?? 2;
- const baseIndent = linePrefix.match(/^(\s*)/)?.[1] ?? '';
-
- // Calculate visual column offset (tabs expand to tabWidth columns)
- const columnOffset = [...linePrefix].reduce(
- (col, ch) => (ch === '\t' ? col + tabWidth : col + 1),
- 0,
- );
-
- // Adjust printWidth so the wrapper prefix occupies the same visual
- // width as the actual file prefix, ensuring identical line breaks.
- const configPrintWidth = (prettierConfig.printWidth as number) ?? 80;
- const wrapperPrefix = 'const __x__ = ';
- const effectivePrintWidth = Math.max(
- configPrintWidth - columnOffset + wrapperPrefix.length,
- 20,
- );
-
- const wrappedSource = `${wrapperPrefix}${inlineContent};\n`;
- const formattedWrapped = await format(wrappedSource, {
- ...prettierConfig,
- printWidth: effectivePrintWidth,
- filepath: 'test.tsx',
- plugins: [],
+ return formatInlineContentWithFormatter({
+ inlineContent,
+ linePrefix,
endOfLine,
+ prettierConfig,
+ format: (source, options) => format(source, {...options, plugins: []}),
});
-
- // Extract the formatted value from the wrapper
- const withoutSemicolon = formattedWrapped.replace(/;\s*$/, '');
- const wrappedInParentheses = withoutSemicolon.startsWith(
- `${wrapperPrefix}(\n`,
- );
- let formattedProps: string;
-
- if (withoutSemicolon.startsWith(wrapperPrefix) && !wrappedInParentheses) {
- formattedProps = withoutSemicolon.slice(wrapperPrefix.length);
- } else {
- // Prettier broke the line after `=` β€” extract and dedent one level
- const lines = withoutSemicolon
- .split('\n')
- .slice(1, wrappedInParentheses ? -1 : undefined);
- const useTabs = prettierConfig.useTabs as boolean;
- const oneIndent = useTabs ? '\t' : ' '.repeat(tabWidth);
- formattedProps = lines
- .map((l) => (l.startsWith(oneIndent) ? l.slice(oneIndent.length) : l))
- .join('\n');
- }
-
- // Add base indentation to all lines except the first
- const indentedProps = formattedProps
- .split('\n')
- .map((line, i) =>
- i === 0 ? line : line.length > 0 ? baseIndent + line : line,
- )
- .join('\n');
-
- return {formatted: indentedProps, didFormat: true};
};
diff --git a/packages/studio-server/src/codemods/update-default-props.ts b/packages/studio-server/src/codemods/update-default-props.ts
index 5266bb31ea..c4fc7dc263 100644
--- a/packages/studio-server/src/codemods/update-default-props.ts
+++ b/packages/studio-server/src/codemods/update-default-props.ts
@@ -1,38 +1,16 @@
-import {stringifyDefaultProps, type EnumPath} from '@remotion/studio-shared';
-import * as recast from 'recast';
+import {
+ updateDefaultProps as updateDefaultPropsCodemod,
+ type FormatInline,
+} from '@remotion/studio-codemods';
+import type {EnumPath} from '@remotion/studio-shared';
import {formatInlineContent} from './format-inline-content';
-import {parseAst} from './parse-ast';
-// Recast uses tabWidth=4 for column counting, so columns don't
-// correspond to character indices when tabs are present.
-// This converts a recast loc (line/column) to a character offset.
-const RECAST_TAB_WIDTH = 4;
+export {getCompositionDefaultPropsLine} from '@remotion/studio-codemods';
-const recastLocToOffset = (
- input: string,
- loc: {line: number; column: number},
-): number => {
- const lines = input.split('\n');
- let offset = 0;
- for (let i = 0; i < loc.line - 1; i++) {
- offset += lines[i].length + 1;
- }
+const formatInline: FormatInline = ({inlineContent, linePrefix, endOfLine}) =>
+ formatInlineContent({inlineContent, linePrefix, endOfLine});
- // Convert recast's tab-expanded column to character index
- const line = lines[loc.line - 1];
- let col = 0;
- for (let i = 0; i < line.length; i++) {
- if (col >= loc.column) {
- return offset + i;
- }
-
- col += line[i] === '\t' ? RECAST_TAB_WIDTH : 1;
- }
-
- return offset + line.length;
-};
-
-export const updateDefaultProps = async ({
+export const updateDefaultProps = ({
input,
compositionId,
newDefaultProps,
@@ -42,223 +20,11 @@ export const updateDefaultProps = async ({
compositionId: string;
newDefaultProps: Record<string, unknown>;
enumPaths: EnumPath[];
-}): Promise<{output: string; formatted: boolean}> => {
- const ast = parseAst(input);
- const stringified = stringifyDefaultProps({
- props: newDefaultProps,
+}): Promise<{output: string; formatted: boolean}> =>
+ updateDefaultPropsCodemod({
+ input,
+ compositionId,
+ newDefaultProps,
enumPaths,
+ formatInline,
});
-
- let replaceStart: number | undefined;
- let replaceEnd: number | undefined;
-
- recast.types.visit(ast, {
- visitJSXElement(path) {
- const {openingElement} = path.node;
- // 1: ensure its the element we're looking for
- const openingName = openingElement.name;
- if (
- openingName.type !== 'JSXIdentifier' &&
- openingName.type !== 'JSXNamespacedName'
- ) {
- this.traverse(path); // Continue traversing the AST
- return;
- }
-
- if (openingName.name !== 'Composition' && openingName.name !== 'Still') {
- this.traverse(path); // Continue traversing the AST
- return;
- }
-
- if (
- !openingElement.attributes?.some((attr) => {
- if (attr.type === 'JSXSpreadAttribute') {
- return;
- }
-
- if (!attr.value) {
- return;
- }
-
- if (attr.value.type === 'JSXElement') {
- return;
- }
-
- if (attr.value.type === 'JSXExpressionContainer') {
- return;
- }
-
- if (attr.value.type === 'JSXFragment') {
- return;
- }
-
- return attr.name.name === 'id' && attr.value.value === compositionId;
- })
- ) {
- this.traverse(path); // Continue traversing the AST
- return;
- }
-
- // 2: Find the defaultProps attribute and handle related errors
- const defaultPropsAttr = openingElement.attributes.find((attr) => {
- if (attr.type === 'JSXSpreadAttribute') {
- this.traverse(path); // Continue traversing the AST
- return;
- }
-
- return attr.name.name === 'defaultProps';
- });
-
- if (!defaultPropsAttr) {
- throw new Error(
- `No \`defaultProps\` prop found in the <Composition/> tag with the ID "${compositionId}".`,
- );
- }
-
- if (defaultPropsAttr.type === 'JSXSpreadAttribute') {
- this.traverse(path); // Continue traversing the AST
- return;
- }
-
- // 3: ensure only hardcoded values are provided
- if (
- !defaultPropsAttr.value ||
- defaultPropsAttr.value.type === 'JSXElement' ||
- defaultPropsAttr.value.type === 'JSXText' ||
- defaultPropsAttr.value.type === 'StringLiteral' ||
- defaultPropsAttr.value.type === 'NumericLiteral' ||
- defaultPropsAttr.value.type === 'BigIntLiteral' ||
- defaultPropsAttr.value.type === 'DecimalLiteral' ||
- defaultPropsAttr.value.type === 'NullLiteral' ||
- defaultPropsAttr.value.type === 'BooleanLiteral' ||
- defaultPropsAttr.value.type === 'RegExpLiteral' ||
- defaultPropsAttr.value.type === 'JSXFragment' ||
- defaultPropsAttr.value.type === 'Literal'
- ) {
- throw new Error(
- `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag, but it is a ${defaultPropsAttr.value?.type}".`,
- );
- }
-
- const defaultPropsValue = defaultPropsAttr.value.expression;
- if (
- defaultPropsValue.type !== 'ObjectExpression' &&
- defaultPropsValue.type !== 'TSAsExpression'
- ) {
- throw new Error(
- `\`defaultProps\` prop must be a hardcoded value in the <Composition/> tag with the ID "${compositionId}".`,
- );
- }
-
- // Capture source positions for direct string replacement
- // instead of modifying the AST and serializing (avoids recast artifacts)
- const valueLoc = defaultPropsAttr.value.loc;
- if (!valueLoc) {
- throw new Error('Could not determine source location of defaultProps');
- }
-
- replaceStart = recastLocToOffset(input, valueLoc.start);
- replaceEnd = recastLocToOffset(input, valueLoc.end);
-
- this.traverse(path); // Continue traversing the AST
- },
- });
-
- if (replaceStart === undefined || replaceEnd === undefined) {
- throw new Error(
- `Could not find defaultProps for composition "${compositionId}"`,
- );
- }
-
- // linePrefix includes the JSX container opening brace
- const lineStart = input.lastIndexOf('\n', replaceStart) + 1;
- const linePrefix = input.substring(lineStart, replaceStart + 1);
-
- const {formatted, didFormat} = await formatInlineContent({
- inlineContent: stringified,
- linePrefix,
- endOfLine: 'auto',
- });
-
- // Replace the JSX expression container in the original input
- const output =
- input.substring(0, replaceStart) +
- '{' +
- formatted +
- '}' +
- input.substring(replaceEnd);
-
- return {output, formatted: didFormat};
-};
-
-/** Line of the matching `<Composition>` / `<Still>` opening tag (for log links). */
-export const getCompositionDefaultPropsLine = ({
- input,
- compositionId,
-}: {
- input: string;
- compositionId: string;
-}): number => {
- const ast = parseAst(input);
- let line = 1;
- let found = false;
-
- recast.types.visit(ast, {
- visitJSXElement(path) {
- if (found) {
- this.traverse(path);
- return;
- }
-
- const {openingElement} = path.node;
- const openingName = openingElement.name;
- if (
- openingName.type !== 'JSXIdentifier' &&
- openingName.type !== 'JSXNamespacedName'
- ) {
- this.traverse(path);
- return;
- }
-
- if (openingName.name !== 'Composition' && openingName.name !== 'Still') {
- this.traverse(path);
- return;
- }
-
- if (
- !openingElement.attributes?.some((attr) => {
- if (attr.type === 'JSXSpreadAttribute') {
- return;
- }
-
- if (!attr.value) {
- return;
- }
-
- if (attr.value.type === 'JSXElement') {
- return;
- }
-
- if (attr.value.type === 'JSXExpressionContainer') {
- return;
- }
-
- if (attr.value.type === 'JSXFragment') {
- return;
- }
-
- return attr.name.name === 'id' && attr.value.value === compositionId;
- })
- ) {
- this.traverse(path);
- return;
- }
-
- found = true;
- line = openingElement.loc?.start.line ?? path.node.loc?.start.line ?? 1;
- this.traverse(path);
- },
- });
-
- return line;
-};
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index 06bb72b24c..27588cd093 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -32,6 +32,8 @@ import type {
UndoResponse,
UnsubscribeFromDefaultPropsRequest,
UnsubscribeFromSequencePropsRequest,
+ UpdateDefaultPropsRequest,
+ UpdateDefaultPropsResponse,
} from './api-requests';
import type {RecastCodemod} from './codemods';
import type {EventSourceEvent} from './event-source-event';
@@ -117,6 +119,9 @@ export type BrowserStudioOperations = {
unsubscribeFromSequenceProps: (
request: UnsubscribeFromSequencePropsRequest,
) => Promise<undefined>;
+ updateDefaultProps: (
+ request: UpdateDefaultPropsRequest,
+ ) => Promise<UpdateDefaultPropsResponse>;
writeStaticFile: (request: WriteStaticFileRequest) => Promise<void>;
};
diff --git a/packages/studio/src/components/RenderQueue/actions.ts b/packages/studio/src/components/RenderQueue/actions.ts
index 2ea8be4311..f1c4a1ec25 100644
--- a/packages/studio/src/components/RenderQueue/actions.ts
+++ b/packages/studio/src/components/RenderQueue/actions.ts
@@ -395,7 +395,7 @@ export const callUpdateDefaultPropsApi = (
defaultProps: Record<string, unknown>,
enumPaths: EnumPath[],
) => {
- return callApi('/api/update-default-props', {
+ const body = {
compositionId,
defaultProps: NoReactInternals.serializeJSONWithSpecialTypes({
data: defaultProps,
@@ -403,7 +403,13 @@ export const callUpdateDefaultPropsApi = (
staticBase: window.remotion_staticBase,
}).serializedString,
enumPaths,
- });
+ };
+ const browserStudioOperations = getBrowserStudioOperations();
+ if (browserStudioOperations !== null) {
+ return browserStudioOperations.updateDefaultProps(body);
+ }
+
+ return callApi('/api/update-default-props', body);
};
export const applyVisualControlChange = ({
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index 4ef9da9cef..8116f13ad6 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -35,6 +35,7 @@ export const makeBrowserStudioOperations = (
unusedOperation('unsubscribeFromDefaultProps'),
unsubscribeFromSequenceProps: () =>
unusedOperation('unsubscribeFromSequenceProps'),
+ updateDefaultProps: () => unusedOperation('updateDefaultProps'),
writeStaticFile: () => unusedOperation('writeStaticFile'),
...overrides,
};