# Kbd

Keycaps as real keys in miniature, a face on a skirt, with the modifier and arrow keys drawn, that press down while you hold the keys they show.

Tier: free. Type: component. Category: data. Tags: keyboard.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/kbd.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/kbd.tsx`.

## Preview

Live preview: https://pixilui.com/components/kbd

Knobs:

- `size`: `md`, `sm`

Signature: Hold ⌘ and every ⌘ cap on the page sinks into its skirt and its legend lights up like a backlit key.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/kbd.tsx, quiet https://pixilui.com/r/standalone/kbd.quiet.tsx.

## Code

`components/pixilui/kbd.tsx`

```tsx
"use client";

/*
  Keycaps, locked 1 Dec 2026 with the tooltips (B10, design/explorations/components/locked/tooltip). Their look is
  foundation.css section 8 (.pixilui-kbd): every key is a real key in miniature, a face on a skirt. Modifier and arrow
  keys are drawn on one 12-unit grid with the legend's stroke, and keep their character for screen readers.

  Held      while the person holds a key, its caps travel down into the skirt, the face darkens and (lively) the legend
            lights. A state with no transition: keyboard actions never animate. Letters and digits are matched by the
            physical key, since ⌥ changes the typed character.
*/

import { forwardRef, useSyncExternalStore, type ComponentPropsWithoutRef } from "react";
import { cn } from "./lib/utils";

/** A missing list prop (plain JavaScript, a guessing agent): one stable empty list, so nothing throws or re-renders. */
const NONE: never[] = [];

/** The drawn keys, on one 12-unit grid (the locked glyphs). */
export const KbdGlyphs: Record<string, string> = {
  "⌘": "M7.75 2.5v7a1.75 1.75 0 1 0 1.75-1.75h-7a1.75 1.75 0 1 0 1.75 1.75v-7a1.75 1.75 0 1 0-1.75 1.75h7a1.75 1.75 0 1 0-1.75-1.75",
  "⇧": "M6 1.75 10.25 6.25H7.75v4h-3.5v-4H1.75Z",
  "⌥": "M1.5 3h2.75l3.5 6h2.75M7.5 3h3",
  "⌃": "M2.75 7.5 6 4.25 9.25 7.5",
  "↵": "M10 2.25V6a1.25 1.25 0 0 1-1.25 1.25H2.25M4.75 4.75 2.25 7.25l2.5 2.5",
  "⌫": "M4.5 2.5h5.25c.69 0 1.25.56 1.25 1.25v4.5c0 .69-.56 1.25-1.25 1.25H4.5L1.25 6ZM6.25 4.75l2.5 2.5M8.75 4.75l-2.5 2.5",
  "⇥": "M1.5 6h7.25M6.25 3.5 8.75 6l-2.5 2.5M10.5 3v6",
  "↑": "M6 10V2.25M2.75 5.5 6 2.25 9.25 5.5",
  "↓": "M6 2v7.75M2.75 6.5 6 9.75 9.25 6.5",
  "←": "M10 6H2.25M5.5 2.75 2.25 6l3.25 3.25",
  "→": "M2 6h7.75M6.5 2.75 9.75 6 6.5 9.25",
};

const MODIFIERS = new Set(["⌘", "⇧", "⌥", "⌃"]);

/**
 * A shortcut as its keys: "⌘ K" and ["⌘", "K"] are two keys; "⌘K" and "⌘↵" peel their leading modifiers off, so the
 * rest is one key ("Esc", "K", "↵").
 */
export function parseKeys(keys: string | readonly string[]): string[] {
  if (typeof keys !== "string") return [...keys];
  const s = keys.trim();
  if (/\s/.test(s)) return s.split(/\s+/);
  const out: string[] = [];
  let rest = s;
  while (rest.length > 1 && MODIFIERS.has(rest[0]!)) {
    out.push(rest[0]!);
    rest = rest.slice(1);
  }
  if (rest) out.push(rest);
  return out;
}

/* ------------------------------------------------------------------ the keys held right now, shared by every cap */

const NAME: Record<string, string> = { Meta: "⌘", Shift: "⇧", Alt: "⌥", Control: "⌃", Enter: "↵", Backspace: "⌫", Escape: "Esc", Tab: "⇥", ArrowUp: "↑", ArrowDown: "↓", ArrowLeft: "←", ArrowRight: "→", " ": "Space" };
// ⌥ changes e.key (⌥C is ç), so letters and digits come from the physical key
const CODE = /^Key([A-Z])$|^Digit(\d)$/;
const nameOf = (e: KeyboardEvent) => {
  const m = CODE.exec(e.code);
  return NAME[e.key] ?? (m ? (m[1] ?? m[2]!) : e.key.length === 1 ? e.key.toUpperCase() : e.key);
};
let held = new Set<string>();
const listeners = new Set<() => void>();
const emit = (next: Set<string>) => {
  held = next;
  listeners.forEach((l) => l());
};
const down = (e: KeyboardEvent) => emit(new Set(held).add(nameOf(e)));
const up = (e: KeyboardEvent) => {
  const next = new Set(held);
  next.delete(nameOf(e));
  // macOS drops keyups while ⌘ is down
  emit(e.key === "Meta" ? new Set() : next);
};
const clear = () => emit(new Set());
/** Listens for the keys held right now (the tooltip's own keycaps use it); returns the unsubscribe. */
export function subscribeHeldKeys(listener: () => void) {
  if (!listeners.size) {
    document.addEventListener("keydown", down);
    document.addEventListener("keyup", up);
    window.addEventListener("blur", clear);
  }
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
    if (!listeners.size) {
      document.removeEventListener("keydown", down);
      document.removeEventListener("keyup", up);
      window.removeEventListener("blur", clear);
    }
  };
}
const empty = new Set<string>();
/** The keys held right now, by their cap names ("⌘", "K"). */
export const heldKeys = () => held;
/** The keys held right now (an empty set on the server). */
export const useHeldKeys = () => useSyncExternalStore(subscribeHeldKeys, heldKeys, () => empty);

export type KbdProps = Omit<ComponentPropsWithoutRef<"span">, "children"> & {
  /** The shortcut: "⌘ K", "⌘K" or ["⌘", "K"]. Modifier and arrow keys are drawn. */
  keys: string | readonly string[];
  /** md 20 tall (sentences and shortcut sheets, default); sm 18 (tooltips and dense rows). */
  size?: "md" | "sm";
  /** dark: on a dark surface, the key's front lighter than the surface and darker than its face. Inside a tooltip this is automatic. */
  tone?: "dark";
  /** Keys shown held, for a still copy (a shortcut sheet, a screenshot). Live holding needs nothing: caps press while their keys are held. */
  held?: readonly string[];
  /** Turn off the live press (a cap that should never move). */
  still?: boolean;
};

/** One key as a real key in miniature: a face on a skirt. */
function Key({ k, down, held }: { k: string; down: boolean; held: boolean }) {
  const glyph = KbdGlyphs[k];
  return (
    <kbd data-key={k} data-down={down ? "" : undefined} data-held={held ? "" : undefined}>
      {glyph ? (
        <>
          <svg viewBox="0 0 12 12" aria-hidden="true">
            <path d={glyph} />
          </svg>
          <span className="pixilui-kbd-name">{k}</span>
        </>
      ) : (
        k
      )}
    </kbd>
  );
}

/** A run of keycaps: shortcuts in sentences, shortcut sheets and tooltips. */
export const Kbd = forwardRef<HTMLSpanElement, KbdProps>(function Kbd({ keys = NONE, size, tone, held: shownHeld, still, className, ...props }, ref) {
  const live = useHeldKeys();
  return (
    <span ref={ref} className={cn("pixilui-kbd", className)} data-size={size === "sm" ? "sm" : undefined} data-tone={tone} {...props}>
      {parseKeys(keys).map((k, i) => (
        <Key key={`${k}-${i}`} k={k} down={!still && live.has(k)} held={!!shownHeld?.includes(k)} />
      ))}
    </span>
  );
});
```

## Usage

When to use:

- A shortcut in a sentence: "Press ⌘ K to search runs".
- A shortcuts sheet, an action and its keys on each row.
- Keys on a dark surface (tone="dark"); inside a tooltip this is automatic.

When not to use:

- Menu shortcuts: menus keep plain-text shortcuts, like macOS menus.
- A button's own shortcut chip: the button draws it.

```tsx
import { Kbd } from "@/components/pixilui/kbd";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  size: ["md", "sm"],
} as const;

const shortcuts: [string, string][] = [
  ["Search runs", "⌘ K"],
  ["New run", "⌘ N"],
  ["Approve", "⌘ ↵"],
  ["Deny", "⌘ ⌫"],
  ["Copy as Markdown", "⌥ C"],
  ["Step through the trail", "↑ ↓"],
  ["Close", "Esc"],
];

/** A shortcuts sheet: hold any of these keys and their caps press. */
export default function KbdDemo({ size = "md" }: KnobValues<typeof knobs>) {
  return (
    <div className="w-full max-w-sm">
      <ul className="flex flex-col">
        {shortcuts.map(([action, keys]) => (
          <li key={action} className="flex items-center justify-between border-b border-divider py-2.5 type-label text-secondary last:border-0">
            <span>{action}</span>
            <Kbd keys={keys} size={size} />
          </li>
        ))}
      </ul>
      <p className="mt-4 type-body text-muted">
        Press <Kbd keys="⌘ K" size={size} /> to search runs, or <Kbd keys="?" size={size} /> for every shortcut.
      </p>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keys` (required) | `string \| readonly string[]` | `NONE` | The shortcut: "⌘ K", "⌘K" or ["⌘", "K"]. Modifier and arrow keys are drawn. |
| `size` | `"md" \| "sm"` |  | md 20 tall (sentences and shortcut sheets, default); sm 18 (tooltips and dense rows). |
| `tone` | `"dark"` |  | dark: on a dark surface, the key's front lighter than the surface and darker than its face. Inside a tooltip this is automatic. |
| `held` | `readonly string[]` |  | Keys shown held, for a still copy (a shortcut sheet, a screenshot). Live holding needs nothing: caps press while their keys are held. |
| `still` | `boolean` |  | Turn off the live press (a cap that should never move). |

Also accepts every native `<span>` attribute, and a ref to it.

## Keyboard

- `Tab`: Never takes focus: keycaps describe keys, they are not controls.

## Accessibility

- Each key is a kbd element; drawn keys keep their character in visually hidden text, so readers say "command", not nothing.
- Pressing is a state shown while the real key is held, never the only way to learn a shortcut.

## Motion

- None by design: a held key travels down into its skirt as a state, with no transition, since keyboard actions never animate.

## Responsive

- md 20 tall for sentences and sheets, sm 18 for tooltips and dense rows; caps sit on the text's middle.

## Performance

- One document key listener shared by every cap on the page, added with the first and removed with the last.

## Notes for AI

- <Kbd keys="⌘ K" /> or keys={["⌘", "K"]}; "⌘K" also works (leading modifiers peel off).
- Drawn keys: ⌘ ⇧ ⌥ ⌃ ↵ ⌫ ⇥ ↑ ↓ ← →. Others are written: Esc, Space, K.
- size="sm" in dense rows; tone="dark" on a dark surface; held={[...]} for a still copy of held keys; still turns the live press off.

## Related

- [Tooltip](https://pixilui.com/components/tooltip/markdown): One charcoal tooltip for every hover hint: a control's name and keys, why it can't act, a small breakdown, a person's name, cut-off text and long text, travelling with the pointer along a row.
- [Button](https://pixilui.com/components/button/markdown): The PixilUI button in four main styles and four more, five sizes from 24 to 44, with icons, loading, disabled, a count and a shortcut.
