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

sidebar.tsx

867 lines28.7 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 { 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;
94​
95function useSidebarVisibility() {
96 const { isMobile, open, openMobile } = useSidebar();
97 return isMobile ? openMobile : open;
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;
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 });
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 });
128​
129interface SidebarOpenState {
130 readonly open: boolean;
131 readonly openMobile: boolean;
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 };
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 );
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 };
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 );
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 );
419​
420function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
421 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
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 );
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 );
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 );
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 );
629​
630function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
631 return (
632 <div
633 className={cn(
634 "flex flex-col gap-2 px-[var(--sidebar-content-inset)] pt-1 pb-[var(--sidebar-content-inset)]",
635 className,
636 )}
637 data-sidebar="footer"
638 data-slot="sidebar-footer"
639 {...props}
640 />
641 );
643​
644function SidebarContent({
645 className,
646 fixedHeader,
647 ...props
648}: React.ComponentProps<"div"> & {
649 fixedHeader?: React.ReactNode;
650}) {
651 return (
652 <>
653 {fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
654 <ScrollArea
655 hideScrollbars
656 scrollFade
657 scrollFadePadding={false}
658 // Rows provide keyboard access; exclude the viewport from tab order to flatten VoiceOver's WebKit
659 // interaction boundary.
660 viewportTabIndex={-1}
661 className="h-auto min-h-0 flex-1 [&>[data-slot=scroll-area-viewport]]:[--fade-size:0.75rem]"
662 >
663 <div
664 className={cn(
665 "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",
666 fixedHeader && "[&>[data-sidebar=group]:first-child]:pt-0",
667 className,
668 )}
669 data-sidebar="content"
670 data-slot="sidebar-content"
671 {...props}
672 />
673 </ScrollArea>
674 </>
675 );
677​
678function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
679 return (
680 <div
681 className={cn(
682 "relative flex w-full min-w-0 flex-col p-[var(--sidebar-content-inset)]",
683 className,
684 )}
685 data-sidebar="group"
686 data-slot="sidebar-group"
687 {...props}
688 />
689 );
691​
692function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
693 return (
694 <ul
695 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
696 data-sidebar="menu"
697 data-slot="sidebar-menu"
698 {...props}
699 />
700 );
702​
703function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
704 return (
705 <li
706 className={cn("group/menu-item relative", className)}
707 data-sidebar="menu-item"
708 data-slot="sidebar-menu-item"
709 {...props}
710 />
711 );
713​
714const sidebarMenuButtonVariants = cva(
715 "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",
716 {
717 defaultVariants: {
718 size: "default",
719 variant: "default",
720 },
721 variants: {
722 size: {
723 default:
724 "h-8 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-1.5 text-sm",
725 icon: "size-8 justify-center rounded-[var(--control-radius)] p-0",
726 lg: "h-12 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-sm group-data-[collapsible=icon]:p-0!",
727 sm: "h-7 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-xs",
728 },
729 variant: {
730 default: "font-medium text-sidebar-muted-foreground/80",
731 outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
732 },
733 },
734 },
735);
736​
737function SidebarMenuButton({
738 isActive = false,
739 variant = "default",
740 size = "default",
741 tooltip,
742 className,
743 render,
744 ...props
745}: useRender.ComponentProps<"button"> & {
746 isActive?: boolean;
747 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
748} & VariantProps<typeof sidebarMenuButtonVariants>) {
749 const { isMobile, state } = useSidebar();
750​
751 const defaultProps = {
752 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
753 "data-active": isActive,
754 "data-sidebar": "menu-button",
755 "data-size": size,
756 "data-slot": "sidebar-menu-button",
757 };
758​
759 const buttonProps = mergeProps<"button">(defaultProps, props);
760​
761 const buttonElement = useRender({
762 defaultTagName: "button",
763 props: buttonProps,
764 render,
765 });
766​
767 if (!tooltip) {
768 return buttonElement;
769 }
770​
771 if (typeof tooltip === "string") {
772 tooltip = {
773 children: tooltip,
774 };
775 }
776​
777 return (
778 <Tooltip>
779 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
780 <TooltipPopup
781 align="center"
782 hidden={state !== "collapsed" || isMobile}
783 side="right"
784 {...tooltip}
785 />
786 </Tooltip>
787 );
789​
790function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
791 return (
792 <ul
793 className={cn(
794 "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",
795 "group-data-[collapsible=icon]:hidden",
796 className,
797 )}
798 data-sidebar="menu-sub"
799 data-slot="sidebar-menu-sub"
800 {...props}
801 />
802 );
804​
805function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
806 return (
807 <li
808 className={cn("group/menu-sub-item relative", className)}
809 data-sidebar="menu-sub-item"
810 data-slot="sidebar-menu-sub-item"
811 {...props}
812 />
813 );
815​
816function SidebarMenuSubButton({
817 size = "md",
818 isActive = false,
819 className,
820 render,
821 ...props
822}: useRender.ComponentProps<"a"> & {
823 size?: "sm" | "md";
824 isActive?: boolean;
825}) {
826 const defaultProps = {
827 className: cn(
828 "-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",
829 "data-[active=true]:bg-sidebar-row-selected data-[active=true]:text-sidebar-foreground",
830 size === "sm" && "text-xs",
831 size === "md" && "text-sm",
832 "group-data-[collapsible=icon]:hidden",
833 className,
834 ),
835 "data-active": isActive,
836 "data-sidebar": "menu-sub-button",
837 "data-size": size,
838 "data-slot": "sidebar-menu-sub-button",
839 };
840​
841 return useRender({
842 defaultTagName: "a",
843 props: mergeProps<"a">(defaultProps, props),
844 render,
845 });
847​
848export {
849 SidebarInput,
850 Sidebar,
851 SidebarContent,
852 SidebarFooter,
853 SidebarGroup,
854 SidebarHeader,
855 SidebarInset,
856 SidebarMenu,
857 SidebarMenuButton,
858 SidebarMenuItem,
859 SidebarMenuSub,
860 SidebarMenuSubButton,
861 SidebarMenuSubItem,
862 SidebarProvider,
863 SidebarRail,
864 SidebarTrigger,
865 useSidebar,
866 useSidebarVisibility,
867};