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

composerSlashCommandSearch.ts

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