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

composerSlashCommandSearch.ts

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