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

CommandPalette.tsx

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