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 // oxlint-disable-next-line react/set-state-in-effect -- Refreshes the minute clock when the minute interval starts.
278 setNow(new Date().toISOString());
279 const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
280 return () => clearInterval(id);
281 }, []);
282 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
283 const {
284 providersByEnvironmentId,
285 machineByEnvironmentId,
286 settlementEnvironmentIds,
287 snoozeEnvironmentIds,
288 pinningEnvironmentIds,
289 autoSettleOptOutEnvironmentIds,
290 pinReorderEnvironmentIds,
291 activeReorderEnvironmentIds,
292 titleRegenerationEnvironmentIds,
293 } = listEnvironments;
294 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
295 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
296 const {
297 layout: threadListV2Layout,
298 items: threadListV2Items,
299 contentOnlyThreadKeys,
300 olderSettledShelf,
301 } = useThreadListV2({
302 threads,
303 pendingTasks,
304 environmentId: options.selectedEnvironmentId,
305 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
306 searchQuery: props.searchQuery,
307 searchMatches: threadSearchMatchByKey,
308 settlementEnvironmentIds,
309 snoozeEnvironmentIds,
310 pinReorderEnvironmentIds,
311 activeReorderEnvironmentIds,
312 queuedThreadKeys,
313 settledLimit: settledVisibleCount,
314 now,
315 pendingOrder,
316 shelfPreferencesLoaded,
317 workingShelfEnabled,
318 workingShelfExpanded,
319 snoozedShelfExpanded,
320 settledShelfExpanded,
321 selectedThreadKey: props.selectedThreadKey ?? null,
322 });
323 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
324 useEffect(() => {
325 if (nextSnoozeWakeAt === null) return;
326 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
327 if (Number.isNaN(wakeAtMs)) return;
328 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
329 const id = setTimeout(() => {
330 setNow(new Date().toISOString());
331 bumpSnoozeWakeTick((tick) => tick + 1);
332 }, delayMs);
333 return () => clearTimeout(id);
334 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- snoozeWakeTick re-arms clamped timers even when the wake date exceeds 32-bit setTimeout and stays unchanged.
335 }, [nextSnoozeWakeAt, snoozeWakeTick]);
336 const listItems: readonly SidebarListItem[] =
337 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0
338 ? [
339 ...threadListV2Items,
340 {
341 type: "v2-show-more",
342 key: "v2-show-more",
343 hiddenCount: threadListV2Layout.hiddenSettledCount,
344 ...(olderSettledShelf.loading
345 ? { state: "loading" as const }
346 : olderSettledShelf.failed
347 ? { state: "failed" as const }
348 : {}),
349 },
350 ]
351 : threadListV2Items;
352 const listMenuActions = [
353 {
354 id: "environment",
355 title: "Environment",
356 subactions: [
357 {
358 id: "environment:all",
359 title: "All environments",
360 subtitle: "Show threads from every environment",
361 state: options.selectedEnvironmentId === null ? "on" : "off",
362 },
363 ...environments.map((environment) => ({
364 id: `environment:${environment.environmentId}`,
365 title: environment.label,
366 state:
367 options.selectedEnvironmentId === environment.environmentId
368 ? ("on" as const)
369 : ("off" as const),
370 })),
371 ],
372 },
373 ...(projectFilterOptions.length === 0
374 ? []
375 : ([
376 {
377 id: "project",
378 title: "Project",
379 subactions: [
380 {
381 id: "project:all",
382 title: "All projects",
383 subtitle: "Show threads from every project",
384 state: selectedProjectKey === null ? "on" : "off",
385 },
386 ...projectFilterOptions.map((project) => ({
387 id: `project:${project.key}`,
388 title: project.label,
389 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
390 })),
391 ],
392 },
393 ] satisfies MenuAction[])),
394 ] satisfies MenuAction[];
395 const handleListMenuAction = ({
396 nativeEvent,
397 }: {
398 readonly nativeEvent: { readonly event: string };
399 }) => {
400 const event = nativeEvent.event;
401 if (event === "environment:all") {
402 setSelectedEnvironmentId(null);
403 return;
404 }
405 if (event.startsWith("environment:")) {
406 const environment = environments.find(
407 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
408 );
409 if (environment) setSelectedEnvironmentId(environment.environmentId);
410 return;
411 }
412 if (event === "project:all") {
413 setSelectedProjectKey(null);
414 return;
415 }
416 if (event.startsWith("project:")) {
417 const projectKey = event.slice("project:".length);
418 if (projectFilterOptions.some((project) => project.key === projectKey)) {
419 setSelectedProjectKey(projectKey);
420 }
421 return;
422 }
423 };
424
425 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
426 const { height, paddingTop, paddingBottom } = useToolbarLayout();
427 const stickyHeaderHeight =
428 measuredHeaderHeight ??
429 (Platform.OS === "android"
430 ? paddingTop + height + paddingBottom
431 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
432 const topListInset = stickyHeaderHeight + 6;
433 const handleStickyHeaderLayout = (event: LayoutChangeEvent) => {
434 const nextHeight = event.nativeEvent.layout.height;
435 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
436 };
437 const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
438 if (openSwipeableRef.current !== methods) {
439 openSwipeableRef.current?.close();
440 openSwipeableRef.current = methods;
441 }
442 };
443 const handleSwipeableClose = (methods: SwipeableMethods) => {
444 if (openSwipeableRef.current === methods) {
445 openSwipeableRef.current = null;
446 }
447 };
448 // Destructure callback props; capturing all props would invalidate these row-closing handlers on unrelated changes.
449 const { onSelectThread, onOpenThreadPullRequests } = props;
450 // A row listed for a message match opens the thread at that message, by
451 // tap or by shortcut.
452 const handleSelectThread = (thread: EnvironmentThreadShell) => {
453 const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
454 const messageId = contentOnlyThreadKeys.has(key)
455 ? threadSearchMatchByKey.get(key)?.messageId
456 : undefined;
457 if (messageId) {
458 requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
459 }
460 onSelectThread(thread);
461 openSwipeableRef.current?.close();
462 };
463 const handleOpenThreadPullRequests = (
464 thread: EnvironmentThreadShell,
465 pr: ThreadPrPresentation,
466 ) => {
467 onOpenThreadPullRequests(thread, pr);
468 openSwipeableRef.current?.close();
469 };
470 const handleScrollBeginDrag = () => {
471 openSwipeableRef.current?.close();
472 };
473 const onFabScroll = useFabScroll();
474 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
475 onScroll: onFabScroll,
476 onScrollBeginDrag: handleScrollBeginDrag,
477 });
478 // Recycle equality needs project/search data for titles and favicons; keep the minute clock on items to limit updates.
479 const listExtraData = {
480 activeNewTask,
481 selectedThreadKey: props.selectedThreadKey ?? "",
482 projectByKey,
483 projectTitleByProjectKey,
484 savedConnectionsById,
485 listEnvironments,
486 threadSearchMatchByKey,
487 workingShelfEnabled,
488 };
489 useThreadJumpShortcuts(listItems, handleSelectThread);
490 const sidebarItemsAreEqual = (previous: SidebarListItem, item: SidebarListItem): boolean => {
491 if (isThreadListV2ListItem(previous) && isThreadListV2ListItem(item)) {
492 return threadListV2ListItemsAreEqual(previous, item);
493 }
494 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
495 return previous.hiddenCount === item.hiddenCount && previous.state === item.state;
496 }
497 return false;
498 };
499 const focusSearch = () => {
500 if (Platform.OS === "android") return false;
501 const focus = () => {
502 if (props.nativeChrome) {
503 searchBarRef.current?.focus();
504 return;
505 }
506 searchInputRef.current?.focus();
507 };
508 if (!props.visible) {
509 props.onRequestVisibility();
510 setTimeout(focus, 240);
511 } else {
512 focus();
513 }
514 return true;
515 };
516 useHardwareKeyboardCommand("focusSearch", focusSearch);
517 const renderListItem = ({ item }: { readonly item: SidebarListItem }) => {
518 switch (item.type) {
519 case "v2-pending": {
520 const pendingScopeKey = scopedProjectKey(
521 item.pendingTask.environmentId,
522 item.pendingTask.projectId,
523 );
524 return (
525 <ThreadListV2PendingRow
526 pendingTask={item.pendingTask}
527 selected={
528 activeNewTask?.pendingKey === item.pendingTask.key ||
529 (item.pendingTask.kind === "pending" &&
530 scopedThreadKey(
531 item.pendingTask.environmentId,
532 item.pendingTask.message.threadId,
533 ) === props.selectedThreadKey)
534 }
535 project={projectByKey.get(pendingScopeKey) ?? null}
536 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
537 environmentLabel={
538 Object.keys(savedConnectionsById).length > 1
539 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
540 : null
541 }
542 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
543 pane="sidebar"
544 showPendingDivider={item.showPendingDivider}
545 onSelectPendingTask={props.onOpenPendingTask}
546 onDeletePendingTask={confirmDeletePendingTask}
547 fullSwipeWidth={props.width - 20}
548 onSwipeableClose={handleSwipeableClose}
549 onSwipeableWillOpen={handleSwipeableWillOpen}
550 simultaneousSwipeGesture={sidebarScrollGesture}
551 />
552 );
553 }
554 case "v2-thread": {
555 const thread = item.item.thread;
556 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
557 return (
558 <ThreadListV2Row
559 onNewThreadOnBranch={props.onNewThreadOnBranch}
560 thread={thread}
561 variant={item.item.variant}
562 hasQueuedMessages={item.hasQueuedMessages}
563 snoozed={item.item.snoozed}
564 pinned={item.item.pinned}
565 wokeAt={item.item.wokeAt}
566 snoozePresetMinute={item.snoozePresetMinute ?? ""}
567 snoozeWakeLabelText={item.snoozeWakeLabelText}
568 timeLabel={item.timeLabel}
569 project={projectByKey.get(scopeKey) ?? null}
570 projectTitle={projectTitleByProjectKey.get(scopeKey)}
571 providerInstance={resolveProviderInstance(thread)}
572 providers={providersByEnvironmentId.get(thread.environmentId)}
573 environmentLabel={
574 Object.keys(savedConnectionsById).length > 1
575 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
576 : null
577 }
578 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
579 searchMatch={
580 // Only rows listed for their messages show one and open at it.
581 contentOnlyThreadKeys.has(
582 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
583 )
584 ? threadSearchMatchByKey.get(
585 threadSearchMatchKey({
586 environmentId: thread.environmentId,
587 threadId: thread.id,
588 }),
589 )
590 : undefined
591 }
592 searchQuery={threadSearch.query}
593 pane="sidebar"
594 selected={
595 !activeNewTask &&
596 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
597 }
598 fullSwipeWidth={props.width - 20}
599 onSelectThread={handleSelectThread}
600 onOpenThreadPullRequests={handleOpenThreadPullRequests}
601 onDeleteThread={confirmDeleteThread}
602 onArchiveThread={archiveThread}
603 onRenameThread={renameThread}
604 onRegenerateThreadTitle={regenerateThreadTitle}
605 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
606 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
607 onSettleThread={settleThread}
608 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
609 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
610 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
611 reorderSupported={
612 item.item.pinned
613 ? pinReorderEnvironmentIds.has(thread.environmentId)
614 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
615 }
616 canMoveUp={item.canMoveUp}
617 canMoveDown={item.canMoveDown}
618 onSnoozeThread={snoozeThread}
619 onUnsnoozeThread={unsnoozeThread}
620 onUnsettleThread={unsettleThread}
621 onPinThread={pinThread}
622 onUnpinThread={unpinThread}
623 onSetThreadAutoSettle={setThreadAutoSettle}
624 onMoveThread={moveThread}
625 onSwipeableClose={handleSwipeableClose}
626 onSwipeableWillOpen={handleSwipeableWillOpen}
627 simultaneousSwipeGesture={sidebarScrollGesture}
628 />
629 );
630 }
631 case "v2-working-shelf":
632 return (
633 <ThreadListV2WorkingShelfHeader
634 count={item.count}
635 disabled={item.disabled}
636 expanded={item.expanded}
637 onToggle={toggleWorkingShelf}
638 pane="sidebar"
639 />
640 );
641 case "v2-snoozed-shelf":
642 return (
643 <ThreadListV2SnoozedShelfHeader
644 count={item.count}
645 disabled={item.disabled}
646 expanded={item.expanded}
647 onToggle={toggleSnoozedShelf}
648 pane="sidebar"
649 />
650 );
651 case "v2-settled-shelf":
652 return (
653 <ThreadListV2SettledShelfHeader
654 count={item.count}
655 disabled={item.disabled}
656 expanded={item.expanded}
657 onToggle={toggleSettledShelf}
658 pane="sidebar"
659 />
660 );
661 case "v2-show-more":
662 return (
663 <ThreadListV2ShowMoreRow
664 pane="sidebar"
665 hiddenCount={item.hiddenCount}
666 {...(item.state === undefined ? {} : { state: item.state })}
667 onPress={() => {
668 olderSettledShelf.retry();
669 showMoreSettled();
670 }}
671 />
672 );
673 }
674 };
675 const filterCustomized = options.selectedEnvironmentId !== null || selectedProjectKey !== null;
676 const filterIcon = filterCustomized
677 ? "line.3.horizontal.decrease.circle.fill"
678 : "line.3.horizontal.decrease.circle";
679 const filterMenu = buildHomeListFilterMenu({
680 environments,
681 projects: projectFilterOptions,
682 selectedEnvironmentId: options.selectedEnvironmentId,
683 selectedProjectKey,
684 onEnvironmentChange: setSelectedEnvironmentId,
685 onProjectChange: setSelectedProjectKey,
686 });
687 const nativeHeaderItems = createSidebarHeaderItems({
688 filterIcon,
689 filterMenu,
690 onOpenSettings: props.onOpenSettings,
691 });
692 const listEmpty = (
693 <Text
694 className={
695 Platform.OS === "android"
696 ? "px-4 py-4 text-center text-sm text-drawer-foreground-muted"
697 : "px-2 py-4 text-sm text-drawer-foreground-muted"
698 }
699 >
700 {catalogState.isLoadingConnections
701 ? "Loading threads…"
702 : Platform.OS === "android" && !catalogState.hasConnections
703 ? "No environments connected"
704 : props.searchQuery.trim().length > 0
705 ? threadSearch.isPending
706 ? "Searching thread messages…"
707 : "No matching threads"
708 : selectedProjectScope !== null
709 ? `No threads in ${selectedProjectScope.title}`
710 : "No threads yet"}
711 </Text>
712 );
713
714 if (props.nativeChrome) {
715 return (
716 <>
717 <NativeStackScreenOptions
718 optionsVersion={[nativeHeaderItems, props.width]}
719 options={{
720 ...getConnectionAwareBrandHeaderOptions({
721 headerWidth: props.width,
722 trailingItemCount: nativeHeaderItems.length,
723 onOpenEnvironments: props.onOpenEnvironmentSettings,
724 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
725 }),
726 headerSearchBarOptions: {
727 ref: searchBarRef,
728 autoCapitalize: "none",
729 hideNavigationBar: false,
730 hideWhenScrolling: false,
731 obscureBackground: false,
732 placeholder: "Search",
733 placement: "stacked",
734 onCancelButtonPress: () => {
735 props.onSearchQueryChange("");
736 },
737 onChangeText: (event) => {
738 props.onSearchQueryChange(event.nativeEvent.text);
739 },
740 },
741 unstable_headerRightItems: () => nativeHeaderItems,
742 }}
743 />
744 <View className="flex-1">
745 <SwipeableScrollGateProvider enabled={swipeEnabled}>
746 <GestureDetector gesture={sidebarScrollGesture}>
747 <AnimatedLegendList
748 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
749 itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}
750 data={listItems}
751 drawDistance={500}
752 estimatedItemSize={64}
753 extraData={listExtraData}
754 getItemType={(item) => item.type}
755 itemsAreEqual={sidebarItemsAreEqual}
756 keyExtractor={(item) => item.key}
757 renderItem={renderListItem}
758 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
759 contentInsetAdjustmentBehavior={
760 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
761 }
762 contentContainerStyle={[
763 styles.threadListContent,
764 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
765 {
766 paddingBottom: Math.max(insets.bottom, 16) + 16,
767 paddingTop: 6,
768 },
769 ]}
770 keyboardDismissMode="on-drag"
771 keyboardShouldPersistTaps="handled"
772 {...scrollGateHandlers}
773 recycleItems
774 scrollEventThrottle={16}
775 showsVerticalScrollIndicator={false}
776 style={styles.threadList}
777 ListEmptyComponent={listEmpty}
778 />
779 </GestureDetector>
780 </SwipeableScrollGateProvider>
781 <ThreadUndoNotice visible={props.visible} />
782 </View>
783 </>
784 );
785 }
786
787 return (
788 <View
789 testID="thread-navigation-sidebar"
790 className={
791 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-r border-border bg-drawer"
792 }
793 // Android fills its pane, which animates its width while a hinge resizes the split.
794 style={Platform.OS === "android" ? undefined : { width: props.width }}
795 >
796 <View
797 className="flex-1"
798 style={
799 Platform.OS === "android"
800 ? {
801 marginTop: stickyHeaderHeight,
802 marginHorizontal: 4,
803 paddingBottom: insets.bottom,
804 backgroundColor: drawerColor,
805 borderTopLeftRadius: 28,
806 borderTopRightRadius: 28,
807 overflow: "hidden",
808 }
809 : { paddingBottom: insets.bottom }
810 }
811 >
812 {Platform.OS === "android" && listItems.length === 0 ? (
813 <View className="flex-1 items-center justify-center">{listEmpty}</View>
814 ) : (
815 <SwipeableScrollGateProvider enabled={swipeEnabled}>
816 <GestureDetector gesture={sidebarScrollGesture}>
817 {/* 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. */}
818 <AnimatedLegendList
819 itemLayoutAnimation={THREAD_SIDEBAR_ROW_LAYOUT}
820 data={listItems}
821 drawDistance={500}
822 estimatedItemSize={64}
823 extraData={listExtraData}
824 getItemType={(item) => item.type}
825 itemsAreEqual={sidebarItemsAreEqual}
826 keyExtractor={(item) => item.key}
827 renderItem={renderListItem}
828 contentContainerStyle={[
829 styles.threadListContent,
830 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
831 {
832 paddingBottom:
833 Platform.OS === "android"
834 ? Math.max(insets.bottom, 16) + fabClearance - insets.bottom
835 : 16 + insets.bottom,
836 paddingTop: Platform.OS === "android" ? 6 : topListInset,
837 },
838 ]}
839 keyboardDismissMode="on-drag"
840 keyboardShouldPersistTaps="handled"
841 {...scrollGateHandlers}
842 recycleItems
843 scrollEventThrottle={16}
844 showsVerticalScrollIndicator={false}
845 style={styles.threadList}
846 ListEmptyComponent={listEmpty}
847 />
848 </GestureDetector>
849 </SwipeableScrollGateProvider>
850 )}
851 </View>
852
853 {Platform.OS === "android" ? (
854 <ThreadListToolbar
855 sidebar
856 onLayout={handleStickyHeaderLayout}
857 searchQuery={props.searchQuery}
858 onSearchQueryChange={props.onSearchQueryChange}
859 filterActions={listMenuActions}
860 filterCustomized={filterCustomized}
861 onFilterAction={handleListMenuAction}
862 onOpenEnvironments={props.onOpenEnvironmentSettings}
863 onRequestVisibility={props.onRequestVisibility}
864 />
865 ) : (
866 <View
867 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
868 collapsable={false}
869 onLayout={handleStickyHeaderLayout}
870 pointerEvents="auto"
871 style={{ paddingTop: insets.top }}
872 >
873 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
874 <WorkspaceConnectionTitle
875 grow
876 onPress={props.onOpenEnvironmentSettings}
877 size="pageTitle"
878 brand={
879 <View className="h-11 flex-1 justify-center">
880 <CompactBrandTitle allowFontScaling={false} />
881 </View>
882 }
883 />
884 <View className="flex-row items-center gap-2.5">
885 <Menu actions={listMenuActions} onPressAction={handleListMenuAction}>
886 <SidebarFilterButton accessibilityLabel="Filter threads" icon={filterIcon} />
887 </Menu>
888 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
889 </View>
890 </View>
891
892 <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]">
893 <SymbolView
894 name="magnifyingglass"
895 size={15}
896 tintColorClassName="accent-drawer-foreground-muted"
897 type="monochrome"
898 />
899 <TextInput
900 ref={searchInputRef}
901 accessibilityLabel="Search threads"
902 autoCapitalize="none"
903 autoCorrect={false}
904 clearButtonMode="while-editing"
905 onChangeText={props.onSearchQueryChange}
906 placeholder="Search"
907 placeholderTextColorClassName="accent-placeholder"
908 selectionColorClassName={undefined}
909 cursorColorClassName={undefined}
910 selectionHandleColorClassName={undefined}
911 returnKeyType="search"
912 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-drawer-foreground"
913 value={props.searchQuery}
914 />
915 </View>
916 </View>
917 )}
918 <ThreadUndoNotice visible={props.visible} />
919 </View>
920 );
921}
922
923const styles = StyleSheet.create({
924 threadList: {
925 flex: 1,
926 },
927 threadListContent: {
928 paddingHorizontal: 8,
929 },
930});