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

HomeScreen.tsx

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