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

CaptureShortcutConfig.tsx

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