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

CommandPalette.logic.ts

459 lines14.8 KB

1import {
2 type FilesystemBrowseEntry,
3 type KeybindingCommand,
4 THREAD_JUMP_KEYBINDING_COMMANDS,
5} from "@t3tools/contracts";
6import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
7import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
8import * as Arr from "effect/Array";
9import * as Result from "effect/Result";
10import { type ReactNode } from "react";
11import { sortThreads } from "../lib/threadSort";
12import { formatRelativeTimeLabel } from "../timestampFormat";
13import { type Project, type SidebarThreadSummary, type Thread } from "../types";
14​
15export const RECENT_THREAD_LIMIT = 12;
16export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
17export const ADDON_ICON_CLASS = "size-4";
18​
19export function browseInputEndPaddingClass(input: {
20 readonly willCreateProjectPath: boolean;
21 readonly hasHighlightedBrowseItem: boolean;
22}): string {
23 if (input.willCreateProjectPath) {
24 return "*:data-[slot=autocomplete-input]:pe-38!";
25 }
26 if (input.hasHighlightedBrowseItem) {
27 return "*:data-[slot=autocomplete-input]:pe-30!";
28 }
29 return "*:data-[slot=autocomplete-input]:pe-24!";
31​
32/**
33 * The global search overlay hosts three mutually exclusive surfaces: the
34 * command palette (⌘K), the project file picker (⌘P), and project content
35 * search (⇧⌘F). One reducer owns open/mode state so the surfaces can never
36 * stack and re-triggering a mode's shortcut toggles it closed.
37 */
38export type SearchOverlayMode = "command" | "files" | "content";
39​
40export interface CommandPaletteOpenIntent {
41 readonly kind: "add-project" | "new-thread-in";
43​
44export interface CommandPaletteUiState {
45 readonly open: boolean;
46 readonly mode: SearchOverlayMode;
47 readonly openIntent: CommandPaletteOpenIntent | null;
49​
50export type CommandPaletteUiAction =
51 | { readonly _tag: "SetOpen"; readonly open: boolean }
52 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
53 | { readonly _tag: "OpenAddProject" }
54 | { readonly _tag: "OpenNewThreadIn" }
55 | { readonly _tag: "ClearOpenIntent" };
56​
57export function reduceCommandPaletteUiState(
58 state: CommandPaletteUiState,
59 action: CommandPaletteUiAction,
60): CommandPaletteUiState {
61 switch (action._tag) {
62 case "SetOpen":
63 return {
64 open: action.open,
65 mode: "command",
66 openIntent: action.open ? state.openIntent : null,
67 };
68 case "ToggleMode":
69 return state.open && state.mode === action.mode
70 ? { open: false, mode: "command", openIntent: null }
71 : { open: true, mode: action.mode, openIntent: null };
72 case "OpenAddProject":
73 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
74 case "OpenNewThreadIn":
75 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
76 case "ClearOpenIntent":
77 return state.openIntent ? { ...state, openIntent: null } : state;
78 }
80​
81export interface CommandPaletteThreadContentMatch {
82 readonly source: "user" | "assistant";
83 readonly snippet: string;
84 readonly query: string;
86​
87export interface CommandPaletteItem {
88 readonly kind: "action" | "submenu";
89 readonly value: string;
90 readonly searchTerms: ReadonlyArray<string>;
91 readonly title: ReactNode;
92 readonly description?: ReactNode;
93 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
94 readonly timestamp?: string;
95 readonly icon: ReactNode;
96 readonly disabled?: boolean;
97 /** Optional content rendered inline before the title text. */
98 readonly titleLeadingContent?: ReactNode;
99 /** Optional content rendered inline after the title text (before the timestamp). */
100 readonly titleTrailingContent?: ReactNode;
101 readonly shortcutCommand?: KeybindingCommand;
103​
104export interface CommandPaletteActionItem extends CommandPaletteItem {
105 readonly kind: "action";
106 readonly keepOpen?: boolean;
107 readonly run: () => Promise<void>;
109​
110export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
111 readonly kind: "submenu";
112 readonly addonIcon: ReactNode;
113 readonly groups: ReadonlyArray<CommandPaletteGroup>;
114 readonly initialQuery?: string;
116​
117export interface CommandPaletteGroup {
118 readonly value: string;
119 readonly label: string;
120 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
122​
123export interface CommandPaletteView {
124 readonly addonIcon: ReactNode;
125 readonly groups: ReadonlyArray<CommandPaletteGroup>;
126 readonly initialQuery?: string;
128​
129export function enumerateCommandPaletteItems(
130 items: ReadonlyArray<CommandPaletteActionItem>,
131): CommandPaletteActionItem[] {
132 return items.map((item, index) => {
133 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
134 if (shortcutCommand) return { ...item, shortcutCommand };
135​
136 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
137 return itemWithoutShortcut;
138 });
140​
141export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
142​
143export function normalizeSearchText(value: string): string {
144 return value.trim().toLowerCase().replace(/\s+/g, " ");
146​
147export function buildProjectActionItems(input: {
148 projects: ReadonlyArray<Project>;
149 valuePrefix: string;
150 icon: (project: Project) => ReactNode;
151 runProject: (project: Project) => Promise<void>;
152 searchTerms?: (project: Project) => ReadonlyArray<string>;
153 shortcutCommand?: KeybindingCommand;
154}): CommandPaletteActionItem[] {
155 return input.projects.map((project) => ({
156 kind: "action",
157 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
158 searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
159 title: project.title,
160 description: project.workspaceRoot,
161 icon: input.icon(project),
162 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
163 run: async () => {
164 await input.runProject(project);
165 },
166 }));
168​
169export type BuildThreadActionItemsThread = Pick<
170 SidebarThreadSummary,
171 | "archivedAt"
172 | "branch"
173 | "createdAt"
174 | "environmentId"
175 | "id"
176 | "modelSelection"
177 | "projectId"
178 | "session"
179 | "title"
180 | "worktreePath"
181> & {
182 updatedAt: string;
183 latestUserMessageAt?: string | null;
184};
185​
186export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
187 threads: ReadonlyArray<TThread>;
188 activeThreadId?: Thread["id"];
189 projectTitleById: ReadonlyMap<Project["id"], string>;
190 sortOrder: SidebarThreadSortOrder;
191 icon: ReactNode;
192 /** Optional content rendered inline before the title text per-thread. */
193 renderLeadingContent?: (thread: TThread) => ReactNode;
194 /** Optional content rendered inline after the title text per-thread. */
195 renderTrailingContent?: (thread: TThread) => ReactNode;
196 /** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
197 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
198 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
199 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
200 limit?: number;
201}): CommandPaletteActionItem[] {
202 const sortedThreads = sortThreads(
203 input.threads.filter((thread) => thread.archivedAt === null),
204 input.sortOrder,
205 );
206 const visibleThreads =
207 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
208​
209 return visibleThreads.map((thread) => {
210 const projectTitle = input.projectTitleById.get(thread.projectId);
211 const descriptionParts: string[] = [];
212​
213 if (projectTitle) {
214 descriptionParts.push(projectTitle);
215 }
216 if (thread.branch) {
217 descriptionParts.push(`#${thread.branch}`);
218 }
219 if (thread.id === input.activeThreadId) {
220 descriptionParts.push("Current thread");
221 }
222​
223 const leadingContent = input.renderLeadingContent?.(thread);
224 const trailingContent = input.renderTrailingContent?.(thread);
225 const contentMatch = input.getContentMatch?.(thread);
226 const description = input.renderDescription
227 ? input.renderDescription(thread, { projectTitle })
228 : descriptionParts.join(` · `);
229​
230 return Object.assign(
231 {
232 kind: "action" as const,
233 value: `thread:${thread.id}`,
234 searchTerms: [
235 thread.title,
236 projectTitle ?? ``,
237 thread.branch ?? ``,
238 contentMatch?.snippet ?? ``,
239 ],
240 title: thread.title,
241 description,
242 timestamp: formatRelativeTimeLabel(
243 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
244 ),
245 icon: input.icon,
246 },
247 leadingContent ? { titleLeadingContent: leadingContent } : {},
248 trailingContent ? { titleTrailingContent: trailingContent } : {},
249 contentMatch ? { threadContentMatch: contentMatch } : {},
250 {
251 run: async () => {
252 await input.runThread(thread);
253 },
254 },
255 );
256 });
258​
259function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
260 const normalizedField = normalizeSearchText(field);
261 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
262 return Number.NEGATIVE_INFINITY;
263 }
264 if (normalizedField === normalizedQuery) {
265 return 3;
266 }
267 if (normalizedField.startsWith(normalizedQuery)) {
268 return 2;
269 }
270 return 1;
272​
273function rankCommandPaletteItemMatch(
274 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
275 normalizedQuery: string,
276): number {
277 const terms = item.searchTerms.filter((term) => term.length > 0);
278 if (terms.length === 0) {
279 return 0;
280 }
281​
282 for (const [index, field] of terms.entries()) {
283 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
284 if (fieldRank !== Number.NEGATIVE_INFINITY) {
285 return 1_000 - index * 100 + fieldRank;
286 }
287 }
288​
289 return 0;
291​
292export function filterCommandPaletteGroups(input: {
293 activeGroups: ReadonlyArray<CommandPaletteGroup>;
294 query: string;
295 isInSubmenu: boolean;
296 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
297 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
298}): CommandPaletteGroup[] {
299 const isActionsFilter = input.query.startsWith(">");
300 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
301 const normalizedQuery = normalizeSearchText(searchQuery);
302​
303 if (normalizedQuery.length === 0) {
304 if (isActionsFilter) {
305 return input.activeGroups.filter((group) => group.value === "actions");
306 }
307 return [...input.activeGroups];
308 }
309​
310 let baseGroups = [...input.activeGroups];
311 if (isActionsFilter) {
312 baseGroups = baseGroups.filter((group) => group.value === "actions");
313 } else if (!input.isInSubmenu) {
314 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
315 }
316​
317 const searchableGroups = [...baseGroups];
318 if (!input.isInSubmenu && !isActionsFilter) {
319 if (input.projectSearchItems.length > 0) {
320 searchableGroups.push({
321 value: "projects-search",
322 label: "Projects",
323 items: input.projectSearchItems,
324 });
325 }
326 if (input.threadSearchItems.length > 0) {
327 searchableGroups.push({
328 value: "threads-search",
329 label: "Threads",
330 items: input.threadSearchItems,
331 });
332 }
333 }
334​
335 return searchableGroups.flatMap((group) => {
336 const items = Arr.filterMap(group.items, (item, index) => {
337 const haystack = normalizeSearchText(item.searchTerms.join(" "));
338 if (!haystack.includes(normalizedQuery)) {
339 return Result.failVoid;
340 }
341​
342 return Result.succeed({
343 item,
344 index,
345 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
346 });
347 })
348 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
349 .map((entry) => entry.item);
350​
351 if (items.length === 0) {
352 return [];
353 }
354​
355 return [{ value: group.value, label: group.label, items }];
356 });
358​
359export function buildBrowseGroups(input: {
360 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
361 browseQuery: string;
362 canBrowseUp: boolean;
363 upIcon: ReactNode;
364 directoryIcon: ReactNode;
365 browseUp: () => void | Promise<void>;
366 browseTo: (name: string) => void | Promise<void>;
367}): CommandPaletteGroup[] {
368 const items: CommandPaletteActionItem[] = [];
369​
370 if (input.canBrowseUp) {
371 items.push({
372 kind: "action",
373 value: "browse:up",
374 searchTerms: [input.browseQuery, ".."],
375 title: "..",
376 icon: input.upIcon,
377 keepOpen: true,
378 run: async () => {
379 await input.browseUp();
380 },
381 });
382 }
383​
384 for (const entry of input.browseEntries) {
385 items.push({
386 kind: "action",
387 value: `browse:${entry.fullPath}`,
388 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
389 title: entry.name,
390 icon: input.directoryIcon,
391 keepOpen: true,
392 run: async () => {
393 await input.browseTo(entry.name);
394 },
395 });
396 }
397​
398 return [{ value: "directories", label: "Directories", items }];
400​
401export function filterPinnedBrowseEntries(input: {
402 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
403 filterQuery: string;
404 pinnedDirectoryName: string;
405 caseSensitive: boolean;
406}): ReturnType<typeof filterFilesystemBrowseEntries> {
407 const namesMatch = (left: string, right: string) =>
408 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
409 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
410 ? ""
411 : input.filterQuery;
412 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
413 const exactEntry =
414 input.filterQuery.length > 0
415 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
416 : null;
417 return { visibleEntries, exactEntry };
419​
420export function getCommandPaletteMode(input: {
421 currentView: CommandPaletteView | null;
422 isBrowsing: boolean;
423}): CommandPaletteMode {
424 if (input.currentView) {
425 return input.isBrowsing ? "submenu-browse" : "submenu";
426 }
427 return input.isBrowsing ? "root-browse" : "root";
429​
430export function buildRootGroups(input: {
431 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
432 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
433}): CommandPaletteGroup[] {
434 const groups: CommandPaletteGroup[] = [];
435 if (input.actionItems.length > 0) {
436 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
437 }
438 if (input.recentThreadItems.length > 0) {
439 groups.push({
440 value: "recent-threads",
441 label: "Recent Threads",
442 items: input.recentThreadItems,
443 });
444 }
445 return groups;
447​
448export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
449 switch (mode) {
450 case "root":
451 return "Search commands, projects, and threads...";
452 case "root-browse":
453 return "Enter project path (e.g. ~/projects/my-app)";
454 case "submenu":
455 return "Search...";
456 case "submenu-browse":
457 return "Enter path (e.g. ~/projects/my-app)";
458 }