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

CaptureShortcutConfig.tsx

342 lines12.2 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 { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
16import { useRenderedAppearance } from "../../hooks/useTheme";
17import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
18import { Button } from "../ui/button";
19import { toastManager } from "../ui/toast";
20import { shortcutToKeybindingInput } from "./KeybindingsSettings.logic";
21import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
22​
23const DEFAULT_SHORTCUT = parseKeybindingShortcut("Ctrl+Shift+2")!;
24​
25export function CaptureShortcutConfig({
26 state,
27 disabled = false,
28 onBusyChange,
29 onSaved,
30 onComplete,
31}: {
32 state: DesktopSnapShotState;
33 disabled?: boolean;
34 onBusyChange?: (busy: boolean) => void;
35 onSaved?: () => Promise<unknown>;
36 onComplete?: () => Promise<void>;
37}) {
38 const bridge = getDesktopSnapShotBridge();
39 const resolvedTheme = useRenderedAppearance();
40 const { copyToClipboard, isCopied } = useCopyToClipboard();
41 const [preview, setPreview] = useState<DesktopCaptureConfigPreview | null>(null);
42 const [result, setResult] = useState<DesktopCaptureConfigApplied | null>(null);
43 const [error, setError] = useState<{ message: string; detail?: string } | null>(null);
44 const [working, setWorking] = useState<"reading" | "writing" | null>(null);
45 const [keys, setKeys] = useState<string | null>(null);
46 const [customFile, setCustomFile] = useState(false);
47 const busy = disabled || working !== null;
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) 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) 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 preferredHighlighter: PREFERRED_HIGHLIGHTER,
185 }}
186 />
187 </div>
188 ) : null}
189 {changed ? (
190 <p className="text-xs text-muted-foreground">
191 Only these changes will be saved. We'll keep a backup.
192 </p>
193 ) : null}
194 <div className="flex gap-2">
195 {changed || preview.operation === "install" ? (
196 <Button
197 disabled={
198 actionBusy ||
199 (preview.operation === "install" && state.shortcutActionRegistered === false)
200 }
201 aria-busy={working === "writing"}
202 onClick={() => void apply()}
203 >
204 {working === "writing"
205 ? "Saving…"
206 : changed
207 ? preview.operation === "install"
208 ? "Save shortcut"
209 : "Remove shortcut"
210 : "Done"}
211 </Button>
212 ) : null}
213 <Button variant="ghost" disabled={actionBusy} onClick={() => setPreview(null)}>
214 Cancel
215 </Button>
216 </div>
217 </>
218 ) : (
219 <>
220 <p className="text-muted-foreground">
221 Allow T3 Code to read your desktop settings. You'll review any changes here before
222 saving.
223 </p>
224 <Button
225 disabled={actionBusy || !bridge}
226 aria-busy={working === "reading"}
227 onClick={() => void read()}
228 >
229 {working === "reading" ? "Preparing changes…" : "Review changes"}
230 </Button>
231 </>
232 )}
233 {error ? (
234 <p role="alert" className="text-destructive">
235 {error.message}
236 </p>
237 ) : null}
238 {state.shortcutActionRegistered === false && state.shortcutMessage ? (
239 <p role="status" className="text-muted-foreground">
240 {state.shortcutPending
241 ? "Connecting to your desktop…"
242 : "Restart T3 Code to finish connecting your shortcut."}
243 </p>
244 ) : null}
245 <details className="text-xs text-muted-foreground">
246 <summary className="cursor-pointer">Advanced</summary>
247 <div className="mt-3 space-y-3">
248 {error?.detail || result?.warning ? (
249 <div className="space-y-1">
250 <p className="font-medium text-foreground">Troubleshooting</p>
251 <p className="break-words">{error?.detail ?? result?.warning}</p>
252 </div>
253 ) : null}
254 <div className="space-y-1">
255 <p className="font-medium text-foreground">Settings file</p>
256 <p className="break-all font-mono">
257 {preview?.path ??
258 state.shortcutConfigPath ??
259 (niri ? "~/.config/niri/config.kdl" : "~/.config/hypr/hyprland.conf")}
260 </p>
261 {niri ? <p>T3 Code also reads any files included by this file.</p> : null}
262 {preview && preview.resolvedPath !== preview.path ? (
263 <p className="break-all">Linked to {preview.resolvedPath}. The link will be kept.</p>
264 ) : null}
265 </div>
266 <div className="flex flex-wrap gap-2">
267 <Button
268 size="sm"
269 variant="outline"
270 disabled={actionBusy || !bridge}
271 onClick={() => void read(true)}
272 >
273 Choose a different file…
274 </Button>
275 <Button
276 size="sm"
277 variant="ghost"
278 disabled={actionBusy || !bridge}
279 onClick={() => void read(customFile, "remove")}
280 >
281 Remove shortcut…
282 </Button>
283 {result ? (
284 <Button
285 size="sm"
286 variant="outline"
287 disabled={actionBusy || !bridge}
288 onClick={() => void read()}
289 >
290 Review changes
291 </Button>
292 ) : null}
293 </div>
294 <p>
295 Use your desktop's shortcut settings file.{" "}
296 {niri
297 ? "A custom --config or NIRI_CONFIG can change its location."
298 : "On Omarchy, use your own bindings file, not its defaults."}
299 </p>
300 {result?.backupPath ? <p className="break-all">Backup: {result.backupPath}</p> : null}
301 <p className="font-medium text-foreground">Manual setup</p>
302 <p>
303 {niri
304 ? "Paste this inside binds { … } in your Niri config, then save."
305 : "Add this binding to your Hyprland config, then save."}{" "}
306 Change the keys if needed.
307 </p>
308 <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-xl bg-muted/50 p-3">
309 {state.shortcutBinding}
310 </pre>
311 <Button
312 size="sm"
313 variant="outline"
314 disabled={actionBusy || !state.shortcutBinding}
315 onClick={() => {
316 if (state.shortcutBinding) copyToClipboard(state.shortcutBinding);
317 }}
318 >
319 {isCopied ? "Copied" : "Copy shortcut"}
320 </Button>
321 <p>
322 Turn capture off in T3 Code to stop it. Remove the shortcut from {desktop} to free up
323 the keys.
324 </p>
325 {state.shortcutActionRegistered === false ? (
326 <p role="status">{state.shortcutMessage}</p>
327 ) : null}
328 {onComplete ? (
329 <Button
330 size="sm"
331 variant="outline"
332 disabled={actionBusy || state.shortcutActionRegistered === false}
333 onClick={() => void onComplete()}
334 >
335 I've added the shortcut
336 </Button>
337 ) : null}
338 </div>
339 </details>
340 </div>
341 );