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