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

useShortcut 在组件挂载期间注册一个快捷键。对于已经接受 shortcut 的组件,比如对话框触发器,直接使用那个 prop。

import { useShortcut, useShortcutHint } from "@ui-sdk/solid/shortcuts"
import { createSignal } from "solid-js"

export function Example() {
  const [status, setStatus] = createSignal("Press N or the keys to save.")
  const newNote = () => {
    setStatus("Note created")
  }
  const save = () => {
    setStatus("Saved")
  }

  useShortcut("n", newNote, { description: "New note" })
  useShortcut("mod+s", save, { description: "Save" })
  const saveHint = useShortcutHint("mod+s")

  return (
    <div data-slot="stack">
      <div data-slot="row">
        <button type="button" onClick={newNote} aria-keyshortcuts="N">
          New note
          <kbd aria-hidden="true" data-slot="kbd">
            N
          </kbd>
        </button>
        <button
          type="button"
          onClick={save}
          aria-keyshortcuts={saveHint.ariaKeyshortcuts()}
        >
          Save
          <kbd aria-hidden="true" data-slot="kbd">
            {saveHint.text()}
          </kbd>
        </button>
      </div>
      <output data-slot="output">{status()}</output>
    </div>
  )
}
按 N 创建一条笔记。在 Mac 上按 Command+S,在其他平台上按 Control+S 保存。按钮执行同样的动作。

注册快捷键

按键之间用 + 连接。mod 在 Apple 平台上表示 Command,在其他平台上表示 Control。这个示例还用 useShortcutHint 显示按键:

import { useShortcut, useShortcutHint } from "@ui-sdk/solid/shortcuts"
import { createSignal } from "solid-js"

function Example() {
  const [count, setCount] = createSignal(0)
  const addNote = () => setCount((count) => count + 1)
  useShortcut("mod+enter", addNote, { description: "New note" })
  const hint = useShortcutHint("mod+enter")

  return (
    <button onClick={addNote} aria-keyshortcuts={hint.ariaKeyshortcuts()}>
      New note ({count()}) <kbd aria-hidden="true">{hint.text()}</kbd>
    </button>
  )
}

export { Example }

在组件里调用这个辅助函数。组件消失时它会取消注册。按键和选项可以是 getter;返回 null 作为按键,就能让快捷键保持未注册。

显示按键

useShortcutHint 提供显示文本和 aria-keyshortcuts。它让服务器和客户端的首次渲染保持一致,然后在挂载后按用户的平台更新。

它的字段是访问器(getter)。在 JSX 里调用 hint.text() 和 hint.ariaKeyshortcuts()。

在渲染之外,用 formatShortcut 获取显示文本,或用 ariaKeyshortcuts 获取 ARIA 值,它们来自同一个入口。在从右到左的页面上,提示文本和 formatShortcut 都会保持从左到右的顺序,因为有两个不可见字符包裹着文本。比较原始的按键,而不是格式化后的提示。

当有人正在输入时

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

把快捷键限制到某个区域

用命名的 scope 表示编辑器或其他区域。那个区域获得焦点时把它打开:

import { shortcuts, useShortcut } from "@ui-sdk/solid/shortcuts"
import { createSignal, onCleanup } from "solid-js"

function Example() {
  const [text, setText] = createSignal("")
  useShortcut("escape", () => setText(""), {
    scope: "note",
    allowInInput: true,
  })
  onCleanup(() => shortcuts.setScope("note", false))

  return (
    <textarea
      aria-label="Note"
      value={text()}
      onInput={(event) => setText(event.currentTarget.value)}
      onFocus={() => shortcuts.setScope("note", true)}
      onBlur={() => shortcuts.setScope("note", false)}
    />
  )
}

export { Example }

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

import { shortcuts, useShortcut } from "@ui-sdk/solid/shortcuts"
import { createSignal } from "solid-js"

export function Example() {
  const [text, setText] = createSignal("")
  const [status, setStatus] = createSignal(
    "Focus the note to turn on its shortcuts."
  )

  useShortcut(
    "mod+enter",
    () => {
      setStatus(`Characters saved: ${text().trim().length}`)
    },
    {
      scope: "note",
      when: () => text().trim() !== "",
      description: "Save the note",
    }
  )
  useShortcut(
    "escape",
    () => {
      setText("")
      setStatus("Cleared")
    },
    { scope: "note", allowInInput: true, description: "Clear the note" }
  )

  return (
    <div data-slot="stack">
      <textarea
        aria-label="Note"
        placeholder="Write a note…"
        value={text()}
        onInput={(event) => setText(event.currentTarget.value)}
        onFocus={() => shortcuts.setScope("note", true)}
        onBlur={() => shortcuts.setScope("note", false)}
      />
      <output data-slot="output">{status()}</output>
    </div>
  )
}
聚焦这条笔记并输入一些文字。在 Mac 上按 Command+Enter,在其他平台上按 Control+Enter 保存,或按 Escape 清空。把焦点移出笔记,就会关闭它的快捷键。

在浮层里

模态打开期间,页面快捷键会暂停。传入 layer(浮层内部的元素,或返回元素的 getter),让快捷键属于那个浮层。它只在那个浮层打开时运行。

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

列出可用的快捷键

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