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