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

HomeScreen.tsx

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