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