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

BrowserImportWizard.tsx

475 lines15.7 KB

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