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

CommandPalette.tsx

721 lines27.7 KB

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