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

CommandPalette.tsx

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