Skip to content

🎥 Make videos programmatically with React

Route Studio solid, asset and component insertions through `addElement()`

JonnyBurger88d2355a1e2d
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 32700c07a0..f24f195c41 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -4,6 +4,7 @@ import {
addComposition,
addCanvasCaptureComposition,
addEffect as addEffectCodemod,
+ addElement,
addFolder,
createElement,
deleteComposition,
@@ -31,10 +32,12 @@ import {
updateEffectProps as updateEffectPropsCodemod,
updateJsxNodeKeyframes,
updateJsxNodeProps,
+ type CodemodFileChange,
type CodemodNodeResult,
type CodemodResult,
type CompositionDestination,
type EffectKeyframeUpdate,
+ type InsertableSequenceWrapper,
type SequenceKeyframeUpdate,
} from '@remotion/codemods';
import {
@@ -53,7 +56,9 @@ import {
type ElementInstallExpectedFileState,
type EventSourceEvent,
type InsertElementResponse,
+ type InsertJsxElementRequest,
type RecastCodemod,
+ type SequenceNodePathRemapping,
type SubscribeToSequencePropsRequest,
type SubscribeToSequencePropsResponse,
type SymbolicatedStackFrame,
@@ -84,6 +89,7 @@ import type {VirtualProject, VirtualProjectPublicFile} from './types';
const {
basicCaptionsElementSource,
computeSequencePropsSubscriptionFromContent,
+ createElementFromInsertable,
findProjectFile,
getBasicCaptionsElementFile,
getCanUpdateDefaultPropsForProject,
@@ -108,6 +114,68 @@ const svgMarkupToJsx = (): Promise<never> =>
new Error('Importing SVG markup is not supported in Browser Studio'),
);
+const insertIntoProject = async ({
+ project,
+ request,
+ wrapInSequence,
+}: {
+ project: VirtualProject;
+ request: InsertJsxElementRequest;
+ wrapInSequence: InsertableSequenceWrapper | null;
+}): Promise<{
+ changes: CodemodFileChange[];
+ filePath: string;
+ insertedNodePath: SequenceNodePath | null;
+ nodePathRemappings: SequenceNodePathRemapping[];
+}> => {
+ // SVG markup and compositions need the dedicated insertion pipeline.
+ if (
+ request.element.type === 'svg' ||
+ request.element.type === 'composition'
+ ) {
+ const inserted = await insertJsxElementIntoProjectWithNodePathRemappings({
+ project,
+ request,
+ svgMarkupToJsx,
+ wrapInSequence,
+ });
+ return {
+ changes: [
+ {
+ filePath: inserted.filePath,
+ previousContents: project.files[inserted.filePath] ?? null,
+ nextContents: inserted.output,
+ },
+ ],
+ filePath: inserted.filePath,
+ insertedNodePath: inserted.insertedNodePath,
+ nodePathRemappings: inserted.nodePathRemappings,
+ };
+ }
+
+ const result = addElement({
+ project,
+ element: createElementFromInsertable({
+ element: request.element,
+ from: request.from,
+ wrapInSequence,
+ }),
+ target: {
+ type: 'composition',
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ },
+ });
+ return {
+ changes: result.changes,
+ filePath: result.insertedNode.filePath,
+ insertedNodePath: result.insertedNode.nodePath,
+ nodePathRemappings: result.nodePathRemappings.map(
+ ({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),
+ ),
+ };
+};
+
const formatCodemodFile = async ({contents}: {contents: string}) => ({
formatted: true,
output: await format(contents, {
@@ -2133,19 +2201,12 @@ export const createBrowserStudioOperations = ({
dependencies: installedDependencies,
project: getProject(),
});
- const result = await insertJsxElementIntoProjectWithNodePathRemappings({
+ const result = await insertIntoProject({
project,
request,
- svgMarkupToJsx,
wrapInSequence: null,
});
- const changes = [
- {
- filePath: result.filePath,
- previousContents: project.files[result.filePath] ?? null,
- nextContents: result.output,
- },
- ];
+ const {changes} = result;
const nodePathMutation = controller.applyMutation({
undoRedoNavigation: null,
timelineSelection:
@@ -2413,54 +2474,48 @@ export const createBrowserStudioOperations = ({
request.element.dependencies,
);
const durationInFrames = request.element.durationInFrames ?? null;
- const insertion =
- await insertJsxElementIntoProjectWithNodePathRemappings({
- project,
- request: {
- compositionFile: request.compositionFile,
- compositionId: request.compositionId,
- element: {
- componentName: plan.componentName,
- importName: plan.componentName,
- importPath: plan.importPath,
- position: componentOwnsSequence ? request.position : null,
- props: [
- ...Object.entries(request.element.initialProps ?? {}).map(
- ([name, value]) => ({name, value}),
- ),
- ...(componentOwnsSequence && durationInFrames !== null
- ? [
- {
- name: 'durationInFrames',
- value: durationInFrames,
- },
- ]
- : []),
- ...(componentOwnsSequence
- ? [{name: 'name', value: request.element.displayName}]
- : []),
- ],
- type: 'component',
- },
- from: componentOwnsSequence ? request.from : null,
+ const insertion = await insertIntoProject({
+ project,
+ request: {
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ element: {
+ componentName: plan.componentName,
+ importName: plan.componentName,
+ importPath: plan.importPath,
+ position: componentOwnsSequence ? request.position : null,
+ props: [
+ ...Object.entries(request.element.initialProps ?? {}).map(
+ ([name, value]) => ({name, value}),
+ ),
+ ...(componentOwnsSequence && durationInFrames !== null
+ ? [
+ {
+ name: 'durationInFrames',
+ value: durationInFrames,
+ },
+ ]
+ : []),
+ ...(componentOwnsSequence
+ ? [{name: 'name', value: request.element.displayName}]
+ : []),
+ ],
+ type: 'component',
},
- svgMarkupToJsx,
- wrapInSequence: componentOwnsSequence
- ? null
- : {
- dimensions: request.element.dimensions,
- durationInFrames,
- from: request.from,
- name: request.element.displayName,
- position: request.position,
- },
- });
- const projectWithElement = applyCodemodChanges(project, [
- {
- filePath: insertion.filePath,
- previousContents: project.files[insertion.filePath] ?? null,
- nextContents: insertion.output,
+ from: componentOwnsSequence ? request.from : null,
},
+ wrapInSequence: componentOwnsSequence
+ ? null
+ : {
+ dimensions: request.element.dimensions,
+ durationInFrames,
+ from: request.from,
+ name: request.element.displayName,
+ position: request.position,
+ },
+ });
+ const projectWithElement = applyCodemodChanges(project, [
+ ...insertion.changes,
{
filePath: plan.elementFilePath,
previousContents: project.files[plan.elementFilePath] ?? null,
diff --git a/packages/codemods/src/add-element.ts b/packages/codemods/src/add-element.ts
index 32122c0be0..d91909bc7d 100644
--- a/packages/codemods/src/add-element.ts
+++ b/packages/codemods/src/add-element.ts
@@ -45,6 +45,7 @@ import {stripParenthesizedExtra} from './strip-parenthesized-extra';
export type AddElementTarget =
| ({type: 'composition'} & CompositionTarget)
+ | {type: 'component'; filePath: string; exportName: string | 'default'}
| {type: 'inside'; node: JsxNodeReference}
| {type: 'before'; node: JsxNodeReference}
| {type: 'after'; node: JsxNodeReference};
@@ -53,6 +54,7 @@ export type AddElementOptions<Project extends CodemodProject> = {
project: Project;
element: CodemodElement;
target: AddElementTarget;
+ prettierConfigOverride?: Record<string, unknown> | null;
};
const b = recast.types.builders;
@@ -62,6 +64,7 @@ type SourceEditInput = {
input: string;
insertion: string;
jsx: namedTypes.JSXElement;
+ prettierConfigOverride: Record<string, unknown> | null;
};
const getCompositionRootSourceEdit = ({
@@ -70,6 +73,7 @@ const getCompositionRootSourceEdit = ({
input,
insertion,
jsx,
+ prettierConfigOverride,
}: SourceEditInput & {exportName: string | 'default'}): SourceEdit => {
const declaration = getDeclarationByExportName({ast, exportName});
const root = declaration ? getComponentRootNode(declaration) : null;
@@ -80,7 +84,7 @@ const getCompositionRootSourceEdit = ({
input,
insertion,
nullRoot,
- prettierConfigOverride: null,
+ prettierConfigOverride,
root,
});
};
@@ -90,9 +94,10 @@ const getNodeTargetSourceEdit = ({
input,
insertion,
jsx,
+ prettierConfigOverride,
target,
}: SourceEditInput & {
- target: Exclude<AddElementTarget, {type: 'composition'}>;
+ target: Extract<AddElementTarget, {node: JsxNodeReference}>;
}): SourceEdit => {
const targetPath = findJsxElementPathForDeletion(ast, target.node.nodePath);
if (!targetPath) {
@@ -106,7 +111,7 @@ const getNodeTargetSourceEdit = ({
input,
insertion,
nullRoot: null,
- prettierConfigOverride: null,
+ prettierConfigOverride,
root: targetElement as never,
});
targetElement.children.push(jsx as never);
@@ -159,7 +164,7 @@ const getNodeTargetSourceEdit = ({
target.type === 'after' ? [existing, jsx] : [jsx, existing],
),
);
- const unit = getIndentationUnit(input, null);
+ const unit = getIndentationUnit(input, prettierConfigOverride);
const children =
target.type === 'after' ? [original, insertion] : [insertion, original];
return {
@@ -183,11 +188,13 @@ const insertElementIntoFile = ({
element,
filePath,
getSourceEdit,
+ prettierConfigOverride,
project,
}: {
element: CodemodElement;
filePath: string;
getSourceEdit: (context: SourceEditInput) => SourceEdit;
+ prettierConfigOverride: Record<string, unknown> | null;
project: CodemodProject;
}): CodemodInsertionResult => {
const input = project.files[filePath];
@@ -196,18 +203,25 @@ const insertElementIntoFile = ({
const importSnapshots = captureImportSnapshots(ast);
const jsx = buildJsxElement({ast, element});
const insertion = printInsertedJsx({
+ compactLiteralProps: true,
element: jsx,
input,
- prettierConfigOverride: null,
+ prettierConfigOverride,
+ });
+ const edit = getSourceEdit({
+ ast,
+ input,
+ insertion,
+ jsx,
+ prettierConfigOverride,
});
- const edit = getSourceEdit({ast, input, insertion, jsx});
const output = applySourceEdits({
input,
edits: [
...getInsertImportSourceEdits({
ast,
input,
- prettierConfigOverride: null,
+ prettierConfigOverride,
snapshots: importSnapshots,
}),
edit,
@@ -236,6 +250,7 @@ export const addElement = <Project extends CodemodProject>({
project,
element,
target,
+ prettierConfigOverride = null,
}: AddElementOptions<Project>): CodemodInsertionResult => {
if (!(element instanceof CodemodElement)) {
throw new Error('element must be created with createElement()');
@@ -261,6 +276,21 @@ export const addElement = <Project extends CodemodProject>({
...context,
exportName: resolved.exportName,
}),
+ prettierConfigOverride,
+ project,
+ });
+ }
+
+ if (target.type === 'component') {
+ return insertElementIntoFile({
+ element,
+ filePath: findProjectFile({project, filePath: target.filePath}),
+ getSourceEdit: (context) =>
+ getCompositionRootSourceEdit({
+ ...context,
+ exportName: target.exportName,
+ }),
+ prettierConfigOverride,
project,
});
}
@@ -269,6 +299,7 @@ export const addElement = <Project extends CodemodProject>({
element,
filePath: findProjectFile({project, filePath: target.node.filePath}),
getSourceEdit: (context) => getNodeTargetSourceEdit({...context, target}),
+ prettierConfigOverride,
project,
});
};
diff --git a/packages/codemods/src/build-jsx-element.ts b/packages/codemods/src/build-jsx-element.ts
index 6696f1ea0b..b829993e25 100644
--- a/packages/codemods/src/build-jsx-element.ts
+++ b/packages/codemods/src/build-jsx-element.ts
@@ -69,12 +69,13 @@ export const buildJsxElement = ({
}): namedTypes.JSXElement => {
let localName = element.component;
if (element.importPath !== null) {
- const [importedName, ...members] = element.component.split('.');
+ const [preferredLocalName, ...members] = element.component.split('.');
localName = [
ensureOfficialNamedImport({
ast,
- importedName,
+ importedName: element.importName ?? preferredLocalName,
sourcePath: element.importPath,
+ preferredLocalName,
}),
...members,
].join('.');
diff --git a/packages/codemods/src/codemod-element.ts b/packages/codemods/src/codemod-element.ts
index ded3e4d7ad..7ec4af59a6 100644
--- a/packages/codemods/src/codemod-element.ts
+++ b/packages/codemods/src/codemod-element.ts
@@ -6,12 +6,13 @@ export type CodemodElementChild = CodemodElement | string;
export type CodemodElementOptions = {
component: string;
importPath?: string | null;
+ importName?: 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 importedComponentRegex = /^[A-Z_$][\w$]*$/;
const propNameRegex = /^[A-Za-z_$][\w$-]*(:[A-Za-z_$][\w$-]*)?$/;
const isCodemodValue = (value: unknown): value is CodemodValue => {
@@ -45,12 +46,14 @@ const isCodemodValue = (value: unknown): value is CodemodValue => {
export class CodemodElement {
readonly component: string;
readonly importPath: string | null;
+ readonly importName: string | null;
readonly props: Readonly<Record<string, CodemodValue>>;
readonly children: readonly CodemodElementChild[];
constructor({
component,
importPath = null,
+ importName = null,
props = {},
children = [],
}: CodemodElementOptions) {
@@ -65,13 +68,28 @@ export class CodemodElement {
throw new Error('importPath must be a non-empty module specifier');
}
- if (!importedComponentRegex.test(component)) {
+ if (!importedComponentRegex.test(component.split('.')[0])) {
throw new Error(
`Imported components must start with an uppercase letter, _ or $. Omit importPath to use the HTML tag "${component}"`,
);
}
}
+ if (importName !== null) {
+ if (importPath === null) {
+ throw new Error('importName requires an importPath');
+ }
+
+ if (
+ typeof importName !== 'string' ||
+ !importedComponentRegex.test(importName)
+ ) {
+ throw new Error(
+ `${JSON.stringify(importName)} is not a valid named export to import`,
+ );
+ }
+ }
+
for (const [name, value] of Object.entries(props)) {
if (!propNameRegex.test(name)) {
throw new Error(`"${name}" is not a valid JSX prop name`);
@@ -86,6 +104,7 @@ export class CodemodElement {
this.component = component;
this.importPath = importPath;
+ this.importName = importName;
this.props = {...props};
this.children = children.map((child) => {
if (typeof child === 'string' || child instanceof CodemodElement) {
@@ -112,6 +131,7 @@ export class CodemodElement {
return new CodemodElement({
component: this.component,
importPath: this.importPath,
+ importName: this.importName,
props: {...this.props, ...props},
children: this.children,
});
@@ -122,6 +142,7 @@ export class CodemodElement {
return new CodemodElement({
component: this.component,
importPath: this.importPath,
+ importName: this.importName,
props: Object.fromEntries(
Object.entries(this.props).filter(([key]) => key !== name),
),
@@ -141,6 +162,7 @@ export class CodemodElement {
return new CodemodElement({
component: this.component,
importPath: this.importPath,
+ importName: this.importName,
props: this.props,
children,
});
diff --git a/packages/codemods/src/duplicate-composition-in-source.ts b/packages/codemods/src/duplicate-composition-in-source.ts
index a6d5b8a13d..dc156cc534 100644
--- a/packages/codemods/src/duplicate-composition-in-source.ts
+++ b/packages/codemods/src/duplicate-composition-in-source.ts
@@ -180,6 +180,7 @@ export const duplicateCompositionInSource = ({
metadata,
});
const insertion = printInsertedJsx({
+ compactLiteralProps: false,
element: duplicate as never,
input,
prettierConfigOverride: null,
diff --git a/packages/codemods/src/effect-operations.ts b/packages/codemods/src/effect-operations.ts
index d824e8c957..b988309073 100644
--- a/packages/codemods/src/effect-operations.ts
+++ b/packages/codemods/src/effect-operations.ts
@@ -243,6 +243,7 @@ const getEffectSourceOutput = ({
indent: getJsxSourceIndent(start),
input,
printed: printJsxOpeningElement({
+ compactLiteralProps: false,
openingElement: openingElement as never,
input,
originalAttributeSources: snapshots.originalAttributeSources,
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index 6174611d43..92c11dff00 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -11,6 +11,7 @@ import {
resolveCompositionComponent,
resolveCompositionComponentWithFile,
} from './insert-jsx-element';
+import {createElementFromInsertable} from './insertable-element';
import {
computeCanUpdateDefaultPropsFromContent,
findProjectFile,
@@ -161,9 +162,11 @@ export type {
} from './update-keyframes';
export type {
InsertJsxElementCodemodEnvironment,
+ PipelineInsertableElement,
ResolvedCompositionComponent,
ResolvedCompositionComponentWithFile,
} from './insert-jsx-element';
+export type {InsertableSequenceWrapper} from './insertable-element';
export type {
RemovedProp,
SequencePropUpdate,
@@ -177,6 +180,7 @@ export const CodemodsInternals = {
basicCaptionsElementSource,
computeCanUpdateDefaultPropsFromContent,
computeSequencePropsSubscriptionFromContent,
+ createElementFromInsertable,
enumerateEffectArrayElements,
findProjectFile,
findSearchPosition,
diff --git a/packages/codemods/src/insert-jsx-element.ts b/packages/codemods/src/insert-jsx-element.ts
index 25dcabcf25..10d8335949 100644
--- a/packages/codemods/src/insert-jsx-element.ts
+++ b/packages/codemods/src/insert-jsx-element.ts
@@ -15,16 +15,13 @@ import type {
ObjectProperty,
VariableDeclaration,
} from '@babel/types';
-import {StudioProtocolInternals} from '@remotion/studio-protocol';
-import {
- isUrl,
- type InsertJsxElementRequest,
- type InsertableCompositionElement,
- type InsertableCompositionElementPosition,
- type SequenceNodePathRemapping,
+import type {
+ InsertJsxElementRequest,
+ InsertableCompositionElement,
+ InsertableCompositionElementPosition,
+ SequenceNodePathRemapping,
} from '@remotion/studio-shared';
import type {namedTypes} from 'ast-types';
-import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
import * as recast from 'recast';
import type {SequenceNodePath} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
@@ -50,11 +47,6 @@ import {getEndOfLine, getIndentationUnit, getLineIndent} from './source-style';
import {stripParenthesizedExtra} from './strip-parenthesized-extra';
import {parseValueExpression} from './update-nested-prop';
-type ComponentProp = Extract<
- InsertableCompositionElement,
- {type: 'component'}
->['props'][number];
-
export type InsertJsxElementCodemodEnvironment = {
rootDir: string;
dirname: (fileName: string) => string;
@@ -919,7 +911,10 @@ const roundTranslateCoordinate = (value: number): number => {
return Object.is(rounded, -0) ? 0 : rounded;
};
-const formatTranslateValue = ({x, y}: InsertableCompositionElementPosition) =>
+export const formatTranslateValue = ({
+ x,
+ y,
+}: InsertableCompositionElementPosition) =>
`${roundTranslateCoordinate(x)}px ${roundTranslateCoordinate(y)}px`;
const createStyleAttribute = (
@@ -961,204 +956,6 @@ const createPositionAbsoluteStyleAttribute = (
return createStyleAttribute(getPositionStyleProperties(position));
};
-const createAssetStyleAttribute = ({
- dimensions,
- position,
-}: {
- dimensions: {width: number; height: number} | null;
- position: InsertableCompositionElementPosition | null;
-}): namedTypes.JSXAttribute => {
- return createStyleAttribute([
- ...getPositionStyleProperties(position),
- ...(dimensions
- ? [
- recast.types.builders.objectProperty(
- recast.types.builders.identifier('width'),
- recast.types.builders.numericLiteral(dimensions.width),
- ),
- recast.types.builders.objectProperty(
- recast.types.builders.identifier('height'),
- recast.types.builders.numericLiteral(dimensions.height),
- ),
- ]
- : []),
- ]);
-};
-
-const createStaticFileSrcAttribute = ({
- staticFileLocalName,
- src,
-}: {
- staticFileLocalName: string;
- src: string;
-}): namedTypes.JSXAttribute => {
- return recast.types.builders.jsxAttribute(
- recast.types.builders.jsxIdentifier('src'),
- recast.types.builders.jsxExpressionContainer(
- recast.types.builders.callExpression(
- recast.types.builders.identifier(staticFileLocalName),
- [recast.types.builders.stringLiteral(src)],
- ),
- ),
- );
-};
-
-const createComponentPropValue = (
- value: unknown,
- getStaticFileLocalName: () => string,
-): ExpressionKind => {
- const b = recast.types.builders;
- if (StudioProtocolInternals.isStaticFileRef(value)) {
- return b.callExpression(b.identifier(getStaticFileLocalName()), [
- b.stringLiteral(value.__remotion_element_asset),
- ]);
- }
-
- if (Array.isArray(value)) {
- return b.arrayExpression(
- value.map((item) =>
- createComponentPropValue(item, getStaticFileLocalName),
- ),
- );
- }
-
- if (value !== null && typeof value === 'object') {
- return b.objectExpression(
- Object.entries(value).map(([key, item]) => {
- const property = b.objectProperty(
- b.stringLiteral(key),
- createComponentPropValue(item, getStaticFileLocalName),
- );
- property.computed = key === '__proto__';
- return property;
- }),
- );
- }
-
- return parseValueExpression(value);
-};
-
-const createComponentProp = ({
- name,
- value,
- getStaticFileLocalName,
-}: ComponentProp & {
- getStaticFileLocalName: () => string;
-}): namedTypes.JSXAttribute => {
- if (typeof value === 'string') {
- return createStringAttribute(name, value);
- }
-
- return recast.types.builders.jsxAttribute(
- recast.types.builders.jsxIdentifier(name),
- recast.types.builders.jsxExpressionContainer(
- createComponentPropValue(value, getStaticFileLocalName) as never,
- ),
- ) as unknown as namedTypes.JSXAttribute;
-};
-
-const createStringSrcAttribute = (src: string): namedTypes.JSXAttribute => {
- return recast.types.builders.jsxAttribute(
- recast.types.builders.jsxIdentifier('src'),
- recast.types.builders.stringLiteral(src),
- );
-};
-
-const createSolidElement = ({
- localName,
- width,
- height,
- position,
-}: {
- localName: string;
- width: number;
- height: number;
- position: InsertableCompositionElementPosition | null;
-}): namedTypes.JSXElement => {
- return recast.types.builders.jsxElement(
- recast.types.builders.jsxOpeningElement(
- recast.types.builders.jsxIdentifier(localName),
- [
- createNumberAttribute('width', width),
- createNumberAttribute('height', height),
- createStringAttribute('color', 'gray'),
- createPositionAbsoluteStyleAttribute(position),
- ],
- true,
- ),
- null,
- [],
- );
-};
-
-const createComponentElement = ({
- getStaticFileLocalName,
- addPositionStyle,
- from,
- localName,
- props,
- position,
-}: {
- getStaticFileLocalName: () => string;
- addPositionStyle: boolean;
- from: number | null;
- localName: string;
- props: ComponentProp[];
- position: InsertableCompositionElementPosition | null;
-}): namedTypes.JSXElement => {
- const styleProp = props.find((prop) => prop.name === 'style');
- const propsWithoutStyle = addPositionStyle
- ? props.filter((prop) => prop.name !== 'style')
- : props;
- let styleAttribute: namedTypes.JSXAttribute | null = null;
- if (addPositionStyle) {
- const styleExpression =
- styleProp === undefined
- ? recast.types.builders.objectExpression([])
- : createComponentPropValue(styleProp.value, getStaticFileLocalName);
- if (styleExpression.type !== 'ObjectExpression') {
- throw new Error('Component style must be an object to add a position');
- }
-
- styleExpression.properties = styleExpression.properties.filter(
- (property) => {
- if (property.type !== 'ObjectProperty') {
- return true;
- }
-
- const key =
- property.key.type === 'Identifier'
- ? property.key.name
- : property.key.type === 'StringLiteral'
- ? property.key.value
- : null;
- return key !== 'position' && (position === null || key !== 'translate');
- },
- );
- styleExpression.properties.push(...getPositionStyleProperties(position));
- styleAttribute = recast.types.builders.jsxAttribute(
- recast.types.builders.jsxIdentifier('style'),
- recast.types.builders.jsxExpressionContainer(styleExpression as never),
- ) as unknown as namedTypes.JSXAttribute;
- }
-
- return recast.types.builders.jsxElement(
- recast.types.builders.jsxOpeningElement(
- recast.types.builders.jsxIdentifier(localName),
- [
- ...propsWithoutStyle.map((prop) =>
- createComponentProp({...prop, getStaticFileLocalName}),
- ),
- ...(from === null ? [] : [createNumberAttribute('from', from)]),
- ...(styleAttribute === null ? [] : [styleAttribute]),
- ],
- true,
- ),
- null,
- [],
- );
-};
-
const createSequenceWrappedElement = ({
child,
dimensions,
@@ -1202,47 +999,6 @@ const createSequenceWrappedElement = ({
);
};
-const createAssetElement = ({
- addPositionStyle,
- durationInFrames,
- from,
- localName,
- staticFileLocalName,
- src,
- dimensions,
- position,
-}: {
- addPositionStyle: boolean;
- durationInFrames: number | null;
- from: number | null;
- localName: string;
- staticFileLocalName: string | null;
- src: string;
- dimensions: {width: number; height: number} | null;
- position: InsertableCompositionElementPosition | null;
-}): namedTypes.JSXElement => {
- return recast.types.builders.jsxElement(
- recast.types.builders.jsxOpeningElement(
- recast.types.builders.jsxIdentifier(localName),
- [
- staticFileLocalName === null
- ? createStringSrcAttribute(src)
- : createStaticFileSrcAttribute({staticFileLocalName, src}),
- ...(durationInFrames === null
- ? []
- : [createNumberAttribute('durationInFrames', durationInFrames)]),
- ...(from === null ? [] : [createNumberAttribute('from', from)]),
- ...(addPositionStyle
- ? [createAssetStyleAttribute({dimensions, position})]
- : []),
- ],
- true,
- ),
- null,
- [],
- );
-};
-
const createSvgElement = async ({
environment,
from,
@@ -1430,28 +1186,6 @@ const hasTopLevelBinding = ({ast, name}: {ast: File; name: string}) => {
});
};
-const getAvailableSolidLocalName = (ast: File) => {
- const candidates = ['Solid', 'RemotionSolid'];
- const available = candidates.find((candidate) => {
- return !hasTopLevelBinding({ast, name: candidate});
- });
-
- if (!available) {
- throw new Error('Cannot add <Solid> because Solid is already defined');
- }
-
- return available;
-};
-
-const ensureSolidImport = (ast: File) => {
- return ensureNamedImport({
- ast,
- importedName: 'Solid',
- sourcePath: 'remotion',
- localName: getAvailableSolidLocalName(ast),
- });
-};
-
const getAvailableSequenceLocalName = (ast: File) => {
const candidates = ['Sequence', 'RemotionSequence'];
const available = candidates.find((candidate) => {
@@ -1529,14 +1263,18 @@ const getImportDeclarations = ({
);
};
+// Reuses an existing import of the export, otherwise imports it under the
+// preferred local name, adding a numeric suffix when that name is taken.
export const ensureOfficialNamedImport = ({
ast,
importedName,
sourcePath,
+ preferredLocalName,
}: {
ast: File;
importedName: string;
sourcePath: string;
+ preferredLocalName: string;
}) => {
for (const declaration of getImportDeclarations({ast, sourcePath})) {
if (declaration.importKind === 'type') {
@@ -1554,10 +1292,10 @@ export const ensureOfficialNamedImport = ({
}
}
- let localName = importedName;
+ let localName = preferredLocalName;
let suffix = 2;
while (hasTopLevelBinding({ast, name: localName})) {
- localName = `${importedName}${suffix++}`;
+ localName = `${preferredLocalName}${suffix++}`;
}
return ensureNamedImport({ast, importedName, sourcePath, localName});
@@ -1568,112 +1306,7 @@ const ensureStaticFileImport = (ast: File) => {
ast,
importedName: 'staticFile',
sourcePath: 'remotion',
- });
-};
-
-const ensureCanvasImageImport = (ast: File) => {
- return ensureOfficialNamedImport({
- ast,
- importedName: 'CanvasImage',
- sourcePath: 'remotion',
- });
-};
-
-const ensureAnimatedImageImport = (ast: File) => {
- return ensureOfficialNamedImport({
- ast,
- importedName: 'AnimatedImage',
- sourcePath: 'remotion',
- });
-};
-
-const ensureVideoImport = (ast: File) => {
- return ensureOfficialNamedImport({
- ast,
- importedName: 'Video',
- sourcePath: '@remotion/media',
- });
-};
-
-const ensureAudioImport = (ast: File) => {
- return ensureOfficialNamedImport({
- ast,
- importedName: 'Audio',
- sourcePath: '@remotion/media',
- });
-};
-
-const ensureGifImport = (ast: File) => {
- return ensureOfficialNamedImport({
- ast,
- importedName: 'Gif',
- sourcePath: '@remotion/gif',
- });
-};
-
-const hasComponentLocalImport = ({
- ast,
- importName,
- importPath,
-}: {
- ast: File;
- importName: string;
- importPath: string;
-}) => {
- for (const importDeclaration of getImportDeclarations({
- ast,
- sourcePath: importPath,
- })) {
- if (importDeclaration.importKind === 'type') {
- continue;
- }
-
- for (const specifier of importDeclaration.specifiers ?? []) {
- if (
- specifier.type === 'ImportSpecifier' &&
- specifier.importKind !== 'type' &&
- getImportedName(specifier) === importName
- ) {
- return specifier.local?.name ?? importName;
- }
- }
- }
-
- return null;
-};
-
-const ensureComponentImport = ({
- ast,
- componentName,
- importName,
- importPath,
-}: {
- ast: File;
- componentName: string;
- importName: string;
- importPath: string;
-}) => {
- const existingLocalName = hasComponentLocalImport({
- ast,
- importName,
- importPath,
- });
-
- if (existingLocalName) {
- return existingLocalName;
- }
-
- let localName = componentName;
- let suffix = 2;
- while (hasTopLevelBinding({ast, name: localName})) {
- localName = `${componentName}${suffix++}`;
- }
-
- return ensureNamedImport({
- ast,
- importedName: importName,
- sourcePath: importPath,
- localName,
+ preferredLocalName: 'staticFile',
});
};
@@ -2098,137 +1731,6 @@ const indentExistingJsx = ({
.join(getEndOfLine(original));
};
-const getJsxIdentifierName = (element: namedTypes.JSXElement) => {
- const {name} = element.openingElement;
- if (name.type !== 'JSXIdentifier') {
- throw new Error('Expected the inserted Solid to have an identifier name');
- }
-
- return name.name;
-};
-
-const getPositionStyleSource = (
- position: InsertableCompositionElementPosition | null,
- prettierConfigOverride: Record<string, unknown> | null,
-) => {
- const quote = prettierConfigOverride?.singleQuote === true ? "'" : '"';
- const spacing = prettierConfigOverride?.bracketSpacing === false ? '' : ' ';
- const translate = position
- ? `, translate: ${quote}${formatTranslateValue(position)}${quote}`
- : '';
- return `style={{${spacing}position: ${quote}absolute${quote}${translate}${spacing}}}`;
-};
-
-const getSolidInsertionSource = ({
- element,
- finalElement,
- height,
- input,
- position,
- prettierConfigOverride,
- sequenceWrapper,
- width,
-}: {
- element: namedTypes.JSXElement;
- finalElement: namedTypes.JSXElement;
- height: number;
- input: string;
- position: InsertableCompositionElementPosition | null;
- prettierConfigOverride: Record<string, unknown> | null;
- sequenceWrapper: {
- dimensions: {width: number; height: number} | null;
- durationInFrames: number | null;
- from: number | null;
- name: string | null;
- position: InsertableCompositionElementPosition | null;
- } | null;
- width: number;
-}) => {
- const endOfLine = getEndOfLine(input);
- const unit = getIndentationUnit(input, prettierConfigOverride);
- const solid = [
- `<${getJsxIdentifierName(element)}`,
- `${unit}width={${width}}`,
- `${unit}height={${height}}`,
- `${unit}color="gray"`,
- `${unit}${getPositionStyleSource(position, prettierConfigOverride)}`,
- '/>',
- ].join(endOfLine);
- if (finalElement === element) {
- return solid;
- }
-
- if (sequenceWrapper === null) {
- throw new Error('Expected insertion Sequence metadata');
- }
-
- const attributes = [
- ...(sequenceWrapper.from === null
- ? []
- : [`from={${sequenceWrapper.from}}`]),
- ...(sequenceWrapper.name === null
- ? []
- : [`name=${JSON.stringify(sequenceWrapper.name)}`]),
- ...(sequenceWrapper.dimensions === null
- ? []
- : [
- `width={${sequenceWrapper.dimensions.width}}`,
- `height={${sequenceWrapper.dimensions.height}}`,
- ]),
- ...(sequenceWrapper.durationInFrames === null
- ? []
- : [`durationInFrames={${sequenceWrapper.durationInFrames}}`]),
- getPositionStyleSource(sequenceWrapper.position, prettierConfigOverride),
- ];
- const sequenceName = getJsxIdentifierName(finalElement);
- return [
- `<${sequenceName} ${attributes.join(' ')}>`,
- ...solid.split(/\r?\n/).map((line) => `${unit}${line}`),
- `</${sequenceName}>`,
- ].join(endOfLine);
-};
-
-const getInsertionSource = ({
- element,
- elementToInsert,
- finalElementToInsert,
- input,
- prettierConfigOverride,
- sequenceWrapper,
-}: {
- element: InsertableCompositionElement;
- elementToInsert: namedTypes.JSXElement;
- finalElementToInsert: namedTypes.JSXElement;
- input: string;
- prettierConfigOverride: Record<string, unknown> | null;
- sequenceWrapper: {
- dimensions: {width: number; height: number} | null;
- durationInFrames: number | null;
- from: number | null;
- name: string | null;
- position: InsertableCompositionElementPosition | null;
- } | null;
-}) => {
- if (element.type === 'solid') {
- return getSolidInsertionSource({
- element: elementToInsert,
- finalElement: finalElementToInsert,
- height: element.height,
- input,
- position: element.position,
- prettierConfigOverride,
- sequenceWrapper,
- width: element.width,
- });
- }
-
- return printInsertedJsx({
- element: finalElementToInsert,
- input,
- prettierConfigOverride,
- });
-};
-
export const getInsertionRootSourceEdit = ({
insertInside,
input,
@@ -2681,50 +2183,27 @@ const ensureCompositionComponentImport = async ({
});
};
+// Elements that cannot be described with `createElement()`: SVG markup needs
+// an SVG-to-JSX conversion, and compositions need their component resolved
+// and imported from another project file.
+export type PipelineInsertableElement = Extract<
+ InsertableCompositionElement,
+ {type: 'svg' | 'composition'}
+>;
+
const createInsertableJsxElement = ({
- addPositionStyleToComponent,
ast,
destinationFileName,
element,
environment,
from,
}: {
- addPositionStyleToComponent: boolean;
ast: File;
destinationFileName: string;
- element: InsertableCompositionElement;
+ element: PipelineInsertableElement;
environment: InsertJsxElementCodemodEnvironment;
from: number | null;
-}): Promise<namedTypes.JSXElement> | namedTypes.JSXElement => {
- if (element.type === 'solid') {
- const solidLocalName = ensureSolidImport(ast);
-
- return createSolidElement({
- localName: solidLocalName,
- width: element.width,
- height: element.height,
- position: element.position,
- });
- }
-
- if (element.type === 'component') {
- const componentLocalName = ensureComponentImport({
- ast,
- componentName: element.componentName,
- importName: element.importName,
- importPath: element.importPath,
- });
-
- return createComponentElement({
- getStaticFileLocalName: () => ensureStaticFileImport(ast),
- addPositionStyle: addPositionStyleToComponent,
- from,
- localName: componentLocalName,
- props: element.props,
- position: element.position,
- });
- }
-
+}): Promise<namedTypes.JSXElement> => {
if (element.type === 'svg') {
return createSvgElement({
environment,
@@ -2735,67 +2214,22 @@ const createInsertableJsxElement = ({
});
}
- if (element.type === 'composition') {
- return Promise.resolve(
- ensureCompositionComponentImport({
- ast,
- compositionFile: element.compositionFile,
- compositionId: element.compositionId,
- destinationFileName,
- environment,
- }),
- ).then((localName) => {
- const props = parseSerializedCompositionProps(
- element.serializedResolvedPropsWithCustomSchema,
- );
- if (containsFileToken(props)) {
- ensureStaticFileImport(ast);
- }
-
- return createCompositionComponentElement({localName, props});
- });
- }
-
- if (element.type === 'asset') {
- if (element.srcType === 'remote' && !isUrl(element.src)) {
- throw new Error('Remote asset source must be a URL');
- }
-
- const staticFileLocalName =
- element.srcType === 'remote' ? null : ensureStaticFileImport(ast);
- let localName: string;
- if (element.assetType === 'image') {
- localName = ensureCanvasImageImport(ast);
- } else if (element.assetType === 'video') {
- localName = ensureVideoImport(ast);
- } else if (element.assetType === 'gif') {
- localName = ensureGifImport(ast);
- } else if (element.assetType === 'animated-image') {
- localName = ensureAnimatedImageImport(ast);
- } else if (element.assetType === 'audio') {
- localName = ensureAudioImport(ast);
- } else {
- throw new Error('Unsupported asset type');
+ return ensureCompositionComponentImport({
+ ast,
+ compositionFile: element.compositionFile,
+ compositionId: element.compositionId,
+ destinationFileName,
+ environment,
+ }).then((localName) => {
+ const props = parseSerializedCompositionProps(
+ element.serializedResolvedPropsWithCustomSchema,
+ );
+ if (containsFileToken(props)) {
+ ensureStaticFileImport(ast);
}
- return createAssetElement({
- addPositionStyle:
- addPositionStyleToComponent && element.assetType !== 'audio',
- durationInFrames:
- element.assetType === 'image' ? null : element.durationInFrames,
- from,
- localName,
- staticFileLocalName,
- src: element.src,
- dimensions:
- element.assetType === 'image' && from !== null
- ? null
- : element.dimensions,
- position: element.position,
- });
- }
-
- throw new Error('Unsupported element type');
+ return createCompositionComponentElement({localName, props});
+ });
};
export const insertJsxElementIntoComposition = async ({
@@ -2829,6 +2263,12 @@ export const insertJsxElementIntoComposition = async ({
nodePathRemappings: SequenceNodePathRemapping[];
insertedNodePath: SequenceNodePath | null;
}> => {
+ if (element.type !== 'svg' && element.type !== 'composition') {
+ throw new Error(
+ `Insert ${element.type} elements with addElement() and createElementFromInsertable()`,
+ );
+ }
+
if (
from !== null &&
(!Number.isInteger(from) || !Number.isFinite(from) || from < 0)
@@ -2888,20 +2328,8 @@ export const insertJsxElementIntoComposition = async ({
position: element.position,
from,
}
- : from === null ||
- element.type === 'asset' ||
- element.type === 'svg' ||
- element.type === 'component'
- ? wrapInSequence
- : {
- dimensions: null,
- durationInFrames: null,
- name: null,
- position: element.position,
- from,
- };
+ : wrapInSequence;
const elementToInsert = await createInsertableJsxElement({
- addPositionStyleToComponent: sequenceWrapper === null,
ast,
destinationFileName: location.fileName,
element,
@@ -2935,13 +2363,11 @@ export const insertJsxElementIntoComposition = async ({
getInsertionRootSourceEdit({
insertInside: rootBeforeInsertion?.type === 'JSXFragment',
input,
- insertion: getInsertionSource({
- element,
- elementToInsert,
- finalElementToInsert,
+ insertion: printInsertedJsx({
+ compactLiteralProps: true,
+ element: finalElementToInsert,
input,
prettierConfigOverride,
- sequenceWrapper,
}),
nullRoot: nullRootBeforeInsertion,
prettierConfigOverride,
diff --git a/packages/codemods/src/insertable-element.ts b/packages/codemods/src/insertable-element.ts
new file mode 100644
index 0000000000..eea89bc3ec
--- /dev/null
+++ b/packages/codemods/src/insertable-element.ts
@@ -0,0 +1,207 @@
+import {StudioProtocolInternals} from '@remotion/studio-protocol';
+import {
+ isUrl,
+ type InsertableCompositionElement,
+ type InsertableCompositionElementPosition,
+} from '@remotion/studio-shared';
+import {
+ createElement,
+ staticFileValue,
+ type CodemodElement,
+} from './codemod-element';
+import type {CodemodValue} from './codemod-value';
+import {formatTranslateValue} from './insert-jsx-element';
+
+export type InsertableSequenceWrapper = {
+ dimensions: {width: number; height: number} | null;
+ durationInFrames: number | null;
+ from: number | null;
+ name: string | null;
+ position: InsertableCompositionElementPosition | null;
+};
+
+const assetComponents = {
+ image: {component: 'CanvasImage', importPath: 'remotion'},
+ video: {component: 'Video', importPath: '@remotion/media'},
+ audio: {component: 'Audio', importPath: '@remotion/media'},
+ gif: {component: 'Gif', importPath: '@remotion/gif'},
+ 'animated-image': {component: 'AnimatedImage', importPath: 'remotion'},
+} as const;
+
+const getPositionStyle = (
+ position: InsertableCompositionElementPosition | null,
+): Record<string, CodemodValue> => ({
+ position: 'absolute',
+ ...(position === null ? {} : {translate: formatTranslateValue(position)}),
+});
+
+// Studio Elements reference their assets with `staticFileRef()` markers.
+const toCodemodValue = (value: unknown): CodemodValue => {
+ if (StudioProtocolInternals.isStaticFileRef(value)) {
+ return staticFileValue(value.__remotion_element_asset);
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(toCodemodValue);
+ }
+
+ if (typeof value === 'object' && value !== null) {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, item]) => [key, toCodemodValue(item)]),
+ );
+ }
+
+ return value as CodemodValue;
+};
+
+/**
+ * Translates a Studio insertion request for a solid, asset or component into
+ * an element for `addElement()`. SVG markup and compositions keep using the
+ * dedicated insertion pipeline.
+ */
+export const createElementFromInsertable = ({
+ element,
+ from,
+ wrapInSequence,
+}: {
+ element: InsertableCompositionElement;
+ from: number | null;
+ wrapInSequence: InsertableSequenceWrapper | null;
+}): CodemodElement => {
+ if (element.type === 'svg' || element.type === 'composition') {
+ throw new Error(`Cannot describe a ${element.type} as an element`);
+ }
+
+ if (from !== null && (!Number.isInteger(from) || from < 0)) {
+ throw new Error('from must be a non-negative integer');
+ }
+
+ if (
+ element.position !== null &&
+ (!Number.isFinite(element.position.x) ||
+ !Number.isFinite(element.position.y))
+ ) {
+ throw new Error('Position must be finite');
+ }
+
+ // A timed solid gets its own Sequence; other elements carry `from` themselves
+ // unless the caller asks for a wrapper.
+ const sequence =
+ element.type === 'solid' && from !== null
+ ? {
+ dimensions: null,
+ durationInFrames: null,
+ from,
+ name: null,
+ position: element.position,
+ }
+ : wrapInSequence;
+ const positioned = sequence === null;
+
+ let inner: CodemodElement;
+ if (element.type === 'solid') {
+ inner = createElement({
+ component: 'Solid',
+ importPath: 'remotion',
+ props: {
+ width: element.width,
+ height: element.height,
+ color: 'gray',
+ style: getPositionStyle(element.position),
+ },
+ });
+ } else if (element.type === 'asset') {
+ if (element.srcType === 'remote' && !isUrl(element.src)) {
+ throw new Error('Remote asset source must be a URL');
+ }
+
+ const dimensions =
+ element.assetType === 'image' && from !== null
+ ? null
+ : element.dimensions;
+ inner = createElement({
+ ...assetComponents[element.assetType],
+ props: {
+ src:
+ element.srcType === 'remote'
+ ? element.src
+ : staticFileValue(element.src),
+ ...(element.assetType !== 'image' && element.durationInFrames !== null
+ ? {durationInFrames: element.durationInFrames}
+ : {}),
+ ...(from === null ? {} : {from}),
+ ...(positioned && element.assetType !== 'audio'
+ ? {
+ style: {
+ ...getPositionStyle(element.position),
+ ...(dimensions === null
+ ? {}
+ : {width: dimensions.width, height: dimensions.height}),
+ },
+ }
+ : {}),
+ },
+ });
+ } else {
+ const props: Record<string, CodemodValue> = Object.fromEntries(
+ element.props.map((prop) => [prop.name, toCodemodValue(prop.value)]),
+ );
+ if (from !== null) {
+ props.from = from;
+ }
+
+ const {style, ...propsWithoutStyle} = props;
+ if (positioned && style !== undefined) {
+ if (typeof style !== 'object' || style === null || Array.isArray(style)) {
+ throw new Error('Component style must be an object to add a position');
+ }
+ }
+
+ inner = createElement({
+ component: element.componentName,
+ importName: element.importName,
+ importPath: element.importPath,
+ props: positioned
+ ? {
+ ...propsWithoutStyle,
+ style: {
+ ...Object.fromEntries(
+ Object.entries(
+ (style as Record<string, CodemodValue> | undefined) ?? {},
+ ).filter(
+ ([key]) =>
+ key !== 'position' &&
+ (element.position === null || key !== 'translate'),
+ ),
+ ),
+ ...getPositionStyle(element.position),
+ },
+ }
+ : props,
+ });
+ }
+
+ if (sequence === null) {
+ return inner;
+ }
+
+ return createElement({
+ component: 'Sequence',
+ importPath: 'remotion',
+ props: {
+ ...(sequence.from === null ? {} : {from: sequence.from}),
+ ...(sequence.name === null ? {} : {name: sequence.name}),
+ ...(sequence.dimensions === null
+ ? {}
+ : {
+ width: sequence.dimensions.width,
+ height: sequence.dimensions.height,
+ }),
+ ...(sequence.durationInFrames === null
+ ? {}
+ : {durationInFrames: sequence.durationInFrames}),
+ style: getPositionStyle(sequence.position),
+ },
+ children: [inner],
+ });
+};
diff --git a/packages/codemods/src/print-jsx.ts b/packages/codemods/src/print-jsx.ts
index 54a5b090ce..5fe5f84df5 100644
--- a/packages/codemods/src/print-jsx.ts
+++ b/packages/codemods/src/print-jsx.ts
@@ -65,12 +65,82 @@ export const indentInsertedJsx = ({
.join(insertion.includes('\r\n') ? '\r\n' : '\n');
};
+// Node types that Recast always prints across several lines but that read
+// fine on one line, such as the object in `style={{position: 'absolute'}}`.
+const compactableNodeTypes = new Set([
+ 'ArrayExpression',
+ 'BooleanLiteral',
+ 'CallExpression',
+ 'Identifier',
+ 'JSXAttribute',
+ 'JSXExpressionContainer',
+ 'JSXIdentifier',
+ 'JSXNamespacedName',
+ 'MemberExpression',
+ 'NewExpression',
+ 'NullLiteral',
+ 'NumericLiteral',
+ 'ObjectExpression',
+ 'ObjectProperty',
+ 'StringLiteral',
+ 'TSAsExpression',
+ 'TSTypeReference',
+ 'UnaryExpression',
+]);
+
+const canCompactAttribute = (attribute: namedTypes.Node) => {
+ let compactable = true;
+ recast.types.visit(attribute, {
+ visitNode(path) {
+ const {node} = path;
+ if (
+ !compactableNodeTypes.has(node.type) ||
+ (node.comments ?? []).length > 0
+ ) {
+ compactable = false;
+ return false;
+ }
+
+ this.traverse(path);
+ },
+ });
+ return compactable;
+};
+
+const compactPrintedAttribute = ({
+ bracketSpacing,
+ printed,
+}: {
+ bracketSpacing: boolean;
+ printed: string;
+}) => {
+ return printed
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0)
+ .reduce((result, line) => {
+ if (result.length === 0) {
+ return line;
+ }
+
+ const omitSeparator =
+ result.endsWith('[') ||
+ line.startsWith(']') ||
+ (!bracketSpacing && (result.endsWith('{') || line.startsWith('}')));
+ return `${result}${omitSeparator ? '' : ' '}${line}`;
+ }, '');
+};
+
export const printInsertedJsx = ({
+ compactLiteralProps,
element,
input,
originalAttributeSources,
prettierConfigOverride,
}: {
+ // Whether generated object and array props may be printed on one line
+ // when they fit. Edits of existing source keep Recast's expanded layout.
+ compactLiteralProps: boolean;
element: namedTypes.JSXElement | namedTypes.JSXFragment;
input: string;
originalAttributeSources?: ReadonlyMap<object, string>;
@@ -179,9 +249,18 @@ export const printInsertedJsx = ({
return `${attribute.name.name}="${escapeJsxStringAttribute(attribute.value.value)}"`;
}
- const unwrapped = normalizeIndentation(
+ const printed = normalizeIndentation(
printNode(attribute, Number.POSITIVE_INFINITY),
);
+ const unwrapped =
+ compactLiteralProps &&
+ printed.includes(endOfLine) &&
+ canCompactAttribute(attribute)
+ ? compactPrintedAttribute({
+ bracketSpacing: formattingConfig.bracketSpacing,
+ printed,
+ })
+ : printed;
return !unwrapped.includes(endOfLine) && unwrapped.length <= printWidth
? unwrapped
: normalizeIndentation(printNode(attribute, printWidth));
@@ -283,11 +362,13 @@ export const printInsertedJsx = ({
};
export const printJsxOpeningElement = ({
+ compactLiteralProps,
openingElement,
input,
originalAttributeSources,
prettierConfigOverride,
}: {
+ compactLiteralProps: boolean;
openingElement: namedTypes.JSXOpeningElement;
input: string;
originalAttributeSources?: ReadonlyMap<object, string>;
@@ -304,6 +385,7 @@ export const printJsxOpeningElement = ({
[],
);
const printed = printInsertedJsx({
+ compactLiteralProps,
element: printableElement,
input,
originalAttributeSources,
diff --git a/packages/codemods/src/registration-source-edits.ts b/packages/codemods/src/registration-source-edits.ts
index e55e9b1838..e63357be23 100644
--- a/packages/codemods/src/registration-source-edits.ts
+++ b/packages/codemods/src/registration-source-edits.ts
@@ -226,6 +226,7 @@ export const getRegistrationInsertionSourceEdit = ({
return getInsertionRootSourceEdit({
input,
insertion: printInsertedJsx({
+ compactLiteralProps: false,
element: insertion as never,
input,
prettierConfigOverride: null,
diff --git a/packages/codemods/src/resolve-composition-component-location.ts b/packages/codemods/src/resolve-composition-component-location.ts
index c516962e56..4fc36da26f 100644
--- a/packages/codemods/src/resolve-composition-component-location.ts
+++ b/packages/codemods/src/resolve-composition-component-location.ts
@@ -319,6 +319,33 @@ const getExportedName = (name: Identifier | StringLiteral) => {
return name.type === 'Identifier' ? name.name : name.value;
};
+const findImportedComponent = (file: File, localName: string) => {
+ for (const statement of file.program.body) {
+ if (statement.type !== 'ImportDeclaration') {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers) {
+ if (specifier.local.name !== localName) {
+ continue;
+ }
+
+ if (specifier.type === 'ImportDefaultSpecifier') {
+ return {exportName: 'default' as const, path: statement.source.value};
+ }
+
+ if (specifier.type === 'ImportSpecifier') {
+ return {
+ exportName: getExportedName(specifier.imported),
+ path: statement.source.value,
+ };
+ }
+ }
+ }
+
+ return null;
+};
+
const resolveDeclaration = ({
filePath,
exportName,
@@ -378,10 +405,7 @@ const resolveDeclaration = ({
if (exportName !== 'default') {
for (const statement of file.program.body) {
- if (
- statement.type !== 'ExportNamedDeclaration' ||
- statement.source?.type !== 'StringLiteral'
- ) {
+ if (statement.type !== 'ExportNamedDeclaration') {
continue;
}
@@ -393,16 +417,60 @@ const resolveDeclaration = ({
continue;
}
+ if (statement.source?.type === 'StringLiteral') {
+ return resolveDeclaration({
+ filePath: resolveImport({
+ fromFile: filePath,
+ importPath: statement.source.value,
+ project,
+ }),
+ exportName: getExportedName(specifier.local),
+ project,
+ visited,
+ });
+ }
+
+ // Barrel files that import a component and export it separately.
+ const imported = findImportedComponent(
+ file,
+ getExportedName(specifier.local),
+ );
+ if (imported) {
+ return resolveDeclaration({
+ filePath: resolveImport({
+ fromFile: filePath,
+ importPath: imported.path,
+ project,
+ }),
+ exportName: imported.exportName,
+ project,
+ visited,
+ });
+ }
+ }
+ }
+
+ for (const statement of file.program.body) {
+ if (
+ statement.type !== 'ExportAllDeclaration' ||
+ statement.source.type !== 'StringLiteral'
+ ) {
+ continue;
+ }
+
+ try {
return resolveDeclaration({
filePath: resolveImport({
fromFile: filePath,
importPath: statement.source.value,
project,
}),
- exportName: getExportedName(specifier.local),
+ exportName,
project,
visited,
});
+ } catch {
+ // The export may come from another re-exported module.
}
}
}
@@ -410,33 +478,6 @@ const resolveDeclaration = ({
throw new Error(`Could not find composition component "${exportName}"`);
};
-const findImportedComponent = (file: File, localName: string) => {
- for (const statement of file.program.body) {
- if (statement.type !== 'ImportDeclaration') {
- continue;
- }
-
- for (const specifier of statement.specifiers) {
- if (specifier.local.name !== localName) {
- continue;
- }
-
- if (specifier.type === 'ImportDefaultSpecifier') {
- return {exportName: 'default' as const, path: statement.source.value};
- }
-
- if (specifier.type === 'ImportSpecifier') {
- return {
- exportName: getExportedName(specifier.imported),
- path: statement.source.value,
- };
- }
- }
- }
-
- return null;
-};
-
const unwrapExpression = (node: Node | null): Node | null => {
let current = node;
while (
diff --git a/packages/codemods/src/split-jsx-sequence.ts b/packages/codemods/src/split-jsx-sequence.ts
index 1e5a95bc07..02f20dbc98 100644
--- a/packages/codemods/src/split-jsx-sequence.ts
+++ b/packages/codemods/src/split-jsx-sequence.ts
@@ -382,6 +382,7 @@ const getSplitSourceEdit = ({
indent: lineIndent,
input,
printed: printInsertedJsx({
+ compactLiteralProps: false,
element: element as unknown as
| AstNamedTypes.JSXElement
| AstNamedTypes.JSXFragment,
diff --git a/packages/codemods/src/split-video-from-audio.ts b/packages/codemods/src/split-video-from-audio.ts
index 3e6d8edcd7..37794bd1e5 100644
--- a/packages/codemods/src/split-video-from-audio.ts
+++ b/packages/codemods/src/split-video-from-audio.ts
@@ -478,6 +478,7 @@ export const splitVideoFromAudio = ({
children: [],
};
const audioSource = printInsertedJsx({
+ compactLiteralProps: false,
element: audioElement as never,
input,
originalAttributeSources,
diff --git a/packages/codemods/src/test/insert-solid.test.ts b/packages/codemods/src/test/insert-solid.test.ts
index bc50046809..5710b9562d 100644
--- a/packages/codemods/src/test/insert-solid.test.ts
+++ b/packages/codemods/src/test/insert-solid.test.ts
@@ -1,6 +1,7 @@
import {expect, test} from 'bun:test';
import {addElement, applyCodemodChanges, createElement} from '../index';
import {insertJsxElementIntoProjectWithNodePathRemappings} from '../insert-jsx-element';
+import {createElementFromInsertable} from '../insertable-element';
const solid = createElement({
component: 'Solid',
@@ -128,32 +129,29 @@ export const MyComposition = () => {
export const Root = () => <Composition id = "MyComp" component={MyComposition}/>;
`;
- const result = await insertJsxElementIntoProjectWithNodePathRemappings({
- project: {
- files: {'/project/src/index.tsx': source},
- rootDir: '/project',
- },
- request: {
+ const project = {
+ files: {'/project/src/index.tsx': source},
+ rootDir: '/project',
+ };
+ const result = addElement({
+ project,
+ element: createElementFromInsertable({
+ element: {height: 720, position: null, type: 'solid', width: 1280},
+ from: null,
+ wrapInSequence: null,
+ }),
+ target: {
+ type: 'composition',
compositionFile: '/project/src/index.tsx',
compositionId: 'MyComp',
- element: {
- height: 720,
- position: null,
- type: 'solid',
- width: 1280,
- },
- from: null,
- },
- svgMarkupToJsx: () => {
- throw new Error(
- 'SVG conversion should not be called when inserting a Solid',
- );
},
- wrapInSequence: null,
});
- expect(result.output)
- .toBe(`import {Composition, AbsoluteFill, Solid} from 'remotion';
+ expect(
+ applyCodemodChanges(project, result.changes).files[
+ '/project/src/index.tsx'
+ ],
+ ).toBe(`import {Composition, AbsoluteFill, Solid} from 'remotion';
// Keep the deliberately non-Prettier formatting in this file.
export const MyComposition = () => {
@@ -162,77 +160,110 @@ export const MyComposition = () => {
<AbsoluteFill>
<div>Existing</div>
</AbsoluteFill>
- <Solid
- width={1280}
- height={720}
- color="gray"
- style={{ position: "absolute" }}
- />
+ <Solid width={1280} height={720} color="gray" style={{position: 'absolute'}} />
</>
)
}
export const Root = () => <Composition id = "MyComp" component={MyComposition}/>;
`);
- expect(result.insertedNodePath).not.toBeNull();
+ expect(result.insertedNode.nodePath.length).toBeGreaterThan(0);
+ await expect(
+ insertJsxElementIntoProjectWithNodePathRemappings({
+ project,
+ request: {
+ compositionFile: '/project/src/index.tsx',
+ compositionId: 'MyComp',
+ element: {height: 720, position: null, type: 'solid', width: 1280},
+ from: null,
+ },
+ svgMarkupToJsx: () => {
+ throw new Error('SVG conversion should not be called');
+ },
+ wrapInSequence: null,
+ }),
+ ).rejects.toThrow('addElement()');
});
-test('asset and component insertions also avoid the full-file formatter', async () => {
+test('asset and component insertions also avoid the full-file formatter', () => {
const source = `import {Composition, AbsoluteFill} from 'remotion';
export const MyComposition = () => <><AbsoluteFill /></>;
export const Root = () => <Composition id="MyComp" component={MyComposition}/>;
`;
- const assetResult = await insertJsxElementIntoProjectWithNodePathRemappings({
- project: {
- files: {'/project/src/index.tsx': source},
- rootDir: '/project',
- },
- request: {
- compositionFile: '/project/src/index.tsx',
- compositionId: 'MyComp',
+ const project = {
+ files: {'/project/src/index.tsx': source},
+ rootDir: '/project',
+ };
+ const target = {
+ type: 'composition' as const,
+ compositionFile: '/project/src/index.tsx',
+ compositionId: 'MyComp',
+ };
+ const assetResult = addElement({
+ project,
+ element: createElementFromInsertable({
element: {
assetType: 'image',
dimensions: {height: 720, width: 1280},
durationInFrames: null,
- position: null,
+ position: {x: 10, y: 20.25},
src: 'image.png',
srcType: 'static',
type: 'asset',
},
from: null,
- },
- svgMarkupToJsx: () => {
- throw new Error('SVG conversion should not be called');
- },
- wrapInSequence: null,
+ wrapInSequence: null,
+ }),
+ target,
});
- const componentResult =
- await insertJsxElementIntoProjectWithNodePathRemappings({
- project: {
- files: {'/project/src/index.tsx': source},
- rootDir: '/project',
- },
- request: {
- compositionFile: '/project/src/index.tsx',
- compositionId: 'MyComp',
- element: {
- componentName: 'Chart',
- importName: 'Chart',
- importPath: './Chart',
- position: null,
- props: [{name: 'title', value: 'Revenue'}],
- type: 'component',
- },
- from: null,
+ const componentResult = addElement({
+ project,
+ element: createElementFromInsertable({
+ element: {
+ componentName: 'RevenueChart',
+ importName: 'Chart',
+ importPath: './Chart',
+ position: null,
+ props: [
+ {name: 'title', value: 'Revenue'},
+ {name: 'style', value: {position: 'relative', opacity: 0.5} as never},
+ ],
+ type: 'component',
},
- svgMarkupToJsx: () => {
- throw new Error('SVG conversion should not be called');
+ from: 12,
+ wrapInSequence: {
+ dimensions: {width: 400, height: 300},
+ durationInFrames: 60,
+ from: 12,
+ name: 'Chart',
+ position: {x: 1, y: 2},
},
- wrapInSequence: null,
- });
+ }),
+ target,
+ });
+ const assetOutput = applyCodemodChanges(project, assetResult.changes).files[
+ '/project/src/index.tsx'
+ ];
+ const componentOutput = applyCodemodChanges(project, componentResult.changes)
+ .files['/project/src/index.tsx'];
- expect(assetResult.output).toContain('<CanvasImage\n');
- expect(componentResult.output).toContain('<Chart\n');
- expect(componentResult.output).toContain('title="Revenue"');
+ expect(assetOutput).toContain(
+ "import {Composition, AbsoluteFill, CanvasImage, staticFile} from 'remotion';",
+ );
+ expect(assetOutput).toContain('<CanvasImage\n');
+ expect(assetOutput).toContain("src={staticFile('image.png')}");
+ // Too long for one line, so the style object keeps its expanded layout.
+ expect(assetOutput).toMatch(
+ /style=\{\{\n\s+position: 'absolute',\n\s+translate: '10px 20\.3px',\n\s+width: 1280,\n\s+height: 720\n\s+\}\}/,
+ );
+ expect(componentOutput).toContain(
+ "import {Chart as RevenueChart} from './Chart';",
+ );
+ expect(componentOutput).toContain(
+ `<Sequence\n from={12}\n name="Chart"\n width={400}\n height={300}\n durationInFrames={60}\n style={{position: 'absolute', translate: '1px 2px'}}\n >`,
+ );
+ expect(componentOutput).toContain(
+ `<RevenueChart\n title="Revenue"\n style={{position: 'relative', opacity: 0.5}}\n from={12}\n />`,
+ );
});
diff --git a/packages/codemods/src/test/public-editing.test.ts b/packages/codemods/src/test/public-editing.test.ts
index 6179605971..8e18c14ede 100644
--- a/packages/codemods/src/test/public-editing.test.ts
+++ b/packages/codemods/src/test/public-editing.test.ts
@@ -698,10 +698,17 @@ test('addElement returns remappings usable by public discovery and targets nodes
expect(JSON.parse(JSON.stringify(caption))).toEqual({
component: 'p',
importPath: null,
+ importName: null,
props: {className: 'caption', 'data-testid': 'caption'},
children: [
'Hello {world} & friends',
- {component: 'br', importPath: null, props: {}, children: []},
+ {
+ component: 'br',
+ importPath: null,
+ importName: null,
+ props: {},
+ children: [],
+ },
],
});
});
diff --git a/packages/codemods/src/update-keyframes.ts b/packages/codemods/src/update-keyframes.ts
index bcbd6fc5db..505c48e6fd 100644
--- a/packages/codemods/src/update-keyframes.ts
+++ b/packages/codemods/src/update-keyframes.ts
@@ -110,6 +110,7 @@ const getOpeningElementSourceEdit = ({
const start = recastLocToOffset(input, openingElement.loc.start);
const printed = printJsxOpeningElement({
+ compactLiteralProps: false,
originalAttributeSources,
openingElement: openingElement as never,
input,
diff --git a/packages/codemods/src/update-sequence-props.ts b/packages/codemods/src/update-sequence-props.ts
index 1368736f70..bfcf7d549d 100644
--- a/packages/codemods/src/update-sequence-props.ts
+++ b/packages/codemods/src/update-sequence-props.ts
@@ -1516,6 +1516,7 @@ export const updateMultipleSequenceProps = ({
indent: getJsxSourceIndent(start),
input,
printed: printJsxOpeningElement({
+ compactLiteralProps: false,
originalAttributeSources,
openingElement:
openingElement as unknown as AstNamedTypes.JSXOpeningElement,
@@ -1549,6 +1550,7 @@ export const updateMultipleSequenceProps = ({
indent: getJsxSourceIndent(start),
input,
printed: printInsertedJsx({
+ compactLiteralProps: false,
originalAttributeSources,
element: element as unknown as AstNamedTypes.JSXElement,
input,
diff --git a/packages/codemods/src/wrap-jsx-node.ts b/packages/codemods/src/wrap-jsx-node.ts
index 36fa794a84..35826cae60 100644
--- a/packages/codemods/src/wrap-jsx-node.ts
+++ b/packages/codemods/src/wrap-jsx-node.ts
@@ -250,6 +250,7 @@ export const wrapJsxNode = <Project extends CodemodProject>({
opening.selfClosing = false;
const localName = recast.print(opening.name).code;
const openingLines = printJsxOpeningElement({
+ compactLiteralProps: true,
openingElement: opening,
input,
prettierConfigOverride: null,
diff --git a/packages/docs/docs/codemods/add-element.mdx b/packages/docs/docs/codemods/add-element.mdx
index 7275fd4cf4..208feaf517 100644
--- a/packages/docs/docs/codemods/add-element.mdx
+++ b/packages/docs/docs/codemods/add-element.mdx
@@ -86,6 +86,10 @@ Where to insert the element. One of the following objects.
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: 'component', filePath, exportName}`
+
+Appends the element to the JSX returned by the component that `filePath` exports as `exportName`, or as its default export when `exportName` is `'default'`. Use it when the component is already known, for example from [`resolveCompositionComponent()`](/docs/codemods/resolve-composition-component). Follows the same rules as the `composition` target.
+
#### `{type: 'inside', node}`
Appends the element as the last child of the JSX element referenced by `node`. Self-closing elements are expanded.
@@ -100,6 +104,10 @@ Inserts the element after the JSX element referenced by `node`, following the sa
Obtain a `node` from [`getJsxNodes()`](/docs/codemods/get-jsx-nodes) or a previous result. See [node references](/docs/codemods#node-references).
+### prettierConfigOverride?
+
+Formatting options for generated source, such as `singleQuote`, `useTabs`, `tabWidth`, `printWidth`, and `bracketSpacing`. Defaults to `null`, which follows the existing source style.
+
## Return value
An object with the following properties.
diff --git a/packages/docs/docs/codemods/create-element.mdx b/packages/docs/docs/codemods/create-element.mdx
index a43be1d403..aef91087d7 100644
--- a/packages/docs/docs/codemods/create-element.mdx
+++ b/packages/docs/docs/codemods/create-element.mdx
@@ -52,6 +52,10 @@ The JSX tag name. Use a component name such as `Solid`, a member expression such
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.
+### importName?
+
+The named export to import when it differs from `component`. For example, `{component: 'Title', importName: 'AnimatedTitle', importPath: './Title'}` adds `import {AnimatedTitle as Title} from './Title'` and renders `<Title />`. Requires `importPath`. By default, the first identifier of `component` is imported.
+
### 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 `{}`.
@@ -64,9 +68,9 @@ An array of children. Each child is a string, an element created with `createEle
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
+### component, importPath, importName, 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.
+The values passed to `createElement()`, with `importPath` and `importName` defaulting to `null`. `JSON.stringify()` serializes an element to a plain description that `createElement()` accepts again.
### withProp(name, value)
diff --git a/packages/docs/docs/codemods/resolve-composition-component.mdx b/packages/docs/docs/codemods/resolve-composition-component.mdx
index b8fdc054cd..922a29bf6d 100644
--- a/packages/docs/docs/codemods/resolve-composition-component.mdx
+++ b/packages/docs/docs/codemods/resolve-composition-component.mdx
@@ -62,7 +62,7 @@ The declaration's `{line, column}` location. Lines are one-based; columns are ze
### canAddContent
-Whether the component's returned JSX structure supports content insertion.
+Whether the component's returned JSX structure supports content insertion. Pass `filePath` and `exportName` as a `{type: 'component'}` target to [`addElement()`](/docs/codemods/add-element) to insert into the resolved component.
## Errors
@@ -76,4 +76,5 @@ Throws when the target cannot be resolved, the requested edit is unsupported, or
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/resolve-composition-component.ts)
- [`@remotion/codemods`](/docs/codemods)
+- [`addElement()`](/docs/codemods/add-element)
- [`getJsxNodes()`](/docs/codemods/get-jsx-nodes)
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 89c463594b..b692f99e02 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -1,7 +1,10 @@
import fs from 'node:fs';
import path from 'node:path';
import {
+ addElement,
+ applyCodemodChanges,
CodemodsInternals,
+ getJsxNodes,
type InsertJsxElementCodemodEnvironment,
type ResolvedCompositionComponent,
type ResolvedCompositionComponentWithFile,
@@ -15,6 +18,7 @@ import type {SequenceNodePath} from 'remotion';
import {svgMarkupToJsx} from './svg-to-jsx';
const {
+ createElementFromInsertable,
insertJsxElementIntoComposition: insertJsxElementIntoCompositionCodemod,
resolveCompositionComponent: resolveCompositionComponentCodemod,
resolveCompositionComponentWithFile:
@@ -80,7 +84,7 @@ export const resolveCompositionComponent = ({
environment: makeCodemodEnvironment(remotionRoot, null),
});
-export const insertJsxElementIntoComposition = ({
+export const insertJsxElementIntoComposition = async ({
remotionRoot,
compositionFile,
compositionId,
@@ -112,22 +116,81 @@ export const insertJsxElementIntoComposition = ({
logLine: number;
nodePathRemappings: SequenceNodePathRemapping[];
insertedNodePath: SequenceNodePath | null;
-}> =>
- insertJsxElementIntoCompositionCodemod({
- compositionFile,
- compositionId,
+}> => {
+ const environment = makeCodemodEnvironment(remotionRoot, sourceFileOverrides);
+ const sequence =
+ wrapInSequence === null
+ ? null
+ : {
+ dimensions: wrapInSequence.dimensions,
+ durationInFrames: wrapInSequence.durationInFrames ?? null,
+ from: wrapInSequence.from,
+ name: wrapInSequence.name,
+ position: wrapInSequence.position,
+ };
+ // SVG markup and compositions need the file-system aware pipeline.
+ if (element.type === 'svg' || element.type === 'composition') {
+ return insertJsxElementIntoCompositionCodemod({
+ compositionFile,
+ compositionId,
+ element,
+ environment,
+ from,
+ prettierConfigOverride,
+ wrapInSequence: sequence,
+ });
+ }
+
+ const codemodElement = createElementFromInsertable({
element,
- environment: makeCodemodEnvironment(remotionRoot, sourceFileOverrides),
from,
+ wrapInSequence: sequence,
+ });
+ const location = await resolveCompositionComponentWithFileCodemod({
+ compositionFile,
+ compositionId,
+ environment,
+ });
+ if (!location.canAddSequence) {
+ throw new Error(
+ 'Cannot insert JSX element into this composition component',
+ );
+ }
+
+ const oldContents = await environment.readFile(location.fileName);
+ const project = {
+ rootDir: remotionRoot,
+ files: {[location.fileName]: oldContents},
+ };
+ const result = addElement({
+ project,
+ element: codemodElement,
+ target: {
+ type: 'component',
+ filePath: location.fileName,
+ exportName: location.exportName,
+ },
prettierConfigOverride,
- wrapInSequence:
- wrapInSequence === null
- ? null
- : {
- dimensions: wrapInSequence.dimensions,
- durationInFrames: wrapInSequence.durationInFrames ?? null,
- from: wrapInSequence.from,
- name: wrapInSequence.name,
- position: wrapInSequence.position,
- },
});
+ const nextProject = applyCodemodChanges(project, result.changes);
+ const insertedNode = getJsxNodes({
+ project: nextProject,
+ filePath: location.fileName,
+ }).find(
+ (node) =>
+ JSON.stringify(node.nodePath) ===
+ JSON.stringify(result.insertedNode.nodePath),
+ );
+
+ return {
+ fileName: location.fileName,
+ source: location.source,
+ oldContents,
+ output: nextProject.files[location.fileName],
+ logLine: insertedNode?.location?.line ?? 1,
+ nodePathRemappings: result.nodePathRemappings.map(
+ ({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),
+ ),
+ insertedNodePath: result.insertedNode.nodePath,
+ };
+};
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index f58ca25c80..fe8d819b7b 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -954,9 +954,9 @@ test('inserts an aliased Solid import if Solid is already defined', async () =>
});
expect(result.output).toContain(
- "import {AbsoluteFill, Solid as RemotionSolid} from 'remotion';",
+ "import {AbsoluteFill, Solid as Solid2} from 'remotion';",
);
- expect(result.output).toContain('<RemotionSolid');
+ expect(result.output).toContain('<Solid2');
expect(result.output).toContain('width={1920}');
expect(result.output).toContain('height={1080}');
expect(result.output).toContain("position: 'absolute'");
@@ -1146,7 +1146,7 @@ test('inserts a CanvasImage asset at a timeline frame', async () => {
});
expect(result.output).toContain(
- "import {AbsoluteFill, staticFile, CanvasImage} from 'remotion';",
+ "import {AbsoluteFill, CanvasImage, staticFile} from 'remotion';",
);
expect(result.output).not.toContain('<Sequence');
expect(result.output).toContain('from={42}');
@@ -1213,7 +1213,7 @@ test('inserts a CanvasImage asset with a translate style', async () => {
});
expect(result.output).toContain(
- "import {AbsoluteFill, staticFile, CanvasImage} from 'remotion';",
+ "import {AbsoluteFill, CanvasImage, staticFile} from 'remotion';",
);
expect(result.output).toContain('<CanvasImage');
expect(result.output).toContain("src={staticFile('image.png')}");
@@ -1271,7 +1271,7 @@ test('inserts an AnimatedImage asset into the resolved composition component', a
});
expect(result.output).toContain(
- "import {AbsoluteFill, staticFile, AnimatedImage} from 'remotion';",
+ "import {AbsoluteFill, AnimatedImage, staticFile} from 'remotion';",
);
expect(result.output).toContain('<AnimatedImage');
expect(result.output).toContain("src={staticFile('animated-png.png')}");