Open History to see the last commit
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 { useWorkspaceState } 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";
69}
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 );
131}
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 } = useWorkspaceState();
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: "usage",
230 kind: "action",
231 title: "Usage",
232 searchTerms: ["limits", "accounts", "quota"],
233 run: () =>
234 navigation.navigate("SettingsSheet", {
235 screen: "SettingsContent",
236 params: { screen: "SettingsUsage" },
237 }),
238 },
239 {
240 key: "archive",
241 kind: "action",
242 title: "Archived threads",
243 searchTerms: ["restore", "history"],
244 run: () =>
245 navigation.navigate("SettingsSheet", {
246 screen: "SettingsContent",
247 params: { screen: "SettingsArchive" },
248 }),
249 },
250 ];
251 const projectByKey = new Map(
252 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
253 );
254 const activeProject = activeThread
255 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
256 : null;
257 if (activeProject) {
258 actions.unshift({
259 key: "newThread",
260 kind: "action",
261 title: `New thread in ${activeProject.title}`,
262 searchTerms: ["new task", "chat", "create"],
263 run: () =>
264 navigation.navigate("NewTaskSheet", {
265 screen: "NewTaskDraft",
266 params: {
267 environmentId: activeProject.environmentId,
268 projectId: activeProject.id,
269 title: activeProject.title,
270 },
271 }),
272 });
273 }
274 if (activeThreadRef) {
275 const threadActions = [
276 ["files", "Go to file", ["open", "files", "browse", "search"]],
277 ["terminal", "Open terminal", ["shell", "console"]],
278 ["review", "Review changes", ["diff", "git", "pull request"]],
279 ["copyThreadReference", "Copy PR link or thread ID", ["reference", "clipboard"]],
280 ] as const;
281 actions.push(
282 ...threadActions.map(([command, title, searchTerms]) => ({
283 key: command,
284 kind: "action" as const,
285 title,
286 searchTerms,
287 run: () => runCommand(command),
288 })),
289 );
290 }
291 const projectItems: CommandPaletteItem[] = projects.map((project) => ({
292 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
293 kind: "project",
294 title: project.title,
295 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
296 searchTerms: [project.workspaceRoot, "new thread", "project"],
297 run: () =>
298 navigation.navigate("NewTaskSheet", {
299 screen: "NewTaskDraft",
300 params: {
301 environmentId: project.environmentId,
302 projectId: project.id,
303 title: project.title,
304 },
305 }),
306 }));
307 const threadItems: CommandPaletteItem[] = threads
308 .filter((thread) => thread.archivedAt === null)
309 .sort((left, right) =>
310 (right.latestUserMessageAt ?? right.updatedAt).localeCompare(
311 left.latestUserMessageAt ?? left.updatedAt,
312 ),
313 )
314 .map((thread) => {
315 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
316 const environment =
317 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
318 return {
319 key: scopedThreadKey(thread.environmentId, thread.id),
320 kind: "thread",
321 title: thread.title || "Untitled thread",
322 detail: [project?.title, environment].filter(Boolean).join(" · "),
323 searchTerms: [
324 project?.title ?? "",
325 environment,
326 thread.branch ?? "",
327 ...threadPullRequestSearchTerms(thread),
328 ],
329 run: () => selectThread(thread),
330 };
331 });
332 return [...actions, ...projectItems, ...threadItems];
333 }, [
334 activeThread,
335 activeThreadRef,
336 navigation,
337 projects,
338 runCommand,
339 savedConnectionsById,
340 selectThread,
341 threads,
342 ]);
343 const results = useMemo(
344 () => filterCommandPaletteItems(items, query, matchedThreadKeys),
345 [items, matchedThreadKeys, query],
346 );
347 const selectedIndex = Math.max(
348 0,
349 results.findIndex((item) => item.key === selection),
350 );
351 const selectedKey = results[selectedIndex]?.key;
352 useEffect(() => {
353 if (selectedIndex === 0) {
354 // Centering before the list measures its height scrolls half the first row out of view.
355 listRef.current?.scrollToOffset({ offset: 0, animated: false });
356 } else if (selectedKey !== undefined) {
357 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
358 }
359 }, [selectedIndex, selectedKey]);
360
361 const dismissed = useRef(false);
362 const handleDismissed = useCallback(() => {
363 if (dismissed.current) return;
364 dismissed.current = true;
365 // Present navigation sheets only after UIKit has dismissed this modal.
366 props.onClose();
367 pendingAction.current?.();
368 }, [props]);
369
370 // iOS drops Modal onDismiss when the VC is dismissed mid-presentation (e.g.
371 // ⌘K during the fade-in) or raced by another sheet — without a fallback the
372 // palette stays mounted-but-invisible and ⌘K dead-ends on a stale open state.
373 useEffect(() => {
374 if (visible) return;
375 const fallback = setTimeout(handleDismissed, 400);
376 return () => clearTimeout(fallback);
377 }, [visible, handleDismissed]);
378
379 function close(run?: () => void) {
380 if (closing.current) return;
381 closing.current = true;
382 pendingAction.current = run ?? null;
383 setVisible(false);
384 }
385
386 function onCommand(command: HardwareKeyboardCommand) {
387 if (command === "commandPalette" || command === "paletteDismiss") {
388 close();
389 } else if (command === "paletteNext" || command === "palettePrevious") {
390 setSelection(
391 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
392 ?.key ?? null,
393 );
394 } else {
395 const item = results[threadJumpIndex(command)];
396 if (item) close(item.run);
397 }
398 }
399
400 return (
401 <Modal
402 visible={visible}
403 transparent
404 animationType="fade"
405 onShow={() => inputRef.current?.focus()}
406 onRequestClose={() => close()}
407 onDismiss={handleDismissed}
408 >
409 <GestureHandlerRootView className="flex-1">
410 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
411 <KeyboardAvoidingView
412 behavior="padding"
413 className="flex-1 items-center justify-center p-4"
414 >
415 <Pressable
416 className="absolute inset-0 bg-backdrop"
417 accessibilityLabel="Close command palette"
418 onPress={() => close()}
419 />
420 <GlassSurface
421 accessibilityViewIsModal
422 className="bg-sheet"
423 tintColorClassName="accent-sheet/20"
424 fallbackColor={themeVariables["--color-sheet"]}
425 style={{
426 width: Math.min(600, width - 32),
427 height: Math.min(520, height - 80),
428 borderRadius: 20,
429 }}
430 >
431 <View className="px-3 pb-2.5 pt-3.5">
432 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
433 <SymbolView
434 name="magnifyingglass"
435 size={15}
436 tintColorClassName="accent-foreground-muted"
437 type="monochrome"
438 />
439 <TextInput
440 ref={inputRef}
441 accessibilityLabel="Search commands, projects, and threads"
442 placeholder="Search commands, projects, and threads…"
443 placeholderTextColorClassName="accent-placeholder"
444 autoCorrect={false}
445 autoCapitalize="none"
446 clearButtonMode="while-editing"
447 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
448 value={query}
449 onChangeText={(value) => {
450 setQuery(value);
451 setSelection(null);
452 listRef.current?.scrollToOffset({ offset: 0, animated: false });
453 }}
454 returnKeyType="go"
455 submitBehavior="submit"
456 onSubmitEditing={() => {
457 const item = results[selectedIndex];
458 if (item) close(item.run);
459 }}
460 />
461 </View>
462 </View>
463 <FlatList
464 ref={listRef}
465 data={results}
466 extraData={selectedKey}
467 keyboardShouldPersistTaps="handled"
468 keyExtractor={(item) => item.key}
469 getItemLayout={(_, index) => ({
470 length: ROW_HEIGHT,
471 offset: ROW_HEIGHT * index,
472 index,
473 })}
474 contentContainerClassName="pb-2"
475 ListEmptyComponent={
476 <Text className="p-5 text-center text-foreground-muted">
477 {search.isPending ? "Searching…" : "No results"}
478 </Text>
479 }
480 renderItem={({ item, index }) => (
481 <PaletteRow
482 item={item}
483 index={index}
484 selected={item.key === selectedKey}
485 searchMatch={
486 item.kind === "thread" ? contentMatchByKey.get(item.key) : undefined
487 }
488 searchQuery={query}
489 onSelect={() => close(item.run)}
490 />
491 )}
492 />
493 </GlassSurface>
494 </KeyboardAvoidingView>
495 </T3KeyboardCommands>
496 </GestureHandlerRootView>
497 </Modal>
498 );
499}