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

FileTreeBrowser.tsx

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