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