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

SnapShotSetupDialog.tsx

563 lines19.7 KB

1import {
2 isModifierPairShortcut,
3 type DesktopSnapShotSetupAction,
4 type DesktopSnapShotState,
5} from "@t3tools/contracts";
6import { CircleCheckIcon } from "lucide-react";
7import { useEffect, useId, useState, type ReactNode } from "react";
8import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
9import { Button } from "../ui/button";
10import { Dialog, DialogDescription } from "../ui/dialog";
11import { WizardSteps, WizardPopup, WizardHeader, WizardPanel, WizardFooter } from "../ui/wizard";
12import {
13 captureSetupAccessReady,
14 captureSetupBackend,
15 captureSetupCheckMessage,
16 captureSetupDesktopName,
17 captureSetupInitialStep,
18 captureSetupMacPermissionsReady,
19 captureSetupShortcutReady,
20 type CaptureSetupStep,
21} from "./SnapShotSetupDialog.logic";
22​
23const SETUP_STEPS = [
24 { id: "access", label: "Access" },
25 { id: "shortcut", label: "Shortcut" },
26] as const;
27​
28const GNOME_ACCESS_COPY = {
29 "not-installed": {
30 title: "Install the extension",
31 description:
32 "The T3 Code GNOME extension lets you capture other windows and bring them into your draft. Sign out once after installing.",
33 },
34 "restart-required": {
35 title: "Extension installed",
36 description: "Save your work, then sign out and back in. Your setup will be waiting here.",
37 },
38 "update-required": {
39 title: "Update the extension",
40 description: "Install the update, then sign out and back in.",
41 },
42 "extensions-disabled": {
43 title: "Allow GNOME extensions",
44 description: "Open GNOME Extensions and turn on extensions, then check again.",
45 },
46 disabled: {
47 title: "Enable the extension",
48 description: "Enable T3 Code SnapShots to start capturing windows.",
49 },
50 enabled: {
51 title: "Capture is ready",
52 description: "Next, choose your shortcut.",
53 },
54 unsupported: {
55 title: "Automatic capture isn't available",
56 description: "Use Take snapshot from the command palette to choose a window.",
57 },
58 error: {
59 title: "Couldn't set up the extension",
60 description: "Check T3 Code SnapShots in GNOME Extensions, then try again.",
61 },
62};
63​
64function ScreenRecordingIcon() {
65 const gradientId = useId();
66 return (
67 <svg
68 viewBox="0 0 32 32"
69 className="size-8 shrink-0 drop-shadow-[0_1px_1px_#0005]"
70 aria-hidden="true"
71 >
72 <defs>
73 <linearGradient id={gradientId} x2="0" y2="1">
74 <stop stopColor="#ff6972" />
75 <stop offset="1" stopColor="#ff2938" />
76 </linearGradient>
77 </defs>
78 <rect
79 x="0.5"
80 y="0.5"
81 width="31"
82 height="31"
83 rx="7"
84 fill={`url(#${gradientId})`}
85 stroke="#ffffff40"
86 />
87 <circle cx="16" cy="16" r="10" fill="none" stroke="#fff" strokeWidth="2" />
88 <circle cx="16" cy="16" r="4.5" fill="#fff" />
89 </svg>
90 );
92​
93function AccessibilityPermissionIcon() {
94 const gradientId = useId();
95 return (
96 <svg
97 viewBox="0 0 32 32"
98 className="size-8 shrink-0 drop-shadow-[0_1px_1px_#0005]"
99 aria-hidden="true"
100 >
101 <defs>
102 <linearGradient id={gradientId} x2="0" y2="1">
103 <stop stopColor="#48b6ff" />
104 <stop offset="1" stopColor="#0085ff" />
105 </linearGradient>
106 </defs>
107 <rect
108 x="0.5"
109 y="0.5"
110 width="31"
111 height="31"
112 rx="7"
113 fill={`url(#${gradientId})`}
114 stroke="#ffffff40"
115 />
116 <circle cx="16" cy="16" r="10" fill="none" stroke="#fff" strokeWidth="1.75" />
117 <circle cx="16" cy="10" r="1.6" fill="#fff" />
118 <path
119 d="m10 13 6 1 6-1M16 14v4m0 0-2.5 6m2.5-6 2.5 6"
120 fill="none"
121 stroke="#fff"
122 strokeWidth="1.6"
123 strokeLinecap="round"
124 strokeLinejoin="round"
125 />
126 </svg>
127 );
129​
130function MacPermissionRow({
131 icon,
132 title,
133 description,
134 granted,
135 busy,
136 onAllow,
137}: {
138 icon: ReactNode;
139 title: string;
140 description: string;
141 granted: boolean;
142 busy: boolean;
143 onAllow: () => void;
144}) {
145 return (
146 <div className="flex items-center gap-3 rounded-lg border px-3 py-2">
147 {icon}
148 <div className="min-w-0 flex-1">
149 <p className="font-medium">{title}</p>
150 <p className="text-xs text-muted-foreground">{description}</p>
151 </div>
152 {granted ? (
153 <span className="flex items-center gap-1 text-xs text-success">
154 <CircleCheckIcon className="size-4" aria-hidden="true" />
155 Allowed
156 </span>
157 ) : (
158 <Button size="xs" variant="outline" disabled={busy} onClick={onAllow}>
159 Allow
160 </Button>
161 )}
162 </div>
163 );
165​
166export function SnapShotSetupDialog({
167 state,
168 initialStep,
169 wasEnabled,
170 includeAccessibility,
171 busy: actionBusy,
172 error,
173 shortcutInput,
174 shortcutStatus,
175 shortcutChanged,
176 canSaveShortcut,
177 onSaveShortcut,
178 onEnable,
179 onAction,
180 onRefresh,
181 onClose,
182 onLeaveStep,
183}: {
184 state: DesktopSnapShotState;
185 initialStep: CaptureSetupStep;
186 wasEnabled: boolean;
187 includeAccessibility: boolean;
188 busy: boolean;
189 error: string | null;
190 shortcutInput: ReactNode;
191 shortcutStatus: string | null | undefined;
192 shortcutChanged: boolean;
193 canSaveShortcut: boolean;
194 onSaveShortcut: () => Promise<boolean>;
195 onEnable: () => Promise<boolean>;
196 onAction: (action: DesktopSnapShotSetupAction) => Promise<void>;
197 onRefresh: () => Promise<DesktopSnapShotState | undefined>;
198 onClose: (completed: boolean) => Promise<void>;
199 onLeaveStep: () => void;
200}) {
201 const [step, setStep] = useState(() => captureSetupInitialStep(state, initialStep));
202 const [checking, setChecking] = useState(false);
203 const [checked, setChecked] = useState(false);
204 const [configBusy, setConfigBusy] = useState(false);
205 const busy = actionBusy || checking || configBusy;
206 const backend = captureSetupBackend(state);
207 const configShortcut = backend === "niri" || backend === "hyprland";
208 const desktop = captureSetupDesktopName(state);
209 const extension = state.gnomeExtension;
210 const helper = backend === "hyprland" ? state.hyprlandHelper : state.kdeHelper;
211 const helperBackend = backend === "kde" || backend === "hyprland";
212 const installHelper = backend === "hyprland" ? "install-hyprland-helper" : "install-kde-helper";
213 const removeHelper = backend === "hyprland" ? "remove-hyprland-helper" : "remove-kde-helper";
214 const accessReady = captureSetupAccessReady(state);
215 const macPermissions = state.macPermissions;
216 const macPermissionsReady = captureSetupMacPermissionsReady(state, includeAccessibility);
217 const shortcutReady = captureSetupShortcutReady(state, shortcutChanged);
218 const install = extension?.status === "not-installed" || extension?.status === "update-required";
219 const enable = extension?.status === "disabled";
220 useEffect(() => {
221 if (!macPermissions || step !== "access") return;
222 const refresh = () => void onRefresh();
223 window.addEventListener("focus", refresh);
224 return () => window.removeEventListener("focus", refresh);
225 }, [macPermissions, onRefresh, step]);
226 const changeStep = (next: CaptureSetupStep) => {
227 onLeaveStep();
228 setChecked(false);
229 setStep(next);
230 };
231 const checkAgain = async () => {
232 if (busy) return;
233 setChecking(true);
234 setChecked(false);
235 try {
236 setChecked((await onRefresh()) !== undefined);
237 } finally {
238 setChecking(false);
239 }
240 };
241 const accessCopy =
242 state.message && !macPermissions
243 ? {
244 title: "Let's try that again",
245 description: "Couldn't check snapshots. Try again to continue.",
246 }
247 : backend === "gnome" && extension
248 ? extension.status === "enabled" && !accessReady
249 ? {
250 title: "Check capture access",
251 description: "The extension isn't ready yet. Try again in a moment.",
252 }
253 : GNOME_ACCESS_COPY[extension.status]
254 : helperBackend
255 ? helper?.status === "ready"
256 ? {
257 title: "Capture is ready",
258 description: "Next, choose your shortcut.",
259 }
260 : helper?.status === "error"
261 ? {
262 title: "Let's fix capture access",
263 description: "Try reinstalling the capture helper, then check again.",
264 }
265 : {
266 title:
267 helper?.status === "update-required"
268 ? "Update the capture helper"
269 : "Allow snapshots",
270 description:
271 "T3 Code's capture helper lets you capture other apps and return to your draft. It's included with T3 Code.",
272 }
273 : backend === "niri"
274 ? {
275 title: "Capture is ready",
276 description: "Next, choose your shortcut.",
277 }
278 : backend === "picker"
279 ? {
280 title: "Choose a window each time",
281 description:
282 "Your desktop doesn't support automatic capture. You'll choose the window to capture instead.",
283 }
284 : {
285 title: "Allow snapshots",
286 description:
287 backend === "portal"
288 ? "Your desktop may ask for permission when you first capture."
289 : macPermissions
290 ? macPermissionsReady
291 ? "Test a snapshot of the current window. If macOS asks to bypass its window picker, choose Allow. The test image is discarded."
292 : "Allow each permission, then continue."
293 : "Allow access when prompted to start capturing windows.",
294 };
295 const title = step === "access" ? accessCopy.title : "Choose your shortcut";
296 const description =
297 step === "access"
298 ? accessCopy.description
299 : configShortcut
300 ? "Click the shortcut, then press the keys you want."
301 : state.mode === "portal"
302 ? "Choose your keys, then approve the permission prompt if asked."
303 : "Use both Shift keys, or record a different shortcut.";
304 const stepIndex = SETUP_STEPS.findIndex(({ id }) => id === step);
305 const details = [
306 ...new Set(
307 [
308 error,
309 ...(step === "access"
310 ? [
311 state.message,
312 backend === "gnome" &&
313 (extension?.status === "error" || extension?.status === "unsupported")
314 ? extension.message
315 : null,
316 helperBackend && helper?.status === "error" ? helper.message : null,
317 ]
318 : []),
319 ].filter((detail) => detail !== null),
320 ),
321 ];
322​
323 return (
324 <Dialog
325 open
326 onOpenChange={(open) => {
327 if (!open && !busy) void onClose(false);
328 }}
329 >
330 <WizardPopup showCloseButton={!busy}>
331 <WizardHeader title={desktop ? `Set up snapshots for ${desktop}` : "Set up snapshots"}>
332 <WizardSteps
333 steps={SETUP_STEPS.map((item) => item.label)}
334 currentStep={stepIndex}
335 isStepDisabled={(index) => busy || index > stepIndex}
336 onStepChange={(index) => {
337 const next = SETUP_STEPS[index];
338 if (next && next.id !== step) changeStep(next.id);
339 }}
340 />
341 </WizardHeader>
342 <WizardPanel>
343 <div className="space-y-4 text-sm">
344 <div className="space-y-2" aria-live="polite">
345 <h3 className="flex items-center gap-2 font-medium">{title}</h3>
346 <DialogDescription>{description}</DialogDescription>
347 </div>
348 {step === "access" ? (
349 <>
350 <p
351 role="status"
352 aria-atomic="true"
353 className={
354 checked && !busy && !error ? "text-xs text-muted-foreground" : "sr-only"
355 }
356 >
357 {checked && !busy && !error ? captureSetupCheckMessage(state) : null}
358 </p>
359 {macPermissions ? (
360 <div className="space-y-2">
361 <MacPermissionRow
362 icon={<ScreenRecordingIcon />}
363 title="Screen Recording"
364 description="Capture the window you're using."
365 granted={macPermissions.screenRecording}
366 busy={busy}
367 onAllow={() => void onAction("allow-screen-recording")}
368 />
369 <MacPermissionRow
370 icon={<AccessibilityPermissionIcon />}
371 title="Accessibility"
372 description={
373 includeAccessibility
374 ? "Include text and controls from the captured app."
375 : "Optional. Include text and controls from the captured app."
376 }
377 granted={macPermissions.accessibility}
378 busy={busy}
379 onAllow={() => void onAction("allow-accessibility")}
380 />
381 </div>
382 ) : null}
383 {helperBackend && helper?.status === "error" ? (
384 <Button
385 size="xs"
386 variant="outline"
387 disabled={busy}
388 onClick={() => void onAction(installHelper)}
389 >
390 Reinstall helper
391 </Button>
392 ) : null}
393 </>
394 ) : configShortcut ? (
395 <CaptureShortcutConfig
396 state={state}
397 disabled={actionBusy || checking || !accessReady}
398 onBusyChange={setConfigBusy}
399 onSaved={onRefresh}
400 onComplete={() => onClose(true)}
401 />
402 ) : (
403 <div className="space-y-3">
404 {shortcutInput}
405 {shortcutStatus ? (
406 <p className="text-xs text-muted-foreground" role="status">
407 {shortcutStatus}
408 </p>
409 ) : null}
410 {!shortcutChanged &&
411 !state.shortcutRegistered &&
412 !state.shortcutPending &&
413 state.shortcutCanRetry !== false &&
414 !isModifierPairShortcut(state.shortcut) ? (
415 <Button
416 variant="ghost"
417 size="sm"
418 disabled={busy}
419 onClick={() => void onAction("retry-shortcut")}
420 >
421 {state.mode === "portal" ? "Shortcut permissions" : "Try again"}
422 </Button>
423 ) : null}
424 </div>
425 )}
426 {step === "shortcut" && !accessReady ? (
427 <p role="alert" className="text-destructive">
428 Capture needs attention. Go back to check access.
429 </p>
430 ) : null}
431 {error ? (
432 <p role="alert" className="text-destructive">
433 Couldn't finish this step. Try again or check Advanced for help.
434 </p>
435 ) : null}
436 {details.length > 0 || (step === "access" && (backend === "gnome" || helperBackend)) ? (
437 <details className="text-xs text-muted-foreground">
438 <summary className="cursor-pointer">Advanced</summary>
439 <div className="mt-3 space-y-3">
440 {details.map((detail) => (
441 <p key={detail} className="break-words">
442 {detail}
443 </p>
444 ))}
445 {step === "access" && (backend === "gnome" || helperBackend) ? (
446 <p>Included with T3 Code. No download needed.</p>
447 ) : null}
448 {step === "access" && backend === "gnome" && extension?.status === "enabled" ? (
449 <Button
450 size="xs"
451 variant="ghost"
452 disabled={busy}
453 onClick={() => void onAction("disable-extension")}
454 >
455 Disable extension
456 </Button>
457 ) : null}
458 {step === "access" && helperBackend && helper?.status !== "not-installed" ? (
459 <Button
460 size="xs"
461 variant="ghost"
462 disabled={busy}
463 onClick={() => void onAction(removeHelper)}
464 >
465 Remove capture helper
466 </Button>
467 ) : null}
468 </div>
469 </details>
470 ) : null}
471 </div>
472 </WizardPanel>
473 <WizardFooter>
474 {step !== "access" ? (
475 <Button variant="ghost" disabled={busy} onClick={() => changeStep("access")}>
476 Back
477 </Button>
478 ) : null}
479 <Button variant="ghost" disabled={busy} onClick={() => void onClose(false)}>
480 {wasEnabled ? "Close" : "Finish later"}
481 </Button>
482 {step === "access" ? (
483 helperBackend && !accessReady && helper?.status !== "ready" ? (
484 <Button
485 disabled={busy}
486 aria-busy={busy}
487 onClick={() =>
488 void (helper?.status === "error" ? checkAgain() : onAction(installHelper))
489 }
490 >
491 {checking
492 ? "Checking…"
493 : busy
494 ? "Installing…"
495 : helper?.status === "error"
496 ? "Check again"
497 : helper?.status === "update-required"
498 ? "Update helper"
499 : "Install helper"}
500 </Button>
501 ) : backend === "gnome" && !accessReady && extension?.status !== "enabled" ? (
502 <Button
503 disabled={busy}
504 aria-busy={checking}
505 onClick={() =>
506 void (install
507 ? onAction("install-extension")
508 : enable
509 ? onAction("enable-extension")
510 : checkAgain())
511 }
512 >
513 {checking
514 ? "Checking…"
515 : busy
516 ? install
517 ? "Installing…"
518 : enable
519 ? "Enabling…"
520 : "Working…"
521 : install
522 ? extension?.status === "update-required"
523 ? "Update extension"
524 : "Install extension"
525 : enable
526 ? "Enable extension"
527 : "Check again"}
528 </Button>
529 ) : (
530 <Button
531 disabled={busy || !macPermissionsReady}
532 onClick={async () => {
533 if (await onEnable()) changeStep("shortcut");
534 }}
535 >
536 {busy
537 ? "Working…"
538 : macPermissions
539 ? "Test capture and continue"
540 : backend === "direct"
541 ? "Allow capture"
542 : !accessReady && !macPermissions
543 ? "Try again"
544 : "Continue"}
545 </Button>
546 )
547 ) : !configShortcut ? (
548 <Button
549 disabled={
550 busy || !accessReady || (shortcutChanged ? !canSaveShortcut : !shortcutReady)
551 }
552 onClick={async () => {
553 if (!shortcutChanged || (await onSaveShortcut())) await onClose(true);
554 }}
555 >
556 {busy ? "Saving…" : shortcutChanged ? "Save and finish" : "Done"}
557 </Button>
558 ) : null}
559 </WizardFooter>
560 </WizardPopup>
561 </Dialog>
562 );