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

CommandPalette.logic.ts

528 lines17.4 KB

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