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

CommandPalette.logic.ts

548 lines18.2 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;
146​
147export interface CommandPaletteActionItem extends CommandPaletteItem {
148 readonly kind: "action";
149 readonly keepOpen?: boolean;
150 readonly run: () => Promise<void>;
152​
153export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
154 readonly kind: "submenu";
155 readonly addonIcon: ReactNode;
156 readonly groups: ReadonlyArray<CommandPaletteGroup>;
157 readonly initialQuery?: string;
159​
160export interface CommandPaletteGroup {
161 readonly value: string;
162 readonly label: string;
163 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
165​
166export interface CommandPaletteView {
167 readonly addonIcon: ReactNode;
168 readonly groups: ReadonlyArray<CommandPaletteGroup>;
169 readonly initialQuery?: string;
171​
172export function enumerateCommandPaletteItems(
173 items: ReadonlyArray<CommandPaletteActionItem>,
174): CommandPaletteActionItem[] {
175 return items.map((item, index) => {
176 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
177 if (shortcutCommand) return { ...item, shortcutCommand };
178​
179 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
180 return itemWithoutShortcut;
181 });
183​
184export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
185​
186// A project as the palette shows it. `displayName` is the grouped label (for
187// example "owner/repo" when projects are merged across machines). Keep `title`
188// as the real project title: the automatic project icon is derived from it, and
189// every other surface uses the real title, so overriding it desyncs the icon.
190export type CommandPaletteProject = Project & { readonly displayName: string };
191​
192export function buildCommandPaletteProjectMetadata(input: {
193 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
194 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
195}) {
196 const searchTerms: string[] = [];
197 const environmentLabels = new Set<string>();
198​
199 for (const project of input.projects) {
200 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
201 searchTerms.push(project.title, project.workspaceRoot, label);
202 environmentLabels.add(label);
203 }
204​
205 return { searchTerms, environmentLabels: [...environmentLabels] };
207​
208export function buildProjectActionItems(input: {
209 projects: ReadonlyArray<CommandPaletteProject>;
210 valuePrefix: string;
211 icon: (project: CommandPaletteProject) => ReactNode;
212 runProject: (project: CommandPaletteProject) => Promise<void>;
213 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
214 renderDescription?: (project: CommandPaletteProject) => ReactNode;
215 shortcutCommand?: KeybindingCommand;
216}): CommandPaletteActionItem[] {
217 return input.projects.map((project) => ({
218 kind: "action",
219 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
220 searchTerms: [
221 project.displayName,
222 project.title,
223 project.workspaceRoot,
224 ...(input.searchTerms?.(project) ?? []),
225 ],
226 title: project.displayName,
227 description: input.renderDescription?.(project) ?? project.workspaceRoot,
228 icon: input.icon(project),
229 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
230 run: async () => {
231 await input.runProject(project);
232 },
233 }));
235​
236export type BuildThreadActionItemsThread = Pick<
237 SidebarThreadSummary,
238 | "archivedAt"
239 | "branch"
240 | "createdAt"
241 | "environmentId"
242 | "id"
243 | "modelSelection"
244 | "projectId"
245 | "session"
246 | "title"
247 | "worktreePath"
248> & {
249 pullRequests?: SidebarThreadSummary["pullRequests"];
250 updatedAt: string;
251 latestUserMessageAt?: string | null;
252};
253​
254export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
255 threads: ReadonlyArray<TThread>;
256 activeThreadId?: Thread["id"];
257 projectTitleById: ReadonlyMap<Project["id"], string>;
258 sortOrder: SidebarThreadSortOrder;
259 icon: ReactNode;
260 /** Optional content rendered inline before the title text per-thread. */
261 renderLeadingContent?: (thread: TThread) => ReactNode;
262 /** Optional content rendered inline after the title text per-thread. */
263 renderTrailingContent?: (thread: TThread) => ReactNode;
264 /** Optional rich description (e.g. favicon + workspace icons). Falls back to text. */
265 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
266 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
267 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
268 limit?: number;
269}): CommandPaletteActionItem[] {
270 const sortedThreads = sortThreads(
271 input.threads.filter((thread) => thread.archivedAt === null),
272 input.sortOrder,
273 );
274 const visibleThreads =
275 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
276​
277 return visibleThreads.map((thread) => {
278 const projectTitle = input.projectTitleById.get(thread.projectId);
279 const descriptionParts: string[] = [];
280​
281 if (projectTitle) {
282 descriptionParts.push(projectTitle);
283 }
284 if (thread.branch) {
285 descriptionParts.push(`#${thread.branch}`);
286 }
287 if (thread.id === input.activeThreadId) {
288 descriptionParts.push("Current thread");
289 }
290​
291 const leadingContent = input.renderLeadingContent?.(thread);
292 const trailingContent = input.renderTrailingContent?.(thread);
293 const contentMatch = input.getContentMatch?.(thread);
294 const description = input.renderDescription
295 ? input.renderDescription(thread, { projectTitle })
296 : descriptionParts.join(` · `);
297​
298 return Object.assign(
299 {
300 kind: "action" as const,
301 value: `thread:${thread.id}`,
302 searchTerms: [
303 thread.title,
304 ...threadPullRequestSearchTerms(thread),
305 projectTitle ?? ``,
306 thread.branch ?? ``,
307 contentMatch?.snippet ?? ``,
308 ],
309 title: thread.title,
310 description,
311 timestamp: formatRelativeTimeLabel(
312 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
313 ),
314 icon: input.icon,
315 },
316 leadingContent ? { titleLeadingContent: leadingContent } : {},
317 trailingContent ? { titleTrailingContent: trailingContent } : {},
318 contentMatch ? { threadContentMatch: contentMatch } : {},
319 {
320 run: async () => {
321 await input.runThread(thread);
322 },
323 },
324 );
325 });
327​
328function rankSearchFieldMatch(
329 field: string,
330 normalizedQuery: string,
331 queryTokens: ReadonlyArray<string>,
332): number {
333 const normalizedField = normalizeSearchText(field);
334 if (
335 normalizedField.length === 0 ||
336 !queryTokens.every((token) => normalizedField.includes(token))
337 ) {
338 return Number.NEGATIVE_INFINITY;
339 }
340 if (normalizedField === normalizedQuery) {
341 return 3;
342 }
343 if (normalizedField.startsWith(normalizedQuery)) {
344 return 2;
345 }
346 if (normalizedField.includes(normalizedQuery)) {
347 return 1;
348 }
349 return 0;
351​
352function rankCommandPaletteItemMatch(
353 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
354 normalizedQuery: string,
355 queryTokens: ReadonlyArray<string>,
356): number {
357 const terms = item.searchTerms.filter((term) => term.length > 0);
358 if (terms.length === 0) {
359 return 0;
360 }
361​
362 for (const [index, field] of terms.entries()) {
363 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
364 if (fieldRank !== Number.NEGATIVE_INFINITY) {
365 return 1_000 - index * 100 + fieldRank;
366 }
367 }
368​
369 return 0;
371​
372export function filterCommandPaletteGroups(input: {
373 activeGroups: ReadonlyArray<CommandPaletteGroup>;
374 query: string;
375 isInSubmenu: boolean;
376 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
377 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
378 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
379}): CommandPaletteGroup[] {
380 const isActionsFilter = input.query.startsWith(">");
381 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
382 const normalizedQuery = normalizeSearchText(searchQuery);
383​
384 if (normalizedQuery.length === 0) {
385 if (isActionsFilter) {
386 return input.activeGroups.filter((group) => group.value === "actions");
387 }
388 return [...input.activeGroups];
389 }
390 const queryTokens = normalizedQuery.split(" ");
391​
392 let baseGroups = [...input.activeGroups];
393 if (isActionsFilter) {
394 baseGroups = baseGroups.filter((group) => group.value === "actions");
395 } else if (!input.isInSubmenu) {
396 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
397 }
398​
399 const searchableGroups = [...baseGroups];
400 if (!input.isInSubmenu && !isActionsFilter) {
401 if (input.projectSearchItems.length > 0) {
402 searchableGroups.push({
403 value: "projects-search",
404 label: "Projects",
405 items: input.projectSearchItems,
406 });
407 }
408 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
409 searchableGroups.push({
410 value: "settings-search",
411 label: "Settings",
412 items: input.settingsSearchItems,
413 });
414 }
415 if (input.threadSearchItems.length > 0) {
416 searchableGroups.push({
417 value: "threads-search",
418 label: "Threads",
419 items: input.threadSearchItems,
420 });
421 }
422 }
423​
424 return searchableGroups.flatMap((group) => {
425 const items = Arr.filterMap(group.items, (item, index) => {
426 const haystack = normalizeSearchText(item.searchTerms.join(" "));
427 if (!queryTokens.every((token) => haystack.includes(token))) {
428 return Result.failVoid;
429 }
430​
431 return Result.succeed({
432 item,
433 index,
434 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
435 });
436 })
437 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
438 .map((entry) => entry.item);
439​
440 if (items.length === 0) {
441 return [];
442 }
443​
444 return [{ value: group.value, label: group.label, items }];
445 });
447​
448export function buildBrowseGroups(input: {
449 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
450 browseQuery: string;
451 canBrowseUp: boolean;
452 upIcon: ReactNode;
453 directoryIcon: ReactNode;
454 browseUp: () => void | Promise<void>;
455 browseTo: (name: string) => void | Promise<void>;
456}): CommandPaletteGroup[] {
457 const items: CommandPaletteActionItem[] = [];
458​
459 if (input.canBrowseUp) {
460 items.push({
461 kind: "action",
462 value: "browse:up",
463 searchTerms: [input.browseQuery, ".."],
464 title: "..",
465 icon: input.upIcon,
466 keepOpen: true,
467 run: async () => {
468 await input.browseUp();
469 },
470 });
471 }
472​
473 for (const entry of input.browseEntries) {
474 items.push({
475 kind: "action",
476 value: `browse:${entry.fullPath}`,
477 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
478 title: entry.name,
479 icon: input.directoryIcon,
480 keepOpen: true,
481 run: async () => {
482 await input.browseTo(entry.name);
483 },
484 });
485 }
486​
487 return [{ value: "directories", label: "Directories", items }];
489​
490export function filterPinnedBrowseEntries(input: {
491 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
492 filterQuery: string;
493 pinnedDirectoryName: string;
494 caseSensitive: boolean;
495}): ReturnType<typeof filterFilesystemBrowseEntries> {
496 const namesMatch = (left: string, right: string) =>
497 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
498 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
499 ? ""
500 : input.filterQuery;
501 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
502 const exactEntry =
503 input.filterQuery.length > 0
504 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
505 : null;
506 return { visibleEntries, exactEntry };
508​
509export function getCommandPaletteMode(input: {
510 currentView: CommandPaletteView | null;
511 isBrowsing: boolean;
512}): CommandPaletteMode {
513 if (input.currentView) {
514 return input.isBrowsing ? "submenu-browse" : "submenu";
515 }
516 return input.isBrowsing ? "root-browse" : "root";
518​
519export function buildRootGroups(input: {
520 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
521 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
522}): CommandPaletteGroup[] {
523 const groups: CommandPaletteGroup[] = [];
524 if (input.actionItems.length > 0) {
525 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
526 }
527 if (input.recentThreadItems.length > 0) {
528 groups.push({
529 value: "recent-threads",
530 label: "Recent Threads",
531 items: input.recentThreadItems,
532 });
533 }
534 return groups;
536​
537export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
538 switch (mode) {
539 case "root":
540 return "Search commands, projects, and threads...";
541 case "root-browse":
542 return "Enter project path (e.g. ~/projects/my-app)";
543 case "submenu":
544 return "Search...";
545 case "submenu-browse":
546 return "Enter path (e.g. ~/projects/my-app)";
547 }