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