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

HomeScreen.tsx

502 lines18.2 KB

1import {
2 LegendList,
3 type LegendListRef,
4 type LegendListRenderItemProps,
5} from "@legendapp/list/react-native";
6import {
7 type EnvironmentProject,
8 type EnvironmentThreadShell,
9} from "@t3tools/client-runtime/state/shell";
10import type {
11 EnvironmentId,
12 SidebarProjectGroupingMode,
13 SidebarThreadSortOrder,
14} from "@t3tools/contracts";
15import { useAtomSet, useAtomValue } from "@effect/atom-react";
16import { AsyncResult } from "effect/unstable/reactivity";
17import { useCallback, useMemo, useRef, useState } from "react";
18import { ActivityIndicator, Platform, View } from "react-native";
19import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21import { useThemeColor } from "../../lib/useThemeColor";
22​
23import { EmptyState } from "../../components/EmptyState";
24import type { WorkspaceState } from "../../state/workspaceModel";
25import type { SavedRemoteConnection } from "../../lib/connection";
26import { scopedProjectKey } from "../../lib/scopedEntities";
27import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
28import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
29import type { PendingNewTask } from "../../state/use-pending-new-tasks";
30import {
31 PendingTaskListRow,
32 ThreadListGroupHeader,
33 ThreadListRow,
34 ThreadListShowMoreRow,
35} from "../threads/thread-list-items";
36import type { HomeListFilterMenuEnvironment } from "./home-list-filter-menu";
37import {
38 buildHomeListLayout,
39 DEFAULT_GROUP_DISPLAY_STATE,
40 homeListItemsAreEqual,
41 nextGroupDisplayState,
42 type HomeGroupDisplayAction,
43 type HomeGroupDisplayState,
44 type HomeListItem,
45} from "./homeListItems";
46import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
47import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
48import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
49import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
50​
51/* ─── Types ──────────────────────────────────────────────────────────── */
52​
53interface HomeScreenProps {
54 readonly projects: ReadonlyArray<EnvironmentProject>;
55 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
56 readonly pendingTasks: ReadonlyArray<PendingNewTask>;
57 readonly catalogState: WorkspaceState;
58 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
59 readonly environments: ReadonlyArray<HomeListFilterMenuEnvironment>;
60 readonly searchQuery: string;
61 readonly selectedEnvironmentId: EnvironmentId | null;
62 readonly projectSortOrder: HomeProjectSortOrder;
63 readonly threadSortOrder: SidebarThreadSortOrder;
64 readonly projectGroupingMode: SidebarProjectGroupingMode;
65 readonly onSearchQueryChange: (query: string) => void;
66 readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
67 readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
68 readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
69 readonly onProjectGroupingModeChange: (mode: SidebarProjectGroupingMode) => void;
70 readonly onAddConnection: () => void;
71 readonly onOpenEnvironments: () => void;
72 readonly onOpenSettings: () => void;
73 readonly onStartNewTask: () => void;
74 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
75 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
76 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
77 readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
78 readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
79 readonly onNewThreadInProject: (project: EnvironmentProject) => void;
81​
82/* ─── Layout constants ───────────────────────────────────────────────── */
83​
84const ESTIMATED_THREAD_ROW_HEIGHT = 72;
85/**
86 * Top spacing between the list and the Android custom header. The Android
87 * header (AndroidHomeHeader) is rendered in-flow above this screen and
88 * already consumes the top safe-area inset, so the list only needs breathing
89 * room here.
90 */
91​
92function deriveEmptyState(props: {
93 readonly catalogState: WorkspaceState;
94 readonly projectCount: number;
95}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
96 const { catalogState } = props;
97 if (catalogState.isLoadingConnections) {
98 return {
99 title: "Loading environments",
100 detail: "Checking saved environments on this device.",
101 loading: true,
102 };
103 }
104​
105 if (!catalogState.hasConnections) {
106 return {
107 title: "No environments connected",
108 detail: "Add an environment to load projects and start coding sessions.",
109 loading: false,
110 };
111 }
112​
113 if (
114 (catalogState.connectionState === "available" ||
115 catalogState.connectionState === "offline" ||
116 catalogState.connectionState === "error") &&
117 !catalogState.hasLoadedShellSnapshot
118 ) {
119 return {
120 title: "Environment unavailable",
121 detail:
122 catalogState.connectionError ??
123 "The saved environment is offline. Check the URL or start the environment, then retry.",
124 loading: false,
125 };
126 }
127​
128 if (
129 catalogState.hasConnectingEnvironment &&
130 !catalogState.hasLoadedShellSnapshot &&
131 catalogState.connectionError === null
132 ) {
133 return {
134 title: "Connecting to environment",
135 detail: "Loading projects and threads from the saved environment.",
136 loading: true,
137 };
138 }
139​
140 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
141 return {
142 title: "No projects found",
143 detail: "The connected environment did not report any projects.",
144 loading: false,
145 };
146 }
147​
148 return {
149 title: "No threads yet",
150 detail: "Create a task to start a new coding session in one of your connected projects.",
151 loading: false,
152 };
154​
155function HomeTopContentSpacer() {
156 return <View className="h-4" />;
158​
159/* ─── Main screen ────────────────────────────────────────────────────── */
160​
161export function HomeScreen(props: HomeScreenProps) {
162 const [groupDisplayStates, setGroupDisplayStates] = useState<
163 ReadonlyMap<string, HomeGroupDisplayState>
164 >(() => new Map());
165 const preferencesResult = useAtomValue(mobilePreferencesAtom);
166 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
167 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
168 const listRef = useRef<LegendListRef | null>(null);
169 const insets = useSafeAreaInsets();
170 const accentColor = useThemeColor("--color-icon-muted");
171 const effectiveGroupDisplayStates = useMemo(() => {
172 const next = new Map(groupDisplayStates);
173 if (!AsyncResult.isSuccess(preferencesResult)) {
174 return next;
175 }
176 for (const key of preferencesResult.value.collapsedProjectGroups ?? []) {
177 const existing = next.get(key);
178 next.set(key, {
179 ...(existing ?? DEFAULT_GROUP_DISPLAY_STATE),
180 collapsed: true,
181 });
182 }
183 return next;
184 }, [groupDisplayStates, preferencesResult]);
185 const effectiveGroupDisplayStatesRef = useRef(effectiveGroupDisplayStates);
186 effectiveGroupDisplayStatesRef.current = effectiveGroupDisplayStates;
187​
188 const updateGroupDisplay = useCallback(
189 (key: string, action: HomeGroupDisplayAction) => {
190 const next = new Map(effectiveGroupDisplayStatesRef.current);
191 next.set(key, nextGroupDisplayState(next.get(key) ?? DEFAULT_GROUP_DISPLAY_STATE, action));
192 effectiveGroupDisplayStatesRef.current = next;
193 setGroupDisplayStates(next);
194 if (action === "toggle-collapsed") {
195 const collapsedProjectGroups: string[] = [];
196 for (const [groupKey, state] of next) {
197 if (state.collapsed) {
198 collapsedProjectGroups.push(groupKey);
199 }
200 }
201 savePreferences({ collapsedProjectGroups });
202 }
203 },
204 [savePreferences],
205 );
206​
207 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
208 if (openSwipeableRef.current !== methods) {
209 openSwipeableRef.current?.close();
210 openSwipeableRef.current = methods;
211 }
212 }, []);
213​
214 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
215 if (openSwipeableRef.current === methods) {
216 openSwipeableRef.current = null;
217 }
218 }, []);
219​
220 const handleScrollBeginDrag = useCallback(() => {
221 openSwipeableRef.current?.close();
222 }, []);
223 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
224 onScrollBeginDrag: handleScrollBeginDrag,
225 });
226​
227 const projectGroups = useMemo(
228 () =>
229 buildHomeThreadGroups({
230 projects: props.projects,
231 threads: props.threads,
232 pendingTasks: props.pendingTasks,
233 environmentId: props.selectedEnvironmentId,
234 searchQuery: props.searchQuery,
235 projectSortOrder: props.projectSortOrder,
236 threadSortOrder: props.threadSortOrder,
237 projectGroupingMode: props.projectGroupingMode,
238 }),
239 [
240 props.pendingTasks,
241 props.projectGroupingMode,
242 props.projects,
243 props.projectSortOrder,
244 props.searchQuery,
245 props.selectedEnvironmentId,
246 props.threadSortOrder,
247 props.threads,
248 ],
249 );
250​
251 const hasSearchQuery = props.searchQuery.trim().length > 0;
252 const listLayout = useMemo(
253 () =>
254 buildHomeListLayout({
255 groups: projectGroups,
256 displayStates: effectiveGroupDisplayStates,
257 showAllThreads: hasSearchQuery,
258 }),
259 [projectGroups, effectiveGroupDisplayStates, hasSearchQuery],
260 );
261​
262 const projectCwdByKey = useMemo(() => {
263 const map = new Map<string, string>();
264 for (const project of props.projects) {
265 map.set(scopedProjectKey(project.environmentId, project.id), project.workspaceRoot);
266 }
267 return map;
268 }, [props.projects]);
269​
270 const extraData = useMemo(
271 () => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
272 [props.savedConnectionsById, projectCwdByKey],
273 );
274​
275 const renderItem = useCallback(
276 ({ item }: LegendListRenderItemProps<HomeListItem>) => {
277 switch (item.type) {
278 case "header":
279 return (
280 <ThreadListGroupHeader
281 variant="compact"
282 collapsed={item.collapsed}
283 isFirst={item.isFirst}
284 groupKey={item.group.key}
285 onGroupAction={updateGroupDisplay}
286 // Aggregated groups (same repo across machines) have no single
287 // target project, and `pending-project:` groups hold a placeholder
288 // built from queued-task metadata rather than a real project shell,
289 // so the quick new-thread button is single-real-project only.
290 newThreadTarget={item.group.newThreadTarget}
291 onNewThread={props.onNewThreadInProject}
292 project={item.group.representative}
293 threadCount={item.group.threads.length + item.group.pendingTasks.length}
294 title={item.group.title}
295 />
296 );
297 case "pending-task":
298 return (
299 <PendingTaskListRow
300 variant="compact"
301 pendingTask={item.pendingTask}
302 environmentLabel={
303 props.savedConnectionsById[item.pendingTask.message.environmentId]
304 ?.environmentLabel ?? null
305 }
306 isLast={item.isLast}
307 onSelectPendingTask={props.onSelectPendingTask}
308 onDeletePendingTask={props.onDeletePendingTask}
309 />
310 );
311 case "thread": {
312 const thread = item.thread;
313 return (
314 <ThreadListRow
315 variant="compact"
316 thread={thread}
317 environmentLabel={
318 props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
319 }
320 projectCwd={
321 projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ??
322 null
323 }
324 isLast={item.isLast}
325 onArchiveThread={props.onArchiveThread}
326 onDeleteThread={props.onDeleteThread}
327 onSelectThread={props.onSelectThread}
328 onSwipeableClose={handleSwipeableClose}
329 onSwipeableWillOpen={handleSwipeableWillOpen}
330 />
331 );
332 }
333 case "show-more":
334 return (
335 <ThreadListShowMoreRow
336 variant="compact"
337 hiddenCount={item.hiddenCount}
338 canShowLess={item.canShowLess}
339 groupKey={item.groupKey}
340 onGroupAction={updateGroupDisplay}
341 />
342 );
343 }
344 },
345 [
346 handleSwipeableClose,
347 handleSwipeableWillOpen,
348 projectCwdByKey,
349 props.onArchiveThread,
350 props.onDeletePendingTask,
351 props.onDeleteThread,
352 props.onNewThreadInProject,
353 props.onSelectPendingTask,
354 props.onSelectThread,
355 props.savedConnectionsById,
356 updateGroupDisplay,
357 ],
358 );
359​
360 const keyExtractor = useCallback((item: HomeListItem) => item.key, []);
361​
362 /* Empty states */
363 const hasAnyThreads =
364 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
365 const hasResults = projectGroups.length > 0;
366 const selectedEnvironmentLabel =
367 props.selectedEnvironmentId === null
368 ? null
369 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
370 "this environment");
371 const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
372 const emptyState = deriveEmptyState({
373 catalogState: props.catalogState,
374 projectCount: props.projects.length,
375 });
376 const connectionStatus =
377 shouldShowConnectionStatus && Platform.OS !== "ios" ? (
378 <View
379 className="absolute left-0 right-0 items-center"
380 style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
381 >
382 <WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
383 </View>
384 ) : null;
385​
386 if (!hasAnyThreads) {
387 return (
388 <View
389 className="flex-1 items-center justify-center bg-screen px-8"
390 style={{
391 paddingBottom: Math.max(insets.bottom, 24),
392 paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
393 }}
394 >
395 <View className="w-full max-w-[430px]">
396 <EmptyState
397 title={emptyState.title}
398 detail={emptyState.detail}
399 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
400 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
401 variant="plain"
402 />
403 {emptyState.loading && !shouldShowConnectionStatus ? (
404 <View className="mt-4 items-center">
405 <ActivityIndicator color={accentColor} />
406 </View>
407 ) : null}
408 {shouldShowConnectionStatus && Platform.OS === "ios" ? (
409 <View className="mt-4">
410 <WorkspaceConnectionStatus
411 state={props.catalogState}
412 onPress={props.onOpenEnvironments}
413 variant="sidebar"
414 />
415 </View>
416 ) : null}
417 </View>
418 {connectionStatus}
419 </View>
420 );
421 }
422​
423 const listHeader = (
424 <>
425 {Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
426​
427 {shouldShowConnectionStatus && Platform.OS === "ios" ? (
428 <View className="pb-4">
429 <WorkspaceConnectionStatus
430 state={props.catalogState}
431 onPress={props.onOpenEnvironments}
432 variant="sidebar"
433 />
434 </View>
435 ) : null}
436 </>
437 );
438​
439 const listEmpty = !hasResults ? (
440 hasSearchQuery ? (
441 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
442 ) : selectedEnvironmentLabel ? (
443 <EmptyState
444 title={`No threads in ${selectedEnvironmentLabel}`}
445 detail="Choose another environment or create a new task."
446 />
447 ) : (
448 <EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
449 )
450 ) : null;
451​
452 return (
453 <View className="flex-1 bg-screen">
454 {/* Sticky headers are deliberately not wired up: LegendList's JS sticky
455 implementation mispositions pinned headers at mount under iOS
456 automatic content insets (headers render one nav-inset too low until
457 the first scroll event) and blanks non-pinned headers after
458 collapse/expand data changes. The flattened layout still exposes
459 `stickyHeaderIndices` if this gets revisited. */}
460 <SwipeableScrollGateProvider enabled={swipeEnabled}>
461 <LegendList
462 ref={listRef}
463 data={listLayout.items}
464 renderItem={renderItem}
465 keyExtractor={keyExtractor}
466 itemsAreEqual={homeListItemsAreEqual}
467 drawDistance={500}
468 estimatedItemSize={ESTIMATED_THREAD_ROW_HEIGHT}
469 extraData={extraData}
470 ListHeaderComponent={listHeader}
471 ListEmptyComponent={listEmpty}
472 style={{ flex: 1 }}
473 automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
474 contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
475 showsVerticalScrollIndicator={false}
476 keyboardDismissMode="on-drag"
477 keyboardShouldPersistTaps="handled"
478 {...scrollGateHandlers}
479 recycleItems
480 scrollEventThrottle={16}
481 contentContainerStyle={{
482 // Android reserves room for the floating new-task FAB
483 // (56 button + 16 gap + bottom inset).
484 paddingBottom:
485 Platform.OS === "ios"
486 ? Math.max(insets.bottom, 24) + 24
487 : Math.max(insets.bottom, 16) + 88,
488 }}
489 scrollIndicatorInsets={
490 Platform.OS === "ios"
491 ? {
492 bottom: Math.max(insets.bottom, 16) + 24,
493 top: 0,
494 }
495 : undefined
496 }
497 />
498 </SwipeableScrollGateProvider>
499 {connectionStatus}
500 </View>
501 );