Open History to see the last commit
1import type { ProjectEntry } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3
4import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
5
6export interface FileTreeExpansionModel {
7 getItem(path: string): unknown;
8}
9
10type DirectoryHandle = {
11 isDirectory(): boolean;
12 isExpanded(): boolean;
13 expand(): void;
14 collapse(): void;
15};
16
17function asDirectoryHandle(item: unknown): DirectoryHandle | null {
18 if (
19 typeof item !== "object" ||
20 item === null ||
21 !("isDirectory" in item) ||
22 typeof item.isDirectory !== "function" ||
23 !item.isDirectory() ||
24 !("isExpanded" in item) ||
25 typeof item.isExpanded !== "function" ||
26 !("expand" in item) ||
27 typeof item.expand !== "function" ||
28 !("collapse" in item) ||
29 typeof item.collapse !== "function"
30 ) {
31 return null;
32 }
33 return item as DirectoryHandle;
34}
35
36/**
37 * Calls `listener` once per task, however many events the model emitted in it. Expanding every
38 * folder emits one event per folder, and a listener that rescans the folders is quadratic otherwise.
39 */
40export function subscribeOncePerTask(
41 model: { subscribe(listener: () => void): () => void },
42 listener: () => void,
43): () => void {
44 let queued = false;
45 let subscribed = true;
46 const unsubscribe = model.subscribe(() => {
47 if (queued) return;
48 queued = true;
49 queueMicrotask(() => {
50 queued = false;
51 if (subscribed) listener();
52 });
53 });
54 return () => {
55 subscribed = false;
56 unsubscribe();
57 };
58}
59
60export function areAllDirectoriesExpanded(
61 model: FileTreeExpansionModel,
62 directoryPaths: readonly string[],
63): boolean {
64 return (
65 directoryPaths.length > 0 &&
66 directoryPaths.every((path) => {
67 const item = asDirectoryHandle(model.getItem(path));
68 return item !== null && item.isExpanded();
69 })
70 );
71}
72
73export function setAllDirectoriesExpanded(
74 model: FileTreeExpansionModel,
75 directoryPaths: readonly string[],
76 expanded: boolean,
77): void {
78 for (const path of directoryPaths) {
79 const item = asDirectoryHandle(model.getItem(path));
80 if (item === null || item.isExpanded() === expanded) continue;
81 if (expanded) item.expand();
82 else item.collapse();
83 }
84}
85
86/** Maps each listed parent path to its only child, or to null when it holds several entries. */
87export function onlyChildren(
88 entries: readonly ProjectEntry[],
89): ReadonlyMap<string, ProjectEntry | null> {
90 const result = new Map<string, ProjectEntry | null>();
91 for (const entry of entries) {
92 const parent = entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/")));
93 result.set(parent, result.has(parent) ? null : entry);
94 }
95 return result;
96}
97
98/** Calls made while `run` is running rerun it once it returns, instead of nesting. */
99export function coalesceReentrantCalls(run: () => void): () => void {
100 let running = false;
101 let calledAgain = false;
102 return () => {
103 if (running) {
104 calledAgain = true;
105 return;
106 }
107 running = true;
108 try {
109 do {
110 calledAgain = false;
111 run();
112 } while (calledAgain);
113 } finally {
114 running = false;
115 }
116 };
117}
118
119const EXPANDED_DIRECTORIES_STORAGE_KEY = "t3code.fileTreeExpandedDirectories";
120// Roots are kept most recent first and capped so worktrees that come and go do not grow storage.
121const MAX_STORED_ROOTS = 20;
122// Every restored folder is listed when the panel mounts, so a root keeps the folders nearest it.
123const MAX_STORED_PATHS_PER_ROOT = 100;
124const StoredExpandedDirectories = Schema.Array(
125 Schema.Struct({ root: Schema.String, paths: Schema.Array(Schema.String) }),
126);
127
128function readStoredExpandedDirectories() {
129 try {
130 return getLocalStorageItem(EXPANDED_DIRECTORIES_STORAGE_KEY, StoredExpandedDirectories) ?? [];
131 } catch (error) {
132 console.error(error);
133 return [];
134 }
135}
136
137function nearestToRoot(paths: readonly string[]): readonly string[] {
138 if (paths.length <= MAX_STORED_PATHS_PER_ROOT) return paths;
139 const depth = (path: string) => path.split("/").length;
140 return paths
141 .toSorted((left, right) => depth(left) - depth(right))
142 .slice(0, MAX_STORED_PATHS_PER_ROOT);
143}
144
145export function readExpandedDirectories(root: string): readonly string[] {
146 return nearestToRoot(
147 readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [],
148 );
149}
150
151export function writeExpandedDirectories(root: string, paths: readonly string[]): void {
152 const others = readStoredExpandedDirectories().filter((entry) => entry.root !== root);
153 const next = paths.length > 0 ? [{ root, paths: nearestToRoot(paths) }, ...others] : others;
154 try {
155 setLocalStorageItem(
156 EXPANDED_DIRECTORIES_STORAGE_KEY,
157 next.slice(0, MAX_STORED_ROOTS),
158 StoredExpandedDirectories,
159 );
160 } catch (error) {
161 console.error(error);
162 }
163}