# 快捷键

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

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

```svelte title="basic.svelte"
<script lang="ts">
  import { useShortcut, useShortcutHint } from "@ui-sdk/svelte/shortcuts"

  let status = $state("Press N or the keys to save.")
  const newNote = () => (status = "Note created")
  const save = () => (status = "Saved")

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

<div data-slot="stack">
  <div data-slot="row">
    <button type="button" aria-keyshortcuts="N" onclick={newNote}>
      New note
      <kbd aria-hidden="true" data-slot="kbd">N</kbd>
    </button>
    <button
      type="button"
      aria-keyshortcuts={saveHint.ariaKeyshortcuts}
      onclick={save}
    >
      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` 显示按键：

```svelte
<script lang="ts">
  import { useShortcut, useShortcutHint } from "@ui-sdk/svelte/shortcuts"

  let count = $state(0)
  const addNote = () => count++
  useShortcut("mod+enter", addNote, { description: "New note" })
  const hint = useShortcutHint("mod+enter")
</script>

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

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

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

它的字段是响应式 getter。在标记里读取 `hint.text` 和 `hint.ariaKeyshortcuts`。

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

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

## 把快捷键限制到某个区域
用命名的 `scope` 表示编辑器或其他区域。那个区域获得焦点时把它打开：

```svelte
<script lang="ts">
  import { shortcuts, useShortcut } from "@ui-sdk/svelte/shortcuts"
  import { onDestroy } from "svelte"

  let text = $state("")
  useShortcut(
    "escape",
    () => {
      text = ""
    },
    { scope: "note", allowInInput: true }
  )
  onDestroy(() => shortcuts.setScope("note", false))
</script>

<textarea
  aria-label="Note"
  bind:value={text}
  onfocus={() => shortcuts.setScope("note", true)}
  onblur={() => shortcuts.setScope("note", false)}
/>
```

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

```svelte title="scope.svelte"
<script lang="ts">
  import { shortcuts, useShortcut } from "@ui-sdk/svelte/shortcuts"

  let text = $state("")
  let status = $state("Focus the note to turn on its shortcuts.")

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

<div data-slot="stack">
  <textarea
    bind:value={text}
    aria-label="Note"
    placeholder="Write a note…"
    onfocus={() => shortcuts.setScope("note", true)}
    onblur={() => shortcuts.setScope("note", false)}></textarea>
  <output data-slot="output">{status}</output>
</div>
```

聚焦这条笔记并输入一些文字。在 Mac 上按 Command+Enter，在其他平台上按 Control+Enter 保存，或按 Escape 清空。把焦点移出笔记，就会关闭它的快捷键。

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

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

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