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