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