# Field

The frame every PixilUI field shares: a label row, a well with a rim you can see on white, and a message that says what's wrong in plain words, wired for screen readers.

Tier: free. Type: component. Category: inputs. Tags: form.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/field.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/field.tsx`.

## Preview

Live preview: https://pixilui.com/components/field

Knobs:

- `size`: `none`, `sm`, `md`, `lg`, `xl`

Signature: A field's rim is a full 1px you can see on a white card, and its corners are a third of its height, curved but never a pill.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/field.tsx, quiet https://pixilui.com/r/standalone/field.quiet.tsx.

## Code

`components/pixilui/field.tsx`

```tsx
"use client";

/*
  The field frame, locked 1 Dec 2026 (design/explorations/components/locked/inputs, B8). Its look and motion
  are foundation.css section 8 (.pixilui-field and its parts); this file writes the locked markup and owns
  what every field shares:

  Frame     a <label> holding the head (label, and a hint or counter), the control (the well) and the
            message. The input is named by the label alone (aria-labelledby) and described by the message
            (aria-describedby), so a hint or a counter is never read as part of its name.
  Checks    a validate function runs on blur (with a value or an error) and on Enter in a single line. A
            message it returns marks the input invalid (red ring, the warning icon wags, the message says
            why) and shakes the well once, 4px over 320ms. A promise shows the checking spinner first, then
            the done check draws. Typing clears both.
  Hover     the rim darkens in 150ms; the fill never changes. Focus is a plain 1px ring, no motion.
  Reduced   no shake; the ring and the message still say it.

  Input, Textarea, SearchField, InlineEdit, SecretField and AiField are built from these parts.
*/

import {
  createContext,
  forwardRef,
  useCallback,
  useContext,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ComponentPropsWithoutRef,
  type MouseEvent,
  type ReactNode,
  type RefObject,
} from "react";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";

export type FieldSize = "sm" | "md" | "lg" | "xl";
export type FieldKind = "area" | "reason" | "search" | "inline" | "secret";
/** What a check is doing: running (the spinner) or passed (the drawn check). */
export type FieldCheck = "checking" | "valid";
/**
 * A field's rule. Return the message that says what is wrong and how to fix it, or nothing when the value
 * is fine. Return a promise for a check that takes time (pinging a webhook): the field shows its spinner
 * until it settles. The value comes trimmed.
 */
export type FieldValidate = (value: string) => string | null | undefined | void | Promise<string | null | undefined | void>;

type FieldContextValue = {
  inputId: string;
  labelId?: string;
  messageId?: string;
  invalid: boolean;
  check?: FieldCheck;
  controlRef: RefObject<HTMLSpanElement | null>;
};

const FieldContext = createContext<FieldContextValue | null>(null);

/** The field around a part, for custom controls built from the parts. */
export function useField() {
  const ctx = useContext(FieldContext);
  if (!ctx) throw new Error("Field parts go inside a Field");
  return ctx;
}

/** A --pixilui-field-* time from the foundation, in ms (the copied and saved ticks, the stand-in check). */
export function fieldTime(el: Element | null, name: "--pixilui-field-confirm-hold" | "--pixilui-field-check-wait") {
  if (!el || typeof getComputedStyle === "undefined") return 0;
  return parseFloat(getComputedStyle(el).getPropertyValue(name)) || 0;
}

/**
 * Sets a native input's or textarea's value as typing would, so React's onChange runs for controlled and
 * uncontrolled fields alike (the clear button, Esc, a reason that lands as if typed).
 */
export function setFieldValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {
  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
  Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, value);
  el.dispatchEvent(new Event("input", { bubbles: true }));
}

/**
 * The shared rule runner. run(value) checks it (on blur and Enter); reset() is what typing does (an error
 * or a passed check goes away). shake counts errors, so the Field shakes its well once for each.
 */
export function useFieldValidation(validate?: FieldValidate) {
  const [invalid, setInvalid] = useState<string | null>(null);
  const [check, setCheck] = useState<FieldCheck | undefined>();
  const [shake, setShake] = useState(0);
  const turn = useRef(0);
  const fail = useCallback((message: string) => {
    setInvalid(message);
    setCheck(undefined);
    setShake((n) => n + 1);
  }, []);
  const run = useCallback(
    (value: string): boolean => {
      if (!validate) return true;
      const me = ++turn.current;
      const out = validate(value.trim());
      if (typeof out === "string" && out) {
        fail(out);
        return false;
      }
      setInvalid(null);
      if (out && typeof (out as Promise<unknown>).then === "function") {
        setCheck("checking");
        void (out as Promise<string | null | undefined | void>).then((message) => {
          if (me !== turn.current) return;
          if (typeof message === "string" && message) fail(message);
          else setCheck("valid");
        });
        return true;
      }
      setCheck("valid");
      return true;
    },
    [validate, fail],
  );
  const reset = useCallback(() => {
    turn.current++;
    setCheck((c) => (c === "valid" ? undefined : c));
    setInvalid(null);
  }, []);
  return { invalid, check, shake, run, reset };
}

export type FieldProps = Omit<ComponentPropsWithoutRef<"label">, "children"> & {
  /** The label above the field. Leave it out when the place already names it, and give the input an aria-label. */
  label?: ReactNode;
  /** Right of the label: "Optional", or anything short. */
  hint?: ReactNode;
  /** A counter in the hint's place: the characters typed and the limit. It turns orange at 90% of the limit. */
  count?: { value: number; max?: number; format?: (value: number, max?: number) => string };
  /** Help under the field. An error takes its place while there is one. */
  description?: ReactNode;
  /** What is wrong, in plain words. Marks the input invalid. */
  error?: ReactNode;
  /** Keep an (empty) message line in the markup even with no help, for a field whose rule may speak later. */
  reserveMessage?: boolean;
  /** The button height of the same name: sm 28, md 32, lg 36, xl 44. With none, a lively field is 40 and a quiet one 36. */
  size?: FieldSize;
  /** The kind of field, which changes its well (set by the items built on Field). */
  kind?: FieldKind;
  /** The AI field's still gradient rim (lively; quiet keeps the plain rim). */
  glow?: "ai";
  /** A check in progress or passed. */
  check?: FieldCheck;
  /** The field holds a value (search shows its clear button and hides its shortcut). */
  filled?: boolean;
  /** Inline edit only: editing now. */
  editing?: boolean;
  /** Inline edit only: just saved (the tick shows). */
  saved?: boolean;
  /** Counts errors: each new number shakes the well once. */
  shake?: number;
  /** The input's id; one is made when you leave it out. */
  inputId?: string;
  /** The control: a FieldControl holding the input and its parts. */
  children: ReactNode;
};

/** The shared field frame: the label row, the well and the message, wired for screen readers. */
export const Field = forwardRef<HTMLLabelElement, FieldProps>(function Field(
  { label, hint, count, description, error, reserveMessage, size, kind, glow, check, filled, editing, saved, shake = 0, inputId, className, children, ...props },
  ref,
) {
  const made = useId();
  const controlRef = useRef<HTMLSpanElement | null>(null);
  const id = inputId ?? `${made}-input`;
  const labelId = label != null ? `${made}-label` : undefined;
  const hasMessage = error != null || description != null;
  const messageId = hasMessage ? `${made}-message` : undefined;
  const invalid = error != null && error !== false;
  const ctx = useMemo(() => ({ inputId: id, labelId, messageId, invalid, check, controlRef }), [id, labelId, messageId, invalid, check]);

  // an error shakes the well once (restarted for each new one); reduced motion keeps the ring and the words
  useLayoutEffect(() => {
    const el = controlRef.current;
    if (!shake || !el || prefersReducedMotion()) return;
    delete el.dataset.shake;
    void el.offsetWidth;
    el.dataset.shake = "";
  }, [shake]);

  const near = count?.max ? count.value >= count.max * 0.9 : false;
  const countText = count ? (count.format ? count.format(count.value, count.max) : count.max ? `${count.value} / ${count.max}` : String(count.value)) : null;

  return (
    <FieldContext.Provider value={ctx}>
      <label
        ref={ref}
        className={cn("pixilui-field font-body", className)}
        data-size={size}
        data-kind={kind}
        data-glow={glow}
        data-state={check}
        data-filled={filled ? "" : undefined}
        data-editing={editing ? "" : undefined}
        data-saved={saved ? "" : undefined}
        {...props}
      >
        {label != null || hint != null || count ? (
          <span className="pixilui-field-head">
            {label != null ? (
              <span className="pixilui-field-label" id={labelId}>
                {label}
              </span>
            ) : null}
            {count ? (
              <span className="pixilui-field-hint" data-count={count.max ?? ""} data-near={near ? "" : undefined}>
                {countText}
              </span>
            ) : hint != null ? (
              <span className="pixilui-field-hint">{hint}</span>
            ) : null}
          </span>
        ) : null}
        {children}
        {hasMessage || reserveMessage ? (
          <span className="pixilui-field-message" id={messageId} data-for={invalid ? "error" : undefined} hidden={!hasMessage} aria-live="polite">
            {invalid ? <span>{error}</span> : description}
          </span>
        ) : null}
      </label>
    </FieldContext.Provider>
  );
});

export type FieldControlProps = ComponentPropsWithoutRef<"span">;

/** The well: rim, fill, corners and height. A click anywhere on it puts the caret at the end. */
export const FieldControl = forwardRef<HTMLSpanElement, FieldControlProps>(function FieldControl({ className, onMouseDown, onAnimationEnd, ...props }, ref) {
  const { controlRef } = useField();
  const setRef = useCallback(
    (el: HTMLSpanElement | null) => {
      controlRef.current = el;
      if (typeof ref === "function") ref(el);
      else if (ref) ref.current = el;
    },
    [controlRef, ref],
  );
  const toEnd = (event: MouseEvent<HTMLSpanElement>) => {
    onMouseDown?.(event);
    if (event.defaultPrevented || event.target !== event.currentTarget) return;
    const input = event.currentTarget.querySelector<HTMLInputElement | HTMLTextAreaElement>(".pixilui-field-input");
    if (!input || input.disabled) return;
    event.preventDefault();
    input.focus();
    const n = input.value.length;
    try {
      input.setSelectionRange(n, n);
    } catch {
      // some input types (email, number) have no selection
    }
  };
  return (
    <span
      ref={setRef}
      className={cn("pixilui-field-control", className)}
      onMouseDown={toEnd}
      onAnimationEnd={(event) => {
        onAnimationEnd?.(event);
        if (event.animationName === "pixilui-field-shake") delete event.currentTarget.dataset.shake;
      }}
      {...props}
    />
  );
});

/** The native input, named by the field's label and described by its message. */
export const FieldInput = forwardRef<HTMLInputElement, ComponentPropsWithoutRef<"input">>(function FieldInput({ className, ...props }, ref) {
  const { inputId, labelId, messageId, invalid } = useField();
  return (
    <input
      ref={ref}
      id={inputId}
      aria-labelledby={labelId}
      aria-describedby={messageId}
      aria-invalid={invalid || undefined}
      className={cn("pixilui-field-input", className)}
      {...props}
    />
  );
});

/** The native textarea, wired the same way. */
export const FieldTextarea = forwardRef<HTMLTextAreaElement, ComponentPropsWithoutRef<"textarea">>(function FieldTextarea({ className, ...props }, ref) {
  const { inputId, labelId, messageId, invalid } = useField();
  return (
    <textarea
      ref={ref}
      id={inputId}
      aria-labelledby={labelId}
      aria-describedby={messageId}
      aria-invalid={invalid || undefined}
      className={cn("pixilui-field-input", className)}
      {...props}
    />
  );
});

type SideProps = ComponentPropsWithoutRef<"span"> & {
  /** A unit ($, / day, USD): the help color instead of the icon color. */
  unit?: boolean;
};

/** Before the value: an icon or a unit. */
export const FieldPrefix = forwardRef<HTMLSpanElement, SideProps>(function FieldPrefix({ unit, className, ...props }, ref) {
  return <span ref={ref} className={cn("pixilui-field-prefix", unit && "pixilui-field-unit", className)} {...props} />;
});

/** After the value: a unit, a shortcut hint, status icons, icon buttons. */
export const FieldSuffix = forwardRef<HTMLSpanElement, SideProps>(function FieldSuffix({ unit, className, ...props }, ref) {
  return <span ref={ref} className={cn("pixilui-field-suffix", unit && "pixilui-field-unit", className)} {...props} />;
});

export type FieldStatusProps = Omit<ComponentPropsWithoutRef<"span">, "children"> & {
  /** Which moment the icon shows: the check running, passed, or an error. */
  for: "checking" | "valid" | "error";
  /** The icon: the animated loading, done and warning icons play from the state the field sets. */
  icon: ReactNode;
};

/** A status icon in the suffix, shown only in its moment: the spinner turns, the check draws, the warning wags. */
export const FieldStatus = forwardRef<HTMLSpanElement, FieldStatusProps>(function FieldStatus({ for: moment, icon, className, ...props }, ref) {
  const { check, invalid } = useField();
  const state = moment === "valid" && check === "valid" ? "done" : moment === "error" && invalid ? "warning" : undefined;
  return (
    <span ref={ref} className={cn("pixilui-field-status", className)} data-for={moment} data-state={state} data-working={moment === "checking" && check === "checking" ? "" : undefined} {...props}>
      {icon}
    </span>
  );
});

/** A round icon button inside the field (clear, show, copy): the icon plus 4px around it, pulled back into the side. */
export const FieldIconButton = forwardRef<HTMLButtonElement, ComponentPropsWithoutRef<"button"> & { "aria-label": string }>(function FieldIconButton({ className, type = "button", ...props }, ref) {
  return <button ref={ref} type={type} className={cn("pixilui-field-icon-btn", className)} {...props} />;
});

/** The shortcut that focuses the field, shown at rest without a value (⌘K). */
export const FieldHintKey = forwardRef<HTMLSpanElement, ComponentPropsWithoutRef<"span">>(function FieldHintKey({ className, ...props }, ref) {
  return <span ref={ref} className={cn("pixilui-field-hint-key", className)} {...props} />;
});
```

## Usage

When to use:

- Building your own control from the parts (FieldControl, FieldInput, FieldPrefix, FieldSuffix, FieldStatus) when Input, Textarea or the others do not fit.

When not to use:

- A plain text field: use Input, which is this frame already wired.

```tsx
import { IconWarning } from "@/components/pixilui/icons/warning";
import { Field, FieldControl, FieldInput, FieldStatus, FieldSuffix, useFieldValidation, type FieldSize } from "@/components/pixilui/field";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  size: ["none", "sm", "md", "lg", "xl"],
} as const;

/** A custom field built from the parts: a retry limit with its unit and rule. */
export default function FieldDemo({ size = "none" }: KnobValues<typeof knobs>) {
  const rule = useFieldValidation((v) => (Number(v) > 5 ? "Retry at most 5 times, then the run waits for you" : null));
  return (
    <div className="w-full max-w-sm">
      <Field label="Retries" description="Failed runs try again this many times" error={rule.invalid ?? undefined} check={rule.check} shake={rule.shake} size={size === "none" ? undefined : (size as FieldSize)}>
        <FieldControl>
          <FieldInput type="text" inputMode="numeric" defaultValue="2" onBlur={(e) => rule.run(e.currentTarget.value)} onChange={rule.reset} />
          <FieldSuffix unit>times</FieldSuffix>
          <FieldSuffix>
            <FieldStatus for="error" icon={<IconWarning />} />
          </FieldSuffix>
        </FieldControl>
      </Field>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `ReactNode` |  | The label above the field. Leave it out when the place already names it, and give the input an aria-label. |
| `hint` | `ReactNode` |  | Right of the label: "Optional", or anything short. |
| `count` | `{ value: number; max?: number; format?: (value: number, max?: number) => string }` |  | A counter in the hint's place: the characters typed and the limit. It turns orange at 90% of the limit. |
| `description` | `ReactNode` |  | Help under the field. An error takes its place while there is one. |
| `error` | `ReactNode` |  | What is wrong, in plain words. Marks the input invalid. |
| `reserveMessage` | `boolean` |  | Keep an (empty) message line in the markup even with no help, for a field whose rule may speak later. |
| `size` | `"sm" \| "md" \| "lg" \| "xl"` |  | The button height of the same name: sm 28, md 32, lg 36, xl 44. With none, a lively field is 40 and a quiet one 36. |
| `kind` | `"area" \| "reason" \| "search" \| "inline" \| "secret"` |  | The kind of field, which changes its well (set by the items built on Field). |
| `glow` | `"ai"` |  | The AI field's still gradient rim (lively; quiet keeps the plain rim). |
| `check` | `"checking" \| "valid"` |  | A check in progress or passed. |
| `filled` | `boolean` |  | The field holds a value (search shows its clear button and hides its shortcut). |
| `editing` | `boolean` |  | Inline edit only: editing now. |
| `saved` | `boolean` |  | Inline edit only: just saved (the tick shows). |
| `shake` | `number` | `0` | Counts errors: each new number shakes the well once. |
| `inputId` | `string` |  | The input's id; one is made when you leave it out. |
| `children` (required) | `ReactNode` |  | The control: a FieldControl holding the input and its parts. |

Also accepts every native `<label>` attribute, and a ref to it.

## Keyboard

- `Tab`: Moves into the input; the frame itself never takes focus.

## Accessibility

- The label names the input (aria-labelledby) and the help or error describes it (aria-describedby), so a hint or a counter is never read as its name.
- An error sets aria-invalid and says what is wrong in words; the color is never the only sign.
- useFieldValidation runs a rule on blur and Enter and counts errors so the well shakes once for each.

## Motion

- The rim darkens in 150ms on hover; focus is a plain 1px ring with no motion.
- An error shakes the well once, 4px over 320ms. Reduced motion: no shake, the ring and the words still say it.

## Responsive

- Fills its container's width; the label row and the message wrap.

## Performance

- Native typing: nothing renders per key beyond the value; the look is CSS in the foundation (section 8).

## Notes for AI

- <Field label="Webhook" description="..." error={error}><FieldControl><FieldInput /></FieldControl></Field>.
- Sizes match the buttons: sm 28, md 32, lg 36, xl 44; with none a lively field is 40 and a quiet one 36.
- useFieldValidation(validate) gives { invalid, check, shake, run, reset } for custom controls.

## Related

- [Input](https://pixilui.com/components/input/markdown): A text field with its label, help and error, a unit or icon on either side, and a rule that checks on blur and Enter and says what's wrong in plain words.
- [Textarea](https://pixilui.com/components/textarea/markdown): A text area that opens at three lines and grows to eight as you write, with a counter that turns orange near its limit; its reason kind is where saying no to an agent comes with a why.
- [Search field](https://pixilui.com/components/search-field/markdown): A search field with its ⌘K hint at rest, a clear button once there is text, Esc to clear, and Enter that never fires mid-composition.
