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