1"use client";
2
3import { cva, type VariantProps } from "class-variance-authority";
4import { X } from "lucide-react";
5import { Slot as SlotPrimitive } from "radix-ui";
6import * as React from "react";
7import * as ReactDOM from "react-dom";
8import { cn } from "@/lib/utils";
9import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
10import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
11import { Button } from "@/registry/bases/radix/ui/button";
12
13const BANNER_ANIMATION_DURATION = 400;
14const DEFAULT_BANNER_PRIORITY = 0;
15const DEFAULT_BANNER_DISMISSIBLE = true;
16
17type BannerVariant = "default" | "info" | "success" | "warning" | "destructive";
18type BannerSide = "top" | "bottom";
19
20interface DivProps extends React.ComponentProps<"div"> {
21 asChild?: boolean;
22}
23
24type CloseElement = React.ComponentRef<typeof BannerClose>;
25
26interface BannerRenderProps {
27 id: string;
28 variant?: BannerVariant;
29 dismissible: boolean;
30 onClose: () => void;
31 onRemove: () => void;
32}
33
34type BannerContent =
35 | React.ReactNode
36 | ((props: BannerRenderProps) => React.ReactNode);
37
38interface BannerData {
39 id: string;
40 content: BannerContent;
41 variant?: BannerVariant;
42 priority?: number;
43 dismissible?: boolean;
44 duration?: number;
45 onDismiss?: () => void;
46}
47
48interface StoreState {
49 banners: BannerData[];
50 removing: Set<string>;
51 heights: Map<string, number>;
52}
53
54interface Store {
55 subscribe: (callback: () => void) => () => void;
56 getState: () => StoreState;
57 notify: () => void;
58 onBannerAdd: (banner: Omit<BannerData, "id">) => string;
59 onBannerRemove: (id: string) => void;
60 onBannersClear: () => void;
61 onRemovingChange: (id: string, value: boolean) => void;
62 onHeightChange: (id: string, height: number) => void;
63 onHeightRemove: (id: string) => void;
64}
65
66const StoreContext = React.createContext<Store | null>(null);
67
68function useStoreContext(consumerName: string) {
69 const context = React.useContext(StoreContext);
70 if (!context) {
71 throw new Error(`\`${consumerName}\` must be used within \`Banners\``);
72 }
73 return context;
74}
75
76function useStore<T>(store: Store, selector: (state: StoreState) => T): T {
77 return React.useSyncExternalStore(
78 store.subscribe,
79 () => selector(store.getState()),
80 () => selector(store.getState()),
81 );
82}
83
84interface BannerContextValue {
85 id?: string;
86 variant?: BannerVariant | null;
87 dismissible?: boolean;
88 onClose?: () => void;
89}
90
91const BannerContext = React.createContext<BannerContextValue | null>(null);
92
93function useBannerContext(consumerName: string) {
94 const context = React.useContext(BannerContext);
95 if (!context) {
96 throw new Error(`\`${consumerName}\` must be used within \`Banner\``);
97 }
98 return context;
99}
100
101function useBanner() {
102 const { id, variant, dismissible, onClose } = useBannerContext("useBanner");
103 const storeContext = React.useContext(StoreContext);
104
105 return React.useMemo(() => {
106 const onRemove =
107 id && storeContext ? () => storeContext.onBannerRemove(id) : undefined;
108
109 return {
110 id,
111 variant,
112 dismissible,
113 onClose,
114 onRemove,
115 };
116 }, [id, variant, dismissible, onClose, storeContext]);
117}
118
119interface BannersProps {
120 children?: React.ReactNode;
121 maxVisible?: number;
122 side?: BannerSide;
123 container?: Element | DocumentFragment | null;
124}
125
126function Banners(props: BannersProps) {
127 const {
128 children,
129 maxVisible = 1,
130 side = "top",
131 container: containerProp,
132 } = props;
133
134 const stateRef = useLazyRef<StoreState>(() => ({
135 banners: [],
136 removing: new Set(),
137 heights: new Map(),
138 }));
139 const listenersRef = useLazyRef<Set<() => void>>(() => new Set());
140 const timeoutsRef = useLazyRef<Map<string, ReturnType<typeof setTimeout>>>(
141 () => new Map(),
142 );
143
144 const store: Store = React.useMemo(
145 () => ({
146 subscribe: (cb) => {
147 listenersRef.current.add(cb);
148 return () => listenersRef.current.delete(cb);
149 },
150 getState: () => stateRef.current,
151 notify: () => {
152 for (const listener of listenersRef.current) {
153 listener();
154 }
155 },
156 onBannerAdd: (banner) => {
157 const id = crypto.randomUUID();
158 const newBanner: BannerData = { ...banner, id };
159 const priority = banner.priority ?? DEFAULT_BANNER_PRIORITY;
160
161 const banners = [...stateRef.current.banners];
162 const insertIndex = banners.findIndex(
163 (b) => (b.priority ?? DEFAULT_BANNER_PRIORITY) < priority,
164 );
165
166 if (insertIndex === -1) {
167 banners.push(newBanner);
168 } else {
169 banners.splice(insertIndex, 0, newBanner);
170 }
171
172 stateRef.current.banners = banners;
173 store.notify();
174
175 if (banner.duration && banner.duration > 0) {
176 const timeoutId = setTimeout(() => {
177 store.onRemovingChange(id, true);
178 timeoutsRef.current.delete(id);
179 }, banner.duration);
180 timeoutsRef.current.set(id, timeoutId);
181 }
182
183 return id;
184 },
185 onBannerRemove: (id) => {
186 const banner = stateRef.current.banners.find((b) => b.id === id);
187 if (!banner) return;
188
189 const timeoutId = timeoutsRef.current.get(id);
190 if (timeoutId) {
191 clearTimeout(timeoutId);
192 timeoutsRef.current.delete(id);
193 }
194
195 const newRemoving = new Set(stateRef.current.removing);
196 newRemoving.delete(id);
197 stateRef.current.removing = newRemoving;
198
199 banner.onDismiss?.();
200 stateRef.current.banners = stateRef.current.banners.filter(
201 (b) => b.id !== id,
202 );
203 store.notify();
204 },
205 onBannersClear: () => {
206 for (const timeoutId of timeoutsRef.current.values()) {
207 clearTimeout(timeoutId);
208 }
209 timeoutsRef.current.clear();
210 stateRef.current.removing = new Set();
211 stateRef.current.heights = new Map();
212 stateRef.current.banners = [];
213 store.notify();
214 },
215 onRemovingChange: (id, value) => {
216 const newSet = new Set(stateRef.current.removing);
217 if (value) {
218 newSet.add(id);
219 } else {
220 newSet.delete(id);
221 }
222 stateRef.current.removing = newSet;
223 store.notify();
224 },
225 onHeightChange: (id, height) => {
226 if (stateRef.current.heights.get(id) === height) return;
227 const newHeights = new Map(stateRef.current.heights);
228 newHeights.set(id, height);
229 stateRef.current.heights = newHeights;
230 store.notify();
231 },
232 onHeightRemove: (id) => {
233 if (!stateRef.current.heights.has(id)) return;
234 const newHeights = new Map(stateRef.current.heights);
235 newHeights.delete(id);
236 stateRef.current.heights = newHeights;
237 store.notify();
238 },
239 }),
240 [stateRef, listenersRef, timeoutsRef],
241 );
242
243 const banners = useStore(store, (state) => state.banners);
244 const heights = useStore(store, (state) => state.heights);
245 const visibleBanners = banners.slice(0, maxVisible);
246 const container = containerProp ?? globalThis.document?.body ?? null;
247
248 const totalHeight = React.useMemo(() => {
249 let total = 0;
250 for (const banner of visibleBanners) {
251 total += heights.get(banner.id) ?? 0;
252 }
253 return total;
254 }, [visibleBanners, heights]);
255
256 return (
257 <StoreContext.Provider value={store}>
258 {children}
259 {container &&
260 visibleBanners.length > 0 &&
261 ReactDOM.createPortal(
262 <div
263 data-slot="banner-container"
264 data-side={side}
265 className={cn(
266 "pointer-events-none fixed right-0 left-0 isolate z-50",
267 side === "top" ? "top-0" : "bottom-0",
268 )}
269 style={{
270 height: totalHeight > 0 ? totalHeight : "auto",
271 transition: `height ${BANNER_ANIMATION_DURATION}ms cubic-bezier(0.32, 0.72, 0, 1)`,
272 }}
273 >
274 {visibleBanners.map((banner, index) => (
275 <BannerImpl
276 key={banner.id}
277 banner={banner}
278 side={side}
279 index={index}
280 />
281 ))}
282 </div>,
283 container,
284 )}
285 </StoreContext.Provider>
286 );
287}
288
289function useBanners() {
290 const store = useStoreContext("useBanners");
291 const banners = useStore(store, (state) => state.banners);
292
293 return React.useMemo(
294 () => ({
295 onBannerAdd: store.onBannerAdd,
296 onBannerRemove: store.onBannerRemove,
297 onBannersClear: store.onBannersClear,
298 banners,
299 }),
300 [store, banners],
301 );
302}
303
304const bannerVariants = cva(
305 "pointer-events-auto relative flex w-full items-center gap-3 border-b px-4 py-3 text-sm motion-reduce:transition-none",
306 {
307 variants: {
308 variant: {
309 default: "bg-card text-card-foreground",
310 info: "bg-blue-50 text-blue-900 dark:bg-blue-950 dark:text-blue-50",
311 success:
312 "bg-green-50 text-green-900 dark:bg-green-950 dark:text-green-50",
313 warning:
314 "bg-yellow-50 text-yellow-900 dark:bg-yellow-950 dark:text-yellow-50",
315 destructive: "bg-red-50 text-red-900 dark:bg-red-950 dark:text-red-50",
316 },
317 },
318 defaultVariants: {
319 variant: "default",
320 },
321 },
322);
323
324interface BannerImplProps {
325 banner: BannerData;
326 side: BannerSide;
327 index: number;
328}
329
330function BannerImpl(props: BannerImplProps) {
331 const { banner, side, index } = props;
332
333 const store = useStoreContext("BannerImpl");
334 const removing = useStore(store, (state) => state.removing.has(banner.id));
335 const banners = useStore(store, (state) => state.banners);
336 const heights = useStore(store, (state) => state.heights);
337
338 const [mounted, setMounted] = React.useState(false);
339 const bannerRef = React.useRef<HTMLDivElement>(null);
340 const offsetBeforeRemoveRef = React.useRef(0);
341
342 const offset = React.useMemo(() => {
343 let total = 0;
344 for (const b of banners) {
345 if (b.id === banner.id) break;
346 total += heights.get(b.id) ?? 0;
347 }
348 return total;
349 }, [banners, heights, banner.id]);
350
351 if (!removing) {
352 offsetBeforeRemoveRef.current = offset;
353 }
354
355 React.useEffect(() => {
356 const frame = requestAnimationFrame(() => setMounted(true));
357 return () => cancelAnimationFrame(frame);
358 }, []);
359
360 React.useLayoutEffect(() => {
361 if (!bannerRef.current || removing) return;
362 const height = bannerRef.current.getBoundingClientRect().height;
363 store.onHeightChange(banner.id, height);
364 }, [store, banner.id, removing]);
365
366 React.useEffect(() => {
367 if (!removing) return;
368 store.onHeightRemove(banner.id);
369 const timeoutId = setTimeout(
370 () => store.onBannerRemove(banner.id),
371 BANNER_ANIMATION_DURATION,
372 );
373 return () => clearTimeout(timeoutId);
374 }, [removing, store, banner.id]);
375
376 const onClose = React.useCallback(
377 () => store.onRemovingChange(banner.id, true),
378 [store, banner.id],
379 );
380
381 const onRemove = React.useCallback(
382 () => store.onBannerRemove(banner.id),
383 [store, banner.id],
384 );
385
386 const dismissible = banner.dismissible ?? DEFAULT_BANNER_DISMISSIBLE;
387
388 const contextValue = React.useMemo<BannerContextValue>(
389 () => ({ id: banner.id, variant: banner.variant, dismissible, onClose }),
390 [banner.id, banner.variant, dismissible, onClose],
391 );
392
393 const renderProps = React.useMemo<BannerRenderProps>(
394 () => ({
395 id: banner.id,
396 variant: banner.variant,
397 dismissible,
398 onClose,
399 onRemove,
400 }),
401 [banner.id, banner.variant, dismissible, onClose, onRemove],
402 );
403
404 const currentOffset = removing ? offsetBeforeRemoveRef.current : offset;
405 const isTop = side === "top";
406
407 function getTransform() {
408 if (!mounted) return isTop ? "translateY(-100%)" : "translateY(100%)";
409 if (removing) {
410 return isTop
411 ? `translateY(calc(${currentOffset}px - 100%))`
412 : `translateY(calc(-${currentOffset}px + 100%))`;
413 }
414 return isTop
415 ? `translateY(${currentOffset}px)`
416 : `translateY(-${currentOffset}px)`;
417 }
418
419 return (
420 <BannerContext.Provider value={contextValue}>
421 <div
422 role="status"
423 aria-live="polite"
424 data-slot="queued-banner"
425 data-state={removing ? "closed" : "open"}
426 data-mounted={mounted}
427 data-removed={removing}
428 data-side={side}
429 data-front={index === 0}
430 data-index={index}
431 ref={bannerRef}
432 className={bannerVariants({ variant: banner.variant })}
433 style={{
434 position: "absolute",
435 [isTop ? "top" : "bottom"]: 0,
436 left: 0,
437 right: 0,
438 zIndex: removing ? 0 : 50 - index,
439 transform: getTransform(),
440 opacity: mounted && !removing ? 1 : 0,
441 transition: `transform ${BANNER_ANIMATION_DURATION}ms cubic-bezier(0.32, 0.72, 0, 1), opacity ${removing ? BANNER_ANIMATION_DURATION / 2 : BANNER_ANIMATION_DURATION}ms ease`,
442 }}
443 >
444 {typeof banner.content === "function"
445 ? banner.content(renderProps)
446 : banner.content}
447 </div>
448 </BannerContext.Provider>
449 );
450}
451
452interface BannerProps extends DivProps, VariantProps<typeof bannerVariants> {
453 open?: boolean;
454 defaultOpen?: boolean;
455 onOpenChange?: (open: boolean) => void;
456 onDismiss?: () => void;
457 priority?: number;
458 dismissible?: boolean;
459 duration?: number;
460}
461
462function Banner(props: BannerProps) {
463 const {
464 className,
465 variant = "default",
466 open: openProp,
467 defaultOpen,
468 onOpenChange,
469 onDismiss,
470 priority,
471 dismissible = DEFAULT_BANNER_DISMISSIBLE,
472 duration,
473 children,
474 asChild,
475 ...rootProps
476 } = props;
477
478 const store = React.useContext(StoreContext);
479
480 const isInsideStore = store !== null;
481 const isControlled = openProp !== undefined;
482
483 const openRef = useLazyRef(() => openProp ?? defaultOpen ?? true);
484 const listenersRef = useLazyRef<Set<() => void>>(() => new Set());
485 const bannerIdRef = React.useRef<string | null>(null);
486 const onDismissRef = useAsRef(onDismiss);
487 const onOpenChangeRef = useAsRef(onOpenChange);
488
489 if (isControlled) {
490 openRef.current = openProp;
491 }
492
493 const subscribe = React.useCallback(
494 (cb: () => void) => {
495 listenersRef.current.add(cb);
496 return () => listenersRef.current.delete(cb);
497 },
498 [listenersRef],
499 );
500
501 const getSnapshot = React.useCallback(() => openRef.current, [openRef]);
502
503 const open = React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
504
505 React.useEffect(() => {
506 if (!isInsideStore || !store || !open) return;
507
508 const id = store.onBannerAdd({
509 content: children,
510 variant: variant ?? undefined,
511 priority,
512 dismissible,
513 duration,
514 onDismiss: () => {
515 onDismissRef.current?.();
516 onOpenChangeRef.current?.(false);
517 },
518 });
519 bannerIdRef.current = id;
520
521 return () => {
522 if (bannerIdRef.current) {
523 store.onBannerRemove(bannerIdRef.current);
524 bannerIdRef.current = null;
525 }
526 };
527 }, [
528 isInsideStore,
529 store,
530 open,
531 children,
532 variant,
533 priority,
534 dismissible,
535 duration,
536 onDismissRef,
537 onOpenChangeRef,
538 ]);
539
540 const onClose = React.useCallback(() => {
541 if (!isControlled) {
542 openRef.current = false;
543 for (const listener of listenersRef.current) {
544 listener();
545 }
546 }
547 onOpenChangeRef.current?.(false);
548 }, [isControlled, openRef, listenersRef, onOpenChangeRef]);
549
550 const contextValue = React.useMemo<BannerContextValue>(
551 () => ({
552 variant,
553 dismissible,
554 onClose,
555 }),
556 [variant, dismissible, onClose],
557 );
558
559 if (!open || isInsideStore) return null;
560
561 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
562
563 return (
564 <BannerContext.Provider value={contextValue}>
565 <RootPrimitive
566 role="status"
567 aria-live="polite"
568 data-slot="banner"
569 data-state="open"
570 className={cn(bannerVariants({ variant, className }))}
571 {...rootProps}
572 >
573 {children}
574 </RootPrimitive>
575 </BannerContext.Provider>
576 );
577}
578
579function BannerIcon(props: DivProps) {
580 const { className, asChild, ...iconProps } = props;
581
582 const IconPrimitive = asChild ? SlotPrimitive.Slot : "div";
583
584 return (
585 <IconPrimitive
586 data-slot="banner-icon"
587 className={cn("flex shrink-0 items-center [&>svg]:size-4", className)}
588 {...iconProps}
589 />
590 );
591}
592
593function BannerContent(props: DivProps) {
594 const { className, asChild, ...contentProps } = props;
595
596 const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
597
598 return (
599 <ContentPrimitive
600 data-slot="banner-content"
601 className={cn("flex min-w-0 flex-1 flex-col gap-1", className)}
602 {...contentProps}
603 />
604 );
605}
606
607function BannerTitle(props: React.ComponentProps<"div">) {
608 const { className, ...titleProps } = props;
609
610 return (
611 <div
612 data-slot="banner-title"
613 className={cn("font-medium text-sm leading-none", className)}
614 {...titleProps}
615 />
616 );
617}
618
619function BannerDescription(props: React.ComponentProps<"div">) {
620 const { className, ...descriptionProps } = props;
621
622 return (
623 <div
624 data-slot="banner-description"
625 className={cn("text-xs opacity-90", className)}
626 {...descriptionProps}
627 />
628 );
629}
630
631function BannerActions(props: DivProps) {
632 const { className, asChild, ...actionsProps } = props;
633
634 const ActionsPrimitive = asChild ? SlotPrimitive.Slot : "div";
635
636 return (
637 <ActionsPrimitive
638 data-slot="banner-actions"
639 className={cn("flex items-center gap-2", className)}
640 {...actionsProps}
641 />
642 );
643}
644
645function BannerClose(props: React.ComponentProps<typeof Button>) {
646 const { onClick: onClickProp, disabled, children, ...closeProps } = props;
647
648 const { dismissible = DEFAULT_BANNER_DISMISSIBLE, onClose } =
649 useBannerContext("BannerClose");
650
651 const isDisabled = disabled ?? !dismissible;
652
653 const onClick = React.useCallback(
654 (event: React.MouseEvent<CloseElement>) => {
655 onClickProp?.(event);
656 if (event.defaultPrevented || isDisabled) return;
657 onClose?.();
658 },
659 [onClickProp, isDisabled, onClose],
660 );
661
662 return (
663 <Button
664 data-slot="banner-close"
665 variant="ghost"
666 size="icon-sm"
667 onClick={onClick}
668 disabled={isDisabled}
669 {...closeProps}
670 >
671 {children ?? <X className="size-3.5" />}
672 </Button>
673 );
674}
675
676export {
677 Banner,
678 BannerActions,
679 BannerClose,
680 BannerContent,
681 BannerDescription,
682 BannerIcon,
683 Banners,
684 BannerTitle,
685 useBanner,
686 useBanners,
687};
688