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
35const FileTreeRow = function FileTreeRow(props: {
36 readonly item: VisibleFileTreeNode;
37 readonly selected: boolean;
38 readonly expanded: boolean;
39 readonly loading: boolean;
40 readonly onPressDirectory: (path: string, expand: boolean) => void;
41 readonly onPreviewFile?: (path: string) => void;
42 readonly onPressFile: (path: string) => void;
43}) {
44 const { node, depth } = props.item;
45
46 return (
47 <Pressable
48 accessibilityRole="button"
49 accessibilityLabel={node.path}
50 accessibilityState={{ selected: props.selected }}
51 onPressIn={() => {
52 if (node.kind === "file") {
53 props.onPreviewFile?.(node.path);
54 }
55 }}
56 onPress={() => {
57 if (node.kind === "directory") {
58 props.onPressDirectory(node.path, !props.expanded);
59 return;
60 }
61 props.onPressFile(node.path);
62 }}
63 className={cn(
64 "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
65 props.selected && "bg-thread-selected",
66 )}
67 style={{ paddingLeft: 8 + depth * 18 }}
68 >
69 {node.kind === "directory" ? (
70 <SymbolView
71 name={props.expanded ? "chevron.down" : "chevron.right"}
72 size={12}
73 tintColorClassName="accent-icon-muted"
74 type="monochrome"
75 />
76 ) : (
77 <View className="w-3" />
78 )}
79 <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
80 <Text
81 className={cn(
82 "min-w-0 flex-1 text-sm leading-normal",
83 props.selected
84 ? "font-t3-bold text-thread-selected-foreground"
85 : node.ignored
86 ? "font-t3-medium text-foreground-tertiary"
87 : "font-t3-medium text-foreground-secondary",
88 )}
89 numberOfLines={1}
90 >
91 {node.name}
92 </Text>
93 {node.kind === "directory" && props.expanded && props.loading ? (
94 <AppActivityIndicator size="small" accessibilityLabel={`Loading ${node.name}`} />
95 ) : null}
96 </Pressable>
97 );
98};
99
100export function FileTreeBrowser(props: {
101 readonly revealSelection: (path: string | null) => void;
102 readonly expandedPaths: ReadonlySet<string>;
103 readonly setExpandedPaths: (
104 update: (current: ReadonlySet<string>) => ReadonlySet<string>,
105 ) => void;
106 readonly entries: ReadonlyArray<ProjectEntry>;
107 readonly error: string | null;
108 readonly isPending: boolean;
109 readonly isRefreshing: boolean;
110 readonly searchQuery: string;
111 readonly searchResultPaths: ReadonlySet<string> | null;
112 readonly searchTruncated: boolean;
113 readonly selectedPath: string | null;
114 readonly loadingDirectories: ReadonlySet<string>;
115 readonly onLoadDirectory: (path: string, retry?: boolean) => void;
116 readonly onPreviewFile?: (path: string) => void;
117 readonly onRefresh: () => void;
118 readonly onSelectFile: (path: string) => void;
119}) {
120 const { expandedPaths, setExpandedPaths } = props;
121 const [pendingSelection, setPendingSelection] = useState<{
122 readonly path: string;
123 readonly selectedPathAtPress: string | null;
124 } | null>(null);
125 const insets = useSafeAreaInsets();
126 const columnMetrics = useNativeColumnLayoutMetrics();
127 const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
128 const {
129 onLoadDirectory,
130 onPreviewFile,
131 onSelectFile,
132 loadingDirectories,
133 selectedPath: controlledSelectedPath,
134 } = props;
135 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
136
137 const selectedPath =
138 pendingSelection?.selectedPathAtPress === controlledSelectedPath
139 ? pendingSelection.path
140 : controlledSelectedPath;
141 const tree = cachedFileTree(props.entries);
142 const visibleNodes = flattenFileTree({
143 nodes: tree,
144 expanded: expandedPaths,
145 searchResultPaths: props.searchResultPaths,
146 });
147
148 const { revealSelection } = props;
149 useEffect(() => {
150 revealSelection(controlledSelectedPath);
151 }, [controlledSelectedPath, revealSelection]);
152
153 useEffect(() => {
154 const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
155 for (const node of nodes) {
156 if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
157 onLoadDirectory(node.path);
158 visit(node.children);
159 }
160 };
161 visit(tree);
162 }, [tree, expandedPaths, onLoadDirectory]);
163
164 useEffect(
165 () => () => {
166 if (pendingSelectionTimeoutRef.current !== null) {
167 clearTimeout(pendingSelectionTimeoutRef.current);
168 }
169 },
170 [],
171 );
172
173 const toggleDirectory = (path: string, expand: boolean) => {
174 if (expand) onLoadDirectory(path, true);
175 setExpandedPaths((current) => {
176 const next = new Set(current);
177 if (next.has(path)) {
178 next.delete(path);
179 } else {
180 next.add(path);
181 }
182 return next;
183 });
184 };
185 const handleSelectFile = (path: string) => {
186 if (pendingSelectionTimeoutRef.current !== null) {
187 clearTimeout(pendingSelectionTimeoutRef.current);
188 }
189 setPendingSelection({
190 path,
191 selectedPathAtPress: controlledSelectedPath,
192 });
193 pendingSelectionTimeoutRef.current = setTimeout(() => {
194 pendingSelectionTimeoutRef.current = null;
195 setPendingSelection((current) => (current?.path === path ? null : current));
196 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
197 onSelectFile(path);
198 };
199 const renderItem = ({ item }: { readonly item: VisibleFileTreeNode }) => (
200 <FileTreeRow
201 item={item}
202 selected={item.node.kind === "file" && item.node.path === selectedPath}
203 expanded={expandedPaths.has(item.node.path)}
204 loading={loadingDirectories.has(item.node.path)}
205 onPressDirectory={toggleDirectory}
206 onPreviewFile={onPreviewFile}
207 onPressFile={handleSelectFile}
208 />
209 );
210
211 const extraData = { expandedPaths, loadingDirectories, selectedPath };
212
213 // Keep the list as direct screen content so UIKit can apply header insets.
214 return (
215 <LegendList
216 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
217 contentInsetStartAdjustment={headerInset}
218 alwaysBounceVertical
219 className="flex-1"
220 data={visibleNodes}
221 keyExtractor={(item) => item.node.path}
222 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
223 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
224 keyboardDismissMode="on-drag"
225 keyboardShouldPersistTaps="handled"
226 estimatedItemSize={42}
227 recycleItems
228 maintainVisibleContentPosition
229 extraData={extraData}
230 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
231 refreshControl={
232 <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
233 }
234 renderItem={renderItem}
235 ListHeaderComponent={
236 <>
237 {props.error && props.entries.length > 0 ? (
238 <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
239 {props.error}
240 </Text>
241 ) : null}
242 {props.searchTruncated ? (
243 <Text className="mx-4 my-2 text-xs text-foreground-muted">
244 More search results available. Refine your search to see them.
245 </Text>
246 ) : null}
247 </>
248 }
249 ListEmptyComponent={
250 <View className="px-4 py-5">
251 {props.error && props.entries.length === 0 ? (
252 <>
253 <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
254 <Text
255 accessibilityRole="alert"
256 className="mt-1 text-xs leading-normal text-foreground-muted"
257 >
258 {props.error}
259 </Text>
260 <View className="mt-3">
261 <Button
262 label="Try again"
263 tone="secondary"
264 onPress={props.onRefresh}
265 disabled={props.isPending}
266 />
267 </View>
268 </>
269 ) : props.isPending ? (
270 <AppActivityIndicator size="small" />
271 ) : (
272 <>
273 <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
274 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
275 {props.searchQuery.trim().length > 0
276 ? "Try a different search."
277 : "The workspace is empty."}
278 </Text>
279 </>
280 )}
281 </View>
282 }
283 />
284 );
285}