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