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

HomeScreen.tsx

852 lines34.2 KB

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