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

CommandPalette.logic.ts

262 lines7.9 KB

1import { type KeybindingCommand } from "@t3tools/contracts";
2import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import { type ReactNode } from "react";
4import { sortThreads } from "../lib/threadSort";
5import { formatRelativeTimeLabel } from "../timestampFormat";
6import { type Project, type SidebarThreadSummary, type Thread } from "../types";
7​
8export const RECENT_THREAD_LIMIT = 12;
9export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
10export const ADDON_ICON_CLASS = "size-4";
11​
12export interface CommandPaletteItem {
13 readonly kind: "action" | "submenu";
14 readonly value: string;
15 readonly searchTerms: ReadonlyArray<string>;
16 readonly title: ReactNode;
17 readonly description?: string;
18 readonly timestamp?: string;
19 readonly icon: ReactNode;
20 readonly shortcutCommand?: KeybindingCommand;
22​
23export interface CommandPaletteActionItem extends CommandPaletteItem {
24 readonly kind: "action";
25 readonly keepOpen?: boolean;
26 readonly run: () => Promise<void>;
28​
29export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
30 readonly kind: "submenu";
31 readonly addonIcon: ReactNode;
32 readonly groups: ReadonlyArray<CommandPaletteGroup>;
33 readonly initialQuery?: string;
35​
36export interface CommandPaletteGroup {
37 readonly value: string;
38 readonly label: string;
39 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
41​
42export interface CommandPaletteView {
43 readonly addonIcon: ReactNode;
44 readonly groups: ReadonlyArray<CommandPaletteGroup>;
45 readonly initialQuery?: string;
47​
48export type CommandPaletteMode = "root" | "submenu";
49​
50export function normalizeSearchText(value: string): string {
51 return value.trim().toLowerCase().replace(/\s+/g, " ");
53​
54export function buildProjectActionItems(input: {
55 projects: ReadonlyArray<Project>;
56 valuePrefix: string;
57 icon: (project: Project) => ReactNode;
58 runProject: (project: Project) => Promise<void>;
59}): CommandPaletteActionItem[] {
60 return input.projects.map((project) => ({
61 kind: "action",
62 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
63 searchTerms: [project.name, project.cwd],
64 title: project.name,
65 description: project.cwd,
66 icon: input.icon(project),
67 run: async () => {
68 await input.runProject(project);
69 },
70 }));
72​
73export function buildThreadActionItems(input: {
74 threads: ReadonlyArray<
75 Pick<
76 SidebarThreadSummary,
77 "archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
78 > & {
79 updatedAt?: string | undefined;
80 latestUserMessageAt?: string | null;
81 }
82 >;
83 activeThreadId?: Thread["id"];
84 projectTitleById: ReadonlyMap<Project["id"], string>;
85 sortOrder: SidebarThreadSortOrder;
86 icon: ReactNode;
87 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
88 limit?: number;
89}): CommandPaletteActionItem[] {
90 const sortedThreads = sortThreads(
91 input.threads.filter((thread) => thread.archivedAt === null),
92 input.sortOrder,
93 );
94 const visibleThreads =
95 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
96​
97 return visibleThreads.map((thread) => {
98 const projectTitle = input.projectTitleById.get(thread.projectId);
99 const descriptionParts: string[] = [];
100​
101 if (projectTitle) {
102 descriptionParts.push(projectTitle);
103 }
104 if (thread.branch) {
105 descriptionParts.push(`#${thread.branch}`);
106 }
107 if (thread.id === input.activeThreadId) {
108 descriptionParts.push("Current thread");
109 }
110​
111 return {
112 kind: "action",
113 value: `thread:${thread.id}`,
114 searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
115 title: thread.title,
116 description: descriptionParts.join(" · "),
117 timestamp: formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt),
118 icon: input.icon,
119 run: async () => {
120 await input.runThread(thread);
121 },
122 };
123 });
125​
126function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
127 const normalizedField = normalizeSearchText(field);
128 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
129 return Number.NEGATIVE_INFINITY;
130 }
131 if (normalizedField === normalizedQuery) {
132 return 3;
133 }
134 if (normalizedField.startsWith(normalizedQuery)) {
135 return 2;
136 }
137 return 1;
139​
140function rankCommandPaletteItemMatch(
141 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
142 normalizedQuery: string,
143): number {
144 const terms = item.searchTerms.filter((term) => term.length > 0);
145 if (terms.length === 0) {
146 return 0;
147 }
148​
149 for (const [index, field] of terms.entries()) {
150 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
151 if (fieldRank !== Number.NEGATIVE_INFINITY) {
152 return 1_000 - index * 100 + fieldRank;
153 }
154 }
155​
156 return 0;
158​
159export function filterCommandPaletteGroups(input: {
160 activeGroups: ReadonlyArray<CommandPaletteGroup>;
161 query: string;
162 isInSubmenu: boolean;
163 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
164 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
165}): CommandPaletteGroup[] {
166 const isActionsFilter = input.query.startsWith(">");
167 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
168 const normalizedQuery = normalizeSearchText(searchQuery);
169​
170 if (normalizedQuery.length === 0) {
171 if (isActionsFilter) {
172 return input.activeGroups.filter((group) => group.value === "actions");
173 }
174 return [...input.activeGroups];
175 }
176​
177 let baseGroups = [...input.activeGroups];
178 if (isActionsFilter) {
179 baseGroups = baseGroups.filter((group) => group.value === "actions");
180 } else if (!input.isInSubmenu) {
181 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
182 }
183​
184 const searchableGroups = [...baseGroups];
185 if (!input.isInSubmenu && !isActionsFilter) {
186 if (input.projectSearchItems.length > 0) {
187 searchableGroups.push({
188 value: "projects-search",
189 label: "Projects",
190 items: input.projectSearchItems,
191 });
192 }
193 if (input.threadSearchItems.length > 0) {
194 searchableGroups.push({
195 value: "threads-search",
196 label: "Threads",
197 items: input.threadSearchItems,
198 });
199 }
200 }
201​
202 return searchableGroups.flatMap((group) => {
203 const items = group.items
204 .map((item, index) => {
205 const haystack = normalizeSearchText(item.searchTerms.join(" "));
206 if (!haystack.includes(normalizedQuery)) {
207 return null;
208 }
209​
210 return {
211 item,
212 index,
213 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
214 };
215 })
216 .filter(
217 (entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
218 entry !== null,
219 )
220 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
221 .map((entry) => entry.item);
222​
223 if (items.length === 0) {
224 return [];
225 }
226​
227 return [{ value: group.value, label: group.label, items }];
228 });
230​
231export function getCommandPaletteMode(input: {
232 currentView: CommandPaletteView | null;
233}): CommandPaletteMode {
234 return input.currentView ? "submenu" : "root";
236​
237export function buildRootGroups(input: {
238 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
239 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
240}): CommandPaletteGroup[] {
241 const groups: CommandPaletteGroup[] = [];
242 if (input.actionItems.length > 0) {
243 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
244 }
245 if (input.recentThreadItems.length > 0) {
246 groups.push({
247 value: "recent-threads",
248 label: "Recent Threads",
249 items: input.recentThreadItems,
250 });
251 }
252 return groups;
254​
255export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
256 switch (mode) {
257 case "root":
258 return "Search commands, projects, and threads...";
259 case "submenu":
260 return "Search...";
261 }