Open History to see the last commit
1import { useContentTopInset } from "../../components/ui/useBarInset";
2import { usePaneRole } from "../../components/ui/Pane";
3import { ScreenContent } from "../../components/ui/ScreenContent";
4import { useActiveNewTask } from "../../state/active-new-task";
5import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
7import type { ThreadMoveDestination } from "../threads/threadOrder";
8import type { LegendListRef } from "@legendapp/list/react-native";
9import { AnimatedLegendList } from "@legendapp/list/reanimated";
10import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations";
11import {
12 type EnvironmentProject,
13 type EnvironmentThreadShell,
14} from "@t3tools/client-runtime/state/shell";
15import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
16import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
17import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
18import { useAtomValue } from "@effect/atom-react";
19import {
20 use,
21 useEffect,
22 useLayoutEffect,
23 useMemo,
24 useRef,
25 useState,
26 type ComponentProps,
27} from "react";
28import {
29 Platform,
30 ScrollView,
31 useWindowDimensions,
32 View,
33 type ScrollViewProps,
34 type GestureResponderEvent,
35 type NativeScrollEvent,
36 type NativeSyntheticEvent,
37} from "react-native";
38import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
39import { GestureDetector, useNativeGesture } from "react-native-gesture-handler";
40import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
41import { useSafeAreaInsets } from "react-native-safe-area-context";
42
43import { cn } from "../../lib/cn";
44import {
45 ANDROID_READING_MAX_WIDTH,
46 deriveCenteredContentHorizontalPadding,
47} from "../../lib/layout";
48import { EmptyState } from "../../components/ui/EmptyState";
49import { FloatingActionButton } from "../../components/ui/FloatingActionButton";
50import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
51import type { SavedRemoteConnection } from "../../lib/connection";
52import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
53import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
54import { nativeHeaderScrollEdgeEffects } from "../../native/scrollEdgeEffects";
55import {
56 useNativeColumnLayoutMetrics,
57 useNativeLayoutMetrics,
58} from "../../native/native-layout-metrics";
59import { useWorkspaceListEmptyTopInset } from "../layout/workspace/workspace-list-insets";
60import { useNativeWorkspaceColumnsSupported } from "../../native/NativeWorkspaceColumns";
61import { useThreadSearch } from "../../state/queries";
62import { requestThreadMessageJump } from "../threads/threadMessageJump";
63import { useThreadListSearchMatches } from "../threads/useThreadListSearchMatches";
64import { useThreadListV2 } from "../threads/useThreadListV2";
65import { useThreadListNow } from "../threads/use-thread-list-now";
66import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration";
67import { useThreadJumpShortcuts } from "../keyboard/threadKeyboardShortcuts";
68import { usePendingThreadOrder } from "../../state/thread-order";
69import { threadListEnvironmentsAtom } from "../../state/presentation";
70import type { PendingNewTask } from "../../state/use-pending-new-tasks";
71import { useQueuedThreadKeys } from "../../state/use-thread-outbox";
72import {
73 ThreadListV2PendingRow,
74 ThreadListV2Row,
75 ThreadListV2SettledShelfHeader,
76 ThreadListV2ShowMoreRow,
77 ThreadListV2SnoozedShelfHeader,
78 ThreadListV2WorkingShelfHeader,
79} from "../threads/thread-list-v2-items";
80import { useThreadRowProviderInstanceResolver } from "../threads/thread-provider-instance";
81import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests";
82import type { ThreadPrPresentation } from "../../state/thread-pr-presentation";
83import {
84 threadListV2ListItemsAreEqual,
85 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
86 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
87 type ThreadListV2ListItem,
88} from "../threads/threadListV2";
89import { useThreadListV2ShelfPreferences } from "../threads/use-thread-list-v2-shelf-preferences";
90import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
91import {
92 buildHomeProjectScopes,
93 findHomeProjectScope,
94 type HomeProjectSortOrder,
95} from "./homeThreadList";
96import { createSwipeRowActivation } from "./swipe-row-activation";
97import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
98import { useFabScroll } from "./FabScrollContext";
99import { holdLaunchSplashForHomeRows, settleLaunchSplashHomeRows } from "./home-launch-splash";
100import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext";
101import { ThreadListFilters } from "./ThreadListFilters";
102import { deriveHomeEmptyState } from "./home-empty-state";
103
104interface HomeScreenProps {
105 /** Whether this list is the one on screen; see `useHomeRouteVisible`. */
106 readonly visible: boolean;
107 readonly projects: ReadonlyArray<EnvironmentProject>;
108 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
109 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
110 readonly catalogState: WorkspaceState;
111 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
112 readonly environments: ReadonlyArray<
113 HomeListFilterMenuEnvironment & Pick<WorkspaceEnvironment, "connectionState">
114 >;
115 readonly searchQuery: string;
116 readonly selectedEnvironmentId: EnvironmentId | null;
117 readonly selectedProjectKey: string | null;
118 readonly projectSortOrder: HomeProjectSortOrder;
119 readonly projectGroupingMode: SidebarProjectGroupingMode;
120 readonly onSearchQueryChange: (query: string) => void;
121 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
122 readonly onProjectChange: (projectKey: string | null) => void;
123 readonly onAddConnection: () => void;
124 readonly onOpenSettings: () => void;
125 readonly onStartNewTask: () => void;
126 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
127 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
128 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
129 readonly onSettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
130 readonly onSnoozeThread: (
131 thread: EnvironmentThreadShell,
132 snoozedUntil: string,
133 ) => Promise<boolean>;
134 readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
135 readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
136 readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
137 readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
138 readonly onSetThreadAutoSettle: (
139 thread: EnvironmentThreadShell,
140 enabled: boolean,
141 ) => Promise<boolean>;
142 readonly onMoveThread: (
143 thread: EnvironmentThreadShell,
144 direction: ThreadMoveDestination,
145 ) => Promise<boolean>;
146 readonly onRenameThread: (thread: EnvironmentThreadShell) => void;
147 readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
148 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
149 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
150 readonly onNewThreadOnBranch: (thread: EnvironmentThreadShell) => void;
151 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
152}
153
154const ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT = 72;
155// Rows away from the viewport skip their swipe actions (see
156// swipe-row-activation), so render further ahead: a fast fling then reaches
157// rows that are already built instead of rows still being rebuilt.
158const THREAD_LIST_V2_DRAW_DISTANCE = 1_000;
159
160function HomeTopContentSpacer() {
161 return <View className="h-4" />;
162}
163
164function HomeScrollView(props: ComponentProps<typeof ScrollView>) {
165 const primaryColumn = use(NativePrimaryColumnContext);
166 const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null;
167 if (Platform.OS !== "ios") return <ScrollView {...props} />;
168
169 // Register the scroll view explicitly; layout and header siblings hide it from UIKit.
170 return (
171 <ScrollViewMarker
172 style={{ flex: 1 }}
173 scrollEdgeEffects={{
174 ...nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version),
175 top: Number.parseInt(String(Platform.Version), 10) >= 27 ? "automatic" : "soft",
176 }}
177 >
178 <ScrollView
179 {...props}
180 // UIKit's scroll-edge material needs the scroll view's own surface color.
181 className={cn(props.className, sidebarSurface ? "bg-drawer" : "bg-screen")}
182 />
183 </ScrollViewMarker>
184 );
185}
186
187function renderHomeScrollView(props: ScrollViewProps) {
188 // The list passes its content and ref in these props; keep the marker inside the real ScrollView.
189 return <HomeScrollView {...props} />;
190}
191
192export function HomeScreen(props: HomeScreenProps) {
193 const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported();
194 const workspace = useWorkspaceTabs();
195 const [initialScrollOffset] = useState(() => workspace?.getScrollOffset("threads") ?? 0);
196 const primaryColumn = use(NativePrimaryColumnContext);
197 const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null;
198 const contentBackground = sidebarSurface ? "bg-drawer" : "bg-screen";
199 const containerClassName = cn(
200 "flex-1",
201 Platform.OS === "android" ? "bg-header" : contentBackground,
202 );
203 const columnMetrics = useNativeColumnLayoutMetrics();
204 const activeNewTask = useActiveNewTask();
205 const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null);
206 const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined;
207 const queuedThreadKeys = useQueuedThreadKeys();
208 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
209 const homeScrollGesture = useNativeGesture();
210 const insets = useSafeAreaInsets();
211 const contentTopInset = useContentTopInset();
212 const emptyTopInset = useWorkspaceListEmptyTopInset();
213 const { fabClearance } = useAndroidControlSizing();
214 const screenMetrics = useNativeLayoutMetrics();
215 const contentSideInsets = usesNativeWorkspaceColumns
216 ? (columnMetrics ?? screenMetrics)?.safeArea
217 : undefined;
218 // Wide Android lists need reading-width gutters to clear edges and camera cutouts.
219 const { width: windowWidth } = useWindowDimensions();
220 const androidListGutter =
221 Platform.OS === "android"
222 ? deriveCenteredContentHorizontalPadding({
223 viewportWidth: windowWidth,
224 maxContentWidth: ANDROID_READING_MAX_WIDTH,
225 minimumPadding: 0,
226 })
227 : 0;
228 const iosBottomClearance = Math.max(
229 columnMetrics?.safeArea.bottom ?? insets.bottom,
230 24,
231 workspace?.bottomClearance ?? 0,
232 );
233 const searchEnvironmentIds =
234 props.selectedEnvironmentId === null
235 ? props.environments
236 .filter((environment) => environment.connectionState === "connected")
237 .map((environment) => environment.environmentId)
238 : props.environments.some(
239 (environment) =>
240 environment.environmentId === props.selectedEnvironmentId &&
241 environment.connectionState === "connected",
242 )
243 ? [props.selectedEnvironmentId]
244 : [];
245 const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
246 if (openSwipeableRef.current !== methods) {
247 openSwipeableRef.current?.close();
248 openSwipeableRef.current = methods;
249 }
250 };
251
252 const handleSwipeableClose = (methods: SwipeableMethods) => {
253 if (openSwipeableRef.current === methods) {
254 openSwipeableRef.current = null;
255 }
256 };
257
258 const handleScrollBeginDrag = () => {
259 openSwipeableRef.current?.close();
260 };
261 const openThreadPullRequests = useOpenThreadPullRequests();
262 const handleOpenThreadPullRequests = (
263 thread: EnvironmentThreadShell,
264 pr: ThreadPrPresentation,
265 ) => {
266 openSwipeableRef.current?.close();
267 openThreadPullRequests(thread, pr);
268 };
269 const onFabScroll = useFabScroll();
270 const listRef = useRef<LegendListRef>(null);
271 const searchMode = workspace?.state.tabs.threads.searchMode;
272 const restoredOffset = workspace?.state.tabs.threads.scrollOffset;
273 useSearchScrollRestoration(searchMode, () => {
274 if (restoredOffset === undefined) return;
275 void listRef.current?.scrollToOffset({
276 offset: restoredOffset - contentTopInset,
277 animated: false,
278 });
279 });
280 const swipeRowActivation = createSwipeRowActivation();
281 const activateVisibleRows = (rows: ReadonlyArray<ThreadListV2ListItem>) => {
282 const state = listRef.current?.getState();
283 if (state === undefined || !(state.end >= 0)) return;
284 swipeRowActivation.activate(
285 rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
286 );
287 };
288 // Status-bar, accessibility and programmatic scrolls bypass the gate; activate visible rows after settling.
289 const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
290 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the row activation timer on unmount
291 useEffect(() => () => clearTimeout(activationTimerRef.current), []);
292 const handleListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
293 onFabScroll?.(event);
294 if (workspace)
295 workspace.recordScrollOffset(
296 "threads",
297 Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset),
298 );
299 clearTimeout(activationTimerRef.current);
300 activationTimerRef.current = setTimeout(
301 () => activateVisibleRows(listRef.current?.getState().data ?? []),
302 200,
303 );
304 };
305 const trackListTouches = (event: GestureResponderEvent, started: boolean) => {
306 const { changedTouches, touches } = event.nativeEvent;
307 swipeRowActivation.trackTouches(
308 started ? changedTouches.map((touch) => String(touch.identifier)) : [],
309 touches.map((touch) => String(touch.identifier)),
310 );
311 };
312 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
313 onScroll: handleListScroll,
314 onScrollBeginDrag: handleScrollBeginDrag,
315 });
316
317 const { projects, selectedEnvironmentId, projectGroupingMode } = props;
318 const projectScopes = useMemo(
319 () =>
320 buildHomeProjectScopes({
321 projects,
322 environmentId: selectedEnvironmentId,
323 projectGroupingMode,
324 }),
325 [projects, selectedEnvironmentId, projectGroupingMode],
326 );
327 const hasSearchQuery = props.searchQuery.trim().length > 0;
328 const projectByKey = (() => {
329 const map = new Map<string, EnvironmentProject>();
330 for (const project of props.projects) {
331 map.set(scopedProjectKey(project.environmentId, project.id), project);
332 }
333 return map;
334 })();
335
336 const v2ProjectScopeKey = props.selectedProjectKey;
337 // An archived project's filter reads as all projects, matching the filter menu.
338 const v2ScopedProjectGroup = findHomeProjectScope(
339 pickableProjectGroups(projectScopes),
340 v2ProjectScopeKey,
341 );
342 const threadSearch = useThreadSearch(
343 searchEnvironmentIds,
344 props.searchQuery,
345 v2ScopedProjectGroup === null
346 ? {}
347 : { projectIds: v2ScopedProjectGroup.projectRefs.map((ref) => ref.projectId) },
348 );
349 const threadSearchMatchByKey = useThreadListSearchMatches(props.threads, threadSearch);
350 const v2ProjectTitleByProjectKey = new Map(
351 projectScopes.flatMap((scope) =>
352 scope.projectRefs.map(
353 (projectRef) =>
354 [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
355 ),
356 ),
357 );
358 const handleSettleThread = props.onSettleThread;
359 const handleSnoozeThread = props.onSnoozeThread;
360 const handleUnsnoozeThread = props.onUnsnoozeThread;
361 const handlePinThread = props.onPinThread;
362 const handleMoveThread = props.onMoveThread;
363 const handleUnpinThread = props.onUnpinThread;
364 const handleSetThreadAutoSettle = props.onSetThreadAutoSettle;
365 const handleRegenerateThreadTitle = props.onRegenerateThreadTitle;
366 const handleRenameThread = props.onRenameThread;
367 const handleDeleteThread = props.onDeleteThread;
368 const handleUnsettleThread = props.onUnsettleThread;
369 const [settledVisibleCount, setSettledVisibleCount] = useState(
370 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
371 );
372 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
373 const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
374 if (lastSettledResetKey !== settledResetKey) {
375 setLastSettledResetKey(settledResetKey);
376 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
377 }
378 const showMoreSettled = () =>
379 setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
380 const {
381 loaded: shelfPreferencesLoaded,
382 settledShelfExpanded,
383 snoozedShelfExpanded,
384 workingShelfEnabled,
385 workingShelfExpanded,
386 toggleSettledShelf,
387 toggleSnoozedShelf,
388 toggleWorkingShelf,
389 } = useThreadListV2ShelfPreferences();
390 const now = useThreadListNow(props.threads);
391 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
392 const {
393 providersByEnvironmentId,
394 machineByEnvironmentId,
395 settlementEnvironmentIds,
396 snoozeEnvironmentIds,
397 snoozePresetsByEnvironmentId,
398 pinningEnvironmentIds,
399 autoSettleOptOutEnvironmentIds,
400 pinReorderEnvironmentIds,
401 activeReorderEnvironmentIds,
402 titleRegenerationEnvironmentIds,
403 } = listEnvironments;
404 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
405 const pendingOrder = usePendingThreadOrder();
406 const {
407 layout: threadListV2Layout,
408 items: threadListV2Items,
409 contentOnlyThreadKeys,
410 olderSettledShelf,
411 } = useThreadListV2({
412 threads: props.threads,
413 pendingTasks: props.pendingTasks,
414 environmentId: props.selectedEnvironmentId,
415 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
416 searchQuery: props.searchQuery,
417 searchMatches: threadSearchMatchByKey,
418 settlementEnvironmentIds,
419 snoozeEnvironmentIds,
420 pinReorderEnvironmentIds,
421 activeReorderEnvironmentIds,
422 queuedThreadKeys,
423 settledLimit: settledVisibleCount,
424 now,
425 pendingOrder,
426 shelfPreferencesLoaded,
427 workingShelfEnabled,
428 workingShelfExpanded,
429 snoozedShelfExpanded,
430 settledShelfExpanded,
431 selectedThreadKey,
432 });
433 // Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
434 // props object, which is new on every render of Home's parent.
435 const { onSelectThread } = props;
436 // A row listed for a message match opens the thread at that message, by
437 // tap or by shortcut.
438 const selectThread = (thread: EnvironmentThreadShell) => {
439 const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
440 const messageId = contentOnlyThreadKeys.has(key)
441 ? threadSearchMatchByKey.get(key)?.messageId
442 : undefined;
443 if (messageId) {
444 requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
445 }
446 onSelectThread(thread);
447 };
448 useThreadJumpShortcuts(threadListV2Items, selectThread);
449 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the list's visible range after commit to enable swipe gestures on those rows
450 useEffect(() => {
451 if (swipeEnabled) activateVisibleRows(threadListV2Items);
452 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
453
454 const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {
455 if (item.type === "v2-pending") {
456 const pendingScopeKey = scopedProjectKey(
457 item.pendingTask.environmentId,
458 item.pendingTask.projectId,
459 );
460 return (
461 <ThreadListV2PendingRow
462 pane={sidebarSurface ? "sidebar" : "screen"}
463 pendingTask={item.pendingTask}
464 selected={
465 activeNewTask?.pendingKey === item.pendingTask.key ||
466 (item.pendingTask.kind === "pending" &&
467 scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===
468 selectedThreadKey)
469 }
470 project={projectByKey.get(pendingScopeKey) ?? null}
471 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
472 environmentLabel={
473 Object.keys(props.savedConnectionsById).length > 1
474 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
475 null)
476 : null
477 }
478 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
479 showPendingDivider={item.showPendingDivider}
480 showTrailingDivider={item.showTrailingDivider}
481 onSelectPendingTask={props.onSelectPendingTask}
482 onDeletePendingTask={props.onDeletePendingTask}
483 fullSwipeWidth={fullSwipeWidth}
484 onSwipeableClose={handleSwipeableClose}
485 onSwipeableWillOpen={handleSwipeableWillOpen}
486 simultaneousSwipeGesture={homeScrollGesture}
487 activationKey={item.key}
488 />
489 );
490 }
491 if (item.type === "v2-working-shelf") {
492 return (
493 <ThreadListV2WorkingShelfHeader
494 count={item.count}
495 disabled={item.disabled}
496 expanded={item.expanded}
497 onToggle={toggleWorkingShelf}
498 />
499 );
500 }
501 if (item.type === "v2-snoozed-shelf") {
502 return (
503 <ThreadListV2SnoozedShelfHeader
504 count={item.count}
505 disabled={item.disabled}
506 expanded={item.expanded}
507 onToggle={toggleSnoozedShelf}
508 />
509 );
510 }
511 if (item.type === "v2-settled-shelf") {
512 return (
513 <ThreadListV2SettledShelfHeader
514 count={item.count}
515 disabled={item.disabled}
516 expanded={item.expanded}
517 onToggle={toggleSettledShelf}
518 />
519 );
520 }
521 const thread = item.item.thread;
522 return (
523 <ThreadListV2Row
524 pane={sidebarSurface ? "sidebar" : "screen"}
525 selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
526 fullSwipeWidth={fullSwipeWidth}
527 onNewThreadOnBranch={props.onNewThreadOnBranch}
528 thread={thread}
529 variant={item.item.variant}
530 hasQueuedMessages={item.hasQueuedMessages}
531 snoozed={item.item.snoozed}
532 pinned={item.item.pinned}
533 wokeAt={item.item.wokeAt}
534 snoozePresetMinute={item.snoozePresetMinute ?? ""}
535 snoozeWakeLabelText={item.snoozeWakeLabelText}
536 timeLabel={item.timeLabel}
537 showTrailingDivider={item.showTrailingDivider}
538 project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
539 providerInstance={resolveProviderInstance(thread)}
540 providers={providersByEnvironmentId.get(thread.environmentId)}
541 environmentLabel={
542 Object.keys(props.savedConnectionsById).length > 1
543 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
544 : null
545 }
546 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
547 searchMatch={
548 // Only rows listed for their messages show one and open at it.
549 contentOnlyThreadKeys.has(
550 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
551 )
552 ? threadSearchMatchByKey.get(
553 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
554 )
555 : undefined
556 }
557 searchQuery={threadSearch.query}
558 onSelectThread={selectThread}
559 onOpenThreadPullRequests={handleOpenThreadPullRequests}
560 onDeleteThread={handleDeleteThread}
561 onArchiveThread={props.onArchiveThread}
562 onRenameThread={handleRenameThread}
563 onRegenerateThreadTitle={handleRegenerateThreadTitle}
564 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
565 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
566 onSettleThread={handleSettleThread}
567 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
568 snoozePresets={snoozePresetsByEnvironmentId.get(thread.environmentId)}
569 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
570 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
571 reorderSupported={
572 item.item.pinned
573 ? pinReorderEnvironmentIds.has(thread.environmentId)
574 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
575 }
576 canMoveUp={item.canMoveUp}
577 canMoveDown={item.canMoveDown}
578 onSnoozeThread={handleSnoozeThread}
579 onUnsnoozeThread={handleUnsnoozeThread}
580 onUnsettleThread={handleUnsettleThread}
581 onPinThread={handlePinThread}
582 onUnpinThread={handleUnpinThread}
583 onSetThreadAutoSettle={handleSetThreadAutoSettle}
584 onMoveThread={handleMoveThread}
585 onSwipeableClose={handleSwipeableClose}
586 onSwipeableWillOpen={handleSwipeableWillOpen}
587 simultaneousSwipeGesture={homeScrollGesture}
588 activationKey={item.key}
589 />
590 );
591 };
592 const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
593
594 // extraData changes invalidate every visible row; put the minute clock on items to limit updates.
595 const v2ExtraData = {
596 activeNewTask,
597 projectByKey,
598 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
599 listEnvironments,
600 savedConnectionsById: props.savedConnectionsById,
601 searchQuery: props.searchQuery,
602 selectedThreadKey,
603 threadSearchMatchByKey,
604 workingShelfEnabled,
605 };
606
607 const hasAnyThreads =
608 props.threads.some((thread) => thread.archivedAt === null) ||
609 props.pendingTasks.length > 0 ||
610 threadListV2Layout.settledCount > 0;
611 // A hidden list gets no layout, so it never reports its rows as laid out.
612 const hasRowsToLayOut = props.visible && hasAnyThreads && threadListV2Items.length > 0;
613 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- holds the native launch splash, which is outside React, until the rows are gone or this list unmounts; a layout effect runs before the splash hides in this commit
614 useLayoutEffect(() => {
615 return hasRowsToLayOut ? holdLaunchSplashForHomeRows() : undefined;
616 }, [hasRowsToLayOut]);
617 const selectedEnvironmentLabel =
618 props.selectedEnvironmentId === null
619 ? null
620 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
621 "this environment");
622 const emptyState = deriveHomeEmptyState(props.catalogState, props.projects.length);
623
624 if (!hasAnyThreads) {
625 return (
626 <View className={containerClassName}>
627 <ScreenContent surface={sidebarSurface ? "drawer" : "screen"}>
628 <View
629 className={cn(
630 "flex-1 items-center justify-center px-8",
631 Platform.OS !== "android" && contentBackground,
632 )}
633 style={{
634 paddingBottom:
635 Platform.OS === "ios" ? iosBottomClearance : Math.max(insets.bottom, 24),
636 paddingTop: emptyTopInset,
637 paddingLeft: 32 + (contentSideInsets?.left ?? 0),
638 paddingRight: 32 + (contentSideInsets?.right ?? 0),
639 }}
640 >
641 <View className="w-full max-w-[430px]">
642 <EmptyState
643 title={emptyState.title}
644 detail={emptyState.detail}
645 actionLabel={emptyState.showsAddEnvironment ? "Add environment" : undefined}
646 onAction={emptyState.showsAddEnvironment ? props.onAddConnection : undefined}
647 action={
648 Platform.OS === "android" && emptyState.showsAddEnvironment ? (
649 <FloatingActionButton
650 label="Add environment"
651 icon="plus"
652 variant="extended"
653 tone="primary"
654 onPress={props.onAddConnection}
655 />
656 ) : undefined
657 }
658 variant="plain"
659 />
660 {emptyState.loading ? (
661 <View className="mt-4 items-center">
662 <AppActivityIndicator colorClassName="accent-icon-muted" />
663 </View>
664 ) : null}
665 </View>
666 </View>
667 </ScreenContent>
668 </View>
669 );
670 }
671
672 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
673
674 const v2ListHeader = (
675 <>
676 {listHeader}
677 {Platform.OS === "ios" && workspace ? (
678 <ThreadListFilters
679 gutter={sidebarSurface ? 8 : 0}
680 environments={props.environments}
681 projects={pickableProjectGroups(projectScopes).map((scope) => ({
682 key: scope.key,
683 label: scope.title,
684 }))}
685 selectedEnvironmentId={props.selectedEnvironmentId}
686 selectedProjectKey={props.selectedProjectKey}
687 onEnvironmentChange={props.onEnvironmentChange}
688 onProjectChange={props.onProjectChange}
689 />
690 ) : null}
691 </>
692 );
693
694 const v2ListEmpty =
695 hasSearchQuery && threadSearch.isPending ? (
696 <EmptyState
697 title="Searching thread messages…"
698 detail={`Looking for "${props.searchQuery}" in messages.`}
699 variant={Platform.OS === "android" ? "plain" : undefined}
700 />
701 ) : hasSearchQuery ? (
702 <EmptyState
703 title="No results"
704 detail={`No threads matching "${props.searchQuery}".`}
705 variant={Platform.OS === "android" ? "plain" : undefined}
706 />
707 ) : v2ScopedProjectGroup !== null ? (
708 <EmptyState
709 title={`No threads in ${v2ScopedProjectGroup.title}`}
710 detail="Choose another project or create a new task."
711 variant={Platform.OS === "android" ? "plain" : undefined}
712 />
713 ) : selectedEnvironmentLabel ? (
714 <EmptyState
715 title={`No threads in ${selectedEnvironmentLabel}`}
716 detail="Choose another environment or create a new task."
717 variant={Platform.OS === "android" ? "plain" : undefined}
718 />
719 ) : (
720 <EmptyState
721 title="No threads yet"
722 detail="Create a task to start a new coding session."
723 variant={Platform.OS === "android" ? "plain" : undefined}
724 />
725 );
726
727 if (Platform.OS === "android" && threadListV2Items.length === 0) {
728 return (
729 <ScreenContent surface="screen">
730 <View
731 className="flex-1 items-center justify-center px-4"
732 style={{ paddingBottom: insets.bottom }}
733 >
734 {v2ListEmpty}
735 </View>
736 </ScreenContent>
737 );
738 }
739
740 return (
741 <View className={containerClassName}>
742 <ScreenContent surface="screen">
743 <View className={cn("flex-1", Platform.OS !== "android" && contentBackground)}>
744 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
745 <GestureDetector gesture={homeScrollGesture}>
746 <AnimatedLegendList
747 itemLayoutAnimation={sidebarSurface ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}
748 ref={listRef}
749 onLoad={() => {
750 settleLaunchSplashHomeRows();
751 activateVisibleRows(threadListV2Items);
752 }}
753 onTouchStart={(event) => trackListTouches(event, true)}
754 onTouchEnd={(event) => trackListTouches(event, false)}
755 onTouchCancel={(event) => trackListTouches(event, false)}
756 renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined}
757 data={threadListV2Items}
758 renderItem={renderV2Item}
759 keyExtractor={v2KeyExtractor}
760 getItemType={(item) => item.type}
761 itemsAreEqual={threadListV2ListItemsAreEqual}
762 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
763 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
764 recycleItems
765 extraData={v2ExtraData}
766 ListHeaderComponent={v2ListHeader}
767 // Lifted above the rows so an iOS filter menu's dismissal morph is not covered.
768 ListHeaderComponentStyle={{ zIndex: 1 }}
769 ListFooterComponent={
770 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
771 <ThreadListV2ShowMoreRow
772 hiddenCount={threadListV2Layout.hiddenSettledCount}
773 {...(olderSettledShelf.loading
774 ? { state: "loading" as const }
775 : olderSettledShelf.failed
776 ? { state: "failed" as const }
777 : {})}
778 onPress={() => {
779 olderSettledShelf.retry();
780 showMoreSettled();
781 }}
782 />
783 ) : null
784 }
785 ListEmptyComponent={v2ListEmpty}
786 style={{ flex: 1 }}
787 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
788 contentInsetAdjustmentBehavior="never"
789 contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
790 initialScrollOffset={
791 initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
792 }
793 showsVerticalScrollIndicator={false}
794 keyboardDismissMode="on-drag"
795 keyboardShouldPersistTaps="handled"
796 {...scrollGateHandlers}
797 scrollEventThrottle={16}
798 contentContainerStyle={{
799 paddingLeft:
800 (contentSideInsets?.left ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
801 paddingRight:
802 (contentSideInsets?.right ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
803 paddingBottom:
804 Platform.OS === "ios"
805 ? iosBottomClearance
806 : (workspace?.bottomClearance ??
807 Math.max(insets.bottom, 16) +
808 (Platform.OS === "android" ? fabClearance : 88)),
809 }}
810 />
811 </GestureDetector>
812 </SwipeableScrollGateProvider>
813 </View>
814 </ScreenContent>
815 </View>
816 );
817}