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