1"use client";
2
3import { cva, type VariantProps } from "class-variance-authority";
4import {
5 Direction as DirectionPrimitive,
6 Slot as SlotPrimitive,
7} from "radix-ui";
8import * as React from "react";
9import { useComposedRefs } from "@/lib/compose-refs";
10import { cn } from "@/lib/utils";
11
12const ROOT_NAME = "Marquee";
13const CONTENT_NAME = "MarqueeContent";
14
15type Side = "left" | "right" | "top" | "bottom";
16type Orientation = "horizontal" | "vertical";
17type Direction = "ltr" | "rtl";
18
19type RootElement = React.ComponentRef<typeof Marquee>;
20type ContentElement = React.ComponentRef<typeof MarqueeContent>;
21
22interface Dimensions {
23 width: number;
24 height: number;
25}
26
27interface ElementDimensions {
28 rootSize: number;
29 contentSize: number;
30}
31
32function createResizeObserverStore() {
33 const listeners = new Set<() => void>();
34 let observer: ResizeObserver | null = null;
35 const elements = new Map<Element, Dimensions>();
36 const refCounts = new Map<Element, number>();
37 const isSupported = typeof ResizeObserver !== "undefined";
38 let notificationScheduled = false;
39
40 const snapshotCache = new WeakMap<
41 Element,
42 WeakMap<
43 Element,
44 { horizontal: ElementDimensions; vertical: ElementDimensions }
45 >
46 >();
47
48 function notify() {
49 if (notificationScheduled) return;
50 notificationScheduled = true;
51 queueMicrotask(() => {
52 notificationScheduled = false;
53 for (const callback of listeners) {
54 callback();
55 }
56 });
57 }
58
59 function cleanup() {
60 if (observer) {
61 observer.disconnect();
62 observer = null;
63 }
64 elements.clear();
65 refCounts.clear();
66 }
67
68 function subscribe(callback: () => void) {
69 listeners.add(callback);
70 return () => {
71 listeners.delete(callback);
72 if (listeners.size === 0) {
73 cleanup();
74 }
75 };
76 }
77
78 function getSnapshot(
79 rootElement: RootElement | null,
80 contentElement: ContentElement | null,
81 orientation: Orientation,
82 ): ElementDimensions | null {
83 if (!rootElement || !contentElement) return null;
84
85 const rootDims = elements.get(rootElement);
86 const contentDims = elements.get(contentElement);
87
88 if (!rootDims || !contentDims) return null;
89
90 const rootSize =
91 orientation === "vertical" ? rootDims.height : rootDims.width;
92 const contentSize =
93 orientation === "vertical" ? contentDims.height : contentDims.width;
94
95 let rootCache = snapshotCache.get(rootElement);
96 if (!rootCache) {
97 rootCache = new WeakMap();
98 snapshotCache.set(rootElement, rootCache);
99 }
100
101 let contentCache = rootCache.get(contentElement);
102 if (!contentCache) {
103 contentCache = {
104 horizontal: { rootSize: -1, contentSize: -1 },
105 vertical: { rootSize: -1, contentSize: -1 },
106 };
107 rootCache.set(contentElement, contentCache);
108 }
109
110 const cached = contentCache[orientation];
111 if (cached.rootSize === rootSize && cached.contentSize === contentSize) {
112 return cached;
113 }
114
115 const snapshot = { rootSize, contentSize };
116 contentCache[orientation] = snapshot;
117 return snapshot;
118 }
119
120 function observe(
121 rootElement: RootElement | null,
122 contentElement: Element | null,
123 ) {
124 if (!isSupported || !rootElement || !contentElement) return;
125
126 if (!observer) {
127 observer = new ResizeObserver((entries) => {
128 let hasChanged = false;
129
130 for (const entry of entries) {
131 const element = entry.target;
132 const { width, height } = entry.contentRect;
133
134 const currentData = elements.get(element);
135
136 if (
137 !currentData ||
138 currentData.width !== width ||
139 currentData.height !== height
140 ) {
141 elements.set(element, { width, height });
142 hasChanged = true;
143 }
144 }
145
146 if (hasChanged) {
147 notify();
148 }
149 });
150 }
151
152 refCounts.set(rootElement, (refCounts.get(rootElement) ?? 0) + 1);
153 refCounts.set(contentElement, (refCounts.get(contentElement) ?? 0) + 1);
154
155 observer.observe(rootElement);
156 observer.observe(contentElement);
157
158 const rootRect = rootElement.getBoundingClientRect();
159 const contentRect = contentElement.getBoundingClientRect();
160
161 const rootData = { width: rootRect.width, height: rootRect.height };
162 const contentData = {
163 width: contentRect.width,
164 height: contentRect.height,
165 };
166
167 elements.set(rootElement, rootData);
168 elements.set(contentElement, contentData);
169
170 if (
171 rootData.width > 0 &&
172 rootData.height > 0 &&
173 contentData.width > 0 &&
174 contentData.height > 0
175 ) {
176 notify();
177 }
178 }
179
180 function unobserve(
181 rootElement: RootElement | null,
182 contentElement: Element | null,
183 ) {
184 if (!observer || !rootElement || !contentElement) return;
185
186 const rootCount = (refCounts.get(rootElement) ?? 1) - 1;
187 const contentCount = (refCounts.get(contentElement) ?? 1) - 1;
188
189 if (rootCount <= 0) {
190 observer.unobserve(rootElement);
191 elements.delete(rootElement);
192 refCounts.delete(rootElement);
193 } else {
194 refCounts.set(rootElement, rootCount);
195 }
196
197 if (contentCount <= 0) {
198 observer.unobserve(contentElement);
199 elements.delete(contentElement);
200 refCounts.delete(contentElement);
201 } else {
202 refCounts.set(contentElement, contentCount);
203 }
204 }
205
206 return {
207 subscribe,
208 getSnapshot,
209 observe,
210 unobserve,
211 };
212}
213
214const resizeObserverStore = createResizeObserverStore();
215
216function useResizeObserverStore(
217 rootRef: React.RefObject<RootElement | null>,
218 contentRef: React.RefObject<ContentElement | null>,
219 orientation: Orientation,
220) {
221 const onSubscribe = React.useCallback(
222 (callback: () => void) => resizeObserverStore.subscribe(callback),
223 [],
224 );
225
226 const getSnapshot = React.useCallback(
227 () =>
228 resizeObserverStore.getSnapshot(
229 rootRef.current,
230 contentRef.current,
231 orientation,
232 ),
233 [rootRef, contentRef, orientation],
234 );
235
236 return React.useSyncExternalStore(onSubscribe, getSnapshot, getSnapshot);
237}
238
239interface DivProps extends React.ComponentProps<"div"> {
240 asChild?: boolean;
241}
242
243interface MarqueeContextValue {
244 side: Side;
245 orientation: Orientation;
246 dir: Direction;
247 speed: number;
248 loopCount: number;
249 contentRef: React.RefObject<ContentElement | null>;
250 rootRef: React.RefObject<RootElement | null>;
251 autoFill: boolean;
252 pauseOnHover: boolean;
253 pauseOnKeyboard: boolean;
254 reverse: boolean;
255 paused: boolean;
256}
257
258const MarqueeContext = React.createContext<MarqueeContextValue | null>(null);
259
260function useMarqueeContext(consumerName: string) {
261 const context = React.useContext(MarqueeContext);
262 if (!context) {
263 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
264 }
265 return context;
266}
267
268interface MarqueeProps extends DivProps {
269 side?: Side;
270 dir?: Direction;
271 speed?: number;
272 delay?: number;
273 loopCount?: number;
274 gap?: string | number;
275 autoFill?: boolean;
276 pauseOnHover?: boolean;
277 pauseOnKeyboard?: boolean;
278 reverse?: boolean;
279}
280
281function Marquee(props: MarqueeProps) {
282 const {
283 side = "left",
284 dir: dirProp,
285 speed = 50,
286 delay = 0,
287 loopCount = 0,
288 gap = "1rem",
289 asChild,
290 autoFill = false,
291 pauseOnHover = false,
292 pauseOnKeyboard = false,
293 reverse = false,
294 className,
295 style: styleProp,
296 ref,
297 ...marqueeProps
298 } = props;
299
300 const orientation: Orientation =
301 side === "top" || side === "bottom" ? "vertical" : "horizontal";
302
303 const dir = DirectionPrimitive.useDirection(dirProp);
304
305 const rootRef = React.useRef<RootElement>(null);
306 const contentRef = React.useRef<ContentElement>(null);
307 const composedRef = useComposedRefs(ref, rootRef);
308
309 const [paused, setPaused] = React.useState(false);
310
311 const onKeyDown = React.useCallback(
312 (event: React.KeyboardEvent) => {
313 if (pauseOnKeyboard && event.key === " ") {
314 event.preventDefault();
315 setPaused((prev) => !prev);
316 }
317 },
318 [pauseOnKeyboard],
319 );
320
321 const dimensions = useResizeObserverStore(rootRef, contentRef, orientation);
322
323 const duration = React.useMemo(() => {
324 const safeSpeed = Math.max(0.001, speed);
325
326 if (!dimensions) {
327 const defaultDistance = autoFill ? 1000 : 2000;
328 return defaultDistance / safeSpeed;
329 }
330
331 const { rootSize, contentSize } = dimensions;
332
333 if (autoFill) {
334 const multiplier =
335 contentSize < rootSize ? Math.ceil(rootSize / contentSize) : 1;
336 return (contentSize * multiplier) / safeSpeed;
337 } else {
338 return contentSize < rootSize
339 ? rootSize / safeSpeed
340 : contentSize / safeSpeed;
341 }
342 }, [dimensions, speed, autoFill]);
343
344 const style = React.useMemo<React.CSSProperties>(
345 () => ({
346 "--marquee-duration": `${duration}s`,
347 "--marquee-gap": gap,
348 "--marquee-delay": `${delay}s`,
349 "--marquee-loop-count":
350 loopCount === 0 || loopCount === Infinity
351 ? "infinite"
352 : loopCount.toString(),
353 ...styleProp,
354 }),
355 [duration, gap, delay, loopCount, styleProp],
356 );
357
358 const contextValue = React.useMemo<MarqueeContextValue>(
359 () => ({
360 side,
361 orientation,
362 dir,
363 speed,
364 loopCount,
365 contentRef,
366 rootRef,
367 autoFill,
368 paused,
369 pauseOnHover,
370 pauseOnKeyboard,
371 reverse,
372 }),
373 [
374 side,
375 orientation,
376 dir,
377 speed,
378 loopCount,
379 autoFill,
380 paused,
381 pauseOnHover,
382 pauseOnKeyboard,
383 reverse,
384 ],
385 );
386
387 const MarqueePrimitive = asChild ? SlotPrimitive.Slot : "div";
388
389 return (
390 <MarqueeContext.Provider value={contextValue}>
391 <div data-slot="marquee-wrapper" className="grid">
392 <MarqueePrimitive
393 role="marquee"
394 aria-live="off"
395 data-orientation={orientation}
396 data-slot="marquee"
397 dir={dir}
398 tabIndex={pauseOnKeyboard ? 0 : undefined}
399 {...marqueeProps}
400 ref={composedRef}
401 className={cn(
402 "relative flex overflow-hidden motion-reduce:animate-none",
403 orientation === "vertical" && "h-full flex-col",
404 orientation === "horizontal" && "w-full",
405 paused && "[&_*]:[animation-play-state:paused]",
406 pauseOnHover && "group",
407 pauseOnKeyboard &&
408 "rounded-md focus-visible:border-ring focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
409 className,
410 )}
411 style={style}
412 onKeyDown={pauseOnKeyboard ? onKeyDown : undefined}
413 />
414 </div>
415 </MarqueeContext.Provider>
416 );
417}
418
419const marqueeContentVariants = cva(
420 "flex min-w-full shrink-0 gap-(--marquee-gap)",
421 {
422 variants: {
423 side: {
424 left: "animate-marquee-left",
425 right: "animate-marquee-right",
426 top: "min-h-full min-w-auto animate-marquee-up flex-col",
427 bottom: "min-h-full min-w-auto animate-marquee-down flex-col",
428 },
429 dir: {
430 ltr: "",
431 rtl: "",
432 },
433 pauseOnHover: {
434 true: "group-hover:[animation-play-state:paused]",
435 false: "",
436 },
437 reverse: {
438 true: "[animation-direction:reverse]",
439 false: "",
440 },
441 },
442 compoundVariants: [
443 {
444 side: "left",
445 dir: "rtl",
446 className: "animate-marquee-left-rtl",
447 },
448 {
449 side: "right",
450 dir: "rtl",
451 className: "animate-marquee-right-rtl",
452 },
453 ],
454 defaultVariants: {
455 side: "left",
456 dir: "ltr",
457 pauseOnHover: false,
458 reverse: false,
459 },
460 },
461);
462
463function MarqueeContent(props: DivProps) {
464 const {
465 className,
466 asChild,
467 ref,
468 children,
469 style: styleProp,
470 ...contentProps
471 } = props;
472
473 const context = useMarqueeContext(CONTENT_NAME);
474 const composedRef = useComposedRefs(ref, context.contentRef);
475
476 const isVertical = context.orientation === "vertical";
477 const isRtl = context.dir === "rtl";
478
479 const dimensions = useResizeObserverStore(
480 context.rootRef,
481 context.contentRef,
482 context.orientation,
483 );
484
485 React.useEffect(() => {
486 if (context.rootRef.current && context.contentRef.current) {
487 resizeObserverStore.observe(
488 context.rootRef.current,
489 context.contentRef.current,
490 );
491
492 return () => {
493 resizeObserverStore.unobserve(
494 context.rootRef.current,
495 context.contentRef.current,
496 );
497 };
498 }
499 }, [context.rootRef, context.contentRef]);
500
501 const multiplier = React.useMemo(() => {
502 if (!context.autoFill || !dimensions) return 1;
503
504 const { rootSize, contentSize } = dimensions;
505 if (contentSize === 0) return 1;
506
507 return contentSize < rootSize ? Math.ceil(rootSize / contentSize) : 1;
508 }, [context.autoFill, dimensions]);
509
510 const onMultipliedChildrenRender = React.useCallback(
511 (count: number) => {
512 return Array.from({ length: Math.max(0, count) }).map((_, i) => (
513 <React.Fragment key={i}>{children}</React.Fragment>
514 ));
515 },
516 [children],
517 );
518
519 const style = React.useMemo(
520 () => ({
521 ...styleProp,
522 animationDuration: "var(--marquee-duration)",
523 animationDelay: "var(--marquee-delay)",
524 animationIterationCount: "var(--marquee-loop-count)",
525 animationDirection: context.reverse ? "reverse" : "normal",
526 }),
527 [styleProp, context.reverse],
528 );
529
530 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
531
532 return (
533 <>
534 <ContentPrimitive
535 data-orientation={context.orientation}
536 data-slot="marquee-content"
537 {...contentProps}
538 style={style}
539 className={cn(
540 marqueeContentVariants({
541 side: context.side,
542 dir: context.dir,
543 pauseOnHover: context.pauseOnHover,
544 reverse: context.reverse,
545 className,
546 }),
547 isVertical && "flex-col",
548 isVertical
549 ? "mb-(--marquee-gap)"
550 : isRtl
551 ? "ml-(--marquee-gap)"
552 : "mr-(--marquee-gap)",
553 )}
554 >
555 <div
556 ref={composedRef}
557 className={cn(
558 "flex shrink-0 gap-(--marquee-gap)",
559 isVertical && "flex-col",
560 )}
561 >
562 {children}
563 </div>
564 {onMultipliedChildrenRender(multiplier - 1)}
565 </ContentPrimitive>
566 <ContentPrimitive
567 role="presentation"
568 aria-hidden="true"
569 {...contentProps}
570 style={style}
571 className={cn(
572 marqueeContentVariants({
573 side: context.side,
574 dir: context.dir,
575 pauseOnHover: context.pauseOnHover,
576 reverse: context.reverse,
577 className,
578 }),
579 isVertical && "flex-col",
580 )}
581 >
582 {onMultipliedChildrenRender(multiplier)}
583 </ContentPrimitive>
584 </>
585 );
586}
587
588function MarqueeItem(props: DivProps) {
589 const { className, asChild, ...itemProps } = props;
590
591 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
592
593 return (
594 <ItemPrimitive
595 data-slot="marquee-item"
596 {...itemProps}
597 className={cn("shrink-0", className)}
598 />
599 );
600}
601
602const marqueeEdgeVariants = cva("pointer-events-none absolute z-10", {
603 variants: {
604 side: {
605 left: "top-0 left-0 h-full bg-gradient-to-r from-background to-transparent",
606 right:
607 "top-0 right-0 h-full bg-gradient-to-l from-background to-transparent",
608 top: "top-0 left-0 w-full bg-gradient-to-b from-background to-transparent",
609 bottom:
610 "bottom-0 left-0 w-full bg-gradient-to-t from-background to-transparent",
611 },
612 size: {
613 default: "",
614 sm: "",
615 lg: "",
616 },
617 },
618 compoundVariants: [
619 {
620 side: ["left", "right"],
621 size: "default",
622 className: "w-1/4",
623 },
624 {
625 side: ["left", "right"],
626 size: "sm",
627 className: "w-1/6",
628 },
629 {
630 side: ["left", "right"],
631 size: "lg",
632 className: "w-1/3",
633 },
634 {
635 side: ["top", "bottom"],
636 size: "default",
637 className: "h-1/4",
638 },
639 {
640 side: ["top", "bottom"],
641 size: "sm",
642 className: "h-1/6",
643 },
644 {
645 side: ["top", "bottom"],
646 size: "lg",
647 className: "h-1/3",
648 },
649 ],
650 defaultVariants: {
651 size: "default",
652 },
653});
654
655interface MarqueeEdgeProps
656 extends VariantProps<typeof marqueeEdgeVariants>,
657 DivProps {}
658
659function MarqueeEdge(props: MarqueeEdgeProps) {
660 const { side, size, className, asChild, ...edgeProps } = props;
661
662 const EdgePrimitive = asChild ? SlotPrimitive.Slot : "div";
663
664 return (
665 <EdgePrimitive
666 data-size={size}
667 data-slot="marquee-edge"
668 {...edgeProps}
669 className={cn(marqueeEdgeVariants({ side, size, className }))}
670 />
671 );
672}
673
674export { Marquee, MarqueeContent, MarqueeEdge, MarqueeItem, type MarqueeProps };
675