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

sidebar.tsx

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