Stepper
Numbered steps across the top or down the side, with done, current, loading and error states. Controlled or uncontrolled, linear or in any order, with arrow-key navigation. For checkouts, form wizards and onboarding.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper.json5 examples below; each installs the component with it. They wear whichever DressCode theme you install.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper-horizontal.jsoncomponents/dresscode/stepper-horizontal.tsx
"use client"
// A checkout's steps across the top, with a title and a short description each. In a narrow container
// (a phone) the row collapses to "Step 2 of 4" with the current title and a segmented bar.
// Linear: you can go back to any step, and forward only to steps you have already filled in.
import * as React from "react"
import { ArrowLeft, ArrowRight, CreditCard, FileText, Landmark, Layers, Minus, NotebookText, PackageCheck, PenTool, Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
import {
Stepper,
StepperDescription,
StepperIndicator,
StepperItem,
StepperSeparator,
StepperTitle,
StepperTrigger,
} from "@/components/ui/stepper"
const PRODUCTS = [
{ id: "notebook", icon: NotebookText, name: "Linen notebook, A5", detail: "Dot grid · Sage", price: 18 },
{ id: "mat", icon: Layers, name: "Felt desk mat, large", detail: "Charcoal · 90 × 40 cm", price: 46 },
{ id: "pen", icon: PenTool, name: "Brass fountain pen", detail: "Fine nib · 6 cartridges", price: 54 },
]
const ADDRESSES = [
{ id: "home", label: "Home", lines: "Maya Lindqvist, 214 Alder Street, Portland, OR 97205" },
{ id: "studio", label: "Studio", lines: "Fernwood Studio, 88 Mill Road, Suite 3, Portland, OR 97209" },
]
const DELIVERY = [
{ id: "standard", label: "Standard", price: 0, speed: "3 to 5 working days", arrives: "Nov 27 to Dec 1" },
{ id: "express", label: "Express", price: 12, speed: "Next working day", arrives: "Wednesday, Nov 25" },
]
const PAYMENT = [
{ id: "card", icon: CreditCard, label: "Card ending 2817", note: "Expires 08/28. Billing address: Home." },
{ id: "transfer", icon: Landmark, label: "Bank transfer", note: "We ship once the transfer clears, usually 1 to 2 working days." },
{ id: "invoice", icon: FileText, label: "Pay by invoice", note: "Net 30 for business accounts. The invoice goes to your email." },
]
const TAX_RATE = 0.08
const money = (n: number) => n.toLocaleString("en-US", { style: "currency", currency: "USD" })
export default function StepperHorizontal() {
const [step, setStep] = React.useState(2)
const [furthest, setFurthest] = React.useState(2)
const [qty, setQty] = React.useState<Record<string, number>>({ notebook: 2, mat: 1, pen: 1 })
const [address, setAddress] = React.useState("home")
const [delivery, setDelivery] = React.useState("standard")
const [payment, setPayment] = React.useState("card")
const [placing, setPlacing] = React.useState(false)
const [placed, setPlaced] = React.useState(false)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
const doneHeading = React.useRef<HTMLHeadingElement>(null)
React.useEffect(() => () => clearTimeout(timer.current), [])
React.useEffect(() => {
if (placed) doneHeading.current?.focus()
}, [placed])
const count = PRODUCTS.reduce((n, p) => n + qty[p.id], 0)
const subtotal = PRODUCTS.reduce((n, p) => n + qty[p.id] * p.price, 0)
const shipping = DELIVERY.find((d) => d.id === delivery)!
const tax = Math.round(subtotal * TAX_RATE * 100) / 100
const total = subtotal + shipping.price + tax
const steps = [
{ title: "Cart", description: `${count} items` },
{ title: "Shipping", description: "Address and speed" },
{ title: "Payment", description: "Card or transfer" },
{ title: "Review", description: "Place your order" },
]
function go(to: number) {
setStep(to)
setFurthest((f) => Math.max(f, to))
}
function placeOrder() {
setPlacing(true)
timer.current = setTimeout(() => {
setPlacing(false)
setPlaced(true)
}, 1400)
}
function startOver() {
setPlaced(false)
setStep(1)
setFurthest(1)
}
const current = steps[step - 1]
return (
<div className="@container w-full max-w-4xl">
<Card className="gap-0 py-0">
<div className="border-b border-border px-4 py-5 @md:px-6">
{/* Narrow containers: the current step and a segmented bar instead of the full row. */}
<div aria-hidden="true" className="@2xl:hidden">
<div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
<span>{placed ? "Order placed" : `Step ${step} of ${steps.length}`}</span>
{!placed && step < steps.length ? <span>Next: {steps[step].title}</span> : null}
</div>
<p className="mt-1 text-base font-semibold">{placed ? "Thank you" : current.title}</p>
<div className="mt-3 flex gap-1.5">
{steps.map((s, i) => (
<span key={s.title} className={cn("h-1.5 flex-1 rounded-full bg-primary/15 transition-colors", (placed || i < step) && "bg-primary")} />
))}
</div>
</div>
<Stepper aria-label="Checkout" value={step} onValueChange={go} linear className="hidden @2xl:flex">
{steps.map((s, i) => (
<StepperItem key={s.title} step={i + 1} completed={placed || i + 1 < furthest} loading={placing && i + 1 === steps.length}>
<StepperTrigger disabled={placing || placed}>
<StepperIndicator />
<StepperTitle>{s.title}</StepperTitle>
<StepperDescription>{s.description}</StepperDescription>
</StepperTrigger>
<StepperSeparator />
</StepperItem>
))}
</Stepper>
<p className="sr-only" aria-live="polite">
{placed ? "Order placed." : `Step ${step} of ${steps.length}: ${current.title}`}
</p>
</div>
{placed ? (
<div className="flex flex-col items-center px-6 py-12 text-center">
<span className="flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary">
<PackageCheck className="size-6" aria-hidden="true" />
</span>
<h2 ref={doneHeading} tabIndex={-1} className="mt-4 text-lg font-semibold outline-none">
Order FS-20418 is confirmed
</h2>
<p className="mt-1 max-w-sm text-sm text-muted-foreground">
A receipt is on its way to maya@example.com. {shipping.label} delivery arrives {shipping.arrives}.
</p>
<Button variant="outline" className="mt-6" onClick={startOver}>
Start a new order
</Button>
</div>
) : (
<>
<section aria-labelledby="checkout-step" className="px-4 py-6 @md:px-6">
<h2 id="checkout-step" className="text-base font-semibold">
{["Your cart", "Where should we send it?", "How would you like to pay?", "Check your order"][step - 1]}
</h2>
{step === 1 ? (
<ul className="mt-4 divide-y divide-border">
{PRODUCTS.map((p) => (
<li key={p.id} className="flex items-center gap-3 py-3 first:pt-0 last:pb-0 @md:gap-4">
<span className="hidden size-11 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground @sm:flex">
<p.icon className="size-5" aria-hidden="true" />
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{p.name}</p>
<p className="truncate text-xs text-muted-foreground">{p.detail}</p>
</div>
<div className="flex items-center gap-1" role="group" aria-label={`Quantity of ${p.name}`}>
<Button
variant="outline"
size="icon-sm"
aria-label="One fewer"
disabled={qty[p.id] <= 1}
onClick={() => setQty((q) => ({ ...q, [p.id]: q[p.id] - 1 }))}
>
<Minus />
</Button>
<span className="w-6 text-center text-sm tabular-nums" aria-live="polite">
{qty[p.id]}
</span>
<Button variant="outline" size="icon-sm" aria-label="One more" onClick={() => setQty((q) => ({ ...q, [p.id]: q[p.id] + 1 }))}>
<Plus />
</Button>
</div>
<p className="w-16 text-right text-sm font-medium tabular-nums">{money(qty[p.id] * p.price)}</p>
</li>
))}
</ul>
) : null}
{step === 2 ? (
<div className="mt-4 grid gap-6 @2xl:grid-cols-2">
<ChoiceGroup legend="Ship to" value={address} onChange={setAddress} options={ADDRESSES.map((a) => ({ id: a.id, label: a.label, note: a.lines }))} />
<ChoiceGroup
legend="Delivery"
value={delivery}
onChange={setDelivery}
options={DELIVERY.map((d) => ({ id: d.id, label: d.label, note: `${d.speed}, arrives ${d.arrives}`, aside: d.price ? money(d.price) : "Free" }))}
/>
</div>
) : null}
{step === 3 ? (
<div className="mt-4 max-w-xl">
<ChoiceGroup legend="Payment method" hideLegend value={payment} onChange={setPayment} options={PAYMENT} />
</div>
) : null}
{step === 4 ? (
<div className="mt-4 grid gap-6 @2xl:grid-cols-[minmax(0,1fr)_16rem]">
<dl className="divide-y divide-border rounded-lg border border-border text-sm">
{[
{ term: "Items", detail: PRODUCTS.map((p) => `${qty[p.id]} × ${p.name}`).join(", "), to: 1 },
{ term: "Ship to", detail: ADDRESSES.find((a) => a.id === address)!.lines, to: 2 },
{ term: "Delivery", detail: `${shipping.label}, arrives ${shipping.arrives}`, to: 2 },
{ term: "Payment", detail: PAYMENT.find((p) => p.id === payment)!.label, to: 3 },
].map((row) => (
<div key={row.term} className="flex items-start gap-3 px-3 py-2.5">
<dt className="w-20 shrink-0 text-muted-foreground">{row.term}</dt>
<dd className="min-w-0 flex-1">{row.detail}</dd>
<dd className="shrink-0">
<Button variant="link" size="sm" className="h-5 px-0" onClick={() => setStep(row.to)} disabled={placing}>
Change<span className="sr-only"> {row.term.toLowerCase()}</span>
</Button>
</dd>
</div>
))}
</dl>
<dl className="space-y-2 text-sm">
<div className="flex justify-between">
<dt className="text-muted-foreground">Subtotal</dt>
<dd className="tabular-nums">{money(subtotal)}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Shipping</dt>
<dd className="tabular-nums">{shipping.price ? money(shipping.price) : "Free"}</dd>
</div>
<div className="flex justify-between">
<dt className="text-muted-foreground">Sales tax (8%)</dt>
<dd className="tabular-nums">{money(tax)}</dd>
</div>
<div className="flex justify-between border-t border-border pt-2 font-semibold">
<dt>Total</dt>
<dd className="tabular-nums">{money(total)}</dd>
</div>
</dl>
</div>
) : null}
</section>
<div className="flex flex-col gap-3 border-t border-border bg-muted/50 px-4 py-4 @md:flex-row @md:items-center @md:justify-between @md:px-6">
<p className="text-sm">
<span className="text-muted-foreground">{step === 1 ? "Subtotal" : "Total"} </span>
<span className="font-semibold tabular-nums">{money(step === 1 ? subtotal : total)}</span>
{step === 1 ? <span className="text-muted-foreground"> · shipping and tax next</span> : null}
</p>
<div className="flex gap-2">
{step > 1 ? (
<Button variant="outline" className="flex-1 @md:flex-none" onClick={() => setStep(step - 1)} disabled={placing}>
<ArrowLeft data-icon="inline-start" />
Back
</Button>
) : null}
{step < steps.length ? (
<Button className="flex-1 @md:flex-none" onClick={() => go(step + 1)}>
Continue to {steps[step].title.toLowerCase()}
<ArrowRight data-icon="inline-end" />
</Button>
) : (
<Button className="flex-1 @md:flex-none" onClick={placeOrder} disabled={placing}>
{placing ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
{placing ? "Placing order…" : `Place order · ${money(total)}`}
</Button>
)}
</div>
</div>
</>
)}
</Card>
</div>
)
}
type Choice = { id: string; label: string; note: string; aside?: string; icon?: React.ComponentType<{ className?: string }> }
/** A radio group drawn as bordered cards: the whole card is the label. */
function ChoiceGroup({
legend,
hideLegend,
value,
onChange,
options,
}: {
legend: string
hideLegend?: boolean
value: string
onChange: (id: string) => void
options: Choice[]
}) {
return (
<fieldset className="min-w-0">
<legend className={cn("mb-2 text-sm font-medium", hideLegend && "sr-only")}>{legend}</legend>
<RadioGroup value={value} onValueChange={(v) => onChange(String(v))} className="gap-2">
{options.map((o) => (
<label
key={o.id}
className="flex cursor-pointer items-start gap-3 rounded-lg border border-border p-3 transition-colors hover:bg-muted/50 has-data-checked:border-primary has-data-checked:bg-primary/5"
>
<RadioGroupItem value={o.id} className="mt-0.5" />
{o.icon ? <o.icon className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}
<span className="min-w-0 flex-1">
<span className="block text-sm font-medium">{o.label}</span>
<span className="block text-xs text-muted-foreground">{o.note}</span>
</span>
{o.aside ? <span className="text-sm font-medium tabular-nums">{o.aside}</span> : null}
</label>
))}
</RadioGroup>
</fieldset>
)
}npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper-vertical.jsoncomponents/dresscode/stepper-vertical.tsx
"use client"
// An onboarding checklist down the side: each step says what it is for, and the current step opens
// its form or action right under it. Linear: done steps reopen, later ones wait for the ones before.
import * as React from "react"
import { Landmark, PartyPopper, Send, Upload, Users } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Progress } from "@/components/ui/progress"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
import {
Stepper,
StepperContent,
StepperDescription,
StepperIndicator,
StepperItem,
StepperSeparator,
StepperTitle,
StepperTrigger,
} from "@/components/ui/stepper"
const STEPS = [
{ title: "Add your business details", description: "Your name and tax number appear on every invoice." },
{ title: "Connect a bank account", description: "Client payments land here, two working days after they pay." },
{ title: "Import your clients", description: "Bring your client list over from a spreadsheet." },
{ title: "Brand your invoices", description: "An accent color and a note for the footer." },
{ title: "Send your first invoice", description: "Send a test to yourself first if you like." },
]
const ACCENTS = [
{ id: "1", name: "Accent 1", className: "bg-(--chart-1)" },
{ id: "2", name: "Accent 2", className: "bg-(--chart-2)" },
{ id: "3", name: "Accent 3", className: "bg-(--chart-3)" },
{ id: "4", name: "Accent 4", className: "bg-(--chart-4)" },
{ id: "5", name: "Accent 5", className: "bg-(--chart-5)" },
]
export default function StepperVertical() {
const [step, setStep] = React.useState(2)
const [done, setDone] = React.useState([true, false, false, false, false])
const [busy, setBusy] = React.useState<number | null>(null)
const [business, setBusiness] = React.useState({ name: "Fernwood Studio", tax: "84-2193706" })
const [imported, setImported] = React.useState<string | null>(null)
const [accent, setAccent] = React.useState("1")
const [footer, setFooter] = React.useState("Thank you for your business.")
const fileInput = React.useRef<HTMLInputElement>(null)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(timer.current), [])
const doneCount = done.filter(Boolean).length
const allDone = doneCount === STEPS.length
/** Mark a step done and open the first one still to do. */
function complete(s: number) {
const next = done.map((d, i) => d || i === s - 1)
setDone(next)
const todo = next.findIndex((d) => !d)
if (todo !== -1) setStep(todo + 1)
}
/** The same, after a pretend round trip to the server. */
function completeLater(s: number) {
setBusy(s)
timer.current = setTimeout(() => {
setBusy(null)
complete(s)
}, 1400)
}
return (
<Card className="w-full max-w-xl">
<CardHeader>
<CardTitle>{allDone ? "You're all set" : "Get started with Orbit"}</CardTitle>
<CardDescription>
{allDone ? "Orbit is ready for your first real invoice." : `${doneCount} of ${STEPS.length} done · about ${(STEPS.length - doneCount) * 2} minutes left`}
</CardDescription>
<Progress value={(doneCount / STEPS.length) * 100} aria-label="Setup progress" className="mt-3" />
</CardHeader>
<CardContent>
<Stepper aria-label="Setup checklist" orientation="vertical" value={step} onValueChange={setStep} linear>
{STEPS.map((s, i) => {
const n = i + 1
return (
<StepperItem key={s.title} step={n} completed={done[i]} loading={busy === n} className="pb-6">
<StepperSeparator />
<StepperTrigger disabled={busy !== null}>
<StepperIndicator />
<StepperTitle>{s.title}</StepperTitle>
<StepperDescription>{s.description}</StepperDescription>
</StepperTrigger>
<StepperContent>
{n === 1 ? (
<form
className="grid gap-3"
onSubmit={(e) => {
e.preventDefault()
complete(1)
}}
>
<div className="grid gap-3 sm:grid-cols-2">
<div className="grid gap-1.5">
<Label htmlFor="ob-name">Business name</Label>
<Input id="ob-name" value={business.name} onChange={(e) => setBusiness({ ...business, name: e.target.value })} required />
</div>
<div className="grid gap-1.5">
<Label htmlFor="ob-tax">Tax number</Label>
<Input id="ob-tax" value={business.tax} onChange={(e) => setBusiness({ ...business, tax: e.target.value })} />
</div>
</div>
<div>
<Button type="submit" size="sm">
Save details
</Button>
</div>
</form>
) : null}
{n === 2 ? (
<div className="rounded-lg border border-border bg-muted/40 p-3">
<p className="text-sm text-muted-foreground">
{done[1] && busy !== 2 ? (
<>
Payouts go to the <span className="font-medium text-foreground">checking account ending 4402</span>.
</>
) : (
"Orbit asks your bank for read-only access to confirm the account. It never moves money on its own."
)}
</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
<Button size="sm" variant={done[1] ? "outline" : "default"} onClick={() => completeLater(2)} disabled={busy === 2}>
{busy === 2 ? <Spinner data-icon="inline-start" aria-hidden="true" /> : <Landmark data-icon="inline-start" />}
{busy === 2 ? "Connecting…" : done[1] ? "Use a different account" : "Connect bank account"}
</Button>
{done[1] ? null : <span className="text-xs text-muted-foreground">Takes about two minutes</span>}
</div>
</div>
) : null}
{n === 3 ? (
<div className="grid gap-3">
<input
ref={fileInput}
type="file"
accept=".csv,text/csv"
className="sr-only"
tabIndex={-1}
aria-hidden="true"
onChange={(e) => {
const file = e.target.files?.[0]
if (file) {
setImported(file.name)
complete(3)
}
}}
/>
<div className="flex flex-wrap gap-2">
<Button size="sm" onClick={() => fileInput.current?.click()}>
<Upload data-icon="inline-start" />
Upload a CSV
</Button>
<Button
size="sm"
variant="outline"
onClick={() => {
setImported("12 sample clients")
complete(3)
}}
>
<Users data-icon="inline-start" />
Add sample clients
</Button>
</div>
<p className="text-xs text-muted-foreground">
{imported ? `Imported ${imported}. Upload again to replace them.` : "Orbit looks for name, email and address columns."}
</p>
</div>
) : null}
{n === 4 ? (
<form
className="grid gap-4"
onSubmit={(e) => {
e.preventDefault()
complete(4)
}}
>
<fieldset>
<legend className="mb-2 text-sm font-medium">Accent color</legend>
<div className="flex gap-2.5">
{ACCENTS.map((a) => (
<label key={a.id} className="relative cursor-pointer">
<input
type="radio"
name="ob-accent"
value={a.id}
checked={accent === a.id}
onChange={() => setAccent(a.id)}
className="peer sr-only"
/>
<span className="sr-only">{a.name}</span>
<span
aria-hidden="true"
className={cn(
"block size-7 rounded-full ring-offset-2 ring-offset-card transition-shadow peer-checked:ring-2 peer-checked:ring-foreground peer-focus-visible:ring-2 peer-focus-visible:ring-ring",
a.className,
)}
/>
</label>
))}
</div>
</fieldset>
<div className="grid gap-1.5">
<Label htmlFor="ob-footer">Footer note</Label>
<Input id="ob-footer" value={footer} onChange={(e) => setFooter(e.target.value)} maxLength={80} />
</div>
<div>
<Button type="submit" size="sm">
Save branding
</Button>
</div>
</form>
) : null}
{n === 5 ? (
done[4] ? (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/40 p-3 text-sm">
<PartyPopper className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
<p>
A test invoice is on its way to <span className="font-medium">maya@example.com</span>. Check how it looks, then send the
real thing from Invoices.
</p>
</div>
) : (
<div className="flex flex-wrap gap-2">
<Button size="sm" onClick={() => completeLater(5)} disabled={busy === 5}>
{busy === 5 ? <Spinner data-icon="inline-start" aria-hidden="true" /> : <Send data-icon="inline-start" />}
{busy === 5 ? "Sending…" : "Send a test to me"}
</Button>
<Button size="sm" variant="outline" onClick={() => complete(5)} disabled={busy === 5}>
Create an invoice
</Button>
</div>
)
) : null}
</StepperContent>
</StepperItem>
)
})}
</Stepper>
<p className="sr-only" aria-live="polite">
{allDone ? "All steps done." : `${doneCount} of ${STEPS.length} steps done. Current: ${STEPS[step - 1].title}.`}
</p>
</CardContent>
</Card>
)
}Form wizard
Create an invoice in four steps, with checks per step and a review that links back to each one.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper-form-wizard.jsoncomponents/dresscode/stepper-form-wizard.tsx
"use client"
// A multi-step "create invoice" form: client, line items, schedule, then a review with edit links.
// Continue checks the step's fields and moves focus to the first one that needs fixing. A step gets
// its check mark only once it passes, and the stepper will not jump past a step that is not done.
import * as React from "react"
import { ArrowLeft, ArrowRight, CalendarIcon, CircleCheck, Plus, Send, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"
import { Label } from "@/components/ui/label"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { Switch } from "@/components/ui/switch"
import { cn } from "@/lib/utils"
import { Stepper, StepperIndicator, StepperItem, StepperSeparator, StepperTitle, StepperTrigger } from "@/components/ui/stepper"
const STEPS = ["Client", "Line items", "Schedule", "Review"]
const CLIENTS = [
{ value: "fernwood", label: "Fernwood Studio", email: "accounts@fernwood.studio" },
{ value: "kato-lee", label: "Kato & Lee", email: "finance@katolee.co" },
{ value: "pellucid", label: "Pellucid Health", email: "payables@pellucidhealth.com" },
{ value: "halden", label: "Halden Logistics", email: "invoices@halden.io" },
{ value: "bramble", label: "Bramble & Oak", email: "billing@brambleoak.com" },
]
const TERMS = [
{ value: "0", label: "Due on receipt" },
{ value: "7", label: "Net 7" },
{ value: "15", label: "Net 15" },
{ value: "30", label: "Net 30" },
{ value: "60", label: "Net 60" },
]
const TAXES = [
{ value: "0", label: "No tax" },
{ value: "5", label: "Tax 5%" },
{ value: "10", label: "Tax 10%" },
{ value: "20", label: "Tax 20%" },
]
const REPEAT = [
{ value: "none", label: "Doesn't repeat" },
{ value: "monthly", label: "Every month" },
{ value: "quarterly", label: "Every 3 months" },
]
const TODAY = new Date(2026, 10, 24)
const INVOICE = "INV-1044"
type Line = { id: number; description: string; qty: string; rate: string }
type Errors = Record<string, string>
const money = (n: number) => n.toLocaleString("en-US", { style: "currency", currency: "USD" })
const day = (d: Date) => d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n)
const amount = (l: Line) => (Number(l.qty) > 0 && Number(l.rate) > 0 ? Number(l.qty) * Number(l.rate) : 0)
const labelOf = (list: { value: string; label: string }[], value: string) => list.find((x) => x.value === value)?.label ?? ""
const START_LINES: Line[] = [
{ id: 1, description: "Brand strategy workshop", qty: "1", rate: "1800" },
{ id: 2, description: "Logo and identity design", qty: "1", rate: "2400" },
]
export default function StepperFormWizard() {
const [step, setStep] = React.useState(2)
const [furthest, setFurthest] = React.useState(2)
const [shown, setShown] = React.useState<Record<number, boolean>>({})
const [client, setClient] = React.useState<string | null>("fernwood")
const [email, setEmail] = React.useState("accounts@fernwood.studio")
const [reference, setReference] = React.useState("PO-7781")
const [lines, setLines] = React.useState<Line[]>(START_LINES)
const nextId = React.useRef(3)
const [tax, setTax] = React.useState("10")
const [issued, setIssued] = React.useState<Date | undefined>(undefined)
const [calendarOpen, setCalendarOpen] = React.useState(false)
const [terms, setTerms] = React.useState("30")
const [repeat, setRepeat] = React.useState("none")
const [reminders, setReminders] = React.useState(true)
const [sending, setSending] = React.useState(false)
const [sent, setSent] = React.useState(false)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
const sentHeading = React.useRef<HTMLHeadingElement>(null)
React.useEffect(() => () => clearTimeout(timer.current), [])
React.useEffect(() => {
if (sent) sentHeading.current?.focus()
}, [sent])
const subtotal = lines.reduce((n, l) => n + amount(l), 0)
const taxAmount = Math.round(subtotal * Number(tax)) / 100
const total = subtotal + taxAmount
const due = issued ? addDays(issued, Number(terms)) : undefined
const clientInfo = CLIENTS.find((c) => c.value === client)
function errorsFor(s: number): Errors {
const e: Errors = {}
if (s === 1) {
if (!client) e.client = "Choose who this invoice is for."
if (!email.trim()) e.email = "Enter the email the invoice goes to."
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) e.email = "Enter an email like name@company.com."
}
if (s === 2) {
for (const l of lines) {
if (!l.description.trim()) e[`desc-${l.id}`] = "Describe the work."
if (!(Number(l.qty) > 0)) e[`qty-${l.id}`] = "At least 1."
if (!(Number(l.rate) > 0)) e[`rate-${l.id}`] = "Enter a rate."
}
}
if (s === 3 && !issued) e.issue = "Pick the date the invoice is issued."
return e
}
const errors = errorsFor(step)
const visible: Errors = shown[step] ? errors : {}
const isDone = (s: number) => (s === 4 ? sent : s < furthest && Object.keys(errorsFor(s)).length === 0)
function focusField(key: string) {
requestAnimationFrame(() => document.getElementById(`inv-${key}`)?.focus())
}
function next() {
const keys = Object.keys(errors)
if (keys.length) {
setShown((prev) => ({ ...prev, [step]: true }))
focusField(keys[0])
return
}
setStep(step + 1)
setFurthest((f) => Math.max(f, step + 1))
}
function updateLine(id: number, patch: Partial<Line>) {
setLines((ls) => ls.map((l) => (l.id === id ? { ...l, ...patch } : l)))
}
function addLine() {
const id = nextId.current++
setLines((ls) => [...ls, { id, description: "", qty: "1", rate: "" }])
focusField(`desc-${id}`)
}
function send() {
setSending(true)
timer.current = setTimeout(() => {
setSending(false)
setSent(true)
}, 1400)
}
function startOver() {
setSent(false)
setStep(1)
setFurthest(1)
setShown({})
setClient(null)
setEmail("")
setReference("")
setLines([{ id: nextId.current++, description: "", qty: "1", rate: "" }])
setIssued(undefined)
}
const describedBy = (key: string) => (visible[key] ? `inv-${key}-error` : undefined)
return (
<div className="@container mx-auto w-full max-w-2xl">
<Card className="gap-0 py-0">
<div className="border-b border-border px-4 pt-5 pb-4 @md:px-6">
<div className="flex items-baseline justify-between gap-3">
<h2 className="text-base font-semibold">New invoice</h2>
<span className="text-xs text-muted-foreground tabular-nums">{INVOICE}</span>
</div>
<Stepper aria-label="Invoice steps" value={step} onValueChange={setStep} linear className="mt-4">
{STEPS.map((title, i) => (
<StepperItem key={title} step={i + 1} completed={isDone(i + 1)} invalid={shown[i + 1] && Object.keys(errorsFor(i + 1)).length > 0} loading={sending && i === 3}>
<StepperTrigger disabled={sending || sent}>
<StepperIndicator />
<StepperTitle className="@max-2xl:sr-only">{title}</StepperTitle>
</StepperTrigger>
<StepperSeparator />
</StepperItem>
))}
</Stepper>
</div>
{sent ? (
<div className="flex flex-col items-center px-6 py-12 text-center">
<CircleCheck className="size-10 text-primary" aria-hidden="true" />
<h3 ref={sentHeading} tabIndex={-1} className="mt-4 text-lg font-semibold outline-none">
{INVOICE} is on its way
</h3>
<p className="mt-1 max-w-sm text-sm text-muted-foreground">
Sent to {email} for {money(total)}, due {due ? day(due) : "on receipt"}.
{reminders ? " Orbit will remind them 3 days before it's due." : ""}
</p>
<Button variant="outline" className="mt-6" onClick={startOver}>
Create another invoice
</Button>
</div>
) : (
<form
noValidate
onSubmit={(e) => {
e.preventDefault()
if (step < 4) next()
else send()
}}
>
<fieldset className="min-w-0 px-4 py-5 @md:px-6" disabled={sending}>
<legend className="sr-only">
Step {step} of 4: {STEPS[step - 1]}
</legend>
<p className="text-xs text-muted-foreground" aria-hidden="true">
Step {step} of 4 · {STEPS[step - 1]}
</p>
<h3 className="text-base font-semibold">{["Who is it for?", "What are you billing?", "When is it due?", "Check and send"][step - 1]}</h3>
{step === 1 ? (
<div className="mt-4 grid gap-4 @lg:grid-cols-2">
<Field id="inv-client" label="Client" error={visible.client}>
<Select
items={CLIENTS}
value={client}
onValueChange={(v) => {
const c = CLIENTS.find((x) => x.value === v)
setClient(c?.value ?? null)
if (c) setEmail(c.email)
}}
>
<SelectTrigger id="inv-client" className="w-full" aria-invalid={!!visible.client} aria-describedby={describedBy("client")}>
<SelectValue placeholder="Choose a client" />
</SelectTrigger>
<SelectContent>
{CLIENTS.map((c) => (
<SelectItem key={c.value} value={c.value}>
{c.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field id="inv-email" label="Billing email" error={visible.email}>
<Input
id="inv-email"
type="email"
autoComplete="off"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={!!visible.email}
aria-describedby={describedBy("email")}
/>
</Field>
<Field id="inv-reference" label="PO or reference" hint="Optional. Shown under the invoice number.">
<Input id="inv-reference" value={reference} onChange={(e) => setReference(e.target.value)} aria-describedby="inv-reference-hint" />
</Field>
</div>
) : null}
{step === 2 ? (
<div className="mt-4">
<div className="hidden grid-cols-[minmax(0,1fr)_4.5rem_7rem_6rem_2rem] gap-2 pb-1.5 text-xs font-medium text-muted-foreground @lg:grid" aria-hidden="true">
<span>Description</span>
<span>Qty</span>
<span>Rate</span>
<span className="text-right">Amount</span>
</div>
<ul className="grid gap-3 @lg:gap-2">
{lines.map((l, i) => (
<li
key={l.id}
className="grid grid-cols-[4rem_minmax(0,1fr)_auto_auto] items-start gap-2 border-b border-border pb-3 last:border-0 last:pb-0 @lg:grid-cols-[minmax(0,1fr)_4.5rem_7rem_6rem_2rem] @lg:border-0 @lg:pb-0"
>
<div className="col-span-4 @lg:col-span-1">
<Input
id={`inv-desc-${l.id}`}
placeholder="Description"
aria-label={`Description, line ${i + 1}`}
value={l.description}
onChange={(e) => updateLine(l.id, { description: e.target.value })}
aria-invalid={!!visible[`desc-${l.id}`]}
aria-describedby={describedBy(`desc-${l.id}`)}
/>
<FieldError id={`inv-desc-${l.id}-error`} message={visible[`desc-${l.id}`]} />
</div>
<div>
<Input
id={`inv-qty-${l.id}`}
inputMode="numeric"
aria-label={`Quantity, line ${i + 1}`}
value={l.qty}
onChange={(e) => updateLine(l.id, { qty: e.target.value.replace(/[^\d.]/g, "") })}
aria-invalid={!!visible[`qty-${l.id}`]}
aria-describedby={describedBy(`qty-${l.id}`)}
/>
<FieldError id={`inv-qty-${l.id}-error`} message={visible[`qty-${l.id}`]} />
</div>
<div>
<InputGroup>
<InputGroupAddon>$</InputGroupAddon>
<InputGroupInput
id={`inv-rate-${l.id}`}
inputMode="decimal"
placeholder="0.00"
aria-label={`Rate, line ${i + 1}`}
value={l.rate}
onChange={(e) => updateLine(l.id, { rate: e.target.value.replace(/[^\d.]/g, "") })}
aria-invalid={!!visible[`rate-${l.id}`]}
aria-describedby={describedBy(`rate-${l.id}`)}
/>
</InputGroup>
<FieldError id={`inv-rate-${l.id}-error`} message={visible[`rate-${l.id}`]} />
</div>
<p className="flex h-8 items-center justify-end text-sm font-medium tabular-nums">{amount(l) ? money(amount(l)) : "—"}</p>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={`Remove line ${i + 1}`}
disabled={lines.length === 1}
onClick={() => setLines((ls) => ls.filter((x) => x.id !== l.id))}
>
<Trash2 />
</Button>
</li>
))}
</ul>
<div className="mt-4 flex flex-col gap-4 @lg:flex-row @lg:items-start @lg:justify-between">
<Button type="button" variant="outline" size="sm" className="self-start" onClick={addLine}>
<Plus data-icon="inline-start" />
Add line
</Button>
<dl className="grid w-full gap-1.5 text-sm @lg:w-64">
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">Subtotal</dt>
<dd className="tabular-nums">{money(subtotal)}</dd>
</div>
<div className="flex items-center justify-between gap-3">
<dt>
<Select items={TAXES} value={tax} onValueChange={(v) => v != null && setTax(String(v))}>
<SelectTrigger size="sm" aria-label="Tax rate">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TAXES.map((t) => (
<SelectItem key={t.value} value={t.value}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</dt>
<dd className="tabular-nums">{money(taxAmount)}</dd>
</div>
<div className="flex items-center justify-between border-t border-border pt-1.5 font-semibold">
<dt>Total</dt>
<dd className="tabular-nums">{money(total)}</dd>
</div>
</dl>
</div>
</div>
) : null}
{step === 3 ? (
<div className="mt-4 grid gap-4 @lg:grid-cols-2">
<Field id="inv-issue" label="Issue date" error={visible.issue}>
<Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
<PopoverTrigger
render={
<Button
type="button"
variant="outline"
id="inv-issue"
className={cn("w-full justify-start font-normal", !issued && "text-muted-foreground")}
aria-invalid={!!visible.issue}
aria-describedby={describedBy("issue")}
/>
}
>
<CalendarIcon data-icon="inline-start" />
{issued ? day(issued) : "Pick a date"}
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={issued}
defaultMonth={issued ?? TODAY}
onSelect={(d) => {
setIssued(d)
setCalendarOpen(false)
}}
/>
</PopoverContent>
</Popover>
</Field>
<Field id="inv-terms" label="Payment terms" hint={due ? `Due ${day(due)}` : "Pick an issue date to see the due date."}>
<Select items={TERMS} value={terms} onValueChange={(v) => v != null && setTerms(String(v))}>
<SelectTrigger id="inv-terms" className="w-full" aria-describedby="inv-terms-hint">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TERMS.map((t) => (
<SelectItem key={t.value} value={t.value}>
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field id="inv-repeat" label="Repeat">
<Select items={REPEAT} value={repeat} onValueChange={(v) => v != null && setRepeat(String(v))}>
<SelectTrigger id="inv-repeat" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{REPEAT.map((r) => (
<SelectItem key={r.value} value={r.value}>
{r.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<div className="flex items-start justify-between gap-4 rounded-lg border border-border p-3 @lg:self-end">
<div className="grid gap-1">
<Label htmlFor="inv-reminders">Payment reminders</Label>
<p id="inv-reminders-hint" className="text-xs text-muted-foreground">
3 days before and on the due date
</p>
</div>
<Switch id="inv-reminders" checked={reminders} onCheckedChange={setReminders} aria-describedby="inv-reminders-hint" />
</div>
</div>
) : null}
{step === 4 ? (
<div className="mt-4 grid gap-3 @lg:grid-cols-2">
<ReviewSection title="Client" onEdit={() => setStep(1)}>
<p className="font-medium">{clientInfo?.label}</p>
<p className="truncate text-muted-foreground">{email}</p>
{reference ? <p className="text-muted-foreground">Reference {reference}</p> : null}
</ReviewSection>
<ReviewSection title="Schedule" onEdit={() => setStep(3)}>
<p>Issued {issued ? day(issued) : "—"}</p>
<p>
{labelOf(TERMS, terms)}, due {due ? day(due) : "—"}
</p>
<p className="text-muted-foreground">
{labelOf(REPEAT, repeat)} · Reminders {reminders ? "on" : "off"}
</p>
</ReviewSection>
<ReviewSection title="Line items" onEdit={() => setStep(2)} className="@lg:col-span-2">
<table className="w-full text-sm">
<caption className="sr-only">Line items</caption>
<thead className="sr-only">
<tr>
<th scope="col">Description</th>
<th scope="col">Quantity and rate</th>
<th scope="col">Amount</th>
</tr>
</thead>
<tbody>
{lines.map((l) => (
<tr key={l.id}>
<td className="py-0.5 pr-3">{l.description}</td>
<td className="py-0.5 pr-3 text-muted-foreground tabular-nums whitespace-nowrap">
{l.qty} × {money(Number(l.rate))}
</td>
<td className="py-0.5 text-right tabular-nums">{money(amount(l))}</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
<td colSpan={2} className="pt-2 text-muted-foreground">
Subtotal
</td>
<td className="pt-2 text-right tabular-nums">{money(subtotal)}</td>
</tr>
<tr>
<td colSpan={2} className="text-muted-foreground">
{labelOf(TAXES, tax)}
</td>
<td className="text-right tabular-nums">{money(taxAmount)}</td>
</tr>
<tr className="font-semibold">
<td colSpan={2}>Total</td>
<td className="text-right tabular-nums">{money(total)}</td>
</tr>
</tfoot>
</table>
</ReviewSection>
</div>
) : null}
</fieldset>
<div className="flex items-center justify-between gap-2 border-t border-border bg-muted/50 px-4 py-3 @md:px-6">
{step > 1 ? (
<Button type="button" variant="outline" onClick={() => setStep(step - 1)} disabled={sending}>
<ArrowLeft data-icon="inline-start" />
Back
</Button>
) : (
<span />
)}
{step < 4 ? (
<Button type="submit">
Continue
<ArrowRight data-icon="inline-end" />
</Button>
) : (
<Button type="submit" disabled={sending}>
{sending ? <Spinner data-icon="inline-start" aria-hidden="true" /> : <Send data-icon="inline-start" />}
{sending ? "Sending…" : `Send ${money(total)}`}
</Button>
)}
</div>
</form>
)}
</Card>
</div>
)
}
function Field({ id, label, error, hint, children }: { id: string; label: string; error?: string; hint?: string; children: React.ReactNode }) {
return (
<div className="grid content-start gap-1.5">
<Label htmlFor={id}>{label}</Label>
{children}
{error ? (
<FieldError id={`${id}-error`} message={error} className="mt-0" />
) : hint ? (
<p id={`${id}-hint`} className="text-xs text-muted-foreground">
{hint}
</p>
) : null}
</div>
)
}
function FieldError({ id, message, className }: { id: string; message?: string; className?: string }) {
if (!message) return null
return (
<p id={id} className={cn("mt-1 text-xs text-destructive", className)}>
{message}
</p>
)
}
function ReviewSection({ title, onEdit, className, children }: { title: string; onEdit: () => void; className?: string; children: React.ReactNode }) {
return (
<section className={cn("min-w-0 rounded-lg border border-border p-3 text-sm", className)} aria-label={title}>
<div className="mb-1.5 flex items-center justify-between gap-3">
<h4 className="text-xs font-medium text-muted-foreground">{title}</h4>
<Button type="button" variant="link" size="sm" className="h-5 px-0" onClick={onEdit}>
Edit<span className="sr-only"> {title.toLowerCase()}</span>
</Button>
</div>
{children}
</section>
)
}npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper-progress.jsoncomponents/dresscode/stepper-progress.tsx
"use client"
// A compact progress bar: one segment per step with its label under it, the current one half full.
// Here it leads a four-question setup survey; answered steps stay clickable so you can change an answer.
import * as React from "react"
import { ArrowLeft, Check } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
import { Stepper, StepperItem, StepperTitle, StepperTrigger } from "@/components/ui/stepper"
const STEPS = ["Business", "Volume", "Payments", "Currency"]
const WORK = [
{ id: "services", label: "Services and time", note: "Hourly, daily or project work" },
{ id: "products", label: "Products", note: "Goods you ship or hand over" },
{ id: "both", label: "A bit of both", note: "Services with materials or parts" },
]
const VOLUME = [
{ id: "few", label: "Fewer than 10", note: "A handful of regular clients" },
{ id: "some", label: "10 to 50", note: "A steady stream every week" },
{ id: "many", label: "More than 50", note: "Batches, recurring plans or a team" },
]
const METHODS = [
{ id: "card", label: "Card" },
{ id: "transfer", label: "Bank transfer" },
{ id: "debit", label: "Direct debit" },
{ id: "cash", label: "Cash or cheque" },
]
const CURRENCIES = [
{ value: "USD", label: "US dollar (USD)" },
{ value: "EUR", label: "Euro (EUR)" },
{ value: "GBP", label: "British pound (GBP)" },
{ value: "CAD", label: "Canadian dollar (CAD)" },
{ value: "AUD", label: "Australian dollar (AUD)" },
]
const QUESTIONS = [
"What do you invoice for?",
"How many invoices do you send a month?",
"How do your clients usually pay?",
"Which currency do you invoice in?",
]
export default function StepperProgress() {
const [step, setStep] = React.useState(2)
const [furthest, setFurthest] = React.useState(2)
const [work, setWork] = React.useState<string | null>("services")
const [volume, setVolume] = React.useState<string | null>(null)
const [methods, setMethods] = React.useState<string[]>([])
const [currency, setCurrency] = React.useState<string | null>("USD")
const [error, setError] = React.useState<string | null>(null)
const [saving, setSaving] = React.useState(false)
const [finished, setFinished] = React.useState(false)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(timer.current), [])
const answered = [!!work, !!volume, methods.length > 0, !!currency]
/** Answered and moved past at least once. */
const isDone = (n: number) => finished || (n < furthest && answered[n - 1])
const doneCount = STEPS.filter((_, i) => isDone(i + 1)).length
const percent = Math.round((doneCount / STEPS.length) * 100)
function open(to: number) {
setError(null)
setStep(to)
}
function next() {
if (!answered[step - 1]) {
setError(step === 3 ? "Pick at least one way to continue." : "Pick an answer to continue.")
return
}
setError(null)
if (step < 4) {
setStep(step + 1)
setFurthest((f) => Math.max(f, step + 1))
return
}
setSaving(true)
timer.current = setTimeout(() => {
setSaving(false)
setFinished(true)
}, 1400)
}
return (
<Card className="w-full max-w-lg">
<CardHeader>
<div className="flex items-baseline justify-between gap-3 text-xs text-muted-foreground">
<span>{finished ? "All done" : `Step ${step} of ${STEPS.length}`}</span>
<span className="tabular-nums">{percent}% complete</span>
</div>
<Stepper aria-label="Workspace setup" value={finished ? 0 : step} onValueChange={open} linear className="mt-2 items-start gap-1.5">
{STEPS.map((title, i) => {
const n = i + 1
const completed = isDone(n)
const fill = completed ? "w-full" : n === step && !finished ? "w-1/2" : "w-0"
return (
<StepperItem key={title} step={n} completed={completed} loading={saving && n === 4} className="flex-1 last:flex-1">
<StepperTrigger disabled={saving || finished} className="flex w-full flex-col items-stretch gap-2">
<span className="block h-1.5 overflow-hidden rounded-full bg-primary/15">
<span className={cn("block h-full rounded-full bg-primary transition-[width] duration-500 motion-reduce:transition-none", fill)} />
</span>
<StepperTitle className="flex items-center gap-1 self-start text-xs font-medium">
{saving && n === 4 ? <Spinner className="size-3" aria-hidden="true" /> : completed ? <Check className="size-3 text-primary" aria-hidden="true" /> : null}
<span className="truncate">{title}</span>
</StepperTitle>
</StepperTrigger>
</StepperItem>
)
})}
</Stepper>
</CardHeader>
{finished ? (
<CardContent className="py-6 text-center">
<p className="text-base font-semibold">Your workspace is ready</p>
<p className="mx-auto mt-1 max-w-xs text-sm text-muted-foreground">
We set up invoice templates for {WORK.find((w) => w.id === work)?.label.toLowerCase()}, priced in {currency}, with{" "}
{methods.map((m) => METHODS.find((x) => x.id === m)?.label.toLowerCase()).join(", ")} turned on.
</p>
<Button
className="mt-5"
variant="outline"
onClick={() => {
setFinished(false)
setStep(1)
}}
>
Review answers
</Button>
</CardContent>
) : (
<>
<CardContent>
<fieldset aria-describedby={error ? "survey-error" : undefined} disabled={saving}>
<legend className="text-base font-semibold">{QUESTIONS[step - 1]}</legend>
<div className="mt-3">
{step === 1 ? <Choices value={work} onChange={setWork} options={WORK} onPick={() => setError(null)} /> : null}
{step === 2 ? <Choices value={volume} onChange={setVolume} options={VOLUME} onPick={() => setError(null)} /> : null}
{step === 3 ? (
<div className="grid gap-2 sm:grid-cols-2">
{METHODS.map((m) => (
<label
key={m.id}
className="flex cursor-pointer items-center gap-3 rounded-lg border border-border p-3 text-sm font-medium transition-colors hover:bg-muted/50 has-data-checked:border-primary has-data-checked:bg-primary/5"
>
<Checkbox
checked={methods.includes(m.id)}
onCheckedChange={(on) => {
setError(null)
setMethods((list) => (on ? [...list, m.id] : list.filter((x) => x !== m.id)))
}}
/>
{m.label}
</label>
))}
</div>
) : null}
{step === 4 ? (
<div className="grid gap-1.5">
<Label htmlFor="survey-currency" className="sr-only">
Currency
</Label>
<Select items={CURRENCIES} value={currency} onValueChange={(v) => setCurrency(v == null ? null : String(v))}>
<SelectTrigger id="survey-currency" className="w-full">
<SelectValue placeholder="Choose a currency" />
</SelectTrigger>
<SelectContent>
{CURRENCIES.map((c) => (
<SelectItem key={c.value} value={c.value}>
{c.label}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">You can bill single clients in other currencies later.</p>
</div>
) : null}
</div>
{error ? (
<p id="survey-error" role="alert" className="mt-3 text-sm text-destructive">
{error}
</p>
) : null}
</fieldset>
</CardContent>
<CardFooter className="justify-between gap-2">
{step > 1 ? (
<Button variant="ghost" onClick={() => open(step - 1)} disabled={saving}>
<ArrowLeft data-icon="inline-start" />
Back
</Button>
) : (
<span />
)}
<Button onClick={next} disabled={saving}>
{saving ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
{step < 4 ? "Continue" : saving ? "Setting up…" : "Finish setup"}
</Button>
</CardFooter>
</>
)}
</Card>
)
}
function Choices({
value,
onChange,
onPick,
options,
}: {
value: string | null
onChange: (id: string) => void
onPick: () => void
options: { id: string; label: string; note: string }[]
}) {
return (
<RadioGroup
value={value ?? ""}
onValueChange={(v) => {
onPick()
onChange(String(v))
}}
className="gap-2"
>
{options.map((o) => (
<label
key={o.id}
className="flex cursor-pointer items-start gap-3 rounded-lg border border-border p-3 transition-colors hover:bg-muted/50 has-data-checked:border-primary has-data-checked:bg-primary/5"
>
<RadioGroupItem value={o.id} className="mt-0.5" />
<span>
<span className="block text-sm font-medium">{o.label}</span>
<span className="block text-xs text-muted-foreground">{o.note}</span>
</span>
</label>
))}
</RadioGroup>
)
}Any order
Sections you can fill in any order, each marked done or with what to fix; publish unlocks when all are done.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/stepper-non-linear.jsoncomponents/dresscode/stepper-non-linear.tsx
"use client"
// Steps you can do in any order: each section is checked when you save it or move on from it, and is
// marked done or with the number of things to fix. Publish turns on once every section is done.
import * as React from "react"
import { CircleCheck } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { cn } from "@/lib/utils"
import {
Stepper,
StepperDescription,
StepperIndicator,
StepperItem,
StepperSeparator,
StepperTitle,
StepperTrigger,
} from "@/components/ui/stepper"
const SECTIONS = [
{ title: "Business profile", heading: "Business profile", intro: "Shown at the top of every invoice and receipt." },
{ title: "Branding", heading: "Branding", intro: "How the portal greets your clients." },
{ title: "Payment methods", heading: "Payment methods", intro: "The ways clients can pay from the portal." },
{ title: "Reminders", heading: "Reminders", intro: "Polite nudges for invoices that are due or late." },
]
const ACCENTS: Record<string, string> = {
"1": "bg-(--chart-1)",
"2": "bg-(--chart-2)",
"3": "bg-(--chart-3)",
"4": "bg-(--chart-4)",
"5": "bg-(--chart-5)",
}
const FIRST_REMINDER = [
{ value: "due", label: "On the due date" },
{ value: "3", label: "3 days after" },
{ value: "7", label: "7 days after" },
]
const REPEAT = [
{ value: "3", label: "Every 3 days" },
{ value: "7", label: "Every week" },
{ value: "never", label: "Don't repeat" },
]
const PAYMENT_METHODS = [
{ id: "card", label: "Card payments", note: "Clients pay by card, with a 2.9% fee per payment." },
{ id: "transfer", label: "Bank transfer", note: "Your bank details show on every invoice." },
{ id: "debit", label: "Direct debit", note: "Collect recurring invoices automatically." },
] as const
type Errors = Record<string, string>
export default function StepperNonLinear() {
const [section, setSection] = React.useState(3)
// A section is "checked" once it was saved or left after an edit; from then on it shows done or errors.
const [checked, setChecked] = React.useState([true, false, true, false])
const [touched, setTouched] = React.useState([false, false, false, false])
const [profile, setProfile] = React.useState({ name: "Fernwood Studio LLC", tax: "84-2193706", address: "88 Mill Road, Suite 3\nPortland, OR 97209" })
const [accent, setAccent] = React.useState("1")
const [welcome, setWelcome] = React.useState("")
const [methods, setMethods] = React.useState<Record<string, boolean>>({ card: false, transfer: false, debit: false })
const [replyTo, setReplyTo] = React.useState("")
const [first, setFirst] = React.useState("3")
const [repeat, setRepeat] = React.useState("7")
const [publishing, setPublishing] = React.useState(false)
const [published, setPublished] = React.useState(false)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
const liveHeading = React.useRef<HTMLHeadingElement>(null)
React.useEffect(() => () => clearTimeout(timer.current), [])
React.useEffect(() => {
if (published) liveHeading.current?.focus()
}, [published])
function errorsFor(s: number): Errors {
const e: Errors = {}
if (s === 1) {
if (!profile.name.trim()) e.name = "Enter the legal name of the business."
if (!/^\d{2}-\d{7}$/.test(profile.tax.trim())) e.tax = "Use the format 12-3456789."
if (!profile.address.trim()) e.address = "Enter the address clients should see."
}
if (s === 2 && !welcome.trim()) e.welcome = "Write a line to greet clients."
if (s === 3 && !Object.values(methods).some(Boolean)) e.methods = "Turn on at least one way to pay."
if (s === 4) {
if (!replyTo.trim()) e.replyTo = "Enter the address replies should go to."
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(replyTo.trim())) e.replyTo = "Enter an email like name@company.com."
}
return e
}
const problems = SECTIONS.map((_, i) => Object.keys(errorsFor(i + 1)).length)
const isDone = (s: number) => checked[s - 1] && problems[s - 1] === 0
const isInvalid = (s: number) => checked[s - 1] && problems[s - 1] > 0
const doneCount = SECTIONS.filter((_, i) => isDone(i + 1)).length
const allDone = doneCount === SECTIONS.length
const errors = checked[section - 1] ? errorsFor(section) : {}
const touch = () => setTouched((t) => t.map((x, i) => x || i === section - 1))
const check = (s: number) => setChecked((c) => c.map((x, i) => x || i === s - 1))
function status(s: number) {
if (isDone(s)) return "Done"
if (isInvalid(s)) return problems[s - 1] === 1 ? "1 thing to fix" : `${problems[s - 1]} things to fix`
return touched[s - 1] ? "In progress" : "Not started"
}
function open(to: number) {
if (touched[section - 1]) check(section)
setSection(to)
}
function save() {
check(section)
const keys = Object.keys(errorsFor(section))
if (keys.length) {
requestAnimationFrame(() => document.getElementById(`portal-${keys[0]}`)?.focus())
return
}
// Move on to the next section that still needs work, if there is one.
const order = [...SECTIONS.keys()].map((i) => ((section + i) % SECTIONS.length) + 1)
const nextUp = order.find((s) => s !== section && !isDone(s))
if (nextUp) setSection(nextUp)
}
function publish() {
setPublishing(true)
timer.current = setTimeout(() => {
setPublishing(false)
setPublished(true)
}, 1400)
}
const describedBy = (key: string) => (errors[key] ? `portal-${key}-error` : undefined)
const current = SECTIONS[section - 1]
if (published) {
return (
<Card className="w-full max-w-4xl items-center px-6 py-12 text-center">
<CircleCheck className="size-10 text-primary" aria-hidden="true" />
<h2 ref={liveHeading} tabIndex={-1} className="text-lg font-semibold outline-none">
Your client portal is live
</h2>
<p className="max-w-sm text-sm text-muted-foreground">Clients see it from the pay button on every invoice you send from now on.</p>
<Button variant="outline" className="mt-2" onClick={() => setPublished(false)}>
Back to setup
</Button>
</Card>
)
}
return (
<div className="@container w-full max-w-4xl">
<Card className="gap-0 py-0">
<div className="grid @3xl:grid-cols-[16rem_minmax(0,1fr)]">
<nav aria-label="Portal setup" className="border-b border-border p-4 @3xl:border-e @3xl:border-b-0 @3xl:p-5">
<p className="mb-4 text-sm font-semibold">Client portal setup</p>
<Stepper aria-label="Sections" orientation="vertical" value={section} onValueChange={open}>
{SECTIONS.map((s, i) => (
<StepperItem key={s.title} step={i + 1} completed={isDone(i + 1)} invalid={isInvalid(i + 1)} className="pb-4">
<StepperSeparator className="top-9 bottom-1" />
<StepperTrigger disabled={publishing}>
<StepperIndicator />
<StepperTitle>{s.title}</StepperTitle>
<StepperDescription className={cn("text-xs", isInvalid(i + 1) && "text-destructive")}>{status(i + 1)}</StepperDescription>
</StepperTrigger>
</StepperItem>
))}
</Stepper>
</nav>
<form
noValidate
className="flex min-w-0 flex-col"
onSubmit={(e) => {
e.preventDefault()
save()
}}
onChange={touch}
>
<fieldset className="min-w-0 flex-1 p-4 @3xl:p-6" disabled={publishing} aria-labelledby="portal-section">
<h2 id="portal-section" className="text-base font-semibold">
{current.heading}
</h2>
<p className="text-sm text-muted-foreground">{current.intro}</p>
<div className="mt-5 grid gap-4">
{section === 1 ? (
<>
<div className="grid gap-4 @xl:grid-cols-2">
<Field id="portal-name" label="Legal name" error={errors.name}>
<Input
id="portal-name"
value={profile.name}
onChange={(e) => setProfile({ ...profile, name: e.target.value })}
aria-invalid={!!errors.name}
aria-describedby={describedBy("name")}
/>
</Field>
<Field id="portal-tax" label="Tax ID (EIN)" error={errors.tax}>
<Input
id="portal-tax"
inputMode="numeric"
value={profile.tax}
onChange={(e) => setProfile({ ...profile, tax: e.target.value })}
aria-invalid={!!errors.tax}
aria-describedby={describedBy("tax")}
/>
</Field>
</div>
<Field id="portal-address" label="Address" error={errors.address}>
<Textarea
id="portal-address"
rows={2}
value={profile.address}
onChange={(e) => setProfile({ ...profile, address: e.target.value })}
aria-invalid={!!errors.address}
aria-describedby={describedBy("address")}
/>
</Field>
</>
) : null}
{section === 2 ? (
<>
<fieldset>
<legend className="mb-2 text-sm font-medium">Accent color</legend>
<div className="flex gap-2.5">
{Object.keys(ACCENTS).map((a) => (
<label key={a} className="cursor-pointer">
<input
type="radio"
name="portal-accent"
value={a}
checked={accent === a}
onChange={() => setAccent(a)}
className="peer sr-only"
/>
<span className="sr-only">Accent {a}</span>
<span
aria-hidden="true"
className={cn(
"block size-7 rounded-full ring-offset-2 ring-offset-card transition-shadow peer-checked:ring-2 peer-checked:ring-foreground peer-focus-visible:ring-2 peer-focus-visible:ring-ring",
ACCENTS[a],
)}
/>
</label>
))}
</div>
</fieldset>
<Field id="portal-welcome" label="Welcome line" error={errors.welcome} hint="The first thing clients read on the portal.">
<Input
id="portal-welcome"
placeholder="Thanks for working with us. Pay any open invoice below."
value={welcome}
onChange={(e) => setWelcome(e.target.value)}
maxLength={90}
aria-invalid={!!errors.welcome}
aria-describedby={describedBy("welcome") ?? "portal-welcome-hint"}
/>
</Field>
<div className="overflow-hidden rounded-lg border border-border" aria-hidden="true">
<div className={cn("h-1.5", ACCENTS[accent])} />
<div className="flex items-center justify-between gap-3 bg-muted/40 px-3 py-2.5">
<div className="min-w-0">
<p className="truncate text-sm font-medium">{profile.name || "Your business"}</p>
<p className="truncate text-xs text-muted-foreground">{welcome || "Your welcome line shows here."}</p>
</div>
<span className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground">Pay $1,860.00</span>
</div>
</div>
</>
) : null}
{section === 3 ? (
<div role="group" aria-labelledby="portal-methods-label" aria-describedby={describedBy("methods")}>
<p id="portal-methods-label" className="sr-only">
Payment methods
</p>
<div className={cn("divide-y divide-border rounded-lg border border-border", errors.methods && "border-destructive")}>
{PAYMENT_METHODS.map((m, i) => (
<div key={m.id} className="flex items-start justify-between gap-4 p-3">
<div className="grid gap-0.5">
<Label htmlFor={i === 0 ? "portal-methods" : `portal-method-${m.id}`}>{m.label}</Label>
<p className="text-xs text-muted-foreground">{m.note}</p>
</div>
<Switch
id={i === 0 ? "portal-methods" : `portal-method-${m.id}`}
checked={methods[m.id]}
onCheckedChange={(on) => {
touch()
setMethods((prev) => ({ ...prev, [m.id]: on }))
}}
/>
</div>
))}
</div>
{errors.methods ? (
<p id="portal-methods-error" className="mt-2 text-xs text-destructive">
{errors.methods}
</p>
) : null}
</div>
) : null}
{section === 4 ? (
<>
<Field id="portal-replyTo" label="Reply-to email" error={errors.replyTo} hint="Client replies to reminders land here.">
<Input
id="portal-replyTo"
type="email"
placeholder="billing@yourcompany.com"
value={replyTo}
onChange={(e) => setReplyTo(e.target.value)}
aria-invalid={!!errors.replyTo}
aria-describedby={describedBy("replyTo") ?? "portal-replyTo-hint"}
/>
</Field>
<div className="grid gap-4 @xl:grid-cols-2">
<Field id="portal-first" label="First reminder">
<Select
items={FIRST_REMINDER}
value={first}
onValueChange={(v) => {
touch()
if (v != null) setFirst(String(v))
}}
>
<SelectTrigger id="portal-first" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{FIRST_REMINDER.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field id="portal-repeat" label="Then">
<Select
items={REPEAT}
value={repeat}
onValueChange={(v) => {
touch()
if (v != null) setRepeat(String(v))
}}
>
<SelectTrigger id="portal-repeat" className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{REPEAT.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
</div>
</>
) : null}
</div>
</fieldset>
<div className="flex flex-col gap-3 border-t border-border bg-muted/50 px-4 py-3 @xl:flex-row @xl:items-center @xl:justify-between @3xl:px-6">
<p id="portal-progress" className="text-sm text-muted-foreground" aria-live="polite">
{allDone ? "Every section is done. Ready to publish." : `${doneCount} of ${SECTIONS.length} sections done`}
</p>
<div className="flex gap-2">
<Button type="submit" variant="outline" className="flex-1 @xl:flex-none" disabled={publishing}>
Save section
</Button>
<Button type="button" className="flex-1 @xl:flex-none" disabled={!allDone || publishing} aria-describedby="portal-progress" onClick={publish}>
{publishing ? <Spinner data-icon="inline-start" aria-hidden="true" /> : null}
{publishing ? "Publishing…" : "Publish portal"}
</Button>
</div>
</div>
</form>
</div>
</Card>
</div>
)
}
function Field({ id, label, error, hint, children }: { id: string; label: string; error?: string; hint?: string; children: React.ReactNode }) {
return (
<div className="grid content-start gap-1.5">
<Label htmlFor={id}>{label}</Label>
{children}
{error ? (
<p id={`${id}-error`} className="text-xs text-destructive">
{error}
</p>
) : hint ? (
<p id={`${id}-hint`} className="text-xs text-muted-foreground">
{hint}
</p>
) : null}
</div>
)
}The component
What shadcn@latest add https://dresscodeui.com/r/dresscode/stepper.json writes. It uses only shadcn/ui's variables, so it follows the theme.
components/ui/stepper.tsx
"use client"
// Stepper: numbered steps for checkouts, wizards and onboarding, across the top or down the side.
// Stepper holds the current step (controlled `value` + `onValueChange`, or `defaultValue`) and renders
// the labelled list. Each StepperItem has a 1-based `step` and can be `completed`, `disabled`,
// `loading` or `invalid`; with `linear` on the Stepper, a step opens only once every step before it is
// completed. The step buttons take one Tab stop: arrow keys, Home and End move between them, Enter or
// Space opens one. The current one carries aria-current="step".
// Built for shadcn/ui; reads only the theme's variables.
import * as React from "react"
import { CheckIcon, LoaderCircleIcon, TriangleAlertIcon } from "lucide-react"
import { cn } from "@/lib/utils"
type Orientation = "horizontal" | "vertical"
/** What a step looks like: the current one wins, then an error, then done. */
type StepState = "active" | "invalid" | "completed" | "inactive"
type StepperContextValue = {
value: number
setValue: (step: number) => void
orientation: Orientation
linear: boolean
canOpen: (step: number) => boolean
register: (step: number, completed: boolean) => () => void
}
const StepperContext = React.createContext<StepperContextValue | null>(null)
/** The current step and a way to change it, for buttons and custom parts inside a Stepper. */
function useStepper() {
const context = React.useContext(StepperContext)
if (!context) throw new Error("Stepper parts must be used inside <Stepper>.")
const { value, setValue, orientation, linear, canOpen } = context
return { value, setValue, orientation, linear, canOpen }
}
type StepperItemContextValue = {
step: number
state: StepState
active: boolean
completed: boolean
disabled: boolean
loading: boolean
invalid: boolean
/** The step can be opened now: not disabled, and allowed by `linear`. */
reachable: boolean
}
const StepperItemContext = React.createContext<StepperItemContextValue | null>(null)
function useStepperItem() {
const context = React.useContext(StepperItemContext)
if (!context) throw new Error("This Stepper part must be used inside <StepperItem>.")
return context
}
function useStepperContext() {
const context = React.useContext(StepperContext)
if (!context) throw new Error("Stepper parts must be used inside <Stepper>.")
return context
}
type StepperProps = Omit<React.ComponentProps<"ol">, "defaultValue"> & {
/** The current step, 1-based. Pair with onValueChange. */
value?: number
/** The step to start on when value is not controlled. */
defaultValue?: number
onValueChange?: (step: number) => void
orientation?: Orientation
/** Block jumping ahead: a step opens only once every step before it is completed. */
linear?: boolean
}
function Stepper({
value: valueProp,
defaultValue = 1,
onValueChange,
orientation = "horizontal",
linear = false,
className,
onKeyDown,
...props
}: StepperProps) {
const [uncontrolled, setUncontrolled] = React.useState(defaultValue)
const value = valueProp ?? uncontrolled
const setValue = React.useCallback(
(step: number) => {
if (valueProp === undefined) setUncontrolled(step)
onValueChange?.(step)
},
[valueProp, onValueChange],
)
// Which steps are completed, so `linear` can tell whether a later step may open.
const [completed, setCompleted] = React.useState<Record<number, boolean>>({})
const register = React.useCallback((step: number, done: boolean) => {
setCompleted((prev) => (prev[step] === done ? prev : { ...prev, [step]: done }))
return () =>
setCompleted((prev) => {
if (!(step in prev)) return prev
const next = { ...prev }
delete next[step]
return next
})
}, [])
const canOpen = React.useCallback(
(step: number) => {
if (!linear || step <= value) return true
for (let s = 1; s < step; s++) if (!completed[s]) return false
return true
},
[linear, value, completed],
)
const context = React.useMemo(
() => ({ value, setValue, orientation, linear, canOpen, register }),
[value, setValue, orientation, linear, canOpen, register],
)
function handleKeyDown(event: React.KeyboardEvent<HTMLOListElement>) {
onKeyDown?.(event)
if (event.defaultPrevented) return
const target = event.target as HTMLElement
if (target.dataset.slot !== "stepper-trigger") return
const list = event.currentTarget
const triggers = Array.from(list.querySelectorAll<HTMLButtonElement>('[data-slot="stepper-trigger"]')).filter(
(t) => !t.disabled && t.closest('[data-slot="stepper"]') === list,
)
const index = triggers.indexOf(target as HTMLButtonElement)
if (index === -1) return
const rtl = getComputedStyle(list).direction === "rtl"
const back = orientation === "vertical" ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft"
const forward = orientation === "vertical" ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight"
let to: number
if (event.key === forward) to = (index + 1) % triggers.length
else if (event.key === back) to = (index - 1 + triggers.length) % triggers.length
else if (event.key === "Home") to = 0
else if (event.key === "End") to = triggers.length - 1
else return
event.preventDefault()
triggers[to]?.focus()
}
return (
<StepperContext.Provider value={context}>
<ol
data-slot="stepper"
data-orientation={orientation}
aria-label={props["aria-labelledby"] ? undefined : "Progress"}
onKeyDown={handleKeyDown}
className={cn("group/stepper flex", orientation === "horizontal" ? "w-full items-center gap-3" : "flex-col", className)}
{...props}
/>
</StepperContext.Provider>
)
}
type StepperItemProps = React.ComponentProps<"li"> & {
/** This step's number, 1-based. */
step: number
completed?: boolean
disabled?: boolean
/** Shows a spinner in the indicator, e.g. while the step saves. */
loading?: boolean
/** Marks the step as having errors. */
invalid?: boolean
}
function StepperItem({
step,
completed = false,
disabled = false,
loading = false,
invalid = false,
className,
...props
}: StepperItemProps) {
const { value, orientation, canOpen, register } = useStepperContext()
React.useLayoutEffect(() => register(step, completed), [register, step, completed])
const active = value === step
const state: StepState = active ? "active" : invalid ? "invalid" : completed ? "completed" : "inactive"
const reachable = !disabled && canOpen(step)
const item = React.useMemo(
() => ({ step, state, active, completed, disabled, loading, invalid, reachable }),
[step, state, active, completed, disabled, loading, invalid, reachable],
)
return (
<StepperItemContext.Provider value={item}>
<li
data-slot="stepper-item"
data-state={state}
data-active={active ? "" : undefined}
data-completed={completed ? "" : undefined}
data-invalid={invalid ? "" : undefined}
data-loading={loading ? "" : undefined}
data-disabled={disabled ? "" : undefined}
className={cn(
"group/stepper-item relative",
orientation === "horizontal" ? "flex flex-1 items-center gap-3 last:flex-none" : "flex flex-col pb-8 last:pb-0",
disabled && "opacity-50",
className,
)}
{...props}
/>
</StepperItemContext.Provider>
)
}
/** Words a screen reader hears before the step's title, e.g. "Step 2, completed:". */
function statusText(item: StepperItemContextValue) {
const status = item.loading ? ", in progress" : item.invalid ? ", needs attention" : item.completed ? ", completed" : ""
return `Step ${item.step}${status}: `
}
/** The button that opens a step. Put the indicator, title and description inside it. */
function StepperTrigger({ className, children, onClick, disabled, ...props }: React.ComponentProps<"button">) {
const { setValue, orientation } = useStepperContext()
const item = useStepperItem()
return (
<button
type="button"
data-slot="stepper-trigger"
data-state={item.state}
aria-current={item.active ? "step" : undefined}
aria-busy={item.loading || undefined}
tabIndex={item.active ? 0 : -1}
disabled={disabled || !item.reachable}
onClick={(event) => {
onClick?.(event)
if (!event.defaultPrevented && !item.active) setValue(item.step)
}}
className={cn(
"group/stepper-trigger -m-1 grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-3 rounded-lg p-1 text-start outline-none transition-colors",
"focus-visible:ring-3 focus-visible:ring-ring/50 enabled:cursor-pointer disabled:cursor-default",
"enabled:hover:*:data-[state=inactive]:data-[slot=stepper-title]:text-foreground enabled:hover:*:data-[state=inactive]:data-[slot=stepper-indicator]:border-primary/60",
// horizontal: the title row stretches to the indicator's height when there is no description
orientation === "horizontal" ? "grid-rows-[1fr_auto] items-center" : "items-start",
className,
)}
{...props}
>
<span className="sr-only">{statusText(item)}</span>
{children}
</button>
)
}
/** The circle: the step number (or your icon), a check when completed, a spinner when loading. */
function StepperIndicator({ className, children, ...props }: React.ComponentProps<"span">) {
const { orientation } = useStepperContext()
const item = useStepperItem()
const look = item.loading ? "loading" : item.invalid ? "invalid" : item.completed ? "completed" : item.active ? "active" : "inactive"
return (
<span
aria-hidden="true"
data-slot="stepper-indicator"
data-state={look}
data-active={item.active ? "" : undefined}
className={cn(
"row-span-2 flex size-8 shrink-0 items-center justify-center rounded-full border border-border bg-background text-xs font-semibold text-muted-foreground tabular-nums transition-[color,background-color,border-color,box-shadow] [&_svg]:size-4",
"data-[state=active]:border-primary data-[state=active]:text-foreground data-[state=loading]:border-primary data-[state=loading]:text-foreground",
"data-[state=completed]:border-primary data-[state=completed]:bg-primary data-[state=completed]:text-primary-foreground",
"data-[state=invalid]:border-destructive data-[state=invalid]:bg-destructive/10 data-[state=invalid]:text-destructive",
"data-active:ring-4 data-active:ring-primary/15 data-active:data-[state=invalid]:ring-destructive/15",
orientation === "horizontal" ? "self-center" : "self-start",
className,
)}
{...props}
>
{item.loading ? (
<LoaderCircleIcon className="animate-spin" />
) : item.invalid ? (
<TriangleAlertIcon />
) : item.completed ? (
<CheckIcon />
) : (
(children ?? item.step)
)}
</span>
)
}
function StepperTitle({ className, ...props }: React.ComponentProps<"span">) {
const { orientation } = useStepperContext()
const item = useStepperItem()
return (
<span
data-slot="stepper-title"
data-state={item.state}
className={cn(
"block text-sm leading-5 font-medium text-foreground transition-colors data-[state=inactive]:text-muted-foreground data-[state=invalid]:text-destructive",
orientation === "horizontal" ? "self-center whitespace-nowrap" : "flex min-h-8 items-center",
className,
)}
{...props}
/>
)
}
function StepperDescription({ className, ...props }: React.ComponentProps<"span">) {
const { orientation } = useStepperContext()
const item = useStepperItem()
return (
<span
data-slot="stepper-description"
data-state={item.state}
className={cn(
"col-start-2 block text-muted-foreground",
orientation === "horizontal" ? "self-start text-xs leading-4 whitespace-nowrap" : "-mt-1 text-sm",
className,
)}
{...props}
/>
)
}
/** The line from this step to the next; filled once this step is completed. Hidden on the last step. */
function StepperSeparator({ className, ...props }: React.ComponentProps<"span">) {
const { orientation } = useStepperContext()
const item = useStepperItem()
return (
<span
aria-hidden="true"
data-slot="stepper-separator"
data-state={item.completed ? "completed" : "pending"}
className={cn(
"rounded-full bg-border transition-colors group-last/stepper-item:hidden data-[state=completed]:bg-primary",
orientation === "horizontal" ? "h-0.5 min-w-6 flex-1" : "absolute start-[calc(--spacing(4)-1px)] top-10 bottom-2 w-0.5",
className,
)}
{...props}
/>
)
}
/** What shows under the current step in a vertical stepper. Renders only while its step is current. */
function StepperContent({ className, ...props }: React.ComponentProps<"div">) {
const item = useStepperItem()
if (!item.active) return null
return <div data-slot="stepper-content" className={cn("ps-11 pt-3", className)} {...props} />
}
export {
Stepper,
StepperContent,
StepperDescription,
StepperIndicator,
StepperItem,
StepperSeparator,
StepperTitle,
StepperTrigger,
useStepper,
}