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