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 { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
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 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 : "font-t3-medium text-foreground-secondary",
93 )}
94 numberOfLines={1}
95 >
96 {node.name}
97 </Text>
98 {node.kind === "directory" ? (
99 <Text className="text-2xs font-t3-medium text-foreground-tertiary">
100 {node.children.length}
101 </Text>
102 ) : null}
103 </Pressable>
104 );
105});
106
107export function FileTreeBrowser(props: {
108 readonly entries: ReadonlyArray<ProjectEntry>;
109 readonly error: string | null;
110 readonly isPending: boolean;
111 readonly searchQuery: string;
112 readonly selectedPath: string | null;
113 readonly onPreviewFile?: (path: string) => void;
114 readonly onRefresh: () => void;
115 readonly onSelectFile: (path: string) => void;
116}) {
117 const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
118 const [pendingSelection, setPendingSelection] = useState<{
119 readonly path: string;
120 readonly selectedPathAtPress: string | null;
121 } | null>(null);
122 const insets = useSafeAreaInsets();
123 // Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
124 // observed adjustedContentInset bottom (~102) seen in the native trace.
125 const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + IOS_NAV_BAR_HEIGHT : 0;
126 const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
127 const controlledSelectedPathRef = useRef(controlledSelectedPath);
128 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
129 controlledSelectedPathRef.current = controlledSelectedPath;
130
131 const selectedPath =
132 pendingSelection?.selectedPathAtPress === controlledSelectedPath
133 ? pendingSelection.path
134 : controlledSelectedPath;
135 const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
136 const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
137 const visibleNodes = useMemo(
138 () =>
139 flattenFileTree({
140 nodes: tree,
141 expanded: expandedPaths,
142 searchQuery: props.searchQuery,
143 }),
144 [expandedPaths, props.searchQuery, tree],
145 );
146
147 useEffect(() => {
148 setExpandedPaths((current) => {
149 if (current.size > 0 || defaultExpanded.size === 0) {
150 return current;
151 }
152 return new Set(defaultExpanded);
153 });
154 }, [defaultExpanded]);
155
156 useEffect(() => {
157 if (!controlledSelectedPath) {
158 return;
159 }
160 setExpandedPaths((current) => {
161 const ancestors = ancestorPaths(controlledSelectedPath);
162 if (ancestors.every((ancestor) => current.has(ancestor))) {
163 return current;
164 }
165 const next = new Set(current);
166 for (const ancestor of ancestors) {
167 next.add(ancestor);
168 }
169 return next;
170 });
171 }, [controlledSelectedPath]);
172
173 useEffect(
174 () => () => {
175 if (pendingSelectionTimeoutRef.current !== null) {
176 clearTimeout(pendingSelectionTimeoutRef.current);
177 }
178 },
179 [],
180 );
181
182 const toggleDirectory = useCallback((path: string) => {
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 = useCallback(
194 (path: string) => {
195 if (pendingSelectionTimeoutRef.current !== null) {
196 clearTimeout(pendingSelectionTimeoutRef.current);
197 }
198 setPendingSelection({
199 path,
200 selectedPathAtPress: controlledSelectedPathRef.current,
201 });
202 pendingSelectionTimeoutRef.current = setTimeout(() => {
203 pendingSelectionTimeoutRef.current = null;
204 setPendingSelection((current) => (current?.path === path ? null : current));
205 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
206 onSelectFile(path);
207 },
208 [onSelectFile],
209 );
210 const renderItem = useCallback(
211 ({ item }: { readonly item: VisibleFileTreeNode }) => (
212 <FileTreeRow
213 item={item}
214 selected={item.node.kind === "file" && item.node.path === selectedPath}
215 expanded={expandedPaths.has(item.node.path)}
216 onPressDirectory={toggleDirectory}
217 onPreviewFile={onPreviewFile}
218 onPressFile={handleSelectFile}
219 />
220 ),
221 [expandedPaths, handleSelectFile, onPreviewFile, selectedPath, toggleDirectory],
222 );
223
224 if (props.error && props.entries.length === 0) {
225 return (
226 <View className="flex-1 bg-sheet px-4 py-5">
227 <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
228 <Text className="mt-1 text-xs leading-normal text-foreground-muted">{props.error}</Text>
229 </View>
230 );
231 }
232
233 // SPIKE: render the FlatList as the screen's DIRECT content (no wrapping View), and
234 // mirror the Home ScrollView exactly — `contentInsetAdjustmentBehavior: "automatic"`
235 // with NO manual contentInset. iOS only applies the nav-bar top inset + scroll-edge
236 // blur to a scroll view in the screen's primary position; a scroll view buried in
237 // flex-1 Views is ignored, which is why the tree rendered under the header with no blur.
238 return (
239 <FlatList
240 className="flex-1"
241 data={visibleNodes}
242 keyExtractor={(item) => item.node.path}
243 contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
244 scrollIndicatorInsets={
245 NATIVE_LIQUID_GLASS_SUPPORTED
246 ? { top: headerInset, left: 0, right: 0, bottom: 0 }
247 : undefined
248 }
249 keyboardDismissMode="on-drag"
250 keyboardShouldPersistTaps="handled"
251 initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
252 maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
253 updateCellsBatchingPeriod={16}
254 windowSize={5}
255 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
256 refreshControl={<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />}
257 renderItem={renderItem}
258 ListEmptyComponent={
259 <View className="px-4 py-5">
260 {props.isPending ? (
261 <ActivityIndicator size="small" />
262 ) : (
263 <>
264 <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
265 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
266 {props.searchQuery.trim().length > 0
267 ? "Try a different search."
268 : "The workspace file index is empty."}
269 </Text>
270 </>
271 )}
272 </View>
273 }
274 />
275 );
276}