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

CommandPalette.logic.ts

364 lines11.4 KB

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