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

main
tsx 377 lines 13.2 KB
Raw
1 import {
2 isModifierPairShortcut,
3 type DesktopCaptureConfigApplied,
4 type DesktopCaptureConfigPreview,
5 type DesktopSnapShotState,
6 } from "@t3tools/contracts";
7 import { parseKeybindingShortcut } from "@t3tools/shared/keybindings";
8 import { FileDiff } from "@pierre/diffs/react";
9 import { T, useGT, Var } from "gt-react";
10 import { parseDiffFromFile } from "@pierre/diffs";
11 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
12 import * as Cause from "effect/Cause";
13 import { useState } from "react";
14 import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
15 import { resolveDiffThemeName } from "../../lib/diffRendering";
16 import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
17 import { useRenderedAppearance } from "../../hooks/useTheme";
18 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
19 import { Button } from "../ui/button";
20 import { toastManager } from "../ui/toast";
21 import { shortcutToKeybindingInput } from "./KeybindingsSettings.logic";
22 import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
23
24 const DEFAULT_SHORTCUT = parseKeybindingShortcut("Ctrl+Shift+2")!;
25
26 export function CaptureShortcutConfig({
27 state,
28 disabled = false,
29 onBusyChange,
30 onSaved,
31 onComplete,
32 }: {
33 state: DesktopSnapShotState;
34 disabled?: boolean;
35 onBusyChange?: (busy: boolean) => void;
36 onSaved?: () => Promise<unknown>;
37 onComplete?: () => Promise<void>;
38 }) {
39 const gt = useGT();
40 const bridge = getDesktopSnapShotBridge();
41 const resolvedTheme = useRenderedAppearance();
42 const { copyToClipboard, isCopied } = useCopyToClipboard();
43 const [preview, setPreview] = useState<DesktopCaptureConfigPreview | null>(null);
44 const [result, setResult] = useState<DesktopCaptureConfigApplied | null>(null);
45 const [error, setError] = useState<{ message: string; detail?: string } | null>(null);
46 const [working, setWorking] = useState<"reading" | "writing" | null>(null);
47 const [keys, setKeys] = useState<string | null>(null);
48 const [customFile, setCustomFile] = useState(false);
49 const busy = disabled || working !== null;
50 const changed = preview !== null && preview.before !== preview.after;
51 const niri = state.linuxBackend === "niri";
52 const desktop = niri ? "Niri" : "Hyprland";
53 const shortcutKeys = (keys ?? preview?.shortcut)?.trim();
54 const recorder = useSnapShotShortcutRecorder({
55 shortcut: shortcutKeys
56 ? (parseKeybindingShortcut(shortcutKeys.replace(/super/gi, "meta")) ?? DEFAULT_SHORTCUT)
57 : DEFAULT_SHORTCUT,
58 disabled: busy,
59 allowModifierPairs: false,
60 onStart: () => setError(null),
61 onError: (message) => setError({ message }),
62 onRecord: (shortcut) => {
63 if (isModifierPairShortcut(shortcut)) return;
64 setKeys(
65 shortcutToKeybindingInput({
66 ...shortcut,
67 ctrlKey: shortcut.ctrlKey || shortcut.modKey,
68 modKey: false,
69 }),
70 );
71 setPreview(null);
72 setError(null);
73 },
74 });
75 const actionBusy = busy || recorder.recording;
76 const diff =
77 preview && changed
78 ? parseDiffFromFile(
79 { name: preview.path, contents: preview.before },
80 { name: preview.path, contents: preview.after },
81 )
82 : null;
83 const begin = (phase: "reading" | "writing") => {
84 setWorking(phase);
85 onBusyChange?.(true);
86 setError(null);
87 };
88 const end = () => {
89 setWorking(null);
90 onBusyChange?.(false);
91 };
92 const read = async (chooseFile = customFile, operation: "install" | "remove" = "install") => {
93 if (actionBusy || !bridge) return;
94 begin("reading");
95 setPreview(null);
96 setResult(null);
97 setCustomFile(chooseFile);
98 const previewed = await settlePromise(() =>
99 bridge.previewSnapShotConfig({
100 operation,
101 chooseFile,
102 ...(keys?.trim() ? { shortcut: keys.trim() } : {}),
103 }),
104 );
105 if (previewed._tag === "Success") {
106 setPreview(previewed.value);
107 } else {
108 const cause = Cause.squash(previewed.cause);
109 setError({
110 message: gt("Couldn't prepare the changes. Check Advanced for help."),
111 ...(cause instanceof Error ? { detail: cause.message } : {}),
112 });
113 }
114 end();
115 };
116 const apply = async () => {
117 if (actionBusy || !preview || !bridge) return;
118 begin("writing");
119 const saved = await settlePromise(async () => {
120 const applied = await bridge.applySnapShotConfig(preview.id);
121 setResult(applied);
122 await onSaved?.();
123 if (!applied.warning && preview.operation === "install" && onComplete) {
124 toastManager.add({
125 type: "success",
126 title: gt("Shortcut saved"),
127 description: gt("Use {shortcut} from another app.", { shortcut: preview.shortcut }),
128 });
129 await onComplete();
130 }
131 });
132 if (saved._tag === "Failure") {
133 const cause = Cause.squash(saved.cause);
134 setError({
135 message: gt("Couldn't save your shortcut. Review the changes and try again."),
136 ...(cause instanceof Error ? { detail: cause.message } : {}),
137 });
138 setPreview(null);
139 }
140 end();
141 };
142
143 return (
144 <div className="space-y-4 text-sm">
145 {!result ? (
146 <div className="flex items-center justify-between gap-3">
147 <span>
148 <T>Shortcut</T>
149 </span>
150 {recorder.input}
151 </div>
152 ) : null}
153 {recorder.recording ? (
154 <p role="status" className="text-xs text-muted-foreground">
155 <T>Press your shortcut. Esc cancels.</T>
156 </p>
157 ) : null}
158 {result ? (
159 <p role="status">
160 {result.warning
161 ? gt("Saved, but the shortcut needs attention. Check Advanced for help.")
162 : preview?.operation === "remove"
163 ? gt("Shortcut removed.")
164 : gt("Use {shortcut} from another app to capture a window.", {
165 shortcut: preview?.shortcut,
166 })}
167 </p>
168 ) : preview ? (
169 <>
170 <p className="text-muted-foreground">
171 {changed
172 ? preview.operation === "remove"
173 ? gt("Review the change below to remove your shortcut.")
174 : gt("Review the change below, then save your shortcut.")
175 : preview.operation === "remove"
176 ? gt("There's no capture shortcut to remove.")
177 : gt("This shortcut is already set up.")}
178 </p>
179 {diff ? (
180 <div
181 className="max-h-80 overflow-auto rounded-lg border text-xs"
182 aria-label={gt("Shortcut changes")}
183 >
184 <FileDiff
185 fileDiff={diff}
186 options={{
187 diffStyle: "unified",
188 theme: resolveDiffThemeName(resolvedTheme),
189 overflow: "wrap",
190 preferredHighlighter: PREFERRED_HIGHLIGHTER,
191 }}
192 />
193 </div>
194 ) : null}
195 {changed ? (
196 <p className="text-xs text-muted-foreground">
197 <T>Only these changes will be saved. We'll keep a backup.</T>
198 </p>
199 ) : null}
200 <div className="flex gap-2">
201 {changed || preview.operation === "install" ? (
202 <Button
203 disabled={
204 actionBusy ||
205 (preview.operation === "install" && state.shortcutActionRegistered === false)
206 }
207 aria-busy={working === "writing"}
208 onClick={() => void apply()}
209 >
210 {working === "writing"
211 ? gt("Saving…")
212 : changed
213 ? preview.operation === "install"
214 ? gt("Save shortcut")
215 : gt("Remove shortcut")
216 : gt("Done")}
217 </Button>
218 ) : null}
219 <Button variant="ghost" disabled={actionBusy} onClick={() => setPreview(null)}>
220 <T>Cancel</T>
221 </Button>
222 </div>
223 </>
224 ) : (
225 <>
226 <p className="text-muted-foreground">
227 <T>
228 Allow T3 Code to read your desktop settings. You'll review any changes here before
229 saving.
230 </T>
231 </p>
232 <Button
233 disabled={actionBusy || !bridge}
234 aria-busy={working === "reading"}
235 onClick={() => void read()}
236 >
237 {working === "reading" ? gt("Preparing changes…") : gt("Review changes")}
238 </Button>
239 </>
240 )}
241 {error ? (
242 <p role="alert" className="text-destructive">
243 {error.message}
244 </p>
245 ) : null}
246 {state.shortcutActionRegistered === false && state.shortcutMessage ? (
247 <p role="status" className="text-muted-foreground">
248 {state.shortcutPending
249 ? gt("Connecting to your desktop…")
250 : gt("Restart T3 Code to finish connecting your shortcut.")}
251 </p>
252 ) : null}
253 <details className="text-xs text-muted-foreground">
254 <summary className="cursor-pointer">
255 <T>Advanced</T>
256 </summary>
257 <div className="mt-3 space-y-3">
258 {error?.detail || result?.warning ? (
259 <div className="space-y-1">
260 <p className="font-medium text-foreground">
261 <T>Troubleshooting</T>
262 </p>
263 <p className="break-words">{error?.detail ?? result?.warning}</p>
264 </div>
265 ) : null}
266 <div className="space-y-1">
267 <p className="font-medium text-foreground">
268 <T>Settings file</T>
269 </p>
270 <p className="break-all font-mono">
271 {preview?.path ??
272 state.shortcutConfigPath ??
273 (niri ? "~/.config/niri/config.kdl" : "~/.config/hypr/hyprland.conf")}
274 </p>
275 {niri ? (
276 <p>
277 <T>T3 Code also reads any files included by this file.</T>
278 </p>
279 ) : null}
280 {preview && preview.resolvedPath !== preview.path ? (
281 <p className="break-all">
282 <T>
283 Linked to <Var>{preview.resolvedPath}</Var>. The link will be kept.
284 </T>
285 </p>
286 ) : null}
287 </div>
288 <div className="flex flex-wrap gap-2">
289 <Button
290 size="sm"
291 variant="outline"
292 disabled={actionBusy || !bridge}
293 onClick={() => void read(true)}
294 >
295 <T>Choose a different file…</T>
296 </Button>
297 <Button
298 size="sm"
299 variant="ghost"
300 disabled={actionBusy || !bridge}
301 onClick={() => void read(customFile, "remove")}
302 >
303 <T>Remove shortcut…</T>
304 </Button>
305 {result ? (
306 <Button
307 size="sm"
308 variant="outline"
309 disabled={actionBusy || !bridge}
310 onClick={() => void read()}
311 >
312 <T>Review changes</T>
313 </Button>
314 ) : null}
315 </div>
316 <p>
317 {niri
318 ? gt(
319 "Use your desktop's shortcut settings file. A custom --config or NIRI_CONFIG can change its location.",
320 )
321 : gt(
322 "Use your desktop's shortcut settings file. On Omarchy, use your own bindings file, not its defaults.",
323 )}
324 </p>
325 {result?.backupPath ? (
326 <p className="break-all">{gt("Backup: {path}", { path: result.backupPath })}</p>
327 ) : null}
328 <p className="font-medium text-foreground">
329 <T>Manual setup</T>
330 </p>
331 <p>
332 {niri
333 ? gt(
334 "Paste this inside {block} in your Niri config, then save. Change the keys if needed.",
335 { block: "binds { … }" },
336 )
337 : gt(
338 "Add this binding to your Hyprland config, then save. Change the keys if needed.",
339 )}
340 </p>
341 <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-xl bg-muted/50 p-3">
342 {state.shortcutBinding}
343 </pre>
344 <Button
345 size="sm"
346 variant="outline"
347 disabled={actionBusy || !state.shortcutBinding}
348 onClick={() => {
349 if (state.shortcutBinding) copyToClipboard(state.shortcutBinding);
350 }}
351 >
352 {isCopied ? gt("Copied") : gt("Copy shortcut")}
353 </Button>
354 <p>
355 <T>
356 Turn capture off in T3 Code to stop it. Remove the shortcut from <Var>{desktop}</Var>{" "}
357 to free up the keys.
358 </T>
359 </p>
360 {state.shortcutActionRegistered === false ? (
361 <p role="status">{state.shortcutMessage}</p>
362 ) : null}
363 {onComplete ? (
364 <Button
365 size="sm"
366 variant="outline"
367 disabled={actionBusy || state.shortcutActionRegistered === false}
368 onClick={() => void onComplete()}
369 >
370 <T>I've added the shortcut</T>
371 </Button>
372 ) : null}
373 </div>
374 </details>
375 </div>
376 );
377 }