The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 763 lines 29.6 KB
Raw
1 import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
2 import { useAtomValue } from "@effect/atom-react";
3 import { uuidv4 } from "../../lib/uuid";
4 import { useNavigation } from "@react-navigation/native";
5 import {
6 claimThreadOpen,
7 nextShownOrder,
8 threadSearchSubject,
9 type EnvironmentThreadSearchMatch,
10 type ShownOrder,
11 } from "@t3tools/client-runtime/state/thread-search";
12 import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
13 import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts";
14 import {
15 foldSearchQuery,
16 PALETTE_MESSAGE_LIMIT,
17 rankMessageMatches,
18 splitSearchText,
19 pickedQuery,
20 threadRecentUse,
21 } from "@t3tools/shared/paletteSearch";
22 import { searchMatchHintLabel } from "@t3tools/shared/paletteSearchCopy";
23 import { T, useGT, useMessages } from "gt-react-native";
24 import { useEffect, useMemo, useRef, useState } from "react";
25 import {
26 KeyboardAvoidingView,
27 Modal,
28 Pressable,
29 Text as NativeText,
30 TextInput,
31 useWindowDimensions,
32 View,
33 type TextInputInstance,
34 } from "react-native";
35
36 import { GestureHandlerRootView } from "react-native-gesture-handler";
37
38 import { ProjectFavicon } from "../../components/ProjectFavicon";
39 import { GlassSurface } from "../../components/ui/GlassSurface";
40 import { RowPressable } from "../../components/ui/RowPressable";
41 import { AppText as Text } from "../../components/ui/AppText";
42 import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
43 import { cn } from "../../lib/cn";
44 import { deriveBottomControlInsets } from "../../lib/reserved-regions";
45 import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
46 import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
47 import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
48 import {
49 useDelegatedUnderParent,
50 useProjects,
51 useServerConfigs,
52 useThreadShell,
53 useVisibleThreadShells,
54 } from "../../state/entities";
55 import { useThreadSearch } from "../../state/queries";
56 import { requestThreadMessageJump } from "../threads/threadMessageJump";
57 import { useCanShareWithGuest } from "../threads/useCanShareWithGuest";
58 import { threadEnvironment } from "../../state/threads";
59 import { useAtomCommand } from "../../state/use-atom-command";
60 import { serverEnvironment } from "../../state/server";
61 import { useWorkspaceEnvironments } from "../../state/workspace";
62 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
63 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
64 import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
65 import { pickTriageEnvironment } from "../triage/triageTarget";
66 import { useStartTriage } from "../triage/useStartTriage";
67 import { useNewTaskFlow } from "../threads/new-task-flow-provider";
68 import { useActiveNewTask } from "../../state/active-new-task";
69 import {
70 filterCommandPaletteItems,
71 nextPaletteIndex,
72 type CommandPaletteItem,
73 type CommandPaletteResult,
74 } from "./commandPaletteItems";
75 import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
76 import { threadJumpIndex } from "./threadKeyboardShortcuts";
77 import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
78 import { openSettings } from "../settings/settings-navigation";
79 import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab";
80 import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
81
82 const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
83 "commandPalette",
84 "paletteDismiss",
85 "paletteNext",
86 "palettePrevious",
87 ...THREAD_JUMP_KEYBINDING_COMMANDS,
88 ];
89 const ROW_HEIGHT = 50;
90 // The "In messages" label above the first message match; server results always come last.
91 const SECTION_LABEL_HEIGHT = 26;
92
93 const ACTION_ICONS: Record<string, AppSymbolName> = {
94 newTask: "square.and.pencil",
95 newThread: "square.and.pencil",
96 addProject: "folder.badge.plus",
97 settings: "gearshape",
98 appearance: "paintbrush",
99 environments: "desktopcomputer",
100 usage: "chart.bar.xaxis",
101 archive: "archivebox",
102 files: "doc.text",
103 terminal: "terminal",
104 review: PullRequestGlyph.pullRequest,
105 copyThreadReference: "link",
106 };
107
108 function itemIcon(item: CommandPaletteItem): AppSymbolName {
109 if (item.kind === "thread") return "text.bubble";
110 return ACTION_ICONS[item.key] ?? "ellipsis";
111 }
112
113 function PaletteRow(props: {
114 readonly item: CommandPaletteResult;
115 readonly index: number;
116 readonly selected: boolean;
117 readonly searchMatch?: EnvironmentThreadSearchMatch;
118 readonly searchQuery: string;
119 readonly onSelect: () => void;
120 }) {
121 const foregroundClassName = props.selected
122 ? "text-thread-selected-foreground"
123 : "text-foreground";
124 const mutedForegroundClassName = props.selected
125 ? "text-thread-selected-foreground-muted"
126 : "text-foreground-muted";
127 const m = useMessages();
128 return (
129 <RowPressable
130 accessibilityRole="button"
131 interactionOpacity={props.selected ? 0 : 1}
132 accessibilityState={{ selected: props.selected }}
133 onPress={props.onSelect}
134 className={
135 props.selected
136 ? "mx-2 flex-row items-center gap-3 rounded-xl bg-thread-selected px-3"
137 : "mx-2 flex-row items-center gap-3 rounded-xl px-3"
138 }
139 style={{ height: ROW_HEIGHT }}
140 >
141 <View className="w-7 items-center">
142 {props.item.project ? (
143 <ProjectFavicon
144 environmentId={props.item.project.environmentId}
145 faviconPath={props.item.project.faviconPath}
146 projectIcon={props.item.project.projectIcon}
147 projectTitle={props.item.project.title}
148 size={20}
149 workspaceRoot={props.item.project.workspaceRoot}
150 />
151 ) : (
152 <SymbolView
153 name={itemIcon(props.item)}
154 size={20}
155 tintColorClassName={
156 props.selected ? "accent-thread-selected-foreground" : "accent-icon"
157 }
158 />
159 )}
160 </View>
161 <View className="flex-1">
162 <View className="flex-row items-baseline gap-2">
163 <Text numberOfLines={1} className={cn("shrink text-base", foregroundClassName)}>
164 {props.item.titleRanges?.length
165 ? splitSearchText(props.item.title, props.item.titleRanges).map((part) => (
166 <Text
167 key={part.start}
168 className={cn("text-base", part.highlighted && "font-t3-bold")}
169 >
170 {part.text}
171 </Text>
172 ))
173 : props.item.title}
174 </Text>
175 {/* The second line shows the snippet or hint, so keep where the thread
176 lives, unless the hint already names it. */}
177 {(props.searchMatch ||
178 (props.item.matchHint &&
179 props.item.matchHint.field !== "project" &&
180 props.item.matchHint.field !== "environment")) &&
181 props.item.detail ? (
182 <Text
183 numberOfLines={1}
184 className={cn("max-w-[45%] shrink-0 text-sm", mutedForegroundClassName)}
185 >
186 {props.item.detail}
187 </Text>
188 ) : null}
189 </View>
190 {props.searchMatch ? (
191 <ThreadSearchMatchExcerpt
192 match={props.searchMatch}
193 query={props.searchQuery}
194 selected={props.selected}
195 compact
196 />
197 ) : props.item.matchHint ? (
198 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
199 {searchMatchHintLabel(props.item.matchHint.field, m)}:{" "}
200 {splitSearchText(props.item.matchHint.text, props.item.matchHint.ranges).map((part) => (
201 <Text key={part.start} className={cn("text-sm", part.highlighted && "font-t3-bold")}>
202 {part.text}
203 </Text>
204 ))}
205 </Text>
206 ) : props.item.detail ? (
207 <Text numberOfLines={1} className={cn("text-sm", mutedForegroundClassName)}>
208 {props.item.detail}
209 </Text>
210 ) : null}
211 </View>
212 {props.index < 9 ? (
213 <NativeText
214 className={cn("w-8 shrink-0 text-right text-sm tabular-nums", mutedForegroundClassName)}
215 >
216 ⌘{props.index + 1}
217 </NativeText>
218 ) : null}
219 </RowPressable>
220 );
221 }
222
223 /** Mounted only while open, so the app root does not subscribe to the full thread catalog. */
224 export function CommandPalette(props: {
225 readonly pathname: string;
226 readonly onClose: () => void;
227 readonly onCommand: (command: HardwareKeyboardCommand) => void;
228 }) {
229 const navigation = useNavigation();
230 const gt = useGT();
231 const selectTab = useSelectWorkspaceTab();
232 const { themeVariables } = useAppearancePreferences();
233 const selectDetail = useSelectWorkspaceDetail();
234 const runCommand = props.onCommand;
235 const projects = useProjects();
236 const threads = useVisibleThreadShells();
237 const delegatedUnderParent = useDelegatedUnderParent();
238 const activeThreadRef = parseActiveThreadPath(props.pathname);
239 const activeThread = useThreadShell(activeThreadRef);
240 const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
241 const environments = useWorkspaceEnvironments();
242 const { savedConnectionsById } = useSavedRemoteConnections();
243 const [query, setQuery] = useState("");
244 // Ranking is relative to when the palette opened, so rows do not reorder as time passes.
245 const [now] = useState(() => Date.now());
246 const [selection, setSelection] = useState<string | null>(null);
247 const [visible, setVisible] = useState(true);
248 const pendingAction = useRef<(() => void) | null>(null);
249 const closing = useRef(false);
250 const inputRef = useRef<TextInputInstance>(null);
251 const listRef = useRef<LegendListRef>(null);
252 const { width, height } = useWindowDimensions();
253 // The palette floats above every column, so it keeps itself inside the window's side insets
254 // and to one side of a book fold.
255 const bounds = deriveBottomControlInsets(useNativeLayoutMetrics());
256 const searchEnvironmentIds = useMemo(
257 () =>
258 environments
259 .filter((environment) => environment.connectionState === "connected")
260 .map((environment) => environment.environmentId),
261 [environments],
262 );
263 // The palette matches environment names when there are several; older rows must match the same.
264 const environmentLabels =
265 environments.length > 1
266 ? Object.fromEntries(
267 searchEnvironmentIds.flatMap((environmentId) => {
268 const label = savedConnectionsById[environmentId]?.environmentLabel;
269 return label === undefined ? [] : [[environmentId, label]];
270 }),
271 )
272 : undefined;
273 const search = useThreadSearch(
274 searchEnvironmentIds,
275 query.startsWith(">") ? "" : query,
276 environmentLabels === undefined ? {} : { environmentLabels },
277 );
278 const serverConfigs = useServerConfigs();
279 const startTriage = useStartTriage();
280 const newTaskFlow = useNewTaskFlow();
281 const draftEnvironmentId =
282 useActiveNewTask() === null ? null : (newTaskFlow.selectedProject?.environmentId ?? null);
283 const triageEnvironmentId = pickTriageEnvironment({
284 // The route names the machine even before the thread shell loads.
285 onScreen: activeThreadRef?.environmentId ?? draftEnvironmentId,
286 connected: searchEnvironmentIds,
287 supportsTriage: (environmentId) =>
288 serverConfigs.get(environmentId)?.environment.capabilities.triage === true,
289 });
290 const canTriage =
291 useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) &&
292 triageEnvironmentId !== null &&
293 serverConfigs.get(triageEnvironmentId)?.environment.capabilities.triage === true;
294 const canShareWithGuest = useCanShareWithGuest(activeThreadRef?.environmentId ?? null);
295 const contentMatchByKey = new Map(
296 search.matches
297 .filter((match) => match.source === "user" || match.source === "assistant")
298 .map((match) => [scopedThreadKey(match.environmentId, match.threadId), match]),
299 );
300 const items = useMemo(() => {
301 const actions: CommandPaletteItem[] = [
302 {
303 key: "newTask",
304 kind: "action",
305 title: gt("New thread in…"),
306 searchTerms: ["new task", "chat", "create", "project"],
307 run: () => runCommand("newTask"),
308 },
309 {
310 key: "addProject",
311 kind: "action",
312 title: gt("Add project"),
313 searchTerms: ["folder", "clone", "repository", "git"],
314 run: () => navigation.navigate("AddProject"),
315 },
316 {
317 key: "settings",
318 kind: "action",
319 title: gt("Open settings"),
320 searchTerms: ["preferences", "configuration"],
321 run: () => selectTab("settings"),
322 },
323 {
324 key: "appearance",
325 kind: "action",
326 title: gt("Appearance"),
327 searchTerms: ["theme", "colors", "dark", "light"],
328 run: () => openSettings(navigation, "SettingsAppearance"),
329 },
330 {
331 key: "environments",
332 kind: "action",
333 title: gt("Manage environments"),
334 searchTerms: ["connections", "server", "remote"],
335 run: () => openSettings(navigation, "SettingsEnvironments"),
336 },
337 {
338 key: "scheduledTasks",
339 kind: "action",
340 title: gt("Scheduled tasks"),
341 searchTerms: ["schedule", "automations", "recurring"],
342 run: () => openSettings(navigation, "SettingsScheduledTasks"),
343 },
344 {
345 key: "usage",
346 kind: "action",
347 title: gt("Usage", { $context: "command, opens usage settings" }),
348 searchTerms: ["limits", "accounts", "quota"],
349 run: () => openSettings(navigation, "SettingsUsage"),
350 },
351 {
352 key: "archive",
353 kind: "action",
354 title: gt("Archived threads"),
355 searchTerms: ["restore", "history"],
356 run: () => openSettings(navigation, "SettingsArchive"),
357 },
358 ];
359 if (canTriage) {
360 const triageEnvironmentLabel = savedConnectionsById[triageEnvironmentId]?.environmentLabel;
361 actions.push({
362 key: "triage",
363 kind: "action",
364 title: gt("Triage an issue"),
365 // Mobile has no triage hero, so name the machine before it starts.
366 detail:
367 triageEnvironmentLabel !== undefined
368 ? gt("On {environment}", { environment: triageEnvironmentLabel })
369 : gt("On this machine"),
370 searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"],
371 run: () => void startTriage(triageEnvironmentId),
372 });
373 }
374 const projectByKey = new Map(
375 projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
376 );
377 const activeProject = activeThread
378 ? projectByKey.get(scopedProjectKey(activeThread.environmentId, activeThread.projectId))
379 : null;
380 if (activeProject) {
381 actions.unshift({
382 key: "newThread",
383 kind: "action",
384 title: gt("New thread in {project}", { project: activeProject.title }),
385 searchTerms: ["new task", "chat", "create"],
386 run: () =>
387 selectDetail({
388 name: "Thread",
389 params: {
390 draft: {
391 requestId: uuidv4(),
392 environmentId: activeProject.environmentId,
393 projectId: activeProject.id,
394 title: activeProject.title,
395 },
396 },
397 }),
398 });
399 }
400 if (activeThreadRef) {
401 const threadActions = [
402 ["files", gt("Go to file"), ["open", "files", "browse", "search"]],
403 ["terminal", gt("Open terminal"), ["shell", "console"]],
404 ["review", gt("Review changes"), ["diff", "git", "pull request"]],
405 ["copyThreadReference", gt("Copy PR link or thread"), ["reference", "clipboard"]],
406 ] as const;
407 actions.push(
408 ...threadActions.map(([command, title, searchTerms]) => ({
409 key: command,
410 kind: "action" as const,
411 title,
412 searchTerms,
413 run: () => runCommand(command),
414 })),
415 );
416 if (canShareWithGuest) {
417 actions.push({
418 key: "shareWithGuest",
419 kind: "action",
420 title: gt("Share with guest"),
421 searchTerms: ["share", "guest", "invite", "link", "teammate"],
422 run: () => navigation.navigate("ThreadGuestShare", activeThreadRef),
423 });
424 }
425 }
426 const openProjects = projects.filter((project) => project.archivedAt == null);
427 const projectItems: CommandPaletteItem[] = [
428 ...openProjects.filter((project) => project.pinnedAt != null),
429 ...openProjects.filter((project) => project.pinnedAt == null),
430 ].map((project) => ({
431 key: `project:${scopedProjectKey(project.environmentId, project.id)}`,
432 kind: "project",
433 project,
434 title: project.title,
435 detail: gt("New thread · {environment}", {
436 environment:
437 savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId,
438 }),
439 searchTerms: [project.workspaceRoot, "new thread", "project"],
440 run: () =>
441 selectDetail({
442 name: "Thread",
443 params: {
444 draft: {
445 requestId: uuidv4(),
446 environmentId: project.environmentId,
447 projectId: project.id,
448 title: project.title,
449 },
450 },
451 }),
452 }));
453 const threadItems: CommandPaletteItem[] = threads
454 .filter(
455 (thread) =>
456 thread.archivedAt === null &&
457 !isShownUnderParent(
458 { environmentId: thread.environmentId, threadId: thread.id },
459 thread.lineage,
460 delegatedUnderParent,
461 ),
462 )
463 .map((thread) => {
464 const project = projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId));
465 const environment =
466 savedConnectionsById[thread.environmentId]?.environmentLabel ?? thread.environmentId;
467 return {
468 key: scopedThreadKey(thread.environmentId, thread.id),
469 kind: "thread",
470 title: thread.title || gt("Untitled thread"),
471 detail: [project?.title, environment].filter(Boolean).join(" · "),
472 searchTerms: [],
473 threadSearch: threadSearchSubject(
474 thread,
475 project?.title,
476 environments.length > 1 ? environment : null,
477 ),
478 // Last among threads: picking the thread already open does nothing.
479 ...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id
480 ? { secondary: true }
481 : {}),
482 run: () =>
483 selectDetail({
484 name: "Thread",
485 params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },
486 }),
487 };
488 });
489 // Recent means used recently: written in or opened, whichever is later.
490 threadItems.sort(
491 (left, right) =>
492 (right.threadSearch ? threadRecentUse(right.threadSearch) : 0) -
493 (left.threadSearch ? threadRecentUse(left.threadSearch) : 0),
494 );
495 return [...actions, ...projectItems, ...threadItems];
496 }, [
497 selectTab,
498 activeThread,
499 activeThreadRef,
500 environments.length,
501 canTriage,
502 canShareWithGuest,
503 navigation,
504 projects,
505 runCommand,
506 savedConnectionsById,
507 selectDetail,
508 startTriage,
509 threads,
510 delegatedUnderParent,
511 triageEnvironmentId,
512 gt,
513 ]);
514 const rankedMessageKeys = useMemo(() => {
515 const subjectByKey = new Map(
516 items.flatMap((item) => (item.threadSearch ? [[item.key, item.threadSearch] as const] : [])),
517 );
518 const keyOf = (match: EnvironmentThreadSearchMatch) =>
519 scopedThreadKey(match.environmentId, match.threadId);
520 return rankMessageMatches(
521 search.matches,
522 (match) => subjectByKey.get(keyOf(match)),
523 foldSearchQuery(query),
524 now,
525 { withoutTitleMatches: true },
526 ).map(keyOf);
527 }, [items, now, query, search.matches]);
528 // Rows already shown keep their places when a slower environment answers.
529 const [shownOrder, setShownOrder] = useState<ShownOrder | null>(null);
530 const messageOrder = nextShownOrder(
531 shownOrder,
532 search.query,
533 rankedMessageKeys,
534 PALETTE_MESSAGE_LIMIT,
535 );
536 if (messageOrder !== shownOrder) setShownOrder(messageOrder);
537 const messageMatchKeys = useMemo(
538 () => messageOrder.keys.slice(0, messageOrder.shown),
539 [messageOrder.keys, messageOrder.shown],
540 );
541 const results = useMemo(() => {
542 const ranked = filterCommandPaletteItems(items, query, messageMatchKeys, now);
543 // Recent threads leave out the open one, which would always lead them.
544 const activeKey = activeThread
545 ? scopedThreadKey(activeThread.environmentId, activeThread.id)
546 : null;
547 return query.trim() ? ranked : ranked.filter((item) => item.key !== activeKey);
548 }, [activeThread, items, messageMatchKeys, now, query]);
549 const runResult = (item: CommandPaletteResult) => {
550 const thread =
551 item.kind === "thread" && query.trim() && !query.startsWith(">")
552 ? threads.find(
553 (candidate) => scopedThreadKey(candidate.environmentId, candidate.id) === item.key,
554 )
555 : undefined;
556 // A message result opens the thread at that message.
557 const messageId = item.fromMessages ? contentMatchByKey.get(item.key)?.messageId : undefined;
558 if (messageId) requestThreadMessageJump(item.key, messageId);
559 // A pick sends its open with the query, always, so the server records it;
560 // the thread screen then skips its own open. The open thread is no pick.
561 if (thread && !item.secondary) claimThreadOpen(thread.environmentId, thread.id, Date.now());
562 if (thread && thread.lastVisitedAt !== undefined && !item.secondary) {
563 void visitThread({
564 environmentId: thread.environmentId,
565 input: {
566 threadId: thread.id,
567 visitedAt: thread.updatedAt,
568 opened: true,
569 searchQuery: pickedQuery(query),
570 },
571 });
572 }
573 item.run();
574 };
575 const firstMessageIndex = results.findIndex((item) => item.fromMessages);
576 const selectedIndex = Math.max(
577 0,
578 results.findIndex((item) => item.key === selection),
579 );
580 const selectedKey = results[selectedIndex]?.key;
581 // The native list follows the highlighted row. Key presses move it, but so do
582 // live thread updates and late message matches that reorder or drop the
583 // selected row under a kept selection, so no single handler owns the scroll.
584 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the native list to the highlighted row, which key presses and live result updates both move
585 useEffect(() => {
586 if (selectedIndex === 0) {
587 // Centering before the list measures its height scrolls half the first row out of view.
588 listRef.current?.scrollToOffset({ offset: 0, animated: false });
589 } else if (selectedKey !== undefined) {
590 listRef.current?.scrollToIndex({ index: selectedIndex, animated: false, viewPosition: 0.5 });
591 }
592 }, [selectedIndex, selectedKey]);
593
594 const dismissed = useRef(false);
595 const dismissFallback = useRef<ReturnType<typeof setTimeout> | null>(null);
596 const handleDismissed = () => {
597 if (dismissFallback.current !== null) clearTimeout(dismissFallback.current);
598 dismissFallback.current = null;
599 if (dismissed.current) return;
600 dismissed.current = true;
601 // Present navigation sheets only after UIKit has dismissed this modal.
602 props.onClose();
603 pendingAction.current?.();
604 };
605 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the dismiss fallback timer on unmount
606 useEffect(
607 () => () => {
608 if (dismissFallback.current !== null) clearTimeout(dismissFallback.current);
609 },
610 [],
611 );
612
613 function close(run?: () => void) {
614 if (closing.current) return;
615 closing.current = true;
616 pendingAction.current = run ?? null;
617 setVisible(false);
618 // iOS may drop onDismiss during presentation or competing sheets; a fallback clears stale palette state.
619 dismissFallback.current = setTimeout(handleDismissed, 400);
620 }
621
622 function onCommand(command: HardwareKeyboardCommand) {
623 if (command === "commandPalette" || command === "paletteDismiss") {
624 close();
625 } else if (command === "paletteNext" || command === "palettePrevious") {
626 setSelection(
627 results[nextPaletteIndex(selectedIndex, command === "paletteNext" ? 1 : -1, results.length)]
628 ?.key ?? null,
629 );
630 } else {
631 const item = results[threadJumpIndex(command)];
632 if (item) close(() => runResult(item));
633 }
634 }
635
636 return (
637 <Modal
638 visible={visible}
639 transparent
640 animationType="fade"
641 onShow={() => inputRef.current?.focus()}
642 onRequestClose={() => close()}
643 onDismiss={handleDismissed}
644 >
645 <GestureHandlerRootView className="flex-1">
646 <T3KeyboardCommands enabledCommands={PALETTE_COMMANDS} onCommand={onCommand}>
647 <KeyboardAvoidingView
648 behavior="padding"
649 className="flex-1 items-center justify-center py-4"
650 style={{ paddingLeft: 16 + bounds.left, paddingRight: 16 + bounds.right }}
651 >
652 <Pressable
653 className="absolute inset-0 bg-backdrop"
654 accessibilityLabel={gt("Close command palette")}
655 onPress={() => close()}
656 />
657 <GlassSurface
658 accessibilityViewIsModal
659 className="bg-sheet"
660 tintColorClassName="accent-sheet/20"
661 fallbackColor={themeVariables["--color-sheet"]}
662 style={{
663 width: Math.min(600, width - 32 - bounds.left - bounds.right),
664 height: Math.min(520, height - 80),
665 borderRadius: 20,
666 }}
667 >
668 <View className="px-3 pb-2.5 pt-3.5">
669 <View className="h-[38px] flex-row items-center gap-1.5 pr-2.5 pl-[11px]">
670 <SymbolView
671 name="magnifyingglass"
672 size={15}
673 tintColorClassName="accent-foreground-muted"
674 type="monochrome"
675 />
676 <TextInput
677 ref={inputRef}
678 accessibilityLabel={gt("Search commands, projects, and threads")}
679 placeholder={gt("Search commands, projects, and threads…")}
680 placeholderTextColorClassName="accent-placeholder"
681 autoCorrect={false}
682 autoCapitalize="none"
683 clearButtonMode="while-editing"
684 className="h-[34px] flex-1 px-0 py-0 font-sans text-base text-foreground"
685 value={query}
686 onChangeText={(value) => {
687 setQuery(value);
688 setSelection(null);
689 // The follow effect stays idle when the top row and its key are unchanged,
690 // so a touch-scrolled list would otherwise keep its old offset.
691 listRef.current?.scrollToOffset({ offset: 0, animated: false });
692 }}
693 returnKeyType="go"
694 submitBehavior="submit"
695 onSubmitEditing={() => {
696 const item = results[selectedIndex];
697 if (item) close(() => runResult(item));
698 }}
699 />
700 </View>
701 </View>
702 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- The palette is a modal with no navigation header to register with. */}
703 <LegendList
704 ref={listRef}
705 data={results}
706 extraData={{
707 selectedKey,
708 firstMessageIndex,
709 contentMatchByKey,
710 query: search.query,
711 }}
712 keyboardShouldPersistTaps="handled"
713 keyExtractor={(item) => item.key}
714 getFixedItemSize={(_, index) =>
715 ROW_HEIGHT + (index === firstMessageIndex ? SECTION_LABEL_HEIGHT : 0)
716 }
717 recycleItems
718 contentContainerStyle={{ paddingBottom: 8 }}
719 ListEmptyComponent={
720 <Text className="p-5 text-center text-foreground-muted">
721 {search.isPending
722 ? gt("Searching…")
723 : search.failed
724 ? gt("Couldn't search messages")
725 : gt("No results")}
726 </Text>
727 }
728 // Message results from slower environments may still arrive below.
729 ListFooterComponent={
730 results.length > 0 && search.isPending && !query.startsWith(">") ? (
731 <Text className="px-5 pt-2 text-xs text-foreground-muted">
732 <T>Searching messages…</T>
733 </Text>
734 ) : undefined
735 }
736 renderItem={({ item, index }) => (
737 <>
738 {index === firstMessageIndex ? (
739 <Text
740 className="px-5 pt-2 text-xs text-foreground-muted"
741 style={{ height: SECTION_LABEL_HEIGHT }}
742 >
743 <T>In messages</T>
744 </Text>
745 ) : null}
746 <PaletteRow
747 item={item}
748 index={index}
749 selected={item.key === selectedKey}
750 searchMatch={item.fromMessages ? contentMatchByKey.get(item.key) : undefined}
751 searchQuery={search.query}
752 onSelect={() => close(() => runResult(item))}
753 />
754 </>
755 )}
756 />
757 </GlassSurface>
758 </KeyboardAvoidingView>
759 </T3KeyboardCommands>
760 </GestureHandlerRootView>
761 </Modal>
762 );
763 }