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

SnapShotSettings.tsx

618 lines23.6 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, useUpdateClientSettings } 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();
81 const updateSettings = useUpdateClientSettings();
82 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
83 const bridge = getDesktopSnapShotBridge();
84 const [state, setState] = useState<DesktopSnapShotState | null>(null);
85 const [setupBusy, setSetupBusy] = useState(false);
86 const [setupError, setSetupError] = useState<ReturnType<typeof captureSettingsError> | null>(
87 null,
88 );
89 const [wizard, setWizard] = useState<{
90 initialStep: CaptureSetupStep;
91 wasEnabled: boolean;
92 } | null>(null);
93 const [candidate, setCandidate] = useState<SnapShotShortcut>(settings.snapShotShortcut);
94 const [latestShortcutCheck, setShortcutCheck] = useState<ShortcutCheck>({
95 status: "idle",
96 availability: null,
97 });
98 // A check answers for one shortcut; once the candidate moves on (an edit, or hydration
99 // resetting it) a late answer for the old one no longer shows.
100 const shortcutCheck: ShortcutCheck =
101 latestShortcutCheck.status === "idle" ||
102 sameSnapShotShortcut(latestShortcutCheck.shortcut, candidate)
103 ? latestShortcutCheck
104 : { status: "idle", availability: null };
105 const shortcutCheckIdRef = useRef(0);
106 const stateRequestIdRef = useRef(0);
107 const unavailableMessage = snapShotUnavailableMessage(Boolean(bridge));
108 const captureAvailable = Boolean(bridge) && state !== null && state.mode !== "unavailable";
109 const feedbackUnavailable = snapShotFeedbackUnavailableMessage(state);
110 const savedShortcut = settings.snapShotShortcut;
111 const managedShortcut = state?.linuxBackend === "niri" || state?.linuxBackend === "hyprland";
112 const shortcutChanged = !managedShortcut && !sameSnapShotShortcut(candidate, savedShortcut);
113 const displayShortcut = shortcutChanged ? candidate : (state?.shortcut ?? savedShortcut);
114 const candidateConflict = shortcutChanged
115 ? snapShotKeybindingConflict(candidate, keybindings)
116 : null;
117 const canSaveShortcut =
118 shortcutChanged && candidateConflict === null && shortcutCheck.availability?.available === true;
119 const soundSelection = settings.snapShotPlaySound ? settings.snapShotSound : "off";
120 const soundLabel =
121 soundSelection === "off" ? "Off" : soundSelection === "soft-pop" ? "Whoosh (Default)" : "Click";
122​
123 // Registered as a window focus listener, so it keeps one identity.
124 const refreshState = useStableCallback(async () => {
125 const requestId = ++stateRequestIdRef.current;
126 try {
127 if (bridge) {
128 const nextState = await bridge.getSnapShotState();
129 if (requestId === stateRequestIdRef.current) setState(nextState);
130 return nextState;
131 }
132 } catch (error) {
133 if (requestId === stateRequestIdRef.current)
134 setSetupError(captureSettingsError("Couldn't check capture setup", error));
135 }
136 });
137​
138 const setup = async (action: DesktopSnapShotSetupAction) => {
139 if (!bridge?.setupSnapShot || setupBusy) return;
140 setSetupBusy(true);
141 setSetupError(null);
142 const result = await settlePromise(async () => {
143 if (
144 state?.macPermissions &&
145 wizard &&
146 (action === "allow-screen-recording" || action === "allow-accessibility")
147 ) {
148 // macOS can quit the app from its permission prompt.
149 saveSnapShotSetupResume(wizard.wasEnabled);
150 }
151 await bridge.setupSnapShot!(action);
152 await refreshState();
153 });
154 if (result._tag === "Failure") {
155 setSetupError(
156 captureSettingsError(
157 action === "retry-shortcut"
158 ? "Couldn't open shortcut permissions"
159 : "Couldn't complete capture setup",
160 Cause.squash(result.cause),
161 ),
162 );
163 }
164 setSetupBusy(false);
165 };
166​
167 // Outside the wizard there is nowhere to show an error inline, so it goes to a toast,
168 // once. The error stays in state until the next action clears it.
169 const toastedErrorRef = useRef<typeof setupError>(null);
170 useEffect(() => {
171 if (!setupError || wizard || toastedErrorRef.current === setupError) return;
172 toastedErrorRef.current = setupError;
173 toastManager.add({
174 type: "error",
175 title: setupError.title,
176 description: setupError.message,
177 });
178 }, [setupError, wizard]);
179​
180 useEffect(() => {
181 let cancelled = false;
182 void refreshState().then((current) => {
183 const resume = readSnapShotSetupResume();
184 if (!cancelled && current?.macPermissions && resume) {
185 setWizard({ initialStep: "access", wasEnabled: resume.wasEnabled });
186 }
187 });
188 window.addEventListener("focus", refreshState);
189 return () => {
190 cancelled = true;
191 window.removeEventListener("focus", refreshState);
192 };
193 }, [refreshState]);
194​
195 useEffect(
196 () =>
197 bridge?.onSnapShotEvent((event) => {
198 if (event.type === "shortcut-changed") void refreshState();
199 }),
200 [bridge, refreshState],
201 );
202​
203 // Hydration can hand back an equal shortcut object; only a different shortcut resets the edit.
204 const [renderedSavedShortcut, setRenderedSavedShortcut] = useState(savedShortcut);
205 if (!sameSnapShotShortcut(renderedSavedShortcut, savedShortcut)) {
206 setRenderedSavedShortcut(savedShortcut);
207 setCandidate(savedShortcut);
208 setShortcutCheck({ status: "idle", availability: null });
209 }
210 // A check still in flight was for the shortcut being replaced.
211 const checkedForSavedShortcutRef = useRef(savedShortcut);
212 useEffect(() => {
213 if (sameSnapShotShortcut(checkedForSavedShortcutRef.current, savedShortcut)) return;
214 checkedForSavedShortcutRef.current = savedShortcut;
215 shortcutCheckIdRef.current++;
216 }, [savedShortcut]);
217​
218 const save = async (patch: ClientSettingsPatch) => {
219 setSetupError(null);
220 try {
221 await updateSettings(patch);
222 return await refreshState();
223 } catch (error) {
224 setSetupError(captureSettingsError("Couldn't save capture settings", error));
225 }
226 };
227​
228 const saveIncludeAccessibility = async (includeAccessibility: boolean) => {
229 try {
230 if (includeAccessibility && settings.snapShotEnabled)
231 await bridge?.requestSnapShotPermissions(true);
232 await save({ snapShotIncludeAccessibility: includeAccessibility });
233 } catch (error) {
234 setSetupError(captureSettingsError("Couldn't allow app text capture", error));
235 }
236 };
237​
238 const checkShortcut = async (shortcut: SnapShotShortcut) => {
239 const checkId = ++shortcutCheckIdRef.current;
240 setCandidate(shortcut);
241 const conflict = snapShotKeybindingConflict(shortcut, keybindings);
242 if (conflict || !bridge) return;
243 setShortcutCheck({ status: "checking", availability: null, shortcut });
244 try {
245 const availability = await bridge.checkSnapShotShortcut(shortcut);
246 if (checkId === shortcutCheckIdRef.current) {
247 setShortcutCheck({ status: "checked", availability, shortcut });
248 }
249 } catch (error) {
250 if (checkId !== shortcutCheckIdRef.current) return;
251 setShortcutCheck({
252 status: "checked",
253 shortcut,
254 availability: {
255 available: false,
256 message: error instanceof Error ? error.message : "Could not check this shortcut.",
257 },
258 });
259 }
260 };
261​
262 const {
263 recording,
264 stopRecording,
265 input: shortcutInput,
266 } = useSnapShotShortcutRecorder({
267 shortcut: displayShortcut,
268 shortcutLabel: !shortcutChanged ? state?.shortcutLabel : undefined,
269 disabled: setupBusy,
270 allowModifierPairs: state?.mode !== "portal",
271 onRecord: (shortcut) => void checkShortcut(shortcut),
272 onStart: () => {
273 shortcutCheckIdRef.current++;
274 setShortcutCheck({ status: "idle", availability: null });
275 },
276 onError: (message) =>
277 setShortcutCheck({
278 status: "checked",
279 shortcut: candidate,
280 availability: { available: false, message },
281 }),
282 });
283​
284 const shortcutStatus = recording
285 ? "Press your shortcut. Esc cancels."
286 : candidateConflict
287 ? `T3 Code already uses this for "${commandLabel(candidateConflict)}".`
288 : shortcutCheck.status === "checking"
289 ? "Checking shortcut…"
290 : shortcutCheck.availability
291 ? shortcutCheck.availability.available
292 ? "Ready to save."
293 : shortcutCheck.availability.message
294 : state?.mode === "portal" &&
295 !state.shortcutLabel &&
296 isModifierPairShortcut(displayShortcut)
297 ? "Try a shortcut such as Ctrl+Shift+2."
298 : snapShotShortcutStatus(state);
299​
300 const openSetup = async (requested: CaptureSetupStep | "resume" = "resume") => {
301 if (!state || setupBusy) return;
302 stopRecording();
303 shortcutCheckIdRef.current++;
304 setCandidate(savedShortcut);
305 setShortcutCheck({ status: "idle", availability: null });
306 setSetupError(null);
307 setSetupBusy(true);
308 await prepareSetup(requested).finally(() => setSetupBusy(false));
309 };
310​
311 const prepareSetup = async (requested: CaptureSetupStep | "resume") => {
312 let current = await refreshState();
313 if (!current) return;
314 if (current.macPermissions) requested = "access";
315 if (!settings.snapShotEnabled && captureSetupInitialStep(current, requested) !== "access") {
316 current = await save({ snapShotEnabled: true });
317 if (!current) {
318 // A settings write can succeed even if the following status check
319 // fails. Keep Finish later available to turn capture back off.
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 );