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, type InputProps } from "~/components/ui/input";
9import { ScrollArea } from "~/components/ui/scroll-area";
10import {
11 Sheet,
12 SheetDescription,
13 SheetHeader,
14 SheetPopup,
15 SheetTitle,
16} from "~/components/ui/sheet";
17import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
18import { useResizeDrag } from "~/hooks/useResizeDrag";
19import { useMediaQuery } from "~/hooks/useMediaQuery";
20import { useClientSettings } from "~/hooks/useSettings";
21import {
22 getLocalStorageItem,
23 setLocalStorageItem,
24 writeLocalStorageValue,
25} from "~/hooks/useLocalStorage";
26import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
27import * as Schema from "effect/Schema";
28import { announceSidebarVisibility } from "~/lib/accessibilityAnnouncements";
29
30const SIDEBAR_WIDTH = "16rem";
31const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing) * 3)";
32const SIDEBAR_WIDTH_ICON = "3rem";
33const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
34const SIDEBAR_TITLEBAR_CONTROL_SIZE = "max-sm:[--workspace-titlebar-control-size:--spacing(8)]";
35
36type SidebarContextProps = {
37 state: ResponsiveSidebarState;
38 open: boolean;
39 setOpen: (open: boolean) => void;
40 openMobile: boolean;
41 mobileSheetMounted: boolean;
42 setMobileSheetMounted: (mounted: boolean) => void;
43 setOpenMobile: (open: boolean) => void;
44 isMobile: boolean;
45 toggleSidebar: () => void;
46 /** Runs before the desktop sidebar collapses. */
47 onCollapse: (listener: () => void) => () => void;
48};
49
50type SidebarResizableOptions = {
51 maxWidth?: number;
52 minWidth?: number;
53 onResize?: (width: number) => void;
54 shouldAcceptWidth?: (context: {
55 currentWidth: number;
56 nextWidth: number;
57 rail: HTMLButtonElement;
58 side: "left" | "right";
59 sidebarRoot: HTMLElement;
60 wrapper: HTMLElement;
61 }) => boolean;
62 storageKey?: string;
63};
64
65type SidebarResolvedResizableOptions = {
66 maxWidth: number;
67 minWidth: number;
68 onResize?: (width: number) => void;
69 shouldAcceptWidth?: (context: {
70 currentWidth: number;
71 nextWidth: number;
72 rail: HTMLButtonElement;
73 side: "left" | "right";
74 sidebarRoot: HTMLElement;
75 wrapper: HTMLElement;
76 }) => boolean;
77 storageKey: string | null;
78};
79
80type SidebarInstanceContextProps = {
81 resizable: SidebarResolvedResizableOptions | null;
82 side: "left" | "right";
83};
84
85const SidebarContext = React.createContext<SidebarContextProps | null>(null);
86const SidebarInstanceContext = React.createContext<SidebarInstanceContextProps | null>(null);
87
88function useSidebar() {
89 const context = React.use(SidebarContext);
90 if (!context) {
91 throw new Error("useSidebar must be used within a SidebarProvider.");
92 }
93
94 return context;
95}
96
97function useSidebarVisibility() {
98 const { isMobile, open, openMobile } = useSidebar();
99 return isMobile ? openMobile : open;
100}
101
102/** Whether the mobile sidebar sheet covers the page; false outside a SidebarProvider. */
103function useMobileSidebarSheetMounted() {
104 const context = React.use(SidebarContext);
105 return context !== null && context.isMobile && context.mobileSheetMounted;
106}
107
108// The `max-md` breakpoint, also read when a shortcut fires.
109const SIDEBAR_MOBILE_QUERY = "(max-width: 767px)";
110
111function isMobileViewport(): boolean {
112 return typeof window !== "undefined" && window.matchMedia(SIDEBAR_MOBILE_QUERY).matches;
113}
114
115function readStoredSidebarOpen(storageKey: string | undefined): boolean | null {
116 if (!storageKey) return null;
117 try {
118 return getLocalStorageItem(storageKey, Schema.Boolean);
119 } catch (error) {
120 console.error("Could not restore persisted sidebar state.", error);
121 return null;
122 }
123}
124
125// An offcanvas sidebar turns inert once collapsed, which drops focus to the body.
126function moveFocusOutOfCollapsingSidebar() {
127 const sidebar = document.activeElement?.closest<HTMLElement>(
128 '[data-slot="sidebar"][data-collapsible-mode="offcanvas"]',
129 );
130 const wrapper = sidebar?.closest<HTMLElement>('[data-slot="sidebar-wrapper"]');
131 if (!sidebar || !wrapper) return;
132 const trigger = Array.from(
133 wrapper.querySelectorAll<HTMLElement>('[data-sidebar="trigger"]'),
134 ).find((element) => !sidebar.contains(element));
135 trigger?.focus({ preventScroll: true });
136}
137
138interface SidebarOpenState {
139 readonly open: boolean;
140 readonly openMobile: boolean;
141}
142
143/** Per-provider open state, kept outside React so shortcuts can toggle it at event time. */
144function createSidebarOpenStore(defaultOpen: boolean, storageKey: string | undefined) {
145 let state: SidebarOpenState = {
146 open: readStoredSidebarOpen(storageKey) ?? defaultOpen,
147 openMobile: false,
148 };
149 const listeners = new Set<() => void>();
150 const collapseListeners = new Set<() => void>();
151 const publish = (next: SidebarOpenState) => {
152 state = next;
153 for (const listener of listeners) listener();
154 };
155 const setOpen = (open: boolean) => {
156 if (!open && state.open) {
157 for (const listener of collapseListeners) listener();
158 moveFocusOutOfCollapsingSidebar();
159 }
160 if (open !== state.open) {
161 if (!isMobileViewport()) announceSidebarVisibility(open);
162 publish({ ...state, open });
163 }
164 if (storageKey) writeLocalStorageValue(storageKey, open, defaultOpen, Schema.Boolean);
165 };
166 const setOpenMobile = (openMobile: boolean) => {
167 if (openMobile !== state.openMobile) publish({ ...state, openMobile });
168 };
169 return {
170 subscribe: (listener: () => void) => {
171 listeners.add(listener);
172 return () => {
173 listeners.delete(listener);
174 };
175 },
176 getSnapshot: () => state,
177 setOpen,
178 setOpenMobile,
179 toggle: () => (isMobileViewport() ? setOpenMobile(!state.openMobile) : setOpen(!state.open)),
180 onCollapse: (listener: () => void) => {
181 collapseListeners.add(listener);
182 return () => {
183 collapseListeners.delete(listener);
184 };
185 },
186 };
187}
188
189function SidebarProvider({
190 defaultOpen = true,
191 storageKey,
192 className,
193 style,
194 children,
195 ...props
196}: React.ComponentProps<"div"> & {
197 defaultOpen?: boolean;
198 storageKey?: string;
199}) {
200 const isMobile = useMediaQuery(SIDEBAR_MOBILE_QUERY);
201 const [store] = React.useState(() => createSidebarOpenStore(defaultOpen, storageKey));
202 const { open, openMobile } = React.useSyncExternalStore(
203 store.subscribe,
204 store.getSnapshot,
205 store.getSnapshot,
206 );
207 const [mobileSheetMounted, setMobileSheetMounted] = React.useState(false);
208 if (openMobile && !mobileSheetMounted) {
209 setMobileSheetMounted(true);
210 }
211 // Widening mid-close unmounts the sheet before its close completes.
212 if (!isMobile && !openMobile && mobileSheetMounted) {
213 setMobileSheetMounted(false);
214 }
215
216 const state = resolveSidebarState({ isMobile, open, openMobile });
217
218 const contextValue: SidebarContextProps = {
219 isMobile,
220 open,
221 openMobile,
222 mobileSheetMounted,
223 setMobileSheetMounted,
224 setOpen: store.setOpen,
225 setOpenMobile: store.setOpenMobile,
226 state,
227 toggleSidebar: store.toggle,
228 onCollapse: store.onCollapse,
229 };
230
231 return (
232 <SidebarContext value={contextValue}>
233 <div
234 className={cn(
235 "group/sidebar-wrapper flex min-h-svh w-full",
236 SIDEBAR_TITLEBAR_CONTROL_SIZE,
237 className,
238 )}
239 data-sidebar-state={state}
240 data-slot="sidebar-wrapper"
241 style={
242 {
243 "--sidebar-width": SIDEBAR_WIDTH,
244 "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
245 "--workspace-titlebar-content-left":
246 "calc(var(--workspace-controls-left) + var(--workspace-titlebar-control-size) + var(--workspace-titlebar-control-gap))",
247 ...style,
248 } as React.CSSProperties
249 }
250 {...props}
251 >
252 {children}
253 </div>
254 </SidebarContext>
255 );
256}
257
258function resolveSidebarResizable({
259 collapsible,
260 isMobile,
261 resizable,
262}: {
263 collapsible: "offcanvas" | "icon" | "none";
264 isMobile: boolean;
265 resizable: boolean | SidebarResizableOptions;
266}): SidebarResolvedResizableOptions | null {
267 if (isMobile || collapsible === "none" || !resizable) {
268 return null;
269 }
270
271 const options = typeof resizable === "boolean" ? {} : resizable;
272 return {
273 maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY,
274 minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH,
275 storageKey: options.storageKey ?? null,
276 ...(options.onResize ? { onResize: options.onResize } : {}),
277 ...(options.shouldAcceptWidth ? { shouldAcceptWidth: options.shouldAcceptWidth } : {}),
278 };
279}
280
281function Sidebar({
282 side = "left",
283 variant = "sidebar",
284 collapsible = "offcanvas",
285 resizable = false,
286 className,
287 children,
288 ...props
289}: React.ComponentProps<"div"> & {
290 side?: "left" | "right";
291 variant?: "sidebar" | "floating" | "inset";
292 collapsible?: "offcanvas" | "icon" | "none";
293 resizable?: boolean | SidebarResizableOptions;
294}) {
295 const { isMobile, state, openMobile, setOpenMobile, setMobileSheetMounted } = useSidebar();
296 // Not usePanelAnimationSettings: its navigation suppression would snap the sheet shut mid-exit when an item navigates.
297 const panelAnimationDurationMs = useClientSettings(
298 (settings) => settings.panelAnimationDurationMs,
299 );
300 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
301 const panelAnimationsActive = panelAnimationDurationMs > 0 && !prefersReducedMotion;
302 const offcanvasCollapsed = !isMobile && collapsible === "offcanvas" && state === "collapsed";
303
304 const resolvedResizable = resolveSidebarResizable({ collapsible, isMobile, resizable });
305 const instanceContextValue: SidebarInstanceContextProps = { side, resizable: resolvedResizable };
306
307 if (collapsible === "none") {
308 return (
309 <SidebarInstanceContext value={instanceContextValue}>
310 <div
311 className={cn(
312 "flex h-full w-(--sidebar-width) flex-col bg-sidebar surface-grain text-sidebar-foreground",
313 className,
314 )}
315 data-slot="sidebar"
316 {...props}
317 >
318 {children}
319 </div>
320 </SidebarInstanceContext>
321 );
322 }
323
324 if (isMobile) {
325 return (
326 <SidebarInstanceContext value={instanceContextValue}>
327 <Sheet
328 onOpenChange={setOpenMobile}
329 onOpenChangeComplete={(open) => {
330 if (!open) setMobileSheetMounted(false);
331 }}
332 open={openMobile}
333 >
334 {/* Children stay mounted while closed so their window shortcuts, like thread jumps, keep working. */}
335 <SheetPopup
336 keepMounted
337 {...(panelAnimationsActive ? {} : { transitionDurationMs: 0 })}
338 className={cn(
339 "w-(--sidebar-width) max-w-none bg-sidebar surface-grain p-0 text-sidebar-foreground",
340 className,
341 )}
342 data-mobile="true"
343 data-sidebar="sidebar"
344 data-slot="sidebar"
345 showCloseButton={false}
346 side={side}
347 style={
348 {
349 "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
350 } as React.CSSProperties
351 }
352 >
353 <SheetHeader className="sr-only">
354 <SheetTitle>{props["aria-label"] ?? "Sidebar"}</SheetTitle>
355 <SheetDescription>Displays the mobile sidebar.</SheetDescription>
356 </SheetHeader>
357 <div
358 className={cn(
359 "flex h-full w-full flex-col pb-safe pt-safe",
360 SIDEBAR_TITLEBAR_CONTROL_SIZE,
361 side === "left" ? "pl-safe" : "pr-safe",
362 )}
363 {...props}
364 >
365 {children}
366 </div>
367 </SheetPopup>
368 </Sheet>
369 </SidebarInstanceContext>
370 );
371 }
372
373 return (
374 <SidebarInstanceContext value={instanceContextValue}>
375 <div
376 className="group peer hidden text-sidebar-foreground md:block"
377 data-collapsible={state === "collapsed" ? collapsible : ""}
378 data-collapsible-mode={collapsible}
379 inert={offcanvasCollapsed}
380 data-side={side}
381 data-slot="sidebar"
382 data-state={state}
383 data-variant={variant}
384 >
385 <div
386 className={cn(
387 "relative w-(--sidebar-width) bg-transparent",
388 "[[data-panel-animations=true]_&]:transition-[width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
389 "group-data-[collapsible=offcanvas]:w-0",
390 "group-data-[side=right]:rotate-180",
391 variant === "floating" || variant === "inset"
392 ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
393 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
394 )}
395 data-slot="sidebar-gap"
396 />
397 <div
398 className={cn(
399 "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) md:flex",
400 "[[data-panel-animations=true]_&]:transition-[left,right,width] [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
401 side === "left"
402 ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
403 : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
404 variant === "floating" || variant === "inset"
405 ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
406 : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
407 className,
408 )}
409 data-slot="sidebar-container"
410 {...props}
411 >
412 <div
413 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"
414 data-sidebar="sidebar"
415 data-slot="sidebar-inner"
416 >
417 {children}
418 </div>
419 </div>
420 </div>
421 </SidebarInstanceContext>
422 );
423}
424
425function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
426 const { toggleSidebar } = useSidebar();
427 const isOpen = useSidebarVisibility();
428
429 return (
430 <Button
431 className={cn(
432 "size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]",
433 className,
434 )}
435 data-sidebar="trigger"
436 data-slot="sidebar-trigger"
437 aria-pressed={isOpen}
438 onClick={(event) => {
439 onClick?.(event);
440 toggleSidebar();
441 }}
442 size="icon"
443 variant="ghost"
444 {...props}
445 >
446 {isOpen ? <PanelLeftCloseIcon className="size-4" /> : <PanelLeftIcon className="size-4" />}
447 <span className="sr-only">Toggle Sidebar</span>
448 </Button>
449 );
450}
451
452function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
453 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
454}
455
456function SidebarRail({
457 className,
458 onClick,
459 onPointerCancel,
460 onLostPointerCapture,
461 onPointerDown,
462 onPointerMove,
463 onPointerUp,
464 ...props
465}: React.ComponentProps<"button">) {
466 const { open, toggleSidebar, onCollapse } = useSidebar();
467 const sidebarInstance = React.use(SidebarInstanceContext);
468 const suppressClickRef = React.useRef(false);
469 const resolvedResizable = sidebarInstance?.resizable ?? null;
470 const canResize = resolvedResizable !== null && open;
471 const railLabel = canResize ? "Resize Sidebar" : "Toggle Sidebar";
472 const railTitle = canResize ? "Drag to resize sidebar" : "Toggle Sidebar";
473 const resize = useResizeDrag<HTMLButtonElement>((event) => {
474 const options = resolvedResizable;
475 if (!options || !open) return null;
476 const rail = event.currentTarget;
477 const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
478 const sidebarRoot = rail.closest<HTMLElement>("[data-slot='sidebar']");
479 const sidebarContainer = sidebarRoot?.querySelector<HTMLElement>(
480 "[data-slot='sidebar-container']",
481 );
482 if (!wrapper || !sidebarRoot || !sidebarContainer) return null;
483
484 const side = sidebarInstance?.side ?? "left";
485 let width = clampSidebarWidth(sidebarContainer.getBoundingClientRect().width, options);
486 // Write width only to gap/container during drag; inherited --sidebar-width restyles the whole app, so
487 // update it at commit.
488 const widthTargets = [
489 sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-gap']"),
490 sidebarContainer,
491 ].filter((element): element is HTMLElement => element !== null);
492 const setTargetWidth = (value: number) => {
493 widthTargets.forEach((element) => {
494 element.style.setProperty("width", `${value}px`);
495 });
496 };
497 widthTargets.forEach((element) => {
498 element.style.setProperty("transition-duration", "0ms");
499 });
500 setTargetWidth(width);
501
502 return {
503 width,
504 edge: side === "left" ? "right" : "left",
505 bounds: { min: options.minWidth, max: options.maxWidth },
506 resize(nextWidth) {
507 const accepted =
508 options.shouldAcceptWidth?.({
509 currentWidth: width,
510 nextWidth,
511 rail,
512 side,
513 sidebarRoot,
514 wrapper,
515 }) ?? true;
516 if (accepted) {
517 setTargetWidth(nextWidth);
518 width = nextWidth;
519 }
520 return width;
521 },
522 finish(finalWidth, moved) {
523 wrapper.style.setProperty("--sidebar-width", `${finalWidth}px`);
524 suppressClickRef.current = moved;
525 if (options.storageKey) {
526 try {
527 setLocalStorageItem(options.storageKey, finalWidth, Schema.Finite);
528 } catch (error) {
529 console.error("Could not persist sidebar width.", error);
530 }
531 }
532 options.onResize?.(finalWidth);
533 },
534 cleanup() {
535 widthTargets.forEach((element) => {
536 element.style.removeProperty("width");
537 element.style.removeProperty("transition-duration");
538 });
539 },
540 };
541 });
542 // Collapsing mid-drag abandons the drag instead of committing a width to a hidden sidebar.
543 // Created once: a new ref callback would run the old one's cleanup, which ends a live drag.
544 const [railRef] = React.useState(() => {
545 const { ref: dragRef, cancel } = resize;
546 return (node: HTMLButtonElement | null) => {
547 const releaseDrag = dragRef(node);
548 if (!releaseDrag) return undefined;
549 const stopCancelOnCollapse = onCollapse(cancel);
550 return () => {
551 stopCancelOnCollapse();
552 releaseDrag();
553 };
554 };
555 });
556
557 const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
558 onClick?.(event);
559 if (event.defaultPrevented) return;
560 if (suppressClickRef.current) {
561 suppressClickRef.current = false;
562 event.preventDefault();
563 return;
564 }
565 if (resolvedResizable && open) {
566 event.preventDefault();
567 return;
568 }
569 toggleSidebar();
570 };
571
572 return (
573 <Tooltip>
574 <TooltipTrigger
575 render={
576 <button
577 aria-label={railLabel}
578 className={cn(
579 /* A collapsed offcanvas rail overlaps the native scrollbar on Windows and Linux. */
580 "-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",
581 "[[data-panel-animations=true]_&]:transition-all [[data-panel-animations=true]_&]:[transition-duration:var(--panel-animation-duration)] [[data-panel-animations=true]_&]:ease-out",
582 "touch-none",
583 canResize
584 ? "cursor-col-resize"
585 : "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize [[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
586 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
587 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
588 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
589 className,
590 )}
591 data-sidebar="rail"
592 data-slot="sidebar-rail"
593 onClick={handleClick}
594 onLostPointerCapture={(event) => {
595 onLostPointerCapture?.(event);
596 if (!event.defaultPrevented) resize.onLostPointerCapture(event);
597 }}
598 onPointerCancel={(event) => {
599 onPointerCancel?.(event);
600 if (!event.defaultPrevented) resize.onPointerCancel(event);
601 }}
602 onPointerDown={(event) => {
603 onPointerDown?.(event);
604 if (!event.defaultPrevented) resize.onPointerDown(event);
605 }}
606 onPointerMove={(event) => {
607 onPointerMove?.(event);
608 if (!event.defaultPrevented) resize.onPointerMove(event);
609 }}
610 onPointerUp={(event) => {
611 onPointerUp?.(event);
612 if (!event.defaultPrevented) resize.onPointerUp(event);
613 }}
614 ref={railRef}
615 tabIndex={-1}
616 type="button"
617 {...props}
618 />
619 }
620 />
621 <TooltipPopup side="right">{railTitle}</TooltipPopup>
622 </Tooltip>
623 );
624}
625
626function SidebarInput({ className, ...props }: Omit<InputProps, "unstyled" | "variant">) {
627 return (
628 <Input
629 className={cn(
630 "[&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground",
631 className,
632 )}
633 unstyled
634 {...props}
635 />
636 );
637}
638
639function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
640 return (
641 <main
642 className={cn(
643 "relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
644 "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",
645 className,
646 )}
647 data-slot="sidebar-inset"
648 {...props}
649 />
650 );
651}
652
653function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
654 return (
655 <div
656 className={cn("flex flex-col gap-2 p-2", className)}
657 data-sidebar="header"
658 data-slot="sidebar-header"
659 {...props}
660 />
661 );
662}
663
664function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
665 return (
666 <div
667 className={cn(
668 "flex flex-col gap-2 px-[var(--sidebar-content-inset)] pt-1 pb-[var(--sidebar-content-inset)]",
669 className,
670 )}
671 data-sidebar="footer"
672 data-slot="sidebar-footer"
673 {...props}
674 />
675 );
676}
677
678function SidebarContent({
679 className,
680 fixedHeader,
681 ...props
682}: React.ComponentProps<"div"> & {
683 fixedHeader?: React.ReactNode;
684}) {
685 return (
686 <>
687 {fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
688 <ScrollArea
689 hideScrollbars
690 scrollFade
691 scrollFadePadding={false}
692 // Rows provide keyboard access; exclude the viewport from tab order to flatten VoiceOver's WebKit
693 // interaction boundary.
694 viewportTabIndex={-1}
695 className="h-auto min-h-0 flex-1 [&>[data-slot=scroll-area-viewport]]:[--fade-size:0.75rem]"
696 >
697 <div
698 className={cn(
699 "flex w-full min-w-0 flex-col [overflow-anchor:none] group-data-[collapsible=icon]:overflow-hidden [&>[data-sidebar=group]+[data-sidebar=group]]:pt-0",
700 fixedHeader && "[&>[data-sidebar=group]:first-child]:pt-0",
701 className,
702 )}
703 data-sidebar="content"
704 data-slot="sidebar-content"
705 {...props}
706 />
707 </ScrollArea>
708 </>
709 );
710}
711
712function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
713 return (
714 <div
715 className={cn(
716 "relative flex w-full min-w-0 flex-col p-[var(--sidebar-content-inset)]",
717 className,
718 )}
719 data-sidebar="group"
720 data-slot="sidebar-group"
721 {...props}
722 />
723 );
724}
725
726function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
727 return (
728 <ul
729 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
730 data-sidebar="menu"
731 data-slot="sidebar-menu"
732 {...props}
733 />
734 );
735}
736
737function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
738 return (
739 <li
740 className={cn("group/menu-item relative", className)}
741 data-sidebar="menu-item"
742 data-slot="sidebar-menu-item"
743 {...props}
744 />
745 );
746}
747
748const sidebarMenuButtonVariants = cva(
749 "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 focus-visible:ring-inset active:bg-sidebar-row-active active:text-sidebar-foreground disabled:pointer-events-none disabled:opacity-64 aria-disabled:pointer-events-none aria-disabled:opacity-64 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",
750 {
751 defaultVariants: {
752 size: "default",
753 variant: "default",
754 },
755 variants: {
756 size: {
757 default:
758 "h-8 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-1.5 text-sm",
759 icon: "size-8 justify-center rounded-[var(--control-radius)] p-0",
760 lg: "h-12 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-sm group-data-[collapsible=icon]:p-0!",
761 sm: "h-7 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-xs",
762 },
763 variant: {
764 default: "font-medium text-sidebar-muted-foreground/80",
765 outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
766 },
767 },
768 },
769);
770
771function SidebarMenuButton({
772 isActive = false,
773 variant = "default",
774 size = "default",
775 tooltip,
776 className,
777 render,
778 ...props
779}: useRender.ComponentProps<"button"> & {
780 isActive?: boolean;
781 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
782} & VariantProps<typeof sidebarMenuButtonVariants>) {
783 const { isMobile, state } = useSidebar();
784
785 const defaultProps = {
786 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
787 "data-active": isActive,
788 "data-sidebar": "menu-button",
789 "data-size": size,
790 "data-slot": "sidebar-menu-button",
791 };
792
793 const buttonProps = mergeProps<"button">(defaultProps, props);
794
795 const buttonElement = useRender({
796 defaultTagName: "button",
797 props: buttonProps,
798 render,
799 });
800
801 if (!tooltip) {
802 return buttonElement;
803 }
804
805 if (typeof tooltip === "string") {
806 tooltip = {
807 children: tooltip,
808 };
809 }
810
811 return (
812 <Tooltip>
813 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
814 <TooltipPopup
815 align="center"
816 hidden={state !== "collapsed" || isMobile}
817 side="right"
818 {...tooltip}
819 />
820 </Tooltip>
821 );
822}
823
824function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
825 return (
826 <ul
827 className={cn(
828 "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",
829 "group-data-[collapsible=icon]:hidden",
830 className,
831 )}
832 data-sidebar="menu-sub"
833 data-slot="sidebar-menu-sub"
834 {...props}
835 />
836 );
837}
838
839function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
840 return (
841 <li
842 className={cn("group/menu-sub-item relative", className)}
843 data-sidebar="menu-sub-item"
844 data-slot="sidebar-menu-sub-item"
845 {...props}
846 />
847 );
848}
849
850function SidebarMenuSubButton({
851 size = "md",
852 isActive = false,
853 className,
854 render,
855 ...props
856}: useRender.ComponentProps<"a"> & {
857 size?: "sm" | "md";
858 isActive?: boolean;
859}) {
860 const defaultProps = {
861 className: cn(
862 "-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 focus-visible:ring-inset active:bg-sidebar-row-active active:text-sidebar-foreground disabled:pointer-events-none disabled:opacity-64 aria-disabled:pointer-events-none aria-disabled:opacity-64 [&>span:last-child]:truncate [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-muted-foreground",
863 "data-[active=true]:bg-sidebar-row-selected data-[active=true]:text-sidebar-foreground",
864 size === "sm" && "text-xs",
865 size === "md" && "text-sm",
866 "group-data-[collapsible=icon]:hidden",
867 className,
868 ),
869 "data-active": isActive,
870 "data-sidebar": "menu-sub-button",
871 "data-size": size,
872 "data-slot": "sidebar-menu-sub-button",
873 };
874
875 return useRender({
876 defaultTagName: "a",
877 props: mergeProps<"a">(defaultProps, props),
878 render,
879 });
880}
881
882export {
883 SidebarInput,
884 Sidebar,
885 SidebarContent,
886 SidebarFooter,
887 SidebarGroup,
888 SidebarHeader,
889 SidebarInset,
890 SidebarMenu,
891 SidebarMenuButton,
892 SidebarMenuItem,
893 SidebarMenuSub,
894 SidebarMenuSubButton,
895 SidebarMenuSubItem,
896 SidebarProvider,
897 SidebarRail,
898 SidebarTrigger,
899 useMobileSidebarSheetMounted,
900 useSidebar,
901 useSidebarVisibility,
902};