🎥 Make videos programmatically with React
`@remotion/studio`: Add split clip source edits and serialize writes (#8715)
Jonny Burger1305e6cfa58a
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.tsnew file mode 100644index 0000000000..176cf48fb4--- /dev/null+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts@@ -0,0 +1,459 @@+import type {+ ArrowFunctionExpression,+ Expression,+ JSXAttribute,+ JSXElement,+ JSXExpressionContainer,+ JSXFragment,+ JSXIdentifier,+ JSXMemberExpression,+ JSXNamespacedName,+ Node,+ ReturnStatement,+} from '@babel/types';+import {cloneNode} from '@babel/types';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import {+ findJsxElementPathForDeletion,+ getJsxElementTagLabel,+} from './delete-jsx-node';+import {formatFileContent} from './format-file-content';+import {parseAst, serializeAst} from './parse-ast';++const {builders: b, namedTypes} = recast.types;++type SequenceTiming = {+ from: number;+ durationInFrames: number;+ trimBefore: number;+ hasFrom: boolean;+ hasDurationInFrames: boolean;+ hasTrimBefore: boolean;+};++const jsxId = (name: string) => ({type: 'JSXIdentifier' as const, name});++const numericAttribute = (name: string, value: number): JSXAttribute => ({+ type: 'JSXAttribute',+ name: jsxId(name),+ value: {+ type: 'JSXExpressionContainer',+ expression:+ value === Infinity ? b.identifier('Infinity') : b.numericLiteral(value),+ } as JSXExpressionContainer,+});++const getAttributeName = (+ attribute: JSXElement['openingElement']['attributes'][number],+) => {+ if (+ attribute.type !== 'JSXAttribute' ||+ attribute.name.type !== 'JSXIdentifier'+ ) {+ return null;+ }++ return attribute.name.name;+};++const getStaticNumber = (+ attribute: JSXElement['openingElement']['attributes'][number],+): number | null => {+ if (attribute.type !== 'JSXAttribute') {+ return null;+ }++ if (!attribute.value) {+ return null;+ }++ if (attribute.value.type === 'StringLiteral') {+ const parsed = Number(attribute.value.value);+ return Number.isFinite(parsed) ? parsed : null;+ }++ if (attribute.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ const {expression} = attribute.value;+ if (expression.type === 'NumericLiteral') {+ return expression.value;+ }++ if (expression.type === 'Identifier' && expression.name === 'Infinity') {+ return Infinity;+ }++ return null;+};++const readSequenceTiming = (element: JSXElement): SequenceTiming => {+ let from = 0;+ let durationInFrames = Infinity;+ let trimBefore = 0;+ let hasFrom = false;+ let hasDurationInFrames = false;+ let hasTrimBefore = false;++ for (const attribute of element.openingElement.attributes) {+ const name = getAttributeName(attribute);+ if (!name) {+ continue;+ }++ if (+ name !== 'from' &&+ name !== 'durationInFrames' &&+ name !== 'trimBefore'+ ) {+ continue;+ }++ const value = getStaticNumber(attribute);+ if (value === null) {+ throw new Error(`Cannot split sequence with dynamic ${name}`);+ }++ if (name === 'from') {+ from = value;+ hasFrom = true;+ }++ if (name === 'durationInFrames') {+ durationInFrames = value;+ hasDurationInFrames = true;+ }++ if (name === 'trimBefore') {+ trimBefore = value;+ hasTrimBefore = true;+ }+ }++ return {+ from,+ durationInFrames,+ trimBefore,+ hasFrom,+ hasDurationInFrames,+ hasTrimBefore,+ };+};++const setNumericAttribute = ({+ element,+ name,+ value,+ omitIfMissing,+}: {+ element: JSXElement;+ name: string;+ value: number | null;+ omitIfMissing: boolean;+}) => {+ const {+ openingElement: {attributes},+ } = element;+ const index = attributes.findIndex(+ (attribute) => getAttributeName(attribute) === name,+ );++ if (value === null || (index === -1 && omitIfMissing)) {+ if (index !== -1) {+ attributes.splice(index, 1);+ }++ return;+ }++ const next = numericAttribute(name, value);+ if (index === -1) {+ attributes.push(next);+ } else {+ attributes[index] = next;+ }+};++const timingAttributeOrder = ['from', 'durationInFrames', 'trimBefore'];++const orderTimingAttributes = (element: JSXElement) => {+ const {+ openingElement: {attributes},+ } = element;+ const timingAttributes = new Map<string, (typeof attributes)[number]>();+ const otherAttributes: typeof attributes = [];+ let firstTimingIndex: number | null = null;++ for (let i = 0; i < attributes.length; i++) {+ const attribute = attributes[i];+ const name = getAttributeName(attribute);+ if (name && timingAttributeOrder.includes(name)) {+ timingAttributes.set(name, attribute);+ firstTimingIndex = firstTimingIndex === null ? i : firstTimingIndex;+ } else {+ otherAttributes.push(attribute);+ }+ }++ if (firstTimingIndex === null) {+ return;+ }++ const orderedTimingAttributes = timingAttributeOrder.flatMap((name) => {+ const attribute = timingAttributes.get(name);+ return attribute ? [attribute] : [];+ });+ const insertionIndex = Math.min(firstTimingIndex, otherAttributes.length);+ attributes.splice(+ 0,+ attributes.length,+ ...otherAttributes.slice(0, insertionIndex),+ ...orderedTimingAttributes,+ ...otherAttributes.slice(insertionIndex),+ );+};++const splittableSequenceTags = new Set([+ 'AnimatedImage',+ 'Arrow',+ 'Audio',+ 'Callout',+ 'CanvasImage',+ 'Circle',+ 'Ellipse',+ 'Gif',+ 'Heart',+ 'Html5Audio',+ 'Html5Video',+ 'HtmlInCanvas',+ 'Img',+ 'OffthreadVideo',+ 'Pie',+ 'Polygon',+ 'Rect',+ 'RemotionRiveCanvas',+ 'Sequence',+ 'Solid',+ 'Spark',+ 'Star',+ 'Starburst',+ 'Triangle',+ 'Video',+]);++const unsupportedSequenceTags = new Set([+ 'Series.Sequence',+ 'TransitionSeries.Overlay',+ 'TransitionSeries.Sequence',+]);++const jsxMemberNameToString = (+ name: JSXIdentifier | JSXMemberExpression,+): string => {+ if (name.type === 'JSXIdentifier') {+ return name.name;+ }++ return `${jsxMemberNameToString(name.object)}.${name.property.name}`;+};++const jsxNameToString = (+ name: JSXIdentifier | JSXMemberExpression | JSXNamespacedName,+): string => {+ if (name.type === 'JSXNamespacedName') {+ return `${name.namespace.name}:${name.name.name}`;+ }++ return jsxMemberNameToString(name);+};++export const getSplitUnsupportedSequenceTagReason = (+ tagName: string,+): string | null => {+ if (+ tagName === 'Series.Sequence' ||+ tagName === 'TransitionSeries.Sequence' ||+ tagName === 'TransitionSeries.Overlay'+ ) {+ return `<${tagName}> cannot be split from source`;+ }++ return null;+};++export const getIsSplittableSequenceTag = (tagName: string): boolean => {+ if (unsupportedSequenceTags.has(tagName)) {+ return false;+ }++ if (tagName.startsWith('Interactive.')) {+ return true;+ }++ return splittableSequenceTags.has(tagName);+};++const getSplittableSequenceTagName = (element: JSXElement): string => {+ return jsxNameToString(element.openingElement.name);+};++const makeFragment = (first: JSXElement, second: JSXElement): JSXFragment => ({+ type: 'JSXFragment',+ openingFragment: {type: 'JSXOpeningFragment'},+ closingFragment: {type: 'JSXClosingFragment'},+ children: [first, second],+});++const insertAfter = (+ parentNode: Node,+ node: JSXElement,+ clone: JSXElement,+): boolean => {+ if (+ namedTypes.JSXElement.check(parentNode) ||+ namedTypes.JSXFragment.check(parentNode)+ ) {+ const idx = parentNode.children.indexOf(node);+ if (idx !== -1) {+ parentNode.children.splice(idx + 1, 0, clone);+ return true;+ }+ }++ if (namedTypes.ReturnStatement.check(parentNode)) {+ const parent = parentNode as ReturnStatement;+ if (parent.argument === node) {+ parent.argument = makeFragment(node, clone) as unknown as Expression;+ return true;+ }+ }++ if (namedTypes.ArrowFunctionExpression.check(parentNode)) {+ const parent = parentNode as ArrowFunctionExpression;+ if (parent.body === node) {+ parent.body = makeFragment(+ node,+ clone,+ ) as ArrowFunctionExpression['body'];+ return true;+ }+ }++ return false;+};++export const splitJsxSequence = async ({+ input,+ nodePath,+ splitFrame,+ prettierConfigOverride,+}: {+ input: string;+ nodePath: SequenceNodePath;+ splitFrame: number;+ prettierConfigOverride?: Record<string, unknown> | null;+}): Promise<{+ output: string;+ formatted: boolean;+ nodeLabel: string;+ logLine: number;+}> => {+ if (!Number.isInteger(splitFrame)) {+ throw new Error('Split frame must be an integer');+ }++ const ast = parseAst(input);+ const jsxPath = findJsxElementPathForDeletion(ast, nodePath);+ if (!jsxPath) {+ throw new Error(+ 'Could not find a JSX sequence at the specified location to split',+ );+ }++ const jsxElement = jsxPath.node as JSXElement;+ const tagName = getSplittableSequenceTagName(jsxElement);+ const unsupportedReason = getSplitUnsupportedSequenceTagReason(tagName);+ if (unsupportedReason) {+ throw new Error(unsupportedReason);+ }++ if (!getIsSplittableSequenceTag(tagName)) {+ throw new Error(+ `<${tagName}> does not support sequence timing props and cannot be split`,+ );+ }++ const timing = readSequenceTiming(jsxElement);+ const finiteEnd =+ timing.durationInFrames === Infinity+ ? Infinity+ : timing.from + timing.durationInFrames;++ if (splitFrame <= timing.from) {+ throw new Error('Cannot split at or before the sequence start');+ }++ if (splitFrame >= finiteEnd) {+ throw new Error('Cannot split at or after the sequence end');+ }++ const right = cloneNode(jsxElement, true) as JSXElement;+ const leftDuration = splitFrame - timing.from;+ const rightDuration =+ timing.durationInFrames === Infinity ? Infinity : finiteEnd - splitFrame;+ const rightTrimBefore = timing.trimBefore + leftDuration;++ setNumericAttribute({+ element: jsxElement,+ name: 'durationInFrames',+ value: leftDuration,+ omitIfMissing: false,+ });+ setNumericAttribute({+ element: right,+ name: 'from',+ value: splitFrame,+ omitIfMissing: false,+ });+ setNumericAttribute({+ element: right,+ name: 'durationInFrames',+ value: rightDuration === Infinity ? null : rightDuration,+ omitIfMissing: !timing.hasDurationInFrames,+ });+ setNumericAttribute({+ element: right,+ name: 'trimBefore',+ value: rightTrimBefore === 0 ? null : rightTrimBefore,+ omitIfMissing: !timing.hasTrimBefore && rightTrimBefore === 0,+ });+ orderTimingAttributes(jsxElement);+ orderTimingAttributes(right);++ const {parentPath} = jsxPath;+ if (!parentPath) {+ throw new Error('Cannot split JSX sequence with no parent');+ }++ if (!insertAfter(parentPath.node, jsxElement, right)) {+ jsxPath.replace(makeFragment(jsxElement, right));+ }++ const finalFile = serializeAst(ast);+ const {output, formatted} = await formatFileContent({+ input: finalFile,+ prettierConfigOverride,+ });++ return {+ output,+ formatted,+ nodeLabel: getJsxElementTagLabel(jsxElement),+ logLine:+ jsxElement.openingElement.loc?.start.line ??+ jsxElement.loc?.start.line ??+ 1,+ };+};diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex e604d8e020..764b01cbf5 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -34,6 +34,7 @@ import {reorderSequenceHandler} from './routes/reorder-sequence';import {handleRestartStudio} from './routes/restart-studio';import {saveEffectPropsHandler} from './routes/save-effect-props';import {saveSequencePropsHandler} from './routes/save-sequence-props';+import {splitJsxSequenceHandler} from './routes/split-jsx-sequence';import {subscribeToDefaultProps} from './routes/subscribe-to-default-props';import {subscribeToFileExistence} from './routes/subscribe-to-file-existence';import {subscribeToSequenceProps} from './routes/subscribe-to-sequence-props';@@ -88,6 +89,7 @@ export const allApiRoutes: {'/api/paste-effects': pasteEffectsHandler,'/api/delete-jsx-node': deleteJsxNodeHandler,'/api/duplicate-jsx-node': duplicateJsxNodeHandler,+ '/api/split-jsx-sequence': splitJsxSequenceHandler,'/api/update-available': handleUpdate,'/api/project-info': projectInfoHandler,'/api/delete-static-file': deleteStaticFileHandler,diff --git a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.tsindex 111db5b591..99e64eb202 100644--- a/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts+++ b/packages/studio-server/src/preview-server/routes/add-effect-keyframe.ts@@ -19,7 +19,7 @@ import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeEffectPropStatus} from './can-update-effect-props';import {findJsxElementAtNodePath} from './can-update-sequence-props';import {logEffectUpdate} from './log-updates/log-effect-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const addEffectKeyframeHandler: ApiHandler<AddEffectKeyframeRequest,@@ -38,7 +38,7 @@ export const addEffectKeyframeHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[add-effect-keyframe] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}" frame=${frame}`,diff --git a/packages/studio-server/src/preview-server/routes/add-effect.ts b/packages/studio-server/src/preview-server/routes/add-effect.tsindex 3ab3352795..46de54c77a 100644--- a/packages/studio-server/src/preview-server/routes/add-effect.ts+++ b/packages/studio-server/src/preview-server/routes/add-effect.ts@@ -16,11 +16,12 @@ import {} from '../undo-stack';import {attrName} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const addEffectHandler: ApiHandler<AddEffectRequest,AddEffectResponse-> = async ({+> = ({input: {fileName,sequenceNodePath,@@ -32,73 +33,75 @@ export const addEffectHandler: ApiHandler<remotionRoot,logLevel,}) => {- try {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[add-effect] Received request for fileName="${fileName}" effect="${effectName}"`,- );+ return withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[add-effect] Received request for fileName="${fileName}" effect="${effectName}"`,+ );- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });-- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, effectLabel, nodeLabel, logLine} =- await addEffect({- input: fileContents,- sequenceNodePath: sequenceNodePath.nodePath,- effectName,- effectImportPath,- effectConfig,+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',});- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Addition of ${effectLabel} to ${nodeLabel}`,- redoMessage: `↪️ Addition of ${effectLabel} to ${nodeLabel}`,- },- entryType: 'add-effect',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabel, nodeLabel, logLine} =+ await addEffect({+ input: fileContents,+ sequenceNodePath: sequenceNodePath.nodePath,+ effectName,+ effectImportPath,+ effectConfig,+ });- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Added ${attrName(effectLabel)} to ${nodeLabel}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Addition of ${effectLabel} to ${nodeLabel}`,+ redoMessage: `↪️ Addition of ${effectLabel} to ${nodeLabel}`,+ },+ entryType: 'add-effect',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[add-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,- );+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Added ${attrName(effectLabel)} to ${nodeLabel}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[add-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/add-keyframes.ts b/packages/studio-server/src/preview-server/routes/add-keyframes.tsindex 8b5da873bb..71796513d8 100644--- a/packages/studio-server/src/preview-server/routes/add-keyframes.ts+++ b/packages/studio-server/src/preview-server/routes/add-keyframes.ts@@ -22,7 +22,7 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {logEffectUpdate} from './log-updates/log-effect-update';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';type ResolvedSequenceKeyframe = AddSequenceKeyframe & {readonly index: number;@@ -326,7 +326,7 @@ export const addKeyframesHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[add-keyframes] Received request to add ${diff --git a/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts b/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.tsindex 1d973a5e1c..cfad7a4927 100644--- a/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts+++ b/packages/studio-server/src/preview-server/routes/add-sequence-keyframe.ts@@ -17,7 +17,7 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const addSequenceKeyframeHandler: ApiHandler<AddSequenceKeyframeRequest,@@ -27,7 +27,7 @@ export const addSequenceKeyframeHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[add-sequence-keyframe] Received request for fileName="${fileName}" key="${key}" frame=${frame}`,diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.tsindex cf2f5720ab..13377c382d 100644--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts@@ -21,6 +21,7 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {checkIfTypeScriptFile} from './can-update-default-props';+import {withSourceFileWriteQueue} from './source-file-write-queue';const formatNewCompositionFile = (componentName: string) => {return formatOutput(`import React from 'react';@@ -96,145 +97,147 @@ const getCodemodUndoDescription = (codemod: ApplyCodemodRequest['codemod']) => {export const applyCodemodHandler: ApiHandler<ApplyCodemodRequest,ApplyCodemodResponse-> = async ({+> = ({input: {codemod, dryRun, symbolicatedStack},logLevel,remotionRoot,entryPoint,}) => {- try {- const time = Date.now();+ return withSourceFileWriteQueue(async () => {+ try {+ const time = Date.now();- const filePath = symbolicatedStack- ? resolveFilePathFromSymbolicatedStack(remotionRoot, symbolicatedStack)- : (await getProjectInfo(remotionRoot, entryPoint)).rootFile;+ const filePath = symbolicatedStack+ ? resolveFilePathFromSymbolicatedStack(remotionRoot, symbolicatedStack)+ : (await getProjectInfo(remotionRoot, entryPoint)).rootFile;- if (!filePath) {- throw new Error('Cannot find file for composition in project');- }+ if (!filePath) {+ throw new Error('Cannot find file for composition in project');+ }- checkIfTypeScriptFile(filePath);-- const newCompositionComponentFilePath =- codemod.type === 'new-composition'- ? path.join(path.dirname(filePath), `${codemod.componentName}.tsx`)- : null;-- if (- codemod.type === 'new-composition' &&- newCompositionComponentFilePath &&- existsSync(newCompositionComponentFilePath)- ) {- throw new Error(- `Cannot create ${path.relative(- remotionRoot,- newCompositionComponentFilePath,- )} because it already exists`,- );- }+ checkIfTypeScriptFile(filePath);++ const newCompositionComponentFilePath =+ codemod.type === 'new-composition'+ ? path.join(path.dirname(filePath), `${codemod.componentName}.tsx`)+ : null;++ if (+ codemod.type === 'new-composition' &&+ newCompositionComponentFilePath &&+ existsSync(newCompositionComponentFilePath)+ ) {+ throw new Error(+ `Cannot create ${path.relative(+ remotionRoot,+ newCompositionComponentFilePath,+ )} because it already exists`,+ );+ }- const input = readFileSync(filePath, 'utf-8');- const formatted = await applyCodemodToFile({- filePath,- codeMod: codemod,- });-- const diff = simpleDiff({- oldLines: input.split('\n'),- newLines: formatted.split('\n'),- });-- if (!dryRun) {- const {entryType, undoMessage, redoMessage} =- getCodemodUndoDescription(codemod);- const snapshots: Parameters<- typeof pushTransactionToUndoStack- >[0]['snapshots'] = [- {- filePath,- oldContents: input,- newContents: null,- logLine: symbolicatedStack?.originalLineNumber ?? 1,- },- ];- let componentFilePath: string | null = null;- let componentFileContents: string | null = null;-- if (codemod.type === 'new-composition') {- componentFilePath = newCompositionComponentFilePath;- if (componentFilePath === null) {- throw new Error('Could not determine the new component file path');+ const input = readFileSync(filePath, 'utf-8');+ const formatted = await applyCodemodToFile({+ filePath,+ codeMod: codemod,+ });++ const diff = simpleDiff({+ oldLines: input.split('\n'),+ newLines: formatted.split('\n'),+ });++ if (!dryRun) {+ const {entryType, undoMessage, redoMessage} =+ getCodemodUndoDescription(codemod);+ const snapshots: Parameters<+ typeof pushTransactionToUndoStack+ >[0]['snapshots'] = [+ {+ filePath,+ oldContents: input,+ newContents: null,+ logLine: symbolicatedStack?.originalLineNumber ?? 1,+ },+ ];+ let componentFilePath: string | null = null;+ let componentFileContents: string | null = null;++ if (codemod.type === 'new-composition') {+ componentFilePath = newCompositionComponentFilePath;+ if (componentFilePath === null) {+ throw new Error('Could not determine the new component file path');+ }++ componentFileContents = await formatNewCompositionFile(+ codemod.componentName,+ );+ snapshots.push({+ filePath: componentFilePath,+ oldContents: null,+ newContents: componentFileContents,+ logLine: 1,+ });+ pushTransactionToUndoStack({+ snapshots,+ logLevel,+ remotionRoot,+ description: {+ undoMessage,+ redoMessage,+ },+ entryType,+ suppressHmrOnFileRestore: false,+ });+ } else {+ pushToUndoStack({+ filePath,+ oldContents: input,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine: symbolicatedStack?.originalLineNumber ?? 1,+ description: {+ undoMessage,+ redoMessage,+ },+ entryType,+ suppressHmrOnFileRestore: false,+ });}- componentFileContents = await formatNewCompositionFile(- codemod.componentName,- );- snapshots.push({- filePath: componentFilePath,- oldContents: null,- newContents: componentFileContents,- logLine: 1,- });- pushTransactionToUndoStack({- snapshots,- logLevel,- remotionRoot,- description: {- undoMessage,- redoMessage,- },- entryType,- suppressHmrOnFileRestore: false,- });- } else {- pushToUndoStack({- filePath,- oldContents: input,- newContents: null,- logLevel,- remotionRoot,- logLine: symbolicatedStack?.originalLineNumber ?? 1,- description: {- undoMessage,- redoMessage,- },- entryType,- suppressHmrOnFileRestore: false,- });- }+ suppressUndoStackInvalidation(filePath);+ if (componentFilePath) {+ suppressUndoStackInvalidation(componentFilePath);+ }- suppressUndoStackInvalidation(filePath);- if (componentFilePath) {- suppressUndoStackInvalidation(componentFilePath);- }+ writeFileAndNotifyFileWatchers(filePath, formatted, undefined);+ if (componentFilePath && componentFileContents !== null) {+ writeFileAndNotifyFileWatchers(+ componentFilePath,+ componentFileContents,+ undefined,+ );+ }- writeFileAndNotifyFileWatchers(filePath, formatted, undefined);- if (componentFilePath && componentFileContents !== null) {- writeFileAndNotifyFileWatchers(- componentFilePath,- componentFileContents,- undefined,+ const end = Date.now() - time;+ const relativePath = path.relative(remotionRoot, filePath);+ RenderInternals.Log.info(+ {indent: false, logLevel},+ RenderInternals.chalk.blue(`Edited ${relativePath} in ${end}ms`),);+ printUndoHint(logLevel);}- const end = Date.now() - time;- const relativePath = path.relative(remotionRoot, filePath);- RenderInternals.Log.info(- {indent: false, logLevel},- RenderInternals.chalk.blue(`Edited ${relativePath} in ${end}ms`),- );- printUndoHint(logLevel);+ return {+ success: true,+ diff,+ };+ } catch (err) {+ return {+ success: false,+ reason: (err as Error).message,+ stack: (err as Error).stack as string,+ };}-- return {- success: true,- diff,- };- } 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/routes/apply-visual-control-change.ts b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.tsindex 6ebdf2150d..2a9d09d4c1 100644--- a/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts+++ b/packages/studio-server/src/preview-server/routes/apply-visual-control-change.ts@@ -20,6 +20,7 @@ import {} from '../undo-stack';import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';const getVisualControlChangeLine = (file: File, changeId: string): number => {let line = 1;@@ -47,106 +48,108 @@ const getVisualControlChangeLine = (file: File, changeId: string): number => {export const applyVisualControlHandler: ApiHandler<ApplyVisualControlRequest,ApplyVisualControlResponse-> = async ({input: {fileName, changes}, remotionRoot, logLevel}) => {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[apply-visual-control] Received request for ${fileName} with ${changes.length} changes`,- );- const {absolutePath} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'apply visual control change to',- });+> = ({input: {fileName, changes}, remotionRoot, logLevel}) => {+ return withSourceFileWriteQueue(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[apply-visual-control] Received request for ${fileName} with ${changes.length} changes`,+ );+ const {absolutePath} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'apply visual control change to',+ });- const fileContents = readFileSync(absolutePath, 'utf-8');- const ast = parseAst(fileContents);- const logLine =- changes.length > 0 ? getVisualControlChangeLine(ast, changes[0].id) : 1;+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const ast = parseAst(fileContents);+ const logLine =+ changes.length > 0 ? getVisualControlChangeLine(ast, changes[0].id) : 1;- const {newAst, changesMade} = applyCodemod({- file: ast,- codeMod: {- type: 'apply-visual-control',- changes,- },- });+ const {newAst, changesMade} = applyCodemod({+ file: ast,+ codeMod: {+ type: 'apply-visual-control',+ changes,+ },+ });- if (changesMade.length === 0) {- throw new Error('No changes were made to the file');- }+ if (changesMade.length === 0) {+ throw new Error('No changes were made to the file');+ }- let output = serializeAst(newAst);- let formatted = false;+ let output = serializeAst(newAst);+ let formatted = false;- // eslint-disable-next-line @typescript-eslint/consistent-type-imports- type PrettierType = typeof import('prettier');- try {- const prettier: PrettierType = await import('prettier');- const {format, resolveConfig, resolveConfigFile} = prettier;- const configFilePath = await resolveConfigFile();- if (configFilePath) {- const prettierConfig = await resolveConfig(configFilePath);- if (prettierConfig) {- output = await format(output, {- ...prettierConfig,- filepath: 'test.tsx',- plugins: [],- endOfLine: 'auto',- });- formatted = true;+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports+ type PrettierType = typeof import('prettier');+ try {+ const prettier: PrettierType = await import('prettier');+ const {format, resolveConfig, resolveConfigFile} = prettier;+ const configFilePath = await resolveConfigFile();+ if (configFilePath) {+ const prettierConfig = await resolveConfig(configFilePath);+ if (prettierConfig) {+ output = await format(output, {+ ...prettierConfig,+ filepath: 'test.tsx',+ plugins: [],+ endOfLine: 'auto',+ });+ formatted = true;+ }}+ } catch {+ // Prettier not available, use unformatted output}- } catch {- // Prettier not available, use unformatted output- }- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: '↩️ Visual control change',- redoMessage: '↪️ Visual control change',- },- entryType: 'visual-control',- suppressHmrOnFileRestore: true,- });- suppressUndoStackInvalidation(absolutePath);- suppressBundlerUpdateForFile(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: '↩️ Visual control change',+ redoMessage: '↪️ Visual control change',+ },+ entryType: 'visual-control',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, undefined);- waitForLiveEventsListener().then((listener) => {- listener.sendEventToClient({- type: 'visual-control-values-changed',- values: changes.map((change) => ({- id: change.id,- value: change.newValueIsUndefined- ? null- : JSON.parse(change.newValueSerialized),- isUndefined: change.newValueIsUndefined,- })),+ waitForLiveEventsListener().then((listener) => {+ listener.sendEventToClient({+ type: 'visual-control-values-changed',+ values: changes.map((change) => ({+ id: change.id,+ value: change.newValueIsUndefined+ ? null+ : JSON.parse(change.newValueSerialized),+ isUndefined: change.newValueIsUndefined,+ })),+ });});- });- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Applied visual control changes`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Applied visual control changes`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };+ return {+ success: true,+ };+ });};diff --git a/packages/studio-server/src/preview-server/routes/delete-effect.ts b/packages/studio-server/src/preview-server/routes/delete-effect.tsindex cfe423e91d..72f85472a6 100644--- a/packages/studio-server/src/preview-server/routes/delete-effect.ts+++ b/packages/studio-server/src/preview-server/routes/delete-effect.ts@@ -16,6 +16,7 @@ import {} from '../undo-stack';import {strikeThroughOrRemovedPrefix} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';const getDeletedEffectDescription = (effectLabels: string[]): string => {if (effectLabels.length === 1) {@@ -28,118 +29,119 @@ const getDeletedEffectDescription = (effectLabels: string[]): string => {export const deleteEffectHandler: ApiHandler<DeleteEffectRequest,DeleteEffectResponse-> = async ({input: effects, remotionRoot, logLevel}) => {- try {- if (effects.length === 0) {- throw new Error('No effects were specified for deletion');- }-- RenderInternals.Log.trace(- {indent: false, logLevel},- `[delete-effect] Received request to delete ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,- );+> = ({input: effects, remotionRoot, logLevel}) => {+ return withSourceFileWriteQueue(async () => {+ try {+ if (effects.length === 0) {+ throw new Error('No effects were specified for deletion');+ }- const itemsByFileName = new Map<string, typeof effects>();- for (const item of effects) {- const fileItems = itemsByFileName.get(item.fileName) ?? [];- fileItems.push(item);- itemsByFileName.set(item.fileName, fileItems);- }+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[delete-effect] Received request to delete ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,+ );- const updates = await Promise.all(- [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+ const itemsByFileName = new Map<string, typeof effects>();+ for (const item of effects) {+ const fileItems = itemsByFileName.get(item.fileName) ?? [];+ fileItems.push(item);+ itemsByFileName.set(item.fileName, fileItems);+ }- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, effectLabels, logLines} = await deleteEffects(- {- input: fileContents,- effects: fileItems.map((item) =>- item.type === 'single-effect'- ? {- type: 'single-effect',- sequenceNodePath: item.sequenceNodePath.nodePath,- effectIndex: item.effectIndex,- }- : {- type: 'all-effects',- sequenceNodePath: item.sequenceNodePath.nodePath,- },- ),- },- );+ const updates = await Promise.all(+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- return {- absolutePath,- fileRelativeToRoot,- fileContents,- output,- formatted,- effectLabels,- logLine: Math.min(...logLines),- };- }),- );+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabels, logLines} =+ await deleteEffects({+ input: fileContents,+ effects: fileItems.map((item) =>+ item.type === 'single-effect'+ ? {+ type: 'single-effect',+ sequenceNodePath: item.sequenceNodePath.nodePath,+ effectIndex: item.effectIndex,+ }+ : {+ type: 'all-effects',+ sequenceNodePath: item.sequenceNodePath.nodePath,+ },+ ),+ });- for (const update of updates) {- const deletedEffectDescription = getDeletedEffectDescription(- update.effectLabels,+ return {+ absolutePath,+ fileRelativeToRoot,+ fileContents,+ output,+ formatted,+ effectLabels,+ logLine: Math.min(...logLines),+ };+ }),);- pushToUndoStack({- filePath: update.absolutePath,- oldContents: update.fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine: update.logLine,- description: {- undoMessage: `↩️ Deletion of ${deletedEffectDescription}`,- redoMessage: `↪️ Deletion of ${deletedEffectDescription}`,- },- entryType: 'delete-effect',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(update.absolutePath);- writeFileAndNotifyFileWatchers(- update.absolutePath,- update.output,- undefined,- );+ for (const update of updates) {+ const deletedEffectDescription = getDeletedEffectDescription(+ update.effectLabels,+ );- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath: update.absolutePath,- line: update.logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} ${strikeThroughOrRemovedPrefix(deletedEffectDescription)}`,- );- if (!update.formatted) {- warnAboutPrettierOnce(logLevel);- }+ pushToUndoStack({+ filePath: update.absolutePath,+ oldContents: update.fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine: update.logLine,+ description: {+ undoMessage: `↩️ Deletion of ${deletedEffectDescription}`,+ redoMessage: `↪️ Deletion of ${deletedEffectDescription}`,+ },+ entryType: 'delete-effect',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(update.absolutePath);+ writeFileAndNotifyFileWatchers(+ update.absolutePath,+ update.output,+ undefined,+ );- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[delete-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,- );- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: update.absolutePath,+ line: update.logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} ${strikeThroughOrRemovedPrefix(deletedEffectDescription)}`,+ );+ if (!update.formatted) {+ warnAboutPrettierOnce(logLevel);+ }- printUndoHint(logLevel);+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[delete-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ );+ }- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/delete-jsx-node.ts b/packages/studio-server/src/preview-server/routes/delete-jsx-node.tsindex 86423b54b3..971cd13cb1 100644--- a/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/delete-jsx-node.ts@@ -15,6 +15,7 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';const getDeletedNodeDescription = (nodeLabels: string[]): string => {if (nodeLabels.length === 1) {@@ -27,106 +28,109 @@ const getDeletedNodeDescription = (nodeLabels: string[]): string => {export const deleteJsxNodeHandler: ApiHandler<DeleteJsxNodeRequest,DeleteJsxNodeResponse-> = async ({input: {nodes}, remotionRoot, logLevel}) => {- try {- if (nodes.length === 0) {- throw new Error('No JSX nodes were specified for deletion');- }-- RenderInternals.Log.trace(- {indent: false, logLevel},- `[delete-jsx-node] Received request to delete ${nodes.length} JSX node${nodes.length === 1 ? '' : 's'}`,- );+> = ({input: {nodes}, remotionRoot, logLevel}) => {+ return withSourceFileWriteQueue(async () => {+ try {+ if (nodes.length === 0) {+ throw new Error('No JSX nodes were specified for deletion');+ }- const itemsByFileName = new Map<string, typeof nodes>();- for (const item of nodes) {- const fileItems = itemsByFileName.get(item.fileName) ?? [];- fileItems.push(item);- itemsByFileName.set(item.fileName, fileItems);- }+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[delete-jsx-node] Received request to delete ${nodes.length} JSX node${nodes.length === 1 ? '' : 's'}`,+ );- const updates = await Promise.all(- [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+ const itemsByFileName = new Map<string, typeof nodes>();+ for (const item of nodes) {+ const fileItems = itemsByFileName.get(item.fileName) ?? [];+ fileItems.push(item);+ itemsByFileName.set(item.fileName, fileItems);+ }- const fileContents = readFileSync(absolutePath, 'utf-8');+ const updates = await Promise.all(+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- const {output, formatted, nodeLabels, logLines} = await deleteJsxNodes({- input: fileContents,- nodePaths: fileItems.map((item) => item.nodePath),- });+ const fileContents = readFileSync(absolutePath, 'utf-8');- return {- absolutePath,- fileRelativeToRoot,- fileContents,- output,- formatted,- nodeLabels,- logLine: Math.min(...logLines),- };- }),- );+ const {output, formatted, nodeLabels, logLines} =+ await deleteJsxNodes({+ input: fileContents,+ nodePaths: fileItems.map((item) => item.nodePath),+ });- for (const update of updates) {- const deletedNodeDescription = getDeletedNodeDescription(- update.nodeLabels,+ return {+ absolutePath,+ fileRelativeToRoot,+ fileContents,+ output,+ formatted,+ nodeLabels,+ logLine: Math.min(...logLines),+ };+ }),);- pushToUndoStack({- filePath: update.absolutePath,- oldContents: update.fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine: update.logLine,- description: {- undoMessage: `↩️ Deletion of ${deletedNodeDescription}`,- redoMessage: `↪️ Deletion of ${deletedNodeDescription}`,- },- entryType: 'delete-jsx-node',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(update.absolutePath);- writeFileAndNotifyFileWatchers(- update.absolutePath,- update.output,- undefined,- );+ for (const update of updates) {+ const deletedNodeDescription = getDeletedNodeDescription(+ update.nodeLabels,+ );- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath: update.absolutePath,- line: update.logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Deleted ${deletedNodeDescription}`,- );- if (!update.formatted) {- warnAboutPrettierOnce(logLevel);- }+ pushToUndoStack({+ filePath: update.absolutePath,+ oldContents: update.fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine: update.logLine,+ description: {+ undoMessage: `↩️ Deletion of ${deletedNodeDescription}`,+ redoMessage: `↪️ Deletion of ${deletedNodeDescription}`,+ },+ entryType: 'delete-jsx-node',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(update.absolutePath);+ writeFileAndNotifyFileWatchers(+ update.absolutePath,+ update.output,+ undefined,+ );- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[delete-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,- );- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: update.absolutePath,+ line: update.logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Deleted ${deletedNodeDescription}`,+ );+ if (!update.formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[delete-jsx-node] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ );+ }- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/delete-keyframes.ts b/packages/studio-server/src/preview-server/routes/delete-keyframes.tsindex a6a053660c..490fe18047 100644--- a/packages/studio-server/src/preview-server/routes/delete-keyframes.ts+++ b/packages/studio-server/src/preview-server/routes/delete-keyframes.ts@@ -31,7 +31,7 @@ import {} from './can-update-sequence-props';import {logEffectUpdate} from './log-updates/log-effect-update';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';type ResolvedSequenceKeyframe = DeleteSequenceKeyframe & {index: number;@@ -383,7 +383,7 @@ export const deleteKeyframesHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[delete-keyframes] Received request to delete ${diff --git a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts b/packages/studio-server/src/preview-server/routes/duplicate-effect.tsindex 6d0d4357a2..3e9dc2b18b 100644--- a/packages/studio-server/src/preview-server/routes/duplicate-effect.ts+++ b/packages/studio-server/src/preview-server/routes/duplicate-effect.ts@@ -16,6 +16,7 @@ import {} from '../undo-stack';import {attrName} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';const getDuplicatedEffectDescription = (effectLabels: string[]): string => {if (effectLabels.length === 1) {@@ -28,109 +29,111 @@ const getDuplicatedEffectDescription = (effectLabels: string[]): string => {export const duplicateEffectHandler: ApiHandler<DuplicateEffectRequest,DuplicateEffectResponse-> = async ({input: effects, remotionRoot, logLevel}) => {- try {- if (effects.length === 0) {- throw new Error('No effects were specified for duplication');- }-- RenderInternals.Log.trace(- {indent: false, logLevel},- `[duplicate-effect] Received request to duplicate ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,- );+> = ({input: effects, remotionRoot, logLevel}) => {+ return withSourceFileWriteQueue(async () => {+ try {+ if (effects.length === 0) {+ throw new Error('No effects were specified for duplication');+ }- const itemsByFileName = new Map<string, typeof effects>();- for (const item of effects) {- const fileItems = itemsByFileName.get(item.fileName) ?? [];- fileItems.push(item);- itemsByFileName.set(item.fileName, fileItems);- }+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[duplicate-effect] Received request to duplicate ${effects.length} effect target${effects.length === 1 ? '' : 's'}`,+ );- const updates = await Promise.all(- [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+ const itemsByFileName = new Map<string, typeof effects>();+ for (const item of effects) {+ const fileItems = itemsByFileName.get(item.fileName) ?? [];+ fileItems.push(item);+ itemsByFileName.set(item.fileName, fileItems);+ }- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, effectLabels, logLines} =- await duplicateEffects({- input: fileContents,- effects: fileItems.map((item) => ({- sequenceNodePath: item.sequenceNodePath.nodePath,- effectIndex: item.effectIndex,- })),+ const updates = await Promise.all(+ [...itemsByFileName.entries()].map(async ([fileName, fileItems]) => {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',});- return {- absolutePath,- fileRelativeToRoot,- fileContents,- output,- formatted,- effectLabels,- logLine: Math.min(...logLines),- };- }),- );+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabels, logLines} =+ await duplicateEffects({+ input: fileContents,+ effects: fileItems.map((item) => ({+ sequenceNodePath: item.sequenceNodePath.nodePath,+ effectIndex: item.effectIndex,+ })),+ });- for (const update of updates) {- const duplicatedEffectDescription = getDuplicatedEffectDescription(- update.effectLabels,+ return {+ absolutePath,+ fileRelativeToRoot,+ fileContents,+ output,+ formatted,+ effectLabels,+ logLine: Math.min(...logLines),+ };+ }),);- pushToUndoStack({- filePath: update.absolutePath,- oldContents: update.fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine: update.logLine,- description: {- undoMessage: `↩️ Duplication of ${duplicatedEffectDescription}`,- redoMessage: `↪️ Duplication of ${duplicatedEffectDescription}`,- },- entryType: 'duplicate-effect',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(update.absolutePath);- writeFileAndNotifyFileWatchers(- update.absolutePath,- update.output,- undefined,- );+ for (const update of updates) {+ const duplicatedEffectDescription = getDuplicatedEffectDescription(+ update.effectLabels,+ );- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath: update.absolutePath,- line: update.logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${attrName(duplicatedEffectDescription)}`,- );- if (!update.formatted) {- warnAboutPrettierOnce(logLevel);- }+ pushToUndoStack({+ filePath: update.absolutePath,+ oldContents: update.fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine: update.logLine,+ description: {+ undoMessage: `↩️ Duplication of ${duplicatedEffectDescription}`,+ redoMessage: `↪️ Duplication of ${duplicatedEffectDescription}`,+ },+ entryType: 'duplicate-effect',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(update.absolutePath);+ writeFileAndNotifyFileWatchers(+ update.absolutePath,+ update.output,+ undefined,+ );- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[duplicate-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,- );- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: update.absolutePath,+ line: update.logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${attrName(duplicatedEffectDescription)}`,+ );+ if (!update.formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[duplicate-effect] Wrote ${update.fileRelativeToRoot}${update.formatted ? ' (formatted)' : ''}`,+ );+ }- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/duplicate-jsx-node.ts b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.tsindex 6c94b1a04b..c50931503a 100644--- a/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts+++ b/packages/studio-server/src/preview-server/routes/duplicate-jsx-node.ts@@ -15,74 +15,77 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';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, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+> = ({input: {fileName, nodePath}, remotionRoot, logLevel}) => {+ return withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[duplicate-jsx-node] Received request for fileName="${fileName}"`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- const fileContents = readFileSync(absolutePath, 'utf-8');+ const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, nodeLabel, logLine} = await duplicateJsxNode({- input: fileContents,- nodePath,- });+ const {output, formatted, nodeLabel, logLine} = await duplicateJsxNode({+ input: fileContents,+ nodePath,+ });- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Duplication of ${nodeLabel}`,- redoMessage: `↪️ Duplication of ${nodeLabel}`,- },- entryType: 'duplicate-jsx-node',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, undefined);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Duplication of ${nodeLabel}`,+ redoMessage: `↪️ Duplication of ${nodeLabel}`,+ },+ entryType: 'duplicate-jsx-node',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, undefined);- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Duplicated ${nodeLabel}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ 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)' : ''}`,- );+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[duplicate-jsx-node] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex 8b317f6290..8a29b65caf 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -21,7 +21,7 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';const validatePosition = (position: InsertableCompositionElementPosition | null,@@ -114,7 +114,7 @@ export const insertElementHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {try {validateElement(element);validatePosition(position);diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.tsindex 018f3d0ce4..fb54b18b91 100644--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts@@ -19,7 +19,7 @@ import {suppressUndoStackInvalidation,} from '../undo-stack';import {warnAboutPrettierOnce} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';const validateDimension = (name: string, value: number) => {if (!Number.isFinite(value) || value < 1) {@@ -130,7 +130,7 @@ export const insertJsxElementHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {try {validateElement(element);const elementLabel = getElementLabel(element);diff --git a/packages/studio-server/src/preview-server/routes/move-keyframes.ts b/packages/studio-server/src/preview-server/routes/move-keyframes.tsindex 35116e5fa1..0b44c68c77 100644--- a/packages/studio-server/src/preview-server/routes/move-keyframes.ts+++ b/packages/studio-server/src/preview-server/routes/move-keyframes.ts@@ -22,7 +22,7 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {logEffectUpdate} from './log-updates/log-effect-update';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';type ResolvedSequenceKeyframe = MoveSequenceKeyframe & {index: number;@@ -350,7 +350,7 @@ export const moveKeyframesHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[move-keyframes] Received request to move ${diff --git a/packages/studio-server/src/preview-server/routes/paste-effects.ts b/packages/studio-server/src/preview-server/routes/paste-effects.tsindex 03167c17fb..fce1570419 100644--- a/packages/studio-server/src/preview-server/routes/paste-effects.ts+++ b/packages/studio-server/src/preview-server/routes/paste-effects.ts@@ -16,6 +16,7 @@ import {} from '../undo-stack';import {attrName} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';const getPastedEffectDescription = (effectLabels: string[]): string => {if (effectLabels.length === 1) {@@ -28,83 +29,85 @@ const getPastedEffectDescription = (effectLabels: string[]): string => {export const pasteEffectsHandler: ApiHandler<PasteEffectsRequest,PasteEffectsResponse-> = async ({+> = ({input: {targetFileName, targetSequenceNodePath, type, effects, clientId},remotionRoot,logLevel,}) => {- try {- if (effects.length === 0 && type !== 'effects-replacing') {- throw new Error('No effects were specified for pasting');- }+ return withSourceFileWriteQueue(async () => {+ try {+ if (effects.length === 0 && type !== 'effects-replacing') {+ throw new Error('No effects were specified for pasting');+ }- RenderInternals.Log.trace(- {indent: false, logLevel},- `[paste-effects] Received request to paste ${effects.length} effect${effects.length === 1 ? '' : 's'} into fileName="${targetFileName}"`,- );+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[paste-effects] Received request to paste ${effects.length} effect${effects.length === 1 ? '' : 's'} into fileName="${targetFileName}"`,+ );- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName: targetFileName,- action: 'modify',- });+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName: targetFileName,+ action: 'modify',+ });- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, effectLabels, logLine} = await pasteEffects({- input: fileContents,- targetFileName,- targetSequenceNodePath: targetSequenceNodePath.nodePath,- type,- effects,- });+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabels, logLine} = await pasteEffects({+ input: fileContents,+ targetFileName,+ targetSequenceNodePath: targetSequenceNodePath.nodePath,+ type,+ effects,+ });- const effectDescription = getPastedEffectDescription(effectLabels);+ const effectDescription = getPastedEffectDescription(effectLabels);- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Pasting of ${effectDescription}`,- redoMessage: `↪️ Pasting of ${effectDescription}`,- },- entryType: 'paste-effects',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Pasting of ${effectDescription}`,+ redoMessage: `↪️ Pasting of ${effectDescription}`,+ },+ entryType: 'paste-effects',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Pasted ${attrName(effectDescription)}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Pasted ${attrName(effectDescription)}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[paste-effects] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,- );+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[paste-effects] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/reorder-effect.ts b/packages/studio-server/src/preview-server/routes/reorder-effect.tsindex c22a10de06..5a478ff728 100644--- a/packages/studio-server/src/preview-server/routes/reorder-effect.ts+++ b/packages/studio-server/src/preview-server/routes/reorder-effect.ts@@ -16,80 +16,83 @@ import {} from '../undo-stack';import {attrName} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const reorderEffectHandler: ApiHandler<ReorderEffectRequest,ReorderEffectResponse-> = async ({+> = ({input: {fileName, sequenceNodePath, fromIndex, toIndex, clientId},remotionRoot,logLevel,}) => {- try {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[reorder-effect] Received request for fileName="${fileName}" fromIndex=${fromIndex} toIndex=${toIndex}`,- );+ return withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[reorder-effect] Received request for fileName="${fileName}" fromIndex=${fromIndex} toIndex=${toIndex}`,+ );- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, effectLabel, logLine} = await reorderEffect({- input: fileContents,- sequenceNodePath: sequenceNodePath.nodePath,- fromIndex,- toIndex,- });+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, effectLabel, logLine} = await reorderEffect({+ input: fileContents,+ sequenceNodePath: sequenceNodePath.nodePath,+ fromIndex,+ toIndex,+ });- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Reordering of ${effectLabel}`,- redoMessage: `↪️ Reordering of ${effectLabel}`,- },- entryType: 'reorder-effect',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Reordering of ${effectLabel}`,+ redoMessage: `↪️ Reordering of ${effectLabel}`,+ },+ entryType: 'reorder-effect',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Reordered ${attrName(effectLabel)}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Reordered ${attrName(effectLabel)}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[reorder-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,- );+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[reorder-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/reorder-sequence.ts b/packages/studio-server/src/preview-server/routes/reorder-sequence.tsindex dd15139c63..a0de5cc149 100644--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts@@ -16,80 +16,85 @@ import {} from '../undo-stack';import {attrName} from './log-updates/formatting';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const reorderSequenceHandler: ApiHandler<ReorderSequenceRequest,ReorderSequenceResponse-> = async ({+> = ({input: {fileName, sourceNodePath, targetNodePath, position, clientId},remotionRoot,logLevel,}) => {- try {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[reorder-sequence] Received request for fileName="${fileName}" position=${position}`,- );+ return withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[reorder-sequence] Received request for fileName="${fileName}" position=${position}`,+ );- const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({- remotionRoot,- fileName,- action: 'modify',- });+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });- const fileContents = readFileSync(absolutePath, 'utf-8');- const {output, formatted, sequenceLabel, logLine} = await reorderSequence({- input: fileContents,- sourceNodePath: sourceNodePath.nodePath,- targetNodePath: targetNodePath.nodePath,- position,- });+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const {output, formatted, sequenceLabel, logLine} = await reorderSequence(+ {+ input: fileContents,+ sourceNodePath: sourceNodePath.nodePath,+ targetNodePath: targetNodePath.nodePath,+ position,+ },+ );- pushToUndoStack({- filePath: absolutePath,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ Reordering of ${sequenceLabel}`,- redoMessage: `↪️ Reordering of ${sequenceLabel}`,- },- entryType: 'reorder-sequence',- suppressHmrOnFileRestore: false,- });- suppressUndoStackInvalidation(absolutePath);- writeFileAndNotifyFileWatchers(absolutePath, output, clientId);+ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Reordering of ${sequenceLabel}`,+ redoMessage: `↪️ Reordering of ${sequenceLabel}`,+ },+ entryType: 'reorder-sequence',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Reordered ${attrName(sequenceLabel)}`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Reordered ${attrName(sequenceLabel)}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }- RenderInternals.Log.verbose(- {indent: false, logLevel},- `[reorder-sequence] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,- );+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[reorder-sequence] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,+ );- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/save-effect-props.ts b/packages/studio-server/src/preview-server/routes/save-effect-props.tsindex d5f1cb927f..12bb2dc3c1 100644--- a/packages/studio-server/src/preview-server/routes/save-effect-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-effect-props.ts@@ -21,13 +21,13 @@ import {findJsxElementAtNodePath} from './can-update-sequence-props';import {formatEffectPropChange} from './log-updates/format-effect-prop-change';import {logEffectUpdate} from './log-updates/log-effect-update';import {normalizeQuotes} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const saveEffectPropsHandler: ApiHandler<SaveEffectPropsRequest,SaveEffectPropsResponse> = ({input, remotionRoot, logLevel}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {const {fileName,sequenceNodePath,diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.tsindex 94234a4d92..ac8e86e026 100644--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts@@ -23,7 +23,7 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';type ResolvedSequencePropEdit = {index: number;@@ -89,7 +89,7 @@ export const saveSequencePropsHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {if (edits.length === 0) {throw new Error('No sequence prop edits to save');}diff --git a/packages/studio-server/src/preview-server/routes/save-props-mutex.ts b/packages/studio-server/src/preview-server/routes/source-file-write-queue.tssimilarity index 68%rename from packages/studio-server/src/preview-server/routes/save-props-mutex.tsrename to packages/studio-server/src/preview-server/routes/source-file-write-queue.tsindex 2c9cc0aa41..d840262f67 100644--- a/packages/studio-server/src/preview-server/routes/save-props-mutex.ts+++ b/packages/studio-server/src/preview-server/routes/source-file-write-queue.ts@@ -1,6 +1,8 @@let chain: Promise<unknown> = Promise.resolve();-export const withSavePropsLock = <T>(fn: () => Promise<T>): Promise<T> => {+export const withSourceFileWriteQueue = <T>(+ fn: () => Promise<T>,+): Promise<T> => {const run = () => fn();const next = chain.then(run, run);chain = next.then(diff --git a/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.tsnew file mode 100644index 0000000000..e2e02c61f7--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/split-jsx-sequence.ts@@ -0,0 +1,95 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ SplitJsxSequenceRequest,+ SplitJsxSequenceResponse,+} from '@remotion/studio-shared';+import {splitJsxSequence} from '../../codemods/split-jsx-sequence';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {formatLogFileLocation} from '../format-log-file-location';+import {+ printUndoHint,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';++export const splitJsxSequenceHandler: ApiHandler<+ SplitJsxSequenceRequest,+ SplitJsxSequenceResponse+> = ({input: {fileName, nodePath, splitFrame}, remotionRoot, logLevel}) =>+ withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[split-jsx-sequence] Received request for fileName="${fileName}" at frame ${splitFrame}`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');++ const {output, formatted, nodeLabel, logLine} = await splitJsxSequence({+ input: fileContents,+ nodePath,+ splitFrame,+ });++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ Split of ${nodeLabel}`,+ redoMessage: `↪️ Split of ${nodeLabel}`,+ },+ entryType: 'split-jsx-sequence',+ suppressHmrOnFileRestore: false,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, undefined);++ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(+ `${locationLabel}`,+ )} Split ${nodeLabel}`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[split-jsx-sequence] 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/routes/update-default-props.ts b/packages/studio-server/src/preview-server/routes/update-default-props.tsindex 7cf5e9714d..d75527f583 100644--- a/packages/studio-server/src/preview-server/routes/update-default-props.ts+++ b/packages/studio-server/src/preview-server/routes/update-default-props.ts@@ -20,81 +20,84 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {checkIfTypeScriptFile} from './can-update-default-props';import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const updateDefaultPropsHandler: ApiHandler<UpdateDefaultPropsRequest,UpdateDefaultPropsResponse-> = async ({+> = ({input: {compositionId, defaultProps, enumPaths},remotionRoot,entryPoint,logLevel,}) => {- try {- RenderInternals.Log.trace(- {indent: false, logLevel},- `[update-default-props] Received request for compositionId="${compositionId}"`,- );- const projectInfo = await getProjectInfo(remotionRoot, entryPoint);- if (!projectInfo.rootFile) {- throw new Error('Cannot find root file in project');- }+ return withSourceFileWriteQueue(async () => {+ try {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[update-default-props] Received request for compositionId="${compositionId}"`,+ );+ const projectInfo = await getProjectInfo(remotionRoot, entryPoint);+ if (!projectInfo.rootFile) {+ throw new Error('Cannot find root file in project');+ }- checkIfTypeScriptFile(projectInfo.rootFile);+ checkIfTypeScriptFile(projectInfo.rootFile);- const fileContents = readFileSync(projectInfo.rootFile, 'utf-8');- const logLine = getCompositionDefaultPropsLine({- input: fileContents,- compositionId,- });- const {output, formatted} = await updateDefaultProps({- compositionId,- input: fileContents,- newDefaultProps: JSON.parse(defaultProps),- enumPaths,- });+ const fileContents = readFileSync(projectInfo.rootFile, 'utf-8');+ const logLine = getCompositionDefaultPropsLine({+ input: fileContents,+ compositionId,+ });+ const {output, formatted} = await updateDefaultProps({+ compositionId,+ input: fileContents,+ newDefaultProps: JSON.parse(defaultProps),+ enumPaths,+ });- pushToUndoStack({- filePath: projectInfo.rootFile,- oldContents: fileContents,- newContents: null,- logLevel,- remotionRoot,- logLine,- description: {- undoMessage: `↩️ default props update for "${compositionId}"`,- redoMessage: `↪️ default props update for "${compositionId}"`,- },- entryType: 'default-props',- suppressHmrOnFileRestore: true,- });- suppressUndoStackInvalidation(projectInfo.rootFile);- suppressBundlerUpdateForFile(projectInfo.rootFile);- writeFileAndNotifyFileWatchers(projectInfo.rootFile, output, undefined);+ pushToUndoStack({+ filePath: projectInfo.rootFile,+ oldContents: fileContents,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ default props update for "${compositionId}"`,+ redoMessage: `↪️ default props update for "${compositionId}"`,+ },+ entryType: 'default-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(projectInfo.rootFile);+ suppressBundlerUpdateForFile(projectInfo.rootFile);+ writeFileAndNotifyFileWatchers(projectInfo.rootFile, output, undefined);- const locationLabel = formatLogFileLocation({- remotionRoot,- absolutePath: projectInfo.rootFile,- line: logLine,- });- RenderInternals.Log.info(- {indent: false, logLevel},- `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Updated default props for "${compositionId}"`,- );- if (!formatted) {- warnAboutPrettierOnce(logLevel);- }+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: projectInfo.rootFile,+ line: logLine,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(`${locationLabel}`)} Updated default props for "${compositionId}"`,+ );+ if (!formatted) {+ warnAboutPrettierOnce(logLevel);+ }- printUndoHint(logLevel);+ printUndoHint(logLevel);- return {- success: true,- };- } catch (err) {- return {- success: false,- reason: (err as Error).message,- stack: (err as Error).stack as string,- };- }+ 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/routes/update-effect-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.tsindex 25d72b3fea..94e09e7d7a 100644--- a/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts+++ b/packages/studio-server/src/preview-server/routes/update-effect-keyframe-settings.ts@@ -19,7 +19,7 @@ import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeEffectPropStatus} from './can-update-effect-props';import {findJsxElementAtNodePath} from './can-update-sequence-props';import {logEffectUpdate} from './log-updates/log-effect-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const updateEffectKeyframeSettingsHandler: ApiHandler<UpdateEffectKeyframeSettingsRequest,@@ -37,7 +37,7 @@ export const updateEffectKeyframeSettingsHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[update-effect-keyframe-settings] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}"`,diff --git a/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.tsindex b519a28f3a..93d4a687a9 100644--- a/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts+++ b/packages/studio-server/src/preview-server/routes/update-sequence-keyframe-settings.ts@@ -17,7 +17,7 @@ import {import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';import {logUpdate} from './log-updates/log-update';-import {withSavePropsLock} from './save-props-mutex';+import {withSourceFileWriteQueue} from './source-file-write-queue';export const updateSequenceKeyframeSettingsHandler: ApiHandler<UpdateSequenceKeyframeSettingsRequest,@@ -27,7 +27,7 @@ export const updateSequenceKeyframeSettingsHandler: ApiHandler<remotionRoot,logLevel,}) =>- withSavePropsLock(async () => {+ withSourceFileWriteQueue(async () => {RenderInternals.Log.trace({indent: false, logLevel},`[update-sequence-keyframe-settings] Received request for fileName="${fileName}" key="${key}"`,diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsindex 2197211f08..099ac36c56 100644--- a/packages/studio-server/src/preview-server/undo-stack.ts+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -33,6 +33,7 @@ type UndoEntryType =| 'reorder-sequence'| 'delete-jsx-node'| 'duplicate-jsx-node'+ | 'split-jsx-sequence'| 'insert-jsx-element'| 'delete-composition'| 'rename-composition'@@ -72,6 +73,7 @@ type UndoEntry = {| {entryType: 'reorder-sequence'}| {entryType: 'delete-jsx-node'}| {entryType: 'duplicate-jsx-node'}+ | {entryType: 'split-jsx-sequence'}| {entryType: 'insert-jsx-element'}| {entryType: 'delete-composition'}| {entryType: 'rename-composition'}diff --git a/packages/studio-server/src/test/add-keyframes.test.ts b/packages/studio-server/src/test/add-keyframes.test.tsindex 7304b2fc85..3f2d4ccda3 100644--- a/packages/studio-server/src/test/add-keyframes.test.ts+++ b/packages/studio-server/src/test/add-keyframes.test.ts@@ -84,6 +84,7 @@ const linearProgressiveBlurSchema = {} satisfies InteractivitySchema;test('addKeyframes batches sequence and effect adds into one undo entry', async () => {+ clearUndoStackForTests();const cleanupFileWatcher = setFileWatcherRegistry(createFileWatcherRegistry(),);@@ -157,6 +158,7 @@ test('addKeyframes batches sequence and effect adds into one undo entry', async});test('addKeyframes adds a missing effect prop before keyframing it', async () => {+ clearUndoStackForTests();const cleanupFileWatcher = setFileWatcherRegistry(createFileWatcherRegistry(),);diff --git a/packages/studio-server/src/test/source-file-write-queue.test.ts b/packages/studio-server/src/test/source-file-write-queue.test.tsnew file mode 100644index 0000000000..2352bdd3ed--- /dev/null+++ b/packages/studio-server/src/test/source-file-write-queue.test.ts@@ -0,0 +1,43 @@+import {expect, test} from 'bun:test';+import {withSourceFileWriteQueue} from '../preview-server/routes/source-file-write-queue';++const waitForTask = () => new Promise((resolve) => setTimeout(resolve, 0));++test('withSourceFileWriteQueue serializes pending writes', async () => {+ const events: string[] = [];+ let releaseFirst: () => void = () => undefined;++ const first = withSourceFileWriteQueue(async () => {+ events.push('first:start');+ await new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ events.push('first:end');+ return 1;+ });++ const second = withSourceFileWriteQueue(() => {+ events.push('second:start');+ return Promise.resolve(2);+ });++ await waitForTask();+ expect(events).toEqual(['first:start']);++ releaseFirst();+ await expect(first).resolves.toBe(1);+ await expect(second).resolves.toBe(2);+ expect(events).toEqual(['first:start', 'first:end', 'second:start']);+});++test('withSourceFileWriteQueue continues after a failed write', async () => {+ const failure = new Error('failed write');++ await expect(+ withSourceFileWriteQueue(() => Promise.reject(failure)),+ ).rejects.toThrow('failed write');++ await expect(+ withSourceFileWriteQueue(() => Promise.resolve('next write')),+ ).resolves.toBe('next write');+});diff --git a/packages/studio-server/src/test/split-jsx-sequence.test.ts b/packages/studio-server/src/test/split-jsx-sequence.test.tsnew file mode 100644index 0000000000..e84245369f--- /dev/null+++ b/packages/studio-server/src/test/split-jsx-sequence.test.ts@@ -0,0 +1,231 @@+import {expect, test} from 'bun:test';+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';+import path from 'node:path';+import {splitJsxSequence} from '../codemods/split-jsx-sequence';+import {+ createFileWatcherRegistry,+ setFileWatcherRegistry,+} from '../file-watcher';+import {setLiveEventsListener} from '../preview-server/live-events';+import {splitJsxSequenceHandler} from '../preview-server/routes/split-jsx-sequence';+import {getUndoStack} from '../preview-server/undo-stack';+import {lineColumnToNodePath} from './test-utils';++const wrap = (+ sequence: string,+) => `import {Img, Interactive, Sequence, Series, Solid} from 'remotion';+import {Gif} from '@remotion/gif';++export const Comp = () => {+ return (+ <>+ ${sequence}+ </>+ );+};+`;++const sequenceLine = 7;++const split = async (sequence: string, splitFrame: number) => {+ const input = wrap(sequence);+ const {output} = await splitJsxSequence({+ input,+ nodePath: lineColumnToNodePath(input, sequenceLine),+ splitFrame,+ });++ return output;+};++test('splitJsxSequence splits a sequence with no duration', async () => {+ const output = await split('<Sequence from={0} />', 30);++ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');+});++test('splitJsxSequence omits right Infinity duration', async () => {+ const output = await split(+ '<Sequence from={0} durationInFrames={Infinity} />',+ 30,+ );++ expect(output).toContain('<Sequence from={0} durationInFrames={30} />');+ expect(output).toContain('<Sequence from={30} trimBefore={30} />');+ expect(output).not.toContain('durationInFrames={Infinity}');+});++test('splitJsxSequence keeps missing left from omitted', async () => {+ const output = await split('<Sequence durationInFrames={50} />', 30);++ expect(output).toContain('<Sequence durationInFrames={30} />');+ expect(output).toContain(+ '<Sequence from={30} durationInFrames={20} trimBefore={30} />',+ );+});++test('splitJsxSequence splits finite duration and trimBefore', async () => {+ const output = await split(+ '<Sequence from={10} durationInFrames={50} trimBefore={5} />',+ 30,+ );++ expect(output).toContain(+ '<Sequence from={10} durationInFrames={20} trimBefore={5} />',+ );+ expect(output).toContain(+ '<Sequence from={30} durationInFrames={30} trimBefore={25} />',+ );+});++test('splitJsxSequence splits from-only sequence', async () => {+ const output = await split('<Sequence from={10} />', 30);++ expect(output).toContain('<Sequence from={10} durationInFrames={20} />');+ expect(output).toContain('<Sequence from={30} trimBefore={20} />');+});++test('splitJsxSequence splits sequence-backed components', async () => {+ expect(+ await split('<Img src="image.png" from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Img src="image.png" from={30} durationInFrames={20} trimBefore={30} />',+ );+ expect(+ await split('<Gif src="anim.gif" from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Gif src="anim.gif" from={30} durationInFrames={20} trimBefore={30} />',+ );+ const solidOutput = await split(+ '<Solid width={100} height={100} from={0} durationInFrames={50} />',+ 30,+ );+ expect(solidOutput).toContain(+ '<Solid width={100} height={100} from={0} durationInFrames={30} />',+ );+ expect(solidOutput).toContain('from={30}');+ expect(solidOutput).toContain('durationInFrames={20}');+ expect(solidOutput).toContain('trimBefore={30}');+ expect(+ await split('<Interactive.Div from={0} durationInFrames={50} />', 30),+ ).toContain(+ '<Interactive.Div from={30} durationInFrames={20} trimBefore={30} />',+ );+});++test('splitJsxSequence rejects boundary and dynamic splits', async () => {+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 10),+ ).rejects.toThrow(/sequence start/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 30),+ ).rejects.toThrow(/sequence end/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 8),+ ).rejects.toThrow(/sequence start/);+ await expect(+ split('<Sequence from={10} durationInFrames={20} />', 10.5),+ ).rejects.toThrow(/integer/);+ await expect(+ split('<Sequence from={start} durationInFrames={20} />', 15),+ ).rejects.toThrow(/dynamic from/);+});++test('splitJsxSequence rejects Series.Sequence', async () => {+ await expect(+ split('<Series.Sequence from={0} durationInFrames={50} />', 30),+ ).rejects.toThrow(/cannot be split from source/);+});++test('splitJsxSequence rejects regular DOM elements', async () => {+ await expect(+ split('<div from={0} durationInFrames={50} />', 30),+ ).rejects.toThrow(/does not support sequence timing props/);+});++const clearUndoStack = () => {+ (getUndoStack() as unknown as unknown[]).length = 0;+};++const getHandlerOptions = <T>({+ input,+ entryPoint,+ remotionRoot,+}: {+ input: T;+ entryPoint: string;+ remotionRoot: string;+}) => ({+ input,+ entryPoint,+ remotionRoot,+ request: {} as never,+ response: {} as never,+ logLevel: 'error' as const,+ methods: {+ removeJob: () => undefined,+ cancelJob: () => undefined,+ addJob: () => undefined,+ },+ publicDir: remotionRoot,+ binariesDirectory: null,+});++test('splitJsxSequenceHandler writes success and failure responses', async () => {+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-split-'));+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ sendEventToClient: () => undefined,+ sendEventToClientId: () => undefined,+ router: () => Promise.resolve(),+ closeConnections: () => Promise.resolve(),+ addNewClientListener: () => () => undefined,+ });++ try {+ clearUndoStack();+ const entryPoint = path.join(remotionRoot, 'Root.tsx');+ const input = wrap('<Sequence from={0} durationInFrames={50} />');+ writeFileSync(entryPoint, input);++ const success = await splitJsxSequenceHandler(+ getHandlerOptions({+ input: {+ fileName: entryPoint,+ nodePath: lineColumnToNodePath(input, sequenceLine),+ splitFrame: 30,+ },+ entryPoint,+ remotionRoot,+ }),+ );++ expect(success.success).toBe(true);+ expect(readFileSync(entryPoint, 'utf-8')).toContain(+ '<Sequence from={30} durationInFrames={20} trimBefore={30} />',+ );+ expect(getUndoStack().length).toBe(1);++ const failure = await splitJsxSequenceHandler(+ getHandlerOptions({+ input: {+ fileName: entryPoint,+ nodePath: lineColumnToNodePath(input, sequenceLine),+ splitFrame: 0,+ },+ entryPoint,+ remotionRoot,+ }),+ );++ expect(failure.success).toBe(false);+ } finally {+ cleanupFileWatcher();+ cleanupLiveEvents();+ rmSync(remotionRoot, {recursive: true, force: true});+ }+});diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 775f60f021..8108c42ba0 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -641,6 +641,22 @@ export type DuplicateJsxNodeResponse =stack: string;};+export type SplitJsxSequenceRequest = {+ fileName: string;+ nodePath: SequenceNodePath;+ splitFrame: number;+};++export type SplitJsxSequenceResponse =+ | {+ success: true;+ }+ | {+ success: false;+ reason: string;+ stack: string;+ };+export type InsertableCompositionElement =| {type: 'solid';@@ -861,6 +877,10 @@ export type ApiRoutes = {DuplicateJsxNodeRequest,DuplicateJsxNodeResponse>;+ '/api/split-jsx-sequence': ReqAndRes<+ SplitJsxSequenceRequest,+ SplitJsxSequenceResponse+ >;'/api/insert-jsx-element': ReqAndRes<InsertJsxElementRequest,InsertJsxElementResponsediff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex f01f1d0a76..ad3f3be751 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -80,6 +80,8 @@ export {SaveSequencePropsResponse,SaveSequencePropsResult,SimpleDiff,+ SplitJsxSequenceRequest,+ SplitJsxSequenceResponse,SubscribeToDefaultPropsRequest,SubscribeToDefaultPropsResponse,SubscribeToFileExistenceRequest,diff --git a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsxindex 3024972496..61328642e7 100644--- a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx+++ b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx@@ -15,6 +15,11 @@ import {} from './delete-selected-timeline-item';import {duplicateSelectedTimelineItems} from './duplicate-selected-timeline-item';import {resetSelectedTimelineProps} from './reset-selected-timeline-props';+import {+ shouldHandleTimelineDuplicateShortcut,+ shouldHandleTimelineSplitShortcut,+ splitSelectedTimelineItems,+} from './split-selected-timeline-item';import {useCurrentTimelineSelectionStateAsRef,useTimelineSelection,@@ -155,7 +160,11 @@ export const TimelineDeleteKeybindings: React.FC = () => {const duplicate = keybindings.registerKeybinding({event: 'keydown',key: 'd',- callback: () => {+ callback: (event) => {+ if (!shouldHandleTimelineDuplicateShortcut(event)) {+ return;+ }+const {selectedItems} = currentSelection.current;if (selectedItems.length === 0) {return;@@ -177,11 +186,44 @@ export const TimelineDeleteKeybindings: React.FC = () => {triggerIfInputFieldFocused: false,keepRegisteredWhenNotHighestContext: false,});+ const split = keybindings.registerKeybinding({+ event: 'keydown',+ key: 'd',+ callback: (event) => {+ if (!shouldHandleTimelineSplitShortcut(event)) {+ return;+ }++ const {selectedItems} = currentSelection.current;+ if (selectedItems.length === 0) {+ return;+ }++ const splitPromise = splitSelectedTimelineItems({+ selections: selectedItems,+ sequences: sequencesRef.current,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ propStatuses: propStatusesRef.current,+ splitFrame: timelinePositionRef.current,+ });++ if (splitPromise === null) {+ return;+ }++ splitPromise.catch(() => undefined);+ },+ commandCtrlKey: true,+ preventDefault: true,+ triggerIfInputFieldFocused: false,+ keepRegisteredWhenNotHighestContext: false,+ });return () => {backspace.unregister();deleteKey.unregister();duplicate.unregister();+ split.unregister();};}, [canSelect,diff --git a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts b/packages/studio/src/components/Timeline/split-selected-timeline-item.tsnew file mode 100644index 0000000000..557df8cb90--- /dev/null+++ b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts@@ -0,0 +1,253 @@+import type {+ CanUpdateSequencePropStatus,+ OverrideIdToNodePaths,+ PropStatuses,+ TSequence,+} from 'remotion';+import {Internals} from 'remotion';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {callApi} from '../call-api';+import {showNotification} from '../Notifications/NotificationCenter';+import {findTrackForNodePathInfo} from './find-track-for-node-path-info';+import type {TimelineSelection} from './TimelineSelection';++export type SplitTimelineSequenceEligibility =+ | {+ canSplit: true;+ nodePathInfo: SequenceNodePathInfo;+ }+ | {+ canSplit: false;+ reason: string;+ };++type SplitPropStatuses = Partial<+ Record<+ 'from' | 'durationInFrames' | 'trimBefore',+ CanUpdateSequencePropStatus+ >+>;++export const getTimelineSequenceSplitUnsupportedReason = (+ componentName: string | null | undefined,+): string | null => {+ if (+ componentName === '<TransitionSeries.Sequence>' ||+ componentName === '<TransitionSeries.Overlay>'+ ) {+ return `${componentName} cannot be split from source`;+ }++ return null;+};++const staticNumberish = (+ status: CanUpdateSequencePropStatus | undefined,+): boolean => {+ if (!status) {+ return true;+ }++ return (+ status.status === 'static' &&+ (typeof status.codeValue === 'number' || status.codeValue === undefined)+ );+};++export const getTimelineSequenceSplitEligibility = ({+ selection,+ sequence,+ splitFrame,+ propStatuses,+}: {+ selection: TimelineSelection;+ sequence: TSequence | null;+ splitFrame: number;+ propStatuses?: SplitPropStatuses;+}): SplitTimelineSequenceEligibility => {+ if (selection.type !== 'sequence') {+ return {+ canSplit: false,+ reason: 'Select one sequence to split',+ };+ }++ if (!sequence) {+ return {+ canSplit: false,+ reason: 'Could not find selected sequence',+ };+ }++ if (!Number.isInteger(splitFrame)) {+ return {+ canSplit: false,+ reason: 'Split frame must be an integer',+ };+ }++ if (sequence.isInsideSeries) {+ return {+ canSplit: false,+ reason: 'Series.Sequence clips cannot be split from source',+ };+ }++ const unsupportedReason = getTimelineSequenceSplitUnsupportedReason(+ sequence.controls?.componentName,+ );+ if (unsupportedReason) {+ return {+ canSplit: false,+ reason: unsupportedReason,+ };+ }++ const {nodePathInfo} = selection;+ if (!nodePathInfo.sequenceSubscriptionKey.nodePath) {+ return {+ canSplit: false,+ reason: 'Sequence has no editable source node',+ };+ }++ if (nodePathInfo.numberOfSequencesWithThisNodePath > 1) {+ return {+ canSplit: false,+ reason: 'Programmatically duplicated sequences cannot be split',+ };+ }++ if (+ !staticNumberish(propStatuses?.from) ||+ !staticNumberish(propStatuses?.durationInFrames) ||+ !staticNumberish(propStatuses?.trimBefore)+ ) {+ return {+ canSplit: false,+ reason: 'Sequence timing props must be static numbers',+ };+ }++ const start = sequence.from;+ const end =+ sequence.duration === Infinity+ ? Infinity+ : sequence.from + sequence.duration;++ if (splitFrame <= start) {+ return {+ canSplit: false,+ reason: 'Cannot split at the sequence start',+ };+ }++ if (splitFrame >= end) {+ return {+ canSplit: false,+ reason: 'Cannot split at the sequence end',+ };+ }++ return {+ canSplit: true,+ nodePathInfo,+ };+};++export const splitTimelineSequenceFromSource = ({+ nodePathInfo,+ splitFrame,+}: {+ nodePathInfo: SequenceNodePathInfo;+ splitFrame: number;+}): Promise<boolean> => {+ const nodePath = nodePathInfo.sequenceSubscriptionKey;++ return callApi('/api/split-jsx-sequence', {+ fileName: nodePath.absolutePath,+ nodePath: nodePath.nodePath,+ splitFrame,+ })+ .then((result) => {+ if (result.success) {+ showNotification('Split sequence', 2000);+ return true;+ }++ showNotification(result.reason, 4000);+ return false;+ })+ .catch((err) => {+ showNotification((err as Error).message, 4000);+ return false;+ });+};++export const shouldHandleTimelineDuplicateShortcut = ({+ shiftKey,+}: {+ readonly shiftKey: boolean;+}) => !shiftKey;++export const shouldHandleTimelineSplitShortcut = ({+ shiftKey,+}: {+ readonly shiftKey: boolean;+}) => shiftKey;++export const splitSelectedTimelineItems = ({+ selections,+ sequences,+ overrideIdsToNodePaths,+ propStatuses,+ splitFrame,+ splitSequence = splitTimelineSequenceFromSource,+}: {+ selections: readonly TimelineSelection[];+ sequences: TSequence[];+ overrideIdsToNodePaths: OverrideIdToNodePaths;+ propStatuses: PropStatuses | undefined;+ splitFrame: number;+ splitSequence?: (options: {+ nodePathInfo: SequenceNodePathInfo;+ splitFrame: number;+ }) => Promise<boolean>;+}): Promise<boolean> | null => {+ if (selections.length !== 1) {+ return null;+ }++ const [selection] = selections;+ if (selection.type !== 'sequence') {+ return null;+ }++ const track = findTrackForNodePathInfo({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo: selection.nodePathInfo,+ });+ const sequencePropStatuses = propStatuses+ ? Internals.getPropStatusesCtx(+ propStatuses,+ selection.nodePathInfo.sequenceSubscriptionKey,+ )+ : undefined;+ const eligibility = getTimelineSequenceSplitEligibility({+ selection,+ sequence: track?.sequence ?? null,+ splitFrame,+ propStatuses: sequencePropStatuses,+ });++ if (!eligibility.canSplit) {+ showNotification(eligibility.reason, 4000);+ return Promise.resolve(false);+ }++ return splitSequence({+ nodePathInfo: eligibility.nodePathInfo,+ splitFrame,+ });+};diff --git a/packages/studio/src/test/split-selected-timeline-item.test.ts b/packages/studio/src/test/split-selected-timeline-item.test.tsnew file mode 100644index 0000000000..28cf5fa7ce--- /dev/null+++ b/packages/studio/src/test/split-selected-timeline-item.test.ts@@ -0,0 +1,228 @@+import {expect, test} from 'bun:test';+import type {+ CanUpdateSequencePropStatus,+ PropStatuses,+ SequenceNodePath,+ SequencePropsSubscriptionKey,+ TSequence,+} from 'remotion';+import {Internals} from 'remotion';+import {+ getTimelineSequenceSplitEligibility,+ shouldHandleTimelineDuplicateShortcut,+ shouldHandleTimelineSplitShortcut,+ splitSelectedTimelineItems,+} from '../components/Timeline/split-selected-timeline-item';+import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';++const makeKey = (nodePath: SequenceNodePath): SequencePropsSubscriptionKey => ({+ absolutePath: '/tmp/Comp.tsx',+ nodePath,+ sequenceKeys: [],+ effectKeys: [],+});++const makeNodePathInfo = (+ nodePath: SequenceNodePath,+ numberOfSequencesWithThisNodePath = 1,+): SequenceNodePathInfo => ({+ sequenceSubscriptionKey: makeKey(nodePath),+ auxiliaryKeys: [],+ index: 0,+ numberOfSequencesWithThisNodePath,+ supportsEffects: true,+});++const makeSequence = (overrides: Partial<TSequence> = {}): TSequence =>+ ({+ from: 10,+ trimBefore: null,+ duration: 50,+ id: 'sequence',+ displayName: 'Sequence',+ documentationLink: null,+ parent: null,+ rootId: 'root',+ showInTimeline: true,+ nonce: [[0, 0]],+ loopDisplay: undefined,+ getStack: () => null,+ premountDisplay: null,+ postmountDisplay: null,+ controls: {+ schema: {},+ currentRuntimeValueDotNotation: {},+ overrideId: 'override',+ supportsEffects: true,+ componentIdentity: null,+ componentName: 'Sequence',+ },+ refForOutline: null,+ effects: [],+ isInsideSeries: false,+ frozenFrame: null,+ type: 'sequence',+ ...overrides,+ }) as unknown as TSequence;++const staticNumber = (value: number): CanUpdateSequencePropStatus => ({+ status: 'static',+ codeValue: value,+});++test('getTimelineSequenceSplitEligibility accepts an editable sequence in range', () => {+ const nodePathInfo = makeNodePathInfo(['body', 0]);++ expect(+ getTimelineSequenceSplitEligibility({+ selection: {type: 'sequence', nodePathInfo},+ sequence: makeSequence(),+ splitFrame: 30,+ propStatuses: {+ from: staticNumber(10),+ durationInFrames: staticNumber(50),+ trimBefore: staticNumber(0),+ },+ }),+ ).toEqual({+ canSplit: true,+ nodePathInfo,+ });+});++test('getTimelineSequenceSplitEligibility rejects unsupported split positions', () => {+ const nodePathInfo = makeNodePathInfo(['body', 0]);+ const selection = {type: 'sequence' as const, nodePathInfo};++ expect(+ getTimelineSequenceSplitEligibility({+ selection,+ sequence: makeSequence(),+ splitFrame: 10,+ }).canSplit,+ ).toBe(false);+ expect(+ getTimelineSequenceSplitEligibility({+ selection,+ sequence: makeSequence(),+ splitFrame: 60,+ }).canSplit,+ ).toBe(false);+ expect(+ getTimelineSequenceSplitEligibility({+ selection,+ sequence: makeSequence(),+ splitFrame: 9,+ }).canSplit,+ ).toBe(false);+ expect(+ getTimelineSequenceSplitEligibility({+ selection,+ sequence: makeSequence(),+ splitFrame: 10.5,+ }).canSplit,+ ).toBe(false);+});++test('getTimelineSequenceSplitEligibility rejects non-editable sequence shapes', () => {+ const nodePathInfo = makeNodePathInfo(['body', 0], 2);+ const selection = {type: 'sequence' as const, nodePathInfo};++ expect(+ getTimelineSequenceSplitEligibility({+ selection,+ sequence: makeSequence(),+ splitFrame: 30,+ }).canSplit,+ ).toBe(false);+ expect(+ getTimelineSequenceSplitEligibility({+ selection: {+ type: 'sequence',+ nodePathInfo: makeNodePathInfo(['body', 1]),+ },+ sequence: makeSequence({isInsideSeries: true}),+ splitFrame: 30,+ }).canSplit,+ ).toBe(false);+ expect(+ getTimelineSequenceSplitEligibility({+ selection: {+ type: 'sequence',+ nodePathInfo: makeNodePathInfo(['body', 2]),+ },+ sequence: makeSequence({+ controls: {+ schema: {},+ currentRuntimeValueDotNotation: {},+ overrideId: 'override',+ supportsEffects: true,+ componentIdentity: 'dev.remotion.remotion.Solid',+ componentName: '<Solid>',+ },+ }),+ splitFrame: 30,+ }),+ ).toEqual({+ canSplit: true,+ nodePathInfo: makeNodePathInfo(['body', 2]),+ });+});++test('getTimelineSequenceSplitEligibility rejects dynamic timing props', () => {+ const nodePathInfo = makeNodePathInfo(['body', 0]);++ expect(+ getTimelineSequenceSplitEligibility({+ selection: {type: 'sequence', nodePathInfo},+ sequence: makeSequence(),+ splitFrame: 30,+ propStatuses: {+ from: {status: 'computed'},+ },+ }).canSplit,+ ).toBe(false);+});++test('Cmd+D and Cmd+Shift+D shortcut gates are mutually exclusive', () => {+ expect(shouldHandleTimelineDuplicateShortcut({shiftKey: false})).toBe(true);+ expect(shouldHandleTimelineDuplicateShortcut({shiftKey: true})).toBe(false);+ expect(shouldHandleTimelineSplitShortcut({shiftKey: false})).toBe(false);+ expect(shouldHandleTimelineSplitShortcut({shiftKey: true})).toBe(true);+});++test('splitSelectedTimelineItems splits the selected sequence at the playhead', async () => {+ const nodePathInfo = makeNodePathInfo(['body', 0]);+ const propStatuses = {+ [Internals.makeSequencePropsSubscriptionKey(+ nodePathInfo.sequenceSubscriptionKey,+ )]: {+ canUpdate: true,+ props: {+ from: staticNumber(10),+ durationInFrames: staticNumber(50),+ trimBefore: staticNumber(0),+ },+ effects: [],+ },+ } satisfies PropStatuses;+ const splitCalls: {nodePathInfo: SequenceNodePathInfo; splitFrame: number}[] =+ [];++ const result = await splitSelectedTimelineItems({+ selections: [{type: 'sequence', nodePathInfo}],+ sequences: [makeSequence()],+ overrideIdsToNodePaths: {+ override: nodePathInfo.sequenceSubscriptionKey,+ },+ propStatuses,+ splitFrame: 30,+ splitSequence: (options) => {+ splitCalls.push(options);+ return Promise.resolve(true);+ },+ });++ expect(result).toBe(true);+ expect(splitCalls).toEqual([{nodePathInfo, splitFrame: 30}]);+});