Skip to content

Commit b256f35

Browse files
refactor(web): share one ProjectPicker between sidebar and draft screen
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f808796 commit b256f35

7 files changed

Lines changed: 417 additions & 429 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { filterProjectPickerItems, reduceProjectPickerMenuState } from "./ProjectPicker.logic";
4+
5+
describe("filterProjectPickerItems", () => {
6+
const items = [
7+
{ value: "all", label: "All projects", hideWhileSearching: true },
8+
{ value: "alpha", label: "Alpha workspace" },
9+
{ value: "beta", label: "Beta tools" },
10+
] as const;
11+
const filter = (query: string) =>
12+
filterProjectPickerItems({
13+
items,
14+
query,
15+
matches: (item, candidate) =>
16+
item.label.toLocaleLowerCase().includes(candidate.toLocaleLowerCase()),
17+
});
18+
19+
it("shows every row while the query is empty", () => {
20+
expect(filter("")).toEqual(items);
21+
expect(filter(" ")).toEqual(items);
22+
});
23+
24+
it("hides non-project rows while filtering", () => {
25+
expect(filter("all")).toEqual([]);
26+
});
27+
28+
it("returns matching projects in source order and supports no-match results", () => {
29+
expect(filter("WORK")).toEqual([items[1]]);
30+
expect(filter("missing")).toEqual([]);
31+
});
32+
});
33+
34+
describe("reduceProjectPickerMenuState", () => {
35+
const queriedOpenState = { open: true, query: "alpha" };
36+
37+
it("clears the query when the combobox closes through onOpenChange", () => {
38+
expect(
39+
reduceProjectPickerMenuState(queriedOpenState, { type: "open-changed", open: false }),
40+
).toEqual({ open: false, query: "" });
41+
});
42+
43+
it("clears the query when project settings closes the combobox", () => {
44+
expect(
45+
reduceProjectPickerMenuState(queriedOpenState, { type: "project-settings-opened" }),
46+
).toEqual({ open: false, query: "" });
47+
});
48+
49+
it("keeps the popup open while the query changes", () => {
50+
expect(
51+
reduceProjectPickerMenuState(
52+
{ open: true, query: "" },
53+
{ type: "query-changed", query: "beta" },
54+
),
55+
).toEqual({ open: true, query: "beta" });
56+
});
57+
});
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
export interface ProjectPickerFilterItem {
2+
readonly label: string;
3+
/** Default and action rows ("All projects", "Add project") that only make sense unfiltered. */
4+
readonly hideWhileSearching?: boolean | undefined;
5+
}
6+
7+
/**
8+
* Rows that are not projects head or trail the list while the query is empty
9+
* and drop out while filtering, so they can't outrank a project match under
10+
* autoHighlight and no-hit queries reach the empty state.
11+
*/
12+
export function filterProjectPickerItems<TItem extends ProjectPickerFilterItem>(input: {
13+
items: readonly TItem[];
14+
query: string;
15+
matches: (item: TItem, query: string) => boolean;
16+
}): readonly TItem[] {
17+
const query = input.query.trim();
18+
if (query.length === 0) return input.items;
19+
return input.items.filter((item) => !item.hideWhileSearching && input.matches(item, query));
20+
}
21+
22+
export interface ProjectPickerMenuState {
23+
readonly open: boolean;
24+
readonly query: string;
25+
}
26+
27+
export type ProjectPickerMenuAction =
28+
| { readonly type: "query-changed"; readonly query: string }
29+
| { readonly type: "open-changed"; readonly open: boolean }
30+
| { readonly type: "project-settings-opened" };
31+
32+
export function reduceProjectPickerMenuState(
33+
state: ProjectPickerMenuState,
34+
action: ProjectPickerMenuAction,
35+
): ProjectPickerMenuState {
36+
switch (action.type) {
37+
case "query-changed":
38+
return { ...state, query: action.query };
39+
case "open-changed":
40+
return { open: action.open, query: "" };
41+
case "project-settings-opened":
42+
return { open: false, query: "" };
43+
}
44+
}
Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import { SettingsIcon } from "lucide-react";
2+
import {
3+
useMemo,
4+
useReducer,
5+
useRef,
6+
type KeyboardEvent as ReactKeyboardEvent,
7+
type MouseEvent as ReactMouseEvent,
8+
type ReactNode,
9+
} from "react";
10+
11+
import { useEnvironmentMachines, usePrimaryEnvironmentId } from "~/state/environments";
12+
import {
13+
projectGroupsSpanEnvironments,
14+
type SidebarProjectSnapshot,
15+
} from "~/sidebarProjectGrouping";
16+
import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge";
17+
import { ProjectFavicon } from "./ProjectFavicon";
18+
import { filterProjectPickerItems, reduceProjectPickerMenuState } from "./ProjectPicker.logic";
19+
import { Button } from "./ui/button";
20+
import {
21+
Combobox,
22+
ComboboxEmpty,
23+
ComboboxItem,
24+
ComboboxList,
25+
ComboboxPopup,
26+
ComboboxSearchInput,
27+
useComboboxFilter,
28+
} from "./ui/combobox";
29+
30+
export interface ProjectPickerItem {
31+
readonly value: string;
32+
readonly label: string;
33+
/** Null for rows that are not a project, such as "All projects". */
34+
readonly project: SidebarProjectSnapshot | null;
35+
/** Leading icon for rows without a project. */
36+
readonly icon?: ReactNode;
37+
readonly hideWhileSearching?: boolean;
38+
}
39+
40+
/**
41+
* Searchable project list behind the sidebar's project filter and the draft
42+
* screen's project selector. The caller renders the `ComboboxTrigger` as
43+
* `trigger`, since each surface has its own button.
44+
*/
45+
export function ProjectPicker(props: {
46+
readonly items: readonly ProjectPickerItem[];
47+
readonly selectedValue: string | null;
48+
readonly onSelect: (item: ProjectPickerItem) => void;
49+
readonly trigger: ReactNode;
50+
readonly align?: "start" | "center" | "end";
51+
readonly anchor?: React.RefObject<Element | null>;
52+
/** Adds a settings button and the context-menu gesture to project rows. */
53+
readonly onProjectSettings?: (project: SidebarProjectSnapshot) => void;
54+
}) {
55+
const { items, onProjectSettings } = props;
56+
const primaryEnvironmentId = usePrimaryEnvironmentId();
57+
const environmentMachineById = useEnvironmentMachines();
58+
// Same-named projects on two machines are only told apart by where they
59+
// live, so rows on another machine carry its icon once the catalog spans
60+
// more than one environment; a single-machine catalog stays as it was.
61+
const showProjectEnvironments = useMemo(
62+
() =>
63+
projectGroupsSpanEnvironments(
64+
items.flatMap((item) => (item.project === null ? [] : [item.project])),
65+
),
66+
[items],
67+
);
68+
const [menuState, dispatchMenu] = useReducer(reduceProjectPickerMenuState, {
69+
open: false,
70+
query: "",
71+
});
72+
const filter = useComboboxFilter();
73+
// Filtering derives from the same React state that controls the input, so
74+
// the visible query and the visible list can never desync.
75+
const filteredItems = useMemo(
76+
() =>
77+
filterProjectPickerItems({
78+
items,
79+
query: menuState.query,
80+
matches: (item, query) => filter.contains(item, query, (candidate) => candidate.label),
81+
}),
82+
[filter, items, menuState.query],
83+
);
84+
const selectedItem = items.find((item) => item.value === props.selectedValue) ?? null;
85+
// Safari can send a click after Ctrl+click opens settings. Ignore that one
86+
// selection, then clear the guard when the picker opens again.
87+
const suppressNextChangeRef = useRef(false);
88+
const highlightedValueRef = useRef<string | null>(null);
89+
const openSettings = (
90+
event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
91+
project: SidebarProjectSnapshot,
92+
) => {
93+
if (!onProjectSettings) return;
94+
event.preventDefault();
95+
event.stopPropagation();
96+
suppressNextChangeRef.current = true;
97+
dispatchMenu({ type: "project-settings-opened" });
98+
onProjectSettings(project);
99+
};
100+
101+
return (
102+
<Combobox
103+
items={items}
104+
filteredItems={filteredItems}
105+
autoHighlight
106+
itemToStringLabel={(item) => item.label}
107+
isItemEqualToValue={(a, b) => a.value === b.value}
108+
open={menuState.open}
109+
onOpenChange={(open) => {
110+
if (open) suppressNextChangeRef.current = false;
111+
dispatchMenu({ type: "open-changed", open });
112+
}}
113+
onItemHighlighted={(item) => {
114+
highlightedValueRef.current = item?.value ?? null;
115+
}}
116+
value={selectedItem}
117+
onValueChange={(item) => {
118+
if (suppressNextChangeRef.current) {
119+
suppressNextChangeRef.current = false;
120+
return;
121+
}
122+
if (!item) return;
123+
dispatchMenu({ type: "open-changed", open: false });
124+
props.onSelect(item);
125+
}}
126+
>
127+
{props.trigger}
128+
<ComboboxPopup
129+
align={props.align ?? "start"}
130+
anchor={props.anchor}
131+
// At least as wide as its anchor, growing to fit project names up to
132+
// a cap, past which the rows truncate.
133+
className="max-w-[min(18rem,var(--available-width))] overflow-hidden"
134+
>
135+
<ComboboxSearchInput
136+
aria-label="Search projects"
137+
placeholder="Search projects..."
138+
value={menuState.query}
139+
onKeyDown={(event) => {
140+
if (
141+
event.defaultPrevented ||
142+
event.nativeEvent.isComposing ||
143+
event.ctrlKey ||
144+
event.altKey ||
145+
event.metaKey ||
146+
(event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10"))
147+
) {
148+
return;
149+
}
150+
// Combobox items use virtual focus: keyboard events stay on this
151+
// input, not on the highlighted option.
152+
const project = items.find(
153+
(item) => item.value === highlightedValueRef.current,
154+
)?.project;
155+
if (project) openSettings(event, project);
156+
}}
157+
onChange={(event) => dispatchMenu({ type: "query-changed", query: event.target.value })}
158+
/>
159+
<ComboboxEmpty>No matching projects.</ComboboxEmpty>
160+
<ComboboxList>
161+
{(item: ProjectPickerItem) => {
162+
const project = item.project;
163+
return (
164+
<ComboboxItem
165+
key={item.value}
166+
hideIndicator
167+
value={item}
168+
onContextMenu={(event) => {
169+
if (project) openSettings(event, project);
170+
}}
171+
>
172+
{project ? (
173+
<ProjectFavicon project={project} className="size-4 shrink-0" />
174+
) : (
175+
item.icon
176+
)}
177+
<span className="min-w-0 flex-1 truncate text-sm">{item.label}</span>
178+
{project && showProjectEnvironments ? (
179+
<ProjectEnvironmentBadge
180+
group={project}
181+
primaryEnvironmentId={primaryEnvironmentId}
182+
machineByEnvironmentId={environmentMachineById}
183+
/>
184+
) : null}
185+
{project && onProjectSettings ? (
186+
<Button
187+
size="icon-xs"
188+
variant="ghost-muted"
189+
tabIndex={-1}
190+
aria-hidden="true"
191+
title={`Project settings for ${project.displayName}`}
192+
className="ml-auto"
193+
onPointerDown={(event) => event.stopPropagation()}
194+
onClick={(event) => openSettings(event, project)}
195+
>
196+
<SettingsIcon className="size-3.5" />
197+
</Button>
198+
) : null}
199+
</ComboboxItem>
200+
);
201+
}}
202+
</ComboboxList>
203+
</ComboboxPopup>
204+
</Combobox>
205+
);
206+
}

‎apps/web/src/components/Sidebar.logic.test.ts‎

Lines changed: 0 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import {
1313
buildMultiSelectThreadContextMenuItems,
1414
createThreadJumpHintVisibilityController,
1515
deleteSelectedThreadEntries,
16-
filterSidebarProjectScopeItems,
1716
filterSidebarV2VisibleThreads,
1817
formatWorkingDurationLabel,
1918
getFallbackThreadIdAfterDelete,
@@ -27,7 +26,6 @@ import {
2726
isTrailingDoubleClick,
2827
orderItemsByPreferredIds,
2928
pinOrderKeyBetween,
30-
reduceSidebarProjectScopeMenuState,
3129
resolveAdjacentThreadId,
3230
resolveProjectStatusIndicator,
3331
resolveSidebarSweepKeys,
@@ -1048,65 +1046,6 @@ describe("searchSidebarThreads", () => {
10481046
});
10491047
});
10501048

1051-
describe("filterSidebarProjectScopeItems", () => {
1052-
const items = [
1053-
{ value: "all", label: "All projects" },
1054-
{ value: "alpha", label: "Alpha workspace" },
1055-
{ value: "beta", label: "Beta tools" },
1056-
] as const;
1057-
const filter = (query: string) =>
1058-
filterSidebarProjectScopeItems({
1059-
items,
1060-
query,
1061-
matches: (item, candidate) =>
1062-
item.label.toLocaleLowerCase().includes(candidate.toLocaleLowerCase()),
1063-
});
1064-
1065-
it("shows the default row first while the query is empty", () => {
1066-
expect(filter("")).toEqual(items);
1067-
expect(filter(" ")).toEqual(items);
1068-
});
1069-
1070-
it("hides the default row while filtering", () => {
1071-
expect(filter("all")).toEqual([]);
1072-
});
1073-
1074-
it("returns matching projects in source order and supports no-match results", () => {
1075-
expect(filter("WORK")).toEqual([items[1]]);
1076-
expect(filter("missing")).toEqual([]);
1077-
});
1078-
});
1079-
1080-
describe("reduceSidebarProjectScopeMenuState", () => {
1081-
const queriedOpenState = { open: true, query: "alpha" };
1082-
1083-
it("clears the query when the combobox closes through onOpenChange", () => {
1084-
expect(
1085-
reduceSidebarProjectScopeMenuState(queriedOpenState, {
1086-
type: "open-changed",
1087-
open: false,
1088-
}),
1089-
).toEqual({ open: false, query: "" });
1090-
});
1091-
1092-
it("clears the query when project settings closes the combobox", () => {
1093-
expect(
1094-
reduceSidebarProjectScopeMenuState(queriedOpenState, {
1095-
type: "project-settings-opened",
1096-
}),
1097-
).toEqual({ open: false, query: "" });
1098-
});
1099-
1100-
it("keeps the popup open while the query changes", () => {
1101-
expect(
1102-
reduceSidebarProjectScopeMenuState(
1103-
{ open: true, query: "" },
1104-
{ type: "query-changed", query: "beta" },
1105-
),
1106-
).toEqual({ open: true, query: "beta" });
1107-
});
1108-
});
1109-
11101049
describe("resolveWorkingStartedAt", () => {
11111050
const runtime = {
11121051
status: "running" as const,

0 commit comments

Comments
 (0)