Open History to see the last commit
1import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
2import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import * as Arr from "effect/Array";
4import * as Result from "effect/Result";
5import { type ReactNode } from "react";
6import { sortThreads } from "../lib/threadSort";
7import { formatRelativeTimeLabel } from "../timestampFormat";
8import { type Project, type SidebarThreadSummary, type Thread } from "../types";
9
10export const RECENT_THREAD_LIMIT = 12;
11export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
12export const ADDON_ICON_CLASS = "size-4";
13
14export interface CommandPaletteItem {
15 readonly kind: "action" | "submenu";
16 readonly value: string;
17 readonly searchTerms: ReadonlyArray<string>;
18 readonly title: ReactNode;
19 readonly description?: string;
20 readonly timestamp?: string;
21 readonly icon: ReactNode;
22 readonly disabled?: boolean;
23 /** Optional content rendered inline before the title text. */
24 readonly titleLeadingContent?: ReactNode;
25 /** Optional content rendered inline after the title text (before the timestamp). */
26 readonly titleTrailingContent?: ReactNode;
27 readonly shortcutCommand?: KeybindingCommand;
28}
29
30export interface CommandPaletteActionItem extends CommandPaletteItem {
31 readonly kind: "action";
32 readonly keepOpen?: boolean;
33 readonly run: () => Promise<void>;
34}
35
36export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
37 readonly kind: "submenu";
38 readonly addonIcon: ReactNode;
39 readonly groups: ReadonlyArray<CommandPaletteGroup>;
40 readonly initialQuery?: string;
41}
42
43export interface CommandPaletteGroup {
44 readonly value: string;
45 readonly label: string;
46 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
47}
48
49export interface CommandPaletteView {
50 readonly addonIcon: ReactNode;
51 readonly groups: ReadonlyArray<CommandPaletteGroup>;
52 readonly initialQuery?: string;
53}
54
55export type CommandPaletteMode = "root" | "root-browse" | "submenu" | "submenu-browse";
56
57export function filterBrowseEntries(input: {
58 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
59 browseFilterQuery: string;
60 highlightedItemValue: string | null;
61}): {
62 filteredEntries: FilesystemBrowseEntry[];
63 highlightedEntry: FilesystemBrowseEntry | null;
64 exactEntry: FilesystemBrowseEntry | null;
65} {
66 const lowerFilter = input.browseFilterQuery.toLowerCase();
67 const showHidden = input.browseFilterQuery.startsWith(".");
68
69 const filteredEntries = input.browseEntries.filter(
70 (entry) =>
71 entry.name.toLowerCase().startsWith(lowerFilter) &&
72 (showHidden || !entry.name.startsWith(".")),
73 );
74
75 let highlightedEntry: FilesystemBrowseEntry | null = null;
76 if (input.highlightedItemValue?.startsWith("browse:")) {
77 const highlightedPath = input.highlightedItemValue.slice("browse:".length);
78 highlightedEntry = filteredEntries.find((entry) => entry.fullPath === highlightedPath) ?? null;
79 }
80
81 const exactEntry =
82 input.browseFilterQuery.length > 0
83 ? (filteredEntries.find((entry) => entry.name === input.browseFilterQuery) ?? null)
84 : null;
85
86 return { filteredEntries, highlightedEntry, exactEntry };
87}
88
89export function normalizeSearchText(value: string): string {
90 return value.trim().toLowerCase().replace(/\s+/g, " ");
91}
92
93export function buildProjectActionItems(input: {
94 projects: ReadonlyArray<Project>;
95 valuePrefix: string;
96 icon: (project: Project) => ReactNode;
97 runProject: (project: Project) => Promise<void>;
98 shortcutCommand?: KeybindingCommand;
99}): CommandPaletteActionItem[] {
100 return input.projects.map((project) => ({
101 kind: "action",
102 value: `${input.valuePrefix}:${project.environmentId}:${project.id}`,
103 searchTerms: [project.title, project.workspaceRoot],
104 title: project.title,
105 description: project.workspaceRoot,
106 icon: input.icon(project),
107 ...(input.shortcutCommand !== undefined ? { shortcutCommand: input.shortcutCommand } : {}),
108 run: async () => {
109 await input.runProject(project);
110 },
111 }));
112}
113
114export type BuildThreadActionItemsThread = Pick<
115 SidebarThreadSummary,
116 "archivedAt" | "branch" | "createdAt" | "environmentId" | "id" | "projectId" | "title"
117> & {
118 updatedAt: string;
119 latestUserMessageAt?: string | null;
120};
121
122export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
123 threads: ReadonlyArray<TThread>;
124 activeThreadId?: Thread["id"];
125 projectTitleById: ReadonlyMap<Project["id"], string>;
126 sortOrder: SidebarThreadSortOrder;
127 icon: ReactNode;
128 /** Optional content rendered inline before the title text per-thread. */
129 renderLeadingContent?: (thread: TThread) => ReactNode;
130 /** Optional content rendered inline after the title text per-thread. */
131 renderTrailingContent?: (thread: TThread) => ReactNode;
132 runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>;
133 limit?: number;
134}): CommandPaletteActionItem[] {
135 const sortedThreads = sortThreads(
136 input.threads.filter((thread) => thread.archivedAt === null),
137 input.sortOrder,
138 );
139 const visibleThreads =
140 input.limit === undefined ? sortedThreads : sortedThreads.slice(0, input.limit);
141
142 return visibleThreads.map((thread) => {
143 const projectTitle = input.projectTitleById.get(thread.projectId);
144 const descriptionParts: string[] = [];
145
146 if (projectTitle) {
147 descriptionParts.push(projectTitle);
148 }
149 if (thread.branch) {
150 descriptionParts.push(`#${thread.branch}`);
151 }
152 if (thread.id === input.activeThreadId) {
153 descriptionParts.push("Current thread");
154 }
155
156 const leadingContent = input.renderLeadingContent?.(thread);
157 const trailingContent = input.renderTrailingContent?.(thread);
158
159 return Object.assign(
160 {
161 kind: "action" as const,
162 value: `thread:${thread.id}`,
163 searchTerms: [thread.title, projectTitle ?? ``, thread.branch ?? ``],
164 title: thread.title,
165 description: descriptionParts.join(` · `),
166 timestamp: formatRelativeTimeLabel(
167 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
168 ),
169 icon: input.icon,
170 },
171 leadingContent ? { titleLeadingContent: leadingContent } : {},
172 trailingContent ? { titleTrailingContent: trailingContent } : {},
173 {
174 run: async () => {
175 await input.runThread(thread);
176 },
177 },
178 );
179 });
180}
181
182function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
183 const normalizedField = normalizeSearchText(field);
184 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
185 return Number.NEGATIVE_INFINITY;
186 }
187 if (normalizedField === normalizedQuery) {
188 return 3;
189 }
190 if (normalizedField.startsWith(normalizedQuery)) {
191 return 2;
192 }
193 return 1;
194}
195
196function rankCommandPaletteItemMatch(
197 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
198 normalizedQuery: string,
199): number {
200 const terms = item.searchTerms.filter((term) => term.length > 0);
201 if (terms.length === 0) {
202 return 0;
203 }
204
205 for (const [index, field] of terms.entries()) {
206 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
207 if (fieldRank !== Number.NEGATIVE_INFINITY) {
208 return 1_000 - index * 100 + fieldRank;
209 }
210 }
211
212 return 0;
213}
214
215export function filterCommandPaletteGroups(input: {
216 activeGroups: ReadonlyArray<CommandPaletteGroup>;
217 query: string;
218 isInSubmenu: boolean;
219 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
220 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
221}): CommandPaletteGroup[] {
222 const isActionsFilter = input.query.startsWith(">");
223 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
224 const normalizedQuery = normalizeSearchText(searchQuery);
225
226 if (normalizedQuery.length === 0) {
227 if (isActionsFilter) {
228 return input.activeGroups.filter((group) => group.value === "actions");
229 }
230 return [...input.activeGroups];
231 }
232
233 let baseGroups = [...input.activeGroups];
234 if (isActionsFilter) {
235 baseGroups = baseGroups.filter((group) => group.value === "actions");
236 } else if (!input.isInSubmenu) {
237 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
238 }
239
240 const searchableGroups = [...baseGroups];
241 if (!input.isInSubmenu && !isActionsFilter) {
242 if (input.projectSearchItems.length > 0) {
243 searchableGroups.push({
244 value: "projects-search",
245 label: "Projects",
246 items: input.projectSearchItems,
247 });
248 }
249 if (input.threadSearchItems.length > 0) {
250 searchableGroups.push({
251 value: "threads-search",
252 label: "Threads",
253 items: input.threadSearchItems,
254 });
255 }
256 }
257
258 return searchableGroups.flatMap((group) => {
259 const items = Arr.filterMap(group.items, (item, index) => {
260 const haystack = normalizeSearchText(item.searchTerms.join(" "));
261 if (!haystack.includes(normalizedQuery)) {
262 return Result.failVoid;
263 }
264
265 return Result.succeed({
266 item,
267 index,
268 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
269 });
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 });
280}
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 }];
322}
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";
332}
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;
350}
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 }
363}