# Field

Labels, descriptions, red-pen errors, fieldsets and choice cards: shadcn's field layout, drawn.

Docs: https://ballpoint.st9wd.com/docs/field

```bash
npx shadcn@latest add @ballpoint/field
```

```tsx
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

<Field data-invalid>
  <FieldLabel htmlFor="email">Email</FieldLabel>
  <Input id="email" aria-invalid />
  <FieldDescription>We only write when it matters.</FieldDescription>
  <FieldError>That email is missing its domain.</FieldError>
</Field>
```

Props:

- `Field orientation`: `"vertical" | "horizontal" | "responsive"` (default `"vertical"`). Label above the control, beside it, or beside it once the group is wide enough.
- `FieldLegend variant`: `"legend" | "label"` (default `"legend"`). A fieldset title, or one sized like a label.
- `FieldError errors`: `{ message?: string }[]`. Shows each unique message; children win if given.

## Example

```tsx
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSeparator,
  FieldSet,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";

export default function FieldDemo() {
  return (
    <form className="w-full max-w-lg">
      <FieldGroup>
        <FieldSet>
          <FieldLegend>Book a call</FieldLegend>
          <FieldDescription>Thirty minutes, no slides.</FieldDescription>
          <FieldGroup>
            <Field>
              <FieldLabel htmlFor="form-name">Name</FieldLabel>
              <Input id="form-name" placeholder="Ada Lovelace" seed="form-name" />
            </Field>
            <Field data-invalid>
              <FieldLabel htmlFor="form-email">Email</FieldLabel>
              <Input id="form-email" type="email" defaultValue="ada@" aria-invalid seed="form-email" />
              <FieldError>That email is missing its domain.</FieldError>
            </Field>
            <Field>
              <FieldLabel htmlFor="form-about">What&apos;s it about?</FieldLabel>
              <Textarea id="form-about" placeholder="A sentence or two is plenty." seed="form-about" />
            </Field>
          </FieldGroup>
        </FieldSet>
        <FieldSeparator>When</FieldSeparator>
        <FieldSet>
          <FieldLegend variant="label">Time of day</FieldLegend>
          <RadioGroup defaultValue="morning">
            {["Morning", "Afternoon"].map((t) => (
              <Field key={t} orientation="horizontal">
                <RadioGroupItem value={t.toLowerCase()} id={`form-${t}`} seed={`form-${t}`} />
                <FieldLabel htmlFor={`form-${t}`}>{t}</FieldLabel>
              </Field>
            ))}
          </RadioGroup>
        </FieldSet>
        <Field orientation="horizontal">
          <FieldContent>
            <FieldLabel htmlFor="form-remind">Remind me</FieldLabel>
            <FieldDescription>An email the day before.</FieldDescription>
          </FieldContent>
          <Switch id="form-remind" defaultChecked seed="form-remind" />
        </Field>
        <Field orientation="horizontal">
          <Checkbox id="form-terms" seed="form-terms" />
          <FieldLabel htmlFor="form-terms">I&apos;ve read the small print</FieldLabel>
        </Field>
        <Field orientation="horizontal">
          <Button type="submit" seed="form-submit">
            Send
          </Button>
          <Button variant="ghost" type="reset" seed="form-reset">
            Clear
          </Button>
        </Field>
      </FieldGroup>
    </form>
  );
}
```

## Settings list

A fieldset of horizontal fields, each with a title, a hint and a switch.

```tsx
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel, FieldLegend, FieldSeparator, FieldSet } from "@/components/ui/field";
import { Switch } from "@/components/ui/switch";

const settings = [
  ["draw", "Draw things in", "Strokes draw themselves as they scroll into view.", true],
  ["night", "Follow the lamp", "Switch to the night paper after dark.", true],
  ["sound", "Pen scratch", "A quiet scratch while a line is drawn.", false],
] as const;

export default function FieldSettings() {
  return (
    <FieldSet className="w-full max-w-md">
      <FieldLegend>Pen settings</FieldLegend>
      <FieldGroup className="gap-5">
        {settings.map(([id, title, description, on], i) => (
          <div key={id} className="contents">
            {i > 0 && <FieldSeparator />}
            <Field orientation="horizontal">
              <FieldContent>
                <FieldLabel htmlFor={`fs-${id}`}>{title}</FieldLabel>
                <FieldDescription>{description}</FieldDescription>
              </FieldContent>
              <Switch id={`fs-${id}`} defaultChecked={on} seed={`fs-${id}`} />
            </Field>
          </div>
        ))}
      </FieldGroup>
    </FieldSet>
  );
}
```

## Several errors

Give FieldError a list of errors and it shows each distinct message once.

```tsx
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";

// Hand FieldError a list (from a schema validator, say) and it shows each message once.
const errors = [{ message: "Use at least 8 characters." }, { message: "Add a number." }, { message: "Add a number." }];

export default function FieldErrors() {
  return (
    <div className="grid w-full max-w-md gap-6">
      <Field data-invalid>
        <FieldLabel htmlFor="fe-password">Password</FieldLabel>
        <Input id="fe-password" type="password" aria-invalid defaultValue="ink" seed="fe-password" />
        <FieldError errors={errors} />
      </Field>
      <Field>
        <FieldLabel htmlFor="fe-hint">Display name</FieldLabel>
        <Input id="fe-hint" placeholder="Ada" seed="fe-hint" />
        <FieldDescription>Shown beside your notes. You can change it later.</FieldDescription>
      </Field>
    </div>
  );
}
```

## A whole form

Grouped fields, a radio set and a textarea, checked when submitted.

```tsx
"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel, FieldLegend, FieldSet } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Textarea } from "@/components/ui/textarea";

export default function FieldForm() {
  const [errors, setErrors] = useState<{ name?: string; email?: string }>({});
  const [sent, setSent] = useState(false);
  return (
    <form
      noValidate
      className="w-full max-w-md"
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        const next: typeof errors = {};
        if (!String(data.get("name")).trim()) next.name = "Tell us what to call you.";
        if (!/^\S+@\S+\.\S+$/.test(String(data.get("email")))) next.email = "That doesn't look like an email.";
        setErrors(next);
        setSent(Object.keys(next).length === 0);
      }}
    >
      <FieldSet>
        <FieldLegend>Book a lesson</FieldLegend>
        <FieldDescription>Left-handed or right-handed, we have pens for both.</FieldDescription>
        <FieldGroup>
          <Field data-invalid={errors.name ? true : undefined}>
            <FieldLabel htmlFor="ff-name">Name</FieldLabel>
            <Input id="ff-name" name="name" aria-invalid={!!errors.name} seed="ff-name" />
            {errors.name && <FieldError>{errors.name}</FieldError>}
          </Field>
          <Field data-invalid={errors.email ? true : undefined}>
            <FieldLabel htmlFor="ff-email">Email</FieldLabel>
            <Input id="ff-email" name="email" type="email" aria-invalid={!!errors.email} seed="ff-email" />
            {errors.email && <FieldError>{errors.email}</FieldError>}
          </Field>
          <FieldSet>
            <FieldLegend variant="label">Which hand?</FieldLegend>
            <RadioGroup name="hand" defaultValue="right" orientation="horizontal" aria-label="Which hand">
              {["Right", "Left"].map((hand) => (
                <Field key={hand} orientation="horizontal">
                  <RadioGroupItem value={hand.toLowerCase()} id={`ff-${hand}`} seed={`ff-${hand}`} />
                  <FieldLabel htmlFor={`ff-${hand}`}>{hand}</FieldLabel>
                </Field>
              ))}
            </RadioGroup>
          </FieldSet>
          <Field>
            <FieldLabel htmlFor="ff-note">Anything else</FieldLabel>
            <Textarea id="ff-note" name="note" rows={3} seed="ff-note" />
          </Field>
          <Field orientation="horizontal">
            <Checkbox id="ff-updates" name="updates" defaultChecked seed="ff-updates" />
            <FieldLabel htmlFor="ff-updates">Send me updates</FieldLabel>
          </Field>
          <div className="flex items-center gap-4">
            <Button type="submit" seed="ff-submit">
              Book it
            </Button>
            {sent && <span className="text-ink-2">Booked. See you Tuesday.</span>}
          </div>
        </FieldGroup>
      </FieldSet>
    </form>
  );
}
```
