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

BrowserImportWizard.tsx

577 lines18.7 KB

1import { PermissionChecklist, PermissionContinueButton } from "../permissions/PermissionChecklist";
2import { usePermissionStatus } from "../permissions/usePermissionStatus";
3import type { BrowserImportSource } from "@t3tools/contracts";
4import { BROWSER_IMPORT_FAILURE_COPY } from "@t3tools/contracts";
5import { ArrowDownIcon, ArrowRightIcon, CheckIcon, HardDriveIcon } from "lucide-react";
6import { useRef, useState } from "react";
7​
8import { cn, randomUUID } from "~/lib/utils";
9​
10import { Button } from "../ui/button";
11import {
12 Dialog,
13 DialogClose,
14 DialogDescription,
15 DialogFooter,
16 DialogHeader,
17 DialogPanel,
18 DialogPopup,
19 DialogTitle,
20} from "../ui/dialog";
21import { Spinner } from "../ui/spinner";
22import {
23 initialWizardStep,
24 initialTargetSelection,
25 canCloseWizard,
26 isRetryableReason,
27 formatSkippedDomains,
28 fullDiskAccessRecheckStep,
29 outcomeToStep,
30 refreshedSourceProfileDirectory,
31 refreshedSourceStep,
32 resolveWizardTarget,
33 type ImportOutcome,
34 type WizardTarget,
35 type WizardTargetProfile,
36 type WizardTargetSelection,
37 type WizardStep,
38} from "./browserImportWizard.logic";
39​
40export type { WizardTarget } from "./browserImportWizard.logic";
41​
42interface BrowserImportWizardProps {
43 readonly source: BrowserImportSource;
44 readonly destinationEnvironmentName: string;
45 readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
46 readonly canCreateProfile: boolean;
47 readonly onImport: (input: {
48 readonly sourceProfileDirectory: string;
49 readonly target: WizardTarget;
50 }) => Promise<ImportOutcome>;
51 readonly onRefreshSource: () => Promise<BrowserImportSource | undefined>;
52 readonly onOpenFullDiskAccessSettings: () => void | Promise<void>;
53 readonly onCheckFullDiskAccess?: (() => Promise<boolean>) | undefined;
54 readonly onClose: () => void;
56​
57export function BrowserImportWizard({
58 source: initialSource,
59 destinationEnvironmentName,
60 targetProfiles,
61 canCreateProfile,
62 onImport,
63 onRefreshSource,
64 onOpenFullDiskAccessSettings,
65 onCheckFullDiskAccess,
66 onClose,
67}: BrowserImportWizardProps) {
68 const [source, setSource] = useState(initialSource);
69 const [step, setStep] = useState<WizardStep>(() => initialWizardStep(initialSource));
70 const [sourceProfileDirectory, setSourceProfileDirectory] = useState(
71 () => initialSource.profiles[0]?.directory ?? "",
72 );
73 const [target, setTarget] = useState<WizardTargetSelection>(() =>
74 initialTargetSelection(canCreateProfile, targetProfiles),
75 );
76 const [targetError, setTargetError] = useState<string>();
77 const newProfileId = useRef(`profile-${randomUUID()}`);
78 // Guard synchronously so a second click's refusal cannot leave the importing step during the first write.
79 const importInFlight = useRef(false);
80​
81 const runImport = () => {
82 if (importInFlight.current) return;
83 const chosen = resolveWizardTarget(target, newProfileId.current, targetProfiles);
84 if (chosen === undefined) {
85 setTargetError("That profile is no longer available. Choose where to import these cookies.");
86 setStep({ step: "configure" });
87 return;
88 }
89 setTargetError(undefined);
90 importInFlight.current = true;
91 setStep({ step: "importing" });
92 void onImport({ sourceProfileDirectory, target: chosen })
93 .then((outcome) => setStep(outcomeToStep(outcome)))
94 .catch(() => setStep({ step: "blocked", reason: "readFailed" }))
95 .finally(() => {
96 importInFlight.current = false;
97 });
98 };
99​
100 const recheckSource = (
101 check: "browser" | "fullDiskAccess",
102 nextStep: (refreshed: BrowserImportSource | undefined) => WizardStep,
103 ) => {
104 setStep({ step: "checking", check });
105 void onRefreshSource()
106 .then((refreshed) => {
107 if (refreshed) {
108 setSource(refreshed);
109 setSourceProfileDirectory((current) =>
110 refreshedSourceProfileDirectory(current, refreshed),
111 );
112 }
113 setStep(nextStep(refreshed));
114 })
115 .catch(() => setStep({ step: "blocked", reason: "readFailed" }));
116 };
117 const recheckAfterQuit = () => recheckSource("browser", refreshedSourceStep);
118 const recheckFullDiskAccess = () => recheckSource("fullDiskAccess", fullDiskAccessRecheckStep);
119​
120 return (
121 <Dialog open onOpenChange={(open) => (open || !canCloseWizard(step) ? undefined : onClose())}>
122 <DialogPopup className="max-w-lg" showCloseButton={canCloseWizard(step)}>
123 {step.step === "quit" ? (
124 <QuitStep source={source} onCancel={onClose} onRechecked={recheckAfterQuit} />
125 ) : step.step === "fullDiskAccess" ? (
126 <FullDiskAccessStep
127 source={source}
128 onCancel={onClose}
129 onOpenSettings={onOpenFullDiskAccessSettings}
130 onCheck={
131 onCheckFullDiskAccess ??
132 (async () => {
133 const refreshed = await onRefreshSource();
134 return refreshed !== undefined && refreshed.unavailable === undefined;
135 })
136 }
137 onGranted={step.resume === "import" ? runImport : recheckFullDiskAccess}
138 stillRequired={step.checked === true}
139 />
140 ) : step.step === "importing" ? (
141 <ImportingStep />
142 ) : step.step === "checking" ? (
143 <CheckingStep sourceName={source.name} check={step.check} />
144 ) : step.step === "done" ? (
145 <DoneStep
146 {...step}
147 destinationEnvironmentName={destinationEnvironmentName}
148 onClose={onClose}
149 />
150 ) : step.step === "blocked" ? (
151 <BlockedStep
152 source={source}
153 reason={step.reason}
154 onClose={onClose}
155 onRetry={isRetryableReason(step.reason) ? runImport : undefined}
156 />
157 ) : (
158 <ConfigureStep
159 source={source}
160 destinationEnvironmentName={destinationEnvironmentName}
161 targetProfiles={targetProfiles}
162 canCreateProfile={canCreateProfile}
163 sourceProfileDirectory={sourceProfileDirectory}
164 onSourceProfileChange={setSourceProfileDirectory}
165 target={target}
166 onTargetChange={(selection) => {
167 setTarget(selection);
168 setTargetError(undefined);
169 }}
170 targetError={targetError}
171 onCancel={onClose}
172 onImport={runImport}
173 />
174 )}
175 </DialogPopup>
176 </Dialog>
177 );
179​
180function QuitStep({
181 source,
182 onCancel,
183 onRechecked,
184}: {
185 readonly source: BrowserImportSource;
186 readonly onCancel: () => void;
187 readonly onRechecked: () => void;
188}) {
189 return (
190 <>
191 <DialogHeader>
192 <DialogTitle>Quit {source.name} to import</DialogTitle>
193 <DialogDescription>
194 {source.name} is open, so its cookies can&rsquo;t be read yet. Quit it, then continue.
195 </DialogDescription>
196 </DialogHeader>
197 <DialogFooter>
198 <Button variant="outline" onClick={onCancel}>
199 Cancel
200 </Button>
201 <Button onClick={onRechecked}>I&rsquo;ve quit it</Button>
202 </DialogFooter>
203 </>
204 );
206​
207function cookieCountLabel(count: number | undefined): string | undefined {
208 if (count === undefined) return undefined;
209 if (count === 0) return "no cookies";
210 return `${count.toLocaleString()} ${count === 1 ? "cookie" : "cookies"}`;
212​
213function cookieResultCount(count: number): string {
214 return `${count.toLocaleString()} ${count === 1 ? "cookie" : "cookies"}`;
216​
217type ConfigureStepProps = {
218 readonly source: BrowserImportSource;
219 readonly destinationEnvironmentName: string;
220 readonly targetProfiles: ReadonlyArray<WizardTargetProfile>;
221 readonly canCreateProfile: boolean;
222 readonly sourceProfileDirectory: string;
223 readonly onSourceProfileChange: (directory: string) => void;
224 readonly target: WizardTargetSelection;
225 readonly targetError: string | undefined;
226 readonly onTargetChange: (target: WizardTargetSelection) => void;
227 readonly onCancel: () => void;
228 readonly onImport: () => void;
229};
230​
231function FullDiskAccessStep({
232 source,
233 onCancel,
234 onOpenSettings,
235 onGranted,
236 stillRequired,
237 onCheck,
238}: {
239 readonly source: BrowserImportSource;
240 readonly onCancel: () => void;
241 readonly onOpenSettings: () => void | Promise<void>;
242 readonly onCheck: () => Promise<boolean>;
243 readonly onGranted: () => void;
244 readonly stillRequired: boolean;
245}) {
246 const [opening, setOpening] = useState(false);
247 const [openingError, setOpeningError] = useState<string | null>(null);
248 const permission = usePermissionStatus(async () => ({ fullDiskAccess: await onCheck() }), {
249 fullDiskAccess: false,
250 });
251 const allow = () => {
252 if (opening) return;
253 setOpening(true);
254 setOpeningError(null);
255 void Promise.resolve()
256 .then(onOpenSettings)
257 .catch(() => setOpeningError("Could not open System Settings. Try Allow again."))
258 .finally(() => setOpening(false));
259 };
260 return (
261 <>
262 <DialogHeader>
263 <DialogTitle>Let T3 Code read {source.name}&rsquo;s cookies</DialogTitle>
264 <DialogDescription>
265 To import cookies from {source.name}, T3 Code needs Full Disk Access. Turn it on in System
266 Settings, then come back to finish the import. You can revoke it again once the import is
267 done.
268 </DialogDescription>
269 </DialogHeader>
270 <DialogPanel>
271 <PermissionChecklist
272 busy={opening}
273 permissions={[
274 {
275 id: "fullDiskAccess",
276 icon: (
277 <HardDriveIcon
278 className="size-8 shrink-0 text-muted-foreground"
279 aria-hidden="true"
280 />
281 ),
282 title: "Full Disk Access",
283 description: `Read ${source.name}'s cookies for this import.`,
284 granted: permission.status.fullDiskAccess,
285 onAllow: () => void allow(),
286 },
287 ]}
288 />
289 {openingError || permission.error ? (
290 <p role="status" className="mt-3 text-xs text-muted-foreground">
291 {openingError ?? permission.error}
292 </p>
293 ) : null}
294 {!permission.isReady(["fullDiskAccess"]) ? (
295 <p className="mt-3 text-xs text-muted-foreground">
296 {stillRequired
297 ? "Access is still required. Quit and reopen T3 Code if you just allowed it, then retry the import."
298 : "If access doesn't update after you allow it, quit and reopen T3 Code, then retry the import."}
299 </p>
300 ) : null}
301 </DialogPanel>
302 <DialogFooter>
303 <Button variant="outline" onClick={onCancel}>
304 Cancel
305 </Button>
306 <PermissionContinueButton
307 ready={permission.isReady(["fullDiskAccess"])}
308 busy={opening}
309 onClick={onGranted}
310 >
311 Continue
312 </PermissionContinueButton>
313 </DialogFooter>
314 </>
315 );
317function ConfigureStep({
318 source,
319 destinationEnvironmentName,
320 targetProfiles,
321 canCreateProfile,
322 sourceProfileDirectory,
323 onSourceProfileChange,
324 target,
325 targetError,
326 onTargetChange,
327 onCancel,
328 onImport,
329}: ConfigureStepProps) {
330 const targetMissing =
331 target.kind === "existing" &&
332 !targetProfiles.some((profile) => profile.id === target.profileId);
333 const targetUncreatable = target.kind === "new" && !canCreateProfile;
334 const targetFeedback =
335 targetError ??
336 (targetMissing
337 ? "That profile is no longer available. Choose where to import these cookies."
338 : targetUncreatable
339 ? "You've reached the profile limit. Choose an existing profile to import into."
340 : undefined);
341 return (
342 <>
343 <DialogHeader>
344 <DialogTitle>Import from {source.name}</DialogTitle>
345 <DialogDescription>
346 Choose which cookies to import for {destinationEnvironmentName}.
347 </DialogDescription>
348 </DialogHeader>
349 <DialogPanel>
350 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
351 <section className="flex-1 space-y-2">
352 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
353 From
354 </p>
355 {source.profiles.map((profile) => (
356 <SelectableTile
357 key={profile.directory}
358 selected={sourceProfileDirectory === profile.directory}
359 title={profile.name}
360 subtitle={cookieCountLabel(profile.cookieCount)}
361 onSelect={() => onSourceProfileChange(profile.directory)}
362 />
363 ))}
364 </section>
365 <div className="flex shrink-0 items-center justify-center text-muted-foreground">
366 <ArrowDownIcon className="size-4 sm:hidden" />
367 <ArrowRightIcon className="hidden size-4 sm:block" />
368 </div>
369 <section className="flex-1 space-y-2">
370 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
371 Into
372 </p>
373 {canCreateProfile ? (
374 <SelectableTile
375 selected={target.kind === "new"}
376 title="New profile"
377 subtitle="Created for these cookies"
378 onSelect={() => onTargetChange({ kind: "new" })}
379 />
380 ) : null}
381 {targetProfiles.map((profile) => (
382 <SelectableTile
383 key={profile.id}
384 selected={target.kind === "existing" && target.profileId === profile.id}
385 title={profile.name}
386 subtitle="Existing profile"
387 onSelect={() => onTargetChange({ kind: "existing", profileId: profile.id })}
388 />
389 ))}
390 </section>
391 </div>
392 {targetFeedback ? (
393 <p role="alert" className="mt-3 text-sm text-destructive">
394 {targetFeedback}
395 </p>
396 ) : null}
397 </DialogPanel>
398 <DialogFooter>
399 <Button variant="outline" onClick={onCancel}>
400 Cancel
401 </Button>
402 <Button
403 disabled={sourceProfileDirectory === "" || targetMissing || targetUncreatable}
404 onClick={onImport}
405 >
406 Import
407 </Button>
408 </DialogFooter>
409 </>
410 );
412​
413function SelectableTile({
414 selected,
415 title,
416 subtitle,
417 onSelect,
418}: {
419 readonly selected: boolean;
420 readonly title: string;
421 readonly subtitle?: string | undefined;
422 readonly onSelect: () => void;
423}) {
424 return (
425 <button
426 type="button"
427 aria-pressed={selected}
428 onClick={onSelect}
429 className={cn(
430 "flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
431 selected
432 ? "border-primary bg-primary/8"
433 : "border-border/60 hover:border-border hover:bg-muted/40",
434 )}
435 >
436 <span className="min-w-0">
437 <span className="block truncate text-sm font-medium text-foreground">{title}</span>
438 {subtitle ? (
439 <span className="block truncate text-xs tabular-nums text-muted-foreground">
440 {subtitle}
441 </span>
442 ) : null}
443 </span>
444 <span
445 className={cn(
446 "grid size-4 shrink-0 place-items-center rounded-full border",
447 selected ? "border-primary bg-primary text-primary-foreground" : "border-input",
448 )}
449 >
450 {selected ? <CheckIcon className="size-2.5" /> : null}
451 </span>
452 </button>
453 );
455​
456function ImportingStep() {
457 return (
458 <>
459 <DialogHeader>
460 <DialogTitle>Importing cookies</DialogTitle>
461 <DialogDescription>This may take a moment.</DialogDescription>
462 </DialogHeader>
463 <DialogPanel>
464 <div className="flex items-center gap-3 py-2">
465 <Spinner size="md" tone="muted" />
466 <span className="text-sm text-muted-foreground">Importing…</span>
467 </div>
468 </DialogPanel>
469 </>
470 );
472​
473function CheckingStep({
474 sourceName,
475 check,
476}: {
477 readonly sourceName: string;
478 readonly check: "browser" | "fullDiskAccess";
479}) {
480 return (
481 <>
482 <DialogHeader>
483 <DialogTitle>Checking {sourceName}</DialogTitle>
484 <DialogDescription>
485 {check === "fullDiskAccess"
486 ? "Checking Full Disk Access."
487 : "Checking whether the browser has closed."}
488 </DialogDescription>
489 </DialogHeader>
490 <DialogPanel>
491 <div className="flex items-center gap-3 py-2">
492 <Spinner size="md" tone="muted" />
493 <span className="text-sm text-muted-foreground">
494 {check === "fullDiskAccess" ? "Checking access…" : "Checking…"}
495 </span>
496 </div>
497 </DialogPanel>
498 </>
499 );
501​
502function DoneStep({
503 imported,
504 skipped,
505 skippedDomains,
506 targetName,
507 destinationEnvironmentName,
508 onClose,
509}: {
510 readonly imported: number;
511 readonly skipped: number;
512 readonly skippedDomains: ReadonlyArray<string>;
513 readonly targetName: string;
514 readonly destinationEnvironmentName: string;
515 readonly onClose: () => void;
516}) {
517 return (
518 <>
519 <DialogHeader>
520 <DialogTitle>
521 {imported > 0
522 ? `Imported ${cookieResultCount(imported)}`
523 : skipped > 0
524 ? `Skipped ${cookieResultCount(skipped)}`
525 : "No cookies found"}
526 </DialogTitle>
527 <DialogDescription>
528 {imported > 0
529 ? `Added to ${targetName} for ${destinationEnvironmentName}.${skipped > 0 ? ` ${cookieResultCount(skipped)} skipped.` : ""}`
530 : skipped > 0
531 ? `No cookies were imported for ${destinationEnvironmentName}.`
532 : `There were no cookies to import for ${destinationEnvironmentName}.`}
533 </DialogDescription>
534 </DialogHeader>
535 {skippedDomains.length > 0 ? (
536 <DialogPanel>
537 <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
538 Skipped
539 </p>
540 <p className="mt-1 text-sm text-foreground">{formatSkippedDomains(skippedDomains)}</p>
541 </DialogPanel>
542 ) : null}
543 <DialogFooter>
544 <DialogClose render={<Button />} onClick={onClose}>
545 Done
546 </DialogClose>
547 </DialogFooter>
548 </>
549 );
551​
552function BlockedStep({
553 source,
554 reason,
555 onClose,
556 onRetry,
557}: {
558 readonly source: BrowserImportSource;
559 readonly reason: keyof typeof BROWSER_IMPORT_FAILURE_COPY;
560 readonly onClose: () => void;
561 readonly onRetry: (() => void) | undefined;
562}) {
563 return (
564 <>
565 <DialogHeader>
566 <DialogTitle>Couldn&rsquo;t import from {source.name}</DialogTitle>
567 <DialogDescription>{BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
568 </DialogHeader>
569 <DialogFooter>
570 <Button variant="outline" onClick={onClose}>
571 Close
572 </Button>
573 {onRetry ? <Button onClick={onRetry}>Try again</Button> : null}
574 </DialogFooter>
575 </>
576 );