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

FileTreeBrowser.tsx

295 lines10.0 KB

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