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