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

sidebar.tsx

1,043 lines33.8 KB

1import { mergeProps } from "@base-ui/react/merge-props";
2import { useRender } from "@base-ui/react/use-render";
3import { cva, type VariantProps } from "class-variance-authority";
4import { PanelLeftCloseIcon, PanelLeftIcon } from "lucide-react";
5import * as React from "react";
6import { cn } from "~/lib/utils";
7import { Button } from "~/components/ui/button";
8import { Input } from "~/components/ui/input";
9import { ScrollArea } from "~/components/ui/scroll-area";
10import { Separator } from "~/components/ui/separator";
11import {
12 Sheet,
13 SheetDescription,
14 SheetHeader,
15 SheetPopup,
16 SheetTitle,
17} from "~/components/ui/sheet";
18import { Skeleton } from "~/components/ui/skeleton";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
20import { useIsMobile } from "~/hooks/useMediaQuery";
21import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
22import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
23import * as Schema from "effect/Schema";
24​
25const SIDEBAR_COOKIE_NAME = "sidebar_state";
26const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
27const SIDEBAR_WIDTH = "16rem";
28const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
29const SIDEBAR_WIDTH_ICON = "3rem";
30const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
31​
32type SidebarContextProps = {
33 state: ResponsiveSidebarState;
34 open: boolean;
35 setOpen: (open: boolean) => void;
36 openMobile: boolean;
37 setOpenMobile: (open: boolean) => void;
38 isMobile: boolean;
39 toggleSidebar: () => void;
40};
41​
42type SidebarResizableOptions = {
43 maxWidth?: number;
44 minWidth?: number;
45 onResize?: (width: number) => void;
46 shouldAcceptWidth?: (context: {
47 currentWidth: number;
48 nextWidth: number;
49 rail: HTMLButtonElement;
50 side: "left" | "right";
51 sidebarRoot: HTMLElement;
52 wrapper: HTMLElement;
53 }) => boolean;
54 storageKey?: string;
55};
56​
57type SidebarResolvedResizableOptions = {
58 maxWidth: number;
59 minWidth: number;
60 onResize?: (width: number) => void;
61 shouldAcceptWidth?: (context: {
62 currentWidth: number;
63 nextWidth: number;
64 rail: HTMLButtonElement;
65 side: "left" | "right";
66 sidebarRoot: HTMLElement;
67 wrapper: HTMLElement;
68 }) => boolean;
69 storageKey: string | null;
70};
71​
72type SidebarInstanceContextProps = {
73 resizable: SidebarResolvedResizableOptions | null;
74 side: "left" | "right";
75};
76​
77const SidebarContext = React.createContext<SidebarContextProps | null>(null);
78const SidebarInstanceContext = React.createContext<SidebarInstanceContextProps | null>(null);
79​
80function useSidebar() {
81 const context = React.use(SidebarContext);
82 if (!context) {
83 throw new Error("useSidebar must be used within a SidebarProvider.");
84 }
85​
86 return context;
88​
89function useSidebarVisibility() {
90 const { isMobile, open, openMobile } = useSidebar();
91 return isMobile ? openMobile : open;
93​
94function SidebarProvider({
95 defaultOpen = true,
96 open: openProp,
97 onOpenChange: setOpenProp,
98 className,
99 style,
100 children,
101 ...props
102}: React.ComponentProps<"div"> & {
103 defaultOpen?: boolean;
104 open?: boolean;
105 onOpenChange?: (open: boolean) => void;
106}) {
107 const isMobile = useIsMobile();
108 const [openMobile, setOpenMobile] = React.useState(false);
109​
110 // This is the internal state of the sidebar.
111 // We use openProp and setOpenProp for control from outside the component.
112 const [_open, _setOpen] = React.useState(defaultOpen);
113 const open = openProp ?? _open;
114 const setOpen = React.useCallback(
115 async (value: boolean | ((value: boolean) => boolean)) => {
116 const openState = typeof value === "function" ? value(open) : value;
117 if (setOpenProp) {
118 setOpenProp(openState);
119 } else {
120 _setOpen(openState);
121 }
122​
123 // This sets the cookie to keep the sidebar state.
124 await cookieStore.set({
125 expires: Date.now() + SIDEBAR_COOKIE_MAX_AGE * 1000,
126 name: SIDEBAR_COOKIE_NAME,
127 path: "/",
128 value: String(openState),
129 });
130 },
131 [setOpenProp, open],
132 );
133​
134 // Helper to toggle the sidebar.
135 const toggleSidebar = React.useCallback(() => {
136 return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
137 }, [isMobile, setOpen]);
138​
139 // We add a state so that we can do data-state="expanded" or "collapsed".
140 // This makes it easier to style the sidebar with Tailwind classes.
141 const state = resolveSidebarState({ isMobile, open, openMobile });
142​
143 const contextValue = React.useMemo<SidebarContextProps>(
144 () => ({
145 isMobile,
146 open,
147 openMobile,
148 setOpen,
149 setOpenMobile,
150 state,
151 toggleSidebar,
152 }),
153 [state, open, setOpen, isMobile, openMobile, toggleSidebar],
154 );
155​
156 return (
157 <SidebarContext value={contextValue}>
158 <div
159 className={cn(
160 "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
161 className,
162 )}
163 data-sidebar-state={state}
164 data-slot="sidebar-wrapper"
165 style={
166 {
167 "--sidebar-width": SIDEBAR_WIDTH,
168 "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
169 "--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 );
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 transition-[width] duration-200 ease-linear",
285 "group-data-[collapsible=offcanvas]:w-0",
286 "group-data-[side=right]:rotate-180",
287 variant === "floating" || variant === "inset"
288 ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
289 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
290 )}
291 data-slot="sidebar-gap"
292 />
293 <div
294 className={cn(
295 "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
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 );
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 );
347​
348function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
349 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
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 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",
605 "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
606 "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
607 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
608 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
609 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
610 className,
611 )}
612 data-sidebar="rail"
613 data-slot="sidebar-rail"
614 onClick={handleClick}
615 onPointerCancel={handlePointerCancel}
616 onPointerDown={handlePointerDown}
617 onPointerMove={handlePointerMove}
618 onPointerUp={handlePointerUp}
619 ref={railRef}
620 tabIndex={-1}
621 type="button"
622 {...props}
623 />
624 }
625 />
626 <TooltipPopup side="right">{railTitle}</TooltipPopup>
627 </Tooltip>
628 );
630​
631function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
632 return (
633 <main
634 className={cn(
635 "relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
636 "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",
637 className,
638 )}
639 data-slot="sidebar-inset"
640 {...props}
641 />
642 );
644​
645function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
646 return (
647 <Input
648 className={cn("h-8 w-full bg-background shadow-none", className)}
649 data-sidebar="input"
650 data-slot="sidebar-input"
651 {...props}
652 />
653 );
655​
656function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
657 return (
658 <div
659 className={cn("flex flex-col gap-2 p-2", className)}
660 data-sidebar="header"
661 data-slot="sidebar-header"
662 {...props}
663 />
664 );
666​
667function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
668 return (
669 <div
670 className={cn("flex flex-col gap-2 p-2", className)}
671 data-sidebar="footer"
672 data-slot="sidebar-footer"
673 {...props}
674 />
675 );
677​
678function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
679 return (
680 <Separator
681 className={cn("mx-2 w-auto! bg-sidebar-border", className)}
682 data-sidebar="separator"
683 data-slot="sidebar-separator"
684 {...props}
685 />
686 );
688​
689function SidebarContent({
690 className,
691 fixedHeader,
692 ...props
693}: React.ComponentProps<"div"> & {
694 fixedHeader?: React.ReactNode;
695}) {
696 return (
697 <>
698 {fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
699 <ScrollArea hideScrollbars scrollFade className="h-auto min-h-0 flex-1">
700 <div
701 className={cn(
702 "flex w-full min-w-0 flex-col gap-2 group-data-[collapsible=icon]:overflow-hidden",
703 className,
704 )}
705 data-sidebar="content"
706 data-slot="sidebar-content"
707 {...props}
708 />
709 </ScrollArea>
710 </>
711 );
713​
714function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
715 return (
716 <div
717 className={cn(
718 "relative flex w-full min-w-0 flex-col p-[var(--sidebar-content-inset)]",
719 className,
720 )}
721 data-sidebar="group"
722 data-slot="sidebar-group"
723 {...props}
724 />
725 );
727​
728function SidebarGroupLabel({ className, render, ...props }: useRender.ComponentProps<"div">) {
729 const defaultProps = {
730 className: cn(
731 "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",
732 "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
733 className,
734 ),
735 "data-sidebar": "group-label",
736 "data-slot": "sidebar-group-label",
737 };
738​
739 return useRender({
740 defaultTagName: "div",
741 props: mergeProps(defaultProps, props),
742 render,
743 });
745​
746function SidebarGroupAction({ className, render, ...props }: useRender.ComponentProps<"button">) {
747 const defaultProps = {
748 className: cn(
749 "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",
750 // Increases the hit area of the button on mobile.
751 "after:-inset-2 after:absolute md:after:hidden",
752 "group-data-[collapsible=icon]:hidden",
753 className,
754 ),
755 "data-sidebar": "group-action",
756 "data-slot": "sidebar-group-action",
757 };
758​
759 return useRender({
760 defaultTagName: "button",
761 props: mergeProps(defaultProps, props),
762 render,
763 });
765​
766function SidebarGroupContent({ className, ...props }: React.ComponentProps<"div">) {
767 return (
768 <div
769 className={cn("w-full text-sm", className)}
770 data-sidebar="group-content"
771 data-slot="sidebar-group-content"
772 {...props}
773 />
774 );
776​
777function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
778 return (
779 <ul
780 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
781 data-sidebar="menu"
782 data-slot="sidebar-menu"
783 {...props}
784 />
785 );
787​
788function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
789 return (
790 <li
791 className={cn("group/menu-item relative", className)}
792 data-sidebar="menu-item"
793 data-slot="sidebar-menu-item"
794 {...props}
795 />
796 );
798​
799const sidebarMenuButtonVariants = cva(
800 "peer/menu-button flex w-full cursor-pointer items-center gap-[var(--sidebar-control-gap)] overflow-hidden text-left outline-hidden ring-ring transition-[width,height,padding] hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 active:bg-sidebar-row-active active:text-sidebar-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-row-selected data-[active=true]:font-medium data-[active=true]:text-sidebar-foreground data-[state=open]:hover:bg-sidebar-row-hover data-[state=open]:hover:text-sidebar-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-[var(--sidebar-content-inset)]! [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-[var(--sidebar-icon-color)] hover:[&>svg]:text-sidebar-foreground active:[&>svg]:text-sidebar-foreground data-[active=true]:[&>svg]:text-sidebar-foreground",
801 {
802 defaultVariants: {
803 size: "default",
804 variant: "default",
805 },
806 variants: {
807 size: {
808 default:
809 "h-8 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-1.5 text-sm",
810 icon: "size-8 justify-center rounded-[var(--control-radius)] p-0",
811 lg: "h-12 rounded-lg p-2 text-sm group-data-[collapsible=icon]:p-0!",
812 sm: "h-7 rounded-lg p-2 text-xs",
813 },
814 variant: {
815 default: "font-medium text-sidebar-muted-foreground/80",
816 outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
817 },
818 },
819 },
820);
821​
822function SidebarMenuButton({
823 isActive = false,
824 variant = "default",
825 size = "default",
826 tooltip,
827 className,
828 render,
829 ...props
830}: useRender.ComponentProps<"button"> & {
831 isActive?: boolean;
832 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
833} & VariantProps<typeof sidebarMenuButtonVariants>) {
834 const { isMobile, state } = useSidebar();
835​
836 const defaultProps = {
837 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
838 "data-active": isActive,
839 "data-sidebar": "menu-button",
840 "data-size": size,
841 "data-slot": "sidebar-menu-button",
842 };
843​
844 const buttonProps = mergeProps<"button">(defaultProps, props);
845​
846 const buttonElement = useRender({
847 defaultTagName: "button",
848 props: buttonProps,
849 render,
850 });
851​
852 if (!tooltip) {
853 return buttonElement;
854 }
855​
856 if (typeof tooltip === "string") {
857 tooltip = {
858 children: tooltip,
859 };
860 }
861​
862 return (
863 <Tooltip>
864 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
865 <TooltipPopup
866 align="center"
867 hidden={state !== "collapsed" || isMobile}
868 side="right"
869 {...tooltip}
870 />
871 </Tooltip>
872 );
874​
875function SidebarMenuAction({
876 className,
877 showOnHover = false,
878 render,
879 ...props
880}: useRender.ComponentProps<"button"> & {
881 showOnHover?: boolean;
882}) {
883 const defaultProps = {
884 className: cn(
885 "absolute top-1.5 right-1 flex aspect-square w-5 cursor-pointer items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-ring transition-transform hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
886 // Increases the hit area of the button on mobile.
887 "after:-inset-2 after:absolute md:after:hidden",
888 "peer-data-[size=sm]/menu-button:top-1",
889 "peer-data-[size=default]/menu-button:top-1.5",
890 "peer-data-[size=lg]/menu-button:top-2.5",
891 "group-data-[collapsible=icon]:hidden",
892 showOnHover &&
893 "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-foreground md:opacity-0",
894 className,
895 ),
896 "data-sidebar": "menu-action",
897 "data-slot": "sidebar-menu-action",
898 };
899​
900 return useRender({
901 defaultTagName: "button",
902 props: mergeProps<"button">(defaultProps, props),
903 render,
904 });
906​
907function SidebarMenuBadge({ className, ...props }: React.ComponentProps<"div">) {
908 return (
909 <div
910 className={cn(
911 "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",
912 "peer-hover/menu-button:text-sidebar-foreground peer-data-[active=true]/menu-button:text-sidebar-foreground",
913 "peer-data-[size=sm]/menu-button:top-1",
914 "peer-data-[size=default]/menu-button:top-1.5",
915 "peer-data-[size=lg]/menu-button:top-2.5",
916 "group-data-[collapsible=icon]:hidden",
917 className,
918 )}
919 data-sidebar="menu-badge"
920 data-slot="sidebar-menu-badge"
921 {...props}
922 />
923 );
925​
926function SidebarMenuSkeleton({
927 className,
928 showIcon = false,
929 ...props
930}: React.ComponentProps<"div"> & {
931 showIcon?: boolean;
932}) {
933 // Random width between 50 to 90%. Intentionally wrapped in useMemo to avoid changing width on every render.
934 const width = React.useMemo(() => {
935 return `${Math.floor(Math.random() * 40) + 50}%`;
936 }, []);
937​
938 return (
939 <div
940 className={cn("flex h-8 items-center gap-2 rounded-lg px-2", className)}
941 data-sidebar="menu-skeleton"
942 data-slot="sidebar-menu-skeleton"
943 {...props}
944 >
945 {showIcon && <Skeleton className="size-4 rounded-lg" data-sidebar="menu-skeleton-icon" />}
946 <Skeleton
947 className="h-4 max-w-(--skeleton-width) flex-1"
948 data-sidebar="menu-skeleton-text"
949 style={
950 {
951 "--skeleton-width": width,
952 } as React.CSSProperties
953 }
954 />
955 </div>
956 );
958​
959function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
960 return (
961 <ul
962 className={cn(
963 "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",
964 "group-data-[collapsible=icon]:hidden",
965 className,
966 )}
967 data-sidebar="menu-sub"
968 data-slot="sidebar-menu-sub"
969 {...props}
970 />
971 );
973​
974function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
975 return (
976 <li
977 className={cn("group/menu-sub-item relative", className)}
978 data-sidebar="menu-sub-item"
979 data-slot="sidebar-menu-sub-item"
980 {...props}
981 />
982 );
984​
985function SidebarMenuSubButton({
986 size = "md",
987 isActive = false,
988 className,
989 render,
990 ...props
991}: useRender.ComponentProps<"a"> & {
992 size?: "sm" | "md";
993 isActive?: boolean;
994}) {
995 const defaultProps = {
996 className: cn(
997 "-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",
998 "data-[active=true]:bg-sidebar-row-selected data-[active=true]:text-sidebar-foreground",
999 size === "sm" && "text-xs",
1000 size === "md" && "text-sm",
1001 "group-data-[collapsible=icon]:hidden",
1002 className,
1003 ),
1004 "data-active": isActive,
1005 "data-sidebar": "menu-sub-button",
1006 "data-size": size,
1007 "data-slot": "sidebar-menu-sub-button",
1008 };
1009​
1010 return useRender({
1011 defaultTagName: "a",
1012 props: mergeProps<"a">(defaultProps, props),
1013 render,
1014 });
1016​
1017export {
1018 Sidebar,
1019 SidebarContent,
1020 SidebarFooter,
1021 SidebarGroup,
1022 SidebarGroupAction,
1023 SidebarGroupContent,
1024 SidebarGroupLabel,
1025 SidebarHeader,
1026 SidebarInput,
1027 SidebarInset,
1028 SidebarMenu,
1029 SidebarMenuAction,
1030 SidebarMenuBadge,
1031 SidebarMenuButton,
1032 SidebarMenuItem,
1033 SidebarMenuSkeleton,
1034 SidebarMenuSub,
1035 SidebarMenuSubButton,
1036 SidebarMenuSubItem,
1037 SidebarProvider,
1038 SidebarRail,
1039 SidebarSeparator,
1040 SidebarTrigger,
1041 useSidebar,
1042 useSidebarVisibility,