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

sidebar.tsx

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