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