@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 260 lines 9.79 KB
Raw
1 import type { GitStatusEntry } from "@pierre/trees";
2 import { FileTree, useFileTree } from "@pierre/trees/react";
3 import { T, useGT } from "gt-react";
4 import { ChevronsDownUpIcon, ChevronsUpDownIcon } from "lucide-react";
5 import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
6
7 import { useStableCallback } from "~/hooks/useStableCallback";
8 import { useTheme } from "~/hooks/useTheme";
9 import { cn } from "~/lib/utils";
10 import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";
11
12 import {
13 areAllDirectoriesExpanded,
14 setAllDirectoriesExpanded,
15 subscribeOncePerTask,
16 } from "../files/fileTreeExpansion";
17 import { Button } from "../ui/button";
18 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
19 import {
20 buildDiffFileTreeUpdates,
21 compareDiffFileTreeEntries,
22 collectDirectoryPaths,
23 diffFileTreeModel,
24 type DiffFileTreeEntry,
25 } from "./diffFileTree.logic";
26 import { diffFileTreePositions } from "@t3tools/client-runtime/diff-file-order";
27
28 export type { DiffFileTreeEntry } from "./diffFileTree.logic";
29
30 interface DiffFileTreeProps {
31 readonly entries: ReadonlyArray<DiffFileTreeEntry>;
32 readonly onSelectFile: (path: string) => void;
33 readonly selectedPath?: string | null;
34 readonly revealRequestId?: number;
35 readonly ariaLabel: string;
36 readonly headerAccessory?: ReactNode;
37 readonly footer?: ReactNode;
38 readonly className?: string;
39 }
40
41 export function DiffFileTree({
42 entries,
43 onSelectFile,
44 selectedPath = null,
45 revealRequestId = 0,
46 ariaLabel,
47 headerAccessory,
48 footer,
49 className,
50 }: DiffFileTreeProps) {
51 const gt = useGT();
52 const { resolvedTheme } = useTheme();
53 const paths = entries.map((entry) => entry.path);
54 const presented = diffFileTreeModel(paths);
55 const modelPaths = presented.paths;
56 const icons = presented.icons;
57 const directoryPaths = collectDirectoryPaths(modelPaths);
58 const positions = diffFileTreePositions(modelPaths);
59 const [ordering] = useState(() => {
60 let currentPositions: ReadonlyMap<string, number> = new Map();
61 return {
62 sort: compareDiffFileTreeEntries(() => currentPositions),
63 update: (nextPositions: ReadonlyMap<string, number>) => {
64 currentPositions = nextPositions;
65 },
66 };
67 });
68 const gitStatus: ReadonlyArray<GitStatusEntry> = entries.map((entry) => ({
69 path: presented.modelPath(entry.path),
70 status: entry.status,
71 }));
72 const syncingSelectionRef = useRef(false);
73 const handledRevealRef = useRef<{
74 path: string;
75 revealRequestId: number;
76 } | null>(null);
77 const mountedPresentationRef = useRef<ReturnType<typeof diffFileTreeModel> | null>(null);
78
79 // The tree model keeps the first selection handler it was given.
80 const handleSelectionChange = useStableCallback((selectedPaths: ReadonlyArray<string>) => {
81 if (syncingSelectionRef.current) return;
82 const modelPath = selectedPaths.at(-1);
83 if (modelPath && modelPaths.includes(modelPath)) {
84 onSelectFile(presented.selectionPath(modelPath));
85 }
86 });
87
88 const { model } = useFileTree({
89 density: "compact",
90 flattenEmptyDirectories: true,
91 initialExpansion: "open",
92 icons,
93 onSelectionChange: handleSelectionChange,
94 paths: [],
95 search: false,
96 sort: ordering.sort,
97 unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
98 });
99 const allDirectoriesExpanded = useSyncExternalStore(
100 (listener) => subscribeOncePerTask(model, listener),
101 () => areAllDirectoriesExpanded(model, directoryPaths),
102 );
103
104 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes the icon set into the imperative Pierre file tree model
105 useEffect(() => {
106 model.setIcons(icons);
107 }, [icons, model]);
108
109 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies path updates, ordering and git status to the imperative Pierre file tree model
110 useEffect(() => {
111 ordering.update(positions);
112 const mounted = mountedPresentationRef.current;
113 if (mounted?.paths === modelPaths) return;
114 mountedPresentationRef.current = presented;
115 if (mounted === null) {
116 model.resetPaths(modelPaths);
117 } else if (mounted.paths.every((path, index) => modelPaths[index] === path)) {
118 const updates = buildDiffFileTreeUpdates(mounted.paths, modelPaths);
119 if (updates.length > 0) model.batch(updates);
120 } else {
121 // A reset can turn a file path into a directory. Carry selection and focus
122 // through real paths so paging keeps the same file without revealing it again.
123 const focusedPath = model.getFocusedPath();
124 const nextFocusedPath =
125 focusedPath === null ? null : presented.modelPath(mounted.selectionPath(focusedPath));
126 const selectedPaths = model
127 .getSelectedPaths()
128 .map((path) => presented.modelPath(mounted.selectionPath(path)))
129 .filter((path) => path.endsWith("/") || modelPaths.includes(path));
130 const collapsedDirectories = directoryPaths.filter((path) => {
131 const directory = model.getItem(path);
132 return directory !== null && "isExpanded" in directory && !directory.isExpanded();
133 });
134 syncingSelectionRef.current = true;
135 model.resetPaths(modelPaths);
136 for (const path of model.getSelectedPaths()) model.getItem(path)?.deselect();
137 for (const path of selectedPaths) model.getItem(path)?.select();
138 queueMicrotask(() => {
139 syncingSelectionRef.current = false;
140 });
141 for (const path of collapsedDirectories) {
142 const directory = model.getItem(path);
143 if (directory !== null && "collapse" in directory) directory.collapse();
144 }
145 if (
146 nextFocusedPath !== null &&
147 (modelPaths.includes(nextFocusedPath) || directoryPaths.includes(nextFocusedPath))
148 ) {
149 model.focusPath(nextFocusedPath);
150 }
151 }
152 model.setGitStatus(gitStatus);
153 }, [directoryPaths, gitStatus, model, modelPaths, ordering, positions, presented]);
154
155 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- expands ancestors, selects and scrolls to the requested file in the Pierre tree model
156 useEffect(() => {
157 if (selectedPath === null) {
158 handledRevealRef.current = null;
159 return;
160 }
161 const modelPath = presented.modelPath(selectedPath);
162 const item = model.getItem(modelPath);
163 if (item === null || item.isDirectory()) {
164 handledRevealRef.current = null;
165 return;
166 }
167 const handled = handledRevealRef.current;
168 if (handled?.path === selectedPath && handled.revealRequestId === revealRequestId) {
169 return;
170 }
171 handledRevealRef.current = { path: selectedPath, revealRequestId };
172 syncingSelectionRef.current = true;
173 for (const path of model.getSelectedPaths()) {
174 if (path !== modelPath) model.getItem(path)?.deselect();
175 }
176 let ancestor = "";
177 for (const segment of modelPath.split("/").slice(0, -1)) {
178 ancestor += `${segment}/`;
179 const directory = model.getItem(ancestor);
180 if (directory !== null && "expand" in directory) directory.expand();
181 }
182 item.select();
183 model.scrollToPath(modelPath, { offset: "nearest" });
184 queueMicrotask(() => {
185 syncingSelectionRef.current = false;
186 });
187 }, [model, presented, revealRequestId, selectedPath]);
188
189 return (
190 <div className={cn("flex min-h-0 flex-1 flex-col bg-background", className)}>
191 <div
192 className="flex h-10 min-h-10 shrink-0 items-center gap-1 border-b border-border/60 bg-background px-2 text-xs text-muted-foreground in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent"
193 data-surface-subheader
194 >
195 <span className="px-1 font-medium text-foreground">
196 <T>Files</T>
197 </span>
198 <span className="ml-auto tabular-nums">{entries.length}</span>
199 {headerAccessory}
200 {directoryPaths.length > 0 ? (
201 <Tooltip>
202 <TooltipTrigger
203 render={
204 <Button
205 type="button"
206 size="icon-xs"
207 variant="ghost"
208 aria-label={
209 allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")
210 }
211 onClick={() =>
212 setAllDirectoriesExpanded(model, directoryPaths, !allDirectoriesExpanded)
213 }
214 />
215 }
216 >
217 {allDirectoriesExpanded ? (
218 <ChevronsDownUpIcon className="size-3.5" />
219 ) : (
220 <ChevronsUpDownIcon className="size-3.5" />
221 )}
222 </TooltipTrigger>
223 <TooltipPopup>
224 {allDirectoriesExpanded ? gt("Collapse all folders") : gt("Expand all folders")}
225 </TooltipPopup>
226 </Tooltip>
227 ) : null}
228 </div>
229 <FileTree
230 model={model}
231 aria-label={ariaLabel}
232 onClickCapture={(event) => {
233 if (
234 event.defaultPrevented ||
235 event.button !== 0 ||
236 event.ctrlKey ||
237 event.metaKey ||
238 event.shiftKey ||
239 event.altKey
240 ) {
241 return;
242 }
243 // Pierre emits no change for its sole selected row; read before the click to avoid double reveals.
244 const selected = model.getSelectedPaths();
245 const path = selected.length === 1 ? selected[0] : undefined;
246 if (!path || !modelPaths.includes(path)) return;
247 const clickedSelectedRow = event.nativeEvent
248 .composedPath()
249 .some(
250 (node) => node instanceof HTMLElement && node.getAttribute("data-item-path") === path,
251 );
252 if (clickedSelectedRow) onSelectFile(presented.selectionPath(path));
253 }}
254 className="min-h-0 flex-1 overflow-hidden"
255 style={pierreTreeStyle(resolvedTheme)}
256 />
257 {footer}
258 </div>
259 );
260 }