Open History to see the last commit
1import { mergeProps } from "@base-ui/react/merge-props";
2import { useRender } from "@base-ui/react/use-render";
3import { cva, type VariantProps } from "class-variance-authority";
4import { PanelLeftCloseIcon, PanelLeftIcon } from "lucide-react";
5import * as React from "react";
6import { cn } from "~/lib/utils";
7import { Button } from "~/components/ui/button";
8import { Input } from "~/components/ui/input";
9import { ScrollArea } from "~/components/ui/scroll-area";
10import { Separator } from "~/components/ui/separator";
11import {
12 Sheet,
13 SheetDescription,
14 SheetHeader,
15 SheetPopup,
16 SheetTitle,
17} from "~/components/ui/sheet";
18import { Skeleton } from "~/components/ui/skeleton";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
20import { useIsMobile } from "~/hooks/useMediaQuery";
21import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
22import { Schema } from "effect";
23
24const SIDEBAR_COOKIE_NAME = "sidebar_state";
25const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
26const SIDEBAR_WIDTH = "16rem";
27const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
28const SIDEBAR_WIDTH_ICON = "3rem";
29const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
30
31type SidebarContextProps = {
32 state: "expanded" | "collapsed";
33 open: boolean;
34 setOpen: (open: boolean) => void;
35 openMobile: boolean;
36 setOpenMobile: (open: boolean) => void;
37 isMobile: boolean;
38 toggleSidebar: () => void;
39};
40
41type SidebarResizableOptions = {
42 maxWidth?: number;
43 minWidth?: number;
44 onResize?: (width: number) => void;
45 shouldAcceptWidth?: (context: {
46 currentWidth: number;
47 nextWidth: number;
48 rail: HTMLButtonElement;
49 side: "left" | "right";
50 sidebarRoot: HTMLElement;
51 wrapper: HTMLElement;
52 }) => boolean;
53 storageKey?: string;
54};
55
56type SidebarResolvedResizableOptions = {
57 maxWidth: number;
58 minWidth: number;
59 onResize?: (width: number) => void;
60 shouldAcceptWidth?: (context: {
61 currentWidth: number;
62 nextWidth: number;
63 rail: HTMLButtonElement;
64 side: "left" | "right";
65 sidebarRoot: HTMLElement;
66 wrapper: HTMLElement;
67 }) => boolean;
68 storageKey: string | null;
69};
70
71type SidebarInstanceContextProps = {
72 resizable: SidebarResolvedResizableOptions | null;
73 side: "left" | "right";
74};
75
76const SidebarContext = React.createContext<SidebarContextProps | null>(null);
77const SidebarInstanceContext = React.createContext<SidebarInstanceContextProps | null>(null);
78
79function useSidebar() {
80 const context = React.useContext(SidebarContext);
81 if (!context) {
82 throw new Error("useSidebar must be used within a SidebarProvider.");
83 }
84
85 return context;
86}
87
88function SidebarProvider({
89 defaultOpen = true,
90 open: openProp,
91 onOpenChange: setOpenProp,
92 className,
93 style,
94 children,
95 ...props
96}: React.ComponentProps<"div"> & {
97 defaultOpen?: boolean;
98 open?: boolean;
99 onOpenChange?: (open: boolean) => void;
100}) {
101 const isMobile = useIsMobile();
102 const [openMobile, setOpenMobile] = React.useState(false);
103
104 // This is the internal state of the sidebar.
105 // We use openProp and setOpenProp for control from outside the component.
106 const [_open, _setOpen] = React.useState(defaultOpen);
107 const open = openProp ?? _open;
108 const setOpen = React.useCallback(
109 async (value: boolean | ((value: boolean) => boolean)) => {
110 const openState = typeof value === "function" ? value(open) : value;
111 if (setOpenProp) {
112 setOpenProp(openState);
113 } else {
114 _setOpen(openState);
115 }
116
117 // This sets the cookie to keep the sidebar state.
118 await cookieStore.set({
119 expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
120 name: SIDEBAR_COOKIE_NAME,
121 path: "/",
122 value: String(openState),
123 });
124 },
125 [setOpenProp, open],
126 );
127
128 // Helper to toggle the sidebar.
129 const toggleSidebar = React.useCallback(() => {
130 return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
131 }, [isMobile, setOpen]);
132
133 // We add a state so that we can do data-state="expanded" or "collapsed".
134 // This makes it easier to style the sidebar with Tailwind classes.
135 const state = open ? "expanded" : "collapsed";
136
137 const contextValue = React.useMemo<SidebarContextProps>(
138 () => ({
139 isMobile,
140 open,
141 openMobile,
142 setOpen,
143 setOpenMobile,
144 state,
145 toggleSidebar,
146 }),
147 [state, open, setOpen, isMobile, openMobile, toggleSidebar],
148 );
149
150 return (
151 <SidebarContext.Provider value={contextValue}>
152 <div
153 className={cn(
154 "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
155 className,
156 )}
157 data-slot="sidebar-wrapper"
158 style={
159 {
160 "--sidebar-width": SIDEBAR_WIDTH,
161 "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
162 ...style,
163 } as React.CSSProperties
164 }
165 {...props}
166 >
167 {children}
168 </div>
169 </SidebarContext.Provider>
170 );
171}
172
173function Sidebar({
174 side = "left",
175 variant = "sidebar",
176 collapsible = "offcanvas",
177 resizable = false,
178 className,
179 children,
180 ...props
181}: React.ComponentProps<"div"> & {
182 side?: "left" | "right";
183 variant?: "sidebar" | "floating" | "inset";
184 collapsible?: "offcanvas" | "icon" | "none";
185 resizable?: boolean | SidebarResizableOptions;
186}) {
187 const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
188 const resolvedResizable = React.useMemo<SidebarResolvedResizableOptions | null>(() => {
189 if (isMobile || collapsible === "none" || !resizable) {
190 return null;
191 }
192
193 const options = typeof resizable === "boolean" ? {} : resizable;
194 return {
195 maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY,
196 minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH,
197 storageKey: options.storageKey ?? null,
198 ...(options.onResize ? { onResize: options.onResize } : {}),
199 ...(options.shouldAcceptWidth ? { shouldAcceptWidth: options.shouldAcceptWidth } : {}),
200 };
201 }, [collapsible, isMobile, resizable]);
202 const instanceContextValue = React.useMemo<SidebarInstanceContextProps>(
203 () => ({ side, resizable: resolvedResizable }),
204 [resolvedResizable, side],
205 );
206
207 if (collapsible === "none") {
208 return (
209 <SidebarInstanceContext.Provider value={instanceContextValue}>
210 <div
211 className={cn(
212 "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
213 className,
214 )}
215 data-slot="sidebar"
216 {...props}
217 >
218 {children}
219 </div>
220 </SidebarInstanceContext.Provider>
221 );
222 }
223
224 if (isMobile) {
225 return (
226 <SidebarInstanceContext.Provider value={instanceContextValue}>
227 <Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
228 <SheetPopup
229 className={cn(
230 "w-(--sidebar-width) max-w-none bg-sidebar p-0 text-sidebar-foreground",
231 className,
232 )}
233 data-mobile="true"
234 data-sidebar="sidebar"
235 data-slot="sidebar"
236 showCloseButton={false}
237 side={side}
238 style={
239 {
240 "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
241 } as React.CSSProperties
242 }
243 >
244 <SheetHeader className="sr-only">
245 <SheetTitle>Sidebar</SheetTitle>
246 <SheetDescription>Displays the mobile sidebar.</SheetDescription>
247 </SheetHeader>
248 <div
249 className={cn(
250 "flex h-full w-full flex-col pb-safe pt-safe",
251 side === "left" ? "pl-safe" : "pr-safe",
252 )}
253 >
254 {children}
255 </div>
256 </SheetPopup>
257 </Sheet>
258 </SidebarInstanceContext.Provider>
259 );
260 }
261
262 return (
263 <SidebarInstanceContext.Provider value={instanceContextValue}>
264 <div
265 className="group peer hidden text-sidebar-foreground md:block"
266 data-collapsible={state === "collapsed" ? collapsible : ""}
267 data-side={side}
268 data-slot="sidebar"
269 data-state={state}
270 data-variant={variant}
271 >
272 {/* This is what handles the sidebar gap on desktop */}
273 <div
274 className={cn(
275 "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
276 "group-data-[collapsible=offcanvas]:w-0",
277 "group-data-[side=right]:rotate-180",
278 variant === "floating" || variant === "inset"
279 ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
280 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
281 )}
282 data-slot="sidebar-gap"
283 />
284 <div
285 className={cn(
286 "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
287 side === "left"
288 ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
289 : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
290 // Adjust the padding for floating and inset variants.
291 variant === "floating" || variant === "inset"
292 ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
293 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
294 className,
295 )}
296 data-slot="sidebar-container"
297 {...props}
298 >
299 <div
300 className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
301 data-sidebar="sidebar"
302 data-slot="sidebar-inner"
303 >
304 {children}
305 </div>
306 </div>
307 </div>
308 </SidebarInstanceContext.Provider>
309 );
310}
311
312function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
313 const { toggleSidebar, openMobile } = useSidebar();
314
315 return (
316 <Button
317 className={cn("size-7", className)}
318 data-sidebar="trigger"
319 data-slot="sidebar-trigger"
320 onClick={(event) => {
321 onClick?.(event);
322 toggleSidebar();
323 }}
324 size="icon"
325 variant="ghost"
326 {...props}
327 >
328 {openMobile ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
329 <span className="sr-only">Toggle Sidebar</span>
330 </Button>
331 );
332}
333
334function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
335 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
336}
337
338function SidebarRail({
339 className,
340 onClick,
341 onPointerCancel,
342 onPointerDown,
343 onPointerMove,
344 onPointerUp,
345 ...props
346}: React.ComponentProps<"button">) {
347 const { open, toggleSidebar } = useSidebar();
348 const sidebarInstance = React.useContext(SidebarInstanceContext);
349 const railRef = React.useRef<HTMLButtonElement | null>(null);
350 const suppressClickRef = React.useRef(false);
351 const resizeStateRef = React.useRef<{
352 moved: boolean;
353 pointerId: number;
354 pendingWidth: number;
355 rail: HTMLButtonElement;
356 rafId: number | null;
357 sidebarRoot: HTMLElement;
358 side: "left" | "right";
359 startWidth: number;
360 startX: number;
361 transitionTargets: HTMLElement[];
362 width: number;
363 wrapper: HTMLElement;
364 } | null>(null);
365 const resolvedResizable = sidebarInstance?.resizable ?? null;
366 const canResize = resolvedResizable !== null && open;
367 const railLabel = canResize ? "Resize Sidebar" : "Toggle Sidebar";
368 const railTitle = canResize ? "Drag to resize sidebar" : "Toggle Sidebar";
369
370 const stopResize = React.useCallback(
371 (pointerId: number) => {
372 const resizeState = resizeStateRef.current;
373 if (!resizeState) {
374 return;
375 }
376 if (resizeState.rafId !== null) {
377 window.cancelAnimationFrame(resizeState.rafId);
378 }
379 resizeState.transitionTargets.forEach((element) => {
380 element.style.removeProperty("transition-duration");
381 });
382 if (resolvedResizable?.storageKey && typeof window !== "undefined") {
383 setLocalStorageItem(resolvedResizable.storageKey, resizeState.width, Schema.Finite);
384 }
385 resolvedResizable?.onResize?.(resizeState.width);
386 resizeStateRef.current = null;
387 if (resizeState.rail.hasPointerCapture(pointerId)) {
388 resizeState.rail.releasePointerCapture(pointerId);
389 }
390 document.body.style.removeProperty("cursor");
391 document.body.style.removeProperty("user-select");
392 },
393 [resolvedResizable],
394 );
395
396 const handlePointerDown = React.useCallback(
397 (event: React.PointerEvent<HTMLButtonElement>) => {
398 onPointerDown?.(event);
399 if (event.defaultPrevented) return;
400 if (!resolvedResizable || !open || event.button !== 0) return;
401
402 const wrapper = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
403 const sidebarRoot = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar']");
404 if (!wrapper || !sidebarRoot) {
405 return;
406 }
407
408 const sidebarContainer = sidebarRoot.querySelector<HTMLElement>(
409 "[data-slot='sidebar-container']",
410 );
411 if (!sidebarContainer) {
412 return;
413 }
414
415 const startWidth = sidebarContainer.getBoundingClientRect().width;
416 const initialWidth = clampSidebarWidth(startWidth, resolvedResizable);
417 const transitionTargets = [
418 sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-gap']"),
419 sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-container']"),
420 ].filter((element): element is HTMLElement => element !== null);
421 transitionTargets.forEach((element) => {
422 element.style.setProperty("transition-duration", "0ms");
423 });
424
425 event.preventDefault();
426 event.stopPropagation();
427 resizeStateRef.current = {
428 moved: false,
429 pointerId: event.pointerId,
430 pendingWidth: initialWidth,
431 rail: event.currentTarget,
432 rafId: null,
433 sidebarRoot,
434 side: sidebarInstance?.side ?? "left",
435 startWidth: initialWidth,
436 startX: event.clientX,
437 transitionTargets,
438 width: initialWidth,
439 wrapper,
440 };
441 wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
442 event.currentTarget.setPointerCapture(event.pointerId);
443 document.body.style.cursor = "col-resize";
444 document.body.style.userSelect = "none";
445 },
446 [onPointerDown, open, resolvedResizable, sidebarInstance?.side],
447 );
448
449 const handlePointerMove = React.useCallback(
450 (event: React.PointerEvent<HTMLButtonElement>) => {
451 onPointerMove?.(event);
452 if (event.defaultPrevented) return;
453 const resizeState = resizeStateRef.current;
454 if (!resizeState || resizeState.pointerId !== event.pointerId || !resolvedResizable) return;
455
456 event.preventDefault();
457 const delta =
458 resizeState.side === "right"
459 ? resizeState.startX - event.clientX
460 : event.clientX - resizeState.startX;
461 if (Math.abs(delta) > 2) {
462 resizeState.moved = true;
463 }
464 resizeState.pendingWidth = clampSidebarWidth(
465 resizeState.startWidth + delta,
466 resolvedResizable,
467 );
468 if (resizeState.rafId !== null) {
469 return;
470 }
471
472 resizeState.rafId = window.requestAnimationFrame(() => {
473 const activeResizeState = resizeStateRef.current;
474 if (!activeResizeState || !resolvedResizable) return;
475
476 activeResizeState.rafId = null;
477 const nextWidth = activeResizeState.pendingWidth;
478 const accepted =
479 resolvedResizable.shouldAcceptWidth?.({
480 currentWidth: activeResizeState.width,
481 nextWidth,
482 rail: activeResizeState.rail,
483 side: activeResizeState.side,
484 sidebarRoot: activeResizeState.sidebarRoot,
485 wrapper: activeResizeState.wrapper,
486 }) ?? true;
487 if (!accepted) {
488 return;
489 }
490
491 activeResizeState.wrapper.style.setProperty("--sidebar-width", `${nextWidth}px`);
492 activeResizeState.width = nextWidth;
493 });
494 },
495 [onPointerMove, resolvedResizable],
496 );
497
498 const endResizeInteraction = React.useCallback(
499 (event: React.PointerEvent<HTMLButtonElement>) => {
500 const resizeState = resizeStateRef.current;
501 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
502
503 event.preventDefault();
504 suppressClickRef.current = resizeState.moved;
505 stopResize(event.pointerId);
506 },
507 [stopResize],
508 );
509
510 const handlePointerUp = React.useCallback(
511 (event: React.PointerEvent<HTMLButtonElement>) => {
512 onPointerUp?.(event);
513 if (event.defaultPrevented) return;
514 endResizeInteraction(event);
515 },
516 [endResizeInteraction, onPointerUp],
517 );
518
519 const handlePointerCancel = React.useCallback(
520 (event: React.PointerEvent<HTMLButtonElement>) => {
521 onPointerCancel?.(event);
522 if (event.defaultPrevented) return;
523 endResizeInteraction(event);
524 },
525 [endResizeInteraction, onPointerCancel],
526 );
527
528 const handleClick = React.useCallback(
529 (event: React.MouseEvent<HTMLButtonElement>) => {
530 onClick?.(event);
531 if (event.defaultPrevented) return;
532 if (suppressClickRef.current) {
533 suppressClickRef.current = false;
534 event.preventDefault();
535 return;
536 }
537 if (resolvedResizable && open) {
538 event.preventDefault();
539 return;
540 }
541 toggleSidebar();
542 },
543 [onClick, open, resolvedResizable, toggleSidebar],
544 );
545
546 React.useEffect(() => {
547 if (!resolvedResizable?.storageKey || typeof window === "undefined") return;
548 const rail = railRef.current;
549 if (!rail) return;
550 const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
551 if (!wrapper) return;
552
553 const storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
554 if (storedWidth === null) return;
555 const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
556 wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
557 resolvedResizable.onResize?.(clampedWidth);
558 }, [resolvedResizable]);
559
560 React.useEffect(() => {
561 return () => {
562 const resizeState = resizeStateRef.current;
563 if (resizeState?.rafId != null) {
564 window.cancelAnimationFrame(resizeState.rafId);
565 }
566 resizeState?.transitionTargets.forEach((element) => {
567 element.style.removeProperty("transition-duration");
568 });
569 document.body.style.removeProperty("cursor");
570 document.body.style.removeProperty("user-select");
571 };
572 }, []);
573
574 return (
575 <button
576 aria-label={railLabel}
577 className={cn(
578 /* disable pointer events only when offcanvas sidebar is collapsed, that's when the rail sits over the native scrollbar on windows and linux. icon mode stays fully clickable. */
579 "-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
580 "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
581 "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
582 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
583 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
584 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
585 className,
586 )}
587 data-sidebar="rail"
588 data-slot="sidebar-rail"
589 onClick={handleClick}
590 onPointerCancel={handlePointerCancel}
591 onPointerDown={handlePointerDown}
592 onPointerMove={handlePointerMove}
593 onPointerUp={handlePointerUp}
594 ref={railRef}
595 tabIndex={-1}
596 title={railTitle}
597 type="button"
598 {...props}
599 />
600 );
601}
602
603function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
604 return (
605 <main
606 className={cn(
607 "relative flex min-w-0 w-full flex-1 flex-col bg-background",
608 "md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2 md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm/5",
609 className,
610 )}
611 data-slot="sidebar-inset"
612 {...props}
613 />
614 );
615}
616
617function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
618 return (
619 <Input
620 className={cn("h-8 w-full bg-background shadow-none", className)}
621 data-sidebar="input"
622 data-slot="sidebar-input"
623 {...props}
624 />
625 );
626}
627
628function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
629 return (
630 <div
631 className={cn("flex flex-col gap-2 p-2", className)}
632 data-sidebar="header"
633 data-slot="sidebar-header"
634 {...props}
635 />
636 );
637}
638
639function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
640 return (
641 <div
642 className={cn("flex flex-col gap-2 p-2", className)}
643 data-sidebar="footer"
644 data-slot="sidebar-footer"
645 {...props}
646 />
647 );
648}
649
650function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
651 return (
652 <Separator
653 className={cn("mx-2 w-auto bg-sidebar-border", className)}
654 data-sidebar="separator"
655 data-slot="sidebar-separator"
656 {...props}
657 />
658 );
659}
660
661function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
662 return (
663 <ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
664 <div
665 className={cn(
666 "flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
667 className,
668 )}
669 data-sidebar="content"
670 data-slot="sidebar-content"
671 {...props}
672 />
673 </ScrollArea>
674 );
675}
676
677function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
678 return (
679 <div
680 className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
681 data-sidebar="group"
682 data-slot="sidebar-group"
683 {...props}
684 />
685 );
686}
687
688function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
689 const defaultProps = {
690 className: cn(
691 "flex h-8 shrink-0 items-center rounded-lg px-2 font-medium text-sidebar-foreground text-xs outline-hidden ring-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
692 "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
693 className,
694 ),
695 "data-sidebar": "group-label",
696 "data-slot": "sidebar-group-label",
697 };
698
699 return useRender({
700 defaultTagName: "div",
701 props: mergeProps(defaultProps, props),
702 render,
703 });
704}
705
706function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
707 const defaultProps = {
708 className: cn(
709 "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
710 // Increases the hit area of the button on mobile.
711 "after:-inset-2 after:absolute md:after:hidden",
712 "group-data-[collapsible=icon]:hidden",
713 className,
714 ),
715 "data-sidebar": "group-action",
716 "data-slot": "sidebar-group-action",
717 };
718
719 return useRender({
720 defaultTagName: "button",
721 props: mergeProps(defaultProps, props),
722 render,
723 });
724}
725
726function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
727 return (
728 <div
729 className={cn("w-full text-sm", className)}
730 data-sidebar="group-content"
731 data-slot="sidebar-group-content"
732 {...props}
733 />
734 );
735}
736
737function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
738 return (
739 <ul
740 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
741 data-sidebar="menu"
742 data-slot="sidebar-menu"
743 {...props}
744 />
745 );
746}
747
748function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
749 return (
750 <li
751 className={cn("group/menu-item relative", className)}
752 data-sidebar="menu-item"
753 data-slot="sidebar-menu-item"
754 {...props}
755 />
756 );
757}
758
759const sidebarMenuButtonVariants = cva(
760 "peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
761 {
762 defaultVariants: {
763 size: "default",
764 variant: "default",
765 },
766 variants: {
767 size: {
768 default: "h-8 text-sm",
769 lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
770 sm: "h-7 text-xs",
771 },
772 variant: {
773 default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
774 outline:
775 "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
776 },
777 },
778 },
779);
780
781function SidebarMenuButton({
782 isActive = false,
783 variant = "default",
784 size = "default",
785 tooltip,
786 className,
787 render,
788 ...props
789}: useRender.ComponentProps<"button"> & {
790 isActive?: boolean;
791 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
792} & VariantProps<typeof sidebarMenuButtonVariants>) {
793 const { isMobile, state } = useSidebar();
794
795 const defaultProps = {
796 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
797 "data-active": isActive,
798 "data-sidebar": "menu-button",
799 "data-size": size,
800 "data-slot": "sidebar-menu-button",
801 };
802
803 const buttonProps = mergeProps<"button">(defaultProps, props);
804
805 const buttonElement = useRender({
806 defaultTagName: "button",
807 props: buttonProps,
808 render,
809 });
810
811 if (!tooltip) {
812 return buttonElement;
813 }
814
815 if (typeof tooltip === "string") {
816 tooltip = {
817 children: tooltip,
818 };
819 }
820
821 return (
822 <Tooltip>
823 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
824 <TooltipPopup
825 align="center"
826 hidden={state !== "collapsed" || isMobile}
827 side="right"
828 {...tooltip}
829 />
830 </Tooltip>
831 );
832}
833
834function SidebarMenuAction({
835 className,
836 showOnHover = false,
837 render,
838 ...props
839}: useRender.ComponentProps<"button"> & {
840 showOnHover?: boolean;
841}) {
842 const defaultProps = {
843 className: cn(
844 "absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
845 // Increases the hit area of the button on mobile.
846 "after:-inset-2 after:absolute md:after:hidden",
847 "peer-data-[size=sm]/menu-button:top-1",
848 "peer-data-[size=default]/menu-button:top-1.5",
849 "peer-data-[size=lg]/menu-button:top-2.5",
850 "group-data-[collapsible=icon]:hidden",
851 showOnHover &&
852 "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
853 className,
854 ),
855 "data-sidebar": "menu-action",
856 "data-slot": "sidebar-menu-action",
857 };
858
859 return useRender({
860 defaultTagName: "button",
861 props: mergeProps<"button">(defaultProps, props),
862 render,
863 });
864}
865
866function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
867 return (
868 <div
869 className={cn(
870 "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-lg px-1 font-medium text-sidebar-foreground text-xs tabular-nums",
871 "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
872 "peer-data-[size=sm]/menu-button:top-1",
873 "peer-data-[size=default]/menu-button:top-1.5",
874 "peer-data-[size=lg]/menu-button:top-2.5",
875 "group-data-[collapsible=icon]:hidden",
876 className,
877 )}
878 data-sidebar="menu-badge"
879 data-slot="sidebar-menu-badge"
880 {...props}
881 />
882 );
883}
884
885function SidebarMenuSkeleton({
886 className,
887 showIcon = false,
888 ...props
889}: React.ComponentProps<"div"> & {
890 showIcon?: boolean;
891}) {
892 // Random width between 50 to 90%.
893 const width = React.useMemo(() => {
894 return `${Math.floor(Math.random() * 40) + 50}%`;
895 }, []);
896
897 return (
898 <div
899 className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
900 data-sidebar="menu-skeleton"
901 data-slot="sidebar-menu-skeleton"
902 {...props}
903 >
904 {showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
905 <Skeleton
906 className="h-4 max-w-(--skeleton-width) flex-1"
907 data-sidebar="menu-skeleton-text"
908 style={
909 {
910 "--skeleton-width": width,
911 } as React.CSSProperties
912 }
913 />
914 </div>
915 );
916}
917
918function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
919 return (
920 <ul
921 className={cn(
922 "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-sidebar-border border-l px-2.5 py-0.5",
923 "group-data-[collapsible=icon]:hidden",
924 className,
925 )}
926 data-sidebar="menu-sub"
927 data-slot="sidebar-menu-sub"
928 {...props}
929 />
930 );
931}
932
933function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
934 return (
935 <li
936 className={cn("group/menu-sub-item relative", className)}
937 data-sidebar="menu-sub-item"
938 data-slot="sidebar-menu-sub-item"
939 {...props}
940 />
941 );
942}
943
944function SidebarMenuSubButton({
945 size = "md",
946 isActive = false,
947 className,
948 render,
949 ...props
950}: useRender.ComponentProps<"a"> & {
951 size?: "sm" | "md";
952 isActive?: boolean;
953}) {
954 const defaultProps = {
955 className: cn(
956 "-translate-x-px flex h-7 min-w-0 cursor-pointer items-center gap-2 overflow-hidden rounded-lg px-2 text-sidebar-foreground outline-hidden ring-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
957 "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
958 size === "sm" && "text-xs",
959 size === "md" && "text-sm",
960 "group-data-[collapsible=icon]:hidden",
961 className,
962 ),
963 "data-active": isActive,
964 "data-sidebar": "menu-sub-button",
965 "data-size": size,
966 "data-slot": "sidebar-menu-sub-button",
967 };
968
969 return useRender({
970 defaultTagName: "a",
971 props: mergeProps<"a">(defaultProps, props),
972 render,
973 });
974}
975
976export {
977 Sidebar,
978 SidebarContent,
979 SidebarFooter,
980 SidebarGroup,
981 SidebarGroupAction,
982 SidebarGroupContent,
983 SidebarGroupLabel,
984 SidebarHeader,
985 SidebarInput,
986 SidebarInset,
987 SidebarMenu,
988 SidebarMenuAction,
989 SidebarMenuBadge,
990 SidebarMenuButton,
991 SidebarMenuItem,
992 SidebarMenuSkeleton,
993 SidebarMenuSub,
994 SidebarMenuSubButton,
995 SidebarMenuSubItem,
996 SidebarProvider,
997 SidebarRail,
998 SidebarSeparator,
999 SidebarTrigger,
1000 useSidebar,
1001};