# Password Input

输入密码、显示或隐藏它，并在原生表单里使用它。

Password Input 是一个原生密码字段，带一个显示和隐藏已输入内容的按钮。它让光标留在原处，让密码管理器提供正确的密码，并在表单提交时再次隐藏密码。

```svelte title="basic.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput>
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription>Use at least 8 characters.</FieldDescription>
</Field>
```

输入密码，然后选择 Show password 显示或隐藏它。点击切换按钮会让光标留在输入框里。用键盘时，按 Tab 到切换按钮，再按 Space 或 Enter。

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

## 组合
用下面的组合构建 `PasswordInput`：

```text
PasswordInput
├── PasswordInputControl
└── PasswordInputToggle
```

`PasswordInput` 保存值和可见性状态。`PasswordInputControl` 渲染原生输入框；`PasswordInputToggle` 渲染显示和隐藏它的按钮。切换按钮在 `password` 和 `text` 之间切换输入框，并且是 `type="button"`，所以在输入框里按 Enter 仍然会提交表单。

把 `name`、`form`、`required`、`disabled` 和 `readOnly` 这样的表单选项放在 `PasswordInput` 上。把 `placeholder` 或 `id` 这样的其他原生输入属性放在 `PasswordInputControl` 上。

## 用法
导入部件并把它们组合起来：

```svelte
<script lang="ts">
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<PasswordInput name="password">
  <PasswordInputControl aria-label="Password" />
  <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
</PasswordInput>
```

## 新密码
创建或修改密码时，在根部件上使用 `autoComplete="new-password"`。它告诉浏览器和密码管理器要提供哪种密码。登录时的默认值是 `current-password`。

示例从当前值推导出一份检查清单。这些规则属于示例；组件不强制任何密码策略。

```svelte title="new-password.svelte"
<script lang="ts">
  import { CheckIcon, EyeIcon, EyeOffIcon, XIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"

  const rules = [
    {
      label: "At least 8 characters",
      test: (password: string) => password.length >= 8,
    },
    { label: "A number", test: (password: string) => /\d/.test(password) },
    {
      label: "An uppercase and a lowercase letter",
      test: (password: string) =>
        /[a-z]/.test(password) && /[A-Z]/.test(password),
    },
  ]

  let password = $state("")
</script>

<Field name="new-password">
  <FieldLabel>Create a password</FieldLabel>
  <PasswordInput
    value={password}
    autoComplete="new-password"
    onValueChange={(value: string) => (password = value)}
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <ul data-slot="stack" aria-label="Password requirements">
    {#each rules as rule (rule.label)}
      {#if rule.test(password)}
        <li data-slot="row">
          <CheckIcon aria-hidden="true" />
          <span data-slot="visually-hidden">Done:</span>
          {rule.label}
        </li>
      {:else}
        <li data-slot="row">
          <XIcon aria-hidden="true" />
          <span data-slot="visually-hidden">To do:</span>
          {rule.label}
        </li>
      {/if}
    {/each}
  </ul>
</Field>
```

输入密码，观察检查清单更新。试着加入数字和大小写字母，然后切换它的可见性。

## 一开始就可见
设置 `defaultVisible` 让文字一开始就可见，设置 `defaultValue` 提供初始值。对于需要有人读取或复制的 Wi-Fi 密码，这很有用。

```svelte title="default-visible.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="wifi-password">
  <FieldLabel>Wi-Fi password</FieldLabel>
  <PasswordInput
    defaultVisible
    defaultValue="maple-orbit-42"
    autoComplete="new-password"
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription
    >Guests read it from here, so it starts shown.</FieldDescription
  >
</Field>
```

读取 Wi-Fi 密码，然后选择 Show password 隐藏它。再次选择它会显示值。

## 大写锁定
用 `data-capslock` 或部件的 `capsLock` 状态显示警告。输入框获得焦点时，它会随按键事件更新。示例为图标和警告预留了空间。

```svelte title="caps-lock.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon, LockIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput>
    {#snippet children(state)}
      <PasswordInputControl />
      <span
        >{#if state.capsLock}<LockIcon aria-hidden="true" />{/if}</span
      >
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(toggle)}
          {#if toggle.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    {/snippet}
  </PasswordInput>
  <p data-slot="caps-lock">Caps Lock is on.</p>
</Field>
```

聚焦 Password 并按 Caps Lock。大写锁定开启时警告会出现。关闭它或离开字段，警告就会隐藏。

## 禁用
在根部件、它的 Field 或包住它的字段集上设置 `disabled`，同时禁用输入框和切换按钮。这个值不会出现在表单提交里。

```svelte title="disabled.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field disabled name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput defaultValue="hunter22">
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription>Your administrator manages this password.</FieldDescription>
</Field>
```

试着编辑 Password 或按它的切换按钮。两个控件都被禁用，Tab 会跳过它们。

## 只读
当值可以读取但不能编辑时，设置 `readOnly`。输入框仍然可以聚焦，切换按钮仍然可用，值也仍然参与表单提交。

```svelte title="read-only.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
</script>

<Field name="recovery-key">
  <FieldLabel>Recovery key</FieldLabel>
  <PasswordInput readOnly defaultValue="7Hq2-vX9p-Lm4c" autoComplete="off">
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show recovery key">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
  <FieldDescription
    >Keep it somewhere safe. You can show it, but not change it.</FieldDescription
  >
</Field>
```

选择 Show recovery key 来读取它。试着在输入框里输入；它的值保持不变。

## 受控的可见性
用 `bind:visible` 绑定 `visible` 来控制可见性，并用 `onVisibleChange` 获取详情。[原因](https://ui-sdk.cn/docs/svelte/components/password-input#reasons)区分切换按钮的按压、表单提交、重置、页面隐藏，以及控制器动作。

```svelte title="controlled.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
  let visible = $state(false)
</script>

<Field name="password">
  <FieldLabel>Password</FieldLabel>
  <PasswordInput
    bind:visible
    onVisibleChange={(next: boolean, details: { reason: string }) =>
      log(`${next ? "Shown" : "Hidden"} (${details.reason})`)}
  >
    <PasswordInputControl />
    <PasswordInputToggle aria-label="Show password">
      {#snippet children(state)}
        {#if state.visible}
          <EyeOffIcon aria-hidden="true" />
        {:else}
          <EyeIcon aria-hidden="true" />
        {/if}
      {/snippet}
    </PasswordInputToggle>
  </PasswordInput>
</Field>
```

切换 Show password。控制台会记录每一次变更及其原因。

在变更回调里调用 `details.cancel()` 来拒绝一次可见性变更。表单提交期间，即使回调拒绝隐藏密码，原生输入框也会暂时变成密码字段。

## 控制器
创建 `createPasswordInputController()` 并作为 `controller` 传入，处理输入框之外的动作。读取或更改值、切换可见性，或聚焦输入框。写入会使用 `imperative` 原因。

```svelte title="controller.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import {
    createPasswordInputController,
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
  const password = createPasswordInputController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button
      type="button"
      onclick={() => {
        password.setValue("plum-kettle-orbit-42")
        password.setVisible(true)
      }}
    >
      Suggest
    </button>
    <button type="button" onclick={() => password.toggleVisible()}
      >Toggle</button
    >
    <button type="button" onclick={() => password.clear()}>Clear</button>
    <button
      type="button"
      onclick={() =>
        log(
          `${password.getValue().length} characters, ${password.isVisible() ? "shown" : "hidden"}`
        )}
    >
      Read
    </button>
    <button type="button" onclick={() => password.focus()}>Focus</button>
  </div>
  <Field name="new-password">
    <FieldLabel>New password</FieldLabel>
    <PasswordInput controller={password} autoComplete="new-password">
      <PasswordInputControl />
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(state)}
          {#if state.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    </PasswordInput>
  </Field>
</div>
```

选择 Suggest 填入并显示一个示例值。试试 Toggle、Read、Clear 和 Focus，从字段之外调用每个动作。

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

## 表单
原生输入框参与 `FormData`、校验和重置。用 `form` 把它和页面别处的表单关联起来，就像这个示例一样。

```svelte title="form.svelte"
<script lang="ts">
  import { EyeIcon, EyeOffIcon } from "@lucide/svelte"
  import { Field, FieldLabel } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
  import {
    PasswordInput,
    PasswordInputControl,
    PasswordInputToggle,
  } from "@ui-sdk/svelte/password-input"
  import { useLog } from "./log"

  const log = useLog()
</script>

<div data-slot="stack">
  <form
    data-slot="stack"
    id="sign-in"
    onsubmit={(event) => {
      event.preventDefault()
      const data = new FormData(event.currentTarget)
      const length = String(data.get("password")).length
      log(
        `Signed in as ${data.get("email")}, with a password of ${length} characters`
      )
    }}
  >
    <Field name="email">
      <FieldLabel>Email</FieldLabel>
      <Input type="email" required autocomplete="username" />
    </Field>
  </form>
  <Field>
    <FieldLabel>Password</FieldLabel>
    <PasswordInput name="password" form="sign-in" required>
      <PasswordInputControl />
      <PasswordInputToggle aria-label="Show password">
        {#snippet children(state)}
          {#if state.visible}
            <EyeOffIcon aria-hidden="true" />
          {:else}
            <EyeIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </PasswordInputToggle>
    </PasswordInput>
  </Field>
  <div data-slot="row">
    <button type="submit" form="sign-in" data-variant="solid">Sign In</button>
    <button type="reset" form="sign-in">Reset</button>
  </div>
</div>
```

输入邮箱和密码，显示密码，然后在字段里按 Enter。提交会再次隐藏它，控制台会记录它的长度。重置会清空表单。为空的必填字段会阻止提交。

提交、重置和页面隐藏都会请求再次隐藏密码。重置还会恢复它的默认值。密码可见时，拼写标记、自动更正和自动大写保持禁用。

## 受控的值
用 `bind:value` 绑定密码，或传入 `value` 并处理 `onValueChange`。[新密码示例](https://ui-sdk.cn/docs/svelte/components/password-input#new-password)就是这样推导检查清单的。[状态与事件](/docs/svelte/state-and-events)介绍了通用的状态约定。

```svelte
<script lang="ts">
  let password = $state("")
</script>

<PasswordInput bind:value={password}>
  <PasswordInputControl aria-label="Password" />
  <PasswordInputToggle aria-label="Show password">Show</PasswordInputToggle>
</PasswordInput>
```

## 自定义渲染
每个部件都接受一个 `render` 片段，它接收要展开的 props 和部件的状态，`children` 片段也会收到状态：密码是否 `visible`、大写锁定是否开启（`capsLock`），以及字段是否 `filled`。渲染约定见[部件与组合](/docs/svelte/parts-and-composition)。

```svelte
<PasswordInputToggle aria-label="Show password">
  {#snippet render({ props, state })}
    <button {...props}>
      {#if state.visible}
        <EyeOffIcon aria-hidden="true" />
      {:else}
        <EyeIcon aria-hidden="true" />
      {/if}
    </button>
  {/snippet}
</PasswordInputToggle>
```

## 样式
把根部件当作字段的盒子来设置样式，原生输入框和切换按钮放在里面。密码显示时，`data-visible` 会标记每个部件，切换按钮还会设置 `aria-pressed`。用 `data-capslock` 表示大写锁定警告，用 `data-filled`、`data-disabled` 和 `data-readonly` 表示字段的其他状态。在 Field 内部，原生输入框还会收到 `data-invalid` 这样的校验属性。使用逻辑间距，让字段和切换按钮跟随周围的方向。

每个部件都有一个 `data-slot`，比如 `password-input-toggle`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/svelte/components/password-input#data-attributes)下。

## 数据属性
### PasswordInput
`[data-slot="password-input"]`

- `data-visible`: Present while the password is shown, so the field is a text field.
- `data-filled`: Present while the field holds any text.
- `data-disabled`: Present when disabled, by its own prop, a Field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when a password is required.
- `data-capslock`: Present while Caps Lock is on and the field has focus.

### PasswordInputControl
`[data-slot="password-input-control"]`

- `data-visible`: Present while the password is shown, so the field is a text field.
- `data-filled`: Present while the field holds any text.
- `data-disabled`: Present when disabled, by its own prop, a Field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when a password is required.
- `data-capslock`: Present while Caps Lock is on and the field has focus.

### PasswordInputToggle
`[data-slot="password-input-toggle"]`

- `data-visible`: Present while the password is shown, so the field is a text field.
- `data-filled`: Present while the field holds any text.
- `data-disabled`: Present when disabled, by its own prop, a Field or a `<fieldset>`.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when a password is required.
- `data-capslock`: Present while Caps Lock is on and the field has focus.

## API 参考
属性和回调与下面相同，都作为 Svelte props。`value` 和 `visible` 可以用 `bind:value` 和 `bind:visible` 绑定。

### PasswordInput
- `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.
- `visible?` (`boolean`): Whether the password is shown. Pass it to control it.
- `defaultVisible?` (`boolean`): Whether the password is shown at first, when uncontrolled.
- `onVisibleChange?` (`((visible: boolean, details: ChangeDetails<PasswordInputVisibleChangeReason>) => void)`): Runs when the password wants to be shown or hidden: the toggle (`"toggle-press"`), submitting or resetting its form (`"form-submit"`, `"reset"`), the page being hidden (`"page-hide"`) or a controller (`"imperative"`). `details.cancel()` keeps it as it was; the field is a password field while the browser reads a submitted form either way.
- `autoComplete?` (`"current-password" | "new-password" | "off" | (string & {})`): What the browser and password managers fill in: `"current-password"` for signing in, `"new-password"` for signing up or changing it.
- `name?` (`string`): The name the password submits under. Inside a Field, the Field's name.
- `form?` (`string`): The id of the form the field belongs to, when it isn't inside it.
- `required?` (`boolean`): Whether a password is required to submit the form.
- `disabled?` (`boolean`): Disables the field and the toggle. Inside a Field or a disabled `<fieldset>`, they follow it.
- `readOnly?` (`boolean`): Makes the field read-only. The toggle still shows and hides it.
- `controller?` (`object`): Reads, writes, shows and hides it from anywhere. Create one with `createPasswordInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
渲染函数、基于状态的类名和槽位会收到什么。每个部件都会收到相同的状态。

- `visible` (`boolean`): Whether the password is shown.
- `capsLock` (`boolean`): Whether Caps Lock is on while the field has focus.
- `filled` (`boolean`): Whether the field holds any text.
- `disabled` (`boolean`): Whether the field is disabled, by itself, its Field or a `<fieldset>`.
- `readOnly` (`boolean`): Whether the field is read-only.
- `required` (`boolean`): Whether a form won't submit while the field is empty.

### 原因
`details.reason` 说明值为什么变更。自动填充和密码管理器的填入都是 `input-change`。

- `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.

以及密码为什么被显示或隐藏：

- `toggle-press` (`MouseEvent | KeyboardEvent`): A toggle was pressed: a password input's, which shows or hides the password, or a carousel's, which starts or stops rotation.
- `form-submit` (`SubmitEvent`): The form was submitted, which hides a shown password so the browser offers to save it.
- `reset` (`none`): A form reset.
- `page-hide` (`PageTransitionEvent`): The page was hidden, like when navigating away, which hides a shown password before the browser keeps the page.
- `imperative` (`none`): A controller or `api` call.

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

每个写入方法都接受可选的 `{ reason, event }`，并像输入或按压一样运行变更回调。变更被取消时，`setVisible()` 和 `toggleVisible()` 返回 `false`。

- `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.
- `isVisible()` (`() => boolean`): Whether the password is shown.
- `setVisible(visible, options?)` (`(visible: boolean, options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean`): Shows or hides the password. Returns false when canceled.
- `toggleVisible(options?)` (`(options?: ChangeOptions<PasswordInputVisibleChangeReason> | undefined) => boolean`): Shows the password if it's hidden, and hides it if it's shown. Returns false when canceled.
- `focus()` (`() => void`): Moves focus to the field.

### 事件
回调先收到新值，再收到详情。只有回调没有取消变更时，绑定的 prop 才会更新。

| Prop              | 所属部件        | 收到                                                       |
| ----------------- | --------------- | ---------------------------------------------------------- |
| `bind:value`      | `PasswordInput` | 密码                                                       |
| `bind:visible`    | `PasswordInput` | 密码是否显示                                               |
| `onValueChange`   | `PasswordInput` | `(value, details)`：新密码和[原因](https://ui-sdk.cn/docs/svelte/components/password-input#reasons)               |
| `onVisibleChange` | `PasswordInput` | `(visible, details)`：密码是否要显示，以及[原因](https://ui-sdk.cn/docs/svelte/components/password-input#reasons) |

## 无障碍
密码字段没有 WAI-ARIA 模式。输入框保持为原生密码字段，由它的字段标签或 `aria-label` 提供名称；切换按钮则按 [WAI-ARIA 按钮模式](https://www.w3.org/WAI/ARIA/apg/patterns/button/)作为切换按钮。按切换按钮做的事来命名它，比如“Show password”，并保持这个名称不变：它的 `aria-pressed` 状态告诉屏幕阅读器密码是否显示，`aria-controls` 指向输入框。

### 键盘
Tab 从输入框移动到切换按钮，在切换按钮上按 Space 或 Enter 会显示或隐藏密码。在输入框里按 Enter 会提交它的表单；它永远不会按压切换按钮。

### 焦点
用指针按压切换按钮时，焦点留在输入框里，光标和选区保持原位。从别处按压会把焦点带回输入框。键盘按压会让焦点留在切换按钮上。

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

- The field is a password field named by its label and described by its description.
- The toggle is a button that says what it does, and isn't pressed.
- Pressing the toggle shows the password, and pressing it again hides it.
- Space on the focused toggle shows the password and keeps focus on the toggle.
- Enter on the focused toggle shows the password and keeps focus on the toggle.
- The toggle keeps its name when the password shows.
- Enter in the field submits the form, and never presses the toggle.
- The password submits under its name.
- The password can start shown.
- A change can be canceled.
- A disabled password input disables the field and the toggle.
- A read-only field can still be shown.
- The controller shows and hides the password.
- A controlled password input follows its owner. React 和 Vue only.
- A click with no pointer behind it, like a screen reader's, shows the password.

Runs in React、Vue 和 web components.

模式之外：

- Showing the password keeps focus in the field, with the caret where it was.
- Showing and hiding the password keeps the selection.
- A click on the toggle while typing never blurs the field.
- A click on the toggle from elsewhere brings focus back to the field.
- Submitting hides a shown password before the page's own submit handler runs.
- Submitting hides the password even when the change is canceled, while the browser reads the form.
- Resetting the form hides the password.
- Hiding the page hides the password, so the browser never keeps it as text.
- A shown password is never spellchecked, autocorrected or capitalized.
- The field asks password managers for the current password, or a new one.
- Caps Lock marks the input while the field has focus.
- A click into the field with Caps Lock on shows the warning before any key.
- A web field keeps an autocomplete changed after it connects. Web components only.
- The toggle has its own id and controls the field.
- A disabled fieldset disables the toggle too.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器录制：

- Announcements while showing and hiding a password with a keyboard.

Runs in React、Vue 和 web components.

还测试了：

- No axe violations at rest.
- No axe violations with the password shown.
- No axe violations while disabled.
- No axe violations while read-only.
- The field is named by its label, and the toggle by its aria-label.
- Accessibility tree.

Runs in React、Vue 和 web components.
