Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 isModifierPairShortcut,
4 type ClientSettingsPatch,
5 type DesktopSnapShotShortcutAvailability,
6 type DesktopSnapShotState,
7 type DesktopSnapShotSetupAction,
8 type SnapShotShortcut,
9} from "@t3tools/contracts";
10import { PlayIcon } from "lucide-react";
11import { useCallback, useEffect, useRef, useState } from "react";
12
13import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
14import { getDesktopSnapShotBridge } from "../../lib/desktopSnapShot";
15import {
16 readSnapShotSetupResume,
17 saveSnapShotSetupResume,
18 clearSnapShotSetupResume,
19} from "../../lib/snapShotSetupResume";
20import { sameSnapShotShortcut, snapShotKeybindingConflict } from "../../lib/snapShotShortcut";
21import { playSnapShotSound } from "../../lib/snapShotSound";
22import { primaryServerKeybindingsAtom } from "../../state/server";
23import { commandLabel } from "./KeybindingsSettings.logic";
24import {
25 snapShotStatus,
26 snapShotShortcutStatus,
27 snapShotSetupButtonLabel,
28 snapShotUnavailableMessage,
29 snapShotSoundPatch,
30 snapShotFeedbackUnavailableMessage,
31 snapShotDescription,
32 snapShotAccessibilityUnavailableMessage,
33 snapShotSetupComplete,
34 type SnapShotSoundSelection,
35} from "./SnapShotSettings.logic";
36import {
37 SettingsUnavailableGroup,
38 SettingsPageContainer,
39 SettingsRow,
40 SettingsSection,
41} from "./settingsLayout";
42import { searchableSetting } from "./settingsSearch";
43import { Button } from "../ui/button";
44import { Menu, MenuItem, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";
45import { SelectButton } from "../ui/select";
46import { Switch } from "../ui/switch";
47import { toastManager } from "../ui/toast";
48import { SnapShotSetupDialog } from "./SnapShotSetupDialog";
49import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
50import {
51 captureSetupAccessReady,
52 captureSetupInitialStep,
53 captureSetupShouldDisableOnClose,
54 type CaptureSetupStep,
55} from "./SnapShotSetupDialog.logic";
56
57const soundOptionRowClassName = "grid grid-cols-[1fr_auto]";
58
59function captureSettingsError(title: string, error: unknown) {
60 return { title, message: error instanceof Error ? error.message : "Try again." };
61}
62
63type ShortcutCheck =
64 | { readonly status: "idle"; readonly availability: null }
65 | { readonly status: "checking"; readonly availability: null }
66 | {
67 readonly status: "checked";
68 readonly availability: DesktopSnapShotShortcutAvailability;
69 };
70
71export function SnapShotSettings() {
72 const settings = useClientSettings();
73 const updateSettings = useUpdateClientSettings();
74 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
75 const bridge = getDesktopSnapShotBridge();
76 const [state, setState] = useState<DesktopSnapShotState | null>(null);
77 const [setupBusy, setSetupBusy] = useState(false);
78 const [setupError, setSetupError] = useState<ReturnType<typeof captureSettingsError> | null>(
79 null,
80 );
81 const [wizard, setWizard] = useState<{
82 initialStep: CaptureSetupStep;
83 wasEnabled: boolean;
84 } | null>(null);
85 const [candidate, setCandidate] = useState<SnapShotShortcut>(settings.snapShotShortcut);
86 const [shortcutCheck, setShortcutCheck] = useState<ShortcutCheck>({
87 status: "idle",
88 availability: null,
89 });
90 const shortcutCheckIdRef = useRef(0);
91 const stateRequestIdRef = useRef(0);
92 const unavailableMessage = snapShotUnavailableMessage(Boolean(bridge));
93 const captureAvailable = Boolean(bridge) && state !== null && state.mode !== "unavailable";
94 const feedbackUnavailable = snapShotFeedbackUnavailableMessage(state);
95 const savedShortcut = settings.snapShotShortcut;
96 const managedShortcut = state?.linuxBackend === "niri" || state?.linuxBackend === "hyprland";
97 const shortcutChanged = !managedShortcut && !sameSnapShotShortcut(candidate, savedShortcut);
98 const displayShortcut = shortcutChanged ? candidate : (state?.shortcut ?? savedShortcut);
99 const candidateConflict = shortcutChanged
100 ? snapShotKeybindingConflict(candidate, keybindings)
101 : null;
102 const canSaveShortcut =
103 shortcutChanged && candidateConflict === null && shortcutCheck.availability?.available === true;
104 const soundSelection = settings.snapShotPlaySound ? settings.snapShotSound : "off";
105 const soundLabel =
106 soundSelection === "off" ? "Off" : soundSelection === "soft-pop" ? "Whoosh (Default)" : "Click";
107
108 const refreshState = useCallback(async () => {
109 const requestId = ++stateRequestIdRef.current;
110 try {
111 if (bridge) {
112 const nextState = await bridge.getSnapShotState();
113 if (requestId === stateRequestIdRef.current) setState(nextState);
114 return nextState;
115 }
116 } catch (error) {
117 if (requestId === stateRequestIdRef.current)
118 setSetupError(captureSettingsError("Couldn't check capture setup", error));
119 }
120 }, [bridge]);
121
122 const setup = useCallback(
123 async (action: DesktopSnapShotSetupAction) => {
124 if (!bridge?.setupSnapShot || setupBusy) return;
125 setSetupBusy(true);
126 setSetupError(null);
127 try {
128 if (
129 state?.macPermissions &&
130 wizard &&
131 (action === "allow-screen-recording" || action === "allow-accessibility")
132 ) {
133 // macOS can quit the app from its permission prompt.
134 saveSnapShotSetupResume(wizard.wasEnabled);
135 }
136 await bridge.setupSnapShot(action);
137 await refreshState();
138 } catch (error) {
139 setSetupError(
140 captureSettingsError(
141 action === "retry-shortcut"
142 ? "Couldn't open shortcut permissions"
143 : "Couldn't complete capture setup",
144 error,
145 ),
146 );
147 } finally {
148 setSetupBusy(false);
149 }
150 },
151 [bridge, refreshState, setupBusy, state, wizard],
152 );
153
154 useEffect(() => {
155 if (!setupError || wizard) return;
156 toastManager.add({
157 type: "error",
158 title: setupError.title,
159 description: setupError.message,
160 });
161 setSetupError(null);
162 }, [setupError, wizard]);
163
164 useEffect(() => {
165 let cancelled = false;
166 void refreshState().then((current) => {
167 const resume = readSnapShotSetupResume();
168 if (!cancelled && current?.macPermissions && resume) {
169 setWizard({ initialStep: "access", wasEnabled: resume.wasEnabled });
170 }
171 });
172 window.addEventListener("focus", refreshState);
173 return () => {
174 cancelled = true;
175 window.removeEventListener("focus", refreshState);
176 };
177 }, [refreshState]);
178
179 useEffect(
180 () =>
181 bridge?.onSnapShotEvent((event) => {
182 if (event.type === "shortcut-changed") void refreshState();
183 }),
184 [bridge, refreshState],
185 );
186
187 useEffect(() => {
188 shortcutCheckIdRef.current++;
189 setCandidate(savedShortcut);
190 setShortcutCheck({ status: "idle", availability: null });
191 }, [savedShortcut]);
192
193 const save = useCallback(
194 async (patch: ClientSettingsPatch) => {
195 setSetupError(null);
196 try {
197 await updateSettings(patch);
198 return await refreshState();
199 } catch (error) {
200 setSetupError(captureSettingsError("Couldn't save capture settings", error));
201 }
202 },
203 [refreshState, updateSettings],
204 );
205
206 const saveIncludeAccessibility = useCallback(
207 async (includeAccessibility: boolean) => {
208 try {
209 if (includeAccessibility && settings.snapShotEnabled)
210 await bridge?.requestSnapShotPermissions(true);
211 await save({ snapShotIncludeAccessibility: includeAccessibility });
212 } catch (error) {
213 setSetupError(captureSettingsError("Couldn't allow app text capture", error));
214 }
215 },
216 [bridge, save, settings.snapShotEnabled],
217 );
218
219 const checkShortcut = useCallback(
220 async (shortcut: SnapShotShortcut) => {
221 const checkId = ++shortcutCheckIdRef.current;
222 setCandidate(shortcut);
223 const conflict = snapShotKeybindingConflict(shortcut, keybindings);
224 if (conflict || !bridge) return;
225 setShortcutCheck({ status: "checking", availability: null });
226 try {
227 const availability = await bridge.checkSnapShotShortcut(shortcut);
228 if (checkId === shortcutCheckIdRef.current) {
229 setShortcutCheck({ status: "checked", availability });
230 }
231 } catch (error) {
232 if (checkId !== shortcutCheckIdRef.current) return;
233 setShortcutCheck({
234 status: "checked",
235 availability: {
236 available: false,
237 message: error instanceof Error ? error.message : "Could not check this shortcut.",
238 },
239 });
240 }
241 },
242 [bridge, keybindings],
243 );
244
245 const {
246 recording,
247 stopRecording,
248 input: shortcutInput,
249 } = useSnapShotShortcutRecorder({
250 shortcut: displayShortcut,
251 shortcutLabel: !shortcutChanged ? state?.shortcutLabel : undefined,
252 disabled: setupBusy,
253 allowModifierPairs: state?.mode !== "portal",
254 onRecord: (shortcut) => void checkShortcut(shortcut),
255 onStart: () => {
256 shortcutCheckIdRef.current++;
257 setShortcutCheck({ status: "idle", availability: null });
258 },
259 onError: (message) =>
260 setShortcutCheck({ status: "checked", availability: { available: false, message } }),
261 });
262
263 const shortcutStatus = recording
264 ? "Press your shortcut. Esc cancels."
265 : candidateConflict
266 ? `T3 Code already uses this for "${commandLabel(candidateConflict)}".`
267 : shortcutCheck.status === "checking"
268 ? "Checking shortcut…"
269 : shortcutCheck.availability
270 ? shortcutCheck.availability.available
271 ? "Ready to save."
272 : shortcutCheck.availability.message
273 : state?.mode === "portal" &&
274 !state.shortcutLabel &&
275 isModifierPairShortcut(displayShortcut)
276 ? "Try a shortcut such as Ctrl+Shift+2."
277 : snapShotShortcutStatus(state);
278
279 const openSetup = async (requested: CaptureSetupStep | "resume" = "resume") => {
280 if (!state || setupBusy) return;
281 stopRecording();
282 shortcutCheckIdRef.current++;
283 setCandidate(savedShortcut);
284 setShortcutCheck({ status: "idle", availability: null });
285 setSetupError(null);
286 setSetupBusy(true);
287 try {
288 let current = await refreshState();
289 if (!current) return;
290 if (current.macPermissions) requested = "access";
291 if (!settings.snapShotEnabled && captureSetupInitialStep(current, requested) !== "access") {
292 current = await save({ snapShotEnabled: true });
293 if (!current) {
294 // A settings write can succeed even if the following status check
295 // fails. Keep Finish later available to turn capture back off.
296 setWizard({ initialStep: "access", wasEnabled: false });
297 return;
298 }
299 }
300 setWizard({
301 initialStep: captureSetupInitialStep(current, requested),
302 wasEnabled: settings.snapShotEnabled,
303 });
304 } finally {
305 setSetupBusy(false);
306 }
307 };
308
309 const enableForSetup = async () => {
310 if (setupBusy) return false;
311 setSetupBusy(true);
312 setSetupError(null);
313 try {
314 if (state?.macPermissions) {
315 saveSnapShotSetupResume(wizard?.wasEnabled ?? settings.snapShotEnabled);
316 if (!bridge?.setupSnapShot) throw new Error("Restart T3 Code to finish capture setup.");
317 await bridge.setupSnapShot("test-mac-capture");
318 }
319 if (state?.mode === "direct")
320 await bridge?.requestSnapShotPermissions(settings.snapShotIncludeAccessibility);
321 const nextState =
322 settings.snapShotEnabled && !state?.message
323 ? await refreshState()
324 : await save({ snapShotEnabled: true });
325 return nextState !== undefined && captureSetupAccessReady(nextState);
326 } catch (error) {
327 setSetupError(captureSettingsError("Couldn't verify capture access", error));
328 return false;
329 } finally {
330 setSetupBusy(false);
331 }
332 };
333
334 const closeSetup = async (completed: boolean) => {
335 if (!wizard || setupBusy) return;
336 setSetupBusy(true);
337 try {
338 if (
339 settings.snapShotEnabled &&
340 captureSetupShouldDisableOnClose(wizard.wasEnabled, completed)
341 ) {
342 if (!(await save({ snapShotEnabled: false }))) return;
343 }
344 stopRecording();
345 setSetupError(null);
346 clearSnapShotSetupResume();
347 setWizard(null);
348 } catch (error) {
349 setSetupError(captureSettingsError("Couldn't close capture setup", error));
350 } finally {
351 setSetupBusy(false);
352 }
353 };
354
355 const saveShortcut = async () => {
356 if (!canSaveShortcut || setupBusy) return false;
357 setSetupBusy(true);
358 try {
359 const saved = await save({ snapShotShortcut: candidate });
360 return Boolean(saved?.shortcutRegistered || saved?.shortcutPending);
361 } finally {
362 setSetupBusy(false);
363 }
364 };
365
366 return (
367 <SettingsPageContainer>
368 <SettingsSection id="snap-shot" title="SnapShots">
369 <SettingsUnavailableGroup message={unavailableMessage}>
370 <SettingsRow
371 {...searchableSetting("snap-shot-enabled")}
372 description={snapShotDescription(state)}
373 status={
374 bridge
375 ? setupBusy && !wizard
376 ? "Updating capture settings…"
377 : snapShotStatus(state, settings.snapShotEnabled)
378 : undefined
379 }
380 control={
381 <>
382 {settings.snapShotEnabled &&
383 !snapShotSetupComplete(state, settings.snapShotIncludeAccessibility) ? (
384 <Button
385 size="xs"
386 variant="outline"
387 disabled={setupBusy}
388 onClick={() => void openSetup()}
389 >
390 {snapShotSetupButtonLabel(state)}
391 </Button>
392 ) : null}
393 <Switch
394 checked={settings.snapShotEnabled || Boolean(wizard)}
395 disabled={!captureAvailable || setupBusy}
396 aria-label="Enable snapshots"
397 onCheckedChange={(checked) => {
398 if (!checked) void save({ snapShotEnabled: false });
399 else if (state?.windows) void save({ snapShotEnabled: true });
400 else void openSetup();
401 }}
402 />
403 </>
404 }
405 />
406 {settings.snapShotEnabled && captureAvailable ? (
407 <>
408 <SettingsRow
409 {...searchableSetting("snap-shot-accessibility")}
410 description="Include text and controls when the app makes them available."
411 status={snapShotAccessibilityUnavailableMessage(state)}
412 control={
413 <Switch
414 checked={
415 !snapShotAccessibilityUnavailableMessage(state) &&
416 settings.snapShotIncludeAccessibility
417 }
418 disabled={
419 !captureAvailable || Boolean(snapShotAccessibilityUnavailableMessage(state))
420 }
421 aria-label="Include app text in snapshots"
422 onCheckedChange={(checked) => void saveIncludeAccessibility(checked)}
423 />
424 }
425 />
426 <SettingsRow
427 {...searchableSetting("snap-shot-shortcut")}
428 description={
429 state?.linuxBackend === "picker"
430 ? "Choose a window to capture from any app."
431 : "Capture the window you're using without switching apps."
432 }
433 status={managedShortcut ? undefined : shortcutStatus}
434 control={
435 managedShortcut ? (
436 <Button
437 size="xs"
438 variant="outline"
439 disabled={setupBusy}
440 onClick={() => void openSetup("shortcut")}
441 >
442 Change shortcut
443 </Button>
444 ) : (
445 <>
446 {shortcutInput}
447 {shortcutChanged ? (
448 <>
449 <Button
450 size="xs"
451 disabled={!canSaveShortcut || setupBusy}
452 onClick={() => void saveShortcut()}
453 >
454 {setupBusy ? "Saving…" : "Save"}
455 </Button>
456 <Button
457 size="xs"
458 variant="ghost"
459 disabled={setupBusy}
460 onClick={() => {
461 stopRecording();
462 shortcutCheckIdRef.current++;
463 setCandidate(savedShortcut);
464 setShortcutCheck({ status: "idle", availability: null });
465 }}
466 >
467 Cancel
468 </Button>
469 </>
470 ) : state?.mode === "portal" &&
471 state.shortcutCanRetry !== false &&
472 !isModifierPairShortcut(savedShortcut) ? (
473 <Button
474 size="xs"
475 variant="ghost"
476 disabled={setupBusy || state.shortcutPending}
477 onClick={() => void setup("retry-shortcut")}
478 >
479 Shortcut permissions
480 </Button>
481 ) : null}
482 </>
483 )
484 }
485 />
486 <SettingsRow
487 {...searchableSetting("snap-shot-sound")}
488 description="Choose the sound played when capture starts."
489 control={
490 <Menu>
491 <MenuTrigger
492 aria-label={"Snapshot sound: " + soundLabel}
493 render={<SelectButton size="sm" />}
494 className="w-auto min-w-0"
495 disabled={!captureAvailable}
496 >
497 {soundSelection === "off" ? (
498 "Off"
499 ) : soundSelection === "soft-pop" ? (
500 <>
501 Whoosh <span className="text-muted-foreground">(Default)</span>
502 </>
503 ) : (
504 "Click"
505 )}
506 </MenuTrigger>
507 <MenuPopup align="end">
508 <MenuRadioGroup
509 onValueChange={(value) =>
510 void save(snapShotSoundPatch(value as SnapShotSoundSelection))
511 }
512 value={soundSelection}
513 >
514 <MenuRadioItem closeOnClick value="off">
515 Off
516 </MenuRadioItem>
517 <div className={soundOptionRowClassName}>
518 <MenuRadioItem closeOnClick value="soft-pop">
519 Whoosh <span className="text-muted-foreground">(Default)</span>
520 </MenuRadioItem>
521 <MenuItem
522 aria-label="Play Whoosh"
523 closeOnClick={false}
524 onClick={() => playSnapShotSound("soft-pop")}
525 >
526 <PlayIcon />
527 </MenuItem>
528 </div>
529 <div className={soundOptionRowClassName}>
530 <MenuRadioItem closeOnClick value="camera-shutter">
531 Click
532 </MenuRadioItem>
533 <MenuItem
534 aria-label="Play Click"
535 closeOnClick={false}
536 onClick={() => playSnapShotSound("camera-shutter")}
537 >
538 <PlayIcon />
539 </MenuItem>
540 </div>
541 </MenuRadioGroup>
542 </MenuPopup>
543 </Menu>
544 }
545 />
546 <SettingsRow
547 {...searchableSetting("snap-shot-flash")}
548 description="Show a gentle cue on the captured window."
549 status={feedbackUnavailable}
550 control={
551 <Switch
552 checked={!feedbackUnavailable && settings.snapShotFlash}
553 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
554 aria-label="Flash captured window"
555 onCheckedChange={(checked) => void save({ snapShotFlash: checked })}
556 />
557 }
558 />
559 <SettingsRow
560 {...searchableSetting("snap-shot-animations")}
561 description="Animate captured windows into your draft."
562 status={feedbackUnavailable}
563 control={
564 <Switch
565 checked={!feedbackUnavailable && settings.snapShotAnimations}
566 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
567 aria-label="Animate snapshots"
568 onCheckedChange={(checked) => void save({ snapShotAnimations: checked })}
569 />
570 }
571 />
572 </>
573 ) : null}
574 </SettingsUnavailableGroup>
575 </SettingsSection>
576 {wizard && state ? (
577 <SnapShotSetupDialog
578 state={state}
579 initialStep={wizard.initialStep}
580 wasEnabled={wizard.wasEnabled}
581 includeAccessibility={settings.snapShotIncludeAccessibility}
582 busy={setupBusy}
583 error={setupError?.message ?? null}
584 shortcutInput={shortcutInput}
585 shortcutStatus={shortcutStatus}
586 shortcutChanged={shortcutChanged}
587 canSaveShortcut={canSaveShortcut}
588 onSaveShortcut={saveShortcut}
589 onEnable={enableForSetup}
590 onAction={setup}
591 onRefresh={refreshState}
592 onClose={closeSetup}
593 onLeaveStep={stopRecording}
594 />
595 ) : null}
596 </SettingsPageContainer>
597 );
598}