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