Open History to see the last commit
1import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
2import { createThreadMovePlanner } from "./threadOrder";
3import type {
4 EnvironmentProject,
5 EnvironmentThreadShell,
6} from "@t3tools/client-runtime/state/shell";
7import {
8 threadSearchMatchKey,
9 type EnvironmentThreadSearchMatch,
10} from "@t3tools/client-runtime/state/thread-search";
11import { LegendList } from "@legendapp/list/react-native";
12import type { MenuAction } from "@react-native-menu/menu";
13import { useAtomValue } from "@effect/atom-react";
14import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";
15import { useCallback, useEffect, useMemo, useRef, useState } from "react";
16import type { LayoutChangeEvent } from "react-native";
17import { Platform, StyleSheet, TextInput, View } from "react-native";
18import { Gesture, GestureDetector } from "react-native-gesture-handler";
19import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21import type { SearchBarCommands } from "react-native-screens";
22
23import { AppText as Text } from "../../components/AppText";
24import { CompactBrandTitle } from "../../components/CompactBrandTitle";
25import { ControlPillMenu } from "../../components/ControlPill";
26import { SymbolView } from "../../components/AppSymbol";
27import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
28import { NativeStackScreenOptions } from "../../native/StackHeader";
29import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
30import { useProjects, useThreadShells } from "../../state/entities";
31import { useThreadSearch } from "../../state/queries";
32import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
33import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
34import { usePendingThreadOrder } from "../../state/thread-order";
35import { environmentServerConfigsAtom } from "../../state/server";
36import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
37import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
38import { useWorkspaceState } from "../../state/workspace";
39import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
40import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
41import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
42import {
43 hasCustomHomeListOptions,
44 PROJECT_SORT_OPTIONS,
45 THREAD_SORT_OPTIONS,
46 useHomeListOptions,
47} from "../home/home-list-options";
48import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
49import {
50 buildHomeListLayout,
51 DEFAULT_GROUP_DISPLAY_STATE,
52 EMPTY_HOME_LIST_LAYOUT,
53 homeListItemsAreEqual,
54 nextGroupDisplayState,
55 type HomeGroupDisplayAction,
56 type HomeGroupDisplayState,
57 type HomeListItem,
58} from "../home/homeListItems";
59import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThreadList";
60import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
61import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
62import { useThreadListActions } from "../home/useThreadListActions";
63import {
64 getConnectionAwareBrandHeaderOptions,
65 WorkspaceConnectionTitle,
66} from "../home/WorkspaceConnectionTitle";
67import { SidebarHeaderActions } from "./sidebar-header-actions";
68import { MaterialThreadListToolbar } from "../home/MaterialThreadListToolbar";
69import { useMaterialToolbarHeight } from "../../components/useMaterialToolbarHeight";
70import { useMaterialFabScroll } from "../home/MaterialFabScrollContext";
71import { SidebarFilterButton } from "./sidebar-filter-button";
72import { createSidebarHeaderItems } from "./sidebar-native-header-items";
73import { SidebarNavigationShell } from "./sidebar-navigation-shell";
74import {
75 PendingTaskListRow,
76 ThreadListGroupHeader,
77 ThreadListRow,
78 ThreadListShowMoreRow,
79} from "./thread-list-items";
80import {
81 ThreadListV2PendingRow,
82 ThreadListV2Row,
83 ThreadListV2SettledShelfHeader,
84 ThreadListV2ShowMoreRow,
85 ThreadListV2SnoozedShelfHeader,
86} from "./thread-list-v2-items";
87import { resolveThreadProviderInstance } from "./thread-provider-instance";
88import {
89 buildThreadListV2Items,
90 getThreadListV2OrderedSection,
91 buildThreadListV2ListItems,
92 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
93 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
94 type ThreadListV2ListItem,
95} from "./threadListV2";
96
97/** The sidebar list serves both lists: v1 grouped items or, when the Thread
98 List v2 beta is on, flat v2 rows with queued tasks spliced in, and a settled
99 "Show more" pager. */
100type SidebarListItem =
101 | HomeListItem
102 | ThreadListV2ListItem
103 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
104
105const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
106
107interface ThreadNavigationSidebarProps {
108 readonly width: number;
109 readonly visible: boolean;
110 readonly selectedThreadKey: string | null;
111 readonly onOpenSettings: () => void;
112 readonly onOpenEnvironmentSettings: () => void;
113 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
114 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
115 readonly onSearchQueryChange: (query: string) => void;
116 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
117 readonly onRequestVisibility: () => void;
118 readonly searchQuery: string;
119}
120
121/**
122 * iPad/large-width sidebar column.
123 *
124 * On iOS the pane is hosted inside its own navigation-inert single-screen
125 * native stack (SidebarNavigationShell) so the header is a real
126 * UINavigationBar: large title, native bar-button items, and a
127 * UISearchController search field — the same chrome a UISplitViewController
128 * column gets. Other platforms keep the custom header chrome.
129 */
130export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
131 if (Platform.OS !== "ios") {
132 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
133 }
134 return <NativeSidebarContainer {...props} />;
135}
136
137function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
138 return (
139 <View
140 testID="thread-navigation-sidebar"
141 className="flex-1 border-border bg-drawer"
142 style={{ borderRightWidth: StyleSheet.hairlineWidth, width: props.width }}
143 >
144 <SidebarNavigationShell>
145 <ThreadNavigationSidebarPane {...props} nativeChrome />
146 </SidebarNavigationShell>
147 </View>
148 );
149}
150
151function ThreadNavigationSidebarPane(
152 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
153) {
154 const { themeVariables: materialTheme } = useAppearancePreferences();
155 const drawerColor = materialTheme["--color-drawer"];
156
157 const insets = useSafeAreaInsets();
158 const projects = useProjects();
159 const threads = useThreadShells();
160 const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
161 const { savedConnectionsById } = useSavedRemoteConnections();
162 const searchInputRef = useRef<TextInput>(null);
163 const searchBarRef = useRef<SearchBarCommands>(null);
164 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
165 const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
166 const {
167 archiveThread,
168 confirmDeleteThread,
169 settleThread,
170 snoozeThread,
171 unsnoozeThread,
172 unsettleThread,
173 pinThread,
174 unpinThread,
175 moveThread,
176 renameThread,
177 regenerateThreadTitle,
178 } = useThreadListActions();
179 const threadListV2Enabled = useThreadListV2Enabled();
180 const pendingTasks = usePendingNewTasks();
181 const queuedThreadKeys = useQueuedThreadKeys();
182 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
183 const environments = useMemo(
184 () =>
185 Object.values(savedConnectionsById)
186 .map((connection) => ({
187 environmentId: connection.environmentId,
188 label: connection.environmentLabel,
189 }))
190 .sort((left, right) => left.label.localeCompare(right.label)),
191 [savedConnectionsById],
192 );
193 const availableEnvironmentIds = useMemo(
194 () => new Set(environments.map((environment) => environment.environmentId)),
195 [environments],
196 );
197 const { options, setSelectedEnvironmentId, setProjectSortOrder, setThreadSortOrder } =
198 useHomeListOptions(availableEnvironmentIds);
199 const searchEnvironmentIds = useMemo(
200 () =>
201 options.selectedEnvironmentId === null
202 ? workspaceEnvironments
203 .filter((environment) => environment.connectionState === "connected")
204 .map((environment) => environment.environmentId)
205 : workspaceEnvironments.some(
206 (environment) =>
207 environment.environmentId === options.selectedEnvironmentId &&
208 environment.connectionState === "connected",
209 )
210 ? [options.selectedEnvironmentId]
211 : [],
212 [options.selectedEnvironmentId, workspaceEnvironments],
213 );
214 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
215 const threadSearchMatchByKey = useMemo(() => {
216 const matches = new Map<string, EnvironmentThreadSearchMatch>();
217 for (const match of threadSearch.matches) {
218 if (match.source === "user" || match.source === "assistant") {
219 matches.set(threadSearchMatchKey(match), match);
220 }
221 }
222 return matches;
223 }, [threadSearch.matches]);
224 const matchedThreadKeys = useMemo(
225 () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
226 [threadSearch.matches],
227 );
228 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
229 const projectScopes = useMemo(
230 () =>
231 buildHomeProjectScopes({
232 projects,
233 environmentId: options.selectedEnvironmentId,
234 projectGroupingMode: options.projectGroupingMode,
235 }),
236 [options.projectGroupingMode, options.selectedEnvironmentId, projects],
237 );
238 const projectFilterOptions = useMemo(
239 () =>
240 projectScopes.map((scope) => ({
241 key: scope.key,
242 label: scope.title,
243 })),
244 [projectScopes],
245 );
246 const projectTitleByProjectKey = useMemo(
247 () =>
248 new Map(
249 projectScopes.flatMap((scope) =>
250 scope.projectRefs.map(
251 (projectRef) =>
252 [
253 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
254 scope.title,
255 ] as const,
256 ),
257 ),
258 ),
259 [projectScopes],
260 );
261 const selectedProjectScope = useMemo(
262 () =>
263 selectedProjectKey === null
264 ? null
265 : (projectScopes.find((scope) => scope.key === selectedProjectKey) ?? null),
266 [projectScopes, selectedProjectKey],
267 );
268 useEffect(() => {
269 if (
270 selectedProjectKey !== null &&
271 !projectFilterOptions.some((project) => project.key === selectedProjectKey)
272 ) {
273 setSelectedProjectKey(null);
274 }
275 }, [projectFilterOptions, selectedProjectKey]);
276 const selectedProjectRefs = useMemo(
277 () =>
278 selectedProjectScope === null
279 ? null
280 : new Set(
281 selectedProjectScope.projectRefs.map((projectRef) =>
282 scopedProjectKey(projectRef.environmentId, projectRef.projectId),
283 ),
284 ),
285 [selectedProjectScope],
286 );
287 const scopedProjects = useMemo(
288 () =>
289 threadListV2Enabled
290 ? []
291 : selectedProjectRefs === null
292 ? projects
293 : projects.filter((project) =>
294 selectedProjectRefs.has(scopedProjectKey(project.environmentId, project.id)),
295 ),
296 [threadListV2Enabled, projects, selectedProjectRefs],
297 );
298 const scopedThreads = useMemo(
299 () =>
300 threadListV2Enabled
301 ? []
302 : selectedProjectRefs === null
303 ? threads
304 : threads.filter((thread) =>
305 selectedProjectRefs.has(scopedProjectKey(thread.environmentId, thread.projectId)),
306 ),
307 [threadListV2Enabled, selectedProjectRefs, threads],
308 );
309 const scopedPendingTasks = useMemo(
310 () =>
311 threadListV2Enabled
312 ? []
313 : selectedProjectRefs === null
314 ? pendingTasks
315 : pendingTasks.filter((pendingTask) =>
316 selectedProjectRefs.has(
317 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
318 ),
319 ),
320 [threadListV2Enabled, pendingTasks, selectedProjectRefs],
321 );
322 const groups = useMemo(
323 () =>
324 threadListV2Enabled
325 ? []
326 : buildHomeThreadGroups({
327 projects: scopedProjects,
328 threads: scopedThreads,
329 pendingTasks: scopedPendingTasks,
330 queuedThreadKeys,
331 environmentId: options.selectedEnvironmentId,
332 searchQuery: props.searchQuery,
333 matchedThreadKeys,
334 projectSortOrder: options.projectSortOrder,
335 threadSortOrder: options.threadSortOrder,
336 projectGroupingMode: options.projectGroupingMode,
337 }),
338 [
339 threadListV2Enabled,
340 queuedThreadKeys,
341 matchedThreadKeys,
342 options,
343 props.searchQuery,
344 scopedPendingTasks,
345 scopedProjects,
346 scopedThreads,
347 ],
348 );
349 const [groupDisplayStates, setGroupDisplayStates] = useState<
350 ReadonlyMap<string, HomeGroupDisplayState>
351 >(() => new Map());
352 const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
353 setGroupDisplayStates((previous) => {
354 const next = new Map(previous);
355 next.set(
356 key,
357 nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
358 );
359 return next;
360 });
361 }, []);
362 const hasSearchQuery = props.searchQuery.trim().length > 0;
363 const listLayout = useMemo(
364 () =>
365 threadListV2Enabled
366 ? EMPTY_HOME_LIST_LAYOUT
367 : buildHomeListLayout({
368 groups,
369 displayStates: groupDisplayStates,
370 showAllThreads: hasSearchQuery,
371 }),
372 [threadListV2Enabled, groups, groupDisplayStates, hasSearchQuery],
373 );
374 const projectByKey = useMemo(() => {
375 const map = new Map<string, EnvironmentProject>();
376 for (const project of projects) {
377 map.set(scopedProjectKey(project.environmentId, project.id), project);
378 }
379 return map;
380 }, [projects]);
381
382 // Thread List v2 (beta) support — same model as the compact Home list
383 // (HomeScreen.tsx): flat creation-order card block + settled recency tail.
384 // The settled tail renders in pages; expansion resets when the filter
385 // context changes so environment/search flips never inherit a deep page.
386 const [settledVisibleCount, setSettledVisibleCount] = useState(
387 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
388 );
389 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
390 const lastSettledResetKeyRef = useRef(settledResetKey);
391 if (lastSettledResetKeyRef.current !== settledResetKey) {
392 lastSettledResetKeyRef.current = settledResetKey;
393 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
394 }
395 const showMoreSettled = useCallback(
396 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
397 [],
398 );
399 const {
400 loaded: shelfPreferencesLoaded,
401 settledShelfExpanded,
402 snoozedShelfExpanded,
403 toggleSettledShelf,
404 toggleSnoozedShelf,
405 } = useThreadListV2ShelfPreferences();
406 // The queued-start and snooze helpers need a clock while the pane stays open.
407 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
408 // Snooze wake times are second-precise; a counter bumped exactly at the
409 // next wake boundary re-runs the partition with a fresh clock so a woken
410 // thread reappears immediately instead of on the next minute tick.
411 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
412 useEffect(() => {
413 if (!threadListV2Enabled) return;
414 // Refresh immediately because the mount-time value can be hours old.
415 setNowMinute(new Date().toISOString().slice(0, 16));
416 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
417 return () => clearInterval(id);
418 }, [threadListV2Enabled]);
419 // Threads on servers without the settlement capability never classify as
420 // settled (the user could neither un-settle nor pin them).
421 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
422 const settlementEnvironmentIds = useMemo(() => {
423 const supported = new Set<EnvironmentId>();
424 for (const [environmentId, config] of serverConfigs) {
425 if (config.environment.capabilities.threadSettlement === true) {
426 supported.add(environmentId);
427 }
428 }
429 return supported;
430 }, [serverConfigs]);
431 const snoozeEnvironmentIds = useMemo(() => {
432 const supported = new Set<EnvironmentId>();
433 for (const [environmentId, config] of serverConfigs) {
434 if (config.environment.capabilities.threadSnooze === true) {
435 supported.add(environmentId);
436 }
437 }
438 return supported;
439 }, [serverConfigs]);
440 const pinningEnvironmentIds = useMemo(() => {
441 const supported = new Set<EnvironmentId>();
442 for (const [environmentId, config] of serverConfigs) {
443 if (config.environment.capabilities.threadPinning === true) {
444 supported.add(environmentId);
445 }
446 }
447 return supported;
448 }, [serverConfigs]);
449 const pinReorderEnvironmentIds = useMemo(() => {
450 const supported = new Set<EnvironmentId>();
451 for (const [environmentId, config] of serverConfigs) {
452 if (config.environment.capabilities.threadPinReorder === true) {
453 supported.add(environmentId);
454 }
455 }
456 return supported;
457 }, [serverConfigs]);
458 const activeReorderEnvironmentIds = useMemo(() => {
459 const supported = new Set<EnvironmentId>();
460 for (const [environmentId, config] of serverConfigs) {
461 if (config.environment.capabilities.threadActiveReorder === true) {
462 supported.add(environmentId);
463 }
464 }
465 return supported;
466 }, [serverConfigs]);
467 const titleRegenerationEnvironmentIds = useMemo(() => {
468 const supported = new Set<EnvironmentId>();
469 for (const [environmentId, config] of serverConfigs) {
470 if (config.environment.capabilities.threadTitleRegeneration === true) {
471 supported.add(environmentId);
472 }
473 }
474 return supported;
475 }, [serverConfigs]);
476 const machineByEnvironmentId = useMemo(
477 () =>
478 new Map(
479 [...serverConfigs].map(
480 ([environmentId, config]) =>
481 [environmentId, resolveEnvironmentMachineKind(config)] as const,
482 ),
483 ),
484 [serverConfigs],
485 );
486 const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick);
487 const threadMovePlanners = useMemo(() => {
488 const sectionPlanner = (section: "pinned" | "active") =>
489 createThreadMovePlanner({
490 allThreads: threads,
491 section,
492 reorderableEnvironmentIds: new Set(
493 [...serverConfigs].flatMap(([id, config]) =>
494 (section === "pinned"
495 ? config.environment.capabilities.threadPinReorder
496 : config.environment.capabilities.threadActiveReorder) === true
497 ? [id]
498 : [],
499 ),
500 ),
501 ordered: getThreadListV2OrderedSection({
502 threads,
503 section,
504 pendingOrder,
505 now: new Date().toISOString(),
506 settlementEnvironmentIds,
507 snoozeEnvironmentIds,
508 queuedThreadKeys,
509 }),
510 });
511 return { pinned: sectionPlanner("pinned"), active: sectionPlanner("active") };
512 }, [
513 serverConfigs,
514 threads,
515 pendingOrder,
516 queuedThreadKeys,
517 settlementEnvironmentIds,
518 snoozeEnvironmentIds,
519 nowMinute,
520 snoozeWakeTick,
521 ]);
522 const threadListV2Layout = useMemo(() => {
523 if (!threadListV2Enabled)
524 return {
525 items: [],
526 hiddenSettledCount: 0,
527 snoozedCount: 0,
528 snoozedShelfHeaderIndex: null,
529 settledCount: 0,
530 settledShelfHeaderIndex: null,
531 nextSnoozeWakeAt: null,
532 };
533 return buildThreadListV2Items({
534 pendingOrder,
535 threads: threads.filter((thread) => thread.archivedAt === null),
536 environmentId: options.selectedEnvironmentId,
537 projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
538 searchQuery: props.searchQuery,
539 matchedThreadKeys,
540 settlementEnvironmentIds,
541 snoozeEnvironmentIds,
542 queuedThreadKeys,
543 settledLimit: settledVisibleCount,
544 now: new Date().toISOString(),
545 snoozedShelfExpanded,
546 settledShelfExpanded,
547 selectedThreadKey: props.selectedThreadKey ?? null,
548 });
549 }, [
550 pendingOrder,
551 queuedThreadKeys,
552 nowMinute,
553 snoozeWakeTick,
554 snoozedShelfExpanded,
555 settledShelfExpanded,
556 props.selectedThreadKey,
557 options.selectedEnvironmentId,
558 props.searchQuery,
559 matchedThreadKeys,
560 settledVisibleCount,
561 settlementEnvironmentIds,
562 snoozeEnvironmentIds,
563 threadListV2Enabled,
564 threads,
565 selectedProjectScope,
566 ]);
567 // Re-partition the moment the earliest snooze expires (clamped to the
568 // signed-32-bit setTimeout range; far-future wakes re-arm at the clamp).
569 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
570 useEffect(() => {
571 if (nextSnoozeWakeAt === null) return;
572 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
573 if (Number.isNaN(wakeAtMs)) return;
574 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
575 const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
576 return () => clearTimeout(id);
577 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
578 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
579 // range) the boundary string is identical and the chain would die.
580 }, [nextSnoozeWakeAt, snoozeWakeTick]);
581 const listItems = useMemo<readonly SidebarListItem[]>(() => {
582 if (!threadListV2Enabled) return listLayout.items;
583 // Queued offline tasks are not thread shells, so the v2 item builder
584 // never sees them; the shared splice puts them below the active block
585 // (mirrors the compact Home v2 list) where they stay visible and
586 // deletable while their environment is offline. Same environment scope
587 // and search filter as the list.
588 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
589 const v2PendingTasks = pendingTasks.filter(
590 (pendingTask) =>
591 (options.selectedEnvironmentId === null ||
592 pendingTask.environmentId === options.selectedEnvironmentId) &&
593 (selectedProjectRefs === null ||
594 selectedProjectRefs.has(
595 scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
596 )) &&
597 (v2SearchQuery.length === 0 ||
598 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
599 );
600 const items: SidebarListItem[] = buildThreadListV2ListItems({
601 items: threadListV2Layout.items,
602 pendingTasks: v2PendingTasks,
603 snoozedCount: threadListV2Layout.snoozedCount,
604 snoozedShelfExpanded,
605 snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
606 settledCount: threadListV2Layout.settledCount,
607 settledShelfExpanded,
608 settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
609 snoozeLabelNow: `${nowMinute}:00.000Z`,
610 });
611 if (settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0) {
612 items.push({
613 type: "v2-show-more",
614 key: "v2-show-more",
615 hiddenCount: threadListV2Layout.hiddenSettledCount,
616 });
617 }
618 return items;
619 }, [
620 listLayout.items,
621 nowMinute,
622 options.selectedEnvironmentId,
623 pendingTasks,
624 props.searchQuery,
625 selectedProjectRefs,
626 settledShelfExpanded,
627 snoozedShelfExpanded,
628 threadListV2Enabled,
629 threadListV2Layout,
630 ]);
631 const listMenuActions = useMemo<MenuAction[]>(
632 () => [
633 {
634 id: "environment",
635 title: "Environment",
636 subactions: [
637 {
638 id: "environment:all",
639 title: "All environments",
640 subtitle: "Show threads from every environment",
641 state: options.selectedEnvironmentId === null ? "on" : "off",
642 },
643 ...environments.map((environment) => ({
644 id: `environment:${environment.environmentId}`,
645 title: environment.label,
646 state:
647 options.selectedEnvironmentId === environment.environmentId
648 ? ("on" as const)
649 : ("off" as const),
650 })),
651 ],
652 },
653 ...(projectFilterOptions.length === 0
654 ? []
655 : ([
656 {
657 id: "project",
658 title: "Project",
659 subactions: [
660 {
661 id: "project:all",
662 title: "All projects",
663 subtitle: "Show threads from every project",
664 state: selectedProjectKey === null ? "on" : "off",
665 },
666 ...projectFilterOptions.map((project) => ({
667 id: `project:${project.key}`,
668 title: project.label,
669 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
670 })),
671 ],
672 },
673 ] satisfies MenuAction[])),
674 // v2 lays the list out in fixed creation order — offering sort/group
675 // controls it silently ignores would be a lie. Environment still
676 // scopes the v2 partition, so it stays.
677 ...(threadListV2Enabled
678 ? []
679 : ([
680 {
681 id: "project-sort",
682 title: "Sort projects",
683 subactions: PROJECT_SORT_OPTIONS.map((option) => ({
684 id: `project-sort:${option.value}`,
685 title: option.label,
686 state: options.projectSortOrder === option.value ? "on" : "off",
687 })),
688 },
689 {
690 id: "thread-sort",
691 title: "Sort threads",
692 subactions: THREAD_SORT_OPTIONS.map((option) => ({
693 id: `thread-sort:${option.value}`,
694 title: option.label,
695 state: options.threadSortOrder === option.value ? "on" : "off",
696 })),
697 },
698 ] satisfies MenuAction[])),
699 ],
700 [environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
701 );
702 const handleListMenuAction = useCallback(
703 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
704 const event = nativeEvent.event;
705 if (event === "environment:all") {
706 setSelectedEnvironmentId(null);
707 return;
708 }
709 if (event.startsWith("environment:")) {
710 const environment = environments.find(
711 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
712 );
713 if (environment) setSelectedEnvironmentId(environment.environmentId);
714 return;
715 }
716 if (event === "project:all") {
717 setSelectedProjectKey(null);
718 return;
719 }
720 if (event.startsWith("project:")) {
721 const projectKey = event.slice("project:".length);
722 if (projectFilterOptions.some((project) => project.key === projectKey)) {
723 setSelectedProjectKey(projectKey);
724 }
725 return;
726 }
727 const projectSort = PROJECT_SORT_OPTIONS.find(
728 (option) => `project-sort:${option.value}` === event,
729 );
730 if (projectSort) {
731 setProjectSortOrder(projectSort.value);
732 return;
733 }
734 const threadSort = THREAD_SORT_OPTIONS.find(
735 (option) => `thread-sort:${option.value}` === event,
736 );
737 if (threadSort) {
738 setThreadSortOrder(threadSort.value);
739 return;
740 }
741 },
742 [
743 environments,
744 projectFilterOptions,
745 setProjectSortOrder,
746 setSelectedEnvironmentId,
747 setThreadSortOrder,
748 ],
749 );
750
751 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
752 const materialToolbarHeight = useMaterialToolbarHeight();
753 // The sticky header (title row, search field, optional connection status)
754 // is measured so the list inset always matches its real height — no
755 // hardcoded per-variant constants.
756 const stickyHeaderHeight =
757 measuredHeaderHeight ??
758 (Platform.OS === "android"
759 ? Math.max(insets.top, 12) + materialToolbarHeight + 8
760 : insets.top + SIDEBAR_STICKY_HEADER_HEIGHT);
761 const topListInset = stickyHeaderHeight + 6;
762 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
763 const nextHeight = event.nativeEvent.layout.height;
764 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
765 }, []);
766 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
767 if (openSwipeableRef.current !== methods) {
768 openSwipeableRef.current?.close();
769 openSwipeableRef.current = methods;
770 }
771 }, []);
772 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
773 if (openSwipeableRef.current === methods) {
774 openSwipeableRef.current = null;
775 }
776 }, []);
777 const handleSelectThread = useCallback(
778 (thread: EnvironmentThreadShell) => {
779 props.onSelectThread(thread);
780 openSwipeableRef.current?.close();
781 },
782 [props.onSelectThread],
783 );
784 const handleScrollBeginDrag = useCallback(() => {
785 openSwipeableRef.current?.close();
786 }, []);
787 const onMaterialFabScroll = useMaterialFabScroll();
788 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
789 onScroll: onMaterialFabScroll,
790 onScrollBeginDrag: handleScrollBeginDrag,
791 });
792 // Project shells load after the first rows draw, so the maps they feed have
793 // to bust the recycler's memoization — otherwise a row keeps the blank
794 // favicon and fallback title it was first rendered with.
795 const listExtraData = useMemo(
796 () => ({
797 selectedThreadKey: props.selectedThreadKey ?? "",
798 projectByKey,
799 projectTitleByProjectKey,
800 savedConnectionsById,
801 serverConfigs,
802 snoozePresetMinute: nowMinute,
803 threadSearchMatchByKey,
804 }),
805 [
806 props.selectedThreadKey,
807 projectByKey,
808 projectTitleByProjectKey,
809 savedConnectionsById,
810 serverConfigs,
811 nowMinute,
812 threadSearchMatchByKey,
813 ],
814 );
815 useThreadJumpShortcuts(listItems, handleSelectThread);
816 const sidebarItemsAreEqual = useCallback(
817 (previous: SidebarListItem, item: SidebarListItem): boolean => {
818 if (previous.type === "v2-thread" && item.type === "v2-thread") {
819 return (
820 previous.key === item.key &&
821 previous.item.thread === item.item.thread &&
822 previous.item.variant === item.item.variant &&
823 previous.item.snoozed === item.item.snoozed &&
824 previous.item.pinned === item.item.pinned &&
825 previous.snoozeWakeLabelText === item.snoozeWakeLabelText
826 );
827 }
828 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
829 return previous.hiddenCount === item.hiddenCount;
830 }
831 if (previous.type === "v2-pending" && item.type === "v2-pending") {
832 return (
833 previous.pendingTask === item.pendingTask &&
834 previous.showPendingDivider === item.showPendingDivider
835 );
836 }
837 if (previous.type === "v2-snoozed-shelf" && item.type === "v2-snoozed-shelf") {
838 return previous.count === item.count && previous.expanded === item.expanded;
839 }
840 if (previous.type === "v2-settled-shelf" && item.type === "v2-settled-shelf") {
841 return previous.count === item.count && previous.expanded === item.expanded;
842 }
843 if (
844 previous.type === "v2-thread" ||
845 previous.type === "v2-show-more" ||
846 previous.type === "v2-pending" ||
847 previous.type === "v2-snoozed-shelf" ||
848 previous.type === "v2-settled-shelf" ||
849 item.type === "v2-thread" ||
850 item.type === "v2-show-more" ||
851 item.type === "v2-pending" ||
852 item.type === "v2-snoozed-shelf" ||
853 item.type === "v2-settled-shelf"
854 ) {
855 return false;
856 }
857 return homeListItemsAreEqual(previous, item);
858 },
859 [],
860 );
861 const focusSearch = useCallback(() => {
862 if (Platform.OS === "android") return false;
863 const focus = () => {
864 if (props.nativeChrome) {
865 searchBarRef.current?.focus();
866 return;
867 }
868 searchInputRef.current?.focus();
869 };
870 if (!props.visible) {
871 props.onRequestVisibility();
872 setTimeout(focus, 240);
873 } else {
874 focus();
875 }
876 return true;
877 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
878 useHardwareKeyboardCommand("focusSearch", focusSearch);
879 const renderListItem = useCallback(
880 ({ item }: { readonly item: SidebarListItem }) => {
881 switch (item.type) {
882 case "v2-pending": {
883 const pendingScopeKey = scopedProjectKey(
884 item.pendingTask.environmentId,
885 item.pendingTask.projectId,
886 );
887 return (
888 <ThreadListV2PendingRow
889 pendingTask={item.pendingTask}
890 project={projectByKey.get(pendingScopeKey) ?? null}
891 projectTitle={projectTitleByProjectKey.get(pendingScopeKey)}
892 environmentLabel={
893 Object.keys(savedConnectionsById).length > 1
894 ? (savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null)
895 : null
896 }
897 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
898 pane="sidebar"
899 showPendingDivider={item.showPendingDivider}
900 onSelectPendingTask={openPendingTask}
901 onDeletePendingTask={confirmDeletePendingTask}
902 />
903 );
904 }
905 case "v2-thread": {
906 const thread = item.item.thread;
907 const movePlanner = item.item.pinned
908 ? threadMovePlanners.pinned
909 : threadMovePlanners.active;
910 const movedId = `${thread.environmentId}:${thread.id}`;
911 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
912 return (
913 <ThreadListV2Row
914 onNewThreadOnBranch={props.onNewThreadOnBranch}
915 thread={thread}
916 variant={item.item.variant}
917 hasQueuedMessages={queuedThreadKeys.has(`${thread.environmentId}:${thread.id}`)}
918 snoozed={item.item.snoozed}
919 pinned={item.item.pinned}
920 snoozePresetMinute={nowMinute}
921 snoozeWakeLabelText={item.snoozeWakeLabelText}
922 project={projectByKey.get(scopeKey) ?? null}
923 projectTitle={projectTitleByProjectKey.get(scopeKey)}
924 providerInstance={resolveThreadProviderInstance(serverConfigs, thread)}
925 environmentLabel={
926 Object.keys(savedConnectionsById).length > 1
927 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
928 : null
929 }
930 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
931 searchMatch={threadSearchMatchByKey.get(
932 threadSearchMatchKey({
933 environmentId: thread.environmentId,
934 threadId: thread.id,
935 }),
936 )}
937 searchQuery={props.searchQuery}
938 pane="sidebar"
939 selected={
940 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
941 }
942 fullSwipeWidth={props.width - 20}
943 onSelectThread={handleSelectThread}
944 onDeleteThread={confirmDeleteThread}
945 onArchiveThread={archiveThread}
946 onRenameThread={renameThread}
947 onRegenerateThreadTitle={regenerateThreadTitle}
948 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
949 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
950 onSettleThread={settleThread}
951 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
952 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
953 reorderSupported={
954 item.item.pinned
955 ? pinReorderEnvironmentIds.has(thread.environmentId)
956 : activeReorderEnvironmentIds.has(thread.environmentId)
957 }
958 canMoveUp={pendingOrder === null && movePlanner(movedId, "up") !== null}
959 canMoveDown={pendingOrder === null && movePlanner(movedId, "down") !== null}
960 onSnoozeThread={snoozeThread}
961 onUnsnoozeThread={unsnoozeThread}
962 onUnsettleThread={unsettleThread}
963 onPinThread={pinThread}
964 onUnpinThread={unpinThread}
965 onMoveThread={moveThread}
966 onSwipeableClose={handleSwipeableClose}
967 onSwipeableWillOpen={handleSwipeableWillOpen}
968 simultaneousSwipeGesture={sidebarScrollGesture}
969 />
970 );
971 }
972 case "v2-snoozed-shelf":
973 return (
974 <ThreadListV2SnoozedShelfHeader
975 count={item.count}
976 disabled={!shelfPreferencesLoaded}
977 expanded={item.expanded}
978 onToggle={toggleSnoozedShelf}
979 pane="sidebar"
980 />
981 );
982 case "v2-settled-shelf":
983 return (
984 <ThreadListV2SettledShelfHeader
985 count={item.count}
986 disabled={!shelfPreferencesLoaded}
987 expanded={item.expanded}
988 onToggle={toggleSettledShelf}
989 pane="sidebar"
990 />
991 );
992 case "v2-show-more":
993 return (
994 <ThreadListV2ShowMoreRow
995 pane="sidebar"
996 hiddenCount={item.hiddenCount}
997 onPress={showMoreSettled}
998 />
999 );
1000 case "header":
1001 return (
1002 <ThreadListGroupHeader
1003 variant="sidebar"
1004 collapsed={item.collapsed}
1005 isFirst={item.isFirst}
1006 groupKey={item.group.key}
1007 onGroupAction={updateGroupDisplay}
1008 // Same gating as the compact Home list: aggregated groups have no
1009 // single target project, and pending-project groups hold a
1010 // placeholder shell rather than a real project.
1011 newThreadTarget={item.group.newThreadTarget}
1012 onNewThread={props.onNewThreadInProject}
1013 project={item.group.representative}
1014 threadCount={item.group.threads.length + item.group.pendingTasks.length}
1015 title={item.group.title}
1016 />
1017 );
1018 case "pending-task":
1019 return (
1020 <PendingTaskListRow
1021 variant="sidebar"
1022 pendingTask={item.pendingTask}
1023 environmentLabel={
1024 savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ?? null
1025 }
1026 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
1027 isLast={item.isLast}
1028 onSelectPendingTask={openPendingTask}
1029 onDeletePendingTask={confirmDeletePendingTask}
1030 />
1031 );
1032 case "thread": {
1033 const thread = item.thread;
1034 return (
1035 <ThreadListRow
1036 onNewThreadOnBranch={props.onNewThreadOnBranch}
1037 variant="sidebar"
1038 thread={thread}
1039 hasQueuedMessages={queuedThreadKeys.has(`${thread.environmentId}:${thread.id}`)}
1040 environmentLabel={
1041 savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
1042 }
1043 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
1044 isLast={item.isLast}
1045 searchMatch={threadSearchMatchByKey.get(
1046 threadSearchMatchKey({
1047 environmentId: thread.environmentId,
1048 threadId: thread.id,
1049 }),
1050 )}
1051 searchQuery={props.searchQuery}
1052 selected={
1053 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
1054 }
1055 fullSwipeWidth={props.width - 20}
1056 onArchiveThread={archiveThread}
1057 onDeleteThread={confirmDeleteThread}
1058 onRenameThread={renameThread}
1059 onRegenerateThreadTitle={regenerateThreadTitle}
1060 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
1061 onSelectThread={handleSelectThread}
1062 onSwipeableClose={handleSwipeableClose}
1063 onSwipeableWillOpen={handleSwipeableWillOpen}
1064 simultaneousSwipeGesture={sidebarScrollGesture}
1065 />
1066 );
1067 }
1068 case "show-more":
1069 return (
1070 <ThreadListShowMoreRow
1071 variant="sidebar"
1072 hiddenCount={item.hiddenCount}
1073 canShowLess={item.canShowLess}
1074 groupKey={item.groupKey}
1075 onGroupAction={updateGroupDisplay}
1076 />
1077 );
1078 }
1079 },
1080 [
1081 archiveThread,
1082 activeReorderEnvironmentIds,
1083 threadMovePlanners,
1084 pendingOrder,
1085 queuedThreadKeys,
1086 confirmDeletePendingTask,
1087 confirmDeleteThread,
1088 handleSelectThread,
1089 handleSwipeableClose,
1090 handleSwipeableWillOpen,
1091 machineByEnvironmentId,
1092 moveThread,
1093 openPendingTask,
1094 pinReorderEnvironmentIds,
1095 pinThread,
1096 pinningEnvironmentIds,
1097 projectByKey,
1098 projectTitleByProjectKey,
1099 regenerateThreadTitle,
1100 renameThread,
1101 props.onNewThreadInProject,
1102 props.onNewThreadOnBranch,
1103 props.searchQuery,
1104 props.selectedThreadKey,
1105 props.width,
1106 savedConnectionsById,
1107 serverConfigs,
1108 shelfPreferencesLoaded,
1109 threadSearchMatchByKey,
1110 titleRegenerationEnvironmentIds,
1111 settleThread,
1112 settlementEnvironmentIds,
1113 showMoreSettled,
1114 sidebarScrollGesture,
1115 snoozeEnvironmentIds,
1116 snoozeThread,
1117 nowMinute,
1118 toggleSettledShelf,
1119 toggleSnoozedShelf,
1120 unpinThread,
1121 unsettleThread,
1122 unsnoozeThread,
1123 updateGroupDisplay,
1124 ],
1125 );
1126 // v2 ignores the sort/group options, so only the environment filter can
1127 // light the "customized" state while the beta is on.
1128 const filterCustomized = threadListV2Enabled
1129 ? options.selectedEnvironmentId !== null || selectedProjectKey !== null
1130 : hasCustomHomeListOptions({ ...options, selectedProjectKey });
1131 const filterIcon = filterCustomized
1132 ? "line.3.horizontal.decrease.circle.fill"
1133 : "line.3.horizontal.decrease.circle";
1134 const filterMenu = useMemo(
1135 () =>
1136 buildHomeListFilterMenu({
1137 environments,
1138 projects: projectFilterOptions,
1139 selectedEnvironmentId: options.selectedEnvironmentId,
1140 selectedProjectKey,
1141 projectSortOrder: options.projectSortOrder,
1142 threadSortOrder: options.threadSortOrder,
1143 onEnvironmentChange: setSelectedEnvironmentId,
1144 onProjectChange: setSelectedProjectKey,
1145 onProjectSortOrderChange: setProjectSortOrder,
1146 onThreadSortOrderChange: setThreadSortOrder,
1147 listOrganization: !threadListV2Enabled,
1148 }),
1149 [
1150 environments,
1151 options,
1152 projectFilterOptions,
1153 selectedProjectKey,
1154 setProjectSortOrder,
1155 setSelectedEnvironmentId,
1156 setThreadSortOrder,
1157 threadListV2Enabled,
1158 ],
1159 );
1160 const nativeHeaderItems = useMemo(
1161 () =>
1162 createSidebarHeaderItems({
1163 filterIcon,
1164 filterMenu,
1165 onOpenSettings: props.onOpenSettings,
1166 }),
1167 [filterIcon, filterMenu, props.onOpenSettings],
1168 );
1169 // Snoozed threads need no special case: the shelf header is a list row
1170 // even while collapsed.
1171 const listEmpty = (
1172 <Text
1173 className={
1174 Platform.OS === "android"
1175 ? "px-4 py-4 text-center text-sm text-drawer-foreground-muted"
1176 : "px-2 py-4 text-sm text-drawer-foreground-muted"
1177 }
1178 >
1179 {catalogState.isLoadingConnections
1180 ? "Loading threads…"
1181 : Platform.OS === "android" && !catalogState.hasConnections
1182 ? "No environments connected"
1183 : props.searchQuery.trim().length > 0
1184 ? threadSearch.isPending
1185 ? "Searching thread messages…"
1186 : "No matching threads"
1187 : selectedProjectScope !== null
1188 ? `No threads in ${selectedProjectScope.title}`
1189 : "No threads yet"}
1190 </Text>
1191 );
1192
1193 if (props.nativeChrome) {
1194 return (
1195 <>
1196 <NativeStackScreenOptions
1197 optionsVersion={[nativeHeaderItems, props.width]}
1198 options={{
1199 // Re-applies the shell's static brand slot with the
1200 // connection-status swap so reconnects surface in the header
1201 // instead of shifting the list.
1202 ...getConnectionAwareBrandHeaderOptions({
1203 headerWidth: props.width,
1204 trailingItemCount: nativeHeaderItems.length,
1205 onOpenEnvironments: props.onOpenEnvironmentSettings,
1206 fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
1207 }),
1208 headerSearchBarOptions: {
1209 ref: searchBarRef,
1210 autoCapitalize: "none",
1211 hideNavigationBar: false,
1212 // Keep the search bar pinned under the title — UIKit's default
1213 // hidesSearchBarWhenScrolling collapses it on scroll.
1214 hideWhenScrolling: false,
1215 obscureBackground: false,
1216 placeholder: "Search",
1217 placement: "stacked",
1218 onCancelButtonPress: () => {
1219 props.onSearchQueryChange("");
1220 },
1221 onChangeText: (event) => {
1222 props.onSearchQueryChange(event.nativeEvent.text);
1223 },
1224 },
1225 unstable_headerRightItems: () => nativeHeaderItems,
1226 }}
1227 />
1228 <View className="flex-1">
1229 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1230 <GestureDetector gesture={sidebarScrollGesture}>
1231 <LegendList
1232 data={listItems}
1233 drawDistance={500}
1234 estimatedItemSize={64}
1235 extraData={listExtraData}
1236 getItemType={(item) => item.type}
1237 itemsAreEqual={sidebarItemsAreEqual}
1238 keyExtractor={(item) => item.key}
1239 renderItem={renderListItem}
1240 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
1241 contentInsetAdjustmentBehavior={
1242 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
1243 }
1244 contentContainerStyle={[
1245 styles.threadListContent,
1246 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
1247 {
1248 paddingBottom: Math.max(insets.bottom, 16) + 16,
1249 paddingTop: 6,
1250 },
1251 ]}
1252 keyboardDismissMode="on-drag"
1253 keyboardShouldPersistTaps="handled"
1254 {...scrollGateHandlers}
1255 recycleItems
1256 scrollEventThrottle={16}
1257 showsVerticalScrollIndicator={false}
1258 style={styles.threadList}
1259 ListEmptyComponent={listEmpty}
1260 />
1261 </GestureDetector>
1262 </SwipeableScrollGateProvider>
1263 </View>
1264 </>
1265 );
1266 }
1267
1268 return (
1269 <View
1270 testID="thread-navigation-sidebar"
1271 className={
1272 Platform.OS === "android" ? "flex-1 bg-header" : "flex-1 border-r border-border bg-drawer"
1273 }
1274 style={{ width: props.width }}
1275 >
1276 <View
1277 className="flex-1"
1278 style={
1279 Platform.OS === "android"
1280 ? {
1281 marginTop: stickyHeaderHeight,
1282 marginHorizontal: 4,
1283 paddingBottom: insets.bottom,
1284 backgroundColor: drawerColor,
1285 borderTopLeftRadius: 28,
1286 borderTopRightRadius: 28,
1287 overflow: "hidden",
1288 }
1289 : { paddingBottom: insets.bottom }
1290 }
1291 >
1292 {Platform.OS === "android" && listItems.length === 0 ? (
1293 <View className="flex-1 items-center justify-center">{listEmpty}</View>
1294 ) : (
1295 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1296 <GestureDetector gesture={sidebarScrollGesture}>
1297 <LegendList
1298 data={listItems}
1299 drawDistance={500}
1300 estimatedItemSize={64}
1301 extraData={listExtraData}
1302 getItemType={(item) => item.type}
1303 itemsAreEqual={sidebarItemsAreEqual}
1304 keyExtractor={(item) => item.key}
1305 renderItem={renderListItem}
1306 contentContainerStyle={[
1307 styles.threadListContent,
1308 Platform.OS === "android" ? { paddingHorizontal: 0 } : null,
1309 {
1310 paddingBottom:
1311 Platform.OS === "android"
1312 ? Math.max(insets.bottom, 16) + 148 - insets.bottom
1313 : 16 + insets.bottom,
1314 paddingTop: Platform.OS === "android" ? 6 : topListInset,
1315 },
1316 ]}
1317 keyboardDismissMode="on-drag"
1318 keyboardShouldPersistTaps="handled"
1319 {...scrollGateHandlers}
1320 recycleItems
1321 scrollEventThrottle={16}
1322 showsVerticalScrollIndicator={false}
1323 style={styles.threadList}
1324 ListEmptyComponent={listEmpty}
1325 />
1326 </GestureDetector>
1327 </SwipeableScrollGateProvider>
1328 )}
1329 </View>
1330
1331 {Platform.OS === "android" ? (
1332 <MaterialThreadListToolbar
1333 sidebar
1334 onLayout={handleStickyHeaderLayout}
1335 searchQuery={props.searchQuery}
1336 onSearchQueryChange={props.onSearchQueryChange}
1337 filterActions={listMenuActions}
1338 filterCustomized={filterCustomized}
1339 onFilterAction={handleListMenuAction}
1340 onOpenSettings={props.onOpenSettings}
1341 onOpenEnvironments={props.onOpenEnvironmentSettings}
1342 onRequestVisibility={props.onRequestVisibility}
1343 />
1344 ) : (
1345 <View
1346 className="absolute inset-x-0 top-0 z-[4] bg-drawer"
1347 collapsable={false}
1348 onLayout={handleStickyHeaderLayout}
1349 pointerEvents="auto"
1350 style={{ paddingTop: insets.top }}
1351 >
1352 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1353 {/* Title slot doubles as the connection status surface: while an
1354 environment reconnects, the brand fades to a status label in
1355 place (no layout shift in the list below). */}
1356 <WorkspaceConnectionTitle
1357 grow
1358 onPress={props.onOpenEnvironmentSettings}
1359 size="pageTitle"
1360 brand={
1361 <View className="h-11 flex-1 justify-center">
1362 <CompactBrandTitle allowFontScaling={false} />
1363 </View>
1364 }
1365 />
1366 <View className="flex-row items-center gap-2.5">
1367 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1368 <SidebarFilterButton
1369 accessibilityLabel="Filter and sort threads"
1370 icon={filterIcon}
1371 />
1372 </ControlPillMenu>
1373 <SidebarHeaderActions onOpenSettings={props.onOpenSettings} />
1374 </View>
1375 </View>
1376
1377 <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]">
1378 <SymbolView
1379 name="magnifyingglass"
1380 size={15}
1381 tintColorClassName="accent-drawer-foreground-muted"
1382 type="monochrome"
1383 />
1384 <TextInput
1385 ref={searchInputRef}
1386 accessibilityLabel="Search threads"
1387 autoCapitalize="none"
1388 autoCorrect={false}
1389 clearButtonMode="while-editing"
1390 onChangeText={props.onSearchQueryChange}
1391 placeholder="Search"
1392 placeholderTextColorClassName="accent-placeholder"
1393 selectionColorClassName={undefined}
1394 cursorColorClassName={undefined}
1395 selectionHandleColorClassName={undefined}
1396 returnKeyType="search"
1397 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-drawer-foreground"
1398 value={props.searchQuery}
1399 />
1400 </View>
1401 </View>
1402 )}
1403 </View>
1404 );
1405}
1406
1407const styles = StyleSheet.create({
1408 threadList: {
1409 flex: 1,
1410 },
1411 threadListContent: {
1412 paddingHorizontal: 8,
1413 },
1414});