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