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

ThreadNavigationSidebar.tsx

1,158 lines42.5 KB

1import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
2import type {
3 EnvironmentProject,
4 EnvironmentThreadShell,
5} from "@t3tools/client-runtime/state/shell";
6import { LegendList } from "@legendapp/list/react-native";
7import type { MenuAction } from "@react-native-menu/menu";
8import { useAtomValue } from "@effect/atom-react";
9import { AsyncResult } from "effect/unstable/reactivity";
10import type { EnvironmentId } from "@t3tools/contracts";
11import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
12import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
13import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
14import { Gesture, GestureDetector } from "react-native-gesture-handler";
15import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17import type { SearchBarCommands } from "react-native-screens";
18import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
19​
20import { AppText as Text } from "../../components/AppText";
21import { ControlPillMenu } from "../../components/ControlPill";
22import { SymbolView } from "../../components/AppSymbol";
23import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
24import { NativeStackScreenOptions } from "../../native/StackHeader";
25import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
26import { useThemeColor } from "../../lib/useThemeColor";
27import { useProjects, useThreadShells } from "../../state/entities";
28import { mobilePreferencesAtom } from "../../state/preferences";
29import { environmentServerConfigsAtom } from "../../state/server";
30import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
31import { useWorkspaceState } from "../../state/workspace";
32import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
33import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
34import {
35 hasCustomHomeListOptions,
36 PROJECT_GROUPING_OPTIONS,
37 PROJECT_SORT_OPTIONS,
38 THREAD_SORT_OPTIONS,
39 useHomeListOptions,
40} from "../home/home-list-options";
41import { buildHomeListFilterMenu } from "../home/home-list-filter-menu";
42import {
43 buildHomeListLayout,
44 DEFAULT_GROUP_DISPLAY_STATE,
45 homeListItemsAreEqual,
46 nextGroupDisplayState,
47 type HomeGroupDisplayAction,
48 type HomeGroupDisplayState,
49 type HomeListItem,
50} from "../home/homeListItems";
51import { buildHomeThreadGroups } from "../home/homeThreadList";
52import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
53import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
54import { useThreadListActions } from "../home/useThreadListActions";
55import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
56import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
57import { SidebarHeaderActions } from "./sidebar-header-actions";
58import { SidebarFilterButton } from "./sidebar-filter-button";
59import { createSidebarHeaderItems } from "./sidebar-native-header-items";
60import { SidebarNavigationShell } from "./sidebar-navigation-shell";
61import {
62 PendingTaskListRow,
63 ThreadListGroupHeader,
64 ThreadListRow,
65 ThreadListShowMoreRow,
66} from "./thread-list-items";
67import { ThreadListV2Row } from "./thread-list-v2-items";
68import {
69 buildThreadListV2Items,
70 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
71 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
72 type ThreadListV2Item,
73} from "./threadListV2";
74​
75/** The sidebar list serves both lists: v1 grouped items or, when the Thread
76 List v2 beta is on, queued offline tasks, flat v2 rows, and a settled
77 "Show more" pager. */
78type SidebarListItem =
79 | HomeListItem
80 | {
81 readonly type: "v2-pending-task";
82 readonly key: string;
83 readonly pendingTask: PendingNewTask;
84 readonly isLast: boolean;
85 }
86 | { readonly type: "v2-thread"; readonly key: string; readonly item: ThreadListV2Item }
87 | { readonly type: "v2-show-more"; readonly key: string; readonly hiddenCount: number };
88​
89/**
90 * Shared capsule behind the sidebar header buttons — a native liquid-glass
91 * surface on iOS 26+, a tinted pill everywhere else.
92 */
93function SidebarHeaderButtonGroup(props: {
94 readonly children: ReactNode;
95 readonly colorScheme: "light" | "dark";
96}) {
97 if (isLiquidGlassSupported) {
98 return (
99 <LiquidGlassView
100 colorScheme={props.colorScheme}
101 effect="regular"
102 interactive
103 style={styles.headerButtonGroup}
104 >
105 {props.children}
106 </LiquidGlassView>
107 );
108 }
109​
110 return (
111 <View
112 style={[
113 styles.headerButtonGroup,
114 props.colorScheme === "dark"
115 ? { backgroundColor: "rgba(118,118,128,0.24)", borderColor: "rgba(255,255,255,0.08)" }
116 : { backgroundColor: "rgba(255,255,255,0.72)", borderColor: "rgba(0,0,0,0.08)" },
117 { borderWidth: StyleSheet.hairlineWidth },
118 ]}
119 >
120 {props.children}
121 </View>
122 );
124​
125const SIDEBAR_STICKY_HEADER_HEIGHT = 106;
126const SIDEBAR_STICKY_HEADER_FADE_HEIGHT = 44;
127const SIDEBAR_HEADER_WASH_OPACITY = {
128 dark: [0.22, 0.14, 0.04],
129 light: [0.46, 0.3, 0.08],
130} as const;
131​
132interface ThreadNavigationSidebarProps {
133 readonly width: number;
134 readonly visible: boolean;
135 readonly selectedThreadKey: string | null;
136 readonly onOpenSettings: () => void;
137 readonly onOpenEnvironmentSettings: () => void;
138 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
139 readonly onSearchQueryChange: (query: string) => void;
140 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
141 readonly onRequestVisibility: () => void;
142 readonly searchQuery: string;
144​
145/**
146 * iPad/large-width sidebar column.
147 *
148 * On iOS the pane is hosted inside its own navigation-inert single-screen
149 * native stack (SidebarNavigationShell) so the header is a real
150 * UINavigationBar: large title, native bar-button items, and a
151 * UISearchController search field — the same chrome a UISplitViewController
152 * column gets. Other platforms keep the custom header chrome.
153 */
154export function ThreadNavigationSidebar(props: ThreadNavigationSidebarProps) {
155 if (Platform.OS !== "ios") {
156 return <ThreadNavigationSidebarPane {...props} nativeChrome={false} />;
157 }
158 return <NativeSidebarContainer {...props} />;
160​
161function NativeSidebarContainer(props: ThreadNavigationSidebarProps) {
162 const backgroundColor = useThemeColor("--color-drawer");
163 const borderColor = useThemeColor("--color-border");
164​
165 return (
166 <View
167 testID="thread-navigation-sidebar"
168 className="flex-1"
169 style={{
170 width: props.width,
171 backgroundColor,
172 borderRightColor: borderColor,
173 borderRightWidth: StyleSheet.hairlineWidth,
174 }}
175 >
176 <SidebarNavigationShell>
177 <ThreadNavigationSidebarPane {...props} nativeChrome />
178 </SidebarNavigationShell>
179 </View>
180 );
182​
183function ThreadNavigationSidebarPane(
184 props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean },
185) {
186 const insets = useSafeAreaInsets();
187 const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
188 const projects = useProjects();
189 const threads = useThreadShells();
190 const { state: catalogState } = useWorkspaceState();
191 const { savedConnectionsById } = useSavedRemoteConnections();
192 const [headerIsOverContent, setHeaderIsOverContent] = useState(false);
193 const searchInputRef = useRef<TextInput>(null);
194 const searchBarRef = useRef<SearchBarCommands>(null);
195 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
196 const headerIsOverContentRef = useRef(false);
197 const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
198 const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
199 useThreadListActions();
200 const preferencesResult = useAtomValue(mobilePreferencesAtom);
201 const threadListV2Enabled =
202 AsyncResult.isSuccess(preferencesResult) &&
203 preferencesResult.value.threadListV2Enabled === true;
204 const pendingTasks = usePendingNewTasks();
205 const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
206 const environments = useMemo(
207 () =>
208 Object.values(savedConnectionsById)
209 .map((connection) => ({
210 environmentId: connection.environmentId,
211 label: connection.environmentLabel,
212 }))
213 .sort((left, right) => left.label.localeCompare(right.label)),
214 [savedConnectionsById],
215 );
216 const availableEnvironmentIds = useMemo(
217 () => new Set(environments.map((environment) => environment.environmentId)),
218 [environments],
219 );
220 const {
221 options,
222 setSelectedEnvironmentId,
223 setProjectGroupingMode,
224 setProjectSortOrder,
225 setThreadSortOrder,
226 } = useHomeListOptions(availableEnvironmentIds);
227 const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
228 const projectFilterOptions = useMemo(
229 () =>
230 projects
231 .filter(
232 (project) =>
233 options.selectedEnvironmentId === null ||
234 project.environmentId === options.selectedEnvironmentId,
235 )
236 .map((project) => ({
237 key: scopedProjectKey(project.environmentId, project.id),
238 label: project.title,
239 })),
240 [options.selectedEnvironmentId, projects],
241 );
242 const selectedProject = useMemo(
243 () =>
244 selectedProjectKey === null
245 ? null
246 : (projects.find(
247 (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
248 ) ?? null),
249 [projects, selectedProjectKey],
250 );
251 useEffect(() => {
252 if (
253 selectedProjectKey !== null &&
254 !projectFilterOptions.some((project) => project.key === selectedProjectKey)
255 ) {
256 setSelectedProjectKey(null);
257 }
258 }, [projectFilterOptions, selectedProjectKey]);
259 const scopedProjects = useMemo(
260 () => (selectedProject === null ? projects : [selectedProject]),
261 [projects, selectedProject],
262 );
263 const scopedThreads = useMemo(
264 () =>
265 selectedProject === null
266 ? threads
267 : threads.filter(
268 (thread) =>
269 thread.environmentId === selectedProject.environmentId &&
270 thread.projectId === selectedProject.id,
271 ),
272 [selectedProject, threads],
273 );
274 const scopedPendingTasks = useMemo(
275 () =>
276 selectedProject === null
277 ? pendingTasks
278 : pendingTasks.filter(
279 (pendingTask) =>
280 pendingTask.message.environmentId === selectedProject.environmentId &&
281 pendingTask.creation.projectId === selectedProject.id,
282 ),
283 [pendingTasks, selectedProject],
284 );
285 const groups = useMemo(
286 () =>
287 buildHomeThreadGroups({
288 projects: scopedProjects,
289 threads: scopedThreads,
290 pendingTasks: scopedPendingTasks,
291 environmentId: options.selectedEnvironmentId,
292 searchQuery: props.searchQuery,
293 projectSortOrder: options.projectSortOrder,
294 threadSortOrder: options.threadSortOrder,
295 projectGroupingMode: options.projectGroupingMode,
296 }),
297 [options, props.searchQuery, scopedPendingTasks, scopedProjects, scopedThreads],
298 );
299 const [groupDisplayStates, setGroupDisplayStates] = useState<
300 ReadonlyMap<string, HomeGroupDisplayState>
301 >(() => new Map());
302 const updateGroupDisplay = useCallback((key: string, action: HomeGroupDisplayAction) => {
303 setGroupDisplayStates((previous) => {
304 const next = new Map(previous);
305 next.set(
306 key,
307 nextGroupDisplayState(previous.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action),
308 );
309 return next;
310 });
311 }, []);
312 const hasSearchQuery = props.searchQuery.trim().length > 0;
313 const listLayout = useMemo(
314 () =>
315 buildHomeListLayout({
316 groups,
317 displayStates: groupDisplayStates,
318 showAllThreads: hasSearchQuery,
319 }),
320 [groups, groupDisplayStates, hasSearchQuery],
321 );
322 const projectCwdByKey = useMemo(() => {
323 const map = new Map<string, string>();
324 for (const project of projects) {
325 map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
326 }
327 return map;
328 }, [projects]);
329 const projectByKey = useMemo(() => {
330 const map = new Map<string, EnvironmentProject>();
331 for (const project of projects) {
332 map.set(scopedProjectKey(project.environmentId, project.id), project);
333 }
334 return map;
335 }, [projects]);
336​
337 // Thread List v2 (beta) support — same model as the compact Home list
338 // (HomeScreen.tsx): flat creation-order card block + settled recency tail.
339 // PR states stream in per-row; merged/closed PRs auto-settle their thread
340 // on the next partition.
341 const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
342 ReadonlyMap<string, "open" | "closed" | "merged">
343 >(() => new Map());
344 const handleChangeRequestState = useCallback(
345 (threadKey: string, state: "open" | "closed" | "merged" | null) => {
346 setChangeRequestStateByKey((current) => {
347 if ((current.get(threadKey) ?? null) === state) return current;
348 const next = new Map(current);
349 if (state === null) {
350 next.delete(threadKey);
351 } else {
352 next.set(threadKey, state);
353 }
354 return next;
355 });
356 },
357 [],
358 );
359 // The settled tail renders in pages; expansion resets when the filter
360 // context changes so environment/search flips never inherit a deep page.
361 const [settledVisibleCount, setSettledVisibleCount] = useState(
362 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
363 );
364 const settledResetKey = `${options.selectedEnvironmentId ?? "all"}:${selectedProjectKey ?? "all"}:${props.searchQuery.trim()}`;
365 const lastSettledResetKeyRef = useRef(settledResetKey);
366 if (lastSettledResetKeyRef.current !== settledResetKey) {
367 lastSettledResetKeyRef.current = settledResetKey;
368 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
369 }
370 const showMoreSettled = useCallback(
371 () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
372 [],
373 );
374 // now ticks per minute so the inactivity auto-settle boundary is actually
375 // crossed while the pane stays open; without a clock dependency the
376 // partition memoizes a frozen "now".
377 const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
378 useEffect(() => {
379 if (!threadListV2Enabled) return;
380 // Refresh immediately on enable: the mount-time value can be hours old
381 // by the time the beta is switched on, which would misclassify the
382 // inactivity auto-settle boundary until the first tick.
383 setNowMinute(new Date().toISOString().slice(0, 16));
384 const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
385 return () => clearInterval(id);
386 }, [threadListV2Enabled]);
387 // Threads on servers without the settlement capability never classify as
388 // settled (the user could neither un-settle nor pin them).
389 const serverConfigs = useAtomValue(environmentServerConfigsAtom);
390 const settlementEnvironmentIds = useMemo(() => {
391 const supported = new Set<EnvironmentId>();
392 for (const [environmentId, config] of serverConfigs) {
393 if (config.environment.capabilities.threadSettlement === true) {
394 supported.add(environmentId);
395 }
396 }
397 return supported;
398 }, [serverConfigs]);
399 const threadListV2Layout = useMemo(() => {
400 if (!threadListV2Enabled) return { items: [], hiddenSettledCount: 0 };
401 return buildThreadListV2Items({
402 threads: threads.filter((thread) => thread.archivedAt === null),
403 environmentId: options.selectedEnvironmentId,
404 projectRef:
405 selectedProject === null
406 ? null
407 : {
408 environmentId: selectedProject.environmentId,
409 projectId: selectedProject.id,
410 },
411 searchQuery: props.searchQuery,
412 changeRequestStateByKey,
413 settlementEnvironmentIds,
414 settledLimit: settledVisibleCount,
415 now: `${nowMinute}:00.000Z`,
416 });
417 }, [
418 changeRequestStateByKey,
419 nowMinute,
420 options.selectedEnvironmentId,
421 props.searchQuery,
422 settledVisibleCount,
423 settlementEnvironmentIds,
424 threadListV2Enabled,
425 threads,
426 selectedProject,
427 ]);
428 const listItems = useMemo<readonly SidebarListItem[]>(() => {
429 if (!threadListV2Enabled) return listLayout.items;
430 // Queued offline tasks render above the thread rows (mirrors the
431 // compact Home v2 list): they are not thread shells, so the v2 item
432 // builder never sees them, but they must stay visible and deletable
433 // while their environment is offline. Same environment scope and
434 // search filter as the list.
435 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
436 const v2PendingTasks = pendingTasks.filter(
437 (pendingTask) =>
438 (options.selectedEnvironmentId === null ||
439 pendingTask.message.environmentId === options.selectedEnvironmentId) &&
440 (selectedProject === null ||
441 (pendingTask.message.environmentId === selectedProject.environmentId &&
442 pendingTask.creation.projectId === selectedProject.id)) &&
443 (v2SearchQuery.length === 0 ||
444 pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
445 );
446 const items: SidebarListItem[] = v2PendingTasks.map((pendingTask, index) => ({
447 type: "v2-pending-task" as const,
448 key: `v2-pending:${pendingTask.message.messageId}`,
449 pendingTask,
450 isLast: index === v2PendingTasks.length - 1,
451 }));
452 for (const item of threadListV2Layout.items) {
453 items.push({
454 type: "v2-thread" as const,
455 key: scopedThreadKey(item.thread.environmentId, item.thread.id),
456 item,
457 });
458 }
459 if (threadListV2Layout.hiddenSettledCount > 0) {
460 items.push({
461 type: "v2-show-more",
462 key: "v2-show-more",
463 hiddenCount: threadListV2Layout.hiddenSettledCount,
464 });
465 }
466 return items;
467 }, [
468 listLayout.items,
469 options.selectedEnvironmentId,
470 pendingTasks,
471 props.searchQuery,
472 selectedProject,
473 threadListV2Enabled,
474 threadListV2Layout,
475 ]);
476 const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
477 const listMenuActions = useMemo<MenuAction[]>(
478 () => [
479 {
480 id: "environment",
481 title: "Environment",
482 subactions: [
483 {
484 id: "environment:all",
485 title: "All environments",
486 subtitle: "Show threads from every environment",
487 state: options.selectedEnvironmentId === null ? "on" : "off",
488 },
489 ...environments.map((environment) => ({
490 id: `environment:${environment.environmentId}`,
491 title: environment.label,
492 state:
493 options.selectedEnvironmentId === environment.environmentId
494 ? ("on" as const)
495 : ("off" as const),
496 })),
497 ],
498 },
499 ...(projectFilterOptions.length === 0
500 ? []
501 : ([
502 {
503 id: "project",
504 title: "Project",
505 subactions: [
506 {
507 id: "project:all",
508 title: "All projects",
509 subtitle: "Show threads from every project",
510 state: selectedProjectKey === null ? "on" : "off",
511 },
512 ...projectFilterOptions.map((project) => ({
513 id: `project:${project.key}`,
514 title: project.label,
515 state: selectedProjectKey === project.key ? ("on" as const) : ("off" as const),
516 })),
517 ],
518 },
519 ] satisfies MenuAction[])),
520 // v2 lays the list out in fixed creation order — offering sort/group
521 // controls it silently ignores would be a lie. Environment still
522 // scopes the v2 partition, so it stays.
523 ...(threadListV2Enabled
524 ? []
525 : ([
526 {
527 id: "project-sort",
528 title: "Sort projects",
529 subactions: PROJECT_SORT_OPTIONS.map((option) => ({
530 id: `project-sort:${option.value}`,
531 title: option.label,
532 state: options.projectSortOrder === option.value ? "on" : "off",
533 })),
534 },
535 {
536 id: "thread-sort",
537 title: "Sort threads",
538 subactions: THREAD_SORT_OPTIONS.map((option) => ({
539 id: `thread-sort:${option.value}`,
540 title: option.label,
541 state: options.threadSortOrder === option.value ? "on" : "off",
542 })),
543 },
544 {
545 id: "project-grouping",
546 title: "Group projects",
547 subactions: PROJECT_GROUPING_OPTIONS.map((option) => ({
548 id: `project-grouping:${option.value}`,
549 title: option.label,
550 subtitle: option.subtitle,
551 state: options.projectGroupingMode === option.value ? "on" : "off",
552 })),
553 },
554 ] satisfies MenuAction[])),
555 ],
556 [environments, options, projectFilterOptions, selectedProjectKey, threadListV2Enabled],
557 );
558 const handleListMenuAction = useCallback(
559 ({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
560 const event = nativeEvent.event;
561 if (event === "environment:all") {
562 setSelectedEnvironmentId(null);
563 return;
564 }
565 if (event.startsWith("environment:")) {
566 const environment = environments.find(
567 (candidate) => String(candidate.environmentId) === event.slice("environment:".length),
568 );
569 if (environment) setSelectedEnvironmentId(environment.environmentId);
570 return;
571 }
572 if (event === "project:all") {
573 setSelectedProjectKey(null);
574 return;
575 }
576 if (event.startsWith("project:")) {
577 const projectKey = event.slice("project:".length);
578 if (projectFilterOptions.some((project) => project.key === projectKey)) {
579 setSelectedProjectKey(projectKey);
580 }
581 return;
582 }
583 const projectSort = PROJECT_SORT_OPTIONS.find(
584 (option) => `project-sort:${option.value}` === event,
585 );
586 if (projectSort) {
587 setProjectSortOrder(projectSort.value);
588 return;
589 }
590 const threadSort = THREAD_SORT_OPTIONS.find(
591 (option) => `thread-sort:${option.value}` === event,
592 );
593 if (threadSort) {
594 setThreadSortOrder(threadSort.value);
595 return;
596 }
597 const grouping = PROJECT_GROUPING_OPTIONS.find(
598 (option) => `project-grouping:${option.value}` === event,
599 );
600 if (grouping) setProjectGroupingMode(grouping.value);
601 },
602 [
603 environments,
604 projectFilterOptions,
605 setProjectGroupingMode,
606 setProjectSortOrder,
607 setSelectedEnvironmentId,
608 setThreadSortOrder,
609 ],
610 );
611​
612 const backgroundColor = useThemeColor("--color-drawer");
613 const borderColor = useThemeColor("--color-border");
614 const mutedColor = useThemeColor("--color-foreground-muted");
615 const placeholderColor = useThemeColor("--color-placeholder");
616 const headerFadeColor = String(backgroundColor);
617 const headerWashOpacity = SIDEBAR_HEADER_WASH_OPACITY[colorScheme];
618 const [measuredHeaderHeight, setMeasuredHeaderHeight] = useState<number | null>(null);
619 // The sticky header (title row, search field, optional connection status)
620 // is measured so the list inset always matches its real height — no
621 // hardcoded per-variant constants.
622 const stickyHeaderHeight = measuredHeaderHeight ?? insets.top + SIDEBAR_STICKY_HEADER_HEIGHT;
623 const topListInset = stickyHeaderHeight + 6;
624 const handleStickyHeaderLayout = useCallback((event: LayoutChangeEvent) => {
625 const nextHeight = Math.round(event.nativeEvent.layout.height);
626 setMeasuredHeaderHeight((current) => (current === nextHeight ? current : nextHeight));
627 }, []);
628 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
629 if (openSwipeableRef.current !== methods) {
630 openSwipeableRef.current?.close();
631 openSwipeableRef.current = methods;
632 }
633 }, []);
634 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
635 if (openSwipeableRef.current === methods) {
636 openSwipeableRef.current = null;
637 }
638 }, []);
639 const handleSelectThread = useCallback(
640 (thread: EnvironmentThreadShell) => {
641 props.onSelectThread(thread);
642 openSwipeableRef.current?.close();
643 },
644 [props.onSelectThread],
645 );
646 const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
647 const next = event.nativeEvent.contentOffset.y > 6;
648 if (headerIsOverContentRef.current === next) {
649 return;
650 }
651 headerIsOverContentRef.current = next;
652 setHeaderIsOverContent(next);
653 }, []);
654 const handleScrollBeginDrag = useCallback(() => {
655 openSwipeableRef.current?.close();
656 }, []);
657 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
658 onScroll: handleScroll,
659 onScrollBeginDrag: handleScrollBeginDrag,
660 });
661 const listExtraData = useMemo(
662 () => ({
663 selectedThreadKey: props.selectedThreadKey ?? "",
664 savedConnectionsById,
665 serverConfigs,
666 }),
667 [props.selectedThreadKey, savedConnectionsById, serverConfigs],
668 );
669 const sidebarItemsAreEqual = useCallback(
670 (previous: SidebarListItem, item: SidebarListItem): boolean => {
671 if (previous.type === "v2-thread" && item.type === "v2-thread") {
672 return (
673 previous.key === item.key &&
674 previous.item.thread === item.item.thread &&
675 previous.item.variant === item.item.variant &&
676 previous.item.showSettledDivider === item.item.showSettledDivider
677 );
678 }
679 if (previous.type === "v2-show-more" && item.type === "v2-show-more") {
680 return previous.hiddenCount === item.hiddenCount;
681 }
682 if (previous.type === "v2-pending-task" && item.type === "v2-pending-task") {
683 return previous.pendingTask === item.pendingTask && previous.isLast === item.isLast;
684 }
685 if (
686 previous.type === "v2-thread" ||
687 previous.type === "v2-show-more" ||
688 previous.type === "v2-pending-task" ||
689 item.type === "v2-thread" ||
690 item.type === "v2-show-more" ||
691 item.type === "v2-pending-task"
692 ) {
693 return false;
694 }
695 return homeListItemsAreEqual(previous, item);
696 },
697 [],
698 );
699 const focusSearch = useCallback(() => {
700 const focus = () => {
701 if (props.nativeChrome) {
702 searchBarRef.current?.focus();
703 return;
704 }
705 searchInputRef.current?.focus();
706 };
707 if (!props.visible) {
708 props.onRequestVisibility();
709 setTimeout(focus, 240);
710 } else {
711 focus();
712 }
713 return true;
714 }, [props.nativeChrome, props.onRequestVisibility, props.visible]);
715 useHardwareKeyboardCommand("focusSearch", focusSearch);
716 const renderListItem = useCallback(
717 ({ item }: { readonly item: SidebarListItem }) => {
718 switch (item.type) {
719 case "v2-pending-task":
720 return (
721 <PendingTaskListRow
722 variant="sidebar"
723 pendingTask={item.pendingTask}
724 environmentLabel={
725 savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
726 null
727 }
728 isLast={item.isLast}
729 onSelectPendingTask={openPendingTask}
730 onDeletePendingTask={confirmDeletePendingTask}
731 />
732 );
733 case "v2-thread": {
734 const thread = item.item.thread;
735 const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId);
736 return (
737 <ThreadListV2Row
738 thread={thread}
739 variant={item.item.variant}
740 showSettledDivider={item.item.showSettledDivider}
741 project={projectByKey.get(scopeKey) ?? null}
742 providerDriver={
743 serverConfigs
744 .get(thread.environmentId)
745 ?.providers.find(
746 (provider) =>
747 provider.instanceId ===
748 (thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
749 )?.driver ?? null
750 }
751 environmentLabel={
752 Object.keys(savedConnectionsById).length > 1
753 ? (savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
754 : null
755 }
756 pane="sidebar"
757 selected={
758 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
759 }
760 fullSwipeWidth={props.width - 20}
761 onSelectThread={handleSelectThread}
762 onDeleteThread={confirmDeleteThread}
763 onArchiveThread={archiveThread}
764 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
765 onSettleThread={settleThread}
766 onUnsettleThread={unsettleThread}
767 onChangeRequestState={handleChangeRequestState}
768 projectCwd={projectCwdByKey.get(scopeKey) ?? null}
769 onSwipeableClose={handleSwipeableClose}
770 onSwipeableWillOpen={handleSwipeableWillOpen}
771 simultaneousSwipeGesture={sidebarScrollGesture}
772 />
773 );
774 }
775 case "v2-show-more":
776 return (
777 <Pressable
778 accessibilityRole="button"
779 accessibilityLabel={`Show ${Math.min(item.hiddenCount, THREAD_LIST_V2_SETTLED_PAGE_COUNT)} more settled threads`}
780 onPress={showMoreSettled}
781 className="mx-4 mt-2 items-center rounded-lg border border-dashed border-border py-2.5"
782 style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
783 >
784 <Text className="text-xs font-t3-medium text-foreground-muted">
785 Show more ({item.hiddenCount} settled hidden)
786 </Text>
787 </Pressable>
788 );
789 case "header":
790 return (
791 <ThreadListGroupHeader
792 variant="sidebar"
793 collapsed={item.collapsed}
794 isFirst={item.isFirst}
795 groupKey={item.group.key}
796 onGroupAction={updateGroupDisplay}
797 // Same gating as the compact Home list: aggregated groups have no
798 // single target project, and pending-project groups hold a
799 // placeholder shell rather than a real project.
800 newThreadTarget={item.group.newThreadTarget}
801 onNewThread={props.onNewThreadInProject}
802 project={item.group.representative}
803 threadCount={item.group.threads.length + item.group.pendingTasks.length}
804 title={item.group.title}
805 />
806 );
807 case "pending-task":
808 return (
809 <PendingTaskListRow
810 variant="sidebar"
811 pendingTask={item.pendingTask}
812 environmentLabel={
813 savedConnectionsById[item.pendingTask.message.environmentId]?.environmentLabel ??
814 null
815 }
816 isLast={item.isLast}
817 onSelectPendingTask={openPendingTask}
818 onDeletePendingTask={confirmDeletePendingTask}
819 />
820 );
821 case "thread": {
822 const thread = item.thread;
823 return (
824 <ThreadListRow
825 variant="sidebar"
826 thread={thread}
827 environmentLabel={
828 savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
829 }
830 projectCwd={
831 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
832 null
833 }
834 isLast={item.isLast}
835 selected={
836 scopedThreadKey(thread.environmentId, thread.id) === props.selectedThreadKey
837 }
838 fullSwipeWidth={props.width - 20}
839 onArchiveThread={archiveThread}
840 onDeleteThread={confirmDeleteThread}
841 onSelectThread={handleSelectThread}
842 onSwipeableClose={handleSwipeableClose}
843 onSwipeableWillOpen={handleSwipeableWillOpen}
844 simultaneousSwipeGesture={sidebarScrollGesture}
845 />
846 );
847 }
848 case "show-more":
849 return (
850 <ThreadListShowMoreRow
851 variant="sidebar"
852 hiddenCount={item.hiddenCount}
853 canShowLess={item.canShowLess}
854 groupKey={item.groupKey}
855 onGroupAction={updateGroupDisplay}
856 />
857 );
858 }
859 },
860 [
861 archiveThread,
862 confirmDeletePendingTask,
863 confirmDeleteThread,
864 handleChangeRequestState,
865 handleSelectThread,
866 handleSwipeableClose,
867 handleSwipeableWillOpen,
868 openPendingTask,
869 projectByKey,
870 projectCwdByKey,
871 props.onNewThreadInProject,
872 props.selectedThreadKey,
873 props.width,
874 savedConnectionsById,
875 serverConfigs,
876 settleThread,
877 settlementEnvironmentIds,
878 showMoreSettled,
879 sidebarScrollGesture,
880 unsettleThread,
881 updateGroupDisplay,
882 ],
883 );
884 // v2 ignores the sort/group options, so only the environment filter can
885 // light the "customized" state while the beta is on.
886 const filterCustomized = threadListV2Enabled
887 ? options.selectedEnvironmentId !== null || selectedProjectKey !== null
888 : hasCustomHomeListOptions({ ...options, selectedProjectKey });
889 const filterIcon = filterCustomized
890 ? "line.3.horizontal.decrease.circle.fill"
891 : "line.3.horizontal.decrease.circle";
892 const filterMenu = useMemo(
893 () =>
894 buildHomeListFilterMenu({
895 environments,
896 projects: projectFilterOptions,
897 selectedEnvironmentId: options.selectedEnvironmentId,
898 selectedProjectKey,
899 projectSortOrder: options.projectSortOrder,
900 threadSortOrder: options.threadSortOrder,
901 projectGroupingMode: options.projectGroupingMode,
902 onEnvironmentChange: setSelectedEnvironmentId,
903 onProjectChange: setSelectedProjectKey,
904 onProjectSortOrderChange: setProjectSortOrder,
905 onThreadSortOrderChange: setThreadSortOrder,
906 onProjectGroupingModeChange: setProjectGroupingMode,
907 listOrganization: !threadListV2Enabled,
908 }),
909 [
910 environments,
911 options,
912 projectFilterOptions,
913 selectedProjectKey,
914 setProjectGroupingMode,
915 setProjectSortOrder,
916 setSelectedEnvironmentId,
917 setThreadSortOrder,
918 threadListV2Enabled,
919 ],
920 );
921 const nativeHeaderItems = useMemo(
922 () =>
923 createSidebarHeaderItems({
924 filterIcon,
925 filterMenu,
926 onOpenSettings: props.onOpenSettings,
927 }),
928 [filterIcon, filterMenu, props.onOpenSettings],
929 );
930 const listEmpty = (
931 <Text className="px-2 py-4 text-sm text-foreground-muted">
932 {catalogState.isLoadingConnections
933 ? "Loading threads…"
934 : props.searchQuery.trim().length > 0
935 ? "No matching threads"
936 : selectedProject !== null
937 ? `No threads in ${selectedProject.title}`
938 : "No threads yet"}
939 </Text>
940 );
941​
942 if (props.nativeChrome) {
943 return (
944 <>
945 <NativeStackScreenOptions
946 optionsVersion={nativeHeaderItems}
947 options={{
948 headerSearchBarOptions: {
949 ref: searchBarRef,
950 autoCapitalize: "none",
951 hideNavigationBar: false,
952 // Keep the search bar pinned under the title — UIKit's default
953 // hidesSearchBarWhenScrolling collapses it on scroll.
954 hideWhenScrolling: false,
955 obscureBackground: false,
956 placeholder: "Search",
957 placement: "stacked",
958 onCancelButtonPress: () => {
959 props.onSearchQueryChange("");
960 },
961 onChangeText: (event) => {
962 props.onSearchQueryChange(event.nativeEvent.text);
963 },
964 },
965 unstable_headerRightItems: () => nativeHeaderItems,
966 }}
967 />
968 <View className="flex-1">
969 <SwipeableScrollGateProvider enabled={swipeEnabled}>
970 <GestureDetector gesture={sidebarScrollGesture}>
971 <LegendList
972 data={listItems}
973 drawDistance={500}
974 estimatedItemSize={64}
975 extraData={listExtraData}
976 getItemType={(item) => item.type}
977 itemsAreEqual={sidebarItemsAreEqual}
978 keyExtractor={(item) => item.key}
979 renderItem={renderListItem}
980 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
981 contentInsetAdjustmentBehavior={
982 NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"
983 }
984 contentContainerStyle={[
985 styles.threadListContent,
986 {
987 paddingBottom: Math.max(insets.bottom, 16) + 16,
988 paddingTop: 6,
989 },
990 ]}
991 keyboardDismissMode="on-drag"
992 keyboardShouldPersistTaps="handled"
993 {...scrollGateHandlers}
994 recycleItems
995 scrollEventThrottle={16}
996 showsVerticalScrollIndicator={false}
997 style={styles.threadList}
998 ListHeaderComponent={
999 showsConnectionStatus ? (
1000 <View className="px-1.5 pt-0.5 pb-2">
1001 <WorkspaceConnectionStatus
1002 onPress={props.onOpenEnvironmentSettings}
1003 state={catalogState}
1004 variant="sidebar"
1005 />
1006 </View>
1007 ) : null
1009 ListEmptyComponent={listEmpty}
1010 />
1011 </GestureDetector>
1012 </SwipeableScrollGateProvider>
1013 </View>
1014 </>
1015 );
1017​
1018 return (
1019 <View
1020 testID="thread-navigation-sidebar"
1021 className="flex-1"
1022 style={{
1023 width: props.width,
1024 backgroundColor,
1025 borderRightColor: borderColor,
1026 borderRightWidth: StyleSheet.hairlineWidth,
1027 }}
1029 <View className="flex-1" style={{ paddingBottom: insets.bottom }}>
1030 <SwipeableScrollGateProvider enabled={swipeEnabled}>
1031 <GestureDetector gesture={sidebarScrollGesture}>
1032 <LegendList
1033 data={listItems}
1034 drawDistance={500}
1035 estimatedItemSize={64}
1036 extraData={listExtraData}
1037 getItemType={(item) => item.type}
1038 itemsAreEqual={sidebarItemsAreEqual}
1039 keyExtractor={(item) => item.key}
1040 renderItem={renderListItem}
1041 contentContainerStyle={[
1042 styles.threadListContent,
1044 paddingBottom: 16 + insets.bottom,
1045 paddingTop: topListInset,
1046 },
1047 ]}
1048 keyboardDismissMode="on-drag"
1049 keyboardShouldPersistTaps="handled"
1050 {...scrollGateHandlers}
1051 recycleItems
1052 scrollEventThrottle={16}
1053 showsVerticalScrollIndicator={false}
1054 style={styles.threadList}
1055 ListEmptyComponent={listEmpty}
1056 />
1057 </GestureDetector>
1058 </SwipeableScrollGateProvider>
1059 </View>
1060​
1061 <View
1062 className="absolute inset-x-0 top-0 z-[4]"
1063 onLayout={handleStickyHeaderLayout}
1064 pointerEvents="box-none"
1065 style={{ paddingTop: insets.top }}
1067 <View
1068 className="absolute inset-x-0 top-0"
1069 pointerEvents="none"
1070 accessibilityElementsHidden
1071 importantForAccessibility="no-hide-descendants"
1072 style={{ height: stickyHeaderHeight + SIDEBAR_STICKY_HEADER_FADE_HEIGHT }}
1074 <Svg width="100%" height="100%">
1075 <Defs>
1076 <LinearGradient id="sidebar-header-wash" x1="0%" x2="0%" y1="0%" y2="100%">
1077 <Stop
1078 offset="0%"
1079 stopColor={headerFadeColor}
1080 stopOpacity={headerIsOverContent ? headerWashOpacity[0] : 0}
1081 />
1082 <Stop
1083 offset="58%"
1084 stopColor={headerFadeColor}
1085 stopOpacity={headerIsOverContent ? headerWashOpacity[1] : 0}
1086 />
1087 <Stop
1088 offset="88%"
1089 stopColor={headerFadeColor}
1090 stopOpacity={headerIsOverContent ? headerWashOpacity[2] : 0}
1091 />
1092 <Stop offset="100%" stopColor={headerFadeColor} stopOpacity={0} />
1093 </LinearGradient>
1094 </Defs>
1095 <Rect width="100%" height="100%" fill="url(#sidebar-header-wash)" />
1096 </Svg>
1097 </View>
1098 <View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
1099 <Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
1100 Threads
1101 </Text>
1102 <SidebarHeaderButtonGroup colorScheme={colorScheme}>
1103 <ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
1104 <SidebarFilterButton
1105 grouped
1106 accessibilityLabel="Filter and sort threads"
1107 icon={filterIcon}
1108 />
1109 </ControlPillMenu>
1110 <SidebarHeaderActions grouped onOpenSettings={props.onOpenSettings} />
1111 </SidebarHeaderButtonGroup>
1112 </View>
1113​
1114 <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]">
1115 <SymbolView name="magnifyingglass" size={15} tintColor={mutedColor} type="monochrome" />
1116 <TextInput
1117 ref={searchInputRef}
1118 accessibilityLabel="Search threads"
1119 autoCapitalize="none"
1120 autoCorrect={false}
1121 clearButtonMode="while-editing"
1122 onChangeText={props.onSearchQueryChange}
1123 placeholder="Search"
1124 placeholderTextColor={placeholderColor}
1125 returnKeyType="search"
1126 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
1127 value={props.searchQuery}
1128 />
1129 </View>
1130​
1131 {showsConnectionStatus ? (
1132 <View className="px-3.5 pt-2.5">
1133 <WorkspaceConnectionStatus
1134 onPress={props.onOpenEnvironmentSettings}
1135 state={catalogState}
1136 variant="sidebar"
1137 />
1138 </View>
1139 ) : null}
1140 </View>
1141 </View>
1142 );
1144​
1145const styles = StyleSheet.create({
1146 headerButtonGroup: {
1147 alignItems: "center",
1148 borderRadius: 22,
1149 flexDirection: "row",
1150 overflow: "hidden",
1151 },
1152 threadList: {
1153 flex: 1,
1154 },
1155 threadListContent: {
1156 paddingHorizontal: 8,
1157 },
1158});