注册键盘快捷键,并显示符合用户平台的按键。
useShortcut 在组件挂载期间注册一个键盘快捷键。用它处理不属于某个具体控件的动作。对于已经接受 shortcut 的组件,比如对话框触发器,直接使用那个 prop。
import { useShortcut, useShortcutHint } from "@ui-sdk/react/shortcuts"
import * as React from "react"
export function Example() {
const [status, setStatus] = React.useState("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>
)
}注册快捷键
按键之间用 + 连接。mod 在 Apple 平台上表示 Command,在其他平台上表示 Control:
"use client"
import { useShortcut } from "@ui-sdk/react/shortcuts"
import { useState } from "react"
function NewNote() {
const [count, setCount] = useState(0)
const addNote = () => setCount((count) => count + 1)
useShortcut("mod+enter", addNote, { description: "New note" })
return <button onClick={addNote}>New note ({count})</button>
}
export { NewNote }这个 Hook 使用你最新的处理函数,并在卸载时取消注册。你不需要 useCallback。传入 null 而不是按键,就能让快捷键保持未注册。
显示按键
useShortcutHint 按当前平台格式化按键,并为控件提供 aria-keyshortcuts:
"use client"
import { useShortcut, useShortcutHint } from "@ui-sdk/react/shortcuts"
function SaveButton({ onSave }: { onSave: () => void }) {
useShortcut("mod+s", onSave, { description: "Save" })
const hint = useShortcutHint("mod+s")
return (
<button onClick={onSave} aria-keyshortcuts={hint.ariaKeyshortcuts}>
Save <kbd aria-hidden="true">{hint.text}</kbd>
</button>
)
}
export { SaveButton }它在 Apple 平台上显示 ⌘S,在其他平台上显示 Ctrl+S。这个 Hook 让服务器和客户端的首次渲染保持一致,然后在挂载后更新。
在渲染之外,用 formatShortcut 获取显示文本,或用 ariaKeyshortcuts 获取 ARIA 值。两者都从同一个入口导出。在从右到左的页面上,提示文本和 formatShortcut 都会保持从左到右的顺序,因为有两个不可见字符包裹着文本。比较原始的按键,而不是格式化后的提示。
当有人正在输入时
带 Command、Control 或 Option 的快捷键可以在文本字段里运行。普通字母和其他按键仍然可以用于输入。
当快捷键也需要在那里生效时,设置 allowInInput: true,比如用 Escape 清空搜索。when 在每次按键时检查一个条件;它可以让 Save 快捷键在有文本之前保持不生效。快捷键每次按键只运行一次。设置 repeat: true,就能在按住按键期间持续运行,比如用 j 在列表里向下移动。
import { shortcuts, useShortcut } from "@ui-sdk/react/shortcuts"
import * as React from "react"
export function Example() {
const [text, setText] = React.useState("")
const [status, setStatus] = React.useState(
"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}
onChange={(event) => setText(event.target.value)}
onFocus={() => shortcuts.setScope("note", true)}
onBlur={() => shortcuts.setScope("note", false)}
/>
<output data-slot="output">{status}</output>
</div>
)
}把快捷键限制到某个区域
用命名的 scope 表示编辑器或应用的其他区域。那个区域获得焦点时把它打开:
"use client"
import { shortcuts, useShortcut } from "@ui-sdk/react/shortcuts"
import { useEffect, useState } from "react"
function Note() {
const [text, setText] = useState("")
useEffect(() => () => shortcuts.setScope("note", false), [])
useShortcut("escape", () => setText(""), {
scope: "note",
allowInInput: true,
})
return (
<textarea
aria-label="Note"
value={text}
onChange={(event) => setText(event.target.value)}
onFocus={() => shortcuts.setScope("note", true)}
onBlur={() => shortcuts.setScope("note", false)}
/>
)
}
export { Note }when: () => text.length > 0 选项可以进一步限制它何时运行。作用域名称是共享的,所以给每个你想一起启用的区域选一个名字。
在浮层里
模态打开期间,页面快捷键会暂停。传入 layer,让快捷键改为属于某个浮层:
"use client"
import { DialogContent } from "@ui-sdk/react/dialog"
import { useShortcut } from "@ui-sdk/react/shortcuts"
import { useRef } from "react"
function EditorContent({ onSave }: { onSave: () => void }) {
const content = useRef<HTMLDivElement>(null)
useShortcut("mod+enter", onSave, { layer: content, description: "Save" })
return <DialogContent ref={content}>Edit your note here.</DialogContent>
}
export { EditorContent }把这个部件渲染在 Dialog 里。它的快捷键只在该对话框打开时运行。layer 也接受元素或返回元素的函数。
当多个快捷键共用同一组按键时,打开的最上层图层优先,其次是最近注册的快捷键。开发构建会对同一位置重复的按键发出警告。
列出可用的快捷键
打开帮助界面时调用 shortcuts.list()。它返回当前可以运行的快捷键,包括它们的 keys、格式化后的 hint 和 description:
import { shortcuts } from "@ui-sdk/react/shortcuts"
const labels = shortcuts
.list()
.map(({ hint, description }) => `${hint} ${description ?? ""}`)注册快捷键时加上描述,这样帮助界面就能解释每个动作。