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

BrowserImportWizard.tsx

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