# Textarea

输入多行文本、随输入调整字段大小，并把它连接到表单。

文本域是原生的多行文本框，用来输入消息、笔记和描述。它可以在字段和表单里使用，可以随文字增长，并报告与 Input 相同的变更原因。

```tsx title="basic.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <Field name="message">
      <FieldLabel>Message</FieldLabel>
      <Textarea placeholder="Type your message here…" />
    </Field>
  )
}

export { Example }
```

点击 Message 让文本域获得焦点，然后输入。按 Enter 开始新的一行。

## 安装
```bash
npm install @ui-sdk/react @ui-sdk/core
```

## 用法
`Textarea` 渲染一个原生 `<textarea>`。直接传 `rows`、`placeholder`、`maxLength` 和其他原生属性。

```tsx
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return <Textarea aria-label="Message" placeholder="Type your message here…" />
}

export { Example }
```

## 字段
把文本域包进 [Field](/docs/react/components/field)，给它一个可见的标签和描述。文本域没有 `name` 时，字段也会提供自己的 `name`。

```tsx title="field.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <Field name="feedback">
      <FieldLabel>Feedback</FieldLabel>
      <Textarea placeholder="What could we do better?" />
      <FieldDescription>Only the product team can see this.</FieldDescription>
    </Field>
  )
}

export { Example }
```

点击 Feedback 让文本域获得焦点。屏幕阅读器会连同字段一起读出描述。

## 自动调整大小
设置 `autoResize`，让文本域随文字增长和收缩。CSS `min-height` 和 `max-height` 设定它的范围；超过最大值后，文字在它内部滚动。

```tsx title="auto-resize.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <Field name="notes">
      <FieldLabel>Notes</FieldLabel>
      <Textarea autoResize placeholder="Add notes for the delivery driver…" />
      <FieldDescription>Your driver sees these notes.</FieldDescription>
    </Field>
  )
}

export { Example }
```

在 Notes 里输入几行。文本域随每一行增长，直到达到最大高度，然后滚动。删掉这些行，它会缩回去。

支持 `field-sizing: content` 的浏览器会原生地调整它的大小。在其他情况下，组件会在值变化、表单重置或宽度变化时测量它。

## 受控
把 `value` 放在状态里，并用 `onValueChange` 更新它。这里的字符计数由那个值计算，原生 `maxLength` 限制文字长度。

```tsx title="controlled.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"
import * as React from "react"

function Example() {
  const [bio, setBio] = React.useState(
    "Product designer in Lisbon. I write about type and interfaces."
  )
  return (
    <Field name="bio">
      <FieldLabel>Bio</FieldLabel>
      <Textarea value={bio} onValueChange={setBio} maxLength={160} />
      <FieldDescription>{bio.length} / 160 characters</FieldDescription>
    </Field>
  )
}

export { Example }
```

编辑 Bio，观察它下面的字符计数。文本域在 160 个字符时停止接收文字。

Textarea 与 Input 共用[变更原因](https://ui-sdk.cn/docs/react/components/textarea#reasons)和取消行为。通用约定见[状态与事件](/docs/react/state-and-events)。

## 表单
文本域通过字段的 `name` 下的原生表单提交它的值。传入 `createInputController()` 创建的控制器来从外部更改它，这里用来在发送后清空它。原生 `required` 约束会阻止空消息。

```tsx title="button.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Textarea, createInputController } from "@ui-sdk/react/textarea"
import * as React from "react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [message] = React.useState(createInputController)
  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        const data = new FormData(event.currentTarget)
        log(`Sent “${data.get("message")}”`)
        message.clear()
      }}
    >
      <Field name="message">
        <FieldLabel>Message</FieldLabel>
        <Textarea
          controller={message}
          required
          placeholder="Write a reply to Hollis Grant…"
        />
      </Field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">
          Send Message
        </button>
      </div>
    </form>
  )
}

export { Example }
```

输入一条消息，然后按 Send Message。控制台会记录它，文本域会清空。在为空时按 Send Message 会被阻止。

[控制器](/docs/react/controllers)介绍了创建和共享控制器。

## 禁用
在文本域或它的字段上设置 `disabled`，阻止编辑，并把它移出 Tab 顺序和提交的值。

```tsx title="disabled.tsx"
import { Field, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <Field disabled>
      <FieldLabel>Reply</FieldLabel>
      <Textarea defaultValue="Replies are closed for this thread." />
    </Field>
  )
}

export { Example }
```

试着编辑 Reply，或用 Tab 到达它。禁用的文本域保留它的值，但无法更改。

## 无效
对于应用自己判定的错误，在字段上设置 `invalid`。字段会显示错误，把它与文本域关联起来，并设置 `aria-invalid`。[Field](https://ui-sdk.cn/docs/react/components/field#validation) 介绍了原生约束和错误匹配。

```tsx title="invalid.tsx"
import { Field, FieldError, FieldLabel } from "@ui-sdk/react/field"
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <Field invalid>
      <FieldLabel>Review</FieldLabel>
      <Textarea defaultValue="Great." />
      <FieldError match>Write at least 20 characters.</FieldError>
    </Field>
  )
}

export { Example }
```

聚焦 Review。文本域被标记为无效，下面的错误说明评审应该有多长。

## 提交快捷键
设置 `submitShortcut`，用键盘提交文本域所在的表单。设为 `"mod+enter"` 时，Enter 仍然开始新的一行，Command 或 Control+Enter 提交。设为 `"enter"` 时，Enter 提交，Shift+Enter 开始新的一行。不设置时，Enter 总是开始新的一行，而输入法正在组合文字时，两者都不会提交。

```tsx
import { Textarea } from "@ui-sdk/react/textarea"

function Example() {
  return (
    <form action="/messages" method="post">
      <Textarea
        name="message"
        aria-label="Message"
        required
        submitShortcut="mod+enter"
      />
      <button type="submit">Send</button>
    </form>
  )
}

export { Example }
```

这个快捷键像 Send 按钮一样提交，所以 `required` 和表单的 `onSubmit` 仍然生效。改为给文本域传 `onSubmit` 来自己处理这个快捷键。它会收到值，表单不会提交。

## 样式
直接给原生文本域设置样式，用 `data-filled`、`data-disabled`、`data-readonly` 和 `data-required` 表示它的状态。在字段内部，它还会收到字段的校验属性，比如 `data-invalid`。使用 `autoResize` 时，设置 `min-height` 和 `max-height` 来限制它的增长。使用逻辑间距，让文字跟随周围的方向。

文本域的 `data-slot` 是 `textarea`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/react/components/textarea#data-attributes)下。

## 数据属性
### Textarea
`[data-slot="textarea"]`

- `data-filled`: Present while the field holds any text.
- `data-disabled`: Present when the field is disabled, by its own prop or its Field.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when the field is required.

## API 参考
Props 与下面相同，作为 React props，再加上所有原生 textarea prop。

### Textarea
- `value?` (`string`): The value, for a controlled field.
- `defaultValue?` (`string`): The value it starts with. A form reset returns here.
- `onValueChange?` (`((value: string, details: ChangeDetails<InputValueChangeReason>) => void)`): Called when the user changes the value: typing (`"input-change"`), a Clear part (`"clear-press"`), a form reset (`"reset"`) or a controller (`"imperative"`). `details.cancel()` keeps the value as it was.
- `controller?` (`object`): Reads and writes the field from anywhere. Create one with `createInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.
- `autoResize?` (`boolean`): Grows and shrinks with the text. Bound it with CSS `min-height` and `max-height`; past the maximum, it scrolls.
- `onSubmit?` (`((value: string, details: TextareaSubmitDetails) => void)`): Runs on the submit shortcut, unless an input method is composing. Without it, the shortcut submits the form the textarea is in. With neither, the key is left alone, so Enter adds a line.
- `submitShortcut?` (`"enter" | "mod+enter"`): Which keys submit: `"enter"`, with Shift+Enter for a new line, or `"mod+enter"`, with Enter for a new line. Without it, Enter always starts a new line.

- `disabled?` (`boolean`): Disables the field.
- `readOnly?` (`boolean`): Makes the field read-only.
- `required?` (`boolean`): Makes the field required.

### 状态
- `filled` (`boolean`): Whether the field holds any text.
- `disabled` (`boolean`): Whether the field is disabled.
- `readOnly` (`boolean`): Whether the field is read-only.
- `required` (`boolean`): Whether the field is required.

### 原因
- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `reset` (`none`): A form reset.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createInputController()` 创建一个，并作为 `controller` 传入。

- `getValue()` (`() => string`): The current value.
- `setValue(value, options?)` (`(value: string, options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean`): Sets the value as if the user typed it, so `input` fires. Returns false when the change was canceled or nothing changed.
- `clear(options?)` (`(options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean`): Empties the field, as if the user deleted the text, so `input` fires. Returns false when the change was canceled or nothing changed.
- `focus()` (`() => void`): Moves focus to the field.

## 无障碍
多行文本字段没有 WAI-ARIA 模式。文本域保持为原生 `<textarea>`，带有标准的文本编辑、选择、拼写检查和表单行为。给它一个可见的字段标签或 `aria-label`，并把描述和错误放在它们的字段部件里，这样它们会与它关联。

### 经过测试的行为
下面每一行都是一个自动化测试。

- The label names the textarea and the description describes it.

**Auto resize**

- Grows with its text and shrinks back.
- Stops at its max height and scrolls.
- Shrinks back when a reset empties it.
- Follows text written from code.

**Submit shortcut**

- Without a submit shortcut, Enter starts a new line and doesn't submit.
- With enter, Enter submits the form and Shift+Enter starts a new line.
- With mod+enter, Enter starts a new line and Cmd or Ctrl+Enter submits.
- Enter while an input method composes doesn't submit.

Runs in React、Vue 和 web components.
