Skip to content

🎥 Make videos programmatically with React

`@remotion/studio-server`: Add duplicate sequence from timeline and jsxInMapCallback

JonnyBurger571d3941c4a1
diff --git a/bun.lock b/bun.lock
index 26a7eb7dce..872a68176b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1489,6 +1489,7 @@
"version": "4.0.445",
"dependencies": {
"@babel/parser": "7.24.1",
+ "@babel/types": "7.24.0",
"@remotion/bundler": "workspace:*",
"@remotion/renderer": "workspace:*",
"@remotion/studio-shared": "workspace:*",
@@ -1501,7 +1502,6 @@
"source-map": "0.7.3",
},
"devDependencies": {
- "@babel/types": "7.24.0",
"@remotion/eslint-config-internal": "workspace:*",
"@types/node": "catalog:",
"@types/semver": "^7.3.4",
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index b00131673f..0ab843ebab 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -24,6 +24,7 @@
"access": "public"
},
"dependencies": {
+ "@babel/types": "7.24.0",
"@babel/parser": "7.24.1",
"semver": "7.5.3",
"prettier": "catalog:",
@@ -39,7 +40,6 @@
"devDependencies": {
"ast-types": "0.16.1",
"react": "catalog:",
- "@babel/types": "7.24.0",
"@types/semver": "^7.3.4",
"@remotion/eslint-config-internal": "workspace:*",
"eslint": "catalog:",
diff --git a/packages/studio-server/src/codemods/duplicate-jsx-node.ts b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
new file mode 100644
index 0000000000..676ad2f30d
--- /dev/null
+++ b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
@@ -0,0 +1,508 @@
+import type {
+ ArrowFunctionExpression,
+ ArrayExpression,
+ AssignmentExpression,
+ CallExpression,
+ ConditionalExpression,
+ ExportDefaultDeclaration,
+ Expression,
+ ExpressionStatement,
+ JSXElement,
+ JSXExpressionContainer,
+ JSXFragment,
+ LogicalExpression,
+ NewExpression,
+ Node,
+ OptionalCallExpression,
+ ParenthesizedExpression,
+ ReturnStatement,
+ SequenceExpression,
+ TSAsExpression,
+ VariableDeclarator,
+} from '@babel/types';
+import {cloneNode} from '@babel/types';
+import type {SequenceNodePath} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import {
+ findJsxElementPathForDeletion,
+ getJsxElementTagLabel,
+} from './delete-jsx-node';
+import {parseAst, serializeAst} from './parse-ast';
+
+const {namedTypes} = recast.types;
+
+const makeFragment = (first: JSXElement, second: JSXElement): JSXFragment => ({
+ type: 'JSXFragment',
+ openingFragment: {type: 'JSXOpeningFragment'},
+ closingFragment: {type: 'JSXClosingFragment'},
+ children: [first, second],
+});
+
+const uniquifyNamePropOnClone = (clone: JSXElement): void => {
+ for (const attr of clone.openingElement.attributes) {
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier') {
+ continue;
+ }
+
+ if (attr.name.name !== 'name') {
+ continue;
+ }
+
+ if (!attr.value) {
+ continue;
+ }
+
+ if (attr.value.type === 'StringLiteral') {
+ attr.value.value = `${attr.value.value}-copy`;
+ return;
+ }
+
+ if (
+ attr.value.type === 'JSXExpressionContainer' &&
+ attr.value.expression.type === 'StringLiteral'
+ ) {
+ attr.value.expression.value = `${attr.value.expression.value}-copy`;
+ return;
+ }
+ }
+};
+
+const duplicateInLogicalExpression = (
+ parent: LogicalExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.left === node) {
+ parent.left = frag as unknown as Expression;
+ return true;
+ }
+
+ if (parent.right === node) {
+ parent.right = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInConditionalExpression = (
+ parent: ConditionalExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.consequent === node) {
+ parent.consequent = frag as unknown as Expression;
+ return true;
+ }
+
+ if (parent.alternate === node) {
+ parent.alternate = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInArrowFunctionExpression = (
+ parent: ArrowFunctionExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.body === node) {
+ parent.body = frag as ArrowFunctionExpression['body'];
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInReturnStatement = (
+ parent: ReturnStatement,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.argument === node) {
+ parent.argument = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInCallExpression = (
+ parent: CallExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInOptionalCallExpression = (
+ parent: OptionalCallExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInArrayExpression = (
+ parent: ArrayExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.elements.indexOf(node);
+ if (idx !== -1) {
+ parent.elements.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInAssignmentExpression = (
+ parent: AssignmentExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.right === node) {
+ parent.right = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInVariableDeclarator = (
+ parent: VariableDeclarator,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.init === node) {
+ parent.init = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInExportDefaultDeclaration = (
+ parent: ExportDefaultDeclaration,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.declaration === node) {
+ parent.declaration =
+ frag as unknown as ExportDefaultDeclaration['declaration'];
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInSequenceExpression = (
+ parent: SequenceExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.expressions.indexOf(node);
+ if (idx !== -1) {
+ parent.expressions.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInNewExpression = (
+ parent: NewExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.arguments.indexOf(node);
+ if (idx !== -1) {
+ parent.arguments.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInExpressionStatement = (
+ parent: ExpressionStatement,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.expression === node) {
+ parent.expression = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInParenthesizedExpression = (
+ parent: ParenthesizedExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.expression === node) {
+ parent.expression = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInJSXExpressionContainer = (
+ parent: JSXExpressionContainer,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.expression === node) {
+ parent.expression = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInTSAsExpression = (
+ parent: TSAsExpression,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const frag = makeFragment(node, clone);
+ if (parent.expression === node) {
+ parent.expression = frag as unknown as Expression;
+ return true;
+ }
+
+ return false;
+};
+
+const duplicateInJSXParentChildren = (
+ parent: JSXElement | JSXFragment,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ const idx = parent.children.indexOf(node);
+ if (idx !== -1) {
+ parent.children.splice(idx + 1, 0, clone);
+ return true;
+ }
+
+ return false;
+};
+
+const insertDuplicateForParent = (
+ parentNode: Node,
+ node: JSXElement,
+ clone: JSXElement,
+): boolean => {
+ if (namedTypes.LogicalExpression.check(parentNode)) {
+ return duplicateInLogicalExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.ConditionalExpression.check(parentNode)) {
+ return duplicateInConditionalExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.ArrowFunctionExpression.check(parentNode)) {
+ return duplicateInArrowFunctionExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.ReturnStatement.check(parentNode)) {
+ return duplicateInReturnStatement(parentNode, node, clone);
+ }
+
+ if (namedTypes.CallExpression.check(parentNode)) {
+ return duplicateInCallExpression(parentNode, node, clone);
+ }
+
+ if (parentNode.type === 'OptionalCallExpression') {
+ return duplicateInOptionalCallExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.ArrayExpression.check(parentNode)) {
+ return duplicateInArrayExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.AssignmentExpression.check(parentNode)) {
+ return duplicateInAssignmentExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.VariableDeclarator.check(parentNode)) {
+ return duplicateInVariableDeclarator(parentNode, node, clone);
+ }
+
+ if (namedTypes.ExportDefaultDeclaration.check(parentNode)) {
+ return duplicateInExportDefaultDeclaration(parentNode, node, clone);
+ }
+
+ if (namedTypes.SequenceExpression.check(parentNode)) {
+ return duplicateInSequenceExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.NewExpression.check(parentNode)) {
+ return duplicateInNewExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.ExpressionStatement.check(parentNode)) {
+ return duplicateInExpressionStatement(parentNode, node, clone);
+ }
+
+ if (namedTypes.ParenthesizedExpression.check(parentNode)) {
+ return duplicateInParenthesizedExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.JSXExpressionContainer.check(parentNode)) {
+ return duplicateInJSXExpressionContainer(parentNode, node, clone);
+ }
+
+ if (namedTypes.TSAsExpression.check(parentNode)) {
+ return duplicateInTSAsExpression(parentNode, node, clone);
+ }
+
+ if (namedTypes.JSXElement.check(parentNode)) {
+ return duplicateInJSXParentChildren(parentNode, node, clone);
+ }
+
+ if (namedTypes.JSXFragment.check(parentNode)) {
+ return duplicateInJSXParentChildren(parentNode, node, clone);
+ }
+
+ return false;
+};
+
+export const duplicateJsxElementAtPath = (
+ jsxPath: recast.types.NodePath,
+): void => {
+ const {node, parentPath} = jsxPath;
+ if (!parentPath) {
+ throw new Error('Cannot duplicate JSX element with no parent');
+ }
+
+ const jsxNode = node as JSXElement;
+ const clone = cloneNode(jsxNode, true) as JSXElement;
+ uniquifyNamePropOnClone(clone);
+
+ if (insertDuplicateForParent(parentPath.node, jsxNode, clone)) {
+ return;
+ }
+
+ jsxPath.replace(makeFragment(jsxNode, clone));
+};
+
+export const duplicateJsxNode = async ({
+ input,
+ nodePath,
+ prettierConfigOverride,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ nodeLabel: string;
+ logLine: number;
+}> => {
+ const ast = parseAst(input);
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to duplicate',
+ );
+ }
+
+ const jsxElement = jsxPath.node as JSXElement;
+ const nodeLabel = getJsxElementTagLabel(jsxElement);
+ const logLine =
+ jsxElement.openingElement.loc?.start.line ??
+ jsxElement.loc?.start.line ??
+ 1;
+
+ duplicateJsxElementAtPath(jsxPath);
+
+ const finalFile = serializeAst(ast);
+
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
+ type PrettierType = typeof import('prettier');
+ let prettier: PrettierType | null = null;
+
+ try {
+ prettier = await import('prettier');
+ } catch {
+ return {
+ output: finalFile,
+ formatted: false,
+ nodeLabel,
+ logLine,
+ };
+ }
+
+ const {format, resolveConfig, resolveConfigFile} = prettier as PrettierType;
+
+ let prettierConfig: Record<string, unknown> | null;
+
+ if (prettierConfigOverride !== undefined) {
+ prettierConfig = prettierConfigOverride;
+ } else {
+ const configFilePath = await resolveConfigFile();
+ if (!configFilePath) {
+ return {
+ output: finalFile,
+ formatted: false,
+ nodeLabel,
+ logLine,
+ };
+ }
+
+ prettierConfig = await resolveConfig(configFilePath);
+ }
+
+ if (!prettierConfig) {
+ return {
+ output: finalFile,
+ formatted: false,
+ nodeLabel,
+ logLine,
+ };
+ }
+
+ const prettified = await format(finalFile, {
+ ...prettierConfig,
+ filepath: 'test.tsx',
+ plugins: [],
+ endOfLine: 'lf',
+ });
+
+ return {
+ output: prettified,
+ formatted: true,
+ nodeLabel,
+ logLine,
+ };
+};
diff --git a/packages/studio-server/src/codemods/jsx-sequence-context.ts b/packages/studio-server/src/codemods/jsx-sequence-context.ts
new file mode 100644
index 0000000000..93518dc88c
--- /dev/null
+++ b/packages/studio-server/src/codemods/jsx-sequence-context.ts
@@ -0,0 +1,102 @@
+import type {
+ CallExpression,
+ Expression,
+ File,
+ Node,
+ OptionalCallExpression,
+ ParenthesizedExpression,
+ TSAsExpression,
+} from '@babel/types';
+import type {SequenceNodePath} from '@remotion/studio-shared';
+import type {types as RecastTypes} from 'recast';
+import {findJsxElementPathForDeletion} from './delete-jsx-node';
+
+const unwrapExpression = (expr: Expression): Expression => {
+ if (expr.type === 'TSAsExpression') {
+ return unwrapExpression((expr as TSAsExpression).expression as Expression);
+ }
+
+ if (expr.type === 'ParenthesizedExpression') {
+ return unwrapExpression(
+ (expr as ParenthesizedExpression).expression as Expression,
+ );
+ }
+
+ return expr;
+};
+
+/**
+ * Whether the callee is a `.map(...)` member call (including optional `?.map`).
+ */
+export const isMapCallee = (callee: Expression): boolean => {
+ const c = unwrapExpression(callee);
+ if (c.type === 'MemberExpression') {
+ if (c.computed) {
+ return c.property.type === 'StringLiteral' && c.property.value === 'map';
+ }
+
+ return c.property.type === 'Identifier' && c.property.name === 'map';
+ }
+
+ if (c.type === 'OptionalMemberExpression') {
+ if (c.computed) {
+ return c.property.type === 'StringLiteral' && c.property.value === 'map';
+ }
+
+ return c.property.type === 'Identifier' && c.property.name === 'map';
+ }
+
+ return false;
+};
+
+/**
+ * True when the JSX element at `nodePath` is defined inside a `.map()` callback
+ * (array iteration). Used to flag duplicate / edit behavior for list-driven JSX.
+ */
+export const isJsxUnderMapCallback = (
+ ast: File,
+ nodePath: SequenceNodePath,
+): boolean => {
+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!jsxPath) {
+ return false;
+ }
+
+ let path: RecastTypes.NodePath | null = jsxPath.parentPath;
+ while (path) {
+ const n = path.node as Node;
+ if (
+ n.type === 'ArrowFunctionExpression' ||
+ n.type === 'FunctionExpression'
+ ) {
+ const outer = path.parentPath;
+ if (outer?.node.type === 'CallExpression') {
+ const call = outer.node;
+ if (
+ isMapCallee(call.callee as Expression) &&
+ call.arguments.some(
+ (arg: CallExpression['arguments'][number]) => arg === n,
+ )
+ ) {
+ return true;
+ }
+ }
+
+ if (outer?.node.type === 'OptionalCallExpression') {
+ const call = outer.node as OptionalCallExpression;
+ if (
+ isMapCallee(call.callee as Expression) &&
+ call.arguments.some(
+ (arg: CallExpression['arguments'][number]) => arg === n,
+ )
+ ) {
+ return true;
+ }
+ }
+ }
+
+ path = path.parentPath;
+ }
+
+ return false;
+};
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index f583b98fe1..38a2cae7c1 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -6,6 +6,7 @@ import {applyVisualControlHandler} from './routes/apply-visual-control-change';
import {handleCancelRender} from './routes/cancel-render';
import {deleteJsxNodeHandler} from './routes/delete-jsx-node';
import {deleteStaticFileHandler} from './routes/delete-static-file';
+import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';
import {handleInstallPackage} from './routes/install-dependency';
import {handleOpenInFileExplorer} from './routes/open-in-file-explorer';
import {projectInfoHandler} from './routes/project-info';
@@ -44,6 +45,7 @@ export const allApiRoutes: {
'/api/unsubscribe-from-sequence-props': unsubscribeFromSequenceProps,
'/api/save-sequence-props': saveSequencePropsHandler,
'/api/delete-jsx-node': deleteJsxNodeHandler,
+ '/api/duplicate-jsx-node': duplicateJsxNodeHandler,
'/api/update-available': handleUpdate,
'/api/project-info': projectInfoHandler,
'/api/delete-static-file': deleteStaticFileHandler,
diff --git a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
index 125ab81efe..fbb7d9dc27 100644
--- a/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.ts
@@ -16,6 +16,7 @@ import type {
} from '@remotion/studio-shared';
import * as recast from 'recast';
import type {CanUpdateSequencePropStatus} from 'remotion';
+import {isJsxUnderMapCallback} from '../../codemods/jsx-sequence-context';
import {parseAst} from '../../codemods/parse-ast';
type CanUpdatePropStatus = CanUpdateSequencePropStatus;
@@ -337,6 +338,7 @@ export const computeSequencePropsStatusFromContent = (
canUpdate: true as const,
props: filteredProps,
nodePath,
+ jsxInMapCallback: isJsxUnderMapCallback(ast, nodePath),
};
};
diff --git a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
new file mode 100644
index 0000000000..30c2e240c2
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts
@@ -0,0 +1,87 @@
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ DuplicateJsxNodeRequest,
+ DuplicateJsxNodeResponse,
+} from '@remotion/studio-shared';
+import {duplicateJsxNode} from '../../codemods/duplicate-jsx-node';
+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
+import type {ApiHandler} from '../api-types';
+import {formatLogFileLocation} from '../format-log-file-location';
+import {
+ printUndoHint,
+ pushToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {warnAboutPrettierOnce} from './log-update';
+
+export const duplicateJsxNodeHandler: ApiHandler<
+ DuplicateJsxNodeRequest,
+ DuplicateJsxNodeResponse
+> = async ({input: {fileName, nodePath}, remotionRoot, logLevel}) => {
+ try {
+ RenderInternals.Log.trace(
+ {indent: false, logLevel},
+ `[duplicate-jsx-node] Received request for fileName="${fileName}"`,
+ );
+ const absolutePath = path.resolve(remotionRoot, fileName);
+ const fileRelativeToRoot = path.relative(remotionRoot, absolutePath);
+ if (fileRelativeToRoot.startsWith('..')) {
+ throw new Error('Cannot modify a file outside the project');
+ }
+
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+
+ const {output, formatted, nodeLabel, logLine} = await duplicateJsxNode({
+ input: fileContents,
+ nodePath,
+ });
+
+ pushToUndoStack({
+ filePath: absolutePath,
+ oldContents: fileContents,
+ logLevel,
+ remotionRoot,
+ logLine,
+ description: {
+ undoMessage: `Undid duplication of ${nodeLabel}`,
+ redoMessage: `Redid duplication of ${nodeLabel}`,
+ },
+ entryType: 'duplicate-jsx-node',
+ suppressHmrOnFileRestore: false,
+ });
+ suppressUndoStackInvalidation(absolutePath);
+ writeFileAndNotifyFileWatchers(absolutePath, output);
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${RenderInternals.chalk.blueBright(`${locationLabel}:`)} Duplicated ${nodeLabel}`,
+ );
+ if (!formatted) {
+ warnAboutPrettierOnce(logLevel);
+ }
+
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[duplicate-jsx-node] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,
+ );
+
+ printUndoHint(logLevel);
+
+ return {
+ success: true,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ reason: (err as Error).message,
+ stack: (err as Error).stack as string,
+ };
+ }
+};
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index c5e3ac3140..45ac822493 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -20,7 +20,8 @@ type UndoEntryType =
| 'visual-control'
| 'default-props'
| 'sequence-props'
- | 'delete-jsx-node';
+ | 'delete-jsx-node'
+ | 'duplicate-jsx-node';
type UndoEntry = {
filePath: string;
@@ -35,6 +36,7 @@ type UndoEntry = {
| {entryType: 'default-props'}
| {entryType: 'sequence-props'}
| {entryType: 'delete-jsx-node'}
+ | {entryType: 'duplicate-jsx-node'}
);
const MAX_ENTRIES = 100;
diff --git a/packages/studio-server/src/test/compute-sequence-props-status.test.ts b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
index 00b1a8fdcc..32768dbd4d 100644
--- a/packages/studio-server/src/test/compute-sequence-props-status.test.ts
+++ b/packages/studio-server/src/test/compute-sequence-props-status.test.ts
@@ -4,8 +4,10 @@ import path from 'node:path';
import {parseAst} from '../codemods/parse-ast';
import {
computeSequencePropsStatus,
+ computeSequencePropsStatusFromContent,
lineColumnToNodePath,
} from '../preview-server/routes/can-update-sequence-props';
+import {lineColumnToNodePath as lineColumnToNodePathFromString} from './test-utils';
const getNodePath = (filePath: string, line: number) => {
const content = readFileSync(filePath, 'utf-8');
@@ -144,3 +146,41 @@ test('computeSequencePropsStatus should report unset when parent attribute missi
codeValue: undefined,
});
});
+
+test('jsxInMapCallback is true when JSX is inside a .map callback', () => {
+ const src = `import React from 'react';
+export const X = () => (
+ <>
+ {[1].map((i) => (
+ <div key={i} />
+ ))}
+ </>
+);
+`;
+ const nodePath = lineColumnToNodePathFromString(src, 5);
+ const result = computeSequencePropsStatusFromContent(src, nodePath, [
+ 'children',
+ ]);
+ expect(result.canUpdate).toBe(true);
+ if (!result.canUpdate) {
+ throw new Error('Expected canUpdate to be true');
+ }
+
+ expect(result.jsxInMapCallback).toBe(true);
+});
+
+test('jsxInMapCallback is false for JSX outside .map', () => {
+ const src = `import React from 'react';
+export const X = () => <div />;
+`;
+ const nodePath = lineColumnToNodePathFromString(src, 2);
+ const result = computeSequencePropsStatusFromContent(src, nodePath, [
+ 'children',
+ ]);
+ expect(result.canUpdate).toBe(true);
+ if (!result.canUpdate) {
+ throw new Error('Expected canUpdate to be true');
+ }
+
+ expect(result.jsxInMapCallback).toBe(false);
+});
diff --git a/packages/studio-server/src/test/duplicate-jsx-node.test.ts b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
new file mode 100644
index 0000000000..6d40341502
--- /dev/null
+++ b/packages/studio-server/src/test/duplicate-jsx-node.test.ts
@@ -0,0 +1,67 @@
+import {expect, test} from 'bun:test';
+import {duplicateJsxNode} from '../codemods/duplicate-jsx-node';
+import {lineColumnToNodePath} from './test-utils';
+
+const sample = `import React from 'react';
+import {AbsoluteFill} from 'remotion';
+
+export const X: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <div />
+ </AbsoluteFill>
+ );
+};
+`;
+
+test('duplicateJsxNode inserts a sibling JSX element', async () => {
+ const {output} = await duplicateJsxNode({
+ input: sample,
+ nodePath: lineColumnToNodePath(sample, 7),
+ });
+
+ const divOpens = output.match(/<div/g);
+ expect(divOpens?.length).toBe(2);
+ expect(output).toContain('<AbsoluteFill>');
+});
+
+const onlyReturn = `import React from 'react';
+
+export const X: React.FC = () => {
+ return <div />;
+};
+`;
+
+test('duplicateJsxNode wraps sole return JSX in a fragment with two elements', async () => {
+ const {output} = await duplicateJsxNode({
+ input: onlyReturn,
+ nodePath: lineColumnToNodePath(onlyReturn, 4),
+ });
+
+ expect(output).toMatch(/return\s*\(?\s*</);
+ const divOpens = output.match(/<div/g);
+ expect(divOpens?.length).toBe(2);
+});
+
+const mapCase = `import React from 'react';
+
+export const X: React.FC = () => {
+ return (
+ <>
+ {[1].map((i) => (
+ <div key={i} />
+ ))}
+ </>
+ );
+};
+`;
+
+test('duplicateJsxNode duplicates JSX inside map callback', async () => {
+ const {output} = await duplicateJsxNode({
+ input: mapCase,
+ nodePath: lineColumnToNodePath(mapCase, 7),
+ });
+
+ const divOpens = output.match(/<div/g);
+ expect(divOpens?.length).toBe(2);
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index fe4ff6f6bc..378ff1c768 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -230,6 +230,8 @@ export type CanUpdateSequencePropsResponse =
canUpdate: true;
props: Record<string, CanUpdateSequencePropStatus>;
nodePath: SequenceNodePath;
+ /** True when the JSX is inside a `.map()` callback (list iteration). */
+ jsxInMapCallback: boolean;
}
| {
canUpdate: false;
@@ -271,6 +273,21 @@ export type DeleteJsxNodeResponse =
stack: string;
};
+export type DuplicateJsxNodeRequest = {
+ fileName: string;
+ nodePath: SequenceNodePath;
+};
+
+export type DuplicateJsxNodeResponse =
+ | {
+ success: true;
+ }
+ | {
+ success: false;
+ reason: string;
+ stack: string;
+ };
+
export type UpdateAvailableRequest = {};
export type UpdateAvailableResponse = {
currentVersion: string;
@@ -358,6 +375,10 @@ export type ApiRoutes = {
DeleteJsxNodeRequest,
DeleteJsxNodeResponse
>;
+ '/api/duplicate-jsx-node': ReqAndRes<
+ DuplicateJsxNodeRequest,
+ DuplicateJsxNodeResponse
+ >;
'/api/update-available': ReqAndRes<
UpdateAvailableRequest,
UpdateAvailableResponse
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index ab66d1a2fd..198b680d3e 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -17,6 +17,8 @@ export {
CopyStillToClipboardRequest,
DeleteJsxNodeRequest,
DeleteJsxNodeResponse,
+ DuplicateJsxNodeRequest,
+ DuplicateJsxNodeResponse,
DeleteStaticFileRequest,
DeleteStaticFileResponse,
InstallPackageRequest,
diff --git a/packages/studio/src/components/Timeline/TimelineListItem.tsx b/packages/studio/src/components/Timeline/TimelineListItem.tsx
index aeb4ac830b..37d18768b4 100644
--- a/packages/studio/src/components/Timeline/TimelineListItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineListItem.tsx
@@ -61,7 +61,7 @@ export const TimelineListItem: React.FC<{
const {expandedTracks, toggleTrack} = useContext(ExpandedTracksContext);
const originalLocation = useResolvedStack(sequence.stack ?? null);
- const nodePath = useSequencePropsSubscription(
+ const {nodePath, jsxInMapCallback} = useSequencePropsSubscription(
sequence,
originalLocation,
visualModeActive,
@@ -90,6 +90,37 @@ export const TimelineListItem: React.FC<{
[previewConnected, sequence.controls, canDeleteFromSource],
);
+ const duplicateDisabled = deleteDisabled;
+
+ const onDuplicateSequenceFromSource = useCallback(async () => {
+ if (!validatedLocation?.source || !nodePath) {
+ return;
+ }
+
+ if (
+ jsxInMapCallback &&
+ !window.confirm(
+ 'This sequence is rendered inside a .map() callback. Duplicating inserts another copy in that callback (affecting each list item). Continue?',
+ )
+ ) {
+ return;
+ }
+
+ try {
+ const result = await callApi('/api/duplicate-jsx-node', {
+ fileName: validatedLocation.source,
+ nodePath,
+ });
+ if (result.success) {
+ showNotification('Duplicated sequence in source file', 2000);
+ } else {
+ showNotification(result.reason, 4000);
+ }
+ } catch (err) {
+ showNotification((err as Error).message, 4000);
+ }
+ }, [jsxInMapCallback, nodePath, validatedLocation?.source]);
+
const onDeleteSequenceFromSource = useCallback(async () => {
if (!validatedLocation?.source || !nodePath) {
return;
@@ -116,6 +147,24 @@ export const TimelineListItem: React.FC<{
}
return [
+ {
+ type: 'item',
+ id: 'duplicate-sequence',
+ keyHint: null,
+ label: 'Duplicate',
+ leftItem: null,
+ disabled: duplicateDisabled,
+ onClick: () => {
+ if (duplicateDisabled) {
+ return;
+ }
+
+ void onDuplicateSequenceFromSource();
+ },
+ quickSwitcherLabel: null,
+ subMenu: null,
+ value: 'duplicate-sequence',
+ },
{
type: 'item',
id: 'delete-sequence',
@@ -135,7 +184,13 @@ export const TimelineListItem: React.FC<{
value: 'delete-sequence',
},
];
- }, [deleteDisabled, onDeleteSequenceFromSource, visualModeEnvEnabled]);
+ }, [
+ deleteDisabled,
+ duplicateDisabled,
+ onDeleteSequenceFromSource,
+ onDuplicateSequenceFromSource,
+ visualModeEnvEnabled,
+ ]);
const isExpanded = visualModeActive && (expandedTracks[sequence.id] ?? false);
diff --git a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
index 9094c92fcb..2d22427ce1 100644
--- a/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
+++ b/packages/studio/src/components/Timeline/use-sequence-props-subscription.ts
@@ -18,7 +18,10 @@ export const useSequencePropsSubscription = (
sequence: TSequence,
originalLocation: OriginalPosition | null,
visualModeEnabled: boolean,
-): SequenceNodePath | null => {
+): {
+ nodePath: SequenceNodePath | null;
+ jsxInMapCallback: boolean;
+} => {
const {setCodeValues} = useContext(Internals.VisualModeOverridesContext);
const overrideId = sequence.controls?.overrideId ?? null;
@@ -77,6 +80,7 @@ export const useSequencePropsSubscription = (
const nodePathRef = useRef<SequenceNodePath | null>(null);
const [nodePath, setNodePath] = useState<SequenceNodePath | null>(null);
+ const [jsxInMapCallback, setJsxInMapCallback] = useState(false);
const isMountedRef = useRef(true);
const setNodePathBoth = useCallback((next: SequenceNodePath | null) => {
@@ -95,6 +99,7 @@ export const useSequencePropsSubscription = (
if (!visualModeEnabled) {
setPropStatusesForSequence(null);
setNodePathBoth(null);
+ setJsxInMapCallback(false);
return;
}
@@ -107,6 +112,7 @@ export const useSequencePropsSubscription = (
) {
setPropStatusesForSequence(null);
setNodePathBoth(null);
+ setJsxInMapCallback(false);
return;
}
@@ -131,13 +137,16 @@ export const useSequencePropsSubscription = (
if (result.canUpdate) {
setNodePathBoth(result.nodePath);
setPropStatusesForSequence(result.props);
+ setJsxInMapCallback(result.jsxInMapCallback);
} else {
setNodePathBoth(null);
setPropStatusesForSequence(null);
+ setJsxInMapCallback(false);
}
})
.catch((err) => {
setNodePathBoth(null);
+ setJsxInMapCallback(false);
Internals.Log.error(err);
setPropStatusesForSequence(null);
});
@@ -151,6 +160,7 @@ export const useSequencePropsSubscription = (
}
setNodePathBoth(null);
+ setJsxInMapCallback(false);
if (currentNodePath) {
callApi('/api/unsubscribe-from-sequence-props', {
fileName: locationSource,
@@ -196,9 +206,11 @@ export const useSequencePropsSubscription = (
if (event.result.canUpdate) {
setPropStatusesForSequence(event.result.props);
+ setJsxInMapCallback(event.result.jsxInMapCallback);
} else {
setPropStatusesForSequence(null);
setNodePathBoth(null);
+ setJsxInMapCallback(false);
}
};
@@ -216,5 +228,5 @@ export const useSequencePropsSubscription = (
setNodePathBoth,
]);
- return nodePath;
+ return {nodePath, jsxInMapCallback};
};