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

CommandPalette.logic.ts

557 lines18.5 KB

1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
3import {
4 type EnvironmentId,
5 type FilesystemBrowseEntry,
6 type KeybindingCommand,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8} from "@t3tools/contracts";
9import { filterFilesystemBrowseEntries } from "@t3tools/client-runtime/state/filesystem";
10import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
11import * as Arr from "effect/Array";
12import * as Result from "effect/Result";
13import { type ReactNode } from "react";
14import { sortThreads } from "../lib/threadSort";
15import { normalizeSearchText } from "../lib/utils";
16import { formatRelativeTimeLabel } from "../timestampFormat";
17import { type Project, type SidebarThreadSummary, type Thread } from "../types";
18​
19export const RECENT_THREAD_LIMIT = 12;
20export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
21export const ADDON_ICON_CLASS = "size-4";
22​
23/** A PR's relations include archived threads that normal palette search omits. */
24export function buildLinkedThreadActionItems(
25 input: CommandPaletteLinkedThreads & {
26 query: string;
27 icon: ReactNode;
28 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
29 },
30): CommandPaletteActionItem[] {
31 return input.threads.map((thread) => ({
32 kind: "action",
33 value: `thread:${input.environmentId}:${thread.id}`,
34 title: thread.title || "Untitled thread",
35 description: thread.archivedAt === null ? "Linked thread" : "Archived thread",
36 searchTerms: [input.query, thread.title],
37 icon: input.icon,
38 run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }),
39 }));
41​
42export function browseInputEndPaddingClass(input: {
43 readonly willCreateProjectPath: boolean;
44 readonly hasHighlightedBrowseItem: boolean;
45}): string {
46 if (input.willCreateProjectPath) {
47 return "*:data-[slot=autocomplete-input]:pe-38!";
48 }
49 if (input.hasHighlightedBrowseItem) {
50 return "*:data-[slot=autocomplete-input]:pe-30!";
51 }
52 return "*:data-[slot=autocomplete-input]:pe-24!";
54​
55/**
56 * The global search overlay hosts three mutually exclusive surfaces: the
57 * command palette (⌘K), the project file picker (⌘P), and project content
58 * search (⇧⌘F). One reducer owns open/mode state so the surfaces can never
59 * stack and re-triggering a mode's shortcut toggles it closed.
60 */
61export type SearchOverlayMode = "command" | "files" | "content";
62​
63export type CommandPaletteOpenIntent =
64 | { readonly kind: "add-project" | "new-thread-in" | "change-theme" }
65 | {
66 readonly kind: "search";
67 readonly query: string;
68 readonly linkedThreads?: CommandPaletteLinkedThreads;
69 };
70​
71export interface CommandPaletteUiState {
72 readonly open: boolean;
73 readonly mode: SearchOverlayMode;
74 readonly openIntent: CommandPaletteOpenIntent | null;
76​
77export type CommandPaletteUiAction =
78 | { readonly _tag: "SetOpen"; readonly open: boolean }
79 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
80 | {
81 readonly _tag: "OpenSearch";
82 readonly query: string;
83 readonly linkedThreads?: CommandPaletteLinkedThreads;
84 }
85 | { readonly _tag: "OpenAddProject" }
86 | { readonly _tag: "OpenNewThreadIn" }
87 | { readonly _tag: "OpenChangeTheme" }
88 | { readonly _tag: "ClearOpenIntent" };
89​
90export function reduceCommandPaletteUiState(
91 state: CommandPaletteUiState,
92 action: CommandPaletteUiAction,
93): CommandPaletteUiState {
94 switch (action._tag) {
95 case "SetOpen":
96 return action.open
97 ? { open: true, mode: "command", openIntent: state.openIntent }
98 : { ...state, open: false, openIntent: null };
99 case "ToggleMode":
100 return state.open && state.mode === action.mode
101 ? { ...state, open: false, openIntent: null }
102 : { open: true, mode: action.mode, openIntent: null };
103 case "OpenSearch":
104 return {
105 open: true,
106 mode: "command",
107 openIntent: {
108 kind: "search",
109 query: action.query,
110 ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
111 },
112 };
113 case "OpenAddProject":
114 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
115 case "OpenNewThreadIn":
116 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
117 case "OpenChangeTheme":
118 return { open: true, mode: "command", openIntent: { kind: "change-theme" } };
119 case "ClearOpenIntent":
120 return state.openIntent ? { ...state, openIntent: null } : state;
121 }
123​
124export interface CommandPaletteThreadContentMatch {
125 readonly source: "user" | "assistant";
126 readonly snippet: string;
127 readonly query: string;
129​
130export interface CommandPaletteItem {
131 readonly kind: "action" | "submenu";
132 readonly value: string;
133 readonly searchTerms: ReadonlyArray<string>;
134 readonly title: ReactNode;
135 readonly description?: ReactNode;
136 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
137 readonly timestamp?: string;
138 readonly icon: ReactNode;
139 readonly disabled?: boolean;
140 /** Optional content rendered inline before the title text. */
141 readonly titleLeadingContent?: ReactNode;
142 /** Optional content rendered inline after the title text (before the timestamp). */
143 readonly titleTrailingContent?: ReactNode;
144 readonly shortcutCommand?: KeybindingCommand;
145 /** Sorts after every other match in its group; see `SettingsSearchItem.secondary`. */
146 readonly secondary?: boolean;
148​
149export interface CommandPaletteActionItem extends CommandPaletteItem {
150 readonly kind: "action";
151 readonly keepOpen?: boolean;
152 readonly run: () => Promise<void>;
154​
155export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
156 readonly kind: "submenu";
157 readonly addonIcon: ReactNode;
158 readonly groups: ReadonlyArray<CommandPaletteGroup>;
159 readonly initialQuery?: string;
161​
162export interface CommandPaletteGroup {
163 readonly value: string;
164 readonly label: string;
165 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
167​
168export interface CommandPaletteView {
169 readonly addonIcon: ReactNode;
170 readonly groups: ReadonlyArray<CommandPaletteGroup>;
171 readonly initialQuery?: string;
173​
174export function enumerateCommandPaletteItems(
175 items: ReadonlyArray<CommandPaletteActionItem>,
176): CommandPaletteActionItem[] {
177 return items.map((item, index) => {
178 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
179 if (shortcutCommand) return { ...item, shortcutCommand };
180​
181 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
182 return itemWithoutShortcut;
183 });
185​
186export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
187​
188// A project as the palette shows it. `displayName` is the grouped label (for
189// example "owner/repo" when projects are merged across machines). Keep `title`
190// as the real project title: the automatic project icon is derived from it, and
191// every other surface uses the real title, so overriding it desyncs the icon.
192export type CommandPaletteProject = Project & { readonly displayName: string };
193​
194export function buildCommandPaletteProjectMetadata(input: {
195 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
196 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
197}) {
198 const searchTerms: string[] = [];
199 const environmentLabels = new Set<string>();
200​
201 for (const project of input.projects) {
202 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
203 searchTerms.push(project.title, project.workspaceRoot, label);
204 environmentLabels.add(label);
205 }
206​
207 return { searchTerms, environmentLabels: [...environmentLabels] };
209​
210export function buildProjectActionItems(input: {
211 projects: ReadonlyArray<CommandPaletteProject>;
212 valuePrefix: string;
213 icon: (project: CommandPaletteProject) => ReactNode;
214 runProject: (project: CommandPaletteProject) => Promise<void>;
215 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
216 renderDescription?: (project: CommandPaletteProject) => ReactNode;
217 shortcutCommand?: KeybindingCommand;
218}): CommandPaletteActionItem[] {
219 return input.projects.map((project) => ({
220 kind: "action",
221 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
222 searchTerms: [
223 project.displayName,
224 project.title,
225 project.workspaceRoot,
226 ...(input.searchTerms?.(project) ?? []),
227 ],
228 title: project.displayName,
229 description: input.renderDescription?.(project) ?? project.workspaceRoot,
230 icon: input.icon(project),
231 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
232 run: async () => {
233 await input.runProject(project);
234 },
235 }));
237​
238export type BuildThreadActionItemsThread = Pick<
239 SidebarThreadSummary,
240 | "archivedAt"
241 | "branch"
242 | "createdAt"
243 | "environmentId"
244 | "id"
245 | "modelSelection"
246 | "projectId"
247 | "session"
248 | "title"
249 | "worktreePath"
250> & {
251 pullRequests?: SidebarThreadSummary["pullRequests"];
252 updatedAt: string;
253 latestUserMessageAt?: string | null;
254};
255​
256export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
257 threads: ReadonlyArray<TThread>;
258 activeThreadId?: Thread["id"];
259 projectTitleById: ReadonlyMap<Project["id"], string>;
260 sortOrder: SidebarThreadSortOrder;
261 icon: ReactNode;
262 /** Optional content rendered inline before the title text per-thread. */
263 renderLeadingContent?: (thread: TThread) => ReactNode;
264 /** Optional content rendered inline after the title text per-thread. */
265 renderTrailingContent?: (thread: TThread) => ReactNode;
266 /** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
267 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
268 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
269 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
270 limit?: number;
271}): CommandPaletteActionItem[] {
272 const sortedThreads = sortThreads(
273 input.threads.filter((thread) => thread.archivedAt === null),
274 input.sortOrder,
275 );
276 const visibleThreads =
277 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
278​
279 return visibleThreads.map((thread) => {
280 const projectTitle = input.projectTitleById.get(thread.projectId);
281 const descriptionParts: string[] = [];
282​
283 if (projectTitle) {
284 descriptionParts.push(projectTitle);
285 }
286 if (thread.branch) {
287 descriptionParts.push(`#${thread.branch}`);
288 }
289 if (thread.id === input.activeThreadId) {
290 descriptionParts.push("Current thread");
291 }
292​
293 const leadingContent = input.renderLeadingContent?.(thread);
294 const trailingContent = input.renderTrailingContent?.(thread);
295 const contentMatch = input.getContentMatch?.(thread);
296 const description = input.renderDescription
297 ? input.renderDescription(thread, { projectTitle })
298 : descriptionParts.join(` · `);
299​
300 return Object.assign(
301 {
302 kind: "action" as const,
303 value: `thread:${thread.id}`,
304 searchTerms: [
305 thread.title,
306 ...threadPullRequestSearchTerms(thread),
307 projectTitle ?? ``,
308 thread.branch ?? ``,
309 contentMatch?.snippet ?? ``,
310 // Last so pasted IDs never outrank title matches for shared substrings.
311 thread.id,
312 ],
313 title: thread.title,
314 description,
315 timestamp: formatRelativeTimeLabel(
316 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
317 ),
318 icon: input.icon,
319 },
320 leadingContent ? { titleLeadingContent: leadingContent } : {},
321 trailingContent ? { titleTrailingContent: trailingContent } : {},
322 contentMatch ? { threadContentMatch: contentMatch } : {},
323 {
324 run: async () => {
325 await input.runThread(thread);
326 },
327 },
328 );
329 });
331​
332function rankSearchFieldMatch(
333 field: string,
334 normalizedQuery: string,
335 queryTokens: ReadonlyArray<string>,
336): number {
337 const normalizedField = normalizeSearchText(field);
338 if (
339 normalizedField.length === 0 ||
340 !queryTokens.every((token) => normalizedField.includes(token))
341 ) {
342 return Number.NEGATIVE_INFINITY;
343 }
344 if (normalizedField === normalizedQuery) {
345 return 3;
346 }
347 if (normalizedField.startsWith(normalizedQuery)) {
348 return 2;
349 }
350 if (normalizedField.includes(normalizedQuery)) {
351 return 1;
352 }
353 return 0;
355​
356function rankCommandPaletteItemMatch(
357 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
358 normalizedQuery: string,
359 queryTokens: ReadonlyArray<string>,
360): number {
361 const terms = item.searchTerms.filter((term) => term.length > 0);
362 if (terms.length === 0) {
363 return 0;
364 }
365​
366 for (const [index, field] of terms.entries()) {
367 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
368 if (fieldRank !== Number.NEGATIVE_INFINITY) {
369 return 1_000 - index * 100 + fieldRank;
370 }
371 }
372​
373 return 0;
375​
376export function filterCommandPaletteGroups(input: {
377 activeGroups: ReadonlyArray<CommandPaletteGroup>;
378 query: string;
379 isInSubmenu: boolean;
380 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
381 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
382 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
383}): CommandPaletteGroup[] {
384 const isActionsFilter = input.query.startsWith(">");
385 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
386 const normalizedQuery = normalizeSearchText(searchQuery);
387​
388 if (normalizedQuery.length === 0) {
389 if (isActionsFilter) {
390 return input.activeGroups.filter((group) => group.value === "actions");
391 }
392 return [...input.activeGroups];
393 }
394 const queryTokens = normalizedQuery.split(" ");
395​
396 let baseGroups = [...input.activeGroups];
397 if (isActionsFilter) {
398 baseGroups = baseGroups.filter((group) => group.value === "actions");
399 } else if (!input.isInSubmenu) {
400 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
401 }
402​
403 const searchableGroups = [...baseGroups];
404 if (!input.isInSubmenu && !isActionsFilter) {
405 if (input.projectSearchItems.length > 0) {
406 searchableGroups.push({
407 value: "projects-search",
408 label: "Projects",
409 items: input.projectSearchItems,
410 });
411 }
412 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
413 searchableGroups.push({
414 value: "settings-search",
415 label: "Settings",
416 items: input.settingsSearchItems,
417 });
418 }
419 if (input.threadSearchItems.length > 0) {
420 searchableGroups.push({
421 value: "threads-search",
422 label: "Threads",
423 items: input.threadSearchItems,
424 });
425 }
426 }
427​
428 return searchableGroups.flatMap((group) => {
429 const items = Arr.filterMap(group.items, (item, index) => {
430 const haystack = normalizeSearchText(item.searchTerms.join(" "));
431 if (!queryTokens.every((token) => haystack.includes(token))) {
432 return Result.failVoid;
433 }
434​
435 return Result.succeed({
436 item,
437 index,
438 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
439 });
440 })
441 .toSorted(
442 (left, right) =>
443 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
444 right.rank - left.rank ||
445 left.index - right.index,
446 )
447 .map((entry) => entry.item);
448​
449 if (items.length === 0) {
450 return [];
451 }
452​
453 return [{ value: group.value, label: group.label, items }];
454 });
456​
457export function buildBrowseGroups(input: {
458 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
459 browseQuery: string;
460 canBrowseUp: boolean;
461 upIcon: ReactNode;
462 directoryIcon: ReactNode;
463 browseUp: () => void | Promise<void>;
464 browseTo: (name: string) => void | Promise<void>;
465}): CommandPaletteGroup[] {
466 const items: CommandPaletteActionItem[] = [];
467​
468 if (input.canBrowseUp) {
469 items.push({
470 kind: "action",
471 value: "browse:up",
472 searchTerms: [input.browseQuery, ".."],
473 title: "..",
474 icon: input.upIcon,
475 keepOpen: true,
476 run: async () => {
477 await input.browseUp();
478 },
479 });
480 }
481​
482 for (const entry of input.browseEntries) {
483 items.push({
484 kind: "action",
485 value: `browse:${entry.fullPath}`,
486 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
487 title: entry.name,
488 icon: input.directoryIcon,
489 keepOpen: true,
490 run: async () => {
491 await input.browseTo(entry.name);
492 },
493 });
494 }
495​
496 return [{ value: "directories", label: "Directories", items }];
498​
499export function filterPinnedBrowseEntries(input: {
500 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
501 filterQuery: string;
502 pinnedDirectoryName: string;
503 caseSensitive: boolean;
504}): ReturnType<typeof filterFilesystemBrowseEntries> {
505 const namesMatch = (left: string, right: string) =>
506 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
507 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
508 ? ""
509 : input.filterQuery;
510 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
511 const exactEntry =
512 input.filterQuery.length > 0
513 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
514 : null;
515 return { visibleEntries, exactEntry };
517​
518export function getCommandPaletteMode(input: {
519 currentView: CommandPaletteView | null;
520 isBrowsing: boolean;
521}): CommandPaletteMode {
522 if (input.currentView) {
523 return input.isBrowsing ? "submenu-browse" : "submenu";
524 }
525 return input.isBrowsing ? "root-browse" : "root";
527​
528export function buildRootGroups(input: {
529 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
530 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
531}): CommandPaletteGroup[] {
532 const groups: CommandPaletteGroup[] = [];
533 if (input.actionItems.length > 0) {
534 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
535 }
536 if (input.recentThreadItems.length > 0) {
537 groups.push({
538 value: "recent-threads",
539 label: "Recent Threads",
540 items: input.recentThreadItems,
541 });
542 }
543 return groups;
545​
546export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
547 switch (mode) {
548 case "root":
549 return "Search commands, projects, and threads...";
550 case "root-browse":
551 return "Enter project path (e.g. ~/projects/my-app)";
552 case "submenu":
553 return "Search...";
554 case "submenu-browse":
555 return "Enter path (e.g. ~/projects/my-app)";
556 }