Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FileTreeBrowser.tsx

314 lines10.3 KB

1import { LegendList } from "@legendapp/list/react-native";
2import type { ProjectEntry } from "@t3tools/contracts";
3import { SymbolView } from "../../components/AppSymbol";
4import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
5import { ActivityIndicator, Platform, Pressable, RefreshControl, View } from "react-native";
6import { useSafeAreaInsets } from "react-native-safe-area-context";
7​
8import { AppText as Text } from "../../components/AppText";
9import { PierreEntryIcon } from "../../components/PierreEntryIcon";
10import { cn } from "../../lib/cn";
11import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
12import {
13 buildFileTree,
14 flattenFileTree,
15 type FileTreeNode,
16 type VisibleFileTreeNode,
17} from "./fileTree";
18​
19const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
20const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
21​
22function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
23 const cached = fileTreeCache.get(entries);
24 if (cached !== undefined) {
25 return cached;
26 }
27 const tree = buildFileTree(entries);
28 fileTreeCache.set(entries, tree);
29 return tree;
31​
32function ancestorPaths(path: string): ReadonlyArray<string> {
33 const parts = path.split("/").filter(Boolean);
34 const ancestors: string[] = [];
35 for (let index = 1; index < parts.length; index += 1) {
36 ancestors.push(parts.slice(0, index).join("/"));
37 }
38 return ancestors;
40​
41const FileTreeRow = memo(function FileTreeRow(props: {
42 readonly item: VisibleFileTreeNode;
43 readonly selected: boolean;
44 readonly expanded: boolean;
45 readonly loading: boolean;
46 readonly onPressDirectory: (path: string, expand: boolean) => void;
47 readonly onPreviewFile?: (path: string) => void;
48 readonly onPressFile: (path: string) => void;
49}) {
50 const { node, depth } = props.item;
51​
52 return (
53 <Pressable
54 accessibilityRole="button"
55 accessibilityLabel={node.path}
56 onPressIn={() => {
57 if (node.kind === "file") {
58 props.onPreviewFile?.(node.path);
59 }
60 }}
61 onPress={() => {
62 if (node.kind === "directory") {
63 props.onPressDirectory(node.path, !props.expanded);
64 return;
65 }
66 props.onPressFile(node.path);
67 }}
68 className={cn(
69 "mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
70 props.selected && "bg-subtle-strong",
71 )}
72 style={{ paddingLeft: 8 + depth * 18 }}
73 >
74 {node.kind === "directory" ? (
75 <SymbolView
76 name={props.expanded ? "chevron.down" : "chevron.right"}
77 size={12}
78 tintColorClassName="accent-icon-muted"
79 type="monochrome"
80 />
81 ) : (
82 <View className="w-3" />
83 )}
84 <PierreEntryIcon path={node.path} kind={node.kind} size={17} />
85 <Text
86 className={cn(
87 "min-w-0 flex-1 text-sm leading-normal",
88 props.selected
89 ? "font-t3-bold text-foreground"
90 : node.ignored
91 ? "font-t3-medium text-foreground-tertiary"
92 : "font-t3-medium text-foreground-secondary",
93 )}
94 numberOfLines={1}
95 >
96 {node.name}
97 </Text>
98 {node.kind === "directory" && props.expanded && props.loading ? (
99 <ActivityIndicator size="small" accessibilityLabel={`Loading ${node.name}`} />
100 ) : null}
101 </Pressable>
102 );
103});
104​
105export function FileTreeBrowser(props: {
106 readonly entries: ReadonlyArray<ProjectEntry>;
107 readonly error: string | null;
108 readonly isPending: boolean;
109 readonly isRefreshing: boolean;
110 readonly searchQuery: string;
111 readonly searchTruncated: boolean;
112 readonly selectedPath: string | null;
113 readonly loadingDirectories: ReadonlySet<string>;
114 readonly onLoadDirectory: (path: string) => void;
115 readonly onPreviewFile?: (path: string) => void;
116 readonly onRefresh: () => void;
117 readonly onSelectFile: (path: string) => void;
118}) {
119 const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
120 const [pendingSelection, setPendingSelection] = useState<{
121 readonly path: string;
122 readonly selectedPathAtPress: string | null;
123 } | null>(null);
124 const insets = useSafeAreaInsets();
125 const columnMetrics = useNativeColumnLayoutMetrics();
126 const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
127 const {
128 onLoadDirectory,
129 onPreviewFile,
130 onSelectFile,
131 loadingDirectories,
132 selectedPath: controlledSelectedPath,
133 } = props;
134 const controlledSelectedPathRef = useRef(controlledSelectedPath);
135 const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
136 controlledSelectedPathRef.current = controlledSelectedPath;
137​
138 const selectedPath =
139 pendingSelection?.selectedPathAtPress === controlledSelectedPath
140 ? pendingSelection.path
141 : controlledSelectedPath;
142 const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
143 const visibleNodes = useMemo(
144 () =>
145 flattenFileTree({
146 nodes: tree,
147 expanded: expandedPaths,
148 searchQuery: props.searchQuery,
149 }),
150 [expandedPaths, props.searchQuery, tree],
151 );
152​
153 useEffect(() => {
154 if (!controlledSelectedPath) {
155 return;
156 }
157 setExpandedPaths((current) => {
158 const ancestors = ancestorPaths(controlledSelectedPath);
159 if (ancestors.every((ancestor) => current.has(ancestor))) {
160 return current;
161 }
162 const next = new Set(current);
163 for (const ancestor of ancestors) {
164 next.add(ancestor);
165 }
166 return next;
167 });
168 }, [controlledSelectedPath]);
169​
170 useEffect(() => {
171 for (const path of expandedPaths) onLoadDirectory(path);
172 }, [expandedPaths, onLoadDirectory]);
173​
174 useEffect(
175 () => () => {
176 if (pendingSelectionTimeoutRef.current !== null) {
177 clearTimeout(pendingSelectionTimeoutRef.current);
178 }
179 },
180 [],
181 );
182​
183 const toggleDirectory = useCallback(
184 (path: string, expand: boolean) => {
185 if (expand) onLoadDirectory(path);
186 setExpandedPaths((current) => {
187 const next = new Set(current);
188 if (next.has(path)) {
189 next.delete(path);
190 } else {
191 next.add(path);
192 }
193 return next;
194 });
195 },
196 [onLoadDirectory],
197 );
198 const handleSelectFile = useCallback(
199 (path: string) => {
200 if (pendingSelectionTimeoutRef.current !== null) {
201 clearTimeout(pendingSelectionTimeoutRef.current);
202 }
203 setPendingSelection({
204 path,
205 selectedPathAtPress: controlledSelectedPathRef.current,
206 });
207 pendingSelectionTimeoutRef.current = setTimeout(() => {
208 pendingSelectionTimeoutRef.current = null;
209 setPendingSelection((current) => (current?.path === path ? null : current));
210 }, OPTIMISTIC_SELECTION_TIMEOUT_MS);
211 onSelectFile(path);
212 },
213 [onSelectFile],
214 );
215 const renderItem = useCallback(
216 ({ item }: { readonly item: VisibleFileTreeNode }) => (
217 <FileTreeRow
218 item={item}
219 selected={item.node.kind === "file" && item.node.path === selectedPath}
220 expanded={expandedPaths.has(item.node.path)}
221 loading={loadingDirectories.has(item.node.path)}
222 onPressDirectory={toggleDirectory}
223 onPreviewFile={onPreviewFile}
224 onPressFile={handleSelectFile}
225 />
226 ),
227 [
228 expandedPaths,
229 handleSelectFile,
230 onPreviewFile,
231 loadingDirectories,
232 selectedPath,
233 toggleDirectory,
234 ],
235 );
236​
237 const extraData = useMemo(
238 () => ({ expandedPaths, loadingDirectories, selectedPath }),
239 [expandedPaths, loadingDirectories, selectedPath],
240 );
241​
242 // UIKit owns the header inset on every supported iOS version. Keep the
243 // list as direct screen content so automatic inset adjustment can find it.
244 return (
245 <LegendList
246 contentInsetStartAdjustment={headerInset}
247 alwaysBounceVertical
248 className="flex-1"
249 data={visibleNodes}
250 keyExtractor={(item) => item.node.path}
251 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
252 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
253 keyboardDismissMode="on-drag"
254 keyboardShouldPersistTaps="handled"
255 estimatedItemSize={42}
256 recycleItems
257 maintainVisibleContentPosition
258 extraData={extraData}
259 contentContainerStyle={{ paddingTop: 8, paddingBottom: 8 }}
260 refreshControl={
261 <RefreshControl refreshing={props.isRefreshing} onRefresh={props.onRefresh} />
262 }
263 renderItem={renderItem}
264 ListHeaderComponent={
265 <>
266 {props.error && props.entries.length > 0 ? (
267 <Text accessibilityRole="alert" className="mx-4 my-2 text-xs text-foreground-muted">
268 {props.error}
269 </Text>
270 ) : null}
271 {props.searchTruncated ? (
272 <Text className="mx-4 my-2 text-xs text-foreground-muted">
273 More search results available. Refine your search to see them.
274 </Text>
275 ) : null}
276 </>
277 }
278 ListEmptyComponent={
279 <View className="px-4 py-5">
280 {props.error && props.entries.length === 0 ? (
281 <>
282 <Text className="text-sm font-t3-bold text-foreground">Files unavailable</Text>
283 <Text
284 accessibilityRole="alert"
285 className="mt-1 text-xs leading-normal text-foreground-muted"
286 >
287 {props.error}
288 </Text>
289 <Pressable
290 accessibilityRole="button"
291 onPress={props.onRefresh}
292 disabled={props.isPending}
293 className="mt-3 min-h-11 self-start justify-center rounded-full bg-subtle px-4 active:opacity-70 disabled:opacity-50"
294 >
295 <Text className="text-sm font-t3-medium text-foreground">Try again</Text>
296 </Pressable>
297 </>
298 ) : props.isPending ? (
299 <ActivityIndicator size="small" />
300 ) : (
301 <>
302 <Text className="text-sm font-t3-bold text-foreground">No files found</Text>
303 <Text className="mt-1 text-xs leading-normal text-foreground-muted">
304 {props.searchQuery.trim().length > 0
305 ? "Try a different search."
306 : "The workspace is empty."}
307 </Text>
308 </>
309 )}
310 </View>
311 }
312 />
313 );