Hotkey
Parses hotkey strings, prints platform-aware key labels and spoken names, and matches keyboard events.
Write a shortcut once as text (mod+s, shift+a, alt+left) and use it twice: matchesHotkey(event, hotkey) tells a key handler whether that shortcut was pressed, and formatHotkey, keyLabel and spokenKey print it for the platform. mod is Command on Apple platforms and Control elsewhere; useIsApple() says which, and is true on the server. The library binds nothing: you choose where to listen. Listen on the part of the page a shortcut belongs to, and keep clear of the keys the browser and assistive technology use.
Key labels for this platform
- Save
- ⌘SCommand S
- Send
- ⌘↵Command Enter
- Assign to me
- ⇧AShift A
- Go back
- ⌥←Option Left arrow
- Close the panel
- escEscape
"use client"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { keyLabel, parseHotkey, spokenKey, useIsApple } from "@/lib/hotkey"
const shortcuts = [
{ action: "Save", hotkey: "mod+s" },
{ action: "Send", hotkey: "mod+enter" },
{ action: "Assign to me", hotkey: "shift+a" },
{ action: "Go back", hotkey: "alt+left" },
{ action: "Close the panel", hotkey: "escape" },
]
export default function HotkeyKeyLabelsForThisPlatform() {
// True on Apple platforms, and on the server until the browser says otherwise.
const apple = useIsApple()
return (
<dl className="grid w-full max-w-64 grid-cols-[1fr_auto] items-center gap-x-6 gap-y-2">
{shortcuts.map(({ action, hotkey }) => {
const keys = parseHotkey(hotkey)[0] ?? []
return (
<div key={hotkey} className="contents">
<dt>{action}</dt>
<dd>
{/* The keycaps are for the eye; the words are what a screen reader says. */}
<KbdGroup aria-hidden="true">
{keys.map((key) => (
<Kbd key={key}>{keyLabel(key, apple)}</Kbd>
))}
</KbdGroup>
<span className="sr-only">{keys.map((key) => spokenKey(key, apple)).join(" ")}</span>
</dd>
</div>
)
})}
</dl>
)
}
Submit with a shortcut
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Kbd } from "@/components/ui/kbd"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { formatHotkey, matchesHotkey, useIsApple } from "@/lib/hotkey"
const SUBMIT = "mod+enter"
export default function HotkeySubmitWithAShortcut() {
const apple = useIsApple()
const [draft, setDraft] = useState("")
const [comments, setComments] = useState<string[]>([])
function post() {
const text = draft.trim()
if (!text) return
setComments([...comments, text])
setDraft("")
}
return (
<form
className="flex w-full max-w-sm flex-col gap-3"
onSubmit={(event) => {
event.preventDefault()
post()
}}
>
<ul aria-label="Comments" aria-live="polite" className="flex flex-col gap-2 empty:hidden">
{comments.map((comment, index) => (
<li key={index} className="rounded-md bg-secondary px-3 py-2 whitespace-pre-wrap">
{comment}
</li>
))}
</ul>
<div className="flex flex-col gap-1.5">
<Label htmlFor="hotkey-comment">Comment</Label>
<Textarea
id="hotkey-comment"
value={draft}
placeholder="Enter adds a line"
aria-keyshortcuts={apple ? "Meta+Enter" : "Control+Enter"}
onChange={(event) => setDraft(event.target.value)}
// The key is heard on the field only, so it does nothing elsewhere on the page.
onKeyDown={(event) => {
if (!matchesHotkey(event.nativeEvent, SUBMIT)) return
event.preventDefault()
post()
}}
/>
</div>
<Button type="submit" className="self-end">
Post
<Kbd aria-hidden="true">{formatHotkey(SUBMIT, apple)}</Kbd>
</Button>
</form>
)
}
Shortcuts for a focused row
Focus a button in the row, then press a shortcut.
"use client"
import { useState } from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Kbd } from "@/components/ui/kbd"
import { formatHotkey, matchesHotkey, useIsApple } from "@/lib/hotkey"
const ASSIGN = "shift+a"
const ARCHIVE = "e"
export default function HotkeyShortcutsForAFocusedRow() {
const apple = useIsApple()
const [mine, setMine] = useState(false)
const [archived, setArchived] = useState(false)
const [pressed, setPressed] = useState("")
return (
<div className="flex w-full max-w-sm flex-col gap-3">
{/* The keys work while focus is anywhere in the row; each one has a button that does the same. */}
<div
role="group"
aria-label="Task T-318, Write the migration guide"
className="flex flex-col gap-3 rounded-xl border border-border p-3"
onKeyDown={(event) => {
const hotkey = [ASSIGN, ARCHIVE].find((candidate) => matchesHotkey(event.nativeEvent, candidate))
if (!hotkey) return
event.preventDefault()
setPressed(formatHotkey(hotkey, apple))
if (hotkey === ASSIGN) setMine(!mine)
else setArchived(!archived)
}}
>
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">Write the migration guide</span>
{mine ? <Badge variant="secondary">Assigned to you</Badge> : null}
{archived ? <Badge variant="outline">Archived</Badge> : null}
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" aria-keyshortcuts="Shift+A" onClick={() => setMine(!mine)}>
{mine ? "Unassign" : "Assign to me"}
<Kbd aria-hidden="true">{formatHotkey(ASSIGN, apple)}</Kbd>
</Button>
<Button variant="outline" aria-keyshortcuts="E" onClick={() => setArchived(!archived)}>
{archived ? "Restore" : "Archive"}
<Kbd aria-hidden="true">{formatHotkey(ARCHIVE, apple)}</Kbd>
</Button>
</div>
</div>
<p role="status" className="min-h-5 text-sm text-muted-foreground">
{pressed ? `Last shortcut pressed: ${pressed}` : "Focus a button in the row, then press a shortcut."}
</p>
</div>
)
}
Installation
npx shadcn@latest add @khaeli/hotkeybunx --bun shadcn@latest add @khaeli/hotkeyInstalls with
Nothing else. This item needs no other Registry item and no npm package.
Keyboard
⌘ EnterCtrl Enter- In Submit with a shortcut, posts the comment while the field has focus. Enter alone adds a line.
Shift A- In Shortcuts for a focused row, assigns the task to you, or unassigns it, while focus is in the row.
E- In Shortcuts for a focused row, archives or restores the task while focus is in the row.
Accessible name
- A shortcut is never the only way: every one here has a button that does the same thing.
- Keycaps are symbols. Hide them with
aria-hiddenand give the words fromspokenKeyto assistive technology, or name the keys inaria-keyshortcutson the control they belong to.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/hotkey.json