Open History to see the last commit
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;
25}
26
27export interface CommandPaletteActionItem extends CommandPaletteItem {
28 readonly kind: "action";
29 readonly keepOpen?: boolean;
30 readonly run: () => Promise<void>;
31}
32
33export interface CommandPaletteSubmenuItem extends CommandPaletteItem {
34 readonly kind: "submenu";
35 readonly addonIcon: ReactNode;
36 readonly groups: ReadonlyArray<CommandPaletteGroup>;
37 readonly initialQuery?: string;
38}
39
40export interface CommandPaletteGroup {
41 readonly value: string;
42 readonly label: string;
43 readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
44}
45
46export interface CommandPaletteView {
47 readonly addonIcon: ReactNode;
48 readonly groups: ReadonlyArray<CommandPaletteGroup>;
49 readonly initialQuery?: string;
50}
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 };
84}
85
86export function normalizeSearchText(value: string): string {
87 return value.trim().toLowerCase().replace(/\s+/g, " ");
88}
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 }));
107}
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 {
155 kind: "action",
156 value: `thread:${thread.id}`,
157 searchTerms: [thread.title, projectTitle ?? "", thread.branch ?? ""],
158 title: thread.title,
159 description: descriptionParts.join(" · "),
160 timestamp: formatRelativeTimeLabel(
161 thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
162 ),
163 icon: input.icon,
164 ...(leadingContent ? { titleLeadingContent: leadingContent } : {}),
165 ...(trailingContent ? { titleTrailingContent: trailingContent } : {}),
166 run: async () => {
167 await input.runThread(thread);
168 },
169 };
170 });
171}
172
173function rankSearchFieldMatch(field: string, normalizedQuery: string): number {
174 const normalizedField = normalizeSearchText(field);
175 if (normalizedField.length === 0 || !normalizedField.includes(normalizedQuery)) {
176 return Number.NEGATIVE_INFINITY;
177 }
178 if (normalizedField === normalizedQuery) {
179 return 3;
180 }
181 if (normalizedField.startsWith(normalizedQuery)) {
182 return 2;
183 }
184 return 1;
185}
186
187function rankCommandPaletteItemMatch(
188 item: CommandPaletteActionItem | CommandPaletteSubmenuItem,
189 normalizedQuery: string,
190): number {
191 const terms = item.searchTerms.filter((term) => term.length > 0);
192 if (terms.length === 0) {
193 return 0;
194 }
195
196 for (const [index, field] of terms.entries()) {
197 const fieldRank = rankSearchFieldMatch(field, normalizedQuery);
198 if (fieldRank !== Number.NEGATIVE_INFINITY) {
199 return 1_000 - index * 100 + fieldRank;
200 }
201 }
202
203 return 0;
204}
205
206export function filterCommandPaletteGroups(input: {
207 activeGroups: ReadonlyArray<CommandPaletteGroup>;
208 query: string;
209 isInSubmenu: boolean;
210 projectSearchItems: ReadonlyArray<CommandPaletteActionItem>;
211 threadSearchItems: ReadonlyArray<CommandPaletteActionItem>;
212}): CommandPaletteGroup[] {
213 const isActionsFilter = input.query.startsWith(">");
214 const searchQuery = isActionsFilter ? input.query.slice(1) : input.query;
215 const normalizedQuery = normalizeSearchText(searchQuery);
216
217 if (normalizedQuery.length === 0) {
218 if (isActionsFilter) {
219 return input.activeGroups.filter((group) => group.value === "actions");
220 }
221 return [...input.activeGroups];
222 }
223
224 let baseGroups = [...input.activeGroups];
225 if (isActionsFilter) {
226 baseGroups = baseGroups.filter((group) => group.value === "actions");
227 } else if (!input.isInSubmenu) {
228 baseGroups = baseGroups.filter((group) => group.value !== "recent-threads");
229 }
230
231 const searchableGroups = [...baseGroups];
232 if (!input.isInSubmenu && !isActionsFilter) {
233 if (input.projectSearchItems.length > 0) {
234 searchableGroups.push({
235 value: "projects-search",
236 label: "Projects",
237 items: input.projectSearchItems,
238 });
239 }
240 if (input.threadSearchItems.length > 0) {
241 searchableGroups.push({
242 value: "threads-search",
243 label: "Threads",
244 items: input.threadSearchItems,
245 });
246 }
247 }
248
249 return searchableGroups.flatMap((group) => {
250 const items = group.items
251 .map((item, index) => {
252 const haystack = normalizeSearchText(item.searchTerms.join(" "));
253 if (!haystack.includes(normalizedQuery)) {
254 return null;
255 }
256
257 return {
258 item,
259 index,
260 rank: rankCommandPaletteItemMatch(item, normalizedQuery),
261 };
262 })
263 .filter(
264 (entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
265 entry !== null,
266 )
267 .toSorted((left, right) => right.rank - left.rank || left.index - right.index)
268 .map((entry) => entry.item);
269
270 if (items.length === 0) {
271 return [];
272 }
273
274 return [{ value: group.value, label: group.label, items }];
275 });
276}
277
278export function buildBrowseGroups(input: {
279 browseEntries: ReadonlyArray<FilesystemBrowseEntry>;
280 browseQuery: string;
281 canBrowseUp: boolean;
282 upIcon: ReactNode;
283 directoryIcon: ReactNode;
284 browseUp: () => void;
285 browseTo: (name: string) => void;
286}): CommandPaletteGroup[] {
287 const items: CommandPaletteActionItem[] = [];
288
289 if (input.canBrowseUp) {
290 items.push({
291 kind: "action",
292 value: "browse:up",
293 searchTerms: [input.browseQuery, ".."],
294 title: "..",
295 icon: input.upIcon,
296 keepOpen: true,
297 run: async () => {
298 input.browseUp();
299 },
300 });
301 }
302
303 for (const entry of input.browseEntries) {
304 items.push({
305 kind: "action",
306 value: `browse:${entry.fullPath}`,
307 searchTerms: [input.browseQuery, entry.fullPath, entry.name],
308 title: entry.name,
309 icon: input.directoryIcon,
310 keepOpen: true,
311 run: async () => {
312 input.browseTo(entry.name);
313 },
314 });
315 }
316
317 return [{ value: "directories", label: "Directories", items }];
318}
319
320export function getCommandPaletteMode(input: {
321 currentView: CommandPaletteView | null;
322 isBrowsing: boolean;
323}): CommandPaletteMode {
324 if (input.currentView) {
325 return input.isBrowsing ? "submenu-browse" : "submenu";
326 }
327 return input.isBrowsing ? "root-browse" : "root";
328}
329
330export function buildRootGroups(input: {
331 actionItems: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;
332 recentThreadItems: ReadonlyArray<CommandPaletteActionItem>;
333}): CommandPaletteGroup[] {
334 const groups: CommandPaletteGroup[] = [];
335 if (input.actionItems.length > 0) {
336 groups.push({ value: "actions", label: "Actions", items: input.actionItems });
337 }
338 if (input.recentThreadItems.length > 0) {
339 groups.push({
340 value: "recent-threads",
341 label: "Recent Threads",
342 items: input.recentThreadItems,
343 });
344 }
345 return groups;
346}
347
348export function getCommandPaletteInputPlaceholder(mode: CommandPaletteMode): string {
349 switch (mode) {
350 case "root":
351 return "Search commands, projects, and threads...";
352 case "root-browse":
353 return "Enter project path (e.g. ~/projects/my-app)";
354 case "submenu":
355 return "Search...";
356 case "submenu-browse":
357 return "Enter path (e.g. ~/projects/my-app)";
358 }
359}