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