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