TypeScript
feat(sidebar): fold the project scope into the search row (#11315)
mariad1d15c67f4a5
diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 33157e7b4b4..f9a62c40a51 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -828,30 +828,26 @@ describe("filterSidebarProjectScopeItems", () => {{ value: "alpha", label: "Alpha workspace" },{ value: "beta", label: "Beta tools" },] as const;- const filter = (activeScopeKey: string | null, query: string) =>+ const filter = (query: string) =>filterSidebarProjectScopeItems({items,- activeScopeKey,query,matches: (item, candidate) =>item.label.toLocaleLowerCase().includes(candidate.toLocaleLowerCase()),});- it("omits the reset row when the sidebar is already unscoped", () => {- expect(filter(null, "")).toEqual(items.slice(1));+ it("shows the default row first while the query is empty", () => {+ expect(filter("")).toEqual(items);+ expect(filter(" ")).toEqual(items);});- it("shows the reset row first while a project scope is active", () => {- expect(filter("alpha", "")).toEqual(items);- });-- it("hides the reset row while filtering an active scope", () => {- expect(filter("alpha", "all")).toEqual([]);+ it("hides the default row while filtering", () => {+ expect(filter("all")).toEqual([]);});it("returns matching projects in source order and supports no-match results", () => {- expect(filter(null, "WORK")).toEqual([items[1]]);- expect(filter(null, "missing")).toEqual([]);+ expect(filter("WORK")).toEqual([items[1]]);+ expect(filter("missing")).toEqual([]);});});diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 0150eb473d5..50650ed389d 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -894,16 +894,12 @@ export function searchSidebarThreads<export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {items: readonly TItem[];- activeScopeKey: string | null;query: string;matches: (item: TItem, query: string) => boolean;}): readonly TItem[] {- const projectItems = input.items.filter((item) => item.value !== "all");const query = input.query.trim();- if (query.length > 0) {- return projectItems.filter((item) => input.matches(item, query));- }- return input.activeScopeKey === null ? projectItems : input.items;+ if (query.length === 0) return input.items;+ return input.items.filter((item) => item.value !== "all" && input.matches(item, query));}export interface SidebarProjectScopeMenuState {diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex c951689230e..445ae533c32 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -46,12 +46,10 @@ import {CircleDashedIcon,ClockIcon,FolderIcon,- FolderPlusIcon,GitBranchIcon,PinIcon,PinOffIcon,PlusIcon,- SearchIcon,SettingsIcon,SquarePenIcon,TerminalIcon,@@ -218,7 +216,6 @@ import {import { useThreadRunningTerminalIds } from "../state/terminalSessions";import { stackedThreadToast, toastManager } from "./ui/toast";import { Button } from "./ui/button";-import { Input } from "./ui/input";import {Combobox,ComboboxEmpty,@@ -229,8 +226,9 @@ import {ComboboxTrigger,useComboboxFilter,} from "./ui/combobox";-import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar";+import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar";import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";+import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader";import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";import {@@ -2370,21 +2368,19 @@ export default function Sidebar() {const projectScopeFilter = useComboboxFilter();// Filtering derives from the same React state that controls the input, so// the visible query and the visible list can never desync — the peer wiring- // in DiffPanel and BranchToolbarBranchSelector. "All projects" is a scope- // reset, not a searchable entry: it only shows while a project scope is- // active (there is something to reset) and the query is empty, so it can't- // outrank a project match under autoHighlight and no-hit queries reach the- // empty state.+ // in DiffPanel and BranchToolbarBranchSelector. "All projects" is the default+ // row, not a searchable entry: it heads the list while the query is empty and+ // drops out while filtering, so it can't outrank a project match under+ // autoHighlight and no-hit queries reach the empty state.const filteredProjectScopeItems = useMemo(() =>filterSidebarProjectScopeItems({items: projectScopeItems,- activeScopeKey: projectScopeKey,query: projectScopeMenuState.query,matches: (item, query) =>projectScopeFilter.contains(item, query, (candidate) => candidate.label),}),- [projectScopeFilter, projectScopeItems, projectScopeKey, projectScopeMenuState.query],+ [projectScopeFilter, projectScopeItems, projectScopeMenuState.query],);const scopedProjectGroup = useMemo(() =>@@ -2457,6 +2453,8 @@ export default function Sidebar() {},[isMobile, router, setOpenMobile],);+ // Anchor for the scope popup: the header search field, not its icon trigger.+ const headerSearchRef = useRef<HTMLDivElement | null>(null);// Safari can send a click after Ctrl+click opens settings. Ignore that one// selection, then clear the guard when the picker opens again.const suppressNextScopeChangeRef = useRef(false);@@ -4325,100 +4323,11 @@ export default function Sidebar() {fixedHeader={// Lifted above the stage backdrop, whose fade bleeds below the// header and would otherwise paint across the search row's outline.- <SidebarGroup className="relative z-[1] gap-1 p-[var(--sidebar-content-inset)]">- <div className="flex items-center gap-1">- <div className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">- <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />- <Input- ref={threadSearchInputRef}- nativeInput- unstyled- type="search"- value={threadSearchQuery}- onChange={(event) => {- setThreadSearchQuery(event.currentTarget.value);- setActiveSearchResultIndex(0);- }}- onKeyDown={handleThreadSearchKeyDown}- placeholder="Search threads or PRs"- aria-label="Search threads"- role="combobox"- aria-autocomplete="list"- aria-expanded={isSearchingThreads && threadSearchResults.length > 0}- aria-controls={- isSearchingThreads && threadSearchResults.length > 0- ? "sidebar-thread-search-results"- : undefined- }- aria-activedescendant={- isSearchingThreads && threadSearchResults[activeSearchResultIndex]- ? `sidebar-thread-search-result-${activeSearchResultIndex}`- : undefined- }- className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground"- />- {isSearchingThreads ? (- <Button- type="button"- size="icon-micro"- variant="ghost"- className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"- aria-label="Clear thread search"- onClick={() => {- clearThreadSearch();- threadSearchInputRef.current?.focus();- }}- >- <XIcon className="size-3" />- </Button>- ) : null}- </div>- <div className="shrink-0">- <Tooltip>- <TooltipTrigger- render={- <SidebarMenuButton- size="icon"- type="button"- className="relative focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"- onClick={handleNewThreadClick}- disabled={projects.length === 0}- aria-label="New thread"- />- }- >- <SquarePenIcon />- <span- className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"- aria-hidden="true"- />- </TooltipTrigger>- <TooltipPopup side="right">- {projectGroups.length > 1 ? (- <span className="flex flex-col gap-0.5">- <span>- {newThreadShortcutLabel- ? `New thread (${newThreadShortcutLabel})`- : "New thread"}- </span>- <span className="text-muted-foreground">- New thread in current project: Shift+click- {newThreadInProjectShortcutLabel- ? ` (${newThreadInProjectShortcutLabel})`- : ""}- </span>- </span>- ) : newThreadShortcutLabel ? (- `New thread (${newThreadShortcutLabel})`- ) : (- "New thread"- )}- </TooltipPopup>- </Tooltip>- </div>- </div>- {projectGroups.length > 0 ? (- <div className="flex items-center gap-1">+ <SidebarGroup className="relative z-[1] p-[var(--sidebar-content-inset)]">+ <SidebarThreadHeader+ searchFieldRef={headerSearchRef}+ hasProjects={projectGroups.length > 0}+ projectScope={<Comboboxitems={projectScopeItems}filteredItems={filteredProjectScopeItems}@@ -4445,34 +4354,33 @@ export default function Sidebar() {><ComboboxTriggerrender={- <SidebarMenuButton- aria-label="Filter threads by project"- className="min-w-0 flex-1 ps-[calc(var(--sidebar-row-content-inset)-1px)] focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"+ <SidebarHeaderIconButton+ label={+ scopedProjectGroup+ ? `Filter threads by project: ${scopedProjectGroup.displayName}`+ : "Filter threads by project"+ }/>}>{scopedProjectGroup ? (+ // Wrapped so the button's direct-child svg color rule cannot override+ // a project's own icon color.<span className="flex shrink-0"><ProjectFavicon project={scopedProjectGroup} className="size-4" /></span>) : (- <FolderIcon className="size-4 shrink-0" />+ <FolderIcon className="size-4" />)}- <span className="min-w-0 flex-1 truncate">- {scopedProjectGroup?.displayName ?? "All projects"}- </span>- {scopedProjectGroup && showProjectEnvironments ? (- <ProjectEnvironmentBadge- group={scopedProjectGroup}- primaryEnvironmentId={primaryEnvironmentId}- machineByEnvironmentId={environmentMachineById}- />- ) : null}- <ChevronDownIcon className="-mr-px size-4 shrink-0" /></ComboboxTrigger><ComboboxPopupalign="start"- className="w-(--anchor-width) min-w-0 overflow-hidden"+ // Anchored to the search field, not the 28px trigger: the+ // popup opens under the field, is at least as wide as it,+ // and grows to fit project names up to a cap, past which+ // the rows truncate.+ anchor={headerSearchRef}+ className="max-w-[min(18rem,var(--available-width))] overflow-hidden"><ComboboxSearchInputaria-label="Search projects"@@ -4552,28 +4460,25 @@ export default function Sidebar() {</ComboboxList></ComboboxPopup></Combobox>- <Tooltip>- <TooltipTrigger- render={- <SidebarMenuButton- size="icon"- className="relative shrink-0 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"- onClick={openAddProjectCommandPalette}- type="button"- aria-label="New project"- />- }- >- <FolderPlusIcon />- <span- className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"- aria-hidden="true"- />- </TooltipTrigger>- <TooltipPopup side="right">New project</TooltipPopup>- </Tooltip>- </div>- ) : null}+ }+ onNewProject={openAddProjectCommandPalette}+ onNewThread={handleNewThreadClick}+ newThreadDisabled={projects.length === 0}+ newThreadShortcutLabel={newThreadShortcutLabel}+ newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel}+ showNewThreadInProjectHint={projectGroups.length > 1}+ searchInputRef={threadSearchInputRef}+ searchQuery={threadSearchQuery}+ onSearchQueryChange={(value) => {+ setThreadSearchQuery(value);+ setActiveSearchResultIndex(0);+ }}+ onSearchKeyDown={handleThreadSearchKeyDown}+ isSearching={isSearchingThreads}+ searchResultCount={threadSearchResults.length}+ activeSearchResultIndex={activeSearchResultIndex}+ onClearSearch={clearThreadSearch}+ /></SidebarGroup>}>diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsxnew file mode 100644index 00000000000..878235615b3--- /dev/null+++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx@@ -0,0 +1,208 @@+/**+ * The sidebar header: one row holding search, project scope and new thread.+ *+ * Search owns the row's text and spans it. Project scope collapses to an icon+ * that sits with new-project and new-thread as a segmented group at the end.+ * The scope icon swaps to the project favicon while a project is selected,+ * so the header still names the scope after the row that showed it is gone.+ *+ * The scope picker itself is passed in: its combobox state lives with the rest+ * of the sidebar's scope logic. `searchFieldRef` lands on the search field so+ * the picker's popup can anchor to that width rather than to its 28px trigger.+ */+import { FolderPlusIcon, SearchIcon, SquarePenIcon, XIcon } from "lucide-react";+import {+ type ComponentProps,+ type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent as ReactMouseEvent,+ type ReactNode,+ type RefObject,+} from "react";++import { cn } from "~/lib/utils";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { SidebarMenuButton } from "../ui/sidebar";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";++export interface SidebarThreadHeaderProps {+ /** Lands on the search field so a popup can anchor to its width. */+ searchFieldRef?: RefObject<HTMLDivElement | null>;+ /** Without projects there is nothing to scope, so those controls stay out. */+ hasProjects: boolean;+ /** The project scope combobox, rendered as the first icon of the group. */+ projectScope: ReactNode;+ onNewProject: () => void;+ /** Receives the click so Shift+click can skip the project picker. */+ onNewThread: (event: ReactMouseEvent) => void;+ newThreadDisabled: boolean;+ newThreadShortcutLabel: string | null | undefined;+ newThreadInProjectShortcutLabel: string | null | undefined;+ /** Shift+click only matters once there is more than one project to pick. */+ showNewThreadInProjectHint: boolean;+ searchInputRef: RefObject<HTMLInputElement | null>;+ searchQuery: string;+ onSearchQueryChange: (value: string) => void;+ onSearchKeyDown: (event: ReactKeyboardEvent<HTMLInputElement>) => void;+ isSearching: boolean;+ searchResultCount: number;+ activeSearchResultIndex: number;+ onClearSearch: () => void;+}++export function SidebarThreadHeader({+ searchFieldRef,+ hasProjects,+ projectScope,+ onNewProject,+ onNewThread,+ newThreadDisabled,+ newThreadShortcutLabel,+ newThreadInProjectShortcutLabel,+ showNewThreadInProjectHint,+ searchInputRef,+ searchQuery,+ onSearchQueryChange,+ onSearchKeyDown,+ isSearching,+ searchResultCount,+ activeSearchResultIndex,+ onClearSearch,+}: SidebarThreadHeaderProps) {+ const resultsVisible = isSearching && searchResultCount > 0;+ // Results shrink as the query narrows, so the active index can outrun the+ // list; pointing aria-activedescendant at a removed option strands the+ // screen reader on nothing.+ const activeResultExists = resultsVisible && activeSearchResultIndex < searchResultCount;+ const newThreadLabel = newThreadShortcutLabel+ ? `New thread (${newThreadShortcutLabel})`+ : "New thread";++ return (+ <div className="flex items-center gap-1">+ <div+ ref={searchFieldRef}+ className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground"+ >+ <SearchIcon className="size-4 shrink-0 text-[var(--sidebar-icon-color)]" />+ <Input+ ref={searchInputRef}+ nativeInput+ unstyled+ type="search"+ value={searchQuery}+ onChange={(event) => onSearchQueryChange(event.currentTarget.value)}+ onKeyDown={onSearchKeyDown}+ placeholder="Search"+ aria-label="Search threads"+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={resultsVisible}+ aria-controls={resultsVisible ? "sidebar-thread-search-results" : undefined}+ aria-activedescendant={+ activeResultExists+ ? `sidebar-thread-search-result-${activeSearchResultIndex}`+ : undefined+ }+ className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-[var(--sidebar-icon-color)]"+ />+ {isSearching ? (+ <Button+ type="button"+ size="icon-micro"+ variant="ghost"+ className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"+ aria-label="Clear thread search"+ onClick={() => {+ onClearSearch();+ searchInputRef.current?.focus();+ }}+ >+ <XIcon className="size-3" />+ </Button>+ ) : null}+ </div>+ {/* Segmented well: the icons read as one control instead of three loose+ buttons competing with the search field beside them. */}+ <div className="flex shrink-0 items-center rounded-md bg-sidebar-control-surface/60 p-px">+ {hasProjects ? (+ <>+ {projectScope}+ <SidebarHeaderIconButton label="New project" onClick={onNewProject}>+ <FolderPlusIcon />+ </SidebarHeaderIconButton>+ </>+ ) : null}+ <SidebarHeaderIconButton+ label="New thread"+ tooltip={+ showNewThreadInProjectHint ? (+ <span className="flex flex-col gap-0.5">+ <span>{newThreadLabel}</span>+ <span className="text-muted-foreground">+ New thread in current project: Shift+click+ {newThreadInProjectShortcutLabel ? ` (${newThreadInProjectShortcutLabel})` : ""}+ </span>+ </span>+ ) : (+ newThreadLabel+ )+ }+ disabled={newThreadDisabled}+ onClick={onNewThread}+ >+ <SquarePenIcon />+ </SidebarHeaderIconButton>+ </div>+ </div>+ );+}++/**+ * Icon button with a tooltip, sized for the header's segmented pair. Spreads+ * unknown props through so it can serve as a popup trigger's render target,+ * which injects its own handlers, ref and aria state.+ */+export function SidebarHeaderIconButton({+ label,+ tooltip = label,+ className,+ children,+ ...rest+}: {+ /** Accessible name; also the tooltip unless `tooltip` says more. */+ label: string;+ tooltip?: ReactNode;+ className?: string | undefined;+ children?: ReactNode;+} & Omit<+ ComponentProps<typeof SidebarMenuButton>,+ "children" | "className" | "tooltip" | "isActive" | "aria-label"+>) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <SidebarMenuButton+ size="icon"+ type="button"+ aria-label={label}+ {...rest}+ className={cn(+ "relative size-7 shrink-0 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar",+ className,+ )}+ />+ }+ >+ {children}+ {/* Coarse-pointer hit area, matching the rest of the sidebar chrome. */}+ <span+ aria-hidden+ className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"+ />+ </TooltipTrigger>+ <TooltipPopup side="top">{tooltip}</TooltipPopup>+ </Tooltip>+ );+}