1"use client";
2
3import { cva, type VariantProps } from "class-variance-authority";
4import {
5 ChevronDown,
6 ChevronLeft,
7 ChevronRight,
8 ChevronUp,
9} from "lucide-react";
10import { Slot as SlotPrimitive } from "radix-ui";
11import * as React from "react";
12import { useComposedRefs } from "@/lib/compose-refs";
13import { cn } from "@/lib/utils";
14
15const DATA_TOP_SCROLL = "data-top-scroll";
16const DATA_BOTTOM_SCROLL = "data-bottom-scroll";
17const DATA_LEFT_SCROLL = "data-left-scroll";
18const DATA_RIGHT_SCROLL = "data-right-scroll";
19const DATA_TOP_BOTTOM_SCROLL = "data-top-bottom-scroll";
20const DATA_LEFT_RIGHT_SCROLL = "data-left-right-scroll";
21
22const scrollerVariants = cva("", {
23 variants: {
24 orientation: {
25 vertical: [
26 "overflow-y-auto",
27 "data-[top-scroll=true]:[mask-image:linear-gradient(0deg,#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
28 "data-[bottom-scroll=true]:[mask-image:linear-gradient(180deg,#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
29 "data-[top-bottom-scroll=true]:[mask-image:linear-gradient(#000,#000,transparent_0,#000_var(--scroll-shadow-size),#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
30 ],
31 horizontal: [
32 "overflow-x-auto",
33 "data-[left-scroll=true]:[mask-image:linear-gradient(270deg,#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
34 "data-[right-scroll=true]:[mask-image:linear-gradient(90deg,#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
35 "data-[left-right-scroll=true]:[mask-image:linear-gradient(to_right,#000,#000,transparent_0,#000_var(--scroll-shadow-size),#000_calc(100%_-_var(--scroll-shadow-size)),transparent)]",
36 ],
37 },
38 hideScrollbar: {
39 true: "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
40 false: "",
41 },
42 },
43 defaultVariants: {
44 orientation: "vertical",
45 hideScrollbar: false,
46 },
47});
48
49type ScrollDirection = "up" | "down" | "left" | "right";
50
51type ScrollVisibility = {
52 [key in ScrollDirection]: boolean;
53};
54
55interface ScrollerProps
56 extends VariantProps<typeof scrollerVariants>,
57 React.ComponentProps<"div"> {
58 size?: number;
59 offset?: number;
60 asChild?: boolean;
61 withNavigation?: boolean;
62 scrollStep?: number;
63 scrollTriggerMode?: "press" | "hover" | "click";
64}
65
66function Scroller(props: ScrollerProps) {
67 const {
68 orientation = "vertical",
69 hideScrollbar,
70 className,
71 size = 40,
72 offset = 0,
73 scrollStep = 40,
74 style,
75 asChild,
76 withNavigation = false,
77 scrollTriggerMode = "press",
78 ref,
79 ...scrollerProps
80 } = props;
81
82 const containerRef = React.useRef<HTMLDivElement | null>(null);
83 const composedRef = useComposedRefs(ref, containerRef);
84 const [scrollVisibility, setScrollVisibility] =
85 React.useState<ScrollVisibility>({
86 up: false,
87 down: false,
88 left: false,
89 right: false,
90 });
91
92 const onScrollBy = React.useCallback(
93 (direction: ScrollDirection) => {
94 const container = containerRef.current;
95 if (!container) return;
96
97 const scrollMap: Record<ScrollDirection, () => void> = {
98 up: () => (container.scrollTop -= scrollStep),
99 down: () => (container.scrollTop += scrollStep),
100 left: () => (container.scrollLeft -= scrollStep),
101 right: () => (container.scrollLeft += scrollStep),
102 };
103
104 scrollMap[direction]();
105 },
106 [scrollStep],
107 );
108
109 const scrollHandlers = React.useMemo(
110 () => ({
111 up: () => onScrollBy("up"),
112 down: () => onScrollBy("down"),
113 left: () => onScrollBy("left"),
114 right: () => onScrollBy("right"),
115 }),
116 [onScrollBy],
117 );
118
119 React.useLayoutEffect(() => {
120 const container = containerRef.current;
121 if (!container) return;
122
123 function onScroll() {
124 if (!container) return;
125
126 const isVertical = orientation === "vertical";
127
128 if (isVertical) {
129 const scrollTop = container.scrollTop;
130 const clientHeight = container.clientHeight;
131 const scrollHeight = container.scrollHeight;
132
133 if (withNavigation) {
134 setScrollVisibility((prev) => {
135 const newUp = scrollTop > offset;
136 const newDown = scrollTop + clientHeight < scrollHeight;
137
138 if (prev.up !== newUp || prev.down !== newDown) {
139 return {
140 ...prev,
141 up: newUp,
142 down: newDown,
143 };
144 }
145 return prev;
146 });
147 }
148
149 const hasTopScroll = scrollTop > offset;
150 const hasBottomScroll =
151 scrollTop + clientHeight + offset < scrollHeight;
152 const isVerticallyScrollable = scrollHeight > clientHeight;
153
154 if (hasTopScroll && hasBottomScroll && isVerticallyScrollable) {
155 container.setAttribute(DATA_TOP_BOTTOM_SCROLL, "true");
156 container.removeAttribute(DATA_TOP_SCROLL);
157 container.removeAttribute(DATA_BOTTOM_SCROLL);
158 } else {
159 container.removeAttribute(DATA_TOP_BOTTOM_SCROLL);
160 if (hasTopScroll) container.setAttribute(DATA_TOP_SCROLL, "true");
161 else container.removeAttribute(DATA_TOP_SCROLL);
162 if (hasBottomScroll && isVerticallyScrollable)
163 container.setAttribute(DATA_BOTTOM_SCROLL, "true");
164 else container.removeAttribute(DATA_BOTTOM_SCROLL);
165 }
166 }
167
168 const scrollLeft = container.scrollLeft;
169 const clientWidth = container.clientWidth;
170 const scrollWidth = container.scrollWidth;
171
172 if (withNavigation) {
173 setScrollVisibility((prev) => {
174 const newLeft = scrollLeft > offset;
175 const newRight = scrollLeft + clientWidth < scrollWidth;
176
177 if (prev.left !== newLeft || prev.right !== newRight) {
178 return {
179 ...prev,
180 left: newLeft,
181 right: newRight,
182 };
183 }
184 return prev;
185 });
186 }
187
188 const hasLeftScroll = scrollLeft > offset;
189 const hasRightScroll = scrollLeft + clientWidth + offset < scrollWidth;
190 const isHorizontallyScrollable = scrollWidth > clientWidth;
191
192 if (hasLeftScroll && hasRightScroll && isHorizontallyScrollable) {
193 container.setAttribute(DATA_LEFT_RIGHT_SCROLL, "true");
194 container.removeAttribute(DATA_LEFT_SCROLL);
195 container.removeAttribute(DATA_RIGHT_SCROLL);
196 } else {
197 container.removeAttribute(DATA_LEFT_RIGHT_SCROLL);
198 if (hasLeftScroll) container.setAttribute(DATA_LEFT_SCROLL, "true");
199 else container.removeAttribute(DATA_LEFT_SCROLL);
200 if (hasRightScroll && isHorizontallyScrollable)
201 container.setAttribute(DATA_RIGHT_SCROLL, "true");
202 else container.removeAttribute(DATA_RIGHT_SCROLL);
203 }
204 }
205
206 onScroll();
207 container.addEventListener("scroll", onScroll);
208 window.addEventListener("resize", onScroll);
209
210 return () => {
211 container.removeEventListener("scroll", onScroll);
212 window.removeEventListener("resize", onScroll);
213 };
214 }, [orientation, offset, withNavigation]);
215
216 const composedStyle = React.useMemo<React.CSSProperties>(
217 () => ({
218 "--scroll-shadow-size": `${size}px`,
219 ...style,
220 }),
221 [size, style],
222 );
223
224 const activeDirections = React.useMemo<ScrollDirection[]>(() => {
225 if (!withNavigation) return [];
226 return orientation === "vertical" ? ["up", "down"] : ["left", "right"];
227 }, [orientation, withNavigation]);
228
229 const ScrollerPrimitive = asChild ? SlotPrimitive.Slot : "div";
230
231 const ScrollerImpl = (
232 <ScrollerPrimitive
233 data-slot="scroller"
234 {...scrollerProps}
235 ref={composedRef}
236 style={composedStyle}
237 className={cn(
238 scrollerVariants({ orientation, hideScrollbar, className }),
239 )}
240 />
241 );
242
243 const navigationButtons = React.useMemo(() => {
244 if (!withNavigation) return null;
245
246 return activeDirections
247 .filter((direction) => scrollVisibility[direction])
248 .map((direction) => (
249 <ScrollButton
250 key={direction}
251 data-slot="scroll-button"
252 direction={direction}
253 onClick={scrollHandlers[direction]}
254 triggerMode={scrollTriggerMode}
255 />
256 ));
257 }, [
258 activeDirections,
259 scrollVisibility,
260 scrollHandlers,
261 scrollTriggerMode,
262 withNavigation,
263 ]);
264
265 if (withNavigation) {
266 return (
267 <div className="relative w-full">
268 {navigationButtons}
269 {ScrollerImpl}
270 </div>
271 );
272 }
273
274 return ScrollerImpl;
275}
276
277const scrollButtonVariants = cva(
278 "absolute z-10 transition-opacity [&>svg]:size-4 [&>svg]:opacity-80 hover:[&>svg]:opacity-100",
279 {
280 variants: {
281 direction: {
282 up: "top-2 left-1/2 -translate-x-1/2",
283 down: "bottom-2 left-1/2 -translate-x-1/2",
284 left: "top-1/2 left-2 -translate-y-1/2",
285 right: "top-1/2 right-2 -translate-y-1/2",
286 },
287 },
288 defaultVariants: {
289 direction: "up",
290 },
291 },
292);
293
294const directionToIcon: Record<ScrollDirection, React.ElementType> = {
295 up: ChevronUp,
296 down: ChevronDown,
297 left: ChevronLeft,
298 right: ChevronRight,
299} as const;
300
301interface ScrollButtonProps extends React.ComponentProps<"button"> {
302 direction: ScrollDirection;
303 triggerMode?: "press" | "hover" | "click";
304}
305
306function ScrollButton(props: ScrollButtonProps) {
307 const {
308 direction,
309 className,
310 triggerMode = "press",
311 onClick,
312 ref,
313 ...buttonProps
314 } = props;
315
316 const [autoScrollTimer, setAutoScrollTimer] = React.useState<number | null>(
317 null,
318 );
319
320 const onAutoScrollStart = React.useCallback(
321 (event?: React.MouseEvent<HTMLButtonElement>) => {
322 if (autoScrollTimer !== null) return;
323
324 if (triggerMode === "press") {
325 const timer = window.setInterval(onClick ?? (() => {}), 50);
326 setAutoScrollTimer(timer);
327 } else if (triggerMode === "hover") {
328 const timer = window.setInterval(() => {
329 if (event) onClick?.(event);
330 }, 50);
331 setAutoScrollTimer(timer);
332 }
333 },
334 [autoScrollTimer, onClick, triggerMode],
335 );
336
337 const onAutoScrollStop = React.useCallback(() => {
338 if (autoScrollTimer === null) return;
339
340 window.clearInterval(autoScrollTimer);
341 setAutoScrollTimer(null);
342 }, [autoScrollTimer]);
343
344 const eventHandlers = React.useMemo(() => {
345 const triggerModeHandlers: Record<
346 NonNullable<ScrollerProps["scrollTriggerMode"]>,
347 React.ComponentProps<"button">
348 > = {
349 press: {
350 onPointerDown: onAutoScrollStart,
351 onPointerUp: onAutoScrollStop,
352 onPointerLeave: onAutoScrollStop,
353 onClick: () => {},
354 },
355 hover: {
356 onPointerEnter: onAutoScrollStart,
357 onPointerLeave: onAutoScrollStop,
358 onClick: () => {},
359 },
360 click: {
361 onClick,
362 },
363 } as const;
364
365 return triggerModeHandlers[triggerMode] ?? {};
366 }, [triggerMode, onAutoScrollStart, onAutoScrollStop, onClick]);
367
368 React.useEffect(() => {
369 return () => onAutoScrollStop();
370 }, [onAutoScrollStop]);
371
372 const Icon = directionToIcon[direction];
373
374 return (
375 <button
376 type="button"
377 {...buttonProps}
378 {...eventHandlers}
379 ref={ref}
380 className={cn(scrollButtonVariants({ direction, className }))}
381 >
382 <Icon />
383 </button>
384 );
385}
386
387export { Scroller };
388