Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { LegendList } from "@legendapp/list/react-native";
3import type { ProjectEntry } from "@t3tools/contracts";
4import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
5import { SymbolView } from "../../components/ui/AppSymbol";
6import { useEffect, useRef, useState } from "react";
7import { Platform, Pressable, RefreshControl, View } from "react-native";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9
10import { AppText as Text } from "../../components/ui/AppText";
11import { PierreEntryIcon } from "../../components/PierreEntryIcon";
12import { cn } from "../../lib/cn";
13import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
14import {
15 buildFileTree,
16 flattenFileTree,
17 type FileTreeNode,
18 type VisibleFileTreeNode,
19} from "./fileTree";
20
21const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
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;
32}
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;
41}
42
43const FileTreeRow = function FileTreeRow(props: {
44 readonly item: VisibleFileTreeNode;
45 readonly selected: boolean;
46 readonly expanded: boolean;
47 readonly loading: boolean;
48 readonly onPressDirectory: (path: string, expand: boolean) => 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 accessibilityState={{ selected: props.selected }}
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, !props.expanded);
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-thread-selected",
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 tintColorClassName="accent-icon-muted"
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-thread-selected-foreground"
93 : node.ignored
94 ? "font-t3-medium text-foreground-tertiary"
95 : "font-t3-medium text-foreground-secondary",
96 )}
97 numberOfLines={1}
98 >
99 {node.name}
100 </Text>
101 {node.kind === "directory" && props.expanded && props.loading ? (
102 <AppActivityIndicator size="small" accessibilityLabel={`Loading ${node.name}`} />
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 isRefreshing: boolean;
113 readonly searchQuery: string;
114 readonly searchResultPaths: ReadonlySet<string> | null;
115 readonly searchTruncated: boolean;
116 readonly selectedPath: string | null;
117 readonly loadingDirectories: ReadonlySet<string>;
118 readonly onLoadDirectory: (path: string) => void;
119 readonly onPreviewFile?: (path: string) => void;
120 readonly onRefresh: () => void;
121 readonly onSelectFile: (path: string) => void;
122}) {
123 const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
124 const [pendingSelection, setPendingSelection] = useState<{
125 readonly path: string;
126 readonly selectedPathAtPress: string | null;
127 } | null>(null);
128 const insets = useSafeAreaInsets();
129 const columnMetrics = useNativeColumnLayoutMetrics();
130 const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
131 const {
132 onLoadDirectory,
133 onPreviewFile,
134 onSelectFile,
135 loadingDirectories,
136 selectedPath: controlledSelectedPath,
137 } = props;
138 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
139
140 const selectedPath =
141 pendingSelection?.selectedPathAtPress === controlledSelectedPath
142 ? pendingSelection.path
143 : controlledSelectedPath;
144 const tree = cachedFileTree(props.entries);
145 const visibleNodes = flattenFileTree({
146 nodes: tree,
147 expanded: expandedPaths,
148 searchResultPaths: props.searchResultPaths,
149 });
150
151 useEffect(() => {
152 if (!controlledSelectedPath) {
153 return;
154 }
155 setExpandedPaths((current) => {
156 const ancestors = ancestorPaths(controlledSelectedPath);
157 if (ancestors.every((ancestor) => current.has(ancestor))) {
158 return current;
159 }
160 const next = new Set(current);
161 for (const ancestor of ancestors) {
162 next.add(ancestor);
163 }
164 return next;
165 });
166 }, [controlledSelectedPath]);
167
168 useEffect(() => {
169 for (const path of expandedPaths) onLoadDirectory(path);
170 }, [expandedPaths, onLoadDirectory]);
171
172 useEffect(
173 () => () => {
174 if (pendingSelectionTimeoutRef.current !== null) {
175 clearTimeout(pendingSelectionTimeoutRef.current);
176 }
177 },
178 [],
179 );
180
181 const toggleDirectory = (path: string, expand: boolean) => {
182 if (expand) onLoadDirectory(path);
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 = (path: string) => {
194 if (pendingSelectionTimeoutRef.current !== null) {
195 clearTimeout(pendingSelectionTimeoutRef.current);
196 }
197 setPendingSelection({
198 path,
199 selectedPathAtPress: controlledSelectedPath,
200 });
201 pendingSelectionTimeoutRef.current = setTimeout(() => {
202 pendingSelectionTimeoutRef.current = null;
203 setPendingSelection((current) => (current?.path === path ? null : current));
204 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
205 onSelectFile(path);
206 };
207 const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (
208 <FileTreeRow
209 item={item}
210 selected={item.node.kind === "file" && item.node.path === selectedPath}
211 expanded={expandedPaths.has(item.node.path)}
212 loading={loadingDirectories.has(item.node.path)}
213 onPressDirectory={toggleDirectory}
214 onPreviewFile={onPreviewFile}
215 onPressFile={handleSelectFile}
216 />
217 );
218
219 const extraData = { expandedPaths, loadingDirectories, selectedPath };
220
221 // UIKit owns the header inset on every supported iOS version. Keep the
222 // list as direct screen content so automatic inset adjustment can find it.
223 return (
224 <LegendList
225 contentInsetStartAdjustment={headerInset}
226 alwaysBounceVertical
227 className="flex-1"
228 data={visibleNodes}
229 keyExtractor={(item) => item.node.path}
230 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
231 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
232 keyboardDismissMode="on-drag"
233 keyboardShouldPersistTaps="handled"
234 estimatedItemSize={42}
235 recycleItems
236 maintainVisibleContentPosition
237 extraData={extraData}
238 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
239 refreshControl={
240 <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
241 }
242 renderItem={renderItem}
243 ListHeaderComponent={
244 <>
245 {props.error && props.entries.length > 0 ? (
246 <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
247 {props.error}
248 </Text>
249 ) : null}
250 {props.searchTruncated ? (
251 <Text className="mx-4 my-2 text-xs text-foreground-muted">
252 More search results available. Refine your search to see them.
253 </Text>
254 ) : null}
255 </>
256 }
257 ListEmptyComponent={
258 <View className="px-4 py-5">
259 {props.error && props.entries.length === 0 ? (
260 <>
261 <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
262 <Text
263 accessibilityRole="alert"
264 className="mt-1 text-xs leading-normal text-foreground-muted"
265 >
266 {props.error}
267 </Text>
268 <View className="mt-3">
269 <Button
270 label="Try again"
271 tone="secondary"
272 onPress={props.onRefresh}
273 disabled={props.isPending}
274 />
275 </View>
276 </>
277 ) : props.isPending ? (
278 <AppActivityIndicator size="small" />
279 ) : (
280 <>
281 <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
282 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
283 {props.searchQuery.trim().length > 0
284 ? "Try a different search."
285 : "The workspace is empty."}
286 </Text>
287 </>
288 )}
289 </View>
290 }
291 />
292 );
293}