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

ThreadNavigationSidebar.tsx

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