# Input
A single line of text, typed by a person or agent.
Source page: https://dinachi.dev/docs/components/input

## Installation
```bash
npx @dinachi/cli@latest add input
```
Adds to your project:
- `components/ui/input/input.tsx`
- `components/ui/input/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import { Input } from "@/components/ui/input"

export function ProjectName() {
  return (
    <div className="space-y-2">
      <label htmlFor="project">Project name</label>
      <Input id="project" placeholder="Atlas" />
    </div>
  )
}
```

## Examples

### With label
A label and helper text tied to the field.
```tsx
import { Input } from '@/components/ui/input';

export function Example() {
  return (
    <div className="space-y-2 w-full max-w-sm">
      <label htmlFor="username" className="text-sm font-medium text-foreground">Username</label>
      <Input 
        id="username" 
        placeholder="Enter your username" 
      />
      <p className="text-sm text-muted-foreground">
        This is your public display name.
      </p>
    </div>
  );
}
```

### Default
A plain field with placeholder text.
```tsx
import { Input } from '@/components/ui/input';

export function Example() {
  return <Input placeholder="Enter your email" />;
}
```

### Types
Email, password and number fields.
```tsx
import { Input } from '@/components/ui/input';

export function Example() {
  return (
    <div className="space-y-4 w-full max-w-md">
      <div className="space-y-2">
        <label htmlFor="email" className="text-sm font-medium text-foreground">Email</label>
        <Input 
          id="email" 
          type="email" 
          placeholder="user@example.com" 
        />
      </div>
      <div className="space-y-2">
        <label htmlFor="password" className="text-sm font-medium text-foreground">Password</label>
        <Input 
          id="password" 
          type="password" 
          placeholder="Enter your password" 
        />
      </div>
      <div className="space-y-2">
        <label htmlFor="number" className="text-sm font-medium text-foreground">Number</label>
        <Input 
          id="number" 
          type="number" 
          placeholder="Enter a number" 
        />
      </div>
    </div>
  );
}
```

### Disabled
Disabled and read-only fields.
```tsx
import { Input } from '@/components/ui/input';

export function Example() {
  return (
    <div className="space-y-4 w-full max-w-sm">
      <div className="space-y-2">
        <label htmlFor="disabled" className="text-sm font-medium text-foreground">Disabled Input</label>
        <Input 
          id="disabled" 
          placeholder="This input is disabled" 
          disabled 
        />
      </div>
      <div className="space-y-2">
        <label htmlFor="readonly" className="text-sm font-medium text-foreground">Read-only Input</label>
        <Input 
          id="readonly" 
          value="This input is read-only" 
          readOnly 
        />
      </div>
    </div>
  );
}
```

### Validation
An error shown while the person types.
```tsx
import { Input } from '@/components/ui/input';
import { useState } from 'react';

export function Example() {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setEmail(value);
    
    if (value && !value.includes('@')) {
      setError('Please enter a valid email address');
    } else {
      setError('');
    }
  };

  return (
    <div className="space-y-2 w-full max-w-sm">
      <label htmlFor="email-validation" className="text-sm font-medium text-foreground">Email Address</label>
      <Input 
        id="email-validation"
        type="email"
        placeholder="user@example.com"
        value={email}
        onChange={handleChange}
        aria-invalid={!!error}
      />
      {error && (
        <p className="text-sm text-destructive">{error}</p>
      )}
      {email && !error && (
        <p className="text-sm text-success">Valid email address</p>
      )}
    </div>
  );
}
```

## Notes

### Labels and fields
Pair the input with a `<label htmlFor>` or wrap it in a `Field` with a `FieldLabel`. Inside a Field, an agent's write marks it dirty and filled like typing.

## API reference
Props marked **agent** change what an agent reads or may do.

### Input
A styled native input.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | - | Controlled value. |
| `defaultValue` | `string` | - | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses an agent's change. |
| `onChange` | `(event) => void` | - | The native change handler. Runs for typing and for an agent's write. |
| `type` **agent** | `string` | `"text"` | The native input type. A `file` input takes no agent actions. |
| `placeholder` **agent** | `string` | - | Shown while empty. The agent's name for the field when nothing else labels it. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Readable and selectable; refuses an agent's write. |
| `aria-invalid` **agent** | `boolean` | - | Draws the error border and ring. The agent reads it as invalid. |

## Agent
Inside an `AgentProvider`, Input appears in `agent.snapshot()` as `input`.
Reads:
- `label`: The aria-label, the associated label, then the placeholder or name.
- `value`: The current text. Redacted for passwords and secret autocomplete fields.
- `disabled`: True when the input is disabled.
- `required`: True when the input is required.
- `invalid`: True when aria-invalid is set or the Field is invalid.
- `errors`: The messages aria-errormessage points to, while invalid.
Actions:
- `setValue("Atlas")`: Replaces the text with a real input event, so `onChange` and a Field see it.
- `clear()`: Empties the field the same way.
An agent's write runs through `onValueChange` first. `isAgentChange(details)` is true for it; `details.cancel()` refuses it before `onChange` or the Field see it, and the agent is told the app refused. A disabled or `readOnly` input refuses on its own, and a `type="file"` input offers no actions.
```ts
await agent.act({
  steps: [{ ref: "Username", action: "setValue", args: ["ada"] }],
})
```

## Accessibility
- Renders a native input with native semantics and keyboard handling.
- Name every input with a label, `FieldLabel` or aria-label. A placeholder vanishes on typing.
- Set aria-invalid when the value is wrong; it is styled and announced.

## Source
`components/ui/input/input.tsx`
```tsx
import * as React from "react";
import { Input as BaseInput } from "@base-ui/react/input";
import { cn } from "@/lib/utils";
import { createAgentChangeDetails, useAgentControl, useMergedRef } from "@/components/ui/agent";

function writeValue(input: HTMLInputElement, value: string) {
  // The prototype setter skips React's value tracker, so React does not treat the write
  // as an edit of its own and the parent's handler is the only one that hears of it.
  Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value);
}

function setValueAsUser(input: HTMLInputElement, value: string) {
  writeValue(input, value);
  input.dispatchEvent(new Event("input", { bubbles: true }));
}

const Input = React.forwardRef<
  HTMLInputElement,
  React.ComponentProps<typeof BaseInput>
>(({ className, ...props }, ref) => {
  const element = React.useRef<HTMLInputElement>(null);
  const mergedRef = useMergedRef(ref, element);

  // Set while the agent's input event runs, as onValueChange has already heard of it.
  const agentWrite = React.useRef(false);
  const { onValueChange } = props;
  const handleValueChange = onValueChange
    ? (value: string, details: BaseInput.ChangeEventDetails) => {
        if (!agentWrite.current) onValueChange(value, details);
      }
    : undefined;

  const setValue = (value: string) => {
    const input = element.current;
    if (!input) return "The input is not mounted.";
    if (input.readOnly) return "The input is read-only.";
    // The app may refuse first, so a refused change reaches nothing else. Then a real
    // input event, as typing sends, so onChange, form libraries and the Field hear of it.
    if (onValueChange) {
      const details = createAgentChangeDetails<BaseInput.ChangeEventDetails>("none");
      onValueChange(value, details);
      if (details.isCanceled) return "The app refused the change.";
    }
    agentWrite.current = true;
    try {
      setValueAsUser(input, value);
    } finally {
      agentWrite.current = false;
    }
  };

  useAgentControl(() => ({
    kind: "input",
    element: element.current,
    value: element.current?.value,
    // A file input takes a file from a person's picker. Nothing an agent sends can be one.
    actions:
      props.type === "file"
        ? ({} as Record<string, never>)
        : {
            setValue: (value: string) => setValue(String(value ?? "")),
            clear: () => setValue(""),
          },
  }));

  return (
    <BaseInput
      data-slot="input"
      className={cn(
        "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
        "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
        "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
        className
      )}
      ref={mergedRef}
      {...props}
      onValueChange={handleValueChange}
    />
  );
});
Input.displayName = "Input";

export { Input };
```
