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

SnapShotSettings.tsx

586 lines23.0 KB

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