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