Setup flow
One question a screen, each with a way past it, beside a card that fills in as you answer.
825 lines · React · Tailwind 4
Install
$ bunx shadcn@latest add @blocco/setup-flowCode
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import { Button } from "@/registry/blocco/ui/button";
import { Field, FieldReason, Input } from "@/registry/blocco/ui/field";
import { Check, Link2, X } from "@/registry/blocco/ui/icons";
import { LiveStatus } from "@/registry/blocco/ui/live-status";
import { MenuSelect } from "@/registry/blocco/ui/menu";
import { BusyContent } from "@/registry/blocco/ui/spinner";
import { Switch } from "@/registry/blocco/ui/switch";
import { useToast } from "@/registry/blocco/ui/toast";
import { cn } from "@/registry/blocco/ui/cn";
type Step = "name" | "link" | "domain" | "team" | "email";
const ORDER: Step[] = ["name", "link", "domain", "team", "email"];
const DEFAULT_NAME = "Ada’s links";
/** As long as .setup-screen-out runs, below. */
const STEP_OUT_MS = 150;
/** How long the made link stays in view before the next question. */
const LINK_BEAT = 1300;
const HOSTNAME = /^(?!https?:)([a-z0-9-]+\.)+[a-z]{2,}$/i;
const EMAIL = /^\S+@\S+\.\S+$/;
interface MadeLink {
short: string;
destination: string;
}
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const bare = (url: string) => url.replace(/^https?:\/\//, "");
const initial = (text: string) => text.trim().charAt(0).toUpperCase() || "?";
/**
* A new organization's setup, one question a screen, each with a way past it. The card beside
* it is the organization as others will see it, and it fills in as the answers come.
*/
export default function SetupFlow() {
const [run, setRun] = useState(0);
const [done, setDone] = useState(false);
return (
<div className="flex min-h-[44rem] flex-col px-5 py-5 sm:px-8">
{done ? (
<Finished
onRestart={() => {
setDone(false);
setRun((n) => n + 1);
}}
/>
) : (
<Flow key={run} onDone={() => setDone(true)} />
)}
</div>
);
}
function Finished({ onRestart }: { onRestart: () => void }) {
return (
<div className="m-auto flex max-w-sm flex-col items-center gap-3 text-center">
<span className="grid size-10 place-items-center rounded-full bg-accent-2 text-bg">
<Check size={20} stroke={2.6} aria-hidden className="welcome-check" />
</span>
<h1 className="text-2xl font-semibold tracking-tight text-balance">You are set up</h1>
<p className="text-sm text-pretty text-muted">
Here the flow would hand over to the app, and the organization card would become its
switcher.
</p>
<Button variant="outline" onClick={onRestart}>
Start again
</Button>
</div>
);
}
function Flow({ onDone }: { onDone: () => void }) {
const [step, setStep] = useState<Step>("name");
const [leaving, setLeaving] = useState(false);
const [name, setName] = useState(DEFAULT_NAME);
const [link, setLink] = useState<MadeLink | null>(null);
const [domain, setDomain] = useState<string | null>(null);
// What the domain step has typed so far, for the card to show.
const [typed, setTyped] = useState("");
const [invited, setInvited] = useState<string[]>([]);
// Moving on, the screen there steps out, quieter than the next comes in, before the next arrives.
const next = () => {
if (leaving) return;
const after = ORDER[ORDER.indexOf(step) + 1];
if (!after) return onDone();
if (matchMedia("(prefers-reduced-motion: reduce)").matches) return setStep(after);
setLeaving(true);
window.setTimeout(() => {
setLeaving(false);
setStep(after);
}, STEP_OUT_MS);
};
const shown = name.trim() || DEFAULT_NAME;
const screens = {
name: () => <NameStep name={name} onName={setName} onNext={next} />,
link: () => <LinkStep link={link} onLink={setLink} onNext={next} />,
domain: () => <DomainStep link={link} onTyped={setTyped} onAdded={setDomain} onNext={next} />,
team: () => (
<TeamStep
invited={invited}
onInvited={(sent) => setInvited((was) => [...was, ...sent])}
onNext={next}
/>
),
email: () => <EmailStep onNext={next} />,
} satisfies Record<Step, () => ReactNode>;
return (
<>
<header className="relative flex h-9 items-center">
<span className="text-[15px] font-semibold tracking-tight">Acme</span>
<Pips at={ORDER.indexOf(step)} />
</header>
<main className="mx-auto grid w-full max-w-[880px] flex-1 grid-cols-[minmax(0,1fr)] items-center gap-10 py-10 md:grid-cols-[minmax(0,1fr)_300px]">
<section
key={step}
className={cn("setup-screen flex max-w-[400px] flex-col", leaving && "setup-screen-out")}
inert={leaving}
aria-live="polite"
>
{screens[step]()}
</section>
<OrgCard
name={shown}
link={link}
domain={domain ?? (typed || "go.acme.test")}
domainSet={!!domain}
invited={invited}
className="max-md:order-first"
/>
</main>
</>
);
}
function Pips({ at }: { at: number }) {
return (
<span
className="absolute left-1/2 flex -translate-x-1/2 gap-1.5"
role="img"
aria-label={`Step ${at + 1} of ${ORDER.length}`}
>
{ORDER.map((s, i) => (
<span
key={s}
className={cn(
"h-2 rounded-full transition-[width,background-color] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]",
i === at ? "w-5" : "w-2",
i <= at ? "bg-accent" : "bg-border",
)}
/>
))}
</span>
);
}
function StepHead({ title, children }: { title: string; children: ReactNode }) {
return (
<>
<h1 className="text-2xl leading-tight font-semibold tracking-tight text-balance">{title}</h1>
<p className="mt-2.5 text-sm text-pretty text-muted">{children}</p>
</>
);
}
function Actions({ children }: { children: ReactNode }) {
return <div className="mt-4 flex flex-wrap items-center gap-2">{children}</div>;
}
function SkipButton({ onClick, label = "Skip" }: { onClick: () => void; label?: string }) {
return (
<Button variant="ghost" onClick={onClick}>
{label}
</Button>
);
}
/* ------------------------------------------------------------------ */
/* The organization card */
/* ------------------------------------------------------------------ */
function OrgCard({
name,
link,
domain,
domainSet,
invited,
className,
}: {
name: string;
link: MadeLink | null;
domain: string;
/** The domain was added, rather than shown as what it could be. */
domainSet: boolean;
invited: string[];
className?: string;
}) {
return (
<aside
aria-label="Your organization"
className={cn(
"flex flex-col gap-4 rounded-2xl bg-surface p-5 smooth-shadow-ring-xl",
className,
)}
>
<div className="flex items-center gap-3">
<span
aria-hidden
className="grid size-11 shrink-0 place-items-center rounded-xl bg-accent text-xl font-bold text-bg"
>
{initial(name)}
</span>
<span className="flex min-w-0 flex-col">
<span className="truncate text-[17px] font-semibold" title={name}>
{name}
</span>
<span className="text-xs text-muted">
Free · 1 member{invited.length > 0 && `, ${invited.length} invited`}
</span>
</span>
</div>
<CardRow label="First link">
{link ? (
<div className="setup-arrive-in flex items-center gap-3 rounded-[10px] p-2 smooth-shadow-ring-xs">
<span
aria-hidden
className="grid size-12 shrink-0 place-items-center rounded-lg bg-surface-2 text-muted"
>
<Link2 size={20} />
</span>
<span className="flex min-w-0 flex-col gap-1">
<span className="truncate font-mono text-[13px] font-bold">{bare(link.short)}</span>
<span className="truncate font-mono text-[11px] text-muted" title={link.destination}>
{bare(link.destination)}
</span>
</span>
</div>
) : (
<div className="grid h-16 place-items-center rounded-[10px] text-xs text-placeholder shadow-[inset_0_0_0_1.5px_var(--border)]">
Shows here once made
</div>
)}
</CardRow>
<CardRow label="Domain">
<DomainLine domain={domain} set={domainSet} />
</CardRow>
<CardRow label="Team">
<Team invited={invited} />
</CardRow>
</aside>
);
}
function CardRow({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="flex flex-col gap-2 pt-3.5 shadow-[inset_0_1px_0_var(--border)]">
<span className="text-xs text-muted">{label}</span>
{children}
</div>
);
}
/** Once added, the domain checks its DNS for a few seconds and goes live. */
function DomainLine({ domain, set }: { domain: string; set: boolean }) {
const [live, setLive] = useState(false);
useEffect(() => {
if (!set) return setLive(false);
const timer = setTimeout(() => setLive(true), 4500);
return () => clearTimeout(timer);
}, [set, domain]);
return (
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className={cn("truncate font-mono text-[12.5px]", !set && "text-placeholder")}>
{domain}
</span>
{set && <LiveStatus done={live} label={live ? "Live" : "Checking DNS"} />}
</span>
);
}
/** The team starts with whoever is setting it up; each invite takes a place, and two empty ones say there is room. */
function Team({ invited }: { invited: string[] }) {
const shown = invited.slice(0, 6);
return (
<span className="flex flex-wrap gap-1.5">
<span className="grid size-7 place-items-center rounded-lg bg-surface-2 text-xs font-semibold smooth-shadow-ring-xs">
A
</span>
{shown.map((email) => (
<span
key={email}
title={`${email}, invited`}
className="setup-arrive-in grid size-7 place-items-center rounded-lg bg-accent/15 font-mono text-xs text-accent shadow-[inset_0_0_0_1.5px_var(--accent)]"
>
{initial(email)}
</span>
))}
{invited.length > shown.length && (
<span className="grid h-7 place-items-center px-1 text-xs text-muted tabular-nums">
+{invited.length - shown.length}
</span>
)}
{invited.length < 2 &&
Array.from({ length: 2 - invited.length }, (_, i) => (
<span key={i} className="size-7 rounded-lg shadow-[inset_0_0_0_1.5px_var(--border)]" />
))}
</span>
);
}
/* ------------------------------------------------------------------ */
/* Steps */
/* ------------------------------------------------------------------ */
function NameStep({
name,
onName,
onNext,
}: {
name: string;
onName: (name: string) => void;
onNext: () => void;
}) {
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const submit = async (e: FormEvent) => {
e.preventDefault();
const value = name.trim();
if (!value) return setError("Needs a name");
setBusy(true);
await wait(400);
setBusy(false);
onNext();
};
return (
<form onSubmit={(e) => void submit(e)} noValidate className="flex flex-col">
<StepHead title="What should we call your organization?">
Teammates see it in invites, and you see it in the corner. Settings can change it later.
</StepHead>
<div className="mt-6">
<Field label="Name" error={error}>
<Input
value={name}
autoFocus
maxLength={100}
onChange={(e) => {
onName(e.target.value);
setError(undefined);
}}
/>
</Field>
</div>
<Actions>
<Button type="submit" variant="primary" disabled={busy}>
<BusyContent busy={busy}>Continue</BusyContent>
</Button>
<SkipButton
onClick={() => {
onName(DEFAULT_NAME);
onNext();
}}
/>
</Actions>
</form>
);
}
function LinkStep({
link,
onLink,
onNext,
}: {
link: MadeLink | null;
onLink: (link: MadeLink) => void;
onNext: () => void;
}) {
const [destination, setDestination] = useState("");
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const submit = async (e: FormEvent) => {
e.preventDefault();
if (link || busy) return;
const value = destination.trim();
if (!value) return setError("Paste a link first");
if (/\s/.test(value) || !value.includes(".")) return setError("Not a web address");
setBusy(true);
await wait(600);
setBusy(false);
// The link lands in the card; a beat to see it, then on by itself.
onLink({
short: "https://acme.link/x7Kq2p",
destination: /^https?:\/\//i.test(value) ? value : `https://${value}`,
});
window.setTimeout(onNext, LINK_BEAT);
};
return (
<form onSubmit={(e) => void submit(e)} noValidate className="flex flex-col">
<StepHead title="Shorten your first link">Paste any long URL. It gets a short link.</StepHead>
<div className="mt-6">
<Field label="Long link" error={error}>
<Input
value={destination}
autoFocus
readOnly={!!link}
inputMode="url"
autoComplete="off"
placeholder="https://example.com/launch"
onChange={(e) => {
setDestination(e.target.value);
setError(undefined);
}}
/>
</Field>
</div>
<Actions>
<Button
type="submit"
variant="primary"
disabled={busy || !!link}
className={cn(link && "!bg-accent-2 disabled:opacity-100")}
>
{link ? (
<span className="flex items-center gap-1.5">
<Check size={15} stroke={2.6} className="welcome-check" />
Link created
</span>
) : (
<BusyContent busy={busy}>Create link</BusyContent>
)}
</Button>
{!link && <SkipButton onClick={onNext} />}
</Actions>
</form>
);
}
function Address({ label, address, accent }: { label: string; address: string; accent?: boolean }) {
return (
<div
className={cn(
"flex flex-col gap-0.5 rounded-[10px] bg-surface px-3 py-2.5",
accent
? "shadow-[inset_0_0_0_1.5px_var(--accent)]"
: "shadow-[inset_0_0_0_1px_var(--border)]",
)}
>
<span className="text-xs text-muted">{label}</span>
<span className="truncate font-mono text-[13px] font-bold" title={address}>
{address}
</span>
</div>
);
}
/** The slug a custom domain would let them choose: the last word of the link's path. */
function chosenSlug(destination: string | undefined): string {
try {
const last = new URL(destination ?? "").pathname.split("/").filter(Boolean).pop() ?? "";
const slug = last
.toLowerCase()
.replace(/\.[a-z0-9]+$/, "")
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 24);
return slug || "launch";
} catch {
return "launch";
}
}
/**
* Their link as it is and as it would be on their own domain: on the shared domain every slug
* is random, and choosing one is what a domain gives. Once added, the step shows the record to set.
*/
function DomainStep({
link,
onTyped,
onAdded,
onNext,
}: {
link: MadeLink | null;
onTyped: (host: string) => void;
onAdded: (host: string) => void;
onNext: () => void;
}) {
const toast = useToast();
const [hostname, setHostname] = useState("");
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const [added, setAdded] = useState<string | null>(null);
const typed = hostname.trim().toLowerCase();
const valid = HOSTNAME.test(typed);
const slug = chosenSlug(link?.destination);
const type = (value: string) => {
setHostname(value);
setError(undefined);
const next = value.trim().toLowerCase();
onTyped(HOSTNAME.test(next) ? next : "");
};
const submit = async (e: FormEvent) => {
e.preventDefault();
if (!valid) return setError(typed ? "Not a domain" : "Add a domain");
setBusy(true);
await wait(600);
setBusy(false);
setAdded(typed);
onAdded(typed);
};
if (added)
return (
<div className="flex flex-col">
<StepHead title={`${added} is yours`}>
Add the record below where you manage its DNS, and links on it work.
</StepHead>
<div className="mt-6 flex items-center gap-1 rounded-lg bg-surface-2 py-2 pr-2 pl-3">
<code className="min-w-0 flex-1 font-mono text-xs [overflow-wrap:anywhere]">
CNAME {added.split(".")[0]} cname.acme.link
</code>
<Button
size="sm"
variant="ghost"
onClick={() =>
void navigator.clipboard
.writeText("cname.acme.link")
.then(() => toast("Copied", "info", { code: "cname.acme.link" }))
}
>
Copy target
</Button>
</div>
<p className="mt-2.5 text-xs text-pretty text-muted">
Usually live within an hour. You can keep going: we check on our own.
</p>
<Actions>
<Button variant="primary" onClick={onNext}>
Continue
</Button>
</Actions>
</div>
);
return (
<form onSubmit={(e) => void submit(e)} noValidate className="flex flex-col">
<StepHead title="Use your own domain">
On your own domain you choose the slug. Links on it read as yours.
</StepHead>
<div className="mt-6">
<Field label="Domain" error={error}>
<Input
value={hostname}
autoFocus
placeholder="go.acme.test"
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
className="font-mono"
onChange={(e) => type(e.target.value)}
/>
</Field>
</div>
<div className="mt-3 flex flex-col gap-2">
{link && <Address label="Now" address={bare(link.short)} />}
<Address
label="On your domain"
address={`${valid ? typed : "go.acme.test"}/${slug}`}
accent
/>
</div>
<Actions>
<Button type="submit" variant="primary" disabled={busy}>
<BusyContent busy={busy}>{valid ? `Add ${typed}` : "Add domain"}</BusyContent>
</Button>
<SkipButton onClick={onNext} label="Not now" />
</Actions>
</form>
);
}
const ROLES = [
{ value: "editor", label: "Editor" },
{ value: "viewer", label: "Viewer" },
{ value: "admin", label: "Admin" },
];
/** What is wrong with a list of addresses, if anything. */
function emailsProblem(all: string[]): string | undefined {
if (!all.length) return "Add an email";
const bad = all.filter((a) => !EMAIL.test(a));
if (bad.length === 1) return `Not an email: ${bad[0]}`;
if (bad.length) return `${bad.length} are not emails`;
return undefined;
}
const splitEmails = (text: string) => text.split(/[\s,;]+/).filter(Boolean);
function TeamStep({
invited,
onInvited,
onNext,
}: {
invited: string[];
onInvited: (emails: string[]) => void;
onNext: () => void;
}) {
const toast = useToast();
const input = useRef<HTMLInputElement>(null);
const errorId = useId();
const [emails, setEmails] = useState<string[]>([]);
const [draft, setDraft] = useState("");
const [role, setRole] = useState("editor");
const [error, setError] = useState<string | undefined>();
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState(false);
const commit = (text: string) => {
const found = splitEmails(text);
if (found.length) {
setEmails((was) => {
const have = new Set(was);
return [...was, ...found.filter((f) => !have.has(f))];
});
}
setDraft("");
};
const send = async (e: FormEvent) => {
e.preventDefault();
if (busy) return;
const have = new Set(emails);
const all = [...emails, ...splitEmails(draft).filter((f) => !have.has(f))];
setEmails(all);
setDraft("");
const reason = emailsProblem(all);
setError(reason);
if (reason) return input.current?.focus();
setBusy(true);
await wait(700);
setBusy(false);
onInvited(all);
setEmails([]);
};
const count = emails.length + splitEmails(draft).length;
return (
<form onSubmit={(e) => void send(e)} noValidate className="flex flex-col">
<StepHead title="Invite your team">
Free includes 3 members. Type their addresses, or share a link.
</StepHead>
<div className="mt-6">
<label className="block">
<span className="mb-1.5 flex min-h-4 items-center gap-1.5 text-xs text-muted">
Emails
{error && <FieldReason id={errorId} reason={error} />}
</span>
<span
className={cn(
"flex min-h-10 cursor-text flex-wrap items-center gap-1.5 rounded-lg bg-bg px-2 py-1.5 smooth-shadow-ring-xs focus-within:shadow-[0_0_0_1.5px_var(--accent)]",
error &&
"shadow-[0_0_0_1.5px_var(--danger)] focus-within:shadow-[0_0_0_1.5px_var(--danger)]",
)}
>
{emails.map((email) => (
<span
key={email}
className="inline-flex max-w-full items-center gap-1 rounded-md bg-surface-2 py-0.5 pr-0.5 pl-2 font-mono text-xs"
>
<span className="truncate">{email}</span>
<button
type="button"
aria-label={`Remove ${email}`}
onClick={(e) => {
e.preventDefault();
setEmails((was) => was.filter((x) => x !== email));
setError(undefined);
}}
className="grid size-5 cursor-pointer place-items-center rounded text-muted [@media(hover:hover)]:hover:text-text"
>
<X size={12} aria-hidden />
</button>
</span>
))}
<input
ref={input}
value={draft}
inputMode="email"
autoComplete="off"
autoCapitalize="none"
spellCheck={false}
aria-invalid={error ? true : undefined}
aria-describedby={error ? errorId : undefined}
placeholder={emails.length ? "" : "sam@example.com"}
onChange={(e) => {
setDraft(e.target.value);
setError(undefined);
}}
onKeyDown={(e) => {
if ((e.key === "Enter" || e.key === ",") && draft.trim()) {
e.preventDefault();
commit(draft);
} else if (e.key === "Backspace" && !draft && emails.length) {
setEmails((was) => was.slice(0, -1));
}
}}
onPaste={(e) => {
const text = e.clipboardData.getData("text");
if (!/[\s,;]/.test(text.trim())) return;
e.preventDefault();
commit(draft + text);
}}
className="min-w-[9rem] flex-1 bg-transparent px-1 py-1 font-mono text-[13px] outline-none focus-visible:!outline-none placeholder:text-placeholder"
/>
</span>
</label>
</div>
<div className="mt-3 flex flex-wrap items-center gap-2">
<div className="w-32">
<MenuSelect label="Role" value={role} onChange={setRole} options={ROLES} />
</div>
<Button type="submit" variant="outline" disabled={busy}>
<BusyContent busy={busy}>
{count > 1 ? `Send ${count} invites` : "Send invite"}
</BusyContent>
</Button>
</div>
<div className="mt-1.5">
<Button
variant="ghost"
className="-ml-2.5"
title="Makes a single-use link, valid 7 days, and copies it"
onClick={() => {
void navigator.clipboard.writeText("https://acme.test/invite/4f9c1b").catch(() => {});
setCopied(true);
toast("Invite link copied");
}}
>
<span className="inline-flex items-center gap-1.5">
{copied ? (
<Check size={15} aria-hidden className="welcome-check" />
) : (
<Link2 size={15} aria-hidden />
)}
{copied ? "Copied" : "Copy invite link"}
</span>
</Button>
</div>
<p className="mt-2.5 min-h-4 text-xs text-muted tabular-nums" aria-live="polite">
{invited.length > 0 &&
`${invited.length} ${invited.length === 1 ? "invite" : "invites"} sent.`}
</p>
<Actions>
<Button variant="primary" onClick={onNext}>
Continue
</Button>
{!invited.length && !copied && <SkipButton onClick={onNext} label="Not now" />}
</Actions>
</form>
);
}
function ListRow({
label,
hint,
checked,
onChange,
}: {
label: string;
hint: string;
checked: boolean;
onChange: (next: boolean) => void;
}) {
const hintId = useId();
return (
<label className="flex min-h-14 cursor-pointer items-center justify-between gap-4 px-4 py-3 transition-colors duration-150 ease-out [@media(hover:hover)]:hover:bg-surface-2/60">
<span className="flex min-w-0 flex-col gap-0.5">
<span className="text-sm font-medium">{label}</span>
<span id={hintId} className="text-xs text-muted">
{hint}
</span>
</span>
<Switch label={label} describedBy={hintId} checked={checked} onCheckedChange={onChange} />
</label>
);
}
/** The last question: product news and offers, a switch each, both off. Skip is a no to both. */
function EmailStep({ onNext }: { onNext: () => void }) {
const [news, setNews] = useState(false);
const [offers, setOffers] = useState(false);
const [pressed, setPressed] = useState<"continue" | "skip" | null>(null);
const answer = async (kind: "continue" | "skip") => {
if (pressed) return;
setPressed(kind);
await wait(500);
onNext();
};
return (
<div className="flex flex-col">
<StepHead title="What should we email you about?">
Pick any or none. You can change this in Settings.
</StepHead>
<div className="mt-6 overflow-hidden rounded-xl bg-surface smooth-shadow-ring-xs [&>*+*]:shadow-[inset_0_1px_0_var(--border)]">
<ListRow
label="Product news"
hint="New features and tips"
checked={news}
onChange={setNews}
/>
<ListRow label="Offers" hint="Deals on paid plans" checked={offers} onChange={setOffers} />
</div>
<Actions>
<Button variant="primary" disabled={!!pressed} onClick={() => void answer("continue")}>
<BusyContent busy={pressed === "continue"}>Open Acme</BusyContent>
</Button>
<Button variant="ghost" disabled={!!pressed} onClick={() => void answer("skip")}>
<BusyContent busy={pressed === "skip"}>Skip</BusyContent>
</Button>
</Actions>
</div>
);
}