The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 298 lines 10.1 KB
Raw
1 import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2 import { Button } from "../../components/ui/Button";
3 import { LegendList } from "@legendapp/list/react-native";
4 import type { ProjectEntry } from "@t3tools/contracts";
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 import { SymbolView } from "../../components/ui/AppSymbol";
7 import { T, useGT } from "gt-react-native";
8 import { useEffect, useRef, useState } from "react";
9 import { Pressable, View } from "react-native";
10 import { RefreshControl } from "../../components/ui/RefreshControl";
11
12 import { AppText as Text } from "../../components/ui/AppText";
13 import { PierreEntryIcon } from "../../components/PierreEntryIcon";
14 import { cn } from "../../lib/cn";
15 import { useContentBottomInset, useContentTopInset } from "../../components/ui/useBarInset";
16 import {
17 buildFileTree,
18 flattenFileTree,
19 type FileTreeNode,
20 type VisibleFileTreeNode,
21 } from "./fileTree";
22
23 const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
24 const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
25
26 function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
27 const cached = fileTreeCache.get(entries);
28 if (cached !== undefined) {
29 return cached;
30 }
31 const tree = buildFileTree(entries);
32 fileTreeCache.set(entries, tree);
33 return tree;
34 }
35
36 const FileTreeRow = function FileTreeRow(props: {
37 readonly item: VisibleFileTreeNode;
38 readonly selected: boolean;
39 readonly expanded: boolean;
40 readonly loading: boolean;
41 readonly onPressDirectory: (path: string, expand: boolean) => void;
42 readonly onPreviewFile?: (path: string) => void;
43 readonly onPressFile: (path: string) => void;
44 }) {
45 const { node, depth } = props.item;
46 const gt = useGT();
47
48 return (
49 <Pressable
50 accessibilityRole="button"
51 accessibilityLabel={node.path}
52 accessibilityState={{ selected: props.selected }}
53 onPressIn={() => {
54 if (node.kind === "file") {
55 props.onPreviewFile?.(node.path);
56 }
57 }}
58 onPress={() => {
59 if (node.kind === "directory") {
60 props.onPressDirectory(node.path, !props.expanded);
61 return;
62 }
63 props.onPressFile(node.path);
64 }}
65 className={cn(
66 "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
67 props.selected && "bg-thread-selected",
68 )}
69 style={{ paddingLeft: 8 + depth * 18 }}
70 >
71 {node.kind === "directory" ? (
72 <SymbolView
73 name={props.expanded ? "chevron.down" : "chevron.right"}
74 size={12}
75 tintColorClassName="accent-icon-muted"
76 type="monochrome"
77 />
78 ) : (
79 <View className="w-3" />
80 )}
81 <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
82 <Text
83 className={cn(
84 "min-w-0 flex-1 text-sm leading-normal",
85 props.selected
86 ? "font-t3-bold text-thread-selected-foreground"
87 : node.ignored
88 ? "font-t3-medium text-foreground-tertiary"
89 : "font-t3-medium text-foreground-secondary",
90 )}
91 numberOfLines={1}
92 >
93 {node.name}
94 </Text>
95 {node.kind === "directory" && props.expanded && props.loading ? (
96 <AppActivityIndicator
97 size="small"
98 accessibilityLabel={gt("Loading {name}", { name: node.name })}
99 />
100 ) : null}
101 </Pressable>
102 );
103 };
104
105 export function FileTreeBrowser(props: {
106 readonly revealSelection: (path: string | null) => void;
107 readonly expandedPaths: ReadonlySet<string>;
108 readonly setExpandedPaths: (
109 update: (current: ReadonlySet<string>) => ReadonlySet<string>,
110 ) => void;
111 readonly entries: ReadonlyArray<ProjectEntry>;
112 readonly error: string | null;
113 readonly isPending: boolean;
114 readonly isRefreshing: boolean;
115 readonly searchQuery: string;
116 readonly searchResultPaths: ReadonlySet<string> | null;
117 readonly searchTruncated: boolean;
118 readonly selectedPath: string | null;
119 readonly loadingDirectories: ReadonlySet<string>;
120 readonly onLoadDirectory: (path: string, retry?: boolean) => void;
121 readonly onPreviewFile?: (path: string) => void;
122 readonly onRefresh: () => void;
123 readonly onSelectFile: (path: string) => void;
124 }) {
125 const { expandedPaths, setExpandedPaths } = props;
126 const gt = useGT();
127 const [pendingSelection, setPendingSelection] = useState<{
128 readonly path: string;
129 readonly selectedPathAtPress: string | null;
130 } | null>(null);
131 const headerInset = useContentTopInset();
132 const bottomInset = useContentBottomInset();
133 const {
134 onLoadDirectory,
135 onPreviewFile,
136 onSelectFile,
137 loadingDirectories,
138 selectedPath: controlledSelectedPath,
139 } = props;
140 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
141
142 const selectedPath =
143 pendingSelection?.selectedPathAtPress === controlledSelectedPath
144 ? pendingSelection.path
145 : controlledSelectedPath;
146 const tree = cachedFileTree(props.entries);
147 const visibleNodes = flattenFileTree({
148 nodes: tree,
149 expanded: expandedPaths,
150 searchResultPaths: props.searchResultPaths,
151 });
152
153 const { revealSelection } = props;
154 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the controlled selection's ancestor directories in the file tree state
155 useEffect(() => {
156 revealSelection(controlledSelectedPath);
157 }, [controlledSelectedPath, revealSelection]);
158
159 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests listings for expanded directories that are not yet loaded or pending
160 useEffect(() => {
161 const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
162 for (const node of nodes) {
163 if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
164 onLoadDirectory(node.path);
165 visit(node.children);
166 }
167 };
168 visit(tree);
169 }, [tree, expandedPaths, onLoadDirectory]);
170
171 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending selection timer on unmount
172 useEffect(
173 () => () => {
174 if (pendingSelectionTimeoutRef.current !== null) {
175 clearTimeout(pendingSelectionTimeoutRef.current);
176 }
177 },
178 [],
179 );
180
181 const toggleDirectory = (path: string, expand: boolean) => {
182 if (expand) onLoadDirectory(path, true);
183 setExpandedPaths((current) => {
184 const next = new Set(current);
185 if (next.has(path)) {
186 next.delete(path);
187 } else {
188 next.add(path);
189 }
190 return next;
191 });
192 };
193 const handleSelectFile = (path: string) => {
194 if (pendingSelectionTimeoutRef.current !== null) {
195 clearTimeout(pendingSelectionTimeoutRef.current);
196 }
197 setPendingSelection({
198 path,
199 selectedPathAtPress: controlledSelectedPath,
200 });
201 pendingSelectionTimeoutRef.current = setTimeout(() => {
202 pendingSelectionTimeoutRef.current = null;
203 setPendingSelection((current) => (current?.path === path ? null : current));
204 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
205 onSelectFile(path);
206 };
207 const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (
208 <FileTreeRow
209 item={item}
210 selected={item.node.kind === "file" && item.node.path === selectedPath}
211 expanded={expandedPaths.has(item.node.path)}
212 loading={loadingDirectories.has(item.node.path)}
213 onPressDirectory={toggleDirectory}
214 onPreviewFile={onPreviewFile}
215 onPressFile={handleSelectFile}
216 />
217 );
218
219 const extraData = { expandedPaths, loadingDirectories, selectedPath };
220
221 // Keep the list as direct screen content so UIKit can apply header insets.
222 return (
223 <LegendList
224 renderScrollComponent={NativeScrollView}
225 nestedScrollEnabled={false}
226 contentInset={{ top: headerInset, bottom: bottomInset }}
227 alwaysBounceVertical
228 className="flex-1"
229 data={visibleNodes}
230 keyExtractor={(item) => item.node.path}
231 contentInsetAdjustmentBehavior="never"
232 automaticallyAdjustsScrollIndicatorInsets
233 keyboardDismissMode="on-drag"
234 keyboardShouldPersistTaps="handled"
235 estimatedItemSize={42}
236 recycleItems
237 maintainVisibleContentPosition
238 extraData={extraData}
239 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
240 refreshControl={
241 <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
242 }
243 renderItem={renderItem}
244 ListHeaderComponent={
245 <>
246 {props.error && props.entries.length > 0 ? (
247 <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
248 {props.error}
249 </Text>
250 ) : null}
251 {props.searchTruncated ? (
252 <Text className="mx-4 my-2 text-xs text-foreground-muted">
253 <T>More search results available. Refine your search to see them.</T>
254 </Text>
255 ) : null}
256 </>
257 }
258 ListEmptyComponent={
259 <View className="px-4 py-5">
260 {props.error && props.entries.length === 0 ? (
261 <>
262 <Text className="text-sm font-t3-bold text-foreground">
263 <T>Files unavailable</T>
264 </Text>
265 <Text
266 accessibilityRole="alert"
267 className="mt-1 text-xs leading-normal text-foreground-muted"
268 >
269 {props.error}
270 </Text>
271 <View className="mt-3">
272 <Button
273 label={gt("Try again")}
274 tone="secondary"
275 onPress={props.onRefresh}
276 disabled={props.isPending}
277 />
278 </View>
279 </>
280 ) : props.isPending ? (
281 <AppActivityIndicator size="small" />
282 ) : (
283 <>
284 <Text className="text-sm font-t3-bold text-foreground">
285 <T>No files found</T>
286 </Text>
287 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
288 {props.searchQuery.trim().length > 0
289 ? gt("Try a different search.")
290 : gt("The workspace is empty.")}
291 </Text>
292 </>
293 )}
294 </View>
295 }
296 />
297 );
298 }