xonecas.io
5414
Sa

sat / files

sat / src / components / ui / sidebar.tsx

20.8 KB
1"use client";
2
3import { cva, type VariantProps } from "class-variance-authority";
4import { PanelLeftIcon } from "lucide-react";
5import { Slot } from "radix-ui";
6import * as React from "react";
7import { Button } from "@/components/ui/button";
8import { Input } from "@/components/ui/input";
9import { Separator } from "@/components/ui/separator";
10import {
11  Sheet,
12  SheetContent,
13  SheetDescription,
14  SheetHeader,
15  SheetTitle,
16} from "@/components/ui/sheet";
17import { Skeleton } from "@/components/ui/skeleton";
18import {
19  Tooltip,
20  TooltipContent,
21  TooltipTrigger,
22} from "@/components/ui/tooltip";
23import { useIsMobile } from "@/hooks/use-mobile";
24import { cn } from "@/lib/utils";
25
26const SIDEBAR_COOKIE_NAME = "sidebar_state";
27const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
28const SIDEBAR_WIDTH = "16rem";
29const SIDEBAR_WIDTH_MOBILE = "18rem";
30const SIDEBAR_WIDTH_ICON = "3rem";
31const SIDEBAR_KEYBOARD_SHORTCUT = "b";
32
33type SidebarContextProps = {
34  state: "expanded" | "collapsed";
35  open: boolean;
36  setOpen: (open: boolean) => void;
37  openMobile: boolean;
38  setOpenMobile: (open: boolean) => void;
39  isMobile: boolean;
40  toggleSidebar: () => void;
41};
42
43const SidebarContext = React.createContext<SidebarContextProps | null>(null);
44
45function useSidebar() {
46  const context = React.useContext(SidebarContext);
47  if (!context) {
48    throw new Error("useSidebar must be used within a SidebarProvider.");
49  }
50
51  return context;
52}
53
54function SidebarProvider({
55  defaultOpen = true,
56  open: openProp,
57  onOpenChange: setOpenProp,
58  className,
59  style,
60  children,
61  ...props
62}: React.ComponentProps<"div"> & {
63  defaultOpen?: boolean;
64  open?: boolean;
65  onOpenChange?: (open: boolean) => void;
66}) {
67  const isMobile = useIsMobile();
68  const [openMobile, setOpenMobile] = React.useState(false);
69
70  // This is the internal state of the sidebar.
71  // We use openProp and setOpenProp for control from outside the component.
72  const [_open, _setOpen] = React.useState(defaultOpen);
73  const open = openProp ?? _open;
74  const setOpen = React.useCallback(
75    (value: boolean | ((value: boolean) => boolean)) => {
76      const openState = typeof value === "function" ? value(open) : value;
77      if (setOpenProp) {
78        setOpenProp(openState);
79      } else {
80        _setOpen(openState);
81      }
82
83      // This sets the cookie to keep the sidebar state.
84      document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
85    },
86    [setOpenProp, open],
87  );
88
89  // Helper to toggle the sidebar.
90  const toggleSidebar = React.useCallback(() => {
91    return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
92  }, [isMobile, setOpen, setOpenMobile]);
93
94  // Adds a keyboard shortcut to toggle the sidebar.
95  React.useEffect(() => {
96    const handleKeyDown = (event: KeyboardEvent) => {
97      if (
98        event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
99        (event.metaKey || event.ctrlKey)
100      ) {
101        event.preventDefault();
102        toggleSidebar();
103      }
104    };
105
106    window.addEventListener("keydown", handleKeyDown);
107    return () => window.removeEventListener("keydown", handleKeyDown);
108  }, [toggleSidebar]);
109
110  // We add a state so that we can do data-state="expanded" or "collapsed".
111  // This makes it easier to style the sidebar with Tailwind classes.
112  const state = open ? "expanded" : "collapsed";
113
114  const contextValue = React.useMemo<SidebarContextProps>(
115    () => ({
116      state,
117      open,
118      setOpen,
119      isMobile,
120      openMobile,
121      setOpenMobile,
122      toggleSidebar,
123    }),
124    [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
125  );
126
127  return (
128    <SidebarContext.Provider value={contextValue}>
129      <div
130        data-slot="sidebar-wrapper"
131        style={
132          {
133            "--sidebar-width": SIDEBAR_WIDTH,
134            "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
135            ...style,
136          } as React.CSSProperties
137        }
138        className={cn(
139          "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
140          className,
141        )}
142        {...props}
143      >
144        {children}
145      </div>
146    </SidebarContext.Provider>
147  );
148}
149
150function Sidebar({
151  side = "left",
152  variant = "sidebar",
153  collapsible = "offExamples",
154  className,
155  children,
156  ...props
157}: React.ComponentProps<"div"> & {
158  side?: "left" | "right";
159  variant?: "sidebar" | "floating" | "inset";
160  collapsible?: "offExamples" | "icon" | "none";
161}) {
162  const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
163
164  if (collapsible === "none") {
165    return (
166      <div
167        data-slot="sidebar"
168        className={cn(
169          "bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
170          className,
171        )}
172        {...props}
173      >
174        {children}
175      </div>
176    );
177  }
178
179  if (isMobile) {
180    return (
181      <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
182        <SheetContent
183          data-sidebar="sidebar"
184          data-slot="sidebar"
185          data-mobile="true"
186          className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
187          style={
188            {
189              "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
190            } as React.CSSProperties
191          }
192          side={side}
193        >
194          <SheetHeader className="sr-only">
195            <SheetTitle>Sidebar</SheetTitle>
196            <SheetDescription>Displays the mobile sidebar.</SheetDescription>
197          </SheetHeader>
198          <div className="flex h-full w-full flex-col">{children}</div>
199        </SheetContent>
200      </Sheet>
201    );
202  }
203
204  return (
205    <div
206      className="group peer text-sidebar-foreground hidden md:block"
207      data-state={state}
208      data-collapsible={state === "collapsed" ? collapsible : ""}
209      data-variant={variant}
210      data-side={side}
211      data-slot="sidebar"
212    >
213      {/* This is what handles the sidebar gap on desktop */}
214      <div
215        data-slot="sidebar-gap"
216        className={cn(
217          "transition-[width] duration-200 ease-linear relative w-(--sidebar-width) bg-transparent",
218          "group-data-[collapsible=offExamples]:w-0",
219          "group-data-[side=right]:rotate-180",
220          variant === "floating" || variant === "inset"
221            ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
222            : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
223        )}
224      />
225      <div
226        data-slot="sidebar-container"
227        className={cn(
228          "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
229          side === "left"
230            ? "left-0 group-data-[collapsible=offExamples]:left-[calc(var(--sidebar-width)*-1)]"
231            : "right-0 group-data-[collapsible=offExamples]:right-[calc(var(--sidebar-width)*-1)]",
232          // Adjust the padding for floating and inset variants.
233          variant === "floating" || variant === "inset"
234            ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
235            : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
236          className,
237        )}
238        {...props}
239      >
240        <div
241          data-sidebar="sidebar"
242          data-slot="sidebar-inner"
243          className="bg-sidebar group-data-[variant=floating]:ring-sidebar-border group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:shadow-sm group-data-[variant=floating]:ring-1 flex size-full flex-col"
244        >
245          {children}
246        </div>
247      </div>
248    </div>
249  );
250}
251
252function SidebarTrigger({
253  className,
254  onClick,
255  ...props
256}: React.ComponentProps<typeof Button>) {
257  const { toggleSidebar } = useSidebar();
258
259  return (
260    <Button
261      data-sidebar="trigger"
262      data-slot="sidebar-trigger"
263      variant="ghost"
264      size="icon-sm"
265      className={cn(className)}
266      onClick={(event) => {
267        onClick?.(event);
268        toggleSidebar();
269      }}
270      {...props}
271    >
272      <PanelLeftIcon />
273      <span className="sr-only">Toggle Sidebar</span>
274    </Button>
275  );
276}
277
278function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
279  const { toggleSidebar } = useSidebar();
280
281  return (
282    <button
283      data-sidebar="rail"
284      data-slot="sidebar-rail"
285      aria-label="Toggle Sidebar"
286      tabIndex={-1}
287      onClick={toggleSidebar}
288      title="Toggle Sidebar"
289      className={cn(
290        "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
291        "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
292        "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
293        "hover:group-data-[collapsible=offExamples]:bg-sidebar group-data-[collapsible=offExamples]:translate-x-0 group-data-[collapsible=offExamples]:after:left-full",
294        "[[data-side=left][data-collapsible=offExamples]_&]:-right-2",
295        "[[data-side=right][data-collapsible=offExamples]_&]:-left-2",
296        className,
297      )}
298      {...props}
299    />
300  );
301}
302
303function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
304  return (
305    <main
306      data-slot="sidebar-inset"
307      className={cn(
308        "bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 relative flex w-full flex-1 flex-col",
309        className,
310      )}
311      {...props}
312    />
313  );
314}
315
316function SidebarInput({
317  className,
318  ...props
319}: React.ComponentProps<typeof Input>) {
320  return (
321    <Input
322      data-slot="sidebar-input"
323      data-sidebar="input"
324      className={cn("bg-background h-8 w-full shadow-none", className)}
325      {...props}
326    />
327  );
328}
329
330function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
331  return (
332    <div
333      data-slot="sidebar-header"
334      data-sidebar="header"
335      className={cn("gap-2 p-2 flex flex-col", className)}
336      {...props}
337    />
338  );
339}
340
341function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
342  return (
343    <div
344      data-slot="sidebar-footer"
345      data-sidebar="footer"
346      className={cn("gap-2 p-2 flex flex-col", className)}
347      {...props}
348    />
349  );
350}
351
352function SidebarSeparator({
353  className,
354  ...props
355}: React.ComponentProps<typeof Separator>) {
356  return (
357    <Separator
358      data-slot="sidebar-separator"
359      data-sidebar="separator"
360      className={cn("bg-sidebar-border mx-2 w-auto", className)}
361      {...props}
362    />
363  );
364}
365
366function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
367  return (
368    <div
369      data-slot="sidebar-content"
370      data-sidebar="content"
371      className={cn(
372        "no-scrollbar gap-2 flex min-h-0 flex-1 flex-col overflow-auto group-data-[collapsible=icon]:overflow-hidden",
373        className,
374      )}
375      {...props}
376    />
377  );
378}
379
380function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
381  return (
382    <div
383      data-slot="sidebar-group"
384      data-sidebar="group"
385      className={cn("p-2 relative flex w-full min-w-0 flex-col", className)}
386      {...props}
387    />
388  );
389}
390
391function SidebarGroupLabel({
392  className,
393  asChild = false,
394  ...props
395}: React.ComponentProps<"div"> & { asChild?: boolean }) {
396  const Comp = asChild ? Slot.Root : "div";
397
398  return (
399    <Comp
400      data-slot="sidebar-group-label"
401      data-sidebar="group-label"
402      className={cn(
403        "text-sidebar-foreground/70 ring-sidebar-ring h-8 rounded-md px-2 text-xs font-medium transition-[margin,opacity] duration-200 ease-linear group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 focus-visible:ring-2 [&>svg]:size-4 flex shrink-0 items-center outline-hidden [&>svg]:shrink-0",
404        className,
405      )}
406      {...props}
407    />
408  );
409}
410
411function SidebarGroupAction({
412  className,
413  asChild = false,
414  ...props
415}: React.ComponentProps<"button"> & { asChild?: boolean }) {
416  const Comp = asChild ? Slot.Root : "button";
417
418  return (
419    <Comp
420      data-slot="sidebar-group-action"
421      data-sidebar="group-action"
422      className={cn(
423        "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 w-5 rounded-md p-0 focus-visible:ring-2 [&>svg]:size-4 flex aspect-square items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0",
424        className,
425      )}
426      {...props}
427    />
428  );
429}
430
431function SidebarGroupContent({
432  className,
433  ...props
434}: React.ComponentProps<"div">) {
435  return (
436    <div
437      data-slot="sidebar-group-content"
438      data-sidebar="group-content"
439      className={cn("text-sm w-full", className)}
440      {...props}
441    />
442  );
443}
444
445function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
446  return (
447    <ul
448      data-slot="sidebar-menu"
449      data-sidebar="menu"
450      className={cn("gap-1 flex w-full min-w-0 flex-col", className)}
451      {...props}
452    />
453  );
454}
455
456function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
457  return (
458    <li
459      data-slot="sidebar-menu-item"
460      data-sidebar="menu-item"
461      className={cn("group/menu-item relative", className)}
462      {...props}
463    />
464  );
465}
466
467const sidebarMenuButtonVariants = cva(
468  "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground data-open:hover:bg-sidebar-accent data-open:hover:text-sidebar-accent-foreground gap-2 rounded-lg p-2 text-left text-sm transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 data-active:font-medium peer/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&_svg]:size-4 [&_svg]:shrink-0",
469  {
470    variants: {
471      variant: {
472        default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
473        outline:
474          "bg-background hover:bg-sidebar-accent hover:text-sidebar-accent-foreground shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
475      },
476      size: {
477        default: "h-9 text-sm",
478        sm: "h-8 text-xs",
479        lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
480      },
481    },
482    defaultVariants: {
483      variant: "default",
484      size: "default",
485    },
486  },
487);
488
489function SidebarMenuButton({
490  asChild = false,
491  isActive = false,
492  variant = "default",
493  size = "default",
494  tooltip,
495  className,
496  ...props
497}: React.ComponentProps<"button"> & {
498  asChild?: boolean;
499  isActive?: boolean;
500  tooltip?: string | React.ComponentProps<typeof TooltipContent>;
501} & VariantProps<typeof sidebarMenuButtonVariants>) {
502  const Comp = asChild ? Slot.Root : "button";
503  const { isMobile, state } = useSidebar();
504
505  const button = (
506    <Comp
507      data-slot="sidebar-menu-button"
508      data-sidebar="menu-button"
509      data-size={size}
510      data-active={isActive}
511      className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
512      {...props}
513    />
514  );
515
516  if (!tooltip) {
517    return button;
518  }
519
520  if (typeof tooltip === "string") {
521    tooltip = {
522      children: tooltip,
523    };
524  }
525
526  return (
527    <Tooltip>
528      <TooltipTrigger asChild>{button}</TooltipTrigger>
529      <TooltipContent
530        side="right"
531        align="center"
532        hidden={state !== "collapsed" || isMobile}
533        {...tooltip}
534      />
535    </Tooltip>
536  );
537}
538
539function SidebarMenuAction({
540  className,
541  asChild = false,
542  showOnHover = false,
543  ...props
544}: React.ComponentProps<"button"> & {
545  asChild?: boolean;
546  showOnHover?: boolean;
547}) {
548  const Comp = asChild ? Slot.Root : "button";
549
550  return (
551    <Comp
552      data-slot="sidebar-menu-action"
553      data-sidebar="menu-action"
554      className={cn(
555        "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 aspect-square w-5 rounded-md p-0 peer-data-[size=default]/menu-button:top-2 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 focus-visible:ring-2 [&>svg]:size-4 flex items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0",
556        showOnHover &&
557          "peer-data-active/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-open:opacity-100 md:opacity-0",
558        className,
559      )}
560      {...props}
561    />
562  );
563}
564
565function SidebarMenuBadge({
566  className,
567  ...props
568}: React.ComponentProps<"div">) {
569  return (
570    <div
571      data-slot="sidebar-menu-badge"
572      data-sidebar="menu-badge"
573      className={cn(
574        "text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground peer-data-active/menu-button:text-sidebar-accent-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 rounded-md px-1 text-xs font-medium peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 peer-data-[size=sm]/menu-button:top-1 flex items-center justify-center tabular-nums select-none group-data-[collapsible=icon]:hidden",
575        className,
576      )}
577      {...props}
578    />
579  );
580}
581
582function SidebarMenuSkeleton({
583  className,
584  showIcon = false,
585  ...props
586}: React.ComponentProps<"div"> & {
587  showIcon?: boolean;
588}) {
589  // Random width between 50 to 90%.
590  const [width] = React.useState(() => {
591    return `${Math.floor(Math.random() * 40) + 50}%`;
592  });
593
594  return (
595    <div
596      data-slot="sidebar-menu-skeleton"
597      data-sidebar="menu-skeleton"
598      className={cn("h-8 gap-2 rounded-md px-2 flex items-center", className)}
599      {...props}
600    >
601      {showIcon && (
602        <Skeleton
603          className="size-4 rounded-md"
604          data-sidebar="menu-skeleton-icon"
605        />
606      )}
607      <Skeleton
608        className="h-4 max-w-(--skeleton-width) flex-1"
609        data-sidebar="menu-skeleton-text"
610        style={
611          {
612            "--skeleton-width": width,
613          } as React.CSSProperties
614        }
615      />
616    </div>
617  );
618}
619
620function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
621  return (
622    <ul
623      data-slot="sidebar-menu-sub"
624      data-sidebar="menu-sub"
625      className={cn(
626        "border-sidebar-border mx-3.5 translate-x-px gap-1 border-l px-2.5 py-0.5 group-data-[collapsible=icon]:hidden flex min-w-0 flex-col",
627        className,
628      )}
629      {...props}
630    />
631  );
632}
633
634function SidebarMenuSubItem({
635  className,
636  ...props
637}: React.ComponentProps<"li">) {
638  return (
639    <li
640      data-slot="sidebar-menu-sub-item"
641      data-sidebar="menu-sub-item"
642      className={cn("group/menu-sub-item relative", className)}
643      {...props}
644    />
645  );
646}
647
648function SidebarMenuSubButton({
649  asChild = false,
650  size = "md",
651  isActive = false,
652  className,
653  ...props
654}: React.ComponentProps<"a"> & {
655  asChild?: boolean;
656  size?: "sm" | "md";
657  isActive?: boolean;
658}) {
659  const Comp = asChild ? Slot.Root : "a";
660
661  return (
662    <Comp
663      data-slot="sidebar-menu-sub-button"
664      data-sidebar="menu-sub-button"
665      data-size={size}
666      data-active={isActive}
667      className={cn(
668        "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground h-7 gap-2 rounded-md px-2 focus-visible:ring-2 data-[size=md]:text-sm data-[size=sm]:text-xs [&>svg]:size-4 flex min-w-0 -translate-x-px items-center overflow-hidden outline-hidden group-data-[collapsible=icon]:hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:shrink-0",
669        className,
670      )}
671      {...props}
672    />
673  );
674}
675
676export {
677  Sidebar,
678  SidebarContent,
679  SidebarFooter,
680  SidebarGroup,
681  SidebarGroupAction,
682  SidebarGroupContent,
683  SidebarGroupLabel,
684  SidebarHeader,
685  SidebarInput,
686  SidebarInset,
687  SidebarMenu,
688  SidebarMenuAction,
689  SidebarMenuBadge,
690  SidebarMenuButton,
691  SidebarMenuItem,
692  SidebarMenuSkeleton,
693  SidebarMenuSub,
694  SidebarMenuSubButton,
695  SidebarMenuSubItem,
696  SidebarProvider,
697  SidebarRail,
698  SidebarSeparator,
699  SidebarTrigger,
700  useSidebar,
701};