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

sidebar.tsx

1,028 lines33.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 { 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 className={cn(
160 "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
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 ...style,
170 } as React.CSSProperties
171 }
172 {...props}
173 >
174 {children}
175 </div>
176 </SidebarContext>
177 );
179​
180function Sidebar({
181 side = "left",
182 variant = "sidebar",
183 collapsible = "offcanvas",
184 resizable = false,
185 className,
186 children,
187 ...props
188}: React.ComponentProps<"div"> & {
189 side?: "left" | "right";
190 variant?: "sidebar" | "floating" | "inset";
191 collapsible?: "offcanvas" | "icon" | "none";
192 resizable?: boolean | SidebarResizableOptions;
193}) {
194 const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
195 const resolvedResizable = React.useMemo<SidebarResolvedResizableOptions | null>(() => {
196 if (isMobile || collapsible === "none" || !resizable) {
197 return null;
198 }
199​
200 const options = typeof resizable === "boolean" ? {} : resizable;
201 return {
202 maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY,
203 minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH,
204 storageKey: options.storageKey ?? null,
205 ...(options.onResize ? { onResize: options.onResize } : {}),
206 ...(options.shouldAcceptWidth ? { shouldAcceptWidth: options.shouldAcceptWidth } : {}),
207 };
208 }, [collapsible, isMobile, resizable]);
209 const instanceContextValue = React.useMemo<SidebarInstanceContextProps>(
210 () => ({ side, resizable: resolvedResizable }),
211 [resolvedResizable, side],
212 );
213​
214 if (collapsible === "none") {
215 return (
216 <SidebarInstanceContext value={instanceContextValue}>
217 <div
218 className={cn(
219 "flex h-full w-(--sidebar-width) flex-col bg-sidebar surface-grain text-sidebar-foreground",
220 className,
221 )}
222 data-slot="sidebar"
223 {...props}
224 >
225 {children}
226 </div>
227 </SidebarInstanceContext>
228 );
229 }
230​
231 if (isMobile) {
232 return (
233 <SidebarInstanceContext value={instanceContextValue}>
234 <Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
235 <SheetPopup
236 className={cn(
237 "w-(--sidebar-width) max-w-none bg-sidebar surface-grain p-0 text-sidebar-foreground",
238 className,
239 )}
240 data-mobile="true"
241 data-sidebar="sidebar"
242 data-slot="sidebar"
243 showCloseButton={false}
244 side={side}
245 style={
246 {
247 "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
248 } as React.CSSProperties
249 }
250 >
251 <SheetHeader className="sr-only">
252 <SheetTitle>Sidebar</SheetTitle>
253 <SheetDescription>Displays the mobile sidebar.</SheetDescription>
254 </SheetHeader>
255 <div
256 className={cn(
257 "flex h-full w-full flex-col pb-safe pt-safe",
258 side === "left" ? "pl-safe" : "pr-safe",
259 )}
260 >
261 {children}
262 </div>
263 </SheetPopup>
264 </Sheet>
265 </SidebarInstanceContext>
266 );
267 }
268​
269 return (
270 <SidebarInstanceContext value={instanceContextValue}>
271 <div
272 className="group peer hidden text-sidebar-foreground md:block"
273 data-collapsible={state === "collapsed" ? collapsible : ""}
274 data-side={side}
275 data-slot="sidebar"
276 data-state={state}
277 data-variant={variant}
278 >
279 {/* This is what handles the sidebar gap on desktop */}
280 <div
281 className={cn(
282 "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
283 "group-data-[collapsible=offcanvas]:w-0",
284 "group-data-[side=right]:rotate-180",
285 variant === "floating" || variant === "inset"
286 ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
287 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
288 )}
289 data-slot="sidebar-gap"
290 />
291 <div
292 className={cn(
293 "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
294 side === "left"
295 ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
296 : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
297 // Adjust the padding for floating and inset variants.
298 variant === "floating" || variant === "inset"
299 ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
300 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
301 className,
302 )}
303 data-slot="sidebar-container"
304 {...props}
305 >
306 <div
307 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"
308 data-sidebar="sidebar"
309 data-slot="sidebar-inner"
310 >
311 {children}
312 </div>
313 </div>
314 </div>
315 </SidebarInstanceContext>
316 );
318​
319function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
320 const { toggleSidebar } = useSidebar();
321 const isOpen = useSidebarVisibility();
322​
323 return (
324 <Button
325 className={cn(
326 "size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]",
327 className,
328 )}
329 data-sidebar="trigger"
330 data-slot="sidebar-trigger"
331 aria-pressed={isOpen}
332 onClick={(event) => {
333 onClick?.(event);
334 toggleSidebar();
335 }}
336 size="icon"
337 variant="ghost"
338 {...props}
339 >
340 {isOpen ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
341 <span className="sr-only">Toggle Sidebar</span>
342 </Button>
343 );
345​
346function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
347 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
349​
350function SidebarRail({
351 className,
352 onClick,
353 onPointerCancel,
354 onPointerDown,
355 onPointerMove,
356 onPointerUp,
357 ...props
358}: React.ComponentProps<"button">) {
359 const { open, toggleSidebar } = useSidebar();
360 const sidebarInstance = React.use(SidebarInstanceContext);
361 const railRef = React.useRef<HTMLButtonElement | null>(null);
362 const suppressClickRef = React.useRef(false);
363 const resizeStateRef = React.useRef<{
364 moved: boolean;
365 pointerId: number;
366 pendingWidth: number;
367 rail: HTMLButtonElement;
368 rafId: number | null;
369 sidebarRoot: HTMLElement;
370 side: "left" | "right";
371 startWidth: number;
372 startX: number;
373 transitionTargets: HTMLElement[];
374 width: number;
375 wrapper: HTMLElement;
376 } | null>(null);
377 const resolvedResizable = sidebarInstance?.resizable ?? null;
378 const canResize = resolvedResizable !== null && open;
379 const railLabel = canResize ? "Resize Sidebar" : "Toggle Sidebar";
380 const railTitle = canResize ? "Drag to resize sidebar" : "Toggle Sidebar";
381​
382 const stopResize = React.useCallback(
383 (pointerId: number) => {
384 const resizeState = resizeStateRef.current;
385 if (!resizeState) {
386 return;
387 }
388 if (resizeState.rafId !== null) {
389 window.cancelAnimationFrame(resizeState.rafId);
390 }
391 resizeState.transitionTargets.forEach((element) => {
392 element.style.removeProperty("transition-duration");
393 });
394 if (resolvedResizable?.storageKey && typeof window !== "undefined") {
395 setLocalStorageItem(resolvedResizable.storageKey, resizeState.width, Schema.Finite);
396 }
397 resolvedResizable?.onResize?.(resizeState.width);
398 resizeStateRef.current = null;
399 if (resizeState.rail.hasPointerCapture(pointerId)) {
400 resizeState.rail.releasePointerCapture(pointerId);
401 }
402 document.body.style.removeProperty("cursor");
403 document.body.style.removeProperty("user-select");
404 },
405 [resolvedResizable],
406 );
407​
408 const handlePointerDown = React.useCallback(
409 (event: React.PointerEvent<HTMLButtonElement>) => {
410 onPointerDown?.(event);
411 if (event.defaultPrevented) return;
412 if (!resolvedResizable || !open || event.button !== 0) return;
413​
414 const wrapper = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
415 const sidebarRoot = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar']");
416 if (!wrapper || !sidebarRoot) {
417 return;
418 }
419​
420 const sidebarContainer = sidebarRoot.querySelector<HTMLElement>(
421 "[data-slot='sidebar-container']",
422 );
423 if (!sidebarContainer) {
424 return;
425 }
426​
427 const startWidth = sidebarContainer.getBoundingClientRect().width;
428 const initialWidth = clampSidebarWidth(startWidth, resolvedResizable);
429 const transitionTargets = [
430 sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-gap']"),
431 sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-container']"),
432 ].filter((element): element is HTMLElement => element !== null);
433 transitionTargets.forEach((element) => {
434 element.style.setProperty("transition-duration", "0ms");
435 });
436​
437 event.preventDefault();
438 event.stopPropagation();
439 resizeStateRef.current = {
440 moved: false,
441 pointerId: event.pointerId,
442 pendingWidth: initialWidth,
443 rail: event.currentTarget,
444 rafId: null,
445 sidebarRoot,
446 side: sidebarInstance?.side ?? "left",
447 startWidth: initialWidth,
448 startX: event.clientX,
449 transitionTargets,
450 width: initialWidth,
451 wrapper,
452 };
453 wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
454 event.currentTarget.setPointerCapture(event.pointerId);
455 document.body.style.cursor = "col-resize";
456 document.body.style.userSelect = "none";
457 },
458 [onPointerDown, open, resolvedResizable, sidebarInstance?.side],
459 );
460​
461 const handlePointerMove = React.useCallback(
462 (event: React.PointerEvent<HTMLButtonElement>) => {
463 onPointerMove?.(event);
464 if (event.defaultPrevented) return;
465 const resizeState = resizeStateRef.current;
466 if (!resizeState || resizeState.pointerId !== event.pointerId || !resolvedResizable) return;
467​
468 event.preventDefault();
469 const delta =
470 resizeState.side === "right"
471 ? resizeState.startX - event.clientX
472 : event.clientX - resizeState.startX;
473 if (Math.abs(delta) > 2) {
474 resizeState.moved = true;
475 }
476 resizeState.pendingWidth = clampSidebarWidth(
477 resizeState.startWidth + delta,
478 resolvedResizable,
479 );
480 if (resizeState.rafId !== null) {
481 return;
482 }
483​
484 resizeState.rafId = window.requestAnimationFrame(() => {
485 const activeResizeState = resizeStateRef.current;
486 if (!activeResizeState || !resolvedResizable) return;
487​
488 activeResizeState.rafId = null;
489 const nextWidth = activeResizeState.pendingWidth;
490 const accepted =
491 resolvedResizable.shouldAcceptWidth?.({
492 currentWidth: activeResizeState.width,
493 nextWidth,
494 rail: activeResizeState.rail,
495 side: activeResizeState.side,
496 sidebarRoot: activeResizeState.sidebarRoot,
497 wrapper: activeResizeState.wrapper,
498 }) ?? true;
499 if (!accepted) {
500 return;
501 }
502​
503 activeResizeState.wrapper.style.setProperty("--sidebar-width", `${nextWidth}px`);
504 activeResizeState.width = nextWidth;
505 });
506 },
507 [onPointerMove, resolvedResizable],
508 );
509​
510 const endResizeInteraction = React.useCallback(
511 (event: React.PointerEvent<HTMLButtonElement>) => {
512 const resizeState = resizeStateRef.current;
513 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
514​
515 event.preventDefault();
516 suppressClickRef.current = resizeState.moved;
517 stopResize(event.pointerId);
518 },
519 [stopResize],
520 );
521​
522 const handlePointerUp = React.useCallback(
523 (event: React.PointerEvent<HTMLButtonElement>) => {
524 onPointerUp?.(event);
525 if (event.defaultPrevented) return;
526 endResizeInteraction(event);
527 },
528 [endResizeInteraction, onPointerUp],
529 );
530​
531 const handlePointerCancel = React.useCallback(
532 (event: React.PointerEvent<HTMLButtonElement>) => {
533 onPointerCancel?.(event);
534 if (event.defaultPrevented) return;
535 endResizeInteraction(event);
536 },
537 [endResizeInteraction, onPointerCancel],
538 );
539​
540 const handleClick = React.useCallback(
541 (event: React.MouseEvent<HTMLButtonElement>) => {
542 onClick?.(event);
543 if (event.defaultPrevented) return;
544 if (suppressClickRef.current) {
545 suppressClickRef.current = false;
546 event.preventDefault();
547 return;
548 }
549 if (resolvedResizable && open) {
550 event.preventDefault();
551 return;
552 }
553 toggleSidebar();
554 },
555 [onClick, open, resolvedResizable, toggleSidebar],
556 );
557​
558 React.useLayoutEffect(() => {
559 if (!resolvedResizable?.storageKey || typeof window === "undefined") return;
560 const rail = railRef.current;
561 if (!rail) return;
562 const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
563 if (!wrapper) return;
564​
565 let storedWidth: number | null;
566 try {
567 storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
568 } catch (error) {
569 console.error("Could not restore persisted sidebar width.", error);
570 return;
571 }
572 if (storedWidth === null) return;
573 const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
574 // Hydrate the CSS variable before the browser paints so a restored sidebar
575 // never flashes at the default width first.
576 wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
577 resolvedResizable.onResize?.(clampedWidth);
578 }, [resolvedResizable]);
579​
580 React.useEffect(() => {
581 return () => {
582 const resizeState = resizeStateRef.current;
583 if (resizeState?.rafId != null) {
584 window.cancelAnimationFrame(resizeState.rafId);
585 }
586 resizeState?.transitionTargets.forEach((element) => {
587 element.style.removeProperty("transition-duration");
588 });
589 document.body.style.removeProperty("cursor");
590 document.body.style.removeProperty("user-select");
591 };
592 }, []);
593​
594 return (
595 <Tooltip>
596 <TooltipTrigger
597 render={
598 <button
599 aria-label={railLabel}
600 className={cn(
601 /* 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. */
602 "-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 [[data-collapsible=offcanvas][data-state=collapsed]_&]:pointer-events-none",
603 "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
604 "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
605 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
606 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
607 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
608 className,
609 )}
610 data-sidebar="rail"
611 data-slot="sidebar-rail"
612 onClick={handleClick}
613 onPointerCancel={handlePointerCancel}
614 onPointerDown={handlePointerDown}
615 onPointerMove={handlePointerMove}
616 onPointerUp={handlePointerUp}
617 ref={railRef}
618 tabIndex={-1}
619 type="button"
620 {...props}
621 />
622 }
623 />
624 <TooltipPopup side="right">{railTitle}</TooltipPopup>
625 </Tooltip>
626 );
628​
629function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
630 return (
631 <main
632 className={cn(
633 "relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
634 "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",
635 className,
636 )}
637 data-slot="sidebar-inset"
638 {...props}
639 />
640 );
642​
643function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
644 return (
645 <Input
646 className={cn("h-8 w-full bg-background shadow-none", className)}
647 data-sidebar="input"
648 data-slot="sidebar-input"
649 {...props}
650 />
651 );
653​
654function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
655 return (
656 <div
657 className={cn("flex flex-col gap-2 p-2", className)}
658 data-sidebar="header"
659 data-slot="sidebar-header"
660 {...props}
661 />
662 );
664​
665function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
666 return (
667 <div
668 className={cn("flex flex-col gap-2 p-2", className)}
669 data-sidebar="footer"
670 data-slot="sidebar-footer"
671 {...props}
672 />
673 );
675​
676function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
677 return (
678 <Separator
679 className={cn("mx-2 w-auto bg-sidebar-border", className)}
680 data-sidebar="separator"
681 data-slot="sidebar-separator"
682 {...props}
683 />
684 );
686​
687function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
688 return (
689 <ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
690 <div
691 className={cn(
692 "flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
693 className,
694 )}
695 data-sidebar="content"
696 data-slot="sidebar-content"
697 {...props}
698 />
699 </ScrollArea>
700 );
702​
703function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
704 return (
705 <div
706 className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
707 data-sidebar="group"
708 data-slot="sidebar-group"
709 {...props}
710 />
711 );
713​
714function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
715 const defaultProps = {
716 className: cn(
717 "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",
718 "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
719 className,
720 ),
721 "data-sidebar": "group-label",
722 "data-slot": "sidebar-group-label",
723 };
724​
725 return useRender({
726 defaultTagName: "div",
727 props: mergeProps(defaultProps, props),
728 render,
729 });
731​
732function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
733 const defaultProps = {
734 className: cn(
735 "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-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
736 // Increases the hit area of the button on mobile.
737 "after:-inset-2 after:absolute md:after:hidden",
738 "group-data-[collapsible=icon]:hidden",
739 className,
740 ),
741 "data-sidebar": "group-action",
742 "data-slot": "sidebar-group-action",
743 };
744​
745 return useRender({
746 defaultTagName: "button",
747 props: mergeProps(defaultProps, props),
748 render,
749 });
751​
752function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
753 return (
754 <div
755 className={cn("w-full text-sm", className)}
756 data-sidebar="group-content"
757 data-slot="sidebar-group-content"
758 {...props}
759 />
760 );
762​
763function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
764 return (
765 <ul
766 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
767 data-sidebar="menu"
768 data-slot="sidebar-menu"
769 {...props}
770 />
771 );
773​
774function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
775 return (
776 <li
777 className={cn("group/menu-item relative", className)}
778 data-sidebar="menu-item"
779 data-slot="sidebar-menu-item"
780 {...props}
781 />
782 );
784​
785const sidebarMenuButtonVariants = cva(
786 "peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-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",
787 {
788 defaultVariants: {
789 size: "default",
790 variant: "default",
791 },
792 variants: {
793 size: {
794 default: "h-8 text-sm",
795 lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
796 sm: "h-7 text-xs",
797 },
798 variant: {
799 default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
800 outline:
801 "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))]",
802 },
803 },
804 },
805);
806​
807function SidebarMenuButton({
808 isActive = false,
809 variant = "default",
810 size = "default",
811 tooltip,
812 className,
813 render,
814 ...props
815}: useRender.ComponentProps<"button"> & {
816 isActive?: boolean;
817 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
818} & VariantProps<typeof sidebarMenuButtonVariants>) {
819 const { isMobile, state } = useSidebar();
820​
821 const defaultProps = {
822 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
823 "data-active": isActive,
824 "data-sidebar": "menu-button",
825 "data-size": size,
826 "data-slot": "sidebar-menu-button",
827 };
828​
829 const buttonProps = mergeProps<"button">(defaultProps, props);
830​
831 const buttonElement = useRender({
832 defaultTagName: "button",
833 props: buttonProps,
834 render,
835 });
836​
837 if (!tooltip) {
838 return buttonElement;
839 }
840​
841 if (typeof tooltip === "string") {
842 tooltip = {
843 children: tooltip,
844 };
845 }
846​
847 return (
848 <Tooltip>
849 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
850 <TooltipPopup
851 align="center"
852 hidden={state !== "collapsed" || isMobile}
853 side="right"
854 {...tooltip}
855 />
856 </Tooltip>
857 );
859​
860function SidebarMenuAction({
861 className,
862 showOnHover = false,
863 render,
864 ...props
865}: useRender.ComponentProps<"button"> & {
866 showOnHover?: boolean;
867}) {
868 const defaultProps = {
869 className: cn(
870 "absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-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",
871 // Increases the hit area of the button on mobile.
872 "after:-inset-2 after:absolute md:after:hidden",
873 "peer-data-[size=sm]/menu-button:top-1",
874 "peer-data-[size=default]/menu-button:top-1.5",
875 "peer-data-[size=lg]/menu-button:top-2.5",
876 "group-data-[collapsible=icon]:hidden",
877 showOnHover &&
878 "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",
879 className,
880 ),
881 "data-sidebar": "menu-action",
882 "data-slot": "sidebar-menu-action",
883 };
884​
885 return useRender({
886 defaultTagName: "button",
887 props: mergeProps<"button">(defaultProps, props),
888 render,
889 });
891​
892function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
893 return (
894 <div
895 className={cn(
896 "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",
897 "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
898 "peer-data-[size=sm]/menu-button:top-1",
899 "peer-data-[size=default]/menu-button:top-1.5",
900 "peer-data-[size=lg]/menu-button:top-2.5",
901 "group-data-[collapsible=icon]:hidden",
902 className,
903 )}
904 data-sidebar="menu-badge"
905 data-slot="sidebar-menu-badge"
906 {...props}
907 />
908 );
910​
911function SidebarMenuSkeleton({
912 className,
913 showIcon = false,
914 ...props
915}: React.ComponentProps<"div"> & {
916 showIcon?: boolean;
917}) {
918 // Random width between 50 to 90%. Intentionally wrapped in useMemo to avoid changing width on every render.
919 const width = React.useMemo(() => {
920 return `${Math.floor(Math.random() * 40) + 50}%`;
921 }, []);
922​
923 return (
924 <div
925 className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
926 data-sidebar="menu-skeleton"
927 data-slot="sidebar-menu-skeleton"
928 {...props}
929 >
930 {showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
931 <Skeleton
932 className="h-4 max-w-(--skeleton-width) flex-1"
933 data-sidebar="menu-skeleton-text"
934 style={
935 {
936 "--skeleton-width": width,
937 } as React.CSSProperties
938 }
939 />
940 </div>
941 );
943​
944function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
945 return (
946 <ul
947 className={cn(
948 "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",
949 "group-data-[collapsible=icon]:hidden",
950 className,
951 )}
952 data-sidebar="menu-sub"
953 data-slot="sidebar-menu-sub"
954 {...props}
955 />
956 );
958​
959function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
960 return (
961 <li
962 className={cn("group/menu-sub-item relative", className)}
963 data-sidebar="menu-sub-item"
964 data-slot="sidebar-menu-sub-item"
965 {...props}
966 />
967 );
969​
970function SidebarMenuSubButton({
971 size = "md",
972 isActive = false,
973 className,
974 render,
975 ...props
976}: useRender.ComponentProps<"a"> & {
977 size?: "sm" | "md";
978 isActive?: boolean;
979}) {
980 const defaultProps = {
981 className: cn(
982 "-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-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",
983 "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
984 size === "sm" && "text-xs",
985 size === "md" && "text-sm",
986 "group-data-[collapsible=icon]:hidden",
987 className,
988 ),
989 "data-active": isActive,
990 "data-sidebar": "menu-sub-button",
991 "data-size": size,
992 "data-slot": "sidebar-menu-sub-button",
993 };
994​
995 return useRender({
996 defaultTagName: "a",
997 props: mergeProps<"a">(defaultProps, props),
998 render,
999 });
1001​
1002export {
1003 Sidebar,
1004 SidebarContent,
1005 SidebarFooter,
1006 SidebarGroup,
1007 SidebarGroupAction,
1008 SidebarGroupContent,
1009 SidebarGroupLabel,
1010 SidebarHeader,
1011 SidebarInput,
1012 SidebarInset,
1013 SidebarMenu,
1014 SidebarMenuAction,
1015 SidebarMenuBadge,
1016 SidebarMenuButton,
1017 SidebarMenuItem,
1018 SidebarMenuSkeleton,
1019 SidebarMenuSub,
1020 SidebarMenuSubButton,
1021 SidebarMenuSubItem,
1022 SidebarProvider,
1023 SidebarRail,
1024 SidebarSeparator,
1025 SidebarTrigger,
1026 useSidebar,
1027 useSidebarVisibility,