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

main
tsx 162 lines 5.26 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m } from "~/i18n/messages";
3 import {
4 isModifierPairShortcut,
5 type SnapShotModifier,
6 type SnapShotShortcut,
7 } from "@t3tools/contracts";
8 import { parseKeybindingShortcut } from "@t3tools/shared/keybindings";
9 import { useGT } from "gt-react";
10 import { useEffect, useRef, useState, type KeyboardEvent } from "react";
11 import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
12 import {
13 formatSnapShotShortcutLabel,
14 parseDesktopSnapShotShortcut,
15 } from "../../lib/snapShotShortcut";
16 import { SnapShotShortcutKeys } from "../desktop/SnapShotShortcutKeys";
17 import { Button } from "../ui/button";
18 import { keybindingFromKeyboardEvent } from "./KeybindingsSettings.logic";
19 import { createRecordingRequestTracker } from "./SnapShotSettings.logic";
20
21 const MODIFIER_FROM_KEY: Readonly<Record<string, SnapShotModifier>> = {
22 Shift: "shift",
23 Meta: "meta",
24 OS: "meta",
25 Control: "control",
26 Alt: "alt",
27 AltGraph: "alt",
28 };
29 const MODIFIER_CODES: Readonly<Record<SnapShotModifier, readonly [string, string]>> = {
30 shift: ["ShiftLeft", "ShiftRight"],
31 meta: ["MetaLeft", "MetaRight"],
32 control: ["ControlLeft", "ControlRight"],
33 alt: ["AltLeft", "AltRight"],
34 };
35
36 export function useSnapShotShortcutRecorder({
37 shortcut,
38 shortcutLabel,
39 disabled = false,
40 allowModifierPairs = true,
41 onRecord,
42 onStart,
43 onError,
44 }: {
45 shortcut: SnapShotShortcut;
46 shortcutLabel?: string | undefined;
47 disabled?: boolean;
48 allowModifierPairs?: boolean;
49 onRecord: (shortcut: SnapShotShortcut) => void;
50 onStart?: () => void;
51 onError: (message: string) => void;
52 }) {
53 const gt = useGT();
54 const bridge = getDesktopSnapShotBridge();
55 const displayShortcut = shortcutLabel ? parseDesktopSnapShotShortcut(shortcutLabel) : shortcut;
56 const [recording, setRecording] = useState(false);
57 const [requests] = useState(createRecordingRequestTracker);
58 const heldModifierCodes = useRef(new Set<string>());
59 const stopRecording = () => {
60 requests.clear();
61 heldModifierCodes.current.clear();
62 setRecording(false);
63 void bridge?.setSnapShotShortcutSuppressed(false).catch(() => undefined);
64 };
65 const startRecording = async () => {
66 if (!bridge || disabled) return;
67 const request = requests.tryBegin();
68 if (!request) return;
69 heldModifierCodes.current.clear();
70 onStart?.();
71 try {
72 await bridge.setSnapShotShortcutSuppressed(true);
73 if (requests.owns(request)) setRecording(true);
74 } catch (error) {
75 if (!requests.owns(request)) return;
76 requests.clear();
77 onError(
78 error instanceof Error
79 ? (thrownErrorMessage(error, m) ?? error.message)
80 : gt("Could not start shortcut recording."),
81 );
82 }
83 };
84 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the desktop bridge's SnapShot shortcut suppression on unmount
85 useEffect(
86 () => () => {
87 requests.clear();
88 void bridge?.setSnapShotShortcutSuppressed(false).catch(() => undefined);
89 },
90 [bridge, requests],
91 );
92 const recordShortcut = (event: KeyboardEvent<HTMLButtonElement>) => {
93 if (!recording || event.key === "Tab" || event.repeat) return;
94 event.preventDefault();
95 event.stopPropagation();
96 if (event.key === "Escape") {
97 stopRecording();
98 return;
99 }
100 const modifier = MODIFIER_FROM_KEY[event.key];
101 if (modifier) {
102 const held = heldModifierCodes.current;
103 held.add(event.code);
104 const [left, right] = MODIFIER_CODES[modifier];
105 if (held.has(left) && held.has(right)) {
106 if (!allowModifierPairs) {
107 onError(gt("Add a letter, number, or function key to your shortcut."));
108 return;
109 }
110 stopRecording();
111 onRecord(
112 modifier === "shift" ? { kind: "both-shift-keys" } : { kind: "modifier-pair", modifier },
113 );
114 }
115 return;
116 }
117 // A global shortcut without a modifier would take that key from every app.
118 if (!event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey) return;
119 const input = keybindingFromKeyboardEvent(event, navigator.platform);
120 if (!input) return;
121 const next = parseKeybindingShortcut(input);
122 if (!next) return;
123 stopRecording();
124 onRecord(next);
125 };
126
127 return {
128 recording,
129 stopRecording,
130 input: (
131 <Button
132 type="button"
133 size="xs"
134 variant={recording ? "secondary" : "outline"}
135 disabled={disabled}
136 aria-label={
137 displayShortcut
138 ? gt("Record snapshot shortcut, currently {shortcut}", {
139 shortcut: formatSnapShotShortcutLabel(displayShortcut),
140 })
141 : gt("Change snapshot shortcut")
142 }
143 aria-pressed={recording}
144 data-keybinding-capture=""
145 onClick={() => void startRecording()}
146 onKeyDown={recordShortcut}
147 onKeyUp={(event) => heldModifierCodes.current.delete(event.code)}
148 onBlur={stopRecording}
149 >
150 {recording ? (
151 gt("Press shortcut…")
152 ) : !displayShortcut ? (
153 gt("Change shortcut")
154 ) : !allowModifierPairs && isModifierPairShortcut(displayShortcut) ? (
155 gt("Choose shortcut")
156 ) : (
157 <SnapShotShortcutKeys shortcut={displayShortcut} />
158 )}
159 </Button>
160 ),
161 };
162 }