import React, { createContext, type RefObject, useCallback, useContext, useEffect, useId, useRef, } from "react"; type ScrollRole = "master" | "slave" | "drag"; interface ScrollableElement { ref: RefObject; role: ScrollRole; } interface SyncScrollContextValue { registerScrollable: (id: string, ref: RefObject, role: ScrollRole) => void; unregisterScrollable: (id: string) => void; syncScroll: (sourceId: string, scrollTop: number, scrollLeft: number) => void; } const SyncScrollContext = createContext(null); interface SyncScrollProviderProps { children: React.ReactNode; } /** * Provider component that manages synchronized scrolling between multiple elements. * Supports master-slave relationships where masters can control slaves but not vice versa. */ export function SyncScrollProvider({ children }: SyncScrollProviderProps) { const scrollablesRef = useRef>(new Map()); const syncingRef = useRef>(new Set()); const registerScrollable = useCallback( (id: string, ref: RefObject, role: ScrollRole) => { scrollablesRef.current.set(id, { ref, role }); }, [], ); const unregisterScrollable = useCallback((id: string) => { scrollablesRef.current.delete(id); syncingRef.current.delete(id); }, []); const syncScroll = useCallback((sourceId: string, scrollTop: number, scrollLeft: number) => { // Prevent circular syncing if (syncingRef.current.has(sourceId)) { return; } const sourceElement = scrollablesRef.current.get(sourceId); if (!sourceElement) return; // Determine which elements should be synced based on source role scrollablesRef.current.forEach((element, id) => { if (id === sourceId) return; // Master and drag can sync everyone if (sourceElement.role === "master" || sourceElement.role === "drag") { syncingRef.current.add(id); if (element.ref.current) { element.ref.current.scrollTop = scrollTop; element.ref.current.scrollLeft = scrollLeft; } } // // Slave can only sync other slaves (not masters or drag) // else if (sourceElement.role === "slave" && element.role === "slave") { // syncingRef.current.add(id); // if (element.ref.current) { // element.ref.current.scrollTop = scrollTop; // element.ref.current.scrollLeft = scrollLeft; // } // } }); // Clear syncing flags after a short delay requestAnimationFrame(() => { syncingRef.current.clear(); }); }, []); return ( {children} ); } interface BaseScrollOptions { /** Whether to enable scroll syncing (default: true) */ enabled?: boolean; /** Axis to sync: 'vertical', 'horizontal', or 'both' (default: 'vertical') */ axis?: "vertical" | "horizontal" | "both"; /** Optional ref to use instead of creating a new one */ ref?: RefObject; } interface UseSyncScrollOptions extends BaseScrollOptions { /** Unique identifier for this scrollable element */ id?: string; /** Role: 'master' (controls others), 'slave' (controlled by master), 'drag' (like master but for drag interactions) */ role?: ScrollRole; } /** * Base hook for synchronized scrolling functionality. * Internal use - prefer useScroll, useScrollSlave, or useSyncDrag instead. */ function useSyncScrollBase({ id: providedId, role, enabled = true, axis = "vertical", ref: providedRef, }: UseSyncScrollOptions & { role: ScrollRole }) { const context = useContext(SyncScrollContext); const autoId = useId(); const id = providedId || autoId; const internalRef = useRef(null); const elementRef = providedRef || internalRef; const lastScrollTop = useRef(0); const lastScrollLeft = useRef(0); if (!context) { throw new Error("Sync scroll hooks must be used within a SyncScrollProvider"); } const { registerScrollable, unregisterScrollable, syncScroll } = context; useEffect(() => { if (!enabled || !elementRef.current) return; const element = elementRef.current; // Register this element with its role registerScrollable(id, elementRef as RefObject, role); const handleScroll = (e: Event) => { const target = e.target as HTMLElement; let hasChanged = false; if (axis === "vertical" || axis === "both") { if (target.scrollTop !== lastScrollTop.current) { lastScrollTop.current = target.scrollTop; hasChanged = true; } } if (axis === "horizontal" || axis === "both") { if (target.scrollLeft !== lastScrollLeft.current) { lastScrollLeft.current = target.scrollLeft; hasChanged = true; } } if (hasChanged) { syncScroll(id, lastScrollTop.current, lastScrollLeft.current); } }; element.addEventListener("scroll", handleScroll, { passive: true }); return () => { element.removeEventListener("scroll", handleScroll); unregisterScrollable(id); }; }, [id, role, enabled, axis, registerScrollable, unregisterScrollable, syncScroll, elementRef]); return elementRef; } /** * Hook for a master scroll element that controls all other elements. * * @example * ```tsx * function MasterPanel() { * const scrollRef = useSyncScroll(); * return
...
; * } * ``` */ export function useSyncScroll(options: BaseScrollOptions = {}) { return useSyncScrollBase({ ...options, role: "master" }); } /** * Hook for a slave scroll element that is controlled by masters. * Slaves can sync with other slaves but cannot control masters. * * @example * ```tsx * function SlavePanel() { * const scrollRef = useScrollSlave(); * return
...
; * } * ``` */ export function useScrollSlave(options: BaseScrollOptions = {}) { return useSyncScrollBase({ ...options, role: "slave" }); } /** * Hook for drag-controlled scrolling that acts like a master. * Typically used with custom drag handlers. * * @example * ```tsx * function DragPanel() { * const scrollRef = useSyncDrag(); * // Add custom drag handling logic * return
...
; * } * ``` */ export function useSyncDrag(options: BaseScrollOptions = {}) { return useSyncScrollBase({ ...options, role: "drag" }); } // Export types export type { ScrollRole, UseSyncScrollOptions, BaseScrollOptions };