Skip to content

🎥 Make videos programmatically with React

@remotion/studio: Fix timeline pinch zoom sensitivity and anchor anchoring

JonnyBurgerf5c224e5bd6e
diff --git a/packages/studio/src/components/Timeline/TimelinePinchZoom.tsx b/packages/studio/src/components/Timeline/TimelinePinchZoom.tsx
index 4c0a931622..ef023e3aaa 100644
--- a/packages/studio/src/components/Timeline/TimelinePinchZoom.tsx
+++ b/packages/studio/src/components/Timeline/TimelinePinchZoom.tsx
@@ -1,26 +1,55 @@
-import {useCallback, useContext, useEffect, type FC} from 'react';
+import {useCallback, useContext, useEffect, useRef, type FC} from 'react';
import {Internals} from 'remotion';
import {useIsVideoComposition} from '../../helpers/is-current-selected-still';
-import {TimelineZoomCtx} from '../../state/timeline-zoom';
+import {EditorZoomGesturesContext} from '../../state/editor-zoom-gestures';
+import {TIMELINE_MIN_ZOOM, TimelineZoomCtx} from '../../state/timeline-zoom';
import {scrollableRef, timelineVerticalScroll} from './timeline-refs';
-import {getFrameFromX} from './timeline-scroll-logic';
+import {viewportClientXToScrollContentX} from './timeline-scroll-logic';
-const ZOOM_WHEEL_DELTA = 0.005;
+/**
+ * Maps wheel deltaY to zoom delta. Must be large enough that typical ctrl+wheel
+ * pinch steps change `TimelineZoomCtx` zoom by at least one 0.1 step after
+ * `Math.round(z * 10) / 10` in `timeline-zoom.tsx` (0.005 was too small).
+ */
+const ZOOM_WHEEL_DELTA = 0.06;
+
+type WebKitGestureEvent = UIEvent & {
+ scale: number;
+ clientX: number;
+ clientY: number;
+};
export const TimelinePinchZoom: FC = () => {
const isVideoComposition = useIsVideoComposition();
const videoConfig = Internals.useUnsafeVideoConfig();
const {canvasContent} = useContext(Internals.CompositionManager);
- const {setZoom} = useContext(TimelineZoomCtx);
+ const {zoom, setZoom} = useContext(TimelineZoomCtx);
+ const {editorZoomGestures} = useContext(EditorZoomGesturesContext);
+
+ const zoomRef = useRef(zoom);
+ zoomRef.current = zoom;
+
+ const pinchBaseZoomRef = useRef<number | null>(null);
+ const suppressWheelFromWebKitPinchRef = useRef(false);
+ const touchPinchRef = useRef<{
+ initialDistance: number;
+ initialZoom: number;
+ } | null>(null);
const onWheel = useCallback(
(e: WheelEvent) => {
- if (!isVideoComposition) {
+ if (!editorZoomGestures || !isVideoComposition) {
+ return;
+ }
+
+ const {ctrlKey, metaKey, clientX, deltaY, deltaMode} = e;
+ const wantsToZoom = ctrlKey || metaKey;
+ if (!wantsToZoom) {
return;
}
- const {ctrlKey, metaKey, clientX} = e;
- if (!(ctrlKey || metaKey)) {
+ if (suppressWheelFromWebKitPinchRef.current && wantsToZoom) {
+ e.preventDefault();
return;
}
@@ -39,35 +68,36 @@ export const TimelinePinchZoom: FC = () => {
e.preventDefault();
- const rect = scrollEl.getBoundingClientRect();
- const clampedClientX = Math.min(Math.max(clientX, rect.left), rect.right);
- const clientXInContent = clampedClientX + scrollEl.scrollLeft - rect.left;
-
- const width = scrollEl.scrollWidth;
- const anchorFrame = getFrameFromX({
- clientX: clientXInContent,
- durationInFrames: videoConfig.durationInFrames,
- width,
- extrapolate: 'clamp',
+ const anchorContentX = viewportClientXToScrollContentX({
+ clientX,
+ scrollEl,
});
- const {deltaMode} = e;
- let {deltaY} = e;
+ let scaledDeltaY = deltaY;
if (deltaMode === WheelEvent.DOM_DELTA_LINE) {
- deltaY *= 16;
+ scaledDeltaY *= 16;
} else if (deltaMode === WheelEvent.DOM_DELTA_PAGE) {
- deltaY *= scrollEl.clientHeight;
+ scaledDeltaY *= scrollEl.clientHeight;
}
setZoom(
canvasContent.compositionId,
- (z) => z - deltaY * ZOOM_WHEEL_DELTA,
- {anchorFrame},
+ (z) => z - scaledDeltaY * ZOOM_WHEEL_DELTA,
+ {anchorContentX},
);
},
- [isVideoComposition, videoConfig, canvasContent, setZoom],
+ [
+ editorZoomGestures,
+ isVideoComposition,
+ videoConfig,
+ canvasContent,
+ setZoom,
+ ],
);
+ const supportsWebKitPinch =
+ typeof window !== 'undefined' && 'GestureEvent' in window;
+
useEffect(() => {
const el = timelineVerticalScroll.current;
if (!el) {
@@ -80,5 +110,201 @@ export const TimelinePinchZoom: FC = () => {
};
}, [onWheel]);
+ useEffect(() => {
+ const el = timelineVerticalScroll.current;
+ if (!el || !editorZoomGestures || !supportsWebKitPinch) {
+ return;
+ }
+
+ const endWebKitPinch = () => {
+ pinchBaseZoomRef.current = null;
+ suppressWheelFromWebKitPinchRef.current = false;
+ };
+
+ const onGestureStart = (event: Event) => {
+ const e = event as WebKitGestureEvent;
+ if (!isVideoComposition) {
+ return;
+ }
+
+ if (!videoConfig || videoConfig.durationInFrames < 2) {
+ return;
+ }
+
+ if (!canvasContent || canvasContent.type !== 'composition') {
+ return;
+ }
+
+ const scrollEl = scrollableRef.current;
+ if (!scrollEl) {
+ return;
+ }
+
+ e.preventDefault();
+ suppressWheelFromWebKitPinchRef.current = true;
+
+ pinchBaseZoomRef.current =
+ zoomRef.current[canvasContent.compositionId] ?? TIMELINE_MIN_ZOOM;
+ };
+
+ const onGestureChange = (event: Event) => {
+ const e = event as WebKitGestureEvent;
+ const base = pinchBaseZoomRef.current;
+ if (
+ base === null ||
+ !isVideoComposition ||
+ !videoConfig ||
+ videoConfig.durationInFrames < 2
+ ) {
+ return;
+ }
+
+ if (!canvasContent || canvasContent.type !== 'composition') {
+ return;
+ }
+
+ const scrollEl = scrollableRef.current;
+ if (!scrollEl) {
+ return;
+ }
+
+ e.preventDefault();
+
+ const anchorContentX = viewportClientXToScrollContentX({
+ clientX: e.clientX,
+ scrollEl,
+ });
+
+ setZoom(canvasContent.compositionId, () => base * e.scale, {
+ anchorContentX,
+ });
+ };
+
+ const onGestureEnd = () => {
+ endWebKitPinch();
+ };
+
+ el.addEventListener('gesturestart', onGestureStart, {passive: false});
+ el.addEventListener('gesturechange', onGestureChange, {passive: false});
+ el.addEventListener('gestureend', onGestureEnd);
+ el.addEventListener('gesturecancel', onGestureEnd);
+
+ return () => {
+ el.removeEventListener('gesturestart', onGestureStart);
+ el.removeEventListener('gesturechange', onGestureChange);
+ el.removeEventListener('gestureend', onGestureEnd);
+ el.removeEventListener('gesturecancel', onGestureEnd);
+ };
+ }, [
+ editorZoomGestures,
+ supportsWebKitPinch,
+ isVideoComposition,
+ videoConfig,
+ canvasContent,
+ setZoom,
+ ]);
+
+ useEffect(() => {
+ const el = timelineVerticalScroll.current;
+ if (!el || !editorZoomGestures) {
+ return;
+ }
+
+ const onTouchStart = (event: TouchEvent) => {
+ if (event.touches.length !== 2) {
+ touchPinchRef.current = null;
+ return;
+ }
+
+ if (
+ !isVideoComposition ||
+ !videoConfig ||
+ videoConfig.durationInFrames < 2
+ ) {
+ return;
+ }
+
+ if (!canvasContent || canvasContent.type !== 'composition') {
+ return;
+ }
+
+ const [t0, t1] = [event.touches[0], event.touches[1]];
+ const initialDistance = Math.hypot(
+ t1.clientX - t0.clientX,
+ t1.clientY - t0.clientY,
+ );
+ if (initialDistance < 1e-6) {
+ return;
+ }
+
+ touchPinchRef.current = {
+ initialDistance,
+ initialZoom:
+ zoomRef.current[canvasContent.compositionId] ?? TIMELINE_MIN_ZOOM,
+ };
+ };
+
+ const onTouchMove = (event: TouchEvent) => {
+ const pinch = touchPinchRef.current;
+ if (
+ pinch === null ||
+ event.touches.length !== 2 ||
+ !videoConfig ||
+ videoConfig.durationInFrames < 2
+ ) {
+ return;
+ }
+
+ if (!canvasContent || canvasContent.type !== 'composition') {
+ return;
+ }
+
+ const scrollEl = scrollableRef.current;
+ if (!scrollEl) {
+ return;
+ }
+
+ event.preventDefault();
+
+ const [t0, t1] = [event.touches[0], event.touches[1]];
+ const dist = Math.hypot(t1.clientX - t0.clientX, t1.clientY - t0.clientY);
+ const ratio = dist / pinch.initialDistance;
+ const clientX = (t0.clientX + t1.clientX) / 2;
+
+ const anchorContentX = viewportClientXToScrollContentX({
+ clientX,
+ scrollEl,
+ });
+
+ setZoom(canvasContent.compositionId, () => pinch.initialZoom * ratio, {
+ anchorContentX,
+ });
+ };
+
+ const onTouchEnd = (event: TouchEvent) => {
+ if (event.touches.length < 2) {
+ touchPinchRef.current = null;
+ }
+ };
+
+ el.addEventListener('touchstart', onTouchStart, {passive: true});
+ el.addEventListener('touchmove', onTouchMove, {passive: false});
+ el.addEventListener('touchend', onTouchEnd);
+ el.addEventListener('touchcancel', onTouchEnd);
+
+ return () => {
+ el.removeEventListener('touchstart', onTouchStart);
+ el.removeEventListener('touchmove', onTouchMove);
+ el.removeEventListener('touchend', onTouchEnd);
+ el.removeEventListener('touchcancel', onTouchEnd);
+ };
+ }, [
+ editorZoomGestures,
+ isVideoComposition,
+ videoConfig,
+ canvasContent,
+ setZoom,
+ ]);
+
return null;
};
diff --git a/packages/studio/src/components/Timeline/timeline-scroll-logic.ts b/packages/studio/src/components/Timeline/timeline-scroll-logic.ts
index 9df768b198..a7d4bb02c6 100644
--- a/packages/studio/src/components/Timeline/timeline-scroll-logic.ts
+++ b/packages/studio/src/components/Timeline/timeline-scroll-logic.ts
@@ -281,18 +281,39 @@ export const getFrameFromX = ({
return frame;
};
+/**
+ * Horizontal position inside the scrollable timeline content (0 … scrollWidth)
+ * for a viewport `clientX`, so pinch-anchoring matches the pointer (not a
+ * rounded frame index).
+ */
+export const viewportClientXToScrollContentX = ({
+ clientX,
+ scrollEl,
+}: {
+ clientX: number;
+ scrollEl: HTMLDivElement;
+}) => {
+ const rect = scrollEl.getBoundingClientRect();
+ const clampedClientX = Math.min(Math.max(clientX, rect.left), rect.right);
+
+ return clampedClientX + scrollEl.scrollLeft - rect.left;
+};
+
export const zoomAndPreserveCursor = ({
oldZoom,
newZoom,
currentFrame,
currentDurationInFrames,
anchorFrame,
+ anchorContentX,
}: {
oldZoom: number;
newZoom: number;
currentFrame: number;
currentDurationInFrames: number;
anchorFrame?: number;
+ /** Prefer this over `anchorFrame` when set (subpixel-accurate anchor). */
+ anchorContentX?: number;
}) => {
const ratio = newZoom / oldZoom;
if (ratio === 1) {
@@ -307,7 +328,10 @@ export const zoomAndPreserveCursor = ({
const frameIncrement = getFrameIncrement(currentDurationInFrames);
const frameForScroll = anchorFrame ?? currentFrame;
- const prevCursorPosition = frameIncrement * frameForScroll + TIMELINE_PADDING;
+ const prevCursorPosition =
+ anchorContentX !== undefined
+ ? Math.min(Math.max(anchorContentX, 0), current.scrollWidth)
+ : frameIncrement * frameForScroll + TIMELINE_PADDING;
const newCursorPosition =
ratio * (prevCursorPosition - TIMELINE_PADDING) + TIMELINE_PADDING;
diff --git a/packages/studio/src/state/timeline-zoom.tsx b/packages/studio/src/state/timeline-zoom.tsx
index ec82308a27..e5e1fda871 100644
--- a/packages/studio/src/state/timeline-zoom.tsx
+++ b/packages/studio/src/state/timeline-zoom.tsx
@@ -14,7 +14,7 @@ export const TimelineZoomCtx = createContext<{
setZoom: (
compositionId: string,
prev: (prevZoom: number) => number,
- options?: {anchorFrame?: number},
+ options?: {anchorFrame?: number; anchorContentX?: number},
) => void;
}>({
zoom: {},
@@ -34,7 +34,7 @@ export const TimelineZoomContext: React.FC<{
(
compositionId: string,
callback: (prevZoomLevel: number) => number,
- options?: {anchorFrame?: number},
+ options?: {anchorFrame?: number; anchorContentX?: number},
) => {
setZoomState((prevZoomMap) => {
const newZoomWithFloatingPointErrors = Math.min(
@@ -52,6 +52,7 @@ export const TimelineZoomContext: React.FC<{
currentDurationInFrames: getCurrentDuration(),
currentFrame: getCurrentFrame(),
anchorFrame: options?.anchorFrame,
+ anchorContentX: options?.anchorContentX,
});
return {...prevZoomMap, [compositionId]: newZoom};
});