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