Open History to see the last commit
1import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
2import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
3import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
4import { computeThreadMoveAvailability } from "./threadOrder";
5import type {
6 EnvironmentProject,
7 EnvironmentThreadShell,
8} from "@t3tools/client-runtime/state/shell";
9import {
10 threadSearchMatchKey,
11 type EnvironmentThreadSearchMatch,
12} from "@t3tools/client-runtime/state/thread-search";
13import { LegendList } from "@legendapp/list/react-native";
14import type { MenuAction } from "@react-native-menu/menu";
15import { useAtomValue } from "@effect/atom-react";
16import { useEffect, useMemo, useRef, useState } from "react";
17import type { LayoutChangeEvent, TextInputInstance } from "react-native";
18import { Platform, StyleSheet, TextInput, View } from "react-native";
19import { GestureDetector, useNativeGesture } from "react-native-gesture-handler";
20import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
21import { useSafeAreaInsets } from "react-native-safe-area-context";
22import type { SearchBarCommands } from "react-native-screens";
23
24import { AppText as Text } from "../../components/ui/AppText";
25import { CompactBrandTitle } from "../../components/CompactBrandTitle";
26import { Menu } from "../../components/ui/Menu";
27import { SymbolView } from "../../components/ui/AppSymbol";
28import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
29import { NativeStackScreenOptions } from "../../native/StackHeader";
30import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
31import { useProjects, useNavigationThreadShells } from "../../state/entities";
32import { useThreadSearch } from "../../state/queries";
33import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
34import { usePendingThreadOrder } from "../../state/thread-order";
35import { threadListEnvironmentsAtom } from "../../state/server";
36import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
37import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
38import { useWorkspaceState } from "../../state/workspace";
39import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
40import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
41import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
42import { useHomeListOptions } from "../home/home-list-options";
43import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
44import { buildHomeProjectScopes } from "../home/homeThreadList";
45import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
46import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
47import { useThreadListActions } from "../home/useThreadListActions";
48import {
49 getConnectionAwareBrandHeaderOptions,
50 WorkspaceConnectionTitle,
51} from "../home/WorkspaceConnectionTitle";
52import { SidebarHeaderActions } from "./sidebar-header-actions";
53import { ThreadListToolbar } from "../home/ThreadListToolbar";
54import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
55import { useFabScroll } from "../home/FabScrollContext";
56import { SidebarFilterButton } from "./sidebar-filter-button";
57import { createSidebarHeaderItems } from "./sidebar-native-header-items";
58import { SidebarNavigationShell } from "./sidebar-navigation-shell";
59import {
60 ThreadListV2PendingRow,
61 ThreadListV2Row,
62 ThreadListV2SettledShelfHeader,
63 ThreadListV2ShowMoreRow,
64 ThreadListV2SnoozedShelfHeader,
65 ThreadListV2WorkingShelfHeader,
66} from "./thread-list-v2-items";
67import { useThreadRowProviderInstanceResolver } from "./thread-provider-instance";
68import type { ThreadPrPresentation } from "../../state/thread-pr-presentation";
69import {
70 buildThreadListV2Items,
71 getThreadListV2OrderedSection,
72 buildThreadListV2ListItems,
73 isThreadListV2ListItem,
74 threadListV2ListItemsAreEqual,
75 threadListInboxReturns,
76 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
77 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
78 type ThreadListV2ListItem,
79} from "./threadListV2";
80
81type SidebarListItem =
82 | ThreadListV2ListItem
83 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
84
85const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
86
87interface ThreadNavigationSidebarProps {
88 readonly width: number;
89 readonly visible: boolean;
90 readonly selectedThreadKey: string | null;
91 readonly onOpenSettings: () => void;
92 readonly onOpenEnvironmentSettings: () => void;
93 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
94 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
95 readonly onOpenPendingTask: (pendingTask: PendingNewTask) => void;
96 readonly onSearchQueryChange: (query: string) => void;
97 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
98 readonly onOpenThreadPullRequests: (
99 thread: EnvironmentThreadShell,
100 pr: ThreadPrPresentation,
101 ) => void;
102 readonly onRequestVisibility: () => void;
103 readonly searchQuery: string;
104}
105
106export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
107 if (Platform.OS !== "ios") {
108 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
109 }
110 return <NativeSidebarContainer {...props} />;
111}
112
113function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
114 return (
115 <View
116 testID="thread-navigation-sidebar"
117 className="flex-1 border-border bg-drawer"
118 style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }}
119 >
120 <SidebarNavigationShell>
121 <ThreadNavigationSidebarPane {...props} nativeChrome />
122 </SidebarNavigationShell>
123 </View>
124 );
125}
126
127function ThreadNavigationSidebarPane(
128 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
129) {
130 const { themeVariables: materialTheme } = useAppearancePreferences();
131 const drawerColor = materialTheme["--color-drawer"];
132
133 const insets = useSafeAreaInsets();
134 const { fabClearance } = useAndroidControlSizing();
135 const projects = useProjects();
136 const threads = useNavigationThreadShells();
137 const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
138 const { savedConnectionsById } = useSavedRemoteConnections();
139 const searchInputRef = useRef<TextInputInstance>(null);
140 const searchBarRef = useRef<SearchBarCommands>(null);
141 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
142 const sidebarScrollGesture = useNativeGesture();
143 const {
144 archiveThread,
145 confirmDeleteThread,
146 settleThread,
147 snoozeThread,
148 unsnoozeThread,
149 unsettleThread,
150 pinThread,
151 unpinThread,
152 setThreadAutoSettle,
153 moveThread,
154 renameThread,
155 regenerateThreadTitle,
156 } = useThreadListActions();
157 const pendingTasks = usePendingNewTasks();
158 const queuedThreadKeys = useQueuedThreadKeys();
159 const { confirmDeletePendingTask } = usePendingTaskListActions();
160 const environments = Object.values(savedConnectionsById)
161 .map((connection) => ({
162 environmentId: connection.environmentId,
163 label: connection.environmentLabel,
164 }))
165 .sort((left, right) => left.label.localeCompare(right.label));
166 const availableEnvironmentIds = new Set(
167 environments.map((environment) => environment.environmentId),
168 );
169 const { options, setSelectedEnvironmentId, setSelectedProjectKey } =
170 useHomeListOptions(availableEnvironmentIds);
171 const searchEnvironmentIds =
172 options.selectedEnvironmentId === null
173 ? workspaceEnvironments
174 .filter((environment) => environment.connectionState === "connected")
175 .map((environment) => environment.environmentId)
176 : workspaceEnvironments.some(
177 (environment) =>
178 environment.environmentId === options.selectedEnvironmentId &&
179 environment.connectionState === "connected",
180 )
181 ? [options.selectedEnvironmentId]
182 : [];
183 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
184 // These maps reach LegendList's extraData, which re-renders every row whenever it changes
185 // identity. The compiler leaves them unmemoized because they stay live across later hook calls.
186 const threadSearchMatchByKey = useMemo(() => {
187 const matches = new Map<string, EnvironmentThreadSearchMatch>();
188 for (const match of threadSearch.matches) {
189 if (match.source === "user" || match.source === "assistant") {
190 matches.set(threadSearchMatchKey(match), match);
191 }
192 }
193 return matches;
194 }, [threadSearch.matches]);
195 const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
196 const projectScopeKey = options.selectedProjectKey;
197 const resolvedProjectKey = resolveScratchProjectScopeKey(projectScopeKey, projects, {
198 sidebarProjectGroupingMode: options.projectGroupingMode,
199 sidebarProjectGroupingOverrides: {},
200 });
201 useEffect(() => {
202 if (resolvedProjectKey !== projectScopeKey) {
203 setSelectedProjectKey(resolvedProjectKey);
204 }
205 }, [projectScopeKey, resolvedProjectKey, setSelectedProjectKey]);
206 const projectScopes = useMemo(
207 () =>
208 buildHomeProjectScopes({
209 projects,
210 environmentId: options.selectedEnvironmentId,
211 projectGroupingMode: options.projectGroupingMode,
212 }),
213 [projects, options.selectedEnvironmentId, options.projectGroupingMode],
214 );
215 const projectFilterOptions = projectScopes.map((scope) => ({
216 key: scope.key,
217 label: scope.title,
218 }));
219 const projectTitleByProjectKey = useMemo(
220 () =>
221 new Map(
222 projectScopes.flatMap((scope) =>
223 scope.projectRefs.map(
224 (projectRef) =>
225 [
226 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
227 scope.title,
228 ] as const,
229 ),
230 ),
231 ),
232 [projectScopes],
233 );
234 const selectedProjectScope =
235 projectScopes.find((scope) => scope.key === resolvedProjectKey) ?? null;
236 const selectedProjectKey = selectedProjectScope?.key ?? null;
237 const selectedProjectRefs =
238 selectedProjectScope === null
239 ? null
240 : new Set(
241 selectedProjectScope.projectRefs.map((projectRef) =>
242 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
243 ),
244 );
245 const projectByKey = useMemo(() => {
246 const map = new Map<string, EnvironmentProject>();
247 for (const project of projects) {
248 map.set(scopedProjectKey(project.environmentId, project.id), project);
249 }
250 return map;
251 }, [projects]);
252
253 const [settledVisibleCount, setSettledVisibleCount] = useState(
254 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
255 );
256 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
257 const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
258 if (lastSettledResetKey !== settledResetKey) {
259 setLastSettledResetKey(settledResetKey);
260 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
261 }
262 const showMoreSettled = () =>
263 setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
264 const {
265 loaded: shelfPreferencesLoaded,
266 settledShelfExpanded,
267 snoozedShelfExpanded,
268 workingShelfEnabled,
269 workingShelfExpanded,
270 toggleSettledShelf,
271 toggleSnoozedShelf,
272 toggleWorkingShelf,
273 } = useThreadListV2ShelfPreferences();
274 // The list's clock is state: the compiler caches anything computed from it on
275 // its other inputs, so a render-time `new Date()` would stop moving. The minute
276 // interval and the snooze-wake timer below both advance it.
277 const [now, setNow] = useState(() => new Date().toISOString());
278 const nowMinute = now.slice(0, 16);
279 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
280 useEffect(() => {
281 setNow(new Date().toISOString());
282 const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
283 return () => clearInterval(id);
284 }, []);
285 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
286 const {
287 providersByEnvironmentId,
288 machineByEnvironmentId,
289 settlementEnvironmentIds,
290 snoozeEnvironmentIds,
291 pinningEnvironmentIds,
292 autoSettleOptOutEnvironmentIds,
293 pinReorderEnvironmentIds,
294 activeReorderEnvironmentIds,
295 titleRegenerationEnvironmentIds,
296 } = listEnvironments;
297 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
298 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
299 // Up/down menu availability for every card, computed once per section per
300 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
301 // list construction quadratic, and this list rebuilds on every minute tick.
302 const threadMoveAvailability = (() => {
303 const sectionAvailability = (section: "pinned" | "active") =>
304 computeThreadMoveAvailability({
305 allThreads: threads,
306 section,
307 pendingOrder,
308 reorderableEnvironmentIds:
309 section === "pinned" ? pinReorderEnvironmentIds : activeReorderEnvironmentIds,
310 ordered: getThreadListV2OrderedSection({
311 threads,
312 section,
313 pendingOrder,
314 now,
315 settlementEnvironmentIds,
316 snoozeEnvironmentIds,
317 queuedThreadKeys,
318 }),
319 });
320 return new Map([
321 ...sectionAvailability("pinned"),
322 ...(workingShelfEnabled ? [] : sectionAvailability("active")),
323 ]);
324 })();
325 const threadListV2Layout = (() => {
326 threadListInboxReturns.observe(workingShelfEnabled ? threads : null);
327 return buildThreadListV2Items({
328 pendingOrder,
329 threads: threads.filter((thread) => thread.archivedAt === null),
330 environmentId: options.selectedEnvironmentId,
331 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
332 searchQuery: props.searchQuery,
333 matchedThreadKeys,
334 settlementEnvironmentIds,
335 snoozeEnvironmentIds,
336 queuedThreadKeys,
337 settledLimit: settledVisibleCount,
338 now,
339 workingShelfEnabled,
340 workingShelfExpanded,
341 inboxReturnAt: threadListInboxReturns.returnedAt,
342 snoozedShelfExpanded,
343 settledShelfExpanded,
344 selectedThreadKey: props.selectedThreadKey ?? null,
345 });
346 })();
347 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
348 useEffect(() => {
349 if (nextSnoozeWakeAt === null) return;
350 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
351 if (Number.isNaN(wakeAtMs)) return;
352 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
353 const id = setTimeout(() => {
354 setNow(new Date().toISOString());
355 bumpSnoozeWakeTick((tick) => tick + 1);
356 }, delayMs);
357 return () => clearTimeout(id);
358 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
359 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
360 // range) the boundary string is identical and the chain would die.
361 }, [nextSnoozeWakeAt, snoozeWakeTick]);
362 const listItems = ((): readonly SidebarListItem[] => {
363 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
364 const v2PendingTasks = pendingTasks.filter(
365 (pendingTask) =>
366 (options.selectedEnvironmentId === null ||
367 pendingTask.environmentId === options.selectedEnvironmentId) &&
368 (selectedProjectRefs === null ||
369 selectedProjectRefs.has(
370 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
371 )) &&
372 (v2SearchQuery.length === 0 ||
373 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
374 );
375 const items: SidebarListItem[] = buildThreadListV2ListItems({
376 items: threadListV2Layout.items,
377 pendingTasks: v2PendingTasks,
378 workingCount: threadListV2Layout.workingCount,
379 workingShelfExpanded,
380 workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex,
381 snoozedCount: threadListV2Layout.snoozedCount,
382 snoozedShelfExpanded,
383 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
384 settledCount: threadListV2Layout.settledCount,
385 settledShelfExpanded,
386 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
387 snoozeLabelNow: `${nowMinute}:00.000Z`,
388 snoozeEnvironmentIds,
389 queuedThreadKeys,
390 moveAvailability: threadMoveAvailability,
391 shelfPreferencesLoading: !shelfPreferencesLoaded,
392 });
393 if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
394 items.push({
395 type: "v2-show-more",
396 key: "v2-show-more",
397 hiddenCount: threadListV2Layout.hiddenSettledCount,
398 });
399 }
400 return items;
401 })();
402 const listMenuActions = [
403 {
404 id: "environment",
405 title: "Environment",
406 subactions: [
407 {
408 id: "environment:all",
409 title: "All environments",
410 subtitle: "Show threads from every environment",
411 state: options.selectedEnvironmentId === null ? "on" : "off",
412 },
413 ...environments.map((environment) => ({
414 id: `environment:${environment.environmentId}`,
415 title: environment.label,
416 state:
417 options.selectedEnvironmentId === environment.environmentId
418 ? ("on" as const)
419 : ("off" as const),
420 })),
421 ],
422 },
423 ...(projectFilterOptions.length === 0
424 ? []
425 : ([
426 {
427 id: "project",
428 title: "Project",
429 subactions: [
430 {
431 id: "project:all",
432 title: "All projects",
433 subtitle: "Show threads from every project",
434 state: selectedProjectKey === null ? "on" : "off",
435 },
436 ...projectFilterOptions.map((project) => ({
437 id: `project:${project.key}`,
438 title: project.label,
439 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
440 })),
441 ],
442 },
443 ] satisfies MenuAction[])),
444 ] satisfies MenuAction[];
445 const handleListMenuAction = ({
446 nativeEvent,
447 }: {
448 readonly nativeEvent: { readonly event: string };
449 }) => {
450 const event = nativeEvent.event;
451 if (event === "environment:all") {
452 setSelectedEnvironmentId(null);
453 return;
454 }
455 if (event.startsWith("environment:")) {
456 const environment = environments.find(
457 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
458 );
459 if (environment) setSelectedEnvironmentId(environment.environmentId);
460 return;
461 }
462 if (event === "project:all") {
463 setSelectedProjectKey(null);
464 return;
465 }
466 if (event.startsWith("project:")) {
467 const projectKey = event.slice("project:".length);
468 if (projectFilterOptions.some((project) => project.key === projectKey)) {
469 setSelectedProjectKey(projectKey);
470 }
471 return;
472 }
473 };
474
475 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
476 const { height, paddingTop, paddingBottom } = useToolbarLayout();
477 // The sticky header (title row, search field, optional connection status)
478 // is measured so the list inset always matches its real height — no
479 // hardcoded per-variant constants.
480 const stickyHeaderHeight =
481 measuredHeaderHeight ??
482 (Platform.OS === "android"
483 ? paddingTop + height + paddingBottom
484 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
485 const topListInset = stickyHeaderHeight + 6;
486 const handleStickyHeaderLayout = (event: LayoutChangeEvent) => {
487 const nextHeight = event.nativeEvent.layout.height;
488 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
489 };
490 const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
491 if (openSwipeableRef.current !== methods) {
492 openSwipeableRef.current?.close();
493 openSwipeableRef.current = methods;
494 }
495 };
496 const handleSwipeableClose = (methods: SwipeableMethods) => {
497 if (openSwipeableRef.current === methods) {
498 openSwipeableRef.current = null;
499 }
500 };
501 // These close the open row too, so they cannot be pass-throughs. The compiler would
502 // recache a closure over `props` whenever any prop changed.
503 const { onSelectThread, onOpenThreadPullRequests } = props;
504 const handleSelectThread = (thread: EnvironmentThreadShell) => {
505 onSelectThread(thread);
506 openSwipeableRef.current?.close();
507 };
508 const handleOpenThreadPullRequests = (
509 thread: EnvironmentThreadShell,
510 pr: ThreadPrPresentation,
511 ) => {
512 onOpenThreadPullRequests(thread, pr);
513 openSwipeableRef.current?.close();
514 };
515 const handleScrollBeginDrag = () => {
516 openSwipeableRef.current?.close();
517 };
518 const onFabScroll = useFabScroll();
519 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
520 onScroll: onFabScroll,
521 onScrollBeginDrag: handleScrollBeginDrag,
522 });
523 // The sticky header's project shells and search maps feed row props, so
524 // they have to bust the recycler's memoization — otherwise a row keeps the
525 // blank favicon and fallback title it was first rendered with. The minute
526 // clock deliberately stays out: its per-row text lives on the items, so a
527 // tick only re-renders rows whose displayed text actually moved.
528 const listExtraData = {
529 selectedThreadKey: props.selectedThreadKey ?? "",
530 projectByKey,
531 projectTitleByProjectKey,
532 savedConnectionsById,
533 listEnvironments,
534 threadSearchMatchByKey,
535 workingShelfEnabled,
536 };
537 useThreadJumpShortcuts(listItems, handleSelectThread);
538 const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
539 if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
540 return threadListV2ListItemsAreEqual(previous, item);
541 }
542 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
543 return previous.hiddenCount === item.hiddenCount;
544 }
545 return false;
546 };
547 const focusSearch = () => {
548 if (Platform.OS === "android") return false;
549 const focus = () => {
550 if (props.nativeChrome) {
551 searchBarRef.current?.focus();
552 return;
553 }
554 searchInputRef.current?.focus();
555 };
556 if (!props.visible) {
557 props.onRequestVisibility();
558 setTimeout(focus, 240);
559 } else {
560 focus();
561 }
562 return true;
563 };
564 useHardwareKeyboardCommand("focusSearch", focusSearch);
565 const renderListItem = ({ item }: { readonly item: SidebarListItem }) => {
566 switch (item.type) {
567 case "v2-pending": {
568 const pendingScopeKey = scopedProjectKey(
569 item.pendingTask.environmentId,
570 item.pendingTask.projectId,
571 );
572 return (
573 <ThreadListV2PendingRow
574 pendingTask={item.pendingTask}
575 project={projectByKey.get(pendingScopeKey) ?? null}
576 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
577 environmentLabel={
578 Object.keys(savedConnectionsById).length > 1
579 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
580 : null
581 }
582 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
583 pane="sidebar"
584 showPendingDivider={item.showPendingDivider}
585 onSelectPendingTask={props.onOpenPendingTask}
586 onDeletePendingTask={confirmDeletePendingTask}
587 />
588 );
589 }
590 case "v2-thread": {
591 const thread = item.item.thread;
592 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
593 return (
594 <ThreadListV2Row
595 onNewThreadOnBranch={props.onNewThreadOnBranch}
596 thread={thread}
597 variant={item.item.variant}
598 hasQueuedMessages={item.hasQueuedMessages}
599 snoozed={item.item.snoozed}
600 pinned={item.item.pinned}
601 snoozePresetMinute={item.snoozePresetMinute ?? ""}
602 snoozeWakeLabelText={item.snoozeWakeLabelText}
603 timeLabel={item.timeLabel}
604 project={projectByKey.get(scopeKey) ?? null}
605 projectTitle={projectTitleByProjectKey.get(scopeKey)}
606 providerInstance={resolveProviderInstance(thread)}
607 providers={providersByEnvironmentId.get(thread.environmentId)}
608 environmentLabel={
609 Object.keys(savedConnectionsById).length > 1
610 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
611 : null
612 }
613 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
614 searchMatch={threadSearchMatchByKey.get(
615 threadSearchMatchKey({
616 environmentId: thread.environmentId,
617 threadId: thread.id,
618 }),
619 )}
620 searchQuery={props.searchQuery}
621 pane="sidebar"
622 selected={scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey}
623 fullSwipeWidth={props.width - 20}
624 onSelectThread={handleSelectThread}
625 onOpenThreadPullRequests={handleOpenThreadPullRequests}
626 onDeleteThread={confirmDeleteThread}
627 onArchiveThread={archiveThread}
628 onRenameThread={renameThread}
629 onRegenerateThreadTitle={regenerateThreadTitle}
630 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
631 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
632 onSettleThread={settleThread}
633 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
634 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
635 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
636 reorderSupported={
637 item.item.pinned
638 ? pinReorderEnvironmentIds.has(thread.environmentId)
639 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
640 }
641 canMoveUp={item.canMoveUp}
642 canMoveDown={item.canMoveDown}
643 onSnoozeThread={snoozeThread}
644 onUnsnoozeThread={unsnoozeThread}
645 onUnsettleThread={unsettleThread}
646 onPinThread={pinThread}
647 onUnpinThread={unpinThread}
648 onSetThreadAutoSettle={setThreadAutoSettle}
649 onMoveThread={moveThread}
650 onSwipeableClose={handleSwipeableClose}
651 onSwipeableWillOpen={handleSwipeableWillOpen}
652 simultaneousSwipeGesture={sidebarScrollGesture}
653 />
654 );
655 }
656 case "v2-working-shelf":
657 return (
658 <ThreadListV2WorkingShelfHeader
659 count={item.count}
660 disabled={item.disabled}
661 expanded={item.expanded}
662 onToggle={toggleWorkingShelf}
663 pane="sidebar"
664 />
665 );
666 case "v2-snoozed-shelf":
667 return (
668 <ThreadListV2SnoozedShelfHeader
669 count={item.count}
670 disabled={item.disabled}
671 expanded={item.expanded}
672 onToggle={toggleSnoozedShelf}
673 pane="sidebar"
674 />
675 );
676 case "v2-settled-shelf":
677 return (
678 <ThreadListV2SettledShelfHeader
679 count={item.count}
680 disabled={item.disabled}
681 expanded={item.expanded}
682 onToggle={toggleSettledShelf}
683 pane="sidebar"
684 />
685 );
686 case "v2-show-more":
687 return (
688 <ThreadListV2ShowMoreRow
689 pane="sidebar"
690 hiddenCount={item.hiddenCount}
691 onPress={showMoreSettled}
692 />
693 );
694 }
695 };
696 const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
697 const filterIcon = filterCustomized
698 ? "line.3.horizontal.decrease.circle.fill"
699 : "line.3.horizontal.decrease.circle";
700 const filterMenu = buildHomeListFilterMenu({
701 environments,
702 projects: projectFilterOptions,
703 selectedEnvironmentId: options.selectedEnvironmentId,
704 selectedProjectKey,
705 onEnvironmentChange: setSelectedEnvironmentId,
706 onProjectChange: setSelectedProjectKey,
707 });
708 const nativeHeaderItems = createSidebarHeaderItems({
709 filterIcon,
710 filterMenu,
711 onOpenSettings: props.onOpenSettings,
712 });
713 const listEmpty = (
714 <Text
715 className={
716 Platform.OS === "android"
717 ? "px-4 py-4 text-center text-sm text-drawer-foreground-muted"
718 : "px-2 py-4 text-sm text-drawer-foreground-muted"
719 }
720 >
721 {catalogState.isLoadingConnections
722 ? "Loading threads…"
723 : Platform.OS === "android" && !catalogState.hasConnections
724 ? "No environments connected"
725 : props.searchQuery.trim().length > 0
726 ? threadSearch.isPending
727 ? "Searching thread messages…"
728 : "No matching threads"
729 : selectedProjectScope !== null
730 ? `No threads in ${selectedProjectScope.title}`
731 : "No threads yet"}
732 </Text>
733 );
734
735 if (props.nativeChrome) {
736 return (
737 <>
738 <NativeStackScreenOptions
739 optionsVersion={[nativeHeaderItems, props.width]}
740 options={{
741 ...getConnectionAwareBrandHeaderOptions({
742 headerWidth: props.width,
743 trailingItemCount: nativeHeaderItems.length,
744 onOpenEnvironments: props.onOpenEnvironmentSettings,
745 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
746 }),
747 headerSearchBarOptions: {
748 ref: searchBarRef,
749 autoCapitalize: "none",
750 hideNavigationBar: false,
751 hideWhenScrolling: false,
752 obscureBackground: false,
753 placeholder: "Search",
754 placement: "stacked",
755 onCancelButtonPress: () => {
756 props.onSearchQueryChange("");
757 },
758 onChangeText: (event) => {
759 props.onSearchQueryChange(event.nativeEvent.text);
760 },
761 },
762 unstable_headerRightItems: () => nativeHeaderItems,
763 }}
764 />
765 <View className="flex-1">
766 <SwipeableScrollGateProvider enabled={swipeEnabled}>
767 <GestureDetector gesture={sidebarScrollGesture}>
768 <LegendList
769 data={listItems}
770 drawDistance={500}
771 estimatedItemSize={64}
772 extraData={listExtraData}
773 getItemType={(item) => item.type}
774 itemsAreEqual={sidebarItemsAreEqual}
775 keyExtractor={(item) => item.key}
776 renderItem={renderListItem}
777 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
778 contentInsetAdjustmentBehavior={
779 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
780 }
781 contentContainerStyle={[
782 styles.threadListContent,
783 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
784 {
785 paddingBottom: Math.max(insets.bottom, 16) + 16,
786 paddingTop: 6,
787 },
788 ]}
789 keyboardDismissMode="on-drag"
790 keyboardShouldPersistTaps="handled"
791 {...scrollGateHandlers}
792 recycleItems
793 scrollEventThrottle={16}
794 showsVerticalScrollIndicator={false}
795 style={styles.threadList}
796 ListEmptyComponent={listEmpty}
797 />
798 </GestureDetector>
799 </SwipeableScrollGateProvider>
800 </View>
801 </>
802 );
803 }
804
805 return (
806 <View
807 testID="thread-navigation-sidebar"
808 className={
809 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-r border-border bg-drawer"
810 }
811 // Android fills its pane, which animates its width while a hinge resizes the split.
812 style={Platform.OS === "android" ? undefined : { width: props.width }}
813 >
814 <View
815 className="flex-1"
816 style={
817 Platform.OS === "android"
818 ? {
819 marginTop: stickyHeaderHeight,
820 marginHorizontal: 4,
821 paddingBottom: insets.bottom,
822 backgroundColor: drawerColor,
823 borderTopLeftRadius: 28,
824 borderTopRightRadius: 28,
825 overflow: "hidden",
826 }
827 : { paddingBottom: insets.bottom }
828 }
829 >
830 {Platform.OS === "android" && listItems.length === 0 ? (
831 <View className="flex-1 items-center justify-center">{listEmpty}</View>
832 ) : (
833 <SwipeableScrollGateProvider enabled={swipeEnabled}>
834 <GestureDetector gesture={sidebarScrollGesture}>
835 <LegendList
836 data={listItems}
837 drawDistance={500}
838 estimatedItemSize={64}
839 extraData={listExtraData}
840 getItemType={(item) => item.type}
841 itemsAreEqual={sidebarItemsAreEqual}
842 keyExtractor={(item) => item.key}
843 renderItem={renderListItem}
844 contentContainerStyle={[
845 styles.threadListContent,
846 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
847 {
848 paddingBottom:
849 Platform.OS === "android"
850 ? Math.max(insets.bottom, 16) + fabClearance - insets.bottom
851 : 16 + insets.bottom,
852 paddingTop: Platform.OS === "android" ? 6 : topListInset,
853 },
854 ]}
855 keyboardDismissMode="on-drag"
856 keyboardShouldPersistTaps="handled"
857 {...scrollGateHandlers}
858 recycleItems
859 scrollEventThrottle={16}
860 showsVerticalScrollIndicator={false}
861 style={styles.threadList}
862 ListEmptyComponent={listEmpty}
863 />
864 </GestureDetector>
865 </SwipeableScrollGateProvider>
866 )}
867 </View>
868
869 {Platform.OS === "android" ? (
870 <ThreadListToolbar
871 sidebar
872 onLayout={handleStickyHeaderLayout}
873 searchQuery={props.searchQuery}
874 onSearchQueryChange={props.onSearchQueryChange}
875 filterActions={listMenuActions}
876 filterCustomized={filterCustomized}
877 onFilterAction={handleListMenuAction}
878 onOpenEnvironments={props.onOpenEnvironmentSettings}
879 onRequestVisibility={props.onRequestVisibility}
880 />
881 ) : (
882 <View
883 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
884 collapsable={false}
885 onLayout={handleStickyHeaderLayout}
886 pointerEvents="auto"
887 style={{ paddingTop: insets.top }}
888 >
889 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
890 <WorkspaceConnectionTitle
891 grow
892 onPress={props.onOpenEnvironmentSettings}
893 size="pageTitle"
894 brand={
895 <View className="h-11 flex-1 justify-center">
896 <CompactBrandTitle allowFontScaling={false} />
897 </View>
898 }
899 />
900 <View className="flex-row items-center gap-2.5">
901 <Menu actions={listMenuActions} onPressAction={handleListMenuAction}>
902 <SidebarFilterButton accessibilityLabel="Filter threads" icon={filterIcon} />
903 </Menu>
904 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
905 </View>
906 </View>
907
908 <View className="mx-4 mt-[9px] h-[38px] flex-row items-center gap-1.5 rounded-xl bg-sidebar-search pr-2.5 pl-[11px]">
909 <SymbolView
910 name="magnifyingglass"
911 size={15}
912 tintColorClassName="accent-drawer-foreground-muted"
913 type="monochrome"
914 />
915 <TextInput
916 ref={searchInputRef}
917 accessibilityLabel="Search threads"
918 autoCapitalize="none"
919 autoCorrect={false}
920 clearButtonMode="while-editing"
921 onChangeText={props.onSearchQueryChange}
922 placeholder="Search"
923 placeholderTextColorClassName="accent-placeholder"
924 selectionColorClassName={undefined}
925 cursorColorClassName={undefined}
926 selectionHandleColorClassName={undefined}
927 returnKeyType="search"
928 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-drawer-foreground"
929 value={props.searchQuery}
930 />
931 </View>
932 </View>
933 )}
934 </View>
935 );
936}
937
938const styles = StyleSheet.create({
939 threadList: {
940 flex: 1,
941 },
942 threadListContent: {
943 paddingHorizontal: 8,
944 },
945});