🎥 Make videos programmatically with React
Fixes #7324
JonnyBurger08362cb00181
diff --git a/packages/core/src/SequenceManager.tsx b/packages/core/src/SequenceManager.tsxindex 681908d060..9a899662ac 100644--- a/packages/core/src/SequenceManager.tsx+++ b/packages/core/src/SequenceManager.tsx@@ -47,7 +47,6 @@ export type VisualModeGetters = {visualModeEnabled: boolean;getDragOverrides: GetDragOverrides;getCodeValues: GetCodeValues;- getIsJsxInMapCallback: (nodePath: SequenceNodePath) => boolean;};export type VisualModeSetters = {@@ -68,8 +67,6 @@ 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;@@ -89,22 +86,6 @@ const getCodeValues = (codeValues: CodeValues, nodePath: SequenceNodePath) => {return status.props;};-const getIsJsxInMapCallback = (- codeValues: CodeValues,- nodePath: SequenceNodePath,-) => {- const status = codeValues[nodePathToString(nodePath)];- if (!status) {- return false;- }-- if (!status.canUpdate) {- return false;- }-- return status.jsxInMapCallback;-};-export type GetCodeValuesType = typeof getCodeValues;export const VisualModeGettersContext = React.createContext<VisualModeGetters>({@@ -114,9 +95,6 @@ export const VisualModeGettersContext = React.createContext<VisualModeGetters>({getCodeValues: () => {throw new Error('VisualModeGettersContext not initialized');},- getIsJsxInMapCallback: () => {- throw new Error('VisualModeGettersContext not initialized');- },visualModeEnabled: false,});@@ -216,8 +194,6 @@ export const SequenceManagerProvider: React.FC<{dragOverrides[nodePathToString(nodePath)] ?? {},getCodeValues: (nodePath: SequenceNodePath) =>getCodeValues(codeValues, nodePath),- getIsJsxInMapCallback: (nodePath: SequenceNodePath) =>- getIsJsxInMapCallback(codeValues, nodePath),};}, [visualModeEnabled, dragOverrides, codeValues]);diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsxindex c4cc0ce4ad..37969d4286 100644--- a/packages/core/src/test/sequence-register-once.test.tsx+++ b/packages/core/src/test/sequence-register-once.test.tsx@@ -46,9 +46,6 @@ test('Sequence calls registerSequence exactly once on mount', () => {getCodeValues: () => {throw new Error('VisualModeGettersContext not initialized');},- getIsJsxInMapCallback: () => {- throw new Error('VisualModeGettersContext not initialized');- },}),[],);diff --git a/packages/core/src/use-schema.ts b/packages/core/src/use-schema.tsindex 9c6405fefc..c22a4e0c37 100644--- a/packages/core/src/use-schema.ts+++ b/packages/core/src/use-schema.ts@@ -19,8 +19,6 @@ export type GetCodeValues = (nodePath: SequenceNodePath,) => Record<string, CanUpdateSequencePropStatus> | undefined;-export type GetIsJsxInMapCallback = (nodePath: SequenceNodePath) => boolean;-export type GetDragOverrides = (nodePath: SequenceNodePath,) => DragOverrides[string];diff --git a/packages/studio-server/src/codemods/jsx-sequence-context.ts b/packages/studio-server/src/codemods/jsx-sequence-context.tsdeleted file mode 100644index e104c819ef..0000000000--- a/packages/studio-server/src/codemods/jsx-sequence-context.ts+++ /dev/null@@ -1,102 +0,0 @@-import type {- CallExpression,- Expression,- File,- Node,- OptionalCallExpression,- ParenthesizedExpression,- TSAsExpression,-} from '@babel/types';-import type {types as RecastTypes} from 'recast';-import type {SequenceNodePath} from 'remotion';-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/routes/can-update-sequence-props.ts b/packages/studio-server/src/preview-server/routes/can-update-sequence-props.tsindex 6dd810004f..f021b07540 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@@ -13,7 +13,6 @@ import type {import * as recast from 'recast';import type {CanUpdateSequencePropsResponse, SequenceNodePath} from 'remotion';import type {CanUpdateSequencePropStatus} from 'remotion';-import {isJsxUnderMapCallback} from '../../codemods/jsx-sequence-context';import {parseAst} from '../../codemods/parse-ast';import {getAstNodePath} from '../../helpers/get-ast-node-path';@@ -333,7 +332,6 @@ export const computeSequencePropsStatusFromContent = (canUpdate: true as const,props: filteredProps,nodePath,- jsxInMapCallback: isJsxUnderMapCallback(ast, nodePath),};};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.tsindex 32768dbd4d..00b1a8fdcc 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,10 +4,8 @@ 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');@@ -146,41 +144,3 @@ test('computeSequencePropsStatus should report unset when parent attribute missicodeValue: 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/src/components/Timeline/TimelineListItem.tsx b/packages/studio/src/components/Timeline/TimelineListItem.tsxindex db191c5f72..3d9328e729 100644--- a/packages/studio/src/components/Timeline/TimelineListItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineListItem.tsx@@ -47,9 +47,6 @@ export const TimelineListItem: React.FC<{);const {getIsExpanded} = useContext(ExpandedTracksGetterContext);const {toggleTrack} = useContext(ExpandedTracksSetterContext);- const {getIsJsxInMapCallback} = useContext(- Internals.VisualModeGettersContext,- );const originalLocation = useResolvedStack(sequence.stack ?? null);@@ -83,9 +80,11 @@ export const TimelineListItem: React.FC<{return;}- if (getIsJsxInMapCallback(nodePath)) {+ if (nodePathInfo && nodePathInfo.numberOfSequencesWithThisNodePath > 1) {const message =- 'This sequence is rendered inside a .map() callback. Duplicating inserts another copy in that callback (affecting each list item). Continue?';+ 'This sequence is programmatically duplicated ' ++ nodePathInfo.numberOfSequencesWithThisNodePath ++ ' times in the code. Duplicating inserts another copy. Continue?';// eslint-disable-next-line no-alert -- native confirm before applying duplicate codemod in .map callbacksif (!window.confirm(message)) {return;@@ -105,16 +104,18 @@ export const TimelineListItem: React.FC<{} catch (err) {showNotification((err as Error).message, 4000);}- }, [nodePath, validatedLocation?.source, getIsJsxInMapCallback]);+ }, [nodePath, validatedLocation?.source, nodePathInfo]);const onDeleteSequenceFromSource = useCallback(async () => {if (!validatedLocation?.source || !nodePath) {return;}- if (getIsJsxInMapCallback(nodePath)) {+ if (nodePathInfo && nodePathInfo.numberOfSequencesWithThisNodePath > 1) {const message =- 'This sequence is rendered inside a .map() callback. Deleting removes all sequences in that callback. Continue?';+ 'This sequence is programmatically duplicated ' ++ nodePathInfo.numberOfSequencesWithThisNodePath ++ ' times in the code. Deleting removes all instances. Continue?';// eslint-disable-next-line no-alert -- native confirm before applying duplicate codemod in .map callbacksif (!window.confirm(message)) {return;@@ -134,7 +135,7 @@ export const TimelineListItem: React.FC<{} catch (err) {showNotification((err as Error).message, 4000);}- }, [nodePath, validatedLocation?.source, getIsJsxInMapCallback]);+ }, [nodePath, validatedLocation?.source, nodePathInfo]);const contextMenuValues = useMemo((): ComboboxValue[] => {if (!visualModeEnvEnabled) {diff --git a/packages/studio/src/helpers/calculate-timeline.ts b/packages/studio/src/helpers/calculate-timeline.tsindex c28258cd25..cf045ef9c3 100644--- a/packages/studio/src/helpers/calculate-timeline.ts+++ b/packages/studio/src/helpers/calculate-timeline.ts@@ -96,7 +96,9 @@ export const calculateTimeline = ({hash: actualHash,cascadedStart,cascadedDuration: sequence.duration,- nodePathInfo: nodePath ? {nodePath, index: 0} : null,+ nodePathInfo: nodePath+ ? {nodePath, index: 0, numberOfSequencesWithThisNodePath: 0}+ : null,});}@@ -130,17 +132,40 @@ export const calculateTimeline = ({});const nodePathIndexCounters = new Map<string, number>();- return sortedTracks.map((track): TrackWithHash => {- if (track.nodePathInfo === null) {- return track;- }- const key = JSON.stringify(track.nodePathInfo.nodePath);- const index = nodePathIndexCounters.get(key) ?? 0;- nodePathIndexCounters.set(key, index + 1);- return {- ...track,- nodePathInfo: {nodePath: track.nodePathInfo.nodePath, index},- };- });+ return sortedTracks+ .map((track): TrackWithHash => {+ if (track.nodePathInfo === null) {+ return track;+ }++ const key = track.nodePathInfo.nodePath.join('.');+ const index = nodePathIndexCounters.get(key) ?? 0;+ nodePathIndexCounters.set(key, index + 1);+ return {+ ...track,+ nodePathInfo: {+ nodePath: track.nodePathInfo.nodePath,+ index,+ numberOfSequencesWithThisNodePath: 0,+ },+ };+ })+ .map((track) => {+ if (track.nodePathInfo === null) {+ return track;+ }++ const key = track.nodePathInfo.nodePath.join('.');++ return {+ ...track,+ nodePathInfo: {+ nodePath: track.nodePathInfo.nodePath,+ index: track.nodePathInfo.index,+ numberOfSequencesWithThisNodePath:+ nodePathIndexCounters.get(key) ?? 0,+ },+ };+ });};diff --git a/packages/studio/src/helpers/get-timeline-sequence-sort-key.ts b/packages/studio/src/helpers/get-timeline-sequence-sort-key.tsindex 4b18809cdd..a22af0e468 100644--- a/packages/studio/src/helpers/get-timeline-sequence-sort-key.ts+++ b/packages/studio/src/helpers/get-timeline-sequence-sort-key.ts@@ -3,6 +3,7 @@ import type {SequenceNodePath, TSequence} from 'remotion';export type SequenceNodePathInfo = {nodePath: SequenceNodePath;index: number;+ numberOfSequencesWithThisNodePath: number;};type Track = {diff --git a/packages/studio/src/helpers/timeline-layout.ts b/packages/studio/src/helpers/timeline-layout.tsindex 77b9c70708..6cac31c39d 100644--- a/packages/studio/src/helpers/timeline-layout.ts+++ b/packages/studio/src/helpers/timeline-layout.ts@@ -80,13 +80,21 @@ export const buildTimelineTree = ({if (sequence.effects.length > 0) {roots.push({kind: 'group',- nodePathInfo: {nodePath: [...nodePath, 'effects'], index},+ nodePathInfo: {+ nodePath: [...nodePath, 'effects'],+ index,+ numberOfSequencesWithThisNodePath: 0,+ },label: 'Effects',children: sequence.effects.map((effect, i): TimelineTreeNode => {const effectNodePath = [...nodePath, 'effects', i];return {kind: 'group',- nodePathInfo: {nodePath: effectNodePath, index},+ nodePathInfo: {+ nodePath: effectNodePath,+ index,+ numberOfSequencesWithThisNodePath: 0,+ },label: effect.definition.label,children: getEffectSchemaLabels(effect).map((label): TimelineTreeNode => ({@@ -94,6 +102,7 @@ export const buildTimelineTree = ({nodePathInfo: {nodePath: [...effectNodePath, label.key],index,+ numberOfSequencesWithThisNodePath: 0,},label: label.description ?? label.key,field: null,@@ -117,7 +126,11 @@ export const buildTimelineTree = ({for (const f of controlFields) {roots.push({kind: 'field',- nodePathInfo: {nodePath: [...nodePath, 'controls', f.key], index},+ nodePathInfo: {+ nodePath: [...nodePath, 'controls', f.key],+ index,+ numberOfSequencesWithThisNodePath: 0,+ },label: f.description ?? f.key,field: f,});