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

ProjectFilePicker.logic.ts

71 lines2.1 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/**
18 * Returns null when `value` does not contain the subsequence at all — the
19 * entry still renders (the server matched it), just without highlights.
20 */
21function findMatchIndices(value: string, query: string): number[] | null {
22 if (!query) return [];
23​
24 const normalizedValue = value.toLowerCase();
25 const indices: number[] = [];
26 let queryIndex = 0;
27​
28 for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) {
29 if (normalizedValue[valueIndex] !== query[queryIndex]) continue;
30 indices.push(valueIndex);
31 queryIndex += 1;
32 if (queryIndex === query.length) return indices;
33 }
34​
35 return null;
37​
38/**
39 * Server ordering is preserved — ranking already happened there; this pass only
40 * filters to files and computes highlight positions with the same query
41 * normalization the server applied.
42 */
43export function getProjectFilePickerMatches(
44 entries: ReadonlyArray<ProjectEntry>,
45 rawQuery: string,
46 limit = PROJECT_FILE_PICKER_RESULT_LIMIT,
47): ProjectFilePickerMatch[] {
48 if (limit <= 0) return [];
49​
50 const query = normalizeSearchQuery(rawQuery, {
51 trimLeadingPattern: /^[@./]+/,
52 }).replaceAll(/\s/g, "");
53 const matches: ProjectFilePickerMatch[] = [];
54​
55 for (const entry of entries) {
56 if (entry.kind !== "file") continue;
57​
58 const name = fileName(entry.path);
59 const nameMatchIndices = findMatchIndices(name, query);
60 const pathMatchIndices = findMatchIndices(entry.path, query);
61 matches.push({
62 name,
63 nameMatchIndices: nameMatchIndices ?? [],
64 path: entry.path,
65 pathMatchIndices: pathMatchIndices ?? [],
66 });
67 if (matches.length >= limit) break;
68 }
69​
70 return matches;