🎥 Make videos programmatically with React
`@remotion/studio`: Constrain sequence reordering to vertical movement
JonnyBurger8e2d9a675e29
diff --git a/packages/example/e2e/sequence-reorder.test.mts b/packages/example/e2e/sequence-reorder.test.mtsindex cf4fa8ffae..538218778e 100644--- a/packages/example/e2e/sequence-reorder.test.mts+++ b/packages/example/e2e/sequence-reorder.test.mts@@ -1,8 +1,16 @@+import fs from 'fs';+import path from 'path';import {expect, test, type Page} from '@playwright/test';-import {STUDIO_URL} from './constants.mts';+import {STUDIO_URL, exampleDir} from './constants.mts';import {startStudio, stopStudio} from './studio-server.mts';const effectDragError = 'Could not read effect drag data';+const issue8216File = path.join(+ exampleDir,+ 'src',+ 'Issue8216',+ 'Issue8216.tsx',+);const dropOnTimelineRow = async ({page,@@ -38,12 +46,72 @@ const dropOnTimelineRow = async ({};test.describe('sequence reorder', () => {+ let sourceBefore: string;+test.beforeEach(async () => {+ sourceBefore = fs.readFileSync(issue8216File, 'utf-8');await startStudio();});test.afterEach(async () => {await stopStudio();+ fs.writeFileSync(issue8216File, sourceBefore);+ });++ test('reorders with a vertically constrained pointer preview', async ({+ page,+ }) => {+ await page.goto(`${STUDIO_URL}/issue-8216`);+ await expect(page).toHaveURL(/issue-8216/, {timeout: 15_000});+ await page.waitForFunction(+ () => !document.body.innerText.includes('Loading...'),+ {timeout: 30_000},+ );++ const source = page+ .locator('[title="Background"]')+ .first()+ .locator('xpath=ancestor::*[@data-remotion-sequence-reorder-row][1]');+ const target = page+ .locator('[title="Foreground"]')+ .first()+ .locator('xpath=ancestor::*[@data-remotion-sequence-reorder-row][1]');+ await expect(source).toBeVisible({timeout: 15_000});+ await expect(target).toBeVisible();+ await source.scrollIntoViewIfNeeded();++ const sourceBox = await source.boundingBox();+ const targetBox = await target.boundingBox();+ if (!sourceBox || !targetBox) {+ throw new Error('Expected sequence rows to have bounding boxes');+ }++ const startX = sourceBox.x + sourceBox.width / 2;+ const startY = sourceBox.y + sourceBox.height / 2;+ await page.mouse.move(startX, startY);+ await page.mouse.down();+ await page.mouse.move(startX + 80, targetBox.y + targetBox.height / 4, {+ steps: 5,+ });++ const preview = page.locator(+ '[data-remotion-sequence-reorder-preview="true"]',+ );+ await expect(preview).toBeVisible();+ const previewBox = await preview.boundingBox();+ expect(previewBox?.x).toBeCloseTo(sourceBox.x, 0);++ await page.mouse.up();+ await expect(preview).toHaveCount(0);+ await expect+ .poll(() => {+ const sourceCode = fs.readFileSync(issue8216File, 'utf-8');+ return (+ sourceCode.indexOf('name="Background"') <+ sourceCode.indexOf('name="Foreground"')+ );+ })+ .toBe(true);});test('does not parse sequence reorder data as effect drag data', async ({diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsxindex 15f12aa095..506d844114 100644--- a/packages/studio/src/components/Timeline/Timeline.tsx+++ b/packages/studio/src/components/Timeline/Timeline.tsx@@ -40,10 +40,6 @@ import {shouldSubscribeToSequenceProps} from './should-subscribe-to-sequence-proimport {SubscribeToNodePaths} from './SubscribeToNodePaths';import {TimelineAssetDropFrameContext} from './timeline-asset-drop-context';import {timelineVerticalScroll} from './timeline-refs';-import {- EDGE_SCROLL_VERTICAL_INCREMENT,- startTimelineEdgeAutoScroll,-} from './timeline-scroll-logic';import {TimelineDragHandler} from './TimelineDragHandler';import {TimelineHeightContainer} from './TimelineHeightContainer';import {TimelineInOutDragHandler} from './TimelineInOutDragHandler';@@ -62,11 +58,9 @@ import {TimelineSelectAllKeybindings,useTimelineSelection,} from './TimelineSelection';-import {SEQUENCE_REORDER_MIME_TYPE} from './TimelineSequenceItem';import {TimelineSlider} from './TimelineSlider';import {TimelineTickFormatProvider} from './TimelineTickFormatProvider';import {- TIMELINE_TIME_INDICATOR_HEIGHT,TimelineTimeIndicators,TimelineTimePlaceholders,} from './TimelineTimeIndicators';@@ -97,7 +91,6 @@ const TimelineContextMenuArea: React.FC<{Internals.CompositionManager,);const videoConfig = Internals.useUnsafeVideoConfig();- const isStill = useIsStill();const [isAddingSolid, setIsAddingSolid] = useState(false);const [isAddingAsset, setIsAddingAsset] = useState(false);const {previewServerState} = useContext(StudioServerConnectionCtx);@@ -106,56 +99,6 @@ const TimelineContextMenuArea: React.FC<{const browserStudioOperations = getBrowserStudioOperations();const browserStudioCanInsertSolid = browserStudioOperations !== null;- useEffect(() => {- const verticalScroll = timelineVerticalScroll.current;- if (!verticalScroll) {- return;- }-- const autoScroll = startTimelineEdgeAutoScroll({- includeHorizontal: false,- includeVertical: true,- verticalTopOffset: isStill ? 0 : TIMELINE_TIME_INDICATOR_HEIGHT,- onTick: (directions) => {- if (directions.y === null) {- return;- }-- verticalScroll.scrollTop +=- directions.y === 'up'- ? -EDGE_SCROLL_VERTICAL_INCREMENT- : EDGE_SCROLL_VERTICAL_INCREMENT;- },- });-- const onDragOver = (event: DragEvent) => {- if (- !event.dataTransfer ||- !Array.from(event.dataTransfer.types).includes(- SEQUENCE_REORDER_MIME_TYPE,- )- ) {- autoScroll.stop();- return;- }-- autoScroll.update(event);- };-- const stopAutoScroll = () => autoScroll.stop();-- verticalScroll.addEventListener('dragover', onDragOver, true);- document.addEventListener('dragend', stopAutoScroll, true);- document.addEventListener('drop', stopAutoScroll, true);-- return () => {- autoScroll.stop();- verticalScroll.removeEventListener('dragover', onDragOver, true);- document.removeEventListener('dragend', stopAutoScroll, true);- document.removeEventListener('drop', stopAutoScroll, true);- };- }, [isStill]);-const currentCompositionId =canvasContent?.type === 'composition' ? canvasContent.compositionId : null;const currentComposition = useMemo(() => {diff --git a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsxindex 4822b45d40..2af098e587 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceItem.tsx@@ -1,5 +1,12 @@import {type ReorderSequencePosition} from '@remotion/studio-shared';-import React, {useCallback, useContext, useMemo, useState} from 'react';+import React, {+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import type {_InternalTypes,SequencePropsSubscriptionKey,@@ -24,6 +31,8 @@ import {isStudioInteractivityEnabled,isStudioSelectionEnabled,} from '../../helpers/interactivity-enabled';+import {useIsStill} from '../../helpers/is-current-selected-still';+import {startCapturedPointerSession} from '../../helpers/pointer-session';import {getStudioKeyboardShortcutsEnabled} from '../../helpers/studio-runtime-config';import {getTimelineLayerHeight,@@ -71,6 +80,11 @@ import {getSequenceSplitMenuItem} from './get-sequence-split-menu-item';import {getCurrentFrame} from './imperative-state';import {saveSequenceProps} from './save-sequence-prop';import {getTimelineAssetLinkInfo} from './timeline-asset-link';+import {timelineVerticalScroll} from './timeline-refs';+import {+ EDGE_SCROLL_VERTICAL_INCREMENT,+ startTimelineEdgeAutoScroll,+} from './timeline-scroll-logic';import {TimelineDuplicateCount} from './TimelineDuplicateCount';import {TimelineExpandArrowButton,@@ -90,6 +104,7 @@ import {useTimelineSelection,} from './TimelineSelection';import {TimelineSequenceName} from './TimelineSequenceName';+import {TIMELINE_TIME_INDICATOR_HEIGHT} from './TimelineTimeIndicators';import {useDeleteTimelineItems} from './use-delete-timeline-items';import {useOpenSequenceInApps} from './use-open-sequence-in-apps';import {useRenameSequence} from './use-rename-sequence';@@ -117,8 +132,7 @@ const effectDropHighlight: React.CSSProperties = {outlineOffset: -1,};-export const SEQUENCE_REORDER_MIME_TYPE =- 'application/remotion-sequence-reorder';+const SEQUENCE_REORDER_MIME_TYPE = 'application/remotion-sequence-reorder';type SequenceReorderDragData = {readonly nodePath: SequencePropsSubscriptionKey;@@ -128,8 +142,6 @@ type SequenceReorderDragData = {readonly fileName: string;};-let currentSequenceDrag: SequenceReorderDragData | null = null;-type TimelineSequenceExpandArrowProps = {readonly disabled: boolean;readonly isExpanded: boolean;@@ -215,40 +227,7 @@ const hasSequenceReorderDragType = (dataTransfer: DataTransfer) => {};const isSequenceReorderDrag = (dataTransfer: DataTransfer) => {- return (- currentSequenceDrag !== null || hasSequenceReorderDragType(dataTransfer)- );-};--const getSequenceReorderDragData = (- dataTransfer: DataTransfer,-): SequenceReorderDragData | null => {- if (currentSequenceDrag) {- return currentSequenceDrag;- }-- const value = dataTransfer.getData(SEQUENCE_REORDER_MIME_TYPE);- if (!value) {- return null;- }-- try {- const parsed = JSON.parse(value) as SequenceReorderDragData;- if (- typeof parsed.nodePathKey === 'string' &&- typeof parsed.siblingIndex === 'number' &&- (typeof parsed.parentId === 'string' || parsed.parentId === null) &&- typeof parsed.fileName === 'string' &&- parsed.nodePath &&- Array.isArray(parsed.nodePath.nodePath)- ) {- return parsed;- }- } catch {- return null;- }-- return null;+ return hasSequenceReorderDragType(dataTransfer);};const getDestinationIndex = ({@@ -272,6 +251,48 @@ type SequenceDropTarget =readonly reason: string;};+type SequencePointerDropTarget = {+ readonly getDropTarget: (+ clientY: number,+ dragData: SequenceReorderDragData,+ ) => SequenceDropTarget | null;+ readonly setDropIndicator: (position: ReorderSequencePosition | null) => void;+ readonly reorder: (+ dropTarget: Extract<SequenceDropTarget, {type: 'valid'}>,+ ) => void;+};++const sequencePointerDropTargets = new Map<+ HTMLDivElement,+ SequencePointerDropTarget+>();++const getSequencePointerDropTargetAtPoint = ({+ clientX,+ clientY,+}: {+ readonly clientX: number;+ readonly clientY: number;+}) => {+ for (const element of document.elementsFromPoint(clientX, clientY)) {+ let current: Element | null = element;+ while (current) {+ const dropTarget = sequencePointerDropTargets.get(+ current as HTMLDivElement,+ );+ if (dropTarget) {+ return dropTarget;+ }++ current = current.parentElement;+ }+ }++ return null;+};++const SEQUENCE_REORDER_POINTER_THRESHOLD = 3;+const TimelineSequenceItemInner: React.FC<{readonly afterDropLineOffset: number;readonly sequence: TSequence;@@ -297,6 +318,7 @@ const TimelineSequenceItemInner: React.FC<{const {previewServerState} = useContext(StudioServerConnectionCtx);const previewConnected = previewServerState.type === 'connected';const previewInteractive = previewConnected && isStudioInteractivityEnabled();+ const isStill = useIsStill();const canMutateEffects =previewConnected && isStudioSelectionEnabled() && canUseEffectOperations();const {getIsExpanded} = useContext(ExpandedTracksGetterContext);@@ -327,6 +349,9 @@ const TimelineSequenceItemInner: React.FC<{const [isRenaming, setIsRenaming] = useState(false);const [sequenceDropIndicator, setSequenceDropIndicator] =useState<ReorderSequencePosition | null>(null);+ const sequenceReorderWrapperRef = useRef<HTMLDivElement>(null);+ const stopSequencePointerSession = useRef<(() => void) | null>(null);+ const suppressNextClick = useRef(false);const {canOpenInEditor,canConfigureApps,@@ -480,12 +505,10 @@ const TimelineSequenceItemInner: React.FC<{]);const getSequenceDropTarget = useCallback(- (e: React.DragEvent<HTMLDivElement>): SequenceDropTarget | null => {- const dragData = getSequenceReorderDragData(e.dataTransfer);- if (!dragData) {- return null;- }-+ (+ clientY: number,+ dragData: SequenceReorderDragData,+ ): SequenceDropTarget | null => {if (!nodePath || !nodePathKey || !validatedLocation?.source) {return {type: 'invalid',@@ -517,8 +540,13 @@ const TimelineSequenceItemInner: React.FC<{};}- const rect = e.currentTarget.getBoundingClientRect();- const before = e.clientY < rect.top + rect.height / 2;+ const element = sequenceReorderWrapperRef.current;+ if (!element) {+ return null;+ }++ const rect = element.getBoundingClientRect();+ const before = clientY < rect.top + rect.height / 2;const insertionIndex = before ? siblingIndex : siblingIndex + 1;const toIndex = getDestinationIndex({fromIndex: dragData.siblingIndex,@@ -548,132 +576,246 @@ const TimelineSequenceItemInner: React.FC<{],);- const onSequenceDragStart = useCallback(- (e: React.DragEvent<HTMLDivElement>) => {+ const reorderSequenceFromPointer = useCallback(+ async (dropTarget: Extract<SequenceDropTarget, {type: 'valid'}>) => {if (!canReorderSequence ||+ previewServerState.type !== 'connected' ||!nodePath ||- !nodePathKey ||!validatedLocation?.source) {- e.preventDefault();return;}- const dragData = {- nodePath,- nodePathKey,- siblingIndex,- parentId,- fileName: validatedLocation.source,- };- currentSequenceDrag = dragData;- e.dataTransfer.effectAllowed = 'move';- e.dataTransfer.setData(- SEQUENCE_REORDER_MIME_TYPE,- JSON.stringify(dragData),- );- e.stopPropagation();+ try {+ const result = await reorderSequence({+ fileName: validatedLocation.source,+ sourceNodePath: dropTarget.dragData.nodePath,+ targetNodePath: nodePath,+ position: dropTarget.position,+ clientId: previewServerState.clientId,+ });++ if (!result.success) {+ showNotification(result.reason, 4000);+ }+ } catch (err) {+ showNotification((err as Error).message, 4000);+ }},[canReorderSequence,nodePath,- nodePathKey,- parentId,- siblingIndex,+ previewServerState,validatedLocation?.source,],);- const onSequenceDragEnd = useCallback(() => {- currentSequenceDrag = null;- setSequenceDropIndicator(null);- }, []);-- const onSequenceDragOver = useCallback(- (e: React.DragEvent<HTMLDivElement>) => {- if (!hasSequenceReorderDragType(e.dataTransfer)) {- return;- }+ useEffect(() => {+ const element = sequenceReorderWrapperRef.current;+ if (!element || !canHandleSequenceDrag) {+ return;+ }- const dropTarget = getSequenceDropTarget(e);- if (!dropTarget) {- setSequenceDropIndicator(null);- return;- }+ const pointerDropTarget: SequencePointerDropTarget = {+ getDropTarget: getSequenceDropTarget,+ reorder: (dropTarget) => {+ reorderSequenceFromPointer(dropTarget).catch(() => undefined);+ },+ setDropIndicator: setSequenceDropIndicator,+ };+ sequencePointerDropTargets.set(element, pointerDropTarget);- if (dropTarget.type === 'invalid') {- setSequenceDropIndicator(null);- e.dataTransfer.dropEffect = 'none';- return;- }+ return () => {+ sequencePointerDropTargets.delete(element);+ };+ }, [+ canHandleSequenceDrag,+ getSequenceDropTarget,+ reorderSequenceFromPointer,+ ]);- e.preventDefault();- e.stopPropagation();- e.dataTransfer.dropEffect = 'move';- setSequenceDropIndicator(dropTarget.position);- },- [getSequenceDropTarget],- );+ useEffect(() => {+ return () => stopSequencePointerSession.current?.();+ }, []);- const onSequenceDragLeave = useCallback(- (e: React.DragEvent<HTMLDivElement>) => {- if (e.currentTarget.contains(e.relatedTarget as Node | null)) {+ const onSequencePointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (!(e.target instanceof Element)) {return;}- setSequenceDropIndicator(null);- },- [],- );-- const onSequenceDrop = useCallback(- async (e: React.DragEvent<HTMLDivElement>) => {if (+ e.button !== 0 ||+ !e.isPrimary ||+ e.target.closest('[data-remotion-sequence-reorder-row]') !==+ e.currentTarget ||+ e.target.closest(+ 'button, input, textarea, select, [contenteditable="true"], [data-timeline-layer-eye]',+ ) ||!canReorderSequence ||- previewServerState.type !== 'connected' ||!nodePath ||+ !nodePathKey ||!validatedLocation?.source) {return;}- const dropTarget = getSequenceDropTarget(e);- if (!dropTarget || dropTarget.type === 'invalid') {- setSequenceDropIndicator(null);- return;- }-- e.preventDefault();- e.stopPropagation();- setSequenceDropIndicator(null);- currentSequenceDrag = null;+ stopSequencePointerSession.current?.();- try {- const result = await reorderSequence({- fileName: validatedLocation.source,- sourceNodePath: dropTarget.dragData.nodePath,- targetNodePath: nodePath,- position: dropTarget.position,- clientId: previewServerState.clientId,+ const dragData: SequenceReorderDragData = {+ fileName: validatedLocation.source,+ nodePath,+ nodePathKey,+ parentId,+ siblingIndex,+ };+ const sourceElement = e.currentTarget;+ const sourceRect = sourceElement.getBoundingClientRect();+ const startX = e.clientX;+ const startY = e.clientY;+ let currentClientY = startY;+ let dragPreview: HTMLDivElement | null = null;+ let activeDropTarget: SequencePointerDropTarget | null = null;+ let activeDrop: Extract<SequenceDropTarget, {type: 'valid'}> | null =+ null;+ let didDrag = false;+ let previousUserSelect = '';+ let previousWebkitUserSelect = '';++ const updateDropTarget = (clientY: number) => {+ const pointerDropTarget = getSequencePointerDropTargetAtPoint({+ clientX: startX,+ clientY,});+ const dropTarget = pointerDropTarget?.getDropTarget(clientY, dragData);- if (!result.success) {- showNotification(result.reason, 4000);+ if (activeDropTarget !== pointerDropTarget) {+ activeDropTarget?.setDropIndicator(null);}- } catch (err) {- showNotification((err as Error).message, 4000);- }++ activeDropTarget = pointerDropTarget;+ activeDrop = dropTarget?.type === 'valid' ? dropTarget : null;+ activeDropTarget?.setDropIndicator(activeDrop?.position ?? null);+ };++ const verticalScroll = timelineVerticalScroll.current;+ const autoScroll = startTimelineEdgeAutoScroll({+ includeHorizontal: false,+ includeVertical: true,+ verticalTopOffset: isStill ? 0 : TIMELINE_TIME_INDICATOR_HEIGHT,+ onTick: (directions) => {+ if (directions.y === null || !verticalScroll) {+ return;+ }++ verticalScroll.scrollTop +=+ directions.y === 'up'+ ? -EDGE_SCROLL_VERTICAL_INCREMENT+ : EDGE_SCROLL_VERTICAL_INCREMENT;+ updateDropTarget(currentClientY);+ },+ });++ stopSequencePointerSession.current = startCapturedPointerSession({+ captureTarget: sourceElement,+ event: e.nativeEvent,+ onMove: (pointerEvent) => {+ currentClientY = pointerEvent.clientY;+ if (+ !didDrag &&+ Math.hypot(+ pointerEvent.clientX - startX,+ pointerEvent.clientY - startY,+ ) < SEQUENCE_REORDER_POINTER_THRESHOLD+ ) {+ return;+ }++ if (!didDrag) {+ didDrag = true;+ previousUserSelect = document.body.style.userSelect;+ previousWebkitUserSelect = document.body.style.webkitUserSelect;+ document.body.style.userSelect = 'none';+ document.body.style.webkitUserSelect = 'none';++ dragPreview = sourceElement.cloneNode(true) as HTMLDivElement;+ dragPreview.setAttribute('aria-hidden', 'true');+ dragPreview.setAttribute(+ 'data-remotion-sequence-reorder-preview',+ 'true',+ );+ dragPreview.removeAttribute('data-remotion-sequence-reorder-row');+ Object.assign(dragPreview.style, {+ height: `${sourceRect.height}px`,+ left: `${sourceRect.left}px`,+ margin: '0',+ opacity: '0.8',+ pointerEvents: 'none',+ position: 'fixed',+ top: `${sourceRect.top}px`,+ width: `${sourceRect.width}px`,+ zIndex: '2147483647',+ });+ document.body.appendChild(dragPreview);+ }++ pointerEvent.preventDefault();+ dragPreview!.style.transform = `translate3d(0, ${pointerEvent.clientY - startY}px, 0)`;+ updateDropTarget(pointerEvent.clientY);+ autoScroll.update({clientX: startX, clientY: pointerEvent.clientY});+ },+ onEnd: (reason, pointerEvent) => {+ if (reason === 'pointerup' && pointerEvent && didDrag) {+ updateDropTarget(pointerEvent.clientY);+ }++ autoScroll.stop();+ activeDropTarget?.setDropIndicator(null);+ dragPreview?.remove();+ stopSequencePointerSession.current = null;++ if (!didDrag) {+ return;+ }++ document.body.style.userSelect = previousUserSelect;+ document.body.style.webkitUserSelect = previousWebkitUserSelect;+ suppressNextClick.current = true;+ setTimeout(() => {+ suppressNextClick.current = false;+ }, 0);++ if (reason === 'pointerup' && pointerEvent && activeDrop) {+ activeDropTarget?.reorder(activeDrop);+ }+ },+ });},[canReorderSequence,- getSequenceDropTarget,+ isStill,nodePath,- previewServerState,+ nodePathKey,+ parentId,+ siblingIndex,validatedLocation?.source,],);+ const onSequenceClickCapture = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (!suppressNextClick.current) {+ return;+ }++ e.preventDefault();+ e.stopPropagation();+ suppressNextClick.current = false;+ },+ [],+ );+const mediaSrc =sequence.type === 'audio' ||sequence.type === 'video' ||@@ -1343,14 +1485,12 @@ const TimelineSequenceItemInner: React.FC<{</TimelineRowChrome>);- const draggableTrackRow = canHandleSequenceDrag ? (+ const reorderableTrackRow = canHandleSequenceDrag ? (<div- draggable={canReorderSequence}- onDragStart={onSequenceDragStart}- onDragEnd={onSequenceDragEnd}- onDragOver={onSequenceDragOver}- onDragLeave={onSequenceDragLeave}- onDrop={onSequenceDrop}+ ref={sequenceReorderWrapperRef}+ data-remotion-sequence-reorder-row+ onClickCapture={onSequenceClickCapture}+ onPointerDownCapture={onSequencePointerDown}style={sequenceReorderWrapper}>{sequenceReorderLineStyle ? (@@ -1376,10 +1516,10 @@ const TimelineSequenceItemInner: React.FC<{<>{previewConnected || window.remotion_isReadOnlyStudio ? (<ContextMenu getItems={getContextMenuItems}>- {draggableTrackRow}+ {reorderableTrackRow}</ContextMenu>) : (- draggableTrackRow+ reorderableTrackRow)}{previewConnected &&isStudioInteractivityEnabled() &&