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