# Input

## Introduction

Input is a single-line text field component for capturing user input. Built on Joy UI's Input with Framer Motion animation support, it includes built-in form field composition (`label`, `helperText`, `error`) so you can build complete form fields without manual `FormControl` wrappers. It supports clearable inputs, password visibility toggling, and start/end decorators.

```tsx
<Input />
```

| Field                       | Description | Default |
| --------------------------- | ----------- | ------- |
| color                       | —           | —       |
| size                        | —           | —       |
| variant                     | —           | —       |
| label                       | —           | —       |
| helperText                  | —           | —       |
| error                       | —           | —       |
| required                    | —           | —       |
| disabled                    | —           | —       |
| value                       | —           | —       |
| defaultValue                | —           | —       |
| onChange                    | —           | —       |
| name                        | —           | —       |
| placeholder                 | —           | —       |
| type                        | —           | —       |
| startDecorator              | —           | —       |
| endDecorator                | —           | —       |
| enableClearable             | —           | —       |
| disableTogglePasswordButton | —           | —       |
| sx                          | —           | —       |
| className                   | —           | —       |

> **Use built-in form props**
>
> This component natively supports `label` and `helperText` props.
> When building forms, use these built-in props instead of manually composing labels and helper text with Typography.

## Usage

```tsx
import { Input } from '@ceed/cds';

function MyComponent() {
  const [value, setValue] = useState('');

  return <Input label="Name" placeholder="Enter your name" value={value} onChange={(e) => setValue(e.target.value)} />;
}
```

## Variants

Input supports four visual styles: `outlined` (default), `solid`, `soft`, and `plain`.

```tsx
<>
    <Input placeholder="Type in here…" variant="solid" />
    <Input placeholder="Type in here…" variant="soft" />
    <Input placeholder="Type in here…" variant="outlined" />
    <Input placeholder="Type in here…" variant="plain" />
  </>
```

## Sizes

Three sizes are available: `sm`, `md` (default), and `lg`.

```tsx
<>
    <Input {...args} size="lg" />
    <Input {...args} size="md" />
    <Input {...args} size="sm" />
  </>
```

## Label and Helper Text

### Label

The `label` prop renders a form label above the input.

```tsx
<>
    <Input placeholder="Type in here…" label="Label" />
  </>
```

### Helper Text

The `helperText` prop renders descriptive text below the input.

```tsx
<>
    <Input placeholder="Type in here…" helperText="I'm helper text" />
  </>
```

## States

### Disabled

A disabled input cannot be focused or interacted with.

```tsx
<Input disabled />
```

### Error

Set `error` to visually indicate a validation failure. Combine with `helperText` to display an error message.

```tsx
<>
    <Input placeholder="Invalid input" label="label" error />
  </>
```

### Required

Set `required` to mark the field as required. An asterisk is added to the label automatically.

```tsx
<Input
  placeholder="Type in here..."
  helperText="I'm helper text"
  label="Label"
  required
/>
```

## Decorators

Use `startDecorator` and `endDecorator` to add icons, buttons, or other elements at the start or end of the input field.

```tsx
<Stack spacing={3}>
    <Input
      placeholder="Amount"
      startDecorator={
        {
          dollar: "$",
          baht: "฿",
          yen: "¥"
        }[currency]
      }
      endDecorator={
        <React.Fragment>
          <Divider orientation="vertical" />
          <Select
            variant="plain"
            value={currency}
            options={[
              {
                value: "dollar",
                label: "US dollar"
              },
              {
                value: "baht",
                label: "Thai baht"
              },
              {
                value: "yen",
                label: "Japanese yen"
              }
            ]}
            onChange={(e) => setCurrency(e.target.value!)}
            slotProps={{
              listbox: {
                variant: "outlined"
              }
            }}
            sx={{
              mr: -1.5,
              "&:hover": {
                bgcolor: "transparent"
              }
            }}
          />
        </React.Fragment>
      }
      sx={{
        width: 300
      }}
    />
    <Input
      placeholder="Your location"
      startDecorator={
        <Button variant="soft" color="neutral" startDecorator={<LocationOn />}>
          Locate
        </Button>
      }
      sx={{
        width: 300
      }}
    />
  </Stack>
```

When using `endDecorator` together with `enableClearable`, both elements are displayed side by side:

```tsx
<Input
  placeholder="Type in here…"
  label="Label"
  enableClearable
  endDecorator={<Chip color="primary">Hi</Chip>}
/>
```

## Clearable Input

Set `enableClearable` to show a clear button when the input has a value. Clicking the button clears the input content.

```tsx
<>
    <Input placeholder="Type in here…" label="Label" enableClearable />
  </>
```

```tsx
<Input enableClearable placeholder="Type something and clear it" />
```

## Password Input

Setting `type="password"` creates a password field with an automatic visibility toggle button.

```tsx
<Stack spacing={3}>
    <Typography level="body-md">Default password input with toggle button:</Typography>
    <Input {...args} placeholder="Enter password" type="password" label="Password" />

    <Typography level="body-md">Disabled password input:</Typography>
    <Input
      {...args}
      placeholder="Enter password"
      type="password"
      label="Disabled Password"
      disabled
    />

    <Typography level="body-md">Password input with toggle button disabled:</Typography>
    <Input
      {...args}
      placeholder="Enter password"
      type="password"
      label="No Toggle"
      disableTogglePasswordButton
    />
  </Stack>
```

### Disabling the Password Toggle

Use `disableTogglePasswordButton` to hide the visibility toggle button on password inputs.

```tsx
<Input type="password" disableTogglePasswordButton placeholder="Password" />
```

### Password Input Limitations

Password inputs (`type="password"`) do not support custom `endDecorator` because the password toggle button occupies that slot. If you provide `endDecorator` with a password input, the component logs a warning and ignores it.

```tsx
<Stack spacing={3}>
    <Typography level="body-md">
      When type="password", the endDecorator is not supported:
    </Typography>
    <Input
      {...args}
      placeholder="Enter password"
      type="password"
      label="Password with endDecorator (will show warning)"
      endDecorator={<Chip color="primary">Hi</Chip>}
    />

    <Typography level="body-md">The password toggle button takes precedence:</Typography>
    <Input {...args} placeholder="Enter password" type="password" label="Password" />
  </Stack>
```

## Form Control

Combining `label`, `helperText`, and `error` produces a complete form field.

```tsx
<>
    <Input placeholder="Type in here..." helperText="I'm helper text" label="Label" />
    <Input placeholder="Invalid input" helperText="I'm helper text" label="Label" error />
  </>
```

```tsx
<Input
  label="Email"
  helperText="We'll never share your email"
  required
/>

<Input
  label="Email"
  error
  helperText="Invalid email address"
/>
```

## Controlled / Uncontrolled

### Controlled

Use `value` and `onChange` for controlled behavior.

```tsx
<>
    <Input
      placeholder="Type in here…"
      label="Label"
      enableClearable
      value={value}
      onChange={handleChange}
    />
  </>
```

```tsx
const [value, setValue] = useState('');

<Input value={value} onChange={(e) => setValue(e.target.value)} placeholder="Controlled input" />;
```

### Uncontrolled

Use `defaultValue` for uncontrolled behavior.

```tsx
<Input defaultValue="Initial value" placeholder="Uncontrolled input" />
```

## Common Use Cases

### Search Field

```tsx
import { Input } from '@ceed/cds';
import SearchIcon from '@mui/icons-material/Search';

function SearchField({ onSearch }) {
  const [query, setQuery] = useState('');

  return (
    <Input
      placeholder="Search..."
      startDecorator={<SearchIcon />}
      enableClearable
      value={query}
      onChange={(e) => {
        setQuery(e.target.value);
        onSearch(e.target.value);
      }}
    />
  );
}
```

### Login Form

```tsx
import { Input, Button, Stack } from '@ceed/cds';

function LoginForm({ onSubmit }) {
  return (
    <form onSubmit={onSubmit}>
      <Stack spacing={2}>
        <Input label="Email" type="email" required placeholder="Enter your email" />
        <Input label="Password" type="password" required placeholder="Enter your password" />
        <Button type="submit">Sign In</Button>
      </Stack>
    </form>
  );
}
```

### Form with Validation

```tsx
import { useState } from 'react';
import { Input, Button, Stack } from '@ceed/cds';

function ValidatedForm() {
  const [email, setEmail] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        setSubmitted(true);
      }}
    >
      <Stack spacing={2}>
        <Input
          label="Email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          error={submitted && !isValid}
          helperText={submitted && !isValid ? 'Please enter a valid email' : undefined}
          placeholder="user@example.com"
        />
        <Button type="submit">Submit</Button>
      </Stack>
    </form>
  );
}
```

## Controlled Empty Value

Whether a field is controlled is decided **once, on mount** — the same convention MUI's `useControlled` follows. A field that mounts with `value={undefined}` is treated as uncontrolled for its whole lifetime, so later updates from the parent never reach the screen.

Pass `null` to express "controlled, but currently empty":

```tsx
import { useState } from 'react';
import { Button, Input } from '@ceed/cds';

function NameField() {
  const [name, setName] = useState<string | undefined>(undefined);

  return (
    <>
      <Input label="Name" value={name ?? null} onChange={(e) => setName(e.target.value)} />
      {/* Clears the input on screen, not just in state. */}
      <Button onClick={() => setName(undefined)}>Reset</Button>
    </>
  );
}
```

Form libraries are where this bites. When something outside the input empties the state — `react-hook-form`'s `setValue('name', undefined)`, for instance — `value={field.value ?? null}` is what carries that back to the screen.

`onChange` never emits `null` or `undefined`: `Input` reports an empty field as `''`. Only the `value` prop accepts `null`.

## Props and Customization

### Key Props

| Prop                          | Type                                                           | Default      | Description                                                                     |
| ----------------------------- | -------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------- |
| `label`                       | `ReactNode`                                                    | -            | Label text displayed above the input                                            |
| `helperText`                  | `ReactNode`                                                    | -            | Helper text displayed below the input                                           |
| `error`                       | `boolean`                                                      | `false`      | Applies danger color to indicate validation error                               |
| `enableClearable`             | `boolean`                                                      | `false`      | Shows a clear button when the input has a value                                 |
| `disableTogglePasswordButton` | `boolean`                                                      | `false`      | Hides the password visibility toggle (only applies when `type="password"`)      |
| `value`                       | `string \| number \| readonly string[] \| null`                | -            | Input value for controlled mode                                                 |
| `defaultValue`                | `string \| number \| readonly string[]`                        | -            | Initial value for uncontrolled mode                                             |
| `onChange`                    | `(event: { target: { name: string; value: string } }) => void` | -            | Callback when the input value changes                                           |
| `placeholder`                 | `string`                                                       | -            | Placeholder text when the input is empty                                        |
| `type`                        | `string`                                                       | `'text'`     | HTML input type (`text`, `password`, `email`, `number`, etc.)                   |
| `disabled`                    | `boolean`                                                      | `false`      | Disables the input                                                              |
| `readOnly`                    | `boolean`                                                      | `false`      | Makes the input read-only (focusable but not editable)                          |
| `required`                    | `boolean`                                                      | `false`      | Marks the field as required (adds asterisk to label)                            |
| `name`                        | `string`                                                       | -            | HTML name attribute for form submission                                         |
| `size`                        | `'sm' \| 'md' \| 'lg'`                                         | `'md'`       | Input size                                                                      |
| `variant`                     | `'outlined' \| 'solid' \| 'soft' \| 'plain'`                   | `'outlined'` | Visual style variant                                                            |
| `color`                       | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'neutral'`  | Color scheme                                                                    |
| `startDecorator`              | `ReactNode`                                                    | -            | Content rendered at the start of the input                                      |
| `endDecorator`                | `ReactNode`                                                    | -            | Content rendered at the end of the input (not supported with `type="password"`) |
| `sx`                          | `SxProps`                                                      | -            | Custom styles using the MUI system                                              |

> **Note**: For a **controlled** field that starts empty, pass `null` as `value`. Passing `undefined` makes the field uncontrolled from the first render, so later external updates (including resetting it to an empty value) are not reflected on screen.

> **Note**: Input also accepts all Joy UI Input props and Framer Motion props.

## Best Practices

1. **Use built-in `label` and `helperText`** instead of wrapping with FormControl manually.

```tsx
// ✅ Good
<Input label="Email" helperText="Enter your work email" />

// ❌ Bad
<FormControl>
  <FormLabel>Email</FormLabel>
  <Input />
  <FormHelperText>Enter your work email</FormHelperText>
</FormControl>
```

2. **Choose the right input type** for the data being captured.

```tsx
// ✅ Good: Appropriate types
<Input type="email" label="Email" />
<Input type="password" label="Password" />
<Input type="tel" label="Phone" />

// ❌ Bad: Generic text for everything
<Input type="text" label="Email" />
```

3. **Always provide labels** for accessibility. If a visible label is not appropriate, use `aria-label`.

```tsx
// ✅ Good: Visible label
<Input label="Search" />

// ✅ Good: Hidden label for icon-only inputs
<Input aria-label="Search" startDecorator={<SearchIcon />} />

// ❌ Bad: No label at all
<Input placeholder="Search..." />
```

4. **Use `enableClearable` for search and filter inputs** where users frequently need to clear and re-enter values.

5. **Do not use `endDecorator` with password inputs.** The password toggle button occupies the end slot. Use `startDecorator` instead for additional icons.

## Accessibility

- **Label association**: The `label` prop automatically connects the label to the input via `htmlFor`/`id` pairing.
- **Keyboard navigation**: Standard keyboard support — Tab to focus, type to input, Escape to blur (when applicable).
- **Error announcement**: When `error` is set, `aria-invalid` is applied. Pair with `helperText` so assistive technology announces the error.
- **Required state**: The `required` prop adds `aria-required` and a visible asterisk to the label.
- **Password toggle**: The visibility toggle button is keyboard-accessible and includes an appropriate `aria-label`.

## Testing Notes

When using Testing Library, always query password inputs by `textbox` role:

```tsx
const passwordInput = screen.getByRole('textbox', { name: /password/i });
```

This is because the ARIA specification does not define a `password` role — password inputs use the default `textbox` role.
