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

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

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Password</ui-field-label>
      <ui-password-input name="password">
        <input />
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <ui-field-description>Use at least 8 characters.</ui-field-description>
    </ui-field>
  `
}

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

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件会定义它的元素。用到字段时也导入字段。在服务器上,导入不会做任何事。

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"

组合

用下面的组合构建 ui-password-input:

ui-password-input
├── input
└── ui-password-input-toggle
    └── button

ui-password-input 保存值和可见性状态。它连接你的原生输入框和 ui-password-input-toggle 里的按钮。切换按钮在 password 和 text 之间切换输入框,它的按钮是 type="button",所以在输入框里按 Enter 仍然会提交表单。

把 name、form、required、disabled 和 read-only 这样的表单选项放在 ui-password-input 上。把 autocomplete、placeholder 或 id 这样的其他原生输入属性放在 <input> 上。

用法

导入部件并把它们组合起来:

<script type="module">
  import "@ui-sdk/web/password-input"
</script>

<ui-password-input name="password">
  <input type="password" aria-label="Password" />
  <ui-password-input-toggle>
    <button aria-label="Show password">Show</button>
  </ui-password-input-toggle>
</ui-password-input>

新密码

创建或修改密码时,在原生输入框上使用 autocomplete="new-password"。它告诉浏览器和密码管理器要提供哪种密码。登录时的默认值是 current-password。

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

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { Check, createElement, Eye, EyeOff, X } from "lucide"

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),
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Create a password</ui-field-label>
      <ui-password-input name="new-password">
        <input autocomplete="new-password" />
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <ul data-slot="stack" aria-label="Password requirements">
        ${rules
          .map(
            (rule) => `
              <li data-slot="row">
                ${createElement(X, { "aria-hidden": "true" }).outerHTML}
                ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                <span data-slot="visually-hidden" data-rule-status>To do:</span>
                ${rule.label}
              </li>
            `
          )
          .join("")}
      </ul>
    </ui-field>
  `
  const items = root.querySelectorAll("li")
  root
    .querySelector("ui-password-input")!
    .addEventListener("valuechange", (event) => {
      rules.forEach((rule, index) => {
        const met = rule.test(event.detail.value)
        items[index].toggleAttribute("data-met", met)
        items[index].querySelector("[data-rule-status]")!.textContent = met
          ? "Done:"
          : "To do:"
      })
    })
}

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

一开始就可见

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

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Wi-Fi password</ui-field-label>
      <ui-password-input name="wifi-password" default-visible default-value="maple-orbit-42">
        <input autocomplete="new-password" />
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <ui-field-description>Guests read it from here, so it starts shown.</ui-field-description>
    </ui-field>
  `
}

export { mount }
读取 Wi-Fi 密码,然后选择 Show password 隐藏它。再次选择它会显示值。

大写锁定

用 data-capslock 显示警告。输入框获得焦点时,它会随按键事件更新。示例为图标和警告预留了空间。

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff, Lock } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Password</ui-field-label>
      <ui-password-input name="password">
        <input />
        ${createElement(Lock, { "aria-hidden": "true" }).outerHTML}
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <p data-slot="caps-lock">Caps Lock is on.</p>
    </ui-field>
  `
}

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

禁用

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

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field disabled>
      <ui-field-label>Password</ui-field-label>
      <ui-password-input name="password" default-value="hunter22">
        <input />
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <ui-field-description>Your administrator manages this password.</ui-field-description>
    </ui-field>
  `
}

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

只读

当值可以读取但不能编辑时,设置 read-only。输入框仍然可以聚焦,切换按钮仍然可用,值也仍然参与表单提交。

import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Recovery key</ui-field-label>
      <ui-password-input name="recovery-key" read-only default-value="7Hq2-vX9p-Lm4c">
        <input autocomplete="off" />
        <ui-password-input-toggle>
          <button aria-label="Show recovery key">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
      <ui-field-description>Keep it somewhere safe. You can show it, but not change it.</ui-field-description>
    </ui-field>
  `
}

export { mount }
选择 Show recovery key 来读取它。试着在输入框里输入;它的值保持不变。

受控的可见性

监听 visiblechange,并在应用需要更改它时设置元素的 visible property。原因区分切换按钮的按压、表单提交、重置、页面隐藏,以及控制器动作。

控制台
import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Password</ui-field-label>
      <ui-password-input name="password">
        <input />
        <ui-password-input-toggle>
          <button aria-label="Show password">
            ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
            ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-password-input-toggle>
      </ui-password-input>
    </ui-field>
  `
  root
    .querySelector("ui-password-input")!
    .addEventListener("visiblechange", (event) => {
      const { value, reason } = event.detail
      log(root, `${value ? "Shown" : "Hidden"} (${reason})`)
    })
}

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

在变更监听器里调用 event.preventDefault() 来拒绝一次可见性变更。表单提交期间,即使监听器拒绝隐藏密码,原生输入框也会暂时变成密码字段。

控制器

输入框之外的动作使用元素的 api。也可以传入用 createPasswordInputController() 创建的控制器。读取或更改值、切换可见性,或聚焦输入框。写入会使用 imperative 原因。

控制台
import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import { createElement, Eye, EyeOff } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="suggest">Suggest</button>
        <button type="button" data-action="toggle">Toggle</button>
        <button type="button" data-action="clear">Clear</button>
        <button type="button" data-action="read">Read</button>
        <button type="button" data-action="focus">Focus</button>
      </div>
      <ui-field>
        <ui-field-label>New password</ui-field-label>
        <ui-password-input name="new-password">
          <input autocomplete="new-password" />
          <ui-password-input-toggle>
            <button aria-label="Show password">
              ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
              ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-password-input-toggle>
        </ui-password-input>
      </ui-field>
    </div>
  `
  const password = root.querySelector("ui-password-input")!.api
  const actions: Record<string, () => void> = {
    suggest: () => {
      password.setValue("plum-kettle-orbit-42")
      password.setVisible(true)
    },
    toggle: () => password.toggleVisible(),
    clear: () => password.clear(),
    read: () =>
      log(
        root,
        `${password.getValue().length} characters, ${password.isVisible() ? "shown" : "hidden"}`
      ),
    focus: () => password.focus(),
  }
  root
    .querySelectorAll<HTMLButtonElement>("[data-action]")
    .forEach((button) => {
      button.addEventListener("click", () => actions[button.dataset.action!]())
    })
}

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

控制器介绍了如何创建和共享控制器。

表单

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

控制台
import "@ui-sdk/web/password-input"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { createElement, Eye, EyeOff } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <form data-slot="stack" id="sign-in">
        <ui-field name="email">
          <ui-field-label>Email</ui-field-label>
          <ui-input><input type="email" required autocomplete="username" /></ui-input>
        </ui-field>
      </form>
      <ui-field>
        <ui-field-label>Password</ui-field-label>
        <ui-password-input name="password" form="sign-in" required>
          <input />
          <ui-password-input-toggle>
            <button aria-label="Show password">
              ${createElement(Eye, { "aria-hidden": "true" }).outerHTML}
              ${createElement(EyeOff, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-password-input-toggle>
        </ui-password-input>
      </ui-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>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const data = new FormData(form)
    const length = String(data.get("password")).length
    log(
      root,
      `Signed in as ${data.get("email")}, with a password of ${length} characters`
    )
  })
}

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

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

受控的值

监听 valuechange 读取输入的变更,并设置元素的 value property 从应用里更新它。新密码示例就是这样推导检查清单的。状态与事件介绍了通用的状态约定。

const password = document.querySelector("ui-password-input")!
password.addEventListener("valuechange", (event) =>
  console.log(event.detail.value, event.detail.reason)
)
password.value = ""

自定义渲染

元素没有渲染函数。切换按钮包住你自己的 <button>,所以可以把任何内容放进去,并从每个部件设置的数据属性读取状态:密码是否显示(data-visible)、大写锁定是否开启(data-capslock),以及字段是否已填(data-filled)。这里按钮同时放两个图标,样式表在设置 data-visible 时显示第二个。

<ui-password-input-toggle>
  <button aria-label="Show password">
    <svg aria-hidden="true"><!-- eye --></svg>
    <svg aria-hidden="true"><!-- eye off --></svg>
  </button>
</ui-password-input-toggle>

样式

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

每个部件都有一个 data-slot,比如 password-input-toggle,它的状态属性列在数据属性下。

数据属性

<ui-password-input>

[data-slot="password-input"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

<input>

[data-slot="password-input-control"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

<ui-password-input-toggle>

[data-slot="password-input-toggle"]

属性含义
data-visiblePresent while the password is shown, so the field is a text field.
data-filledPresent while the field holds any text.
data-disabledPresent when disabled, by its own prop, a Field or a <fieldset>.
data-readonlyPresent when the field is read-only.
data-requiredPresent when a password is required.
data-capslockPresent while Caps Lock is on and the field has focus.

API 参考

属性是 kebab 写法的 attribute,比如 default-value、default-visible 和 read-only。autocomplete 和 id 从 <input> 读取。controller 是 property。回调是 DOM 事件。

PasswordInput

value?string
The value, for a controlled field.
defaultValue?string
The value it starts with. A form reset returns here.
valuechange event
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.
visiblechange event
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.

状态

相同的状态会作为数据属性显示在每个元素上。

visibleboolean
Whether the password is shown.
capsLockboolean
Whether Caps Lock is on while the field has focus.
filledboolean
Whether the field holds any text.
disabledboolean
Whether the field is disabled, by itself, its Field or a <fieldset>.
readOnlyboolean
Whether the field is read-only.
requiredboolean
Whether a form won't submit while the field is empty.

原因

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

input-changeEvent
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-pressMouseEvent | KeyboardEvent
A Clear part was pressed, like on an input, a select or a combobox.
resetnone
A form reset.
imperativenone
A controller or api call.

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

toggle-pressMouseEvent | 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-submitSubmitEvent
The form was submitted, which hides a shown password so the browser offers to save it.
resetnone
A form reset.
page-hidePageTransitionEvent
The page was hidden, like when navigating away, which hides a shown password before the browser keeps the page.
imperativenone
A controller or api call.

控制器

元素的 api property 有相同的方法。value 和 visible property 读取和设置密码以及它是否显示。

每个写入方法都接受可选的 { 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.

事件

事件在自己的元素上触发,不冒泡,新值在 event.detail.value 中,reason、event 和 source 在它旁边。调用 preventDefault() 会取消这次变更。

成员所属说明
value propertyui-password-input密码
visible propertyui-password-input密码是否显示
api propertyui-password-input控制器
controller propertyui-password-input一个 createPasswordInputController() 创建的控制器,用来驱动它
valuechange 事件ui-password-inputdetail: { value, reason, event, source },每次变更时
visiblechange 事件ui-password-inputdetail: { value, reason, event, source },在显示或隐藏时

无障碍

密码字段没有 WAI-ARIA 模式。输入框保持为原生密码字段,由它的字段标签或 aria-label 提供名称;切换按钮则按 WAI-ARIA 按钮模式作为切换按钮。按切换按钮做的事来命名它的按钮,比如“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 运行。
  • A click with no pointer behind it, like a screen reader's, shows the password.

运行于 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 运行。
  • The toggle has its own id and controls the field.
  • A disabled fieldset disables the toggle too.

运行于 React、Vue 和 web components。

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

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

运行于 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.

运行于 React、Vue 和 web components。