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

CommandPalette.tsx

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