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

composerSlashCommandSearch.ts

92 lines2.3 KB

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