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

FileTreeBrowser.tsx

292 lines9.8 KB

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