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

sidebar.tsx

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