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