Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Drag selected clips together to reorder them

Jonny Burger9ea1a90410ad
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 19819870f1..8d977c958c 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -24,7 +24,7 @@ import {
renameComposition as renameCompositionCodemod,
renameFolder as renameFolderCodemod,
reorderEffect as reorderEffectCodemod,
- reorderNode,
+ reorderNodes,
resolveCompositionComponent,
setCompositionDefaultProps,
splitSequences as splitSequencesCodemod,
@@ -1868,21 +1868,25 @@ export const createBrowserStudioOperations = ({
});
};
- const reorderSequence: BrowserStudioOperations['reorderSequence'] = async ({
- fileName,
- sourceNodePath,
- targetNodePath,
- position,
- }) => {
+ const reorderSequence: BrowserStudioOperations['reorderSequence'] = async (
+ request,
+ ) => {
try {
+ const {fileName, targetNodePath, position} = request;
+ const sourceNodePaths =
+ request.sourceNodePaths ??
+ (request.sourceNodePath ? [request.sourceNodePath] : []);
const project = getProject();
const absolutePath = findProjectFile({
filePath: fileName,
project,
});
- const result = await reorderNode({
+ const result = await reorderNodes({
project,
- node: {filePath: absolutePath, nodePath: sourceNodePath.nodePath},
+ nodes: sourceNodePaths.map((sourceNodePath) => ({
+ filePath: absolutePath,
+ nodePath: sourceNodePath.nodePath,
+ })),
target: {filePath: absolutePath, nodePath: targetNodePath.nodePath},
position,
});
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index e30f116817..eef9e5bc36 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -58,7 +58,12 @@ export {
type DuplicateNodesOptions,
type DuplicateNodesResult,
} from './duplicate-nodes';
-export {reorderNode, type ReorderNodeOptions} from './reorder-node';
+export {
+ reorderNode,
+ reorderNodes,
+ type ReorderNodeOptions,
+ type ReorderNodesOptions,
+} from './reorder-node';
export {splitSequences, type SplitSequencesOptions} from './split-sequences';
export {detachAudio, type DetachAudioOptions} from './detach-audio';
export type {
diff --git a/packages/codemods/src/reorder-node.ts b/packages/codemods/src/reorder-node.ts
index cb9fd03f32..080761c906 100644
--- a/packages/codemods/src/reorder-node.ts
+++ b/packages/codemods/src/reorder-node.ts
@@ -5,7 +5,14 @@ import {
getUpdatedNodeReference,
type NodeReference,
} from './node-references';
-import {reorderSequence} from './reorder-sequence';
+import {reorderSequences} from './reorder-sequence';
+
+export type ReorderNodesOptions<Project extends CodemodProject> = {
+ project: Project;
+ nodes: readonly NodeReference[];
+ target: NodeReference;
+ position: 'before' | 'after';
+};
export type ReorderNodeOptions<Project extends CodemodProject> = {
project: Project;
@@ -14,22 +21,31 @@ export type ReorderNodeOptions<Project extends CodemodProject> = {
position: 'before' | 'after';
};
-export const reorderNode = async <Project extends CodemodProject>({
+export const reorderNodes = async <Project extends CodemodProject>({
project,
- node,
+ nodes,
target,
position,
-}: ReorderNodeOptions<Project>) => {
- const filePath = findProjectFile({project, filePath: node.filePath});
- if (filePath !== findProjectFile({project, filePath: target.filePath})) {
+}: ReorderNodesOptions<Project>) => {
+ if (nodes.length === 0) {
+ throw new Error('Expected at least one JSX node to reorder');
+ }
+
+ const filePath = findProjectFile({project, filePath: target.filePath});
+ if (
+ nodes.some(
+ (node) =>
+ filePath !== findProjectFile({project, filePath: node.filePath}),
+ )
+ ) {
throw new Error(
'JSX nodes must be siblings in the same file to reorder them',
);
}
- const edit = await reorderSequence({
+ const edit = await reorderSequences({
input: project.files[filePath],
- sourceNodePath: node.nodePath,
+ sourceNodePaths: nodes.map((node) => node.nodePath),
targetNodePath: target.nodePath,
position,
});
@@ -44,6 +60,23 @@ export const reorderNode = async <Project extends CodemodProject>({
logLine: edit.logLine,
},
],
- updatedNode: getUpdatedNodeReference({project, ...result, node}),
+ updatedNodes: nodes.map((node) =>
+ getUpdatedNodeReference({project, ...result, node}),
+ ),
};
};
+
+export const reorderNode = async <Project extends CodemodProject>({
+ project,
+ node,
+ target,
+ position,
+}: ReorderNodeOptions<Project>) => {
+ const result = await reorderNodes({
+ project,
+ nodes: [node],
+ target,
+ position,
+ });
+ return {...result, updatedNode: result.updatedNodes[0]};
+};
diff --git a/packages/codemods/src/reorder-sequence.ts b/packages/codemods/src/reorder-sequence.ts
index 0f0a4fa3a7..547529cbef 100644
--- a/packages/codemods/src/reorder-sequence.ts
+++ b/packages/codemods/src/reorder-sequence.ts
@@ -20,6 +20,7 @@ import {
getAdjacentJsxInsertionSourceEdit,
getJsxElementSourceForInsertion,
} from './source-edits';
+import {getEndOfLine} from './source-style';
const {namedTypes} = recast.types;
@@ -43,14 +44,14 @@ const getJsxChildrenParent = (
};
/* eslint-disable require-await -- Keep the formatter-era Promise API. */
-export const reorderSequence = async ({
+export const reorderSequences = async ({
input,
- sourceNodePath,
+ sourceNodePaths,
targetNodePath,
position,
}: {
input: string;
- sourceNodePath: SequenceNodePath;
+ sourceNodePaths: readonly SequenceNodePath[];
targetNodePath: SequenceNodePath;
position: ReorderSequencePosition;
// Kept optional for compatibility with callers from before source edits
@@ -67,14 +68,22 @@ export const reorderSequence = async ({
logLine: number;
nodePathRemappings: SequenceNodePathRemapping[];
}> => {
+ if (sourceNodePaths.length === 0) {
+ throw new Error('Cannot reorder an empty selection');
+ }
+
const ast = parseAst(input);
const capturedNodePaths = captureJsxNodePaths(ast);
- const sourcePath = findJsxElementPathForDeletion(ast, sourceNodePath);
- if (!sourcePath) {
- throw new Error(
- 'Could not find a JSX element at the source location to reorder sequence',
- );
- }
+ const sourcePaths = sourceNodePaths.map((sourceNodePath) => {
+ const sourcePath = findJsxElementPathForDeletion(ast, sourceNodePath);
+ if (!sourcePath) {
+ throw new Error(
+ 'Could not find a JSX element at the source location to reorder sequence',
+ );
+ }
+
+ return sourcePath;
+ });
const targetPath = findJsxElementPathForDeletion(ast, targetNodePath);
if (!targetPath) {
@@ -83,48 +92,68 @@ export const reorderSequence = async ({
);
}
- const sourceParent = getJsxChildrenParent(sourcePath);
const targetParent = getJsxChildrenParent(targetPath);
- if (!sourceParent || !targetParent || sourceParent !== targetParent) {
+ if (
+ !targetParent ||
+ sourcePaths.some(
+ (sourcePath) => getJsxChildrenParent(sourcePath) !== targetParent,
+ )
+ ) {
throw new Error(
- 'Cannot reorder sequence: source and target are not JSX siblings',
+ 'Cannot reorder sequences: source and target are not JSX siblings',
);
}
- const sourceElement = sourcePath.node as JSXElement;
+ const sourceElements = sourcePaths.map((path) => path.node as JSXElement);
const targetElement = targetPath.node as JSXElement;
- if (sourceElement === targetElement) {
- throw new Error('Cannot reorder sequence: source and target are identical');
+ const selectedElements = new Set(sourceElements);
+ if (selectedElements.size !== sourceElements.length) {
+ throw new Error('Cannot reorder the same sequence twice');
+ }
+
+ if (selectedElements.has(targetElement)) {
+ throw new Error(
+ sourceElements.length === 1
+ ? 'Cannot reorder sequence: source and target are identical'
+ : 'Cannot reorder sequences relative to a selected sequence',
+ );
}
- const {children} = sourceParent;
- const sourceIndex = children.indexOf(sourceElement);
+ const {children} = targetParent;
+ const orderedSources = sourceElements.sort(
+ (left, right) => children.indexOf(left) - children.indexOf(right),
+ );
const targetIndex = children.indexOf(targetElement);
- if (sourceIndex === -1 || targetIndex === -1) {
+ if (
+ targetIndex === -1 ||
+ orderedSources.some((element) => children.indexOf(element) === -1)
+ ) {
throw new Error('Cannot reorder sequence: JSX sibling was not found');
}
- const sequenceLabel = getJsxElementTagLabel(sourceElement);
+ const sequenceLabel =
+ orderedSources.length === 1
+ ? getJsxElementTagLabel(orderedSources[0])
+ : `${orderedSources.length} sequences`;
const logLine =
- sourceElement.openingElement.loc?.start.line ??
- sourceElement.loc?.start.line ??
+ orderedSources[0].openingElement.loc?.start.line ??
+ orderedSources[0].loc?.start.line ??
1;
const sourceEdits = [
- getNodeSourceEdit({input, jsxPath: sourcePath}),
+ ...sourcePaths.map((jsxPath) => getNodeSourceEdit({input, jsxPath})),
getAdjacentJsxInsertionSourceEdit({
input,
- insertion: getJsxElementSourceForInsertion({
- element: sourceElement,
- input,
- }),
+ insertion: orderedSources
+ .map((element) => getJsxElementSourceForInsertion({element, input}))
+ .join(getEndOfLine(input)),
position,
target: targetElement,
}),
];
- const [moved] = children.splice(sourceIndex, 1);
- if (!moved) {
- throw new Error('Cannot reorder sequence: source sequence was not found');
+ const originalChildren = [...children];
+ for (const source of orderedSources) {
+ children.splice(children.indexOf(source), 1);
}
const targetIndexAfterRemoval = children.indexOf(targetElement);
@@ -137,8 +166,11 @@ export const reorderSequence = async ({
? targetIndexAfterRemoval
: targetIndexAfterRemoval + 1,
0,
- moved,
+ ...orderedSources,
);
+ if (children.every((child, index) => child === originalChildren[index])) {
+ throw new Error('These sequences are already in that position');
+ }
const output = applySourceEdits({edits: sourceEdits, input});
const {nodePathRemappings} = getNodePathRemappings({
@@ -155,4 +187,20 @@ export const reorderSequence = async ({
nodePathRemappings,
};
};
+
+export const reorderSequence = (options: {
+ input: string;
+ sourceNodePath: SequenceNodePath;
+ targetNodePath: SequenceNodePath;
+ position: ReorderSequencePosition;
+ formatFile?: (input: {
+ contents: string;
+ prettierConfigOverride: Record<string, unknown> | null;
+ }) => Promise<{output: string; formatted: boolean}>;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}) =>
+ reorderSequences({
+ ...options,
+ sourceNodePaths: [options.sourceNodePath],
+ });
/* eslint-enable require-await */
diff --git a/packages/docs/docs/codemods/reorder-node.mdx b/packages/docs/docs/codemods/reorder-node.mdx
index 052f040c54..68cd6e8060 100644
--- a/packages/docs/docs/codemods/reorder-node.mdx
+++ b/packages/docs/docs/codemods/reorder-node.mdx
@@ -77,6 +77,7 @@ Throws or rejects when the target cannot be resolved, the requested edit is unsu
## See also
+- [`reorderNodes()`](/docs/codemods/reorder-nodes)
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/reorder-node.ts)
- [`@remotion/codemods`](/docs/codemods)
- [`getNodes()`](/docs/codemods/get-nodes)
diff --git a/packages/docs/docs/codemods/reorder-nodes.mdx b/packages/docs/docs/codemods/reorder-nodes.mdx
new file mode 100644
index 0000000000..e9fb6163e5
--- /dev/null
+++ b/packages/docs/docs/codemods/reorder-nodes.mdx
@@ -0,0 +1,80 @@
+---
+image: /generated/articles-docs-codemods-reorder-nodes.png
+title: 'reorderNodes()'
+crumb: '@remotion/codemods'
+---
+
+# reorderNodes()<AvailableFrom v="4.0.533" />
+
+Moves one or more JSX nodes as a group before or after a sibling. The moved nodes keep their source order. For ordinary `<Sequence>` siblings, this changes stacking order. For `<Series.Sequence>` and `<TransitionSeries.Sequence>` siblings, it also changes their calculated timing.
+
+:::warning
+
+_Draft API_: This API is experimental and may change.
+
+:::
+
+```ts twoslash title="reorder-nodes.ts"
+import {reorderNodes, type CodemodProject, type NodeReference} from '@remotion/codemods';
+
+declare const project: CodemodProject;
+declare const first: NodeReference;
+declare const second: NodeReference;
+declare const target: NodeReference;
+
+const result = await reorderNodes({
+ project,
+ nodes: [first, second],
+ target,
+ position: 'before',
+});
+
+console.log(result.changes);
+```
+
+All moved nodes and the target must be direct JSX siblings in the same file. A target in the moved group is invalid. The edit is atomic, so an invalid node leaves the input project unchanged.
+
+## Options
+
+### project
+
+An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.
+
+### nodes
+
+A nonempty array of [`NodeReference`](/docs/codemods#node-references) values for the nodes to move. Their array order does not affect the result.
+
+### target
+
+The sibling node to position the group relative to.
+
+### position
+
+Either `'before'` or `'after'`.
+
+## Return value
+
+### changes
+
+An array of file changes. This operation changes one file.
+
+### nodePathRemappings
+
+The mappings from old to new JSX node paths. Apply them to references and selections from the input project.
+
+### updatedNodes
+
+References to the moved nodes in the output project, in the order passed in `nodes`.
+
+### editDetails
+
+The source location and label for the edit.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />
+
+## See also
+
+- [`reorderNode()`](/docs/codemods/reorder-node)
+- [`getNodes()`](/docs/codemods/get-nodes)
diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsx
index cd39664ea2..89d566cc5c 100644
--- a/packages/docs/docs/codemods/table-of-contents.tsx
+++ b/packages/docs/docs/codemods/table-of-contents.tsx
@@ -115,6 +115,10 @@ export const TableOfContents: React.FC = () => {
<strong>reorderNode()</strong>
<div>Moves a node before or after a sibling.</div>
</TOCItem>
+ <TOCItem link="/docs/codemods/reorder-nodes">
+ <strong>reorderNodes()</strong>
+ <div>Moves JSX siblings as one ordered group.</div>
+ </TOCItem>
<TOCItem link="/docs/codemods/resolve-composition-component">
<strong>resolveCompositionComponent()</strong>
<div>
diff --git a/packages/docs/docs/sdk/get-canvas-sequence-reorder-insertion-index.mdx b/packages/docs/docs/sdk/get-canvas-sequence-reorder-insertion-index.mdx
new file mode 100644
index 0000000000..27145aaa93
--- /dev/null
+++ b/packages/docs/docs/sdk/get-canvas-sequence-reorder-insertion-index.mdx
@@ -0,0 +1,51 @@
+---
+image: /generated/articles-docs-sdk-get-canvas-sequence-reorder-insertion-index.png
+title: getCanvasSequenceReorderInsertionIndex()
+crumb: '@remotion/sdk'
+---
+
+# getCanvasSequenceReorderInsertionIndex()<AvailableFrom v="4.0.533" />
+
+Calculates where a dragged group lands after removing its selected siblings. Returns `null` for a drop on the selection, a negative or duplicate source index, or a move that leaves a contiguous group in place.
+
+```ts twoslash title="get-insertion-index.ts"
+import {getCanvasSequenceReorderInsertionIndex} from '@remotion/sdk';
+
+const insertionIndex = getCanvasSequenceReorderInsertionIndex({
+ sourceIndexes: [0, 2],
+ targetIndex: 4,
+ position: 'before',
+});
+
+// 2: after removing indexes 0 and 2, insert before the original index 4.
+console.log(insertionIndex);
+```
+
+Indexes must describe siblings in the same order. This helper does not check whether the JSX nodes are direct siblings; [`reorderNodes()`](/docs/codemods/reorder-nodes) validates that against source code.
+
+## Options
+
+### sourceIndexes
+
+The indexes of the selected siblings to move.
+
+### targetIndex
+
+The index of the drop target in the original sibling list.
+
+### position
+
+Either `'before'` or `'after'` the target.
+
+## Return value
+
+The insertion index in the sibling list after the selected items are removed, or `null` for an invalid or unchanged move.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />
+
+## See also
+
+- [`getCanvasSequenceReorderSelection()`](/docs/sdk/get-canvas-sequence-reorder-selection)
+- [`reorderNodes()`](/docs/codemods/reorder-nodes)
diff --git a/packages/docs/docs/sdk/get-canvas-sequence-reorder-selection.mdx b/packages/docs/docs/sdk/get-canvas-sequence-reorder-selection.mdx
new file mode 100644
index 0000000000..acf97dc8b8
--- /dev/null
+++ b/packages/docs/docs/sdk/get-canvas-sequence-reorder-selection.mdx
@@ -0,0 +1,50 @@
+---
+image: /generated/articles-docs-sdk-get-canvas-sequence-reorder-selection.png
+title: getCanvasSequenceReorderSelection()
+crumb: '@remotion/sdk'
+---
+
+# getCanvasSequenceReorderSelection()<AvailableFrom v="4.0.533" />
+
+Returns the sequences to move when a timeline drag starts. Dragging a selected sequence moves the entire sequence selection. Dragging an unselected sequence moves only that sequence.
+
+```ts twoslash title="get-reorder-selection.ts"
+import {
+ getCanvasSequenceReorderSelection,
+ type CanvasSelectionItem,
+} from '@remotion/sdk';
+
+declare const draggedItem: Extract<CanvasSelectionItem, {type: 'sequence'}>;
+declare const selectedItems: CanvasSelectionItem[];
+
+const nodePathInfos = getCanvasSequenceReorderSelection({
+ draggedItem,
+ selectedItems,
+});
+```
+
+The result follows the order of `selectedItems`. A source edit can sort the returned nodes by their JSX order. If the selection contains another item type, only `draggedItem` is returned.
+
+## Options
+
+### draggedItem
+
+The sequence where the drag began.
+
+### selectedItems
+
+The current selection, such as `controller.selection.getSnapshot().selectedItems`.
+
+## Return value
+
+An array of `SequenceNodePathInfo` values to move.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio="" hideServers />
+
+## See also
+
+- [`getCanvasSequenceReorderInsertionIndex()`](/docs/sdk/get-canvas-sequence-reorder-insertion-index)
+- [`getCanvasSelectionItemKey()`](/docs/sdk/get-canvas-selection-item-key)
+- [`reorderNodes()`](/docs/codemods/reorder-nodes)
diff --git a/packages/docs/docs/sdk/index.mdx b/packages/docs/docs/sdk/index.mdx
index 83c246fecb..7f3aeae43d 100644
--- a/packages/docs/docs/sdk/index.mdx
+++ b/packages/docs/docs/sdk/index.mdx
@@ -118,6 +118,8 @@ export const Editor = () => {
The timeline contains registered [`<Sequence>`](/docs/sequence) and other sequence tracks from the mounted composition. The Canvas does not edit source files or provide timeline controls; your interface owns those actions.
+For a timeline reorder gesture, [`getCanvasSequenceReorderSelection()`](/docs/sdk/get-canvas-sequence-reorder-selection) chooses the dragged sequence group. [`getCanvasSequenceReorderInsertionIndex()`](/docs/sdk/get-canvas-sequence-reorder-insertion-index) identifies valid drop positions. Persist the result with [`reorderNodes()`](/docs/codemods/reorder-nodes).
+
## Selection identity
The built-in [`getCanvasSequenceNodePathInfo()`](/docs/sdk/get-canvas-sequence-node-path-info) uses a source identity when available. Otherwise it falls back to a mounted sequence ID, which can change after a remount.
diff --git a/packages/docs/docs/sdk/table-of-contents.tsx b/packages/docs/docs/sdk/table-of-contents.tsx
index 86cf3d488e..bcd97dc847 100644
--- a/packages/docs/docs/sdk/table-of-contents.tsx
+++ b/packages/docs/docs/sdk/table-of-contents.tsx
@@ -50,6 +50,14 @@ export const TableOfContents: React.FC = () => {
<strong>getCanvasSelectionItemKey()</strong>
<div>Compare selection items by identity</div>
</TOCItem>
+ <TOCItem link="/docs/sdk/get-canvas-sequence-reorder-selection">
+ <strong>getCanvasSequenceReorderSelection()</strong>
+ <div>Choose the sequence group when a drag starts</div>
+ </TOCItem>
+ <TOCItem link="/docs/sdk/get-canvas-sequence-reorder-insertion-index">
+ <strong>getCanvasSequenceReorderInsertionIndex()</strong>
+ <div>Locate a group drop in the sibling list</div>
+ </TOCItem>
<TOCItem link="/docs/sdk/get-canvas-keyframes">
<strong>getCanvasKeyframes()</strong>
<div>Place the keyframes of a prop on the timeline</div>
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index cea0829262..54d4b2e2a6 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -2074,6 +2074,8 @@ const sidebars: SidebarsConfig = {
'sdk/get-canvas-sequence-node-path-info',
'sdk/get-canvas-sequence-source-location',
'sdk/get-canvas-selection-item-key',
+ 'sdk/get-canvas-sequence-reorder-selection',
+ 'sdk/get-canvas-sequence-reorder-insertion-index',
'sdk/get-canvas-keyframes',
'sdk/get-canvas-keyframe-toggle',
'sdk/start-canvas-keyframe-drag',
@@ -2119,6 +2121,7 @@ const sidebars: SidebarsConfig = {
'codemods/rename-folder',
'codemods/reorder-effect',
'codemods/reorder-node',
+ 'codemods/reorder-nodes',
'codemods/resolve-composition-component',
'codemods/set-composition-default-props',
'codemods/split-sequences',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index a7cd5deba7..3107de41d5 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -774,6 +774,24 @@ export const articles = [
noAi: false,
slug: 'sdk/get-canvas-selection-item-key',
},
+ {
+ id: 'sdk/get-canvas-sequence-reorder-selection',
+ title: 'getCanvasSequenceReorderSelection()',
+ relativePath: 'docs/sdk/get-canvas-sequence-reorder-selection.mdx',
+ compId: 'articles-docs-sdk-get-canvas-sequence-reorder-selection',
+ crumb: '@remotion/sdk',
+ noAi: false,
+ slug: 'sdk/get-canvas-sequence-reorder-selection',
+ },
+ {
+ id: 'sdk/get-canvas-sequence-reorder-insertion-index',
+ title: 'getCanvasSequenceReorderInsertionIndex()',
+ relativePath: 'docs/sdk/get-canvas-sequence-reorder-insertion-index.mdx',
+ compId: 'articles-docs-sdk-get-canvas-sequence-reorder-insertion-index',
+ crumb: '@remotion/sdk',
+ noAi: false,
+ slug: 'sdk/get-canvas-sequence-reorder-insertion-index',
+ },
{
id: 'sdk/get-canvas-sequence-node-path-info',
title: 'getCanvasSequenceNodePathInfo()',
@@ -1800,6 +1818,15 @@ export const articles = [
noAi: false,
slug: 'codemods/reorder-node',
},
+ {
+ id: 'codemods/reorder-nodes',
+ title: 'reorderNodes()',
+ relativePath: 'docs/codemods/reorder-nodes.mdx',
+ compId: 'articles-docs-codemods-reorder-nodes',
+ crumb: '@remotion/codemods',
+ noAi: false,
+ slug: 'codemods/reorder-nodes',
+ },
{
id: 'codemods/resolve-composition-component',
title: 'resolveCompositionComponent()',
diff --git a/packages/docs/static/generated/articles-docs-codemods-reorder-nodes.png b/packages/docs/static/generated/articles-docs-codemods-reorder-nodes.png
new file mode 100644
index 0000000000..c7a573ac29
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-reorder-nodes.png differ
diff --git a/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-insertion-index.png b/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-insertion-index.png
new file mode 100644
index 0000000000..1a99485237
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-insertion-index.png differ
diff --git a/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-selection.png b/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-selection.png
new file mode 100644
index 0000000000..cfaf37a22a
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-sdk-get-canvas-sequence-reorder-selection.png differ
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 2a0b7cad38..8b85dc2d98 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -34,6 +34,10 @@ export type {
CanvasSelectionInteraction,
CanvasSelectionSnapshot,
} from './selection';
+export {
+ getCanvasSequenceReorderInsertionIndex,
+ getCanvasSequenceReorderSelection,
+} from './sequence-reorder';
export type {
SequenceNodePathInfo,
TimelineTrackData,
diff --git a/packages/sdk/src/sequence-reorder.ts b/packages/sdk/src/sequence-reorder.ts
new file mode 100644
index 0000000000..025fa474dd
--- /dev/null
+++ b/packages/sdk/src/sequence-reorder.ts
@@ -0,0 +1,60 @@
+import type {SequenceNodePathInfo} from './get-timeline-sequence-sort-key';
+import {getCanvasSelectionItemKey, type CanvasSelectionItem} from './selection';
+
+/** The sequences to move when a timeline drag starts on a sequence. */
+export const getCanvasSequenceReorderSelection = ({
+ draggedItem,
+ selectedItems,
+}: {
+ readonly draggedItem: Extract<CanvasSelectionItem, {type: 'sequence'}>;
+ readonly selectedItems: readonly CanvasSelectionItem[];
+}): readonly SequenceNodePathInfo[] => {
+ const draggedKey = getCanvasSelectionItemKey(draggedItem);
+ if (
+ selectedItems.length < 2 ||
+ selectedItems.some((item) => item.type !== 'sequence') ||
+ !selectedItems.some(
+ (item) => getCanvasSelectionItemKey(item) === draggedKey,
+ )
+ ) {
+ return [draggedItem.nodePathInfo];
+ }
+
+ return selectedItems.flatMap((item) =>
+ item.type === 'sequence' ? [item.nodePathInfo] : [],
+ );
+};
+
+/** The insertion index after the selected siblings have been removed. */
+export const getCanvasSequenceReorderInsertionIndex = ({
+ sourceIndexes,
+ targetIndex,
+ position,
+}: {
+ readonly sourceIndexes: readonly number[];
+ readonly targetIndex: number;
+ readonly position: 'before' | 'after';
+}): number | null => {
+ if (
+ sourceIndexes.length === 0 ||
+ targetIndex < 0 ||
+ sourceIndexes.some((index) => index < 0) ||
+ sourceIndexes.includes(targetIndex) ||
+ new Set(sourceIndexes).size !== sourceIndexes.length
+ ) {
+ return null;
+ }
+
+ const sorted = [...sourceIndexes].sort((a, b) => a - b);
+ const rawIndex = targetIndex + (position === 'after' ? 1 : 0);
+ const insertionIndex =
+ rawIndex - sorted.filter((index) => index < rawIndex).length;
+ if (
+ sorted.every((index, offset) => index === sorted[0] + offset) &&
+ insertionIndex === sorted[0]
+ ) {
+ return null;
+ }
+
+ return insertionIndex;
+};
diff --git a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
index 1d12530bb4..5a73b9885a 100644
--- a/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
+++ b/packages/studio-server/src/preview-server/routes/reorder-sequence.ts
@@ -1,5 +1,5 @@
import {readFileSync} from 'node:fs';
-import {reorderNode} from '@remotion/codemods';
+import {reorderNodes} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
ReorderSequenceRequest,
@@ -24,13 +24,13 @@ import {
export const reorderSequenceHandler: ApiHandler<
ReorderSequenceRequest,
ReorderSequenceResponse
-> = ({
- input: {fileName, sourceNodePath, targetNodePath, position, clientId},
- remotionRoot,
- logLevel,
-}) => {
+> = ({input, remotionRoot, logLevel}) => {
return withSourceFileWriteQueue(async () => {
try {
+ const {fileName, targetNodePath, position, clientId} = input;
+ const sourceNodePaths =
+ input.sourceNodePaths ??
+ (input.sourceNodePath ? [input.sourceNodePath] : []);
RenderInternals.Log.trace(
{indent: false, logLevel},
`[reorder-sequence] Received request for fileName="${fileName}" position=${position}`,
@@ -43,9 +43,12 @@ export const reorderSequenceHandler: ApiHandler<
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const result = await reorderNode({
+ const result = await reorderNodes({
project: {files: {[absolutePath]: fileContents}, rootDir: remotionRoot},
- node: {filePath: absolutePath, nodePath: sourceNodePath.nodePath},
+ nodes: sourceNodePaths.map((sourceNodePath) => ({
+ filePath: absolutePath,
+ nodePath: sourceNodePath.nodePath,
+ })),
target: {filePath: absolutePath, nodePath: targetNodePath.nodePath},
position,
});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index f522330752..3c547b3a9b 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -694,11 +694,13 @@ export type ReorderSequencePosition = 'before' | 'after';
export type ReorderSequenceRequest = {
fileName: string;
- sourceNodePath: SequencePropsSubscriptionKey;
targetNodePath: SequencePropsSubscriptionKey;
position: ReorderSequencePosition;
clientId: string;
-};
+} & (
+ | {sourceNodePaths: SequencePropsSubscriptionKey[]; sourceNodePath?: never}
+ | {sourceNodePath: SequencePropsSubscriptionKey; sourceNodePaths?: never}
+);
export type ReorderSequenceResponse =
| {
diff --git a/packages/studio/src/components/Timeline/TimelineRowChrome.tsx b/packages/studio/src/components/Timeline/TimelineRowChrome.tsx
index f2aae9b593..c55a4ea605 100644
--- a/packages/studio/src/components/Timeline/TimelineRowChrome.tsx
+++ b/packages/studio/src/components/Timeline/TimelineRowChrome.tsx
@@ -10,6 +10,7 @@ import {TimelineRowLayoutContext} from './TimelineRowLayoutContext';
import type {TimelineSelectionInteraction} from './TimelineSelection';
import {
getTimelineRowHighlightBackground,
+ shouldSelectTimelineRowOnPointerDown,
TIMELINE_SELECTED_BACKGROUND,
} from './TimelineSelection';
@@ -129,13 +130,22 @@ export const TimelineRowChrome: React.FC<{
(e: React.PointerEvent<HTMLDivElement>) => {
if (e.button === 0) {
e.stopPropagation();
- onSelect({
- shiftKey: e.shiftKey,
- toggleKey: e.metaKey || e.ctrlKey,
- });
+ if (
+ shouldSelectTimelineRowOnPointerDown({
+ selected,
+ shiftKey: e.shiftKey,
+ metaKey: e.metaKey,
+ ctrlKey: e.ctrlKey,
+ })
+ ) {
+ onSelect({
+ shiftKey: e.shiftKey,
+ toggleKey: e.metaKey || e.ctrlKey,
+ });
+ }
}
},
- [onSelect],
+ [onSelect, selected],
);
const onContextMenu = useCallback(
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
index e667eea0bc..0b096d25a6 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx
@@ -1,3 +1,7 @@
+import {
+ getCanvasSequenceReorderInsertionIndex,
+ getCanvasSequenceReorderSelection,
+} from '@remotion/sdk';
import {type ReorderSequencePosition} from '@remotion/studio-shared';
import React, {
useCallback,
@@ -111,6 +115,7 @@ import {
} from './TimelineSelection';
import {TimelineSequenceName} from './TimelineSequenceName';
import {TIMELINE_TIME_INDICATOR_HEIGHT} from './TimelineTimeIndicators';
+import {useTimelineVirtualization} from './TimelineVirtualization';
import {useAssetTimelineContextMenu} from './use-asset-timeline-context-menu';
import {useDeleteTimelineItems} from './use-delete-timeline-items';
import {useOpenSequenceInApps} from './use-open-sequence-in-apps';
@@ -140,9 +145,9 @@ const effectDropHighlight: React.CSSProperties = {
};
type SequenceReorderDragData = {
- readonly nodePath: SequencePropsSubscriptionKey;
- readonly nodePathKey: string;
- readonly siblingIndex: number;
+ readonly sourceNodePaths: readonly SequencePropsSubscriptionKey[];
+ readonly sourceNodePathKeys: readonly string[];
+ readonly siblingIndexes: readonly number[];
readonly parentId: string | null;
readonly fileName: string;
};
@@ -291,16 +296,6 @@ const sequenceReorderAfterLine: React.CSSProperties = {
top: -1,
};
-const getDestinationIndex = ({
- fromIndex,
- insertionIndex,
-}: {
- readonly fromIndex: number;
- readonly insertionIndex: number;
-}) => {
- return insertionIndex > fromIndex ? insertionIndex - 1 : insertionIndex;
-};
-
type SequenceDropTarget =
| {
readonly type: 'valid';
@@ -313,6 +308,7 @@ type SequenceDropTarget =
};
type SequencePointerDropTarget = {
+ readonly nodePathKey: string | null;
readonly getDropTarget: (
clientY: number,
dragData: SequenceReorderDragData,
@@ -396,6 +392,7 @@ const TimelineSequenceItemInner: React.FC<{
const canMutateEffects =
previewConnected && isStudioSelectionEnabled() && canUseEffectOperations();
const {getIsExpanded} = useContext(ExpandedTracksGetterContext);
+ const {rows: timelineRows} = useTimelineVirtualization();
const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
const {setSelectedModal} = useContext(SetSelectedModalContext);
const {isHighestContext} = useKeybinding();
@@ -608,7 +605,7 @@ const TimelineSequenceItemInner: React.FC<{
};
}
- if (dragData.nodePathKey === nodePathKey) {
+ if (dragData.sourceNodePathKeys.includes(nodePathKey)) {
return {
type: 'invalid',
reason: 'Drop onto another sequence to reorder.',
@@ -639,13 +636,13 @@ const TimelineSequenceItemInner: React.FC<{
const rect = element.getBoundingClientRect();
const before = clientY < rect.top + rect.height / 2;
- const insertionIndex = before ? siblingIndex : siblingIndex + 1;
- const toIndex = getDestinationIndex({
- fromIndex: dragData.siblingIndex,
- insertionIndex,
+ const insertionIndex = getCanvasSequenceReorderInsertionIndex({
+ sourceIndexes: dragData.siblingIndexes,
+ targetIndex: siblingIndex,
+ position: before ? 'before' : 'after',
});
- if (toIndex === dragData.siblingIndex) {
+ if (insertionIndex === null) {
return {
type: 'invalid',
reason: 'This sequence is already in that position.',
@@ -682,7 +679,7 @@ const TimelineSequenceItemInner: React.FC<{
try {
const result = await reorderSequence({
fileName: validatedLocation.source,
- sourceNodePath: dropTarget.dragData.nodePath,
+ sourceNodePaths: [...dropTarget.dragData.sourceNodePaths],
targetNodePath: nodePath,
position: dropTarget.position,
clientId: previewServerState.clientId,
@@ -710,6 +707,7 @@ const TimelineSequenceItemInner: React.FC<{
}
const pointerDropTarget: SequencePointerDropTarget = {
+ nodePathKey,
getDropTarget: getSequenceDropTarget,
reorder: (dropTarget) => {
reorderSequenceFromPointer(dropTarget).catch(() => undefined);
@@ -724,6 +722,7 @@ const TimelineSequenceItemInner: React.FC<{
}, [
canHandleSequenceDrag,
getSequenceDropTarget,
+ nodePathKey,
reorderSequenceFromPointer,
]);
@@ -747,20 +746,62 @@ const TimelineSequenceItemInner: React.FC<{
) ||
!canReorderSequence ||
!nodePath ||
+ !nodePathInfo ||
!nodePathKey ||
- !validatedLocation?.source
+ !validatedLocation?.source ||
+ isTimelineSelectionModifierEvent(e)
) {
return;
}
stopSequencePointerSession.current?.();
+ const selectedNodePathInfos = getCanvasSequenceReorderSelection({
+ draggedItem: {type: 'sequence', nodePathInfo},
+ selectedItems,
+ });
+ const sourceRows = selectedNodePathInfos.map((info) => {
+ const key = Internals.makeSequencePropsSubscriptionKey(
+ info.sequenceSubscriptionKey,
+ );
+ return timelineRows.find(
+ (row) =>
+ row.track.nodePathInfo !== null &&
+ Internals.makeSequencePropsSubscriptionKey(
+ row.track.nodePathInfo.sequenceSubscriptionKey,
+ ) === key,
+ );
+ });
+ if (
+ sourceRows.some(
+ (row, index) =>
+ !row ||
+ row.track.sequence.parent !== parentId ||
+ selectedNodePathInfos[index].numberOfSequencesWithThisNodePath !==
+ 1 ||
+ selectedNodePathInfos[index].sequenceSubscriptionKey
+ .absolutePath !== nodePath.absolutePath,
+ )
+ ) {
+ return;
+ }
+
+ const orderedSourceRows = sourceRows
+ .map((row) => row!)
+ .sort((left, right) => left.siblingIndex - right.siblingIndex);
+
const dragData: SequenceReorderDragData = {
fileName: validatedLocation.source,
- nodePath,
- nodePathKey,
+ sourceNodePaths: selectedNodePathInfos.map(
+ (info) => info.sequenceSubscriptionKey,
+ ),
+ sourceNodePathKeys: selectedNodePathInfos.map((info) =>
+ Internals.makeSequencePropsSubscriptionKey(
+ info.sequenceSubscriptionKey,
+ ),
+ ),
parentId,
- siblingIndex,
+ siblingIndexes: sourceRows.map((row) => row!.siblingIndex),
};
const sourceElement = e.currentTarget;
const sourceRect = sourceElement.getBoundingClientRect();
@@ -832,21 +873,71 @@ const TimelineSequenceItemInner: React.FC<{
document.body.style.userSelect = 'none';
document.body.style.webkitUserSelect = 'none';
- dragPreview = sourceElement.cloneNode(true) as HTMLDivElement;
+ const renderedRows = new Map(
+ [...sequencePointerDropTargets].flatMap(([element, target]) =>
+ target.nodePathKey
+ ? [[target.nodePathKey, element] as const]
+ : [],
+ ),
+ );
+ dragPreview = document.createElement('div');
dragPreview.setAttribute('aria-hidden', 'true');
dragPreview.setAttribute(
'data-remotion-sequence-reorder-preview',
'true',
);
- dragPreview.removeAttribute('data-remotion-sequence-reorder-row');
+ let draggedRowOffset = 0;
+ let previewHeight = 0;
+ for (const row of orderedSourceRows) {
+ const key = Internals.makeSequencePropsSubscriptionKey(
+ row.track.nodePathInfo!.sequenceSubscriptionKey,
+ );
+ const renderedRow = renderedRows.get(key);
+ const rowHeight =
+ renderedRow?.getBoundingClientRect().height ??
+ sourceRect.height;
+ const previewRow = renderedRow
+ ? (renderedRow.cloneNode(true) as HTMLDivElement)
+ : document.createElement('div');
+ previewRow.removeAttribute('data-remotion-sequence-reorder-row');
+ if (!renderedRow) {
+ previewRow.textContent =
+ row.track.sequence.displayName ||
+ row.track.sequence.controls?.componentName ||
+ '<Sequence>';
+ Object.assign(previewRow.style, {
+ alignItems: 'center',
+ backgroundColor: '#20242c',
+ color: WHITE,
+ display: 'flex',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: '12px',
+ paddingLeft: '12px',
+ });
+ }
+
+ Object.assign(previewRow.style, {
+ boxSizing: 'border-box',
+ height: `${rowHeight}px`,
+ width: '100%',
+ });
+ if (row.track.sequence.id === sequence.id) {
+ draggedRowOffset = previewHeight;
+ }
+
+ previewHeight += rowHeight;
+ dragPreview.appendChild(previewRow);
+ }
+
Object.assign(dragPreview.style, {
- height: `${sourceRect.height}px`,
+ display: 'flex',
+ flexDirection: 'column',
left: `${sourceRect.left}px`,
margin: '0',
opacity: '0.8',
pointerEvents: 'none',
position: 'fixed',
- top: `${sourceRect.top}px`,
+ top: `${sourceRect.top - draggedRowOffset}px`,
width: `${sourceRect.width}px`,
zIndex: '2147483647',
});
@@ -891,8 +982,11 @@ const TimelineSequenceItemInner: React.FC<{
isStill,
nodePath,
nodePathKey,
+ nodePathInfo,
parentId,
- siblingIndex,
+ selectedItems,
+ sequence.id,
+ timelineRows,
validatedLocation?.source,
],
);
diff --git a/packages/template-vibe-code/README.md b/packages/template-vibe-code/README.md
index dd0207c4c2..65742f7a67 100644
--- a/packages/template-vibe-code/README.md
+++ b/packages/template-vibe-code/README.md
@@ -4,7 +4,7 @@ A Remotion template that turns the browser into a motion graphics editor: write
- **Live compilation** – the project is compiled in a Web Worker with [`@remotion/browser-bundler`](https://www.remotion.dev/docs/browser-bundler) and hot-swapped with Fast Refresh, so component state survives edits.
- **Canvas** – [`@remotion/sdk`](https://www.remotion.dev/docs/sdk) renders the composition with selection outlines. Click a layer on the canvas or in the timeline to select it, drag it to move it (it snaps to the edges and center of the composition, Shift locks the axis, ⌘ disables snapping) or nudge it with the arrow keys. Switch to “Interact” mode to use the composition’s own buttons and inputs.
-- **Timeline** – every mounted sequence shows up as a track. Drag a track to change its `from`, drag its edges to trim `durationInFrames`, split it at the playhead, duplicate, reorder, wrap and delete. In/out points, zoomable ruler, scrubbing.
+- **Timeline** – every mounted sequence shows up as a track. Drag a track bar to change its `from`, drag its edges to trim `durationInFrames`, or drag a track label to reorder selected sibling layers together. Split, duplicate, wrap and delete layers. In/out points, zoomable ruler, scrubbing.
- **Keyframes** – props animated with `interpolate()` get a keyframe row under their track. Drag keyframes to retime them, click to select them (Shift and ⌘ extend the selection), double-click to jump to them, press ⌫ to delete them. In the inspector, a diamond next to each animatable prop adds or removes a keyframe at the playhead and the arrows jump to the neighboring keyframes.
- **Easing** – click the line between two keyframes to edit the easing of that segment: pick a preset (ease in/out, hold, springs), tweak the bezier handles or the spring parameters with live preview, or right-click the line for a preset. The same inspector edits the `interpolate()` options of the prop: extrapolation, `output` mode and `posterize`. ⌫ resets a selected easing to linear.
- **Inspector** – edits props of the selected element directly in the source using [`@remotion/codemods`](https://www.remotion.dev/docs/codemods): position, scale, rotation, opacity, colors, typography, text content, timing and more. Animated props show their value at the playhead; editing one writes a keyframe there. Values computed in code are shown as such. Composition metadata (size, fps, duration) and `defaultProps` are editable too.
diff --git a/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx b/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx
index 99afe69577..a0dbe7d912 100644
--- a/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx
+++ b/packages/template-vibe-code/src/editor/components/Timeline/Timeline.tsx
@@ -3,6 +3,8 @@
import {
canvasKeyframeEasingPresets,
getCanvasSelectionItemKey,
+ getCanvasSequenceReorderInsertionIndex,
+ getCanvasSequenceReorderSelection,
startCanvasKeyframeDrag,
useCanvasSelection,
useCanvasSequenceHover,
@@ -11,6 +13,7 @@ import {
type CanvasSelectionInteraction,
} from "@remotion/sdk";
import { getNodeProps } from "@remotion/codemods";
+import type { NodeReference } from "@remotion/codemods";
import {
ChevronDownIcon,
ChevronRightIcon,
@@ -48,6 +51,7 @@ import {
type KeyframeSelectionItem,
} from "../../model/keyframes";
import {
+ areSiblingNodes,
getLayerLabel,
getNodeReference,
type Layer,
@@ -89,6 +93,13 @@ type DragState = {
startDuration: number;
};
+type ReorderDragState = {
+ nodes: NodeReference[];
+ sourceKeys: string[];
+ targetId: string | null;
+ position: "before" | "after" | null;
+};
+
// The keyframes being dragged are drawn shifted by the previewed delta; the
// source keeps the original frames until the move is committed.
type KeyframeDragState = {
@@ -163,8 +174,13 @@ const TrackRow = memo(function TrackRow({
selected,
drag,
keyframeRows,
+ reorderDropPosition,
onToggleKeyframeRows,
onPointerDownBar,
+ onDragStartLabel,
+ onDragOverLabel,
+ onDropLabel,
+ onDragEndLabel,
}: {
readonly layer: Layer;
readonly index: number;
@@ -174,12 +190,17 @@ const TrackRow = memo(function TrackRow({
readonly drag: DragState | null;
/** Whether the layer has animated props and whether their rows are shown. */
readonly keyframeRows: "none" | "expanded" | "collapsed";
+ readonly reorderDropPosition: "before" | "after" | null;
readonly onToggleKeyframeRows: (layer: Layer) => void;
readonly onPointerDownBar: (
event: React.PointerEvent,
layer: Layer,
mode: DragState["mode"],
) => void;
+ readonly onDragStartLabel: (event: React.DragEvent, layer: Layer) => void;
+ readonly onDragOverLabel: (event: React.DragEvent, layer: Layer) => void;
+ readonly onDropLabel: (event: React.DragEvent, layer: Layer) => void;
+ readonly onDragEndLabel: () => void;
}) {
const { host, actions } = useEditor();
const { hovered, onPointerEnter, onPointerLeave } = useCanvasSequenceHover(
@@ -226,9 +247,15 @@ const TrackRow = memo(function TrackRow({
<div
className={cn(
"bg-background-panel border-border-dim sticky left-0 z-20 flex shrink-0 items-center gap-1.5 border-r border-b pr-2 text-xs",
+ layer.source && "cursor-grab",
selected && "bg-[#141a2a]",
)}
style={{ width: LABEL_WIDTH, paddingLeft: 6 + depth * 14 }}
+ draggable={layer.source !== null}
+ onDragStart={(event) => onDragStartLabel(event, layer)}
+ onDragOver={(event) => onDragOverLabel(event, layer)}
+ onDrop={(event) => onDropLabel(event, layer)}
+ onDragEnd={onDragEndLabel}
onClick={select}
onDoubleClick={() => {
if (layer.source) {
@@ -283,6 +310,14 @@ const TrackRow = memo(function TrackRow({
no source
</span>
) : null}
+ {reorderDropPosition ? (
+ <div
+ className={cn(
+ "bg-primary pointer-events-none absolute right-0 left-0 h-0.5",
+ reorderDropPosition === "before" ? "top-0" : "bottom-0",
+ )}
+ />
+ ) : null}
</div>
<div
className="border-border-dim relative min-w-0 flex-1 border-b"
@@ -560,6 +595,7 @@ export const Timeline: React.FC = () => {
const [zoom, setZoom] = useState(1);
const [drag, setDrag] = useState<DragState | null>(null);
const dragRef = useRef<DragState | null>(null);
+ const [reorderDrag, setReorderDrag] = useState<ReorderDragState | null>(null);
const [keyframeDrag, setKeyframeDrag] = useState<KeyframeDragState | null>(
null,
);
@@ -625,6 +661,182 @@ export const Timeline: React.FC = () => {
});
}, []);
+ const onDragStartLabel = useCallback(
+ (event: React.DragEvent, layer: Layer) => {
+ if (!layer.source || !host) {
+ event.preventDefault();
+ return;
+ }
+
+ const selected = getCanvasSequenceReorderSelection({
+ draggedItem: layer.selectionItem,
+ selectedItems: host.controller.selection.getSnapshot().selectedItems,
+ });
+ const sourceLayers = selected.map((info) =>
+ layers.find(
+ (candidate) =>
+ getCanvasSelectionItemKey(candidate.selectionItem) ===
+ getCanvasSelectionItemKey({ type: "sequence", nodePathInfo: info }),
+ ),
+ );
+ if (
+ sourceLayers.some(
+ (sourceLayer) =>
+ !sourceLayer?.source ||
+ sourceLayer.nodePathInfo.numberOfSequencesWithThisNodePath !== 1 ||
+ !areSiblingNodes(sourceLayer.source, layer.source!),
+ )
+ ) {
+ event.preventDefault();
+ actions.notifyError(
+ new Error("Selected clips must be unique JSX siblings to reorder."),
+ );
+ return;
+ }
+
+ const nodes = sourceLayers.map((sourceLayer) =>
+ getNodeReference(sourceLayer!.selectionItem),
+ );
+ if (nodes.some((node) => node === null)) {
+ event.preventDefault();
+ return;
+ }
+
+ if (sourceLayers.length > 1) {
+ const orderedLayers = sourceLayers
+ .map((sourceLayer) => sourceLayer!)
+ .sort((left, right) => layers.indexOf(left) - layers.indexOf(right));
+ const dragImage = document.createElement("div");
+ Object.assign(dragImage.style, {
+ backgroundColor: "#141a2a",
+ boxShadow: "0 4px 16px #0008",
+ color: "#fff",
+ fontFamily: "Arial, Helvetica, sans-serif",
+ fontSize: "12px",
+ left: "0",
+ pointerEvents: "none",
+ position: "fixed",
+ top: "0",
+ width: `${LABEL_WIDTH}px`,
+ zIndex: "2147483647",
+ });
+ for (const selectedLayer of orderedLayers) {
+ const row = document.createElement("div");
+ row.textContent = getLayerLabel(selectedLayer);
+ Object.assign(row.style, {
+ alignItems: "center",
+ borderBottom: "1px solid #ffffff24",
+ boxSizing: "border-box",
+ display: "flex",
+ height: `${ROW_HEIGHT}px`,
+ overflow: "hidden",
+ paddingLeft: `${6 + selectedLayer.track.depth * 14}px`,
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ });
+ dragImage.appendChild(row);
+ }
+
+ document.body.appendChild(dragImage);
+ const labelRect = event.currentTarget.getBoundingClientRect();
+ event.dataTransfer.setDragImage(
+ dragImage,
+ event.clientX - labelRect.left,
+ orderedLayers.indexOf(layer) * ROW_HEIGHT + event.clientY - labelRect.top,
+ );
+ requestAnimationFrame(() => dragImage.remove());
+ }
+
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("application/x-remotion-layer-reorder", "move");
+ setReorderDrag({
+ nodes: nodes as NodeReference[],
+ sourceKeys: sourceLayers.map((sourceLayer) =>
+ getCanvasSelectionItemKey(sourceLayer!.selectionItem),
+ ),
+ targetId: null,
+ position: null,
+ });
+ },
+ [actions, host, layers],
+ );
+
+ const onDragOverLabel = useCallback(
+ (event: React.DragEvent, layer: Layer) => {
+ if (!reorderDrag || !layer.source) {
+ return;
+ }
+
+ const siblings = layers.filter(
+ (candidate) =>
+ candidate.source && areSiblingNodes(candidate.source, layer.source!),
+ );
+ const sourceIndexes = reorderDrag.nodes.map((node) =>
+ siblings.findIndex(
+ (candidate) =>
+ JSON.stringify(candidate.source?.nodePath) ===
+ JSON.stringify(node.nodePath),
+ ),
+ );
+ const targetIndex = siblings.indexOf(layer);
+ const position =
+ event.clientY < event.currentTarget.getBoundingClientRect().top + 15
+ ? "before"
+ : "after";
+ if (
+ sourceIndexes.some((index) => index === -1) ||
+ getCanvasSequenceReorderInsertionIndex({
+ sourceIndexes,
+ targetIndex,
+ position,
+ }) === null
+ ) {
+ setReorderDrag((current) =>
+ current?.targetId === null
+ ? current
+ : current && { ...current, targetId: null, position: null },
+ );
+ return;
+ }
+
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ setReorderDrag((current) =>
+ current?.targetId === layer.track.sequence.id &&
+ current.position === position
+ ? current
+ : current && {
+ ...current,
+ targetId: layer.track.sequence.id,
+ position,
+ },
+ );
+ },
+ [layers, reorderDrag],
+ );
+
+ const onDropLabel = useCallback(
+ (event: React.DragEvent, layer: Layer) => {
+ if (
+ !reorderDrag ||
+ !layer.source ||
+ reorderDrag.targetId !== layer.track.sequence.id ||
+ reorderDrag.position === null
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ void actions.reorderNodes(
+ reorderDrag.nodes,
+ layer.source,
+ reorderDrag.position,
+ );
+ setReorderDrag(null);
+ },
+ [actions, reorderDrag],
+ );
+
const frameFromClientX = useCallback(
(clientX: number) => {
const element = scrollRef.current;
@@ -1109,6 +1321,11 @@ export const Timeline: React.FC = () => {
durationInFrames={durationInFrames}
selected={selectedKeys.has(layerKey)}
drag={drag}
+ reorderDropPosition={
+ reorderDrag?.targetId === layer.track.sequence.id
+ ? reorderDrag.position
+ : null
+ }
keyframeRows={
!hasKeyframeRows
? "none"
@@ -1118,6 +1335,10 @@ export const Timeline: React.FC = () => {
}
onToggleKeyframeRows={toggleKeyframeRows}
onPointerDownBar={onPointerDownBar}
+ onDragStartLabel={onDragStartLabel}
+ onDragOverLabel={onDragOverLabel}
+ onDropLabel={onDropLabel}
+ onDragEndLabel={() => setReorderDrag(null)}
/>
{getVisibleKeyframeRows(layer).map((prop) => (
<KeyframeRow
diff --git a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
index c9dd5229b3..13c7b056a8 100644
--- a/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
+++ b/packages/template-vibe-code/src/editor/hooks/use-editor-actions.ts
@@ -4,6 +4,7 @@ import {
getCanvasKeyframeChangeOverride,
getCanvasKeyframeToggle,
getCanvasSelectionItemKey,
+ getCanvasSequenceReorderSelection,
type CanvasKeyframeChange,
type CanvasKeyframeEasing,
type CanvasSelectionInteraction,
@@ -24,7 +25,7 @@ import {
moveFolder,
renameComposition,
renameFolder,
- reorderNode as reorderNodeCodemod,
+ reorderNodes as reorderNodesCodemod,
resolveCompositionComponent,
setCompositionDefaultProps,
splitSequences,
@@ -626,6 +627,38 @@ export const ${componentName}: React.FC = () => {
}),
),
reorderNode: (node: NodeReference, direction: "up" | "down") => {
+ const draggedLayer = ref.current.layers.find(
+ (layer) =>
+ layer.source?.filePath === node.filePath &&
+ JSON.stringify(layer.source.nodePath) ===
+ JSON.stringify(node.nodePath),
+ );
+ const selectedNodePathInfos = draggedLayer
+ ? getCanvasSequenceReorderSelection({
+ draggedItem: draggedLayer.selectionItem,
+ selectedItems:
+ ref.current.host?.controller.selection.getSnapshot()
+ .selectedItems ?? [],
+ })
+ : [];
+ const nodesToMove = selectedNodePathInfos.map((info) => {
+ const layer = ref.current.layers.find(
+ (candidate) =>
+ getCanvasSelectionItemKey(candidate.selectionItem) ===
+ getCanvasSelectionItemKey({ type: "sequence", nodePathInfo: info }),
+ );
+ return layer?.source &&
+ info.numberOfSequencesWithThisNodePath === 1 &&
+ areSiblingNodes(layer.source, node)
+ ? layer.source
+ : null;
+ });
+ if (nodesToMove.some((selectedNode) => selectedNode === null)) {
+ notify("Selected clips must be unique JSX siblings to reorder.");
+ return Promise.resolve(false);
+ }
+
+ const moving = nodesToMove.length > 0 ? nodesToMove : [node];
const siblings = ref.current.layers
.map((layer) => layer.source)
.filter(
@@ -640,25 +673,41 @@ export const ${componentName}: React.FC = () => {
JSON.stringify(source.nodePath),
) === index,
);
- const index = siblings.findIndex(
- (sibling) =>
- JSON.stringify(sibling.nodePath) === JSON.stringify(node.nodePath),
+ const selectedIndexes = moving.map((selectedNode) =>
+ siblings.findIndex(
+ (sibling) =>
+ JSON.stringify(sibling.nodePath) ===
+ JSON.stringify(selectedNode!.nodePath),
+ ),
);
- const target = siblings[direction === "up" ? index - 1 : index + 1];
- if (index === -1 || !target) {
+ const target =
+ siblings[
+ direction === "up"
+ ? Math.min(...selectedIndexes) - 1
+ : Math.max(...selectedIndexes) + 1
+ ];
+ if (selectedIndexes.some((index) => index === -1) || !target) {
notify("This layer cannot be moved further.");
return Promise.resolve(false);
}
return applyCodemod((project) =>
- reorderNodeCodemod({
+ reorderNodesCodemod({
project,
- node,
+ nodes: moving as NodeReference[],
target,
position: direction === "up" ? "before" : "after",
}),
);
},
+ reorderNodes: (
+ nodes: NodeReference[],
+ target: NodeReference,
+ position: "before" | "after",
+ ) =>
+ applyCodemod((project) =>
+ reorderNodesCodemod({ project, nodes, target, position }),
+ ),
updateNodeProps: (
node: NodeReference,
updates: SequencePropUpdate[],