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 refreshSetup = useCallback(() => {
342 setSetupError(null);
343 return refreshState();
344 }, [refreshState]);
345
346 const closeSetup = async (completed: boolean) => {
347 if (!wizard || setupBusy) return;
348 setSetupBusy(true);
349 try {
350 if (
351 settings.snapShotEnabled &&
352 captureSetupShouldDisableOnClose(wizard.wasEnabled, completed)
353 ) {
354 if (!(await save({ snapShotEnabled: false }))) return;
355 }
356 stopRecording();
357 setSetupError(null);
358 clearSnapShotSetupResume();
359 setWizard(null);
360 } catch (error) {
361 setSetupError(captureSettingsError("Couldn't close capture setup", error));
362 } finally {
363 setSetupBusy(false);
364 }
365 };
366
367 const saveShortcut = async () => {
368 if (!canSaveShortcut || setupBusy) return false;
369 setSetupBusy(true);
370 try {
371 const saved = await save({ snapShotShortcut: candidate });
372 return Boolean(saved?.shortcutRegistered || saved?.shortcutPending);
373 } finally {
374 setSetupBusy(false);
375 }
376 };
377
378 return (
379 <SettingsPageContainer>
380 <SettingsSection id="snap-shot" title="SnapShots">
381 <SettingsUnavailableGroup message={unavailableMessage}>
382 <SettingsRow
383 {...searchableSetting("snap-shot-enabled")}
384 description={snapShotDescription(state)}
385 status={
386 bridge
387 ? setupBusy && !wizard
388 ? "Updating capture settings…"
389 : snapShotStatus(state, settings.snapShotEnabled)
390 : undefined
391 }
392 control={
393 <>
394 {settings.snapShotEnabled &&
395 !snapShotSetupComplete(state, settings.snapShotIncludeAccessibility) ? (
396 <Button
397 size="xs"
398 variant="outline"
399 disabled={setupBusy}
400 onClick={() => void openSetup()}
401 >
402 {snapShotSetupButtonLabel(state)}
403 </Button>
404 ) : null}
405 <Switch
406 checked={settings.snapShotEnabled || Boolean(wizard)}
407 disabled={!captureAvailable || setupBusy}
408 aria-label="Enable snapshots"
409 onCheckedChange={(checked) => {
410 if (!checked) void save({ snapShotEnabled: false });
411 else if (state?.windows) void save({ snapShotEnabled: true });
412 else void openSetup();
413 }}
414 />
415 </>
416 }
417 />
418 {settings.snapShotEnabled && captureAvailable ? (
419 <>
420 <SettingsRow
421 {...searchableSetting("snap-shot-accessibility")}
422 description="Include text and controls when the app makes them available."
423 status={snapShotAccessibilityUnavailableMessage(state)}
424 control={
425 <Switch
426 checked={
427 !snapShotAccessibilityUnavailableMessage(state) &&
428 settings.snapShotIncludeAccessibility
429 }
430 disabled={
431 !captureAvailable || Boolean(snapShotAccessibilityUnavailableMessage(state))
432 }
433 aria-label="Include app text in snapshots"
434 onCheckedChange={(checked) => void saveIncludeAccessibility(checked)}
435 />
436 }
437 />
438 <SettingsRow
439 {...searchableSetting("snap-shot-shortcut")}
440 description={
441 state?.linuxBackend === "picker"
442 ? "Choose a window to capture from any app."
443 : "Capture the window you're using without switching apps."
444 }
445 status={managedShortcut ? undefined : shortcutStatus}
446 control={
447 managedShortcut ? (
448 <Button
449 size="xs"
450 variant="outline"
451 disabled={setupBusy}
452 onClick={() => void openSetup("shortcut")}
453 >
454 Change shortcut
455 </Button>
456 ) : (
457 <>
458 {shortcutInput}
459 {shortcutChanged ? (
460 <>
461 <Button
462 size="xs"
463 disabled={!canSaveShortcut || setupBusy}
464 onClick={() => void saveShortcut()}
465 >
466 {setupBusy ? "Saving…" : "Save"}
467 </Button>
468 <Button
469 size="xs"
470 variant="ghost"
471 disabled={setupBusy}
472 onClick={() => {
473 stopRecording();
474 shortcutCheckIdRef.current++;
475 setCandidate(savedShortcut);
476 setShortcutCheck({ status: "idle", availability: null });
477 }}
478 >
479 Cancel
480 </Button>
481 </>
482 ) : state?.mode === "portal" &&
483 state.shortcutCanRetry !== false &&
484 !isModifierPairShortcut(savedShortcut) ? (
485 <Button
486 size="xs"
487 variant="ghost"
488 disabled={setupBusy || state.shortcutPending}
489 onClick={() => void setup("retry-shortcut")}
490 >
491 Shortcut permissions
492 </Button>
493 ) : null}
494 </>
495 )
496 }
497 />
498 <SettingsRow
499 {...searchableSetting("snap-shot-sound")}
500 description="Choose the sound played when capture starts."
501 control={
502 <Menu>
503 <MenuTrigger
504 aria-label={"Snapshot sound: " + soundLabel}
505 className={cn(selectTriggerVariants({ size: "sm" }), "w-auto min-w-0")}
506 disabled={!captureAvailable}
507 >
508 <span className="min-w-0 flex-1 truncate text-left">
509 {soundSelection === "off" ? (
510 "Off"
511 ) : soundSelection === "soft-pop" ? (
512 <>
513 Whoosh <span className="text-muted-foreground">(Default)</span>
514 </>
515 ) : (
516 "Click"
517 )}
518 </span>
519 <ChevronDownIcon className="-me-1 size-3 shrink-0 opacity-50" />
520 </MenuTrigger>
521 <MenuPopup align="end">
522 <MenuRadioGroup
523 onValueChange={(value) =>
524 void save(snapShotSoundPatch(value as SnapShotSoundSelection))
525 }
526 value={soundSelection}
527 >
528 <MenuRadioItem closeOnClick value="off">
529 Off
530 </MenuRadioItem>
531 <div className={soundOptionRowClassName}>
532 <MenuRadioItem
533 className={soundOptionItemClassName}
534 closeOnClick
535 value="soft-pop"
536 >
537 Whoosh <span className="text-muted-foreground">(Default)</span>
538 </MenuRadioItem>
539 <MenuItem
540 aria-label="Play Whoosh"
541 className={soundPreviewClassName}
542 closeOnClick={false}
543 onClick={() => playSnapShotSound("soft-pop")}
544 >
545 <PlayIcon />
546 </MenuItem>
547 </div>
548 <div className={soundOptionRowClassName}>
549 <MenuRadioItem
550 className={soundOptionItemClassName}
551 closeOnClick
552 value="camera-shutter"
553 >
554 Click
555 </MenuRadioItem>
556 <MenuItem
557 aria-label="Play Click"
558 className={soundPreviewClassName}
559 closeOnClick={false}
560 onClick={() => playSnapShotSound("camera-shutter")}
561 >
562 <PlayIcon />
563 </MenuItem>
564 </div>
565 </MenuRadioGroup>
566 </MenuPopup>
567 </Menu>
568 }
569 />
570 <SettingsRow
571 {...searchableSetting("snap-shot-flash")}
572 description="Show a gentle cue on the captured window."
573 status={feedbackUnavailable}
574 control={
575 <Switch
576 checked={!feedbackUnavailable && settings.snapShotFlash}
577 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
578 aria-label="Flash captured window"
579 onCheckedChange={(checked) => void save({ snapShotFlash: checked })}
580 />
581 }
582 />
583 <SettingsRow
584 {...searchableSetting("snap-shot-animations")}
585 description="Animate captured windows into your draft."
586 status={feedbackUnavailable}
587 control={
588 <Switch
589 checked={!feedbackUnavailable && settings.snapShotAnimations}
590 disabled={!captureAvailable || Boolean(feedbackUnavailable)}
591 aria-label="Animate snapshots"
592 onCheckedChange={(checked) => void save({ snapShotAnimations: checked })}
593 />
594 }
595 />
596 </>
597 ) : null}
598 </SettingsUnavailableGroup>
599 </SettingsSection>
600 {wizard && state ? (
601 <SnapShotSetupDialog
602 state={state}
603 initialStep={wizard.initialStep}
604 wasEnabled={wizard.wasEnabled}
605 includeAccessibility={settings.snapShotIncludeAccessibility}
606 busy={setupBusy}
607 error={setupError?.message ?? null}
608 shortcutInput={shortcutInput}
609 shortcutStatus={shortcutStatus}
610 shortcutChanged={shortcutChanged}
611 canSaveShortcut={canSaveShortcut}
612 onSaveShortcut={saveShortcut}
613 onEnable={enableForSetup}
614 onAction={setup}
615 onRefresh={refreshSetup}
616 onClose={closeSetup}
617 onLeaveStep={stopRecording}
618 />
619 ) : null}
620 </SettingsPageContainer>
621 );
622}