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