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

HomeScreen.tsx

859 lines34.5 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, useMemo, 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 { projects, selectedEnvironmentId, projectGroupingMode } = props;
366 const projectScopes = useMemo(
367 () =>
368 buildHomeProjectScopes({
369 projects,
370 environmentId: selectedEnvironmentId,
371 projectGroupingMode,
372 }),
373 [projects, selectedEnvironmentId, projectGroupingMode],
374 );
375 const hasSearchQuery = props.searchQuery.trim().length > 0;
376 const projectByKey = (() => {
377 const map = new Map<string, EnvironmentProject>();
378 for (const project of props.projects) {
379 map.set(scopedProjectKey(project.environmentId, project.id), project);
380 }
381 return map;
382 })();
383​
384 const v2ProjectScopeKey = props.selectedProjectKey;
385 // An archived project's filter reads as all projects, matching the filter menu.
386 const v2ScopedProjectGroup = findHomeProjectScope(
387 pickableProjectGroups(projectScopes),
388 v2ProjectScopeKey,
389 );
390 const threadSearch = useThreadSearch(
391 searchEnvironmentIds,
392 props.searchQuery,
393 v2ScopedProjectGroup === null
394 ? {}
395 : { projectIds: v2ScopedProjectGroup.projectRefs.map((ref) => ref.projectId) },
396 );
397 const threadSearchMatchByKey = useThreadListSearchMatches(props.threads, threadSearch);
398 const v2ProjectTitleByProjectKey = new Map(
399 projectScopes.flatMap((scope) =>
400 scope.projectRefs.map(
401 (projectRef) =>
402 [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
403 ),
404 ),
405 );
406 const handleSettleThread = props.onSettleThread;
407 const handleSnoozeThread = props.onSnoozeThread;
408 const handleUnsnoozeThread = props.onUnsnoozeThread;
409 const handlePinThread = props.onPinThread;
410 const handleMoveThread = props.onMoveThread;
411 const handleUnpinThread = props.onUnpinThread;
412 const handleSetThreadAutoSettle = props.onSetThreadAutoSettle;
413 const handleRegenerateThreadTitle = props.onRegenerateThreadTitle;
414 const handleRenameThread = props.onRenameThread;
415 const handleDeleteThread = props.onDeleteThread;
416 const handleUnsettleThread = props.onUnsettleThread;
417 const [settledVisibleCount, setSettledVisibleCount] = useState(
418 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
419 );
420 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
421 const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
422 if (lastSettledResetKey !== settledResetKey) {
423 setLastSettledResetKey(settledResetKey);
424 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
425 }
426 const showMoreSettled = () =>
427 setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
428 const {
429 loaded: shelfPreferencesLoaded,
430 settledShelfExpanded,
431 snoozedShelfExpanded,
432 workingShelfEnabled,
433 workingShelfExpanded,
434 toggleSettledShelf,
435 toggleSnoozedShelf,
436 toggleWorkingShelf,
437 } = useThreadListV2ShelfPreferences();
438 const now = useThreadListNow(props.threads);
439 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
440 const {
441 providersByEnvironmentId,
442 machineByEnvironmentId,
443 settlementEnvironmentIds,
444 snoozeEnvironmentIds,
445 snoozePresetsByEnvironmentId,
446 pinningEnvironmentIds,
447 autoSettleOptOutEnvironmentIds,
448 pinReorderEnvironmentIds,
449 activeReorderEnvironmentIds,
450 titleRegenerationEnvironmentIds,
451 } = listEnvironments;
452 const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId);
453 const pendingOrder = usePendingThreadOrder();
454 const {
455 layout: threadListV2Layout,
456 items: threadListV2Items,
457 contentOnlyThreadKeys,
458 olderSettledShelf,
459 } = useThreadListV2({
460 threads: props.threads,
461 pendingTasks: props.pendingTasks,
462 environmentId: props.selectedEnvironmentId,
463 projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
464 searchQuery: props.searchQuery,
465 searchMatches: threadSearchMatchByKey,
466 settlementEnvironmentIds,
467 snoozeEnvironmentIds,
468 pinReorderEnvironmentIds,
469 activeReorderEnvironmentIds,
470 queuedThreadKeys,
471 settledLimit: settledVisibleCount,
472 now,
473 pendingOrder,
474 shelfPreferencesLoaded,
475 workingShelfEnabled,
476 workingShelfExpanded,
477 snoozedShelfExpanded,
478 settledShelfExpanded,
479 selectedThreadKey,
480 });
481 // Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole
482 // props object, which is new on every render of Home's parent.
483 const { onSelectThread } = props;
484 // A row listed for a message match opens the thread at that message, by
485 // tap or by shortcut.
486 const selectThread = (thread: EnvironmentThreadShell) => {
487 const key = threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id });
488 const messageId = contentOnlyThreadKeys.has(key)
489 ? threadSearchMatchByKey.get(key)?.messageId
490 : undefined;
491 if (messageId) {
492 requestThreadMessageJump(scopedThreadKey(thread.environmentId, thread.id), messageId);
493 }
494 onSelectThread(thread);
495 };
496 useThreadJumpShortcuts(threadListV2Items, selectThread);
497 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads the list's visible range after commit to enable swipe gestures on those rows
498 useEffect(() => {
499 if (swipeEnabled) activateVisibleRows(threadListV2Items);
500 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
501​
502 const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {
503 if (item.type === "v2-pending") {
504 const pendingScopeKey = scopedProjectKey(
505 item.pendingTask.environmentId,
506 item.pendingTask.projectId,
507 );
508 return (
509 <ThreadListV2PendingRow
510 pane={primaryColumn ? "sidebar" : "screen"}
511 pendingTask={item.pendingTask}
512 selected={
513 activeNewTask?.pendingKey === item.pendingTask.key ||
514 (item.pendingTask.kind === "pending" &&
515 scopedThreadKey(item.pendingTask.environmentId, item.pendingTask.message.threadId) ===
516 selectedThreadKey)
517 }
518 project={projectByKey.get(pendingScopeKey) ?? null}
519 projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
520 environmentLabel={
521 Object.keys(props.savedConnectionsById).length > 1
522 ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
523 null)
524 : null
525 }
526 environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
527 showPendingDivider={item.showPendingDivider}
528 showTrailingDivider={item.showTrailingDivider}
529 onSelectPendingTask={props.onSelectPendingTask}
530 onDeletePendingTask={props.onDeletePendingTask}
531 fullSwipeWidth={fullSwipeWidth}
532 onSwipeableClose={handleSwipeableClose}
533 onSwipeableWillOpen={handleSwipeableWillOpen}
534 simultaneousSwipeGesture={homeScrollGesture}
535 activationKey={item.key}
536 />
537 );
538 }
539 if (item.type === "v2-working-shelf") {
540 return (
541 <ThreadListV2WorkingShelfHeader
542 count={item.count}
543 disabled={item.disabled}
544 expanded={item.expanded}
545 onToggle={toggleWorkingShelf}
546 />
547 );
548 }
549 if (item.type === "v2-snoozed-shelf") {
550 return (
551 <ThreadListV2SnoozedShelfHeader
552 count={item.count}
553 disabled={item.disabled}
554 expanded={item.expanded}
555 onToggle={toggleSnoozedShelf}
556 />
557 );
558 }
559 if (item.type === "v2-settled-shelf") {
560 return (
561 <ThreadListV2SettledShelfHeader
562 count={item.count}
563 disabled={item.disabled}
564 expanded={item.expanded}
565 onToggle={toggleSettledShelf}
566 />
567 );
568 }
569 const thread = item.item.thread;
570 return (
571 <ThreadListV2Row
572 pane={primaryColumn ? "sidebar" : "screen"}
573 selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
574 fullSwipeWidth={fullSwipeWidth}
575 onNewThreadOnBranch={props.onNewThreadOnBranch}
576 thread={thread}
577 variant={item.item.variant}
578 hasQueuedMessages={item.hasQueuedMessages}
579 snoozed={item.item.snoozed}
580 pinned={item.item.pinned}
581 wokeAt={item.item.wokeAt}
582 snoozePresetMinute={item.snoozePresetMinute ?? ""}
583 snoozeWakeLabelText={item.snoozeWakeLabelText}
584 timeLabel={item.timeLabel}
585 showTrailingDivider={item.showTrailingDivider}
586 project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
587 providerInstance={resolveProviderInstance(thread)}
588 providers={providersByEnvironmentId.get(thread.environmentId)}
589 environmentLabel={
590 Object.keys(props.savedConnectionsById).length > 1
591 ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
592 : null
593 }
594 environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
595 searchMatch={
596 // Only rows listed for their messages show one and open at it.
597 contentOnlyThreadKeys.has(
598 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
599 )
600 ? threadSearchMatchByKey.get(
601 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
602 )
603 : undefined
604 }
605 searchQuery={threadSearch.query}
606 onSelectThread={selectThread}
607 onOpenThreadPullRequests={handleOpenThreadPullRequests}
608 onDeleteThread={handleDeleteThread}
609 onArchiveThread={props.onArchiveThread}
610 onRenameThread={handleRenameThread}
611 onRegenerateThreadTitle={handleRegenerateThreadTitle}
612 titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
613 settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
614 onSettleThread={handleSettleThread}
615 snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
616 snoozePresets={snoozePresetsByEnvironmentId.get(thread.environmentId)}
617 pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
618 autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
619 reorderSupported={
620 item.item.pinned
621 ? pinReorderEnvironmentIds.has(thread.environmentId)
622 : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
623 }
624 canMoveUp={item.canMoveUp}
625 canMoveDown={item.canMoveDown}
626 onSnoozeThread={handleSnoozeThread}
627 onUnsnoozeThread={handleUnsnoozeThread}
628 onUnsettleThread={handleUnsettleThread}
629 onPinThread={handlePinThread}
630 onUnpinThread={handleUnpinThread}
631 onSetThreadAutoSettle={handleSetThreadAutoSettle}
632 onMoveThread={handleMoveThread}
633 onSwipeableClose={handleSwipeableClose}
634 onSwipeableWillOpen={handleSwipeableWillOpen}
635 simultaneousSwipeGesture={homeScrollGesture}
636 activationKey={item.key}
637 />
638 );
639 };
640 const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
641​
642 // extraData changes invalidate every visible row; put the minute clock on items to limit updates.
643 const v2ExtraData = {
644 activeNewTask,
645 projectByKey,
646 projectTitleByProjectKey: v2ProjectTitleByProjectKey,
647 listEnvironments,
648 savedConnectionsById: props.savedConnectionsById,
649 searchQuery: props.searchQuery,
650 selectedThreadKey,
651 threadSearchMatchByKey,
652 workingShelfEnabled,
653 };
654​
655 const hasAnyThreads =
656 props.threads.some((thread) => thread.archivedAt === null) ||
657 props.pendingTasks.length > 0 ||
658 threadListV2Layout.settledCount > 0;
659 const selectedEnvironmentLabel =
660 props.selectedEnvironmentId === null
661 ? null
662 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
663 "this environment");
664 const emptyState = deriveEmptyState({
665 catalogState: props.catalogState,
666 projectCount: props.projects.length,
667 });
668​
669 if (!hasAnyThreads) {
670 return (
671 <View className={containerClassName}>
672 <View
673 className={cn(
674 "flex-1 items-center justify-center px-8",
675 contentBackground,
676 Platform.OS === "android" && "overflow-hidden rounded-t-[28px]",
677 )}
678 style={{
679 paddingBottom: Platform.OS === "ios" ? iosBottomClearance : Math.max(insets.bottom, 24),
680 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
681 paddingLeft: 32 + (contentSideInsets?.left ?? 0),
682 paddingRight: 32 + (contentSideInsets?.right ?? 0),
683 }}
684 >
685 <View className="w-full max-w-[430px]">
686 <EmptyState
687 title={emptyState.title}
688 detail={emptyState.detail}
689 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
690 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
691 action={
692 Platform.OS === "android" && !props.catalogState.hasReadyEnvironment ? (
693 <FloatingActionButton
694 label="Add environment"
695 icon="plus"
696 variant="extended"
697 tone="primary"
698 onPress={props.onAddConnection}
699 />
700 ) : undefined
701 }
702 variant="plain"
703 />
704 {emptyState.loading ? (
705 <View className="mt-4 items-center">
706 <AppActivityIndicator colorClassName="accent-icon-muted" />
707 </View>
708 ) : null}
709 </View>
710 </View>
711 </View>
712 );
713 }
714​
715 const listHeader = Platform.OS === "ios" ? undefined : <HomeTopContentSpacer />;
716​
717 const v2ListHeader = (
718 <>
719 {listHeader}
720 {Platform.OS === "ios" && workspace ? (
721 <ThreadListFilters
722 gutter={primaryColumn ? 8 : 0}
723 environments={props.environments}
724 projects={pickableProjectGroups(projectScopes).map((scope) => ({
725 key: scope.key,
726 label: scope.title,
727 }))}
728 selectedEnvironmentId={props.selectedEnvironmentId}
729 selectedProjectKey={props.selectedProjectKey}
730 onEnvironmentChange={props.onEnvironmentChange}
731 onProjectChange={props.onProjectChange}
732 />
733 ) : null}
734 </>
735 );
736​
737 const v2ListEmpty =
738 hasSearchQuery && threadSearch.isPending ? undefined : hasSearchQuery ? (
739 <EmptyState
740 title="No results"
741 detail={`No threads matching "${props.searchQuery}".`}
742 variant={Platform.OS === "android" ? "plain" : undefined}
743 />
744 ) : v2ScopedProjectGroup !== null ? (
745 <EmptyState
746 title={`No threads in ${v2ScopedProjectGroup.title}`}
747 detail="Choose another project or create a new task."
748 variant={Platform.OS === "android" ? "plain" : undefined}
749 />
750 ) : selectedEnvironmentLabel ? (
751 <EmptyState
752 title={`No threads in ${selectedEnvironmentLabel}`}
753 detail="Choose another environment or create a new task."
754 variant={Platform.OS === "android" ? "plain" : undefined}
755 />
756 ) : (
757 <EmptyState
758 title="No threads yet"
759 detail="Create a task to start a new coding session."
760 variant={Platform.OS === "android" ? "plain" : undefined}
761 />
762 );
763​
764 if (Platform.OS === "android" && threadListV2Items.length === 0) {
765 return (
766 <View className="flex-1 bg-header">
767 <View
768 className="flex-1 items-center justify-center overflow-hidden rounded-t-[28px] bg-screen px-4"
769 style={{ paddingBottom: insets.bottom }}
770 >
771 {v2ListEmpty}
772 </View>
773 </View>
774 );
775 }
776​
777 return (
778 <View className={containerClassName}>
779 <View
780 className={
781 Platform.OS === "android"
782 ? "flex-1 overflow-hidden rounded-t-[28px] bg-screen"
783 : cn("flex-1", contentBackground)
784 }
785 >
786 <SwipeableScrollGateProvider enabled={swipeEnabled} activation={swipeRowActivation}>
787 <GestureDetector gesture={homeScrollGesture}>
788 <AnimatedLegendList
789 itemLayoutAnimation={primaryColumn ? THREAD_SIDEBAR_ROW_LAYOUT : undefined}
790 ref={listRef}
791 onLoad={() => activateVisibleRows(threadListV2Items)}
792 onTouchStart={(event) => trackListTouches(event, true)}
793 onTouchEnd={(event) => trackListTouches(event, false)}
794 onTouchCancel={(event) => trackListTouches(event, false)}
795 renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined}
796 data={threadListV2Items}
797 renderItem={renderV2Item}
798 keyExtractor={v2KeyExtractor}
799 getItemType={(item) => item.type}
800 itemsAreEqual={threadListV2ListItemsAreEqual}
801 estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT}
802 drawDistance={THREAD_LIST_V2_DRAW_DISTANCE}
803 recycleItems
804 extraData={v2ExtraData}
805 ListHeaderComponent={v2ListHeader}
806 ListFooterComponent={
807 settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
808 <ThreadListV2ShowMoreRow
809 hiddenCount={threadListV2Layout.hiddenSettledCount}
810 {...(olderSettledShelf.loading
811 ? { state: "loading" as const }
812 : olderSettledShelf.failed
813 ? { state: "failed" as const }
814 : {})}
815 onPress={() => {
816 olderSettledShelf.retry();
817 showMoreSettled();
818 }}
819 />
820 ) : null
821 }
822 ListEmptyComponent={v2ListEmpty}
823 style={{ flex: 1 }}
824 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
825 // UIKit owns the bar's inset, so a minimizing bar and a resized column move
826 // the list in the same frame as the bar.
827 contentInsetAdjustmentBehavior="automatic"
828 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
829 // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
830 scrollToOverflowEnabled
831 initialScrollOffset={
832 initialScrollOffset > 0
833 ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
834 : undefined
835 }
836 showsVerticalScrollIndicator={false}
837 keyboardDismissMode="on-drag"
838 keyboardShouldPersistTaps="handled"
839 {...scrollGateHandlers}
840 scrollEventThrottle={16}
841 contentContainerStyle={{
842 paddingLeft:
843 (contentSideInsets?.left ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter,
844 paddingRight:
845 (contentSideInsets?.right ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter,
846 paddingBottom:
847 Platform.OS === "ios"
848 ? iosBottomClearance - (columnMetrics?.safeArea.bottom ?? insets.bottom)
849 : (workspace?.bottomClearance ??
850 Math.max(insets.bottom, 16) +
851 (Platform.OS === "android" ? fabClearance : 88)),
852 }}
853 />
854 </GestureDetector>
855 </SwipeableScrollGateProvider>
856 </View>
857 </View>
858 );