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