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