🎥 Make videos programmatically with React
`@remotion/codemods`: Replace `addSolid()`, `addMedia()` and `addComponent()` with `createElement()` and `addElement()`
JonnyBurger624e30796722
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 8f47e1d3fa..32700c07a0 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -5,7 +5,7 @@ import {addCanvasCaptureComposition,addEffect as addEffectCodemod,addFolder,- addSolid,+ createElement,deleteComposition,deleteEffects as deleteEffectsCodemod,deleteJsxNodes as deleteJsxNodesCodemod,@@ -1488,9 +1488,14 @@ export const createBrowserStudioOperations = ({const result = wrapJsxNodeCodemod({project,node: {filePath, nodePath},- wrapper,- width: width ?? 0,- height: height ?? 0,+ wrapper: createElement({+ component: wrapper,+ importPath: 'remotion',+ props:+ wrapper === 'HtmlInCanvas'+ ? {width: width ?? 0, height: height ?? 0}+ : {},+ }),});const nodePathMutation = controller.applyMutation({undoRedoNavigation: null,@@ -2128,43 +2133,19 @@ export const createBrowserStudioOperations = ({dependencies: installedDependencies,project: getProject(),});- const insertion =- request.element.type === 'solid'- ? addSolid({- project,- compositionId: request.compositionId,- compositionFile: request.compositionFile,- width: request.element.width,- height: request.element.height,- position: request.element.position ?? undefined,- from: request.from ?? undefined,- })- : null;- const result = insertion- ? {- changes: insertion.changes,- filePath: insertion.insertedNode.filePath,- insertedNodePath: insertion.insertedNode.nodePath,- nodePathRemappings: insertion.nodePathRemappings.map(- ({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),- ),- }- : await insertJsxElementIntoProjectWithNodePathRemappings({- project,- request,- svgMarkupToJsx,- wrapInSequence: null,- });- const changes =- 'changes' in result- ? result.changes- : [- {- filePath: result.filePath,- previousContents: project.files[result.filePath] ?? null,- nextContents: result.output,- },- ];+ const result = await insertJsxElementIntoProjectWithNodePathRemappings({+ project,+ request,+ svgMarkupToJsx,+ wrapInSequence: null,+ });+ const changes = [+ {+ filePath: result.filePath,+ previousContents: project.files[result.filePath] ?? null,+ nextContents: result.output,+ },+ ];const nodePathMutation = controller.applyMutation({undoRedoNavigation: null,timelineSelection:diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 430b08f8d8..543505dd07 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -1,8 +1,9 @@import {expect, test} from 'bun:test';import {- addSolid,+ addElement,applyCodemodChanges,CodemodsInternals,+ createElement,getJsxNodes,} from '@remotion/codemods';import {createElementPayload} from '@remotion/studio-protocol';@@ -15,18 +16,27 @@ import type {VirtualProject} from '../types';const {basicCaptionsElementSource} = CodemodsInternals;+const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {+ width: 1280,+ height: 720,+ color: 'gray',+ style: {position: 'absolute'},+ },+});+const insertSolid = (project: VirtualProject,compositionFile = '/project/src/Composition.tsx',) => {return applyCodemodChanges(project,- addSolid({+ addElement({project,- compositionFile,- compositionId: 'MyComp',- width: 1280,- height: 720,+ element: solid,+ target: {type: 'composition', compositionFile, compositionId: 'MyComp'},}).changes,);};@@ -70,10 +80,10 @@ test('adds a Solid to the blank Browser Studio project', () => {expect(composition).toContain('import { CalculateMetadataFunction, Composition, Solid } from "remotion";',);- expect(composition).toContain(- '<Solid width={1280} height={720} color="gray"',+ expect(composition).toMatch(+ /<Solid\s+width=\{1280\}\s+height=\{720\}\s+color="gray"/,);- expect(composition).toContain("style={{position: 'absolute'}}");+ expect(composition).toMatch(/position: ["']absolute["']/);expect(project.files['/project/src/Composition.tsx']).not.toContain('<Solid');});@@ -83,28 +93,36 @@ test('adds multiple Solids without duplicating the import', () => {const composition = twice.files['/project/src/Composition.tsx'];expect(composition.match(/\bSolid\b/g)).toHaveLength(3);- expect(composition.match(/<Solid /g)).toHaveLength(2);+ expect(composition.match(/<Solid\s/g)).toHaveLength(2);});test('adds a Solid at a timeline frame', () => {const project = createBlankTemplateProject();const updated = applyCodemodChanges(project,- addSolid({+ addElement({project,- compositionFile: '/project/src/Composition.tsx',- compositionId: 'MyComp',- from: 42,- width: 1280,- height: 720,- position: {x: 100, y: 50},+ element: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {+ from: 42,+ style: {position: 'absolute', translate: '100px 50px'},+ },+ children: [solid],+ }),+ target: {+ type: 'composition',+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ },}).changes,);const composition = updated.files['/project/src/Composition.tsx'];- expect(composition).toContain('<Sequence from={42}');- expect(composition).toContain("translate: '100px 50px'");- expect(composition).toContain('<Solid width={1280} height={720}');+ expect(composition).toMatch(/<Sequence\s+from=\{42\}/);+ expect(composition).toContain('translate: "100px 50px"');+ expect(composition).toMatch(/<Solid\s+width=\{1280\}\s+height=\{720\}/);});test('resolves an imported composition component', async () => {@@ -129,8 +147,8 @@ export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;expect(updated.files['/project/src/index.tsx']).toBe(project.files['/project/src/index.tsx'],);- expect(updated.files['/project/src/MyComponent.tsx']).toContain(- '<Solid width={1280}',+ expect(updated.files['/project/src/MyComponent.tsx']).toMatch(+ /<Solid\s+width=\{1280\}/,);let currentProject = project;@@ -196,23 +214,25 @@ registerRoot(Root);`,},};- const result = addSolid({+ const result = addElement({project,- compositionFile: '/project/src/index.tsx',- compositionId: 'MyComp',- width: 1280,- height: 720,+ element: solid,+ target: {+ type: 'composition',+ compositionFile: '/project/src/index.tsx',+ compositionId: 'MyComp',+ },});const updated = applyCodemodChanges(project, result.changes);const {nodePathRemappings} = result;const output = updated.files['/project/src/index.tsx'];expect(output).toContain(- "import {AbsoluteFill, Composition, registerRoot, Solid as RemotionSolid} from 'remotion';",+ "import {AbsoluteFill, Composition, registerRoot, Solid as Solid2} from 'remotion';",);- expect(output).not.toContain('<RemotionSequence>');+ expect(output).not.toContain('<Sequence');expect(output).toContain('<AbsoluteFill />');- expect(output).toContain('<RemotionSolid width={1280}');+ expect(output).toMatch(/<Solid2\s+width=\{1280\}/);expect(nodePathRemappings).toHaveLength(2);expect(nodePathRemappings).toEqual(expect.arrayContaining([diff --git a/packages/codemods/src/add-component.ts b/packages/codemods/src/add-component.tsdeleted file mode 100644index 504d9a0fe2..0000000000--- a/packages/codemods/src/add-component.ts+++ /dev/null@@ -1,36 +0,0 @@-import type {CodemodProject} from './codemod-project';-import type {CodemodValue} from './codemod-value';-import {type AddContentOptions, insertContent} from './insert-content';-import {type CodemodInsertionResult} from './node-references';--export type AddComponentOptions<Project extends CodemodProject> =- AddContentOptions<Project> & {- importName: string;- importPath: string;- props?: Record<string, CodemodValue>;- };--export const addComponent = <Project extends CodemodProject>({- importName,- importPath,- props = {},- ...options-}: AddComponentOptions<Project>): Promise<CodemodInsertionResult> => {- if (!/^[A-Z_$][\w$]*$/.test(importName) || importName === 'default') {- throw new Error(- 'importName must be a named component export beginning with an uppercase letter, _ or $',- );- }-- return insertContent({- ...options,- element: {- type: 'component',- componentName: importName,- importName,- importPath,- props: Object.entries(props).map(([name, value]) => ({name, value})),- position: null,- },- });-};diff --git a/packages/codemods/src/add-element.ts b/packages/codemods/src/add-element.tsnew file mode 100644index 0000000000..32122c0be0--- /dev/null+++ b/packages/codemods/src/add-element.ts@@ -0,0 +1,274 @@+import type {File, JSXElement} from '@babel/types';+import type {namedTypes} from 'ast-types';+import * as recast from 'recast';+import {buildJsxElement} from './build-jsx-element';+import {CodemodElement} from './codemod-element';+import type {CodemodProject} from './codemod-project';+import type {CompositionTarget} from './composition-editing';+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';+import {+ captureJsxNodePaths,+ getNodePathRemappings,+} from './get-node-path-remappings';+import {+ addElementToComponentRoot,+ getComponentRootNode,+ getDeclarationByExportName,+ getInsertionRootSourceEdit,+ getNullComponentRoot,+} from './insert-jsx-element';+import {findProjectFile} from './internals';+import {+ getNodeEditResult,+ type CodemodInsertionResult,+ type JsxNodeReference,+} from './node-references';+import {indentInsertedJsx, printInsertedJsx} from './print-jsx';+import {recastLocToOffset} from './recast-loc-to-offset';+import {resolveCompositionComponentInProject} from './resolve-composition-component-location';+import {parseAst} from './sequence-props/parse-ast';+import {+ applySourceEdits,+ captureImportSnapshots,+ getAdjacentJsxInsertionSourceEdit,+ getInsertImportSourceEdits,+ getJsxElementSourceForInsertion,+ type SourceEdit,+} from './source-edits';+import {+ getEndOfLine,+ getIndentationUnit,+ getLineIndent,+ indentContinuationLines,+} from './source-style';+import {stripParenthesizedExtra} from './strip-parenthesized-extra';++export type AddElementTarget =+ | ({type: 'composition'} & CompositionTarget)+ | {type: 'inside'; node: JsxNodeReference}+ | {type: 'before'; node: JsxNodeReference}+ | {type: 'after'; node: JsxNodeReference};++export type AddElementOptions<Project extends CodemodProject> = {+ project: Project;+ element: CodemodElement;+ target: AddElementTarget;+};++const b = recast.types.builders;++type SourceEditInput = {+ ast: File;+ input: string;+ insertion: string;+ jsx: namedTypes.JSXElement;+};++const getCompositionRootSourceEdit = ({+ ast,+ exportName,+ input,+ insertion,+ jsx,+}: SourceEditInput & {exportName: string | 'default'}): SourceEdit => {+ const declaration = getDeclarationByExportName({ast, exportName});+ const root = declaration ? getComponentRootNode(declaration) : null;+ const nullRoot = declaration ? getNullComponentRoot(declaration) : null;+ addElementToComponentRoot({ast, exportName, element: jsx});+ return getInsertionRootSourceEdit({+ insertInside: root?.type === 'JSXFragment',+ input,+ insertion,+ nullRoot,+ prettierConfigOverride: null,+ root,+ });+};++const getNodeTargetSourceEdit = ({+ ast,+ input,+ insertion,+ jsx,+ target,+}: SourceEditInput & {+ target: Exclude<AddElementTarget, {type: 'composition'}>;+}): SourceEdit => {+ const targetPath = findJsxElementPathForDeletion(ast, target.node.nodePath);+ if (!targetPath) {+ throw new Error('Could not find a JSX element at the target node path');+ }++ const targetElement = targetPath.node as JSXElement;+ if (target.type === 'inside') {+ const edit = getInsertionRootSourceEdit({+ insertInside: true,+ input,+ insertion,+ nullRoot: null,+ prettierConfigOverride: null,+ root: targetElement as never,+ });+ targetElement.children.push(jsx as never);+ if (targetElement.openingElement.selfClosing) {+ targetElement.openingElement.selfClosing = false;+ targetElement.closingElement = b.jsxClosingElement(+ targetElement.openingElement.name as never,+ ) as never;+ }++ return edit;+ }++ const parent = targetPath.parentPath?.node;+ if (+ parent &&+ (parent.type === 'JSXElement' || parent.type === 'JSXFragment') &&+ parent.children.includes(targetElement)+ ) {+ const index = parent.children.indexOf(targetElement);+ parent.children.splice(+ target.type === 'after' ? index + 1 : index,+ 0,+ jsx as never,+ );+ return getAdjacentJsxInsertionSourceEdit({+ input,+ insertion,+ position: target.type,+ target: targetElement,+ });+ }++ // The target stands alone, e.g. as a return value. Group both in a fragment.+ if (!targetElement.loc) {+ throw new Error('Could not locate the target JSX element');+ }++ const start = recastLocToOffset(input, targetElement.loc.start);+ const end = recastLocToOffset(input, targetElement.loc.end);+ const original = getJsxElementSourceForInsertion({+ element: targetElement,+ input,+ });+ const existing = stripParenthesizedExtra(targetElement) as never;+ targetPath.replace(+ b.jsxFragment(+ b.jsxOpeningFragment(),+ b.jsxClosingFragment(),+ target.type === 'after' ? [existing, jsx] : [jsx, existing],+ ),+ );+ const unit = getIndentationUnit(input, null);+ const children =+ target.type === 'after' ? [original, insertion] : [insertion, original];+ return {+ start,+ end,+ replacement: indentContinuationLines({+ indent: getLineIndent({input, offset: start}),+ input,+ printed: [+ '<>',+ ...children.map((child) =>+ indentInsertedJsx({indent: unit, insertion: child}),+ ),+ '</>',+ ].join(getEndOfLine(input)),+ }),+ };+};++const insertElementIntoFile = ({+ element,+ filePath,+ getSourceEdit,+ project,+}: {+ element: CodemodElement;+ filePath: string;+ getSourceEdit: (context: SourceEditInput) => SourceEdit;+ project: CodemodProject;+}): CodemodInsertionResult => {+ const input = project.files[filePath];+ const ast = parseAst(input);+ const captured = captureJsxNodePaths(ast);+ const importSnapshots = captureImportSnapshots(ast);+ const jsx = buildJsxElement({ast, element});+ const insertion = printInsertedJsx({+ element: jsx,+ input,+ prettierConfigOverride: null,+ });+ const edit = getSourceEdit({ast, input, insertion, jsx});+ const output = applySourceEdits({+ input,+ edits: [+ ...getInsertImportSourceEdits({+ ast,+ input,+ prettierConfigOverride: null,+ snapshots: importSnapshots,+ }),+ edit,+ ],+ });+ const {finalNodePathByNode, nodePathRemappings} = getNodePathRemappings({+ ast,+ captured,+ output,+ });+ const insertedNodePath = finalNodePathByNode.get(jsx.openingElement as never);+ if (!insertedNodePath) {+ throw new Error('Could not determine the inserted JSX node path');+ }++ return {+ ...getNodeEditResult({+ project,+ edits: [{filePath, output, nodePathRemappings}],+ }),+ insertedNode: {filePath, nodePath: insertedNodePath},+ };+};++export const addElement = <Project extends CodemodProject>({+ project,+ element,+ target,+}: AddElementOptions<Project>): CodemodInsertionResult => {+ if (!(element instanceof CodemodElement)) {+ throw new Error('element must be created with createElement()');+ }++ if (target.type === 'composition') {+ const resolved = resolveCompositionComponentInProject({+ project,+ compositionFile: target.compositionFile,+ compositionId: target.compositionId,+ });+ if (!resolved.canAddSequence) {+ throw new Error(+ 'Cannot insert JSX element into this composition component',+ );+ }++ return insertElementIntoFile({+ element,+ filePath: findProjectFile({project, filePath: resolved.filePath}),+ getSourceEdit: (context) =>+ getCompositionRootSourceEdit({+ ...context,+ exportName: resolved.exportName,+ }),+ project,+ });+ }++ return insertElementIntoFile({+ element,+ filePath: findProjectFile({project, filePath: target.node.filePath}),+ getSourceEdit: (context) => getNodeTargetSourceEdit({...context, target}),+ project,+ });+};diff --git a/packages/codemods/src/add-media.ts b/packages/codemods/src/add-media.tsdeleted file mode 100644index 12ddaf6510..0000000000--- a/packages/codemods/src/add-media.ts+++ /dev/null@@ -1,42 +0,0 @@-import type {CodemodProject} from './codemod-project';-import {type AddContentOptions, insertContent} from './insert-content';-import {type CodemodInsertionResult} from './node-references';--export type AddMediaOptions<Project extends CodemodProject> =- AddContentOptions<Project> & {- type: 'image' | 'video' | 'audio' | 'gif' | 'animated-image';- src: string;- srcType: 'static' | 'remote';- dimensions?: {width: number; height: number};- };--export const addMedia = <Project extends CodemodProject>({- type,- src,- srcType,- dimensions,- ...options-}: AddMediaOptions<Project>): Promise<CodemodInsertionResult> => {- if (- dimensions &&- (!Number.isFinite(dimensions.width) ||- dimensions.width <= 0 ||- !Number.isFinite(dimensions.height) ||- dimensions.height <= 0)- ) {- throw new Error('Media dimensions must be positive finite numbers');- }-- return insertContent({- ...options,- element: {- type: 'asset',- assetType: type,- src,- srcType,- dimensions: dimensions ?? null,- durationInFrames: null,- position: null,- },- });-};diff --git a/packages/codemods/src/add-solid.ts b/packages/codemods/src/add-solid.tsdeleted file mode 100644index 597705a90b..0000000000--- a/packages/codemods/src/add-solid.ts+++ /dev/null@@ -1,64 +0,0 @@-import type {CodemodProject} from './codemod-project';-import {getCodemodResult} from './codemod-project';-import {insertSolidIntoProjectWithNodePathRemappings} from './internals';-import type {CodemodInsertionResult} from './node-references';--export type AddSolidOptions<Project extends CodemodProject> = {- project: Project;- compositionId: string;- compositionFile: string;- width: number;- height: number;- from?: number;- position?: {x: number; y: number};-};--export type AddSolidResult = CodemodInsertionResult;--export const addSolid = <Project extends CodemodProject>({- project,- compositionId,- compositionFile,- width,- height,- from,- position,-}: AddSolidOptions<Project>): AddSolidResult => {- const insertion = insertSolidIntoProjectWithNodePathRemappings({- project,- request: {- compositionFile,- compositionId,- element: {- height,- position: position ?? null,- type: 'solid',- width,- },- from: from ?? null,- },- });- const insertedNodePath = insertion.nodePathRemappings.find(- (remapping) => remapping.oldNodePath === null,- )?.newNodePath;- if (!insertedNodePath) {- throw new Error('Could not determine the inserted JSX node path');- }-- return {- ...getCodemodResult({- project,- edits: [- {filePath: insertion.filePath, nextContents: insertion.nextSource},- ],- }),- nodePathRemappings: insertion.nodePathRemappings.map((remapping) => ({- filePath: insertion.filePath,- ...remapping,- })),- insertedNode: {- filePath: insertion.filePath,- nodePath: insertedNodePath,- },- };-};diff --git a/packages/codemods/src/build-jsx-element.ts b/packages/codemods/src/build-jsx-element.tsnew file mode 100644index 0000000000..6696f1ea0b--- /dev/null+++ b/packages/codemods/src/build-jsx-element.ts@@ -0,0 +1,124 @@+import type {File} from '@babel/types';+import type {namedTypes} from 'ast-types';+import * as recast from 'recast';+import {NoReactInternals} from 'remotion/no-react';+import type {CodemodElement} from './codemod-element';+import type {CodemodValue} from './codemod-value';+import {ensureOfficialNamedImport} from './insert-jsx-element';+import {ensureNamedImports} from './sequence-props/imports';+import {parseValueExpression} from './update-nested-prop';++const b = recast.types.builders;++const isSerializedToken = (value: string) =>+ value.startsWith(NoReactInternals.FILE_TOKEN) ||+ value.startsWith(NoReactInternals.DATE_TOKEN);++const containsFileToken = (value: CodemodValue): boolean => {+ if (typeof value === 'string') {+ return value.startsWith(NoReactInternals.FILE_TOKEN);+ }++ if (Array.isArray(value)) {+ return value.some(containsFileToken);+ }++ if (typeof value === 'object' && value !== null) {+ return Object.values(value).some(containsFileToken);+ }++ return false;+};++const buildJsxName = (+ localName: string,+): namedTypes.JSXIdentifier | namedTypes.JSXMemberExpression => {+ const [root, ...members] = localName.split('.');+ return members.reduce<+ namedTypes.JSXIdentifier | namedTypes.JSXMemberExpression+ >(+ (object, property) =>+ b.jsxMemberExpression(object, b.jsxIdentifier(property)),+ b.jsxIdentifier(root),+ );+};++const buildAttributeName = (name: string) => {+ const [namespace, local] = name.split(':');+ return local === undefined+ ? b.jsxIdentifier(name)+ : b.jsxNamespacedName(b.jsxIdentifier(namespace), b.jsxIdentifier(local));+};++// Text that JSX can hold verbatim. Everything else is wrapped in a string+// expression so braces, angle brackets and surrounding whitespace survive.+const canBeJsxText = (text: string) =>+ text.length > 0 && text === text.trim() && !/[{}<>&\r\n]/.test(text);++/**+ * Converts an element description into a Recast JSX element and adds the+ * imports it needs to the AST. The local names in the returned element account+ * for existing bindings, so aliases are used on conflicts.+ */+export const buildJsxElement = ({+ ast,+ element,+}: {+ ast: File;+ element: CodemodElement;+}): namedTypes.JSXElement => {+ let localName = element.component;+ if (element.importPath !== null) {+ const [importedName, ...members] = element.component.split('.');+ localName = [+ ensureOfficialNamedImport({+ ast,+ importedName,+ sourcePath: element.importPath,+ }),+ ...members,+ ].join('.');+ }++ const attributes = Object.entries(element.props).map(([name, value]) => {+ if (typeof value === 'string' && !isSerializedToken(value)) {+ return b.jsxAttribute(buildAttributeName(name), b.stringLiteral(value));+ }++ if (containsFileToken(value)) {+ ensureNamedImports({+ ast,+ importedNames: new Set(['staticFile']),+ sourcePath: 'remotion',+ });+ }++ return b.jsxAttribute(+ buildAttributeName(name),+ b.jsxExpressionContainer(parseValueExpression(value)),+ );+ });+ const children = element.children.map(+ (+ child,+ ):+ | namedTypes.JSXElement+ | namedTypes.JSXText+ | namedTypes.JSXExpressionContainer => {+ if (typeof child !== 'string') {+ return buildJsxElement({ast, element: child});+ }++ return canBeJsxText(child)+ ? b.jsxText(child)+ : b.jsxExpressionContainer(b.stringLiteral(child));+ },+ );+ const selfClosing = children.length === 0;++ return b.jsxElement(+ b.jsxOpeningElement(buildJsxName(localName), attributes, selfClosing),+ selfClosing ? null : b.jsxClosingElement(buildJsxName(localName)),+ children,+ );+};diff --git a/packages/codemods/src/codemod-element.ts b/packages/codemods/src/codemod-element.tsnew file mode 100644index 0000000000..ded3e4d7ad--- /dev/null+++ b/packages/codemods/src/codemod-element.ts@@ -0,0 +1,169 @@+import {NoReactInternals} from 'remotion/no-react';+import type {CodemodValue} from './codemod-value';++export type CodemodElementChild = CodemodElement | string;++export type CodemodElementOptions = {+ component: string;+ importPath?: string | null;+ props?: Record<string, CodemodValue>;+ children?: readonly (CodemodElement | CodemodElementOptions | string)[];+};++const componentRegex = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/;+const importedComponentRegex = /^[A-Z_$]/;+const propNameRegex = /^[A-Za-z_$][\w$-]*(:[A-Za-z_$][\w$-]*)?$/;++const isCodemodValue = (value: unknown): value is CodemodValue => {+ if (+ value === null ||+ typeof value === 'string' ||+ typeof value === 'boolean' ||+ (typeof value === 'number' && Number.isFinite(value))+ ) {+ return true;+ }++ if (Array.isArray(value)) {+ return value.every(isCodemodValue);+ }++ return (+ typeof value === 'object' &&+ Object.getPrototypeOf(value) === Object.prototype &&+ Object.values(value).every(isCodemodValue)+ );+};++/**+ * Describes a JSX element to insert into source code.+ * Instances are immutable: every method returns a new element and leaves the+ * original untouched, so an element can be reused as a template.+ * `JSON.stringify()` produces a plain description that `createElement()`+ * accepts again.+ */+export class CodemodElement {+ readonly component: string;+ readonly importPath: string | null;+ readonly props: Readonly<Record<string, CodemodValue>>;+ readonly children: readonly CodemodElementChild[];++ constructor({+ component,+ importPath = null,+ props = {},+ children = [],+ }: CodemodElementOptions) {+ if (typeof component !== 'string' || !componentRegex.test(component)) {+ throw new Error(+ `${JSON.stringify(component)} is not a valid JSX tag name. Use a component such as "Solid", a member expression such as "Interactive.Div" or an HTML tag such as "div"`,+ );+ }++ if (importPath !== null) {+ if (typeof importPath !== 'string' || importPath.trim() === '') {+ throw new Error('importPath must be a non-empty module specifier');+ }++ if (!importedComponentRegex.test(component)) {+ throw new Error(+ `Imported components must start with an uppercase letter, _ or $. Omit importPath to use the HTML tag "${component}"`,+ );+ }+ }++ for (const [name, value] of Object.entries(props)) {+ if (!propNameRegex.test(name)) {+ throw new Error(`"${name}" is not a valid JSX prop name`);+ }++ if (!isCodemodValue(value)) {+ throw new Error(+ `The value of prop "${name}" must be a string, finite number, boolean, null, array or plain object`,+ );+ }+ }++ this.component = component;+ this.importPath = importPath;+ this.props = {...props};+ this.children = children.map((child) => {+ if (typeof child === 'string' || child instanceof CodemodElement) {+ return child;+ }++ if (typeof child === 'object' && child !== null) {+ return new CodemodElement(child);+ }++ throw new Error(+ 'Children must be strings, element descriptions or elements created with createElement()',+ );+ });+ }++ /** Returns a copy with the prop set to the value. */+ withProp(name: string, value: CodemodValue): CodemodElement {+ return this.withProps({[name]: value});+ }++ /** Returns a copy with the props merged into the existing props. */+ withProps(props: Record<string, CodemodValue>): CodemodElement {+ return new CodemodElement({+ component: this.component,+ importPath: this.importPath,+ props: {...this.props, ...props},+ children: this.children,+ });+ }++ /** Returns a copy without the prop. */+ withoutProp(name: string): CodemodElement {+ return new CodemodElement({+ component: this.component,+ importPath: this.importPath,+ props: Object.fromEntries(+ Object.entries(this.props).filter(([key]) => key !== name),+ ),+ children: this.children,+ });+ }++ /** Returns a copy with the child appended after the existing children. */+ withChild(child: CodemodElement | CodemodElementOptions | string) {+ return this.withChildren([...this.children, child]);+ }++ /** Returns a copy whose children are replaced. */+ withChildren(+ children: readonly (CodemodElement | CodemodElementOptions | string)[],+ ): CodemodElement {+ return new CodemodElement({+ component: this.component,+ importPath: this.importPath,+ props: this.props,+ children,+ });+ }+}++export const createElement = (options: CodemodElementOptions): CodemodElement =>+ new CodemodElement(options);++/**+ * Returns a value that is written as `staticFile(path)` when inserted into+ * source code. Pass it as a prop value to `createElement()` or+ * `updateJsxNodeProps()`.+ */+export const staticFileValue = (path: string): string => {+ if (typeof path !== 'string' || path === '' || path.includes('\\')) {+ throw new Error(+ 'staticFileValue() expects a path relative to the public folder',+ );+ }++ return `${NoReactInternals.FILE_TOKEN}${path+ .split('/')+ .map(encodeURIComponent)+ .join('/')}`;+};diff --git a/packages/codemods/src/get-jsx-nodes.ts b/packages/codemods/src/get-jsx-nodes.tsindex 6aacf47cc7..9943cb2c21 100644--- a/packages/codemods/src/get-jsx-nodes.ts+++ b/packages/codemods/src/get-jsx-nodes.ts@@ -1,5 +1,5 @@import * as recast from 'recast';-import type {JsxComponentIdentity} from 'remotion';+import type {JsxComponentIdentity, SequenceNodePath} from 'remotion';import type {CodemodProject} from './codemod-project';import {captureJsxNodePaths} from './get-node-path-remappings';import {findProjectFile} from './internals';@@ -12,6 +12,7 @@ export type JsxNode = JsxNodeReference & {tagName: string;componentIdentity: JsxComponentIdentity | null;location: {line: number; column: number} | null;+ parentNodePath: SequenceNodePath | null;};export type GetJsxNodesOptions = {@@ -26,7 +27,11 @@ export const getJsxNodes = ({const resolvedFilePath = findProjectFile({project, filePath});const input = project.files[resolvedFilePath];const {ast} = getReadOnlySourceSnapshot(input);- return captureJsxNodePaths(ast).map(({node, nodePath}) => {+ const captured = captureJsxNodePaths(ast);+ const nodePathByNode = new Map(+ captured.map(({node, nodePath}) => [node, nodePath]),+ );+ return captured.map(({node, nodePath, parentNode}) => {const offset = node.loc ? recastLocToOffset(input, node.loc.start) : null;return {filePath: resolvedFilePath,@@ -43,6 +48,8 @@ export const getJsxNodes = ({.at(-1)!.length,}: null,+ parentNodePath:+ parentNode === null ? null : (nodePathByNode.get(parentNode) ?? null),};});};diff --git a/packages/codemods/src/get-node-path-remappings.ts b/packages/codemods/src/get-node-path-remappings.tsindex 3d11cf9235..a486c61b08 100644--- a/packages/codemods/src/get-node-path-remappings.ts+++ b/packages/codemods/src/get-node-path-remappings.ts@@ -9,16 +9,31 @@ export type CapturedJsxNodePath = {node: JSXOpeningElement;nodePath: SequenceNodePath;signature: string;+ // The opening element of the closest enclosing JSX element, if any.+ parentNode: JSXOpeningElement | null;};export const captureJsxNodePaths = (ast: File): CapturedJsxNodePath[] => {const captured: CapturedJsxNodePath[] = [];recast.visit(ast, {visitJSXOpeningElement(path) {+ let parentNode: JSXOpeningElement | null = null;+ // Skip the JSXElement that owns this opening element.+ let ancestor = path.parentPath?.parentPath ?? null;+ while (ancestor) {+ if (ancestor.node?.type === 'JSXElement') {+ parentNode = ancestor.node.openingElement as JSXOpeningElement;+ break;+ }++ ancestor = ancestor.parentPath;+ }+captured.push({node: path.node as JSXOpeningElement,nodePath: getNodePathForRecastPath(path, ast),signature: recast.prettyPrint(path.node as JSXOpeningElement).code,+ parentNode,});return this.traverse(path);},diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.tsindex 03a448ae51..6174611d43 100644--- a/packages/codemods/src/index.ts+++ b/packages/codemods/src/index.ts@@ -27,10 +27,18 @@ import {getKeyframeInterpolationFunctionForCallee} from './sequence-props/keyfraimport {simpleDiff} from './simple-diff';import {updateInlineCaptionPatches} from './update-inline-caption-patches';-export {addSolid, type AddSolidOptions, type AddSolidResult} from './add-solid';-export {addMedia, type AddMediaOptions} from './add-media';-export {addComponent, type AddComponentOptions} from './add-component';-export {type AddContentOptions} from './insert-content';+export {+ CodemodElement,+ createElement,+ staticFileValue,+ type CodemodElementChild,+ type CodemodElementOptions,+} from './codemod-element';+export {+ addElement,+ type AddElementOptions,+ type AddElementTarget,+} from './add-element';export {type CodemodValue} from './codemod-value';export {getJsxNodes,@@ -130,7 +138,11 @@ export type {} from './codemod-project';export {applyCodemodChanges} from './codemod-project';export {deleteJsxNodes, type DeleteJsxNodesOptions} from './delete-jsx-nodes';-export {canWrapJsxNode, wrapJsxNode} from './wrap-jsx-node';+export {+ canWrapJsxNode,+ wrapJsxNode,+ type WrapJsxNodeOptions,+} from './wrap-jsx-node';export type {EffectArrayElement,EffectDeletionTarget,diff --git a/packages/codemods/src/insert-content.ts b/packages/codemods/src/insert-content.tsdeleted file mode 100644index fa18305aeb..0000000000--- a/packages/codemods/src/insert-content.ts+++ /dev/null@@ -1,88 +0,0 @@-import type {InsertableCompositionElement} from '@remotion/studio-shared';-import type {CodemodProject} from './codemod-project';-import {insertJsxElementIntoProjectWithNodePathRemappings} from './insert-jsx-element';-import {findProjectFile} from './internals';-import {- getNodeEditResult,- type CodemodInsertionResult,-} from './node-references';--export type AddContentOptions<Project extends CodemodProject> = {- project: Project;- compositionFile: string;- compositionId: string;- from?: number;- durationInFrames?: number;- position?: {x: number; y: number};-};--export const insertContent = async <Project extends CodemodProject>({- project,- compositionFile,- compositionId,- from,- durationInFrames,- position,- element,-}: AddContentOptions<Project> & {- element: InsertableCompositionElement;-}): Promise<CodemodInsertionResult> => {- if (from !== undefined && (!Number.isInteger(from) || from < 0)) {- throw new Error('from must be a non-negative integer');- }-- if (- durationInFrames !== undefined &&- (!Number.isInteger(durationInFrames) || durationInFrames <= 0)- ) {- throw new Error('durationInFrames must be a positive integer');- }-- if (- position &&- (!Number.isFinite(position.x) || !Number.isFinite(position.y))- ) {- throw new Error('Position must be finite');- }-- const wrapped = from !== undefined || durationInFrames !== undefined;- const insertion = await insertJsxElementIntoProjectWithNodePathRemappings({- project,- request: {- compositionFile,- compositionId,- from: null,- element: {...element, position: wrapped ? null : (position ?? null)},- },- svgMarkupToJsx: () => {- throw new Error('SVG markup is not supported by this operation');- },- wrapInSequence: wrapped- ? {- dimensions: element.type === 'asset' ? element.dimensions : null,- durationInFrames: durationInFrames ?? null,- from: from ?? 0,- name: null,- position: position ?? null,- }- : null,- });- const filePath = findProjectFile({project, filePath: insertion.filePath});- if (!insertion.insertedNodePath) {- throw new Error('Could not locate the inserted JSX node');- }-- return {- ...getNodeEditResult({- project,- edits: [- {- filePath,- output: insertion.output,- nodePathRemappings: insertion.nodePathRemappings,- },- ],- }),- insertedNode: {filePath, nodePath: insertion.insertedNodePath},- };-};diff --git a/packages/codemods/src/insert-jsx-element.ts b/packages/codemods/src/insert-jsx-element.tsindex 44ec16a1c1..25dcabcf25 100644--- a/packages/codemods/src/insert-jsx-element.ts+++ b/packages/codemods/src/insert-jsx-element.ts@@ -687,7 +687,7 @@ const findDefaultExportLocation = (ast: File): SourceLocation | null => {return location;};-type LocalComponentDeclaration =+export type LocalComponentDeclaration =| namedTypes.VariableDeclarator| namedTypes.FunctionDeclaration| namedTypes.ClassDeclaration;@@ -697,7 +697,7 @@ type FunctionLikeNode =| namedTypes.FunctionExpression| namedTypes.FunctionDeclaration;-type DefaultExportDeclaration =+export type DefaultExportDeclaration =namedTypes.ExportDefaultDeclaration['declaration'];const findLocalComponentDeclaration = ({@@ -833,7 +833,7 @@ const findRenderMethod = (return renderMethod?.type === 'ClassMethod' ? renderMethod : null;};-const getComponentRootNode = (+export const getComponentRootNode = (declaration: LocalComponentDeclaration | DefaultExportDeclaration,): namedTypes.JSXElement | namedTypes.JSXFragment | null => {if (declaration.type === 'VariableDeclarator') {@@ -1529,7 +1529,7 @@ const getImportDeclarations = ({);};-const ensureOfficialNamedImport = ({+export const ensureOfficialNamedImport = ({ast,importedName,sourcePath,@@ -1932,7 +1932,7 @@ const getDefaultExportDeclaration = (return declaration;};-const getDeclarationByExportName = ({+export const getDeclarationByExportName = ({ast,exportName,}: {@@ -1946,7 +1946,7 @@ const getDeclarationByExportName = ({return findLocalComponentDeclaration({ast, name: exportName});};-const addElementToComponentRoot = ({+export const addElementToComponentRoot = ({ast,exportName,element,@@ -2039,7 +2039,7 @@ const getNullRootFromFunctionLike = (: null;};-const getNullComponentRoot = (+export const getNullComponentRoot = (declaration: LocalComponentDeclaration | DefaultExportDeclaration,): NullLiteral | null => {if (declaration.type === 'VariableDeclarator') {@@ -2293,7 +2293,12 @@ export const getInsertionRootSourceEdit = ({start: openingStart,end: openingEnd,replacement: [- input.slice(openingStart, openingEnd).replace(/\s*\/>$/, '>'),+ // Keep a `>` that closed the tag on its own line where it was.+ input+ .slice(openingStart, openingEnd)+ .replace(/(\s*)\/>$/, (_, whitespace: string) =>+ whitespace.includes('\n') ? `${whitespace}>` : '>',+ ),indentInsertedJsx({indent: `${openingIndent}${unit}`, insertion}),`${openingIndent}</${recast.print(root.openingElement.name).code}>`,].join(endOfLine),diff --git a/packages/codemods/src/internals.ts b/packages/codemods/src/internals.tsindex a59c13d711..d99af877e5 100644--- a/packages/codemods/src/internals.ts+++ b/packages/codemods/src/internals.ts@@ -1,17 +1,10 @@import {parse} from '@babel/parser';-import type {JSXOpeningElement} from '@babel/types';import type {CanUpdateDefaultPropsResponse,CompositionComponentInfoRequest,- InsertJsxElementRequest,- SequenceNodePathRemapping,} from '@remotion/studio-shared';-import * as recast from 'recast';-import type {SequenceNodePath} from 'remotion';import type {CodemodProject} from './codemod-project';import {resolveCompositionComponentInProject} from './resolve-composition-component-location';-import {getNodePathForRecastPath} from './sequence-props';-import {parseAst} from './sequence-props/parse-ast';type AstNode = {type: string;@@ -24,12 +17,6 @@ type AstNode = {[key: string]: unknown;};-type TextEdit = {- end: number;- start: number;- text: string;-};-const isAstNode = (value: unknown): value is AstNode => {return (typeof value === 'object' &&@@ -58,15 +45,6 @@ const getString = (node: AstNode | null, key: string): string | null => {return typeof value === 'string' ? value : null;};-const getPosition = (node: AstNode, key: 'start' | 'end'): number => {- const value = node[key];- if (typeof value !== 'number') {- throw new Error(`Could not determine the ${key} of a source node`);- }-- return value;-};-const visit = (value: unknown,visitor: (node: AstNode) => boolean | void,@@ -309,683 +287,6 @@ const findCompositionElement = ({return result;};-const programStatements = (ast: AstNode) => {- const program = ast.type === 'File' ? getNode(ast, 'program') : ast;- if (!program || program.type !== 'Program') {- throw new Error('Could not parse source file');- }-- return getNodes(program, 'body');-};--const unwrapDeclaration = (statement: AstNode) => {- if (- statement.type === 'ExportNamedDeclaration' &&- getNode(statement, 'declaration')- ) {- return getNode(statement, 'declaration');- }-- return statement;-};--const findNamedDeclaration = (ast: AstNode, name: string) => {- for (const statement of programStatements(ast)) {- const declaration = unwrapDeclaration(statement);- if (!declaration) {- continue;- }-- if (- (declaration.type === 'FunctionDeclaration' ||- declaration.type === 'ClassDeclaration') &&- getString(getNode(declaration, 'id'), 'name') === name- ) {- return declaration;- }-- if (declaration.type === 'VariableDeclaration') {- const variable = getNodes(declaration, 'declarations').find(- (item) => getString(getNode(item, 'id'), 'name') === name,- );- if (variable) {- return variable;- }- }- }-- return null;-};--const findDefaultDeclaration = (ast: AstNode) => {- for (const statement of programStatements(ast)) {- if (statement.type !== 'ExportDefaultDeclaration') {- continue;- }-- const declaration = getNode(statement, 'declaration');- if (declaration?.type === 'Identifier') {- const name = getString(declaration, 'name');- return name ? findNamedDeclaration(ast, name) : null;- }-- return declaration;- }-- return null;-};--const unwrapExpression = (node: AstNode | null): AstNode | null => {- let current = node;- while (- current &&- (current.type === 'TSAsExpression' ||- current.type === 'TSSatisfiesExpression' ||- current.type === 'TypeCastExpression' ||- current.type === 'ParenthesizedExpression')- ) {- current = getNode(current, 'expression');- }-- return current;-};--const getReturnedRoot = (declaration: AstNode) => {- let fn: AstNode | null = declaration;- if (declaration.type === 'VariableDeclarator') {- fn = unwrapExpression(getNode(declaration, 'init'));- }-- if (- !fn ||- (fn.type !== 'ArrowFunctionExpression' &&- fn.type !== 'FunctionExpression' &&- fn.type !== 'FunctionDeclaration')- ) {- return null;- }-- const body = unwrapExpression(getNode(fn, 'body'));- if (!body) {- return null;- }-- if (body.type !== 'BlockStatement') {- return body;- }-- const statements = getNodes(body, 'body');- const returnStatements = statements.filter(- (statement) => statement.type === 'ReturnStatement',- );- if (- returnStatements.length !== 1 ||- returnStatements[0] !== statements.at(-1)- ) {- return null;- }-- return unwrapExpression(getNode(returnStatements[0], 'argument'));-};--const isCanvasRoot = (root: AstNode) => {- if (root.type !== 'JSXElement') {- return false;- }-- const openingElement = getNode(root, 'openingElement');- const name = jsxName(getNode(openingElement ?? root, 'name'));- return (- name === 'ThreeCanvas' ||- name === 'RiveCanvas' ||- name === 'SkiaCanvas' ||- name === 'canvas'- );-};--const canAddToRoot = (root: AstNode | null): root is AstNode => {- if (!root) {- return false;- }-- if (root.type === 'NullLiteral') {- return true;- }-- return (- (root.type === 'JSXElement' || root.type === 'JSXFragment') &&- !isCanvasRoot(root)- );-};--const collectBindings = (ast: AstNode) => {- const bindings = new Set<string>();- visit(ast, (node) => {- if (- node.type === 'VariableDeclarator' ||- node.type === 'FunctionDeclaration' ||- node.type === 'ClassDeclaration' ||- node.type === 'ImportSpecifier' ||- node.type === 'ImportDefaultSpecifier' ||- node.type === 'ImportNamespaceSpecifier'- ) {- const identifier = node.type.startsWith('Import')- ? getNode(node, 'local')- : getNode(node, 'id');- const name = getString(identifier, 'name');- if (name) {- bindings.add(name);- }- }-- return false;- });-- return bindings;-};--const findImportedLocalName = ({- ast,- importedName,-}: {- ast: AstNode;- importedName: string;-}) => {- for (const statement of programStatements(ast)) {- if (- statement.type !== 'ImportDeclaration' ||- getString(getNode(statement, 'source'), 'value') !== 'remotion'- ) {- continue;- }-- for (const specifier of getNodes(statement, 'specifiers')) {- if (- specifier.type === 'ImportSpecifier' &&- (getString(getNode(specifier, 'imported'), 'name') ??- getString(getNode(specifier, 'imported'), 'value')) === importedName- ) {- return getString(getNode(specifier, 'local'), 'name');- }- }- }-- return null;-};--const chooseLocalName = ({- ast,- candidates,- importedName,-}: {- ast: AstNode;- candidates: string[];- importedName: string;-}) => {- const existing = findImportedLocalName({ast, importedName});- if (existing) {- return {addImport: false, localName: existing};- }-- const bindings = collectBindings(ast);- const localName = candidates.find((candidate) => !bindings.has(candidate));- if (!localName) {- throw new Error(- `Cannot add <${importedName}> because all supported local names are defined`,- );- }-- return {addImport: true, localName};-};--const getImportEdit = ({- ast,- imports,-}: {- ast: AstNode;- imports: {importedName: string; localName: string}[];-}): TextEdit | null => {- if (imports.length === 0) {- return null;- }-- const specifiers = imports- .map(({importedName, localName}) =>- importedName === localName- ? importedName- : `${importedName} as ${localName}`,- )- .join(', ');- const existingImport = programStatements(ast).find(- (statement) =>- statement.type === 'ImportDeclaration' &&- getString(getNode(statement, 'source'), 'value') === 'remotion' &&- getString(statement, 'importKind') !== 'type' &&- !getNodes(statement, 'specifiers').some(- (specifier) => specifier.type === 'ImportNamespaceSpecifier',- ),- );- if (existingImport) {- const existingSpecifiers = getNodes(existingImport, 'specifiers');- const namedSpecifiers = existingSpecifiers.filter(- (specifier) => specifier.type === 'ImportSpecifier',- );- const lastNamedSpecifier = namedSpecifiers.at(-1);- if (lastNamedSpecifier) {- const end = getPosition(lastNamedSpecifier, 'end');- return {end, start: end, text: `, ${specifiers}`};- }-- const defaultSpecifier = existingSpecifiers.find(- (specifier) => specifier.type === 'ImportDefaultSpecifier',- );- if (defaultSpecifier) {- const end = getPosition(defaultSpecifier, 'end');- return {end, start: end, text: `, {${specifiers}}`};- }- }-- const firstImport = programStatements(ast).find(- (statement) => statement.type === 'ImportDeclaration',- );- const start = firstImport ? getPosition(firstImport, 'start') : 0;-- return {- end: start,- start,- text: `import {${specifiers}} from 'remotion';\n`,- };-};--const lineIndentAt = (source: string, position: number) => {- const lineStart = source.lastIndexOf('\n', position - 1) + 1;- return source.slice(lineStart, position).match(/^\s*/)?.[0] ?? '';-};--const indentationUnit = (source: string) => {- if (/^\t+/m.test(source)) {- return '\t';- }-- const indentation = source.match(/^([ ]+)\S/m)?.[1].length;- return ' '.repeat(indentation && indentation > 1 ? indentation : 2);-};--const roundCoordinate = (value: number) => {- const rounded = Math.round(value * 10) / 10;- return Object.is(rounded, -0) ? 0 : rounded;-};--const solidElement = ({- from,- height,- localName,- position,- sequenceLocalName,- width,-}: {- from: number | null;- height: number;- localName: string;- position: {x: number; y: number} | null;- sequenceLocalName: string | null;- width: number;-}) => {- const translate = position- ? `, translate: '${roundCoordinate(position.x)}px ${roundCoordinate(position.y)}px'`- : '';- const solid = `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;- if (from === null || sequenceLocalName === null) {- return solid;- }-- return `<${sequenceLocalName} from={${from}} style={{position: 'absolute'${translate}}}>${solid}</${sequenceLocalName}>`;-};--const appendToJsxRoot = ({- element,- root,- source,- unit,-}: {- element: string;- root: AstNode;- source: string;- unit: string;-}): TextEdit => {- const closing =- root.type === 'JSXFragment'- ? getNode(root, 'closingFragment')- : getNode(root, 'closingElement');- if (!closing) {- throw new Error('Composition component root does not accept children');- }-- const closingStart = getPosition(closing, 'start');- const lineStart = source.lastIndexOf('\n', closingStart - 1) + 1;- const beforeClosing = source.slice(lineStart, closingStart);- const closingIndent = beforeClosing.match(/^\s*$/)- ? beforeClosing- : lineIndentAt(source, getPosition(root, 'start'));-- if (/^\s*$/.test(beforeClosing) && lineStart > 0) {- return {- start: lineStart,- end: closingStart,- text: `${closingIndent}${unit}${element}\n${closingIndent}`,- };- }-- return {- start: closingStart,- end: closingStart,- text: `\n${closingIndent}${unit}${element}\n${closingIndent}`,- };-};--const replaceNullRoot = ({- element,- root,- source,- unit,-}: {- element: string;- root: AstNode;- source: string;- unit: string;-}): TextEdit => {- const indent = lineIndentAt(source, getPosition(root, 'start'));- return {- start: getPosition(root, 'start'),- end: getPosition(root, 'end'),- text: `(\n${indent}${unit}<>\n${indent}${unit}${unit}${element}\n${indent}${unit}</>\n${indent})`,- };-};--const replaceJsxElementRoot = ({- element,- root,- source,- unit,-}: {- element: string;- root: AstNode;- source: string;- unit: string;-}): TextEdit => {- const start = getPosition(root, 'start');- const indent = lineIndentAt(source, start);- const original = source.slice(start, getPosition(root, 'end'));-- return {- start,- end: getPosition(root, 'end'),- text: [- '<>',- `${indent}${unit}${original}`,- `${indent}${unit}${element}`,- `${indent}</>`,- ].join('\n'),- };-};--const applyTextEdits = (source: string, edits: TextEdit[]) => {- const sorted = [...edits].sort((a, b) => b.start - a.start);- let output = source;- let previousStart = source.length + 1;-- for (const edit of sorted) {- if (edit.end > previousStart) {- throw new Error('Overlapping source edits');- }-- output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);- previousStart = edit.start;- }-- return output;-};--export const insertSolidIntoSource = ({- exportName,- from = null,- height,- position,- source,- width,-}: {- exportName: string | 'default';- from?: number | null;- height: number;- position: {x: number; y: number} | null;- source: string;- width: number;-}): {output: string; line: number} => {- const ast = parseSource(source);- const declaration =- exportName === 'default'- ? findDefaultDeclaration(ast)- : findNamedDeclaration(ast, exportName);- if (!declaration) {- throw new Error(`Could not find composition component "${exportName}"`);- }-- const root = getReturnedRoot(declaration);- if (!canAddToRoot(root)) {- throw new Error(- 'Cannot insert JSX element into this composition component',- );- }-- const solidImport = chooseLocalName({- ast,- candidates: ['Solid', 'RemotionSolid'],- importedName: 'Solid',- });- const sequenceImport =- from !== null- ? chooseLocalName({- ast,- candidates: ['Sequence', 'RemotionSequence'],- importedName: 'Sequence',- })- : null;- const imports = [- ...(solidImport.addImport- ? [{importedName: 'Solid', localName: solidImport.localName}]- : []),- ...(sequenceImport?.addImport- ? [{importedName: 'Sequence', localName: sequenceImport.localName}]- : []),- ];- const unit = indentationUnit(source);- const element = solidElement({- from,- height,- localName: solidImport.localName,- position,- sequenceLocalName: sequenceImport?.localName ?? null,- width,- });- const rootEdit =- root.type === 'NullLiteral'- ? replaceNullRoot({- element,- root,- source,- unit,- })- : root.type === 'JSXElement'- ? replaceJsxElementRoot({- element,- root,- source,- unit,- })- : appendToJsxRoot({- element,- root,- source,- unit,- });- const importEdit = getImportEdit({ast, imports});- return {- line: root.loc?.start.line ?? 1,- output: applyTextEdits(source, [- rootEdit,- ...(importEdit ? [importEdit] : []),- ]),- };-};--const getNodePathRemappings = ({- afterSource,- beforeSource,-}: {- afterSource: string;- beforeSource: string;-}) => {- const astBefore = parseAst(beforeSource);- const astAfter = parseAst(afterSource);- const before: Array<{nodePath: SequenceNodePath; signature: string}> = [];- const after: Array<{nodePath: SequenceNodePath; signature: string}> = [];- recast.visit(astBefore, {- visitJSXOpeningElement(path) {- before.push({- nodePath: getNodePathForRecastPath(path, astBefore),- signature: recast.prettyPrint(path.node as JSXOpeningElement).code,- });- return this.traverse(path);- },- });- recast.visit(astAfter, {- visitJSXOpeningElement(path) {- after.push({- nodePath: getNodePathForRecastPath(path, astAfter),- signature: recast.prettyPrint(path.node as JSXOpeningElement).code,- });- return this.traverse(path);- },- });-- let nextAfterIndex = 0;- const matchedAfterIndexes = new Set<number>();- const remappings = before.flatMap(- ({nodePath, signature}): SequenceNodePathRemapping[] => {- const matchedIndex = after.findIndex(- (item, index) =>- index >= nextAfterIndex && item.signature === signature,- );- if (matchedIndex === -1) {- throw new Error(- 'Could not map JSX node paths after inserting an element',- );- }-- nextAfterIndex = matchedIndex + 1;- matchedAfterIndexes.add(matchedIndex);- const newNodePath = after[matchedIndex].nodePath;- if (JSON.stringify(nodePath) === JSON.stringify(newNodePath)) {- return [];- }-- return [{oldNodePath: nodePath, newNodePath}];- },- );-- for (let i = 0; i < after.length; i++) {- if (!matchedAfterIndexes.has(i)) {- remappings.push({oldNodePath: null, newNodePath: after[i].nodePath});- }- }-- return remappings;-};--const insertSolidIntoProjectWithoutNodePathRemappings = ({- project,- request,-}: {- project: CodemodProject;- request: InsertJsxElementRequest;-}): {- filePath: string;- previousSource: string;- nextSource: string;-} => {- if (request.element.type !== 'solid') {- throw new Error('This codemod only supports adding <Solid>');- }-- if (!Number.isFinite(request.element.width) || request.element.width < 1) {- throw new Error('width must be a positive number');- }-- if (!Number.isFinite(request.element.height) || request.element.height < 1) {- throw new Error('height must be a positive number');- }-- if (- request.element.position !== null &&- (!Number.isFinite(request.element.position.x) ||- !Number.isFinite(request.element.position.y))- ) {- throw new Error('Position must be finite');- }-- if (- request.from !== null &&- (!Number.isInteger(request.from) || request.from < 0)- ) {- throw new Error('from must be a non-negative integer');- }-- const resolved = resolveCompositionComponentInProject({- compositionFile: request.compositionFile,- compositionId: request.compositionId,- project,- });- const {output} = insertSolidIntoSource({- exportName: resolved.exportName,- from: request.from,- height: request.element.height,- position: request.element.position,- source: resolved.source,- width: request.element.width,- });- return {- filePath: resolved.filePath,- nextSource: output,- previousSource: resolved.source,- };-};--export const insertSolidIntoProjectWithNodePathRemappings = ({- project,- request,-}: {- project: CodemodProject;- request: InsertJsxElementRequest;-}): {- filePath: string;- nextSource: string;- nodePathRemappings: SequenceNodePathRemapping[];-} => {- const result = insertSolidIntoProjectWithoutNodePathRemappings({- project,- request,- });-- return {- filePath: result.filePath,- nextSource: result.nextSource,- nodePathRemappings: getNodePathRemappings({- afterSource: result.nextSource,- beforeSource: result.previousSource,- }),- };-};-const relativeToRoot = (filePath: string, rootDir: string) => {const normalizedFile = normalizePath(filePath);const normalizedRoot = normalizePath(rootDir).replace(/\/$/, '');diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.tsindex 96d46d2da6..bc50046809 100644--- a/packages/codemods/src/test/insert-solid.test.ts+++ b/packages/codemods/src/test/insert-solid.test.ts@@ -1,61 +1,115 @@import {expect, test} from 'bun:test';+import {addElement, applyCodemodChanges, createElement} from '../index';import {insertJsxElementIntoProjectWithNodePathRemappings} from '../insert-jsx-element';-import {insertSolidIntoSource} from '../internals';++const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 1280, height: 720, color: 'gray'},+});test('inserts a Solid into a component source file', () => {- const result = insertSolidIntoSource({- exportName: 'MyComposition',- height: 720,- position: null,- source: `import {AbsoluteFill} from 'remotion';+ const project = {+ rootDir: '/',+ files: {+ 'src/index.tsx': `import {AbsoluteFill, Composition} from 'remotion';export const MyComposition = () => <AbsoluteFill>Existing</AbsoluteFill>;+export const Root = () => <Composition id="MyComp" component={MyComposition} />;`,- width: 1280,+ },+ };+ const result = addElement({+ project,+ element: solid,+ target: {+ type: 'composition',+ compositionFile: 'src/index.tsx',+ compositionId: 'MyComp',+ },});+ const output = applyCodemodChanges(project, result.changes).files[+ 'src/index.tsx'+ ];- expect(result.output).toContain(- "import {AbsoluteFill, Solid} from 'remotion';",- );- expect(result.output).toContain(- '<Solid width={1280} height={720} color="gray"',+ expect(output).toContain(+ "import {AbsoluteFill, Composition, Solid} from 'remotion';",);- expect(result.line).toBe(3);+ expect(output).toContain('<Solid width={1280} height={720} color="gray" />');+ expect(result.insertedNode.filePath).toBe('src/index.tsx');});test('inserts a timeline Solid in a positioned Sequence', () => {- const result = insertSolidIntoSource({- exportName: 'MyComposition',- from: 42,- height: 720,- position: {x: 120.25, y: 80},- source: `export const MyComposition = () => null;\n`,- width: 1280,+ const project = {+ rootDir: '/',+ files: {+ 'src/index.tsx': `import {Composition} from 'remotion';+export const MyComposition = () => null;+export const Root = () => <Composition id="MyComp" component={MyComposition} />;+`,+ },+ };+ const sequence = createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 42, style: {position: 'absolute', translate: '120.3px 80px'}},+ }).withChild(solid);+ const result = addElement({+ project,+ element: sequence,+ target: {+ type: 'composition',+ compositionFile: 'src/index.tsx',+ compositionId: 'MyComp',+ },});+ const output = applyCodemodChanges(project, result.changes).files[+ 'src/index.tsx'+ ];- expect(result.output).toContain("import {Solid, Sequence} from 'remotion';");- expect(result.output).toContain('<Sequence from={42}');- expect(result.output).toContain("translate: '120.3px 80px'");- expect(result.output).toContain('<Solid width={1280} height={720}');+ expect(output).toContain(+ "import {Composition, Sequence, Solid} from 'remotion';",+ );+ expect(output).toContain('<Sequence');+ expect(output).toContain('from={42}');+ expect(output).toContain("translate: '120.3px 80px'");+ expect(output).toContain('<Solid width={1280} height={720} color="gray" />');+ expect(output.indexOf('<Sequence')).toBeLessThan(output.indexOf('<Solid'));+ expect(+ result.nodePathRemappings.filter((entry) => entry.oldNodePath === null),+ ).toHaveLength(2);});test('inserts a Solid as a sibling of a component root', () => {- const result = insertSolidIntoSource({- exportName: 'MyComposition',- height: 720,- position: null,- source: `export const MyComposition = () => (+ const project = {+ rootDir: '/',+ files: {+ 'src/index.tsx': `import {Composition} from 'remotion';+export const MyComposition = () => (<MapViewport><MapRegion /></MapViewport>);+export const Root = () => <Composition id="MyComp" component={MyComposition} />;`,- width: 1280,+ },+ };+ const result = addElement({+ project,+ element: solid,+ target: {+ type: 'composition',+ compositionFile: 'src/index.tsx',+ compositionId: 'MyComp',+ },});+ const output = applyCodemodChanges(project, result.changes).files[+ 'src/index.tsx'+ ];- const rootEnd = result.output.indexOf('</MapViewport>');- const solidStart = result.output.indexOf('<Solid');- expect(result.output).toContain('<>');+ const rootEnd = output.indexOf('</MapViewport>');+ const solidStart = output.indexOf('<Solid');+ expect(output).toContain('<>');expect(rootEnd).toBeGreaterThan(-1);expect(solidStart).toBeGreaterThan(rootEnd);});diff --git a/packages/codemods/src/test/public-api.test.ts b/packages/codemods/src/test/public-api.test.tsindex c60ad2f69f..0ac6c93d9f 100644--- a/packages/codemods/src/test/public-api.test.ts+++ b/packages/codemods/src/test/public-api.test.ts@@ -1,11 +1,43 @@import {expect, test} from 'bun:test';import {- addSolid,+ addElement,applyCodemodChanges,+ createElement,deleteJsxNodes,type CodemodProject,} from '../index';+const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 1280, height: 720, color: 'gray'},+});++const addSolid = ({+ project,+ compositionFile,+ compositionId,+ from,+}: {+ project: CodemodProject;+ compositionFile: string;+ compositionId: string;+ from?: number;+}) =>+ addElement({+ project,+ element:+ from === undefined+ ? solid+ : createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from},+ children: [solid],+ }),+ target: {type: 'composition', compositionFile, compositionId},+ });+const makeProject = () => ({entryPoint: 'src/index.ts',rootDir: '/',@@ -31,14 +63,12 @@ export const Video2 = () => <AbsoluteFill>Existing</AbsoluteFill>;},});-test('addSolid() immutably updates a virtual project', () => {+test('addElement() immutably updates a virtual project', () => {const project = makeProject();const result = addSolid({compositionFile: 'src/Root.tsx',compositionId: 'Demo',- height: 720,project,- width: 1280,});const updated = applyCodemodChanges(project, result.changes);@@ -64,17 +94,13 @@ test('deleteJsxNodes() deletes nodes from multiple files', async () => {const first = addSolid({compositionFile: 'src/Root.tsx',compositionId: 'Demo',- height: 720,project,- width: 1280,});const afterFirst = applyCodemodChanges(project, first.changes);const second = addSolid({compositionFile: 'src/Root2.tsx',compositionId: 'Demo2',- height: 720,project: afterFirst,- width: 1280,});const afterSecond = applyCodemodChanges(afterFirst, second.changes);const result = await deleteJsxNodes({@@ -97,9 +123,7 @@ test('deleteJsxNodes() deletes the Sequence wrapper identified by a node path',compositionFile: 'src/Root.tsx',compositionId: 'Demo',from: 10,- height: 720,project,- width: 1280,});const afterAdd = applyCodemodChanges(project, added.changes);const sourceWithSolid = afterAdd.files['src/Video.tsx'];diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.tsindex 0ab722f347..6179605971 100644--- a/packages/codemods/src/test/public-editing.test.ts+++ b/packages/codemods/src/test/public-editing.test.ts@@ -1,12 +1,11 @@import {expect, test} from 'bun:test';import {- addComponent,addComposition,addEffect,+ addElement,addFolder,- addMedia,- addSolid,applyCodemodChanges,+ createElement,deleteComposition,deleteEffects,deleteJsxNodes,@@ -25,6 +24,7 @@ import {resolveCompositionComponent,setCompositionDefaultProps,splitSequences,+ staticFileValue,unwrapFolder,updateCompositionMetadata,updateEffectKeyframes,@@ -32,12 +32,18 @@ import {updateJsxNodeKeyframes,updateJsxNodeProps,updateMultipleJsxNodeProps,+ wrapJsxNode,type CodemodProject,} from '../index';import {getChangedContents} from './get-changed-contents';const compositionFile = 'src/Root.tsx';const filePath = 'src/Video.tsx';+const compositionTarget = {+ type: 'composition' as const,+ compositionFile,+ compositionId: 'Demo',+};const makeProject = () => ({rootDir: '/',entryPoint: 'src/index.ts',@@ -152,20 +158,29 @@ test('discover, inspect, edit, animate, and remove JSX through the public API',test('insert media and components, reorder copies, and delete nodes across files', async () => {const project = makeProject();- const media = await addMedia({+ const image = createElement({+ component: 'Img',+ importPath: 'remotion',+ props: {+ src: staticFileValue('photo.png'),+ style: {width: 100, height: 100},+ },+ });+ const media = addElement({project,- compositionFile,- compositionId: 'Demo',- type: 'image',- src: 'photo.png',- srcType: 'static',- from: 10,- durationInFrames: 30,- dimensions: {width: 100, height: 100},+ element: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 10, durationInFrames: 30},+ }).withChild(image),+ target: compositionTarget,});expect(getChangedContents(media, filePath)).toMatch(/staticFile\(["']photo\.png["']\)/,);+ expect(getChangedContents(media, filePath)).toContain(+ "import {AbsoluteFill, Sequence, Img, staticFile} from 'remotion';",+ );const afterMedia = applyCodemodChanges(project, media.changes);expect(getJsxNodeProps({@@ -174,15 +189,23 @@ test('insert media and components, reorder copies, and delete nodes across fileskeys: ['from'],}).props.from,).toMatchObject({codeValue: 10});- const added = await addComponent({+ const imageNode = getJsxNodes({project: afterMedia, filePath}).find(+ (node) => node.tagName === 'Img',+ )!;+ expect(imageNode.parentNodePath).toEqual(media.insertedNode.nodePath);+ const added = addElement({project: afterMedia,- compositionFile,- compositionId: 'Demo',- importName: 'Title',- importPath: './Title',- props: {text: 'A title'},+ element: createElement({+ component: 'Title',+ importPath: './Title',+ props: {text: 'A title'},+ }),+ target: compositionTarget,});expect(getChangedContents(added, filePath)).toContain("from './Title'");+ expect(getChangedContents(added, filePath)).toContain(+ '<Title text="A title" />',+ );const afterAdd = applyCodemodChanges(afterMedia, added.changes);const duplicated = await duplicateJsxNodes({project: afterAdd,@@ -563,15 +586,22 @@ test('reject unsupported expressions and invalid edits atomically', async () =>expect(project.files).toEqual(original);});-test('existing addSolid returns remappings usable by public discovery', () => {+test('addElement returns remappings usable by public discovery and targets nodes', () => {const project = makeProject();- const inserted = addSolid({+ const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 100, height: 100, color: 'gray'},+ });+ const inserted = addElement({project,- compositionFile,- compositionId: 'Demo',- width: 100,- height: 100,- from: 15,+ element: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 15},+ children: [solid],+ }),+ target: compositionTarget,});const afterInsert = applyCodemodChanges(project, inserted.changes);expect(@@ -589,20 +619,118 @@ test('existing addSolid returns remappings usable by public discovery', () => {keys: ['from'],}).props.from,).toMatchObject({status: 'static', codeValue: 15});++ const nodes = getJsxNodes({project: afterInsert, filePath});+ const sequence = nodes.find((node) => node.tagName === 'Sequence')!;+ const div = nodes.find((node) => node.tagName === 'div')!;+ const caption = createElement({+ component: 'p',+ props: {className: 'caption', 'data-testid': 'caption'},+ children: ['Hello {world} & friends', {component: 'br'}],+ });+ const inside = addElement({+ project: afterInsert,+ element: caption,+ target: {type: 'inside', node: sequence},+ });+ expect(getChangedContents(inside, filePath)).toContain(+ `<p className="caption" data-testid="caption">`,+ );+ expect(getChangedContents(inside, filePath)).toContain(+ "{'Hello {world} & friends'}",+ );+ const afterInside = applyCodemodChanges(afterInsert, inside.changes);+ expect(+ getJsxNodes({project: afterInside, filePath})+ .filter(+ (node) =>+ JSON.stringify(node.parentNodePath) ===+ JSON.stringify(inside.insertedNode.nodePath),+ )+ .map((node) => node.tagName),+ ).toEqual(['br']);+ const before = addElement({+ project: afterInside,+ element: createElement({component: 'span', children: ['first']}),+ target: {+ type: 'before',+ node: getJsxNodes({project: afterInside, filePath}).find(+ (node) => node.tagName === 'div',+ )!,+ },+ });+ const afterBefore = applyCodemodChanges(afterInside, before.changes);+ expect(+ getJsxNodes({project: afterBefore, filePath}).map((node) => node.tagName),+ ).toEqual(['AbsoluteFill', 'span', 'div', 'Sequence', 'Solid', 'p', 'br']);+ expect(afterBefore.files[filePath]).toContain('<span>first</span>');+ const wrapped = wrapJsxNode({+ project: afterBefore,+ node: getJsxNodes({project: afterBefore, filePath}).find(+ (node) => node.tagName === 'div',+ )!,+ wrapper: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 5, name: 'Wrapped'},+ }),+ });+ expect(getChangedContents(wrapped, filePath)).toContain(+ '<Sequence from={5} name="Wrapped">',+ );+ expect(() =>+ wrapJsxNode({+ project: afterBefore,+ node: div,+ wrapper: createElement({component: 'div', children: ['x']}),+ }),+ ).toThrow('cannot have children');+ expect(() =>+ createElement({component: 'div', importPath: 'remotion'}),+ ).toThrow('uppercase');+ expect(() => createElement({component: '1Bad'})).toThrow('tag name');+ expect(() =>+ createElement({component: 'div', props: {'bad name': 1}}),+ ).toThrow('prop name');+ expect(solid.withProp('width', 200).props.width).toBe(200);+ expect(solid.props.width).toBe(100);+ expect(solid.withoutProp('color').props).toEqual({width: 100, height: 100});+ expect(JSON.parse(JSON.stringify(caption))).toEqual({+ component: 'p',+ importPath: null,+ props: {className: 'caption', 'data-testid': 'caption'},+ children: [+ 'Hello {world} & friends',+ {component: 'br', importPath: null, props: {}, children: []},+ ],+ });});test('nested copies return root references and insertion preserves relative keys under a project root', async () => {const original = {...makeProject(), rootDir: '/project'};- const media = await addMedia({+ const media = addElement({project: original,- compositionFile,- compositionId: 'Demo',- type: 'video',- src: 'https://example.com/video.mp4',- srcType: 'remote',- from: 0,- durationInFrames: 60,+ element: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 0, durationInFrames: 60},+ children: [+ {+ component: 'Video',+ importPath: '@remotion/media',+ props: {src: 'https://example.com/video.mp4'},+ },+ ],+ }),+ target: compositionTarget,});+ // The component file already declares `Video`, so the import is aliased.+ expect(getChangedContents(media, filePath)).toContain(+ "import {Video as Video2} from '@remotion/media';",+ );+ expect(getChangedContents(media, filePath)).toContain(+ '<Video2 src="https://example.com/video.mp4" />',+ );expect(media.insertedNode.filePath).toBe(filePath);const afterMedia = applyCodemodChanges(original, media.changes);expect(Object.keys(afterMedia.files)).toEqual(Object.keys(original.files));diff --git a/packages/codemods/src/wrap-jsx-node.ts b/packages/codemods/src/wrap-jsx-node.tsindex d878e9afd3..36fa794a84 100644--- a/packages/codemods/src/wrap-jsx-node.ts+++ b/packages/codemods/src/wrap-jsx-node.ts@@ -1,6 +1,8 @@import type {JSXElement, Node} from '@babel/types';import * as recast from 'recast';import type {SequenceNodePath} from 'remotion';+import {buildJsxElement} from './build-jsx-element';+import {CodemodElement} from './codemod-element';import type {CodemodProject} from './codemod-project';import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';import {@@ -11,7 +13,7 @@ import {findProjectFile} from './internals';import {getNodeEditResult, type JsxNodeReference} from './node-references';import {printJsxOpeningElement} from './print-jsx';import {recastLocToOffset} from './recast-loc-to-offset';-import {ensureNamedImport, getImportedName} from './sequence-props/imports';+import {getImportedName} from './sequence-props/imports';import {parseAst} from './sequence-props/parse-ast';import {applySourceEdits,@@ -21,7 +23,14 @@ import {import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';import {stripParenthesizedExtra} from './strip-parenthesized-extra';-type JsxWrapper = 'AbsoluteFill' | 'Sequence' | 'HtmlInCanvas';+export type WrapJsxNodeOptions<Project extends CodemodProject> = {+ project: Project;+ node: JsxNodeReference;+ wrapper: CodemodElement;+};++const isHtmlInCanvasWrapper = (wrapper: CodemodElement) =>+ wrapper.importPath === 'remotion' && wrapper.component === 'HtmlInCanvas';export const canWrapJsxNode = ({input,@@ -92,31 +101,36 @@ export const wrapJsxNode = <Project extends CodemodProject>({project,node,wrapper,- width,- height,-}: {- project: Project;- node: JsxNodeReference;- wrapper: JsxWrapper;- width: number;- height: number;-}) => {+}: WrapJsxNodeOptions<Project>) => {+ if (!(wrapper instanceof CodemodElement)) {+ throw new Error('wrapper must be created with createElement()');+ }++ if (wrapper.children.length > 0) {+ throw new Error(+ 'The wrapper element cannot have children of its own; the wrapped node becomes its only child',+ );+ }+const filePath = findProjectFile({project, filePath: node.filePath});const input = project.files[filePath];const eligibility = canWrapJsxNode({input, nodePath: node.nodePath});+ const htmlInCanvas = isHtmlInCanvasWrapper(wrapper);if (!eligibility.canWrap ||- (wrapper === 'HtmlInCanvas' && !eligibility.canWrapHtmlInCanvas)+ (htmlInCanvas && !eligibility.canWrapHtmlInCanvas)) {throw new Error('This JSX element cannot be wrapped');}if (- wrapper === 'HtmlInCanvas' &&- (!Number.isInteger(width) ||- width <= 0 ||- !Number.isInteger(height) ||- height <= 0)+ htmlInCanvas &&+ [wrapper.props.width, wrapper.props.height].some(+ (dimension) =>+ typeof dimension !== 'number' ||+ !Number.isInteger(dimension) ||+ dimension <= 0,+ )) {throw new Error('HtmlInCanvas requires positive integer dimensions');}@@ -230,44 +244,11 @@ export const wrapJsxNode = <Project extends CodemodProject>({return `${childIndent}${line.startsWith(closingIndent) ? line.slice(closingIndent.length) : line.trimStart()}`;});- const occupiedNames = new Set<string>();- recast.types.visit(ast, {- visitIdentifier(identifierPath) {- occupiedNames.add(identifierPath.node.name);- this.traverse(identifierPath);- },- visitJSXIdentifier(identifierPath) {- occupiedNames.add(identifierPath.node.name);- this.traverse(identifierPath);- },- });- let suggestedName: string = wrapper;- for (let suffix = 1; occupiedNames.has(suggestedName); suffix++) {- suggestedName = `${wrapper}FromRemotion${suffix}`;- }-- const localName = ensureNamedImport({- ast,- importedName: wrapper,- localName: suggestedName,- sourcePath: 'remotion',- });const b = recast.types.builders;- const name = b.jsxIdentifier(localName);- const attributes =- wrapper === 'HtmlInCanvas'- ? [- b.jsxAttribute(- b.jsxIdentifier('width'),- b.jsxExpressionContainer(b.numericLiteral(width)),- ),- b.jsxAttribute(- b.jsxIdentifier('height'),- b.jsxExpressionContainer(b.numericLiteral(height)),- ),- ]- : [];- const opening = b.jsxOpeningElement(name, attributes, false);+ const wrapperElement = buildJsxElement({ast, element: wrapper});+ const opening = wrapperElement.openingElement;+ opening.selfClosing = false;+ const localName = recast.print(opening.name).code;const openingLines = printJsxOpeningElement({openingElement: opening,input,@@ -280,7 +261,7 @@ export const wrapJsxNode = <Project extends CodemodProject>({`${indent}</${localName}>`,].join(endOfLine);path.replace(- b.jsxElement(opening, b.jsxClosingElement(b.jsxIdentifier(localName)), [+ b.jsxElement(opening, b.jsxClosingElement(opening.name), [stripParenthesizedExtra(original) as never,]) as never,);diff --git a/packages/docs/docs/codemods/add-component.mdx b/packages/docs/docs/codemods/add-component.mdxdeleted file mode 100644index e0f6873e7f..0000000000--- a/packages/docs/docs/codemods/add-component.mdx+++ /dev/null@@ -1,104 +0,0 @@-----image: /generated/articles-docs-codemods-add-component.png-title: 'addComponent()'-crumb: '@remotion/codemods'------# addComponent()<AvailableFrom v="4.0.528" />--Adds an instance of a named component export to a composition, including its import.--:::warning--_Draft API_: This API is experimental and may change.--:::--```ts twoslash title="add-component.ts"-import {addComponent, type CodemodProject} from '@remotion/codemods';--declare const project: CodemodProject;--const result = await addComponent({- project,- compositionFile: 'src/Root.tsx',- compositionId: 'MyComposition',- importName: 'Title',- importPath: './Title',- props: {text: 'Hello'},- from: 0,- durationInFrames: 60,-});--console.log(result);-```--Reuses an existing named import where possible and chooses a free local name on conflicts. The imported module must already exist; this operation does not generate the component implementation.--## Options--### project--An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.--### compositionFile--The file registering the composition. The component may be imported from another project file.--### compositionId--The static ID of the composition to edit.--### importName--The named component export to import. Must begin with an uppercase letter, `_`, or `$`. Default exports are not supported.--### importPath--The module specifier to insert. Relative imports are relative to the composition component file receiving the JSX.--### props?--A record of serializable prop values. Defaults to `{}`. Strings are values, not JavaScript expressions.--### from?--The start frame. When supplied, wraps the inserted content in a [`<Sequence>`](/docs/sequence). Must be a non-negative integer. By default, no start frame is set.--### durationInFrames?--A positive integer duration for the wrapper [`<Sequence>`](/docs/sequence). Supplying only a duration creates a wrapper starting at frame `0`. By default, no duration is set.--### position?--An `{x, y}` position in pixels. By default, content starts at the composition origin.--## Return value--A promise resolving to an object with the following properties.--### changes--An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.--### nodePathRemappings--An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).--### insertedNode--The inserted component reference, or its wrapper [`<Sequence>`](/docs/sequence) reference when timing is supplied.--## Errors--Throws or rejects when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.--## Compatibility--<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />--## See also--- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-component.ts)-- [`@remotion/codemods`](/docs/codemods)-- [`getJsxNodes()`](/docs/codemods/get-jsx-nodes)diff --git a/packages/docs/docs/codemods/add-element.mdx b/packages/docs/docs/codemods/add-element.mdxnew file mode 100644index 0000000000..7275fd4cf4--- /dev/null+++ b/packages/docs/docs/codemods/add-element.mdx@@ -0,0 +1,132 @@+---+image: /generated/articles-docs-codemods-add-element.png+title: 'addElement()'+crumb: '@remotion/codemods'+---++# addElement()<AvailableFrom v="4.0.530" />++Inserts an element created with [`createElement()`](/docs/codemods/create-element) into a composition component or relative to an existing JSX node, and adds the imports it needs.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="add-element.ts"+import {addElement, createElement, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const result = addElement({+ project,+ element: createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 1920, height: 1080, color: 'gray'},+ }),+ target: {+ type: 'composition',+ compositionFile: 'src/Root.tsx',+ compositionId: 'MyComposition',+ },+});++console.log(result.changes);+console.log(result.insertedNode);+```++To place the element on the timeline, wrap it in a [`<Sequence>`](/docs/sequence):++```ts twoslash title="add-timed-element.ts"+import {addElement, createElement, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const video = createElement({+ component: 'Video',+ importPath: '@remotion/media',+ props: {src: 'https://example.com/video.mp4'},+});++const result = addElement({+ project,+ element: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 30, durationInFrames: 90},+ children: [video],+ }),+ target: {+ type: 'composition',+ compositionFile: 'src/Root.tsx',+ compositionId: 'MyComposition',+ },+});+```++Media files are not copied or downloaded, metadata is not probed, and packages are not installed. The project must already contain the dependencies needed by the generated imports.++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### element++The element to insert, created with [`createElement()`](/docs/codemods/create-element).++### target++Where to insert the element. One of the following objects.++#### `{type: 'composition', compositionFile, compositionId}`++Appends the element to the component of the composition with the static ID `compositionId`, registered in `compositionFile`. The component may be imported from another project file. If the component returns a single element, both are grouped in a fragment. If it returns `null`, the element becomes its content.++#### `{type: 'inside', node}`++Appends the element as the last child of the JSX element referenced by `node`. Self-closing elements are expanded.++#### `{type: 'before', node}`++Inserts the element before the JSX element referenced by `node`. If the node has no JSX parent, for example because it is returned directly, both are grouped in a fragment.++#### `{type: 'after', node}`++Inserts the element after the JSX element referenced by `node`, following the same rules as `before`.++Obtain a `node` from [`getJsxNodes()`](/docs/codemods/get-jsx-nodes) or a previous result. See [node references](/docs/codemods#node-references).++## Return value++An object with the following properties.++### changes++An array of `{filePath, previousContents, nextContents}` file changes.++### nodePathRemappings++An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Every inserted element, including children of the inserted element, is listed with a `null` old path. See [node references](/docs/codemods#node-references).++### insertedNode++The reference of the outermost inserted element. Use [`getJsxNodes()`](/docs/codemods/get-jsx-nodes) and its `parentNodePath` to find inserted children.++## Errors++Throws when the target cannot be resolved, the composition component cannot receive content, or the element is invalid. Failed edits leave the input project unchanged.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-element.ts)+- [`createElement()`](/docs/codemods/create-element)+- [`deleteJsxNodes()`](/docs/codemods/delete-jsx-nodes)+- [`getJsxNodes()`](/docs/codemods/get-jsx-nodes)diff --git a/packages/docs/docs/codemods/add-media.mdx b/packages/docs/docs/codemods/add-media.mdxdeleted file mode 100644index 6fb754968b..0000000000--- a/packages/docs/docs/codemods/add-media.mdx+++ /dev/null@@ -1,108 +0,0 @@-----image: /generated/articles-docs-codemods-add-media.png-title: 'addMedia()'-crumb: '@remotion/codemods'------# addMedia()<AvailableFrom v="4.0.528" />--Adds an image, video, audio, GIF, or animated image to a composition component and adds the required imports.--:::warning--_Draft API_: This API is experimental and may change.--:::--```ts twoslash title="add-media.ts"-import {addMedia, type CodemodProject} from '@remotion/codemods';--declare const project: CodemodProject;--const result = await addMedia({- project,- compositionFile: 'src/Root.tsx',- compositionId: 'MyComposition',- type: 'video',- src: 'clip.mp4',- srcType: 'static',- from: 30,- durationInFrames: 90,-});--console.log(result);-```--Media files are not copied or downloaded, metadata is not probed, and packages are not installed. The project must already contain the dependencies needed by the generated imports. Relative paths refer to the public directory for `static` media.--## Options--### project--An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.--### compositionFile--The file registering the composition. The component may be imported from another project file.--### compositionId--The static ID of the composition to edit.--### type--One of `image`, `video`, `audio`, `gif`, or `animated-image`.--### src--The URL or public-directory-relative media path.--### srcType--Use `static` to generate a `staticFile(src)` expression, or `remote` for a URL.--### dimensions?--The media's `{width, height}` in pixels. Both must be positive finite numbers. By default, dimensions are not specified.--### from?--The start frame. When supplied, wraps the inserted content in a [`<Sequence>`](/docs/sequence). Must be a non-negative integer. By default, no start frame is set.--### durationInFrames?--A positive integer duration for the wrapper [`<Sequence>`](/docs/sequence). Supplying only a duration creates a wrapper starting at frame `0`. By default, no duration is set.--### position?--An `{x, y}` position in pixels. By default, content starts at the composition origin.--## Return value--A promise resolving to an object with the following properties.--### changes--An array of `{filePath, previousContents, nextContents}` file changes. A `null` content value indicates a created or deleted file.--### nodePathRemappings--An array of `{filePath, oldNodePath, newNodePath}` mappings. A `null` old path indicates an insertion; a `null` new path indicates removal. Apply these mappings to references from the input project. See [node references](/docs/codemods#node-references).--### insertedNode--The inserted element's reference, or the wrapper [`<Sequence>`](/docs/sequence) reference when timing is supplied.--## Errors--Throws or rejects when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.--## Compatibility--<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />--## See also--- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-media.ts)-- [`@remotion/codemods`](/docs/codemods)-- [`getJsxNodes()`](/docs/codemods/get-jsx-nodes)diff --git a/packages/docs/docs/codemods/add-solid.mdx b/packages/docs/docs/codemods/add-solid.mdxdeleted file mode 100644index e565f2f155..0000000000--- a/packages/docs/docs/codemods/add-solid.mdx+++ /dev/null@@ -1,93 +0,0 @@-----image: /generated/articles-docs-codemods-add-solid.png-title: 'addSolid()'-crumb: '@remotion/codemods'------# addSolid()<AvailableFrom v="4.0.527" />--Adds a [`<Solid>`](/docs/solid) to a composition component and adds the required imports.--:::warning--_Draft API_: This API is not yet stable. We are in the experimental phase of this package and reserve to change it at any time.--:::--```ts twoslash title="add-solid.ts"-import {addSolid, type CodemodProject} from '@remotion/codemods';--declare const project: CodemodProject;--const result = addSolid({- project,- compositionFile: 'src/Root.tsx',- compositionId: 'MyComposition',- width: 1920,- height: 1080,-});--console.log(result.changes);-console.log(result.insertedNode);-```--The input project is not mutated.--## Options--Pass an object with the following properties.--### project--An in-memory Remotion project containing `rootDir` and a `files` record.--### compositionFile--The path to the file that registers the composition. The component may be declared in that file or imported from another project file.--### compositionId--The ID of the [`<Composition>`](/docs/composition) to edit.--### width--The width of the inserted [`<Solid>`](/docs/solid).--### height--The height of the inserted [`<Solid>`](/docs/solid).--### from?--Wraps the [`<Solid>`](/docs/solid) in a [`<Sequence>`](/docs/sequence) starting at this frame. By default, the solid is not wrapped in a sequence.--### position?--Positions the solid at `{x, y}` pixels and adds a CSS translation. By default, the solid starts at the composition origin.--## Return value--An object with the following properties.--### changes--An array describing each changed file with its `filePath`, `previousContents`, and `nextContents`.--### insertedNode--The `filePath` and `nodePath` of the inserted JSX element. Pass these values as an item in `nodes` to [`deleteJsxNodes()`](/docs/codemods/delete-jsx-nodes) to remove the element again.--### nodePathRemappings<AvailableFrom v="4.0.528" />--File-qualified `{filePath, oldNodePath, newNodePath}` mappings for keeping node references after the edit. A `null` old path indicates an insertion; a `null` new path indicates removal. See [node references](/docs/codemods#node-references).--## Compatibility--<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />--## See also--- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/add-solid.ts)-- [`<Solid>`](/docs/solid)-- [`deleteJsxNodes()`](/docs/codemods/delete-jsx-nodes)-- [`@remotion/browser-bundler`](/docs/browser-bundler)diff --git a/packages/docs/docs/codemods/create-element.mdx b/packages/docs/docs/codemods/create-element.mdxnew file mode 100644index 0000000000..a43be1d403--- /dev/null+++ b/packages/docs/docs/codemods/create-element.mdx@@ -0,0 +1,104 @@+---+image: /generated/articles-docs-codemods-create-element.png+title: 'createElement()'+crumb: '@remotion/codemods'+---++# createElement()<AvailableFrom v="4.0.530" />++Describes a JSX element to insert into source code. Pass the result to [`addElement()`](/docs/codemods/add-element) to add it to a composition or next to an existing node, or to [`wrapJsxNode()`](/docs/codemods/wrap-jsx-node) to wrap an existing node.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="create-element.ts"+import {createElement} from '@remotion/codemods';++const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 1920, height: 1080, color: 'gray'},+});++const sequence = createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 30, durationInFrames: 60},+}).withChild(solid);+```++Inserting `sequence` produces the following JSX and adds `import {Sequence, Solid} from 'remotion'` if the imports are missing:++```tsx title="Generated JSX"+<Sequence from={30} durationInFrames={60}>+ <Solid width={1920} height={1080} color="gray" />+</Sequence>+```++An element is a description, not source code. Imports, local names, and formatting are decided when the element is inserted into a file. If the file already declares a binding with the same name, the import is aliased, for example `import {Solid as Solid2} from 'remotion'`.++## Options++Pass an object with the following properties.++### component++The JSX tag name. Use a component name such as `Solid`, a member expression such as `Interactive.Div`, or an HTML tag such as `div`.++### importPath?++The module to import `component` from, such as `remotion`, `@remotion/media`, or a relative path such as `./Title`. The first identifier of `component` is imported as a named export. Relative paths are resolved from the file that receives the element. Omit it for HTML tags and identifiers that are already in scope.++### props?++A record of prop values. Strings become string attributes, other values become JSX expressions. Values must be strings, finite numbers, booleans, `null`, arrays, or plain objects. Use [`staticFileValue()`](/docs/codemods/static-file-value) to reference a file in the public folder. Defaults to `{}`.++### children?++An array of children. Each child is a string, an element created with `createElement()`, or a plain element description with the same shape as these options. Text that JSX cannot hold verbatim, such as text containing braces, is wrapped in a string expression. Defaults to `[]`.++## Return value++A `CodemodElement`. It is immutable: the following methods return a new element and leave the original unchanged, so an element can be reused as a template.++### component, importPath, props, children++The values passed to `createElement()`, with `importPath` defaulting to `null`. `JSON.stringify()` serializes an element to a plain description that `createElement()` accepts again.++### withProp(name, value)++Returns a copy with the prop set to the value.++### withProps(props)++Returns a copy with the props merged into the existing props.++### withoutProp(name)++Returns a copy without the prop.++### withChild(child)++Returns a copy with the child appended after the existing children.++### withChildren(children)++Returns a copy whose children are replaced.++## Errors++Throws when the tag name, a prop name, or a prop value is invalid, or when `importPath` is set for a tag that does not start with an uppercase letter, `_`, or `$`.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/codemod-element.ts)+- [`addElement()`](/docs/codemods/add-element)+- [`wrapJsxNode()`](/docs/codemods/wrap-jsx-node)+- [`staticFileValue()`](/docs/codemods/static-file-value)diff --git a/packages/docs/docs/codemods/delete-jsx-nodes.mdx b/packages/docs/docs/codemods/delete-jsx-nodes.mdxindex e821fe1c8f..9116f35f2d 100644--- a/packages/docs/docs/codemods/delete-jsx-nodes.mdx+++ b/packages/docs/docs/codemods/delete-jsx-nodes.mdx@@ -70,5 +70,5 @@ File-qualified `{filePath, oldNodePath, newNodePath}` mappings for keeping node## See also- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/delete-jsx-nodes.ts)-- [`addSolid()`](/docs/codemods/add-solid)+- [`addElement()`](/docs/codemods/add-element)- [`<Sequence>`](/docs/sequence)diff --git a/packages/docs/docs/codemods/get-jsx-nodes.mdx b/packages/docs/docs/codemods/get-jsx-nodes.mdxindex 4399299111..f5c9908c5a 100644--- a/packages/docs/docs/codemods/get-jsx-nodes.mdx+++ b/packages/docs/docs/codemods/get-jsx-nodes.mdx@@ -63,6 +63,10 @@ The recognized component identity, or `null` when it cannot be determined. ImporThe opening tag's `{line, column}` location, or `null`. Lines are one-based; columns are zero-based.+### parentNodePath<AvailableFrom v="4.0.530" />++The `nodePath` of the closest enclosing JSX element in the same file, or `null` for top-level elements. Elements rendered through expressions, such as `{condition && <div />}` or a `.map()` callback, report the enclosing element. Compare it with the `nodePath` of other entries to build a tree or to find the children of a node.+## ErrorsThrows when the target cannot be resolved, the requested edit is unsupported, or an option is invalid. Failed edits leave the input project unchanged.diff --git a/packages/docs/docs/codemods/index.mdx b/packages/docs/docs/codemods/index.mdxindex 0aefe993cf..03575c8779 100644--- a/packages/docs/docs/codemods/index.mdx+++ b/packages/docs/docs/codemods/index.mdx@@ -51,6 +51,37 @@ export const Root = () => <Composition id="Demo" component={Video} width={1920}Include the files needed for the edit. A JSX prop edit needs its target file; resolving an imported composition component also needs the files along the import path. Mutations leave the input project unchanged.+## Creating elements<AvailableFrom v="4.0.530" />++Describe JSX with [`createElement()`](/docs/codemods/create-element) and insert it with [`addElement()`](/docs/codemods/add-element). Elements are immutable descriptions: methods such as `withProp()` and `withChild()` return new elements. Imports and local names are resolved when the element is inserted.++```ts twoslash title="insert.ts"+import {addElement, applyCodemodChanges, createElement, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const solid = createElement({+ component: 'Solid',+ importPath: 'remotion',+ props: {width: 1920, height: 1080, color: 'gray'},+});+const sequence = createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 30},+}).withChild(solid);++const result = addElement({+ project,+ element: sequence,+ target: {type: 'composition', compositionFile: 'src/Root.tsx', compositionId: 'Demo'},+});+const nextProject = applyCodemodChanges(project, result.changes);+console.log(nextProject.files, result.insertedNode);+```++Elements can also be inserted `inside`, `before`, or `after` an existing node, and [`wrapJsxNode()`](/docs/codemods/wrap-jsx-node) wraps an existing node in an element.+## Editing a node<AvailableFrom v="4.0.528" />Find a node, inspect the properties you want to edit, and pass its reference to a mutation.@@ -86,7 +117,7 @@ The file containing the JSX element.### nodePath-The `SequenceNodePath` identifying the element in the current source snapshot. Obtain it from [`getJsxNodes()`](/docs/codemods/get-jsx-nodes), an insertion result, or a mounted layer's `nodePathInfo.sequenceSubscriptionKey.nodePath`. Treat its contents as opaque.+The `SequenceNodePath` identifying the element in the current source snapshot. Obtain it from [`getJsxNodes()`](/docs/codemods/get-jsx-nodes), an insertion result, or a mounted layer's `nodePathInfo.sequenceSubscriptionKey.nodePath`. Treat its contents as opaque. To traverse the tree, compare it with the `parentNodePath` that [`getJsxNodes()`](/docs/codemods/get-jsx-nodes) returns for each node.A reference identifies source, not a particular rendered instance. Editing a component used by several compositions changes that shared component. Editing a node inside a loop changes the source used by every iteration.@@ -138,7 +169,7 @@ Code must be valid JavaScript or TypeScript with supported JSX structures. PropRegistration edits use explicit composition files and static IDs. They support `Composition`, `Still`, and `Folder` from `remotion`, including aliased and namespace imports. Component insertion and resolution support additional import patterns, as documented on their pages.-`CodemodValue` represents serializable strings, numbers, booleans, `null`, arrays, and objects. Strings are values, not executable expressions. [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props) also accepts `undefined` to remove a property.+`CodemodValue` represents serializable strings, numbers, booleans, `null`, arrays, and objects. Strings are values, not executable expressions; use [`staticFileValue()`](/docs/codemods/static-file-value) to reference a file in the public folder. [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props) also accepts `undefined` to remove a property.Unsupported edits throw or reject without mutating the input project. Batch operations resolve their references against the same input snapshot. Unrelated source formatting and comments are preserved; edited regions use the surrounding source style.diff --git a/packages/docs/docs/codemods/static-file-value.mdx b/packages/docs/docs/codemods/static-file-value.mdxnew file mode 100644index 0000000000..2cca396972--- /dev/null+++ b/packages/docs/docs/codemods/static-file-value.mdx@@ -0,0 +1,49 @@+---+image: /generated/articles-docs-codemods-static-file-value.png+title: 'staticFileValue()'+crumb: '@remotion/codemods'+---++# staticFileValue()<AvailableFrom v="4.0.530" />++Returns a `CodemodValue` that is written as a [`staticFile()`](/docs/staticfile) call when it is inserted into source code. The `staticFile` import is added if it is missing.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="static-file-value.ts"+import {createElement, staticFileValue} from '@remotion/codemods';++const image = createElement({+ component: 'Img',+ importPath: 'remotion',+ props: {src: staticFileValue('photo.png')},+});+```++Inserting `image` produces `<Img src={staticFile('photo.png')} />`.++The value is also accepted by [`updateJsxNodeProps()`](/docs/codemods/update-jsx-node-props) and [`setCompositionDefaultProps()`](/docs/codemods/set-composition-default-props), and it can be nested inside arrays and objects.++## Arguments++### path++The path of the file relative to the public folder, using forward slashes.++## Return value++A string. Treat it as opaque and pass it as a prop value.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/codemod-element.ts)+- [`createElement()`](/docs/codemods/create-element)+- [`staticFile()`](/docs/staticfile)diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsxindex 3923438fe3..7df474cd23 100644--- a/packages/docs/docs/codemods/table-of-contents.tsx+++ b/packages/docs/docs/codemods/table-of-contents.tsx@@ -11,13 +11,6 @@ export const TableOfContents: React.FC = () => {Creates and registers an interactive Canvas Capture component.</div></TOCItem>- <TOCItem link="/docs/codemods/add-component">- <strong>addComponent()</strong>- <div>- Adds an instance of a named component export to a composition,- including its import.- </div>- </TOCItem><TOCItem link="/docs/codemods/add-composition"><strong>addComposition()</strong><div>@@ -32,25 +25,28 @@ export const TableOfContents: React.FC = () => {import.</div></TOCItem>- <TOCItem link="/docs/codemods/add-folder">- <strong>addFolder()</strong>- <div>Adds an empty <Folder> to the registration tree.</div>- </TOCItem>- <TOCItem link="/docs/codemods/add-media">- <strong>addMedia()</strong>+ <TOCItem link="/docs/codemods/add-element">+ <strong>addElement()</strong><div>- Adds an image, video, audio, GIF, or animated image to a composition- component and adds the required imports.+ Inserts an element into a composition or relative to an existing node,+ including its imports.</div></TOCItem>- <TOCItem link="/docs/codemods/add-solid">- <strong>addSolid()</strong>- <div>Add a solid to a composition.</div>+ <TOCItem link="/docs/codemods/add-folder">+ <strong>addFolder()</strong>+ <div>Adds an empty <Folder> to the registration tree.</div></TOCItem><TOCItem link="/docs/codemods/apply-codemod-changes"><strong>applyCodemodChanges()</strong><div>Applies file changes to an in-memory project.</div></TOCItem>+ <TOCItem link="/docs/codemods/create-element">+ <strong>createElement()</strong>+ <div>+ Describes a JSX element with props and children to insert into source+ code.+ </div>+ </TOCItem><TOCItem link="/docs/codemods/delete-composition"><strong>deleteComposition()</strong><div>Removes a composition or still registration.</div>@@ -139,6 +135,10 @@ export const TableOfContents: React.FC = () => {Splits supported timing elements into two adjacent JSX elements.</div></TOCItem>+ <TOCItem link="/docs/codemods/static-file-value">+ <strong>staticFileValue()</strong>+ <div>Creates a prop value that is written as a staticFile() call.</div>+ </TOCItem><TOCItem link="/docs/codemods/unwrap-folder"><strong>unwrapFolder()</strong><div>@@ -185,6 +185,10 @@ export const TableOfContents: React.FC = () => {Updates visual control defaults while preserving surrounding source.</div></TOCItem>+ <TOCItem link="/docs/codemods/wrap-jsx-node">+ <strong>wrapJsxNode()</strong>+ <div>Wraps an existing JSX element in a new element.</div>+ </TOCItem></Grid>);};diff --git a/packages/docs/docs/codemods/update-jsx-node-props.mdx b/packages/docs/docs/codemods/update-jsx-node-props.mdxindex 6564cd3cda..a94e5034a4 100644--- a/packages/docs/docs/codemods/update-jsx-node-props.mdx+++ b/packages/docs/docs/codemods/update-jsx-node-props.mdx@@ -43,7 +43,7 @@ A [`JsxNodeReference`](/docs/codemods#node-references) from [`getJsxNodes()`](/d### props?-A non-empty record of new values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes the prop or nested property. Only one level of nested keys is supported. Use `children` to replace static text. Provide exactly one of `props` or `updates`.+A non-empty record of new values, such as `{from: 30, 'style.opacity': 0.5}`. A value of `undefined` removes the prop or nested property. Only one level of nested keys is supported. Use `children` to replace static text. Use [`staticFileValue()`](/docs/codemods/static-file-value) to write a [`staticFile()`](/docs/staticfile) call. Provide exactly one of `props` or `updates`.### updates?diff --git a/packages/docs/docs/codemods/wrap-jsx-node.mdx b/packages/docs/docs/codemods/wrap-jsx-node.mdxnew file mode 100644index 0000000000..625445599f--- /dev/null+++ b/packages/docs/docs/codemods/wrap-jsx-node.mdx@@ -0,0 +1,82 @@+---+image: /generated/articles-docs-codemods-wrap-jsx-node.png+title: 'wrapJsxNode()'+crumb: '@remotion/codemods'+---++# wrapJsxNode()<AvailableFrom v="4.0.530" />++Wraps an existing JSX element in an element created with [`createElement()`](/docs/codemods/create-element). The wrapped element becomes the only child of the wrapper, and the wrapper's imports are added.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="wrap-jsx-node.ts"+import {createElement, getJsxNodes, wrapJsxNode, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const node = getJsxNodes({project, filePath: 'src/Video.tsx'}).find((candidate) => candidate.tagName === 'div');++if (node) {+ const result = wrapJsxNode({+ project,+ node,+ wrapper: createElement({+ component: 'Sequence',+ importPath: 'remotion',+ props: {from: 30, durationInFrames: 60},+ }),+ });+ console.log(result.changes);+}+```++The wrapped element keeps its source formatting.++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### node++The reference of the JSX element to wrap. See [node references](/docs/codemods#node-references).++### wrapper++The wrapper element, created with [`createElement()`](/docs/codemods/create-element). It must not have children. Wrapping in [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) requires positive integer `width` and `height` props and is rejected inside or around another `<HtmlInCanvas>`.++## Return value++An object with the following properties.++### changes++An array of `{filePath, previousContents, nextContents}` file changes.++### nodePathRemappings++An array of `{filePath, oldNodePath, newNodePath}` mappings. The wrapped element and its descendants receive new paths, and the wrapper is listed with a `null` old path. See [node references](/docs/codemods#node-references).++### logLine++The one-based line of the wrapped element's opening tag in the input source.++## Errors++Throws when the node cannot be found, cannot be wrapped, or the wrapper is invalid. Failed edits leave the input project unchanged.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/wrap-jsx-node.ts)+- [`createElement()`](/docs/codemods/create-element)+- [`addElement()`](/docs/codemods/add-element)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 33ffa1ad23..e85b7377c4 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -2080,13 +2080,12 @@ const sidebars: SidebarsConfig = {},items: ['codemods/add-canvas-capture-composition',- 'codemods/add-component','codemods/add-composition','codemods/add-effect',+ 'codemods/add-element','codemods/add-folder',- 'codemods/add-media',- 'codemods/add-solid','codemods/apply-codemod-changes',+ 'codemods/create-element','codemods/delete-composition','codemods/delete-effects','codemods/delete-jsx-nodes',@@ -2105,6 +2104,7 @@ const sidebars: SidebarsConfig = {'codemods/resolve-composition-component','codemods/set-composition-default-props','codemods/split-sequences',+ 'codemods/static-file-value','codemods/unwrap-folder','codemods/update-composition-metadata','codemods/update-effect-keyframes',@@ -2113,6 +2113,7 @@ const sidebars: SidebarsConfig = {'codemods/update-jsx-node-props','codemods/update-multiple-jsx-node-props','codemods/update-visual-controls',+ 'codemods/wrap-jsx-node',],},],diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 7c24ccac31..816a29cebd 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1503,15 +1503,6 @@ export const articles = [noAi: false,slug: 'codemods/add-canvas-capture-composition',},- {- id: 'codemods/add-component',- title: 'addComponent()',- relativePath: 'docs/codemods/add-component.mdx',- compId: 'articles-docs-codemods-add-component',- crumb: '@remotion/codemods',- noAi: false,- slug: 'codemods/add-component',- },{id: 'codemods/add-composition',title: 'addComposition()',@@ -1530,6 +1521,15 @@ export const articles = [noAi: false,slug: 'codemods/add-effect',},+ {+ id: 'codemods/add-element',+ title: 'addElement()',+ relativePath: 'docs/codemods/add-element.mdx',+ compId: 'articles-docs-codemods-add-element',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/add-element',+ },{id: 'codemods/add-folder',title: 'addFolder()',@@ -1539,24 +1539,6 @@ export const articles = [noAi: false,slug: 'codemods/add-folder',},- {- id: 'codemods/add-media',- title: 'addMedia()',- relativePath: 'docs/codemods/add-media.mdx',- compId: 'articles-docs-codemods-add-media',- crumb: '@remotion/codemods',- noAi: false,- slug: 'codemods/add-media',- },- {- id: 'codemods/add-solid',- title: 'addSolid()',- relativePath: 'docs/codemods/add-solid.mdx',- compId: 'articles-docs-codemods-add-solid',- crumb: '@remotion/codemods',- noAi: false,- slug: 'codemods/add-solid',- },{id: 'codemods/apply-codemod-changes',title: 'applyCodemodChanges()',@@ -1566,6 +1548,15 @@ export const articles = [noAi: false,slug: 'codemods/apply-codemod-changes',},+ {+ id: 'codemods/create-element',+ title: 'createElement()',+ relativePath: 'docs/codemods/create-element.mdx',+ compId: 'articles-docs-codemods-create-element',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/create-element',+ },{id: 'codemods/delete-composition',title: 'deleteComposition()',@@ -1737,6 +1728,15 @@ export const articles = [noAi: false,slug: 'codemods/split-sequences',},+ {+ id: 'codemods/static-file-value',+ title: 'staticFileValue()',+ relativePath: 'docs/codemods/static-file-value.mdx',+ compId: 'articles-docs-codemods-static-file-value',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/static-file-value',+ },{id: 'codemods/unwrap-folder',title: 'unwrapFolder()',@@ -1809,6 +1809,15 @@ export const articles = [noAi: false,slug: 'codemods/update-visual-controls',},+ {+ id: 'codemods/wrap-jsx-node',+ title: 'wrapJsxNode()',+ relativePath: 'docs/codemods/wrap-jsx-node.mdx',+ compId: 'articles-docs-codemods-wrap-jsx-node',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/wrap-jsx-node',+ },{id: 'color-correction',title: 'Color correction',diff --git a/packages/docs/static/generated/articles-docs-codemods-add-component.png b/packages/docs/static/generated/articles-docs-codemods-add-component.pngdeleted file mode 100644index 7c78031fd9..0000000000Binary files a/packages/docs/static/generated/articles-docs-codemods-add-component.png and /dev/null differdiff --git a/packages/docs/static/generated/articles-docs-codemods-add-element.png b/packages/docs/static/generated/articles-docs-codemods-add-element.pngnew file mode 100644index 0000000000..60257fff46Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-add-element.png differdiff --git a/packages/docs/static/generated/articles-docs-codemods-add-media.png b/packages/docs/static/generated/articles-docs-codemods-add-media.pngdeleted file mode 100644index a7e1e8a529..0000000000Binary files a/packages/docs/static/generated/articles-docs-codemods-add-media.png and /dev/null differdiff --git a/packages/docs/static/generated/articles-docs-codemods-add-solid.png b/packages/docs/static/generated/articles-docs-codemods-add-solid.pngdeleted file mode 100644index 5a058f4466..0000000000Binary files a/packages/docs/static/generated/articles-docs-codemods-add-solid.png and /dev/null differdiff --git a/packages/docs/static/generated/articles-docs-codemods-create-element.png b/packages/docs/static/generated/articles-docs-codemods-create-element.pngnew file mode 100644index 0000000000..3fb8046be4Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-create-element.png differdiff --git a/packages/docs/static/generated/articles-docs-codemods-static-file-value.png b/packages/docs/static/generated/articles-docs-codemods-static-file-value.pngnew file mode 100644index 0000000000..9d2c5a96e1Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-static-file-value.png differdiff --git a/packages/docs/static/generated/articles-docs-codemods-wrap-jsx-node.png b/packages/docs/static/generated/articles-docs-codemods-wrap-jsx-node.pngnew file mode 100644index 0000000000..e29254f4dfBinary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-wrap-jsx-node.png differdiff --git a/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts b/packages/studio-server/src/preview-server/routes/wrap-jsx-node.tsindex bf00132acb..102b9203ce 100644--- a/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts@@ -1,5 +1,5 @@import {readFileSync} from 'node:fs';-import {canWrapJsxNode, wrapJsxNode} from '@remotion/codemods';+import {canWrapJsxNode, createElement, wrapJsxNode} from '@remotion/codemods';import {RenderInternals} from '@remotion/renderer';import type {WrapJsxNodeRequest,@@ -55,9 +55,14 @@ export const wrapJsxNodeHandler: ApiHandler<const result = wrapJsxNode({project: {files: {[absolutePath]: fileContents}, rootDir: remotionRoot},node: {filePath: absolutePath, nodePath},- wrapper,- width: width ?? 0,- height: height ?? 0,+ wrapper: createElement({+ component: wrapper,+ importPath: 'remotion',+ props:+ wrapper === 'HtmlInCanvas'+ ? {width: width ?? 0, height: height ?? 0}+ : {},+ }),});const change = result.changes.find(({filePath}) => filePath === absolutePath,diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.tsindex b6f4a78a7f..5b95f3f713 100644--- a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts@@ -6,11 +6,10 @@ import {type SequenceNodePathInfo,} from "@remotion/canvas";import {- addComponent,addComposition,- addMedia,- addSolid,+ addElement,applyCodemodChanges,+ createElement,deleteComposition,deleteJsxNodes,duplicateComposition,@@ -23,6 +22,7 @@ import {updateCompositionMetadata,updateJsxNodeProps,wrapJsxNode,+ type CodemodElement,type CodemodProject,type CodemodResult,type CodemodValue,@@ -165,6 +165,34 @@ export const useEditorActions = ({const currentFrame = () => playback.getSnapshot().frame;+ // Adds an element to the active composition, starting at the playhead.+ // Element creation validates its input, so it happens inside the guard.+ const addElementAtPlayhead = (getElement: () => CodemodElement) => {+ try {+ const { activeComposition, compositionFile } = requireComposition();+ const sequence = createElement({+ component: "Sequence",+ importPath: "remotion",+ props: { from: currentFrame() },+ children: [getElement()],+ });+ return applyCodemod((project) =>+ addElement({+ project,+ element: sequence,+ target: {+ type: "composition",+ compositionFile,+ compositionId: activeComposition.id,+ },+ }),+ );+ } catch (error) {+ notifyError(error);+ return Promise.resolve(false);+ }+ };+const setZoom = (zoom: PreviewZoom) => {dispatch({ type: "set-playback", patch: { zoom } });};@@ -338,9 +366,10 @@ export const ${componentName}: React.FC = () => {wrapJsxNode({project,node,- wrapper,- width: ref.current.compositionWidth,- height: ref.current.compositionHeight,+ wrapper: createElement({+ component: wrapper,+ importPath: "remotion",+ }),}),{ clearSelection: true },),@@ -486,61 +515,37 @@ export const ${componentName}: React.FC = () => {],}),),- addSolid: () => {- try {- const { activeComposition, compositionFile } = requireComposition();- return applyCodemod((project) =>- addSolid({- project,- compositionFile,- compositionId: activeComposition.id,+ addSolid: () =>+ addElementAtPlayhead(() =>+ createElement({+ component: "Solid",+ importPath: "remotion",+ props: {width: ref.current.compositionWidth,height: ref.current.compositionHeight,- from: currentFrame(),- }),- );- } catch (error) {- notifyError(error);- return Promise.resolve(false);- }- },- addMedia: (type: "image" | "video" | "audio", src: string) => {- try {- const { activeComposition, compositionFile } = requireComposition();- return applyCodemod((project) =>- addMedia({- project,- compositionFile,- compositionId: activeComposition.id,- type,- src,- srcType: "remote",- from: currentFrame(),- }),- );- } catch (error) {- notifyError(error);- return Promise.resolve(false);- }- },- addComponent: (importName: string, importPath: string) => {- try {- const { activeComposition, compositionFile } = requireComposition();- return applyCodemod((project) =>- addComponent({- project,- compositionFile,- compositionId: activeComposition.id,- importName,- importPath,- from: currentFrame(),- }),- );- } catch (error) {- notifyError(error);- return Promise.resolve(false);- }- },+ color: "gray",+ style: { position: "absolute" },+ },+ }),+ ),+ addMedia: (type: "image" | "video" | "audio", src: string) =>+ addElementAtPlayhead(() =>+ type === "image"+ ? createElement({+ component: "CanvasImage",+ importPath: "remotion",+ props: { src },+ })+ : createElement({+ component: type === "video" ? "Video" : "Audio",+ importPath: "@remotion/media",+ props: { src },+ }),+ ),+ addComponent: (importName: string, importPath: string) =>+ addElementAtPlayhead(() =>+ createElement({ component: importName, importPath }),+ ),resolveCompositionSource: () => {try {const { activeComposition, compositionFile } = requireComposition();