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