Recorded demo
Source
/**
* Waitlist form - original UI Stacks free component, MIT licensed.
* Source: public page https://uistacks.dev/components/waitlist-form (code block reproduced verbatim, unmodified).
* Upstream project: https://github.com/nazmijavier/uistacks
*/
"use client";
import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type FormEvent, type ReactNode } from "react";
import { AnimatePresence, animate, motion, useAnimationControls, useReducedMotion } from "motion/react";
import { Check, Copy, Loader2 } from "lucide-react";
export interface WaitlistResult {
/** Their place in line. Defaults to `count + 1`. */
position?: number;
/** Their personal share link. Defaults to `shareUrl` with a code made from the address. */
link?: string;
}
export interface WaitlistFormProps {
title?: ReactNode;
description?: ReactNode;
placeholder?: string;
buttonLabel?: string;
/** People already waiting; shown under the field, and the next person's place is this plus one. Default 1,283. */
count?: number;
/** Up to three names for the small avatar row next to the count (first letters only). */
people?: string[];
/** Called with the address once it passes the format check. A promise keeps the button busy; resolve with a
* position and link from your backend, or reject to show its message. Without it the form waits a moment. */
onJoin?: (email: string) => Promise<WaitlistResult | void> | WaitlistResult | void;
/** The base of the share link. Default "https://uistacks.dev/waitlist". */
shareUrl?: string;
/** The line under the place number. */
joinedNote?: ReactNode;
/** Start in the joined state (with `defaultEmail`), e.g. for a returning visitor. */
defaultStatus?: "idle" | "joined";
defaultEmail?: string;
className?: string;
}
type Status = "idle" | "sending" | "joined";
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const EASE = [0.22, 1, 0.36, 1] as const;
const spring = { type: "spring", stiffness: 420, damping: 34 } as const;
const press = { type: "spring", stiffness: 600, damping: 26 } as const;
const noSubscribe = () => () => {};
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]";
const btn =
"relative isolate inline-flex h-9 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-4 text-[14px] font-medium leading-5 before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:opacity-0 before:transition-opacity";
const primary = `${btn} bg-[image:var(--grad-primary)] text-[var(--inverse-fg)] shadow-[var(--shadow-btn-primary)] before:bg-[var(--inverse-fg)] hover:before:opacity-[0.08] active:before:opacity-[0.14] ${focusRing}`;
const secondary = `${btn} bg-surface text-fg shadow-[var(--shadow-btn-secondary)] before:bg-fg hover:before:opacity-[0.04] active:before:opacity-[0.08] dark:bg-raised ${focusRing}`;
const fmt = (n: number) => n.toLocaleString("en-US");
/** A short, stable referral code from the address (same address, same link). */
function refCode(email: string) {
let h = 2166136261;
for (const ch of email.toLowerCase()) h = Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0;
return h.toString(36).slice(0, 6).padStart(6, "0");
}
/** Eases its height to fit its content, so swapping the form for the joined state never jumps. */
function AutoHeight({ children, reduce }: { children: ReactNode; reduce: boolean }) {
const inner = useRef<HTMLDivElement>(null);
const [h, setH] = useState<number | "auto">("auto");
useLayoutEffect(() => {
const el = inner.current;
if (!el) return;
const ro = new ResizeObserver(() => setH(el.offsetHeight + 12));
ro.observe(el);
return () => ro.disconnect();
}, []);
return (
<motion.div initial={false} animate={{ height: h }} transition={reduce ? { duration: 0 } : spring} className="-m-1.5 overflow-hidden p-1.5">
<div ref={inner}>{children}</div>
</motion.div>
);
}
/** The place number: eases down from a little higher and lands on the real place, in tabular figures. */
function Place({ value, reduce }: { value: number; reduce: boolean }) {
const ref = useRef<HTMLSpanElement>(null);
useEffect(() => {
const el = ref.current;
if (!el) return;
if (reduce) return void (el.textContent = fmt(value));
const from = value + Math.max(24, Math.round(value * 0.2));
const c = animate(from, value, { duration: 1.2, delay: 0.15, ease: EASE, onUpdate: (n) => (el.textContent = fmt(Math.round(n))) });
return () => c.stop();
}, [value, reduce]);
return (
<span ref={ref} className="tabular-nums">
{fmt(value)}
</span>
);
}
/**
* A waitlist card: heading, one line, the email field with its Join button, and how many people are already waiting.
* After a valid address it shows the person's place in line with the number easing into place, and a personal share
* link with a Copy button.
*/
export function WaitlistForm({
title = "Save your seat",
description = "We open the beta to small groups each week. Leave your email and we'll write when your turn comes.",
placeholder = "you@company.com",
buttonLabel = "Join waitlist",
count = 1283,
people = ["Maya Collins", "Ethan Brooks", "Ava Thompson"],
onJoin,
shareUrl = "https://uistacks.dev/waitlist",
joinedNote = "Every friend who joins with your link moves you up five places.",
defaultStatus = "idle",
defaultEmail = "",
className = "",
}: WaitlistFormProps) {
const prefers = useReducedMotion();
const mounted = useSyncExternalStore(noSubscribe, () => true, () => false);
const reduce = mounted && Boolean(prefers);
const id = useId();
const input = useRef<HTMLInputElement>(null);
const heading = useRef<HTMLHeadingElement>(null);
const shake = useAnimationControls();
const [email, setEmail] = useState(defaultEmail);
const [status, setStatus] = useState<Status>(defaultStatus === "joined" && defaultEmail ? "joined" : "idle");
const [error, setError] = useState("");
const [result, setResult] = useState<Required<WaitlistResult>>(() => ({ position: count + 1, link: `${shareUrl}?ref=${refCode(defaultEmail)}` }));
const [copied, setCopied] = useState(0);
const [fresh, setFresh] = useState(false);
// Focus follows the swap to the joined heading (not on first render for a returning visitor).
useEffect(() => {
if (status === "joined" && fresh) heading.current?.focus({ preventScroll: true });
}, [status, fresh]);
// "Copied" stays a moment, then the button reads Copy again.
useEffect(() => {
if (!copied) return;
const t = window.setTimeout(() => setCopied(0), 1800);
return () => window.clearTimeout(t);
}, [copied]);
const fail = (text: string) => {
setError(text);
input.current?.focus();
if (!reduce) shake.start({ x: [0, -7, 6, -4, 2, 0], transition: { duration: 0.38, ease: "easeOut" } });
};
const submit = async (e: FormEvent) => {
e.preventDefault();
if (status === "sending") return;
const value = email.trim();
if (!value) return fail("Enter your email address.");
if (!EMAIL.test(value)) return fail("That address looks incomplete. Check it and try again.");
setError("");
setStatus("sending");
try {
const r = (await (onJoin ? onJoin(value) : new Promise<void>((res) => setTimeout(res, 1000)))) || {};
setEmail(value);
setResult({ position: r.position ?? count + 1, link: r.link ?? `${shareUrl}?ref=${refCode(value)}` });
setFresh(true);
setStatus("joined");
} catch (err) {
setStatus("idle");
fail(err instanceof Error && err.message ? err.message : "We couldn't add you. Try again in a moment.");
}
};
const copy = async () => {
try {
await navigator.clipboard.writeText(result.link);
} catch {
// Clipboard blocked (an iframe, an old browser): select the link so Cmd/Ctrl+C still works.
document.getElementById(`${id}-link`)?.focus();
(document.getElementById(`${id}-link`) as HTMLInputElement | null)?.select();
}
setCopied((n) => n + 1);
};
const swap = reduce
? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }
: { initial: { opacity: 0, y: 10, filter: "blur(3px)" }, animate: { opacity: 1, y: 0, filter: "blur(0px)" }, exit: { opacity: 0, y: -10, filter: "blur(3px)" } };
const sending = status === "sending";
return (
<section aria-labelledby={`${id}-title`} className={`w-full max-w-[480px] rounded-[20px] bg-surface p-5 shadow-[var(--shadow-card)] sm:p-6 ${className}`}>
<p role="status" aria-live="polite" className="sr-only">
{sending ? "Joining" : status === "joined" ? `You're number ${fmt(result.position)} on the waitlist.` : ""}
{copied ? " Link copied." : ""}
</p>
<AutoHeight reduce={reduce}>
<AnimatePresence mode="popLayout" initial={false}>
{status === "joined" ? (
<motion.div key="joined" {...swap} transition={reduce ? { duration: 0.15 } : spring}>
<motion.span
aria-hidden
initial={reduce ? false : { scale: 0.4, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", stiffness: 600, damping: 18, delay: 0.05 }}
className="grid size-10 place-items-center rounded-full bg-[image:var(--grad-primary)] text-[var(--inverse-fg)] shadow-[var(--shadow-btn-primary)]"
>
<Check size={20} strokeWidth={1.5} />
</motion.span>
<p className="mt-4 text-[13px] font-medium leading-5 text-fg-muted">Your place in line</p>
<h3 ref={heading} tabIndex={-1} id={`${id}-title`} className="mt-0.5 text-[28px] font-medium leading-9 tracking-[-0.03em] text-fg outline-none">
You're number <Place value={result.position} reduce={reduce || !fresh} />
</h3>
<p className="mt-2 text-pretty text-[14px] leading-5 text-fg-muted">
We'll write to <span className="break-all font-medium text-fg">{email}</span> when your seat opens. {joinedNote}
</p>
<div className="mt-5 flex h-11 items-center gap-1 rounded-full bg-subtle p-1 pl-4 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--fg)_8%,transparent)]">
<label htmlFor={`${id}-link`} className="sr-only">
Your share link
</label>
<input
id={`${id}-link`}
readOnly
value={result.link.replace(/^https?:\/\//, "")}
onFocus={(e) => e.currentTarget.select()}
className="h-full min-w-0 flex-1 truncate bg-transparent text-[14px] text-fg outline-none"
/>
<motion.button type="button" onClick={copy} whileTap={reduce ? undefined : { scale: 0.94 }} transition={press} className={secondary}>
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={copied ? "done" : "copy"}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.5 }}
transition={{ type: "spring", stiffness: 600, damping: 22 }}
className="grid place-items-center"
>
{copied ? <Check size={16} strokeWidth={1.5} aria-hidden /> : <Copy size={16} strokeWidth={1.5} aria-hidden />}
</motion.span>
</AnimatePresence>
{copied ? "Copied" : "Copy"}
</motion.button>
</div>
</motion.div>
) : (
<motion.div key="form" {...swap} transition={reduce ? { duration: 0.15 } : spring}>
<h3 id={`${id}-title`} className="text-[18px] font-medium leading-7 tracking-[-0.015em] text-fg">
{title}
</h3>
{description && <p className="mt-1 text-pretty text-[14px] leading-5 text-fg-muted">{description}</p>}
<form noValidate onSubmit={submit} className="mt-5">
<label htmlFor={`${id}-email`} className="sr-only">
Email address
</label>
<motion.div
animate={shake}
className={`flex h-11 items-center gap-1 rounded-full bg-surface p-1 pl-4 transition-shadow dark:bg-subtle ${
error
? "shadow-[inset_0_0_0_1px_var(--danger)]"
: "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--fg)_14%,transparent)] focus-within:shadow-[inset_0_0_0_1px_var(--select),0_0_0_3px_color-mix(in_srgb,var(--select)_18%,transparent)]"
}`}
>
<input
ref={input}
id={`${id}-email`}
type="email"
inputMode="email"
autoComplete="email"
spellCheck={false}
value={email}
readOnly={sending}
placeholder={placeholder}
aria-invalid={Boolean(error) || undefined}
aria-describedby={error ? `${id}-error` : `${id}-count`}
onChange={(e) => {
setEmail(e.target.value);
if (error) setError("");
}}
className="h-full min-w-0 flex-1 bg-transparent text-[14px] text-fg outline-none placeholder:text-fg-subtle"
/>
<motion.button type="submit" aria-busy={sending || undefined} whileTap={reduce ? undefined : { scale: 0.94 }} transition={press} className={primary}>
{sending && <Loader2 size={16} strokeWidth={1.5} aria-hidden className="animate-spin" />}
{sending ? "Joining" : buttonLabel}
</motion.button>
</motion.div>
<AnimatePresence initial={false}>
{error && (
<motion.p
id={`${id}-error`}
role="alert"
initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
animate={reduce ? { opacity: 1 } : { opacity: 1, height: "auto" }}
exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
transition={spring}
className="overflow-hidden"
>
<span className="block pt-2 pl-4 text-[13px] leading-5 text-danger">{error}</span>
</motion.p>
)}
</AnimatePresence>
</form>
<div id={`${id}-count`} className="mt-4 flex items-center gap-2.5">
{people.length > 0 && (
<span aria-hidden className="flex -space-x-1.5">
{people.slice(0, 3).map((p, i) => (
<span key={i} className="grid size-6 place-items-center rounded-full bg-muted text-[12px] font-medium text-fg-muted ring-2 ring-[var(--surface)]">
{p.trim().charAt(0).toUpperCase()}
</span>
))}
</span>
)}
<span className="text-[13px] leading-5 text-fg-muted">
<span className="font-medium tabular-nums text-fg">{fmt(count)}</span> people are already waiting
</span>
</div>
</motion.div>
)}
</AnimatePresence>
</AutoHeight>
</section>
);
}
Usage
Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。
Package dependencies · lucide-react、motion、react
Props
| Name | Type | Description |
|---|---|---|
`title / description / placeholder / buttonLabel` | `ReactNode / ReactNode / string / string` | The card's copy. |
`count / people` | `number / string[]` | People already waiting (default 1,283; the next place is count + 1) and up to three names for the avatar row. |
`onJoin` | `(email) => Promise<{ position?; link? } \| void>` | Busy while it runs; resolve with the real place and link, or reject to show its message. |
`shareUrl` | `string` | Base of the share link; a stable code from the address is added. Default https://example.com/waitlist. |
`joinedNote` | `ReactNode` | The line under the place number. |
`defaultStatus / defaultEmail` | `"idle" \| "joined" / string` | Open in the joined state for a returning visitor. |