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.useEffect(() => {
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 const storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
566 if (storedWidth === null) return;
567 const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
568 wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
569 resolvedResizable.onResize?.(clampedWidth);
570 }, [resolvedResizable]);
571
572 React.useEffect(() => {
573 return () => {
574 const resizeState = resizeStateRef.current;
575 if (resizeState?.rafId != null) {
576 window.cancelAnimationFrame(resizeState.rafId);
577 }
578 resizeState?.transitionTargets.forEach((element) => {
579 element.style.removeProperty("transition-duration");
580 });
581 document.body.style.removeProperty("cursor");
582 document.body.style.removeProperty("user-select");
583 };
584 }, []);
585
586 return (
587 <Tooltip>
588 <TooltipTrigger
589 render={
590 <button
591 aria-label={railLabel}
592 className={cn(
593 /* 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. */
594 "-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",
595 "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
596 "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
597 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
598 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
599 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
600 className,
601 )}
602 data-sidebar="rail"
603 data-slot="sidebar-rail"
604 onClick={handleClick}
605 onPointerCancel={handlePointerCancel}
606 onPointerDown={handlePointerDown}
607 onPointerMove={handlePointerMove}
608 onPointerUp={handlePointerUp}
609 ref={railRef}
610 tabIndex={-1}
611 type="button"
612 {...props}
613 />
614 }
615 />
616 <TooltipPopup side="right">{railTitle}</TooltipPopup>
617 </Tooltip>
618 );
619}
620
621function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
622 return (
623 <main
624 className={cn(
625 "relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
626 "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",
627 className,
628 )}
629 data-slot="sidebar-inset"
630 {...props}
631 />
632 );
633}
634
635function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
636 return (
637 <Input
638 className={cn("h-8 w-full bg-background shadow-none", className)}
639 data-sidebar="input"
640 data-slot="sidebar-input"
641 {...props}
642 />
643 );
644}
645
646function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
647 return (
648 <div
649 className={cn("flex flex-col gap-2 p-2", className)}
650 data-sidebar="header"
651 data-slot="sidebar-header"
652 {...props}
653 />
654 );
655}
656
657function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
658 return (
659 <div
660 className={cn("flex flex-col gap-2 p-2", className)}
661 data-sidebar="footer"
662 data-slot="sidebar-footer"
663 {...props}
664 />
665 );
666}
667
668function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
669 return (
670 <Separator
671 className={cn("mx-2 w-auto bg-sidebar-border", className)}
672 data-sidebar="separator"
673 data-slot="sidebar-separator"
674 {...props}
675 />
676 );
677}
678
679function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
680 return (
681 <ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
682 <div
683 className={cn(
684 "flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
685 className,
686 )}
687 data-sidebar="content"
688 data-slot="sidebar-content"
689 {...props}
690 />
691 </ScrollArea>
692 );
693}
694
695function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
696 return (
697 <div
698 className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
699 data-sidebar="group"
700 data-slot="sidebar-group"
701 {...props}
702 />
703 );
704}
705
706function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
707 const defaultProps = {
708 className: cn(
709 "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",
710 "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
711 className,
712 ),
713 "data-sidebar": "group-label",
714 "data-slot": "sidebar-group-label",
715 };
716
717 return useRender({
718 defaultTagName: "div",
719 props: mergeProps(defaultProps, props),
720 render,
721 });
722}
723
724function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
725 const defaultProps = {
726 className: cn(
727 "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
728 // Increases the hit area of the button on mobile.
729 "after:-inset-2 after:absolute md:after:hidden",
730 "group-data-[collapsible=icon]:hidden",
731 className,
732 ),
733 "data-sidebar": "group-action",
734 "data-slot": "sidebar-group-action",
735 };
736
737 return useRender({
738 defaultTagName: "button",
739 props: mergeProps(defaultProps, props),
740 render,
741 });
742}
743
744function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
745 return (
746 <div
747 className={cn("w-full text-sm", className)}
748 data-sidebar="group-content"
749 data-slot="sidebar-group-content"
750 {...props}
751 />
752 );
753}
754
755function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
756 return (
757 <ul
758 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
759 data-sidebar="menu"
760 data-slot="sidebar-menu"
761 {...props}
762 />
763 );
764}
765
766function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
767 return (
768 <li
769 className={cn("group/menu-item relative", className)}
770 data-sidebar="menu-item"
771 data-slot="sidebar-menu-item"
772 {...props}
773 />
774 );
775}
776
777const sidebarMenuButtonVariants = cva(
778 "peer/menu-button flex w-full cursor-pointer items-center gap-2 overflow-hidden rounded-lg p-2 text-left text-sm outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
779 {
780 defaultVariants: {
781 size: "default",
782 variant: "default",
783 },
784 variants: {
785 size: {
786 default: "h-8 text-sm",
787 lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
788 sm: "h-7 text-xs",
789 },
790 variant: {
791 default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
792 outline:
793 "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
794 },
795 },
796 },
797);
798
799function SidebarMenuButton({
800 isActive = false,
801 variant = "default",
802 size = "default",
803 tooltip,
804 className,
805 render,
806 ...props
807}: useRender.ComponentProps<"button"> & {
808 isActive?: boolean;
809 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
810} & VariantProps<typeof sidebarMenuButtonVariants>) {
811 const { isMobile, state } = useSidebar();
812
813 const defaultProps = {
814 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
815 "data-active": isActive,
816 "data-sidebar": "menu-button",
817 "data-size": size,
818 "data-slot": "sidebar-menu-button",
819 };
820
821 const buttonProps = mergeProps<"button">(defaultProps, props);
822
823 const buttonElement = useRender({
824 defaultTagName: "button",
825 props: buttonProps,
826 render,
827 });
828
829 if (!tooltip) {
830 return buttonElement;
831 }
832
833 if (typeof tooltip === "string") {
834 tooltip = {
835 children: tooltip,
836 };
837 }
838
839 return (
840 <Tooltip>
841 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
842 <TooltipPopup
843 align="center"
844 hidden={state !== "collapsed" || isMobile}
845 side="right"
846 {...tooltip}
847 />
848 </Tooltip>
849 );
850}
851
852function SidebarMenuAction({
853 className,
854 showOnHover = false,
855 render,
856 ...props
857}: useRender.ComponentProps<"button"> & {
858 showOnHover?: boolean;
859}) {
860 const defaultProps = {
861 className: cn(
862 "absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
863 // Increases the hit area of the button on mobile.
864 "after:-inset-2 after:absolute md:after:hidden",
865 "peer-data-[size=sm]/menu-button:top-1",
866 "peer-data-[size=default]/menu-button:top-1.5",
867 "peer-data-[size=lg]/menu-button:top-2.5",
868 "group-data-[collapsible=icon]:hidden",
869 showOnHover &&
870 "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
871 className,
872 ),
873 "data-sidebar": "menu-action",
874 "data-slot": "sidebar-menu-action",
875 };
876
877 return useRender({
878 defaultTagName: "button",
879 props: mergeProps<"button">(defaultProps, props),
880 render,
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-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-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-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
975 "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-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 SidebarMenuAction,
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};