注册键盘快捷键,并显示符合用户平台的按键。

registerShortcut 把按键连接到动作。对于已经接受 shortcut 的元素,比如对话框触发器,直接使用那个属性。

import { ariaKeyshortcuts, formatShortcut, registerShortcut } from "@ui-sdk/web"

export function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="row">
        <button type="button" data-action="new" aria-keyshortcuts="N">New note <kbd aria-hidden="true" data-slot="kbd">N</kbd></button>
        <button type="button" data-action="save" aria-keyshortcuts="${ariaKeyshortcuts("mod+s")}">Save <kbd aria-hidden="true" data-slot="kbd">${formatShortcut("mod+s")}</kbd></button>
      </div>
      <output data-slot="output">Press N or the keys to save.</output>
    </div>
  `
  const output = root.querySelector("output")!
  const actions = {
    new: () => (output.textContent = "Note created"),
    save: () => (output.textContent = "Saved"),
  }
  root
    .querySelector('[data-action="new"]')!
    .addEventListener("click", actions.new)
  root
    .querySelector('[data-action="save"]')!
    .addEventListener("click", actions.save)

  const offs = [
    registerShortcut("n", actions.new, { description: "New note" }),
    registerShortcut("mod+s", actions.save, { description: "Save" }),
  ]
  return () => offs.forEach((off) => off())
}
按 N 创建一条笔记。在 Mac 上按 Command+S,在其他平台上按 Control+S 保存。按钮执行同样的动作。

注册快捷键

按键之间用 + 连接。mod 在 Apple 平台上表示 Command,在其他平台上表示 Control:

<button id="new-note">New note <kbd aria-hidden="true"></kbd></button>
<p id="count" aria-live="polite">0 notes</p>
import { ariaKeyshortcuts, formatShortcut, registerShortcut } from "@ui-sdk/web"

const button = document.querySelector<HTMLButtonElement>("#new-note")!
const count = document.querySelector("#count")!
let total = 0
function addNote() {
  total++
  count.textContent = `${total} notes`
}

const unregister = registerShortcut("mod+enter", addNote, {
  description: "New note",
})
button.addEventListener("click", addNote)
button.setAttribute("aria-keyshortcuts", ariaKeyshortcuts("mod+enter"))
button.querySelector("kbd")!.textContent = formatShortcut("mod+enter")

function disconnect() {
  unregister()
  button.removeEventListener("click", addNote)
}

移除这个视图时调用 disconnect()。registerShortcut 返回取消注册它的函数。

显示按键

formatShortcut 按当前平台生成显示文本。ariaKeyshortcuts 生成对应的 aria-keyshortcuts 值。示例对屏幕阅读器隐藏可见的提示,因为按钮本身已经暴露了这个快捷键。

页面加载之后再格式化浏览器相关的提示。在从右到左的页面上,文本会保持从左到右的顺序,因为有两个不可见字符包裹着它。比较原始的按键,而不是格式化后的显示文本。

当有人正在输入时

带 Command、Control 或 Option 的快捷键可以在文本字段里运行。普通字母和其他按键仍然可以用于输入。当快捷键也需要在那里生效时,设置 allowInInput: true,比如用 Escape 清空搜索。快捷键每次按键只运行一次。设置 repeat: true,就能在按住按键期间持续运行,比如用 j 在列表里向下移动。

把快捷键限制到某个区域

命名的 scope 只在启用期间运行。这段连接在 textarea 获得焦点时打开它,并在清理时清除:

<textarea id="note" aria-label="Note"></textarea>
import { registerShortcut, shortcuts } from "@ui-sdk/web"

function connectNote(note: HTMLTextAreaElement) {
  const unregister = registerShortcut(
    "escape",
    () => {
      note.value = ""
    },
    {
      scope: "note",
      allowInInput: true,
    }
  )
  const events = new AbortController()
  note.addEventListener("focus", () => shortcuts.setScope("note", true), {
    signal: events.signal,
  })
  note.addEventListener("blur", () => shortcuts.setScope("note", false), {
    signal: events.signal,
  })
  shortcuts.setScope("note", document.activeElement === note)

  return () => {
    events.abort()
    shortcuts.setScope("note", false)
    unregister()
  }
}

const disconnect = connectNote(
  document.querySelector<HTMLTextAreaElement>("#note")!
)

移除笔记时调用 disconnect()。作用域名称是共享的,所以给每个你想一起启用的区域选一个名字。when 函数可以加一个条件,在每次按键时检查。

import { registerShortcut, shortcuts } from "@ui-sdk/web"

export function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <textarea aria-label="Note" placeholder="Write a note…"></textarea>
      <output data-slot="output">Focus the note to turn on its shortcuts.</output>
    </div>
  `
  const textarea = root.querySelector("textarea")!
  const output = root.querySelector("output")!
  textarea.addEventListener("focus", () => shortcuts.setScope("note", true))
  textarea.addEventListener("blur", () => shortcuts.setScope("note", false))

  const offs = [
    registerShortcut(
      "mod+enter",
      () =>
        (output.textContent = `Characters saved: ${textarea.value.trim().length}`),
      {
        scope: "note",
        when: () => textarea.value.trim() !== "",
        description: "Save the note",
      }
    ),
    registerShortcut(
      "escape",
      () => {
        textarea.value = ""
        output.textContent = "Cleared"
      },
      { scope: "note", allowInInput: true, description: "Clear the note" }
    ),
  ]
  return () => {
    offs.forEach((off) => off())
    shortcuts.setScope("note", false)
  }
}
聚焦这条笔记并输入一些文字。在 Mac 上按 Command+Enter,在其他平台上按 Control+Enter 保存,或按 Escape 清空。把焦点移出笔记,就会关闭它的快捷键。

在浮层里

模态打开期间,页面快捷键会暂停。传入 layer(浮层内部的元素,或返回元素的函数),让快捷键属于那个浮层。它只在浮层打开时运行,即使浮层关闭的内容仍留在 DOM 里。

当多个快捷键共用同一组按键时,打开的最上层图层优先,其次是最近注册的快捷键。

列出可用的快捷键

打开帮助界面时调用 shortcuts.list()。它返回当前可以运行的快捷键,包括它们的 keys、格式化后的 hint 和 description。注册快捷键时加上描述,这样帮助界面就能解释每个动作。