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

fileTree.ts

195 lines5.3 KB

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 children: ReadonlyArray<FileTreeNode>;
9 readonly searchSegments: ReadonlyArray<string>;
10 readonly searchWords: ReadonlyArray<string>;
12​
13export interface VisibleFileTreeNode {
14 readonly node: FileTreeNode;
15 readonly depth: number;
17​
18interface MutableFileTreeNode {
19 path: string;
20 name: string;
21 kind: ProjectEntry["kind"];
22 children: Map<string, MutableFileTreeNode>;
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 };
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());
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 };
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 };
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" });
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);
119​
120export function defaultExpandedTreePaths(nodes: ReadonlyArray<FileTreeNode>): ReadonlySet<string> {
121 const expanded = new Set<string>();
122 for (const node of nodes) {
123 if (node.kind === "directory") {
124 expanded.add(node.path);
125 }
126 }
127 return expanded;
129​
130function valueMatchesSearchToken(value: string, token: string, fuzzy: boolean): boolean {
131 return (
132 scoreQueryMatch({
133 value,
134 query: token,
135 exactBase: 0,
136 prefixBase: 2,
137 boundaryBase: 4,
138 includesBase: 6,
139 ...(fuzzy ? { fuzzyBase: 100 } : {}),
140 boundaryMarkers: ["/", "-", "_", "."],
141 }) !== null
142 );
144​
145function nodeMatchesSearch(node: FileTreeNode, tokens: ReadonlyArray<string>): boolean {
146 return tokens.every(
147 (token) =>
148 node.searchSegments.some((segment) => valueMatchesSearchToken(segment, token, false)) ||
149 node.searchWords.some((word) => valueMatchesSearchToken(word, token, true)),
150 );
152​
153function flattenNode(
154 output: VisibleFileTreeNode[],
155 node: FileTreeNode,
156 depth: number,
157 expanded: ReadonlySet<string>,
158 searchTokens: ReadonlyArray<string>,
159): boolean {
160 const isSearching = searchTokens.length > 0;
161 const matches = isSearching && nodeMatchesSearch(node, searchTokens);
162 let descendantMatches = false;
163 const childOutput: VisibleFileTreeNode[] = [];
164​
165 if (node.kind === "directory" && (expanded.has(node.path) || isSearching)) {
166 for (const child of node.children) {
167 if (flattenNode(childOutput, child, depth + 1, expanded, searchTokens)) {
168 descendantMatches = true;
169 }
170 }
171 }
172​
173 const visible = !isSearching || matches || descendantMatches;
174 if (!visible) {
175 return false;
176 }
177​
178 output.push({ node, depth });
179 output.push(...childOutput);
180 return matches || descendantMatches;
182​
183export function flattenFileTree(input: {
184 readonly nodes: ReadonlyArray<FileTreeNode>;
185 readonly expanded: ReadonlySet<string>;
186 readonly searchQuery?: string;
187}): ReadonlyArray<VisibleFileTreeNode> {
188 const output: VisibleFileTreeNode[] = [];
189 const normalizedSearch = normalizeSearchQuery(input.searchQuery ?? "");
190 const searchTokens = normalizedSearch.split(/[\s/\\._-]+/).filter(Boolean);
191 for (const node of input.nodes) {
192 flattenNode(output, node, 0, input.expanded, searchTokens);
193 }
194 return output;