Skip to content
Atoms

Kbd

Key caps that press with the real key.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add kbd

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/kbd.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/kbd and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { Kbd } from "asta-ui/kbd";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useState, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    // Display label → KeyboardEvent.key values that should press it.
    const MATCH: Record<string, string[]> = {
      "⌘": ["Meta"],
      Cmd: ["Meta"],
      Ctrl: ["Control"],
      "⌃": ["Control"],
      "⌥": ["Alt"],
      Alt: ["Alt"],
      "⇧": ["Shift"],
      Shift: ["Shift"],
      "↵": ["Enter"],
      Enter: ["Enter"],
      Esc: ["Escape"],
      "⌫": ["Backspace"],
      Tab: ["Tab"],
      Space: [" "],
      "↑": ["ArrowUp"],
      "↓": ["ArrowDown"],
      "←": ["ArrowLeft"],
      "→": ["ArrowRight"],
    };
    const keysFor = (label: string) => MATCH[label] ?? [label.toLowerCase()];
    
    /** Tracks which of the given labels are held down right now. */
    function useHeld(labels: string[], on: boolean) {
      const [held, setHeld] = useState<Set<string>>(new Set());
      const sig = labels.join("\u0000");
      useEffect(() => {
        if (!on) return;
        const list = sig.split("\u0000");
        const set = (e: KeyboardEvent, down: boolean) => {
          const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;
          const hit = list.filter((l) => keysFor(l).includes(k));
          if (!hit.length) return;
          setHeld((prev) => {
            const next = new Set(prev);
            hit.forEach((h) => (down ? next.add(h) : next.delete(h)));
            return next;
          });
        };
        const down = (e: KeyboardEvent) => set(e, true);
        const up = (e: KeyboardEvent) => set(e, false);
        const clear = () => setHeld(new Set());
        window.addEventListener("keydown", down);
        window.addEventListener("keyup", up);
        window.addEventListener("blur", clear);
        return () => {
          window.removeEventListener("keydown", down);
          window.removeEventListener("keyup", up);
          window.removeEventListener("blur", clear);
        };
      }, [sig, on]);
      return held;
    }
    
    export interface KbdProps {
      children: ReactNode;
      size?: "sm" | "md" | "lg";
      /** Force the pressed look. */
      pressed?: boolean;
      /** Press down when the matching real key is pressed (children must be a string like "K" or "⌘"). */
      live?: boolean;
      className?: string;
    }
    
    const SIZE = {
      sm: "h-5 min-w-5 px-1 text-[11px] rounded-[5px]",
      md: "h-7 min-w-7 px-1.5 text-[12.5px] rounded-[7px]",
      lg: "h-10 min-w-10 px-2.5 text-[15px] rounded-[10px]",
    };
    
    /** A key cap. A thicker bottom edge sinks when pressed. */
    export function Kbd({ children, size = "md", pressed, live, className }: KbdProps) {
      const label = typeof children === "string" ? children : "";
      const held = useHeld(label ? [label] : [], !!live && !!label);
      const down = pressed || held.has(label);
      return (
        <kbd
          data-pressed={down || undefined}
          className={cx(
            "inline-flex select-none items-center justify-center bg-paper font-sans font-medium text-ink-2",
            "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent),inset_0_-2px_0_color-mix(in_srgb,var(--color-ink)_12%,transparent)]",
            "transition-[transform,box-shadow,background-color,color] duration-100 ease-out",
            "data-[pressed]:translate-y-px data-[pressed]:bg-paper-2 data-[pressed]:text-brand data-[pressed]:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-brand)_45%,transparent)]",
            SIZE[size],
            className,
          )}
        >
          {children}
        </kbd>
      );
    }
    
    /**
     * A shortcut made of several keys. With `live`, each cap presses with its real key, and `onTrigger`
     * fires when the whole combo is held at once.
     */
    export function KbdCombo({
      keys,
      size = "md",
      live,
      separator,
      onTrigger,
      className,
    }: {
      keys: string[];
      size?: KbdProps["size"];
      live?: boolean;
      /** Shown between caps, e.g. "+" or "then". Omit for none. */
      separator?: ReactNode;
      onTrigger?: () => void;
      className?: string;
    }) {
      const held = useHeld(keys, !!live);
      const all = keys.every((k) => held.has(k));
      useEffect(() => {
        if (all && live) onTrigger?.();
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [all]);
      return (
        <span className={cx("inline-flex items-center gap-1", className)} aria-label={keys.join(" + ")}>
          {keys.map((k, i) => (
            <span key={k} className="inline-flex items-center gap-1">
              {i > 0 && separator && <span className="text-[12px] text-mute">{separator}</span>}
              <Kbd size={size} pressed={held.has(k)}>
                {k}
              </Kbd>
            </span>
          ))}
        </span>
      );
    }
    
    export default Kbd;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Kbd component to my project.
    
    Key caps that press with the real key.
    It includes: Kbd, KbdCombo, live.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add kbd --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/kbd.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Kbd, KbdCombo } from "@/components/astabyte/kbd";
    ```
    
    Usage example and props: https://ui.astabyte.com/kbd
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <div style="display:flex;flex-wrap:wrap;align-items:center;gap:12px">
    <kbd class="asta-kbd asta-kbd-sm">K</kbd><kbd class="asta-kbd">Esc</kbd><kbd class="asta-kbd asta-kbd-lg" data-pressed>⌘</kbd><span class="asta-kbd-combo" aria-label="⌘ + K"><kbd class="asta-kbd">⌘</kbd><span class="asta-kbd-combo-sep" aria-hidden="true">+</span><kbd class="asta-kbd">K</kbd></span>
    </div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { Kbd, KbdCombo } from "@/components/astabyte/kbd";

const Row = ({ label, children }: { label: string; children: React.ReactNode }) => (
  <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
    <span className="w-20 shrink-0 font-mono text-[11px] uppercase tracking-wider text-mute">{label}</span>
    <div className="flex flex-wrap items-center gap-3">{children}</div>
  </div>
);

const SHORTCUTS = [
  { keys: ["⌘", "K"], label: "Search" },
  { keys: ["⌘", "⇧", "P"], label: "Commands" },
  { keys: ["⌥", "↵"], label: "Open in new tab" },
];

export default function KbdDemo() {
  const [hits, setHits] = useState(0);

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex flex-col gap-7">
        <Row label="Size">
          <Kbd size="sm">K</Kbd>
          <Kbd>K</Kbd>
          <Kbd size="lg">K</Kbd>
          <Kbd>Esc</Kbd>
          <Kbd>⌫</Kbd>
        </Row>
        <Row label="Live">
          {["←", "↑", "↓", "→", "Space", "Shift"].map((k) => (
            <Kbd key={k} size="lg" live>
              {k}
            </Kbd>
          ))}
        </Row>
        <Row label="Combo">
          <div className="flex items-center gap-3">
            <KbdCombo keys={["Shift", "A"]} size="lg" separator="+" live onTrigger={() => setHits((n) => n + 1)} />
            <span className="text-[13px] tabular-nums text-mute">{hits ? `Pressed ${hits}×` : "Hold both keys"}</span>
          </div>
        </Row>
        <Row label="In a menu">
          <ul className="w-full min-w-[260px] rounded-xl bg-paper p-1.5 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent),0_8px_24px_-12px_rgb(0_0_0/0.2)]">
            {SHORTCUTS.map((s) => (
              <li key={s.label} className="flex h-9 items-center justify-between gap-6 rounded-[10px] px-2.5 text-[13px] text-ink-2 hover:bg-paper-2">
                {s.label}
                <KbdCombo keys={s.keys} size="sm" />
              </li>
            ))}
          </ul>
        </Row>
      </div>
    </div>
  );
}