Keyboard key
80 lines · 1 file · MIT
Keys and shortcuts, drawn as keys.
Search New project CClose Esc
import { useSyncExternalStore, type ReactNode } from "react";
import { cn } from "./cn";
/**
* A key, as shadcn/ui draws one (ui.shadcn.com/docs/components/kbd): its own
* small filled box, in the sans, so a shortcut reads as keys on a keyboard
* rather than a code fragment. Each key of a chord gets a box (`Shortcut`).
*
* `tone` follows what it sits on: the page and menus, a tooltip (already on
* surface-2), or a primary button (on the accent).
*/
export function Kbd({
children,
tone = "default",
className,
}: {
children: ReactNode;
tone?: "default" | "tooltip" | "primary";
className?: string;
}) {
return (
<kbd
className={cn(
"pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded-[5px] px-1 font-sans text-xs font-medium select-none",
tone === "default" && "bg-surface-2 text-muted",
tone === "tooltip" && "bg-bg text-muted",
tone === "primary" && "bg-bg/20 text-current",
className,
)}
>
{children}
</kbd>
);
}
const isApple = () => /Mac|iPhone|iPad/.test(navigator.userAgent);
const noSubscribe = () => () => {};
/**
* The command key for this device: ⌘ on a Mac (and an iPad with a keyboard),
* Ctrl everywhere else, where ⌘ means nothing. Null on the server, which has
* no device: a shortcut stays invisible until the browser knows, so nobody
* ever sees the wrong key.
*/
export function useModKey(): "⌘" | "Ctrl" | null {
return useSyncExternalStore(
noSubscribe,
() => (isApple() ? "⌘" : "Ctrl"),
() => null,
);
}
/** A chord as separate keys: `<Shortcut keys={["mod", "K"]} />`, where
* "mod" becomes ⌘ or Ctrl for the device. Hidden from screen readers; the
* control it sits in carries the name. */
export function Shortcut({
keys,
tone,
className,
}: {
keys: string[];
tone?: "default" | "tooltip" | "primary";
className?: string;
}) {
const mod = useModKey();
const waiting = mod === null && keys.includes("mod");
return (
<span
aria-hidden
className={cn("inline-flex items-center gap-1", waiting && "invisible", className)}
>
{keys.map((key) => (
<Kbd key={key} tone={tone}>
{key === "mod" ? (mod ?? "⌘") : key}
</Kbd>
))}
</span>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/kbd- Category
- Display
- Files
- kbd.tsx