Skip to content

🎥 Make videos programmatically with React

`@remotion/browser-studio`: Split a sequence at the playhead (#10587)

Jonny Burger51e73d69abed
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 362142fb0f..62e49c8169 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -13,6 +13,7 @@ import {
makeInMemoryInsertJsxElementCodemodEnvironment,
resolveCompositionComponentWithFile,
simpleDiff,
+ splitJsxSequence as splitJsxSequenceCodemod,
splitVideoFromAudio as splitVideoFromAudioCodemod,
} from '@remotion/studio-codemods';
import {StudioProtocolInternals} from '@remotion/studio-protocol';
@@ -461,6 +462,53 @@ export const createBrowserStudioOperations = ({
}
};
+ const splitJsxSequence: BrowserStudioOperations['splitJsxSequence'] = async ({
+ fileName,
+ nodePath,
+ sequenceKeys,
+ splitFrame,
+ }) => {
+ try {
+ const project = getProject();
+ const absolutePath = findProjectFile({
+ filePath: fileName,
+ project,
+ });
+ const result = await splitJsxSequenceCodemod({
+ input: project.files[absolutePath],
+ nodePath,
+ sequenceKeys,
+ splitFrame,
+ formatFile: formatCodemodFile,
+ });
+ const nodePathMutation = controller.applyMutation({
+ fileName: absolutePath,
+ mutate: () => ({
+ ...project,
+ files: {...project.files, [absolutePath]: result.output},
+ }),
+ nodePathMutationFiles: [
+ {
+ absolutePath,
+ remappings: result.nodePathRemappings,
+ restoredNodePaths: [],
+ },
+ ],
+ });
+ if (nodePathMutation === null) {
+ throw new Error('Could not split JSX sequence');
+ }
+
+ return {success: true, nodePathMutation};
+ } catch (error) {
+ return {
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error && error.stack ? error.stack : '',
+ };
+ }
+ };
+
const duplicateComposition: BrowserStudioOperations['duplicateComposition'] =
async ({codemod, dryRun}) => {
try {
@@ -826,6 +874,7 @@ export const createBrowserStudioOperations = ({
lastDefaultPropsResults.set(compositionId, JSON.stringify(result));
return Promise.resolve(result);
},
+ splitJsxSequence,
subscribeToEvent: controller.subscribeToEvent,
subscribeToSequenceProps: (request) => {
const result = getSequencePropsSubscription(request);
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index d10f5ffbd6..a10e0f7452 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -671,3 +671,104 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
),
).toHaveLength(sequenceEventCount);
});
+
+test('splits a JSX sequence at the playhead as an undoable project mutation', async () => {
+ const fileName = '/project/src/Composition.tsx';
+ const initialContents = `import {Composition, Sequence} from 'remotion';
+export const Component = () => <Sequence from={10} durationInFrames={20} />;
+export const Root = () => <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />;`;
+ let currentProject: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.tsx',
+ files: {
+ '/project/src/index.tsx': `import {registerRoot} from 'remotion';
+import {Root} from './Composition';
+registerRoot(Root);`,
+ [fileName]: initialContents,
+ },
+ };
+ const operations = createBrowserStudioOperations({
+ dependencyVersions: {},
+ getStaticFiles: null,
+ getProject: () => currentProject,
+ onProjectChange: (nextProject) => {
+ currentProject = nextProject;
+ },
+ resolveDependencies: null,
+ });
+ const events: EventSourceEvent[] = [];
+ operations.subscribeToEvent((event) => events.push(event));
+
+ const subscription = await operations.subscribeToSequenceProps({
+ fileName: 'src/Composition.tsx',
+ line: 2,
+ column: 31,
+ nodePath: null,
+ componentIdentity: 'dev.remotion.remotion.Sequence',
+ keys: ['from', 'durationInFrames'],
+ assetKeys: [],
+ effects: [],
+ clientId: 'browser-studio',
+ videoConfigValues: {
+ durationInFrames: 60,
+ fps: 30,
+ height: 720,
+ width: 1280,
+ },
+ });
+ if (!subscription.success) {
+ throw new Error('Expected sequence props subscription to succeed');
+ }
+
+ const failure = await operations.splitJsxSequence({
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 10,
+ });
+ expect(failure).toMatchObject({
+ success: false,
+ reason: 'Cannot split at or before the sequence start',
+ stack: expect.any(String),
+ });
+ expect(currentProject.files[fileName]).toBe(initialContents);
+
+ const splitResult = await operations.splitJsxSequence({
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ sequenceKeys: ['from', 'durationInFrames', 'trimBefore'],
+ splitFrame: 15,
+ });
+ if (!splitResult.success) {
+ throw new Error(splitResult.reason);
+ }
+
+ expect(currentProject.files[fileName]).toContain(
+ '<Sequence from={10} durationInFrames={5} />',
+ );
+ expect(currentProject.files[fileName]).toContain(
+ '<Sequence from={15} durationInFrames={15} trimBefore={5} />',
+ );
+ expect(
+ events.findLast((event) => event.type === 'sequence-node-paths-remapped'),
+ ).toEqual({
+ type: 'sequence-node-paths-remapped',
+ mutation: splitResult.nodePathMutation,
+ });
+ expect(splitResult.nodePathMutation.files).toEqual([
+ {
+ absolutePath: fileName,
+ remappings: expect.any(Array),
+ restoredNodePaths: [],
+ },
+ ]);
+
+ const undoResult = await operations.undo();
+ expect(undoResult.success).toBe(true);
+ expect(currentProject.files[fileName]).toBe(initialContents);
+ const redoResult = await operations.redo();
+ expect(redoResult.success).toBe(true);
+ expect(currentProject.files[fileName]).toContain(
+ '<Sequence from={15} durationInFrames={15} trimBefore={5} />',
+ );
+});
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index bb70562b42..fef6435669 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -37,6 +37,7 @@ export {
export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
export {simpleDiff} from './simple-diff';
+export {splitJsxSequence} from './split-jsx-sequence';
export {splitVideoFromAudio} from './split-video-from-audio';
export {updateInlineCaptionPatches} from './update-inline-caption-patches';
export {
diff --git a/packages/studio-codemods/src/split-jsx-sequence.ts b/packages/studio-codemods/src/split-jsx-sequence.ts
new file mode 100644
index 0000000000..c29185acb4
--- /dev/null
+++ b/packages/studio-codemods/src/split-jsx-sequence.ts
@@ -0,0 +1,453 @@
+import type {
+ ArrowFunctionExpression,
+ Expression,
+ JSXAttribute,
+ JSXElement,
+ JSXExpressionContainer,
+ JSXFragment,
+ JSXIdentifier,
+ JSXMemberExpression,
+ JSXNamespacedName,
+ Node,
+ ReturnStatement,
+} from '@babel/types';
+import {
+ hasSequenceTimingTraits,
+ type SequenceNodePathRemapping,
+} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {
+ findJsxElementPathForDeletion,
+ getJsxElementTagLabel,
+} from './delete-jsx-node';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
+import {
+ parseAst,
+ parseAstForReadOnly,
+ serializeAst,
+} from './sequence-props/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 === 'UnaryExpression' &&
+ expression.operator === '-' &&
+ expression.argument.type === 'NumericLiteral'
+ ) {
+ return -expression.argument.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 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);
+};
+
+const getSplittableSequenceTagName = (element: JSXElement): string => {
+ return jsxNameToString(element.openingElement.name);
+};
+
+/*
+ * `cloneNode` from `@babel/types` reads `process.env` at module scope, which
+ * breaks browser bundles. Printing and reparsing yields an equally detached
+ * deep copy without the Node-only dependency.
+ */
+const cloneJsxElement = (element: JSXElement): JSXElement => {
+ const printed = recast.print(
+ element as Parameters<typeof recast.print>[0],
+ ).code;
+ const file = parseAstForReadOnly(`<>${printed}</>;`);
+ const statement = file.program.body[0];
+ if (
+ statement?.type !== 'ExpressionStatement' ||
+ statement.expression.type !== 'JSXFragment'
+ ) {
+ throw new Error('Could not clone the JSX sequence to split');
+ }
+
+ const cloned = statement.expression.children.find(
+ (child): child is JSXElement => child.type === 'JSXElement',
+ );
+ if (!cloned) {
+ throw new Error('Could not clone the JSX sequence to split');
+ }
+
+ return cloned;
+};
+
+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,
+ sequenceKeys,
+ splitFrame,
+ formatFile,
+ prettierConfigOverride,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ sequenceKeys: string[];
+ splitFrame: number;
+ formatFile: (input: {
+ contents: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ }) => Promise<{output: string; formatted: boolean}>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ nodeLabel: string;
+ logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
+}> => {
+ if (!Number.isInteger(splitFrame)) {
+ throw new Error('Split frame must be an integer');
+ }
+
+ const ast = parseAst(input);
+ const capturedNodePaths = captureJsxNodePaths(ast);
+ 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);
+ if (!hasSequenceTimingTraits(sequenceKeys)) {
+ throw new Error(`<${tagName}> 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 = cloneJsxElement(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 formatFile({
+ contents: finalFile,
+ prettierConfigOverride: prettierConfigOverride ?? null,
+ });
+ const {nodePathRemappings} = getNodePathRemappings({
+ ast,
+ captured: capturedNodePaths,
+ output,
+ });
+
+ return {
+ output,
+ formatted,
+ nodeLabel: getJsxElementTagLabel(jsxElement),
+ logLine:
+ jsxElement.openingElement.loc?.start.line ??
+ jsxElement.loc?.start.line ??
+ 1,
+ nodePathRemappings,
+ };
+};
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index 9010b922e3..9a4c8a84c3 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -1,306 +1,8 @@
-import type {
- ArrowFunctionExpression,
- Expression,
- JSXAttribute,
- JSXElement,
- JSXExpressionContainer,
- JSXFragment,
- JSXIdentifier,
- JSXMemberExpression,
- JSXNamespacedName,
- Node,
- ReturnStatement,
-} from '@babel/types';
-import {cloneNode} from '@babel/types';
-import {
- hasSequenceTimingTraits,
- type SequenceNodePathRemapping,
-} from '@remotion/studio-shared';
-import * as recast from 'recast';
+import {splitJsxSequence as splitJsxSequenceCodemod} from '@remotion/studio-codemods';
import type {SequenceNodePath} from 'remotion';
-import {
- findJsxElementPathForDeletion,
- getJsxElementTagLabel,
-} from './delete-jsx-node';
import {formatFileContent} from './format-file-content';
-import {
- captureJsxNodePaths,
- getNodePathRemappings,
-} from './get-node-path-remappings';
-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 === 'UnaryExpression' &&
- expression.operator === '-' &&
- expression.argument.type === 'NumericLiteral'
- ) {
- return -expression.argument.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 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);
-};
-
-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 ({
+export const splitJsxSequence = ({
input,
nodePath,
sequenceKeys,
@@ -312,107 +14,16 @@ export const splitJsxSequence = async ({
sequenceKeys: string[];
splitFrame: number;
prettierConfigOverride?: Record<string, unknown> | null;
-}): Promise<{
- output: string;
- formatted: boolean;
- nodeLabel: string;
- logLine: number;
- nodePathRemappings: SequenceNodePathRemapping[];
-}> => {
- if (!Number.isInteger(splitFrame)) {
- throw new Error('Split frame must be an integer');
- }
-
- const ast = parseAst(input);
- const capturedNodePaths = captureJsxNodePaths(ast);
- 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);
- if (!hasSequenceTimingTraits(sequenceKeys)) {
- throw new Error(`<${tagName}> 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,
+}) =>
+ splitJsxSequenceCodemod({
+ input,
+ nodePath,
+ sequenceKeys,
+ splitFrame,
+ formatFile: ({contents, prettierConfigOverride: override}) =>
+ formatFileContent({
+ input: contents,
+ prettierConfigOverride: override,
+ }),
prettierConfigOverride,
});
- const {nodePathRemappings} = getNodePathRemappings({
- ast,
- captured: capturedNodePaths,
- output,
- });
-
- return {
- output,
- formatted,
- nodeLabel: getJsxElementTagLabel(jsxElement),
- logLine:
- jsxElement.openingElement.loc?.start.line ??
- jsxElement.loc?.start.line ??
- 1,
- nodePathRemappings,
- };
-};
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index efcae14791..e1e3465734 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -19,6 +19,8 @@ import type {
SaveSequencePropsRequest,
SaveSequencePropsResponse,
SimpleDiff,
+ SplitJsxSequenceRequest,
+ SplitJsxSequenceResponse,
SplitVideoFromAudioRequest,
SplitVideoFromAudioResponse,
SubscribeToDefaultPropsRequest,
@@ -92,6 +94,9 @@ export type BrowserStudioOperations = {
saveSequenceProps: (
request: SaveSequencePropsRequest,
) => Promise<SaveSequencePropsResponse>;
+ splitJsxSequence: (
+ request: SplitJsxSequenceRequest,
+ ) => Promise<SplitJsxSequenceResponse>;
splitVideoFromAudio: (
request: SplitVideoFromAudioRequest,
) => Promise<SplitVideoFromAudioResponse>;
diff --git a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
index 804980da63..9d33cdbfaa 100644
--- a/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
+++ b/packages/studio/src/components/Timeline/split-selected-timeline-item.ts
@@ -7,8 +7,8 @@ import type {
} 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 {splitJsxSequence} from '../split-jsx-sequence-api';
import {findTrackForNodePathInfo} from './find-track-for-node-path-info';
import type {TimelineSelection} from './TimelineSelection';
@@ -153,7 +153,7 @@ export const splitTimelineSequenceFromSource = ({
}): Promise<boolean> => {
const nodePath = nodePathInfo.sequenceSubscriptionKey;
- return callApi('/api/split-jsx-sequence', {
+ return splitJsxSequence({
fileName: nodePath.absolutePath,
nodePath: nodePath.nodePath,
sequenceKeys: nodePath.sequenceKeys,
diff --git a/packages/studio/src/components/split-jsx-sequence-api.ts b/packages/studio/src/components/split-jsx-sequence-api.ts
new file mode 100644
index 0000000000..6c776e21cf
--- /dev/null
+++ b/packages/studio/src/components/split-jsx-sequence-api.ts
@@ -0,0 +1,15 @@
+import type {
+ SplitJsxSequenceRequest,
+ SplitJsxSequenceResponse,
+} from '@remotion/studio-shared';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+import {callApi} from './call-api';
+
+export const splitJsxSequence = (
+ request: SplitJsxSequenceRequest,
+): Promise<SplitJsxSequenceResponse> => {
+ const browserStudioOperations = getBrowserStudioOperations();
+ return browserStudioOperations
+ ? browserStudioOperations.splitJsxSequence(request)
+ : callApi('/api/split-jsx-sequence', request);
+};
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index ac25a9c2d8..7b3fc04190 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -24,6 +24,7 @@ export const makeBrowserStudioOperations = (
redo: () => unusedOperation('redo'),
renameStaticFile: () => unusedOperation('renameStaticFile'),
saveSequenceProps: () => unusedOperation('saveSequenceProps'),
+ splitJsxSequence: () => unusedOperation('splitJsxSequence'),
splitVideoFromAudio: () => unusedOperation('splitVideoFromAudio'),
subscribeToDefaultProps: () => unusedOperation('subscribeToDefaultProps'),
subscribeToEvent: () => unusedOperation('subscribeToEvent'),