UNPKG

@faceless-ui/slider

Version:

A React library for building every kind of slider

49 lines 1.85 kB
import { useCallback, useEffect, useRef } from "react"; export const useMarquee = (args) => { const { sliderTrackRef, isFullyScrolled, enable, isPaused, marqueeSpeed // NOTE: this is technically a requested frame rate } = args; const animationRef = useRef(undefined); const prevTimestamp = useRef(undefined); const timeSincePrev = useRef(0); const scroll = useCallback((timestamp) => { if (enable && !isPaused) { const elapsed = prevTimestamp.current ? timestamp - prevTimestamp.current : 0; prevTimestamp.current = timestamp; timeSincePrev.current += elapsed; if (!marqueeSpeed || (marqueeSpeed && timeSincePrev.current > marqueeSpeed)) { if (sliderTrackRef.current) { if (!isFullyScrolled) sliderTrackRef.current.scrollLeft = sliderTrackRef.current.scrollLeft + 1; else sliderTrackRef.current.scrollLeft = 0; } timeSincePrev.current = 0; } // NOTE: recursively request animation to create a loop at ~60fps animationRef.current = window.requestAnimationFrame(scroll); } }, [ sliderTrackRef, enable, isPaused, marqueeSpeed, isFullyScrolled ]); useEffect(() => { if (enable && !isPaused) animationRef.current = window.requestAnimationFrame(scroll); if (isPaused && animationRef.current) cancelAnimationFrame(animationRef.current); return () => { if (animationRef.current) { cancelAnimationFrame(animationRef.current); } }; }, [ scroll, enable, isPaused ]); return null; }; //# sourceMappingURL=useMarquee.js.map