Open History to see the last commit
1import {
2 insertRankedSearchResult,
3 normalizeSearchQuery,
4 scoreQueryMatch,
5} from "@t3tools/shared/searchRanking";
6
7import type { ComposerCommandItem } from "./ComposerCommandMenu";
8
9function scoreSlashCommandItem(
10 item: Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>,
11 query: string,
12): number | null {
13 const primaryValue =
14 item.type === "slash-command" ? item.command.toLowerCase() : item.command.name.toLowerCase();
15 const description = item.description.toLowerCase();
16
17 const scores = [
18 scoreQueryMatch({
19 value: primaryValue,
20 query,
21 exactBase: 0,
22 prefixBase: 2,
23 boundaryBase: 4,
24 includesBase: 6,
25 fuzzyBase: 100,
26 boundaryMarkers: ["-", "_", "/"],
27 }),
28 scoreQueryMatch({
29 value: description,
30 query,
31 exactBase: 20,
32 prefixBase: 22,
33 boundaryBase: 24,
34 includesBase: 26,
35 }),
36 ].filter((score): score is number => score !== null);
37
38 if (scores.length === 0) {
39 return null;
40 }
41
42 return Math.min(...scores);
43}
44
45export function searchSlashCommandItems(
46 items: ReadonlyArray<
47 Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>
48 >,
49 query: string,
50): Array<Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>> {
51 const normalizedQuery = normalizeSearchQuery(query, { trimLeadingPattern: /^\/+/ });
52 if (!normalizedQuery) {
53 return [...items];
54 }
55
56 const ranked: Array<{
57 item: Extract<ComposerCommandItem, { type: "slash-command" | "provider-slash-command" }>;
58 score: number;
59 tieBreaker: string;
60 }> = [];
61
62 for (const item of items) {
63 const score = scoreSlashCommandItem(item, normalizedQuery);
64 if (score === null) {
65 continue;
66 }
67
68 insertRankedSearchResult(
69 ranked,
70 {
71 item,
72 score,
73 tieBreaker:
74 item.type === "slash-command"
75 ? `0\u0000${item.command}`
76 : `1\u0000${item.command.name}\u0000${item.provider}`,
77 },
78 Number.POSITIVE_INFINITY,
79 );
80 }
81
82 return ranked.map((entry) => entry.item);
83}