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