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

composerSlashCommandSearch.ts

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