Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SnapShotSettings.tsx

625 lines23.9 KB

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