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

ProjectFilePicker.logic.ts

64 lines1.9 KB

1import type { ProjectEntry } from "@t3tools/contracts";
2import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";
3​
4export const PROJECT_FILE_PICKER_RESULT_LIMIT = 200;
5​
6export interface ProjectFilePickerMatch {
7 readonly name: string;
8 readonly nameMatchIndices: ReadonlyArray<number>;
9 readonly path: string;
10 readonly pathMatchIndices: ReadonlyArray<number>;
12​
13function fileName(path: string): string {
14 return path.slice(path.lastIndexOf("/") + 1);
16​
17/** Return null for unmatched subsequences; server-matched entries still render without highlights. */
18function findMatchIndices(value: string, query: string): number[] | null {
19 if (!query) return [];
20​
21 const normalizedValue = value.toLowerCase();
22 const indices: number[] = [];
23 let queryIndex = 0;
24​
25 for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) {
26 if (normalizedValue[valueIndex] !== query[queryIndex]) continue;
27 indices.push(valueIndex);
28 queryIndex += 1;
29 if (queryIndex === query.length) return indices;
30 }
31​
32 return null;
34​
35/** Preserve server ranking and query normalization while filtering files and computing highlights. */
36export function getProjectFilePickerMatches(
37 entries: ReadonlyArray<ProjectEntry>,
38 rawQuery: string,
39 limit = PROJECT_FILE_PICKER_RESULT_LIMIT,
40): ProjectFilePickerMatch[] {
41 if (limit <= 0) return [];
42​
43 const query = normalizeSearchQuery(rawQuery, {
44 trimLeadingPattern: /^[@./]+/,
45 }).replaceAll(/\s/g, "");
46 const matches: ProjectFilePickerMatch[] = [];
47​
48 for (const entry of entries) {
49 if (entry.kind !== "file") continue;
50​
51 const name = fileName(entry.path);
52 const nameMatchIndices = findMatchIndices(name, query);
53 const pathMatchIndices = findMatchIndices(entry.path, query);
54 matches.push({
55 name,
56 nameMatchIndices: nameMatchIndices ?? [],
57 path: entry.path,
58 pathMatchIndices: pathMatchIndices ?? [],
59 });
60 if (matches.length >= limit) break;
61 }
62​
63 return matches;