Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CaptureShortcutConfig.tsx

345 lines12.1 KB

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