# Textarea
A multi-line text field.
Source page: https://dinachi.dev/docs/components/textarea

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

## Usage
```tsx
import { Textarea } from "@/components/ui/textarea"

export function BioField() {
  return (
    <div>
      <label htmlFor="bio">Bio</label>
      <Textarea id="bio" placeholder="A sentence or two about yourself" />
    </div>
  )
}
```

## Examples

### With label
A labelled field with helper text.
```tsx
import { Textarea } from '@/components/ui/textarea';

export function Example() {
  return (
    <div className="space-y-2 w-full max-w-md">
      <label htmlFor="bio" className="text-sm font-medium text-foreground">Bio</label>
      <Textarea
        id="bio"
        placeholder="A sentence or two about yourself"
        rows={4}
      />
      <p className="text-sm text-muted-foreground">
        This appears on your public profile.
      </p>
    </div>
  );
}
```

### Character count
A length limit the reader sees as they approach it.
```tsx
import { Textarea } from '@/components/ui/textarea';
import { useState } from 'react';

export function Example() {
  const [value, setValue] = useState('');
  const limit = 180;

  return (
    <div className="space-y-2 w-full max-w-md">
      <label htmlFor="summary" className="text-sm font-medium text-foreground">Summary</label>
      <Textarea
        id="summary"
        placeholder="What is this release about?"
        rows={4}
        maxLength={limit}
        value={value}
        onChange={(event) => setValue(event.target.value)}
        aria-describedby="summary-count"
      />
      <p id="summary-count" aria-live="polite" className="text-sm text-muted-foreground">
        {value.length} / {limit} characters
      </p>
    </div>
  );
}
```

### Disabled
Disabled and read-only states.
```tsx
import { Textarea } from '@/components/ui/textarea';

export function Example() {
  return (
    <div className="space-y-4 w-full max-w-md">
      <div className="space-y-2">
        <label htmlFor="disabled-note" className="text-sm font-medium text-foreground">Disabled</label>
        <Textarea id="disabled-note" placeholder="Not accepting notes right now" disabled />
      </div>
      <div className="space-y-2">
        <label htmlFor="readonly-note" className="text-sm font-medium text-foreground">Read-only</label>
        <Textarea
          id="readonly-note"
          value="Submitted on 12 March. Edits are closed."
          readOnly
        />
      </div>
    </div>
  );
}
```

### Default
A multi-line field with placeholder text.
```tsx
import { Textarea } from '@/components/ui/textarea';

export function Example() {
  return <Textarea placeholder="Tell us what happened" className="max-w-md" />;
}
```

## Notes

### When to use it
- Answers of a sentence or more.
- For a short value, use [Input](/docs/components/input).

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

### Textarea
A native `<textarea>` styled like Input.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` | - | Controlled text. |
| `defaultValue` | `string` | - | Starting text when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs on every edit, for people and agents. `details.cancel()` refuses an agent's change. |
| `onChange` | `(event) => void` | - | The native change event. Fires for typing and agent edits. |
| `rows` | `number` | - | Visible height in lines. A min-height of 80px still applies. |
| `placeholder` | `string` | - | Shown while the field is empty. |
| `maxLength` | `number` | - | The most characters it accepts. |
| `readOnly` **agent** | `boolean` | `false` | Selectable but not editable. Refuses agents too. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |

## Agent
Inside an `AgentProvider`, Textarea appears in `agent.snapshot()` as `textarea`.
Reads:
- `label`: The `<label>` tied to it, or its aria-label.
- `value`: The current text.
- `disabled`: True when the field is disabled.
Actions:
- `setValue("Final")`: Replaces the text.
- `clear()`: Empties the field.
An agent's edit runs through `onValueChange` first. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and tells the agent. A disabled or `readOnly` textarea refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Bio", action: "setValue", args: ["Designer in Lagos."] }],
})
```

## Accessibility
- A native `<textarea>`, with the browser's semantics and editing keys.
- Name it with `<label htmlFor>` or aria-label; the agent reads the same name.
- Point aria-describedby at helper text and character counts.

## Source
`components/ui/textarea/textarea.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"

export interface TextareaChangeDetails {
  reason: string
  event: Event | undefined
  isCanceled: boolean
  cancel(): void
}

export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  /** Called with the new text on each edit, a person's or an agent's. An agent's can be canceled. */
  onValueChange?: (value: string, details: TextareaChangeDetails) => void
}

function writeValue(textarea: HTMLTextAreaElement, value: string) {
  Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call(textarea, value)
}

function personDetails(event: Event): TextareaChangeDetails {
  const details = { reason: "none", event, isCanceled: false, cancel: () => void (details.isCanceled = true) }
  return details
}

const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
  ({ className, onValueChange, onChange, ...props }, ref) => {
    const element = React.useRef<HTMLTextAreaElement>(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 setValue = (value: string) => {
      const textarea = element.current
      if (!textarea) return "The textarea is not mounted."
      if (textarea.readOnly) return "The textarea is read-only."
      // The app may refuse first. Then a real input event, so onChange hears of it too.
      if (onValueChange) {
        const details = createAgentChangeDetails<TextareaChangeDetails>("none")
        onValueChange(value, details)
        if (details.isCanceled) return "The app refused the change."
      }
      agentWrite.current = true
      try {
        writeValue(textarea, value)
        textarea.dispatchEvent(new Event("input", { bubbles: true }))
      } finally {
        agentWrite.current = false
      }
    }

    useAgentControl(() => ({
      kind: "textarea",
      element: element.current,
      value: element.current?.value,
      actions: {
        setValue: (value: string) => setValue(String(value ?? "")),
        clear: () => setValue(""),
      },
    }))

    const Control = BaseInput as unknown as React.ComponentType<React.ComponentProps<"textarea"> & { render: React.ReactElement }>
    return (
      <Control
        render={<textarea />}
        className={cn(
          "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
          className
        )}
        ref={mergedRef}
        onChange={
          onValueChange
            ? (event) => {
                onChange?.(event)
                if (!agentWrite.current) onValueChange(event.target.value, personDetails(event.nativeEvent))
              }
            : onChange
        }
        data-slot="textarea"
        {...props}
      />
    )
  }
)
Textarea.displayName = "Textarea"

export { Textarea }
```
