Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Optimize remaining selection subscribers

Jonny Burger908e023b552a
diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsx
index 14cbbc49af..3aa228f44e 100644
--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx
@@ -489,7 +489,10 @@ const TimelineSelectionContext = createContext<TimelineSelectionContextValue>(
type TimelineRowSelectionContextValue = Pick<
TimelineSelectionContextValue,
- 'canSelect' | 'registerMarqueeSelectableItem' | 'selectItem'
+ | 'canSelect'
+ | 'clearSelection'
+ | 'registerMarqueeSelectableItem'
+ | 'selectItem'
> & {
readonly getSnapshot: () => TimelineSelectionState;
readonly subscribe: (listener: () => void) => () => void;
@@ -1340,6 +1343,7 @@ export const TimelineSelectionProvider: React.FC<{
const rowSelectionContextValue = useMemo(
(): TimelineRowSelectionContextValue => ({
canSelect,
+ clearSelection,
getSnapshot: getAvailableSelectionState,
registerMarqueeSelectableItem,
selectItem,
@@ -1347,6 +1351,7 @@ export const TimelineSelectionProvider: React.FC<{
}),
[
canSelect,
+ clearSelection,
getAvailableSelectionState,
registerMarqueeSelectableItem,
selectItem,
@@ -1621,19 +1626,37 @@ export const useTimelineRowSelection = (
nodePathInfo: SequenceNodePathInfo | null,
revealInInspector = false,
) => {
+ const selectionItem = useMemo(
+ (): TimelineSelection | null =>
+ getTimelineSelectionFromNodePathInfo(nodePathInfo),
+ [nodePathInfo],
+ );
+ return useTimelineSelectionItem({
+ revealInInspector,
+ selectionItem,
+ useSelectionOrder: true,
+ });
+};
+
+const useTimelineSelectionItem = <
+ TSelectionItem extends TimelineSelection | null,
+>({
+ revealInInspector,
+ selectionItem,
+ useSelectionOrder,
+}: {
+ readonly revealInInspector: boolean;
+ readonly selectionItem: TSelectionItem;
+ readonly useSelectionOrder: boolean;
+}) => {
const selectionContext = useContext(TimelineRowSelectionContext);
if (selectionContext === null) {
throw new Error(
- 'useTimelineRowSelection must be used inside TimelineSelectionProvider',
+ 'useTimelineSelectionItem must be used inside TimelineSelectionProvider',
);
}
const selectableTimelineItemsRef = useContext(SelectableTimelineItemsContext);
- const selectionItem = useMemo(
- (): TimelineSelection | null =>
- getTimelineSelectionFromNodePathInfo(nodePathInfo),
- [nodePathInfo],
- );
const selectionItemKey = useMemo(
() =>
selectionItem === null ? null : getTimelineSelectionKey(selectionItem),
@@ -1666,7 +1689,7 @@ export const useTimelineRowSelection = (
selectionContext.selectItem(
selectionItem,
interaction,
- selectableTimelineItemsRef.current,
+ useSelectionOrder ? selectableTimelineItemsRef.current : undefined,
{revealInInspector},
);
},
@@ -1675,10 +1698,12 @@ export const useTimelineRowSelection = (
selectableTimelineItemsRef,
selectionContext,
selectionItem,
+ useSelectionOrder,
],
);
return {
+ clearSelection: selectionContext.clearSelection,
onSelect,
selectable: selectionContext.canSelect && selectionItem !== null,
selectedItems:
@@ -1694,8 +1719,6 @@ export const useTimelineKeyframeSelection = (
nodePathInfo: SequenceNodePathInfo,
frame: number,
) => {
- const {canSelect, isSelected, selectItem} = useTimelineSelection();
- const selectableTimelineItemsRef = useContext(SelectableTimelineItemsContext);
const selectionItem = useMemo(
(): TimelineSelection => ({
type: 'keyframe',
@@ -1704,26 +1727,11 @@ export const useTimelineKeyframeSelection = (
}),
[nodePathInfo, frame],
);
-
- const selected = isSelected(selectionItem);
-
- const onSelect = useCallback(
- (interaction?: TimelineSelectionInteraction) => {
- selectItem(
- selectionItem,
- interaction,
- selectableTimelineItemsRef.current,
- );
- },
- [selectItem, selectableTimelineItemsRef, selectionItem],
- );
-
- return {
- onSelect,
- selectable: canSelect,
+ return useTimelineSelectionItem({
+ revealInInspector: false,
selectionItem,
- selected,
- };
+ useSelectionOrder: true,
+ });
};
export const useTimelineEasingSelection = ({
@@ -1737,8 +1745,6 @@ export const useTimelineEasingSelection = ({
readonly toFrame: number;
readonly segmentIndex: number;
}) => {
- const {canSelect, isSelected, selectItem} = useTimelineSelection();
- const selectableTimelineItemsRef = useContext(SelectableTimelineItemsContext);
const selectionItem = useMemo(
(): TimelineEasingSelection => ({
type: 'easing',
@@ -1749,31 +1755,14 @@ export const useTimelineEasingSelection = ({
}),
[nodePathInfo, fromFrame, segmentIndex, toFrame],
);
-
- const selected = isSelected(selectionItem);
-
- const onSelect = useCallback(
- (interaction?: TimelineSelectionInteraction) => {
- selectItem(
- selectionItem,
- interaction,
- selectableTimelineItemsRef.current,
- );
- },
- [selectItem, selectableTimelineItemsRef, selectionItem],
- );
-
- return {
- onSelect,
- selectable: canSelect,
- selected,
+ return useTimelineSelectionItem({
+ revealInInspector: false,
selectionItem,
- };
+ useSelectionOrder: true,
+ });
};
export const useTimelineGuideSelection = (guideId: string) => {
- const {canSelect, clearSelection, isSelected, selectItem} =
- useTimelineSelection();
const selectionItem = useMemo(
(): TimelineSelection => ({
type: 'guide',
@@ -1781,20 +1770,11 @@ export const useTimelineGuideSelection = (guideId: string) => {
}),
[guideId],
);
-
- const selected = isSelected(selectionItem);
-
- const onSelect = useCallback(() => {
- selectItem(selectionItem);
- }, [selectItem, selectionItem]);
-
- return {
- clearSelection,
- onSelect,
- selectable: canSelect,
- selected,
+ return useTimelineSelectionItem({
+ revealInInspector: false,
selectionItem,
- };
+ useSelectionOrder: false,
+ });
};
export const useTimelineRowContainsSelection = (
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index 0a6f94ccc6..903413e9c6 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -1,5 +1,12 @@
import {isValidPackageName} from '@remotion/studio-shared';
-import {useContext, useEffect, useMemo, useRef, type FC} from 'react';
+import {
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ type FC,
+ type MutableRefObject,
+} from 'react';
import {Internals, staticFile} from 'remotion';
import {installPackages} from '../api/install-package';
import {pause} from '../api/pause';
@@ -53,6 +60,7 @@ import {shouldShowTrackInTimeline} from './Timeline/should-show-track-in-timelin
import {scrollableRef} from './Timeline/timeline-refs';
import {
getTimelineSelectionFromNodePathInfo,
+ useCurrentTimelineSelectionStateAsRef,
useTimelineSelection,
} from './Timeline/TimelineSelection';
import {getOriginalLocationFromStack} from './Timeline/TimelineStack/get-stack';
@@ -185,23 +193,11 @@ const resolveAssetPath = ({
return resolvedAssetPath;
};
-export const WebMcp: FC = () => {
- const {addCaptionJob, addVideoMattingJob} = useContext(RenderQueueContext);
- const staticFiles = useStaticFiles();
- const {canSelect, clearSelection, selectedItems, selectItems} =
- useTimelineSelection();
- const {canvasContent, compositions, currentCompositionMetadata, folders} =
- useContext(Internals.CompositionManager);
- const {playbackRate: currentPlaybackRate, setPlaybackRate} =
- Internals.usePlaybackRate();
- const {isPlaying} = Internals.Timeline.useTimelineContext();
- const {mediaVolume, playerMuted} = useContext(Internals.MediaVolumeContext);
- const {setPlayerMuted} = useContext(Internals.SetMediaVolumeContext);
- const {setZoom: setTimelineZoom, zoom: timelineZoomMap} =
- useContext(TimelineZoomCtx);
- const selectComposition = useSelectComposition();
- const {editorShowGuides, guidesList, setEditorShowGuides, setGuidesList} =
- useContext(EditorShowGuidesContext);
+const WebMcpSelectionSync: FC<{
+ readonly currentSelectionRef: MutableRefObject<string | null>;
+ readonly selectedSequenceRef: MutableRefObject<WebMcpSequence | null>;
+}> = ({currentSelectionRef, selectedSequenceRef}) => {
+ const {selectedItems} = useTimelineSelection();
const {sequences} = useContext(Internals.SequenceManager);
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
@@ -230,19 +226,12 @@ export const WebMcp: FC = () => {
const currentResolvedLocation =
stack === currentStack ? resolvedLocation : null;
const currentSelection = useMemo(() => {
- if (selectedItems.length === 0) {
- return null;
- }
-
- if (selectedItems.length > 1) {
- return null;
- }
-
- if (selectedItem === null || selectedItem.type === 'guide') {
- return null;
- }
-
- if (track === null) {
+ if (
+ selectedItems.length !== 1 ||
+ selectedItem === null ||
+ selectedItem.type === 'guide' ||
+ track === null
+ ) {
return null;
}
@@ -280,18 +269,35 @@ export const WebMcp: FC = () => {
root: window.remotion_cwd,
});
}, [currentResolvedLocation, selectedItem, selectedItems.length, track]);
- const currentSelectionRef = useRef(currentSelection);
currentSelectionRef.current = currentSelection;
- const selectedSequence = useMemo(
- () => (track === null ? null : serializeSequence(track)),
- [track],
+ selectedSequenceRef.current =
+ track === null ? null : serializeSequence(track);
+
+ return null;
+};
+
+export const WebMcp: FC = () => {
+ const {addCaptionJob, addVideoMattingJob} = useContext(RenderQueueContext);
+ const staticFiles = useStaticFiles();
+ const timelineSelectionRef = useCurrentTimelineSelectionStateAsRef();
+ const currentSelectionRef = useRef<string | null>(null);
+ const selectedSequenceRef = useRef<WebMcpSequence | null>(null);
+ const {canvasContent, compositions, currentCompositionMetadata, folders} =
+ useContext(Internals.CompositionManager);
+ const {playbackRate: currentPlaybackRate, setPlaybackRate} =
+ Internals.usePlaybackRate();
+ const {isPlaying} = Internals.Timeline.useTimelineContext();
+ const {mediaVolume, playerMuted} = useContext(Internals.MediaVolumeContext);
+ const {setPlayerMuted} = useContext(Internals.SetMediaVolumeContext);
+ const {setZoom: setTimelineZoom, zoom: timelineZoomMap} =
+ useContext(TimelineZoomCtx);
+ const selectComposition = useSelectComposition();
+ const {editorShowGuides, guidesList, setEditorShowGuides, setGuidesList} =
+ useContext(EditorShowGuidesContext);
+ const {sequences} = useContext(Internals.SequenceManager);
+ const {overrideIdToNodePathMappings} = useContext(
+ Internals.OverrideIdsToNodePathsGettersContext,
);
- const selectedSequenceRef = useRef(selectedSequence);
- selectedSequenceRef.current = selectedSequence;
- const selectedItemsRef = useRef(selectedItems);
- selectedItemsRef.current = selectedItems;
- const canSelectRef = useRef(canSelect);
- canSelectRef.current = canSelect;
const currentCompositionDefinition = useMemo(() => {
if (canvasContent?.type !== 'composition') {
return null;
@@ -971,7 +977,7 @@ export const WebMcp: FC = () => {
throw new Error('No composition is currently selected.');
}
- if (!canSelectRef.current) {
+ if (!timelineSelectionRef.current.canSelect) {
throw new Error('Studio sequence selection is unavailable.');
}
@@ -991,7 +997,9 @@ export const WebMcp: FC = () => {
throw new Error(`Sequence ${sequenceId} cannot be selected.`);
}
- selectItems([selection], {reveal: true});
+ timelineSelectionRef.current.selectItems([selection], {
+ reveal: true,
+ });
return Promise.resolve({
currentContent: currentContentRef.current,
selectedSequence: serializeSequence(timelineTrack),
@@ -1293,8 +1301,8 @@ export const WebMcp: FC = () => {
currentSelection: currentSelectionRef.current,
currentContent: currentContentRef.current,
selectionType:
- selectedItemsRef.current.length === 1
- ? selectedItemsRef.current[0].type
+ timelineSelectionRef.current.selectedItems.length === 1
+ ? timelineSelectionRef.current.selectedItems[0].type
: null,
selectedSequence: selectedSequenceRef.current,
}),
@@ -1489,11 +1497,12 @@ export const WebMcp: FC = () => {
setGuidesList(() => nextGuides);
persistGuidesList(nextGuides);
- const removedGuideWasSelected = selectedItemsRef.current.some(
- (item) => item.type === 'guide' && item.guideId === guideId,
- );
+ const removedGuideWasSelected =
+ timelineSelectionRef.current.selectedItems.some(
+ (item) => item.type === 'guide' && item.guideId === guideId,
+ );
if (removedGuideWasSelected) {
- clearSelection();
+ timelineSelectionRef.current.clearSelection();
}
return Promise.resolve({
@@ -1797,16 +1806,20 @@ export const WebMcp: FC = () => {
}, [
addCaptionJob,
addVideoMattingJob,
- clearSelection,
isPlaying,
selectComposition,
- selectItems,
setEditorShowGuides,
setGuidesList,
setPlaybackRate,
setPlayerMuted,
setTimelineZoom,
+ timelineSelectionRef,
]);
- return null;
+ return (
+ <WebMcpSelectionSync
+ currentSelectionRef={currentSelectionRef}
+ selectedSequenceRef={selectedSequenceRef}
+ />
+ );
};
diff --git a/packages/studio/src/test/sequence-props-observer.test.tsx b/packages/studio/src/test/sequence-props-observer.test.tsx
index 6d772145c5..7334788185 100644
--- a/packages/studio/src/test/sequence-props-observer.test.tsx
+++ b/packages/studio/src/test/sequence-props-observer.test.tsx
@@ -7,12 +7,10 @@ import {subscribeToSequencePropsRefresh} from '../components/Timeline/sequence-p
import {SequencePropsObserver} from '../components/Timeline/SequencePropsObserver';
import {
TimelineSelectionProvider,
- useTimelineRowSelection,
useTimelineSelection,
} from '../components/Timeline/TimelineSelection';
import {FastRefreshContext} from '../fast-refresh-context';
import {StudioServerConnectionCtx} from '../helpers/client-id';
-import type {SequenceNodePathInfo} from '../helpers/get-timeline-sequence-sort-key';
import {queueSequenceNodePathMutation} from '../helpers/sequence-node-path-mutations';
import {KeybindingContextProvider} from '../state/keybindings';
@@ -265,106 +263,3 @@ test('keeps the selected sequence selected after its node path changes', () => {
: null,
).toEqual(['body', 1]);
});
-
-test('only rerenders timeline rows whose selected state changes', () => {
- const makeNodePathInfo = (index: number): SequenceNodePathInfo => ({
- sequenceSubscriptionKey: {
- absolutePath: '/project/src/BarChart.tsx',
- effectKeys: [],
- nodePath: ['body', index],
- sequenceKeys: ['hidden', 'name'],
- videoConfigValues: null,
- },
- auxiliaryKeys: [],
- index,
- numberOfSequencesWithThisNodePath: 1,
- supportsEffects: true,
- });
- const firstNodePathInfo = makeNodePathInfo(0);
- const secondNodePathInfo = makeNodePathInfo(1);
- const renderCounts = {first: 0, second: 0};
- const selectedStates = {first: false, second: false};
- const selectionRef: {
- current: ReturnType<typeof useTimelineSelection> | null;
- } = {current: null};
- const CaptureSelection = () => {
- selectionRef.current = useTimelineSelection();
- return null;
- };
-
- const Row = ({
- name,
- nodePathInfo,
- }: {
- readonly name: keyof typeof renderCounts;
- readonly nodePathInfo: SequenceNodePathInfo;
- }) => {
- const {selected} = useTimelineRowSelection(nodePathInfo);
- renderCounts[name] += 1;
- selectedStates[name] = selected;
- return null;
- };
-
- render(
- <ObserverTestProviders
- values={{
- fastRefresh: {
- fastRefreshes: 0,
- manualRefreshes: 0,
- increaseManualRefreshes: () => undefined,
- },
- expandedTracksSetter: {
- expandParentTracks: () => undefined,
- toggleTrack: () => undefined,
- migrateExpandedTracksForSubscriptionKey: () => undefined,
- } as never,
- overrideIdsGetter: {overrideIdToNodePathMappings: {}},
- overrideIdsSetter: {setOverrideIdToNodePath: () => undefined},
- propStatusesRef: {current: {}},
- visualModeSetters: {
- remapPropStatuses: () => undefined,
- setPropStatuses: () => undefined,
- } as never,
- }}
- >
- <KeybindingContextProvider>
- <TimelineSelectionProvider>
- <CaptureSelection />
- <Row name="first" nodePathInfo={firstNodePathInfo} />
- <Row name="second" nodePathInfo={secondNodePathInfo} />
- </TimelineSelectionProvider>
- </KeybindingContextProvider>
- </ObserverTestProviders>,
- );
-
- expect(renderCounts).toEqual({first: 1, second: 1});
- expect(selectedStates).toEqual({first: false, second: false});
-
- act(() => {
- selectionRef.current?.selectItems([
- {type: 'sequence', nodePathInfo: firstNodePathInfo},
- ]);
- });
-
- expect(renderCounts).toEqual({first: 2, second: 1});
- expect(selectedStates).toEqual({first: true, second: false});
-
- act(() => {
- selectionRef.current?.selectItems([
- {type: 'sequence', nodePathInfo: secondNodePathInfo},
- ]);
- });
-
- expect(renderCounts).toEqual({first: 3, second: 2});
- expect(selectedStates).toEqual({first: false, second: true});
-
- act(() => {
- selectionRef.current?.selectItems([
- {type: 'sequence', nodePathInfo: firstNodePathInfo},
- {type: 'sequence', nodePathInfo: secondNodePathInfo},
- ]);
- });
-
- expect(renderCounts).toEqual({first: 4, second: 3});
- expect(selectedStates).toEqual({first: true, second: true});
-});