Three-step sign-up
A sign-up flow in one card with three steps (account, workspace, invite teammates), a labelled progress bar that marks the current and finished steps, Back and Continue, and validation for each step before moving on. The workspace address fills itself from the name until edited, team size uses native radio buttons, invites can be added, removed or skipped, focus moves to each step's heading, and the last step shows a creating state and a summary.
Source
"use client";
import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from "react";
import { ArrowLeft, Check, CircleCheck, LoaderCircle, Plus, X } from "lucide-react";
import { cn } from "@/lib/utils";
export type TeamSize = "1" | "2-10" | "11-50" | "51+";
export type SignUpData = {
name: string;
email: string;
password: string;
workspace: string;
slug: string;
size: TeamSize | "";
invites: string[];
role: "editor" | "viewer";
};
export type SignUpStepsProps = {
/** Shown before the workspace address, for example "paperlark.app/". */
addressPrefix?: string;
logo?: ReactNode;
/** Called with everything once the last step is submitted. Throw to show an error. */
onComplete?: (data: SignUpData) => Promise<void> | void;
/** Prefill fields, for example from an invite link. */
defaultValues?: Partial<SignUpData>;
/** Start on a later step (0, 1 or 2), for demos or when the account already exists. */
defaultStep?: number;
className?: string;
};
const STEPS = [
{ id: "account", label: "Account", title: "Create your account" },
{ id: "workspace", label: "Workspace", title: "Set up your workspace" },
{ id: "invite", label: "Invite", title: "Invite your team" },
] as const;
const SIZES: { value: TeamSize; label: string }[] = [
{ value: "1", label: "Just me" },
{ value: "2-10", label: "2 to 10" },
{ value: "11-50", label: "11 to 50" },
{ value: "51+", label: "More than 50" },
];
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";
const toSlug = (value: string) => value.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 32);
type Errors = Partial<Record<string, string>>;
function validate(step: number, data: SignUpData): Errors {
const errors: Errors = {};
if (step === 0) {
if (!data.name.trim()) errors.name = "Enter your name.";
if (!data.email.trim()) errors.email = "Enter your work email.";
else if (!EMAIL.test(data.email.trim())) errors.email = "Enter an email like name@company.com.";
if (data.password.length < 8 || !/\d/.test(data.password)) errors.password = "Use at least 8 characters, including a number.";
}
if (step === 1) {
if (!data.workspace.trim()) errors.workspace = "Name your workspace.";
if (!/^[a-z0-9](?:[a-z0-9-]{1,30}[a-z0-9])$/.test(data.slug)) errors.slug = "Use 3 to 32 lowercase letters, numbers or hyphens.";
if (!data.size) errors.size = "Choose a team size.";
}
if (step === 2) {
data.invites.forEach((invite, index) => {
if (invite.trim() && !EMAIL.test(invite.trim())) errors[`invite-${index}`] = "Check this address.";
});
}
return errors;
}
function Field({ id, label, error, hint, children }: { id: string; label: string; error?: string; hint?: ReactNode; children: ReactNode }) {
return (
<div>
<label htmlFor={id} className="text-sm font-medium text-foreground">{label}</label>
<div className="mt-2">{children}</div>
{hint && !error && <p id={`${id}-hint`} className="mt-2 text-sm text-muted-foreground">{hint}</p>}
{error && <p id={`${id}-error`} className="mt-2 text-sm text-destructive">{error}</p>}
</div>
);
}
const input = (error?: string) =>
cn(
"h-11 w-full rounded-md border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground transition-colors",
error ? "border-destructive" : "border-input hover:border-foreground/30",
focusRing,
);
export function SignUpSteps({
addressPrefix = "paperlark.app/",
logo,
onComplete = () => new Promise((resolve) => setTimeout(resolve, 1200)),
defaultValues,
defaultStep = 0,
className,
}: SignUpStepsProps) {
const id = useId();
const headingRef = useRef<HTMLHeadingElement>(null);
const formRef = useRef<HTMLFormElement>(null);
const moved = useRef(false);
const [step, setStep] = useState(Math.min(Math.max(defaultStep, 0), STEPS.length - 1));
const [errors, setErrors] = useState<Errors>({});
const [slugEdited, setSlugEdited] = useState(Boolean(defaultValues?.slug));
const [status, setStatus] = useState<"idle" | "sending" | "done">("idle");
const [submitError, setSubmitError] = useState("");
const [data, setData] = useState<SignUpData>({
name: "", email: "", password: "", workspace: "", size: "", invites: ["", ""], role: "editor", ...defaultValues,
slug: defaultValues?.slug ?? toSlug(defaultValues?.workspace ?? ""),
});
const set = <K extends keyof SignUpData>(key: K, value: SignUpData[K]) => {
setData((current) => ({ ...current, [key]: value }));
if (errors[key as string]) setErrors((current) => ({ ...current, [key]: undefined }));
};
// After Back or Continue, put focus on the new step's heading so screen readers announce it.
useEffect(() => {
if (!moved.current) return;
headingRef.current?.focus();
}, [step, status]);
const focusFirstError = (found: Errors) => {
const first = Object.keys(found)[0];
if (!first) return;
requestAnimationFrame(() => formRef.current?.querySelector<HTMLElement>(`[data-field="${first}"]`)?.focus());
};
const advance = async (skipInvites = false) => {
const payload = skipInvites ? { ...data, invites: [] } : data;
const found = validate(step, payload);
setErrors(found);
if (Object.keys(found).length) return focusFirstError(found);
moved.current = true;
if (step < STEPS.length - 1) return setStep(step + 1);
setStatus("sending");
setSubmitError("");
try {
await onComplete({ ...payload, email: payload.email.trim(), invites: payload.invites.map((value) => value.trim()).filter(Boolean) });
setStatus("done");
} catch (cause) {
setStatus("idle");
setSubmitError(cause instanceof Error ? cause.message : "We could not create the workspace. Try again.");
}
};
const back = () => {
moved.current = true;
setErrors({});
setStep((current) => Math.max(0, current - 1));
};
const card = cn("w-full max-w-md rounded-xl bg-card p-6 text-card-foreground ring-1 ring-border sm:p-8", className);
if (status === "done") {
const invited = data.invites.filter((value) => value.trim()).length;
return (
<div className={card}>
<CircleCheck className="size-10 text-emerald-600 dark:text-emerald-400" aria-hidden="true" />
<h1 ref={headingRef} tabIndex={-1} className="mt-5 text-2xl font-semibold tracking-tight outline-none">{data.workspace} is ready</h1>
<dl className="mt-6 space-y-3 rounded-lg bg-muted/60 p-4 text-sm">
<div className="flex justify-between gap-4"><dt className="text-muted-foreground">Address</dt><dd className="truncate font-medium">{addressPrefix}{data.slug}</dd></div>
<div className="flex justify-between gap-4"><dt className="text-muted-foreground">Invites sent</dt><dd className="font-medium">{invited || "None yet"}</dd></div>
</dl>
<a href={`#${data.slug}`} className={cn("mt-6 inline-flex h-11 w-full items-center justify-center rounded-md bg-primary text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90", focusRing)}>
Open workspace
</a>
</div>
);
}
const current = STEPS[step];
const last = step === STEPS.length - 1;
return (
<div className={card}>
{logo && <div className="mb-6">{logo}</div>}
<ol aria-label="Sign-up progress" className="grid grid-cols-3 gap-2">
{STEPS.map((item, index) => {
const state = index < step ? "complete" : index === step ? "current" : "upcoming";
return (
<li key={item.id} aria-current={state === "current" ? "step" : undefined}>
<span className={cn("block h-1 rounded-full motion-safe:transition-colors motion-safe:duration-300", state === "upcoming" ? "bg-muted" : "bg-primary")} />
<span className={cn("mt-2 flex items-center gap-1 text-xs font-medium", state === "upcoming" ? "text-muted-foreground" : "text-foreground")}>
{state === "complete" && <Check className="size-3.5" aria-hidden="true" />}
{item.label}
<span className="sr-only">{state === "complete" ? ", done" : state === "current" ? ", current step" : ""}</span>
</span>
</li>
);
})}
</ol>
<h1 ref={headingRef} tabIndex={-1} className="mt-8 text-2xl font-semibold tracking-tight outline-none">{current.title}</h1>
<form
ref={formRef}
noValidate
onSubmit={(event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
void advance();
}}
className="mt-6 space-y-5"
>
{step === 0 && (
<>
<Field id={`${id}-name`} label="Full name" error={errors.name}>
<input data-field="name" id={`${id}-name`} autoComplete="name" value={data.name} onChange={(event) => set("name", event.target.value)}
aria-invalid={errors.name ? true : undefined} aria-describedby={errors.name ? `${id}-name-error` : undefined} className={input(errors.name)} />
</Field>
<Field id={`${id}-email`} label="Work email" error={errors.email}>
<input data-field="email" id={`${id}-email`} type="email" inputMode="email" autoComplete="email" placeholder="name@company.com" value={data.email}
onChange={(event) => set("email", event.target.value)} aria-invalid={errors.email ? true : undefined}
aria-describedby={errors.email ? `${id}-email-error` : undefined} className={input(errors.email)} />
</Field>
<Field id={`${id}-password`} label="Password" error={errors.password} hint="At least 8 characters, including a number.">
<input data-field="password" id={`${id}-password`} type="password" autoComplete="new-password" value={data.password}
onChange={(event) => set("password", event.target.value)} aria-invalid={errors.password ? true : undefined}
aria-describedby={errors.password ? `${id}-password-error` : `${id}-password-hint`} className={input(errors.password)} />
</Field>
</>
)}
{step === 1 && (
<>
<Field id={`${id}-workspace`} label="Workspace name" error={errors.workspace}>
<input data-field="workspace" id={`${id}-workspace`} autoComplete="organization" placeholder="Northvane" value={data.workspace}
onChange={(event) => {
set("workspace", event.target.value);
if (!slugEdited) set("slug", toSlug(event.target.value));
}}
aria-invalid={errors.workspace ? true : undefined} aria-describedby={errors.workspace ? `${id}-workspace-error` : undefined} className={input(errors.workspace)} />
</Field>
<Field id={`${id}-slug`} label="Workspace address" error={errors.slug}>
<div className={cn("flex h-11 overflow-hidden rounded-md border bg-background has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring", errors.slug ? "border-destructive" : "border-input")}>
<span className="flex items-center bg-muted px-3 text-sm text-muted-foreground">{addressPrefix}</span>
<input data-field="slug" id={`${id}-slug`} value={data.slug} spellCheck={false} autoCapitalize="none"
onChange={(event) => {
setSlugEdited(true);
set("slug", toSlug(event.target.value) + (event.target.value.endsWith("-") ? "-" : ""));
}}
aria-invalid={errors.slug ? true : undefined} aria-describedby={errors.slug ? `${id}-slug-error` : undefined}
className="min-w-0 flex-1 bg-transparent px-3 text-sm text-foreground outline-none" />
</div>
</Field>
<fieldset>
<legend className="text-sm font-medium text-foreground">Team size</legend>
<div className="mt-2 grid grid-cols-2 gap-2">
{SIZES.map((option, index) => (
<label
key={option.value}
className={cn(
"flex h-11 cursor-pointer items-center gap-2.5 rounded-md px-3 text-sm ring-1 transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring",
data.size === option.value ? "bg-accent font-medium text-foreground ring-foreground" : "text-foreground ring-border hover:bg-accent/60",
)}
>
<input data-field={index === 0 ? "size" : undefined} type="radio" name={`${id}-size`} value={option.value} checked={data.size === option.value}
onChange={() => set("size", option.value)} className="size-4 accent-primary"
aria-describedby={errors.size ? `${id}-size-error` : undefined} />
{option.label}
</label>
))}
</div>
{errors.size && <p id={`${id}-size-error`} className="mt-2 text-sm text-destructive">{errors.size}</p>}
</fieldset>
</>
)}
{step === 2 && (
<>
<fieldset className="space-y-2">
<legend className="text-sm font-medium text-foreground">Email addresses</legend>
{data.invites.map((invite, index) => {
const error = errors[`invite-${index}`];
return (
<div key={index}>
<div className="flex gap-2">
<input data-field={`invite-${index}`} type="email" inputMode="email" aria-label={`Teammate ${index + 1} email`}
placeholder="name@company.com"
value={invite}
onChange={(event) => set("invites", data.invites.map((value, i) => (i === index ? event.target.value : value)))}
aria-invalid={error ? true : undefined} aria-describedby={error ? `${id}-invite-${index}-error` : undefined}
className={input(error)} />
{data.invites.length > 1 && (
<button type="button" aria-label={`Remove teammate ${index + 1}`}
onClick={() => set("invites", data.invites.filter((_, i) => i !== index))}
className={cn("grid size-11 shrink-0 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", focusRing)}>
<X className="size-4" aria-hidden="true" />
</button>
)}
</div>
{error && <p id={`${id}-invite-${index}-error`} className="mt-1.5 text-sm text-destructive">{error}</p>}
</div>
);
})}
{data.invites.length < 10 && (
<button type="button" onClick={() => set("invites", [...data.invites, ""])}
className={cn("inline-flex h-9 items-center gap-1.5 rounded-md px-2 text-sm font-medium text-foreground transition-colors hover:bg-accent", focusRing)}>
<Plus className="size-4" aria-hidden="true" /> Add another
</button>
)}
</fieldset>
<Field id={`${id}-role`} label="They can">
<select id={`${id}-role`} value={data.role} onChange={(event) => set("role", event.target.value as SignUpData["role"])} className={input()}>
<option value="editor">Edit and comment</option>
<option value="viewer">View and comment</option>
</select>
</Field>
</>
)}
{submitError && <p role="alert" className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">{submitError}</p>}
<div className="flex items-center gap-2 pt-3">
{step > 0 && (
<button type="button" onClick={back} disabled={status === "sending"}
className={cn("inline-flex h-11 items-center gap-1.5 rounded-md px-3 text-sm font-medium text-foreground transition-colors hover:bg-accent disabled:opacity-50", focusRing)}>
<ArrowLeft className="size-4" aria-hidden="true" /> Back
</button>
)}
{last && (
<button type="button" disabled={status === "sending"} onClick={() => void advance(true)}
className={cn("ml-auto inline-flex h-11 items-center rounded-md px-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50", focusRing)}>
Skip for now
</button>
)}
<button type="submit" disabled={status === "sending"}
className={cn("inline-flex h-11 items-center justify-center gap-2 rounded-md bg-primary px-5 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-70", last ? "" : "ml-auto", focusRing)}>
{status === "sending" && <LoaderCircle className="size-4 motion-safe:animate-spin" aria-hidden="true" />}
{last ? (status === "sending" ? "Creating…" : "Create workspace") : "Continue"}
</button>
</div>
</form>
</div>
);
}
