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

sidebar.tsx

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