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

HomeScreen.tsx

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