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

CommandPalette.logic.ts

458 lines14.9 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 action.open
64 ? { open: true, mode: "command", openIntent: state.openIntent }
65 : { ...state, open: false, openIntent: null };
66 case "ToggleMode":
67 return state.open && state.mode === action.mode
68 ? { ...state, open: false, openIntent: null }
69 : { open: true, mode: action.mode, openIntent: null };
70 case "OpenAddProject":
71 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
72 case "OpenNewThreadIn":
73 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
74 case "ClearOpenIntent":
75 return state.openIntent ? { ...state, openIntent: null } : state;
76 }
78​
79export interface CommandPaletteThreadContentMatch {
80 readonly source: "user" | "assistant";
81 readonly snippet: string;
82 readonly query: string;
84​
85export interface CommandPaletteItem {
86 readonly kind: "action" | "submenu";
87 readonly value: string;
88 readonly searchTerms: ReadonlyArray<string>;
89 readonly title: ReactNode;
90 readonly description?: ReactNode;
91 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
92 readonly timestamp?: string;
93 readonly icon: ReactNode;
94 readonly disabled?: boolean;
95 /** Optional content rendered inline before the title text. */
96 readonly titleLeadingContent?: ReactNode;
97 /** Optional content rendered inline after the title text (before the timestamp). */
98 readonly titleTrailingContent?: ReactNode;
99 readonly shortcutCommand?: KeybindingCommand;
101​
102export interface CommandPaletteActionItem extends CommandPaletteItem {
103 readonly kind: "action";
104 readonly keepOpen?: boolean;
105 readonly run: () => Promise<void>;
107​
108export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
109 readonly kind: "submenu";
110 readonly addonIcon: ReactNode;
111 readonly groups: ReadonlyArray<CommandPaletteGroup>;
112 readonly initialQuery?: string;
114​
115export interface CommandPaletteGroup {
116 readonly value: string;
117 readonly label: string;
118 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
120​
121export interface CommandPaletteView {
122 readonly addonIcon: ReactNode;
123 readonly groups: ReadonlyArray<CommandPaletteGroup>;
124 readonly initialQuery?: string;
126​
127export function enumerateCommandPaletteItems(
128 items: ReadonlyArray<CommandPaletteActionItem>,
129): CommandPaletteActionItem[] {
130 return items.map((item, index) => {
131 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
132 if (shortcutCommand) return { ...item, shortcutCommand };
133​
134 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
135 return itemWithoutShortcut;
136 });
138​
139export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
140​
141export function normalizeSearchText(value: string): string {
142 return value.trim().toLowerCase().replace(/\s+/g, " ");
144​
145export function buildProjectActionItems(input: {
146 projects: ReadonlyArray<Project>;
147 valuePrefix: string;
148 icon: (project: Project) => ReactNode;
149 runProject: (project: Project) => Promise<void>;
150 searchTerms?: (project: Project) => ReadonlyArray<string>;
151 renderDescription?: (project: Project) => ReactNode;
152 shortcutCommand?: KeybindingCommand;
153}): CommandPaletteActionItem[] {
154 return input.projects.map((project) => ({
155 kind: "action",
156 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
157 searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
158 title: project.title,
159 description: input.renderDescription?.(project) ?? project.workspaceRoot,
160 icon: input.icon(project),
161 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
162 run: async () => {
163 await input.runProject(project);
164 },
165 }));
167​
168export type BuildThreadActionItemsThread = Pick<
169 SidebarThreadSummary,
170 | "archivedAt"
171 | "branch"
172 | "createdAt"
173 | "environmentId"
174 | "id"
175 | "modelSelection"
176 | "projectId"
177 | "session"
178 | "title"
179 | "worktreePath"
180> & {
181 updatedAt: string;
182 latestUserMessageAt?: string | null;
183};
184​
185export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
186 threads: ReadonlyArray<TThread>;
187 activeThreadId?: Thread["id"];
188 projectTitleById: ReadonlyMap<Project["id"], string>;
189 sortOrder: SidebarThreadSortOrder;
190 icon: ReactNode;
191 /** Optional content rendered inline before the title text per-thread. */
192 renderLeadingContent?: (thread: TThread) => ReactNode;
193 /** Optional content rendered inline after the title text per-thread. */
194 renderTrailingContent?: (thread: TThread) => ReactNode;
195 /** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
196 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
197 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
198 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
199 limit?: number;
200}): CommandPaletteActionItem[] {
201 const sortedThreads = sortThreads(
202 input.threads.filter((thread) => thread.archivedAt === null),
203 input.sortOrder,
204 );
205 const visibleThreads =
206 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
207​
208 return visibleThreads.map((thread) => {
209 const projectTitle = input.projectTitleById.get(thread.projectId);
210 const descriptionParts: string[] = [];
211​
212 if (projectTitle) {
213 descriptionParts.push(projectTitle);
214 }
215 if (thread.branch) {
216 descriptionParts.push(`#${thread.branch}`);
217 }
218 if (thread.id === input.activeThreadId) {
219 descriptionParts.push("Current thread");
220 }
221​
222 const leadingContent = input.renderLeadingContent?.(thread);
223 const trailingContent = input.renderTrailingContent?.(thread);
224 const contentMatch = input.getContentMatch?.(thread);
225 const description = input.renderDescription
226 ? input.renderDescription(thread, { projectTitle })
227 : descriptionParts.join(` · `);
228​
229 return Object.assign(
230 {
231 kind: "action" as const,
232 value: `thread:${thread.id}`,
233 searchTerms: [
234 thread.title,
235 projectTitle ?? ``,
236 thread.branch ?? ``,
237 contentMatch?.snippet ?? ``,
238 ],
239 title: thread.title,
240 description,
241 timestamp: formatRelativeTimeLabel(
242 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
243 ),
244 icon: input.icon,
245 },
246 leadingContent ? { titleLeadingContent: leadingContent } : {},
247 trailingContent ? { titleTrailingContent: trailingContent } : {},
248 contentMatch ? { threadContentMatch: contentMatch } : {},
249 {
250 run: async () => {
251 await input.runThread(thread);
252 },
253 },
254 );
255 });
257​
258function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
259 const normalizedField = normalizeSearchText(field);
260 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
261 return Number.NEGATIVE_INFINITY;
262 }
263 if (normalizedField === normalizedQuery) {
264 return 3;
265 }
266 if (normalizedField.startsWith(normalizedQuery)) {
267 return 2;
268 }
269 return 1;
271​
272function rankCommandPaletteItemMatch(
273 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
274 normalizedQuery: string,
275): number {
276 const terms = item.searchTerms.filter((term) => term.length > 0);
277 if (terms.length === 0) {
278 return 0;
279 }
280​
281 for (const [index, field] of terms.entries()) {
282 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
283 if (fieldRank !== Number.NEGATIVE_INFINITY) {
284 return 1_000 - index * 100 + fieldRank;
285 }
286 }
287​
288 return 0;
290​
291export function filterCommandPaletteGroups(input: {
292 activeGroups: ReadonlyArray<CommandPaletteGroup>;
293 query: string;
294 isInSubmenu: boolean;
295 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
296 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
297}): CommandPaletteGroup[] {
298 const isActionsFilter = input.query.startsWith(">");
299 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
300 const normalizedQuery = normalizeSearchText(searchQuery);
301​
302 if (normalizedQuery.length === 0) {
303 if (isActionsFilter) {
304 return input.activeGroups.filter((group) => group.value === "actions");
305 }
306 return [...input.activeGroups];
307 }
308​
309 let baseGroups = [...input.activeGroups];
310 if (isActionsFilter) {
311 baseGroups = baseGroups.filter((group) => group.value === "actions");
312 } else if (!input.isInSubmenu) {
313 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
314 }
315​
316 const searchableGroups = [...baseGroups];
317 if (!input.isInSubmenu && !isActionsFilter) {
318 if (input.projectSearchItems.length > 0) {
319 searchableGroups.push({
320 value: "projects-search",
321 label: "Projects",
322 items: input.projectSearchItems,
323 });
324 }
325 if (input.threadSearchItems.length > 0) {
326 searchableGroups.push({
327 value: "threads-search",
328 label: "Threads",
329 items: input.threadSearchItems,
330 });
331 }
332 }
333​
334 return searchableGroups.flatMap((group) => {
335 const items = Arr.filterMap(group.items, (item, index) => {
336 const haystack = normalizeSearchText(item.searchTerms.join(" "));
337 if (!haystack.includes(normalizedQuery)) {
338 return Result.failVoid;
339 }
340​
341 return Result.succeed({
342 item,
343 index,
344 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
345 });
346 })
347 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
348 .map((entry) => entry.item);
349​
350 if (items.length === 0) {
351 return [];
352 }
353​
354 return [{ value: group.value, label: group.label, items }];
355 });
357​
358export function buildBrowseGroups(input: {
359 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
360 browseQuery: string;
361 canBrowseUp: boolean;
362 upIcon: ReactNode;
363 directoryIcon: ReactNode;
364 browseUp: () => void | Promise<void>;
365 browseTo: (name: string) => void | Promise<void>;
366}): CommandPaletteGroup[] {
367 const items: CommandPaletteActionItem[] = [];
368​
369 if (input.canBrowseUp) {
370 items.push({
371 kind: "action",
372 value: "browse:up",
373 searchTerms: [input.browseQuery, ".."],
374 title: "..",
375 icon: input.upIcon,
376 keepOpen: true,
377 run: async () => {
378 await input.browseUp();
379 },
380 });
381 }
382​
383 for (const entry of input.browseEntries) {
384 items.push({
385 kind: "action",
386 value: `browse:${entry.fullPath}`,
387 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
388 title: entry.name,
389 icon: input.directoryIcon,
390 keepOpen: true,
391 run: async () => {
392 await input.browseTo(entry.name);
393 },
394 });
395 }
396​
397 return [{ value: "directories", label: "Directories", items }];
399​
400export function filterPinnedBrowseEntries(input: {
401 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
402 filterQuery: string;
403 pinnedDirectoryName: string;
404 caseSensitive: boolean;
405}): ReturnType<typeof filterFilesystemBrowseEntries> {
406 const namesMatch = (left: string, right: string) =>
407 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
408 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
409 ? ""
410 : input.filterQuery;
411 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
412 const exactEntry =
413 input.filterQuery.length > 0
414 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
415 : null;
416 return { visibleEntries, exactEntry };
418​
419export function getCommandPaletteMode(input: {
420 currentView: CommandPaletteView | null;
421 isBrowsing: boolean;
422}): CommandPaletteMode {
423 if (input.currentView) {
424 return input.isBrowsing ? "submenu-browse" : "submenu";
425 }
426 return input.isBrowsing ? "root-browse" : "root";
428​
429export function buildRootGroups(input: {
430 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
431 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
432}): CommandPaletteGroup[] {
433 const groups: CommandPaletteGroup[] = [];
434 if (input.actionItems.length > 0) {
435 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
436 }
437 if (input.recentThreadItems.length > 0) {
438 groups.push({
439 value: "recent-threads",
440 label: "Recent Threads",
441 items: input.recentThreadItems,
442 });
443 }
444 return groups;
446​
447export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
448 switch (mode) {
449 case "root":
450 return "Search commands, projects, and threads...";
451 case "root-browse":
452 return "Enter project path (e.g. ~/projects/my-app)";
453 case "submenu":
454 return "Search...";
455 case "submenu-browse":
456 return "Enter path (e.g. ~/projects/my-app)";
457 }