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

CommandPalette.logic.ts

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