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

sidebar.tsx

900 lines30.1 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 { 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;
96​
97function useSidebarVisibility() {
98 const { isMobile, open, openMobile } = useSidebar();
99 return isMobile ? openMobile : open;
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;
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;
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 }
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 });
137​
138interface SidebarOpenState {
139 readonly open: boolean;
140 readonly openMobile: boolean;
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 };
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 );
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 };
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 );
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 );
451​
452function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
453 return Math.max(options.minWidth, Math.min(width, options.maxWidth));
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 in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
583 "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
584 "group-data-[collapsible=offcanvas]:translate-x-0 hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:after:left-full",
585 "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
586 "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
587 className,
588 )}
589 data-sidebar="rail"
590 data-slot="sidebar-rail"
591 onClick={handleClick}
592 onLostPointerCapture={(event) => {
593 onLostPointerCapture?.(event);
594 if (!event.defaultPrevented) resize.onLostPointerCapture(event);
595 }}
596 onPointerCancel={(event) => {
597 onPointerCancel?.(event);
598 if (!event.defaultPrevented) resize.onPointerCancel(event);
599 }}
600 onPointerDown={(event) => {
601 onPointerDown?.(event);
602 if (!event.defaultPrevented) resize.onPointerDown(event);
603 }}
604 onPointerMove={(event) => {
605 onPointerMove?.(event);
606 if (!event.defaultPrevented) resize.onPointerMove(event);
607 }}
608 onPointerUp={(event) => {
609 onPointerUp?.(event);
610 if (!event.defaultPrevented) resize.onPointerUp(event);
611 }}
612 ref={railRef}
613 tabIndex={-1}
614 type="button"
615 {...props}
616 />
617 }
618 />
619 <TooltipPopup side="right">{railTitle}</TooltipPopup>
620 </Tooltip>
621 );
623​
624function SidebarInput({ className, ...props }: Omit<InputProps, "unstyled" | "variant">) {
625 return (
626 <Input
627 className={cn(
628 "[&_[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",
629 className,
630 )}
631 unstyled
632 {...props}
633 />
634 );
636​
637function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
638 return (
639 <main
640 className={cn(
641 "relative flex min-w-0 w-full flex-1 flex-col bg-background surface-grain",
642 "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",
643 className,
644 )}
645 data-slot="sidebar-inset"
646 {...props}
647 />
648 );
650​
651function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
652 return (
653 <div
654 className={cn("flex flex-col gap-2 p-2", className)}
655 data-sidebar="header"
656 data-slot="sidebar-header"
657 {...props}
658 />
659 );
661​
662function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
663 return (
664 <div
665 className={cn(
666 "flex flex-col gap-2 px-[var(--sidebar-content-inset)] pt-1 pb-[var(--sidebar-content-inset)]",
667 className,
668 )}
669 data-sidebar="footer"
670 data-slot="sidebar-footer"
671 {...props}
672 />
673 );
675​
676function SidebarContent({
677 className,
678 fixedHeader,
679 ...props
680}: React.ComponentProps<"div"> & {
681 fixedHeader?: React.ReactNode;
682}) {
683 return (
684 <>
685 {fixedHeader ? <div className="w-full shrink-0">{fixedHeader}</div> : null}
686 <ScrollArea
687 hideScrollbars
688 scrollFade
689 scrollFadePadding={false}
690 // Rows provide keyboard access; exclude the viewport from tab order to flatten VoiceOver's WebKit
691 // interaction boundary.
692 viewportTabIndex={-1}
693 className="h-auto min-h-0 flex-1 [&>[data-slot=scroll-area-viewport]]:[--fade-size:0.75rem]"
694 >
695 <div
696 className={cn(
697 "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",
698 fixedHeader && "[&>[data-sidebar=group]:first-child]:pt-0",
699 className,
700 )}
701 data-sidebar="content"
702 data-slot="sidebar-content"
703 {...props}
704 />
705 </ScrollArea>
706 </>
707 );
709​
710function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
711 return (
712 <div
713 className={cn(
714 "relative flex w-full min-w-0 flex-col p-[var(--sidebar-content-inset)]",
715 className,
716 )}
717 data-sidebar="group"
718 data-slot="sidebar-group"
719 {...props}
720 />
721 );
723​
724function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
725 return (
726 <ul
727 className={cn("flex w-full min-w-0 flex-col gap-1", className)}
728 data-sidebar="menu"
729 data-slot="sidebar-menu"
730 {...props}
731 />
732 );
734​
735function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
736 return (
737 <li
738 className={cn("group/menu-item relative", className)}
739 data-sidebar="menu-item"
740 data-slot="sidebar-menu-item"
741 {...props}
742 />
743 );
745​
746const sidebarMenuButtonVariants = cva(
747 "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",
748 {
749 defaultVariants: {
750 size: "default",
751 variant: "default",
752 },
753 variants: {
754 size: {
755 default:
756 "h-8 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-1.5 text-sm",
757 icon: "size-8 justify-center rounded-[var(--control-radius)] p-0",
758 lg: "h-12 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-sm group-data-[collapsible=icon]:p-0!",
759 sm: "h-7 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-xs",
760 },
761 variant: {
762 default: "font-medium text-sidebar-muted-foreground/80",
763 outline: "bg-sidebar-control-surface ring-1 ring-sidebar-border",
764 },
765 },
766 },
767);
768​
769function SidebarMenuButton({
770 isActive = false,
771 variant = "default",
772 size = "default",
773 tooltip,
774 className,
775 render,
776 ...props
777}: useRender.ComponentProps<"button"> & {
778 isActive?: boolean;
779 tooltip?: string | React.ComponentProps<typeof TooltipPopup>;
780} & VariantProps<typeof sidebarMenuButtonVariants>) {
781 const { isMobile, state } = useSidebar();
782​
783 const defaultProps = {
784 className: cn(sidebarMenuButtonVariants({ size, variant }), className),
785 "data-active": isActive,
786 "data-sidebar": "menu-button",
787 "data-size": size,
788 "data-slot": "sidebar-menu-button",
789 };
790​
791 const buttonProps = mergeProps<"button">(defaultProps, props);
792​
793 const buttonElement = useRender({
794 defaultTagName: "button",
795 props: buttonProps,
796 render,
797 });
798​
799 if (!tooltip) {
800 return buttonElement;
801 }
802​
803 if (typeof tooltip === "string") {
804 tooltip = {
805 children: tooltip,
806 };
807 }
808​
809 return (
810 <Tooltip>
811 <TooltipTrigger render={buttonElement as React.ReactElement<Record<string, unknown>>} />
812 <TooltipPopup
813 align="center"
814 hidden={state !== "collapsed" || isMobile}
815 side="right"
816 {...tooltip}
817 />
818 </Tooltip>
819 );
821​
822function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
823 return (
824 <ul
825 className={cn(
826 "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",
827 "group-data-[collapsible=icon]:hidden",
828 className,
829 )}
830 data-sidebar="menu-sub"
831 data-slot="sidebar-menu-sub"
832 {...props}
833 />
834 );
836​
837function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<"li">) {
838 return (
839 <li
840 className={cn("group/menu-sub-item relative", className)}
841 data-sidebar="menu-sub-item"
842 data-slot="sidebar-menu-sub-item"
843 {...props}
844 />
845 );
847​
848function SidebarMenuSubButton({
849 size = "md",
850 isActive = false,
851 className,
852 render,
853 ...props
854}: useRender.ComponentProps<"a"> & {
855 size?: "sm" | "md";
856 isActive?: boolean;
857}) {
858 const defaultProps = {
859 className: cn(
860 "-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",
861 "data-[active=true]:bg-sidebar-row-selected data-[active=true]:text-sidebar-foreground",
862 size === "sm" && "text-xs",
863 size === "md" && "text-sm",
864 "group-data-[collapsible=icon]:hidden",
865 className,
866 ),
867 "data-active": isActive,
868 "data-sidebar": "menu-sub-button",
869 "data-size": size,
870 "data-slot": "sidebar-menu-sub-button",
871 };
872​
873 return useRender({
874 defaultTagName: "a",
875 props: mergeProps<"a">(defaultProps, props),
876 render,
877 });
879​
880export {
881 SidebarInput,
882 Sidebar,
883 SidebarContent,
884 SidebarFooter,
885 SidebarGroup,
886 SidebarHeader,
887 SidebarInset,
888 SidebarMenu,
889 SidebarMenuButton,
890 SidebarMenuItem,
891 SidebarMenuSub,
892 SidebarMenuSubButton,
893 SidebarMenuSubItem,
894 SidebarProvider,
895 SidebarRail,
896 SidebarTrigger,
897 useMobileSidebarSheetMounted,
898 useSidebar,
899 useSidebarVisibility,
900};