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

ThreadNavigationSidebar.tsx

1,067 lines39.5 KB

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