# Input

Single-line text field and Field (label, hint, error).

Live variants: https://design.arcadia.is/components/input

```tsx
import { Input, Field } from "@arcadia/ui";
```

## In context

Correct the folder path to clear the error.

```tsx
import { useState } from "react";
import { Field, Input } from "@arcadia/ui";

function Fields() {
  const [folder, setFolder] = useState("projects/acme-wbe");
  const error = folder.trim() !== "projects/acme-web" ? "Folder not found. Try projects/acme-web." : null;
  return (
    <div {...sx("cmp-form", cmp.form)}>
      <Field label="Project name">
        <Input defaultValue="Acme web" />
      </Field>
      <Field label="Folder" error={error}>
        <Input
          value={folder}
          leadingIcon="folder"
          onChange={(e) => setFolder(e.target.value)}
        />
      </Field>
      <Field label="Project ID" disabled>
        <Input defaultValue="acme-web" mono />
      </Field>
    </div>
  );
}
```

## When to use

- Enter one line of text in a labelled field.
- Search, rename or edit an address in place.

## When not to use

- Use `Textarea` for multiple lines.
- Use `DateField` for a date.

## Usage

```tsx
import { Field, Input } from "@arcadia/ui";

<Field label="API URL" hint="Any OpenAI-compatible endpoint works.">
  <Input type="url" placeholder="https://api.example.com/v1" />
</Field>
```

Wrap an input in `Field` to connect its label, hint and error.

Put the format in the placeholder and the fix in the error.

Focus strengthens the border. Invalid fields keep their danger ink.

Use compact density for Body fields with trailing controls. Touch keeps Headline.

## Examples

### Slots

Add a leading icon or place a shortcut at the end.

```tsx
import { useState } from "react";
import { Input, Kbd, Spinner } from "@arcadia/ui";

function Slots() {
  const [query, setQuery] = useState("compaction");
  return (
    <div {...sx("cmp-form", cmp.form)}>
      <Input density="compact" type="search" leadingIcon="search" aria-label="Compact search" defaultValue="Search" />
      <Input density="compact" type="search" aria-label="Compact trailing search" defaultValue="Search" />
      <Input type="search" aria-label="Trailing search" defaultValue="Search" />
      <Input
        leadingIcon="search"
        placeholder="Search settings"
        aria-label="Search settings"
        end={<Kbd keys="mod+k" variant="plain" />}
      />
      <Input
        type="search"
        leadingIcon="search"
        aria-label="Search"
        value={query}
        onValueChange={setQuery}
      />
      <Input
        leadingIcon="globe"
        aria-label="API URL"
        defaultValue="https://api.example.com/v1"
        end={<Spinner size="sm" label="Checking" />}
      />
    </div>
  );
}
```

### Ghost

Use a ghost field where the surrounding surface supplies the frame.

```tsx
import { Input } from "@arcadia/ui";

<Input variant="ghost" leadingIcon="search" placeholder="Search projects and chats" aria-label="Search" />
```

### On its container's edge

Keep the text aligned when it turns into an editable field.

```tsx
import { Card, CardBody, Input } from "@arcadia/ui";

<div {...sx("input-edge", edge.pair)}>
  <Card><CardBody><p {...sx("input-edge-text", edge.text)}>Release checklist</p></CardBody></Card>
  <Card><CardBody><Input variant="edge" aria-label="Title" defaultValue="Release checklist" /></CardBody></Card>
</div>
```

### Bar

Show a shorter address until the field receives focus.

```tsx
import { useRef, useState } from "react";
import { Button, Field, IconButton, Input } from "@arcadia/ui";

function Bar() {
  const value = "https://docs.example.com/guides/getting-started";
  return (
    <Input
      variant="bar"
      size="sm"
      aria-label="Address"
      value={value}
      rest={value.replace(/^https:\/\//, "")}
      readOnly
      end={<IconButton icon="external" label="Open elsewhere" size="xs" tone="muted" />}
    />
  );
}

function Mono() {
  return (
    <Input mono placeholder="XXXX-XXXX" aria-label="One-time code" />
  );
}

function Digits() {
  const [left, setLeft] = useState("20");
  return (
    <Field label="Switch at, percent left">
      <Input digits={2} inputMode="numeric" value={left} onValueChange={setLeft} />
    </Field>
  );
}

function TitleSizes() {
  return (
    <div {...sx("input-title-sizes", widths.titles)}>
      <Input size="xl" aria-label="Column title" defaultValue="In review" />
      <Input size="2xl" aria-label="Board title" defaultValue="Launch plan" />
      <Input size="3xl" aria-label="Project title" defaultValue="Acme web" />
    </div>
  );
}

function InAForm() {
  const [email, setEmail] = useState("");

  const [left, setLeft] = useState(false);
  const [sent, setSent] = useState(false);
  const field = useRef<HTMLInputElement>(null);
  const wrong = email.includes("@") ? null : "Enter an email address, like ada@example.com.";
  const error = wrong && (sent || (left && email.trim() !== "")) ? wrong : null;
  const submit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSent(true);
    if (wrong) field.current?.focus();
  };
  return (
    <form {...sx("cmp-form", cmp.form)} onSubmit={submit} noValidate>
      <Field label="Email" error={error}>
        <Input
          ref={field}
          type="email"
          name="email"
          autoComplete="email"
          required
          value={email}

          onChange={(e) => { setEmail(e.target.value); if (!error) setLeft(false); }}
          onBlur={(e) => setLeft(e.target.value.trim() !== "")}
        />
      </Field>
      <div {...sx("cmp-form-actions", cmp.formActions)}>
        <Button type="submit" variant="primary">Send link</Button>
      </div>
    </form>
  );
}

type State = { label: string; props: Record<string, unknown>; force?: string };
const STATES: Col<State>[] = [
  { label: "Rest", value: { label: "Rest", props: { placeholder: "Search" } } },
  { label: "Hover", forced: true, value: { label: "Hover", props: { placeholder: "Search" }, force: "hover" } },
  { label: "Focus", forced: true, value: { label: "Focus", props: { placeholder: "Search" }, force: "focus-within" } },
  { label: "Filled", value: { label: "Filled", props: { defaultValue: "project" } } },
  { label: "Invalid", value: { label: "Invalid", props: { defaultValue: "!project", invalid: true } } },
  { label: "Disabled", value: { label: "Disabled", props: { placeholder: "Search", disabled: true } } },
];

export default function InputPage() {
  return (
    <>
      <Section title="In context">
        <Specimen code={SRC.Fields} caption="Correct the folder path to clear the error."><Fields /></Specimen>
      </Section>

      <Section title="When to use">
        <Bullets items={[
          "Enter one line of text in a labelled field.",
          "Search, rename or edit an address in place.",
        ]} />
      </Section>

      <Section title="When not to use">
        <Bullets items={[
          "Use `Textarea` for multiple lines.",
          "Use `DateField` for a date.",
        ]} />
      </Section>

      <Section title="Usage">
        <CodeBlock code={displaySnippet(SRC.Usage)} />
        <P>Wrap an input in `Field` to connect its label, hint and error.</P>
        <P>Put the format in the placeholder and the fix in the error.</P>
        <P>Focus strengthens the border. Invalid fields keep their danger ink.</P>
        <P>Use compact density for Body fields with trailing controls. Touch keeps Headline.</P>
      </Section>
      <Section title="Examples">
        <Sub title="Slots">
          <Specimen code={SRC.Slots} caption="Add a leading icon or place a shortcut at the end."><Slots /></Specimen>
        </Sub>
        <Sub title="Ghost">
          <Specimen code={SRC.Ghost} layout="stretch" size="compact" caption="Use a ghost field where the surrounding surface supplies the frame."><Ghost /></Specimen>
        </Sub>
        <Sub title="On its container's edge">
          <Specimen code={SRC.OnTheEdge} layout="stretch" caption="Keep the text aligned when it turns into an editable field."><OnTheEdge /></Specimen>
        </Sub>
        <Sub title="Bar">
          <Specimen code={SRC.Bar} size="compact" caption="Show a shorter address until the field receives focus."><Bar /></Specimen>
        </Sub>
        <Sub title="Mono">
          <Specimen code={SRC.Mono} size="compact" caption="Use mono for codes and paths, not for a person’s words."><Mono /></Specimen>
        </Sub>
        <Sub title="Digits">
          <Specimen code={SRC.Digits} size="compact" caption="Use `digits` and a numeric keyboard for short, aligned numbers."><Digits /></Specimen>
        </Sub>
        <Sub title="Title sizes">
          <Specimen code={SRC.TitleSizes} layout="stretch" caption="Use `xl`, `2xl` and `3xl` to edit Title 3, Title 2 and Title 1 text."><TitleSizes /></Specimen>
        </Sub>
        <Sub title="In a form">
          <Specimen code={SRC.InAForm} caption="Submit an invalid address, then correct it to clear the error."><InAForm /></Specimen>
        </Sub>
        <Sub title="An error">
          <Specimen code={SRC.ErrorLine} caption="Tell people how to fix an error or give them an override."><ErrorLine /></Specimen>
        </Sub>
      </Section>
      <Section title="Matrix">
        <Matrix
          title="Size and state"
          rows={["sm", "md", "lg"] satisfies InputSize[]}
          cols={STATES}
          cell={(size, s) => {
            const input = <Input size={size} aria-label={s.label} rootStyle={widths.cell} {...s.props} />;
            return s.force ? <Force state={s.force}>{input}</Force> : input;
          }}
        />
      </Section>

      <Section title="Customising" lead="Set field layout and override the input’s documented knobs.">
        <CodeBlock code={CUSTOMISE} />
        <Knobs type="InputKnobs" label="Input knobs" />
        <P>Invalid styling takes precedence over custom focus and border colours.</P>
      </Section>
    </>
  );
}

export function Notes() {
  return (
    <Section title="Accessibility">
      <P>
        {"A native `<input>`. Inside `Field`, the label's `for`, `aria-describedby` (hint and error) and `aria-invalid` are wired for you, and an `error` always shows, announced in a live region. The error's glyph is decorative. The `leadingIcon` is decorative and the `end` slot's controls carry their own labels."}
      </P>
      <P>
        {"Without a `Field`, name the input yourself: a `<label htmlFor>` or `aria-label`. A placeholder is not a label; it disappears as soon as someone types."}
      </P>
      <P>
        Pass `required` for a required field and say so in the label text too. An error appears when it is set, so on submit
        move focus to the first invalid field (or to a summary with `role="alert"`) to have it announced. Give `autoComplete`
        a real value (`email`, `name`, `url`) so browsers and password managers can fill it, and `off` only for search fields.
        A field the browser fills keeps the kit's own ground and text colour, in both themes, so autofill never paints over
        the system.
      </P>
      <P>
        {"A `bar` field's `end` slot is hidden while the value is edited but stays in the Tab order, and shows when it takes keyboard focus. Its `rest` readout is what a screen reader hears until the field is focused, so keep it a faithful short form of the value."}
      </P>
      <P>
        {"A `type=\"search\"` field hides the browser's own clear and draws one button named Clear search while it holds text, in any variant. It empties the field as typing would, so `onChange` and `onValueChange` hear it, and focus stays in the field. It is out of the Tab order because Escape does the same from the field; with the field empty, Escape passes on and closes what holds it."}
      </P>
      <Keys rows={[["Tab", "Moves into and out of the field"], ["Enter", "Submits the surrounding form"], ["Escape", "In a search field with text, clears it"]]} />
    </Section>
  );
}
```

### Mono

Use mono for codes and paths, not for a person’s words.

```tsx
import { Input } from "@arcadia/ui";

<Input mono placeholder="XXXX-XXXX" aria-label="One-time code" />
```

### Digits

Use `digits` and a numeric keyboard for short, aligned numbers.

```tsx
import { useState } from "react";
import { Field, Input } from "@arcadia/ui";

function Digits() {
  const [left, setLeft] = useState("20");
  return (
    <Field label="Switch at, percent left">
      <Input digits={2} inputMode="numeric" value={left} onValueChange={setLeft} />
    </Field>
  );
}
```

### Title sizes

Use `xl`, `2xl` and `3xl` to edit Title 3, Title 2 and Title 1 text.

```tsx
import { Input } from "@arcadia/ui";

<div {...sx("input-title-sizes", widths.titles)}>
  <Input size="xl" aria-label="Column title" defaultValue="In review" />
  <Input size="2xl" aria-label="Board title" defaultValue="Launch plan" />
  <Input size="3xl" aria-label="Project title" defaultValue="Acme web" />
</div>
```

### In a form

Submit an invalid address, then correct it to clear the error.

```tsx
import { useRef, useState } from "react";
import { Button, Field, Input } from "@arcadia/ui";

function InAForm() {
  const [email, setEmail] = useState("");

  const [left, setLeft] = useState(false);
  const [sent, setSent] = useState(false);
  const field = useRef<HTMLInputElement>(null);
  const wrong = email.includes("@") ? null : "Enter an email address, like ada@example.com.";
  const error = wrong && (sent || (left && email.trim() !== "")) ? wrong : null;
  const submit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSent(true);
    if (wrong) field.current?.focus();
  };
  return (
    <form {...sx("cmp-form", cmp.form)} onSubmit={submit} noValidate>
      <Field label="Email" error={error}>
        <Input
          ref={field}
          type="email"
          name="email"
          autoComplete="email"
          required
          value={email}

          onChange={(e) => { setEmail(e.target.value); if (!error) setLeft(false); }}
          onBlur={(e) => setLeft(e.target.value.trim() !== "")}
        />
      </Field>
      <div {...sx("cmp-form-actions", cmp.formActions)}>
        <Button type="submit" variant="primary">Send link</Button>
      </div>
    </form>
  );
}
```

### An error

Tell people how to fix an error or give them an override.

```tsx
import { Button, Field, Input } from "@arcadia/ui";

<div {...sx("cmp-form", cmp.form)}>
  <Field label="Folder" error="No folder at projects/acme-wbe. Pick one from the list, or create it first.">
    <Input defaultValue="projects/acme-wbe" leadingIcon="folder" />
  </Field>
  <Field label="Project key" error="The team already uses the key acme."
    action={<Button size="sm" variant="secondary">Use it anyway</Button>}>
    <Input defaultValue="acme" />
  </Field>
</div>
```

## Matrix

Size and state

Rows: Small, Medium, Large. Columns: Rest, Hover, Focus, Filled, Invalid, Disabled.

## Customising

Set field layout and override the input’s documented knobs.

```tsx
import * as stylex from "@stylexjs/stylex";

const styles = stylex.create({
  search: { "--input-h": "var(--control-lg)", "--input-px": "var(--space-3)", maxWidth: "var(--home-width)" },
});

<Input placeholder="Search" leadingIcon="search" rootStyle={styles.search} />
```

- `--input-w` (`"auto" | "100%" | Ref<Measure> | Derived`, default `var(--input-field-w, auto)`): Width: `auto`, its text's natural size. A container that sizes its fields sets `--input-field-w` instead (a settings page's row does).
- `--input-h` (`Ref<Control>`, default `initial`): Height.
- `--input-px` (`Ref<Space>`, default `initial`): Inline padding.
- `--input-radius` (`Ref<Radius>`): Corner radius (8, or the inset step 6 inside a card).
- `--input-bg` (`Paint`, default `transparent`): Fill.
- `--input-fg` (`Paint`, default `var(--text-1)`): Text colour.
- `--input-fg-disabled` (`Paint`, default `var(--text-4)`): Text colour when disabled.
- `--input-placeholder` (`Paint`, default `var(--text-3)`): Placeholder colour.
- `--input-icon` (`Paint`, default `var(--icon-3)`): Leading glyph colour.
- `--input-icon-disabled` (`Paint`, default `var(--icon-4)`): Leading glyph colour when disabled.
- `--input-border` (`Paint`, default `var(--stroke-field)`): Frame colour (1px) at rest.
- `--input-border-hover` (`Paint`, default `color-mix(in srgb, var(--stroke-field) 76%, var(--ink) 24%)`): Frame colour under the pointer.
- `--input-border-focus` (`Paint`, default `var(--stroke-field)`): Frame colour while the field has focus.
- `--input-border-disabled` (`Paint`, default `var(--stroke-4)`): Frame colour when disabled.

Invalid styling takes precedence over custom focus and border colours.

## Accessibility

A native `<input>`. Inside `Field`, the label's `for`, `aria-describedby` (hint and error) and `aria-invalid` are wired for you, and an `error` always shows, announced in a live region. The error's glyph is decorative. The `leadingIcon` is decorative and the `end` slot's controls carry their own labels.

Without a `Field`, name the input yourself: a `<label htmlFor>` or `aria-label`. A placeholder is not a label; it disappears as soon as someone types.

Pass `required` for a required field and say so in the label text too. An error appears when it is set, so on submit move focus to the first invalid field (or to a summary with `role="alert"`) to have it announced. Give `autoComplete` a real value (`email`, `name`, `url`) so browsers and password managers can fill it, and `off` only for search fields. A field the browser fills keeps the kit's own ground and text colour, in both themes, so autofill never paints over the system.

A `bar` field's `end` slot is hidden while the value is edited but stays in the Tab order, and shows when it takes keyboard focus. Its `rest` readout is what a screen reader hears until the field is focused, so keep it a faithful short form of the value.

A `type="search"` field hides the browser's own clear and draws one button named Clear search while it holds text, in any variant. It empties the field as typing would, so `onChange` and `onValueChange` hear it, and focus stays in the field. It is out of the Tab order because Escape does the same from the field; with the field empty, Escape passes on and closes what holds it.

- Tab: Moves into and out of the field
- Enter: Submits the surrounding form
- Escape: In a search field with text, clears it

## API reference

### Input

- `size` (`"sm" | "md" | "lg" | "xl" | "2xl" | "3xl"`, default `"md"`): The text style it stands in, and its height: `sm` 24px, a Caption pair; `md` 28px, Body; `lg` 32px, Headline; `xl` 35px, Title 3; `2xl` 57px, Title 2; `3xl` 83px, Title 1.
- `density` (`"standard" | "compact"`)
- `weight` (`TextWeight`, default `"regular"`): The weight the text it edits is shown in. A title is bold whatever this says.
- `variant` (`"default" | "ghost" | "bar" | "edge"`, default `"default"`)
- `rest` (`string`): Read in place of `value` while the field is not focused: a shorter readout of it. Focus shows the value.
- `leadingIcon` (`IconName`): Decorative glyph before the text (icon-3).
- `end` (`ReactNode`): Trailing slot: a Spinner, a key hint. A `type="search"` field draws its own clear here, before this.
- `invalid` (`boolean`): Marks the control invalid (aria-invalid); a surrounding `Field` with `error` does it too.
- `mono` (`boolean`)
- `digits` (`number`): A short number typed in a row (a percent, a count): tabular figures, centred, the field as wide as that many digits and a quarter digit more, at the size the value is drawn in (16px on touch), no native spinner. Pair it with `inputMode="numeric"`.
- `rootStyle` (`InputStyle`): Typed StyleX override for the `.ui-input` frame: where it sits and its `--input-*` knobs.
- `onValueChange` (`(value: string, details: { event: Event }) => void`): Called with the new text on every change (beside `onChange`).
- `render` (`RenderProp`): Replaces the `<input>`. Every other prop, `ref` included, lands on the input.
- `disabled` (`boolean`): Disables the field; the frame dims.
- `placeholder` (`string`): Placeholder at text-4.

Rest props go to `<input>` props.

### Field

- `label` (`ReactNode`)
- `hint` (`string`): Why or how, for a field its label cannot explain: a `Hint` after the label, and the control's description. At most 160 characters.
- `description` (`ReactNode`): Help text under the label (text-3, Caption).
- `error` (`ReactNode`): Error message; when present the field is invalid and the message is always shown.
- `action` (`ReactNode`): One control at the end of the error line, for an override its message allows ("Save anyway"): it shows with the error, never without one, and moves under the message when the line is narrow.
- `invalid` (`boolean`)
- `disabled` (`boolean`, default `false`): Disables the control and dims the label.
- `rootStyle` (`RootStyle`): Typed StyleX override: where the field sits.

Rest props go to `<div>` props.
