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

SnapShotSetupDialog.tsx

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