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