Skip to content
Shaken UI
Sign in

Keyboard keys and key combinations as quiet keycaps, with a platform-aware Mod key that shows ⌘ on Apple devices and Ctrl elsewhere.

Category
Data display
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Kbd preview
  • Open the command menuControlK
  • Send the promptControlEnter
  • Stop the running agentEscape
  • Toggle the trace panelControlShiftT

Press / to search the docs, or Shift? for every shortcut.

Installation

npx @shakenui/cli add kbd

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add kbd --dry-run

Usage

kbd-example.tsx
import { Kbd, KbdGroup } from "@/components/shaken/ui/kbd";

const shortcuts = [
  { action: "Open the command menu", keys: "Mod+K" },
  { action: "Send the prompt", keys: "Mod+Enter" },
  { action: "Stop the running agent", keys: "Escape" },
  { action: "Toggle the trace panel", keys: "Mod+Shift+T" },
];

export default function KbdExample() {
  return (
    <div className="grid w-full max-w-sm gap-5">
      <ul className="grid divide-y divide-zinc-950/[0.07] rounded-xl border border-zinc-950/10 dark:divide-white/[0.08] dark:border-white/10">
        {shortcuts.map((shortcut) => (
          <li key={shortcut.action} className="flex items-center justify-between gap-4 px-4 py-2.5 text-sm">
            <span className="text-zinc-700 dark:text-zinc-300">{shortcut.action}</span>
            <KbdGroup keys={shortcut.keys} />
          </li>
        ))}
      </ul>
      <p className="text-sm text-zinc-600 dark:text-zinc-400">
        Press <Kbd>/</Kbd> to search the docs, or <KbdGroup keys={["Shift", "?"]} /> for every shortcut.
      </p>
    </div>
  );
}

API

PropTypeDefaultDescription
Kbd size"sm" | "md""sm"20 or 24 pixels tall.
KbdGroup keysstring | string[]—Keys pressed together: ["Mod", "K"] or "Mod+Shift+P". Mod, Shift, Alt, Ctrl, Enter, Escape, Backspace, Tab, and arrows map to symbols on Apple platforms.
KbdGroup separatorReactNode—Between keys. None on Apple platforms, + elsewhere.
KbdGroup platform"mac" | "other"—Forces a platform; detected from the browser by default.
useKbdPlatform / formatKeyhook / (key, platform) => { label, name }—The detection and key mapping, for building your own shortcut hints.

Accessibility

  • Renders kbd elements, with a combination as a kbd that contains one kbd per key, as HTML specifies.
  • Symbols carry their spoken names in visually hidden text ("Command", "Shift"), and a title tooltip for sighted users.
  • Platform detection renders the non-Apple labels on the server and during hydration, then settles, so there is no hydration mismatch.
  • Separators are decorative and hidden from assistive technology.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/kbd.tsxkbd
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/kbd/0.1.0.json.

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

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

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

export type KbdPlatform = "mac" | "other";

function detectPlatform(): KbdPlatform {
  if (typeof navigator === "undefined") return "other";
  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";
}

const subscribe = () => () => {};

/**
 * The visitor's platform: `"mac"` on macOS and iOS, `"other"` elsewhere. Renders `"other"` on the
 * server and during hydration, then settles on the real value, so there is no hydration mismatch.
 */
export function useKbdPlatform(): KbdPlatform {
  return useSyncExternalStore(subscribe, detectPlatform, () => "other");
}

type KeyLabel = { mac: string; other: string; name: string };

// Symbols on Apple platforms, words elsewhere. `name` is what a screen reader hears.
const keys: Record<string, KeyLabel> = {
  mod: { mac: "⌘", other: "Ctrl", name: "Command" },
  cmd: { mac: "⌘", other: "Win", name: "Command" },
  command: { mac: "⌘", other: "Win", name: "Command" },
  meta: { mac: "⌘", other: "Win", name: "Command" },
  ctrl: { mac: "⌃", other: "Ctrl", name: "Control" },
  control: { mac: "⌃", other: "Ctrl", name: "Control" },
  shift: { mac: "⇧", other: "Shift", name: "Shift" },
  alt: { mac: "⌥", other: "Alt", name: "Option" },
  option: { mac: "⌥", other: "Alt", name: "Option" },
  enter: { mac: "↵", other: "Enter", name: "Enter" },
  return: { mac: "↵", other: "Enter", name: "Return" },
  escape: { mac: "Esc", other: "Esc", name: "Escape" },
  esc: { 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" },
  up: { mac: "↑", other: "↑", name: "Up arrow" },
  arrowup: { mac: "↑", other: "↑", name: "Up arrow" },
  down: { mac: "↓", other: "↓", name: "Down arrow" },
  arrowdown: { mac: "↓", other: "↓", name: "Down arrow" },
  left: { mac: "←", other: "←", name: "Left arrow" },
  arrowleft: { mac: "←", other: "←", name: "Left arrow" },
  right: { mac: "→", other: "→", name: "Right arrow" },
  arrowright: { mac: "→", other: "→", name: "Right arrow" },
};

/** Resolves a key name such as `"Mod"` or `"shift"` to its label for a platform, with a spoken name. */
export function formatKey(key: string, platform: KbdPlatform) {
  const known = keys[key.toLowerCase()];
  if (known) {
    // The modifier's spoken name follows the platform: "Command" on a Mac, "Control" elsewhere.
    const lower = key.toLowerCase();
    const name =
      platform === "other" && lower === "mod"
        ? "Control"
        : platform === "other" && (lower === "cmd" || lower === "command" || lower === "meta")
          ? "Windows"
          : platform === "other" && (lower === "alt" || lower === "option")
            ? "Alt"
            : known.name;
    return { label: known[platform], name };
  }
  return { label: key.length === 1 ? key.toUpperCase() : key, name: key.length === 1 ? key.toUpperCase() : key };
}

const sizes = {
  sm: "h-5 min-w-5 px-1 text-[11px]",
  md: "h-6 min-w-6 px-1.5 text-xs",
} as const;

export interface KbdProps extends ComponentProps<"kbd"> {
  size?: keyof typeof sizes;
}

/**
 * One key, drawn as a quiet keycap: hairline border with a slightly heavier bottom edge.
 * Renders a `<kbd>`, so assistive technology knows it is keyboard input.
 */
export function Kbd({ size = "sm", className, ...props }: KbdProps) {
  return (
    <kbd
      data-slot="kbd"
      className={cx(
        "inline-flex shrink-0 items-center justify-center rounded-md font-sans leading-none font-medium whitespace-nowrap select-none",
        "border border-b-[1.5px] border-zinc-950/12 bg-white text-zinc-600 shadow-[0_1px_0_rgb(0_0_0/0.04)]",
        "dark:border-white/15 dark:bg-white/[0.04] dark:text-zinc-300 dark:shadow-none",
        "[&_svg]:size-3 [&_svg]:shrink-0",
        sizes[size],
        className,
      )}
      {...props}
    />
  );
}

export interface KbdGroupProps extends Omit<ComponentProps<"kbd">, "children"> {
  /**
   * The keys to press together, as an array (`["Mod", "K"]`) or a string joined by `+`
   * (`"Mod+Shift+P"`). `Mod` becomes ⌘ on Apple platforms and Ctrl elsewhere.
   */
  keys: string | string[];
  size?: KbdProps["size"];
  /**
   * Text between keys. Defaults to nothing on Apple platforms (⌘K reads as one chord there)
   * and `+` elsewhere.
   */
  separator?: ReactNode;
  /** Forces a platform, for example to document both. Detected from the browser by default. */
  platform?: KbdPlatform;
}

/**
 * A key combination: a `<kbd>` holding one `<kbd>` per key, as HTML specifies for chords.
 * Each symbol carries its spoken name for screen readers ("Command K", not "K").
 */
export function KbdGroup({ keys: input, size = "sm", separator, platform: forced, className, ...props }: KbdGroupProps) {
  const detected = useKbdPlatform();
  const platform = forced ?? detected;
  const list = Array.isArray(input) ? input : input.split("+").map((key) => key.trim()).filter(Boolean);
  const between = separator !== undefined ? separator : platform === "mac" ? null : "+";

  return (
    <kbd data-slot="kbd-group" className={cx("inline-flex items-center gap-1 font-sans", className)} {...props}>
      {list.map((key, index) => {
        const { label, name } = formatKey(key, platform);
        const spoken = name !== label;
        return (
          <Fragment key={`${key}-${index}`}>
            {index > 0 && between != null ? (
              <span aria-hidden="true" className="text-[11px] text-zinc-400 dark:text-zinc-500">
                {between}
              </span>
            ) : null}
            <Kbd size={size} title={spoken ? name : undefined}>
              {spoken ? (
                <>
                  <span aria-hidden="true">{label}</span>
                  <span className="sr-only">{name}</span>
                </>
              ) : (
                label
              )}
            </Kbd>
          </Fragment>
        );
      })}
    </kbd>
  );
}