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