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