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

sidebar.tsx

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