Open History to see the last commit
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>;
11}
12
13function fileName(path: string): string {
14 return path.slice(path.lastIndexOf("/") + 1);
15}
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 // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back.
23 const sourceSpans: Array<readonly [number, number]> = [];
24 if (normalizedValue.length !== value.length) {
25 let sourceOffset = 0;
26 for (const char of value) {
27 const span = [sourceOffset, sourceOffset + char.length] as const;
28 for (let n = char.toLowerCase().length; n > 0; n -= 1) sourceSpans.push(span);
29 sourceOffset = span[1];
30 }
31 }
32 const indices: number[] = [];
33 let queryIndex = 0;
34
35 for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) {
36 if (normalizedValue[valueIndex] !== query[queryIndex]) continue;
37 const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1];
38 for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i);
39 queryIndex += 1;
40 if (queryIndex === query.length) return indices;
41 }
42
43 return null;
44}
45
46/** Preserve server ranking and query normalization while filtering files and computing highlights. */
47export function getProjectFilePickerMatches(
48 entries: ReadonlyArray<ProjectEntry>,
49 rawQuery: string,
50 limit = PROJECT_FILE_PICKER_RESULT_LIMIT,
51): ProjectFilePickerMatch[] {
52 if (limit <= 0) return [];
53
54 const query = normalizeSearchQuery(rawQuery, {
55 trimLeadingPattern: /^[@./]+/,
56 }).replaceAll(/\s/g, "");
57 const matches: ProjectFilePickerMatch[] = [];
58
59 for (const entry of entries) {
60 if (entry.kind !== "file") continue;
61
62 const name = fileName(entry.path);
63 const nameMatchIndices = findMatchIndices(name, query);
64 const pathMatchIndices = findMatchIndices(entry.path, query);
65 matches.push({
66 name,
67 nameMatchIndices: nameMatchIndices ?? [],
68 path: entry.path,
69 pathMatchIndices: pathMatchIndices ?? [],
70 });
71 if (matches.length >= limit) break;
72 }
73
74 return matches;
75}