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