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

CommandPalette.logic.ts

346 lines10.4 KB

1import { type KeybindingCommand, type FilesystemBrowseEntry } 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" | "root-browse" | "submenu" | "submenu-browse";
49​
50export function filterBrowseEntries(input: {
51 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
52 browseFilterQuery: string;
53 highlightedItemValue: string | null;
54}): {
55 filteredEntries: FilesystemBrowseEntry[];
56 highlightedEntry: FilesystemBrowseEntry | null;
57 exactEntry: FilesystemBrowseEntry | null;
58} {
59 const lowerFilter = input.browseFilterQuery.toLowerCase();
60 const showHidden = input.browseFilterQuery.startsWith(".");
61​
62 const filteredEntries = input.browseEntries.filter(
63 (entry) =>
64 entry.name.toLowerCase().startsWith(lowerFilter) &&
65 (showHidden || !entry.name.startsWith(".")),
66 );
67​
68 let highlightedEntry: FilesystemBrowseEntry | null = null;
69 if (input.highlightedItemValue?.startsWith("browse:")) {
70 const highlightedPath = input.highlightedItemValue.slice("browse:".length);
71 highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null;
72 }
73​
74 const exactEntry =
75 input.browseFilterQuery.length > 0
76 ? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
77 : null;
78​
79 return { filteredEntries, highlightedEntry, exactEntry };
81​
82export function normalizeSearchText(value: string): string {
83 return value.trim().toLowerCase().replace(/\s+/g, " ");
85​
86export function buildProjectActionItems(input: {
87 projects: ReadonlyArray<Project>;
88 valuePrefix: string;
89 icon: (project: Project) => ReactNode;
90 runProject: (project: Project) => Promise<void>;
91}): CommandPaletteActionItem[] {
92 return input.projects.map((project) => ({
93 kind: "action",
94 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
95 searchTerms: [project.name, project.cwd],
96 title: project.name,
97 description: project.cwd,
98 icon: input.icon(project),
99 run: async () => {
100 await input.runProject(project);
101 },
102 }));
104​
105export function buildThreadActionItems(input: {
106 threads: ReadonlyArray<
107 Pick<
108 SidebarThreadSummary,
109 "archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
110 > & {
111 updatedAt?: string | undefined;
112 latestUserMessageAt?: string | null;
113 }
114 >;
115 activeThreadId?: Thread["id"];
116 projectTitleById: ReadonlyMap<Project["id"], string>;
117 sortOrder: SidebarThreadSortOrder;
118 icon: ReactNode;
119 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
120 limit?: number;
121}): CommandPaletteActionItem[] {
122 const sortedThreads = sortThreads(
123 input.threads.filter((thread) => thread.archivedAt === null),
124 input.sortOrder,
125 );
126 const visibleThreads =
127 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
128​
129 return visibleThreads.map((thread) => {
130 const projectTitle = input.projectTitleById.get(thread.projectId);
131 const descriptionParts: string[] = [];
132​
133 if (projectTitle) {
134 descriptionParts.push(projectTitle);
135 }
136 if (thread.branch) {
137 descriptionParts.push(`#${thread.branch}`);
138 }
139 if (thread.id === input.activeThreadId) {
140 descriptionParts.push("Current thread");
141 }
142​
143 return {
144 kind: "action",
145 value: `thread:${thread.id}`,
146 searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
147 title: thread.title,
148 description: descriptionParts.join(" · "),
149 timestamp: formatRelativeTimeLabel(
150 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
151 ),
152 icon: input.icon,
153 run: async () => {
154 await input.runThread(thread);
155 },
156 };
157 });
159​
160function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
161 const normalizedField = normalizeSearchText(field);
162 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
163 return Number.NEGATIVE_INFINITY;
164 }
165 if (normalizedField === normalizedQuery) {
166 return 3;
167 }
168 if (normalizedField.startsWith(normalizedQuery)) {
169 return 2;
170 }
171 return 1;
173​
174function rankCommandPaletteItemMatch(
175 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
176 normalizedQuery: string,
177): number {
178 const terms = item.searchTerms.filter((term) => term.length > 0);
179 if (terms.length === 0) {
180 return 0;
181 }
182​
183 for (const [index, field] of terms.entries()) {
184 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
185 if (fieldRank !== Number.NEGATIVE_INFINITY) {
186 return 1_000 - index * 100 + fieldRank;
187 }
188 }
189​
190 return 0;
192​
193export function filterCommandPaletteGroups(input: {
194 activeGroups: ReadonlyArray<CommandPaletteGroup>;
195 query: string;
196 isInSubmenu: boolean;
197 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
198 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
199}): CommandPaletteGroup[] {
200 const isActionsFilter = input.query.startsWith(">");
201 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
202 const normalizedQuery = normalizeSearchText(searchQuery);
203​
204 if (normalizedQuery.length === 0) {
205 if (isActionsFilter) {
206 return input.activeGroups.filter((group) => group.value === "actions");
207 }
208 return [...input.activeGroups];
209 }
210​
211 let baseGroups = [...input.activeGroups];
212 if (isActionsFilter) {
213 baseGroups = baseGroups.filter((group) => group.value === "actions");
214 } else if (!input.isInSubmenu) {
215 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
216 }
217​
218 const searchableGroups = [...baseGroups];
219 if (!input.isInSubmenu && !isActionsFilter) {
220 if (input.projectSearchItems.length > 0) {
221 searchableGroups.push({
222 value: "projects-search",
223 label: "Projects",
224 items: input.projectSearchItems,
225 });
226 }
227 if (input.threadSearchItems.length > 0) {
228 searchableGroups.push({
229 value: "threads-search",
230 label: "Threads",
231 items: input.threadSearchItems,
232 });
233 }
234 }
235​
236 return searchableGroups.flatMap((group) => {
237 const items = group.items
238 .map((item, index) => {
239 const haystack = normalizeSearchText(item.searchTerms.join(" "));
240 if (!haystack.includes(normalizedQuery)) {
241 return null;
242 }
243​
244 return {
245 item,
246 index,
247 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
248 };
249 })
250 .filter(
251 (entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
252 entry !== null,
253 )
254 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
255 .map((entry) => entry.item);
256​
257 if (items.length === 0) {
258 return [];
259 }
260​
261 return [{ value: group.value, label: group.label, items }];
262 });
264​
265export function buildBrowseGroups(input: {
266 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
267 browseQuery: string;
268 canBrowseUp: boolean;
269 upIcon: ReactNode;
270 directoryIcon: ReactNode;
271 browseUp: () => void;
272 browseTo: (name: string) => void;
273}): CommandPaletteGroup[] {
274 const items: CommandPaletteActionItem[] = [];
275​
276 if (input.canBrowseUp) {
277 items.push({
278 kind: "action",
279 value: "browse:up",
280 searchTerms: [input.browseQuery, ".."],
281 title: "..",
282 icon: input.upIcon,
283 keepOpen: true,
284 run: async () => {
285 input.browseUp();
286 },
287 });
288 }
289​
290 for (const entry of input.browseEntries) {
291 items.push({
292 kind: "action",
293 value: `browse:${entry.fullPath}`,
294 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
295 title: entry.name,
296 icon: input.directoryIcon,
297 keepOpen: true,
298 run: async () => {
299 input.browseTo(entry.name);
300 },
301 });
302 }
303​
304 return [{ value: "directories", label: "Directories", items }];
306​
307export function getCommandPaletteMode(input: {
308 currentView: CommandPaletteView | null;
309 isBrowsing: boolean;
310}): CommandPaletteMode {
311 if (input.currentView) {
312 return input.isBrowsing ? "submenu-browse" : "submenu";
313 }
314 return input.isBrowsing ? "root-browse" : "root";
316​
317export function buildRootGroups(input: {
318 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
319 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
320}): CommandPaletteGroup[] {
321 const groups: CommandPaletteGroup[] = [];
322 if (input.actionItems.length > 0) {
323 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
324 }
325 if (input.recentThreadItems.length > 0) {
326 groups.push({
327 value: "recent-threads",
328 label: "Recent Threads",
329 items: input.recentThreadItems,
330 });
331 }
332 return groups;
334​
335export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
336 switch (mode) {
337 case "root":
338 return "Search commands, projects, and threads...";
339 case "root-browse":
340 return "Enter project path (e.g. ~/projects/my-app)";
341 case "submenu":
342 return "Search...";
343 case "submenu-browse":
344 return "Enter path (e.g. ~/projects/my-app)";
345 }