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

commandPaletteItems.ts

45 lines1.5 KB

1export interface CommandPaletteItem {
2 readonly key: string;
3 readonly kind: "action" | "project" | "thread";
4 readonly title: string;
5 readonly detail?: string;
6 readonly searchTerms: ReadonlyArray<string>;
7 readonly run: () => void;
8}
9​
10export function filterCommandPaletteItems(
11 items: ReadonlyArray<CommandPaletteItem>,
12 query: string,
13 matchedThreadKeys: ReadonlySet<string>,
14) {
15 const actionsOnly = query.startsWith(">");
16 const normalized = (actionsOnly ? query.slice(1) : query).trim().toLocaleLowerCase();
17 const tokens = normalized.split(/\s+/);
18 return items
19 .flatMap((item, index) => {
20 if (actionsOnly && item.kind !== "action") return [];
21 if (!normalized) return item.kind === "project" ? [] : [{ item, rank: 0, index }];
22 const title = item.title.toLocaleLowerCase();
23 const haystack = [title, ...item.searchTerms].join(" ").toLocaleLowerCase();
24 if (
25 !tokens.every((token) => haystack.includes(token)) &&
26 !(item.kind === "thread" && matchedThreadKeys.has(item.key))
27 )
28 return [];
29 const rank =
30 title === normalized
31 ? 3
32 : title.startsWith(normalized)
33 ? 2
34 : title.includes(normalized)
35 ? 1
36 : 0;
37 return [{ item, rank, index }];
38 })
39 .sort((left, right) => right.rank - left.rank || left.index - right.index)
40 .map(({ item }) => item);
42​
43export function nextPaletteIndex(index: number, direction: -1 | 1, count: number) {
44 return count === 0 ? 0 : (index + direction + count) % count;