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