# Button

执行动作，显示它正在工作，并在禁用时仍可聚焦。

Button 包裹一个原生 `button`，并补上它自己做不到的事：异步动作运行时它保持待处理，所以表单不会提交两次；它向屏幕阅读器播报缓慢的动作；禁用时仍可聚焦；包裹链接时也保持相同的行为。如果只是需要一个普通的点击处理函数，原生 `button` 就够了。

```ts title="basic.ts"
import "@ui-sdk/web/button"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `<ui-button><button>Button</button></ui-button>`
  root
    .querySelector("ui-button")!
    .addEventListener("action", () => log(root, "Pressed"))
}

export { mount }
```

点击 Button，或聚焦它后按 Enter 或 Space。控制台会记录每一次按压。

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

导入这个组件会在浏览器里注册 `<ui-button>`。在服务器上，导入什么也不做。

```ts
import "@ui-sdk/web/button"
```

## 用法
把原生 `<button>` 包进 `<ui-button>`，然后监听它的 `action` 事件来执行动作。没有 type 的按钮会得到 `type="button"`。

```html
<ui-button><button>Save</button></ui-button>
```

```ts
import "@ui-sdk/web/button"

document.querySelector("ui-button")!.addEventListener("action", () => save())
```

外层元素以 `contents` 显示。把类和原生属性放在里面的按钮上；把 `disabled` 这类选项放在 `<ui-button>` 上。

## 待处理
把一个 Promise 传给 `event.detail.waitUntil()`，让按钮保持待处理，直到它结束。等待期间，按钮保持焦点，并忽略后续的按压。在事件监听器里、`await` 之前调用 `waitUntil()`。

```ts
button.addEventListener("action", (event) => {
  event.detail.waitUntil(new Promise((resolve) => setTimeout(resolve, 1500)))
})
```

一秒之后，它会向屏幕阅读器播报“Loading”。在 `<ui-button>` 上设置 `pending-announcement="Saving"` 可以换掉这条消息，或者使用空字符串让它静默。

```ts title="pending.ts"
import "@ui-sdk/web/button"

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function mount(root: HTMLElement) {
  root.innerHTML = `<ui-button pending-announcement="Saving"><button>Save</button></ui-button>`
  root
    .querySelector("ui-button")!
    .addEventListener("action", (event) => event.detail.waitUntil(wait(1500)))
}

export { mount }
```

按 Save，然后在它保存时再按一次。第一次动作结束之前，什么也不会发生。

## 待处理内容
要在按钮等待时改变它显示的内容，用 `data-show="idle"` 或 `data-show="pending"` 标记内容，再用各自一条 CSS 规则在另一状态下隐藏它，或者使用 Tailwind 的 `in-data-pending` 变体：

```css
[data-slot="button"]:not([data-pending]) [data-show="pending"],
[data-slot="button"][data-pending] [data-show="idle"] {
  display: none;
}
```

```ts title="pending-content.ts"
import "@ui-sdk/web/button"
import { ArrowDownToLine, createElement, LoaderCircle } from "lucide"

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-button pending-announcement="Saving">
      <button>
        ${createElement(ArrowDownToLine, { "data-show": "idle", "aria-hidden": "true" }).outerHTML}
        ${createElement(LoaderCircle, { "data-show": "pending", "data-slot": "spinner", "aria-hidden": "true" }).outerHTML}
        Save
      </button>
    </ui-button>
  `
  root
    .querySelector("ui-button")!
    .addEventListener("action", (event) => event.detail.waitUntil(wait(1500)))
}

export { mount }
```

按 Save。保存期间，它的箭头会变成一个加载指示器。

保持标签不变，只改视觉，就像上面这样。如果文字也必须变，用同样的方式替换，不要加 `aria-label`。[待处理的按钮](https://ui-sdk.cn/docs/web-components/components/button#pending-buttons)解释了原因：

```html
<ui-button>
  <button>
    <span data-show="idle">Save</span>
    <span data-show="pending">Saving…</span>
  </button>
</ui-button>
```

## 处理错误
如果 Promise 被拒绝，Button 会清除它的待处理状态，并接受下一次按压。处理这个拒绝，以显示消息或重试标签。

Web Components 没有渲染函数：示例把原来的 Promise 传给 `waitUntil()`，并单独处理它的拒绝来改变标签，这样 Button 仍然能收到这个拒绝。

```ts title="render.ts"
import "@ui-sdk/web/button"
import { log } from "./log"

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-button><button>Save Changes</button></ui-button>
    </div>
  `
  const save = root.querySelector("ui-button")!
  const button = save.querySelector("button")!
  save.addEventListener("action", (event) => {
    button.textContent = "Saving…"
    const saving = wait(1000).then(() => {
      log(root, "Couldn't save. Check your connection and try again.")
      throw new Error("Couldn't save")
    })
    event.detail.waitUntil(saving)
    saving.catch(() => {
      button.textContent = "Try Again"
    })
  })
}

export { mount }
```

选择 Save Changes。这里的保存总是失败：控制台会显示错误，标签会变成 Try Again。

## await 之后的变更
`action` 事件的 `detail.source` 说明按钮是如何被按压的。如果监听器在 `await` 之后更改另一个 ui-sdk 组件，就用 `withSource` 包住那次变更，以保留原来的来源。否则，之后的变更会被上报为 `"programmatic"`。

这里 `save()` 是你的请求，`saveButton` 是一个 `<ui-button>`，`status` 是一个 `<ui-input>`，它的 `api` 就是它的[控制器](/docs/web-components/controllers)：

```ts
import "@ui-sdk/web/button"
import { withSource } from "@ui-sdk/web/observe"

saveButton.addEventListener("action", (event) => {
  const { source, waitUntil } = event.detail
  waitUntil(
    save().then(() => withSource(source, () => status.api.setValue("Saved")))
  )
})
```

[观察](https://ui-sdk.cn/docs/core/observe#keep-the-source-after-an-await)解释了来源跟踪。保留 `"agent"` 能让 [`undoSource("agent")`](https://ui-sdk.cn/docs/agents/connect-an-agent/history-and-undo#undo-the-agents-changes) 把之后的那次变更也包含进去。

## 禁用
在 `<ui-button>` 上设置 `disabled`，阻止按压并把它的按钮从 Tab 顺序中移除。按钮外层禁用的 `<fieldset>` 也会禁用它。

```html
<ui-button disabled><button>Disabled</button></ui-button>
```

```ts title="disabled.ts"
import "@ui-sdk/web/button"

function mount(root: HTMLElement) {
  root.innerHTML = `<ui-button disabled><button>Disabled</button></ui-button>`
}

export { mount }
```

试着点击这个按钮。它什么也不做，Tab 会跳过它。

## 禁用时仍可聚焦
如果人们仍应能聚焦禁用的按钮，就加上 `focusable-when-disabled`。里面的按钮会使用 `aria-disabled`，而不是原生的 `disabled` 属性。按压仍然不起作用。

在里面的按钮上用 `aria-describedby` 说明这个动作为什么不可用：

```html
<ui-button disabled focusable-when-disabled>
  <button aria-describedby="publish-hint">Publish</button>
</ui-button>
<p id="publish-hint">Add a title to publish.</p>
```

```ts title="focusable-when-disabled.ts"
import "@ui-sdk/web/button"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { log } from "./log"

function mount(root: HTMLElement) {
  const hintId = `publish-hint-${crypto.randomUUID()}`
  root.innerHTML = `
    <div data-slot="stack">
      <ui-field>
        <ui-field-label>Title</ui-field-label>
        <ui-input>
          <input />
        </ui-input>
      </ui-field>
      <div data-slot="row">
        <ui-button disabled focusable-when-disabled>
          <button aria-describedby="${hintId}">Publish</button>
        </ui-button>
        <p id="${hintId}" data-slot="hint">Add a title to publish.</p>
      </div>
    </div>
  `
  const title = root.querySelector("input")!
  const publish = root.querySelector("ui-button")!
  const hint = root.querySelector("p")!
  title.addEventListener("input", () => {
    const ready = title.value.trim() !== ""
    publish.disabled = !ready
    hint.textContent = ready ? "Ready to publish." : "Add a title to publish."
  })
  publish.addEventListener("action", () =>
    log(root, `Published “${title.value}”`)
  )
}

export { mount }
```

聚焦 Title，然后按 Tab 在它禁用时到达 Publish。输入标题来启用它，再选择 Publish。控制台会记录发布的内容。

## 链接
包裹一个 `<a>` 来生成链接。它会保留 `href` 和链接语义，包括在新标签页中打开。禁用的链接无法导航，并且会离开 Tab 顺序。

```html
<ui-button><a href="/docs/web-components">Get started</a></ui-button>
```

```ts title="link.ts"
import "@ui-sdk/web/button"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="row">
      <ui-button><a href="#installation">Get Started</a></ui-button>
      <ui-button disabled><a href="#changelog">Changelog</a></ui-button>
    </div>
  `
}

export { mount }
```

选择 Get Started 跳到本页的 Installation。Changelog 处于禁用状态，不会导航。

要使用你自己的元素，见[部件与组合](/docs/web-components/parts-and-composition)。

## 表单
在里面的按钮上设置 `type="submit"` 来提交表单，或 `type="reset"` 来恢复表单的默认值。默认的 `type="button"` 两者都不做。

```html
<ui-button><button type="submit">Subscribe</button></ui-button>
<ui-button><button type="reset">Reset</button></ui-button>
```

```ts title="form.ts"
import "@ui-sdk/web/button"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-field-label>Email</ui-field-label>
        <ui-input>
          <input name="email" type="email" value="ada@example.com" />
        </ui-input>
      </ui-field>
      <div data-slot="row">
        <ui-button><button type="submit">Subscribe</button></ui-button>
        <ui-button><button type="reset">Reset</button></ui-button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Subscribed ${new FormData(form).get("email")}`)
  })
}

export { mount }
```

修改邮箱并选择 Subscribe，或在输入框里按 Enter。控制台会记录每次提交，Reset 会恢复原来的邮箱。

Button 跟踪的是传给它自己的 `action` 事件的 `waitUntil()` 的 Promise，而不是表单的 `submit` 处理函数。对于异步提交处理函数，在它运行时给 `<ui-button>` 设置 `disabled`，同时用 [`focusable-when-disabled`](https://ui-sdk.cn/docs/web-components/components/button#focusable-when-disabled) 让按钮在等待时保持焦点。

## 样式
状态属性放在里面的元素上：用 `data-pending` 显示加载指示器或等待光标，用 `data-disabled` 为不可用的动作设置样式。里面元素的 `data-slot` 是 `button`，它的属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/button#data-attributes)下。

[样式与动画](/docs/web-components/styling-and-animation)涵盖了所有组件共用的样式模式。

## 数据属性
### `<ui-button>`
`[data-slot="button"]`

- `data-pending`: Present while the Promise its press handler returned is running.
- `data-disabled`: Present when disabled.

## API 参考
在 `<ui-button>` 上把选项设为 kebab-case 属性或 camelCase property，比如 `focusable-when-disabled` 或 `focusableWhenDisabled`。`type` 来自里面的按钮。`<ui-button>` 绑定到它的第一个子按钮或链接，否则绑定到它的第一个元素；这个元素会获得 `button` 角色、一个 Tab 停靠点，以及用于按压它的 Enter 和 Space。见[部件与组合](/docs/web-components/parts-and-composition)。

### Button
- `disabled?` (`boolean`): Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless `focusableWhenDisabled` is set.
- `focusableWhenDisabled?` (`boolean`): Keeps a disabled button in the tab order with `aria-disabled` instead of the native attribute, so it can hold focus while it becomes disabled and host a tooltip that says why. Presses still do nothing.
- `type?` (`"button" | "reset" | "submit"`): What a native button does in a form: `"submit"` submits it and `"reset"` resets it. Ignored when the button renders as something else.
- `pendingAnnouncement?` (`string`): What screen readers hear once the button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
Web Components 没有渲染函数。给里面元素的状态属性设置样式，并处理动作的 Promise 来显示错误。

- `disabled` (`boolean`): Whether it's disabled, by the `disabled` option or a disabled fieldset around it. A running press shows in `pending` instead.
- `pending` (`boolean`): Whether the Promise the last press returned is still running. Presses do nothing meanwhile.
- `error` (`unknown`): Why the last press failed: what its handler threw, or its Promise rejected with. Cleared by the next press.

### 事件
监听 `<ui-button>` 本身。`action` 事件可以取消，也带有 composed 标志，但不会冒泡。禁用或待处理的按钮不会触发它。

| 事件     | 收到                                                                                                                  |
| -------- | --------------------------------------------------------------------------------------------------------------------- |
| `action` | `detail: { source, waitUntil(promise) }`。在派发期间把一个 Promise 传给 `waitUntil()`，让按钮保持待处理，直到它结束。 |

## 无障碍
给按钮一个清晰的文本标签。如果它只包含一个图标，给里面的按钮加上 `aria-label`。原生按钮响应 Enter 和 Space；链接响应 Enter。

### 待处理的按钮
动作运行期间，按钮会告诉辅助技术它正忙，所以你不需要添加任何东西：

- 它在里面的按钮上设置 `aria-busy="true"` 和 `aria-disabled="true"`，并在动作结束前忽略按压。整个过程它一直保持焦点。
- 一秒之后，它通过一个礼貌的实时区域（polite live region）播报 `pending-announcement`（默认是 `"Loading"`）。快速的动作保持静默。这是一条状态消息：人们不用移动焦点就能听到。

要显示进度，保持标签不变，只改视觉，比如一个加载指示器。改变文字会在按钮获得焦点时给它改名：屏幕阅读器并不能可靠地播报聚焦元素上的新名称，所以这种改动主要帮助有视力的用户，而且文字长度变化时按钮的宽度也会跟着变。播报已经告诉大家它正在工作。

```html title="Do"
<ui-button pending-announcement="Saving">
  <button>
    <svg data-show="idle" aria-hidden="true">…</svg>
    <svg data-show="pending" aria-hidden="true">…</svg>
    Save
  </button>
</ui-button>
```

```html title="Don't"
<ui-button>
  <button aria-label="Save">
    Saving…
    <span aria-live="polite">Saving</span>
  </button>
</ui-button>
```

第二个按钮在保存时替换自己的文字，显示了它的无障碍名称里没有的文字，并且把同一个状态播报了两次。如果文字无论如何都必须变，就用 `data-show` 替换它，并去掉 `aria-label`，这样按钮的名称始终包含屏幕上的文字。标记见[待处理内容](https://ui-sdk.cn/docs/web-components/components/button#pending-content)。

参考：

- [WCAG 2.5.3 Label in Name](https://www.w3.org/WAI/WCAG22/Understanding/label-in-name.html)
- [WCAG 4.1.3 Status Messages](https://www.w3.org/WAI/WCAG22/Understanding/status-messages.html)
- [WAI-ARIA `aria-busy`](https://www.w3.org/TR/wai-aria-1.2/#aria-busy) 和 [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled)

### 经过测试的行为
以下行为由自动化测试覆盖：

- Clicking a button runs its handler.
- Space presses a focused button.
- Enter presses a focused button.
- A submit button submits its form.
- A reset button resets its form.
- A disabled button can't be focused or pressed.
- A button rendered as a link stays a link.

**Focusable when disabled**

- It stays focusable and says it's disabled.
- Tab reaches it.
- Clicking it runs nothing and submits nothing.
- Space on it runs nothing and submits nothing.
- Enter on it runs nothing and submits nothing.

**Pending**

- A returned Promise makes it busy, and it keeps focus until the Promise settles.
- While pending, it says it's unavailable with aria-disabled and keeps focus.
- Still pending after a second, it tells screen readers it's loading.
- A rejected Promise ends the pending state.

Runs in React、Vue 和 web components.
