Skip to content

🎥 Make videos programmatically with React

Defer keyframe trim analysis until interaction

JonnyBurger3dbf039022db
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index da71eff188..0c85e3d6cf 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -23,6 +23,7 @@ import {
} from './internals';
import {computeSequencePropsSubscriptionFromContent} from './sequence-props';
import {computeEffectPropsStatusesFromContent} from './sequence-props/can-update-effect-props';
+import {getDurationDependentKeyframesFromContent} from './sequence-props/duration-dependent-keyframes';
import {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
import {getKeyframeInterpolationFunctionForCallee} from './sequence-props/keyframe-interpolation-function';
@@ -172,6 +173,7 @@ export type {
export const CodemodsInternals = {
computeEffectPropsStatusesFromContent,
+ getDurationDependentKeyframesFromContent,
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
basicCaptionsElementSource,
diff --git a/packages/codemods/src/sequence-props.ts b/packages/codemods/src/sequence-props.ts
index 04e9c2d07d..5612de029c 100644
--- a/packages/codemods/src/sequence-props.ts
+++ b/packages/codemods/src/sequence-props.ts
@@ -31,7 +31,6 @@ import {NoReactInternals} from 'remotion/no-react';
import {getReadOnlySourceSnapshot} from './sequence-props-snapshot';
import {computeEffectPropStatus} from './sequence-props/can-update-effect-props';
import {getCssShorthandForLonghand} from './sequence-props/css-shorthand-properties';
-import {getDurationDependentKeyframes} from './sequence-props/duration-dependent-keyframes';
import {getAstNodePath} from './sequence-props/get-ast-node-path';
import {toImportAgnosticNodePath} from './sequence-props/import-agnostic-node-path';
import {
@@ -2325,11 +2324,6 @@ const computeSequencePropsStatusFromAstAndIdentifiers = ({
ast,
videoConfigValues: videoConfigIdentifierValues,
});
- const durationDependentKeyframes = getDurationDependentKeyframes({
- ast,
- jsxPath,
- videoConfigIdentifierValues,
- });
const addDefaultKeyframeDisplayOffsetAdjustment = (
status: CanUpdateSequencePropSource,
): CanUpdateSequencePropSource => {
@@ -2367,7 +2361,7 @@ const computeSequencePropsStatusFromAstAndIdentifiers = ({
return {
canUpdate: true as const,
- durationDependentKeyframes,
+ durationDependentKeyframes: null,
props: Object.fromEntries(
Object.entries(filteredProps).map(([key, status]) => [
key,
diff --git a/packages/codemods/src/sequence-props/duration-dependent-keyframes.ts b/packages/codemods/src/sequence-props/duration-dependent-keyframes.ts
index ca1781dccd..8509b2f80b 100644
--- a/packages/codemods/src/sequence-props/duration-dependent-keyframes.ts
+++ b/packages/codemods/src/sequence-props/duration-dependent-keyframes.ts
@@ -3,10 +3,16 @@ import * as recast from 'recast';
import type {
CanUpdateSequencePropsResponseTrue,
SourceNumericValue,
+ SequenceNodePath,
} from 'remotion';
-import {getNodePathForRecastPath} from '../sequence-props';
+import {
+ findJsxElementPathAtNodePath,
+ getNodePathForRecastPath,
+} from '../sequence-props';
+import {getReadOnlySourceSnapshot} from '../sequence-props-snapshot';
import {getKeyframeInterpolationFunctionForCallee} from './keyframe-interpolation-function';
import {parseVideoConfigNumericExpression} from './video-config-numeric-expression';
+import {getVideoConfigIdentifiers} from './video-config-values';
import type {VideoConfigIdentifierValues} from './video-config-values';
type DurationDependentKeyframes = NonNullable<
@@ -186,3 +192,27 @@ export const getDurationDependentKeyframes = ({
cache.set(scopeNode, result);
return result;
};
+
+// Kept separate from prop subscriptions: scanning the render scope is only
+// needed when a timing edit begins.
+export const getDurationDependentKeyframesFromContent = ({
+ fileContents,
+ nodePath,
+}: {
+ fileContents: string;
+ nodePath: SequenceNodePath;
+}): DurationDependentKeyframes | null => {
+ const snapshot = getReadOnlySourceSnapshot(fileContents);
+ const jsxPath = findJsxElementPathAtNodePath(snapshot.ast, nodePath);
+ if (!jsxPath)
+ throw new Error('Could not find the sequence to check keyframes');
+ const videoConfigIdentifierValues =
+ snapshot.videoConfigIdentifierValues ??
+ getVideoConfigIdentifiers({ast: snapshot.ast});
+ snapshot.videoConfigIdentifierValues = videoConfigIdentifierValues;
+ return getDurationDependentKeyframes({
+ ast: snapshot.ast,
+ jsxPath,
+ videoConfigIdentifierValues,
+ });
+};
diff --git a/packages/studio/src/components/InspectorPanel/MultiSequenceField.tsx b/packages/studio/src/components/InspectorPanel/MultiSequenceField.tsx
index 62f1e733ec..f7df49b9ac 100644
--- a/packages/studio/src/components/InspectorPanel/MultiSequenceField.tsx
+++ b/packages/studio/src/components/InspectorPanel/MultiSequenceField.tsx
@@ -68,7 +68,9 @@ export const MultiSequenceField: React.FC<{
isStudioInteractivityEnabled() &&
previewServerState.type === 'connected' &&
staticValues;
+ const previewGeneration = useRef(0);
const clear = useCallback(() => {
+ previewGeneration.current++;
clearTimingLimits();
for (const target of targets) {
clearDragOverrides(target.nodePath);
@@ -77,25 +79,43 @@ export const MultiSequenceField: React.FC<{
const targetsRef = useRef(targets);
targetsRef.current = targets;
useEffect(() => {
+ const generation = previewGeneration;
return () => {
+ generation.current++;
for (const target of targetsRef.current) {
clearDragOverrides(target.nodePath);
}
};
}, [clearDragOverrides]);
const preview = useCallback(
- (nextValues: unknown[]) => {
+ async (nextValues: unknown[]) => {
if (!editable) {
return;
}
+ const generation = ++previewGeneration.current;
+ let clamped: unknown[];
+ try {
+ clamped = await Promise.all(
+ targets.map((target, index) =>
+ clampTimingValue(target.nodePath, field.key, nextValues[index]),
+ ),
+ );
+ } catch (error) {
+ if (generation === previewGeneration.current)
+ showNotification(
+ `Could not check timing constraints: ${(error as Error).message}`,
+ 3000,
+ );
+ return;
+ }
+
+ if (generation !== previewGeneration.current) return;
for (const [index, target] of targets.entries()) {
setDragOverrides(
target.nodePath,
field.key,
- Internals.makeStaticDragOverride(
- clampTimingValue(target.nodePath, field.key, nextValues[index]),
- ),
+ Internals.makeStaticDragOverride(clamped[index]),
);
}
},
@@ -111,16 +131,17 @@ export const MultiSequenceField: React.FC<{
}
try {
+ const clamped = await Promise.all(
+ targets.map((target, index) =>
+ clampTimingValue(target.nodePath, field.key, nextValues[index]),
+ ),
+ );
await saveSequenceProps({
changes: targets.map((target, index) => ({
fileName: target.nodePath.absolutePath,
nodePath: target.nodePath,
fieldKey: field.key,
- value: clampTimingValue(
- target.nodePath,
- field.key,
- nextValues[index],
- ),
+ value: clamped[index],
defaultValue:
field.typeName === 'string' ||
field.typeName === 'text-content' ||
diff --git a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
index 1768384d66..09f9d5869b 100644
--- a/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequencePropItem.tsx
@@ -3,7 +3,13 @@ import {
isSchemaFieldKeyframable,
stringifySequenceSubscriptionKey,
} from '@remotion/studio-shared';
-import React, {useCallback, useContext, useMemo, useRef} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+} from 'react';
import {unstable_batchedUpdates} from 'react-dom';
import type {
CanUpdateSequencePropStatus,
@@ -242,8 +248,8 @@ const Value: React.FC<{
: null;
const onSave = useCallback<TimelineFieldOnSave>(
- (value, options) => {
- value = clampTimingValue(nodePath, field.key, value);
+ async (value, options) => {
+ value = await clampTimingValue(nodePath, field.key, value);
if (!clientId) {
return Promise.reject(new Error('Not connected to studio server'));
}
@@ -324,13 +330,35 @@ const Value: React.FC<{
],
);
+ const previewGeneration = useRef(0);
+ useEffect(
+ () => () => {
+ previewGeneration.current++;
+ },
+ [],
+ );
const onDragValueChange = useCallback<TimelineFieldOnDragValueChange>(
- (value) => {
+ async (value) => {
if (nodePath === null) {
throw new Error('Cannot drag value');
}
- value = clampTimingValue(nodePath, field.key, value);
+ const generation = ++previewGeneration.current;
+ try {
+ value = await clampTimingValue(nodePath, field.key, value);
+ } catch (error) {
+ if (generation === previewGeneration.current) {
+ Internals.Log.error(
+ {logLevel: 'error', tag: null},
+ 'Could not check timing constraints',
+ error,
+ );
+ }
+
+ return;
+ }
+
+ if (generation !== previewGeneration.current) return;
const keyframeChanges = getPlaybackRateChanges(value);
unstable_batchedUpdates(() => {
for (const preview of previewedKeyframes.current) {
@@ -377,6 +405,7 @@ const Value: React.FC<{
);
const onDragEnd = useCallback(() => {
+ previewGeneration.current++;
clearTimingLimits();
if (nodePath === null) {
throw new Error('Cannot clear drag value');
diff --git a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
index 83180d4780..126ad86e1f 100644
--- a/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSequenceRightEdgeDragHandle.tsx
@@ -28,15 +28,16 @@ import {TRANSPARENT} from '../../helpers/colors';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
import {
isPointerSessionRelease,
- startCapturedPointerSession,
startDeferredCapturedPointerSession,
} from '../../helpers/pointer-session';
+import {startPreparedPointerSession} from '../../helpers/start-prepared-pointer-session';
import {TIMELINE_PADDING} from '../../helpers/timeline-layout';
import {EditorSnappingContext} from '../../state/editor-snapping';
import {
forceSpecificCursor,
stopForcingSpecificCursor,
} from '../ForceSpecificCursor';
+import {showNotification} from '../Notifications/NotificationCenter';
import {OverrideIdToNodePathMappingsRefContext} from '../SequencePropsSubscriptionProvider';
import type {
MoveEffectKeyframeChange,
@@ -54,6 +55,7 @@ import {
getEffectiveSequenceTimingValues,
getTimelineSequenceTimingLimits,
} from './get-timeline-sequence-timing-limits';
+import {loadKeyframeTrimConstraints} from './load-keyframe-trim-constraints';
import {
saveSequenceProps,
type SaveSequencePropChange,
@@ -1816,307 +1818,333 @@ const TimelineSequenceLeftEdgeDragHandleInner: React.FC<{
const {nodePathInfo: latestNodePathInfo} = latestRef.current;
const {selectedItems: latestSelectedItems} = currentSelection.current;
- const targets = canCalculateDelta
- ? (getTimelineSequenceLeftEdgeDragTargets({
- draggedNodePathInfo: latestNodePathInfo,
- selectedItems: latestSelectedItems,
- sequences: sequencesRef.current,
- overrideIdsToNodePaths: overrideIdToNodePathMappingsRef.current,
- propStatuses: propStatusesRef.current,
- timelineDurationInFrames,
- trimBeforeOnly,
- rippleEdit: mode === 'ripple',
- }) ?? [])
- : [];
- const draggedKey = stringifySequenceSubscriptionKey(
- latestNodePathInfo.sequenceSubscriptionKey,
- );
- const draggedTarget = targets.find(
- (target) =>
- stringifySequenceSubscriptionKey(target.nodePath) === draggedKey,
- );
- const handleRect = e.currentTarget.getBoundingClientRect();
+ const captureTarget = e.currentTarget;
+ const downEvent = e.nativeEvent;
+ const sequences = sequencesRef.current;
+ const overrideIdsToNodePaths = overrideIdToNodePathMappingsRef.current;
+ const propStatuses = propStatusesRef.current;
+ const handleRect = captureTarget.getBoundingClientRect();
const initialEdgeClientX = handleRect.left + HANDLE_OUTSET;
const initialEdgeClientY = handleRect.top;
const initialTimelineEdge = latestRef.current.initialEdgeFrame;
stopPointerSessionRef.current?.();
- onDragStart(
- mode,
- targets.map((target) => target.nodePath),
- );
- dragStateRef.current = {
- initialClientX: e.clientX,
- latestDeltaFrames: 0,
- lastPreviewDeltaFrames: 0,
- previousPreviewValues: new Map(),
- lastTooltipDelta: null,
- lastTooltipReason: null,
- didMove: false,
- pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
- pointerId: e.pointerId,
- selectionInteraction,
- targets,
- mode,
- };
- document.body.style.userSelect = 'none';
- document.body.style.webkitUserSelect = 'none';
- forceSpecificCursor(activeCursor);
+ stopPointerSessionRef.current = startPreparedPointerSession({
+ event: downEvent,
+ captureTarget,
+ prepare: () =>
+ loadKeyframeTrimConstraints({propStatuses, overrideIdsToNodePaths}),
+ onCancel: () => {
+ stopPointerSessionRef.current = null;
+ finishDrag(false);
+ },
+ onError: (error) =>
+ showNotification(
+ `Could not check trim constraints: ${(error as Error).message}`,
+ 3000,
+ ),
+ onReady: (preparedPropStatuses) => {
+ const targets = canCalculateDelta
+ ? (getTimelineSequenceLeftEdgeDragTargets({
+ draggedNodePathInfo: latestNodePathInfo,
+ selectedItems: latestSelectedItems,
+ sequences,
+ overrideIdsToNodePaths,
+ propStatuses: preparedPropStatuses,
+ timelineDurationInFrames,
+ trimBeforeOnly,
+ rippleEdit: mode === 'ripple',
+ }) ?? [])
+ : [];
+ const draggedKey = stringifySequenceSubscriptionKey(
+ latestNodePathInfo.sequenceSubscriptionKey,
+ );
+ const draggedTarget = targets.find(
+ (target) =>
+ stringifySequenceSubscriptionKey(target.nodePath) === draggedKey,
+ );
+ onDragStart(
+ mode,
+ targets.map((target) => target.nodePath),
+ );
+ dragStateRef.current = {
+ initialClientX: downEvent.clientX,
+ latestDeltaFrames: 0,
+ lastPreviewDeltaFrames: 0,
+ previousPreviewValues: new Map(),
+ lastTooltipDelta: null,
+ lastTooltipReason: null,
+ didMove: false,
+ pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
+ pointerId: downEvent.pointerId,
+ selectionInteraction,
+ targets,
+ mode,
+ };
+ document.body.style.userSelect = 'none';
+ document.body.style.webkitUserSelect = 'none';
+ forceSpecificCursor(activeCursor);
+
+ const onMove = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- const onMove = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
+ const dx = pointerEvent.clientX - dragState.initialClientX;
+ const pointerDeltaFrames = Math.round(dx / dragState.pxPerFrame);
+ const deltaFrames =
+ dragState.mode === 'self-trim'
+ ? -pointerDeltaFrames
+ : pointerDeltaFrames;
+ dragState.latestDeltaFrames = deltaFrames;
+ if (
+ Math.abs(dx) >= timelineSequenceEdgeDragThresholdPx ||
+ getTimelineSequenceLeftEdgeDragChanges({
+ targets: dragState.targets,
+ deltaFrames,
+ trimBeforeOnly: dragState.mode === 'source-only',
+ }).length > 0
+ ) {
+ dragState.didMove = true;
+ }
- const dx = pointerEvent.clientX - dragState.initialClientX;
- const pointerDeltaFrames = Math.round(dx / dragState.pxPerFrame);
- const deltaFrames =
- dragState.mode === 'self-trim'
- ? -pointerDeltaFrames
- : pointerDeltaFrames;
- dragState.latestDeltaFrames = deltaFrames;
- if (
- Math.abs(dx) >= timelineSequenceEdgeDragThresholdPx ||
- getTimelineSequenceLeftEdgeDragChanges({
- targets: dragState.targets,
- deltaFrames,
- trimBeforeOnly: dragState.mode === 'source-only',
- }).length > 0
- ) {
- dragState.didMove = true;
- }
+ if (
+ deltaFrames === dragState.lastPreviewDeltaFrames &&
+ (!dragState.didMove ||
+ draggedTarget === undefined ||
+ dragState.lastTooltipDelta !== null)
+ ) {
+ return;
+ }
- if (
- deltaFrames === dragState.lastPreviewDeltaFrames &&
- (!dragState.didMove ||
- draggedTarget === undefined ||
- dragState.lastTooltipDelta !== null)
- ) {
- return;
- }
+ dragState.lastPreviewDeltaFrames = deltaFrames;
+
+ const updates: DragOverrideUpdate[] = [];
+ let limitReason: TimelineTrimLimitReason | null = null;
+ for (const target of dragState.targets) {
+ if (target.ripplePrevious) {
+ const previous = target.ripplePrevious;
+ const nextDuration = getTimelineSequenceDurationDragValue({
+ initialDuration: previous.initialDuration,
+ deltaFrames: deltaFrames * previous.parentPlaybackRate,
+ maximumDuration: previous.maximumDuration,
+ minimumDuration: previous.minimumDuration,
+ });
+ if (nextDuration === previous.minimumDuration)
+ limitReason ??= getVisibleTimelineTrimLimitReason(
+ previous.minimumDurationReason,
+ );
+ if (nextDuration === previous.maximumDuration)
+ limitReason ??= getVisibleTimelineTrimLimitReason(
+ previous.maximumDurationReason,
+ );
+ 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;
+ }
- dragState.lastPreviewDeltaFrames = deltaFrames;
-
- const updates: DragOverrideUpdate[] = [];
- let limitReason: TimelineTrimLimitReason | null = null;
- for (const target of dragState.targets) {
- if (target.ripplePrevious) {
- const previous = target.ripplePrevious;
- const nextDuration = getTimelineSequenceDurationDragValue({
- initialDuration: previous.initialDuration,
- deltaFrames: deltaFrames * previous.parentPlaybackRate,
- maximumDuration: previous.maximumDuration,
- minimumDuration: previous.minimumDuration,
- });
- if (nextDuration === previous.minimumDuration)
- limitReason ??= getVisibleTimelineTrimLimitReason(
- previous.minimumDurationReason,
- );
- if (nextDuration === previous.maximumDuration)
- limitReason ??= getVisibleTimelineTrimLimitReason(
- previous.maximumDurationReason,
+ const nextValues = getTimelineSequenceLeftEdgeDragValuesForTarget(
+ {
+ target,
+ deltaFrames,
+ trimBeforeOnly: dragState.mode === 'source-only',
+ },
);
- 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;
- }
-
- const nextValues = getTimelineSequenceLeftEdgeDragValuesForTarget({
- target,
- deltaFrames,
- trimBeforeOnly: dragState.mode === 'source-only',
- });
- // Probe both directions through the same clamp, including source-only
- // trims and parent/neighbor bounds. No separate limit math to drift.
- const targetIsAtLimit = [-1, 1].some((direction) => {
- const adjacent = getTimelineSequenceLeftEdgeDragValuesForTarget({
- target,
- deltaFrames: deltaFrames + direction / target.parentPlaybackRate,
- trimBeforeOnly: dragState.mode === 'source-only',
- });
- return (
- adjacent.durationInFrames === nextValues.durationInFrames &&
- adjacent.from === nextValues.from &&
- adjacent.trimBefore === nextValues.trimBefore
- );
- });
- if (targetIsAtLimit) {
- const limits = target.timingLimits;
- const targetLimitReason =
- dragState.mode === 'source-only'
- ? getTimelineTrimLimitReason(nextValues.trimBefore, [
- [
- limits?.minimumTrimBefore ?? NaN,
- limits?.limitReasons.minimumTrimBefore ?? null,
- ],
- [
- limits?.maximumTrimBefore ?? NaN,
- limits?.limitReasons.maximumTrimBefore ?? null,
- ],
- ])
- : nextValues.durationInFrames === target.minimumDuration
- ? target.minimumDuration > 1
- ? 'Transition limit'
- : 'Minimum duration'
- : nextValues.trimBefore === 0
- ? 'Source start'
- : getTimelineTrimLimitReason(nextValues.from, [
+ // Probe both directions through the same clamp, including source-only
+ // trims and parent/neighbor bounds. No separate limit math to drift.
+ const targetIsAtLimit = [-1, 1].some((direction) => {
+ const adjacent = getTimelineSequenceLeftEdgeDragValuesForTarget(
+ {
+ target,
+ deltaFrames:
+ deltaFrames + direction / target.parentPlaybackRate,
+ trimBeforeOnly: dragState.mode === 'source-only',
+ },
+ );
+ return (
+ adjacent.durationInFrames === nextValues.durationInFrames &&
+ adjacent.from === nextValues.from &&
+ adjacent.trimBefore === nextValues.trimBefore
+ );
+ });
+ if (targetIsAtLimit) {
+ const limits = target.timingLimits;
+ const targetLimitReason =
+ dragState.mode === 'source-only'
+ ? getTimelineTrimLimitReason(nextValues.trimBefore, [
[
- limits?.minimumFrom ?? NaN,
- limits?.limitReasons.minimumFrom ?? null,
+ limits?.minimumTrimBefore ?? NaN,
+ limits?.limitReasons.minimumTrimBefore ?? null,
],
- ]);
- limitReason ??=
- getVisibleTimelineTrimLimitReason(targetLimitReason);
- }
-
- if (
- dragState.mode !== 'source-only' &&
- target.positionField !== null
- ) {
- queueStaticDragOverrideIfChanged({
- updates,
- previousValues: dragState.previousPreviewValues,
- nodePath: target.nodePath,
- key: target.positionField,
- value: nextValues.from,
- initialValue: target.initialFrom,
- });
- }
+ [
+ limits?.maximumTrimBefore ?? NaN,
+ limits?.limitReasons.maximumTrimBefore ?? null,
+ ],
+ ])
+ : nextValues.durationInFrames === target.minimumDuration
+ ? target.minimumDuration > 1
+ ? 'Transition limit'
+ : 'Minimum duration'
+ : nextValues.trimBefore === 0
+ ? 'Source start'
+ : getTimelineTrimLimitReason(nextValues.from, [
+ [
+ limits?.minimumFrom ?? NaN,
+ limits?.limitReasons.minimumFrom ?? null,
+ ],
+ ]);
+ limitReason ??=
+ getVisibleTimelineTrimLimitReason(targetLimitReason);
+ }
- if (dragState.mode !== 'source-only') {
- queueStaticDragOverrideIfChanged({
- updates,
- previousValues: dragState.previousPreviewValues,
- nodePath: target.nodePath,
- key: 'durationInFrames',
- value: nextValues.durationInFrames * target.playbackRate,
- initialValue: target.initialDuration * target.playbackRate,
- });
- }
+ if (
+ dragState.mode !== 'source-only' &&
+ target.positionField !== null
+ ) {
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: target.positionField,
+ value: nextValues.from,
+ initialValue: target.initialFrom,
+ });
+ }
- queueStaticDragOverrideIfChanged({
- updates,
- previousValues: dragState.previousPreviewValues,
- nodePath: target.nodePath,
- key: 'trimBefore',
- value: nextValues.trimBefore,
- initialValue: target.initialTrimBefore,
- });
- }
+ if (dragState.mode !== 'source-only') {
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: 'durationInFrames',
+ value: nextValues.durationInFrames * target.playbackRate,
+ initialValue: target.initialDuration * target.playbackRate,
+ });
+ }
- latestRef.current.onLimitChange(limitReason !== null);
- 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,
- );
+ queueStaticDragOverrideIfChanged({
+ updates,
+ previousValues: dragState.previousPreviewValues,
+ nodePath: target.nodePath,
+ key: 'trimBefore',
+ value: nextValues.trimBefore,
+ initialValue: target.initialTrimBefore,
+ });
}
- }
- }
- if (dragState.didMove && draggedTarget) {
- const {ripplePrevious} = draggedTarget;
- let appliedDelta: number;
- if (ripplePrevious) {
- const nextDuration = getTimelineSequenceDurationDragValue({
- initialDuration: ripplePrevious.initialDuration,
- deltaFrames: deltaFrames * ripplePrevious.parentPlaybackRate,
- maximumDuration: ripplePrevious.maximumDuration,
- minimumDuration: ripplePrevious.minimumDuration,
- });
- appliedDelta =
- (nextDuration - ripplePrevious.initialDuration) /
- ripplePrevious.parentPlaybackRate;
- } else {
- const values = getTimelineSequenceLeftEdgeDragValuesForTarget({
- target: draggedTarget,
- deltaFrames,
- trimBeforeOnly: dragState.mode === 'source-only',
- });
- appliedDelta =
- dragState.mode === 'source-only'
- ? (values.trimBefore - draggedTarget.initialTrimBefore) /
- draggedTarget.playbackRate
- : values.from - draggedTarget.initialFrom;
- }
+ latestRef.current.onLimitChange(limitReason !== null);
+ 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,
+ );
+ }
+ }
+ }
- const edgeDelta =
- dragState.mode === 'source-only' ||
- (draggedTarget.positionField === null && ripplePrevious === null)
- ? 0
- : appliedDelta;
- if (
- dragState.lastTooltipDelta !== appliedDelta ||
- dragState.lastTooltipReason !== limitReason
- ) {
- dragState.lastTooltipDelta = appliedDelta;
- dragState.lastTooltipReason = limitReason;
- setTrimTooltip({
- limitReason,
- deltaFrames: appliedDelta,
- edgeFrame: initialTimelineEdge + edgeDelta,
- x:
- initialEdgeClientX +
- (edgeDelta / draggedTarget.parentPlaybackRate) *
- dragState.pxPerFrame,
- y: initialEdgeClientY,
- });
- }
- }
- };
+ if (dragState.didMove && draggedTarget) {
+ const {ripplePrevious} = draggedTarget;
+ let appliedDelta: number;
+ if (ripplePrevious) {
+ const nextDuration = getTimelineSequenceDurationDragValue({
+ initialDuration: ripplePrevious.initialDuration,
+ deltaFrames: deltaFrames * ripplePrevious.parentPlaybackRate,
+ maximumDuration: ripplePrevious.maximumDuration,
+ minimumDuration: ripplePrevious.minimumDuration,
+ });
+ appliedDelta =
+ (nextDuration - ripplePrevious.initialDuration) /
+ ripplePrevious.parentPlaybackRate;
+ } else {
+ const values = getTimelineSequenceLeftEdgeDragValuesForTarget({
+ target: draggedTarget,
+ deltaFrames,
+ trimBeforeOnly: dragState.mode === 'source-only',
+ });
+ appliedDelta =
+ dragState.mode === 'source-only'
+ ? (values.trimBefore - draggedTarget.initialTrimBefore) /
+ draggedTarget.playbackRate
+ : values.from - draggedTarget.initialFrom;
+ }
- const onUp = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
+ const edgeDelta =
+ dragState.mode === 'source-only' ||
+ (draggedTarget.positionField === null &&
+ ripplePrevious === null)
+ ? 0
+ : appliedDelta;
+ if (
+ dragState.lastTooltipDelta !== appliedDelta ||
+ dragState.lastTooltipReason !== limitReason
+ ) {
+ dragState.lastTooltipDelta = appliedDelta;
+ dragState.lastTooltipReason = limitReason;
+ setTrimTooltip({
+ limitReason,
+ deltaFrames: appliedDelta,
+ edgeFrame: initialTimelineEdge + edgeDelta,
+ x:
+ initialEdgeClientX +
+ (edgeDelta / draggedTarget.parentPlaybackRate) *
+ dragState.pxPerFrame,
+ y: initialEdgeClientY,
+ });
+ }
+ }
+ };
- // Include the release position even if the final pointermove was skipped.
- onMove(pointerEvent);
- finishDrag(true);
- };
+ const onUp = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- const onCancel = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
+ // Include the release position even if the final pointermove was skipped.
+ onMove(pointerEvent);
+ finishDrag(true);
+ };
- finishDrag(false);
- };
+ const onCancel = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- stopPointerSessionRef.current = startCapturedPointerSession({
- event: e.nativeEvent,
- captureTarget: e.currentTarget,
- onMove,
- onEnd: (reason, endEvent) => {
- stopPointerSessionRef.current = null;
- if (isPointerSessionRelease(reason, endEvent)) {
- onUp(endEvent);
- } else if (endEvent) {
- onCancel(endEvent);
- } else {
finishDrag(false);
- }
+ };
+
+ return {
+ onMove,
+ onEnd: (reason, endEvent) => {
+ stopPointerSessionRef.current = null;
+ if (isPointerSessionRelease(reason, endEvent)) {
+ onUp(endEvent);
+ } else if (endEvent) {
+ onCancel(endEvent);
+ } else {
+ finishDrag(false);
+ }
+ },
+ };
},
});
},
@@ -2733,199 +2761,219 @@ const TimelineSequenceRightEdgeDragHandleInner: React.FC<{
mediaDurationDragLimits: latestMediaDurationDragLimits,
} = latestRef.current;
const {selectedItems: latestSelectedItems} = currentSelection.current;
- const targets = canCalculateDelta
- ? (getTimelineSequenceDurationDragTargets({
- draggedNodePathInfo: latestNodePathInfo,
- draggedSequenceMediaDurationDragLimits:
- latestMediaDurationDragLimits,
- selectedSequenceMediaDurationDragLimits:
- mediaDurationDragLimitsRegistry?.current ?? null,
- selectedItems: latestSelectedItems,
- sequences: sequencesRef.current,
- overrideIdsToNodePaths: overrideIdToNodePathMappingsRef.current,
- propStatuses: propStatusesRef.current,
- timelineDurationInFrames,
- }) ?? [])
- : [];
- const draggedKey = stringifySequenceSubscriptionKey(
- latestNodePathInfo.sequenceSubscriptionKey,
- );
- const draggedTarget = targets.find(
- (target) =>
- stringifySequenceSubscriptionKey(target.nodePath) === draggedKey,
- );
- const handleRect = e.currentTarget.getBoundingClientRect();
+ const captureTarget = e.currentTarget;
+ const downEvent = e.nativeEvent;
+ const sequences = sequencesRef.current;
+ const overrideIdsToNodePaths = overrideIdToNodePathMappingsRef.current;
+ const propStatuses = propStatusesRef.current;
+ const handleRect = captureTarget.getBoundingClientRect();
const initialEdgeClientX = handleRect.right - HANDLE_OUTSET;
const initialEdgeClientY = handleRect.top;
const initialTimelineEdge = latestRef.current.initialEdgeFrame;
stopPointerSessionRef.current?.();
- onDragStart(targets.map((target) => target.nodePath));
- dragStateRef.current = {
- initialClientX: e.clientX,
- latestDeltaFrames: 0,
- lastPreviewDeltaFrames: 0,
- previousPreviewValues: new Map(),
- lastTooltipDelta: null,
- lastTooltipReason: null,
- didMove: false,
- pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
- pointerId: e.pointerId,
- selectionInteraction,
- targets,
- };
- document.body.style.userSelect = 'none';
- document.body.style.webkitUserSelect = 'none';
- forceSpecificCursor(cursor);
+ stopPointerSessionRef.current = startPreparedPointerSession({
+ event: downEvent,
+ captureTarget,
+ prepare: () =>
+ loadKeyframeTrimConstraints({propStatuses, overrideIdsToNodePaths}),
+ onCancel: () => {
+ stopPointerSessionRef.current = null;
+ finishDrag(false);
+ },
+ onError: (error) =>
+ showNotification(
+ `Could not check trim constraints: ${(error as Error).message}`,
+ 3000,
+ ),
+ onReady: (preparedPropStatuses) => {
+ const targets = canCalculateDelta
+ ? (getTimelineSequenceDurationDragTargets({
+ draggedNodePathInfo: latestNodePathInfo,
+ draggedSequenceMediaDurationDragLimits:
+ latestMediaDurationDragLimits,
+ selectedSequenceMediaDurationDragLimits:
+ mediaDurationDragLimitsRegistry?.current ?? null,
+ selectedItems: latestSelectedItems,
+ sequences,
+ overrideIdsToNodePaths,
+ propStatuses: preparedPropStatuses,
+ timelineDurationInFrames,
+ }) ?? [])
+ : [];
+ const draggedKey = stringifySequenceSubscriptionKey(
+ latestNodePathInfo.sequenceSubscriptionKey,
+ );
+ const draggedTarget = targets.find(
+ (target) =>
+ stringifySequenceSubscriptionKey(target.nodePath) === draggedKey,
+ );
+ onDragStart(targets.map((target) => target.nodePath));
+ dragStateRef.current = {
+ initialClientX: downEvent.clientX,
+ latestDeltaFrames: 0,
+ lastPreviewDeltaFrames: 0,
+ previousPreviewValues: new Map(),
+ lastTooltipDelta: null,
+ lastTooltipReason: null,
+ didMove: false,
+ pxPerFrame: canCalculateDelta ? pxPerFrame : 1,
+ pointerId: downEvent.pointerId,
+ selectionInteraction,
+ targets,
+ };
+ document.body.style.userSelect = 'none';
+ document.body.style.webkitUserSelect = 'none';
+ forceSpecificCursor(cursor);
+
+ const onMove = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- const onMove = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
+ const dx = pointerEvent.clientX - dragState.initialClientX;
+ const deltaFrames = Math.round(dx / dragState.pxPerFrame);
+ dragState.latestDeltaFrames = deltaFrames;
+ if (
+ Math.abs(dx) >= timelineSequenceEdgeDragThresholdPx ||
+ getTimelineSequenceDurationDragChanges({
+ targets: dragState.targets,
+ deltaFrames,
+ }).length > 0
+ ) {
+ dragState.didMove = true;
+ }
- const dx = pointerEvent.clientX - dragState.initialClientX;
- const deltaFrames = Math.round(dx / dragState.pxPerFrame);
- dragState.latestDeltaFrames = deltaFrames;
- if (
- Math.abs(dx) >= timelineSequenceEdgeDragThresholdPx ||
- getTimelineSequenceDurationDragChanges({
- targets: dragState.targets,
- deltaFrames,
- }).length > 0
- ) {
- dragState.didMove = true;
- }
+ if (
+ deltaFrames === dragState.lastPreviewDeltaFrames &&
+ (!dragState.didMove ||
+ draggedTarget === undefined ||
+ dragState.lastTooltipDelta !== null)
+ ) {
+ return;
+ }
- if (
- deltaFrames === dragState.lastPreviewDeltaFrames &&
- (!dragState.didMove ||
- draggedTarget === undefined ||
- dragState.lastTooltipDelta !== null)
- ) {
- return;
- }
+ dragState.lastPreviewDeltaFrames = deltaFrames;
- dragState.lastPreviewDeltaFrames = deltaFrames;
+ const updates: DragOverrideUpdate[] = [];
+ let limitReason: TimelineTrimLimitReason | null = null;
+ for (const target of dragState.targets) {
+ const previewValue = getTimelineSequenceDurationDragValue({
+ initialDuration: target.initialDuration,
+ deltaFrames: deltaFrames * target.parentPlaybackRate,
+ maximumDuration: target.maximumDuration,
+ minimumDuration: target.minimumDuration,
+ });
+ if (previewValue === target.minimumDuration)
+ limitReason ??= getVisibleTimelineTrimLimitReason(
+ target.minimumDurationReason,
+ );
+ if (previewValue === target.maximumDuration)
+ limitReason ??= getVisibleTimelineTrimLimitReason(
+ target.maximumDurationReason,
+ );
- const updates: DragOverrideUpdate[] = [];
- let limitReason: TimelineTrimLimitReason | null = null;
- for (const target of dragState.targets) {
- const previewValue = getTimelineSequenceDurationDragValue({
- initialDuration: target.initialDuration,
- deltaFrames: deltaFrames * target.parentPlaybackRate,
- maximumDuration: target.maximumDuration,
- minimumDuration: target.minimumDuration,
- });
- if (previewValue === target.minimumDuration)
- limitReason ??= getVisibleTimelineTrimLimitReason(
- target.minimumDurationReason,
- );
- if (previewValue === target.maximumDuration)
- limitReason ??= getVisibleTimelineTrimLimitReason(
- target.maximumDurationReason,
- );
+ 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,
+ }),
+ });
+ }
- 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,
- }),
- });
- }
+ latestRef.current.onLimitChange(limitReason !== null);
+ 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,
+ );
+ }
+ }
+ }
- latestRef.current.onLimitChange(limitReason !== null);
- 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) {
+ const previewValue = getTimelineSequenceDurationDragValue({
+ initialDuration: draggedTarget.initialDuration,
+ deltaFrames: deltaFrames * draggedTarget.parentPlaybackRate,
+ maximumDuration: draggedTarget.maximumDuration,
+ minimumDuration: draggedTarget.minimumDuration,
+ });
+ const appliedDelta =
+ (previewValue - draggedTarget.initialDuration) /
+ draggedTarget.parentPlaybackRate;
+ updateSnapFrameRef?.current(
+ 'naturalDuration' in draggedTarget &&
+ previewValue === draggedTarget.naturalDuration
+ ? initialTimelineEdge + appliedDelta
+ : null,
);
+ if (
+ dragState.lastTooltipDelta !== appliedDelta ||
+ dragState.lastTooltipReason !== limitReason
+ ) {
+ dragState.lastTooltipDelta = appliedDelta;
+ dragState.lastTooltipReason = limitReason;
+ setTrimTooltip({
+ limitReason,
+ deltaFrames: appliedDelta,
+ edgeFrame: initialTimelineEdge + appliedDelta,
+ x:
+ initialEdgeClientX +
+ (appliedDelta / draggedTarget.parentPlaybackRate) *
+ dragState.pxPerFrame,
+ y: initialEdgeClientY,
+ });
+ }
}
- }
- }
+ };
- if (dragState.didMove && draggedTarget) {
- const previewValue = getTimelineSequenceDurationDragValue({
- initialDuration: draggedTarget.initialDuration,
- deltaFrames: deltaFrames * draggedTarget.parentPlaybackRate,
- maximumDuration: draggedTarget.maximumDuration,
- minimumDuration: draggedTarget.minimumDuration,
- });
- const appliedDelta =
- (previewValue - draggedTarget.initialDuration) /
- draggedTarget.parentPlaybackRate;
- updateSnapFrameRef?.current(
- 'naturalDuration' in draggedTarget &&
- previewValue === draggedTarget.naturalDuration
- ? initialTimelineEdge + appliedDelta
- : null,
- );
- if (
- dragState.lastTooltipDelta !== appliedDelta ||
- dragState.lastTooltipReason !== limitReason
- ) {
- dragState.lastTooltipDelta = appliedDelta;
- dragState.lastTooltipReason = limitReason;
- setTrimTooltip({
- limitReason,
- deltaFrames: appliedDelta,
- edgeFrame: initialTimelineEdge + appliedDelta,
- x:
- initialEdgeClientX +
- (appliedDelta / draggedTarget.parentPlaybackRate) *
- dragState.pxPerFrame,
- y: initialEdgeClientY,
- });
- }
- }
- };
-
- const onUp = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
-
- // Include the release position even if the final pointermove was skipped.
- onMove(pointerEvent);
- finishDrag(true);
- };
+ const onUp = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- const onCancel = (pointerEvent: PointerEvent) => {
- const dragState = dragStateRef.current;
- if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
- return;
- }
+ // Include the release position even if the final pointermove was skipped.
+ onMove(pointerEvent);
+ finishDrag(true);
+ };
- finishDrag(false);
- };
+ const onCancel = (pointerEvent: PointerEvent) => {
+ const dragState = dragStateRef.current;
+ if (!dragState || pointerEvent.pointerId !== dragState.pointerId) {
+ return;
+ }
- stopPointerSessionRef.current = startCapturedPointerSession({
- event: e.nativeEvent,
- captureTarget: e.currentTarget,
- onMove,
- onEnd: (reason, endEvent) => {
- stopPointerSessionRef.current = null;
- if (isPointerSessionRelease(reason, endEvent)) {
- onUp(endEvent);
- } else if (endEvent) {
- onCancel(endEvent);
- } else {
finishDrag(false);
- }
+ };
+
+ return {
+ onMove,
+ onEnd: (reason, endEvent) => {
+ stopPointerSessionRef.current = null;
+ if (isPointerSessionRelease(reason, endEvent)) {
+ onUp(endEvent);
+ } else if (endEvent) {
+ onCancel(endEvent);
+ } else {
+ finishDrag(false);
+ }
+ },
+ };
},
});
},
diff --git a/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts b/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts
new file mode 100644
index 0000000000..2bd1106b0b
--- /dev/null
+++ b/packages/studio/src/components/Timeline/load-keyframe-trim-constraints.ts
@@ -0,0 +1,59 @@
+import type {OverrideIdToNodePaths, PropStatuses} from 'remotion';
+import {Internals} from 'remotion';
+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
+
+export const loadKeyframeTrimConstraints = async ({
+ propStatuses,
+ overrideIdsToNodePaths,
+}: {
+ propStatuses: PropStatuses;
+ overrideIdsToNodePaths: OverrideIdToNodePaths;
+}): Promise<PropStatuses> => {
+ const sources = new Map(
+ Object.values(overrideIdsToNodePaths).flatMap((nodePath) => {
+ const key = Internals.makeSequencePropsSubscriptionKey(nodePath);
+ return propStatuses[key]?.canUpdate ? [[key, nodePath] as const] : [];
+ }),
+ );
+ if (sources.size === 0) return propStatuses;
+
+ // Neither the parser nor source files are loaded during rendering or prop
+ // subscription updates. Keep this snapshot local to the editing gesture.
+ const browserOperations = getBrowserStudioOperations();
+ const [codemods, files] = await Promise.all([
+ import('@remotion/codemods'),
+ Promise.all(
+ [
+ ...new Set([...sources.values()].map((source) => source.absolutePath)),
+ ].map(async (fileName) => {
+ if (browserOperations) {
+ const contents = await browserOperations.getFileSource(fileName);
+ if (contents === null) throw new Error(`Could not load ${fileName}`);
+ return [fileName, contents] as const;
+ }
+
+ const response = await fetch(
+ `/api/file-source?f=${encodeURIComponent(fileName)}`,
+ );
+ if (!response.ok) throw new Error(`Could not load ${fileName}`);
+ return [fileName, await response.text()] as const;
+ }),
+ ),
+ ]);
+ const contentsByFile = new Map(files);
+ const result = {...propStatuses};
+ for (const [key, source] of sources) {
+ const status = propStatuses[key];
+ if (!status?.canUpdate) continue;
+ result[key] = {
+ ...status,
+ durationDependentKeyframes:
+ codemods.CodemodsInternals.getDurationDependentKeyframesFromContent({
+ fileContents: contentsByFile.get(source.absolutePath)!,
+ nodePath: source.nodePath,
+ }),
+ };
+ }
+
+ return result;
+};
diff --git a/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts b/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts
index f145e6cfee..185fb85aac 100644
--- a/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts
+++ b/packages/studio/src/components/Timeline/use-clamp-sequence-timing-value.ts
@@ -5,6 +5,7 @@ import {Internals} from 'remotion';
import {calculateTimeline} from '../../helpers/calculate-timeline';
import {OverrideIdToNodePathMappingsRefContext} from '../SequencePropsSubscriptionProvider';
import {getTimelineSequenceTimingLimits} from './get-timeline-sequence-timing-limits';
+import {loadKeyframeTrimConstraints} from './load-keyframe-trim-constraints';
export const useClampSequenceTimingValue = () => {
const propStatusesRef = useContext(
@@ -14,11 +15,20 @@ export const useClampSequenceTimingValue = () => {
const mappingsRef = useContext(OverrideIdToNodePathMappingsRefContext);
const video = Internals.useVideo();
const limitsRef = useRef(
- new Map<string, ReturnType<typeof getTimelineSequenceTimingLimits>>(),
+ new Map<
+ string,
+ Promise<ReturnType<typeof getTimelineSequenceTimingLimits> | null>
+ >(),
);
- const clearTimingLimits = useCallback(() => limitsRef.current.clear(), []);
+ const preparedPropsRef = useRef<ReturnType<
+ typeof loadKeyframeTrimConstraints
+ > | null>(null);
+ const clearTimingLimits = useCallback(() => {
+ limitsRef.current.clear();
+ preparedPropsRef.current = null;
+ }, []);
const clampTimingValue = useCallback(
- (
+ async (
nodePath: SequencePropsSubscriptionKey,
fieldKey: string,
value: unknown,
@@ -31,13 +41,20 @@ export const useClampSequenceTimingValue = () => {
)
return value;
const key = stringifySequenceSubscriptionKey(nodePath);
- let limits = limitsRef.current.get(key);
- if (!limits) {
+ let pendingLimits = limitsRef.current.get(key);
+ if (!pendingLimits) {
const sequences = sequencesRef.current;
const tracks = calculateTimeline({
sequences,
overrideIdsToNodePaths: mappingsRef.current,
});
+ const preparedProps =
+ fieldKey === 'from'
+ ? Promise.resolve(propStatusesRef.current)
+ : (preparedPropsRef.current ??= loadKeyframeTrimConstraints({
+ propStatuses: propStatusesRef.current,
+ overrideIdsToNodePaths: mappingsRef.current,
+ }));
const matching = tracks.filter(
(track) =>
track.nodePathInfo &&
@@ -45,52 +62,66 @@ export const useClampSequenceTimingValue = () => {
track.nodePathInfo.sequenceSubscriptionKey,
) === key,
);
- for (const track of matching) {
- const next = getTimelineSequenceTimingLimits({
- propStatuses: propStatusesRef.current,
- movingSequenceIds: null,
- track,
- tracks,
- sequences,
- timelineDurationInFrames: video?.durationInFrames ?? Infinity,
- });
- limits = limits
- ? {
- ...next,
- minimumDuration: Math.max(
- limits.minimumDuration,
- next.minimumDuration,
- ),
- maximumDuration: Math.min(
- limits.maximumDuration,
- next.maximumDuration,
- ),
- minimumFrom: Math.max(limits.minimumFrom, next.minimumFrom),
- maximumFrom: Math.min(limits.maximumFrom, next.maximumFrom),
- minimumTrimBefore: Math.max(
- limits.minimumTrimBefore,
- next.minimumTrimBefore,
- ),
- maximumTrimBefore: Math.min(
- limits.maximumTrimBefore,
- next.maximumTrimBefore,
- ),
- minimumTrimAfter: Math.max(
- limits.minimumTrimAfter,
- next.minimumTrimAfter,
- ),
- maximumTrimAfter: Math.min(
- limits.maximumTrimAfter,
- next.maximumTrimAfter,
- ),
- }
- : next;
- }
+ pendingLimits = preparedProps.then((propStatuses) => {
+ let mergedLimits: ReturnType<
+ typeof getTimelineSequenceTimingLimits
+ > | null = null;
+ for (const track of matching) {
+ const next = getTimelineSequenceTimingLimits({
+ propStatuses,
+ movingSequenceIds: null,
+ track,
+ tracks,
+ sequences,
+ timelineDurationInFrames: video?.durationInFrames ?? Infinity,
+ });
+ mergedLimits = mergedLimits
+ ? {
+ ...next,
+ minimumDuration: Math.max(
+ mergedLimits.minimumDuration,
+ next.minimumDuration,
+ ),
+ maximumDuration: Math.min(
+ mergedLimits.maximumDuration,
+ next.maximumDuration,
+ ),
+ minimumFrom: Math.max(
+ mergedLimits.minimumFrom,
+ next.minimumFrom,
+ ),
+ maximumFrom: Math.min(
+ mergedLimits.maximumFrom,
+ next.maximumFrom,
+ ),
+ minimumTrimBefore: Math.max(
+ mergedLimits.minimumTrimBefore,
+ next.minimumTrimBefore,
+ ),
+ maximumTrimBefore: Math.min(
+ mergedLimits.maximumTrimBefore,
+ next.maximumTrimBefore,
+ ),
+ minimumTrimAfter: Math.max(
+ mergedLimits.minimumTrimAfter,
+ next.minimumTrimAfter,
+ ),
+ maximumTrimAfter: Math.min(
+ mergedLimits.maximumTrimAfter,
+ next.maximumTrimAfter,
+ ),
+ }
+ : next;
+ }
- if (!limits) return value;
- limitsRef.current.set(key, limits);
+ return mergedLimits;
+ });
+ limitsRef.current.set(key, pendingLimits);
}
+ const limits = await pendingLimits;
+ if (!limits) return value;
+
const [minimum, maximum] =
fieldKey === 'from'
? [limits.minimumFrom, limits.maximumFrom]
diff --git a/packages/studio/src/helpers/start-prepared-pointer-session.ts b/packages/studio/src/helpers/start-prepared-pointer-session.ts
new file mode 100644
index 0000000000..fdc5d645b2
--- /dev/null
+++ b/packages/studio/src/helpers/start-prepared-pointer-session.ts
@@ -0,0 +1,79 @@
+import type {PointerSessionEndReason} from './pointer-session';
+import {
+ isPointerSessionRelease,
+ startCapturedPointerSession,
+} from './pointer-session';
+
+type PreparedPointerHandlers = {
+ onMove: (event: PointerEvent) => void;
+ onEnd: (reason: PointerSessionEndReason, event: PointerEvent | null) => void;
+};
+
+export const startPreparedPointerSession = <T>({
+ event,
+ captureTarget,
+ prepare,
+ onReady,
+ onCancel,
+ onError,
+}: {
+ event: PointerEvent;
+ captureTarget: Element;
+ prepare: () => Promise<T>;
+ onReady: (prepared: T) => PreparedPointerHandlers;
+ onCancel: () => void;
+ onError: (error: unknown) => void;
+}): (() => void) => {
+ let active = true;
+ let handlers: PreparedPointerHandlers | null = null;
+ let latestMove: PointerEvent | null = null;
+ let release: {reason: PointerSessionEndReason; event: PointerEvent} | null =
+ null;
+ const stopCapture = startCapturedPointerSession({
+ event,
+ captureTarget,
+ onMove: (move) => {
+ latestMove = move;
+ handlers?.onMove(move);
+ },
+ onEnd: (reason, endEvent) => {
+ if (!active) return;
+ if (handlers) {
+ active = false;
+ handlers.onEnd(reason, endEvent);
+ } else if (isPointerSessionRelease(reason, endEvent)) {
+ // A quick drag can finish before preparation. Apply its final position
+ // only once the bounds are known; a new gesture/unmount can cancel it.
+ release = {reason, event: endEvent};
+ } else {
+ active = false;
+ onCancel();
+ }
+ },
+ });
+ const cancel = () => {
+ if (!active) return;
+ stopCapture();
+ if (!active) return;
+ active = false;
+ onCancel();
+ };
+
+ prepare()
+ .then((prepared) => {
+ if (!active) return;
+ handlers = onReady(prepared);
+ if (release) {
+ active = false;
+ handlers.onEnd(release.reason, release.event);
+ } else if (latestMove) {
+ handlers.onMove(latestMove);
+ }
+ })
+ .catch((error) => {
+ if (!active) return;
+ cancel();
+ onError(error);
+ });
+ return cancel;
+};