diff options
Diffstat (limited to 'apps/web/src/hooks')
| -rw-r--r-- | apps/web/src/hooks/use-disable-browser-zoom.ts | 63 | ||||
| -rw-r--r-- | apps/web/src/hooks/use-timeline-playhead.ts | 202 | ||||
| -rw-r--r-- | apps/web/src/hooks/use-timeline-zoom.ts | 103 |
3 files changed, 219 insertions, 149 deletions
diff --git a/apps/web/src/hooks/use-disable-browser-zoom.ts b/apps/web/src/hooks/use-disable-browser-zoom.ts new file mode 100644 index 00000000..9467cb71 --- /dev/null +++ b/apps/web/src/hooks/use-disable-browser-zoom.ts @@ -0,0 +1,63 @@ +import { useEffect } from "react"; + +/** + * useDisableBrowserZoom + * + * This React hook prevents users from zooming in/out the browser window using keyboard shortcuts, + * mouse wheel, or gesture events (such as pinch-to-zoom on trackpads or touch devices). + * + * Typical use case: apps with fixed-size UIs, custom editors, or when zooming would break layout. + * + * NOTE: Disabling browser zoom may negatively affect accessibility and user experience. + * Use with caution, especially for public-facing applications. + */ +export const useDisableBrowserZoom = () => { + useEffect(() => { + /** + * Prevents browser zoom when user holds Ctrl (or Cmd on Mac) and scrolls the mouse wheel. + */ + const handleWheel = (e: WheelEvent) => { + if (e.ctrlKey) { + e.preventDefault(); + } + }; + + /** + * Prevents browser zoom via keyboard shortcuts: + * Ctrl/Cmd + '+', '-', '=', or '0' (reset zoom) + * Some keyboards emit '=' for '+' (without Shift). + */ + const handleKeyDown = (e: KeyboardEvent) => { + if (e.ctrlKey) { + const key = e.key; + if (key === "+" || key === "-" || key === "0" || key === "=") { + e.preventDefault(); + } + } + }; + + /** + * Prevents pinch-zoom gestures on supported browsers (mainly Safari/macOS/iOS). + * gesturestart, gesturechange, and gestureend are non-standard and not supported everywhere. + */ + const handleGesture = (e: Event) => { + e.preventDefault(); + }; + + // Attach event listeners (passive: false is required for preventDefault to work) + window.addEventListener("wheel", handleWheel, { passive: false }); + window.addEventListener("keydown", handleKeyDown, { passive: false }); + window.addEventListener("gesturestart", handleGesture, { passive: false }); + window.addEventListener("gesturechange", handleGesture, { passive: false }); + window.addEventListener("gestureend", handleGesture, { passive: false }); + + // Cleanup listeners on unmount to avoid memory leaks + return () => { + window.removeEventListener("wheel", handleWheel); + window.removeEventListener("keydown", handleKeyDown); + window.removeEventListener("gesturestart", handleGesture); + window.removeEventListener("gesturechange", handleGesture); + window.removeEventListener("gestureend", handleGesture); + }; + }, []); +}; diff --git a/apps/web/src/hooks/use-timeline-playhead.ts b/apps/web/src/hooks/use-timeline-playhead.ts index 9a82c23f..9eb06485 100644 --- a/apps/web/src/hooks/use-timeline-playhead.ts +++ b/apps/web/src/hooks/use-timeline-playhead.ts @@ -1,6 +1,6 @@ import { snapTimeToFrame } from "@/constants/timeline-constants";
import { useProjectStore } from "@/stores/project-store";
-import { useState, useEffect, useCallback } from "react";
+import { useRef, useState, useCallback } from "react";
interface UseTimelinePlayheadProps {
currentTime: number;
@@ -9,10 +9,15 @@ interface UseTimelinePlayheadProps { seek: (time: number) => void;
rulerRef: React.RefObject<HTMLDivElement>;
rulerScrollRef: React.RefObject<HTMLDivElement>;
- tracksScrollRef: React.RefObject<HTMLDivElement>;
- playheadRef?: React.RefObject<HTMLDivElement>;
}
+/**
+ * useTimelinePlayhead
+ *
+ * Custom hook to manage playhead (scrubbing) logic for a timeline editor.
+ * Handles mouse interaction for timeline ruler, calculates time from mouse,
+ * and enables smooth scrubbing without unnecessary re-renders.
+ */
export function useTimelinePlayhead({
currentTime,
duration,
@@ -20,138 +25,101 @@ export function useTimelinePlayhead({ seek,
rulerRef,
rulerScrollRef,
- tracksScrollRef,
- playheadRef,
}: UseTimelinePlayheadProps) {
- // Playhead scrubbing state
- const [isScrubbing, setIsScrubbing] = useState(false);
- const [scrubTime, setScrubTime] = useState<number | null>(null);
+ // Get current project info (especially FPS) from global store
+ const { activeProject } = useProjectStore();
- // Ruler drag detection state
- const [isDraggingRuler, setIsDraggingRuler] = useState(false);
- const [hasDraggedRuler, setHasDraggedRuler] = useState(false);
+ // Ref to track if currently scrubbing
+ const isScrubbingRef = useRef(false);
+ // Ref to hold the playhead time while scrubbing (does not trigger re-render)
+ const scrubTimeRef = useRef<number | null>(null);
+
+ // State to force re-render when scrubbing ends
+ const [_, forceRerender] = useState(0);
+
+ /**
+ * Determines the actual playhead position:
+ * - If scrubbing, use the value in scrubTimeRef
+ * - Otherwise, use the currentTime (controlled by external state)
+ */
const playheadPosition =
- isScrubbing && scrubTime !== null ? scrubTime : currentTime;
+ isScrubbingRef.current && scrubTimeRef.current !== null
+ ? scrubTimeRef.current
+ : currentTime;
- // --- Playhead Scrubbing Handlers ---
- const handlePlayheadMouseDown = useCallback(
- (e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation(); // Prevent ruler drag from triggering
- setIsScrubbing(true);
- handleScrub(e);
+ /**
+ * Calculate timeline time (in seconds) based on mouse X position.
+ * - Gets bounding rect of the ruler
+ * - Adjusts for scroll position if ruler is scrollable
+ * - Converts X pixel offset to seconds using current zoom level
+ * - Snaps to nearest frame using FPS
+ */
+ const getTimeFromMouse = useCallback(
+ (e: MouseEvent | React.MouseEvent) => {
+ const ruler = rulerRef.current;
+ const scrollArea = rulerScrollRef.current?.querySelector(
+ "[data-radix-scroll-area-viewport]"
+ ) as HTMLElement;
+
+ if (!ruler || !scrollArea) return 0;
+
+ const rect = ruler.getBoundingClientRect();
+ const scrollLeft = scrollArea.scrollLeft;
+ const x = e.clientX - rect.left + scrollLeft;
+
+ // Calculate how many pixels represent one second, depending on zoom
+ const pixelsPerSecond = 50 * zoomLevel;
+ const rawTime = Math.max(0, Math.min(duration, x / pixelsPerSecond));
+ const time = snapTimeToFrame(rawTime, activeProject?.fps || 30);
+ return time;
},
- [duration, zoomLevel]
+ [rulerRef, rulerScrollRef, duration, zoomLevel, activeProject?.fps]
);
- // Ruler mouse down handler
+ /**
+ * Handle mouse down event on the ruler:
+ * - Starts scrubbing and updates playhead immediately
+ * - Registers mousemove/mouseup events to allow scrubbing
+ * - Updates time as mouse moves and seeks to new time
+ * - Cleans up listeners and triggers re-render when scrubbing ends
+ */
const handleRulerMouseDown = useCallback(
(e: React.MouseEvent) => {
- // Only handle left mouse button
if (e.button !== 0) return;
+ e.preventDefault();
+ const time = getTimeFromMouse(e);
- // Don't interfere if clicking on the playhead itself
- if (playheadRef?.current?.contains(e.target as Node)) return;
+ isScrubbingRef.current = true;
+ scrubTimeRef.current = time;
+ seek(time);
- e.preventDefault();
- setIsDraggingRuler(true);
- setHasDraggedRuler(false);
+ // Mouse move handler: update playhead and seek to new time
+ const onMouseMove = (e: MouseEvent) => {
+ const t = getTimeFromMouse(e);
+ if (t !== scrubTimeRef.current) {
+ scrubTimeRef.current = t;
+ seek(t);
+ }
+ };
- // Start scrubbing immediately
- setIsScrubbing(true);
- handleScrub(e);
- },
- [duration, zoomLevel]
- );
+ // Mouse up handler: stop scrubbing, cleanup, and force re-render
+ const onMouseUp = () => {
+ isScrubbingRef.current = false;
+ window.removeEventListener("mousemove", onMouseMove);
+ window.removeEventListener("mouseup", onMouseUp);
+ forceRerender((v) => v + 1);
+ };
- const handleScrub = useCallback(
- (e: MouseEvent | React.MouseEvent) => {
- const ruler = rulerRef.current;
- if (!ruler) return;
- const rect = ruler.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const rawTime = Math.max(0, Math.min(duration, x / (50 * zoomLevel)));
- // Use frame snapping for playhead scrubbing
- const projectStore = useProjectStore.getState();
- const projectFps = projectStore.activeProject?.fps || 30;
- const time = snapTimeToFrame(rawTime, projectFps);
- setScrubTime(time);
- seek(time); // update video preview in real time
+ // Attach listeners to window for drag outside the ruler area
+ window.addEventListener("mousemove", onMouseMove);
+ window.addEventListener("mouseup", onMouseUp);
},
- [duration, zoomLevel, seek, rulerRef]
+ [getTimeFromMouse, seek]
);
- // Mouse move/up event handlers
- useEffect(() => {
- if (!isScrubbing) return;
- const onMouseMove = (e: MouseEvent) => {
- handleScrub(e);
- // Mark that we've dragged if ruler drag is active
- if (isDraggingRuler) {
- setHasDraggedRuler(true);
- }
- };
- const onMouseUp = (e: MouseEvent) => {
- setIsScrubbing(false);
- if (scrubTime !== null) seek(scrubTime); // finalize seek
- setScrubTime(null);
-
- // Handle ruler click vs drag
- if (isDraggingRuler) {
- setIsDraggingRuler(false);
- // If we didn't drag, treat it as a click-to-seek
- if (!hasDraggedRuler) {
- handleScrub(e);
- }
- setHasDraggedRuler(false);
- }
- };
- window.addEventListener("mousemove", onMouseMove);
- window.addEventListener("mouseup", onMouseUp);
- return () => {
- window.removeEventListener("mousemove", onMouseMove);
- window.removeEventListener("mouseup", onMouseUp);
- };
- }, [
- isScrubbing,
- scrubTime,
- seek,
- handleScrub,
- isDraggingRuler,
- hasDraggedRuler,
- ]);
-
- // --- Playhead auto-scroll effect ---
- useEffect(() => {
- const rulerViewport = rulerScrollRef.current?.querySelector(
- "[data-radix-scroll-area-viewport]"
- ) as HTMLElement;
- const tracksViewport = tracksScrollRef.current?.querySelector(
- "[data-radix-scroll-area-viewport]"
- ) as HTMLElement;
- if (!rulerViewport || !tracksViewport) return;
- const playheadPx = playheadPosition * 50 * zoomLevel; // TIMELINE_CONSTANTS.PIXELS_PER_SECOND = 50
- const viewportWidth = rulerViewport.clientWidth;
- const scrollMin = 0;
- const scrollMax = rulerViewport.scrollWidth - viewportWidth;
- // Center the playhead if it's not visible (100px buffer)
- const desiredScroll = Math.max(
- scrollMin,
- Math.min(scrollMax, playheadPx - viewportWidth / 2)
- );
- if (
- playheadPx < rulerViewport.scrollLeft + 100 ||
- playheadPx > rulerViewport.scrollLeft + viewportWidth - 100
- ) {
- rulerViewport.scrollLeft = tracksViewport.scrollLeft = desiredScroll;
- }
- }, [playheadPosition, duration, zoomLevel, rulerScrollRef, tracksScrollRef]);
-
return {
- playheadPosition,
- handlePlayheadMouseDown,
- handleRulerMouseDown,
- isDraggingRuler,
+ playheadPosition, // Current playhead position (real-time while scrubbing)
+ handleRulerMouseDown, // Attach to the ruler's onMouseDown
};
}
diff --git a/apps/web/src/hooks/use-timeline-zoom.ts b/apps/web/src/hooks/use-timeline-zoom.ts index ce32c9f0..c8780f9a 100644 --- a/apps/web/src/hooks/use-timeline-zoom.ts +++ b/apps/web/src/hooks/use-timeline-zoom.ts @@ -1,4 +1,5 @@ -import { useState, useCallback, useEffect, RefObject } from "react";
+import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
+import { useState, useCallback, RefObject, useMemo } from "react";
interface UseTimelineZoomProps {
containerRef: RefObject<HTMLDivElement>;
@@ -7,48 +8,86 @@ interface UseTimelineZoomProps { interface UseTimelineZoomReturn {
zoomLevel: number;
+ zoomStep: number;
setZoomLevel: (zoomLevel: number | ((prev: number) => number)) => void;
+ handleChangeZoomStep: (zoomStep: number) => void;
+ handleChangeZoomLevel: (zoomStep: number) => void;
handleWheel: (e: React.WheelEvent) => void;
}
-export function useTimelineZoom({
- containerRef,
- isInTimeline = false,
-}: UseTimelineZoomProps): UseTimelineZoomReturn {
+/**
+ * useTimelineZoom
+ *
+ * Custom hook to manage zoom logic for a timeline component.
+ * Handles zoom state, step calculation, level changes, and mouse wheel zooming (with ctrl/meta).
+ */
+export function useTimelineZoom(): UseTimelineZoomReturn {
+ // Current zoom level (1 = default)
const [zoomLevel, setZoomLevel] = useState(1);
+ /**
+ * Calculate the current zoom step based on the zoom level and a base step constant.
+ * Ensures minimum step is 1 (prevents zero or negative step).
+ */
+ const zoomStep = useMemo(
+ () =>
+ Math.max(1, Math.round(zoomLevel / TIMELINE_CONSTANTS.ZOOM_STEP_BASE)),
+ [zoomLevel]
+ );
+
+ /**
+ * Update the zoom level using a given step.
+ * The zoom level is clamped to a minimum value defined in constants.
+ */
+ const handleChangeZoomStep = useCallback((newStep: number) => {
+ setZoomLevel(
+ Math.max(
+ TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
+ newStep * TIMELINE_CONSTANTS.ZOOM_STEP_BASE
+ )
+ );
+ }, []);
+
+ /**
+ * Update the zoom level directly.
+ * The new value is clamped between the defined minimum and maximum levels.
+ */
+ const handleChangeZoomLevel = useCallback((newLevel: number) => {
+ setZoomLevel(
+ Math.max(
+ TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
+ Math.min(TIMELINE_CONSTANTS.ZOOM_LEVEL_MAX, newLevel)
+ )
+ );
+ }, []);
+
+ /**
+ * Handle zooming using mouse wheel + ctrl/meta key (like browser zoom).
+ * Prevents default browser behavior and updates zoom level accordingly.
+ */
const handleWheel = useCallback((e: React.WheelEvent) => {
- // Only zoom if user is using pinch gesture (ctrlKey or metaKey is true)
if (e.ctrlKey || e.metaKey) {
- e.preventDefault();
- const delta = e.deltaY > 0 ? -0.15 : 0.15;
- setZoomLevel((prev) => Math.max(0.1, Math.min(10, prev + delta)));
+ e.preventDefault?.();
+ const delta =
+ e.deltaY > 0
+ ? -TIMELINE_CONSTANTS.ZOOM_STEP_BASE
+ : TIMELINE_CONSTANTS.ZOOM_STEP_BASE;
+ setZoomLevel((prev) =>
+ Math.max(
+ TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
+ Math.min(TIMELINE_CONSTANTS.ZOOM_LEVEL_MAX, prev + delta)
+ )
+ );
}
- // Otherwise, allow normal scrolling
}, []);
- // Prevent browser zooming in/out when in timeline
- useEffect(() => {
- const preventZoom = (e: WheelEvent) => {
- if (
- isInTimeline &&
- (e.ctrlKey || e.metaKey) &&
- containerRef.current?.contains(e.target as Node)
- ) {
- e.preventDefault();
- }
- };
-
- document.addEventListener("wheel", preventZoom, { passive: false });
-
- return () => {
- document.removeEventListener("wheel", preventZoom);
- };
- }, [isInTimeline, containerRef]);
-
+ // Return all handlers and state values for use in timeline components
return {
- zoomLevel,
- setZoomLevel,
- handleWheel,
+ zoomLevel, // Current zoom level
+ zoomStep, // Current zoom step (calculated from zoomLevel)
+ setZoomLevel, // Directly set the zoom level (accepts value or updater function)
+ handleChangeZoomStep, // Change zoom by step value
+ handleChangeZoomLevel, // Change zoom by level value
+ handleWheel, // Handler for mouse wheel zooming
};
}
|
