# Keyboard
*URL: https://www.grettech.com/components/keyboard*

A Mac-style keyboard with real keycap depth, spring presses and synthesised switch sounds by key type, plus a live keystroke row, shortcut glows and auto-typing.

- Keycaps with side walls that sink when pressed, on an aluminium case
- Four switch sounds; long keys rattle, keys pan left to right
- Lights up as you type, glows shortcuts, or types by itself
- No audio files; scales to its container; light and dark

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/keyboard
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/keyboard-demo`

**Dependencies:** npm: motion, lucide-react, clsx, tailwind-merge

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install motion lucide-react clsx tailwind-merge
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/keyboard.tsx`
```tsx
"use client"

import { cn } from "@/lib/utils"
import {
  FastForward,
  Globe,
  LayoutGrid,
  Mic,
  Moon,
  Play,
  Rewind,
  Search,
  Sun,
  SunDim,
  Volume1,
  Volume2,
  VolumeX,
} from "lucide-react"
import {
  AnimatePresence,
  motion,
  useInView,
  useReducedMotion,
} from "motion/react"
import * as React from "react"

export interface KeyboardProps extends Omit<
  React.HTMLAttributes<HTMLDivElement>,
  "onKeyPress"
> {
  /** Mechanical key sounds, made in the browser (no files to download) */
  sound?: boolean
  /** Loudness of the sounds, 0–1 */
  volume?: number
  /**
   * How the switches sound: tactile (a soft bump), clicky (a sharp snap),
   * linear (quiet and smooth) or thock (deep and muted)
   */
  switchType?: SwitchType
  /** Tilt the keyboard back, in degrees, as if it sat on a desk */
  tilt?: number
  /**
   * Light up keys as they're typed on a real keyboard, while on screen.
   * Meanwhile Space and the arrow keys type instead of scrolling the page
   * (except in text fields and other controls, which keep working)
   */
  listen?: boolean
  /** A row of the last keys pressed, above the keyboard */
  showPreview?: boolean
  /** Key codes to glow, e.g. a shortcut: ["MetaLeft", "KeyK"] */
  highlight?: string[]
  /** A phrase the keyboard can type by itself; see `typing` */
  autoType?: string
  /**
   * Who types. "idle": the keyboard types `autoType` while nobody is using
   * it and hands over the moment someone hovers or types. "auto": it keeps
   * typing whatever the visitor does. "user": only the visitor types
   */
  typing?: "idle" | "auto" | "user"
  /** Seconds without any interaction before auto-typing picks up again */
  idleDelay?: number
  /** Colour of highlighted keys */
  accentColor?: string
  /** Called with the key code (KeyboardEvent.code) of every key pressed */
  onKeyPress?: (code: string) => void
}

/* ─── Layout ────────────────────────────────────────────────────────── */

type KeyDef = {
  code: string
  /** Width in key units; every row adds up to 14.67 */
  w?: number
  /** Main legend */
  label?: React.ReactNode
  /** Second legend above the main one (shifted symbol, or a modifier glyph) */
  top?: React.ReactNode
  /** Where the legend sits on wide keys */
  align?: "left" | "right" | "corners"
  /** Spoken name, when the legend is a symbol */
  name?: string
}

const fnIcon = "size-[1.3em]"
const ROWS: KeyDef[][] = [
  [
    { code: "Escape", w: 1.67, label: "esc", align: "left" },
    { code: "F1", label: "F1", top: <SunDim className={fnIcon} /> },
    { code: "F2", label: "F2", top: <Sun className={fnIcon} /> },
    { code: "F3", label: "F3", top: <LayoutGrid className={fnIcon} /> },
    { code: "F4", label: "F4", top: <Search className={fnIcon} /> },
    { code: "F5", label: "F5", top: <Mic className={fnIcon} /> },
    { code: "F6", label: "F6", top: <Moon className={fnIcon} /> },
    { code: "F7", label: "F7", top: <Rewind className={fnIcon} /> },
    { code: "F8", label: "F8", top: <Play className={fnIcon} /> },
    { code: "F9", label: "F9", top: <FastForward className={fnIcon} /> },
    { code: "F10", label: "F10", top: <VolumeX className={fnIcon} /> },
    { code: "F11", label: "F11", top: <Volume1 className={fnIcon} /> },
    { code: "F12", label: "F12", top: <Volume2 className={fnIcon} /> },
    { code: "TouchId", name: "Touch ID" },
  ],
  [
    { code: "Backquote", label: "`", top: "~" },
    ...["!", "@", "#", "$", "%", "^", "&", "*", "(", ")"].map((top, i) => ({
      code: `Digit${(i + 1) % 10}`,
      label: String((i + 1) % 10),
      top,
    })),
    { code: "Minus", label: "-", top: "_" },
    { code: "Equal", label: "=", top: "+" },
    { code: "Backspace", w: 1.67, label: "delete", align: "right" },
  ],
  [
    { code: "Tab", w: 1.67, label: "tab", align: "left" },
    ..."QWERTYUIOP".split("").map((l) => ({ code: `Key${l}`, label: l })),
    { code: "BracketLeft", label: "[", top: "{" },
    { code: "BracketRight", label: "]", top: "}" },
    { code: "Backslash", label: "\\", top: "|" },
  ],
  [
    {
      code: "CapsLock",
      w: 1.835,
      label: "caps lock",
      top: "⇪",
      align: "corners",
    },
    ..."ASDFGHJKL".split("").map((l) => ({ code: `Key${l}`, label: l })),
    { code: "Semicolon", label: ";", top: ":" },
    { code: "Quote", label: "'", top: '"' },
    { code: "Enter", w: 1.835, label: "return", align: "right" },
  ],
  [
    { code: "ShiftLeft", w: 2.335, label: "shift", top: "⇧", align: "corners" },
    ..."ZXCVBNM".split("").map((l) => ({ code: `Key${l}`, label: l })),
    { code: "Comma", label: ",", top: "<" },
    { code: "Period", label: ".", top: ">" },
    { code: "Slash", label: "/", top: "?" },
    {
      code: "ShiftRight",
      w: 2.335,
      label: "shift",
      top: "⇧",
      align: "corners",
    },
  ],
]

/** The bottom row, with the arrow cluster */
const BOTTOM: KeyDef[] = [
  {
    code: "Fn",
    label: <Globe className={fnIcon} />,
    top: "fn",
    align: "corners",
    name: "fn",
  },
  { code: "ControlLeft", label: "control", top: "⌃", align: "corners" },
  { code: "AltLeft", label: "option", top: "⌥", align: "corners" },
  { code: "MetaLeft", w: 1.25, label: "command", top: "⌘", align: "corners" },
  { code: "Space", w: 5.17, name: "space" },
  { code: "MetaRight", w: 1.25, label: "command", top: "⌘", align: "corners" },
  { code: "AltRight", label: "option", top: "⌥", align: "corners" },
]

/** Short labels for the preview row */
const SHORT: Record<string, string> = {
  Escape: "esc",
  Backspace: "⌫",
  Tab: "⇥",
  CapsLock: "⇪",
  Enter: "↵",
  ShiftLeft: "⇧",
  ShiftRight: "⇧",
  ControlLeft: "⌃",
  ControlRight: "⌃",
  AltLeft: "⌥",
  AltRight: "⌥",
  MetaLeft: "⌘",
  MetaRight: "⌘",
  Fn: "fn",
  Space: "space",
  ArrowUp: "↑",
  ArrowDown: "↓",
  ArrowLeft: "←",
  ArrowRight: "→",
  Backquote: "`",
  Minus: "-",
  Equal: "=",
  BracketLeft: "[",
  BracketRight: "]",
  Backslash: "\\",
  Semicolon: ";",
  Quote: "'",
  Comma: ",",
  Period: ".",
  Slash: "/",
}
const shortLabel = (code: string) =>
  SHORT[code] ??
  (code.startsWith("Key")
    ? code.slice(3)
    : code.startsWith("Digit")
      ? code.slice(5)
      : code)

/** Keys that would scroll the page while someone types on the keyboard */
const SCROLL_KEYS = new Set([
  "Space",
  "ArrowUp",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
])
/** Focused elements that need those keys for themselves */
const CONTROLS =
  'input, textarea, select, button, a[href], [contenteditable=""], [contenteditable="true"], [role="slider"], [role="radio"], [role="tab"], [role="menuitem"], [role="option"], [role="combobox"]'

/** The key that types a character, for autoType */
function codeFor(char: string) {
  if (/^[a-z]$/i.test(char)) return `Key${char.toUpperCase()}`
  if (/^\d$/.test(char)) return `Digit${char}`
  const map: Record<string, string> = {
    " ": "Space",
    ",": "Comma",
    ".": "Period",
    "/": "Slash",
    "-": "Minus",
    "=": "Equal",
    ";": "Semicolon",
    "'": "Quote",
    "\n": "Enter",
  }
  return map[char] ?? null
}

/* ─── Sound ─────────────────────────────────────────────────────────── */

export type SwitchType = "tactile" | "clicky" | "linear" | "thock"
type Category = "alpha" | "function" | "arrow" | "modifier" | "large" | "space"

/** Keys sound different by kind, like a real board */
function categoryOf(code: string): Category {
  if (code === "Space") return "space"
  if (/^(Enter|Backspace|Shift|CapsLock|Tab)/.test(code)) return "large"
  if (/^(F\d+|Escape)$/.test(code)) return "function"
  if (code.startsWith("Arrow")) return "arrow"
  if (/^(Control|Alt|Meta|Fn)/.test(code)) return "modifier"
  return "alpha"
}

type Tone = { freq: number; q: number; gain: number; decay: number }
type SwitchSound = {
  /** The switch actuating */
  down: Tone
  /** The switch letting go */
  up: Tone
  /** The cap bottoming out on the plate */
  body: { pitch: number; gain: number; decay: number }
  /** Clicky switches snap twice: the click jacket, then the bottom-out */
  snap?: boolean
}

const SWITCHES: Record<SwitchType, SwitchSound> = {
  tactile: {
    down: { freq: 2400, q: 1.2, gain: 0.45, decay: 0.03 },
    up: { freq: 3800, q: 1.5, gain: 0.18, decay: 0.02 },
    body: { pitch: 200, gain: 0.32, decay: 0.07 },
  },
  clicky: {
    down: { freq: 4300, q: 3.5, gain: 1, decay: 0.022 },
    up: { freq: 4700, q: 3, gain: 0.6, decay: 0.018 },
    body: { pitch: 230, gain: 0.2, decay: 0.05 },
    snap: true,
  },
  linear: {
    down: { freq: 1800, q: 0.9, gain: 0.22, decay: 0.03 },
    up: { freq: 3000, q: 1, gain: 0.1, decay: 0.02 },
    body: { pitch: 170, gain: 0.42, decay: 0.09 },
  },
  thock: {
    down: { freq: 950, q: 0.8, gain: 0.32, decay: 0.04 },
    up: { freq: 1700, q: 0.9, gain: 0.1, decay: 0.03 },
    body: { pitch: 118, gain: 0.58, decay: 0.12 },
  },
}

/** How each kind of key colours the switch's sound */
const CATEGORIES: Record<
  Category,
  { pitch: number; gain: number; decay: number; rattle?: boolean }
> = {
  alpha: { pitch: 1, gain: 1, decay: 1 },
  function: { pitch: 1.18, gain: 0.75, decay: 0.8 },
  arrow: { pitch: 1.1, gain: 0.8, decay: 0.85 },
  modifier: { pitch: 0.92, gain: 0.9, decay: 1.05 },
  // Long keys sit on stabilisers, which add a low rattle
  large: { pitch: 0.78, gain: 1.1, decay: 1.25, rattle: true },
  space: { pitch: 0.6, gain: 1.2, decay: 1.5, rattle: true },
}

/** Where each key sits from left (-1) to right (1), for stereo */
const PAN = (() => {
  const out: Record<string, number> = {}
  const place = (row: KeyDef[], extra = 0) => {
    const total = row.reduce((sum, k) => sum + (k.w ?? 1), 0) + extra
    let x = 0
    for (const k of row) {
      const w = k.w ?? 1
      out[k.code] = ((x + w / 2) / total) * 2 - 1
      x += w
    }
  }
  ROWS.forEach((row) => place(row))
  place(BOTTOM, 3)
  Object.assign(out, {
    ArrowLeft: 0.8,
    ArrowUp: 0.87,
    ArrowDown: 0.87,
    ArrowRight: 0.94,
  })
  return out
})()

/**
 * Mechanical key sounds, synthesised with Web Audio: a filtered click for
 * the switch, a low tone for the cap bottoming out, a stabiliser rattle on
 * long keys, panned to where the key sits. Each switch type and each kind
 * of key sounds different, and no two presses are quite the same. Nothing
 * to download; audio starts only with a person's own press.
 */
function useKeySound(enabled: boolean, volume: number, type: SwitchType) {
  const ctx = React.useRef<AudioContext | null>(null)
  const noise = React.useRef<AudioBuffer | null>(null)
  React.useEffect(
    () => () => {
      void ctx.current?.close().catch(() => {})
      ctx.current = null
    },
    []
  )

  return React.useCallback(
    (code: string, phase: "down" | "up", byPerson: boolean) => {
      if (!enabled || volume <= 0 || !byPerson) return
      if (!ctx.current) {
        const audio = new AudioContext()
        const buffer = audio.createBuffer(
          1,
          audio.sampleRate * 0.1,
          audio.sampleRate
        )
        const data = buffer.getChannelData(0)
        for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1
        ctx.current = audio
        noise.current = buffer
      }
      const audio = ctx.current
      const buffer = noise.current
      if (!buffer) return
      void audio.resume().catch(() => {})

      const sw = SWITCHES[type] ?? SWITCHES.tactile
      const cat = CATEGORIES[categoryOf(code)]
      const vary = () => 0.94 + Math.random() * 0.12
      const t = audio.currentTime

      const out = audio.createGain()
      out.gain.value = Math.min(1, volume) * cat.gain * vary()
      const pan = audio.createStereoPanner()
      pan.pan.value = (PAN[code] ?? 0) * 0.6
      out.connect(pan).connect(audio.destination)

      /** A short burst of band-passed noise */
      const burst = (tone: Tone, at: number, scale = 1) => {
        const src = audio.createBufferSource()
        src.buffer = buffer
        const band = audio.createBiquadFilter()
        band.type = "bandpass"
        band.frequency.value = tone.freq * cat.pitch * vary()
        band.Q.value = tone.q
        const g = audio.createGain()
        g.gain.setValueAtTime(0.0001, at)
        g.gain.exponentialRampToValueAtTime(tone.gain * scale, at + 0.002)
        g.gain.exponentialRampToValueAtTime(0.0001, at + tone.decay * cat.decay)
        src.connect(band).connect(g).connect(out)
        src.start(at)
        src.stop(at + 0.09)
      }

      if (phase === "down") {
        burst(sw.down, t)
        if (sw.snap) burst(sw.down, t + 0.007, 0.6)
        // The cap bottoming out: a quick, falling low tone
        const body = audio.createOscillator()
        body.type = "triangle"
        const pitch = sw.body.pitch * cat.pitch * vary()
        body.frequency.setValueAtTime(pitch, t + 0.004)
        body.frequency.exponentialRampToValueAtTime(pitch * 0.55, t + 0.07)
        const g = audio.createGain()
        g.gain.setValueAtTime(0.0001, t)
        g.gain.exponentialRampToValueAtTime(sw.body.gain, t + 0.006)
        g.gain.exponentialRampToValueAtTime(
          0.0001,
          t + sw.body.decay * cat.decay
        )
        body.connect(g).connect(out)
        body.start(t)
        body.stop(t + 0.2)
      } else {
        burst(sw.up, t)
      }

      // Stabiliser wire on long keys: a low, slightly late rattle
      if (cat.rattle)
        burst(
          {
            freq: 1150,
            q: 4,
            gain: phase === "down" ? 0.16 : 0.1,
            decay: 0.05,
          },
          t + 0.012
        )
    },
    [enabled, volume, type]
  )
}

/* ─── Keys ──────────────────────────────────────────────────────────── */

const unit = (w = 1) => `calc(var(--k) * ${w} + var(--gap) * ${w - 1})`

/**
 * One key: side walls with a shadow on the case, and a cap that travels
 * down into them when pressed. Sizes are in em of one key width.
 */
function Key({
  def,
  pressed,
  glow,
  accent,
  height = "var(--k)",
  onPress,
  onRelease,
}: {
  def: KeyDef
  pressed: boolean
  glow: boolean
  accent: string
  height?: string
  onPress: (code: string) => void
  onRelease: (code: string) => void
}) {
  const reduced = useReducedMotion() ?? false
  const { code, w = 1, label, top, align, name } = def
  const spoken =
    name ?? (typeof label === "string" ? label : undefined) ?? shortLabel(code)
  const down = pressed && !reduced
  return (
    <button
      type="button"
      aria-label={spoken}
      aria-pressed={pressed}
      onPointerDown={(e) => {
        e.currentTarget.setPointerCapture(e.pointerId)
        onPress(code)
      }}
      onPointerUp={() => onRelease(code)}
      onPointerCancel={() => onRelease(code)}
      onKeyDown={(e) => {
        // Activating a focused key with the keyboard presses it too
        if ((e.key === "Enter" || e.key === " ") && !e.repeat) {
          e.preventDefault()
          e.stopPropagation()
          onPress(code)
        }
      }}
      onKeyUp={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.stopPropagation()
          onRelease(code)
        }
      }}
      className="group/key relative shrink-0 cursor-pointer rounded-[0.15em] select-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
      style={{ width: unit(w), height, fontSize: "var(--k)" }}
    >
      {/* Side walls, darker toward the front, and the shadow on the case */}
      <span
        aria-hidden="true"
        className="absolute inset-0 rounded-[inherit] transition-shadow duration-100"
        style={{
          backgroundImage:
            "linear-gradient(to bottom, var(--kb-side-top), var(--kb-side-bottom))",
          boxShadow: down
            ? "0 0.01em 0.02em rgb(0 0 0 / 0.3)"
            : "0 0.03em 0.05em rgb(0 0 0 / 0.28), 0 0.1em 0.14em -0.05em rgb(0 0 0 / 0.3)",
        }}
      />
      {/* The cap */}
      <motion.span
        className={cn(
          "absolute inset-x-[0.035em] top-[0.012em] bottom-[0.085em] flex rounded-[0.12em] p-[0.11em] leading-none text-(--kb-legend)",
          align === "left" && "items-end justify-start",
          align === "right" && "items-end justify-end",
          align === "corners" && "flex-col items-start justify-between",
          !align && "flex-col items-center justify-center gap-[0.07em]"
        )}
        style={{
          backgroundImage:
            "linear-gradient(to bottom, var(--kb-cap-top), var(--kb-cap-bottom))",
          boxShadow:
            "inset 0 0.012em 0 var(--kb-shine), inset 0 -0.025em 0.03em rgb(0 0 0 / 0.05)",
        }}
        initial={false}
        animate={{ y: down ? "0.06em" : "0em" }}
        transition={{
          type: "spring",
          stiffness: 1100,
          damping: 34,
          mass: 0.35,
        }}
      >
        {/* A highlighted key glows softly, inviting a press */}
        {glow && (
          <motion.span
            aria-hidden="true"
            className="pointer-events-none absolute inset-[-0.02em] rounded-[inherit]"
            style={{
              boxShadow: `0 0 0 0.03em ${accent}, 0 0 0.25em 0.03em color-mix(in oklab, ${accent} 55%, transparent)`,
            }}
            animate={reduced ? { opacity: 1 } : { opacity: [0.5, 1, 0.5] }}
            transition={{ duration: 1.8, ease: "easeInOut", repeat: Infinity }}
          />
        )}
        {code === "TouchId" ? (
          <span className="m-auto size-[0.6em] rounded-full bg-linear-to-b from-black/15 via-black/5 to-black/15 p-[0.02em] dark:from-white/15 dark:via-white/5 dark:to-white/15">
            <span
              className="block size-full rounded-full"
              style={{
                backgroundImage:
                  "linear-gradient(to bottom, var(--kb-cap-bottom), var(--kb-cap-top))",
              }}
            />
          </span>
        ) : (
          <>
            {top && (
              <span className="flex items-center text-[0.17em]">{top}</span>
            )}
            {label && <span className="text-[0.17em]">{label}</span>}
          </>
        )}
      </motion.span>
    </button>
  )
}

/* ─── Keyboard ──────────────────────────────────────────────────────── */

/**
 * A Mac-style keyboard you can type on: keycaps with real depth travel
 * into their walls when pressed, light up as you type on your own keyboard
 * (while it's on screen), and click with synthesised mechanical sounds:
 * pick a switch type, and long keys rattle on their stabilisers. Glow a shortcut with
 * `highlight`, let it type a phrase on its own with `autoType` (only while
 * nobody is using it, always, or never: see `typing`), or use it
 * as input with `onKeyPress`. It scales to its container.
 */
export const Keyboard = React.forwardRef<HTMLDivElement, KeyboardProps>(
  (
    {
      sound = false,
      volume = 0.6,
      switchType = "tactile",
      tilt = 0,
      listen = true,
      showPreview = false,
      highlight = [],
      autoType,
      typing = "idle",
      idleDelay = 4,
      accentColor = "#6366f1",
      onKeyPress,
      className,
      ...props
    },
    ref
  ) => {
    const box = React.useRef<HTMLDivElement>(null)
    const onScreen = useInView(box, { amount: 0.3 })
    const reduced = useReducedMotion() ?? false
    const play = useKeySound(sound, volume, switchType)
    const [pressed, setPressed] = React.useState<Set<string>>(new Set())
    const [recent, setRecent] = React.useState<{ id: number; code: string }[]>(
      []
    )
    const nextId = React.useRef(0)
    const lastHuman = React.useRef(0)
    const glowing = new Set(highlight)

    const press = React.useCallback(
      (code: string, human = true) => {
        if (human) lastHuman.current = Date.now()
        setPressed((p) => (p.has(code) ? p : new Set(p).add(code)))
        if (code === "TouchId") return
        play(code, "down", human)
        onKeyPress?.(code)
        setRecent((r) => [...r, { id: nextId.current++, code }].slice(-8))
      },
      [play, onKeyPress]
    )
    const release = React.useCallback(
      (code: string, human = true) => {
        setPressed((p) => {
          if (!p.has(code)) return p
          const next = new Set(p)
          next.delete(code)
          return next
        })
        if (code !== "TouchId") play(code, "up", human)
      },
      [play]
    )

    // Real typing lights the keys up, but only while the keyboard is seen
    React.useEffect(() => {
      if (!listen || !onScreen) return
      const down = (e: KeyboardEvent) => {
        if (!e.code) return
        // Typing on the keyboard shouldn't scroll the page. Focused fields,
        // buttons and sliders still get their keys as usual
        const target = e.target instanceof Element ? e.target : null
        const control = target?.closest(CONTROLS)
        if (
          SCROLL_KEYS.has(e.code) &&
          !e.metaKey &&
          !e.ctrlKey &&
          !e.altKey &&
          (!control || box.current?.contains(control))
        )
          e.preventDefault()
        if (e.repeat) return
        press(e.code)
      }
      const up = (e: KeyboardEvent) => release(e.code)
      const clear = () => setPressed(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)
      }
    }, [listen, onScreen, press, release])

    // Typing a phrase by itself: always ("auto"), or only while nobody is
    // using the keyboard ("idle"). In "user" mode only the visitor types
    React.useEffect(() => {
      if (!autoType || typing === "user" || !onScreen || reduced) return
      const codes = autoType.split("").map(codeFor)
      let i = 0
      let timer = 0
      const step = () => {
        // Hand over to the visitor until they've left it alone for a while,
        // then start the phrase again from the top
        if (
          typing === "idle" &&
          Date.now() - lastHuman.current < idleDelay * 1000
        ) {
          i = 0
          timer = window.setTimeout(step, 400)
          return
        }
        const code = codes[i]
        i = (i + 1) % codes.length
        if (code) {
          press(code, false)
          window.setTimeout(() => release(code, false), 110)
        }
        const pause = i === 0 ? 1800 : autoType[i - 1] === " " ? 260 : 160
        timer = window.setTimeout(step, pause + Math.random() * 80)
      }
      timer = window.setTimeout(step, 600)
      return () => window.clearTimeout(timer)
    }, [autoType, typing, idleDelay, onScreen, reduced, press, release])

    const key = (def: KeyDef, height?: string) => (
      <Key
        key={def.code}
        def={def}
        height={height}
        pressed={pressed.has(def.code)}
        glow={glowing.has(def.code)}
        accent={accentColor}
        onPress={press}
        onRelease={(code) => release(code)}
      />
    )
    const half = "calc((var(--k) - var(--gap)) / 2)"

    return (
      <div
        ref={(el) => {
          box.current = el
          if (typeof ref === "function") ref(el)
          else if (ref) ref.current = el
        }}
        className={cn("@container mx-auto w-full max-w-3xl", className)}
        {...props}
        onPointerMove={(e) => {
          // Hovering counts as using the keyboard, so auto-typing waits
          lastHuman.current = Date.now()
          props.onPointerMove?.(e)
        }}
      >
        {showPreview && (
          <div
            aria-live="polite"
            className="mb-4 flex h-8 items-center justify-center gap-1.5 overflow-hidden"
          >
            <AnimatePresence mode="popLayout" initial={false}>
              {recent.slice(-6).map(({ id, code }) => (
                <motion.kbd
                  key={id}
                  layout
                  initial={{ opacity: 0, y: 10, scale: 0.8 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: -8, scale: 0.8 }}
                  transition={{ type: "spring", stiffness: 500, damping: 32 }}
                  className="min-w-8 rounded-md bg-card px-2 py-1 text-center font-sans text-xs font-medium text-foreground shadow-[0_0_0_0.5px_rgb(0_0_0/0.3),0_1px_2px_rgb(0_0_0/0.12)]"
                >
                  {shortLabel(code)}
                </motion.kbd>
              ))}
            </AnimatePresence>
          </div>
        )}

        <div
          role="group"
          aria-label="Keyboard"
          className={cn(
            "mx-auto flex w-fit flex-col rounded-[calc(var(--k)*0.38)]",
            // Keycap and case colours, for light and dark themes
            "[--kb-cap-bottom:#f2f2f4] [--kb-cap-top:#ffffff] [--kb-legend:#52525b] [--kb-shine:rgb(255_255_255)] [--kb-side-bottom:#b9b9c0] [--kb-side-top:#dcdce0]",
            "dark:[--kb-cap-bottom:#2c2c31] dark:[--kb-cap-top:#3a3a40] dark:[--kb-legend:#d4d4d8] dark:[--kb-shine:rgb(255_255_255/0.09)] dark:[--kb-side-bottom:#0b0b0d] dark:[--kb-side-top:#1d1d21]",
            // Brushed aluminium: a soft gradient, a bevelled edge, a shadow
            "bg-linear-to-b from-[#ececef] to-[#d7d7dc] shadow-[inset_0_1px_0_rgb(255_255_255/0.9),inset_0_-1px_0_rgb(0_0_0/0.08),0_0_0_1px_rgb(0_0_0/0.07),0_2px_4px_rgb(0_0_0/0.06),0_30px_60px_-30px_rgb(0_0_0/0.35)]",
            "dark:from-[#2b2b30] dark:to-[#1b1b1f] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.08),inset_0_-1px_0_rgb(0_0_0/0.4),0_0_0_1px_rgb(0_0_0/0.6),0_30px_60px_-30px_rgb(0_0_0/0.8)]"
          )}
          style={
            {
              // One key is 1/16.26 of the width: 14.67 keys, their gaps
              // and the padding fill it exactly
              "--k": "calc(100cqw / 16.26)",
              "--gap": "calc(var(--k) * 0.08)",
              gap: "var(--gap)",
              padding: "calc(var(--k) * 0.25)",
              transform: tilt
                ? `perspective(1400px) rotateX(${tilt}deg)`
                : undefined,
              transformOrigin: "50% 100%",
            } as React.CSSProperties
          }
        >
          {ROWS.map((row, r) => (
            <div key={r} className="flex" style={{ gap: "var(--gap)" }}>
              {row.map((def) => key(def))}
            </div>
          ))}
          <div className="flex items-end" style={{ gap: "var(--gap)" }}>
            {BOTTOM.map((def) => key(def))}
            {/* Arrows: left and right full height, up and down halves */}
            {key({ code: "ArrowLeft", label: "◀", name: "left" })}
            <div className="flex flex-col" style={{ gap: "var(--gap)" }}>
              {key({ code: "ArrowUp", label: "▲", name: "up" }, half)}
              {key({ code: "ArrowDown", label: "▼", name: "down" }, half)}
            </div>
            {key({ code: "ArrowRight", label: "▶", name: "right" })}
          </div>
        </div>
      </div>
    )
  }
)
Keyboard.displayName = "Keyboard"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `sound` | `boolean` | `false` | No | Mechanical key sounds, made in the browser. They start after the visitor's first press. |
| `volume` | `number` | `0.6` | No | Loudness of the sounds, from 0 to 1. |
| `switchType` | `"tactile" \| "clicky" \| "linear" \| "thock"` | `"tactile"` | No | How the switches sound: tactile (a soft bump), clicky (a sharp snap), linear (quiet and smooth) or thock (deep and muted). Each kind of key sounds a little different, and long keys rattle on their stabilisers. |
| `tilt` | `number` | `0` | No | Tilt the keyboard back, in degrees, as if it sat on a desk. |
| `listen` | `boolean` | `true` | No | Light up keys as they're typed on a real keyboard, while the keyboard is on screen. |
| `showPreview` | `boolean` | `false` | No | A row of the last keys pressed, above the keyboard. |
| `highlight` | `string[]` | `[]` | No | Key codes to glow, such as a shortcut: ["MetaLeft", "KeyK"]. Uses KeyboardEvent.code names. |
| `autoType` | `string` | - | No | A phrase the keyboard can type by itself. When it types depends on typing. |
| `typing` | `"idle" \| "auto" \| "user"` | `"idle"` | No | Who types. idle: the keyboard types autoType while nobody is using it, and hands over the moment someone hovers or types. auto: it keeps typing whatever the visitor does. user: only the visitor types; auto-typing is off. |
| `idleDelay` | `number` | `4` | No | Seconds without any interaction before auto-typing picks up again (idle mode). |
| `accentColor` | `string` | `"#6366f1"` | No | Colour of highlighted keys. |
| `onKeyPress` | `(code: string) => void` | - | No | Called with the key code of every key pressed, so it can work as an input. |
| `className` | `string` | - | No | Extra classes for the wrapper; set a max width to size it. |

## Usage
```tsx
"use client"

import { Keyboard } from "@/components/ui/keyboard"

export default function KeyboardDemo() {
  return (
    <div className="flex w-full flex-col items-center gap-4 py-8">
      <Keyboard
        sound
        showPreview
        autoType="type here to hear it click"
      />
      <p className="text-sm text-muted-foreground">
        Type, or click the keys. Sound starts after your first press.
      </p>
    </div>
  )
}

```
