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

CommandPalette.tsx

458 lines14.1 KB

1"use client";
2​
3import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
4import type { ProjectId } from "@t3tools/contracts";
5import { useNavigate, useParams } from "@tanstack/react-router";
6import {
7 ArrowDownIcon,
8 ArrowLeftIcon,
9 ArrowUpIcon,
10 MessageSquareIcon,
11 SettingsIcon,
12 SquarePenIcon,
13} from "lucide-react";
14import {
15 useDeferredValue,
16 useEffect,
17 useMemo,
18 useRef,
19 useState,
20 type KeyboardEvent,
21 type ReactNode,
22} from "react";
23import { useShallow } from "zustand/react/shallow";
24import { useCommandPaletteStore } from "../commandPaletteStore";
25import { useHandleNewThread } from "../hooks/useHandleNewThread";
26import { useSettings } from "../hooks/useSettings";
27import {
28 startNewThreadInProjectFromContext,
29 startNewThreadFromContext,
30} from "../lib/chatThreadActions";
31import { isTerminalFocused } from "../lib/terminalFocus";
32import { getLatestThreadForProject } from "../lib/threadSort";
33import { cn } from "../lib/utils";
34import {
35 selectProjectsAcrossEnvironments,
36 selectSidebarThreadsAcrossEnvironments,
37 useStore,
38} from "../store";
39import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
40import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
41import {
42 ADDON_ICON_CLASS,
43 buildProjectActionItems,
44 buildRootGroups,
45 buildThreadActionItems,
46 type CommandPaletteActionItem,
47 type CommandPaletteSubmenuItem,
48 type CommandPaletteView,
49 filterCommandPaletteGroups,
50 getCommandPaletteInputPlaceholder,
51 getCommandPaletteMode,
52 ITEM_ICON_CLASS,
53 RECENT_THREAD_LIMIT,
54} from "./CommandPalette.logic";
55import { CommandPaletteResults } from "./CommandPaletteResults";
56import { ProjectFavicon } from "./ProjectFavicon";
57import { useServerKeybindings } from "../rpc/serverState";
58import { resolveShortcutCommand } from "../keybindings";
59import {
60 Command,
61 CommandDialog,
62 CommandDialogPopup,
63 CommandFooter,
64 CommandInput,
65 CommandPanel,
66} from "./ui/command";
67import { Kbd, KbdGroup } from "./ui/kbd";
68import { toastManager } from "./ui/toast";
69import { ComposerHandleContext, useComposerHandleContext } from "../composerHandleContext";
70import type { ChatComposerHandle } from "./chat/ChatComposer";
71​
72export function CommandPalette({ children }: { children: ReactNode }) {
73 const open = useCommandPaletteStore((store) => store.open);
74 const setOpen = useCommandPaletteStore((store) => store.setOpen);
75 const toggleOpen = useCommandPaletteStore((store) => store.toggleOpen);
76 const keybindings = useServerKeybindings();
77 const composerHandleRef = useRef<ChatComposerHandle | null>(null);
78 const routeTarget = useParams({
79 strict: false,
80 select: (params) => resolveThreadRouteTarget(params),
81 });
82 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
83 const terminalOpen = useTerminalStateStore((state) =>
84 routeThreadRef
85 ? selectThreadTerminalState(state.terminalStateByThreadKey, routeThreadRef).terminalOpen
86 : false,
87 );
88​
89 useEffect(() => {
90 const onKeyDown = (event: globalThis.KeyboardEvent) => {
91 if (event.defaultPrevented) return;
92 const command = resolveShortcutCommand(event, keybindings, {
93 context: {
94 terminalFocus: isTerminalFocused(),
95 terminalOpen,
96 },
97 });
98 if (command !== "commandPalette.toggle") {
99 return;
100 }
101 event.preventDefault();
102 event.stopPropagation();
103 toggleOpen();
104 };
105 window.addEventListener("keydown", onKeyDown);
106 return () => window.removeEventListener("keydown", onKeyDown);
107 }, [keybindings, terminalOpen, toggleOpen]);
108​
109 return (
110 <ComposerHandleContext.Provider value={composerHandleRef}>
111 <CommandDialog open={open} onOpenChange={setOpen}>
112 {children}
113 <CommandPaletteDialog />
114 </CommandDialog>
115 </ComposerHandleContext.Provider>
116 );
118​
119function CommandPaletteDialog() {
120 const open = useCommandPaletteStore((store) => store.open);
121 const setOpen = useCommandPaletteStore((store) => store.setOpen);
122​
123 useEffect(() => {
124 return () => {
125 setOpen(false);
126 };
127 }, [setOpen]);
128​
129 if (!open) {
130 return null;
131 }
132​
133 return <OpenCommandPaletteDialog />;
135​
136function OpenCommandPaletteDialog() {
137 const navigate = useNavigate();
138 const setOpen = useCommandPaletteStore((store) => store.setOpen);
139 const composerHandleRef = useComposerHandleContext();
140 const [query, setQuery] = useState("");
141 const deferredQuery = useDeferredValue(query);
142 const isActionsOnly = deferredQuery.startsWith(">");
143 const settings = useSettings();
144 const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread } =
145 useHandleNewThread();
146 const projects = useStore(useShallow(selectProjectsAcrossEnvironments));
147 const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments));
148 const keybindings = useServerKeybindings();
149 const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
150 const currentView = viewStack.at(-1) ?? null;
151 const paletteMode = getCommandPaletteMode({ currentView });
152​
153 const projectTitleById = useMemo(
154 () => new Map<ProjectId, string>(projects.map((project) => [project.id, project.name])),
155 [projects],
156 );
157​
158 const activeThreadId = activeThread?.id;
159 const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;
160​
161 const openProjectFromSearch = useMemo(
162 () => async (project: (typeof projects)[number]) => {
163 const latestThread = getLatestThreadForProject(
164 threads.filter((thread) => thread.environmentId === project.environmentId),
165 project.id,
166 settings.sidebarThreadSortOrder,
167 );
168 if (latestThread) {
169 await navigate({
170 to: "/$environmentId/$threadId",
171 params: buildThreadRouteParams(
172 scopeThreadRef(latestThread.environmentId, latestThread.id),
173 ),
174 });
175 return;
176 }
177​
178 await handleNewThread(scopeProjectRef(project.environmentId, project.id), {
179 envMode: settings.defaultThreadEnvMode,
180 });
181 },
182 [
183 handleNewThread,
184 navigate,
185 settings.defaultThreadEnvMode,
186 settings.sidebarThreadSortOrder,
187 threads,
188 ],
189 );
190​
191 const projectSearchItems = useMemo(
192 () =>
193 buildProjectActionItems({
194 projects,
195 valuePrefix: "project",
196 icon: (project) => (
197 <ProjectFavicon
198 environmentId={project.environmentId}
199 cwd={project.cwd}
200 className={ITEM_ICON_CLASS}
201 />
202 ),
203 runProject: openProjectFromSearch,
204 }),
205 [openProjectFromSearch, projects],
206 );
207​
208 const projectThreadItems = useMemo(
209 () =>
210 buildProjectActionItems({
211 projects,
212 valuePrefix: "new-thread-in",
213 icon: (project) => (
214 <ProjectFavicon
215 environmentId={project.environmentId}
216 cwd={project.cwd}
217 className={ITEM_ICON_CLASS}
218 />
219 ),
220 runProject: async (project) => {
221 await startNewThreadInProjectFromContext(
222 {
223 activeDraftThread,
224 activeThread,
225 defaultProjectRef,
226 defaultThreadEnvMode: settings.defaultThreadEnvMode,
227 handleNewThread,
228 },
229 scopeProjectRef(project.environmentId, project.id),
230 );
231 },
232 }),
233 [
234 activeDraftThread,
235 activeThread,
236 defaultProjectRef,
237 handleNewThread,
238 projects,
239 settings.defaultThreadEnvMode,
240 ],
241 );
242​
243 const allThreadItems = useMemo(
244 () =>
245 buildThreadActionItems({
246 threads,
247 ...(activeThreadId ? { activeThreadId } : {}),
248 projectTitleById,
249 sortOrder: settings.sidebarThreadSortOrder,
250 icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
251 runThread: async (thread) => {
252 await navigate({
253 to: "/$environmentId/$threadId",
254 params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
255 });
256 },
257 }),
258 [activeThreadId, navigate, projectTitleById, settings.sidebarThreadSortOrder, threads],
259 );
260 const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
261​
262 function pushView(item: CommandPaletteSubmenuItem): void {
263 setViewStack((previousViews) => [
264 ...previousViews,
265 {
266 addonIcon: item.addonIcon,
267 groups: item.groups,
268 ...(item.initialQuery ? { initialQuery: item.initialQuery } : {}),
269 },
270 ]);
271 setQuery(item.initialQuery ?? "");
272 }
273​
274 function popView(): void {
275 setViewStack((previousViews) => previousViews.slice(0, -1));
276 setQuery("");
277 }
278​
279 function handleQueryChange(nextQuery: string): void {
280 setQuery(nextQuery);
281 if (nextQuery === "" && currentView?.initialQuery) {
282 popView();
283 }
284 }
285​
286 const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
287​
288 if (projects.length > 0) {
289 const activeProjectTitle = currentProjectId
290 ? (projectTitleById.get(currentProjectId) ?? null)
291 : null;
292​
293 if (activeProjectTitle) {
294 actionItems.push({
295 kind: "action",
296 value: "action:new-thread",
297 searchTerms: ["new thread", "chat", "create", "draft"],
298 title: (
299 <>
300 New thread in <span className="font-semibold">{activeProjectTitle}</span>
301 </>
302 ),
303 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
304 shortcutCommand: "chat.new",
305 run: async () => {
306 await startNewThreadFromContext({
307 activeDraftThread,
308 activeThread,
309 defaultProjectRef,
310 defaultThreadEnvMode: settings.defaultThreadEnvMode,
311 handleNewThread,
312 });
313 },
314 });
315 }
316​
317 actionItems.push({
318 kind: "submenu",
319 value: "action:new-thread-in",
320 searchTerms: ["new thread", "project", "pick", "choose", "select"],
321 title: "New thread in...",
322 icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,
323 addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
324 groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
325 });
326 }
327​
328 actionItems.push({
329 kind: "action",
330 value: "action:settings",
331 searchTerms: ["settings", "preferences", "configuration", "keybindings"],
332 title: "Open settings",
333 icon: <SettingsIcon className={ITEM_ICON_CLASS} />,
334 run: async () => {
335 await navigate({ to: "/settings" });
336 },
337 });
338​
339 const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
340 const activeGroups = currentView ? currentView.groups : rootGroups;
341​
342 const displayedGroups = filterCommandPaletteGroups({
343 activeGroups,
344 query: deferredQuery,
345 isInSubmenu: currentView !== null,
346 projectSearchItems: projectSearchItems,
347 threadSearchItems: allThreadItems,
348 });
349​
350 const inputPlaceholder = getCommandPaletteInputPlaceholder(paletteMode);
351 const isSubmenu = paletteMode === "submenu";
352​
353 function handleKeyDown(event: KeyboardEvent<HTMLInputElement>): void {
354 if (event.key === "Backspace" && query === "" && isSubmenu) {
355 event.preventDefault();
356 popView();
357 }
358 }
359​
360 function executeItem(item: CommandPaletteActionItem | CommandPaletteSubmenuItem): void {
361 if (item.kind === "submenu") {
362 pushView(item);
363 return;
364 }
365​
366 if (!item.keepOpen) {
367 setOpen(false);
368 }
369​
370 void item.run().catch((error: unknown) => {
371 toastManager.add({
372 type: "error",
373 title: "Unable to run command",
374 description: error instanceof Error ? error.message : "An unexpected error occurred.",
375 });
376 });
377 }
378​
379 return (
380 <CommandDialogPopup
381 aria-label="Command palette"
382 className="overflow-hidden p-0"
383 data-testid="command-palette"
384 finalFocus={() => {
385 composerHandleRef?.current?.focusAtEnd();
386 return false;
387 }}
388 >
389 <Command
390 key={viewStack.length}
391 aria-label="Command palette"
392 autoHighlight="always"
393 mode="none"
394 onValueChange={handleQueryChange}
395 value={query}
396 >
397 <CommandInput
398 placeholder={inputPlaceholder}
399 wrapperClassName={
400 isSubmenu
401 ? "[&_[data-slot=autocomplete-start-addon]]:pointer-events-auto [&_[data-slot=autocomplete-start-addon]]:cursor-pointer"
402 : undefined
403 }
404 {...(isSubmenu
405 ? {
406 startAddon: (
407 <button
408 type="button"
409 className="flex cursor-pointer items-center"
410 aria-label="Back"
411 onClick={popView}
412 >
413 <ArrowLeftIcon />
414 </button>
415 ),
416 }
417 : {})}
418 onKeyDown={handleKeyDown}
419 />
420 <CommandPanel className="max-h-[min(28rem,70vh)]">
421 <CommandPaletteResults
422 groups={displayedGroups}
423 isActionsOnly={isActionsOnly}
424 keybindings={keybindings}
425 onExecuteItem={executeItem}
426 />
427 </CommandPanel>
428 <CommandFooter className="gap-3 max-sm:flex-col max-sm:items-start">
429 <div className="flex items-center gap-3">
430 <KbdGroup className="items-center gap-1.5">
431 <Kbd>
432 <ArrowUpIcon />
433 </Kbd>
434 <Kbd>
435 <ArrowDownIcon />
436 </Kbd>
437 <span className={cn("text-muted-foreground/80")}>Navigate</span>
438 </KbdGroup>
439 <KbdGroup className="items-center gap-1.5">
440 <Kbd>Enter</Kbd>
441 <span className={cn("text-muted-foreground/80")}>Select</span>
442 </KbdGroup>
443 {isSubmenu ? (
444 <KbdGroup className="items-center gap-1.5">
445 <Kbd>Backspace</Kbd>
446 <span className={cn("text-muted-foreground/80")}>Back</span>
447 </KbdGroup>
448 ) : null}
449 <KbdGroup className="items-center gap-1.5">
450 <Kbd>Esc</Kbd>
451 <span className={cn("text-muted-foreground/80")}>Close</span>
452 </KbdGroup>
453 </div>
454 </CommandFooter>
455 </Command>
456 </CommandDialogPopup>
457 );