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

CommandPalette.logic.ts

661 lines21.4 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 { getThreadSortTimestamp, 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​
23export function buildLinkedThreadActionItems(
24 input: CommandPaletteLinkedThreads & {
25 query: string;
26 icon: ReactNode;
27 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
28 },
29): CommandPaletteActionItem[] {
30 return input.threads.map((thread) => ({
31 kind: "action",
32 value: `thread:${input.environmentId}:${thread.id}`,
33 title: thread.title || "Untitled thread",
34 description: thread.archivedAt === null ? "Linked thread" : "Archived thread",
35 searchTerms: [input.query, thread.title],
36 icon: input.icon,
37 run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }),
38 }));
40​
41export function browseInputEndPaddingClass(input: {
42 readonly willCreateProjectPath: boolean;
43 readonly hasHighlightedBrowseItem: boolean;
44}): string {
45 if (input.willCreateProjectPath) {
46 return "*:data-[slot=autocomplete-input]:pe-38!";
47 }
48 if (input.hasHighlightedBrowseItem) {
49 return "*:data-[slot=autocomplete-input]:pe-30!";
50 }
51 return "*:data-[slot=autocomplete-input]:pe-24!";
53​
54export type SearchOverlayMode = "command" | "files" | "content";
55​
56export type CommandPaletteOpenIntent =
57 | { readonly kind: "add-project" | "new-thread-in" | "change-theme" }
58 | {
59 readonly kind: "search";
60 readonly query: string;
61 readonly linkedThreads?: CommandPaletteLinkedThreads;
62 };
63​
64export interface CommandPaletteUiState {
65 readonly open: boolean;
66 readonly mode: SearchOverlayMode;
67 readonly openIntent: CommandPaletteOpenIntent | null;
68 readonly parentSearch?: CommandPaletteReturnContext;
69 readonly restoredSearch?: CommandPaletteReturnContext;
71​
72export type CommandPaletteUiAction =
73 | { readonly _tag: "SetOpen"; readonly open: boolean }
74 | { readonly _tag: "ToggleMode"; readonly mode: SearchOverlayMode }
75 | {
76 readonly _tag: "OpenSearch";
77 readonly query: string;
78 readonly linkedThreads?: CommandPaletteLinkedThreads;
79 }
80 | { readonly _tag: "OpenAddProject" }
81 | { readonly _tag: "OpenNewThreadIn" }
82 | { readonly _tag: "OpenChangeTheme" }
83 | { readonly _tag: "ClearOpenIntent" }
84 | {
85 readonly _tag: "OpenChildSearch";
86 readonly mode: "files" | "content";
87 readonly context: CommandPaletteReturnContext;
88 }
89 | { readonly _tag: "BackToCommand" };
90​
91export function reduceCommandPaletteUiState(
92 state: CommandPaletteUiState,
93 action: CommandPaletteUiAction,
94): CommandPaletteUiState {
95 switch (action._tag) {
96 case "SetOpen":
97 return action.open
98 ? { open: true, mode: "command", openIntent: state.openIntent }
99 : { open: false, mode: state.mode, openIntent: null };
100 case "ToggleMode":
101 return state.open && state.mode === action.mode
102 ? { open: false, mode: state.mode, openIntent: null }
103 : { open: true, mode: action.mode, openIntent: null };
104 case "OpenChildSearch":
105 return { open: true, mode: action.mode, openIntent: null, parentSearch: action.context };
106 case "BackToCommand":
107 return state.open && state.mode !== "command"
108 ? {
109 open: true,
110 mode: "command",
111 openIntent: null,
112 ...(state.parentSearch ? { restoredSearch: state.parentSearch } : {}),
113 }
114 : state;
115 case "OpenSearch":
116 return {
117 open: true,
118 mode: "command",
119 openIntent: {
120 kind: "search",
121 query: action.query,
122 ...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
123 },
124 };
125 case "OpenAddProject":
126 return { open: true, mode: "command", openIntent: { kind: "add-project" } };
127 case "OpenNewThreadIn":
128 return { open: true, mode: "command", openIntent: { kind: "new-thread-in" } };
129 case "OpenChangeTheme":
130 return { open: true, mode: "command", openIntent: { kind: "change-theme" } };
131 case "ClearOpenIntent":
132 return state.openIntent ? { ...state, openIntent: null } : state;
133 }
135​
136export interface CommandPaletteThreadContentMatch {
137 readonly source: "user" | "assistant";
138 readonly snippet: string;
139 readonly query: string;
141​
142export interface CommandPaletteItem {
143 readonly kind: "action" | "submenu";
144 readonly value: string;
145 readonly searchTerms: ReadonlyArray<string>;
146 readonly title: ReactNode;
147 readonly description?: ReactNode;
148 readonly threadContentMatch?: CommandPaletteThreadContentMatch;
149 readonly timestamp?: string;
150 readonly searchRecency?: number;
151 readonly icon: ReactNode;
152 readonly disabled?: boolean;
153 readonly titleLeadingContent?: ReactNode;
154 readonly titleTrailingContent?: ReactNode;
155 readonly shortcutCommand?: KeybindingCommand;
156 readonly secondary?: boolean;
158​
159export interface CommandPaletteActionItem extends CommandPaletteItem {
160 readonly kind: "action";
161 readonly keepOpen?: boolean;
162 readonly run: () => Promise<void>;
164​
165export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
166 readonly kind: "submenu";
167 readonly addonIcon: ReactNode;
168 readonly groups: ReadonlyArray<CommandPaletteGroup>;
169 readonly initialQuery?: string;
171​
172export interface CommandPaletteGroup {
173 readonly value: string;
174 readonly label: string;
175 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
177​
178export interface CommandPaletteView {
179 readonly addonIcon: ReactNode;
180 readonly groups: ReadonlyArray<CommandPaletteGroup>;
181 readonly initialQuery?: string;
183​
184// Child search unmounts the palette; retain search data without its view closures.
185export interface CommandPaletteReturnContext {
186 readonly query: string;
187 readonly linkedThreadSearch: Extract<CommandPaletteOpenIntent, { kind: "search" }> | null;
189​
190export interface CommandPaletteSearchState {
191 readonly query: string;
192 readonly views: ReadonlyArray<{
193 readonly view: CommandPaletteView;
194 readonly parentQuery: string;
195 }>;
197​
198export function createCommandPaletteSearchState(query = ""): CommandPaletteSearchState {
199 return { query, views: [] };
201​
202export function reduceCommandPaletteSearchState(
203 state: CommandPaletteSearchState,
204 action:
205 | { readonly type: "query"; readonly query: string }
206 | { readonly type: "push"; readonly view: CommandPaletteView }
207 | { readonly type: "back" }
208 | { readonly type: "reset"; readonly query?: string },
209): CommandPaletteSearchState {
210 switch (action.type) {
211 case "query":
212 return { ...state, query: action.query };
213 case "push":
214 return {
215 query: action.view.initialQuery ?? "",
216 views: [...state.views, { view: action.view, parentQuery: state.query }],
217 };
218 case "back": {
219 const parent = state.views.at(-1);
220 return parent ? { query: parent.parentQuery, views: state.views.slice(0, -1) } : state;
221 }
222 case "reset":
223 return createCommandPaletteSearchState(action.query);
224 }
226​
227export type CommandPaletteRow =
228 | {
229 readonly kind: "label";
230 readonly key: string;
231 readonly label: string;
232 readonly first: boolean;
233 }
234 | {
235 readonly kind: "item";
236 readonly key: string;
237 readonly item: CommandPaletteActionItem | CommandPaletteSubmenuItem;
238 readonly itemIndex: number | null;
239 };
240​
241export function buildCommandPaletteRows(groups: ReadonlyArray<CommandPaletteGroup>) {
242 const rows: CommandPaletteRow[] = [];
243 const itemValues: string[] = [];
244 const rowIndexByItemIndex: number[] = [];
245 for (const group of groups) {
246 if (group.label) {
247 rows.push({
248 kind: "label",
249 key: `group:${group.value}`,
250 label: group.label,
251 first: rows.length === 0,
252 });
253 }
254 for (const item of group.items) {
255 const itemIndex = item.disabled ? null : itemValues.length;
256 if (itemIndex !== null) {
257 itemValues.push(item.value);
258 rowIndexByItemIndex.push(rows.length);
259 }
260 rows.push({ kind: "item", key: `${group.value}:${item.value}`, item, itemIndex });
261 }
262 }
263 return { rows, itemValues, rowIndexByItemIndex };
265​
266export function findHighlightedCommandPaletteItem(
267 groups: ReadonlyArray<CommandPaletteGroup>,
268 highlightedItemValue: string | null,
269): CommandPaletteActionItem | CommandPaletteSubmenuItem | null {
270 if (highlightedItemValue === null) return null;
271 for (const group of groups) {
272 for (const item of group.items) {
273 if (item.value === highlightedItemValue && !item.disabled) return item;
274 }
275 }
276 return null;
278​
279export function enumerateCommandPaletteItems(
280 items: ReadonlyArray<CommandPaletteActionItem>,
281): CommandPaletteActionItem[] {
282 return items.map((item, index) => {
283 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
284 if (shortcutCommand) return { ...item, shortcutCommand };
285​
286 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
287 return itemWithoutShortcut;
288 });
290​
291export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
292​
293export type CommandPaletteProject = Project & { readonly displayName: string };
294​
295export function buildCommandPaletteProjectMetadata(input: {
296 readonly projects: ReadonlyArray<Pick<Project, "environmentId" | "title" | "workspaceRoot">>;
297 readonly locationByEnvironmentId: ReadonlyMap<EnvironmentId, { readonly label: string }>;
298}) {
299 const searchTerms: string[] = [];
300 const environmentLabels = new Set<string>();
301​
302 for (const project of input.projects) {
303 const label = input.locationByEnvironmentId.get(project.environmentId)?.label ?? "Remote";
304 searchTerms.push(project.title, project.workspaceRoot, label);
305 environmentLabels.add(label);
306 }
307​
308 return { searchTerms, environmentLabels: [...environmentLabels] };
310​
311export function buildProjectActionItems(input: {
312 projects: ReadonlyArray<CommandPaletteProject>;
313 valuePrefix: string;
314 icon: (project: CommandPaletteProject) => ReactNode;
315 runProject: (project: CommandPaletteProject) => Promise<void>;
316 searchTerms?: (project: CommandPaletteProject) => ReadonlyArray<string>;
317 renderDescription?: (project: CommandPaletteProject) => ReactNode;
318 disabled?: (project: CommandPaletteProject) => boolean;
319 shortcutCommand?: KeybindingCommand;
320}): CommandPaletteActionItem[] {
321 return input.projects.map((project) => ({
322 kind: "action",
323 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
324 searchTerms: [
325 project.displayName,
326 project.title,
327 project.workspaceRoot,
328 ...(input.searchTerms?.(project) ?? []),
329 ],
330 title: project.displayName,
331 description: input.renderDescription?.(project) ?? project.workspaceRoot,
332 icon: input.icon(project),
333 ...(input.disabled ? { disabled: input.disabled(project) } : {}),
334 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
335 run: async () => {
336 await input.runProject(project);
337 },
338 }));
340​
341export type BuildThreadActionItemsThread = Pick<
342 SidebarThreadSummary,
343 | "archivedAt"
344 | "branch"
345 | "createdAt"
346 | "environmentId"
347 | "id"
348 | "modelSelection"
349 | "projectId"
350 | "runtime"
351 | "title"
352 | "worktreePath"
353> & {
354 pullRequests?: SidebarThreadSummary["pullRequests"];
355 updatedAt: string;
356 latestUserMessageAt?: string | null;
357};
358​
359export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
360 threads: ReadonlyArray<TThread>;
361 activeThreadId?: Thread["id"];
362 projectTitleById: ReadonlyMap<Project["id"], string>;
363 sortOrder: SidebarThreadSortOrder;
364 icon: ReactNode;
365 renderLeadingContent?: (thread: TThread) => ReactNode;
366 renderTrailingContent?: (thread: TThread) => ReactNode;
367 renderDescription?: (thread: TThread, meta: { projectTitle: string | undefined }) => ReactNode;
368 getContentMatch?: (thread: TThread) => CommandPaletteThreadContentMatch | undefined;
369 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
370 limit?: number;
371}): CommandPaletteActionItem[] {
372 const sortedThreads = sortThreads(
373 input.threads.filter((thread) => thread.archivedAt === null),
374 input.sortOrder,
375 );
376 const visibleThreads =
377 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
378​
379 return visibleThreads.map((thread) => {
380 const projectTitle = input.projectTitleById.get(thread.projectId);
381 const descriptionParts: string[] = [];
382​
383 if (projectTitle) {
384 descriptionParts.push(projectTitle);
385 }
386 if (thread.branch) {
387 descriptionParts.push(`#${thread.branch}`);
388 }
389 if (thread.id === input.activeThreadId) {
390 descriptionParts.push("Current thread");
391 }
392​
393 const leadingContent = input.renderLeadingContent?.(thread);
394 const trailingContent = input.renderTrailingContent?.(thread);
395 const contentMatch = input.getContentMatch?.(thread);
396 const description = input.renderDescription
397 ? input.renderDescription(thread, { projectTitle })
398 : descriptionParts.join(` · `);
399​
400 return Object.assign(
401 {
402 kind: "action" as const,
403 value: `thread:${thread.id}`,
404 searchTerms: [
405 thread.title,
406 ...threadPullRequestSearchTerms(thread),
407 projectTitle ?? ``,
408 thread.branch ?? ``,
409 contentMatch?.snippet ?? ``,
410 thread.id,
411 ],
412 title: thread.title,
413 description,
414 timestamp: formatRelativeTimeLabel(
415 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
416 ),
417 searchRecency: getThreadSortTimestamp(thread, "updated_at"),
418 icon: input.icon,
419 },
420 leadingContent ? { titleLeadingContent: leadingContent } : {},
421 trailingContent ? { titleTrailingContent: trailingContent } : {},
422 contentMatch ? { threadContentMatch: contentMatch } : {},
423 {
424 run: async () => {
425 await input.runThread(thread);
426 },
427 },
428 );
429 });
431​
432function rankSearchFieldMatch(
433 field: string,
434 normalizedQuery: string,
435 queryTokens: ReadonlyArray<string>,
436): number {
437 const normalizedField = normalizeSearchText(field);
438 if (
439 normalizedField.length === 0 ||
440 !queryTokens.every((token) => normalizedField.includes(token))
441 ) {
442 return Number.NEGATIVE_INFINITY;
443 }
444 if (normalizedField === normalizedQuery) {
445 return 3;
446 }
447 if (normalizedField.startsWith(normalizedQuery)) {
448 return 2;
449 }
450 if (normalizedField.includes(normalizedQuery)) {
451 return 1;
452 }
453 return 0;
455​
456function rankCommandPaletteItemMatch(
457 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
458 normalizedQuery: string,
459 queryTokens: ReadonlyArray<string>,
460): number {
461 const terms = item.searchTerms.filter((term) => term.length > 0);
462 if (terms.length === 0) {
463 return 0;
464 }
465​
466 for (const [index, field] of terms.entries()) {
467 const fieldRank = rankSearchFieldMatch(field, normalizedQuery, queryTokens);
468 if (fieldRank !== Number.NEGATIVE_INFINITY) {
469 if (index === 0 && item.searchRecency !== undefined) {
470 return 1_000 + Number(fieldRank === 3);
471 }
472 return 1_000 - index * 100 + fieldRank;
473 }
474 }
475​
476 return 0;
478​
479export function filterCommandPaletteGroups(input: {
480 activeGroups: ReadonlyArray<CommandPaletteGroup>;
481 query: string;
482 isInSubmenu: boolean;
483 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
484 settingsSearchItems?: ReadonlyArray<CommandPaletteActionItem>;
485 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
486}): CommandPaletteGroup[] {
487 const isActionsFilter = input.query.startsWith(">");
488 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
489 const normalizedQuery = normalizeSearchText(searchQuery);
490​
491 if (normalizedQuery.length === 0) {
492 if (isActionsFilter) {
493 return input.activeGroups.filter((group) => group.value === "actions");
494 }
495 return [...input.activeGroups];
496 }
497 const queryTokens = normalizedQuery.split(" ");
498​
499 let baseGroups = [...input.activeGroups];
500 if (isActionsFilter) {
501 baseGroups = baseGroups.filter((group) => group.value === "actions");
502 } else if (!input.isInSubmenu) {
503 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
504 }
505​
506 const searchableGroups = [...baseGroups];
507 if (!input.isInSubmenu && !isActionsFilter) {
508 if (input.projectSearchItems.length > 0) {
509 searchableGroups.push({
510 value: "projects-search",
511 label: "Projects",
512 items: input.projectSearchItems,
513 });
514 }
515 if (input.settingsSearchItems && input.settingsSearchItems.length > 0) {
516 searchableGroups.push({
517 value: "settings-search",
518 label: "Settings",
519 items: input.settingsSearchItems,
520 });
521 }
522 if (input.threadSearchItems.length > 0) {
523 searchableGroups.push({
524 value: "threads-search",
525 label: "Threads",
526 items: input.threadSearchItems,
527 });
528 }
529 }
530​
531 return searchableGroups.flatMap((group) => {
532 const items = Arr.filterMap(group.items, (item, index) => {
533 const haystack = normalizeSearchText(item.searchTerms.join(" "));
534 if (!queryTokens.every((token) => haystack.includes(token))) {
535 return Result.failVoid;
536 }
537​
538 return Result.succeed({
539 item,
540 index,
541 rank: rankCommandPaletteItemMatch(item, normalizedQuery, queryTokens),
542 });
543 })
544 .toSorted(
545 (left, right) =>
546 Number(left.item.secondary ?? false) - Number(right.item.secondary ?? false) ||
547 right.rank - left.rank ||
548 (right.item.searchRecency ?? 0) - (left.item.searchRecency ?? 0) ||
549 left.index - right.index,
550 )
551 .map((entry) => entry.item);
552​
553 if (items.length === 0) {
554 return [];
555 }
556​
557 return [{ value: group.value, label: group.label, items }];
558 });
560​
561export function buildBrowseGroups(input: {
562 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
563 browseQuery: string;
564 canBrowseUp: boolean;
565 upIcon: ReactNode;
566 directoryIcon: ReactNode;
567 browseUp: () => void | Promise<void>;
568 browseTo: (name: string) => void | Promise<void>;
569}): CommandPaletteGroup[] {
570 const items: CommandPaletteActionItem[] = [];
571​
572 if (input.canBrowseUp) {
573 items.push({
574 kind: "action",
575 value: "browse:up",
576 searchTerms: [input.browseQuery, ".."],
577 title: "..",
578 icon: input.upIcon,
579 keepOpen: true,
580 run: async () => {
581 await input.browseUp();
582 },
583 });
584 }
585​
586 for (const entry of input.browseEntries) {
587 items.push({
588 kind: "action",
589 value: `browse:${entry.fullPath}`,
590 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
591 title: entry.name,
592 icon: input.directoryIcon,
593 keepOpen: true,
594 run: async () => {
595 await input.browseTo(entry.name);
596 },
597 });
598 }
599​
600 return [{ value: "directories", label: "Directories", items }];
602​
603export function filterPinnedBrowseEntries(input: {
604 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
605 filterQuery: string;
606 pinnedDirectoryName: string;
607 caseSensitive: boolean;
608}): ReturnType<typeof filterFilesystemBrowseEntries> {
609 const namesMatch = (left: string, right: string) =>
610 input.caseSensitive ? left === right : left.toLowerCase() === right.toLowerCase();
611 const visibleFilterQuery = namesMatch(input.filterQuery, input.pinnedDirectoryName)
612 ? ""
613 : input.filterQuery;
614 const { visibleEntries } = filterFilesystemBrowseEntries(input.browseEntries, visibleFilterQuery);
615 const exactEntry =
616 input.filterQuery.length > 0
617 ? (input.browseEntries.find((entry) => namesMatch(entry.name, input.filterQuery)) ?? null)
618 : null;
619 return { visibleEntries, exactEntry };
621​
622export function getCommandPaletteMode(input: {
623 currentView: CommandPaletteView | null;
624 isBrowsing: boolean;
625}): CommandPaletteMode {
626 if (input.currentView) {
627 return input.isBrowsing ? "submenu-browse" : "submenu";
628 }
629 return input.isBrowsing ? "root-browse" : "root";
631​
632export function buildRootGroups(input: {
633 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
634 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
635}): CommandPaletteGroup[] {
636 const groups: CommandPaletteGroup[] = [];
637 if (input.actionItems.length > 0) {
638 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
639 }
640 if (input.recentThreadItems.length > 0) {
641 groups.push({
642 value: "recent-threads",
643 label: "Recent Threads",
644 items: input.recentThreadItems,
645 });
646 }
647 return groups;
649​
650export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
651 switch (mode) {
652 case "root":
653 return "Search commands, projects, and threads...";
654 case "root-browse":
655 return "Enter project path (e.g. ~/projects/my-app)";
656 case "submenu":
657 return "Search...";
658 case "submenu-browse":
659 return "Enter path (e.g. ~/projects/my-app)";
660 }