Open History to see the last commit
1import { StackActions, useNavigation } from "@react-navigation/native";
2import { useCallback, useMemo, useSyncExternalStore, type PropsWithChildren } from "react";
3
4import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
5import {
6 dispatchHardwareKeyboardCommand,
7 getHardwareKeyboardCommandRegistrationVersion,
8 getRegisteredHardwareKeyboardCommands,
9 parseActiveThreadPath,
10 subscribeToHardwareKeyboardCommandRegistrations,
11 type HardwareKeyboardCommand,
12} from "./hardwareKeyboardCommands";
13
14export function HardwareKeyboardCommandProvider({
15 children,
16 pathname,
17}: PropsWithChildren<{ readonly pathname: string }>) {
18 const navigation = useNavigation();
19 const registrationVersion = useSyncExternalStore(
20 subscribeToHardwareKeyboardCommandRegistrations,
21 getHardwareKeyboardCommandRegistrationVersion,
22 getHardwareKeyboardCommandRegistrationVersion,
23 );
24 const enabledCommands = useMemo(() => {
25 const commands = new Set<HardwareKeyboardCommand>(getRegisteredHardwareKeyboardCommands());
26 commands.add("newTask");
27 if (pathname !== "/" || navigation.canGoBack()) commands.add("back");
28 if (parseActiveThreadPath(pathname)) {
29 commands.add("files");
30 commands.add("terminal");
31 commands.add("review");
32 }
33 return [...commands];
34 }, [pathname, registrationVersion, navigation]);
35
36 const onCommand = useCallback(
37 (command: HardwareKeyboardCommand) => {
38 if (dispatchHardwareKeyboardCommand(command)) return;
39
40 if (command === "newTask") {
41 navigation.navigate("NewTaskSheet", { screen: "NewTask" });
42 return;
43 }
44 if (command === "back") {
45 if (navigation.canGoBack()) {
46 navigation.goBack();
47 } else {
48 navigation.dispatch(StackActions.replace("Home"));
49 }
50 return;
51 }
52
53 const thread = parseActiveThreadPath(pathname);
54 if (!thread) return;
55 if (command === "files" && !/\/files(?:\/|$)/.test(pathname)) {
56 navigation.navigate("ThreadFiles", thread);
57 }
58 if (command === "terminal" && !/\/terminal(?:\/|$)/.test(pathname)) {
59 navigation.navigate("ThreadTerminal", thread);
60 }
61 if (command === "review" && !/\/review(?:\/|$)/.test(pathname)) {
62 navigation.navigate("ThreadReview", thread);
63 }
64 },
65 [pathname, navigation],
66 );
67
68 return (
69 <T3KeyboardCommands enabledCommands={enabledCommands} onCommand={onCommand}>
70 {children}
71 </T3KeyboardCommands>
72 );
73}