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