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

CommandPalette.logic.ts

380 lines12.0 KB

1import {
2 type KeybindingCommand,
3 type FilesystemBrowseEntry,
4 THREAD_JUMP_KEYBINDING_COMMANDS,
5} from "@t3tools/contracts";
6import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
7import * as Arr from "effect/Array";
8import * as Result from "effect/Result";
9import { type ReactNode } from "react";
10import { sortThreads } from "../lib/threadSort";
11import { formatRelativeTimeLabel } from "../timestampFormat";
12import { type Project, type SidebarThreadSummary, type Thread } from "../types";
13​
14export const RECENT_THREAD_LIMIT = 12;
15export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
16export const ADDON_ICON_CLASS = "size-4";
17​
18export interface CommandPaletteItem {
19 readonly kind: "action" | "submenu";
20 readonly value: string;
21 readonly searchTerms: ReadonlyArray<string>;
22 readonly title: ReactNode;
23 readonly description?: string;
24 readonly timestamp?: string;
25 readonly icon: ReactNode;
26 readonly disabled?: boolean;
27 /** Optional content rendered inline before the title text. */
28 readonly titleLeadingContent?: ReactNode;
29 /** Optional content rendered inline after the title text (before the timestamp). */
30 readonly titleTrailingContent?: ReactNode;
31 readonly shortcutCommand?: KeybindingCommand;
33​
34export interface CommandPaletteActionItem extends CommandPaletteItem {
35 readonly kind: "action";
36 readonly keepOpen?: boolean;
37 readonly run: () => Promise<void>;
39​
40export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
41 readonly kind: "submenu";
42 readonly addonIcon: ReactNode;
43 readonly groups: ReadonlyArray<CommandPaletteGroup>;
44 readonly initialQuery?: string;
46​
47export interface CommandPaletteGroup {
48 readonly value: string;
49 readonly label: string;
50 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
52​
53export interface CommandPaletteView {
54 readonly addonIcon: ReactNode;
55 readonly groups: ReadonlyArray<CommandPaletteGroup>;
56 readonly initialQuery?: string;
58​
59export function enumerateCommandPaletteItems(
60 items: ReadonlyArray<CommandPaletteActionItem>,
61): CommandPaletteActionItem[] {
62 return items.map((item, index) => {
63 const shortcutCommand = THREAD_JUMP_KEYBINDING_COMMANDS[index];
64 if (shortcutCommand) return { ...item, shortcutCommand };
65​
66 const { shortcutCommand: _shortcutCommand, ...itemWithoutShortcut } = item;
67 return itemWithoutShortcut;
68 });
70​
71export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
72​
73export function filterBrowseEntries(input: {
74 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
75 browseFilterQuery: string;
76 highlightedItemValue: string | null;
77}): {
78 filteredEntries: FilesystemBrowseEntry[];
79 highlightedEntry: FilesystemBrowseEntry | null;
80 exactEntry: FilesystemBrowseEntry | null;
81} {
82 const lowerFilter = input.browseFilterQuery.toLowerCase();
83 const showHidden = input.browseFilterQuery.startsWith(".");
84​
85 const filteredEntries = input.browseEntries.filter(
86 (entry) =>
87 entry.name.toLowerCase().startsWith(lowerFilter) &&
88 (showHidden || !entry.name.startsWith(".")),
89 );
90​
91 let highlightedEntry: FilesystemBrowseEntry | null = null;
92 if (input.highlightedItemValue?.startsWith("browse:")) {
93 const highlightedPath = input.highlightedItemValue.slice("browse:".length);
94 highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null;
95 }
96​
97 const exactEntry =
98 input.browseFilterQuery.length > 0
99 ? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
100 : null;
101​
102 return { filteredEntries, highlightedEntry, exactEntry };
104​
105export function normalizeSearchText(value: string): string {
106 return value.trim().toLowerCase().replace(/\s+/g, " ");
108​
109export function buildProjectActionItems(input: {
110 projects: ReadonlyArray<Project>;
111 valuePrefix: string;
112 icon: (project: Project) => ReactNode;
113 runProject: (project: Project) => Promise<void>;
114 searchTerms?: (project: Project) => ReadonlyArray<string>;
115 shortcutCommand?: KeybindingCommand;
116}): CommandPaletteActionItem[] {
117 return input.projects.map((project) => ({
118 kind: "action",
119 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
120 searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
121 title: project.title,
122 description: project.workspaceRoot,
123 icon: input.icon(project),
124 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
125 run: async () => {
126 await input.runProject(project);
127 },
128 }));
130​
131export type BuildThreadActionItemsThread = Pick<
132 SidebarThreadSummary,
133 "archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
134> & {
135 updatedAt: string;
136 latestUserMessageAt?: string | null;
137};
138​
139export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
140 threads: ReadonlyArray<TThread>;
141 activeThreadId?: Thread["id"];
142 projectTitleById: ReadonlyMap<Project["id"], string>;
143 sortOrder: SidebarThreadSortOrder;
144 icon: ReactNode;
145 /** Optional content rendered inline before the title text per-thread. */
146 renderLeadingContent?: (thread: TThread) => ReactNode;
147 /** Optional content rendered inline after the title text per-thread. */
148 renderTrailingContent?: (thread: TThread) => ReactNode;
149 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
150 limit?: number;
151}): CommandPaletteActionItem[] {
152 const sortedThreads = sortThreads(
153 input.threads.filter((thread) => thread.archivedAt === null),
154 input.sortOrder,
155 );
156 const visibleThreads =
157 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
158​
159 return visibleThreads.map((thread) => {
160 const projectTitle = input.projectTitleById.get(thread.projectId);
161 const descriptionParts: string[] = [];
162​
163 if (projectTitle) {
164 descriptionParts.push(projectTitle);
165 }
166 if (thread.branch) {
167 descriptionParts.push(`#${thread.branch}`);
168 }
169 if (thread.id === input.activeThreadId) {
170 descriptionParts.push("Current thread");
171 }
172​
173 const leadingContent = input.renderLeadingContent?.(thread);
174 const trailingContent = input.renderTrailingContent?.(thread);
175​
176 return Object.assign(
177 {
178 kind: "action" as const,
179 value: `thread:${thread.id}`,
180 searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``],
181 title: thread.title,
182 description: descriptionParts.join(` · `),
183 timestamp: formatRelativeTimeLabel(
184 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
185 ),
186 icon: input.icon,
187 },
188 leadingContent ? { titleLeadingContent: leadingContent } : {},
189 trailingContent ? { titleTrailingContent: trailingContent } : {},
190 {
191 run: async () => {
192 await input.runThread(thread);
193 },
194 },
195 );
196 });
198​
199function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
200 const normalizedField = normalizeSearchText(field);
201 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
202 return Number.NEGATIVE_INFINITY;
203 }
204 if (normalizedField === normalizedQuery) {
205 return 3;
206 }
207 if (normalizedField.startsWith(normalizedQuery)) {
208 return 2;
209 }
210 return 1;
212​
213function rankCommandPaletteItemMatch(
214 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
215 normalizedQuery: string,
216): number {
217 const terms = item.searchTerms.filter((term) => term.length > 0);
218 if (terms.length === 0) {
219 return 0;
220 }
221​
222 for (const [index, field] of terms.entries()) {
223 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
224 if (fieldRank !== Number.NEGATIVE_INFINITY) {
225 return 1_000 - index * 100 + fieldRank;
226 }
227 }
228​
229 return 0;
231​
232export function filterCommandPaletteGroups(input: {
233 activeGroups: ReadonlyArray<CommandPaletteGroup>;
234 query: string;
235 isInSubmenu: boolean;
236 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
237 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
238}): CommandPaletteGroup[] {
239 const isActionsFilter = input.query.startsWith(">");
240 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
241 const normalizedQuery = normalizeSearchText(searchQuery);
242​
243 if (normalizedQuery.length === 0) {
244 if (isActionsFilter) {
245 return input.activeGroups.filter((group) => group.value === "actions");
246 }
247 return [...input.activeGroups];
248 }
249​
250 let baseGroups = [...input.activeGroups];
251 if (isActionsFilter) {
252 baseGroups = baseGroups.filter((group) => group.value === "actions");
253 } else if (!input.isInSubmenu) {
254 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
255 }
256​
257 const searchableGroups = [...baseGroups];
258 if (!input.isInSubmenu && !isActionsFilter) {
259 if (input.projectSearchItems.length > 0) {
260 searchableGroups.push({
261 value: "projects-search",
262 label: "Projects",
263 items: input.projectSearchItems,
264 });
265 }
266 if (input.threadSearchItems.length > 0) {
267 searchableGroups.push({
268 value: "threads-search",
269 label: "Threads",
270 items: input.threadSearchItems,
271 });
272 }
273 }
274​
275 return searchableGroups.flatMap((group) => {
276 const items = Arr.filterMap(group.items, (item, index) => {
277 const haystack = normalizeSearchText(item.searchTerms.join(" "));
278 if (!haystack.includes(normalizedQuery)) {
279 return Result.failVoid;
280 }
281​
282 return Result.succeed({
283 item,
284 index,
285 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
286 });
287 })
288 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
289 .map((entry) => entry.item);
290​
291 if (items.length === 0) {
292 return [];
293 }
294​
295 return [{ value: group.value, label: group.label, items }];
296 });
298​
299export function buildBrowseGroups(input: {
300 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
301 browseQuery: string;
302 canBrowseUp: boolean;
303 upIcon: ReactNode;
304 directoryIcon: ReactNode;
305 browseUp: () => void;
306 browseTo: (name: string) => void;
307}): CommandPaletteGroup[] {
308 const items: CommandPaletteActionItem[] = [];
309​
310 if (input.canBrowseUp) {
311 items.push({
312 kind: "action",
313 value: "browse:up",
314 searchTerms: [input.browseQuery, ".."],
315 title: "..",
316 icon: input.upIcon,
317 keepOpen: true,
318 run: async () => {
319 input.browseUp();
320 },
321 });
322 }
323​
324 for (const entry of input.browseEntries) {
325 items.push({
326 kind: "action",
327 value: `browse:${entry.fullPath}`,
328 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
329 title: entry.name,
330 icon: input.directoryIcon,
331 keepOpen: true,
332 run: async () => {
333 input.browseTo(entry.name);
334 },
335 });
336 }
337​
338 return [{ value: "directories", label: "Directories", items }];
340​
341export function getCommandPaletteMode(input: {
342 currentView: CommandPaletteView | null;
343 isBrowsing: boolean;
344}): CommandPaletteMode {
345 if (input.currentView) {
346 return input.isBrowsing ? "submenu-browse" : "submenu";
347 }
348 return input.isBrowsing ? "root-browse" : "root";
350​
351export function buildRootGroups(input: {
352 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
353 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
354}): CommandPaletteGroup[] {
355 const groups: CommandPaletteGroup[] = [];
356 if (input.actionItems.length > 0) {
357 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
358 }
359 if (input.recentThreadItems.length > 0) {
360 groups.push({
361 value: "recent-threads",
362 label: "Recent Threads",
363 items: input.recentThreadItems,
364 });
365 }
366 return groups;
368​
369export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
370 switch (mode) {
371 case "root":
372 return "Search commands, projects, and threads...";
373 case "root-browse":
374 return "Enter project path (e.g. ~/projects/my-app)";
375 case "submenu":
376 return "Search...";
377 case "submenu-browse":
378 return "Enter path (e.g. ~/projects/my-app)";
379 }