Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Reduce trim work in large timelines

Jonny Burger625a7e528769
diff --git a/packages/canvas/src/calculate-timeline.ts b/packages/canvas/src/calculate-timeline.ts
index f13712d21a..8e0a7d8b88 100644
--- a/packages/canvas/src/calculate-timeline.ts
+++ b/packages/canvas/src/calculate-timeline.ts
@@ -1,73 +1,22 @@
import type {_InternalTypes, OverrideIdToNodePaths, TSequence} from 'remotion';
-import {getConnectedCompositions} from './get-connected-compositions';
-import {
- getParentSequencePlaybackRate,
- getCascadedStart,
- getCascadedStartWithTrim,
- getTimelineVisibleDuration,
- getTimelineVisibleStart,
-} from './get-sequence-visible-range';
-import {getTimelineNestedLevel} from './get-timeline-nestedness';
import type {
TimelineTrackData,
TimelineTrackWithOriginalTimings,
TimelineLoopDisplay,
} from './get-timeline-sequence-sort-key';
-import {getTimelineSequenceSortKey} from './get-timeline-sequence-sort-key';
import {sortItemsByCommitOrder} from './sort-by-commit-order';
import {timelineSequenceNodePathToKey} from './timeline-sequence-node-path-to-key';
-const getInheritedLoopDisplay = (
- sequence: TSequence,
- sequences: TSequence[],
-): TimelineLoopDisplay | undefined => {
- let owner: TSequence | undefined = sequence;
- while (owner && !owner.loopDisplay) {
- const parentId: string | null = owner.parent;
- owner = sequences.find((candidate) => candidate.id === parentId);
- }
-
- if (!owner?.loopDisplay) return undefined;
-
- const parentRate = getParentSequencePlaybackRate(owner, sequences);
- const durationInFrames = owner.loopDisplay.durationInFrames / parentRate;
- const iterationStart = getCascadedStart(owner, sequences);
- let mediaIterationStart = iterationStart;
- let descendant = sequence;
- while (descendant.id !== owner.id) {
- mediaIterationStart = Math.max(
- mediaIterationStart,
- getCascadedStart(descendant, sequences),
- );
- const parentId = descendant.parent;
- descendant = sequences.find((candidate) => candidate.id === parentId)!;
- }
-
- const origin =
- mediaIterationStart + owner.loopDisplay.startOffset / parentRate;
- let start = Math.max(0, origin);
- let end = origin + durationInFrames * owner.loopDisplay.numberOfTimes;
- if (owner.parent) {
- const parent = sequences.find(
- (candidate) => candidate.id === owner.parent,
- )!;
- const parentStart = getTimelineVisibleStart(parent, sequences);
- start = Math.max(start, parentStart);
- end = Math.min(
- end,
- parentStart + getTimelineVisibleDuration(parent, sequences),
- );
- }
-
- const visibleStart = getTimelineVisibleStart(sequence, sequences);
-
- return {
- durationInFrames,
- numberOfTimes: Math.max(0, end - start) / durationInFrames,
- startOffset: start - visibleStart,
- phaseOffsetInFrames: (start - origin) % durationInFrames,
- mediaOffsetInFrames: visibleStart - mediaIterationStart,
- };
+type SequenceTiming = {
+ parentPlaybackRate: number;
+ sequencePlaybackRate: number;
+ cascadedStart: number;
+ visibleStart: number;
+ visibleDuration: number;
+ depth: number;
+ loopOwner: TSequence | null;
+ mediaIterationStart: number;
+ hasConnectedCompositionAncestor: boolean;
};
export const calculateTimeline = ({
@@ -83,19 +32,24 @@ export const calculateTimeline = ({
sequences.map((sequence) => [sequence.id, sequence]),
);
// Nested renderers can unregister a child after its parent during navigation.
- const completeSequences = sequences.filter((sequence) => {
- let parentId = sequence.parent;
- while (parentId !== null) {
- const parent = registeredSequencesById.get(parentId);
- if (!parent) {
- return false;
- }
+ const completenessById = new Map<string, boolean>();
+ const hasCompleteAncestors = (sequence: TSequence): boolean => {
+ if (sequence.parent === null) {
+ return true;
+ }
- parentId = parent.parent;
+ const cached = completenessById.get(sequence.id);
+ if (cached !== undefined) {
+ return cached;
}
- return true;
- });
+ const parent = registeredSequencesById.get(sequence.parent);
+ const complete = parent !== undefined && hasCompleteAncestors(parent);
+ completenessById.set(sequence.id, complete);
+ return complete;
+ };
+
+ const completeSequences = sequences.filter(hasCompleteAncestors);
const sortedSequences = sortItemsByCommitOrder(
completeSequences,
(sequence) => sequence.timelineOrder,
@@ -110,51 +64,160 @@ export const calculateTimeline = ({
string,
readonly _InternalTypes['AnyComposition'][]
>();
+ const compositionsByComponent = new Map<
+ unknown,
+ _InternalTypes['AnyComposition'][]
+ >();
+ for (const composition of compositions) {
+ const component = composition.componentFromProps;
+ if (
+ component === null ||
+ component === undefined ||
+ (typeof component === 'number' && Number.isNaN(component))
+ ) {
+ continue;
+ }
+
+ const connectedCompositions = compositionsByComponent.get(component);
+ if (connectedCompositions) {
+ connectedCompositions.push(composition);
+ } else {
+ compositionsByComponent.set(component, [composition]);
+ }
+ }
+
for (const sequence of sortedSequences) {
- const connectedCompositions = getConnectedCompositions({
- compositions,
- singleChildComponent: sequence.singleChildComponent,
- });
- if (connectedCompositions.length > 0) {
- connectedCompositionsBySequenceId.set(sequence.id, connectedCompositions);
+ const connectedCompositions = compositionsByComponent.get(
+ sequence.singleChildComponent,
+ );
+ if (connectedCompositions) {
+ connectedCompositionsBySequenceId.set(
+ sequence.id,
+ connectedCompositions.slice(),
+ );
}
}
const sequencesById = new Map(
sortedSequences.map((sequence) => [sequence.id, sequence]),
);
- const timelineSequences = sortedSequences.filter((sequence) => {
- let parentId = sequence.parent;
- while (parentId !== null) {
- if (connectedCompositionsBySequenceId.has(parentId)) {
- return false;
- }
+ const timingsById = new Map<string, SequenceTiming>();
+ const getTiming = (sequence: TSequence): SequenceTiming => {
+ const cached = timingsById.get(sequence.id);
+ if (cached) {
+ return cached;
+ }
- parentId = sequencesById.get(parentId)?.parent ?? null;
+ const parent =
+ sequence.parent === null ? null : sequencesById.get(sequence.parent);
+ if (sequence.parent !== null && !parent) {
+ throw new TypeError('Parent not found for sequence ' + sequence.id);
}
- return true;
- });
+ const parentTiming = parent ? getTiming(parent) : null;
+ // Timing and nesting helpers historically treat an empty parent ID as a
+ // root, while playback rate and inherited loop lookup still resolve it.
+ const timingParent = sequence.parent ? parentTiming! : null;
+ const parentPlaybackRate = parent
+ ? parent.sequencePlaybackRate * parentTiming!.parentPlaybackRate
+ : 1;
+ const sequencePlaybackRate =
+ parentPlaybackRate * sequence.sequencePlaybackRate;
+ const cascadedStart = timingParent
+ ? timingParent.cascadedStart +
+ (sequence.from - (parent!.trimBefore ?? 0)) / parentPlaybackRate
+ : sequence.from;
+ const visibleStart = timingParent
+ ? Math.max(timingParent.visibleStart, Math.max(0, cascadedStart))
+ : Math.max(0, cascadedStart);
+ const end = cascadedStart + sequence.duration / parentPlaybackRate;
+ const visibleDuration = Math.max(
+ 0,
+ (timingParent
+ ? Math.min(
+ end,
+ timingParent.visibleStart + timingParent.visibleDuration,
+ )
+ : end) - visibleStart,
+ );
+ const loopOwner = sequence.loopDisplay
+ ? sequence
+ : (parentTiming?.loopOwner ?? null);
+ const mediaIterationStart = sequence.loopDisplay
+ ? cascadedStart
+ : parentTiming?.loopOwner
+ ? Math.max(parentTiming.mediaIterationStart, cascadedStart)
+ : cascadedStart;
+ const timing: SequenceTiming = {
+ parentPlaybackRate,
+ sequencePlaybackRate,
+ cascadedStart,
+ visibleStart,
+ visibleDuration,
+ depth: timingParent
+ ? timingParent.depth + (parent!.showInTimeline ? 1 : 0)
+ : 0,
+ loopOwner,
+ mediaIterationStart,
+ hasConnectedCompositionAncestor: parent
+ ? connectedCompositionsBySequenceId.has(parent.id) ||
+ parentTiming!.hasConnectedCompositionAncestor
+ : false,
+ };
+ timingsById.set(sequence.id, timing);
+ return timing;
+ };
+
+ const timelineSequences = sortedSequences.filter(
+ (sequence) => !getTiming(sequence).hasConnectedCompositionAncestor,
+ );
for (let i = 0; i < timelineSequences.length; i++) {
const sequence = timelineSequences[i];
- const cascadedStart = getCascadedStart(sequence, sortedSequences);
- const cascadedStartWithTrim = getCascadedStartWithTrim(
- sequence,
- sortedSequences,
- );
- const parentPlaybackRate = getParentSequencePlaybackRate(
- sequence,
- sortedSequences,
- );
- const sequencePlaybackRate =
- parentPlaybackRate * sequence.sequencePlaybackRate;
+ const timing = getTiming(sequence);
+ const {
+ cascadedStart,
+ parentPlaybackRate,
+ sequencePlaybackRate,
+ visibleStart,
+ visibleDuration,
+ } = timing;
+ const cascadedStartWithTrim =
+ cascadedStart - (sequence.trimBefore ?? 0) / sequencePlaybackRate;
+ let loopDisplay: TimelineLoopDisplay | undefined;
+ if (
+ sequence.loopDisplay ||
+ sequence.type === 'audio' ||
+ sequence.type === 'video'
+ ) {
+ const owner = timing.loopOwner;
+ if (owner?.loopDisplay) {
+ const ownerTiming = getTiming(owner);
+ const durationInFrames =
+ owner.loopDisplay.durationInFrames / ownerTiming.parentPlaybackRate;
+ const origin =
+ timing.mediaIterationStart +
+ owner.loopDisplay.startOffset / ownerTiming.parentPlaybackRate;
+ let start = Math.max(0, origin);
+ let end = origin + durationInFrames * owner.loopDisplay.numberOfTimes;
+ if (owner.parent) {
+ const parentTiming = getTiming(sequencesById.get(owner.parent)!);
+ start = Math.max(start, parentTiming.visibleStart);
+ end = Math.min(
+ end,
+ parentTiming.visibleStart + parentTiming.visibleDuration,
+ );
+ }
- const visibleStart = getTimelineVisibleStart(sequence, sortedSequences);
- const visibleDuration = getTimelineVisibleDuration(
- sequence,
- sortedSequences,
- );
+ loopDisplay = {
+ durationInFrames,
+ numberOfTimes: Math.max(0, end - start) / durationInFrames,
+ startOffset: start - visibleStart,
+ phaseOffsetInFrames: (start - origin) % durationInFrames,
+ mediaOffsetInFrames: visibleStart - timing.mediaIterationStart,
+ };
+ }
+ }
const overrideId = sequence.controls?.overrideId ?? null;
const nodePath = overrideId ? overrideIdsToNodePaths[overrideId] : null;
@@ -178,14 +241,9 @@ export const calculateTimeline = ({
? null
: sequence.postmountDisplay / parentPlaybackRate,
duration: visibleDuration,
- loopDisplay:
- sequence.loopDisplay ||
- sequence.type === 'audio' ||
- sequence.type === 'video'
- ? getInheritedLoopDisplay(sequence, sortedSequences)
- : undefined,
+ loopDisplay,
},
- depth: getTimelineNestedLevel(sequence, sortedSequences, 0),
+ depth: timing.depth,
cascadedStart,
localStart: sequence.from,
cascadedDuration: sequence.duration,
@@ -212,13 +270,28 @@ export const calculateTimeline = ({
sequenceRanks.set(tracks[i].sequence.id, i);
}
+ const tracksById = new Map(tracks.map((track) => [track.sequence.id, track]));
+ const sortKeysById = new Map<string, string>();
+ const getSortKey = (track: TimelineTrackWithOriginalTimings): string => {
+ const cached = sortKeysById.get(track.sequence.id);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const rank = sequenceRanks.get(track.sequence.id) ?? 0;
+ const id = String(rank).padStart(6, '0');
+ const parent = track.sequence.parent
+ ? tracksById.get(track.sequence.parent)
+ : null;
+ const key = parent ? `${getSortKey(parent)}-${id}` : id;
+ sortKeysById.set(track.sequence.id, key);
+ return key;
+ };
+
const sortedTracks: TimelineTrackData[] = tracks
- .sort((a, b) => {
- const sortKeyA = getTimelineSequenceSortKey(a, tracks, sequenceRanks);
- const sortKeyB = getTimelineSequenceSortKey(b, tracks, sequenceRanks);
- return sortKeyA.localeCompare(sortKeyB);
- })
- .map((track) => {
+ .map((track) => ({track, sortKey: getSortKey(track)}))
+ .sort((a, b) => a.sortKey.localeCompare(b.sortKey))
+ .map(({track}) => {
const {cascadedDuration, ...cleanTrack} = track;
return cleanTrack;
});
diff --git a/packages/core/src/SequenceManager.tsx b/packages/core/src/SequenceManager.tsx
index abeb41d56f..c266ff014a 100644
--- a/packages/core/src/SequenceManager.tsx
+++ b/packages/core/src/SequenceManager.tsx
@@ -1,4 +1,4 @@
-import React, {useCallback, useMemo, useRef, useState} from 'react';
+import React, {useCallback, useContext, useMemo, useRef, useState} from 'react';
import type {TSequence} from './CompositionManager.js';
import {
COMMIT_ORDER_EVENT,
@@ -15,6 +15,7 @@ import type {
GetEffectDragOverrides,
PropStatuses,
} from './use-schema.js';
+import {useSyncExternalStore} from './use-sync-external-store.js';
import type {VideoConfigValues} from './video-config.js';
const useIsomorphicLayoutEffect =
@@ -33,7 +34,7 @@ export type SequenceManagerRef = {
export type SequenceNodePath = Array<string | number>;
-export const SequenceManager = React.createContext<SequenceManagerContext>({
+const defaultSequenceManager: SequenceManagerContext = {
registerSequence: () => {
throw new Error('SequenceManagerContext not initialized');
},
@@ -42,8 +43,52 @@ export const SequenceManager = React.createContext<SequenceManagerContext>({
throw new Error('SequenceManagerContext not initialized');
},
sequences: [],
+};
+
+type SequenceManagerActions = Pick<
+ SequenceManagerContext,
+ 'registerSequence' | 'updateSequence' | 'unregisterSequence'
+>;
+
+export const SequenceManagerActionsContext =
+ React.createContext<SequenceManagerActions>({
+ registerSequence: defaultSequenceManager.registerSequence,
+ updateSequence: defaultSequenceManager.updateSequence,
+ unregisterSequence: defaultSequenceManager.unregisterSequence,
+ });
+
+export const SequenceManager = React.createContext(defaultSequenceManager);
+const NativeSequenceManagerProvider = SequenceManager.Provider;
+const SequenceManagerProviderWithActions: React.FC<
+ React.ProviderProps<SequenceManagerContext>
+> = ({value, children}) => {
+ const actions = useMemo<SequenceManagerActions>(
+ () => ({
+ registerSequence: value.registerSequence,
+ updateSequence: value.updateSequence,
+ unregisterSequence: value.unregisterSequence,
+ }),
+ [value.registerSequence, value.updateSequence, value.unregisterSequence],
+ );
+ return (
+ <SequenceManagerActionsContext.Provider value={actions}>
+ <NativeSequenceManagerProvider value={value}>
+ {children}
+ </NativeSequenceManagerProvider>
+ </SequenceManagerActionsContext.Provider>
+ );
+};
+
+// Keep custom SequenceManager.Provider trees in sync with the stable actions
+// context while preserving the legacy reactive sequence-list context.
+Object.defineProperty(SequenceManager, 'Provider', {
+ value: SequenceManagerProviderWithActions,
});
+export const useSequenceManagerSequences = (): TSequence[] => {
+ return useContext(SequenceManager).sequences;
+};
+
export const SequenceManagerRefContext =
React.createContext<SequenceManagerRef>({
current: [],
@@ -76,6 +121,64 @@ export type VisualModeDragOverrides = {
getEffectDragOverrides: GetEffectDragOverrides;
};
+type DragOverridesSubscription = {
+ manager: SequenceManagerActions;
+ subscribe: (key: string | null, listener: () => void) => () => void;
+ getSnapshot: (key: string | null) => Record<string, DragOverrideValue>;
+ subscribeEffects: (key: string | null, listener: () => void) => () => void;
+ getEffectSnapshot: (
+ key: string | null,
+ ) => Record<string, Record<string, DragOverrideValue>>;
+};
+
+export const VisualModeDragOverridesSubscriptionContext =
+ React.createContext<DragOverridesSubscription | null>(null);
+
+type ActiveFromDragOverrideKeys = {
+ manager: SequenceManagerActions;
+ keys: ReadonlySet<string>;
+};
+
+const ActiveFromDragOverrideKeysContext =
+ React.createContext<ActiveFromDragOverrideKeys | null>(null);
+
+const SequenceManagerScopeProviders: React.FC<{
+ readonly children: React.ReactNode;
+ readonly dragOverridesSubscription: Omit<
+ DragOverridesSubscription,
+ 'manager'
+ >;
+ readonly fromKeys: ReadonlySet<string>;
+}> = ({children, dragOverridesSubscription, fromKeys}) => {
+ const manager = useContext(SequenceManagerActionsContext);
+ const scopedDragOverridesSubscription = useMemo<DragOverridesSubscription>(
+ () => ({...dragOverridesSubscription, manager}),
+ [dragOverridesSubscription, manager],
+ );
+ const activeFromDragOverrideKeys = useMemo<ActiveFromDragOverrideKeys>(
+ () => ({manager, keys: fromKeys}),
+ [fromKeys, manager],
+ );
+ return (
+ <ActiveFromDragOverrideKeysContext.Provider
+ value={activeFromDragOverrideKeys}
+ >
+ <VisualModeDragOverridesSubscriptionContext.Provider
+ value={scopedDragOverridesSubscription}
+ >
+ {children}
+ </VisualModeDragOverridesSubscriptionContext.Provider>
+ </ActiveFromDragOverrideKeysContext.Provider>
+ );
+};
+
+const emptyDragOverrides: Record<string, DragOverrideValue> = {};
+const emptyFromOverrideKeys: ReadonlySet<string> = new Set();
+const emptyEffectDragOverrides: Record<
+ string,
+ Record<string, DragOverrideValue>
+> = {};
+
export type SequencePropsStatusRemapping = {
previousNodePath: SequencePropsSubscriptionKey;
nodePath: SequencePropsSubscriptionKey | null;
@@ -110,6 +213,24 @@ export type VisualModeSetters = {
) => void;
};
+export type VisualModeBatchSetters = {
+ setDragOverridesBatch: (
+ overrides: readonly {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly key: string;
+ readonly value: DragOverrideValue;
+ }[],
+ ) => void;
+ setEffectDragOverridesBatch: (
+ overrides: readonly {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly effectIndex: number;
+ readonly key: string;
+ readonly value: DragOverrideValue;
+ }[],
+ ) => void;
+};
+
export type CanUpdateEffectPropsResponseTrue = {
canUpdate: true;
callee: string;
@@ -176,6 +297,86 @@ export const VisualModeDragOverridesContext =
},
});
+/* eslint-disable react-hooks/rules-of-hooks */
+export const useDragOverridesForNodePath = (
+ nodePath: SequencePropsSubscriptionKey | null,
+): Record<string, DragOverrideValue> => {
+ const subscription = useContext(VisualModeDragOverridesSubscriptionContext);
+ const manager = useContext(SequenceManagerActionsContext);
+ const scopedSubscription =
+ subscription?.manager === manager ? subscription : null;
+ // Legacy providers only supply VisualModeDragOverridesContext. Its presence is
+ // fixed for the lifetime of a mounted tree.
+ const legacy =
+ scopedSubscription === null
+ ? useContext(VisualModeDragOverridesContext)
+ : null;
+ const key =
+ nodePath === null ? null : makeSequencePropsSubscriptionKey(nodePath);
+ const subscribe = useCallback(
+ (listener: () => void) =>
+ scopedSubscription?.subscribe(key, listener) ?? (() => undefined),
+ [key, scopedSubscription],
+ );
+ const getSnapshot = useCallback(
+ () => scopedSubscription?.getSnapshot(key) ?? emptyDragOverrides,
+ [key, scopedSubscription],
+ );
+ const overrides = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ return legacy !== null && nodePath !== null
+ ? legacy.getDragOverrides(nodePath)
+ : overrides;
+};
+
+export const useActiveFromDragOverrideKeys = (): ReadonlySet<string> => {
+ const snapshot = useContext(ActiveFromDragOverrideKeysContext);
+ const manager = useContext(SequenceManagerActionsContext);
+ return snapshot?.manager === manager ? snapshot.keys : emptyFromOverrideKeys;
+};
+
+export const useEffectDragOverridesForNodePath = (
+ nodePath: SequencePropsSubscriptionKey | null,
+ effectCount: number,
+): Record<string, Record<string, DragOverrideValue>> => {
+ const subscription = useContext(VisualModeDragOverridesSubscriptionContext);
+ const manager = useContext(SequenceManagerActionsContext);
+ const scopedSubscription =
+ subscription?.manager === manager ? subscription : null;
+ // Legacy providers only supply VisualModeDragOverridesContext. Its presence is
+ // fixed for the lifetime of a mounted tree.
+ const legacy =
+ scopedSubscription === null
+ ? useContext(VisualModeDragOverridesContext)
+ : null;
+ const key =
+ nodePath === null ? null : makeSequencePropsSubscriptionKey(nodePath);
+ const subscribe = useCallback(
+ (listener: () => void) =>
+ scopedSubscription?.subscribeEffects(key, listener) ?? (() => undefined),
+ [key, scopedSubscription],
+ );
+ const getSnapshot = useCallback(
+ () =>
+ scopedSubscription?.getEffectSnapshot(key) ?? emptyEffectDragOverrides,
+ [key, scopedSubscription],
+ );
+ const overrides = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ if (legacy !== null && nodePath !== null) {
+ const legacyOverrides: Record<
+ string,
+ Record<string, DragOverrideValue>
+ > = {};
+ for (let index = 0; index < effectCount; index++) {
+ legacyOverrides[index] = legacy.getEffectDragOverrides(nodePath, index);
+ }
+
+ return legacyOverrides;
+ }
+
+ return overrides;
+};
+/* eslint-enable react-hooks/rules-of-hooks */
+
export const VisualModeSettersContext = React.createContext<VisualModeSetters>({
setDragOverrides: () => {
throw new Error('VisualModeSettersContext not initialized');
@@ -197,6 +398,9 @@ export const VisualModeSettersContext = React.createContext<VisualModeSetters>({
},
});
+export const VisualModeBatchSettersContext =
+ React.createContext<VisualModeBatchSetters | null>(null);
+
export type SequencePropsSubscriptionKey = {
absolutePath: string;
nodePath: SequenceNodePath;
@@ -223,68 +427,273 @@ export const SequenceManagerProvider: React.FC<{
const [sequences, setSequences] = useState<TSequence[]>([]);
const sequencesRef = useRef(sequences);
sequencesRef.current = sequences;
- const [dragOverrides, setControlOverrides] = useState<DragOverrides>({});
- const controlOverridesRef = useRef(dragOverrides);
- controlOverridesRef.current = dragOverrides;
+ const [dragOverrideState, setDragOverrideState] = useState(() => ({
+ overrides: {} as DragOverrides,
+ fromKeys: new Set<string>(),
+ }));
+ const dragOverrides = dragOverrideState.overrides;
+ const dragOverridesStore = useRef({
+ snapshot: dragOverrides,
+ listeners: new Map<string, Set<() => void>>(),
+ });
const [effectDragOverridesState, setEffectDragOverridesState] =
useState<EffectDragOverrides>({});
+ const effectDragOverridesStore = useRef({
+ snapshot: effectDragOverridesState,
+ byNode: new Map<
+ string,
+ Record<string, Record<string, DragOverrideValue>>
+ >(),
+ listeners: new Map<string, Set<() => void>>(),
+ });
const [propStatuses, setPropStatusesMapState] = useState<PropStatuses>({});
const propStatusesRef = useRef(propStatuses);
propStatusesRef.current = propStatuses;
+ const setDragOverridesBatch = useCallback(
+ (
+ overrides: readonly {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly key: string;
+ readonly value: DragOverrideValue;
+ }[],
+ ) => {
+ setDragOverrideState((prevState) => {
+ const prev = prevState.overrides;
+ let next: DragOverrides | null = null;
+ let nextFromKeys = prevState.fromKeys;
+ for (const {nodePath, key, value} of overrides) {
+ const mapKey = makeSequencePropsSubscriptionKey(nodePath);
+ const existing = (next ?? prev)[mapKey]?.[key];
+ if (
+ existing === value ||
+ (existing?.type === 'static' &&
+ value.type === 'static' &&
+ Object.is(existing.value, value.value))
+ ) {
+ continue;
+ }
+
+ if (next === null) {
+ next = {...prev};
+ }
+
+ if (next[mapKey] === prev[mapKey]) {
+ next[mapKey] = {...prev[mapKey]};
+ }
+
+ next[mapKey][key] = value;
+ if (key === 'from' && !nextFromKeys.has(mapKey)) {
+ nextFromKeys = new Set(nextFromKeys);
+ nextFromKeys.add(mapKey);
+ }
+ }
+
+ return next === null
+ ? prevState
+ : {overrides: next, fromKeys: nextFromKeys};
+ });
+ },
+ [],
+ );
+
const setDragOverrides = useCallback(
(
nodePath: SequencePropsSubscriptionKey,
key: string,
value: DragOverrideValue,
- ) => {
- setControlOverrides((prev) => ({
- ...prev,
- [makeSequencePropsSubscriptionKey(nodePath)]: {
- ...prev[makeSequencePropsSubscriptionKey(nodePath)],
- [key]: value,
- },
- }));
+ ) => setDragOverridesBatch([{nodePath, key, value}]),
+ [setDragOverridesBatch],
+ );
+
+ const subscribeDragOverrides = useCallback(
+ (key: string | null, listener: () => void) => {
+ if (key === null) {
+ return () => undefined;
+ }
+
+ let listeners = dragOverridesStore.current.listeners.get(key);
+ if (!listeners) {
+ listeners = new Set();
+ dragOverridesStore.current.listeners.set(key, listeners);
+ }
+
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ dragOverridesStore.current.listeners.delete(key);
+ }
+ };
},
[],
);
+ const getDragOverridesSnapshot = useCallback((key: string | null) => {
+ return key === null
+ ? emptyDragOverrides
+ : (dragOverridesStore.current.snapshot[key] ?? emptyDragOverrides);
+ }, []);
+ useIsomorphicLayoutEffect(() => {
+ const previous = dragOverridesStore.current.snapshot;
+ dragOverridesStore.current.snapshot = dragOverrides;
+ for (const key of new Set([
+ ...Object.keys(previous),
+ ...Object.keys(dragOverrides),
+ ])) {
+ if (previous[key] !== dragOverrides[key]) {
+ for (const listener of dragOverridesStore.current.listeners.get(key) ??
+ []) {
+ listener();
+ }
+ }
+ }
+ }, [dragOverrides]);
+ const subscribeEffectDragOverrides = useCallback(
+ (key: string | null, listener: () => void) => {
+ if (key === null) {
+ return () => undefined;
+ }
+
+ let listeners = effectDragOverridesStore.current.listeners.get(key);
+ if (!listeners) {
+ listeners = new Set();
+ effectDragOverridesStore.current.listeners.set(key, listeners);
+ }
+
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ effectDragOverridesStore.current.listeners.delete(key);
+ }
+ };
+ },
+ [],
+ );
+ const getEffectDragOverridesSnapshot = useCallback((key: string | null) => {
+ return key === null
+ ? emptyEffectDragOverrides
+ : (effectDragOverridesStore.current.byNode.get(key) ??
+ emptyEffectDragOverrides);
+ }, []);
+ useIsomorphicLayoutEffect(() => {
+ const previous = effectDragOverridesStore.current.snapshot;
+ const byNode = new Map(effectDragOverridesStore.current.byNode);
+ const changedNodes = new Set<string>();
+ for (const flatKey of new Set([
+ ...Object.keys(previous),
+ ...Object.keys(effectDragOverridesState),
+ ])) {
+ if (previous[flatKey] === effectDragOverridesState[flatKey]) {
+ continue;
+ }
+
+ const separator = flatKey.lastIndexOf('.effects.');
+ if (separator === -1) {
+ throw new Error('Invalid effect drag override key');
+ }
+
+ const nodeKey = flatKey.slice(0, separator);
+ const effectIndex = flatKey.slice(separator + '.effects.'.length);
+ if (!changedNodes.has(nodeKey)) {
+ byNode.set(nodeKey, {...byNode.get(nodeKey)});
+ changedNodes.add(nodeKey);
+ }
+
+ const next = byNode.get(nodeKey)!;
+ if (effectDragOverridesState[flatKey] === undefined) {
+ delete next[effectIndex];
+ } else {
+ next[effectIndex] = effectDragOverridesState[flatKey];
+ }
+ }
+
+ for (const nodeKey of changedNodes) {
+ if (Object.keys(byNode.get(nodeKey)!).length === 0) {
+ byNode.delete(nodeKey);
+ }
+ }
+
+ effectDragOverridesStore.current.snapshot = effectDragOverridesState;
+ effectDragOverridesStore.current.byNode = byNode;
+ for (const nodeKey of changedNodes) {
+ for (const listener of effectDragOverridesStore.current.listeners.get(
+ nodeKey,
+ ) ?? []) {
+ listener();
+ }
+ }
+ }, [effectDragOverridesState]);
const clearDragOverrides = useCallback(
(nodePath: SequencePropsSubscriptionKey) => {
- setControlOverrides((prev) => {
+ setDragOverrideState((prevState) => {
+ const prev = prevState.overrides;
const key = makeSequencePropsSubscriptionKey(nodePath);
if (!prev[key]) {
- return prev;
+ return prevState;
}
const next = {...prev};
delete next[key];
- return next;
+ const nextFromKeys = prevState.fromKeys.has(key)
+ ? new Set(prevState.fromKeys)
+ : prevState.fromKeys;
+ nextFromKeys.delete(key);
+ return {overrides: next, fromKeys: nextFromKeys};
});
},
[],
);
- const setEffectDragOverrides = useCallback(
+ const setEffectDragOverridesBatch = useCallback(
(
- nodePath: SequencePropsSubscriptionKey,
- effectIndex: number,
- key: string,
- value: DragOverrideValue,
+ overrides: readonly {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly effectIndex: number;
+ readonly key: string;
+ readonly value: DragOverrideValue;
+ }[],
) => {
setEffectDragOverridesState((prev) => {
- const mapKey = effectDragOverridesKey(nodePath, effectIndex);
- return {
- ...prev,
- [mapKey]: {
- ...prev[mapKey],
- [key]: value,
- },
- };
+ let next: EffectDragOverrides | null = null;
+ for (const {nodePath, effectIndex, key, value} of overrides) {
+ const mapKey = effectDragOverridesKey(nodePath, effectIndex);
+ const existing = (next ?? prev)[mapKey]?.[key];
+ if (
+ existing === value ||
+ (existing?.type === 'static' &&
+ value.type === 'static' &&
+ Object.is(existing.value, value.value))
+ ) {
+ continue;
+ }
+
+ if (next === null) {
+ next = {...prev};
+ }
+
+ if (next[mapKey] === prev[mapKey]) {
+ next[mapKey] = {...prev[mapKey]};
+ }
+
+ next[mapKey][key] = value;
+ }
+
+ return next ?? prev;
});
},
[],
);
+ const setEffectDragOverrides = useCallback(
+ (
+ nodePath: SequencePropsSubscriptionKey,
+ effectIndex: number,
+ key: string,
+ value: DragOverrideValue,
+ ) => setEffectDragOverridesBatch([{nodePath, effectIndex, key, value}]),
+ [setEffectDragOverridesBatch],
+ );
const clearEffectDragOverrides = useCallback(
(nodePath: SequencePropsSubscriptionKey, effectIndex: number) => {
@@ -449,6 +858,22 @@ export const SequenceManagerProvider: React.FC<{
unregisterSequence,
};
}, [registerSequence, sequences, unregisterSequence, updateSequence]);
+ const dragOverridesSubscription = useMemo<
+ Omit<DragOverridesSubscription, 'manager'>
+ >(
+ () => ({
+ subscribe: subscribeDragOverrides,
+ getSnapshot: getDragOverridesSnapshot,
+ subscribeEffects: subscribeEffectDragOverrides,
+ getEffectSnapshot: getEffectDragOverridesSnapshot,
+ }),
+ [
+ getDragOverridesSnapshot,
+ getEffectDragOverridesSnapshot,
+ subscribeDragOverrides,
+ subscribeEffectDragOverrides,
+ ],
+ );
const getDragOverrides = useCallback(
(nodePath: SequencePropsSubscriptionKey) => {
@@ -498,19 +923,32 @@ export const SequenceManagerProvider: React.FC<{
setPropStatuses,
remapPropStatuses,
]);
+ const batchSettersContext = useMemo<VisualModeBatchSetters>(
+ () => ({setDragOverridesBatch, setEffectDragOverridesBatch}),
+ [setDragOverridesBatch, setEffectDragOverridesBatch],
+ );
const providers = (
<SequenceManagerRefContext.Provider value={sequencesRef}>
<SequenceManager.Provider value={sequenceContext}>
<VisualModePropStatusesRefContext.Provider value={propStatusesRef}>
<VisualModePropStatusesContext.Provider value={propStatusesContext}>
- <VisualModeDragOverridesContext.Provider
- value={dragOverridesContext}
+ <SequenceManagerScopeProviders
+ dragOverridesSubscription={dragOverridesSubscription}
+ fromKeys={dragOverrideState.fromKeys}
>
- <VisualModeSettersContext.Provider value={settersContext}>
- {children}
- </VisualModeSettersContext.Provider>
- </VisualModeDragOverridesContext.Provider>
+ <VisualModeDragOverridesContext.Provider
+ value={dragOverridesContext}
+ >
+ <VisualModeSettersContext.Provider value={settersContext}>
+ <VisualModeBatchSettersContext.Provider
+ value={batchSettersContext}
+ >
+ {children}
+ </VisualModeBatchSettersContext.Provider>
+ </VisualModeSettersContext.Provider>
+ </VisualModeDragOverridesContext.Provider>
+ </SequenceManagerScopeProviders>
</VisualModePropStatusesContext.Provider>
</VisualModePropStatusesRefContext.Provider>
</SequenceManager.Provider>
diff --git a/packages/core/src/effects/use-memoized-effects.ts b/packages/core/src/effects/use-memoized-effects.ts
index 6e9a8b80d3..709d12fd42 100644
--- a/packages/core/src/effects/use-memoized-effects.ts
+++ b/packages/core/src/effects/use-memoized-effects.ts
@@ -13,7 +13,7 @@ import type {
} from '../SequenceManager.js';
import {
makeSequencePropsSubscriptionKey,
- VisualModeDragOverridesContext,
+ useEffectDragOverridesForNodePath,
VisualModePropStatusesContext,
type SequencePropsSubscriptionKey,
} from '../SequenceManager.js';
@@ -29,6 +29,8 @@ import type {
EffectDefinition,
} from './effect-types.js';
+const emptyDragOverrides: Record<string, DragOverrideValue> = {};
+
const mergeOverrides = ({
descriptor,
propStatusOverrides,
@@ -220,7 +222,6 @@ export const useMemoizedEffects = ({
const previousRef = useRef<EffectDefinitionAndStack<unknown>[] | null>(null);
const {propStatuses} = useContext(VisualModePropStatusesContext);
- const {getEffectDragOverrides} = useContext(VisualModeDragOverridesContext);
const frame = useCurrentFrame();
const {overrideIdToNodePathMappings} = useContext(
@@ -232,6 +233,10 @@ export const useMemoizedEffects = ({
const nodePath = overrideId
? (overrideIdToNodePathMappings[overrideId] ?? null)
: null;
+ const effectDragOverrides = useEffectDragOverridesForNodePath(
+ nodePath,
+ effects.length,
+ );
const resolved = effects.map((descriptor, index) => {
if (nodePath === null) {
@@ -251,7 +256,7 @@ export const useMemoizedEffects = ({
effectStatus.type === 'can-update-effect'
? resolvePropStatusOverrides(effectStatus.props, frame)
: null;
- const dragOverridesMap = getEffectDragOverrides(nodePath, index);
+ const dragOverridesMap = effectDragOverrides[index] ?? emptyDragOverrides;
const dragOverrides =
Object.keys(dragOverridesMap).length === 0 ? null : dragOverridesMap;
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 5c2e8e59f8..7d5434482c 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -188,7 +188,10 @@ import {
SequenceManager,
SequenceManagerProvider,
SequenceManagerRefContext,
+ useActiveFromDragOverrideKeys,
+ useSequenceManagerSequences,
SequenceRegistrationContext,
+ VisualModeBatchSettersContext,
VisualModeDragOverridesContext,
VisualModePropStatusesContext,
VisualModePropStatusesRefContext,
@@ -346,11 +349,14 @@ export const Internals = {
CompositionSetters,
VisualModePropStatusesContext,
VisualModePropStatusesRefContext,
+ VisualModeBatchSettersContext,
VisualModeDragOverridesContext,
VisualModeSettersContext,
SequenceManager,
SequenceManagerProvider,
SequenceManagerRefContext,
+ useActiveFromDragOverrideKeys,
+ useSequenceManagerSequences,
SequenceRegistrationContext,
DisableSequenceRegistrationProvider,
CommitOrderInternals,
diff --git a/packages/core/src/use-sequence-registration.ts b/packages/core/src/use-sequence-registration.ts
index 92a14a83e6..f2dac240ec 100644
--- a/packages/core/src/use-sequence-registration.ts
+++ b/packages/core/src/use-sequence-registration.ts
@@ -2,7 +2,7 @@ import {useContext, useEffect, useRef} from 'react';
import type {TSequence} from './CompositionManager.js';
import {
DisableSequenceRegistrationContext,
- SequenceManager,
+ SequenceManagerActionsContext,
} from './SequenceManager.js';
export const useSequenceRegistration = ({
@@ -12,8 +12,9 @@ export const useSequenceRegistration = ({
getSequence: (() => TSequence) | null;
id: string;
}) => {
- const {registerSequence, unregisterSequence, updateSequence} =
- useContext(SequenceManager);
+ const {registerSequence, unregisterSequence, updateSequence} = useContext(
+ SequenceManagerActionsContext,
+ );
const registrationDisabled = useContext(DisableSequenceRegistrationContext);
const getSequenceRef = useRef(getSequence);
getSequenceRef.current = getSequence;
diff --git a/packages/core/src/with-interactivity-schema.ts b/packages/core/src/with-interactivity-schema.ts
index fe959055f2..0f34718ff1 100644
--- a/packages/core/src/with-interactivity-schema.ts
+++ b/packages/core/src/with-interactivity-schema.ts
@@ -28,7 +28,7 @@ import {
import {createRuntimeValueStore} from './runtime-value-store.js';
import {OverrideIdsToNodePathsGettersContext} from './sequence-node-path.js';
import {
- VisualModeDragOverridesContext,
+ useDragOverridesForNodePath,
VisualModePropStatusesContext,
} from './SequenceManager.js';
import {useCurrentFrame} from './use-current-frame.js';
@@ -242,8 +242,6 @@ export const withInteractivitySchema = <
// eslint-disable-next-line react-hooks/rules-of-hooks
const {propStatuses} = useContext(VisualModePropStatusesContext);
// eslint-disable-next-line react-hooks/rules-of-hooks
- const {getDragOverrides} = useContext(VisualModeDragOverridesContext);
- // eslint-disable-next-line react-hooks/rules-of-hooks
const nodePathMapping = useContext(OverrideIdsToNodePathsGettersContext);
// eslint-disable-next-line react-hooks/rules-of-hooks
const frame = useCurrentFrame();
@@ -306,6 +304,8 @@ export const withInteractivitySchema = <
const nodePath = env.isReadOnlyStudio
? null
: (nodePathMapping.overrideIdToNodePathMappings[overrideId] ?? null);
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ const dragOverrides = useDragOverridesForNodePath(nodePath);
// Read the runtime values for every flat key from the JSX props,
// memoized on the leaf values so the object reference is stable
@@ -366,7 +366,7 @@ export const withInteractivitySchema = <
return computeEffectiveSchemaValuesDotNotation({
schema: schemaWithSequenceName,
currentValue: currentRuntimeValueDotNotation,
- overrideValues: nodePath === null ? {} : getDragOverrides(nodePath),
+ overrideValues: dragOverrides,
propStatus:
nodePath === null
? undefined
@@ -375,7 +375,7 @@ export const withInteractivitySchema = <
});
}, [
currentRuntimeValueDotNotation,
- getDragOverrides,
+ dragOverrides,
nodePath,
propStatuses,
frame,
diff --git a/packages/player/src/Player.tsx b/packages/player/src/Player.tsx
index 7e0225a346..e07b2b9a92 100644
--- a/packages/player/src/Player.tsx
+++ b/packages/player/src/Player.tsx
@@ -124,7 +124,7 @@ export const componentOrNullIfLazy = <Props,>(
const TimelineSequenceObserverComponent: React.FC<{
readonly onTimelineSequenceChange: TimelineSequenceObserver;
}> = ({onTimelineSequenceChange}) => {
- const {sequences} = React.useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
useEffect(() => {
onTimelineSequenceChange(sequences);
diff --git a/packages/studio/src/components/GlobalKeybindings.tsx b/packages/studio/src/components/GlobalKeybindings.tsx
index e0285c1aff..bf07533303 100644
--- a/packages/studio/src/components/GlobalKeybindings.tsx
+++ b/packages/studio/src/components/GlobalKeybindings.tsx
@@ -116,7 +116,7 @@ export const GlobalKeybindings: React.FC = () => {
]);
const currentSelection = useCurrentTimelineSelectionStateAsRef();
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const videoConfig = Internals.useUnsafeVideoConfig();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
diff --git a/packages/studio/src/components/InspectorPanel/EasingInspector.tsx b/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
index 7da4a32a68..300fd4846b 100644
--- a/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/EasingInspector.tsx
@@ -60,7 +60,7 @@ export const EasingInspector: React.FC<{
const runtimeValues = useRuntimeValues(track?.sequence.controls ?? null);
const videoConfig = useVideoConfig();
const timelinePosition = Internals.Timeline.useTimelinePosition();
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
diff --git a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
index 6f73e26c35..f615c7676c 100644
--- a/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/MultiSequenceInspector.tsx
@@ -60,7 +60,7 @@ export const MultiSequenceInspector: React.FC<{
readonly readOnlyStudio: boolean;
}> = ({selections, readOnlyStudio}) => {
const {previewServerState} = useContext(StudioServerConnectionCtx);
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const timelinePosition = Internals.Timeline.useTimelinePosition();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
diff --git a/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx b/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx
index dd2d8c5db4..d0788eef55 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx
@@ -46,7 +46,7 @@ export const SequenceWrapAction: React.FC<{
}> = ({nodePathInfo, track, sourceActionsDisabled, sourceLocation}) => {
const {width, height} = useVideoConfig();
const {setSelectedModal} = useContext(SetSelectedModalContext);
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
diff --git a/packages/studio/src/components/InspectorPanel/use-track-for-selection.ts b/packages/studio/src/components/InspectorPanel/use-track-for-selection.ts
index 77c93c0c75..631247e93b 100644
--- a/packages/studio/src/components/InspectorPanel/use-track-for-selection.ts
+++ b/packages/studio/src/components/InspectorPanel/use-track-for-selection.ts
@@ -4,7 +4,7 @@ import {findTrackForNodePathInfo} from '../Timeline/find-track-for-node-path-inf
import type {TimelineSelection} from '../Timeline/TimelineSelection';
export const useTrackForSelection = (selection: TimelineSelection) => {
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index f82433cf15..55e45962d7 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -843,7 +843,7 @@ const SelectedOutlineOverlayUnmemoized: React.FC<
}) => {
const {selectedItems, selectItem} = useTimelineSelection();
const currentSelection = useCurrentTimelineSelectionStateAsRef();
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {compositions} = useContext(Internals.CompositionManager);
const {propStatuses} = useContext(Internals.VisualModePropStatusesContext);
const {previewServerState} = useContext(StudioServerConnectionCtx);
diff --git a/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx b/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
index 5058892f04..a156dc7c1d 100644
--- a/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
+++ b/packages/studio/src/components/SequencePropsSubscriptionProvider.tsx
@@ -1,11 +1,4 @@
-import {
- createContext,
- useCallback,
- useContext,
- useMemo,
- useRef,
- useState,
-} from 'react';
+import {createContext, useCallback, useMemo, useRef, useState} from 'react';
import {Internals} from 'remotion';
import type {
OverrideIdToNodePaths,
@@ -48,7 +41,7 @@ export const getReadOnlyOverrideIdToNodePathMappings = (
export const SequencePropsSubscriptionProvider: React.FC<{
readonly children: React.ReactNode;
}> = ({children}) => {
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const [overrideToNodePathMap, setOverrideIdToNodePathMap] =
useState<OverrideIdToNodePaths>({});
const readOnlyOverrideToNodePathMap = useMemo(
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 08aa57d054..b9a45573f6 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -7,7 +7,7 @@ import React, {
useRef,
useState,
} from 'react';
-import {Internals} from 'remotion';
+import {Internals, type TSequence} from 'remotion';
import {FastRefreshContext} from '../../fast-refresh-context';
import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {calculateTimeline} from '../../helpers/calculate-timeline';
@@ -269,7 +269,7 @@ const TimelineContextMenuArea: React.FC<{
};
const TimelineInner: React.FC = () => {
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {canvasContent, compositions} = useContext(
Internals.CompositionManager,
);
@@ -285,30 +285,109 @@ const TimelineInner: React.FC = () => {
const previewInteractive = previewConnected && isStudioInteractivityEnabled();
const videoConfigIsNull = videoConfig === null;
+ const previousTimelineRef = useRef<{
+ readonly sequences: TSequence[];
+ readonly overrideIdsToNodePaths: typeof overrideIdToNodePathMappings;
+ readonly compositions: typeof compositions;
+ readonly timeline: TimelineTrackWithDisplayGroup[];
+ } | null>(null);
const timeline = useMemo((): TimelineTrackWithDisplayGroup[] => {
if (videoConfigIsNull) {
return [];
}
- return addTimelineDisplayGroups(
+ const next = addTimelineDisplayGroups(
calculateTimeline({
sequences,
overrideIdsToNodePaths: overrideIdToNodePathMappings,
compositions,
}),
);
+ const previous = previousTimelineRef.current;
+ if (
+ previous === null ||
+ previous.overrideIdsToNodePaths !== overrideIdToNodePathMappings ||
+ previous.compositions !== compositions
+ ) {
+ return next;
+ }
+
+ const previousSequencesById = new Map(
+ previous.sequences.map((sequence) => [sequence.id, sequence]),
+ );
+ const currentSequencesById = new Map(
+ sequences.map((sequence) => [sequence.id, sequence]),
+ );
+ const previousTracksById = new Map(
+ previous.timeline.map((track) => [track.sequence.id, track]),
+ );
+ return next.map((track) => {
+ const oldTrack = previousTracksById.get(track.sequence.id);
+ const currentSource = currentSequencesById.get(track.sequence.id);
+ const oldNodePath = oldTrack?.nodePathInfo;
+ const nodePath = track.nodePathInfo;
+ const oldLoop = oldTrack?.sequence.loopDisplay;
+ const loop = track.sequence.loopDisplay;
+ if (
+ oldTrack === undefined ||
+ currentSource !== previousSequencesById.get(track.sequence.id) ||
+ oldTrack.depth !== track.depth ||
+ oldTrack.cascadedStart !== track.cascadedStart ||
+ oldTrack.localStart !== track.localStart ||
+ oldTrack.keyframeDisplayOffset !== track.keyframeDisplayOffset ||
+ oldTrack.keyframePlaybackRate !== track.keyframePlaybackRate ||
+ oldTrack.sequenceFrameOffset !== track.sequenceFrameOffset ||
+ oldTrack.sequence.from !== track.sequence.from ||
+ oldTrack.sequence.duration !== track.sequence.duration ||
+ oldTrack.sequence.sequencePlaybackRate !==
+ track.sequence.sequencePlaybackRate ||
+ oldTrack.sequence.premountDisplay !== track.sequence.premountDisplay ||
+ oldTrack.sequence.postmountDisplay !==
+ track.sequence.postmountDisplay ||
+ oldTrack.displayGroup?.key !== track.displayGroup?.key ||
+ oldTrack.displayGroup?.numberOfSequences !==
+ track.displayGroup?.numberOfSequences ||
+ (oldNodePath === null) !== (nodePath === null) ||
+ (oldNodePath !== null &&
+ nodePath !== null &&
+ (oldNodePath?.sequenceSubscriptionKey !==
+ nodePath.sequenceSubscriptionKey ||
+ oldNodePath?.index !== nodePath.index ||
+ oldNodePath?.numberOfSequencesWithThisNodePath !==
+ nodePath.numberOfSequencesWithThisNodePath ||
+ oldNodePath?.supportsEffects !== nodePath.supportsEffects)) ||
+ (oldLoop === undefined) !== (loop === undefined) ||
+ (oldLoop !== undefined &&
+ loop !== undefined &&
+ (oldLoop.durationInFrames !== loop.durationInFrames ||
+ oldLoop.numberOfTimes !== loop.numberOfTimes ||
+ oldLoop.startOffset !== loop.startOffset ||
+ oldLoop.phaseOffsetInFrames !== loop.phaseOffsetInFrames ||
+ oldLoop.mediaOffsetInFrames !== loop.mediaOffsetInFrames))
+ ) {
+ return track;
+ }
+
+ return oldTrack;
+ });
}, [
sequences,
videoConfigIsNull,
overrideIdToNodePathMappings,
compositions,
]);
+ useLayoutEffect(() => {
+ previousTimelineRef.current = {
+ sequences,
+ overrideIdsToNodePaths: overrideIdToNodePathMappings,
+ compositions,
+ timeline,
+ };
+ }, [compositions, overrideIdToNodePathMappings, sequences, timeline]);
const durationInFrames = videoConfig?.durationInFrames ?? 0;
- const {getDragOverrides} = useContext(
- Internals.VisualModeDragOverridesContext,
- );
+ const activeFromDragOverrideKeys = Internals.useActiveFromDragOverrideKeys();
const filtered = useMemo(() => {
return timeline.filter((t) => {
// Moving outside the composition can reduce the displayed duration to
@@ -316,15 +395,18 @@ const TimelineInner: React.FC = () => {
if (
t.sequence.showInTimeline &&
t.nodePathInfo !== null &&
- getDragOverrides(t.nodePathInfo.sequenceSubscriptionKey).from !==
- undefined
+ activeFromDragOverrideKeys.has(
+ Internals.makeSequencePropsSubscriptionKey(
+ t.nodePathInfo.sequenceSubscriptionKey,
+ ),
+ )
) {
return true;
}
return shouldShowTrackInTimeline(t, durationInFrames);
});
- }, [durationInFrames, getDragOverrides, timeline]);
+ }, [activeFromDragOverrideKeys, durationInFrames, timeline]);
// Keep `filtered` complete so a future toggle can show every programmatic
// instance without recalculating the timeline or losing its instance index.
diff --git a/packages/studio/src/components/Timeline/TimelineSelection.tsx b/packages/studio/src/components/Timeline/TimelineSelection.tsx
index aa835d1df2..34498ba1fc 100644
--- a/packages/studio/src/components/Timeline/TimelineSelection.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSelection.tsx
@@ -17,6 +17,7 @@ import React, {
useCallback,
useContext,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
@@ -102,6 +103,18 @@ const {
useCanvasSelectionController,
} = CanvasInternals;
+const emptyDragOverrideSnapshot = {};
+const getDragOverrideSnapshot = (overrides: Record<string, unknown>): object =>
+ Object.keys(overrides).length === 0 ? emptyDragOverrideSnapshot : overrides;
+
+type SelectableTrackCache = {
+ readonly track: TimelineTrackData;
+ readonly expanded: boolean;
+ readonly dragOverride: object | null;
+ readonly effectOverrides: readonly object[];
+ readonly items: TimelineSelection[];
+};
+
export const TIMELINE_SELECTED_BACKGROUND = TIMELINE_SELECTED_BACKGROUND_COLOR;
export const TIMELINE_EXPANDED_SELECTED_BACKGROUND = BACKGROUND;
export const TIMELINE_HOVER_BACKGROUND = WHITE_ALPHA_05;
@@ -652,6 +665,115 @@ export const getSelectableTimelineSequenceSelections = (
});
};
+const getSelectableTimelineItemsForTrack = ({
+ getDragOverrides,
+ getEffectDragOverrides,
+ getIsExpanded,
+ propStatuses,
+ selectedRowKeys,
+ track,
+ timelinePosition,
+}: {
+ readonly getDragOverrides: GetDragOverrides;
+ readonly getEffectDragOverrides: GetEffectDragOverrides;
+ readonly getIsExpanded: GetIsExpanded;
+ readonly propStatuses: PropStatuses;
+ readonly selectedRowKeys: ReadonlySet<string>;
+ readonly track: TimelineTrackData;
+ readonly timelinePosition: number;
+}): TimelineSelection[] => {
+ const {nodePathInfo} = track;
+ if (nodePathInfo === null) {
+ return [];
+ }
+
+ const sequenceSelection = getTimelineSelectionFromNodePathInfo(nodePathInfo);
+ if (sequenceSelection === null) {
+ return [];
+ }
+
+ if (!getIsExpanded(nodePathInfo)) {
+ return [sequenceSelection];
+ }
+
+ const tree = buildTimelineTree({
+ sequence: track.sequence,
+ nodePathInfo,
+ getDragOverrides,
+ getEffectDragOverrides,
+ propStatuses,
+ includeTextContent: false,
+ includeSourceControls: false,
+ runtimeValues: null,
+ });
+ const filteredTree = filterTimelineExpandedTree({
+ nodes: tree,
+ shouldShowNode: (node) =>
+ isTimelineExpandedNodeSelected({
+ nodePathInfo: node.nodePathInfo,
+ selectedRowKeys,
+ }) ||
+ getNodeHasKeyframes({
+ node,
+ nodePath: nodePathInfo.sequenceSubscriptionKey,
+ propStatuses,
+ getDragOverrides,
+ getEffectDragOverrides,
+ }),
+ });
+ const visibleTreeRows = flattenVisibleTreeNodes({
+ nodes: filteredTree,
+ getIsExpanded,
+ });
+
+ return [
+ sequenceSelection,
+ ...visibleTreeRows.flatMap(({node}): TimelineSelection[] => {
+ const rowSelection = getTimelineSelectionFromNodePathInfo(
+ node.nodePathInfo,
+ );
+ if (rowSelection === null) {
+ return [];
+ }
+
+ const keyframes = getNodeKeyframes({
+ node,
+ nodePath: nodePathInfo.sequenceSubscriptionKey,
+ propStatuses,
+ keyframeDisplayOffset: track.keyframeDisplayOffset,
+ keyframePlaybackRate: track.keyframePlaybackRate,
+ getDragOverrides,
+ getEffectDragOverrides,
+ timelinePosition,
+ });
+ const keyframeSelections = keyframes.map(
+ (keyframe): TimelineSelection => ({
+ type: 'keyframe',
+ nodePathInfo: node.nodePathInfo,
+ frame: keyframe.frame,
+ }),
+ );
+ const easingSelections = getNodeCanEditEasing({
+ node,
+ nodePath: nodePathInfo.sequenceSubscriptionKey,
+ propStatuses,
+ })
+ ? getKeyframeSegments(keyframes).map(
+ (segment): TimelineSelection => ({
+ type: 'easing',
+ nodePathInfo: node.nodePathInfo,
+ fromFrame: segment.fromFrame,
+ toFrame: segment.toFrame,
+ segmentIndex: segment.segmentIndex,
+ }),
+ )
+ : [];
+
+ return [rowSelection, ...easingSelections, ...keyframeSelections];
+ }),
+ ];
+};
+
export const getSelectableTimelineItems = ({
getDragOverrides,
getEffectDragOverrides,
@@ -670,100 +792,17 @@ export const getSelectableTimelineItems = ({
readonly timelinePosition: number;
}): TimelineSelection[] => {
const selectedRowKeys = getSelectedTimelineExpandedRowKeys(selectedItems);
-
- return timeline.flatMap((track): TimelineSelection[] => {
- const {nodePathInfo} = track;
- if (nodePathInfo === null) {
- return [];
- }
-
- const sequenceSelection =
- getTimelineSelectionFromNodePathInfo(nodePathInfo);
- if (sequenceSelection === null) {
- return [];
- }
-
- if (!getIsExpanded(nodePathInfo)) {
- return [sequenceSelection];
- }
-
- const tree = buildTimelineTree({
- sequence: track.sequence,
- nodePathInfo,
+ return timeline.flatMap((track) =>
+ getSelectableTimelineItemsForTrack({
getDragOverrides,
getEffectDragOverrides,
- propStatuses,
- includeTextContent: false,
- includeSourceControls: false,
- runtimeValues: null,
- });
- const filteredTree = filterTimelineExpandedTree({
- nodes: tree,
- shouldShowNode: (node) =>
- isTimelineExpandedNodeSelected({
- nodePathInfo: node.nodePathInfo,
- selectedRowKeys,
- }) ||
- getNodeHasKeyframes({
- node,
- nodePath: nodePathInfo.sequenceSubscriptionKey,
- propStatuses,
- getDragOverrides,
- getEffectDragOverrides,
- }),
- });
- const visibleTreeRows = flattenVisibleTreeNodes({
- nodes: filteredTree,
getIsExpanded,
- });
-
- return [
- sequenceSelection,
- ...visibleTreeRows.flatMap(({node}): TimelineSelection[] => {
- const rowSelection = getTimelineSelectionFromNodePathInfo(
- node.nodePathInfo,
- );
- if (rowSelection === null) {
- return [];
- }
-
- const keyframes = getNodeKeyframes({
- node,
- nodePath: nodePathInfo.sequenceSubscriptionKey,
- propStatuses,
- keyframeDisplayOffset: track.keyframeDisplayOffset,
- keyframePlaybackRate: track.keyframePlaybackRate,
- getDragOverrides,
- getEffectDragOverrides,
- timelinePosition,
- });
- const keyframeSelections = keyframes.map(
- (keyframe): TimelineSelection => ({
- type: 'keyframe',
- nodePathInfo: node.nodePathInfo,
- frame: keyframe.frame,
- }),
- );
- const easingSelections = getNodeCanEditEasing({
- node,
- nodePath: nodePathInfo.sequenceSubscriptionKey,
- propStatuses,
- })
- ? getKeyframeSegments(keyframes).map(
- (segment): TimelineSelection => ({
- type: 'easing',
- nodePathInfo: node.nodePathInfo,
- fromFrame: segment.fromFrame,
- toFrame: segment.toFrame,
- segmentIndex: segment.segmentIndex,
- }),
- )
- : [];
-
- return [rowSelection, ...easingSelections, ...keyframeSelections];
- }),
- ];
- });
+ propStatuses,
+ selectedRowKeys,
+ track,
+ timelinePosition,
+ }),
+ );
};
export const getTimelineSequenceSelectionKey = getCanvasSequenceSelectionKey;
@@ -908,26 +947,138 @@ export const TimelineSelectableItemsProvider: React.FC<{
Internals.VisualModeDragOverridesContext,
);
const {selectedItems} = useTimelineSelection();
- const selectableItems = useMemo(
- () =>
- getSelectableTimelineItems({
- getDragOverrides,
- getEffectDragOverrides,
- getIsExpanded,
- propStatuses,
- selectedItems,
- timeline,
- timelinePosition: getCurrentFrame(),
- }),
- [
- getDragOverrides,
- getEffectDragOverrides,
- getIsExpanded,
+ const previousSelectionRef = useRef<{
+ readonly timeline: readonly TimelineTrackData[];
+ readonly propStatuses: PropStatuses;
+ readonly selectedItems: readonly TimelineSelection[];
+ readonly getIsExpanded: GetIsExpanded;
+ readonly timelinePosition: number;
+ readonly items: TimelineSelection[];
+ readonly byId: Map<string, SelectableTrackCache>;
+ readonly expandedEntries: readonly SelectableTrackCache[];
+ } | null>(null);
+ const selection = useMemo(() => {
+ const previous = previousSelectionRef.current;
+ const timelinePosition = getCurrentFrame();
+ if (
+ previous !== null &&
+ previous.timeline === timeline &&
+ previous.propStatuses === propStatuses &&
+ previous.selectedItems === selectedItems &&
+ previous.getIsExpanded === getIsExpanded &&
+ previous.timelinePosition === timelinePosition &&
+ previous.expandedEntries.every((entry) => {
+ const nodePath = entry.track.nodePathInfo?.sequenceSubscriptionKey;
+ if (nodePath === undefined) {
+ return false;
+ }
+
+ return (
+ entry.dragOverride ===
+ getDragOverrideSnapshot(getDragOverrides(nodePath)) &&
+ entry.effectOverrides.every(
+ (value, index) =>
+ value ===
+ getDragOverrideSnapshot(getEffectDragOverrides(nodePath, index)),
+ )
+ );
+ })
+ ) {
+ return previous;
+ }
+
+ const invalidateAll =
+ previous === null ||
+ previous.propStatuses !== propStatuses ||
+ previous.selectedItems !== selectedItems ||
+ previous.getIsExpanded !== getIsExpanded ||
+ previous.timelinePosition !== timelinePosition;
+ const selectedRowKeys = getSelectedTimelineExpandedRowKeys(selectedItems);
+ const byId = new Map<string, SelectableTrackCache>();
+ const expandedEntries: SelectableTrackCache[] = [];
+ let changed = previous === null || previous.timeline !== timeline;
+ const items: TimelineSelection[] = [];
+
+ for (const track of timeline) {
+ const nodePath = track.nodePathInfo?.sequenceSubscriptionKey ?? null;
+ const expanded =
+ track.nodePathInfo !== null && getIsExpanded(track.nodePathInfo);
+ let dragOverride: object | null = null;
+ if (expanded && nodePath !== null) {
+ dragOverride = getDragOverrideSnapshot(getDragOverrides(nodePath));
+ }
+
+ const effectOverrides =
+ expanded && nodePath !== null
+ ? track.sequence.effects.map((_, index) =>
+ getDragOverrideSnapshot(getEffectDragOverrides(nodePath, index)),
+ )
+ : [];
+ const old = previous?.byId.get(track.sequence.id);
+ const canReuse =
+ !invalidateAll &&
+ old?.track === track &&
+ old.expanded === expanded &&
+ (!expanded ||
+ (old.dragOverride === dragOverride &&
+ old.effectOverrides.length === effectOverrides.length &&
+ old.effectOverrides.every(
+ (value, index) => value === effectOverrides[index],
+ )));
+ const trackItems = canReuse
+ ? old.items
+ : getSelectableTimelineItemsForTrack({
+ getDragOverrides,
+ getEffectDragOverrides,
+ getIsExpanded,
+ propStatuses,
+ selectedRowKeys,
+ track,
+ timelinePosition,
+ });
+ if (!canReuse) {
+ changed = true;
+ }
+
+ const entry: SelectableTrackCache = {
+ track,
+ expanded,
+ dragOverride,
+ effectOverrides,
+ items: trackItems,
+ };
+ byId.set(track.sequence.id, entry);
+ if (expanded) {
+ expandedEntries.push(entry);
+ }
+
+ for (const item of trackItems) {
+ items.push(item);
+ }
+ }
+
+ return {
+ timeline,
propStatuses,
selectedItems,
- timeline,
- ],
- );
+ getIsExpanded,
+ timelinePosition,
+ byId,
+ expandedEntries,
+ items: changed ? items : previous!.items,
+ };
+ }, [
+ getDragOverrides,
+ getEffectDragOverrides,
+ getIsExpanded,
+ propStatuses,
+ selectedItems,
+ timeline,
+ ]);
+ useLayoutEffect(() => {
+ previousSelectionRef.current = selection;
+ }, [selection]);
+ const selectableItems = selection.items;
return (
<TimelineSelectionOrderProvider items={selectableItems}>
diff --git a/packages/studio/src/components/Timeline/TimelineSequence.tsx b/packages/studio/src/components/Timeline/TimelineSequence.tsx
index 3d8620b18c..7787d72d96 100644
--- a/packages/studio/src/components/Timeline/TimelineSequence.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequence.tsx
@@ -587,7 +587,7 @@ const TimelineSequenceInner: React.FC<{
// if that is the case, it needs to be asynchronously determined
const video = Internals.useVideo();
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const overrideIdToNodePathMappingsRef = useContext(
OverrideIdToNodePathMappingsRefContext,
);
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
index 0a6ef2145d..ef15ef2fa0 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
@@ -13,6 +13,7 @@ import React, {
import type {
CanUpdateSequencePropStatus,
CanUpdateSequencePropStatusKeyframed,
+ DragOverrideValue,
InteractivitySchema,
OverrideIdToNodePaths,
PropStatuses,
@@ -249,6 +250,50 @@ export type TimelineSequenceFromDragTarget = {
readonly sequenceKeyframes: TimelineSequenceKeyframeDragTarget[];
};
+type DragOverrideUpdate = {
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly key: string;
+ readonly value: DragOverrideValue;
+};
+
+type EffectDragOverrideUpdate = DragOverrideUpdate & {
+ readonly effectIndex: number;
+};
+
+const queueStaticDragOverrideIfChanged = ({
+ updates,
+ previousValues,
+ nodePath,
+ key,
+ value,
+ initialValue,
+}: {
+ readonly updates: DragOverrideUpdate[];
+ readonly previousValues: Map<string, Map<string, number>>;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly key: string;
+ readonly value: number;
+ readonly initialValue: number;
+}) => {
+ const nodeKey = stringifySequenceSubscriptionKey(nodePath);
+ const previousForNode = previousValues.get(nodeKey);
+ const previousValue = previousForNode?.get(key);
+ if (
+ previousValue === value ||
+ (previousValue === undefined && value === initialValue)
+ ) {
+ return;
+ }
+
+ if (previousForNode) {
+ previousForNode.set(key, value);
+ } else {
+ previousValues.set(nodeKey, new Map([[key, value]]));
+ }
+
+ updates.push({nodePath, key, value: Internals.makeStaticDragOverride(value)});
+};
+
const shiftKeyframedStatus = ({
status,
deltaFrames,
@@ -1427,6 +1472,7 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(
Internals.VisualModeSettersContext,
);
+ const batchSetters = useContext(Internals.VisualModeBatchSettersContext);
const propStatusesRef = useContext(
Internals.VisualModePropStatusesRefContext,
);
@@ -1443,6 +1489,9 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
const dragStateRef = useRef<{
initialClientX: number;
latestDeltaFrames: number;
+ lastPreviewDeltaFrames: number;
+ previousPreviewValues: Map<string, Map<string, number>>;
+ lastTooltipDelta: number | null;
didMove: boolean;
pxPerFrame: number;
pointerId: number;
@@ -1456,6 +1505,7 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
initialEdgeFrame,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
previewServerState,
overrideIdToNodePathMappings,
@@ -1467,6 +1517,7 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
initialEdgeFrame,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
previewServerState,
overrideIdToNodePathMappings,
@@ -1626,6 +1677,9 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
dragStateRef.current = {
initialClientX: e.clientX,
latestDeltaFrames: 0,
+ lastPreviewDeltaFrames: 0,
+ previousPreviewValues: new Map(),
+ lastTooltipDelta: null,
didMove: false,
pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
pointerId: e.pointerId,
@@ -1661,6 +1715,18 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
dragState.didMove = true;
}
+ if (
+ deltaFrames === dragState.lastPreviewDeltaFrames &&
+ (!dragState.didMove ||
+ draggedTarget === undefined ||
+ dragState.lastTooltipDelta !== null)
+ ) {
+ return;
+ }
+
+ dragState.lastPreviewDeltaFrames = deltaFrames;
+
+ const updates: DragOverrideUpdate[] = [];
for (const target of dragState.targets) {
if (target.ripplePrevious) {
const previous = target.ripplePrevious;
@@ -1670,16 +1736,20 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
maximumDuration: previous.maximumDuration,
minimumDuration: previous.minimumDuration,
});
- latestRef.current.setDragOverrides(
- previous.nodePath,
- previous.endField.fieldKey,
- Internals.makeStaticDragOverride(
- getTimelineSequenceEndFieldValue({
- endField: previous.endField,
- durationInFrames: nextDuration,
- }),
- ),
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: previous.nodePath,
+ key: previous.endField.fieldKey,
+ value: getTimelineSequenceEndFieldValue({
+ endField: previous.endField,
+ durationInFrames: nextDuration,
+ }),
+ initialValue: getTimelineSequenceEndFieldValue({
+ endField: previous.endField,
+ durationInFrames: previous.initialDuration,
+ }),
+ });
continue;
}
@@ -1697,28 +1767,49 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
dragState.mode !== 'source-only' &&
target.positionField !== null
) {
- latestRef.current.setDragOverrides(
- target.nodePath,
- target.positionField,
- Internals.makeStaticDragOverride(nextValues.from),
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: target.positionField,
+ value: nextValues.from,
+ initialValue: target.initialFrom,
+ });
}
if (dragState.mode !== 'source-only') {
- latestRef.current.setDragOverrides(
- target.nodePath,
- 'durationInFrames',
- Internals.makeStaticDragOverride(
- nextValues.durationInFrames * target.playbackRate,
- ),
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: 'durationInFrames',
+ value: nextValues.durationInFrames * target.playbackRate,
+ initialValue: target.initialDuration * target.playbackRate,
+ });
}
- latestRef.current.setDragOverrides(
- target.nodePath,
- 'trimBefore',
- Internals.makeStaticDragOverride(nextValues.trimBefore),
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: 'trimBefore',
+ value: nextValues.trimBefore,
+ initialValue: target.initialTrimBefore,
+ });
+ }
+
+ if (updates.length > 0) {
+ if (latestRef.current.batchSetters) {
+ latestRef.current.batchSetters.setDragOverridesBatch(updates);
+ } else {
+ for (const update of updates) {
+ latestRef.current.setDragOverrides(
+ update.nodePath,
+ update.key,
+ update.value,
+ );
+ }
+ }
}
if (dragState.didMove && draggedTarget) {
@@ -1756,15 +1847,18 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
(draggedTarget.positionField === null && ripplePrevious === null)
? 0
: appliedDelta;
- setTrimTooltip({
- deltaFrames: appliedDelta,
- edgeFrame: initialTimelineEdge + edgeDelta,
- x:
- initialEdgeClientX +
- (edgeDelta / draggedTarget.parentPlaybackRate) *
- dragState.pxPerFrame,
- y: initialEdgeClientY,
- });
+ if (dragState.lastTooltipDelta !== appliedDelta) {
+ dragState.lastTooltipDelta = appliedDelta;
+ setTrimTooltip({
+ deltaFrames: appliedDelta,
+ edgeFrame: initialTimelineEdge + edgeDelta,
+ x:
+ initialEdgeClientX +
+ (edgeDelta / draggedTarget.parentPlaybackRate) *
+ dragState.pxPerFrame,
+ y: initialEdgeClientY,
+ });
+ }
}
};
@@ -1894,6 +1988,7 @@ export const useTimelineSequenceFromDrag = ({
setEffectDragOverrides,
clearEffectDragOverrides,
} = useContext(Internals.VisualModeSettersContext);
+ const batchSetters = useContext(Internals.VisualModeBatchSettersContext);
const propStatusesRef = useContext(
Internals.VisualModePropStatusesRefContext,
);
@@ -1909,6 +2004,7 @@ export const useTimelineSequenceFromDrag = ({
const dragStateRef = useRef<{
initialClientX: number;
latestDeltaFrames: number;
+ lastPreviewDeltaFrames: number;
didMove: boolean;
pxPerFrame: number;
targets: readonly TimelineSequenceFromDragTarget[];
@@ -1918,6 +2014,7 @@ export const useTimelineSequenceFromDrag = ({
nodePathInfo,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
setEffectDragOverrides,
clearEffectDragOverrides,
@@ -1930,6 +2027,7 @@ export const useTimelineSequenceFromDrag = ({
nodePathInfo,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
setEffectDragOverrides,
clearEffectDragOverrides,
@@ -2055,6 +2153,7 @@ export const useTimelineSequenceFromDrag = ({
dragStateRef.current = {
initialClientX: e.clientX,
latestDeltaFrames: 0,
+ lastPreviewDeltaFrames: 0,
didMove: false,
pxPerFrame,
targets,
@@ -2081,7 +2180,7 @@ export const useTimelineSequenceFromDrag = ({
targets: dragState.targets,
});
dragState.latestDeltaFrames = deltaFrames;
- if (deltaFrames !== 0) {
+ if (deltaFrames !== 0 && !dragState.didMove) {
// The bar can be removed when it leaves the visible timeline.
// Capture only after a real drag starts so clicks and double-clicks
// remain targeted at the bar.
@@ -2089,21 +2188,29 @@ export const useTimelineSequenceFromDrag = ({
dragState.didMove = true;
}
+ if (deltaFrames === dragState.lastPreviewDeltaFrames) {
+ return;
+ }
+
+ dragState.lastPreviewDeltaFrames = deltaFrames;
+ const updates: DragOverrideUpdate[] = [];
+ const effectUpdates: EffectDragOverrideUpdate[] = [];
+
for (const target of dragState.targets) {
const nextFrom = getTimelineSequenceFromDragValue({
initialFrom: target.initialFrom,
deltaFrames: deltaFrames * target.parentPlaybackRate,
});
- latestRef.current.setDragOverrides(
- target.nodePath,
- 'from',
- Internals.makeStaticDragOverride(nextFrom),
- );
+ updates.push({
+ nodePath: target.nodePath,
+ key: 'from',
+ value: Internals.makeStaticDragOverride(nextFrom),
+ });
for (const keyframeTarget of target.sequenceKeyframes) {
- latestRef.current.setDragOverrides(
- keyframeTarget.nodePath,
- keyframeTarget.fieldKey,
- {
+ updates.push({
+ nodePath: keyframeTarget.nodePath,
+ key: keyframeTarget.fieldKey,
+ value: {
type: 'keyframed',
status: shiftKeyframedStatus({
status: keyframeTarget.status,
@@ -2112,15 +2219,15 @@ export const useTimelineSequenceFromDrag = ({
isDescendant: keyframeTarget.isDescendant,
}),
},
- );
+ });
}
for (const keyframeTarget of target.effectKeyframes) {
- latestRef.current.setEffectDragOverrides(
- keyframeTarget.nodePath,
- keyframeTarget.effectIndex,
- keyframeTarget.fieldKey,
- {
+ effectUpdates.push({
+ nodePath: keyframeTarget.nodePath,
+ effectIndex: keyframeTarget.effectIndex,
+ key: keyframeTarget.fieldKey,
+ value: {
type: 'keyframed',
status: shiftKeyframedStatus({
status: keyframeTarget.status,
@@ -2129,9 +2236,38 @@ export const useTimelineSequenceFromDrag = ({
isDescendant: keyframeTarget.isDescendant,
}),
},
+ });
+ }
+ }
+
+ if (latestRef.current.batchSetters) {
+ latestRef.current.batchSetters.setDragOverridesBatch(updates);
+ } else {
+ for (const update of updates) {
+ latestRef.current.setDragOverrides(
+ update.nodePath,
+ update.key,
+ update.value,
);
}
}
+
+ if (effectUpdates.length > 0) {
+ if (latestRef.current.batchSetters) {
+ latestRef.current.batchSetters.setEffectDragOverridesBatch(
+ effectUpdates,
+ );
+ } else {
+ for (const update of effectUpdates) {
+ latestRef.current.setEffectDragOverrides(
+ update.nodePath,
+ update.effectIndex,
+ update.key,
+ update.value,
+ );
+ }
+ }
+ }
},
onEnd: (reason, endEvent) => {
stopPointerSessionRef.current = null;
@@ -2191,6 +2327,7 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(
Internals.VisualModeSettersContext,
);
+ const batchSetters = useContext(Internals.VisualModeBatchSettersContext);
const propStatusesRef = useContext(
Internals.VisualModePropStatusesRefContext,
);
@@ -2210,6 +2347,9 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
const dragStateRef = useRef<{
initialClientX: number;
latestDeltaFrames: number;
+ lastPreviewDeltaFrames: number;
+ previousPreviewValues: Map<string, Map<string, number>>;
+ lastTooltipDelta: number | null;
didMove: boolean;
pxPerFrame: number;
pointerId: number;
@@ -2224,6 +2364,7 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
initialEdgeFrame,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
previewServerState,
overrideIdToNodePathMappings,
@@ -2236,6 +2377,7 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
initialEdgeFrame,
setPropStatuses,
setDragOverrides,
+ batchSetters,
clearDragOverrides,
previewServerState,
overrideIdToNodePathMappings,
@@ -2375,6 +2517,9 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
dragStateRef.current = {
initialClientX: e.clientX,
latestDeltaFrames: 0,
+ lastPreviewDeltaFrames: 0,
+ previousPreviewValues: new Map(),
+ lastTooltipDelta: null,
didMove: false,
pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
pointerId: e.pointerId,
@@ -2404,6 +2549,18 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
dragState.didMove = true;
}
+ if (
+ deltaFrames === dragState.lastPreviewDeltaFrames &&
+ (!dragState.didMove ||
+ draggedTarget === undefined ||
+ dragState.lastTooltipDelta !== null)
+ ) {
+ return;
+ }
+
+ dragState.lastPreviewDeltaFrames = deltaFrames;
+
+ const updates: DragOverrideUpdate[] = [];
for (const target of dragState.targets) {
const previewValue = getTimelineSequenceDurationDragValue({
initialDuration: target.initialDuration,
@@ -2412,16 +2569,34 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
minimumDuration: target.minimumDuration,
});
- latestRef.current.setDragOverrides(
- target.nodePath,
- target.endField.fieldKey,
- Internals.makeStaticDragOverride(
- getTimelineSequenceEndFieldValue({
- endField: target.endField,
- durationInFrames: previewValue,
- }),
- ),
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: target.endField.fieldKey,
+ value: getTimelineSequenceEndFieldValue({
+ endField: target.endField,
+ durationInFrames: previewValue,
+ }),
+ initialValue: getTimelineSequenceEndFieldValue({
+ endField: target.endField,
+ durationInFrames: target.initialDuration,
+ }),
+ });
+ }
+
+ if (updates.length > 0) {
+ if (latestRef.current.batchSetters) {
+ latestRef.current.batchSetters.setDragOverridesBatch(updates);
+ } else {
+ for (const update of updates) {
+ latestRef.current.setDragOverrides(
+ update.nodePath,
+ update.key,
+ update.value,
+ );
+ }
+ }
}
if (dragState.didMove && draggedTarget) {
@@ -2434,15 +2609,18 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
const appliedDelta =
(previewValue - draggedTarget.initialDuration) /
draggedTarget.parentPlaybackRate;
- setTrimTooltip({
- deltaFrames: appliedDelta,
- edgeFrame: initialTimelineEdge + appliedDelta,
- x:
- initialEdgeClientX +
- (appliedDelta / draggedTarget.parentPlaybackRate) *
- dragState.pxPerFrame,
- y: initialEdgeClientY,
- });
+ if (dragState.lastTooltipDelta !== appliedDelta) {
+ dragState.lastTooltipDelta = appliedDelta;
+ setTrimTooltip({
+ deltaFrames: appliedDelta,
+ edgeFrame: initialTimelineEdge + appliedDelta,
+ x:
+ initialEdgeClientX +
+ (appliedDelta / draggedTarget.parentPlaybackRate) *
+ dragState.pxPerFrame,
+ y: initialEdgeClientY,
+ });
+ }
}
};
diff --git a/packages/studio/src/components/Timeline/TimelineVirtualization.tsx b/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
index 5f4e4941eb..cf4fdcbdf4 100644
--- a/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVirtualization.tsx
@@ -61,6 +61,7 @@ export const TimelineVirtualizationProvider: React.FC<{
const paddingEnd =
TIMELINE_ITEM_BORDER_BOTTOM +
(hasBeenCut ? MAX_TIMELINE_TRACKS_NOTICE_HEIGHT : 0);
+ const previousRowsRef = useRef<readonly TimelineVirtualRow[]>([]);
const layout = useMemo(() => {
const siblingIndexes = new Array<number>(timeline.length);
@@ -93,13 +94,21 @@ export const TimelineVirtualizationProvider: React.FC<{
offsets[index + 1] = offsets[index] + trackHeights[index];
}
- const rows = timeline.map(
- (track, index): TimelineVirtualRow => ({
- afterDropLineOffset: offsets[subtreeEndIndexes[index]] - offsets[index],
- siblingIndex: siblingIndexes[index],
- track,
- }),
- );
+ const rows = timeline.map((track, index): TimelineVirtualRow => {
+ const afterDropLineOffset =
+ offsets[subtreeEndIndexes[index]] - offsets[index];
+ const siblingIndex = siblingIndexes[index];
+ const previous = previousRowsRef.current[index];
+ if (
+ previous?.track === track &&
+ previous.afterDropLineOffset === afterDropLineOffset &&
+ previous.siblingIndex === siblingIndex
+ ) {
+ return previous;
+ }
+
+ return {afterDropLineOffset, siblingIndex, track};
+ });
const rootTrackIndexes = new Map<string, number>();
for (let index = 0; index < timeline.length; index++) {
const {nodePathInfo} = timeline[index];
@@ -117,6 +126,9 @@ export const TimelineVirtualizationProvider: React.FC<{
tracksEnd: offsets[offsets.length - 1],
};
}, [paddingStart, timeline, trackHeights]);
+ useLayoutEffect(() => {
+ previousRowsRef.current = layout.rows;
+ }, [layout.rows]);
const selectedTrackIndexes = useMemo(() => {
const indexes = new Set<number>();
diff --git a/packages/studio/src/components/Timeline/use-timeline-height.ts b/packages/studio/src/components/Timeline/use-timeline-height.ts
index e7c93556a8..9320f45fcd 100644
--- a/packages/studio/src/components/Timeline/use-timeline-height.ts
+++ b/packages/studio/src/components/Timeline/use-timeline-height.ts
@@ -1,5 +1,5 @@
-import {useContext, useMemo, useRef} from 'react';
-import {Internals} from 'remotion';
+import {useContext, useLayoutEffect, useMemo, useRef} from 'react';
+import {Internals, type PropStatuses} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
import {
@@ -19,6 +19,19 @@ import {
} from './timeline-expanded-filter';
import {useTimelineSelection} from './TimelineSelection';
+const emptyDragOverrideSnapshot = {};
+const getDragOverrideSnapshot = (overrides: Record<string, unknown>): object =>
+ Object.keys(overrides).length === 0 ? emptyDragOverrideSnapshot : overrides;
+
+type HeightTrackCache = {
+ readonly track: TimelineTrackData;
+ readonly expanded: boolean;
+ readonly runtimeValues: Readonly<Record<string, unknown>> | null;
+ readonly dragOverride: object | null;
+ readonly effectOverrides: readonly object[];
+ readonly height: number;
+};
+
export const useTimelineTrackHeights = ({
timeline,
}: {
@@ -65,12 +78,92 @@ export const useTimelineTrackHeights = ({
[expandedControls, runtimeValueSnapshots],
);
- const heights = useMemo(() => {
- return timeline.map((track) => {
+ const previousHeightsRef = useRef<{
+ readonly timeline: readonly TimelineTrackData[];
+ readonly entries: readonly HeightTrackCache[];
+ readonly expandedEntries: readonly HeightTrackCache[];
+ readonly heights: readonly number[];
+ readonly propStatuses: PropStatuses;
+ readonly selectedRowKeys: ReadonlySet<string>;
+ readonly getIsExpanded: typeof getIsExpanded;
+ readonly previewServerConnected: boolean;
+ readonly runtimeValuesByStore: typeof runtimeValuesByStore;
+ } | null>(null);
+ const result = useMemo(() => {
+ const previous = previousHeightsRef.current;
+ if (
+ previous !== null &&
+ previous.timeline === timeline &&
+ previous.propStatuses === propStatuses &&
+ previous.selectedRowKeys === selectedRowKeys &&
+ previous.getIsExpanded === getIsExpanded &&
+ previous.previewServerConnected === previewServerConnected &&
+ previous.runtimeValuesByStore === runtimeValuesByStore &&
+ previous.expandedEntries.every((entry) => {
+ const nodePath = entry.track.nodePathInfo?.sequenceSubscriptionKey;
+ if (nodePath === undefined) {
+ return false;
+ }
+
+ return (
+ entry.dragOverride ===
+ getDragOverrideSnapshot(getDragOverrides(nodePath)) &&
+ entry.effectOverrides.every(
+ (value, index) =>
+ value ===
+ getDragOverrideSnapshot(getEffectDragOverrides(nodePath, index)),
+ )
+ );
+ })
+ ) {
+ return previous;
+ }
+
+ const invalidateExpanded =
+ previous === null ||
+ previous.propStatuses !== propStatuses ||
+ previous.selectedRowKeys !== selectedRowKeys ||
+ previous.getIsExpanded !== getIsExpanded;
+ const entries = timeline.map((track, index): HeightTrackCache => {
const isExpanded =
previewServerConnected &&
track.nodePathInfo !== null &&
getIsExpanded(track.nodePathInfo);
+ const nodePath = track.nodePathInfo?.sequenceSubscriptionKey ?? null;
+ const runtimeValues =
+ isExpanded && track.sequence.controls
+ ? (runtimeValuesByStore.get(track.sequence.controls.runtimeValues) ??
+ null)
+ : null;
+ let dragOverride: object | null = null;
+ if (isExpanded && nodePath !== null) {
+ dragOverride = getDragOverrideSnapshot(getDragOverrides(nodePath));
+ }
+
+ const effectOverrides =
+ isExpanded && nodePath !== null
+ ? track.sequence.effects.map((_, effectIndex) =>
+ getDragOverrideSnapshot(
+ getEffectDragOverrides(nodePath, effectIndex),
+ ),
+ )
+ : [];
+ const old = previous?.entries[index];
+ if (
+ old?.track === track &&
+ old.expanded === isExpanded &&
+ (!isExpanded ||
+ (!invalidateExpanded &&
+ old.runtimeValues === runtimeValues &&
+ old.dragOverride === dragOverride &&
+ old.effectOverrides.length === effectOverrides.length &&
+ old.effectOverrides.every(
+ (value, effectIndex) => value === effectOverrides[effectIndex],
+ )))
+ ) {
+ return old;
+ }
+
const layerHeight =
getTimelineLayerHeight(track.sequence.type) +
TIMELINE_ITEM_BORDER_BOTTOM;
@@ -88,11 +181,7 @@ export const useTimelineTrackHeights = ({
propStatuses,
includeTextContent: false,
includeSourceControls: false,
- runtimeValues: track.sequence.controls
- ? (runtimeValuesByStore.get(
- track.sequence.controls.runtimeValues,
- ) ?? null)
- : null,
+ runtimeValues,
});
const filteredTree = filterTimelineExpandedTree({
nodes: tree,
@@ -125,8 +214,34 @@ export const useTimelineTrackHeights = ({
const separators = Math.max(0, flat.length - 1);
return totalRowsHeight + separators + TIMELINE_ITEM_BORDER_BOTTOM;
})();
- return layerHeight + expandedHeight;
+ return {
+ track,
+ expanded: isExpanded,
+ runtimeValues,
+ dragOverride,
+ effectOverrides,
+ height: layerHeight + expandedHeight,
+ };
});
+ const expandedEntries = entries.filter((entry) => entry.expanded);
+ const heights = entries.map((entry) => entry.height);
+ const stableHeights =
+ previous !== null &&
+ previous.heights.length === heights.length &&
+ heights.every((height, index) => previous.heights[index] === height)
+ ? previous.heights
+ : heights;
+ return {
+ timeline,
+ entries,
+ expandedEntries,
+ heights: stableHeights,
+ propStatuses,
+ selectedRowKeys,
+ getIsExpanded,
+ previewServerConnected,
+ runtimeValuesByStore,
+ };
}, [
timeline,
previewServerConnected,
@@ -137,13 +252,9 @@ export const useTimelineTrackHeights = ({
selectedRowKeys,
runtimeValuesByStore,
]);
- const stableHeights = useRef(heights);
- if (
- stableHeights.current.length !== heights.length ||
- heights.some((height, index) => stableHeights.current[index] !== height)
- ) {
- stableHeights.current = heights;
- }
+ useLayoutEffect(() => {
+ previousHeightsRef.current = result;
+ }, [result]);
- return stableHeights.current;
+ return result.heights;
};
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index e5a89e4ebb..b1b12ee998 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -198,7 +198,7 @@ const WebMcpSelectionSync: FC<{
readonly selectedSequenceRef: MutableRefObject<WebMcpSequence | null>;
}> = ({currentSelectionRef, selectedSequenceRef}) => {
const {selectedItems} = useTimelineSelection();
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);
@@ -294,7 +294,7 @@ export const WebMcp: FC = () => {
const selectComposition = useSelectComposition();
const {editorShowGuides, guidesList, setEditorShowGuides, setGuidesList} =
useContext(EditorShowGuidesContext);
- const {sequences} = useContext(Internals.SequenceManager);
+ const sequences = Internals.useSequenceManagerSequences();
const {overrideIdToNodePathMappings} = useContext(
Internals.OverrideIdsToNodePathsGettersContext,
);