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

CommandPalette.logic.ts

348 lines10.9 KB

1import {
2 type FilesystemBrowseEntry,
3 type KeybindingCommand,
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 normalizeSearchText(value: string): string {
74 return value.trim().toLowerCase().replace(/\s+/g, " ");
76​
77export function buildProjectActionItems(input: {
78 projects: ReadonlyArray<Project>;
79 valuePrefix: string;
80 icon: (project: Project) => ReactNode;
81 runProject: (project: Project) => Promise<void>;
82 searchTerms?: (project: Project) => ReadonlyArray<string>;
83 shortcutCommand?: KeybindingCommand;
84}): CommandPaletteActionItem[] {
85 return input.projects.map((project) => ({
86 kind: "action",
87 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
88 searchTerms: [project.title, project.workspaceRoot, ...(input.searchTerms?.(project) ?? [])],
89 title: project.title,
90 description: project.workspaceRoot,
91 icon: input.icon(project),
92 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
93 run: async () => {
94 await input.runProject(project);
95 },
96 }));
98​
99export type BuildThreadActionItemsThread = Pick<
100 SidebarThreadSummary,
101 "archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
102> & {
103 updatedAt: string;
104 latestUserMessageAt?: string | null;
105};
106​
107export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
108 threads: ReadonlyArray<TThread>;
109 activeThreadId?: Thread["id"];
110 projectTitleById: ReadonlyMap<Project["id"], string>;
111 sortOrder: SidebarThreadSortOrder;
112 icon: ReactNode;
113 /** Optional content rendered inline before the title text per-thread. */
114 renderLeadingContent?: (thread: TThread) => ReactNode;
115 /** Optional content rendered inline after the title text per-thread. */
116 renderTrailingContent?: (thread: TThread) => ReactNode;
117 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
118 limit?: number;
119}): CommandPaletteActionItem[] {
120 const sortedThreads = sortThreads(
121 input.threads.filter((thread) => thread.archivedAt === null),
122 input.sortOrder,
123 );
124 const visibleThreads =
125 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
126​
127 return visibleThreads.map((thread) => {
128 const projectTitle = input.projectTitleById.get(thread.projectId);
129 const descriptionParts: string[] = [];
130​
131 if (projectTitle) {
132 descriptionParts.push(projectTitle);
133 }
134 if (thread.branch) {
135 descriptionParts.push(`#${thread.branch}`);
136 }
137 if (thread.id === input.activeThreadId) {
138 descriptionParts.push("Current thread");
139 }
140​
141 const leadingContent = input.renderLeadingContent?.(thread);
142 const trailingContent = input.renderTrailingContent?.(thread);
143​
144 return Object.assign(
145 {
146 kind: "action" as const,
147 value: `thread:${thread.id}`,
148 searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``],
149 title: thread.title,
150 description: descriptionParts.join(` · `),
151 timestamp: formatRelativeTimeLabel(
152 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
153 ),
154 icon: input.icon,
155 },
156 leadingContent ? { titleLeadingContent: leadingContent } : {},
157 trailingContent ? { titleTrailingContent: trailingContent } : {},
158 {
159 run: async () => {
160 await input.runThread(thread);
161 },
162 },
163 );
164 });
166​
167function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
168 const normalizedField = normalizeSearchText(field);
169 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
170 return Number.NEGATIVE_INFINITY;
171 }
172 if (normalizedField === normalizedQuery) {
173 return 3;
174 }
175 if (normalizedField.startsWith(normalizedQuery)) {
176 return 2;
177 }
178 return 1;
180​
181function rankCommandPaletteItemMatch(
182 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
183 normalizedQuery: string,
184): number {
185 const terms = item.searchTerms.filter((term) => term.length > 0);
186 if (terms.length === 0) {
187 return 0;
188 }
189​
190 for (const [index, field] of terms.entries()) {
191 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
192 if (fieldRank !== Number.NEGATIVE_INFINITY) {
193 return 1_000 - index * 100 + fieldRank;
194 }
195 }
196​
197 return 0;
199​
200export function filterCommandPaletteGroups(input: {
201 activeGroups: ReadonlyArray<CommandPaletteGroup>;
202 query: string;
203 isInSubmenu: boolean;
204 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
205 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
206}): CommandPaletteGroup[] {
207 const isActionsFilter = input.query.startsWith(">");
208 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
209 const normalizedQuery = normalizeSearchText(searchQuery);
210​
211 if (normalizedQuery.length === 0) {
212 if (isActionsFilter) {
213 return input.activeGroups.filter((group) => group.value === "actions");
214 }
215 return [...input.activeGroups];
216 }
217​
218 let baseGroups = [...input.activeGroups];
219 if (isActionsFilter) {
220 baseGroups = baseGroups.filter((group) => group.value === "actions");
221 } else if (!input.isInSubmenu) {
222 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
223 }
224​
225 const searchableGroups = [...baseGroups];
226 if (!input.isInSubmenu && !isActionsFilter) {
227 if (input.projectSearchItems.length > 0) {
228 searchableGroups.push({
229 value: "projects-search",
230 label: "Projects",
231 items: input.projectSearchItems,
232 });
233 }
234 if (input.threadSearchItems.length > 0) {
235 searchableGroups.push({
236 value: "threads-search",
237 label: "Threads",
238 items: input.threadSearchItems,
239 });
240 }
241 }
242​
243 return searchableGroups.flatMap((group) => {
244 const items = Arr.filterMap(group.items, (item, index) => {
245 const haystack = normalizeSearchText(item.searchTerms.join(" "));
246 if (!haystack.includes(normalizedQuery)) {
247 return Result.failVoid;
248 }
249​
250 return Result.succeed({
251 item,
252 index,
253 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
254 });
255 })
256 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
257 .map((entry) => entry.item);
258​
259 if (items.length === 0) {
260 return [];
261 }
262​
263 return [{ value: group.value, label: group.label, items }];
264 });
266​
267export function buildBrowseGroups(input: {
268 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
269 browseQuery: string;
270 canBrowseUp: boolean;
271 upIcon: ReactNode;
272 directoryIcon: ReactNode;
273 browseUp: () => void | Promise<void>;
274 browseTo: (name: string) => void | Promise<void>;
275}): CommandPaletteGroup[] {
276 const items: CommandPaletteActionItem[] = [];
277​
278 if (input.canBrowseUp) {
279 items.push({
280 kind: "action",
281 value: "browse:up",
282 searchTerms: [input.browseQuery, ".."],
283 title: "..",
284 icon: input.upIcon,
285 keepOpen: true,
286 run: async () => {
287 await input.browseUp();
288 },
289 });
290 }
291​
292 for (const entry of input.browseEntries) {
293 items.push({
294 kind: "action",
295 value: `browse:${entry.fullPath}`,
296 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
297 title: entry.name,
298 icon: input.directoryIcon,
299 keepOpen: true,
300 run: async () => {
301 await input.browseTo(entry.name);
302 },
303 });
304 }
305​
306 return [{ value: "directories", label: "Directories", items }];
308​
309export function getCommandPaletteMode(input: {
310 currentView: CommandPaletteView | null;
311 isBrowsing: boolean;
312}): CommandPaletteMode {
313 if (input.currentView) {
314 return input.isBrowsing ? "submenu-browse" : "submenu";
315 }
316 return input.isBrowsing ? "root-browse" : "root";
318​
319export function buildRootGroups(input: {
320 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
321 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
322}): CommandPaletteGroup[] {
323 const groups: CommandPaletteGroup[] = [];
324 if (input.actionItems.length > 0) {
325 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
326 }
327 if (input.recentThreadItems.length > 0) {
328 groups.push({
329 value: "recent-threads",
330 label: "Recent Threads",
331 items: input.recentThreadItems,
332 });
333 }
334 return groups;
336​
337export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
338 switch (mode) {
339 case "root":
340 return "Search commands, projects, and threads...";
341 case "root-browse":
342 return "Enter project path (e.g. ~/projects/my-app)";
343 case "submenu":
344 return "Search...";
345 case "submenu-browse":
346 return "Enter path (e.g. ~/projects/my-app)";
347 }