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

ThreadNavigationSidebar.tsx

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