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

HomeScreen.tsx

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