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

ThreadNavigationSidebar.tsx

932 lines36.0 KB

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