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

main
tsx 210 lines 7.45 KB
Raw
1 import { StackActions, useNavigation } from "@react-navigation/native";
2 import { msg, useMessages } from "gt-react-native";
3 import { Platform } from "react-native";
4 import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
5 import {
6 createContext,
7 use,
8 useCallback,
9 useEffect,
10 useMemo,
11 useRef,
12 useState,
13 useSyncExternalStore,
14 type PropsWithChildren,
15 type ReactNode,
16 } from "react";
17
18 import { copyThreadReference } from "../../lib/copyThreadReference";
19 import { m } from "../../i18n/messages";
20 import {
21 firstWorkspaceDetailOpen,
22 workspaceHasColumns,
23 } from "../layout/workspace/workspace-selection-store";
24 import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
25 import { useThreadShell } from "../../state/entities";
26 import type { GitActionProgress } from "../../state/use-vcs-action-state";
27 import { GitActionProgressOverlay } from "../threads/GitActionProgressOverlay";
28 import { CommandPalette } from "./CommandPalette";
29 import {
30 dispatchHardwareKeyboardCommand,
31 getHardwareKeyboardCommandRegistrationVersion,
32 getRegisteredHardwareKeyboardCommands,
33 parseActiveThreadPath,
34 subscribeToHardwareKeyboardCommandRegistrations,
35 type HardwareKeyboardCommand,
36 } from "./hardwareKeyboardCommands";
37 import { selectWorkspaceDetail } from "../layout/workspace/workspace-detail-selection";
38
39 const EMPTY_COPY_FEEDBACK: GitActionProgress = {
40 phase: "idle",
41 label: null,
42 description: null,
43 };
44 const COPY_FEEDBACK_DISMISS_MS = 3_000;
45
46 const CommandPaletteContext = createContext<ReactNode>(null);
47
48 /** Render inside the workspace so palette actions share its navigation and pane state. */
49 export function HardwareKeyboardCommandOverlay() {
50 return use(CommandPaletteContext);
51 }
52
53 export function HardwareKeyboardCommandProvider({
54 children,
55 pathname,
56 }: PropsWithChildren<{ readonly pathname: string }>) {
57 const navigation = useNavigation();
58 const messages = useMessages();
59 const [paletteOpen, setPaletteOpen] = useState(false);
60 const closePalette = useCallback(() => setPaletteOpen(false), []);
61 const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
62 const activeThread = useThreadShell(activeThreadRef);
63 const copyTarget = useMemo(
64 () =>
65 activeThreadRef === null
66 ? null
67 : resolveThreadReferenceCopyTarget(
68 {
69 threadRef: activeThreadRef,
70 title: activeThread?.title ?? "",
71 pullRequests: activeThread?.pullRequests,
72 linkedPullRequestUrl:
73 (activeThread?.linkedPullRequest ?? activeThread?.branchPullRequest)?.url ?? null,
74 },
75 messages,
76 ),
77 [activeThread, activeThreadRef, messages],
78 );
79 const [copyFeedback, setCopyFeedback] = useState<GitActionProgress>(EMPTY_COPY_FEEDBACK);
80 const copyRequestIdRef = useRef(0);
81 const copyFeedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
82 const dismissCopyFeedback = useCallback(() => {
83 if (copyFeedbackTimerRef.current !== null) {
84 clearTimeout(copyFeedbackTimerRef.current);
85 copyFeedbackTimerRef.current = null;
86 }
87 setCopyFeedback(EMPTY_COPY_FEEDBACK);
88 }, []);
89 const showCopyFeedback = useCallback((feedback: GitActionProgress) => {
90 if (copyFeedbackTimerRef.current !== null) {
91 clearTimeout(copyFeedbackTimerRef.current);
92 }
93 setCopyFeedback(feedback);
94 copyFeedbackTimerRef.current = setTimeout(() => {
95 copyFeedbackTimerRef.current = null;
96 setCopyFeedback(EMPTY_COPY_FEEDBACK);
97 }, COPY_FEEDBACK_DISMISS_MS);
98 }, []);
99 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the copy feedback timer on unmount
100 useEffect(
101 () => () => {
102 if (copyFeedbackTimerRef.current !== null) {
103 clearTimeout(copyFeedbackTimerRef.current);
104 }
105 },
106 [],
107 );
108 const registrationVersion = useSyncExternalStore(
109 subscribeToHardwareKeyboardCommandRegistrations,
110 getHardwareKeyboardCommandRegistrationVersion,
111 getHardwareKeyboardCommandRegistrationVersion,
112 );
113 const enabledCommands = useMemo(() => {
114 const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
115 commands.add("newTask");
116 commands.add("commandPalette");
117 if (pathname !== "/" && !pathname.startsWith("/threads/")) {
118 for (const command of commands) {
119 if (command.startsWith("thread.jump.")) commands.delete(command);
120 }
121 }
122 if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
123 if (activeThreadRef !== null) {
124 commands.add("files");
125 commands.add("terminal");
126 commands.add("review");
127 if (pathname.split("/")[4] !== "terminal") commands.add("copyThreadReference");
128 }
129 return [...commands];
130 // oxlint-disable-next-line react/memo-dependencies -- registrationVersion invalidates the snapshot of the external keyboard-command registry.
131 }, [activeThreadRef, pathname, registrationVersion, navigation]);
132
133 const onCommand = useCallback(
134 (command: HardwareKeyboardCommand) => {
135 if (command === "commandPalette") {
136 setPaletteOpen(true);
137 return;
138 }
139 if (dispatchHardwareKeyboardCommand(command)) return;
140
141 if (command === "copyThreadReference") {
142 if (copyTarget === null) return;
143 const requestId = ++copyRequestIdRef.current;
144 void copyThreadReference(copyTarget).then((didCopy) => {
145 if (requestId !== copyRequestIdRef.current) return;
146 showCopyFeedback(
147 didCopy
148 ? {
149 phase: "success",
150 label: copyTarget.successTitle,
151 description: copyTarget.description,
152 }
153 : {
154 phase: "error",
155 label: copyTarget.failureTitle,
156 description: m(msg("Try again.")),
157 },
158 );
159 });
160 return;
161 }
162
163 if (command === "newTask") {
164 navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params: { draft: {} } }));
165 return;
166 }
167 if (command === "back") {
168 // Beside a visible list, the first detail page has nothing to go back to.
169 if (Platform.OS === "ios" && workspaceHasColumns() && firstWorkspaceDetailOpen(navigation))
170 return;
171 if (navigation.canGoBack()) {
172 navigation.goBack();
173 } else {
174 navigation.dispatch(StackActions.replace("Home"));
175 }
176 return;
177 }
178
179 const thread = parseActiveThreadPath(pathname);
180 if (!thread) return;
181 if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
182 navigation.navigate("ThreadFiles", thread);
183 }
184 if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
185 navigation.navigate("ThreadTerminal", thread);
186 }
187 if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
188 navigation.navigate("ThreadReview", thread);
189 }
190 },
191 [copyTarget, navigation, pathname, showCopyFeedback],
192 );
193
194 const palette = useMemo(
195 () =>
196 paletteOpen ? (
197 <CommandPalette pathname={pathname} onClose={closePalette} onCommand={onCommand} />
198 ) : null,
199 [closePalette, onCommand, paletteOpen, pathname],
200 );
201
202 return (
203 <CommandPaletteContext value={palette}>
204 <T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
205 {children}
206 </T3KeyboardCommands>
207 <GitActionProgressOverlay progress={copyFeedback} onDismiss={dismissCopyFeedback} />
208 </CommandPaletteContext>
209 );
210 }