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

ThreadNavigationSidebar.tsx

949 lines36.8 KB

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