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

sidebar.tsx

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