Open History to see the last commit
1import type { ProjectEntry } from "@t3tools/contracts";
2import { normalizeSearchQuery, scoreQueryMatch } from "@t3tools/shared/searchRanking";
3
4export interface FileTreeNode {
5 readonly path: string;
6 readonly name: string;
7 readonly kind: ProjectEntry["kind"];
8 readonly ignored?: boolean;
9 readonly children: ReadonlyArray<FileTreeNode>;
10 readonly searchSegments: ReadonlyArray<string>;
11 readonly searchWords: ReadonlyArray<string>;
12}
13
14export interface VisibleFileTreeNode {
15 readonly node: FileTreeNode;
16 readonly depth: number;
17}
18
19interface MutableFileTreeNode {
20 path: string;
21 name: string;
22 kind: ProjectEntry["kind"];
23 ignored?: boolean;
24 children: Map<string, MutableFileTreeNode>;
25}
26
27function createMutableNode(
28 path: string,
29 name: string,
30 kind: ProjectEntry["kind"],
31): MutableFileTreeNode {
32 return {
33 path,
34 name,
35 kind,
36 children: new Map(),
37 };
38}
39
40function splitSearchWords(value: string): ReadonlyArray<string> {
41 return value
42 .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
43 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
44 .split(/[^A-Za-z0-9]+/)
45 .filter(Boolean)
46 .map((word) => word.toLowerCase());
47}
48
49function buildNodeSearchTerms(path: string): {
50 readonly segments: ReadonlyArray<string>;
51 readonly words: ReadonlyArray<string>;
52} {
53 const segments: string[] = [];
54 const words: string[] = [];
55
56 for (const segment of path.split("/")) {
57 if (!segment) {
58 continue;
59 }
60 segments.push(segment.toLowerCase());
61 words.push(...splitSearchWords(segment));
62 }
63
64 return { segments, words };
65}
66
67function freezeNode(node: MutableFileTreeNode): FileTreeNode {
68 const searchTerms = buildNodeSearchTerms(node.path);
69 return {
70 path: node.path,
71 name: node.name,
72 kind: node.kind,
73 ...(node.ignored ? { ignored: true } : {}),
74 children: [...node.children.values()].sort(compareNodes).map(freezeNode),
75 searchSegments: searchTerms.segments,
76 searchWords: searchTerms.words,
77 };
78}
79
80function compareNodes(
81 left: Pick<FileTreeNode, "kind" | "name">,
82 right: Pick<FileTreeNode, "kind" | "name">,
83): number {
84 if (left.kind !== right.kind) {
85 return left.kind === "directory" ? -1 : 1;
86 }
87 return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
88}
89
90export function buildFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
91 const root = createMutableNode("", "", "directory");
92
93 for (const entry of entries) {
94 const parts = entry.path.split("/").filter(Boolean);
95 if (parts.length === 0) {
96 continue;
97 }
98
99 let current = root;
100 for (let index = 0; index < parts.length; index += 1) {
101 const part = parts[index];
102 if (!part) {
103 continue;
104 }
105
106 const path = parts.slice(0, index + 1).join("/");
107 const isLeaf = index === parts.length - 1;
108 const kind = isLeaf ? entry.kind : "directory";
109 let child = current.children.get(part);
110 if (!child) {
111 child = createMutableNode(path, part, kind);
112 current.children.set(part, child);
113 } else if (isLeaf) {
114 child.kind = entry.kind;
115 }
116 if (isLeaf && entry.ignored) child.ignored = true;
117 current = child;
118 }
119 }
120
121 return [...root.children.values()].sort(compareNodes).map(freezeNode);
122}
123
124export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
125 const expanded = new Set<string>();
126 for (const node of nodes) {
127 if (node.kind === "directory") {
128 expanded.add(node.path);
129 }
130 }
131 return expanded;
132}
133
134function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
135 return (
136 scoreQueryMatch({
137 value,
138 query: token,
139 exactBase: 0,
140 prefixBase: 2,
141 boundaryBase: 4,
142 includesBase: 6,
143 ...(fuzzy ? { fuzzyBase: 100 } : {}),
144 boundaryMarkers: ["/", "-", "_", "."],
145 }) !== null
146 );
147}
148
149function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
150 return tokens.every(
151 (token) =>
152 node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
153 node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
154 );
155}
156
157function flattenNode(
158 output: VisibleFileTreeNode[],
159 node: FileTreeNode,
160 depth: number,
161 expanded: ReadonlySet<string>,
162 searchTokens: ReadonlyArray<string>,
163): boolean {
164 const isSearching = searchTokens.length > 0;
165 const matches = isSearching && nodeMatchesSearch(node, searchTokens);
166 let descendantMatches = false;
167 const childOutput: VisibleFileTreeNode[] = [];
168
169 if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
170 for (const child of node.children) {
171 if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
172 descendantMatches = true;
173 }
174 }
175 }
176
177 const visible = !isSearching || matches || descendantMatches;
178 if (!visible) {
179 return false;
180 }
181
182 output.push({ node, depth });
183 output.push(...childOutput);
184 return matches || descendantMatches;
185}
186
187export function flattenFileTree(input: {
188 readonly nodes: ReadonlyArray<FileTreeNode>;
189 readonly expanded: ReadonlySet<string>;
190 readonly searchQuery?: string;
191}): ReadonlyArray<VisibleFileTreeNode> {
192 const output: VisibleFileTreeNode[] = [];
193 const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
194 const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
195 for (const node of input.nodes) {
196 flattenNode(output, node, 0, input.expanded, searchTokens);
197 }
198 return output;
199}