Skip to content
Thrum

Kbd

A keyboard key, for writing shortcuts in menus, tooltips and help text. Kbd is one key and KbdGroup holds several. Shortcut takes a string such as mod+k and prints the keys the reader's own keyboard has.

Install

npx shadcn@latest add https://thrumui.dev/r/kbd.json

Adds components/ui/kbd.tsx. Nothing else in your project changes.

import { parseKeys } from "@/components/ui/kbd";

Data shape

Type
// Names a shortcut string understands. Anything else is printed as written.
type KeyName =
  | "mod" | "cmd" | "ctrl" | "alt" | "shift"
  | "enter" | "backspace" | "delete" | "esc" | "tab" | "space"
  | "up" | "down" | "left" | "right" | "plus";
Sample
<Shortcut keys="mod+k" />          // ⌘ K on Apple devices, Ctrl K elsewhere
<Shortcut keys="shift+enter" />    // ⇧ ↵, or Shift Enter
<Shortcut keys="g i" />            // G then I
<Shortcut keys="mod+plus" />       // ⌘ +, or Ctrl +

Props

PropTypeDefaultDescription
KbdComponentProps<"kbd">–One key: a kbd element 20 pixels tall, at least 20 wide, in 11 pixel monospaced text, with a 1 pixel frame and a 2 pixel bottom edge.
KbdGroupComponentProps<"kbd">–Keys pressed together, 4 pixels apart. It is an outer kbd element, the way HTML writes a combination.
Shortcut: keysstringRequiredThe shortcut. A plus sign joins keys pressed together, a space separates steps pressed in turn: “mod+shift+k”, “g i”. Names are not case sensitive.
classNamestring–On every part: extra classes, merged last.
parseKeys()(keys: string, apple?: boolean) => ShortcutKey[][]–A second export: the steps and keys of a shortcut string, each with its printed label and, for a symbol, its spoken name.

Motion and sound

Motion

  • The keys do not move.

Sound

Silent. This component makes no sound.

Accessibility

  • Each key is a kbd element, and a combination is a kbd around them: the markup HTML defines for keyboard input. Nothing takes focus.
  • A key printed as a symbol is read by its name: ⌘ is “Command”, ⇧ is “Shift”, ↵ is “Return”. The symbol itself is hidden from screen readers.
  • Shortcut prints Ctrl on the server and in the first render, then switches to ⌘ on Apple devices once the page has loaded. Server and browser markup match.
  • The component only shows a shortcut. Listening for the keys is your code's job; add aria-keyshortcuts to the control the shortcut triggers.
  • Key text is the theme's text colour on its muted colour, and the frame is the input border colour, which keeps 3 to 1 against the page.

Source

components/ui/kbd.tsx
"use client";

import { Fragment, useSyncExternalStore, type ComponentProps } from "react";

import { cn } from "@/lib/utils";

/** One key of a shortcut: what is printed on it, and its name when the print is a symbol. */
export type ShortcutKey = { label: string; name?: string };

// [name in a shortcut string]: [on Apple devices, elsewhere]. A symbol carries its spoken name.
const KEYS: Record<string, readonly [ShortcutKey, ShortcutKey]> = {
  mod: [{ label: "⌘", name: "Command" }, { label: "Ctrl" }],
  cmd: [{ label: "⌘", name: "Command" }, { label: "Win" }],
  meta: [{ label: "⌘", name: "Command" }, { label: "Win" }],
  ctrl: [{ label: "⌃", name: "Control" }, { label: "Ctrl" }],
  control: [{ label: "⌃", name: "Control" }, { label: "Ctrl" }],
  alt: [{ label: "⌥", name: "Option" }, { label: "Alt" }],
  option: [{ label: "⌥", name: "Option" }, { label: "Alt" }],
  shift: [{ label: "⇧", name: "Shift" }, { label: "Shift" }],
  enter: [{ label: "↵", name: "Return" }, { label: "Enter" }],
  return: [{ label: "↵", name: "Return" }, { label: "Enter" }],
  backspace: [{ label: "⌫", name: "Delete" }, { label: "Backspace" }],
  delete: [{ label: "⌦", name: "Forward delete" }, { label: "Del" }],
  escape: [{ label: "Esc", name: "Escape" }, { label: "Esc", name: "Escape" }],
  esc: [{ label: "Esc", name: "Escape" }, { label: "Esc", name: "Escape" }],
  tab: [{ label: "⇥", name: "Tab" }, { label: "Tab" }],
  space: [{ label: "Space" }, { label: "Space" }],
  up: [{ label: "↑", name: "Up" }, { label: "↑", name: "Up" }],
  down: [{ label: "↓", name: "Down" }, { label: "↓", name: "Down" }],
  left: [{ label: "←", name: "Left" }, { label: "←", name: "Left" }],
  right: [{ label: "→", name: "Right" }, { label: "→", name: "Right" }],
  plus: [{ label: "+", name: "Plus" }, { label: "+", name: "Plus" }],
};

/**
 * Reads a shortcut string into steps of keys. `+` joins keys pressed together and a space separates steps pressed in turn:
 * `"mod+shift+k"` is one step of three keys, `"g i"` is two steps. `mod` is Command on Apple devices and Ctrl elsewhere.
 * A key with no entry is printed as written, with a single letter in upper case. Write the plus key as `plus`, or as `++`.
 */
export function parseKeys(keys: string, apple = false): ShortcutKey[][] {
  return keys
    .trim()
    .split(/\s+/)
    .filter(Boolean)
    .map((step) =>
      (step === "+" ? "plus" : step.replaceAll("++", "+plus"))
        .split("+")
        .filter(Boolean)
        .map((key) => KEYS[key.toLowerCase()]?.[apple ? 0 : 1] ?? { label: key.length === 1 ? key.toUpperCase() : key }),
    );
}

const never = () => () => {};
/** Whether this is an Apple device. False on the server and in the first client render, so the two match. */
function useApple(): boolean {
  return useSyncExternalStore(
    never,
    () => /Mac|iPhone|iPad/.test(navigator.userAgent),
    () => false,
  );
}

/** One key. It is a `<kbd>` element: a 1 pixel frame with a 2 pixel bottom edge, like the side of a key cap. */
export function Kbd({ className, ...props }: ComponentProps<"kbd">) {
  return (
    <kbd
      data-slot="kbd"
      data-surface="control"
      className={cn(
        "inline-flex h-5 min-w-5 items-center justify-center rounded-sm border border-b-2 border-foreground/25 bg-muted px-1 font-mono text-[0.6875rem] leading-none font-medium whitespace-nowrap text-foreground select-none",
        className,
      )}
      {...props}
    />
  );
}

/** Several keys pressed together. An outer `<kbd>`, as HTML writes a combination, with 4 pixels between the keys. */
export function KbdGroup({ className, ...props }: ComponentProps<"kbd">) {
  return <kbd data-slot="kbd-group" className={cn("inline-flex max-w-full flex-wrap items-center gap-1 align-middle font-sans text-xs", className)} {...props} />;
}

export type ShortcutProps = Omit<ComponentProps<"kbd">, "children"> & {
  /** The shortcut as a string: `"mod+k"`, `"shift+enter"`, `"g i"`. See `parseKeys`. */
  keys: string;
};

/**
 * A shortcut written as a string. `mod` and the other modifier names are printed the way the reader's keyboard has them:
 * symbols on Apple devices, words elsewhere. The device is read after the page loads, so the server and the browser agree.
 */
export function Shortcut({ keys, className, ...props }: ShortcutProps) {
  const steps = parseKeys(keys, useApple());
  return (
    <KbdGroup data-slot="shortcut" className={className} {...props}>
      {steps.map((step, i) => (
        <Fragment key={i}>
          {i > 0 && <span className="text-muted-foreground">then</span>}
          {step.map((key, j) => (
            <Kbd key={j}>
              {key.name ? (
                <>
                  <span aria-hidden="true">{key.label}</span>
                  <span className="sr-only">{key.name}</span>
                </>
              ) : (
                key.label
              )}
            </Kbd>
          ))}
        </Fragment>
      ))}
    </KbdGroup>
  );
}

Files and dependencies

Adds
components/ui/kbd.tsx
Packages
None
Brings along
Nothing

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor