Open History to see the last commit
1import { StackActions, useNavigation } from "@react-navigation/native";
2import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
3import {
4 useCallback,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 useSyncExternalStore,
10 type PropsWithChildren,
11} from "react";
12
13import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
14import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
15import { useProject, useThreadShell } from "../../state/entities";
16import { useEnvironmentQuery } from "../../state/query";
17import type { GitActionProgress } from "../../state/use-vcs-action-state";
18import { vcsEnvironment } from "../../state/vcs";
19import { GitActionProgressOverlay } from "../threads/GitActionProgressOverlay";
20import {
21 dispatchHardwareKeyboardCommand,
22 getHardwareKeyboardCommandRegistrationVersion,
23 getRegisteredHardwareKeyboardCommands,
24 parseActiveThreadPath,
25 subscribeToHardwareKeyboardCommandRegistrations,
26 type HardwareKeyboardCommand,
27} from "./hardwareKeyboardCommands";
28
29const EMPTY_COPY_FEEDBACK: GitActionProgress = {
30 phase: "idle",
31 label: null,
32 description: null,
33};
34const COPY_FEEDBACK_DISMISS_MS = 3_000;
35
36export function HardwareKeyboardCommandProvider({
37 children,
38 pathname,
39}: PropsWithChildren<{ readonly pathname: string }>) {
40 const navigation = useNavigation();
41 const activeThreadRef = useMemo(() => parseActiveThreadPath(pathname), [pathname]);
42 const activeThread = useThreadShell(activeThreadRef);
43 const activeProjectRef = useMemo(
44 () =>
45 activeThread === null
46 ? null
47 : {
48 environmentId: activeThread.environmentId,
49 projectId: activeThread.projectId,
50 },
51 [activeThread],
52 );
53 const activeProject = useProject(activeProjectRef);
54 const activeThreadCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot ?? null;
55 const gitStatus = useEnvironmentQuery(
56 activeThread !== null &&
57 activeThread.linkedPullRequest == null &&
58 activeThread.branch !== null &&
59 activeThreadCwd !== null
60 ? vcsEnvironment.status({
61 environmentId: activeThread.environmentId,
62 input: { cwd: activeThreadCwd },
63 })
64 : null,
65 ).data;
66 const detectedPullRequestUrl =
67 activeThread?.branch != null && gitStatus?.refName === activeThread.branch
68 ? (gitStatus.pr?.url ?? null)
69 : null;
70 const copyTarget = useMemo(
71 () =>
72 activeThreadRef === null
73 ? null
74 : resolveThreadReferenceCopyTarget({
75 threadId: activeThread?.id ?? activeThreadRef.threadId,
76 linkedPullRequestUrl: activeThread?.linkedPullRequest?.url ?? null,
77 detectedPullRequestUrl,
78 }),
79 [activeThread, activeThreadRef, detectedPullRequestUrl],
80 );
81 const [copyFeedback, setCopyFeedback] = useState<GitActionProgress>(EMPTY_COPY_FEEDBACK);
82 const copyRequestIdRef = useRef(0);
83 const copyFeedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
84 const dismissCopyFeedback = useCallback(() => {
85 if (copyFeedbackTimerRef.current !== null) {
86 clearTimeout(copyFeedbackTimerRef.current);
87 copyFeedbackTimerRef.current = null;
88 }
89 setCopyFeedback(EMPTY_COPY_FEEDBACK);
90 }, []);
91 const showCopyFeedback = useCallback((feedback: GitActionProgress) => {
92 if (copyFeedbackTimerRef.current !== null) {
93 clearTimeout(copyFeedbackTimerRef.current);
94 }
95 setCopyFeedback(feedback);
96 copyFeedbackTimerRef.current = setTimeout(() => {
97 copyFeedbackTimerRef.current = null;
98 setCopyFeedback(EMPTY_COPY_FEEDBACK);
99 }, COPY_FEEDBACK_DISMISS_MS);
100 }, []);
101 useEffect(
102 () => () => {
103 if (copyFeedbackTimerRef.current !== null) {
104 clearTimeout(copyFeedbackTimerRef.current);
105 }
106 },
107 [],
108 );
109 const registrationVersion = useSyncExternalStore(
110 subscribeToHardwareKeyboardCommandRegistrations,
111 getHardwareKeyboardCommandRegistrationVersion,
112 getHardwareKeyboardCommandRegistrationVersion,
113 );
114 const enabledCommands = useMemo(() => {
115 const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
116 commands.add("newTask");
117 if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
118 if (activeThreadRef !== null) {
119 commands.add("files");
120 commands.add("terminal");
121 commands.add("review");
122 if (pathname.split("/")[4] !== "terminal") commands.add("copyThreadReference");
123 }
124 return [...commands];
125 }, [pathname, registrationVersion, navigation]);
126
127 const onCommand = useCallback(
128 (command: HardwareKeyboardCommand) => {
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("NewTaskSheet", { screen: "NewTask" });
157 return;
158 }
159 if (command === "back") {
160 if (navigation.canGoBack()) {
161 navigation.goBack();
162 } else {
163 navigation.dispatch(StackActions.replace("Home"));
164 }
165 return;
166 }
167
168 const thread = parseActiveThreadPath(pathname);
169 if (!thread) return;
170 if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
171 navigation.navigate("ThreadFiles", thread);
172 }
173 if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
174 navigation.navigate("ThreadTerminal", thread);
175 }
176 if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
177 navigation.navigate("ThreadReview", thread);
178 }
179 },
180 [copyTarget, navigation, pathname, showCopyFeedback],
181 );
182
183 return (
184 <>
185 <T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
186 {children}
187 </T3KeyboardCommands>
188 <GitActionProgressOverlay progress={copyFeedback} onDismiss={dismissCopyFeedback} />
189 </>
190 );
191}