🎥 Make videos programmatically with React
`@remotion/studio`: Allow clicking timeline tracks (behind flag) (#7765)
Jonny Burgerdb4dbe35aeab
diff --git a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.tsindex dd8c066000..5fcaf00d02 100644--- a/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts+++ b/packages/studio-server/src/codemods/update-keyframes/update-keyframes.ts@@ -477,6 +477,7 @@ export const updateSequenceKeyframesAst = ({}): {serialized: string;oldValueStrings: string[];+ newValueStrings: string[];logLine: number;} => {const ast = parseAst(input);@@ -492,23 +493,25 @@ export const updateSequenceKeyframesAst = ({}const oldValueStrings: string[] = [];+ const newValueStrings: string[] = [];for (const update of updates) {const prop = getSequenceWritableProp({attributes: node.attributes,key: update.key,});oldValueStrings.push(recast.print(prop.expression).code);- prop.setExpression(- applyKeyframeOperation({- expression: prop.expression,- operation: update.operation,- }),- );+ const nextExpression = applyKeyframeOperation({+ expression: prop.expression,+ operation: update.operation,+ });+ newValueStrings.push(recast.print(nextExpression).code);+ prop.setExpression(nextExpression);}return {serialized: serializeAst(ast),oldValueStrings,+ newValueStrings,logLine: node.loc?.start.line ?? 1,};};@@ -527,19 +530,21 @@ export const updateSequenceKeyframes = async ({output: string;formatted: boolean;oldValueStrings: string[];+ newValueStrings: string[];logLine: number;}> => {- const {serialized, oldValueStrings, logLine} = updateSequenceKeyframesAst({- input,- nodePath,- updates,- });+ const {serialized, oldValueStrings, newValueStrings, logLine} =+ updateSequenceKeyframesAst({+ input,+ nodePath,+ updates,+ });const {output, formatted} = await formatFileContent({input: serialized,prettierConfigOverride,});- return {output, formatted, oldValueStrings, logLine};+ return {output, formatted, oldValueStrings, newValueStrings, logLine};};export const updateEffectKeyframesAst = ({@@ -555,6 +560,7 @@ export const updateEffectKeyframesAst = ({}): {serialized: string;oldValueStrings: string[];+ newValueStrings: string[];logLine: number;effectCallee: string;} => {@@ -586,6 +592,7 @@ export const updateEffectKeyframesAst = ({const objExpr = call.arguments[0] as ObjectExpression;const oldValueStrings: string[] = [];+ const newValueStrings: string[] = [];for (const update of updates) {const {prop} = findObjectProperty(objExpr, update.key);if (!prop) {@@ -593,15 +600,18 @@ export const updateEffectKeyframesAst = ({}oldValueStrings.push(recast.print(prop.value).code);- prop.value = applyKeyframeOperation({+ const nextExpression = applyKeyframeOperation({expression: prop.value as Expression,operation: update.operation,- }) as ObjectProperty['value'];+ });+ newValueStrings.push(recast.print(nextExpression).code);+ prop.value = nextExpression as ObjectProperty['value'];}return {serialized: serializeAst(ast),oldValueStrings,+ newValueStrings,logLine: call.loc?.start.line ?? jsx.loc?.start.line ?? 1,effectCallee,};@@ -623,10 +633,11 @@ export const updateEffectKeyframes = async ({output: string;formatted: boolean;oldValueStrings: string[];+ newValueStrings: string[];logLine: number;effectCallee: string;}> => {- const {serialized, oldValueStrings, logLine, effectCallee} =+ const {serialized, oldValueStrings, newValueStrings, logLine, effectCallee} =updateEffectKeyframesAst({input,sequenceNodePath,@@ -638,5 +649,12 @@ export const updateEffectKeyframes = async ({prettierConfigOverride,});- return {output, formatted, oldValueStrings, logLine, effectCallee};+ return {+ output,+ formatted,+ oldValueStrings,+ newValueStrings,+ logLine,+ effectCallee,+ };};diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 3580f876ec..8e4b281c0a 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -5,7 +5,9 @@ import {applyCodemodHandler} from './routes/apply-codemod';import {applyVisualControlHandler} from './routes/apply-visual-control-change';import {handleCancelRender} from './routes/cancel-render';import {deleteEffectHandler} from './routes/delete-effect';+import {deleteEffectKeyframeHandler} from './routes/delete-effect-keyframe';import {deleteJsxNodeHandler} from './routes/delete-jsx-node';+import {deleteSequenceKeyframeHandler} from './routes/delete-sequence-keyframe';import {deleteStaticFileHandler} from './routes/delete-static-file';import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';import {handleInstallPackage} from './routes/install-dependency';@@ -47,6 +49,8 @@ export const allApiRoutes: {'/api/unsubscribe-from-sequence-props': unsubscribeFromSequenceProps,'/api/save-sequence-props': saveSequencePropsHandler,'/api/save-effect-props': saveEffectPropsHandler,+ '/api/delete-sequence-keyframe': deleteSequenceKeyframeHandler,+ '/api/delete-effect-keyframe': deleteEffectKeyframeHandler,'/api/delete-effect': deleteEffectHandler,'/api/delete-jsx-node': deleteJsxNodeHandler,'/api/duplicate-jsx-node': duplicateJsxNodeHandler,diff --git a/packages/studio-server/src/preview-server/routes/delete-effect-keyframe.ts b/packages/studio-server/src/preview-server/routes/delete-effect-keyframe.tsnew file mode 100644index 0000000000..4210e15b76--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/delete-effect-keyframe.ts@@ -0,0 +1,149 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ DeleteEffectKeyframeRequest,+ DeleteEffectKeyframeResponse,+} from '@remotion/studio-shared';+import {getAllSchemaKeys} from '@remotion/studio-shared';+import {parseAst} from '../../codemods/parse-ast';+import {updateEffectKeyframes} from '../../codemods/update-keyframes/update-keyframes';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {+ printUndoHint,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {computeEffectPropStatus} from './can-update-effect-props';+import {findJsxElementAtNodePath} from './can-update-sequence-props';+import {formatEffectPropChange} from './log-updates/format-effect-prop-change';+import {logEffectUpdate} from './log-updates/log-effect-update';+import {normalizeQuotes} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';++export const deleteEffectKeyframeHandler: ApiHandler<+ DeleteEffectKeyframeRequest,+ DeleteEffectKeyframeResponse+> = ({+ input: {+ fileName,+ sequenceNodePath,+ effectIndex,+ key,+ frame,+ schema,+ clientId,+ },+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[delete-effect-keyframe] Received request for fileName="${fileName}" effectIndex=${effectIndex} key="${key}" frame=${frame}`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');++ const {+ output,+ oldValueStrings,+ newValueStrings,+ formatted,+ logLine,+ effectCallee,+ } = await updateEffectKeyframes({+ input: fileContents,+ sequenceNodePath: sequenceNodePath.nodePath,+ effectIndex,+ updates: [+ {+ key,+ operation: {+ type: 'remove',+ frame,+ },+ },+ ],+ });++ const oldValueString = oldValueStrings[0];+ const newValueString = newValueStrings[0];+ const normalizedOld = normalizeQuotes(oldValueString);+ const normalizedNew = normalizeQuotes(newValueString);++ const undoPropChange = formatEffectPropChange({+ effectName: effectCallee,+ key,+ oldValueString: normalizedNew,+ newValueString: normalizedOld,+ defaultValueString: null,+ removedProps: [],+ addedProps: [],+ });+ const redoPropChange = formatEffectPropChange({+ effectName: effectCallee,+ key,+ oldValueString: normalizedOld,+ newValueString: normalizedNew,+ defaultValueString: null,+ removedProps: [],+ addedProps: [],+ });++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'effect-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);++ logEffectUpdate({+ fileRelativeToRoot,+ line: logLine,+ effectName: effectCallee,+ propKey: key,+ oldValueString,+ newValueString,+ defaultValueString: null,+ formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });++ printUndoHint(logLevel);++ const ast = parseAst(readFileSync(absolutePath, 'utf-8'));+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath.nodePath);+ if (!jsx) {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-found',+ };+ }++ return computeEffectPropStatus({+ jsx,+ effectIndex,+ keys: getAllSchemaKeys(schema),+ });+ });diff --git a/packages/studio-server/src/preview-server/routes/delete-sequence-keyframe.ts b/packages/studio-server/src/preview-server/routes/delete-sequence-keyframe.tsnew file mode 100644index 0000000000..dc00374ae7--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/delete-sequence-keyframe.ts@@ -0,0 +1,124 @@+import {readFileSync} from 'node:fs';+import {RenderInternals} from '@remotion/renderer';+import type {+ DeleteSequenceKeyframeRequest,+ DeleteSequenceKeyframeResponse,+} from '@remotion/studio-shared';+import {getAllSchemaKeys} from '@remotion/studio-shared';+import {updateSequenceKeyframes} from '../../codemods/update-keyframes/update-keyframes';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {+ printUndoHint,+ pushToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {suppressBundlerUpdateForFile} from '../watch-ignore-next-change';+import {computeSequencePropsStatusFromContent} from './can-update-sequence-props';+import {formatPropChange} from './log-updates/format-prop-change';+import {logUpdate, normalizeQuotes} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';++export const deleteSequenceKeyframeHandler: ApiHandler<+ DeleteSequenceKeyframeRequest,+ DeleteSequenceKeyframeResponse+> = ({+ input: {fileName, nodePath, key, frame, schema, clientId},+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[delete-sequence-keyframe] Received request for fileName="${fileName}" key="${key}" frame=${frame}`,+ );+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });++ const fileContents = readFileSync(absolutePath, 'utf-8');++ const {output, oldValueStrings, newValueStrings, formatted, logLine} =+ await updateSequenceKeyframes({+ input: fileContents,+ nodePath: nodePath.nodePath,+ updates: [+ {+ key,+ operation: {+ type: 'remove',+ frame,+ },+ },+ ],+ });++ const oldValueString = oldValueStrings[0];+ const newValueString = newValueStrings[0];+ const normalizedOld = normalizeQuotes(oldValueString);+ const normalizedNew = normalizeQuotes(newValueString);++ const undoPropChange = formatPropChange({+ key,+ oldValueString: normalizedNew,+ newValueString: normalizedOld,+ defaultValueString: null,+ removedProps: [],+ addedProps: [],+ });+ const redoPropChange = formatPropChange({+ key,+ oldValueString: normalizedOld,+ newValueString: normalizedNew,+ defaultValueString: null,+ removedProps: [],+ addedProps: [],+ });++ pushToUndoStack({+ filePath: absolutePath,+ oldContents: fileContents,+ logLevel,+ remotionRoot,+ logLine,+ description: {+ undoMessage: `↩️ ${undoPropChange}`,+ redoMessage: `↪️ ${redoPropChange}`,+ },+ entryType: 'sequence-props',+ suppressHmrOnFileRestore: true,+ });+ suppressUndoStackInvalidation(absolutePath);+ suppressBundlerUpdateForFile(absolutePath);+ writeFileAndNotifyFileWatchers(absolutePath, output, clientId);++ logUpdate({+ fileRelativeToRoot,+ line: logLine,+ key,+ oldValueString,+ newValueString,+ defaultValueString: null,+ formatted,+ logLevel,+ removedProps: [],+ addedProps: [],+ });++ printUndoHint(logLevel);++ const status = computeSequencePropsStatusFromContent({+ fileContents: output,+ keys: getAllSchemaKeys(schema),+ nodePath: nodePath.nodePath,+ effects: [],+ });++ return {+ canUpdate: true,+ props: status.props,+ };+ });diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 731b402fbc..faa252d9d6 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -281,6 +281,29 @@ export type SaveEffectPropsRequest = {export type SaveEffectPropsResponse = CanUpdateEffectPropsResponse;+export type DeleteSequenceKeyframeRequest = {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ key: string;+ frame: number;+ schema: SequenceSchema;+ clientId: string;+};++export type DeleteSequenceKeyframeResponse = SaveSequencePropsResponse;++export type DeleteEffectKeyframeRequest = {+ fileName: string;+ sequenceNodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ key: string;+ frame: number;+ schema: SequenceSchema;+ clientId: string;+};++export type DeleteEffectKeyframeResponse = SaveEffectPropsResponse;+export type DeleteEffectRequest = {fileName: string;sequenceNodePath: SequencePropsSubscriptionKey;@@ -414,6 +437,14 @@ export type ApiRoutes = {SaveEffectPropsRequest,SaveEffectPropsResponse>;+ '/api/delete-sequence-keyframe': ReqAndRes<+ DeleteSequenceKeyframeRequest,+ DeleteSequenceKeyframeResponse+ >;+ '/api/delete-effect-keyframe': ReqAndRes<+ DeleteEffectKeyframeRequest,+ DeleteEffectKeyframeResponse+ >;'/api/delete-effect': ReqAndRes<DeleteEffectRequest, DeleteEffectResponse>;'/api/delete-jsx-node': ReqAndRes<DeleteJsxNodeRequest,diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex de6508bbcd..1c5471e8eb 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -16,6 +16,10 @@ export {CopyStillToClipboardRequest,DeleteEffectRequest,DeleteEffectResponse,+ DeleteEffectKeyframeRequest,+ DeleteEffectKeyframeResponse,+ DeleteSequenceKeyframeRequest,+ DeleteSequenceKeyframeResponse,DeleteJsxNodeRequest,DeleteJsxNodeResponse,DuplicateJsxNodeRequest,@@ -121,6 +125,10 @@ export {export {EnumPath, stringifyDefaultProps} from './stringify-default-props';export type {VisualControlChange} from './codemods';+export {+ optimisticDeleteEffectKeyframe,+ optimisticDeleteSequenceKeyframe,+} from './optimistic-delete-keyframe';export {optimisticUpdateForCodeValues} from './optimistic-update-for-code-values';export {optimisticUpdateForEffectCodeValues} from './optimistic-update-for-effect-code-values';export {stringifySequenceSubscriptionKey} from './stringify-sequence-subscription-key';diff --git a/packages/studio-shared/src/optimistic-delete-keyframe.ts b/packages/studio-shared/src/optimistic-delete-keyframe.tsnew file mode 100644index 0000000000..733810a022--- /dev/null+++ b/packages/studio-shared/src/optimistic-delete-keyframe.ts@@ -0,0 +1,118 @@+import {+ type CanUpdateSequencePropsResponse,+ type CanUpdateSequencePropStatus,+} from 'remotion';++const removeKeyframeFromPropStatus = ({+ status,+ frame,+}: {+ status: CanUpdateSequencePropStatus;+ frame: number;+}): CanUpdateSequencePropStatus => {+ if (status.canUpdate) {+ return status;+ }++ if (status.reason !== 'keyframed') {+ return status;+ }++ const index = status.keyframes.findIndex((kf) => kf.frame === frame);+ if (index === -1) {+ return status;+ }++ const keyframes = status.keyframes.filter((_, i) => i !== index);++ // Easing holds one segment per gap between consecutive keyframes+ // (keyframes.length - 1 entries). Drop the segment adjacent to the removed+ // keyframe so the invariant keeps holding until the server responds.+ const easing = [...status.easing];+ if (easing.length > 0) {+ const easingIndexToRemove = index === 0 ? 0 : index - 1;+ easing.splice(easingIndexToRemove, 1);+ }++ return {+ ...status,+ keyframes,+ easing,+ };+};++export const optimisticDeleteSequenceKeyframe = ({+ previous,+ fieldKey,+ frame,+}: {+ previous: CanUpdateSequencePropsResponse;+ fieldKey: string;+ frame: number;+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const status = previous.props[fieldKey];+ if (!status) {+ return previous;+ }++ return {+ ...previous,+ props: {+ ...previous.props,+ [fieldKey]: removeKeyframeFromPropStatus({status, frame}),+ },+ };+};++export const optimisticDeleteEffectKeyframe = ({+ previous,+ effectIndex,+ fieldKey,+ frame,+}: {+ previous: CanUpdateSequencePropsResponse;+ effectIndex: number;+ fieldKey: string;+ frame: number;+}): CanUpdateSequencePropsResponse => {+ if (!previous.canUpdate) {+ return previous;+ }++ const targetIndex = previous.effects.findIndex(+ (e) => e.effectIndex === effectIndex,+ );+ if (targetIndex === -1) {+ return previous;+ }++ const target = previous.effects[targetIndex];+ if (!target.canUpdate) {+ return previous;+ }++ const status = target.props[fieldKey];+ if (!status) {+ return previous;+ }++ const updatedEffect = {+ ...target,+ props: {+ ...target.props,+ [fieldKey]: removeKeyframeFromPropStatus({status, frame}),+ },+ };++ const effects = [...previous.effects];+ effects[targetIndex] = updatedEffect;++ return {+ ...previous,+ effects,+ };+};diff --git a/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts b/packages/studio-shared/src/test/optimistic-delete-keyframe.test.tsnew file mode 100644index 0000000000..8fc7b248de--- /dev/null+++ b/packages/studio-shared/src/test/optimistic-delete-keyframe.test.ts@@ -0,0 +1,155 @@+import {expect, test} from 'bun:test';+import type {CanUpdateSequencePropsResponse} from 'remotion';+import {+ optimisticDeleteEffectKeyframe,+ optimisticDeleteSequenceKeyframe,+} from '../optimistic-delete-keyframe';++test('optimisticDeleteSequenceKeyframe removes the matching keyframe and an easing segment', () => {+ const previous: CanUpdateSequencePropsResponse = {+ canUpdate: true,+ props: {+ 'style.opacity': {+ canUpdate: false,+ reason: 'keyframed',+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 0.5},+ {frame: 60, value: 1},+ ],+ easing: ['linear', 'linear'],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ effects: [],+ };++ const updated = optimisticDeleteSequenceKeyframe({+ previous,+ fieldKey: 'style.opacity',+ frame: 30,+ });++ if (!updated.canUpdate) {+ throw new Error('expected canUpdate true');+ }++ const status = updated.props['style.opacity'];+ if (status.canUpdate || status.reason !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([+ {frame: 0, value: 0},+ {frame: 60, value: 1},+ ]);+ expect(status.easing).toEqual(['linear']);+});++test('optimisticDeleteSequenceKeyframe is a no-op when no keyframe matches', () => {+ const previous: CanUpdateSequencePropsResponse = {+ canUpdate: true,+ props: {+ 'style.opacity': {+ canUpdate: false,+ reason: 'keyframed',+ keyframes: [{frame: 0, value: 0}],+ easing: [],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ effects: [],+ };++ const updated = optimisticDeleteSequenceKeyframe({+ previous,+ fieldKey: 'style.opacity',+ frame: 99,+ });++ expect(updated.canUpdate && updated.props['style.opacity']).toEqual(+ previous.canUpdate && previous.props['style.opacity'],+ );+});++test('optimisticDeleteSequenceKeyframe is a no-op when sequence is not updateable', () => {+ const previous: CanUpdateSequencePropsResponse = {+ canUpdate: false,+ reason: 'not-found',+ };++ const result = optimisticDeleteSequenceKeyframe({+ previous,+ fieldKey: 'style.opacity',+ frame: 0,+ });++ expect(result).toBe(previous);+});++test('optimisticDeleteEffectKeyframe removes the matching keyframe on the target effect', () => {+ const previous: CanUpdateSequencePropsResponse = {+ canUpdate: true,+ props: {},+ effects: [+ {+ canUpdate: true,+ effectIndex: 0,+ callee: 'tint',+ props: {+ amount: {+ canUpdate: false,+ reason: 'keyframed',+ keyframes: [+ {frame: 0, value: 0},+ {frame: 30, value: 1},+ ],+ easing: ['linear'],+ clamping: {left: 'extend', right: 'extend'},+ },+ },+ },+ ],+ };++ const updated = optimisticDeleteEffectKeyframe({+ previous,+ effectIndex: 0,+ fieldKey: 'amount',+ frame: 0,+ });++ if (!updated.canUpdate) {+ throw new Error('expected canUpdate true');+ }++ const effect = updated.effects[0];+ if (!effect.canUpdate) {+ throw new Error('expected effect canUpdate true');+ }++ const status = effect.props.amount;+ if (status.canUpdate || status.reason !== 'keyframed') {+ throw new Error('expected keyframed status');+ }++ expect(status.keyframes).toEqual([{frame: 30, value: 1}]);+ expect(status.easing).toEqual([]);+});++test('optimisticDeleteEffectKeyframe is a no-op when effect index not found', () => {+ const previous: CanUpdateSequencePropsResponse = {+ canUpdate: true,+ props: {},+ effects: [],+ };++ const result = optimisticDeleteEffectKeyframe({+ previous,+ effectIndex: 0,+ fieldKey: 'amount',+ frame: 0,+ });++ expect(result).toBe(previous);+});diff --git a/packages/studio/src/components/ContextMenu.tsx b/packages/studio/src/components/ContextMenu.tsxindex 8fa035fcc9..2558274595 100644--- a/packages/studio/src/components/ContextMenu.tsx+++ b/packages/studio/src/components/ContextMenu.tsx@@ -126,6 +126,11 @@ export const ContextMenu: React.FC<{setOpened({type: 'not-open'});}, []);+ // Prevent deselection of a selected item+ const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {+ e.stopPropagation();+ }, []);+return (<><div ref={ref} onContextMenu={() => false} style={style}>@@ -136,7 +141,7 @@ export const ContextMenu: React.FC<{<div style={fullScreenOverlay}><div style={outerPortal} className="css-reset"><HigherZIndex onOutsideClick={onHide} onEscape={onHide}>- <div style={portalStyle}>+ <div style={portalStyle} onPointerDown={onPointerDown}><MenuContentonNextMenu={noop}onPreviousMenu={noop}diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsxindex f3d4ea38b7..d171bc3a19 100644--- a/packages/studio/src/components/Timeline/Timeline.tsx+++ b/packages/studio/src/components/Timeline/Timeline.tsx@@ -16,6 +16,7 @@ import {SubscribeToNodePaths} from './SubscribeToNodePaths';import {timelineVerticalScroll} from './timeline-refs';import {TimelineDragHandler} from './TimelineDragHandler';import {TimelineHeightContainer} from './TimelineHeightContainer';+import {TimelineInOutDragHandler} from './TimelineInOutDragHandler';import {TimelineInOutPointer} from './TimelineInOutPointer';import {TimelineList} from './TimelineList';import {TimelinePinchZoom} from './TimelinePinchZoom';@@ -128,10 +129,11 @@ const TimelineInner: React.FC = () => {<SplitterElement type="anti-flexer" sticky={null}><TimelineScrollable><TimelineTracks timeline={shown} hasBeenCut={hasBeenCut} />- <TimelineInOutPointer /><TimelinePlayCursorSyncer />- <TimelineDragHandler />+ <TimelineInOutPointer /><TimelineTimeIndicators />+ <TimelineDragHandler />+ <TimelineInOutDragHandler /><TimelineSlider /></TimelineScrollable></SplitterElement>diff --git a/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsxnew file mode 100644index 0000000000..fa2500fc4c--- /dev/null+++ b/packages/studio/src/components/Timeline/TimelineDeleteKeybindings.tsx@@ -0,0 +1,69 @@+import type React from 'react';+import {useContext, useEffect} from 'react';+import {Internals} from 'remotion';+import {StudioServerConnectionCtx} from '../../helpers/client-id';+import {useKeybinding} from '../../helpers/use-keybinding';+import {deleteSelectedTimelineItem} from './delete-selected-timeline-item';+import {useTimelineSelection} from './TimelineSelection';++export const TimelineDeleteKeybindings: React.FC = () => {+ const keybindings = useKeybinding();+ const {previewServerState} = useContext(StudioServerConnectionCtx);+ const {sequences} = useContext(Internals.SequenceManager);+ const {overrideIdToNodePathMappings} = useContext(+ Internals.OverrideIdsToNodePathsGettersContext,+ );+ const {setCodeValues} = useContext(Internals.VisualModeSettersContext);+ const {canSelect, selectedItem, clearSelection} = useTimelineSelection();++ useEffect(() => {+ if (+ !canSelect ||+ previewServerState.type !== 'connected' ||+ !selectedItem+ ) {+ return;+ }++ const {clientId} = previewServerState;+ const currentSelection = selectedItem;+ const backspace = keybindings.registerKeybinding({+ event: 'keydown',+ key: 'Backspace',+ callback: () => {+ const deletePromise = deleteSelectedTimelineItem({+ selection: currentSelection,+ sequences,+ overrideIdsToNodePaths: overrideIdToNodePathMappings,+ setCodeValues,+ clientId,+ });+ if (deletePromise === null) {+ return;+ }++ clearSelection();+ deletePromise.catch(() => undefined);+ },+ commandCtrlKey: false,+ preventDefault: true,+ triggerIfInputFieldFocused: false,+ keepRegisteredWhenNotHighestContext: false,+ });++ return () => {+ backspace.unregister();+ };+ }, [+ canSelect,+ clearSelection,+ keybindings,+ overrideIdToNodePathMappings,+ previewServerState,+ selectedItem,+ sequences,+ setCodeValues,+ ]);++ return null;+};diff --git a/packages/studio/src/components/Timeline/TimelineDragHandler.tsx b/packages/studio/src/components/Timeline/TimelineDragHandler.tsxindex 40443d57c7..4996a7a307 100644--- a/packages/studio/src/components/Timeline/TimelineDragHandler.tsx+++ b/packages/studio/src/components/Timeline/TimelineDragHandler.tsx@@ -8,23 +8,15 @@ import React, {useState,} from 'react';import {Internals, useVideoConfig} from 'remotion';-import {getXPositionOfItemInTimelineImperatively} from '../../helpers/get-left-of-timeline-slider';import {TIMELINE_PADDING} from '../../helpers/timeline-layout';-import {- useTimelineInOutFramePosition,- useTimelineSetInOutFramePosition,-} from '../../state/in-out';import {TIMELINE_MIN_ZOOM, TimelineZoomCtx} from '../../state/timeline-zoom';import {useZIndex} from '../../state/z-index';-import {ContextMenu} from '../ContextMenu';-import {- forceSpecificCursor,- stopForcingSpecificCursor,-} from '../ForceSpecificCursor';import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';-import type {ComboboxValue} from '../NewComposition/ComboBox';-import {defaultInOutValue} from '../TimelineInOutToggle';-import {scrollableRef, sliderAreaRef} from './timeline-refs';+import {+ scrollableRef,+ sliderAreaRef,+ timelineVerticalScroll,+} from './timeline-refs';import {canScrollTimelineIntoDirection,getFrameFromX,@@ -34,14 +26,9 @@ import {getScrollPositionForCursorOnRightEdge,scrollToTimelineXOffset,} from './timeline-scroll-logic';-import {inMarkerAreaRef, outMarkerAreaRef} from './TimelineInOutPointer';-import {- TimelineInOutPointerHandle,- inPointerHandle,- outPointerHandle,-} from './TimelineInOutPointerHandle';+import {TIMELINE_TOP_DRAG} from './TimelineSelection';import {redrawTimelineSliderFast} from './TimelineSlider';-import {TimelineWidthContext} from './TimelineWidthProvider';+import {TIMELINE_TIME_INDICATOR_HEIGHT} from './TimelineTimeIndicators';const inner: React.CSSProperties = {overflowY: 'auto',@@ -61,6 +48,7 @@ const style: React.CSSProperties = {height: '100%',userSelect: 'none',WebkitUserSelect: 'none',+ position: 'absolute',};const getClientXWithScroll = (x: number) => {@@ -82,6 +70,7 @@ export const TimelineDragHandler: React.FC = () => {return {...container,width: 100 * zoom + '%',+ ...(TIMELINE_TOP_DRAG ? {height: TIMELINE_TIME_INDICATOR_HEIGHT} : {}),};}, [canvasContent, zoomMap]);@@ -105,43 +94,9 @@ const TimelineDragHandlerInner: React.FC = () => {const {isHighestContext} = useZIndex();const setFrame = Internals.useTimelineSetFrame();- const [inOutDragging, setInOutDragging] = useState<- | {- dragging: false;- }- | {- dragging: 'in' | 'out';- initialOffset: number;- boundaries: [number, number];- }- >({- dragging: false,- });-- const timelineWidth = useContext(TimelineWidthContext);-- const get = useCallback(- (frame: number) => {- if (timelineWidth === null) {- throw new Error('timeline width is not yet determined');- }-- return getXPositionOfItemInTimelineImperatively(- frame,- videoConfig.durationInFrames,- timelineWidth,- );- },- [timelineWidth, videoConfig.durationInFrames],- );-const width = scrollableRef.current?.scrollWidth ?? 0;const left = size?.left ?? 0;- const {inFrame, outFrame} = useTimelineInOutFramePosition();-- const {setInAndOutFrames} = useTimelineSetInOutFramePosition();-const [dragging, setDragging] = useState<| {dragging: false;@@ -182,43 +137,6 @@ const TimelineDragHandlerInner: React.FC = () => {document.body.style.userSelect = 'none';document.body.style.webkitUserSelect = 'none';- if ((e.target as Node) === inPointerHandle.current) {- if (inFrame === null) {- throw new Error('expected outframe');- }-- const inMarker = get(inFrame);- const outMarker = outFrame === null ? Infinity : get(outFrame - 1);- forceSpecificCursor('ew-resize');- setInOutDragging({- dragging: 'in',- initialOffset: getClientXWithScroll(e.clientX),- boundaries: [-Infinity, outMarker - inMarker],- });- return;- }-- if ((e.target as Node) === outPointerHandle.current) {- if (outFrame === null) {- throw new Error('expected outframe');- }-- const outMarker = get(outFrame);- const inMarker = inFrame === null ? -Infinity : get(inFrame + 1);- forceSpecificCursor('ew-resize');- setInOutDragging({- dragging: 'out',- initialOffset: getClientXWithScroll(e.clientX),- boundaries: [inMarker - outMarker, Infinity],- });-- return;- }-- if (e.button !== 0) {- return;- }-const frame = getFrameFromX({clientX: getClientXWithScroll(e.clientX) - left,durationInFrames: videoConfig.durationInFrames,@@ -232,18 +150,7 @@ const TimelineDragHandlerInner: React.FC = () => {});pause();},- [- isHighestContext,- videoConfig,- left,- width,- seek,- playing,- pause,- inFrame,- get,- outFrame,- ],+ [isHighestContext, videoConfig, left, width, seek, playing, pause],);const onPointerMoveScrubbing = useCallback(@@ -343,68 +250,6 @@ const TimelineDragHandlerInner: React.FC = () => {[videoConfig, dragging.dragging, left, width, seek],);- const onPointerMoveInOut = useCallback(- (e: PointerEvent) => {- if (!videoConfig) {- return;- }-- if (!inOutDragging.dragging) {- return;- }-- const offset = Math.max(- inOutDragging.boundaries[0],- Math.min(- inOutDragging.boundaries[1],- getClientXWithScroll(e.clientX) - inOutDragging.initialOffset,- ),- );- if (inOutDragging.dragging === 'in') {- if (!inPointerHandle.current) {- throw new Error('in pointer handle');- }-- if (!inMarkerAreaRef.current) {- throw new Error('expected inMarkerAreaRef');- }-- if (!inFrame) {- throw new Error('expected inframes');- }-- inPointerHandle.current.style.transform = `translateX(${- get(inFrame) + offset- }px)`;- inMarkerAreaRef.current.style.width =- String(get(inFrame) + offset) + 'px';- }-- if (inOutDragging.dragging === 'out') {- if (!outPointerHandle.current) {- throw new Error('in pointer handle');- }-- if (!outMarkerAreaRef.current) {- throw new Error('in outMarkerAreaRef');- }-- if (!outFrame) {- throw new Error('expected outframes');- }-- outPointerHandle.current.style.transform = `translateX(${- get(outFrame) + offset- }px)`;- outMarkerAreaRef.current.style.left =- String(get(outFrame) + offset) + 'px';- outMarkerAreaRef.current.style.width =- String(width - get(outFrame) - offset) + 'px';- }- },- [get, inFrame, inOutDragging, outFrame, videoConfig, width],- );-const onPointerUpScrubbing = useCallback((e: PointerEvent) => {stopInterval();@@ -443,81 +288,6 @@ const TimelineDragHandlerInner: React.FC = () => {[dragging, left, play, videoConfig, setFrame, width],);- const onPointerUpInOut = useCallback(- (e: PointerEvent) => {- document.body.style.userSelect = '';- document.body.style.webkitUserSelect = '';- stopForcingSpecificCursor();-- if (!videoConfig) {- return;- }-- if (!inOutDragging.dragging) {- return;- }-- setInOutDragging({- dragging: false,- });-- const frame = getFrameFromX({- clientX: getClientXWithScroll(e.clientX) - left,- durationInFrames: videoConfig.durationInFrames,- width,- extrapolate: 'extend',- });- if (inOutDragging.dragging === 'in') {- if (frame < 1) {- return setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- inFrame: null,- },- }));- }-- const maxFrame = outFrame === null ? Infinity : outFrame - 1;- setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- inFrame: Math.min(maxFrame, frame),- },- }));- } else {- if (frame > videoConfig.durationInFrames - 2) {- return setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- outFrame: null,- },- }));- }-- const minFrame = inFrame === null ? -Infinity : inFrame + 1;- setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- outFrame: Math.max(minFrame, frame),- },- }));- }- },- [- inFrame,- inOutDragging.dragging,- left,- outFrame,- setInAndOutFrames,- videoConfig,- width,- ],- );-useEffect(() => {if (!dragging.dragging) {return;@@ -531,92 +301,32 @@ const TimelineDragHandlerInner: React.FC = () => {};}, [dragging.dragging, onPointerMoveScrubbing, onPointerUpScrubbing]);+ const ref = useRef<HTMLDivElement>(null);+useEffect(() => {- if (inOutDragging.dragging === false) {+ const currentRef = ref.current;+ if (!currentRef) {+ return;+ }++ const {current} = timelineVerticalScroll;+ if (!current) {return;}- window.addEventListener('pointermove', onPointerMoveInOut);- window.addEventListener('pointerup', onPointerUpInOut);+ const onScroll = () => {+ currentRef.style.top = current.scrollTop + 'px';+ };++ current.addEventListener('scroll', onScroll);return () => {- window.removeEventListener('pointermove', onPointerMoveInOut);- window.removeEventListener('pointerup', onPointerUpInOut);+ current.removeEventListener('scroll', onScroll);};- }, [inOutDragging.dragging, onPointerMoveInOut, onPointerUpInOut]);-- const inContextMenu = useMemo((): ComboboxValue[] => {- return [- {- id: 'hide-in',- keyHint: null,- label: 'Clear In marker',- leftItem: null,- onClick: (_, e) => {- e?.stopPropagation();- e?.preventDefault();- setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- inFrame: null,- },- }));- },- quickSwitcherLabel: null,- subMenu: null,- type: 'item',- value: 'hide-in',- },- ];- }, [setInAndOutFrames, videoConfig.id]);-- const outContextMenu = useMemo((): ComboboxValue[] => {- return [- {- id: 'hide-out',- keyHint: null,- label: 'Clear Out marker',- leftItem: null,- onClick: (_, e) => {- e?.stopPropagation();- e?.preventDefault();- setInAndOutFrames((prev) => ({- ...prev,- [videoConfig.id]: {- ...(prev[videoConfig.id] ?? defaultInOutValue),- outFrame: null,- },- }));- },- quickSwitcherLabel: null,- subMenu: null,- type: 'item',- value: 'hide-out',- },- ];- }, [setInAndOutFrames, videoConfig.id]);+ }, []);return (- <div style={style} onPointerDown={onPointerDown}>+ <div ref={ref} style={style} onPointerDown={onPointerDown}><div style={inner} className={VERTICAL_SCROLLBAR_CLASSNAME} />- {inFrame !== null && (- <ContextMenu values={inContextMenu} onOpen={null}>- <TimelineInOutPointerHandle- type="in"- atFrame={inFrame}- dragging={inOutDragging.dragging === 'in'}- />- </ContextMenu>- )}- {outFrame !== null && (- <ContextMenu values={outContextMenu} onOpen={null}>- <TimelineInOutPointerHandle- type="out"- dragging={inOutDragging.dragging === 'out'}- atFrame={outFrame}- />- </ContextMenu>- )}</div>);};diff --git a/packages/studio/src/components/Timeline/TimelineEffectGroupRow.tsx b/packages/studio/src/components/Timeline/TimelineEffectGroupRow.tsxindex 211ebbf4ca..00f907c148 100644--- a/packages/studio/src/components/Timeline/TimelineEffectGroupRow.tsx+++ b/packages/studio/src/components/Timeline/TimelineEffectGroupRow.tsx@@ -1,4 +1,4 @@-import React, {useCallback, useContext, useMemo, useState} from 'react';+import React, {useCallback, useContext, useMemo} from 'react';import type {SequencePropsSubscriptionKey, SequenceSchema} from 'remotion';import {Internals} from 'remotion';import type {CodePosition} from '../../error-overlay/react-overlay/utils/get-source-map';@@ -52,7 +52,6 @@ export const TimelineEffectGroupRow: React.FC<{getIsExpanded,toggleTrack,}) => {- const [labelHovered, setLabelHovered] = useState(false);const {previewServerState} = useContext(StudioServerConnectionCtx);const previewConnected = previewServerState.type === 'connected';const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);@@ -116,27 +115,55 @@ export const TimelineEffectGroupRow: React.FC<{return [];}- return [- {+ const items: ComboboxValue[] = [];++ if (documentationLink) {+ items.push({type: 'item',- id: 'delete-effect',+ id: 'open-effect-docs',keyHint: null,- label: 'Delete',+ label: 'Open effect docs',leftItem: null,- disabled: deleteDisabled,+ disabled: false,onClick: () => {- if (deleteDisabled) {- return;- }-- onDeleteEffectFromSource();+ window.open(documentationLink, '_blank', 'noopener,noreferrer');},quickSwitcherLabel: null,subMenu: null,- value: 'delete-effect',+ value: 'open-effect-docs',+ });+ items.push({+ type: 'divider',+ id: 'open-effect-docs-divider',+ });+ }++ items.push({+ type: 'item',+ id: 'delete-effect',+ keyHint: null,+ label: 'Delete',+ leftItem: null,+ disabled: deleteDisabled,+ onClick: () => {+ if (deleteDisabled) {+ return;+ }++ onDeleteEffectFromSource();},- ];- }, [deleteDisabled, onDeleteEffectFromSource, previewConnected]);+ quickSwitcherLabel: null,+ subMenu: null,+ value: 'delete-effect',+ });++ return items;+ }, [+ deleteDisabled,+ documentationLink,+ onDeleteEffectFromSource,+ previewConnected,+ ]);const onToggle = useCallback((type: 'enable' | 'disable') => {@@ -184,7 +211,6 @@ export const TimelineEffectGroupRow: React.FC<{);const labelStyle = useMemo((): React.CSSProperties => {- const hoverEffect = labelHovered && documentationLink !== null;return {...rowLabel,...getTimelineSelectedLabelStyle(selection.selected, true),@@ -195,19 +221,8 @@ export const TimelineEffectGroupRow: React.FC<{flex: 1,minWidth: 0,paddingRight: EXPANDED_SECTION_PADDING_RIGHT,- textDecoration: hoverEffect ? 'underline' : 'none',- textUnderlineOffset: 2,- cursor: hoverEffect ? 'pointer' : undefined,};- }, [documentationLink, labelHovered, selection.selected]);-- const onClickLabel = useCallback(() => {- if (documentationLink === null) {- return;- }-- window.open(documentationLink, '_blank', 'noopener,noreferrer');- }, [documentationLink]);+ }, [selection.selected]);const row = (<TimelineRowChrome@@ -239,15 +254,7 @@ export const TimelineEffectGroupRow: React.FC<{containsSelection={false}outerHeight={null}>- <span- onPointerEnter={() => setLabelHovered(true)}- onPointerLeave={() => setLabelHovered(false)}- onClick={onClickLabel}- title={- documentationLink ? `Open documentation: ${documentationLink}` : label- }- style={labelStyle}- >+ <span title={label} style={labelStyle}>{label}</span></TimelineRowChrome>diff --git a/packages/studio/src/components/Timeline/TimelineExpandedKeyframeRow.tsx b/packages/studio/src/components/Timeline/TimelineExpandedKeyframeRow.tsxindex 840ed55378..a49f2de749 100644--- a/packages/studio/src/components/Timeline/TimelineExpandedKeyframeRow.tsx+++ b/packages/studio/src/components/Timeline/TimelineExpandedKeyframeRow.tsx@@ -1,12 +1,13 @@-import React from 'react';+import React, {useContext} from 'react';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {TIMELINE_ITEM_BORDER_BOTTOM} from '../../helpers/timeline-layout';import type {getTimelineKeyframes} from './get-timeline-keyframes';import {TimelineKeyframeDiamond} from './TimelineKeyframeDiamond';import {- TIMELINE_SELECTED_TRACK_HIGHLIGHT_STYLE,+ getTimelineSelectedTrackHighlightStyle,useTimelineRowSelection,} from './TimelineSelection';+import {TimelineWidthContext} from './TimelineWidthProvider';const row: React.CSSProperties = {position: 'relative',@@ -22,14 +23,15 @@ const TimelineExpandedKeyframeRowUnmemoized: React.FC<{readonly nodePathInfo: SequenceNodePathInfo;readonly showSeparator: boolean;}> = ({height, keyframes, nodePathInfo, showSeparator}) => {+ const timelineWidth = useContext(TimelineWidthContext);const {selected: rowSelected} = useTimelineRowSelection(nodePathInfo);return (<>{showSeparator ? <div style={rowSeparator} /> : null}<div style={{...row, height}}>- {rowSelected ? (- <div style={TIMELINE_SELECTED_TRACK_HIGHLIGHT_STYLE} />+ {rowSelected && timelineWidth !== null ? (+ <div style={getTimelineSelectedTrackHighlightStyle(timelineWidth)} />) : null}{keyframes.map((keyframe) => (<TimelineKeyframeDiamonddiff --git a/packages/studio/src/components/Timeline/TimelineExpandedRow.tsx b/packages/studio/src/components/Timeline/TimelineExpandedRow.tsxindex e37a6a8c2c..6557d81692 100644--- a/packages/studio/src/components/Timeline/TimelineExpandedRow.tsx+++ b/packages/studio/src/components/Timeline/TimelineExpandedRow.tsx@@ -70,6 +70,7 @@ export const TimelineExpandedRow: React.FC<{if (node.kind === 'group') {if (node.effectInfo) {return (+ // A single effect<TimelineEffectGroupRowlabel={node.label}nodePathInfo={node.nodePathInfo}diff --git a/packages/studio/src/components/Timeline/TimelineInOutDragHandler.tsx b/packages/studio/src/components/Timeline/TimelineInOutDragHandler.tsxnew file mode 100644index 0000000000..5354935c07--- /dev/null+++ b/packages/studio/src/components/Timeline/TimelineInOutDragHandler.tsx@@ -0,0 +1,393 @@+import {PlayerInternals} from '@remotion/player';+import React, {+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+} from 'react';+import {Internals, useVideoConfig} from 'remotion';+import {getXPositionOfItemInTimelineImperatively} from '../../helpers/get-left-of-timeline-slider';+import {+ useTimelineInOutFramePosition,+ useTimelineSetInOutFramePosition,+} from '../../state/in-out';+import {useZIndex} from '../../state/z-index';+import {ContextMenu} from '../ContextMenu';+import {+ forceSpecificCursor,+ stopForcingSpecificCursor,+} from '../ForceSpecificCursor';+import type {ComboboxValue} from '../NewComposition/ComboBox';+import {defaultInOutValue} from '../TimelineInOutToggle';+import {scrollableRef} from './timeline-refs';+import {getFrameFromX} from './timeline-scroll-logic';+import {inMarkerAreaRef, outMarkerAreaRef} from './TimelineInOutPointer';+import {+ TimelineInOutPointerHandle,+ inPointerHandle,+ outPointerHandle,+} from './TimelineInOutPointerHandle';+import {TimelineWidthContext} from './TimelineWidthProvider';++const getClientXWithScroll = (x: number) => {+ return x + (scrollableRef.current?.scrollLeft as number);+};++export const TimelineInOutDragHandler: React.FC = () => {+ const video = Internals.useUnsafeVideoConfig();+ const {canvasContent} = useContext(Internals.CompositionManager);++ if (!canvasContent || canvasContent.type !== 'composition') {+ return null;+ }++ return video ? <TimelineInOutDragHandlerInnerMemo /> : null;+};++const TimelineInOutDragHandlerInner: React.FC = () => {+ const videoConfig = useVideoConfig();+ const size = PlayerInternals.useElementSize(scrollableRef, {+ triggerOnWindowResize: true,+ shouldApplyCssTransforms: true,+ });+ const {isHighestContext} = useZIndex();++ const [inOutDragging, setInOutDragging] = useState<+ | {+ dragging: false;+ }+ | {+ dragging: 'in' | 'out';+ initialOffset: number;+ boundaries: [number, number];+ }+ >({+ dragging: false,+ });++ const timelineWidth = useContext(TimelineWidthContext);++ const get = useCallback(+ (frame: number) => {+ if (timelineWidth === null) {+ throw new Error('timeline width is not yet determined');+ }++ return getXPositionOfItemInTimelineImperatively(+ frame,+ videoConfig.durationInFrames,+ timelineWidth,+ );+ },+ [timelineWidth, videoConfig.durationInFrames],+ );++ const width = scrollableRef.current?.scrollWidth ?? 0;+ const left = size?.left ?? 0;++ const {inFrame, outFrame} = useTimelineInOutFramePosition();++ const {setInAndOutFrames} = useTimelineSetInOutFramePosition();++ const onInPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) {+ return;+ }++ if (!isHighestContext) {+ return;+ }++ if (!videoConfig) {+ return;+ }++ if (inFrame === null) {+ throw new Error('expected in frame');+ }++ e.stopPropagation();++ document.body.style.userSelect = 'none';+ document.body.style.webkitUserSelect = 'none';++ const inMarker = get(inFrame);+ const outMarker = outFrame === null ? Infinity : get(outFrame - 1);+ forceSpecificCursor('ew-resize');+ setInOutDragging({+ dragging: 'in',+ initialOffset: getClientXWithScroll(e.clientX),+ boundaries: [-Infinity, outMarker - inMarker],+ });+ },+ [isHighestContext, videoConfig, inFrame, get, outFrame],+ );++ const onOutPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) {+ return;+ }++ if (!isHighestContext) {+ return;+ }++ if (!videoConfig) {+ return;+ }++ if (outFrame === null) {+ throw new Error('expected out frame');+ }++ e.stopPropagation();++ document.body.style.userSelect = 'none';+ document.body.style.webkitUserSelect = 'none';++ const outMarker = get(outFrame);+ const inMarker = inFrame === null ? -Infinity : get(inFrame + 1);+ forceSpecificCursor('ew-resize');+ setInOutDragging({+ dragging: 'out',+ initialOffset: getClientXWithScroll(e.clientX),+ boundaries: [inMarker - outMarker, Infinity],+ });+ },+ [isHighestContext, videoConfig, inFrame, get, outFrame],+ );++ const onPointerMoveInOut = useCallback(+ (e: PointerEvent) => {+ if (!videoConfig) {+ return;+ }++ if (!inOutDragging.dragging) {+ return;+ }++ const offset = Math.max(+ inOutDragging.boundaries[0],+ Math.min(+ inOutDragging.boundaries[1],+ getClientXWithScroll(e.clientX) - inOutDragging.initialOffset,+ ),+ );+ if (inOutDragging.dragging === 'in') {+ if (!inPointerHandle.current) {+ throw new Error('in pointer handle');+ }++ if (!inMarkerAreaRef.current) {+ throw new Error('expected inMarkerAreaRef');+ }++ if (!inFrame) {+ throw new Error('expected inframes');+ }++ inPointerHandle.current.style.transform = `translateX(${+ get(inFrame) + offset+ }px)`;+ inMarkerAreaRef.current.style.width =+ String(get(inFrame) + offset) + 'px';+ }++ if (inOutDragging.dragging === 'out') {+ if (!outPointerHandle.current) {+ throw new Error('in pointer handle');+ }++ if (!outMarkerAreaRef.current) {+ throw new Error('in outMarkerAreaRef');+ }++ if (!outFrame) {+ throw new Error('expected outframes');+ }++ outPointerHandle.current.style.transform = `translateX(${+ get(outFrame) + offset+ }px)`;+ outMarkerAreaRef.current.style.left =+ String(get(outFrame) + offset) + 'px';+ outMarkerAreaRef.current.style.width =+ String(width - get(outFrame) - offset) + 'px';+ }+ },+ [get, inFrame, inOutDragging, outFrame, videoConfig, width],+ );++ const onPointerUpInOut = useCallback(+ (e: PointerEvent) => {+ document.body.style.userSelect = '';+ document.body.style.webkitUserSelect = '';+ stopForcingSpecificCursor();++ if (!videoConfig) {+ return;+ }++ if (!inOutDragging.dragging) {+ return;+ }++ setInOutDragging({+ dragging: false,+ });++ const frame = getFrameFromX({+ clientX: getClientXWithScroll(e.clientX) - left,+ durationInFrames: videoConfig.durationInFrames,+ width,+ extrapolate: 'extend',+ });+ if (inOutDragging.dragging === 'in') {+ if (frame < 1) {+ return setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ inFrame: null,+ },+ }));+ }++ const maxFrame = outFrame === null ? Infinity : outFrame - 1;+ setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ inFrame: Math.min(maxFrame, frame),+ },+ }));+ } else {+ if (frame > videoConfig.durationInFrames - 2) {+ return setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ outFrame: null,+ },+ }));+ }++ const minFrame = inFrame === null ? -Infinity : inFrame + 1;+ setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ outFrame: Math.max(minFrame, frame),+ },+ }));+ }+ },+ [+ inFrame,+ inOutDragging.dragging,+ left,+ outFrame,+ setInAndOutFrames,+ videoConfig,+ width,+ ],+ );++ useEffect(() => {+ if (inOutDragging.dragging === false) {+ return;+ }++ window.addEventListener('pointermove', onPointerMoveInOut);+ window.addEventListener('pointerup', onPointerUpInOut);+ return () => {+ window.removeEventListener('pointermove', onPointerMoveInOut);+ window.removeEventListener('pointerup', onPointerUpInOut);+ };+ }, [inOutDragging.dragging, onPointerMoveInOut, onPointerUpInOut]);++ const inContextMenu = useMemo((): ComboboxValue[] => {+ return [+ {+ id: 'hide-in',+ keyHint: null,+ label: 'Clear In marker',+ leftItem: null,+ onClick: (_, e) => {+ e?.stopPropagation();+ e?.preventDefault();+ setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ inFrame: null,+ },+ }));+ },+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item',+ value: 'hide-in',+ },+ ];+ }, [setInAndOutFrames, videoConfig.id]);++ const outContextMenu = useMemo((): ComboboxValue[] => {+ return [+ {+ id: 'hide-out',+ keyHint: null,+ label: 'Clear Out marker',+ leftItem: null,+ onClick: (_, e) => {+ e?.stopPropagation();+ e?.preventDefault();+ setInAndOutFrames((prev) => ({+ ...prev,+ [videoConfig.id]: {+ ...(prev[videoConfig.id] ?? defaultInOutValue),+ outFrame: null,+ },+ }));+ },+ quickSwitcherLabel: null,+ subMenu: null,+ type: 'item',+ value: 'hide-out',+ },+ ];+ }, [setInAndOutFrames, videoConfig.id]);++ return (+ <>+ {inFrame !== null && (+ <ContextMenu values={inContextMenu} onOpen={null}>+ <TimelineInOutPointerHandle+ type="in"+ atFrame={inFrame}+ dragging={inOutDragging.dragging === 'in'}+ onPointerDown={onInPointerDown}+ />+ </ContextMenu>+ )}+ {outFrame !== null && (+ <ContextMenu values={outContextMenu} onOpen={null}>+ <TimelineInOutPointerHandle+ type="out"+ dragging={inOutDragging.dragging === 'out'}+ atFrame={outFrame}+ onPointerDown={onOutPointerDown}+ />+ </ContextMenu>+ )}+ </>+ );+};++const TimelineInOutDragHandlerInnerMemo = React.memo(+ TimelineInOutDragHandlerInner,+);diff --git a/packages/studio/src/components/Timeline/TimelineInOutPointer.tsx b/packages/studio/src/components/Timeline/TimelineInOutPointer.tsxindex 46bb530e64..7a891cd34f 100644--- a/packages/studio/src/components/Timeline/TimelineInOutPointer.tsx+++ b/packages/studio/src/components/Timeline/TimelineInOutPointer.tsx@@ -10,6 +10,7 @@ const areaHighlight: React.CSSProperties = {height: '100%',bottom: 0,top: 0,+ pointerEvents: 'none',};export const inMarkerAreaRef = createRef<HTMLDivElement>();@@ -55,7 +56,7 @@ export const TimelineInOutPointer: React.FC = () => {timelineWidth -getXPositionOfItemInTimelineImperatively(outFrame,- videoConfig.durationInFrames,+ videoConfig.durationInFrames + 1, // last frame also has width of 1 frametimelineWidth,),}}diff --git a/packages/studio/src/components/Timeline/TimelineInOutPointerHandle.tsx b/packages/studio/src/components/Timeline/TimelineInOutPointerHandle.tsxindex ac29c48aa1..afab27f0d4 100644--- a/packages/studio/src/components/Timeline/TimelineInOutPointerHandle.tsx+++ b/packages/studio/src/components/Timeline/TimelineInOutPointerHandle.tsx@@ -21,13 +21,14 @@ type Props = {readonly dragging: boolean;readonly type: 'in' | 'out';readonly atFrame: number;+ readonly onPointerDown?: (e: React.PointerEvent<HTMLDivElement>) => void;};const InnerTimelineInOutPointerHandle: React.FC<Props & {readonly timelineWidth: number;}-> = ({atFrame, dragging, timelineWidth, type}) => {+> = ({atFrame, dragging, onPointerDown, timelineWidth, type}) => {const videoConfig = useVideoConfig();const style: React.CSSProperties = useMemo(() => {@@ -41,6 +42,7 @@ const InnerTimelineInOutPointerHandle: React.FC<videoConfig.durationInFrames,timelineWidth,)}px)`,+ top: 0,};}, [atFrame, dragging, timelineWidth, videoConfig.durationInFrames]);@@ -48,12 +50,14 @@ const InnerTimelineInOutPointerHandle: React.FC<<divref={type === 'in' ? inPointerHandle : outPointerHandle}style={style}+ onPointerDown={onPointerDown}/>);};export const TimelineInOutPointerHandle: React.FC<Props> = ({dragging,+ onPointerDown,type,atFrame,}) => {@@ -69,6 +73,7 @@ export const TimelineInOutPointerHandle: React.FC<Props> = ({<InnerTimelineInOutPointerHandleatFrame={atFrame}dragging={dragging}+ onPointerDown={onPointerDown}timelineWidth={timelineWidth}type={type}/>diff --git a/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx b/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsxindex 03260a8635..76d33d8108 100644--- a/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx+++ b/packages/studio/src/components/Timeline/TimelineKeyframeDiamond.tsx@@ -1,13 +1,10 @@import React, {useCallback, useContext, useMemo} from 'react';import {useVideoConfig} from 'remotion';-import {LIGHT_TEXT} from '../../helpers/colors';+import {BLUE, LIGHT_TEXT} from '../../helpers/colors';import {getXPositionOfItemInTimelineImperatively} from '../../helpers/get-left-of-timeline-slider';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {TIMELINE_PADDING} from '../../helpers/timeline-layout';-import {- TIMELINE_SELECTED_LABEL_BACKGROUND,- useTimelineKeyframeSelection,-} from './TimelineSelection';+import {useTimelineKeyframeSelection} from './TimelineSelection';import {TimelineWidthContext} from './TimelineWidthProvider';const diamondBase: React.CSSProperties = {@@ -17,7 +14,6 @@ const diamondBase: React.CSSProperties = {backgroundColor: LIGHT_TEXT,borderRadius: 1,boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.4)',- pointerEvents: 'none',};const TimelineKeyframeDiamondUnmemoized: React.FC<{@@ -39,11 +35,10 @@ const TimelineKeyframeDiamondUnmemoized: React.FC<{return {...diamondBase,- backgroundColor: selected- ? TIMELINE_SELECTED_LABEL_BACKGROUND- : LIGHT_TEXT,+ backgroundColor: LIGHT_TEXT,+ outline: selected ? '2px solid ' + BLUE : 'none',border: 'none',- cursor: 'default',+ cursor: 'pointer',left:getXPositionOfItemInTimelineImperatively(frame,diff --git a/packages/studio/src/components/Timeline/TimelineScrollable.tsx b/packages/studio/src/components/Timeline/TimelineScrollable.tsxindex ccd994e3ef..53778c7b3a 100644--- a/packages/studio/src/components/Timeline/TimelineScrollable.tsx+++ b/packages/studio/src/components/Timeline/TimelineScrollable.tsx@@ -1,7 +1,8 @@-import React, {useMemo} from 'react';+import React, {useCallback, useMemo} from 'react';import {TIMELINE_BACKGROUND} from '../../helpers/colors';import {HORIZONTAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';import {scrollableRef} from './timeline-refs';+import {useTimelineSelection} from './TimelineSelection';const outer: React.CSSProperties = {width: '100%',@@ -15,6 +16,22 @@ const outer: React.CSSProperties = {export const TimelineScrollable: React.FC<{readonly children: React.ReactNode;}> = ({children}) => {+ const {clearSelection} = useTimelineSelection();++ // Selection-triggering click handlers in children call e.stopPropagation(),+ // so any pointerdown that bubbles up here is by definition on empty space+ // and should clear the current selection.+ const onPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) {+ return;+ }++ clearSelection();+ },+ [clearSelection],+ );+const containerStyle: React.CSSProperties = useMemo(() => {return {width: '100%',@@ -28,7 +45,9 @@ export const TimelineScrollable: React.FC<{style={outer}className={HORIZONTAL_SCROLLBAR_CLASSNAME}>- <div style={containerStyle}>{children}</div>+ <div style={containerStyle} onPointerDown={onPointerDown}>+ {children}+ </div></div>);};diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsxindex 9a28c44bb1..906f26377e 100644--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx@@ -12,6 +12,7 @@ import {StudioServerConnectionCtx} from '../../helpers/client-id';import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {TIMELINE_PADDING} from '../../helpers/timeline-layout';import {timelineNodePathInfoToKey} from '../../helpers/timeline-node-path-key';+import {TimelineDeleteKeybindings} from './TimelineDeleteKeybindings';export const TIMELINE_SELECTED_BACKGROUND = '#3B3F42';export const TIMELINE_SELECTED_LABEL_BACKGROUND = '#B0B0B0';@@ -41,17 +42,20 @@ export const getTimelineColor = (selected: boolean, subcategory: boolean) => {: 'rgba(255, 255, 255, 0.8)';};-export const TIMELINE_SELECTED_TRACK_HIGHLIGHT_STYLE: CSSProperties = {+export const getTimelineSelectedTrackHighlightStyle = (+ timelineWidth: number,+): CSSProperties => ({backgroundColor: TIMELINE_SELECTED_BACKGROUND,bottom: 0,left: -TIMELINE_PADDING,pointerEvents: 'none',position: 'absolute',- right: -TIMELINE_PADDING,top: 0,-};+ width: timelineWidth,+});export const SELECTION_ENABLED = false;+export const TIMELINE_TOP_DRAG = false;export type TimelineSelection =| {@@ -66,6 +70,7 @@ export type TimelineSelection =type TimelineSelectionContextValue = {readonly canSelect: boolean;+ readonly selectedItem: TimelineSelection | null;readonly isSelected: (item: TimelineSelection) => boolean;readonly selectItem: (item: TimelineSelection) => void;readonly containsSelection: (nodePathInfo: SequenceNodePathInfo) => boolean;@@ -74,6 +79,7 @@ type TimelineSelectionContextValue = {const TimelineSelectionContext = createContext<TimelineSelectionContextValue>({canSelect: false,+ selectedItem: null,isSelected: () => false,selectItem: () => undefined,containsSelection: () => false,@@ -172,17 +178,26 @@ export const TimelineSelectionProvider: React.FC<{const value = useMemo((): TimelineSelectionContextValue => ({canSelect,+ selectedItem,isSelected,selectItem,containsSelection,clearSelection,}),- [canSelect, isSelected, selectItem, containsSelection, clearSelection],+ [+ canSelect,+ selectedItem,+ isSelected,+ selectItem,+ containsSelection,+ clearSelection,+ ],);return (<TimelineSelectionContext.Provider value={value}>{children}+ <TimelineDeleteKeybindings /></TimelineSelectionContext.Provider>);};diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsxindex 23c49b6aa8..12912d858e 100644--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx@@ -1,4 +1,4 @@-import React, {useContext, useMemo} from 'react';+import React, {useCallback, useContext, useMemo} from 'react';import type {TSequence} from 'remotion';import {Internals, useCurrentFrame} from 'remotion';import {BLUE} from '../../helpers/colors';@@ -6,6 +6,7 @@ import {SEQUENCE_BORDER_WIDTH,getTimelineSequenceLayout,} from '../../helpers/get-timeline-sequence-layout';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';import {getTimelineLayerHeight,TIMELINE_LAYER_HEIGHT_AUDIO,@@ -14,6 +15,7 @@ import {useMaxMediaDuration} from '../../helpers/use-max-media-duration';import {AudioWaveform} from '../AudioWaveform';import {LoopedTimelineIndicator} from './LoopedTimelineIndicators';import {TimelineImageInfo} from './TimelineImageInfo';+import {TIMELINE_TOP_DRAG, useTimelineRowSelection} from './TimelineSelection';import {TimelineSequenceFrame} from './TimelineSequenceFrame';import {TimelineVideoInfo} from './TimelineVideoInfo';import {TimelineWidthContext} from './TimelineWidthProvider';@@ -24,14 +26,21 @@ const IMAGE_GRADIENT = 'linear-gradient(to top, #2980b9, #3498db)';const TimelineSequenceFn: React.FC<{readonly s: TSequence;-}> = ({s}) => {+ readonly nodePathInfo: SequenceNodePathInfo | null;+}> = ({s, nodePathInfo}) => {const windowWidth = useContext(TimelineWidthContext);if (windowWidth === null) {return null;}- return <TimelineSequenceInner windowWidth={windowWidth} s={s} />;+ return (+ <TimelineSequenceInner+ windowWidth={windowWidth}+ s={s}+ nodePathInfo={nodePathInfo}+ />+ );};const TimelineSequenceCurrentFrame: React.FC<{@@ -41,6 +50,7 @@ const TimelineSequenceCurrentFrame: React.FC<{readonly postmountWidth: number | null;readonly style: React.CSSProperties;readonly children: React.ReactNode;+ readonly nodePathInfo: SequenceNodePathInfo | null;}> = ({s,displayDurationInFrames,@@ -48,7 +58,19 @@ const TimelineSequenceCurrentFrame: React.FC<{postmountWidth,style,children,+ nodePathInfo,}) => {+ const {onSelect, selectable} = useTimelineRowSelection(nodePathInfo);++ const onPointerDown = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button === 0) {+ e.stopPropagation();+ onSelect();+ }+ },+ [onSelect],+ );const frame = useCurrentFrame();const relativeFrame = frame - s.from;const relativeFrameWithPremount = relativeFrame + (s.premountDisplay ?? 0);@@ -71,11 +93,16 @@ const TimelineSequenceCurrentFrame: React.FC<{return {...style,opacity: isInRange ? 1 : 0.5,+ ...(TIMELINE_TOP_DRAG ? {cursor: 'pointer'} : {}),};}, [isInRange, style]);return (- <div style={actualStyle} title={s.displayName}>+ <div+ style={actualStyle}+ title={s.displayName}+ onPointerDown={selectable ? onPointerDown : undefined}+ >{premountWidth ? (<divstyle={{@@ -140,7 +167,8 @@ const TimelineSequenceCurrentFrame: React.FC<{const TimelineSequenceInner: React.FC<{readonly s: TSequence;readonly windowWidth: number;-}> = ({s, windowWidth}) => {+ readonly nodePathInfo: SequenceNodePathInfo | null;+}> = ({s, windowWidth, nodePathInfo}) => {// If a duration is 1, it is essentially a still and it should have width 0// Some compositions may not be longer than their media duration,// if that is the case, it needs to be asynchronously determined@@ -211,6 +239,7 @@ const TimelineSequenceInner: React.FC<{premountWidth={premountWidth}postmountWidth={postmountWidth}style={style}+ nodePathInfo={nodePathInfo}>{s.type === 'audio' ? (<AudioWaveformdiff --git a/packages/studio/src/components/Timeline/TimelineSequenceFrame.tsx b/packages/studio/src/components/Timeline/TimelineSequenceFrame.tsxindex 30abfe2d3b..174f591762 100644--- a/packages/studio/src/components/Timeline/TimelineSequenceFrame.tsx+++ b/packages/studio/src/components/Timeline/TimelineSequenceFrame.tsx@@ -6,6 +6,7 @@ const relativeFrameStyle: React.CSSProperties = {color: 'white',opacity: 0.5,whiteSpace: 'nowrap',+ pointerEvents: 'none',};export const TimelineSequenceFrame: React.FC<{diff --git a/packages/studio/src/components/Timeline/TimelineTimeIndicators.tsx b/packages/studio/src/components/Timeline/TimelineTimeIndicators.tsxindex 03aa3aa766..6a0447613e 100644--- a/packages/studio/src/components/Timeline/TimelineTimeIndicators.tsx+++ b/packages/studio/src/components/Timeline/TimelineTimeIndicators.tsx@@ -20,7 +20,6 @@ export const TIMELINE_TIME_INDICATOR_HEIGHT = 39;const container: React.CSSProperties = {height: TIMELINE_TIME_INDICATOR_HEIGHT,- boxShadow: `0 0 4px ${TIMELINE_BACKGROUND}`,position: 'absolute',backgroundColor: TIMELINE_BACKGROUND,top: 0,diff --git a/packages/studio/src/components/Timeline/TimelineTrack.tsx b/packages/studio/src/components/Timeline/TimelineTrack.tsxindex df20ed962e..b9871d548b 100644--- a/packages/studio/src/components/Timeline/TimelineTrack.tsx+++ b/packages/studio/src/components/Timeline/TimelineTrack.tsx@@ -8,11 +8,12 @@ import {import {ExpandedTracksGetterContext} from '../ExpandedTracksProvider';import {TimelineExpandedTrackKeyframes} from './TimelineExpandedTrackKeyframes';import {- TIMELINE_SELECTED_TRACK_HIGHLIGHT_STYLE,+ getTimelineSelectedTrackHighlightStyle,useTimelineRowContainsSelection,useTimelineRowSelection,} from './TimelineSelection';import {TimelineSequence} from './TimelineSequence';+import {TimelineWidthContext} from './TimelineWidthProvider';const TimelineTrackUnmemoized: React.FC<{readonly track: TrackWithHash;@@ -20,6 +21,7 @@ const TimelineTrackUnmemoized: React.FC<{const {getIsExpanded} = useContext(ExpandedTracksGetterContext);const {previewServerState} = useContext(StudioServerConnectionCtx);const previewServerConnected = previewServerState.type === 'connected';+ const timelineWidth = useContext(TimelineWidthContext);const {selected: rowSelected} = useTimelineRowSelection(track.nodePathInfo);const containsSelection = useTimelineRowContainsSelection(track.nodePathInfo);@@ -43,10 +45,13 @@ const TimelineTrackUnmemoized: React.FC<{return (<div><div style={layerStyle}>- {showRowHighlight ? (- <div style={TIMELINE_SELECTED_TRACK_HIGHLIGHT_STYLE} />+ {showRowHighlight && timelineWidth !== null ? (+ <div style={getTimelineSelectedTrackHighlightStyle(timelineWidth)} />) : null}- <TimelineSequence s={track.sequence} />+ <TimelineSequence+ s={track.sequence}+ nodePathInfo={track.nodePathInfo}+ /></div>{showExpandedKeyframes && track.nodePathInfo ? (<TimelineExpandedTrackKeyframesdiff --git a/packages/studio/src/components/Timeline/call-delete-keyframe.ts b/packages/studio/src/components/Timeline/call-delete-keyframe.tsnew file mode 100644index 0000000000..e114fa3e41--- /dev/null+++ b/packages/studio/src/components/Timeline/call-delete-keyframe.ts@@ -0,0 +1,90 @@+import {+ optimisticDeleteEffectKeyframe,+ optimisticDeleteSequenceKeyframe,+} from '@remotion/studio-shared';+import type {SequencePropsSubscriptionKey, SequenceSchema} from 'remotion';+import {callApi} from '../call-api';+import {enqueueSavePropChange} from './save-prop-queue';+import type {SetCodeValues} from './save-sequence-prop';++export const callDeleteSequenceKeyframe = ({+ fileName,+ nodePath,+ fieldKey,+ sourceFrame,+ schema,+ setCodeValues,+ clientId,+}: {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ fieldKey: string;+ sourceFrame: number;+ schema: SequenceSchema;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> => {+ return enqueueSavePropChange({+ nodePath,+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticDeleteSequenceKeyframe({+ previous: prev,+ fieldKey,+ frame: sourceFrame,+ }),+ apiCall: () =>+ callApi('/api/delete-sequence-keyframe', {+ fileName,+ nodePath,+ key: fieldKey,+ frame: sourceFrame,+ schema,+ clientId,+ }),+ errorLabel: 'Could not delete keyframe',+ });+};++export const callDeleteEffectKeyframe = ({+ fileName,+ nodePath,+ effectIndex,+ fieldKey,+ sourceFrame,+ schema,+ setCodeValues,+ clientId,+}: {+ fileName: string;+ nodePath: SequencePropsSubscriptionKey;+ effectIndex: number;+ fieldKey: string;+ sourceFrame: number;+ schema: SequenceSchema;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> => {+ return enqueueSavePropChange({+ nodePath,+ setCodeValues,+ applyOptimistic: (prev) =>+ optimisticDeleteEffectKeyframe({+ previous: prev,+ effectIndex,+ fieldKey,+ frame: sourceFrame,+ }),+ apiCall: () =>+ callApi('/api/delete-effect-keyframe', {+ fileName,+ sequenceNodePath: nodePath,+ effectIndex,+ key: fieldKey,+ frame: sourceFrame,+ schema,+ clientId,+ }),+ errorLabel: 'Could not delete keyframe',+ });+};diff --git a/packages/studio/src/components/Timeline/delete-selected-keyframe.ts b/packages/studio/src/components/Timeline/delete-selected-keyframe.tsnew file mode 100644index 0000000000..1abe4dd078--- /dev/null+++ b/packages/studio/src/components/Timeline/delete-selected-keyframe.ts@@ -0,0 +1,72 @@+import type {OverrideIdToNodePaths, TSequence} from 'remotion';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {+ callDeleteEffectKeyframe,+ callDeleteSequenceKeyframe,+} from './call-delete-keyframe';+import {findTrackForNodePathInfo} from './find-track-for-node-path-info';+import {parseKeyframeFieldFromNodePath} from './parse-keyframe-field-from-node-path';+import type {SetCodeValues} from './save-sequence-prop';++export const deleteSelectedKeyframe = ({+ nodePathInfo,+ frame,+ sequences,+ overrideIdsToNodePaths,+ setCodeValues,+ clientId,+}: {+ nodePathInfo: SequenceNodePathInfo;+ frame: number;+ sequences: TSequence[];+ overrideIdsToNodePaths: OverrideIdToNodePaths;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> | null => {+ const field = parseKeyframeFieldFromNodePath(nodePathInfo.auxiliaryKeys);+ if (field === null) {+ return null;+ }++ const track = findTrackForNodePathInfo({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo,+ });+ const sequence = track?.sequence ?? null;+ if (!sequence?.controls) {+ return null;+ }++ const sourceFrame = frame - (track?.keyframeDisplayOffset ?? 0);+ const nodePath = nodePathInfo.sequenceSubscriptionKey;+ const fileName = nodePath.absolutePath;++ if (field.type === 'effect') {+ const effect = sequence.effects[field.effectIndex];+ if (!effect) {+ return null;+ }++ return callDeleteEffectKeyframe({+ fileName,+ nodePath,+ effectIndex: field.effectIndex,+ fieldKey: field.fieldKey,+ sourceFrame,+ schema: effect.schema,+ setCodeValues,+ clientId,+ });+ }++ return callDeleteSequenceKeyframe({+ fileName,+ nodePath,+ fieldKey: field.fieldKey,+ sourceFrame,+ schema: sequence.controls.schema,+ setCodeValues,+ clientId,+ });+};diff --git a/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts b/packages/studio/src/components/Timeline/delete-selected-timeline-item.tsnew file mode 100644index 0000000000..24bcee5aa6--- /dev/null+++ b/packages/studio/src/components/Timeline/delete-selected-timeline-item.ts@@ -0,0 +1,106 @@+import type {OverrideIdToNodePaths, TSequence} from 'remotion';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {callApi} from '../call-api';+import {showNotification} from '../Notifications/NotificationCenter';+import {deleteSelectedKeyframe} from './delete-selected-keyframe';+import type {SetCodeValues} from './save-sequence-prop';+import type {TimelineSelection} from './TimelineSelection';++const deleteSequence = (nodePathInfo: SequenceNodePathInfo): Promise<void> => {+ const nodePath = nodePathInfo.sequenceSubscriptionKey;++ if (nodePathInfo.numberOfSequencesWithThisNodePath > 1) {+ const message =+ 'This sequence is programmatically duplicated ' ++ nodePathInfo.numberOfSequencesWithThisNodePath ++ ' times in the code. Deleting removes all instances. Continue?';+ // eslint-disable-next-line no-alert -- native confirm before deleting all instances of a duplicated sequence+ if (!window.confirm(message)) {+ return Promise.resolve();+ }+ }++ return callApi('/api/delete-jsx-node', {+ fileName: nodePath.absolutePath,+ nodePath: nodePath.nodePath,+ })+ .then((result) => {+ if (result.success) {+ showNotification('Removed sequence from source file', 2000);+ } else {+ showNotification(result.reason, 4000);+ }+ })+ .catch((err) => {+ showNotification((err as Error).message, 4000);+ });+};++const deleteEffect = (+ nodePathInfo: SequenceNodePathInfo,+ effectIndex: number,+): Promise<void> => {+ const nodePath = nodePathInfo.sequenceSubscriptionKey;++ return callApi('/api/delete-effect', {+ fileName: nodePath.absolutePath,+ sequenceNodePath: nodePath,+ effectIndex,+ })+ .then((result) => {+ if (result.success) {+ showNotification('Removed effect from source file', 2000);+ } else {+ showNotification(result.reason, 4000);+ }+ })+ .catch((err) => {+ showNotification((err as Error).message, 4000);+ });+};++export const deleteSelectedTimelineItem = ({+ selection,+ sequences,+ overrideIdsToNodePaths,+ setCodeValues,+ clientId,+}: {+ selection: TimelineSelection;+ sequences: TSequence[];+ overrideIdsToNodePaths: OverrideIdToNodePaths;+ setCodeValues: SetCodeValues;+ clientId: string;+}): Promise<void> | null => {+ if (selection.type === 'keyframe') {+ return deleteSelectedKeyframe({+ nodePathInfo: selection.nodePathInfo,+ frame: selection.frame,+ sequences,+ overrideIdsToNodePaths,+ setCodeValues,+ clientId,+ });+ }++ const {nodePathInfo} = selection;+ const {auxiliaryKeys} = nodePathInfo;++ // The sequence track row itself has no auxiliary keys.+ if (auxiliaryKeys.length === 0) {+ return deleteSequence(nodePathInfo);+ }++ // An effect group row is ['effects', effectIndex].+ if (auxiliaryKeys.length === 2 && auxiliaryKeys[0] === 'effects') {+ const effectIndex = Number(auxiliaryKeys[1]);+ if (!Number.isInteger(effectIndex) || effectIndex < 0) {+ return null;+ }++ return deleteEffect(nodePathInfo, effectIndex);+ }++ // Field rows and other intermediate rows are not deletable on their own.+ return null;+};diff --git a/packages/studio/src/components/Timeline/find-track-for-node-path-info.ts b/packages/studio/src/components/Timeline/find-track-for-node-path-info.tsnew file mode 100644index 0000000000..0b393d27c9--- /dev/null+++ b/packages/studio/src/components/Timeline/find-track-for-node-path-info.ts@@ -0,0 +1,27 @@+import {stringifySequenceSubscriptionKey} from '@remotion/studio-shared';+import type {OverrideIdToNodePaths, TSequence} from 'remotion';+import {calculateTimeline} from '../../helpers/calculate-timeline';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';++export const findTrackForNodePathInfo = ({+ sequences,+ overrideIdsToNodePaths,+ nodePathInfo,+}: {+ sequences: TSequence[];+ overrideIdsToNodePaths: OverrideIdToNodePaths;+ nodePathInfo: SequenceNodePathInfo;+}) => {+ const tracks = calculateTimeline({sequences, overrideIdsToNodePaths});+ return tracks.find(+ (candidate) =>+ candidate.nodePathInfo !== null &&+ stringifySequenceSubscriptionKey(+ candidate.nodePathInfo.sequenceSubscriptionKey,+ ) ===+ stringifySequenceSubscriptionKey(+ nodePathInfo.sequenceSubscriptionKey,+ ) &&+ candidate.nodePathInfo.index === nodePathInfo.index,+ );+};diff --git a/packages/studio/src/components/Timeline/parse-keyframe-field-from-node-path.ts b/packages/studio/src/components/Timeline/parse-keyframe-field-from-node-path.tsnew file mode 100644index 0000000000..c59373779e--- /dev/null+++ b/packages/studio/src/components/Timeline/parse-keyframe-field-from-node-path.ts@@ -0,0 +1,37 @@+export const parseKeyframeFieldFromNodePath = (+ auxiliaryKeys: string[],+):+ | {+ readonly type: 'sequence';+ readonly fieldKey: string;+ }+ | {+ readonly type: 'effect';+ readonly effectIndex: number;+ readonly fieldKey: string;+ }+ | null => {+ // Sequence control field: ['controls', fieldKey]+ if (auxiliaryKeys[0] === 'controls' && auxiliaryKeys.length >= 2) {+ return {+ type: 'sequence',+ fieldKey: auxiliaryKeys[1],+ };+ }++ // Effect field: ['effects', effectIndex, fieldKey]+ if (auxiliaryKeys[0] === 'effects' && auxiliaryKeys.length >= 3) {+ const effectIndex = Number(auxiliaryKeys[1]);+ if (!Number.isInteger(effectIndex) || effectIndex < 0) {+ return null;+ }++ return {+ type: 'effect',+ effectIndex,+ fieldKey: auxiliaryKeys[2],+ };+ }++ return null;+};diff --git a/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts b/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.tsindex 922bbb01ad..a8e86fb42b 100644--- a/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts+++ b/packages/studio/src/components/Timeline/use-expanded-track-keyframe-rows.ts@@ -33,17 +33,26 @@ export const useExpandedTrackKeyframeRows = ({} => {const {getIsExpanded} = useContext(ExpandedTracksGetterContext);const {codeValues} = useContext(Internals.VisualModeCodeValuesContext);+ const {getDragOverrides, getEffectDragOverrides} = useContext(+ Internals.VisualModeDragOverridesContext,+ );const tree = useMemo(() =>buildTimelineTree({sequence,nodePathInfo,- getDragOverrides: () => ({}),- getEffectDragOverrides: () => ({}),+ getDragOverrides,+ getEffectDragOverrides,codeValues,}),- [codeValues, nodePathInfo, sequence],+ [+ codeValues,+ getDragOverrides,+ getEffectDragOverrides,+ nodePathInfo,+ sequence,+ ],);const flat = useMemo(diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.tsindex e92b2e3ebf..b37279fed9 100644--- a/packages/studio/src/test/timeline-selection.test.ts+++ b/packages/studio/src/test/timeline-selection.test.ts@@ -1,6 +1,13 @@import {expect, test} from 'bun:test';-import {SELECTION_ENABLED} from '../components/Timeline/TimelineSelection';+import {+ SELECTION_ENABLED,+ TIMELINE_TOP_DRAG,+} from '../components/Timeline/TimelineSelection';test('Timeline selection should stay disabled until released publicly', () => {expect(SELECTION_ENABLED).toBe(false);});++test('Timeline top drag should not be enabled', () => {+ expect(TIMELINE_TOP_DRAG).toBe(false);+});