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

sidebar.tsx

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