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

HomeScreen.tsx

865 lines36.0 KB

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