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

FileTreeBrowser.tsx

313 lines10.5 KB

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