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

HomeScreen.tsx

620 lines21.2 KB

1import {
2 type EnvironmentProject,
3 type EnvironmentThreadShell,
4} from "@t3tools/client-runtime/state/shell";
5import type {
6 EnvironmentId,
7 SidebarProjectGroupingMode,
8 SidebarThreadSortOrder,
9} from "@t3tools/contracts";
10import * as Haptics from "expo-haptics";
11import { SymbolView } from "expo-symbols";
12import { useCallback, useMemo, useRef, useState } from "react";
13import { ActivityIndicator, Pressable, ScrollView, useWindowDimensions, View } from "react-native";
14import ReanimatedSwipeable, {
15 type SwipeableMethods,
16} from "react-native-gesture-handler/ReanimatedSwipeable";
17import Animated, {
18 Easing,
19 LinearTransition,
20 type ExitAnimationsValues,
21 withDelay,
22 withTiming,
23} from "react-native-reanimated";
24import { useSafeAreaInsets } from "react-native-safe-area-context";
25import { useThemeColor } from "../../lib/useThemeColor";
26​
27import { AppText as Text } from "../../components/AppText";
28import { EmptyState } from "../../components/EmptyState";
29import { ProjectFavicon } from "../../components/ProjectFavicon";
30import type { WorkspaceState } from "../../state/workspaceModel";
31import type { SavedRemoteConnection } from "../../lib/connection";
32import { relativeTime } from "../../lib/time";
33import { threadStatusTone } from "../threads/threadPresentation";
34import { buildHomeThreadGroups, type HomeProjectSortOrder } from "./homeThreadList";
35import {
36 THREAD_SWIPE_ACTIONS_WIDTH,
37 THREAD_SWIPE_SPRING,
38 ThreadSwipeActions,
39} from "./thread-swipe-actions";
40​
41/* ─── Types ──────────────────────────────────────────────────────────── */
42​
43interface HomeScreenProps {
44 readonly projects: ReadonlyArray<EnvironmentProject>;
45 readonly threads: ReadonlyArray<EnvironmentThreadShell>;
46 readonly catalogState: WorkspaceState;
47 readonly savedConnectionsById: Readonly<Record<string, SavedRemoteConnection>>;
48 readonly searchQuery: string;
49 readonly selectedEnvironmentId: EnvironmentId | null;
50 readonly projectSortOrder: HomeProjectSortOrder;
51 readonly threadSortOrder: SidebarThreadSortOrder;
52 readonly projectGroupingMode: SidebarProjectGroupingMode;
53 readonly onAddConnection: () => void;
54 readonly onOpenEnvironments: () => void;
55 readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
56 readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
57 readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
59​
60/* ─── Status indicator colors ────────────────────────────────────────── */
61​
62function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
63 switch (thread.session?.status) {
64 case "running":
65 return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
66 case "ready":
67 return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
68 case "starting":
69 return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
70 case "error":
71 return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
72 default:
73 return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
74 }
76​
77const COLLAPSED_THREAD_LIMIT = 6;
78const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
79​
80function threadRowExit(values: ExitAnimationsValues) {
81 "worklet";
82​
83 return {
84 initialValues: {
85 height: values.currentHeight,
86 opacity: 1,
87 originX: values.currentOriginX,
88 },
89 animations: {
90 height: withDelay(
91 90,
92 withTiming(0, {
93 duration: 170,
94 easing: Easing.inOut(Easing.cubic),
95 }),
96 ),
97 opacity: withDelay(80, withTiming(0, { duration: 100 })),
98 originX: withTiming(values.currentOriginX - values.windowWidth, {
99 duration: 190,
100 easing: Easing.out(Easing.cubic),
101 }),
102 },
103 };
105​
106function deriveEmptyState(props: {
107 readonly catalogState: WorkspaceState;
108 readonly projectCount: number;
109}): { readonly title: string; readonly detail: string; readonly loading: boolean } {
110 const { catalogState } = props;
111 if (catalogState.isLoadingConnections) {
112 return {
113 title: "Loading environments",
114 detail: "Checking saved environments on this device.",
115 loading: true,
116 };
117 }
118​
119 if (!catalogState.hasConnections) {
120 return {
121 title: "No environments connected",
122 detail: "Add an environment to load projects and start coding sessions.",
123 loading: false,
124 };
125 }
126​
127 if (
128 (catalogState.connectionState === "available" ||
129 catalogState.connectionState === "offline" ||
130 catalogState.connectionState === "error") &&
131 !catalogState.hasLoadedShellSnapshot
132 ) {
133 return {
134 title: "Environment unavailable",
135 detail:
136 catalogState.connectionError ??
137 "The saved environment is offline. Check the URL or start the environment, then retry.",
138 loading: false,
139 };
140 }
141​
142 if (
143 catalogState.hasConnectingEnvironment &&
144 !catalogState.hasLoadedShellSnapshot &&
145 catalogState.connectionError === null
146 ) {
147 return {
148 title: "Connecting to environment",
149 detail: "Loading projects and threads from the saved environment.",
150 loading: true,
151 };
152 }
153​
154 if (props.projectCount === 0 && catalogState.hasLoadedShellSnapshot) {
155 return {
156 title: "No projects found",
157 detail: "The connected environment did not report any projects.",
158 loading: false,
159 };
160 }
161​
162 return {
163 title: "No threads yet",
164 detail: "Create a task to start a new coding session in one of your connected projects.",
165 loading: false,
166 };
168​
169/* ─── Project group header ───────────────────────────────────────────── */
170​
171function ProjectGroupLabel(props: {
172 readonly project: EnvironmentProject;
173 readonly title: string;
174 readonly totalThreadCount: number;
175 readonly isExpanded: boolean;
176 readonly onToggleExpand: () => void;
177}) {
178 const hiddenCount = props.totalThreadCount - COLLAPSED_THREAD_LIMIT;
179​
180 return (
181 <View className="flex-row items-center gap-2.5 px-1 pb-2">
182 <ProjectFavicon
183 environmentId={props.project.environmentId}
184 size={18}
185 projectTitle={props.project.title}
186 workspaceRoot={props.project.workspaceRoot}
187 />
188 <Text
189 className="flex-1 text-xs font-t3-medium uppercase text-foreground-muted"
190 style={{ letterSpacing: 0.5 }}
191 numberOfLines={1}
192 >
193 {props.title}
194 </Text>
195​
196 {hiddenCount > 0 ? (
197 <Pressable onPress={props.onToggleExpand} hitSlop={8}>
198 <Text
199 className="text-xs font-t3-medium text-foreground-muted"
200 style={{ letterSpacing: 0.4 }}
201 >
202 {props.isExpanded ? "Show less" : `${hiddenCount} more`}
203 </Text>
204 </Pressable>
205 ) : null}
206 </View>
207 );
209​
210/* ─── Thread row ─────────────────────────────────────────────────────── */
211​
212function ThreadRow(props: {
213 readonly thread: EnvironmentThreadShell;
214 readonly environmentLabel: string | null;
215 readonly onPress: () => void;
216 readonly onArchive: () => void;
217 readonly onDelete: () => void;
218 readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
219 readonly onSwipeableClose: (methods: SwipeableMethods) => void;
220 readonly isLast: boolean;
221}) {
222 const swipeableRef = useRef<SwipeableMethods | null>(null);
223 const fullSwipeArmedRef = useRef(false);
224 const { width: windowWidth } = useWindowDimensions();
225 const separatorColor = useThemeColor("--color-separator");
226 const iconSubtleColor = useThemeColor("--color-icon-subtle");
227 const cardColor = useThemeColor("--color-card");
228 const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
229 const { bg, fg } = statusColors(props.thread);
230 const tone = threadStatusTone(props.thread);
231 const timestamp = relativeTime(
232 props.thread.latestUserMessageAt ?? props.thread.updatedAt ?? props.thread.createdAt,
233 );
234 const branch = props.thread.branch;
235 const subtitleParts = [props.environmentLabel, branch].filter((part): part is string =>
236 Boolean(part),
237 );
238 const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
239 if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
240 void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
241 }
242 fullSwipeArmedRef.current = armed;
243 }, []);
244​
245 return (
246 <ReanimatedSwipeable
247 ref={swipeableRef}
248 animationOptions={THREAD_SWIPE_SPRING}
249 childrenContainerStyle={{ backgroundColor: cardColor }}
250 containerStyle={{ backgroundColor: cardColor }}
251 dragOffsetFromRightEdge={8}
252 enableTrackpadTwoFingerGesture
253 friction={1}
254 onSwipeableClose={() => {
255 fullSwipeArmedRef.current = false;
256 if (swipeableRef.current) {
257 props.onSwipeableClose(swipeableRef.current);
258 }
259 }}
260 onSwipeableOpenStartDrag={() => {
261 if (swipeableRef.current) {
262 props.onSwipeableWillOpen(swipeableRef.current);
263 }
264 }}
265 onSwipeableWillOpen={() => {
266 const methods = swipeableRef.current;
267 if (!methods) {
268 return;
269 }
270​
271 props.onSwipeableWillOpen(methods);
272 if (fullSwipeArmedRef.current) {
273 fullSwipeArmedRef.current = false;
274 methods.close();
275 props.onDelete();
276 }
277 }}
278 overshootFriction={1}
279 overshootRight
280 renderRightActions={(_progress, translation, methods) => (
281 <ThreadSwipeActions
282 backgroundColor={cardColor}
283 fullSwipeThreshold={fullSwipeThreshold}
284 onDelete={props.onDelete}
285 onFullSwipeArmedChange={handleFullSwipeArmedChange}
286 primaryAction={{
287 accessibilityLabel: `Archive ${props.thread.title}`,
288 icon: "archivebox",
289 label: "Archive",
290 onPress: props.onArchive,
291 }}
292 swipeableMethods={methods}
293 threadTitle={props.thread.title}
294 translation={translation}
295 />
296 )}
297 rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
298 >
299 <Pressable
300 accessibilityHint="Swipe left for archive and delete actions"
301 accessibilityLabel={props.thread.title}
302 accessibilityRole="button"
303 className="bg-card"
304 onPress={() => {
305 swipeableRef.current?.close();
306 props.onPress();
307 }}
308 style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}
309 >
310 <View
311 style={{
312 flexDirection: "row",
313 paddingLeft: 16,
314 paddingRight: 16,
315 paddingVertical: 10,
316 gap: 12,
317 borderBottomWidth: props.isLast ? 0 : 1,
318 borderBottomColor: separatorColor,
319 }}
320 >
321 <View
322 style={{
323 width: 30,
324 height: 30,
325 borderRadius: 9,
326 backgroundColor: bg,
327 alignItems: "center",
328 justifyContent: "center",
329 marginTop: 2,
330 }}
331 >
332 <SymbolView name="arrow.triangle.branch" size={13} tintColor={fg} type="monochrome" />
333 </View>
334​
335 <View style={{ flex: 1, gap: 3 }}>
336 <View className="flex-row items-center justify-between gap-2">
337 <Text
338 className="flex-1 text-base font-t3-bold leading-[20px] text-foreground"
339 numberOfLines={1}
340 >
341 {props.thread.title}
342 </Text>
343 <View className="flex-row items-center gap-2">
344 <View
345 className={tone.pillClassName}
346 style={{ borderRadius: 99, paddingHorizontal: 6, paddingVertical: 2 }}
347 >
348 <Text className={`text-3xs font-t3-bold ${tone.textClassName}`}>
349 {tone.label}
350 </Text>
351 </View>
352 <Text
353 className="text-xs text-foreground-tertiary"
354 style={{ fontVariant: ["tabular-nums"] }}
355 >
356 {timestamp}
357 </Text>
358 </View>
359 </View>
360​
361 {subtitleParts.length > 0 ? (
362 <View className="flex-row items-center gap-1.5" style={{ marginTop: 1 }}>
363 <SymbolView
364 name="arrow.triangle.branch"
365 size={10}
366 tintColor={iconSubtleColor}
367 type="monochrome"
368 />
369 <Text
370 className="text-2xs text-foreground-tertiary"
371 numberOfLines={1}
372 style={{ fontFamily: "monospace" }}
373 >
374 {subtitleParts.join(" · ")}
375 </Text>
376 </View>
377 ) : null}
378 </View>
379 </View>
380 </Pressable>
381 </ReanimatedSwipeable>
382 );
384​
385/* ─── Main screen ────────────────────────────────────────────────────── */
386​
387function staleCatalogPillLabel(props: { readonly catalogState: WorkspaceState }): string {
388 if (props.catalogState.networkStatus === "offline") {
389 return "You are offline";
390 }
391 const connectingEnvironments = props.catalogState.connectingEnvironments;
392 if (connectingEnvironments.length === 1) {
393 return `Reconnecting to ${connectingEnvironments[0]!.environmentLabel}`;
394 }
395 if (connectingEnvironments.length > 1) {
396 return `Reconnecting ${connectingEnvironments.length} environments`;
397 }
398 return "Not connected";
400​
401function StaleCatalogStatusPill(props: {
402 readonly catalogState: WorkspaceState;
403 readonly onPress: () => void;
404}) {
405 const iconColor = useThemeColor("--color-icon-muted");
406 const label = staleCatalogPillLabel(props);
407 const isReconnecting = props.catalogState.connectingEnvironments.length > 0;
408​
409 return (
410 <Pressable
411 accessibilityRole="button"
412 onPress={props.onPress}
413 className="flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
414 style={{
415 shadowColor: "#000",
416 shadowOffset: { width: 0, height: 10 },
417 shadowOpacity: 0.12,
418 shadowRadius: 24,
419 }}
420 >
421 {isReconnecting ? (
422 <ActivityIndicator color={iconColor} size="small" />
423 ) : (
424 <SymbolView
425 name="wifi.slash"
426 size={15}
427 tintColor={iconColor}
428 type="monochrome"
429 weight="semibold"
430 />
431 )}
432 <Text className="max-w-[260px] text-sm font-t3-bold text-foreground" numberOfLines={1}>
433 {label}
434 </Text>
435 </Pressable>
436 );
438​
439export function HomeScreen(props: HomeScreenProps) {
440 const [expandedProjects, setExpandedProjects] = useState<Set<string>>(() => new Set());
441 const openSwipeableRef = useRef<SwipeableMethods | null>(null);
442 const insets = useSafeAreaInsets();
443 const accentColor = useThemeColor("--color-icon-muted");
444​
445 const toggleExpanded = useCallback((key: string) => {
446 setExpandedProjects((prev) => {
447 const next = new Set(prev);
448 if (next.has(key)) next.delete(key);
449 else next.add(key);
450 return next;
451 });
452 }, []);
453​
454 const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
455 if (openSwipeableRef.current !== methods) {
456 openSwipeableRef.current?.close();
457 openSwipeableRef.current = methods;
458 }
459 }, []);
460​
461 const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
462 if (openSwipeableRef.current === methods) {
463 openSwipeableRef.current = null;
464 }
465 }, []);
466​
467 const projectGroups = useMemo(
468 () =>
469 buildHomeThreadGroups({
470 projects: props.projects,
471 threads: props.threads,
472 environmentId: props.selectedEnvironmentId,
473 searchQuery: props.searchQuery,
474 projectSortOrder: props.projectSortOrder,
475 threadSortOrder: props.threadSortOrder,
476 projectGroupingMode: props.projectGroupingMode,
477 }),
478 [
479 props.projectGroupingMode,
480 props.projects,
481 props.projectSortOrder,
482 props.searchQuery,
483 props.selectedEnvironmentId,
484 props.threadSortOrder,
485 props.threads,
486 ],
487 );
488​
489 /* Empty states */
490 const hasAnyThreads = props.threads.some((thread) => thread.archivedAt === null);
491 const hasResults = projectGroups.length > 0;
492 const selectedEnvironmentLabel =
493 props.selectedEnvironmentId === null
494 ? null
495 : (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
496 "this environment");
497 const hasSearchQuery = props.searchQuery.trim().length > 0;
498 const shouldShowConnectionStatus =
499 props.catalogState.networkStatus === "offline" ||
500 props.catalogState.hasConnectingEnvironment ||
501 (props.catalogState.hasLoadedShellSnapshot && !props.catalogState.hasReadyEnvironment);
502 const emptyState = deriveEmptyState({
503 catalogState: props.catalogState,
504 projectCount: props.projects.length,
505 });
506​
507 return (
508 <View className="flex-1 bg-screen">
509 <ScrollView
510 contentInsetAdjustmentBehavior="automatic"
511 showsVerticalScrollIndicator={false}
512 keyboardDismissMode="on-drag"
513 keyboardShouldPersistTaps="handled"
514 onScrollBeginDrag={() => openSwipeableRef.current?.close()}
515 className="flex-1"
516 contentContainerStyle={{
517 paddingHorizontal: 16,
518 paddingTop: 8,
519 paddingBottom: 24,
520 gap: 20,
521 }}
522 >
523 {!hasAnyThreads ? (
524 <View>
525 <EmptyState
526 title={emptyState.title}
527 detail={emptyState.detail}
528 actionLabel={!props.catalogState.hasReadyEnvironment ? "Add environment" : undefined}
529 onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
530 />
531 {emptyState.loading ? (
532 <View className="absolute right-5 top-5">
533 <ActivityIndicator color={accentColor} />
534 </View>
535 ) : null}
536 </View>
537 ) : !hasResults && hasSearchQuery ? (
538 <EmptyState title="No results" detail={`No threads matching "${props.searchQuery}".`} />
539 ) : !hasResults && selectedEnvironmentLabel ? (
540 <EmptyState
541 title={`No threads in ${selectedEnvironmentLabel}`}
542 detail="Choose another environment or create a new task."
543 />
544 ) : !hasResults ? (
545 <EmptyState
546 title="No threads yet"
547 detail="Create a task to start a new coding session."
548 />
549 ) : (
550 projectGroups.map((group) => {
551 const isExpanded = expandedProjects.has(group.key);
552 const visibleThreads = isExpanded
553 ? group.threads
554 : group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
555​
556 return (
557 <Animated.View
558 key={group.key}
559 collapsable={false}
560 exiting={threadRowExit}
561 layout={THREAD_LAYOUT_TRANSITION}
562 style={{ overflow: "hidden" }}
563 >
564 <ProjectGroupLabel
565 isExpanded={isExpanded}
566 onToggleExpand={() => toggleExpanded(group.key)}
567 project={group.representative}
568 title={group.title}
569 totalThreadCount={group.threads.length}
570 />
571 <View
572 className="overflow-hidden rounded-[20px] bg-card"
573 style={{ borderCurve: "continuous" }}
574 >
575 {visibleThreads.map((thread, i) => {
576 const threadKey = `${thread.environmentId}:${thread.id}`;
577 return (
578 <Animated.View
579 key={threadKey}
580 collapsable={false}
581 exiting={threadRowExit}
582 layout={THREAD_LAYOUT_TRANSITION}
583 style={{ overflow: "hidden" }}
584 >
585 <ThreadRow
586 thread={thread}
587 environmentLabel={
588 props.savedConnectionsById[thread.environmentId]?.environmentLabel ??
589 null
590 }
591 isLast={i === visibleThreads.length - 1}
592 onArchive={() => props.onArchiveThread(thread)}
593 onDelete={() => props.onDeleteThread(thread)}
594 onPress={() => props.onSelectThread(thread)}
595 onSwipeableClose={handleSwipeableClose}
596 onSwipeableWillOpen={handleSwipeableWillOpen}
597 />
598 </Animated.View>
599 );
600 })}
601 </View>
602 </Animated.View>
603 );
604 })
605 )}
606 </ScrollView>
607 {shouldShowConnectionStatus ? (
608 <View
609 className="absolute left-0 right-0 items-center"
610 style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
611 >
612 <StaleCatalogStatusPill
613 catalogState={props.catalogState}
614 onPress={props.onOpenEnvironments}
615 />
616 </View>
617 ) : null}
618 </View>
619 );