1"use client"
2
3import React, { useContext, useEffect, useRef, useState } from "react"
4import {
5 motion,
6 useAnimationFrame,
7 useMotionValue,
8 useScroll,
9 useSpring,
10 useTransform,
11 useVelocity,
12} from "motion/react"
13import type { MotionValue } from "motion/react"
14
15import { cn } from "@/lib/utils"
16
17interface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {
18 children: React.ReactNode
19 baseVelocity?: number
20 direction?: 1 | -1
21 scrollReactivity?: boolean
22}
23
24export const wrap = (min: number, max: number, v: number) => {
25 const rangeSize = max - min
26 return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min
27}
28
29const ScrollVelocityContext = React.createContext<MotionValue<number> | null>(
30 null
31)
32
33export function ScrollVelocityContainer({
34 children,
35 className,
36 ...props
37}: React.HTMLAttributes<HTMLDivElement>) {
38 const { scrollY } = useScroll()
39 const scrollVelocity = useVelocity(scrollY)
40 const smoothVelocity = useSpring(scrollVelocity, {
41 damping: 50,
42 stiffness: 400,
43 })
44 const velocityFactor = useTransform(smoothVelocity, (v) => {
45 const sign = v < 0 ? -1 : 1
46 const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)
47 return sign * magnitude
48 })
49
50 return (
51 <ScrollVelocityContext.Provider value={velocityFactor}>
52 <div className={cn("relative w-full", className)} {...props}>
53 {children}
54 </div>
55 </ScrollVelocityContext.Provider>
56 )
57}
58
59export function ScrollVelocityRow(props: ScrollVelocityRowProps) {
60 const sharedVelocityFactor = useContext(ScrollVelocityContext)
61 if (sharedVelocityFactor) {
62 return (
63 <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />
64 )
65 }
66 return <ScrollVelocityRowLocal {...props} />
67}
68
69interface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {
70 velocityFactor: MotionValue<number>
71}
72
73function ScrollVelocityRowImpl({
74 children,
75 baseVelocity = 5,
76 direction = 1,
77 className,
78 velocityFactor,
79 scrollReactivity = true,
80 ...props
81}: ScrollVelocityRowImplProps) {
82 const containerRef = useRef<HTMLDivElement>(null)
83 const blockRef = useRef<HTMLDivElement>(null)
84 const [numCopies, setNumCopies] = useState(1)
85
86 const baseX = useMotionValue(0)
87 const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)
88 const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1)
89 const unitWidth = useMotionValue(0)
90
91 const isInViewRef = useRef(true)
92 const isPageVisibleRef = useRef(true)
93 const prefersReducedMotionRef = useRef(false)
94
95 useEffect(() => {
96 const container = containerRef.current
97 const block = blockRef.current
98 let ro: ResizeObserver | null = null
99 let io: IntersectionObserver | null = null
100 let mq: MediaQueryList | null = null
101 const handleVisibility = () => {
102 isPageVisibleRef.current = document.visibilityState === "visible"
103 }
104 const handlePRM = () => {
105 if (mq) {
106 prefersReducedMotionRef.current = mq.matches
107 }
108 }
109
110 if (container && block) {
111 const updateSizes = () => {
112 const cw = container.offsetWidth || 0
113 const bw = block.scrollWidth || 0
114 unitWidth.set(bw)
115 const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1
116 setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies))
117 }
118
119 updateSizes()
120
121 ro = new ResizeObserver(updateSizes)
122 ro.observe(container)
123 ro.observe(block)
124
125 io = new IntersectionObserver(([entry]) => {
126 isInViewRef.current = entry.isIntersecting
127 })
128 io.observe(container)
129
130 document.addEventListener("visibilitychange", handleVisibility, {
131 passive: true,
132 })
133 handleVisibility()
134
135 mq = window.matchMedia("(prefers-reduced-motion: reduce)")
136 mq.addEventListener("change", handlePRM)
137 handlePRM()
138 }
139
140 return () => {
141 if (ro) {
142 ro.disconnect()
143 }
144 if (io) {
145 io.disconnect()
146 }
147 document.removeEventListener("visibilitychange", handleVisibility)
148 if (mq) {
149 mq.removeEventListener("change", handlePRM)
150 }
151 }
152 }, [children, unitWidth])
153
154 const x = useTransform([baseX, unitWidth], ([v, bw]) => {
155 const width = Number(bw) || 1
156 const offset = Number(v) || 0
157 return `${-wrap(0, width, offset)}px`
158 })
159
160 useAnimationFrame((_, delta) => {
161 if (!isInViewRef.current || !isPageVisibleRef.current) return
162 const dt = delta / 1000
163 const vf = scrollReactivity ? velocityFactor.get() : 0
164 const absVf = Math.min(5, Math.abs(vf))
165 const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf
166
167 if (absVf > 0.1) {
168 const scrollDirection = vf >= 0 ? 1 : -1
169 currentDirectionRef.current = baseDirectionRef.current * scrollDirection
170 }
171
172 const bw = unitWidth.get() || 0
173 if (bw <= 0) return
174 const pixelsPerSecond = (bw * baseVelocity) / 100
175 const moveBy =
176 currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt
177 baseX.set(baseX.get() + moveBy)
178 })
179
180 return (
181 <div
182 ref={containerRef}
183 className={cn("w-full overflow-hidden whitespace-nowrap", className)}
184 {...props}
185 >
186 <motion.div
187 className="inline-flex transform-gpu items-center will-change-transform select-none"
188 style={{ x }}
189 >
190 {Array.from({ length: numCopies }).map((_, i) => (
191 <div
192 key={i}
193 ref={i === 0 ? blockRef : null}
194 aria-hidden={i !== 0}
195 className="inline-flex shrink-0 items-center"
196 >
197 {children}
198 </div>
199 ))}
200 </motion.div>
201 </div>
202 )
203}
204
205function ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {
206 const { scrollY } = useScroll()
207 const localVelocity = useVelocity(scrollY)
208 const localSmoothVelocity = useSpring(localVelocity, {
209 damping: 50,
210 stiffness: 400,
211 })
212 const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {
213 const sign = v < 0 ? -1 : 1
214 const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5)
215 return sign * magnitude
216 })
217 return (
218 <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />
219 )
220}
221