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

CommandPalette.tsx

512 lines18.2 KB

1import { useNavigation } from "@react-navigation/native";
2import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
3import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
4import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
5import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6import {
7 FlatList,
8 KeyboardAvoidingView,
9 Modal,
10 Pressable,
11 Text as NativeText,
12 TextInput,
13 useWindowDimensions,
14 View,
15 type TextInputInstance,
16} from "react-native";
17​
18import { GestureHandlerRootView } from "react-native-gesture-handler";
19​
20import { GlassSurface } from "../../components/ui/GlassSurface";
21import { RowPressable } from "../../components/ui/RowPressable";
22import { AppText as Text } from "../../components/ui/AppText";
23import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
24import { cn } from "../../lib/cn";
25import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
26import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
27import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
28import { useThreadSearch } from "../../state/queries";
29import { useWorkspaceEnvironments } from "../../state/workspace";
30import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
31import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
32import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
33import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
34import {
35 filterCommandPaletteItems,
36 nextPaletteIndex,
37 type CommandPaletteItem,
38} from "./commandPaletteItems";
39import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
40import { threadJumpIndex } from "./threadKeyboardShortcuts";
41import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
42​
43const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
44 "commandPalette",
45 "paletteDismiss",
46 "paletteNext",
47 "palettePrevious",
48 ...THREAD_JUMP_KEYBINDING_COMMANDS,
49];
50const ROW_HEIGHT = 50;
51​
52const ACTION_ICONS: Record<string, AppSymbolName> = {
53 newTask: "square.and.pencil",
54 newThread: "square.and.pencil",
55 addProject: "folder.badge.plus",
56 settings: "gearshape",
57 appearance: "paintbrush",
58 environments: "desktopcomputer",
59 usage: "chart.bar.xaxis",
60 archive: "archivebox",
61 files: "doc.text",
62 terminal: "terminal",
63 review: PullRequestGlyph.pullRequest,
64 copyThreadReference: "link",
65};
66​
67function itemIcon(item: CommandPaletteItem): AppSymbolName {
68 if (item.kind === "project") return "folder";
69 if (item.kind === "thread") return "text.bubble";
70 return ACTION_ICONS[item.key] ?? "ellipsis";
72​
73function PaletteRow(props: {
74 readonly item: CommandPaletteItem;
75 readonly index: number;
76 readonly selected: boolean;
77 readonly searchMatch?: EnvironmentThreadSearchMatch;
78 readonly searchQuery: string;
79 readonly onSelect: () => void;
80}) {
81 const foregroundClassName = props.selected
82 ? "text-thread-selected-foreground"
83 : "text-foreground";
84 const mutedForegroundClassName = props.selected
85 ? "text-thread-selected-foreground-muted"
86 : "text-foreground-muted";
87 return (
88 <RowPressable
89 accessibilityRole="button"
90 interactionOpacity={props.selected ? 0 : 1}
91 accessibilityState={{ selected: props.selected }}
92 onPress={props.onSelect}
93 className={
94 props.selected
95 ? "mx-2 flex-row items-center gap-3 rounded-xl bg-thread-selected px-3"
96 : "mx-2 flex-row items-center gap-3 rounded-xl px-3"
97 }
98 style={{ height: ROW_HEIGHT }}
99 >
100 <View className="w-7 items-center">
101 <SymbolView
102 name={itemIcon(props.item)}
103 size={20}
104 tintColorClassName={props.selected ? "accent-thread-selected-foreground" : "accent-icon"}
105 />
106 </View>
107 <View className="flex-1">
108 <Text numberOfLines={1} className={cn("text-base", foregroundClassName)}>
109 {props.item.title}
110 </Text>
111 {props.searchMatch ? (
112 <ThreadSearchMatchExcerpt
113 match={props.searchMatch}
114 query={props.searchQuery}
115 selected={props.selected}
116 compact
117 />
118 ) : props.item.detail ? (
119 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
120 {props.item.detail}
121 </Text>
122 ) : null}
123 </View>
124 {props.index < 9 ? (
125 <NativeText
126 className={cn("w-8 shrink-0 text-right text-sm tabular-nums", mutedForegroundClassName)}
127 >
128 ⌘{props.index + 1}
129 </NativeText>
130 ) : null}
131 </RowPressable>
132 );
134​
135/** Mounted only while open, so the app root does not subscribe to the full thread catalog. */
136export function CommandPalette(props: {
137 readonly pathname: string;
138 readonly onClose: () => void;
139 readonly onCommand: (command: HardwareKeyboardCommand) => void;
140}) {
141 const navigation = useNavigation();
142 const { themeVariables } = useAppearancePreferences();
143 const { selectThread } = useAdaptiveWorkspaceLayout();
144 const runCommand = props.onCommand;
145 const projects = useProjects();
146 const threads = useThreadShells();
147 const activeThreadRef = useMemo(() => parseActiveThreadPath(props.pathname), [props.pathname]);
148 const activeThread = useThreadShell(activeThreadRef);
149 const environments = useWorkspaceEnvironments();
150 const { savedConnectionsById } = useSavedRemoteConnections();
151 const [query, setQuery] = useState("");
152 const [selection, setSelection] = useState<string | null>(null);
153 const [visible, setVisible] = useState(true);
154 const pendingAction = useRef<(() => void) | null>(null);
155 const closing = useRef(false);
156 const inputRef = useRef<TextInputInstance>(null);
157 const listRef = useRef<FlatList<CommandPaletteItem>>(null);
158 const { width, height } = useWindowDimensions();
159 const searchEnvironmentIds = useMemo(
160 () =>
161 environments
162 .filter((environment) => environment.connectionState === "connected")
163 .map((environment) => environment.environmentId),
164 [environments],
165 );
166 const search = useThreadSearch(searchEnvironmentIds, query.startsWith(">") ? "" : query);
167 const matchedThreadKeys = useMemo(
168 () =>
169 new Set(search.matches.map((match) => scopedThreadKey(match.environmentId, match.threadId))),
170 [search.matches],
171 );
172 const contentMatchByKey = useMemo(
173 () =>
174 new Map(
175 search.matches
176 .filter((match) => match.source === "user" || match.source === "assistant")
177 .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]),
178 ),
179 [search.matches],
180 );
181 const items = useMemo(() => {
182 const actions: CommandPaletteItem[] = [
183 {
184 key: "newTask",
185 kind: "action",
186 title: "New thread in…",
187 searchTerms: ["new task", "chat", "create", "project"],
188 run: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
189 },
190 {
191 key: "addProject",
192 kind: "action",
193 title: "Add project",
194 searchTerms: ["folder", "clone", "repository", "git"],
195 run: () => navigation.navigate("NewTaskSheet", { screen: "AddProject" }),
196 },
197 {
198 key: "settings",
199 kind: "action",
200 title: "Open settings",
201 searchTerms: ["preferences", "configuration"],
202 run: () =>
203 navigation.navigate("SettingsSheet", {
204 screen: "SettingsContent",
205 params: { screen: "Settings" },
206 }),
207 },
208 {
209 key: "appearance",
210 kind: "action",
211 title: "Appearance",
212 searchTerms: ["theme", "colors", "dark", "light"],
213 run: () =>
214 navigation.navigate("SettingsSheet", {
215 screen: "SettingsContent",
216 params: { screen: "SettingsAppearance" },
217 }),
218 },
219 {
220 key: "environments",
221 kind: "action",
222 title: "Manage environments",
223 searchTerms: ["connections", "server", "remote"],
224 run: () =>
225 navigation.navigate("SettingsSheet", {
226 screen: "SettingsContent",
227 params: { screen: "SettingsEnvironments" },
228 }),
229 },
230 {
231 key: "scheduledTasks",
232 kind: "action",
233 title: "Scheduled tasks",
234 searchTerms: ["schedule", "automations", "recurring"],
235 run: () =>
236 navigation.navigate("SettingsSheet", {
237 screen: "SettingsContent",
238 params: { screen: "SettingsScheduledTasks" },
239 }),
240 },
241 {
242 key: "usage",
243 kind: "action",
244 title: "Usage",
245 searchTerms: ["limits", "accounts", "quota"],
246 run: () =>
247 navigation.navigate("SettingsSheet", {
248 screen: "SettingsContent",
249 params: { screen: "SettingsUsage" },
250 }),
251 },
252 {
253 key: "archive",
254 kind: "action",
255 title: "Archived threads",
256 searchTerms: ["restore", "history"],
257 run: () =>
258 navigation.navigate("SettingsSheet", {
259 screen: "SettingsContent",
260 params: { screen: "SettingsArchive" },
261 }),
262 },
263 ];
264 const projectByKey = new Map(
265 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
266 );
267 const activeProject = activeThread
268 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
269 : null;
270 if (activeProject) {
271 actions.unshift({
272 key: "newThread",
273 kind: "action",
274 title: `New thread in ${activeProject.title}`,
275 searchTerms: ["new task", "chat", "create"],
276 run: () =>
277 navigation.navigate("NewTaskSheet", {
278 screen: "NewTaskDraft",
279 params: {
280 environmentId: activeProject.environmentId,
281 projectId: activeProject.id,
282 title: activeProject.title,
283 },
284 }),
285 });
286 }
287 if (activeThreadRef) {
288 const threadActions = [
289 ["files", "Go to file", ["open", "files", "browse", "search"]],
290 ["terminal", "Open terminal", ["shell", "console"]],
291 ["review", "Review changes", ["diff", "git", "pull request"]],
292 ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
293 ] as const;
294 actions.push(
295 ...threadActions.map(([command, title, searchTerms]) => ({
296 key: command,
297 kind: "action" as const,
298 title,
299 searchTerms,
300 run: () => runCommand(command),
301 })),
302 );
303 }
304 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
305 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
306 kind: "project",
307 title: project.title,
308 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
309 searchTerms: [project.workspaceRoot, "new thread", "project"],
310 run: () =>
311 navigation.navigate("NewTaskSheet", {
312 screen: "NewTaskDraft",
313 params: {
314 environmentId: project.environmentId,
315 projectId: project.id,
316 title: project.title,
317 },
318 }),
319 }));
320 const threadItems: CommandPaletteItem[] = threads
321 .filter((thread) => thread.archivedAt === null)
322 .sort((left, right) =>
323 (right.latestUserMessageAt ?? right.updatedAt).localeCompare(
324 left.latestUserMessageAt ?? left.updatedAt,
325 ),
326 )
327 .map((thread) => {
328 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
329 const environment =
330 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
331 return {
332 key: scopedThreadKey(thread.environmentId, thread.id),
333 kind: "thread",
334 title: thread.title || "Untitled thread",
335 detail: [project?.title, environment].filter(Boolean).join(" · "),
336 searchTerms: [
337 project?.title ?? "",
338 environment,
339 thread.branch ?? "",
340 ...threadPullRequestSearchTerms(thread),
341 ],
342 run: () => selectThread(thread),
343 };
344 });
345 return [...actions, ...projectItems, ...threadItems];
346 }, [
347 activeThread,
348 activeThreadRef,
349 navigation,
350 projects,
351 runCommand,
352 savedConnectionsById,
353 selectThread,
354 threads,
355 ]);
356 const results = useMemo(
357 () => filterCommandPaletteItems(items, query, matchedThreadKeys),
358 [items, matchedThreadKeys, query],
359 );
360 const selectedIndex = Math.max(
361 0,
362 results.findIndex((item) => item.key === selection),
363 );
364 const selectedKey = results[selectedIndex]?.key;
365 useEffect(() => {
366 if (selectedIndex === 0) {
367 // Centering before the list measures its height scrolls half the first row out of view.
368 listRef.current?.scrollToOffset({ offset: 0, animated: false });
369 } else if (selectedKey !== undefined) {
370 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
371 }
372 }, [selectedIndex, selectedKey]);
373​
374 const dismissed = useRef(false);
375 const handleDismissed = useCallback(() => {
376 if (dismissed.current) return;
377 dismissed.current = true;
378 // Present navigation sheets only after UIKit has dismissed this modal.
379 props.onClose();
380 pendingAction.current?.();
381 }, [props]);
382​
383 // iOS drops Modal onDismiss when the VC is dismissed mid-presentation (e.g.
384 // ⌘K during the fade-in) or raced by another sheet — without a fallback the
385 // palette stays mounted-but-invisible and ⌘K dead-ends on a stale open state.
386 useEffect(() => {
387 if (visible) return;
388 const fallback = setTimeout(handleDismissed, 400);
389 return () => clearTimeout(fallback);
390 }, [visible, handleDismissed]);
391​
392 function close(run?: () => void) {
393 if (closing.current) return;
394 closing.current = true;
395 pendingAction.current = run ?? null;
396 setVisible(false);
397 }
398​
399 function onCommand(command: HardwareKeyboardCommand) {
400 if (command === "commandPalette" || command === "paletteDismiss") {
401 close();
402 } else if (command === "paletteNext" || command === "palettePrevious") {
403 setSelection(
404 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
405 ?.key ?? null,
406 );
407 } else {
408 const item = results[threadJumpIndex(command)];
409 if (item) close(item.run);
410 }
411 }
412​
413 return (
414 <Modal
415 visible={visible}
416 transparent
417 animationType="fade"
418 onShow={() => inputRef.current?.focus()}
419 onRequestClose={() => close()}
420 onDismiss={handleDismissed}
421 >
422 <GestureHandlerRootView className="flex-1">
423 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
424 <KeyboardAvoidingView
425 behavior="padding"
426 className="flex-1 items-center justify-center p-4"
427 >
428 <Pressable
429 className="absolute inset-0 bg-backdrop"
430 accessibilityLabel="Close command palette"
431 onPress={() => close()}
432 />
433 <GlassSurface
434 accessibilityViewIsModal
435 className="bg-sheet"
436 tintColorClassName="accent-sheet/20"
437 fallbackColor={themeVariables["--color-sheet"]}
438 style={{
439 width: Math.min(600, width - 32),
440 height: Math.min(520, height - 80),
441 borderRadius: 20,
442 }}
443 >
444 <View className="px-3 pb-2.5 pt-3.5">
445 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
446 <SymbolView
447 name="magnifyingglass"
448 size={15}
449 tintColorClassName="accent-foreground-muted"
450 type="monochrome"
451 />
452 <TextInput
453 ref={inputRef}
454 accessibilityLabel="Search commands, projects, and threads"
455 placeholder="Search commands, projects, and threads…"
456 placeholderTextColorClassName="accent-placeholder"
457 autoCorrect={false}
458 autoCapitalize="none"
459 clearButtonMode="while-editing"
460 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
461 value={query}
462 onChangeText={(value) => {
463 setQuery(value);
464 setSelection(null);
465 listRef.current?.scrollToOffset({ offset: 0, animated: false });
466 }}
467 returnKeyType="go"
468 submitBehavior="submit"
469 onSubmitEditing={() => {
470 const item = results[selectedIndex];
471 if (item) close(item.run);
472 }}
473 />
474 </View>
475 </View>
476 <FlatList
477 ref={listRef}
478 data={results}
479 extraData={selectedKey}
480 keyboardShouldPersistTaps="handled"
481 keyExtractor={(item) => item.key}
482 getItemLayout={(_, index) => ({
483 length: ROW_HEIGHT,
484 offset: ROW_HEIGHT * index,
485 index,
486 })}
487 contentContainerClassName="pb-2"
488 ListEmptyComponent={
489 <Text className="p-5 text-center text-foreground-muted">
490 {search.isPending ? "Searching…" : "No results"}
491 </Text>
492 }
493 renderItem={({ item, index }) => (
494 <PaletteRow
495 item={item}
496 index={index}
497 selected={item.key === selectedKey}
498 searchMatch={
499 item.kind === "thread" ? contentMatchByKey.get(item.key) : undefined
500 }
501 searchQuery={query}
502 onSelect={() => close(item.run)}
503 />
504 )}
505 />
506 </GlassSurface>
507 </KeyboardAvoidingView>
508 </T3KeyboardCommands>
509 </GestureHandlerRootView>
510 </Modal>
511 );