Kbd
Keyboard keys for React styled as real keycaps, with a pressed state that sinks and brightens — plus an animated shortcut block whose keys sink as you press the combo, knows ⌘ from Ctrl without hydration mismatches, and ships a useShortcut hook.
- shadcn API
- Server Component friendly
- Mac / Windows aware
- No hydration mismatch
Press the shortcut — each key lights up as you hold it.
"use client";
import * as React from "react";
import { ShortcutKbd } from "@/components/dusk/kbd/shortcut-kbd";
export default function ShortcutKbdDemo() {
const [count, setCount] = React.useState(0);
return (
<div className="flex flex-col items-center gap-5 text-center">
{/* ⌘K is taken by this site's search, so the demo listens for ⌘J / Ctrl+J. */}
<ShortcutKbd keys={["mod", "j"]} size="lg" onTrigger={() => setCount((c) => c + 1)} />
<p className="text-sm text-muted-foreground" aria-live="polite">
{count === 0 ? "Press the shortcut — each key lights up as you hold it." : `Shortcut fired ${count} ${count === 1 ? "time" : "times"}.`}
</p>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/kbd.json1. Install the dependencies.
npm install class-variance-authority2. Copy the source into
components/ui/kbd.tsx.kbd.tsx import * as React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; /** * DuskUI Kbd — keyboard keys styled as real keycaps. * * Same parts and data-slot attributes as shadcn/ui's Kbd (Kbd, KbdGroup) plus: * - A quiet keycap look: a hairline border and a subtle bottom lip, tuned * for dark surfaces. * - `pressed`: the cap sinks by a pixel, loses its lip and brightens. * Drive it from keyboard events to show which keys are held. * - `size`: sm, default, lg. Icons inside are sized automatically. * - Flattens itself inside tooltips. * CSS only, so it works in Server Components. */ const kbdVariants = cva( [ "pointer-events-none inline-flex w-fit select-none items-center justify-center gap-1 rounded-[5px] border font-sans font-medium whitespace-nowrap", "border-white/10 bg-muted text-muted-foreground", "shadow-[inset_0_-1px_0_rgb(0_0_0/0.4)]", "transition-[translate,box-shadow,color,border-color,background-color] duration-100 ease-out motion-reduce:transition-none", "data-[pressed=true]:translate-y-px data-[pressed=true]:border-white/20 data-[pressed=true]:bg-accent data-[pressed=true]:text-foreground data-[pressed=true]:shadow-none", "motion-reduce:data-[pressed=true]:translate-y-0", "[&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3", "[[data-slot=tooltip-content]_&]:border-transparent [[data-slot=tooltip-content]_&]:bg-white/15 [[data-slot=tooltip-content]_&]:bg-none [[data-slot=tooltip-content]_&]:text-current [[data-slot=tooltip-content]_&]:shadow-none", ], { variants: { size: { sm: "h-[1.125rem] min-w-[1.125rem] px-1 text-[0.625rem]", default: "h-5 min-w-5 px-1.5 text-xs", lg: "h-7 min-w-7 rounded-md px-2 text-sm [&_svg:not([class*='size-'])]:size-3.5", }, }, defaultVariants: { size: "default" }, } ); export interface KbdProps extends React.ComponentProps<"kbd">, VariantProps<typeof kbdVariants> { /** Show the key held down: it sinks and lights up. */ pressed?: boolean; } function Kbd({ className, size, pressed = false, ...props }: KbdProps) { return ( <kbd data-slot="kbd" data-size={size ?? "default"} data-pressed={pressed || undefined} className={cn(kbdVariants({ size }), className)} {...props} /> ); } /** Lays out a key combination, e.g. ⌘ + K. Renders a `<kbd>`, so nested Kbds read as one shortcut. */ function KbdGroup({ className, ...props }: React.ComponentProps<"kbd">) { return ( <kbd data-slot="kbd-group" className={cn("inline-flex items-center gap-1 font-sans text-xs text-muted-foreground", className)} {...props} /> ); } export { Kbd, KbdGroup, kbdVariants };
Adds components/ui/kbd.tsx with shadcn's Kbd and KbdGroup, plus size and pressed. CSS only.
Usage
import { Kbd, KbdGroup } from "@/components/ui/kbd"
export function SearchHint() {
return (
<p className="text-sm text-muted-foreground">
Press{" "}
<KbdGroup>
<Kbd>⌘</Kbd>
<Kbd>K</Kbd>
</KbdGroup>{" "}
to search
</p>
)
}Examples
Keycaps
Three sizes, icons sized automatically, and KbdGroup for combinations. Add pressed to show a key held down. Keys sit nicely inside running text too.
Press CtrlB to toggle the sidebar, or / to jump to search.
import { ArrowBigUp, Command, CornerDownLeft } from "lucide-react";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
export default function KbdBasicDemo() {
return (
<div className="flex flex-col items-center gap-6">
<div className="flex flex-wrap items-center justify-center gap-3">
<Kbd size="sm">Esc</Kbd>
<Kbd>Tab</Kbd>
<Kbd size="lg">Space</Kbd>
<KbdGroup>
<Kbd>
<Command aria-hidden />
<span className="sr-only">Command</span>
</Kbd>
<Kbd>
<ArrowBigUp aria-hidden />
<span className="sr-only">Shift</span>
</Kbd>
<Kbd>P</Kbd>
</KbdGroup>
<Kbd pressed>
<CornerDownLeft aria-hidden />
<span className="sr-only">Enter</span>
</Kbd>
</div>
<p className="max-w-sm text-center text-sm text-muted-foreground">
Press{" "}
<KbdGroup>
<Kbd>Ctrl</Kbd>
<span aria-hidden>+</span>
<Kbd>B</Kbd>
</KbdGroup>{" "}
to toggle the sidebar, or <Kbd>/</Kbd> to jump to search.
</p>
</div>
);
}In buttons
Hint the shortcut right on the control it triggers. Kbd flattens itself inside tooltips.
import { SearchIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
export default function KbdButtonDemo() {
return (
<div className="flex flex-wrap items-center justify-center gap-3">
<Button variant="outline" className="w-60 justify-start px-3 font-normal text-muted-foreground">
<SearchIcon />
Search docs…
<KbdGroup className="ml-auto">
<Kbd size="sm">Ctrl</Kbd>
<Kbd size="sm">K</Kbd>
</KbdGroup>
</Button>
<Button size="sm">
Save changes
<Kbd size="sm" className="border-black/15 bg-black/10 text-primary-foreground/80 shadow-none">
↵<span className="sr-only">Enter</span>
</Kbd>
</Button>
</div>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Shortcut Kbd
Keycaps that listen. Each cap sinks while its key is held; when the full combination lands they dip once together and onTrigger runs. mod shows ⌘ on Apple devices and Ctrl elsewhere — the platform is read with useSyncExternalStore, so the server HTML and first client render always match. Letters match by physical key, so ⌥ and ⇧ can't change them. The file also exports useShortcut and usePlatform for your own UI.
Press the shortcut — each key lights up as you hold it.
"use client";
import * as React from "react";
import { ShortcutKbd } from "@/components/dusk/kbd/shortcut-kbd";
export default function ShortcutKbdDemo() {
const [count, setCount] = React.useState(0);
return (
<div className="flex flex-col items-center gap-5 text-center">
{/* ⌘K is taken by this site's search, so the demo listens for ⌘J / Ctrl+J. */}
<ShortcutKbd keys={["mod", "j"]} size="lg" onTrigger={() => setCount((c) => c + 1)} />
<p className="text-sm text-muted-foreground" aria-live="polite">
{count === 0 ? "Press the shortcut — each key lights up as you hold it." : `Shortcut fired ${count} ${count === 1 ? "time" : "times"}.`}
</p>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/shortcut-kbd.json1. Install the dependencies.
npm install motion class-variance-authority2. Copy the source into
components/dusk/kbd/shortcut-kbd.tsx.shortcut-kbd.tsx "use client"; import * as React from "react"; import { motion, useReducedMotion } from "motion/react"; import { Kbd, KbdGroup, type KbdProps } from "@/components/ui/kbd"; import { cn } from "@/lib/utils"; /* -------------------------------------------------------------------------- */ /* Platform */ /* -------------------------------------------------------------------------- */ export type Platform = "mac" | "other"; const subscribeNoop = () => () => {}; function readPlatform(): Platform { const nav = navigator as Navigator & { userAgentData?: { platform?: string } }; const name = nav.userAgentData?.platform || nav.platform || nav.userAgent; return /mac|iphone|ipad|ipod/i.test(name) ? "mac" : "other"; } /** * The visitor's platform, or `null` while rendering on the server and during * hydration. Using `useSyncExternalStore` with a server snapshot means the * first client render matches the server HTML exactly, then updates. */ export function usePlatform(): Platform | null { return React.useSyncExternalStore(subscribeNoop, readPlatform, () => null); } /* -------------------------------------------------------------------------- */ /* Keys */ /* -------------------------------------------------------------------------- */ const MODIFIERS = ["mod", "ctrl", "shift", "alt", "meta"] as const; type Modifier = (typeof MODIFIERS)[number]; const aliases: Record<string, string> = { cmd: "meta", command: "meta", win: "meta", super: "meta", control: "ctrl", option: "alt", opt: "alt", esc: "escape", return: "enter", up: "arrowup", down: "arrowdown", left: "arrowleft", right: "arrowright", del: "delete", " ": "space", }; /** Lower-cases a key name and resolves aliases ("cmd" → "meta", "esc" → "escape"…). */ export function normalizeKey(key: string) { const lower = key.toLowerCase(); return aliases[lower] ?? lower; } const isModifier = (key: string): key is Modifier => (MODIFIERS as readonly string[]).includes(key); const symbols: Record<string, { mac: string; other: string; name: string }> = { mod: { mac: "⌘", other: "Ctrl", name: "Command" }, meta: { mac: "⌘", other: "Win", name: "Command" }, ctrl: { mac: "⌃", other: "Ctrl", name: "Control" }, shift: { mac: "⇧", other: "Shift", name: "Shift" }, alt: { mac: "⌥", other: "Alt", name: "Option" }, enter: { mac: "↵", other: "Enter", name: "Enter" }, escape: { mac: "Esc", other: "Esc", name: "Escape" }, backspace: { mac: "⌫", other: "Backspace", name: "Backspace" }, delete: { mac: "⌦", other: "Del", name: "Delete" }, tab: { mac: "⇥", other: "Tab", name: "Tab" }, space: { mac: "Space", other: "Space", name: "Space" }, arrowup: { mac: "↑", other: "↑", name: "Up arrow" }, arrowdown: { mac: "↓", other: "↓", name: "Down arrow" }, arrowleft: { mac: "←", other: "←", name: "Left arrow" }, arrowright: { mac: "→", other: "→", name: "Right arrow" }, }; /** The visible label and the spoken name of a key on a platform. */ export function describeKey(key: string, platform: Platform) { const k = normalizeKey(key); const symbol = symbols[k]; // On Windows / Linux "mod" means Control, so speak it that way. if (symbol) return { label: symbol[platform], name: k === "mod" && platform === "other" ? "Control" : symbol.name }; const label = k.length === 1 ? k.toUpperCase() : k.charAt(0).toUpperCase() + k.slice(1); return { label, name: label }; } function modifierDown(mod: Modifier, e: KeyboardEvent, platform: Platform) { switch (mod) { case "mod": return platform === "mac" ? e.metaKey : e.ctrlKey; case "ctrl": return e.ctrlKey; case "shift": return e.shiftKey; case "alt": return e.altKey; case "meta": return e.metaKey; } } /** Matches by physical key for letters and digits, so Option / Shift can't change them. */ function eventMatchesKey(key: string, e: KeyboardEvent) { if (/^[a-z]$/.test(key)) return e.code === `Key${key.toUpperCase()}`; if (/^[0-9]$/.test(key)) return e.code === `Digit${key}` || e.code === `Numpad${key}`; if (key === "space") return e.code === "Space"; return normalizeKey(e.key) === key; } function isEditable(target: EventTarget | null) { if (!(target instanceof HTMLElement)) return false; return target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName); } /* -------------------------------------------------------------------------- */ /* Hook */ /* -------------------------------------------------------------------------- */ export interface UseShortcutOptions { /** Listen for the shortcut. Default true. */ enabled?: boolean; /** Call `preventDefault()` when the shortcut fires (e.g. to stop the browser's ⌘K). Default true. */ preventDefault?: boolean; /** * Fire while focus is in a text field. Defaults to true for combos with * mod / ctrl / meta / alt and false for plain keys like "/". */ enableInInputs?: boolean; } /** * Listens for a key combination such as `["mod", "k"]` and reports which of * its keys are held right now, so you can light them up. `mod` is ⌘ on Apple * platforms and Ctrl elsewhere. Returns `pressed` (one boolean per key) and * `count`, which goes up every time the full combo fires. */ export function useShortcut( keys: string[], onTrigger?: (event: KeyboardEvent) => void, { enabled = true, preventDefault = true, enableInInputs }: UseShortcutOptions = {} ) { const platform = usePlatform(); const [pressed, setPressed] = React.useState<boolean[]>(() => keys.map(() => false)); const [count, setCount] = React.useState(0); const handlerRef = React.useRef(onTrigger); React.useEffect(() => { handlerRef.current = onTrigger; }, [onTrigger]); // A stable string, so a new `keys` array with the same keys doesn't re-subscribe. const signature = keys.map(normalizeKey).join("\n"); React.useEffect(() => { if (!enabled || !platform) return; const combo = signature.split("\n"); const mods = combo.filter(isModifier); const main = combo.filter((k) => !isModifier(k)); const hasChord = mods.some((m) => m !== "shift"); const allowInInputs = enableInInputs ?? hasChord; // Main keys currently held. const held = new Set<string>(); const sync = (e: KeyboardEvent) => { const next = combo.map((k) => (isModifier(k) ? modifierDown(k, e, platform) : held.has(k))); setPressed((prev) => (prev.length === next.length && prev.every((v, i) => v === next[i]) ? prev : next)); }; const onKeyDown = (e: KeyboardEvent) => { // Typing in a field shouldn't light up (or fire) plain-key shortcuts. if (!allowInInputs && isEditable(e.target)) return; for (const k of main) if (eventMatchesKey(k, e)) held.add(k); sync(e); if (e.repeat) return; const allMods = MODIFIERS.every((m) => { // "mod" and its platform twin are the same physical key. if (m === "mod") return true; // Symbols like "?" need Shift on most layouts, so don't insist it stays up. if (m === "shift" && !mods.includes("shift") && main.some((k) => !/^[a-z0-9]$/.test(k))) return true; const wanted = mods.includes(m) || (mods.includes("mod") && (platform === "mac" ? m === "meta" : m === "ctrl")); return modifierDown(m, e, platform) === wanted; }); const modsDown = mods.every((m) => modifierDown(m, e, platform)); const mainDown = main.length > 0 ? main.every((k) => held.has(k)) && main.some((k) => eventMatchesKey(k, e)) : false; if (allMods && modsDown && mainDown) { if (preventDefault) e.preventDefault(); setCount((c) => c + 1); handlerRef.current?.(e); } }; const onKeyUp = (e: KeyboardEvent) => { for (const k of main) if (eventMatchesKey(k, e)) held.delete(k); // Releasing a modifier releases everything: macOS never sends keyup for keys // pressed with ⌘, and "?" turns back into "/" once Shift is up. if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) held.clear(); sync(e); }; const reset = () => { held.clear(); setPressed((prev) => (prev.some(Boolean) ? prev.map(() => false) : prev)); }; window.addEventListener("keydown", onKeyDown); window.addEventListener("keyup", onKeyUp); window.addEventListener("blur", reset); return () => { window.removeEventListener("keydown", onKeyDown); window.removeEventListener("keyup", onKeyUp); window.removeEventListener("blur", reset); reset(); }; }, [signature, enabled, platform, preventDefault, enableInInputs]); return { pressed, count, platform }; } /* -------------------------------------------------------------------------- */ /* Component */ /* -------------------------------------------------------------------------- */ export interface ShortcutKbdProps extends Omit<React.ComponentProps<"kbd">, "children">, UseShortcutOptions, Pick<KbdProps, "size"> { /** The combination, e.g. `["mod", "k"]`, `["shift", "?"]` or `["g", "d"]` held together. */ keys: string[]; /** Called when the full combination is pressed. */ onTrigger?: (event: KeyboardEvent) => void; /** Classes for each keycap. */ keyClassName?: string; } /** * Keycaps for a shortcut that respond as you press it. Each cap sinks and * brightens slightly while its key is held, and when the whole combination * lands the caps dip once together and `onTrigger` runs. `mod` renders ⌘ on Apple * platforms and Ctrl elsewhere; until the platform is known (server render * and hydration) that cap is reserved but blank, so there is no mismatch. * Under reduced motion the dip is a surface change only. */ export function ShortcutKbd({ keys, onTrigger, enabled, preventDefault, enableInInputs, size, className, keyClassName, ...props }: ShortcutKbdProps) { const reduceMotion = useReducedMotion() ?? false; const { pressed, count, platform } = useShortcut(keys, onTrigger, { enabled, preventDefault, enableInInputs }); const [flashing, setFlashing] = React.useState(false); const [seenCount, setSeenCount] = React.useState(count); // Start a flash whenever the combo fires (adjusting state during render, no effect needed). if (count !== seenCount) { setSeenCount(count); setFlashing(true); } React.useEffect(() => { if (!flashing) return; const timer = window.setTimeout(() => setFlashing(false), 450); return () => window.clearTimeout(timer); }, [flashing, count]); const described = keys.map((key) => describeKey(key, platform ?? "mac")); const spoken = described.map((d) => d.name).join(" + "); return ( <KbdGroup data-slot="shortcut-kbd" title={platform ? spoken : undefined} className={className} {...props}> {keys.map((key, index) => { const { label, name } = described[index]; const isPlatformKey = ["mod", "meta", "ctrl", "alt"].includes(normalizeKey(key)); return ( <motion.span key={`${key}-${index}`} className="inline-flex" animate={ flashing && !reduceMotion ? { y: [0, 1, 0] } : { y: 0 } } transition={{ duration: 0.25, delay: index * 0.03, ease: "easeOut" }} > <Kbd size={size} pressed={pressed[index] || flashing} className={keyClassName} > <span aria-hidden className={cn(isPlatformKey && !platform && "invisible")}> {label} </span> <span className="sr-only">{name}</span> </Kbd> </motion.span> ); })} </KbdGroup> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| keys | string[] | — | The combination, e.g. ["mod", "k"]. Modifiers: mod, ctrl, shift, alt (option), meta (cmd). Required. |
| onTrigger | (event: KeyboardEvent) => void | — | Called when the full combination is pressed. |
| enabled | boolean | true | Listen for the shortcut. |
| preventDefault | boolean | true | Stop the browser's own action for the combo. |
| enableInInputs | boolean | — | Fire while typing in a field. Defaults to true for combos with mod / ctrl / meta / alt, false for plain keys. |
| size | "sm" | "default" | "lg" | "default" | Keycap size. |
| keyClassName | string | — | Classes for each keycap. |
Shortcut cheat sheet
Several ShortcutKbds make a live cheat sheet: every row lights up as you try it. Plain keys like J and / pause while you type in a field, so they never steal input.
- Next itemJ
- Previous itemK
- Focus filter/
- New noteOptionN
- Show shortcuts?
Try the keys (they pause while you type in a field).
"use client";
import * as React from "react";
import { ShortcutKbd } from "@/components/dusk/kbd/shortcut-kbd";
import { cn } from "@/lib/utils";
const shortcuts = [
{ label: "Next item", keys: ["j"] },
{ label: "Previous item", keys: ["k"] },
{ label: "Focus filter", keys: ["/"] },
{ label: "New note", keys: ["alt", "n"] },
{ label: "Show shortcuts", keys: ["?"] },
];
export default function ShortcutListDemo() {
const [last, setLast] = React.useState<string | null>(null);
return (
<div className="w-full max-w-sm">
<ul className="divide-y divide-white/5 rounded-xl border bg-card/40">
{shortcuts.map((shortcut) => (
<li
key={shortcut.label}
className={cn(
"flex items-center justify-between px-4 py-2.5 text-sm transition-colors duration-200",
last === shortcut.label && "bg-white/[0.03] text-foreground"
)}
>
{shortcut.label}
<ShortcutKbd keys={shortcut.keys} onTrigger={() => setLast(shortcut.label)} />
</li>
))}
</ul>
<p className="mt-3 text-center text-xs text-muted-foreground" aria-live="polite">
{last ? `Last shortcut: ${last}` : "Try the keys (they pause while you type in a field)."}
</p>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/shortcut-kbd.json1. Install the dependencies.
npm install motion class-variance-authority2. Copy the source into
components/dusk/kbd/shortcut-kbd.tsx.shortcut-kbd.tsx "use client"; import * as React from "react"; import { motion, useReducedMotion } from "motion/react"; import { Kbd, KbdGroup, type KbdProps } from "@/components/ui/kbd"; import { cn } from "@/lib/utils"; /* -------------------------------------------------------------------------- */ /* Platform */ /* -------------------------------------------------------------------------- */ export type Platform = "mac" | "other"; const subscribeNoop = () => () => {}; function readPlatform(): Platform { const nav = navigator as Navigator & { userAgentData?: { platform?: string } }; const name = nav.userAgentData?.platform || nav.platform || nav.userAgent; return /mac|iphone|ipad|ipod/i.test(name) ? "mac" : "other"; } /** * The visitor's platform, or `null` while rendering on the server and during * hydration. Using `useSyncExternalStore` with a server snapshot means the * first client render matches the server HTML exactly, then updates. */ export function usePlatform(): Platform | null { return React.useSyncExternalStore(subscribeNoop, readPlatform, () => null); } /* -------------------------------------------------------------------------- */ /* Keys */ /* -------------------------------------------------------------------------- */ const MODIFIERS = ["mod", "ctrl", "shift", "alt", "meta"] as const; type Modifier = (typeof MODIFIERS)[number]; const aliases: Record<string, string> = { cmd: "meta", command: "meta", win: "meta", super: "meta", control: "ctrl", option: "alt", opt: "alt", esc: "escape", return: "enter", up: "arrowup", down: "arrowdown", left: "arrowleft", right: "arrowright", del: "delete", " ": "space", }; /** Lower-cases a key name and resolves aliases ("cmd" → "meta", "esc" → "escape"…). */ export function normalizeKey(key: string) { const lower = key.toLowerCase(); return aliases[lower] ?? lower; } const isModifier = (key: string): key is Modifier => (MODIFIERS as readonly string[]).includes(key); const symbols: Record<string, { mac: string; other: string; name: string }> = { mod: { mac: "⌘", other: "Ctrl", name: "Command" }, meta: { mac: "⌘", other: "Win", name: "Command" }, ctrl: { mac: "⌃", other: "Ctrl", name: "Control" }, shift: { mac: "⇧", other: "Shift", name: "Shift" }, alt: { mac: "⌥", other: "Alt", name: "Option" }, enter: { mac: "↵", other: "Enter", name: "Enter" }, escape: { mac: "Esc", other: "Esc", name: "Escape" }, backspace: { mac: "⌫", other: "Backspace", name: "Backspace" }, delete: { mac: "⌦", other: "Del", name: "Delete" }, tab: { mac: "⇥", other: "Tab", name: "Tab" }, space: { mac: "Space", other: "Space", name: "Space" }, arrowup: { mac: "↑", other: "↑", name: "Up arrow" }, arrowdown: { mac: "↓", other: "↓", name: "Down arrow" }, arrowleft: { mac: "←", other: "←", name: "Left arrow" }, arrowright: { mac: "→", other: "→", name: "Right arrow" }, }; /** The visible label and the spoken name of a key on a platform. */ export function describeKey(key: string, platform: Platform) { const k = normalizeKey(key); const symbol = symbols[k]; // On Windows / Linux "mod" means Control, so speak it that way. if (symbol) return { label: symbol[platform], name: k === "mod" && platform === "other" ? "Control" : symbol.name }; const label = k.length === 1 ? k.toUpperCase() : k.charAt(0).toUpperCase() + k.slice(1); return { label, name: label }; } function modifierDown(mod: Modifier, e: KeyboardEvent, platform: Platform) { switch (mod) { case "mod": return platform === "mac" ? e.metaKey : e.ctrlKey; case "ctrl": return e.ctrlKey; case "shift": return e.shiftKey; case "alt": return e.altKey; case "meta": return e.metaKey; } } /** Matches by physical key for letters and digits, so Option / Shift can't change them. */ function eventMatchesKey(key: string, e: KeyboardEvent) { if (/^[a-z]$/.test(key)) return e.code === `Key${key.toUpperCase()}`; if (/^[0-9]$/.test(key)) return e.code === `Digit${key}` || e.code === `Numpad${key}`; if (key === "space") return e.code === "Space"; return normalizeKey(e.key) === key; } function isEditable(target: EventTarget | null) { if (!(target instanceof HTMLElement)) return false; return target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName); } /* -------------------------------------------------------------------------- */ /* Hook */ /* -------------------------------------------------------------------------- */ export interface UseShortcutOptions { /** Listen for the shortcut. Default true. */ enabled?: boolean; /** Call `preventDefault()` when the shortcut fires (e.g. to stop the browser's ⌘K). Default true. */ preventDefault?: boolean; /** * Fire while focus is in a text field. Defaults to true for combos with * mod / ctrl / meta / alt and false for plain keys like "/". */ enableInInputs?: boolean; } /** * Listens for a key combination such as `["mod", "k"]` and reports which of * its keys are held right now, so you can light them up. `mod` is ⌘ on Apple * platforms and Ctrl elsewhere. Returns `pressed` (one boolean per key) and * `count`, which goes up every time the full combo fires. */ export function useShortcut( keys: string[], onTrigger?: (event: KeyboardEvent) => void, { enabled = true, preventDefault = true, enableInInputs }: UseShortcutOptions = {} ) { const platform = usePlatform(); const [pressed, setPressed] = React.useState<boolean[]>(() => keys.map(() => false)); const [count, setCount] = React.useState(0); const handlerRef = React.useRef(onTrigger); React.useEffect(() => { handlerRef.current = onTrigger; }, [onTrigger]); // A stable string, so a new `keys` array with the same keys doesn't re-subscribe. const signature = keys.map(normalizeKey).join("\n"); React.useEffect(() => { if (!enabled || !platform) return; const combo = signature.split("\n"); const mods = combo.filter(isModifier); const main = combo.filter((k) => !isModifier(k)); const hasChord = mods.some((m) => m !== "shift"); const allowInInputs = enableInInputs ?? hasChord; // Main keys currently held. const held = new Set<string>(); const sync = (e: KeyboardEvent) => { const next = combo.map((k) => (isModifier(k) ? modifierDown(k, e, platform) : held.has(k))); setPressed((prev) => (prev.length === next.length && prev.every((v, i) => v === next[i]) ? prev : next)); }; const onKeyDown = (e: KeyboardEvent) => { // Typing in a field shouldn't light up (or fire) plain-key shortcuts. if (!allowInInputs && isEditable(e.target)) return; for (const k of main) if (eventMatchesKey(k, e)) held.add(k); sync(e); if (e.repeat) return; const allMods = MODIFIERS.every((m) => { // "mod" and its platform twin are the same physical key. if (m === "mod") return true; // Symbols like "?" need Shift on most layouts, so don't insist it stays up. if (m === "shift" && !mods.includes("shift") && main.some((k) => !/^[a-z0-9]$/.test(k))) return true; const wanted = mods.includes(m) || (mods.includes("mod") && (platform === "mac" ? m === "meta" : m === "ctrl")); return modifierDown(m, e, platform) === wanted; }); const modsDown = mods.every((m) => modifierDown(m, e, platform)); const mainDown = main.length > 0 ? main.every((k) => held.has(k)) && main.some((k) => eventMatchesKey(k, e)) : false; if (allMods && modsDown && mainDown) { if (preventDefault) e.preventDefault(); setCount((c) => c + 1); handlerRef.current?.(e); } }; const onKeyUp = (e: KeyboardEvent) => { for (const k of main) if (eventMatchesKey(k, e)) held.delete(k); // Releasing a modifier releases everything: macOS never sends keyup for keys // pressed with ⌘, and "?" turns back into "/" once Shift is up. if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) held.clear(); sync(e); }; const reset = () => { held.clear(); setPressed((prev) => (prev.some(Boolean) ? prev.map(() => false) : prev)); }; window.addEventListener("keydown", onKeyDown); window.addEventListener("keyup", onKeyUp); window.addEventListener("blur", reset); return () => { window.removeEventListener("keydown", onKeyDown); window.removeEventListener("keyup", onKeyUp); window.removeEventListener("blur", reset); reset(); }; }, [signature, enabled, platform, preventDefault, enableInInputs]); return { pressed, count, platform }; } /* -------------------------------------------------------------------------- */ /* Component */ /* -------------------------------------------------------------------------- */ export interface ShortcutKbdProps extends Omit<React.ComponentProps<"kbd">, "children">, UseShortcutOptions, Pick<KbdProps, "size"> { /** The combination, e.g. `["mod", "k"]`, `["shift", "?"]` or `["g", "d"]` held together. */ keys: string[]; /** Called when the full combination is pressed. */ onTrigger?: (event: KeyboardEvent) => void; /** Classes for each keycap. */ keyClassName?: string; } /** * Keycaps for a shortcut that respond as you press it. Each cap sinks and * brightens slightly while its key is held, and when the whole combination * lands the caps dip once together and `onTrigger` runs. `mod` renders ⌘ on Apple * platforms and Ctrl elsewhere; until the platform is known (server render * and hydration) that cap is reserved but blank, so there is no mismatch. * Under reduced motion the dip is a surface change only. */ export function ShortcutKbd({ keys, onTrigger, enabled, preventDefault, enableInInputs, size, className, keyClassName, ...props }: ShortcutKbdProps) { const reduceMotion = useReducedMotion() ?? false; const { pressed, count, platform } = useShortcut(keys, onTrigger, { enabled, preventDefault, enableInInputs }); const [flashing, setFlashing] = React.useState(false); const [seenCount, setSeenCount] = React.useState(count); // Start a flash whenever the combo fires (adjusting state during render, no effect needed). if (count !== seenCount) { setSeenCount(count); setFlashing(true); } React.useEffect(() => { if (!flashing) return; const timer = window.setTimeout(() => setFlashing(false), 450); return () => window.clearTimeout(timer); }, [flashing, count]); const described = keys.map((key) => describeKey(key, platform ?? "mac")); const spoken = described.map((d) => d.name).join(" + "); return ( <KbdGroup data-slot="shortcut-kbd" title={platform ? spoken : undefined} className={className} {...props}> {keys.map((key, index) => { const { label, name } = described[index]; const isPlatformKey = ["mod", "meta", "ctrl", "alt"].includes(normalizeKey(key)); return ( <motion.span key={`${key}-${index}`} className="inline-flex" animate={ flashing && !reduceMotion ? { y: [0, 1, 0] } : { y: 0 } } transition={{ duration: 0.25, delay: index * 0.03, ease: "easeOut" }} > <Kbd size={size} pressed={pressed[index] || flashing} className={keyClassName} > <span aria-hidden className={cn(isPlatformKey && !platform && "invisible")}> {label} </span> <span className="sr-only">{name}</span> </Kbd> </motion.span> ); })} </KbdGroup> ); }
API Reference
Kbd renders a <kbd>; KbdGroup renders a wrapping <kbd> so nested keys read as one shortcut.
| Prop | Type | Default | Description |
|---|---|---|---|
| size | "sm" | "default" | "lg" | "default" | Kbd. Keycap size. |
| pressed | boolean | false | Kbd. Shows the key held down: it sinks a pixel and brightens. |
Accessibility
- Keys use the semantic
<kbd>element, and a group of keys is nested in another<kbd>, the HTML pattern for a key combination. - Give symbol keys a spoken name: pair
⌘or an icon with<span className="sr-only">Command</span>. Shortcut Kbd does this for you (Command, Control, Shift, Option…). - Shortcut Kbd only listens; announce the result of a shortcut yourself, e.g. with a polite live region as in the demos.
- Avoid single-key shortcuts for destructive actions; they are paused inside text fields by default, but can still be pressed by accident.
- Under prefers-reduced-motion the trigger dip is a surface change only, without movement.