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

CommandPalette.tsx

659 lines24.7 KB

1import { uuidv4 } from "../../lib/uuid";
2import { useNavigation } from "@react-navigation/native";
3import {
4 claimThreadOpen,
5 nextShownOrder,
6 threadSearchSubject,
7 type EnvironmentThreadSearchMatch,
8 type ShownOrder,
9} from "@t3tools/client-runtime/state/thread-search";
10import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
11import {
12 foldSearchQuery,
13 PALETTE_MESSAGE_LIMIT,
14 rankMessageMatches,
15 splitSearchText,
16 pickedQuery,
17 threadRecentUse,
18} from "@t3tools/shared/paletteSearch";
19import { useCallback, useEffect, useMemo, useRef, useState } from "react";
20import {
21 FlatList,
22 KeyboardAvoidingView,
23 Modal,
24 Pressable,
25 Text as NativeText,
26 TextInput,
27 useWindowDimensions,
28 View,
29 type TextInputInstance,
30} from "react-native";
31​
32import { GestureHandlerRootView } from "react-native-gesture-handler";
33​
34import { ProjectFavicon } from "../../components/ProjectFavicon";
35import { GlassSurface } from "../../components/ui/GlassSurface";
36import { RowPressable } from "../../components/ui/RowPressable";
37import { AppText as Text } from "../../components/ui/AppText";
38import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
39import { cn } from "../../lib/cn";
40import { deriveBottomControlInsets } from "../../lib/reserved-regions";
41import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
42import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
43import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
44import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
45import { useThreadSearch } from "../../state/queries";
46import { requestThreadMessageJump } from "../threads/threadMessageJump";
47import { threadEnvironment } from "../../state/threads";
48import { useAtomCommand } from "../../state/use-atom-command";
49import { useWorkspaceEnvironments } from "../../state/workspace";
50import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
51import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
52import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
53import {
54 filterCommandPaletteItems,
55 nextPaletteIndex,
56 type CommandPaletteItem,
57 type CommandPaletteResult,
58} from "./commandPaletteItems";
59import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
60import { threadJumpIndex } from "./threadKeyboardShortcuts";
61import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
62import { openSettings } from "../settings/settings-navigation";
63import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
64import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
65​
66const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
67 "commandPalette",
68 "paletteDismiss",
69 "paletteNext",
70 "palettePrevious",
71 ...THREAD_JUMP_KEYBINDING_COMMANDS,
72];
73const ROW_HEIGHT = 50;
74// The "In messages" label above the first message match; server results always come last.
75const SECTION_LABEL_HEIGHT = 26;
76​
77const ACTION_ICONS: Record<string, AppSymbolName> = {
78 newTask: "square.and.pencil",
79 newThread: "square.and.pencil",
80 addProject: "folder.badge.plus",
81 settings: "gearshape",
82 appearance: "paintbrush",
83 environments: "desktopcomputer",
84 usage: "chart.bar.xaxis",
85 archive: "archivebox",
86 files: "doc.text",
87 terminal: "terminal",
88 review: PullRequestGlyph.pullRequest,
89 copyThreadReference: "link",
90};
91​
92function itemIcon(item: CommandPaletteItem): AppSymbolName {
93 if (item.kind === "thread") return "text.bubble";
94 return ACTION_ICONS[item.key] ?? "ellipsis";
96​
97function PaletteRow(props: {
98 readonly item: CommandPaletteResult;
99 readonly index: number;
100 readonly selected: boolean;
101 readonly searchMatch?: EnvironmentThreadSearchMatch;
102 readonly searchQuery: string;
103 readonly onSelect: () => void;
104}) {
105 const foregroundClassName = props.selected
106 ? "text-thread-selected-foreground"
107 : "text-foreground";
108 const mutedForegroundClassName = props.selected
109 ? "text-thread-selected-foreground-muted"
110 : "text-foreground-muted";
111 return (
112 <RowPressable
113 accessibilityRole="button"
114 interactionOpacity={props.selected ? 0 : 1}
115 accessibilityState={{ selected: props.selected }}
116 onPress={props.onSelect}
117 className={
118 props.selected
119 ? "mx-2 flex-row items-center gap-3 rounded-xl bg-thread-selected px-3"
120 : "mx-2 flex-row items-center gap-3 rounded-xl px-3"
121 }
122 style={{ height: ROW_HEIGHT }}
123 >
124 <View className="w-7 items-center">
125 {props.item.project ? (
126 <ProjectFavicon
127 environmentId={props.item.project.environmentId}
128 faviconPath={props.item.project.faviconPath}
129 projectIcon={props.item.project.projectIcon}
130 projectTitle={props.item.project.title}
131 size={20}
132 workspaceRoot={props.item.project.workspaceRoot}
133 />
134 ) : (
135 <SymbolView
136 name={itemIcon(props.item)}
137 size={20}
138 tintColorClassName={
139 props.selected ? "accent-thread-selected-foreground" : "accent-icon"
140 }
141 />
142 )}
143 </View>
144 <View className="flex-1">
145 <View className="flex-row items-baseline gap-2">
146 <Text numberOfLines={1} className={cn("shrink text-base", foregroundClassName)}>
147 {props.item.titleRanges?.length
148 ? splitSearchText(props.item.title, props.item.titleRanges).map((part) => (
149 <Text
150 key={part.start}
151 className={cn("text-base", part.highlighted && "font-t3-bold")}
152 >
153 {part.text}
154 </Text>
155 ))
156 : props.item.title}
157 </Text>
158 {/* The second line shows the snippet or hint, so keep where the thread
159 lives, unless the hint already names it. */}
160 {(props.searchMatch ||
161 (props.item.matchHint &&
162 props.item.matchHint.label !== "Project" &&
163 props.item.matchHint.label !== "Environment")) &&
164 props.item.detail ? (
165 <Text
166 numberOfLines={1}
167 className={cn("max-w-[45%] shrink-0 text-sm", mutedForegroundClassName)}
168 >
169 {props.item.detail}
170 </Text>
171 ) : null}
172 </View>
173 {props.searchMatch ? (
174 <ThreadSearchMatchExcerpt
175 match={props.searchMatch}
176 query={props.searchQuery}
177 selected={props.selected}
178 compact
179 />
180 ) : props.item.matchHint ? (
181 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
182 {props.item.matchHint.label}:{" "}
183 {splitSearchText(props.item.matchHint.text, props.item.matchHint.ranges).map((part) => (
184 <Text key={part.start} className={cn("text-sm", part.highlighted && "font-t3-bold")}>
185 {part.text}
186 </Text>
187 ))}
188 </Text>
189 ) : props.item.detail ? (
190 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
191 {props.item.detail}
192 </Text>
193 ) : null}
194 </View>
195 {props.index < 9 ? (
196 <NativeText
197 className={cn("w-8 shrink-0 text-right text-sm tabular-nums", mutedForegroundClassName)}
198 >
199 ⌘{props.index + 1}
200 </NativeText>
201 ) : null}
202 </RowPressable>
203 );
205​
206/** Mounted only while open, so the app root does not subscribe to the full thread catalog. */
207export function CommandPalette(props: {
208 readonly pathname: string;
209 readonly onClose: () => void;
210 readonly onCommand: (command: HardwareKeyboardCommand) => void;
211}) {
212 const navigation = useNavigation();
213 const selectTab = useSelectWorkspaceTab();
214 const { themeVariables } = useAppearancePreferences();
215 const selectDetail = useSelectWorkspaceDetail();
216 const runCommand = props.onCommand;
217 const projects = useProjects();
218 const threads = useThreadShells();
219 const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]);
220 const activeThread = useThreadShell(activeThreadRef);
221 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
222 const environments = useWorkspaceEnvironments();
223 const { savedConnectionsById } = useSavedRemoteConnections();
224 const [query, setQuery] = useState("");
225 // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
226 const [now] = useState(() => Date.now());
227 const [selection, setSelection] = useState<string | null>(null);
228 const [visible, setVisible] = useState(true);
229 const pendingAction = useRef<(() => void) | null>(null);
230 const closing = useRef(false);
231 const inputRef = useRef<TextInputInstance>(null);
232 const listRef = useRef<FlatList<CommandPaletteResult>>(null);
233 const { width, height } = useWindowDimensions();
234 // The palette floats above every column, so it keeps itself inside the window's side insets
235 // and to one side of a book fold.
236 const bounds = deriveBottomControlInsets(useNativeLayoutMetrics());
237 const searchEnvironmentIds = useMemo(
238 () =>
239 environments
240 .filter((environment) => environment.connectionState === "connected")
241 .map((environment) => environment.environmentId),
242 [environments],
243 );
244 const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query);
245 const contentMatchByKey = useMemo(
246 () =>
247 new Map(
248 search.matches
249 .filter((match) => match.source === "user" || match.source === "assistant")
250 .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]),
251 ),
252 [search.matches],
253 );
254 const items = useMemo(() => {
255 const actions: CommandPaletteItem[] = [
256 {
257 key: "newTask",
258 kind: "action",
259 title: "New thread in…",
260 searchTerms: ["new task", "chat", "create", "project"],
261 run: () => runCommand("newTask"),
262 },
263 {
264 key: "addProject",
265 kind: "action",
266 title: "Add project",
267 searchTerms: ["folder", "clone", "repository", "git"],
268 run: () => navigation.navigate("AddProject"),
269 },
270 {
271 key: "settings",
272 kind: "action",
273 title: "Open settings",
274 searchTerms: ["preferences", "configuration"],
275 run: () => selectTab("settings"),
276 },
277 {
278 key: "appearance",
279 kind: "action",
280 title: "Appearance",
281 searchTerms: ["theme", "colors", "dark", "light"],
282 run: () => openSettings(navigation, "SettingsAppearance"),
283 },
284 {
285 key: "environments",
286 kind: "action",
287 title: "Manage environments",
288 searchTerms: ["connections", "server", "remote"],
289 run: () => openSettings(navigation, "SettingsEnvironments"),
290 },
291 {
292 key: "scheduledTasks",
293 kind: "action",
294 title: "Scheduled tasks",
295 searchTerms: ["schedule", "automations", "recurring"],
296 run: () => openSettings(navigation, "SettingsScheduledTasks"),
297 },
298 {
299 key: "usage",
300 kind: "action",
301 title: "Usage",
302 searchTerms: ["limits", "accounts", "quota"],
303 run: () => openSettings(navigation, "SettingsUsage"),
304 },
305 {
306 key: "archive",
307 kind: "action",
308 title: "Archived threads",
309 searchTerms: ["restore", "history"],
310 run: () => openSettings(navigation, "SettingsArchive"),
311 },
312 ];
313 const projectByKey = new Map(
314 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
315 );
316 const activeProject = activeThread
317 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
318 : null;
319 if (activeProject) {
320 actions.unshift({
321 key: "newThread",
322 kind: "action",
323 title: `New thread in ${activeProject.title}`,
324 searchTerms: ["new task", "chat", "create"],
325 run: () =>
326 selectDetail({
327 name: "Thread",
328 params: {
329 draft: {
330 requestId: uuidv4(),
331 environmentId: activeProject.environmentId,
332 projectId: activeProject.id,
333 title: activeProject.title,
334 },
335 },
336 }),
337 });
338 }
339 if (activeThreadRef) {
340 const threadActions = [
341 ["files", "Go to file", ["open", "files", "browse", "search"]],
342 ["terminal", "Open terminal", ["shell", "console"]],
343 ["review", "Review changes", ["diff", "git", "pull request"]],
344 ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
345 ] as const;
346 actions.push(
347 ...threadActions.map(([command, title, searchTerms]) => ({
348 key: command,
349 kind: "action" as const,
350 title,
351 searchTerms,
352 run: () => runCommand(command),
353 })),
354 );
355 }
356 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
357 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
358 kind: "project",
359 project,
360 title: project.title,
361 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
362 searchTerms: [project.workspaceRoot, "new thread", "project"],
363 run: () =>
364 selectDetail({
365 name: "Thread",
366 params: {
367 draft: {
368 requestId: uuidv4(),
369 environmentId: project.environmentId,
370 projectId: project.id,
371 title: project.title,
372 },
373 },
374 }),
375 }));
376 const threadItems: CommandPaletteItem[] = threads
377 .filter(
378 (thread) =>
379 thread.archivedAt === null && thread.lineage.relationshipToParent !== "subagent",
380 )
381 .map((thread) => {
382 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
383 const environment =
384 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
385 return {
386 key: scopedThreadKey(thread.environmentId, thread.id),
387 kind: "thread",
388 title: thread.title || "Untitled thread",
389 detail: [project?.title, environment].filter(Boolean).join(" · "),
390 searchTerms: [],
391 threadSearch: threadSearchSubject(
392 thread,
393 project?.title,
394 environments.length > 1 ? environment : null,
395 ),
396 // Last among threads: picking the thread already open does nothing.
397 ...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id
398 ? { secondary: true }
399 : {}),
400 run: () =>
401 selectDetail({
402 name: "Thread",
403 params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },
404 }),
405 };
406 });
407 // Recent means used recently: written in or opened, whichever is later.
408 threadItems.sort(
409 (left, right) =>
410 (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) -
411 (left.threadSearch ? threadRecentUse(left.threadSearch) : 0),
412 );
413 return [...actions, ...projectItems, ...threadItems];
414 }, [
415 selectTab,
416 activeThread,
417 activeThreadRef,
418 environments.length,
419 navigation,
420 projects,
421 runCommand,
422 savedConnectionsById,
423 selectDetail,
424 threads,
425 ]);
426 const rankedMessageKeys = useMemo(() => {
427 const subjectByKey = new Map(
428 items.flatMap((item) => (item.threadSearch ? [[item.key, item.threadSearch] as const] : [])),
429 );
430 const keyOf = (match: EnvironmentThreadSearchMatch) =>
431 scopedThreadKey(match.environmentId, match.threadId);
432 return rankMessageMatches(
433 search.matches,
434 (match) => subjectByKey.get(keyOf(match)),
435 foldSearchQuery(query),
436 now,
437 { withoutTitleMatches: true },
438 ).map(keyOf);
439 }, [items, now, query, search.matches]);
440 // Rows already shown keep their places when a slower environment answers.
441 const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
442 const messageOrder = nextShownOrder(
443 shownOrder,
444 search.query,
445 rankedMessageKeys,
446 PALETTE_MESSAGE_LIMIT,
447 );
448 if (messageOrder !== shownOrder) setShownOrder(messageOrder);
449 const messageMatchKeys = useMemo(
450 () => messageOrder.keys.slice(0, messageOrder.shown),
451 [messageOrder.keys, messageOrder.shown],
452 );
453 const results = useMemo(() => {
454 const ranked = filterCommandPaletteItems(items, query, messageMatchKeys, now);
455 // Recent threads leave out the open one, which would always lead them.
456 const activeKey = activeThread
457 ? scopedThreadKey(activeThread.environmentId, activeThread.id)
458 : null;
459 return query.trim() ? ranked : ranked.filter((item) => item.key !== activeKey);
460 }, [activeThread, items, messageMatchKeys, now, query]);
461 const runResult = (item: CommandPaletteResult) => {
462 const thread =
463 item.kind === "thread" && query.trim() && !query.startsWith(">")
464 ? threads.find(
465 (candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === item.key,
466 )
467 : undefined;
468 // A message result opens the thread at that message.
469 const messageId = item.fromMessages ? contentMatchByKey.get(item.key)?.messageId : undefined;
470 if (messageId) requestThreadMessageJump(item.key, messageId);
471 // A pick sends its open with the query, always, so the server records it;
472 // the thread screen then skips its own open. The open thread is no pick.
473 if (thread && !item.secondary) claimThreadOpen(thread.environmentId, thread.id, Date.now());
474 if (thread && thread.lastVisitedAt !== undefined && !item.secondary) {
475 void visitThread({
476 environmentId: thread.environmentId,
477 input: {
478 threadId: thread.id,
479 visitedAt: thread.updatedAt,
480 opened: true,
481 searchQuery: pickedQuery(query),
482 },
483 });
484 }
485 item.run();
486 };
487 const firstMessageIndex = results.findIndex((item) => item.fromMessages);
488 const selectedIndex = Math.max(
489 0,
490 results.findIndex((item) => item.key === selection),
491 );
492 const selectedKey = results[selectedIndex]?.key;
493 useEffect(() => {
494 if (selectedIndex === 0) {
495 // Centering before the list measures its height scrolls half the first row out of view.
496 listRef.current?.scrollToOffset({ offset: 0, animated: false });
497 } else if (selectedKey !== undefined) {
498 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
499 }
500 }, [selectedIndex, selectedKey]);
501​
502 const dismissed = useRef(false);
503 const handleDismissed = useCallback(() => {
504 if (dismissed.current) return;
505 dismissed.current = true;
506 // Present navigation sheets only after UIKit has dismissed this modal.
507 props.onClose();
508 pendingAction.current?.();
509 }, [props]);
510​
511 // iOS may drop onDismiss during presentation or competing sheets; a fallback clears stale palette state.
512 useEffect(() => {
513 if (visible) return;
514 const fallback = setTimeout(handleDismissed, 400);
515 return () => clearTimeout(fallback);
516 }, [visible, handleDismissed]);
517​
518 function close(run?: () => void) {
519 if (closing.current) return;
520 closing.current = true;
521 pendingAction.current = run ?? null;
522 setVisible(false);
523 }
524​
525 function onCommand(command: HardwareKeyboardCommand) {
526 if (command === "commandPalette" || command === "paletteDismiss") {
527 close();
528 } else if (command === "paletteNext" || command === "palettePrevious") {
529 setSelection(
530 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
531 ?.key ?? null,
532 );
533 } else {
534 const item = results[threadJumpIndex(command)];
535 if (item) close(() => runResult(item));
536 }
537 }
538​
539 return (
540 <Modal
541 visible={visible}
542 transparent
543 animationType="fade"
544 onShow={() => inputRef.current?.focus()}
545 onRequestClose={() => close()}
546 onDismiss={handleDismissed}
547 >
548 <GestureHandlerRootView className="flex-1">
549 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
550 <KeyboardAvoidingView
551 behavior="padding"
552 className="flex-1 items-center justify-center py-4"
553 style={{ paddingLeft: 16 + bounds.left, paddingRight: 16 + bounds.right }}
554 >
555 <Pressable
556 className="absolute inset-0 bg-backdrop"
557 accessibilityLabel="Close command palette"
558 onPress={() => close()}
559 />
560 <GlassSurface
561 accessibilityViewIsModal
562 className="bg-sheet"
563 tintColorClassName="accent-sheet/20"
564 fallbackColor={themeVariables["--color-sheet"]}
565 style={{
566 width: Math.min(600, width - 32 - bounds.left - bounds.right),
567 height: Math.min(520, height - 80),
568 borderRadius: 20,
569 }}
570 >
571 <View className="px-3 pb-2.5 pt-3.5">
572 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
573 <SymbolView
574 name="magnifyingglass"
575 size={15}
576 tintColorClassName="accent-foreground-muted"
577 type="monochrome"
578 />
579 <TextInput
580 ref={inputRef}
581 accessibilityLabel="Search commands, projects, and threads"
582 placeholder="Search commands, projects, and threads…"
583 placeholderTextColorClassName="accent-placeholder"
584 autoCorrect={false}
585 autoCapitalize="none"
586 clearButtonMode="while-editing"
587 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
588 value={query}
589 onChangeText={(value) => {
590 setQuery(value);
591 setSelection(null);
592 listRef.current?.scrollToOffset({ offset: 0, animated: false });
593 }}
594 returnKeyType="go"
595 submitBehavior="submit"
596 onSubmitEditing={() => {
597 const item = results[selectedIndex];
598 if (item) close(() => runResult(item));
599 }}
600 />
601 </View>
602 </View>
603 <FlatList
604 ref={listRef}
605 data={results}
606 extraData={selectedKey}
607 keyboardShouldPersistTaps="handled"
608 keyExtractor={(item) => item.key}
609 getItemLayout={(_, index) => ({
610 length: ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0),
611 offset:
612 ROW_HEIGHT * index +
613 (firstMessageIndex !== -1 && index > firstMessageIndex
614 ? SECTION_LABEL_HEIGHT
615 : 0),
616 index,
617 })}
618 contentContainerClassName="pb-2"
619 ListEmptyComponent={
620 <Text className="p-5 text-center text-foreground-muted">
621 {search.isPending ? "Searching…" : "No results"}
622 </Text>
623 }
624 // Message results from slower environments may still arrive below.
625 ListFooterComponent={
626 results.length > 0 && search.isPending && !query.startsWith(">") ? (
627 <Text className="px-5 pt-2 text-xs text-foreground-muted">
628 Searching messages…
629 </Text>
630 ) : undefined
631 }
632 renderItem={({ item, index }) => (
633 <>
634 {index === firstMessageIndex ? (
635 <Text
636 className="px-5 pt-2 text-xs text-foreground-muted"
637 style={{ height: SECTION_LABEL_HEIGHT }}
638 >
639 In messages
640 </Text>
641 ) : null}
642 <PaletteRow
643 item={item}
644 index={index}
645 selected={item.key === selectedKey}
646 searchMatch={item.fromMessages ? contentMatchByKey.get(item.key) : undefined}
647 searchQuery={search.query}
648 onSelect={() => close(() => runResult(item))}
649 />
650 </>
651 )}
652 />
653 </GlassSurface>
654 </KeyboardAvoidingView>
655 </T3KeyboardCommands>
656 </GestureHandlerRootView>
657 </Modal>
658 );