import { mergeProps } from "@base-ui/react/merge-props"; import { useRender } from "@base-ui/react/use-render"; import { cva, type VariantProps } from "class-variance-authority"; import { T, useGT } from "gt-react"; import { PanelLeftCloseIcon, PanelLeftIcon } from "lucide-react"; import * as React from "react"; import { cn } from "~/lib/utils"; import { Button } from "~/components/ui/button"; import { Input, type InputProps } from "~/components/ui/input"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Sheet, SheetDescription, SheetHeader, SheetPopup, SheetTitle, } from "~/components/ui/sheet"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { SharedTooltipTrigger } from "~/components/ui/shared-tooltip"; import { useResizeDrag } from "~/hooks/useResizeDrag"; import { useMediaQuery } from "~/hooks/useMediaQuery"; import { useClientSettings } from "~/hooks/useSettings"; import { getLocalStorageItem, setLocalStorageItem, writeLocalStorageValue, } from "~/hooks/useLocalStorage"; import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState"; import * as Schema from "effect/Schema"; import { announceSidebarVisibility } from "~/lib/accessibilityAnnouncements"; const SIDEBAR_WIDTH = "16rem"; const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing) * 3)"; const SIDEBAR_WIDTH_ICON = "3rem"; const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16; const SIDEBAR_COLLAPSE_DRAG_RATIO = 0.75; const SIDEBAR_TITLEBAR_CONTROL_SIZE = "max-sm:[--workspace-titlebar-control-size:--spacing(8)]"; type SidebarContextProps = { state: ResponsiveSidebarState; open: boolean; setOpen: (open: boolean) => void; openMobile: boolean; mobileSheetMounted: boolean; setMobileSheetMounted: (mounted: boolean) => void; setOpenMobile: (open: boolean) => void; isMobile: boolean; toggleSidebar: () => void; /** Runs before the desktop sidebar collapses. */ onCollapse: (listener: () => void) => () => void; }; type SidebarResizableOptions = { collapseOnResize?: boolean; maxWidth?: number; minWidth?: number; onResize?: (width: number) => void; shouldAcceptWidth?: (context: { currentWidth: number; nextWidth: number; rail: HTMLButtonElement; side: "left" | "right"; sidebarRoot: HTMLElement; wrapper: HTMLElement; }) => boolean; storageKey?: string; }; type SidebarResolvedResizableOptions = { collapseOnResize: boolean; maxWidth: number; minWidth: number; onResize?: (width: number) => void; shouldAcceptWidth?: (context: { currentWidth: number; nextWidth: number; rail: HTMLButtonElement; side: "left" | "right"; sidebarRoot: HTMLElement; wrapper: HTMLElement; }) => boolean; storageKey: string | null; }; type SidebarInstanceContextProps = { resizable: SidebarResolvedResizableOptions | null; side: "left" | "right"; }; type SidebarMobileContextProps = Pick; const SidebarContext = React.createContext(null); // Unchanged by open and close, so the thread list does not re-render every row on each toggle. const SidebarMobileContext = React.createContext(null); const SidebarInstanceContext = React.createContext(null); function useSidebar() { const context = React.use(SidebarContext); if (!context) { throw new Error("useSidebar must be used within a SidebarProvider."); } return context; } function useSidebarMobile() { const context = React.use(SidebarMobileContext); if (!context) { throw new Error("useSidebarMobile must be used within a SidebarProvider."); } return context; } function useSidebarVisibility() { const { isMobile, open, openMobile } = useSidebar(); return isMobile ? openMobile : open; } /** Whether the mobile sidebar sheet covers the page; false outside a SidebarProvider. */ function useMobileSidebarSheetMounted() { const context = React.use(SidebarContext); return context !== null && context.isMobile && context.mobileSheetMounted; } // The `max-md` breakpoint, also read when a shortcut fires. const SIDEBAR_MOBILE_QUERY = "(max-width: 767px)"; function isMobileViewport(): boolean { return typeof window !== "undefined" && window.matchMedia(SIDEBAR_MOBILE_QUERY).matches; } function readStoredSidebarOpen(storageKey: string | undefined): boolean | null { if (!storageKey) return null; try { return getLocalStorageItem(storageKey, Schema.Boolean); } catch (error) { console.error("Could not restore persisted sidebar state.", error); return null; } } // An offcanvas sidebar turns inert once collapsed, which drops focus to the body. function moveFocusOutOfCollapsingSidebar() { const sidebar = document.activeElement?.closest( '[data-slot="sidebar"][data-collapsible-mode="offcanvas"]', ); const wrapper = sidebar?.closest('[data-slot="sidebar-wrapper"]'); if (!sidebar || !wrapper) return; const trigger = Array.from( wrapper.querySelectorAll('[data-sidebar="trigger"]'), ).find((element) => !sidebar.contains(element)); trigger?.focus({ preventScroll: true }); } interface SidebarOpenState { readonly open: boolean; readonly openMobile: boolean; } /** Per-provider open state, kept outside React so shortcuts can toggle it at event time. */ function createSidebarOpenStore(defaultOpen: boolean, storageKey: string | undefined) { let state: SidebarOpenState = { open: readStoredSidebarOpen(storageKey) ?? defaultOpen, openMobile: false, }; const listeners = new Set<() => void>(); const collapseListeners = new Set<() => void>(); const publish = (next: SidebarOpenState) => { state = next; for (const listener of listeners) listener(); }; const setOpen = (open: boolean) => { if (!open && state.open) { for (const listener of collapseListeners) listener(); moveFocusOutOfCollapsingSidebar(); } if (open !== state.open) { if (!isMobileViewport()) announceSidebarVisibility(open); publish({ ...state, open }); } if (storageKey) writeLocalStorageValue(storageKey, open, defaultOpen, Schema.Boolean); }; const setOpenMobile = (openMobile: boolean) => { if (openMobile !== state.openMobile) publish({ ...state, openMobile }); }; return { subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, getSnapshot: () => state, setOpen, setOpenMobile, toggle: () => (isMobileViewport() ? setOpenMobile(!state.openMobile) : setOpen(!state.open)), onCollapse: (listener: () => void) => { collapseListeners.add(listener); return () => { collapseListeners.delete(listener); }; }, }; } function SidebarProvider({ defaultOpen = true, storageKey, className, style, children, ...props }: React.ComponentProps<"div"> & { defaultOpen?: boolean; storageKey?: string; }) { const isMobile = useMediaQuery(SIDEBAR_MOBILE_QUERY); const [store] = React.useState(() => createSidebarOpenStore(defaultOpen, storageKey)); const { open, openMobile } = React.useSyncExternalStore( store.subscribe, store.getSnapshot, store.getSnapshot, ); const [mobileSheetMounted, setMobileSheetMounted] = React.useState(false); if (openMobile && !mobileSheetMounted) { setMobileSheetMounted(true); } // Widening mid-close unmounts the sheet before its close completes. if (!isMobile && !openMobile && mobileSheetMounted) { setMobileSheetMounted(false); } const state = resolveSidebarState({ isMobile, open, openMobile }); const contextValue: SidebarContextProps = { isMobile, open, openMobile, mobileSheetMounted, setMobileSheetMounted, setOpen: store.setOpen, setOpenMobile: store.setOpenMobile, state, toggleSidebar: store.toggle, onCollapse: store.onCollapse, }; const mobileContextValue = { isMobile, setOpenMobile: store.setOpenMobile }; return (
{children}
); } function resolveSidebarResizable({ collapsible, isMobile, resizable, }: { collapsible: "offcanvas" | "icon" | "none"; isMobile: boolean; resizable: boolean | SidebarResizableOptions; }): SidebarResolvedResizableOptions | null { if (isMobile || collapsible === "none" || !resizable) { return null; } const options = typeof resizable === "boolean" ? {} : resizable; return { collapseOnResize: options.collapseOnResize ?? false, maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY, minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH, storageKey: options.storageKey ?? null, ...(options.onResize ? { onResize: options.onResize } : {}), ...(options.shouldAcceptWidth ? { shouldAcceptWidth: options.shouldAcceptWidth } : {}), }; } function Sidebar({ side = "left", variant = "sidebar", collapsible = "offcanvas", resizable = false, className, children, ...props }: React.ComponentProps<"div"> & { side?: "left" | "right"; variant?: "sidebar" | "floating" | "inset"; collapsible?: "offcanvas" | "icon" | "none"; resizable?: boolean | SidebarResizableOptions; }) { const { isMobile, state, openMobile, setOpenMobile, setMobileSheetMounted } = useSidebar(); const gt = useGT(); // Not usePanelAnimationSettings: its navigation suppression would snap the sheet shut mid-exit when an item navigates. const panelAnimationDurationMs = useClientSettings( (settings) => settings.panelAnimationDurationMs, ); const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)"); const panelAnimationsActive = panelAnimationDurationMs > 0 && !prefersReducedMotion; const offcanvasCollapsed = !isMobile && collapsible === "offcanvas" && state === "collapsed"; const resolvedResizable = resolveSidebarResizable({ collapsible, isMobile, resizable }); const instanceContextValue: SidebarInstanceContextProps = { side, resizable: resolvedResizable }; if (collapsible === "none") { return (
{children}
); } if (isMobile) { return ( { if (!open) setMobileSheetMounted(false); }} open={openMobile} > {/* Children stay mounted while closed so their window shortcuts, like thread jumps, keep working. */} {props["aria-label"] ?? gt("Sidebar")} Displays the mobile sidebar.
{children}
); } return (
{offcanvasCollapsed && side === "left" && resolvedResizable?.collapseOnResize && ( )} ); } function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps) { const { toggleSidebar } = useSidebar(); const isOpen = useSidebarVisibility(); return ( ); } function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number { return Math.max(options.minWidth, Math.min(width, options.maxWidth)); } function commitSidebarWidth( wrapper: HTMLElement, options: SidebarResolvedResizableOptions, width: number, ) { wrapper.style.setProperty("--sidebar-width", `${width}px`); if (options.storageKey) { try { setLocalStorageItem(options.storageKey, width, Schema.Finite); } catch (error) { console.error("Could not persist sidebar width.", error); } } options.onResize?.(width); } function SidebarRestoreHandle({ options }: { options: SidebarResolvedResizableOptions }) { const { setOpen } = useSidebar(); const gt = useGT(); const [near, setNear] = React.useState(false); const suppressClick = React.useRef(false); const resize = useResizeDrag((event) => { if (event.pointerType !== "mouse") return null; const wrapper = event.currentTarget.closest('[data-slot="sidebar-wrapper"]'); const sidebar = wrapper?.querySelector('[data-slot="sidebar"][data-side="left"]'); const container = sidebar?.querySelector('[data-slot="sidebar-container"]'); const gap = sidebar?.querySelector('[data-slot="sidebar-gap"]'); if (!wrapper || !container || !gap) return null; let restorePending = false; wrapper.dataset.sidebarDragState = "collapsed"; return { width: 0, edge: "right", bounds: { min: 0, max: options.maxWidth }, cancelOnInterrupt: true, resize(nextWidth) { const shouldRestore = nextWidth >= 48; if (shouldRestore !== restorePending) { restorePending = shouldRestore; wrapper.dataset.sidebarDragState = restorePending ? "expanded" : "collapsed"; } const width = clampSidebarWidth(nextWidth, options); container.style.left = restorePending ? "0px" : `${-width}px`; for (const element of [container, gap]) { element.style.width = `${restorePending || element === container ? width : 0}px`; element.style.transitionDuration = "0ms"; } return width; }, finish(width, moved) { suppressClick.current = moved; if (moved && restorePending) { commitSidebarWidth(wrapper, options, width); setOpen(true); } }, cleanup() { delete wrapper.dataset.sidebarDragState; container.style.removeProperty("left"); for (const element of [container, gap]) { element.style.removeProperty("width"); element.style.removeProperty("transition-duration"); } }, }; }); const { ref: handleRef, ...drag } = resize; return (
{ if (event.pointerType === "mouse") setNear(true); }} onPointerLeave={() => setNear(false)} >
); } function SidebarRail({ className, onClick, onPointerCancel, onLostPointerCapture, onPointerDown, onPointerMove, onPointerUp, ...props }: React.ComponentProps<"button">) { const { open, setOpen, toggleSidebar, onCollapse } = useSidebar(); const gt = useGT(); const sidebarInstance = React.use(SidebarInstanceContext); const suppressClickRef = React.useRef(false); const resolvedResizable = sidebarInstance?.resizable ?? null; const canResize = resolvedResizable !== null && open; const railLabel = canResize ? gt("Resize Sidebar") : gt("Toggle Sidebar"); const railTitle = canResize ? gt("Drag to resize sidebar") : gt("Toggle Sidebar"); const resize = useResizeDrag((event) => { const options = resolvedResizable; if (!options || !open) return null; const rail = event.currentTarget; const wrapper = rail.closest("[data-slot='sidebar-wrapper']"); const sidebarRoot = rail.closest("[data-slot='sidebar']"); const sidebarContainer = sidebarRoot?.querySelector( "[data-slot='sidebar-container']", ); if (!wrapper || !sidebarRoot || !sidebarContainer) return null; const side = sidebarInstance?.side ?? "left"; const canCollapse = open && side === "left" && options.collapseOnResize; let collapsePending = false; if (canCollapse) wrapper.dataset.sidebarDragState = "expanded"; let width = clampSidebarWidth(sidebarContainer.getBoundingClientRect().width, options); // Write width only to gap/container during drag; inherited --sidebar-width restyles the whole app, so // update it at commit. const widthTargets = [ sidebarRoot.querySelector("[data-slot='sidebar-gap']"), sidebarContainer, ].filter((element): element is HTMLElement => element !== null); const setTargetWidth = (value: number) => { widthTargets.forEach((element) => { element.style.setProperty( "width", `${collapsePending && element !== sidebarContainer ? 0 : value}px`, ); }); // Match the offcanvas left offset so releasing a drag cannot restart the slide. if (canCollapse) sidebarContainer.style.left = collapsePending ? `${-value}px` : "0px"; }; widthTargets.forEach((element) => { element.style.setProperty("transition-duration", "0ms"); }); setTargetWidth(width); return { width, edge: side === "left" ? "right" : "left", bounds: { min: options.minWidth, max: options.maxWidth }, cancelOnInterrupt: canCollapse, resize(nextWidth, rawWidth) { const shouldCollapse = canCollapse && rawWidth < options.minWidth * (1 - SIDEBAR_COLLAPSE_DRAG_RATIO); if (shouldCollapse !== collapsePending) { collapsePending = shouldCollapse; wrapper.dataset.sidebarDragState = collapsePending ? "collapsed" : "expanded"; } const accepted = options.shouldAcceptWidth?.({ currentWidth: width, nextWidth, rail, side, sidebarRoot, wrapper, }) ?? true; if (accepted) { width = nextWidth; } setTargetWidth(width); return width; }, finish(finalWidth, moved) { suppressClickRef.current = moved; commitSidebarWidth(wrapper, options, finalWidth); if (moved && collapsePending) setOpen(false); }, cleanup() { if (canCollapse) { delete wrapper.dataset.sidebarDragState; sidebarContainer.style.removeProperty("left"); } widthTargets.forEach((element) => { element.style.removeProperty("width"); element.style.removeProperty("transition-duration"); }); }, }; }); // Collapsing mid-drag abandons the drag instead of committing a width to a hidden sidebar. // Created once: a new ref callback would run the old one's cleanup, which ends a live drag. const [railRef] = React.useState(() => { const { ref: dragRef, cancel } = resize; return (node: HTMLButtonElement | null) => { const releaseDrag = dragRef(node); if (!releaseDrag) return undefined; const stopCancelOnCollapse = onCollapse(cancel); return () => { stopCancelOnCollapse(); releaseDrag(); }; }; }); const handleClick = (event: React.MouseEvent) => { onClick?.(event); if (event.defaultPrevented) return; if (suppressClickRef.current) { suppressClickRef.current = false; event.preventDefault(); return; } if (resolvedResizable && open) { event.preventDefault(); return; } toggleSidebar(); }; const rail = (