Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadNavigationSidebar.tsx

929 lines36.0 KB

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;
110​
111export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
112 if (Platform.OS !== "ios") {
113 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
114 }
115 return <NativeSidebarContainer {...props} />;
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 );
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 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 );
921​
922const styles = StyleSheet.create({
923 threadList: {
924 flex: 1,
925 },
926 threadListContent: {
927 paddingHorizontal: 8,
928 },
929});