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 { 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 {
126 onLoadDirectory,
127 onPreviewFile,
128 onSelectFile,
129 loadingDirectories,
130 selectedPath: controlledSelectedPath,
131 } = props;
132 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
133
134 const selectedPath =
135 pendingSelection?.selectedPathAtPress === controlledSelectedPath
136 ? pendingSelection.path
137 : controlledSelectedPath;
138 const tree = cachedFileTree(props.entries);
139 const visibleNodes = flattenFileTree({
140 nodes: tree,
141 expanded: expandedPaths,
142 searchResultPaths: props.searchResultPaths,
143 });
144
145 const { revealSelection } = props;
146 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands the controlled selection's ancestor directories in the file tree state
147 useEffect(() => {
148 revealSelection(controlledSelectedPath);
149 }, [controlledSelectedPath, revealSelection]);
150
151 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests listings for expanded directories that are not yet loaded or pending
152 useEffect(() => {
153 const visit = (nodes: ReadonlyArray<FileTreeNode>) => {
154 for (const node of nodes) {
155 if (node.kind !== "directory" || !expandedPaths.has(node.path)) continue;
156 onLoadDirectory(node.path);
157 visit(node.children);
158 }
159 };
160 visit(tree);
161 }, [tree, expandedPaths, onLoadDirectory]);
162
163 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the pending selection timer on unmount
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={NativeScrollView}
217 contentInsetStartAdjustment={headerInset}
218 alwaysBounceVertical
219 className="flex-1"
220 data={visibleNodes}
221 keyExtractor={(item) => item.node.path}
222 contentInsetAdjustmentBehavior="automatic"
223 automaticallyAdjustsScrollIndicatorInsets
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}