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

FileTreeBrowser.tsx

326 lines10.8 KB

1import { LegendList } from "@legendapp/list/react-native";
2import type { ProjectEntry } from "@t3tools/contracts";
3import { SymbolView } from "../../components/AppSymbol";
4import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
5import { ActivityIndicator, Platform, Pressable, RefreshControl, View } from "react-native";
6import { useSafeAreaInsets } from "react-native-safe-area-context";
7​
8import { AppText as Text } from "../../components/AppText";
9import { PierreEntryIcon } from "../../components/PierreEntryIcon";
10import { cn } from "../../lib/cn";
11import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
12import {
13 buildFileTree,
14 flattenFileTree,
15 type FileTreeNode,
16 type VisibleFileTreeNode,
17} from "./fileTree";
18​
19const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
20const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
21​
22function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
23 const cached = fileTreeCache.get(entries);
24 if (cached !== undefined) {
25 return cached;
26 }
27 const tree = buildFileTree(entries);
28 fileTreeCache.set(entries, tree);
29 return tree;
31​
32function ancestorPaths(path: string): ReadonlyArray<string> {
33 const parts = path.split("/").filter(Boolean);
34 const ancestors: string[] = [];
35 for (let index = 1; index < parts.length; index += 1) {
36 ancestors.push(parts.slice(0, index).join("/"));
37 }
38 return ancestors;
40​
41const FileTreeRow = memo(function FileTreeRow(props: {
42 readonly item: VisibleFileTreeNode;
43 readonly selected: boolean;
44 readonly expanded: boolean;
45 readonly loaded: boolean;
46 readonly loading: boolean;
47 readonly onPressDirectory: (path: string, expand: boolean) => void;
48 readonly onPreviewFile?: (path: string) => void;
49 readonly onPressFile: (path: string) => void;
50}) {
51 const { node, depth } = props.item;
52​
53 return (
54 <Pressable
55 accessibilityRole="button"
56 accessibilityLabel={node.path}
57 onPressIn={() => {
58 if (node.kind === "file") {
59 props.onPreviewFile?.(node.path);
60 }
61 }}
62 onPress={() => {
63 if (node.kind === "directory") {
64 props.onPressDirectory(node.path, !props.expanded);
65 return;
66 }
67 props.onPressFile(node.path);
68 }}
69 className={cn(
70 "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
71 props.selected && "bg-subtle-strong",
72 )}
73 style={{ paddingLeft: 8 + depth * 18 }}
74 >
75 {node.kind === "directory" ? (
76 <SymbolView
77 name={props.expanded ? "chevron.down" : "chevron.right"}
78 size={12}
79 tintColorClassName="accent-icon-muted"
80 type="monochrome"
81 />
82 ) : (
83 <View className="w-3" />
84 )}
85 <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
86 <Text
87 className={cn(
88 "min-w-0 flex-1 text-sm leading-normal",
89 props.selected
90 ? "font-t3-bold text-foreground"
91 : node.ignored
92 ? "font-t3-medium text-foreground-tertiary"
93 : "font-t3-medium text-foreground-secondary",
94 )}
95 numberOfLines={1}
96 >
97 {node.name}
98 </Text>
99 {node.kind === "directory" && props.expanded && props.loading ? (
100 <ActivityIndicator size="small" accessibilityLabel={`Loading ${node.name}`} />
101 ) : node.kind === "directory" && props.loaded ? (
102 <Text className="text-2xs font-t3-medium text-foreground-tertiary">
103 {node.children.length}
104 </Text>
105 ) : null}
106 </Pressable>
107 );
108});
109​
110export function FileTreeBrowser(props: {
111 readonly entries: ReadonlyArray<ProjectEntry>;
112 readonly error: string | null;
113 readonly isPending: boolean;
114 readonly isRefreshing: boolean;
115 readonly searchQuery: string;
116 readonly searchTruncated: boolean;
117 readonly selectedPath: string | null;
118 readonly loadedDirectories: ReadonlySet<string>;
119 readonly loadingDirectories: ReadonlySet<string>;
120 readonly onLoadDirectory: (path: string) => void;
121 readonly onPreviewFile?: (path: string) => void;
122 readonly onRefresh: () => void;
123 readonly onSelectFile: (path: string) => void;
124}) {
125 const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
126 const [pendingSelection, setPendingSelection] = useState<{
127 readonly path: string;
128 readonly selectedPathAtPress: string | null;
129 } | null>(null);
130 const insets = useSafeAreaInsets();
131 // Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
132 // observed adjustedContentInset bottom (~102) seen in the native trace.
133 const headerInset = Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT : 0;
134 const {
135 onLoadDirectory,
136 onPreviewFile,
137 onSelectFile,
138 loadedDirectories,
139 loadingDirectories,
140 selectedPath: controlledSelectedPath,
141 } = props;
142 const controlledSelectedPathRef = useRef(controlledSelectedPath);
143 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
144 controlledSelectedPathRef.current = controlledSelectedPath;
145​
146 const selectedPath =
147 pendingSelection?.selectedPathAtPress === controlledSelectedPath
148 ? pendingSelection.path
149 : controlledSelectedPath;
150 const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
151 const visibleNodes = useMemo(
152 () =>
153 flattenFileTree({
154 nodes: tree,
155 expanded: expandedPaths,
156 searchQuery: props.searchQuery,
157 }),
158 [expandedPaths, props.searchQuery, tree],
159 );
160​
161 useEffect(() => {
162 if (!controlledSelectedPath) {
163 return;
164 }
165 setExpandedPaths((current) => {
166 const ancestors = ancestorPaths(controlledSelectedPath);
167 if (ancestors.every((ancestor) => current.has(ancestor))) {
168 return current;
169 }
170 const next = new Set(current);
171 for (const ancestor of ancestors) {
172 next.add(ancestor);
173 }
174 return next;
175 });
176 }, [controlledSelectedPath]);
177​
178 useEffect(() => {
179 for (const path of expandedPaths) onLoadDirectory(path);
180 }, [expandedPaths, onLoadDirectory]);
181​
182 useEffect(
183 () => () => {
184 if (pendingSelectionTimeoutRef.current !== null) {
185 clearTimeout(pendingSelectionTimeoutRef.current);
186 }
187 },
188 [],
189 );
190​
191 const toggleDirectory = useCallback(
192 (path: string, expand: boolean) => {
193 if (expand) onLoadDirectory(path);
194 setExpandedPaths((current) => {
195 const next = new Set(current);
196 if (next.has(path)) {
197 next.delete(path);
198 } else {
199 next.add(path);
200 }
201 return next;
202 });
203 },
204 [onLoadDirectory],
205 );
206 const handleSelectFile = useCallback(
207 (path: string) => {
208 if (pendingSelectionTimeoutRef.current !== null) {
209 clearTimeout(pendingSelectionTimeoutRef.current);
210 }
211 setPendingSelection({
212 path,
213 selectedPathAtPress: controlledSelectedPathRef.current,
214 });
215 pendingSelectionTimeoutRef.current = setTimeout(() => {
216 pendingSelectionTimeoutRef.current = null;
217 setPendingSelection((current) => (current?.path === path ? null : current));
218 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
219 onSelectFile(path);
220 },
221 [onSelectFile],
222 );
223 const renderItem = useCallback(
224 ({ item }: { readonly item: VisibleFileTreeNode }) => (
225 <FileTreeRow
226 item={item}
227 selected={item.node.kind === "file" && item.node.path === selectedPath}
228 expanded={expandedPaths.has(item.node.path)}
229 loaded={loadedDirectories.has(item.node.path)}
230 loading={loadingDirectories.has(item.node.path)}
231 onPressDirectory={toggleDirectory}
232 onPreviewFile={onPreviewFile}
233 onPressFile={handleSelectFile}
234 />
235 ),
236 [
237 expandedPaths,
238 handleSelectFile,
239 onPreviewFile,
240 loadedDirectories,
241 loadingDirectories,
242 selectedPath,
243 toggleDirectory,
244 ],
245 );
246​
247 const extraData = useMemo(
248 () => ({ expandedPaths, loadedDirectories, loadingDirectories, selectedPath }),
249 [expandedPaths, loadedDirectories, loadingDirectories, selectedPath],
250 );
251​
252 // UIKit owns the header inset on every supported iOS version. Keep the
253 // list as direct screen content so automatic inset adjustment can find it.
254 return (
255 <LegendList
256 contentInsetStartAdjustment={headerInset}
257 alwaysBounceVertical
258 className="flex-1"
259 data={visibleNodes}
260 keyExtractor={(item) => item.node.path}
261 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
262 scrollIndicatorInsets={
263 Platform.OS === "ios" ? { top: headerInset, left: 0, right: 0, bottom: 0 } : undefined
264 }
265 keyboardDismissMode="on-drag"
266 keyboardShouldPersistTaps="handled"
267 estimatedItemSize={42}
268 recycleItems
269 maintainVisibleContentPosition
270 extraData={extraData}
271 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
272 refreshControl={
273 <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
274 }
275 renderItem={renderItem}
276 ListHeaderComponent={
277 <>
278 {props.error && props.entries.length > 0 ? (
279 <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
280 {props.error}
281 </Text>
282 ) : null}
283 {props.searchTruncated ? (
284 <Text className="mx-4 my-2 text-xs text-foreground-muted">
285 More search results available. Refine your search to see them.
286 </Text>
287 ) : null}
288 </>
289 }
290 ListEmptyComponent={
291 <View className="px-4 py-5">
292 {props.error && props.entries.length === 0 ? (
293 <>
294 <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
295 <Text
296 accessibilityRole="alert"
297 className="mt-1 text-xs leading-normal text-foreground-muted"
298 >
299 {props.error}
300 </Text>
301 <Pressable
302 accessibilityRole="button"
303 onPress={props.onRefresh}
304 disabled={props.isPending}
305 className="mt-3 min-h-11 self-start justify-center rounded-full bg-subtle px-4 active:opacity-70 disabled:opacity-50"
306 >
307 <Text className="text-sm font-t3-medium text-foreground">Try again</Text>
308 </Pressable>
309 </>
310 ) : props.isPending ? (
311 <ActivityIndicator size="small" />
312 ) : (
313 <>
314 <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
315 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
316 {props.searchQuery.trim().length > 0
317 ? "Try a different search."
318 : "The workspace is empty."}
319 </Text>
320 </>
321 )}
322 </View>
323 }
324 />
325 );