# Setup wizard

A three-step workspace setup: name the workspace, invite the team, choose preferences, then review and finish. Each step uses `Field`, `Textarea`, `RadioGroup`, `Input.Select` and `Switch`; `Button`s move Back and Next, and a `toast` confirms the finished workspace.

**Example: Set up your workspace** (`examples/recipes/setup-wizard.tsx`)

```tsx
'use client'

import {
  Body,
  BodySmall,
  Button,
  Card,
  Field,
  Heading,
  Input,
  Label,
  Link,
  Radio,
  RadioGroup,
  Stack,
  Switch,
  Text,
  Textarea,
  toastSuccess,
} from '@blocks/design-system'
import { Check, PartyPopper } from 'lucide-react'
import { type FormEvent, useCallback, useId, useRef, useState } from 'react'
import styles from './setup-wizard.module.css'

const steps = [
  { label: 'Workspace', title: 'Name your workspace', description: 'This is how teammates find you. You can rename it later.' },
  {
    label: 'Invite team',
    title: 'Invite your team',
    description: 'Each person gets an email with a link to join. Skip this if you’re starting solo.',
  },
  {
    label: 'Preferences',
    title: 'Set your team’s defaults',
    description: 'Everyone starts here, and each person can change their own.',
  },
]
const review = { title: 'Review and finish', description: 'Check the details before we create the workspace.' }
const reviewStep = steps.length

interface Setup {
  name: string
  slug: string
  invites: string
  role: string
  view: string | null
  weekStart: string
  digest: boolean
}

type Errors = Partial<Record<'name' | 'slug' | 'invites' | 'view', string>>

const views = [
  { value: 'board', label: 'Board', description: 'Columns by status' },
  { value: 'list', label: 'List', description: 'One row per item' },
  { value: 'timeline', label: 'Timeline', description: 'Items across weeks' },
]

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

const toSlug = (name: string) =>
  name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
    .slice(0, 30)

const splitInvites = (invites: string) => invites.split(/[\s,;]+/).filter(Boolean)

// Each step checks only its own fields before the wizard moves on.
function validateStep(step: number, setup: Setup): Errors {
  const errors: Errors = {}
  if (step === 0) {
    if (setup.name.trim().length < 2) errors.name = 'Give the workspace a name of at least 2 characters.'
    if (!/^[a-z0-9-]{3,30}$/.test(setup.slug)) errors.slug = 'Use 3–30 lowercase letters, numbers or hyphens.'
  }
  if (step === 1) {
    const invalid = splitInvites(setup.invites).find((email) => !emailPattern.test(email))
    if (invalid) errors.invites = `“${invalid}” isn’t a valid email address.`
  }
  if (step === 2 && !setup.view) errors.view = 'Choose the view your team opens first.'
  return errors
}

const initialSetup: Setup = {
  name: 'Harbor Lane Studio',
  slug: toSlug('Harbor Lane Studio'),
  invites: '',
  role: 'member',
  view: null,
  weekStart: 'monday',
  digest: true,
}

// A three-step workspace setup with a review before it finishes. The step
// indicator is an ordered list; finished steps become buttons that jump back.
export default function SetupWizard() {
  const titleId = useId()
  const roleLabelId = useId()
  const viewLabelId = useId()
  const viewErrorId = useId()
  const weekStartId = useId()
  const [step, setStep] = useState(0)
  const [setup, setSetup] = useState(initialSetup)
  const [slugEdited, setSlugEdited] = useState(false)
  // Errors appear when Next is pressed, then follow the fields as they're fixed.
  const [showErrors, setShowErrors] = useState(false)
  const errors = showErrors ? validateStep(step, setup) : {}
  const [finished, setFinished] = useState(false)
  const moved = useRef(false)

  // Each step's heading is keyed by step, so it mounts fresh and takes focus
  // after every move (but not on the page's first render).
  const focusOnMount = useCallback((heading: HTMLHeadingElement | null) => {
    if (heading && moved.current) heading.focus()
  }, [])

  function update<Key extends keyof Setup>(key: Key, value: Setup[Key]) {
    setSetup((current) => ({ ...current, [key]: value }))
  }

  function goTo(next: number) {
    moved.current = true
    setShowErrors(false)
    setStep(next)
  }

  function advance(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (step === reviewStep) {
      moved.current = true
      setFinished(true)
      toastSuccess(`${setup.name} is ready`)
      return
    }
    const firstInvalid = Object.keys(validateStep(step, setup))[0]
    if (firstInvalid) {
      setShowErrors(true)
      // Text fields are found by name; the view choice by its first radio.
      const selector = firstInvalid === 'view' ? '[role="radio"]' : `[name="${firstInvalid}"]`
      event.currentTarget.querySelector<HTMLElement>(selector)?.focus()
      return
    }
    goTo(step + 1)
  }

  function startOver() {
    setSetup(initialSetup)
    setSlugEdited(false)
    setFinished(false)
    goTo(0)
  }

  const invites = splitInvites(setup.invites)
  const people = `${invites.length} ${invites.length === 1 ? 'person' : 'people'}`
  const teamSummary =
    invites.length === 0 ? 'No invitations yet' : `${people} as ${setup.role === 'admin' ? 'admins' : 'members'}`
  const preferencesSummary = [
    `${views.find((view) => view.value === setup.view)?.label} view`,
    `week starts ${setup.weekStart === 'monday' ? 'Monday' : 'Sunday'}`,
    setup.digest ? 'weekly summary on' : 'no weekly summary',
  ].join(' · ')
  const { title: stepTitle, description: stepDescription } = steps[step] ?? review
  const initials = setup.name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((word) => word[0]?.toUpperCase())
    .join('')

  if (finished) {
    return (
      <Card as="section" aria-labelledby={titleId} padding="xl" borderRadius="xl">
        <Stack gap="md" align="start">
          <span className={styles.doneIcon}>
            <PartyPopper aria-hidden size={24} />
          </span>
          <Heading as="h3" id={titleId} ref={focusOnMount} tabIndex={-1} fontSize="xl" margin="none">
            {setup.name} is ready
          </Heading>
          <Body color="text-muted" margin="none">
            {invites.length > 0
              ? `We invited ${people}. They’ll appear here as they join.`
              : 'Invite teammates any time from Settings → Members.'}
          </Body>
          <Stack direction="row" gap="sm" wrap="wrap">
            <Button as="a" href={`#${setup.slug}`} variant="primary">
              Open workspace
            </Button>
            <Button type="button" variant="ghost" onClick={startOver}>
              Set up another
            </Button>
          </Stack>
        </Stack>
      </Card>
    )
  }

  return (
    <Card
      as="section"
      aria-labelledby={titleId}
      padding="none"
      borderRadius="xl"
      dangerouslySetClassName={styles.wizard}
    >
      <div className={styles.header}>
        <div className={styles.intro}>
          <Stack gap="xs">
            <Heading as="h3" id={titleId} fontSize="lg" margin="none">
              Set up your workspace
            </Heading>
            <BodySmall color="text-muted" margin="none">
              Three short steps, all changeable later.
            </BodySmall>
          </Stack>
          {/* A live preview of what the first step is building. */}
          <p className={styles.preview}>
            <span className={styles.tile} aria-hidden>
              {initials || '?'}
            </span>
            <span className={styles.previewText}>
              <strong>{setup.name.trim() || 'Your workspace'}</strong>
              <span>{setup.slug || 'your-team'}.ledger.example</span>
            </span>
          </p>
        </div>
        <ol className={styles.steps} aria-label="Setup progress">
          {steps.map(({ label }, index) => {
            const complete = index < step
            const current = index === step
            return (
              <li
                key={label}
                className={styles.step}
                data-state={complete ? 'complete' : current ? 'current' : 'upcoming'}
              >
                {complete ? (
                  <button
                    type="button"
                    className={styles.stepTarget}
                    aria-label={`Edit ${label} (completed)`}
                    onClick={() => goTo(index)}
                  >
                    <span className={styles.marker}>
                      <Check aria-hidden size={14} />
                    </span>
                    <span className={styles.stepLabel}>{label}</span>
                  </button>
                ) : (
                  <span className={styles.stepTarget} aria-current={current ? 'step' : undefined}>
                    <span className={styles.marker}>{index + 1}</span>
                    <span className={styles.stepLabel}>{label}</span>
                  </span>
                )}
              </li>
            )
          })}
        </ol>
      </div>

      <Stack as="form" gap="lg" padding="lg" noValidate onSubmit={advance} aria-label={stepTitle}>
        <Stack gap="xs">
          <Heading as="h4" key={step} ref={focusOnMount} tabIndex={-1} fontSize="md" margin="none">
            {stepTitle}
          </Heading>
          <BodySmall color="text-muted" margin="none">
            {stepDescription}
          </BodySmall>
        </Stack>

        {step === 0 && (
          <>
            <Field name="name" invalid={Boolean(errors.name)}>
              <Field.Label>Workspace name</Field.Label>
              <Field.Control
                value={setup.name}
                placeholder="e.g. Harbor Lane Studio"
                autoComplete="organization"
                onValueChange={(value) => {
                  update('name', value)
                  if (!slugEdited) update('slug', toSlug(value))
                }}
              />
              {errors.name && <Field.Error match>{errors.name}</Field.Error>}
            </Field>
            <Field name="slug" invalid={Boolean(errors.slug)}>
              <Field.Label>Workspace URL</Field.Label>
              {/* The fixed domain is the field's description, so it's read with the input. */}
              <div className={styles.suffixed}>
                <Field.Control
                  value={setup.slug}
                  spellCheck={false}
                  dangerouslySetClassName={styles.slugInput}
                  onValueChange={(value) => {
                    setSlugEdited(true)
                    update('slug', value.toLowerCase())
                  }}
                />
                <Field.Description render={<span />} dangerouslySetClassName={styles.suffix}>
                  .ledger.example
                </Field.Description>
              </div>
              {errors.slug && <Field.Error match>{errors.slug}</Field.Error>}
            </Field>
          </>
        )}

        {step === 1 && (
          <>
            <Field name="invites" invalid={Boolean(errors.invites)}>
              <Field.Label>Email addresses</Field.Label>
              <Field.Control
                render={<Textarea rows={3} />}
                value={setup.invites}
                placeholder="ada@harborlane.example, jun@harborlane.example"
                onValueChange={(value) => update('invites', value)}
              />
              <Field.Description>Separate addresses with commas or new lines. You can skip this.</Field.Description>
              {errors.invites && <Field.Error match>{errors.invites}</Field.Error>}
            </Field>
            <Stack gap="sm">
              <Text id={roleLabelId} fontSize="sm" fontWeight="semibold">
                Invite as
              </Text>
              <RadioGroup
                aria-labelledby={roleLabelId}
                value={setup.role}
                onValueChange={(value) => update('role', String(value))}
              >
                <Radio value="member">Member: creates and edits items</Radio>
                <Radio value="admin">Admin: also manages billing and members</Radio>
              </RadioGroup>
            </Stack>
          </>
        )}

        {step === 2 && (
          <>
            {/* A plain group, not a Field: a Field gives every Radio inside it the same label. */}
            <Stack gap="sm">
              <Text id={viewLabelId} fontSize="sm" fontWeight="semibold">
                Default view
              </Text>
              <RadioGroup
                aria-labelledby={viewLabelId}
                aria-describedby={errors.view ? viewErrorId : undefined}
                aria-invalid={errors.view ? true : undefined}
                value={setup.view}
                onValueChange={(value) => update('view', String(value))}
                dangerouslySetClassName={styles.views}
              >
                {views.map((view) => (
                  <Radio key={view.value} value={view.value}>
                    <span>
                      {view.label}
                      <span className={styles.viewHint}>{view.description}</span>
                    </span>
                  </Radio>
                ))}
              </RadioGroup>
              {errors.view && (
                <Text id={viewErrorId} fontSize="sm" color="danger-text">
                  {errors.view}
                </Text>
              )}
            </Stack>
            <div>
              <Label htmlFor={weekStartId}>Week starts on</Label>
              <Input.Select
                id={weekStartId}
                value={setup.weekStart}
                onChange={(event) => update('weekStart', event.currentTarget.value)}
              >
                <option value="monday">Monday</option>
                <option value="sunday">Sunday</option>
              </Input.Select>
            </div>
            <Switch checked={setup.digest} onCheckedChange={(checked) => update('digest', checked)}>
              Email everyone a summary on Monday mornings
            </Switch>
          </>
        )}

        {step === reviewStep && (
          <dl className={styles.review}>
            <div>
              <dt>Workspace</dt>
              <dd>
                <span>
                  {setup.name}
                  <span className={styles.domain}>{setup.slug}.ledger.example</span>
                </span>
                <Button type="button" variant="link" size="sm" onClick={() => goTo(0)} aria-label="Edit workspace">
                  Edit
                </Button>
              </dd>
            </div>
            <div>
              <dt>Team</dt>
              <dd>
                <span>
                  {teamSummary}
                </span>
                <Button type="button" variant="link" size="sm" onClick={() => goTo(1)} aria-label="Edit team">
                  Edit
                </Button>
              </dd>
            </div>
            <div>
              <dt>Preferences</dt>
              <dd>
                <span>
                  {preferencesSummary}
                </span>
                <Button type="button" variant="link" size="sm" onClick={() => goTo(2)} aria-label="Edit preferences">
                  Edit
                </Button>
              </dd>
            </div>
          </dl>
        )}

        <div className={styles.actions}>
          {step > 0 ? (
            <Button type="button" variant="ghost" onClick={() => goTo(step - 1)}>
              Back
            </Button>
          ) : (
            <BodySmall color="text-muted" margin="none">
              Moving from another tool? <Link href="#import">Import</Link>
            </BodySmall>
          )}
          <Button type="submit" variant="primary">
            {step === reviewStep ? 'Finish setup' : step === steps.length - 1 ? 'Review' : 'Next'}
          </Button>
        </div>
      </Stack>
    </Card>
  )
}
```

## How it works

- **The indicator is an ordered list.** The current step carries `aria-current="step"`, finished steps show a check and become buttons named “Edit Workspace (completed)” that jump back, and upcoming steps are plain text.
- **Each step validates only itself.** Next checks the current step’s fields and moves focus to the first problem. Errors then follow the fields as they’re fixed.
- **The URL shows its domain.** The workspace URL is derived from the name until the reader edits it, and its fixed `.ledger.example` suffix is the field’s `Field.Description`, joined to the input, so it’s announced with it and never wraps. A preview in the header shows the workspace’s initials, name and URL as they’re typed.
- **Focus follows the step.** Each step’s heading says what the step does, with a line of context under it. The heading is keyed by the step, so it mounts fresh and takes focus after every move, but not on the page’s first render.
- **The view choice is a plain group.** The default view is a labelled group with its own error text rather than a `Field`: a `Field` gives every `Radio` inside it the same accessible name. Each `Radio`’s label is styled as a card.

## App-owned CSS

The preview, the step indicator, the URL suffix, the view cards, the review list and the footer, which puts the primary action first and full width on a phone.

`examples/recipes/setup-wizard.module.css`:

```css
/* The live preview, step indicator, URL suffix, view cards and review list. */

.wizard {
  container-type: inline-size;
}

.header {
  display: grid;
  gap: var(--ds-space-lg);
  padding: var(--ds-space-lg);
  background: var(--ds-color-bg-subtle);
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-xl) var(--ds-border-radius-xl) 0 0;
}

.intro {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--ds-space-lg);
}

.preview {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  min-width: 0;
  margin: 0;
  padding: var(--ds-space-sm) var(--ds-space-lg) var(--ds-space-sm) var(--ds-space-sm);
  background: var(--ds-color-bg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-md);
}

.tile {
  display: grid;
  place-items: center;
  flex: none;
  width: var(--ds-control-height-lg);
  height: var(--ds-control-height-lg);
  font: var(--ds-font-weight-bold) var(--ds-font-size-sm) / 1 var(--ds-font-heading);
  color: var(--ds-color-accent-fg);
  background: var(--ds-color-accent);
  border-radius: var(--ds-border-radius-md);
}

.previewText {
  display: grid;
  min-width: 0;
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);

  & strong {
    font-size: var(--ds-font-size-sm);
    font-weight: var(--ds-font-weight-semibold);
    color: var(--ds-color-text);
  }

  & > * {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.steps {
  --marker: var(--ds-control-height-sm);
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  margin: 0;
  padding: 0;
  list-style: none;
}

.step {
  position: relative;
  display: flex;
  justify-content: center;

  /* The line joining this step to the one before it. */
  & + &::before {
    content: "";
    position: absolute;
    top: calc(var(--marker) / 2 + var(--ds-space-xs));
    right: calc(50% + var(--marker) / 2 + var(--ds-space-md));
    left: calc(-50% + var(--marker) / 2 + var(--ds-space-md));
    border-top: var(--ds-border-width-md) solid var(--ds-color-border);
  }

  &[data-state="complete"] + &::before {
    border-color: var(--ds-color-accent);
  }
}

.stepTarget {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--ds-space-sm);
  padding: var(--ds-space-xs) var(--ds-space-sm);
  font: inherit;
  color: inherit;
  background: none;
  border: 0;
  border-radius: var(--ds-border-radius-md);

  &:is(button) {
    cursor: pointer;
  }

  &:is(button):hover .stepLabel {
    color: var(--ds-color-text);
    text-decoration: underline;
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }
}

.marker {
  display: grid;
  place-items: center;
  width: var(--marker);
  height: var(--marker);
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-semibold);
  font-variant-numeric: tabular-nums;
  color: var(--ds-color-text-muted);
  background: var(--ds-color-bg);
  border: var(--ds-border-width-md) solid var(--ds-color-border);
  border-radius: var(--ds-border-radius-circle);

  [data-state="current"] & {
    color: var(--ds-color-accent-text);
    border-color: var(--ds-color-accent);
    box-shadow: 0 0 0 var(--ds-space-sm) var(--ds-color-accent-subtle);
  }

  [data-state="complete"] & {
    color: var(--ds-color-accent-fg);
    background: var(--ds-color-accent);
    border-color: var(--ds-color-accent);
  }
}

.stepLabel {
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
  text-align: center;

  [data-state="current"] & {
    font-weight: var(--ds-font-weight-semibold);
    color: var(--ds-color-text);
  }
}

/* Each view Radio's label becomes a card. */
.views {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
  gap: var(--ds-space-md);

  & > label {
    display: flex;
    align-items: flex-start;
    padding: var(--ds-space-md) var(--ds-space-lg);
    border: var(--ds-border-width-sm) solid var(--ds-color-border);
    border-radius: var(--ds-border-radius-md);

    &:hover {
      border-color: var(--ds-color-border-strong);
    }

    &:has([data-checked]) {
      background: var(--ds-color-accent-subtle);
      border-color: var(--ds-color-accent);
    }

  }

  &[aria-invalid="true"] > label {
    border-color: var(--ds-color-danger);
  }
}

.viewHint {
  display: block;
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
}

.review {
  display: grid;
  margin: 0;

  & > div {
    padding-block: var(--ds-space-md);
    border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }

  & dt {
    font-size: var(--ds-font-size-xs);
    font-weight: var(--ds-font-weight-semibold);
    color: var(--ds-color-text-muted);
  }

  & dd > span {
    min-width: 0;
  }

  & dd {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: var(--ds-space-lg);
    margin: 0;
    font-size: var(--ds-font-size-sm);
  }
}

.actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--ds-space-md);
  padding-top: var(--ds-space-lg);
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);

  /* Keep Next on the right when there's no Back button. */
  & > :last-child {
    margin-left: auto;
  }
}

.doneIcon {
  display: grid;
  place-items: center;
  width: calc(var(--ds-control-height-lg) * 1.4);
  height: calc(var(--ds-control-height-lg) * 1.4);
  color: var(--ds-color-accent-text);
  background: var(--ds-color-accent-subtle);
  border-radius: var(--ds-border-radius-circle);
}

/* The workspace URL: an input joined to its fixed domain. */
.suffixed {
  display: flex;
  min-width: 0;
}

.suffixed .slugInput {
  flex: 1;
  min-width: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.suffix {
  display: flex;
  align-items: center;
  padding-inline: var(--ds-space-md);
  white-space: nowrap;
  background: var(--ds-color-bg-subtle);
  border: var(--ds-border-width-sm) solid var(--ds-color-border);
  border-left: 0;
  border-radius: 0 var(--ds-border-radius-sm) var(--ds-border-radius-sm) 0;
}

/* On a phone the primary action comes first, full width, with Back or the helper below. */
@container (max-width: 30rem) {
  .actions {
    flex-direction: column;
    align-items: stretch;
    text-align: center;

    & > :last-child {
      order: -1;
      margin-left: 0;
    }
  }
}

/* The domain stays whole: it truncates rather than breaking mid-name. */
.domain {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--ds-color-text-muted);
}
```
