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