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