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

ThreadNavigationSidebar.tsx

911 lines35.4 KB

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