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