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

sidebar.tsx

1,037 lines33.6 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({
688 className,
689 fixedHeader,
690 ...props
691}: React.ComponentProps<"div"> & {
692 fixedHeader?: React.ReactNode;
693}) {
694 return (
695 <>
696 {fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
697 <ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
698 <div
699 className={cn(
700 "flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
701 className,
702 )}
703 data-sidebar="content"
704 data-slot="sidebar-content"
705 {...props}
706 />
707 </ScrollArea>
708 </>
709 );
711​
712function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
713 return (
714 <div
715 className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
716 data-sidebar="group"
717 data-slot="sidebar-group"
718 {...props}
719 />
720 );
722​
723function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
724 const defaultProps = {
725 className: cn(
726 "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",
727 "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
728 className,
729 ),
730 "data-sidebar": "group-label",
731 "data-slot": "sidebar-group-label",
732 };
733​
734 return useRender({
735 defaultTagName: "div",
736 props: mergeProps(defaultProps, props),
737 render,
738 });
740​
741function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
742 const defaultProps = {
743 className: cn(
744 "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",
745 // Increases the hit area of the button on mobile.
746 "after:-inset-2 after:absolute md:after:hidden",
747 "group-data-[collapsible=icon]:hidden",
748 className,
749 ),
750 "data-sidebar": "group-action",
751 "data-slot": "sidebar-group-action",
752 };
753​
754 return useRender({
755 defaultTagName: "button",
756 props: mergeProps(defaultProps, props),
757 render,
758 });
760​
761function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
762 return (
763 <div
764 className={cn("w-full text-sm", className)}
765 data-sidebar="group-content"
766 data-slot="sidebar-group-content"
767 {...props}
768 />
769 );
771​
772function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
773 return (
774 <ul
775 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
776 data-sidebar="menu"
777 data-slot="sidebar-menu"
778 {...props}
779 />
780 );
782​
783function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
784 return (
785 <li
786 className={cn("group/menu-item relative", className)}
787 data-sidebar="menu-item"
788 data-slot="sidebar-menu-item"
789 {...props}
790 />
791 );
793​
794const sidebarMenuButtonVariants = cva(
795 "peer/menu-button flex w-full cursor-pointer items-center gap-2 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 group-has-data-[sidebar=menu-action]/menu-item:pe-8 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-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-muted-foreground [&>svg]:opacity-60 hover:[&>svg]:text-sidebar-foreground hover:[&>svg]:opacity-100 active:[&>svg]:text-sidebar-foreground active:[&>svg]:opacity-100 data-[active=true]:[&>svg]:text-sidebar-foreground data-[active=true]:[&>svg]:opacity-100",
796 {
797 defaultVariants: {
798 size: "default",
799 variant: "default",
800 },
801 variants: {
802 size: {
803 default: "h-8 rounded-md px-2.5 py-1.5 text-sm",
804 icon: "size-8 justify-center rounded-md p-0",
805 lg: "h-12 rounded-lg p-2 text-sm group-data-[collapsible=icon]:p-0!",
806 sm: "h-7 rounded-lg p-2 text-xs",
807 },
808 variant: {
809 default: "font-medium text-sidebar-muted-foreground/80",
810 outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
811 },
812 },
813 },
814);
815​
816function SidebarMenuButton({
817 isActive = false,
818 variant = "default",
819 size = "default",
820 tooltip,
821 className,
822 render,
823 ...props
824}: useRender.ComponentProps<"button"> & {
825 isActive?: boolean;
826 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
827} & VariantProps<typeof sidebarMenuButtonVariants>) {
828 const { isMobile, state } = useSidebar();
829​
830 const defaultProps = {
831 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
832 "data-active": isActive,
833 "data-sidebar": "menu-button",
834 "data-size": size,
835 "data-slot": "sidebar-menu-button",
836 };
837​
838 const buttonProps = mergeProps<"button">(defaultProps, props);
839​
840 const buttonElement = useRender({
841 defaultTagName: "button",
842 props: buttonProps,
843 render,
844 });
845​
846 if (!tooltip) {
847 return buttonElement;
848 }
849​
850 if (typeof tooltip === "string") {
851 tooltip = {
852 children: tooltip,
853 };
854 }
855​
856 return (
857 <Tooltip>
858 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
859 <TooltipPopup
860 align="center"
861 hidden={state !== "collapsed" || isMobile}
862 side="right"
863 {...tooltip}
864 />
865 </Tooltip>
866 );
868​
869function SidebarMenuAction({
870 className,
871 showOnHover = false,
872 render,
873 ...props
874}: useRender.ComponentProps<"button"> & {
875 showOnHover?: boolean;
876}) {
877 const defaultProps = {
878 className: cn(
879 "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-row-hover hover:text-sidebar-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
880 // Increases the hit area of the button on mobile.
881 "after:-inset-2 after:absolute md:after:hidden",
882 "peer-data-[size=sm]/menu-button:top-1",
883 "peer-data-[size=default]/menu-button:top-1.5",
884 "peer-data-[size=lg]/menu-button:top-2.5",
885 "group-data-[collapsible=icon]:hidden",
886 showOnHover &&
887 "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-foreground md:opacity-0",
888 className,
889 ),
890 "data-sidebar": "menu-action",
891 "data-slot": "sidebar-menu-action",
892 };
893​
894 return useRender({
895 defaultTagName: "button",
896 props: mergeProps<"button">(defaultProps, props),
897 render,
898 });
900​
901function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
902 return (
903 <div
904 className={cn(
905 "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",
906 "peer-hover/menu-button:text-sidebar-foreground peer-data-[active=true]/menu-button:text-sidebar-foreground",
907 "peer-data-[size=sm]/menu-button:top-1",
908 "peer-data-[size=default]/menu-button:top-1.5",
909 "peer-data-[size=lg]/menu-button:top-2.5",
910 "group-data-[collapsible=icon]:hidden",
911 className,
912 )}
913 data-sidebar="menu-badge"
914 data-slot="sidebar-menu-badge"
915 {...props}
916 />
917 );
919​
920function SidebarMenuSkeleton({
921 className,
922 showIcon = false,
923 ...props
924}: React.ComponentProps<"div"> & {
925 showIcon?: boolean;
926}) {
927 // Random width between 50 to 90%. Intentionally wrapped in useMemo to avoid changing width on every render.
928 const width = React.useMemo(() => {
929 return `${Math.floor(Math.random() * 40) + 50}%`;
930 }, []);
931​
932 return (
933 <div
934 className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
935 data-sidebar="menu-skeleton"
936 data-slot="sidebar-menu-skeleton"
937 {...props}
938 >
939 {showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
940 <Skeleton
941 className="h-4 max-w-(--skeleton-width) flex-1"
942 data-sidebar="menu-skeleton-text"
943 style={
944 {
945 "--skeleton-width": width,
946 } as React.CSSProperties
947 }
948 />
949 </div>
950 );
952​
953function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
954 return (
955 <ul
956 className={cn(
957 "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",
958 "group-data-[collapsible=icon]:hidden",
959 className,
960 )}
961 data-sidebar="menu-sub"
962 data-slot="sidebar-menu-sub"
963 {...props}
964 />
965 );
967​
968function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
969 return (
970 <li
971 className={cn("group/menu-sub-item relative", className)}
972 data-sidebar="menu-sub-item"
973 data-slot="sidebar-menu-sub-item"
974 {...props}
975 />
976 );
978​
979function SidebarMenuSubButton({
980 size = "md",
981 isActive = false,
982 className,
983 render,
984 ...props
985}: useRender.ComponentProps<"a"> & {
986 size?: "sm" | "md";
987 isActive?: boolean;
988}) {
989 const defaultProps = {
990 className: cn(
991 "-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",
992 "data-[active=true]:bg-sidebar-row-selected data-[active=true]:text-sidebar-foreground",
993 size === "sm" && "text-xs",
994 size === "md" && "text-sm",
995 "group-data-[collapsible=icon]:hidden",
996 className,
997 ),
998 "data-active": isActive,
999 "data-sidebar": "menu-sub-button",
1000 "data-size": size,
1001 "data-slot": "sidebar-menu-sub-button",
1002 };
1003​
1004 return useRender({
1005 defaultTagName: "a",
1006 props: mergeProps<"a">(defaultProps, props),
1007 render,
1008 });
1010​
1011export {
1012 Sidebar,
1013 SidebarContent,
1014 SidebarFooter,
1015 SidebarGroup,
1016 SidebarGroupAction,
1017 SidebarGroupContent,
1018 SidebarGroupLabel,
1019 SidebarHeader,
1020 SidebarInput,
1021 SidebarInset,
1022 SidebarMenu,
1023 SidebarMenuAction,
1024 SidebarMenuBadge,
1025 SidebarMenuButton,
1026 SidebarMenuItem,
1027 SidebarMenuSkeleton,
1028 SidebarMenuSub,
1029 SidebarMenuSubButton,
1030 SidebarMenuSubItem,
1031 SidebarProvider,
1032 SidebarRail,
1033 SidebarSeparator,
1034 SidebarTrigger,
1035 useSidebar,
1036 useSidebarVisibility,