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