Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sidebar.tsx

814 lines27.4 KB

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