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