Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Allow reordering effects [LGTM after hand commit] (#7978)

Jonny Burgerb25726783872
diff --git a/packages/studio-server/src/codemods/reorder-effect.ts b/packages/studio-server/src/codemods/reorder-effect.ts
new file mode 100644
index 0000000000..d35b74adc5
--- /dev/null
+++ b/packages/studio-server/src/codemods/reorder-effect.ts
@@ -0,0 +1,95 @@
+import type {ArrayExpression, Expression, JSXAttribute} from '@babel/types';
+import type {SequenceNodePath} from 'remotion';
+import {findJsxElementAtNodePath} from '../preview-server/routes/can-update-sequence-props';
+import {formatFileContent} from './format-file-content';
+import {parseAst, serializeAst} from './parse-ast';
+import {
+ enumerateEffectArrayElements,
+ findEffectsAttr,
+} from './update-effect-props/update-effect-props';
+
+const getEffectsArray = (attr: JSXAttribute): ArrayExpression => {
+ if (!attr.value || attr.value.type !== 'JSXExpressionContainer') {
+ throw new Error('Cannot reorder effect: effects prop is not an array');
+ }
+
+ const expr = attr.value.expression as Expression;
+ if (expr.type !== 'ArrayExpression') {
+ throw new Error('Cannot reorder effect: effects prop is not an array');
+ }
+
+ return expr;
+};
+
+export const reorderEffect = async ({
+ input,
+ sequenceNodePath,
+ fromIndex,
+ toIndex,
+ prettierConfigOverride,
+}: {
+ input: string;
+ sequenceNodePath: SequenceNodePath;
+ fromIndex: number;
+ toIndex: number;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): Promise<{
+ output: string;
+ formatted: boolean;
+ effectLabel: string;
+ logLine: number;
+}> => {
+ const ast = parseAst(input);
+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);
+ if (!jsx) {
+ throw new Error(
+ 'Could not find a JSX element at the specified location to reorder effect',
+ );
+ }
+
+ const attr = findEffectsAttr(jsx.attributes ?? []);
+ if (!attr) {
+ throw new Error('Could not find effects on the target JSX element');
+ }
+
+ const effectsArray = getEffectsArray(attr);
+ const elements = enumerateEffectArrayElements(effectsArray);
+ if (fromIndex < 0 || fromIndex >= elements.length) {
+ throw new Error('Cannot reorder effect: source index not-found');
+ }
+
+ if (toIndex < 0 || toIndex >= elements.length) {
+ throw new Error('Cannot reorder effect: target index not-found');
+ }
+
+ const target = elements[fromIndex];
+ if (target.kind !== 'call') {
+ throw new Error(
+ 'Cannot reorder effect: source effect is not-call-expression',
+ );
+ }
+
+ if (fromIndex !== toIndex) {
+ const [moved] = effectsArray.elements.splice(fromIndex, 1);
+ if (!moved) {
+ throw new Error(
+ 'Cannot reorder effect: source effect is not-call-expression',
+ );
+ }
+
+ effectsArray.elements.splice(toIndex, 0, moved);
+ }
+
+ const finalFile = serializeAst(ast);
+ const {output, formatted} = await formatFileContent({
+ input: finalFile,
+ prettierConfigOverride,
+ });
+
+ return {
+ output,
+ formatted,
+ effectLabel: `${target.callee}()`,
+ logLine: target.node.loc?.start.line ?? jsx.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.ts
index 8aa0380bee..6e8bf8dbee 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -22,6 +22,7 @@ import {projectInfoHandler} from './routes/project-info';
import {redoHandler} from './routes/redo';
import {registerClientRenderHandler} from './routes/register-client-render';
import {handleRemoveRender} from './routes/remove-render';
+import {reorderEffectHandler} from './routes/reorder-effect';
import {handleRestartStudio} from './routes/restart-studio';
import {saveEffectPropsHandler} from './routes/save-effect-props';
import {saveSequencePropsHandler} from './routes/save-sequence-props';
@@ -62,6 +63,7 @@ export const allApiRoutes: {
'/api/save-sequence-props': saveSequencePropsHandler,
'/api/save-effect-props': saveEffectPropsHandler,
'/api/add-effect': addEffectHandler,
+ '/api/reorder-effect': reorderEffectHandler,
'/api/delete-sequence-keyframe': deleteSequenceKeyframeHandler,
'/api/add-sequence-keyframe': addSequenceKeyframeHandler,
'/api/delete-effect-keyframe': deleteEffectKeyframeHandler,
diff --git a/packages/studio-server/src/preview-server/routes/reorder-effect.ts b/packages/studio-server/src/preview-server/routes/reorder-effect.ts
new file mode 100644
index 0000000000..c22a10de06
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/reorder-effect.ts
@@ -0,0 +1,95 @@
+import {readFileSync} from 'node:fs';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ ReorderEffectRequest,
+ ReorderEffectResponse,
+} from '@remotion/studio-shared';
+import {reorderEffect} from '../../codemods/reorder-effect';
+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 {attrName} from './log-updates/formatting';
+import {warnAboutPrettierOnce} from './log-updates/log-update';
+
+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}`,
+ );
+
+ 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,
+ });
+
+ 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);
+ }
+
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[reorder-effect] Wrote ${fileRelativeToRoot}${formatted ? ' (formatted)' : ''}`,
+ );
+
+ printUndoHint(logLevel);
+
+ return {
+ success: true,
+ };
+ } catch (err) {
+ return {
+ success: false,
+ reason: (err as Error).message,
+ stack: (err as Error).stack as string,
+ };
+ }
+};
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index f4fb3592ad..683adcf75e 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -23,6 +23,7 @@ type UndoEntryType =
| 'effect-props'
| 'add-effect'
| 'delete-effect'
+ | 'reorder-effect'
| 'delete-jsx-node'
| 'duplicate-jsx-node'
| 'insert-jsx-element'
@@ -53,6 +54,7 @@ type UndoEntry = {
| {entryType: 'effect-props'}
| {entryType: 'add-effect'}
| {entryType: 'delete-effect'}
+ | {entryType: 'reorder-effect'}
| {entryType: 'delete-jsx-node'}
| {entryType: 'duplicate-jsx-node'}
| {entryType: 'insert-jsx-element'}
diff --git a/packages/studio-server/src/test/reorder-effect.test.ts b/packages/studio-server/src/test/reorder-effect.test.ts
new file mode 100644
index 0000000000..d7f29c02fd
--- /dev/null
+++ b/packages/studio-server/src/test/reorder-effect.test.ts
@@ -0,0 +1,75 @@
+import {expect, test} from 'bun:test';
+import {reorderEffect} from '../codemods/reorder-effect';
+import {lineColumnToNodePath} from './test-utils';
+
+const buildInput = (
+ effects: string,
+) => `import {HtmlInCanvas} from '@remotion/html-in-canvas';
+import {blur} from '@remotion/effects/blur';
+import {brightness} from '@remotion/effects/brightness';
+import {tint} from '@remotion/effects/tint';
+
+export const Comp = () => {
+ return (
+ <HtmlInCanvas effects={${effects}}>
+ hi
+ </HtmlInCanvas>
+ );
+};
+`;
+
+test('reorderEffect moves an effect forward', async () => {
+ const input = buildInput(
+ '[blur({amount: 1}), brightness({amount: 2}), tint({color: "red"})]',
+ );
+ const {output, effectLabel} = await reorderEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ fromIndex: 0,
+ toIndex: 2,
+ });
+
+ expect(effectLabel).toBe('blur()');
+ expect(output.indexOf('brightness({')).toBeLessThan(output.indexOf('tint({'));
+ expect(output.indexOf('tint({')).toBeLessThan(output.indexOf('blur({'));
+});
+
+test('reorderEffect moves an effect backward', async () => {
+ const input = buildInput(
+ '[blur({amount: 1}), brightness({amount: 2}), tint({color: "red"})]',
+ );
+ const {output, effectLabel} = await reorderEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ fromIndex: 2,
+ toIndex: 0,
+ });
+
+ expect(effectLabel).toBe('tint()');
+ expect(output.indexOf('tint({')).toBeLessThan(output.indexOf('blur({'));
+ expect(output.indexOf('blur({')).toBeLessThan(output.indexOf('brightness({'));
+});
+
+test('reorderEffect throws when source index is out of range', async () => {
+ const input = buildInput('[tint({color: "red"})]');
+ await expect(
+ reorderEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ fromIndex: 4,
+ toIndex: 0,
+ }),
+ ).rejects.toThrow(/source index not-found/);
+});
+
+test('reorderEffect throws when effects are not an inline array', async () => {
+ const input = buildInput('effects');
+ await expect(
+ reorderEffect({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 8),
+ fromIndex: 0,
+ toIndex: 0,
+ }),
+ ).rejects.toThrow(/not an array/);
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 83b31d3c45..24b4875fdf 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -339,6 +339,24 @@ export type AddEffectResponse =
stack: string;
};
+export type ReorderEffectRequest = {
+ fileName: string;
+ sequenceNodePath: SequencePropsSubscriptionKey;
+ fromIndex: number;
+ toIndex: number;
+ clientId: string;
+};
+
+export type ReorderEffectResponse =
+ | {
+ success: true;
+ }
+ | {
+ success: false;
+ reason: string;
+ stack: string;
+ };
+
export type DeleteSequenceKeyframeRequest = {
fileName: string;
nodePath: SequencePropsSubscriptionKey;
@@ -564,6 +582,7 @@ export type ApiRoutes = {
SaveEffectPropsResponse
>;
'/api/add-effect': ReqAndRes<AddEffectRequest, AddEffectResponse>;
+ '/api/reorder-effect': ReqAndRes<ReorderEffectRequest, ReorderEffectResponse>;
'/api/delete-sequence-keyframe': ReqAndRes<
DeleteSequenceKeyframeRequest,
DeleteSequenceKeyframeResponse
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 082ea0d6fb..3e76aa3545 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -46,6 +46,8 @@ export {
RedoRequest,
RedoResponse,
RemoveRenderRequest,
+ ReorderEffectRequest,
+ ReorderEffectResponse,
RestartStudioRequest,
RestartStudioResponse,
SaveEffectPropsRequest,
diff --git a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx b/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
index 283b38b28e..f0710c3d29 100644
--- a/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineEffectItem.tsx
@@ -1,4 +1,4 @@
-import React, {useCallback, useContext, useMemo} from 'react';
+import React, {useCallback, useContext, useMemo, useState} from 'react';
import type {SequencePropsSubscriptionKey, SequenceSchema} from 'remotion';
import {Internals} from 'remotion';
import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-source-map';
@@ -20,15 +20,85 @@ import {TimelineRowChrome} from './TimelineRowChrome';
import {
getTimelineColor,
getTimelineSelectedLabelStyle,
+ SELECTION_ENABLED,
useTimelineRowSelection,
} from './TimelineSelection';
+const EFFECT_REORDER_MIME_TYPE = 'application/remotion-effect-reorder';
+
+type EffectReorderDragData = {
+ readonly nodePathKey: string;
+ readonly effectIndex: number;
+};
+
+let currentEffectDrag: EffectReorderDragData | null = null;
+
const rowLabel: React.CSSProperties = {
fontSize: 12,
color: 'rgba(255, 255, 255, 0.8)',
userSelect: 'none',
};
+const rowStyle: React.CSSProperties = {
+ height: TREE_GROUP_ROW_HEIGHT,
+ cursor: 'default',
+};
+
+const reorderWrapper: React.CSSProperties = {
+ position: 'relative',
+};
+
+const reorderLineBase: React.CSSProperties = {
+ backgroundColor: '#0b84ff',
+ height: 2,
+ left: 0,
+ pointerEvents: 'none',
+ position: 'absolute',
+ right: 0,
+ zIndex: 1,
+};
+
+const hasEffectReorderDragType = (dataTransfer: DataTransfer) => {
+ return Array.from(dataTransfer.types).includes(EFFECT_REORDER_MIME_TYPE);
+};
+
+const getEffectReorderDragData = (
+ dataTransfer: DataTransfer,
+): EffectReorderDragData | null => {
+ if (currentEffectDrag) {
+ return currentEffectDrag;
+ }
+
+ const value = dataTransfer.getData(EFFECT_REORDER_MIME_TYPE);
+ if (!value) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(value) as EffectReorderDragData;
+ if (
+ typeof parsed.nodePathKey === 'string' &&
+ typeof parsed.effectIndex === 'number'
+ ) {
+ return parsed;
+ }
+ } catch {
+ return null;
+ }
+
+ return null;
+};
+
+const getDestinationIndex = ({
+ fromIndex,
+ insertionIndex,
+}: {
+ readonly fromIndex: number;
+ readonly insertionIndex: number;
+}) => {
+ return insertionIndex > fromIndex ? insertionIndex - 1 : insertionIndex;
+};
+
export const TimelineEffectItem: React.FC<{
readonly label: string;
readonly nodePathInfo: SequenceNodePathInfo;
@@ -57,6 +127,9 @@ export const TimelineEffectItem: React.FC<{
const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);
const {setCodeValues} = useContext(Internals.VisualModeSettersContext);
const selection = useTimelineRowSelection(nodePathInfo);
+ const [dropIndicator, setDropIndicator] = useState<'before' | 'after' | null>(
+ null,
+ );
const effectStatus = useMemo(
() =>
@@ -89,6 +162,17 @@ export const TimelineEffectItem: React.FC<{
effectStatus.type !== 'can-update-effect' ||
!validatedLocation.source;
+ const canReorder =
+ SELECTION_ENABLED &&
+ previewConnected &&
+ effectStatus.type === 'can-update-effect' &&
+ Boolean(validatedLocation.source);
+
+ const nodePathKey = useMemo(
+ () => Internals.makeSequencePropsSubscriptionKey(nodePath),
+ [nodePath],
+ );
+
const onDeleteEffectFromSource = useCallback(async () => {
if (deleteDisabled) {
return;
@@ -206,13 +290,6 @@ export const TimelineEffectItem: React.FC<{
const isExpanded = getIsExpanded(nodePathInfo);
- const rowStyle = useMemo(
- (): React.CSSProperties => ({
- height: TREE_GROUP_ROW_HEIGHT,
- }),
- [],
- );
-
const labelStyle = useMemo((): React.CSSProperties => {
return {
...rowLabel,
@@ -227,6 +304,145 @@ export const TimelineEffectItem: React.FC<{
};
}, [selection.selected]);
+ const getDropTarget = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ const dragData = getEffectReorderDragData(e.dataTransfer);
+ if (!dragData || dragData.nodePathKey !== nodePathKey) {
+ return null;
+ }
+
+ const rect = e.currentTarget.getBoundingClientRect();
+ const before = e.clientY < rect.top + rect.height / 2;
+ const insertionIndex = before ? effectIndex : effectIndex + 1;
+ const toIndex = getDestinationIndex({
+ fromIndex: dragData.effectIndex,
+ insertionIndex,
+ });
+
+ if (toIndex === dragData.effectIndex) {
+ return null;
+ }
+
+ return {
+ dragData,
+ toIndex,
+ indicator: before ? ('before' as const) : ('after' as const),
+ };
+ },
+ [effectIndex, nodePathKey],
+ );
+
+ const onDragStart = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ if (!canReorder) {
+ e.preventDefault();
+ return;
+ }
+
+ const dragData = {nodePathKey, effectIndex};
+ currentEffectDrag = dragData;
+ e.dataTransfer.effectAllowed = 'move';
+ e.dataTransfer.setData(
+ EFFECT_REORDER_MIME_TYPE,
+ JSON.stringify(dragData),
+ );
+ e.stopPropagation();
+ },
+ [canReorder, effectIndex, nodePathKey],
+ );
+
+ const onDragEnd = useCallback(() => {
+ currentEffectDrag = null;
+ setDropIndicator(null);
+ }, []);
+
+ const onDragOver = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ if (!canReorder || !hasEffectReorderDragType(e.dataTransfer)) {
+ return;
+ }
+
+ const dropTarget = getDropTarget(e);
+ if (!dropTarget) {
+ setDropIndicator(null);
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ e.dataTransfer.dropEffect = 'move';
+ setDropIndicator(dropTarget.indicator);
+ },
+ [canReorder, getDropTarget],
+ );
+
+ const onDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
+ return;
+ }
+
+ setDropIndicator(null);
+ }, []);
+
+ const onDrop = useCallback(
+ async (e: React.DragEvent<HTMLDivElement>) => {
+ if (
+ !canReorder ||
+ previewServerState.type !== 'connected' ||
+ !validatedLocation.source
+ ) {
+ return;
+ }
+
+ const dropTarget = getDropTarget(e);
+ if (!dropTarget) {
+ setDropIndicator(null);
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ setDropIndicator(null);
+ currentEffectDrag = null;
+
+ try {
+ const result = await callApi('/api/reorder-effect', {
+ fileName: validatedLocation.source,
+ sequenceNodePath: nodePath,
+ fromIndex: dropTarget.dragData.effectIndex,
+ toIndex: dropTarget.toIndex,
+ clientId: previewServerState.clientId,
+ });
+
+ if (result.success) {
+ showNotification('Reordered effect', 2000);
+ } else {
+ showNotification(result.reason, 4000);
+ }
+ } catch (err) {
+ showNotification((err as Error).message, 4000);
+ }
+ },
+ [
+ canReorder,
+ getDropTarget,
+ nodePath,
+ previewServerState,
+ validatedLocation.source,
+ ],
+ );
+
+ const reorderLineStyle = useMemo((): React.CSSProperties | null => {
+ if (!dropIndicator) {
+ return null;
+ }
+
+ return {
+ ...reorderLineBase,
+ ...(dropIndicator === 'before' ? {top: -1} : {bottom: -1}),
+ };
+ }, [dropIndicator]);
+
const row = (
<TimelineRowChrome
depth={rowDepth}
@@ -263,14 +479,31 @@ export const TimelineEffectItem: React.FC<{
</TimelineRowChrome>
);
+ const draggableRow = canReorder ? (
+ <div
+ draggable
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ onDragOver={onDragOver}
+ onDragLeave={onDragLeave}
+ onDrop={onDrop}
+ style={reorderWrapper}
+ >
+ {reorderLineStyle ? <div style={reorderLineStyle} /> : null}
+ {row}
+ </div>
+ ) : (
+ row
+ );
+
return previewConnected ? (
<ContextMenu
values={contextMenuValues}
onOpen={selection.selectable ? selection.onSelect : null}
>
- {row}
+ {draggableRow}
</ContextMenu>
) : (
- row
+ draggableRow
);
};