{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "mech-keyboard",
  "title": "Mech Keyboard",
  "description": "A 75% mechanical keyboard drawn as an isometric illustration in three.js, with ink outlines and a volume knob. Keys press along with your real keyboard, and a recorder spells out the shortcut for onboarding flows.",
  "dependencies": [
    "three"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "files": [
    {
      "path": "registry/mech-keyboard/mech-keyboard.tsx",
      "content": "\"use client\"\n\nimport {\n  Fragment,\n  useEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type CSSProperties,\n} from \"react\"\nimport { cn } from \"@/lib/utils\"\nimport {\n  AmbientLight,\n  BoxGeometry,\n  BufferGeometry,\n  CanvasTexture,\n  Color,\n  DataTexture,\n  DepthTexture,\n  DirectionalLight,\n  ExtrudeGeometry,\n  Float32BufferAttribute,\n  Group,\n  HalfFloatType,\n  LatheGeometry,\n  Mesh,\n  MeshBasicMaterial,\n  MeshNormalMaterial,\n  MeshToonMaterial,\n  NearestFilter,\n  NoBlending,\n  OrthographicCamera,\n  Path,\n  PlaneGeometry,\n  Raycaster,\n  RedFormat,\n  Scene,\n  ShaderMaterial,\n  Shape,\n  ShapeGeometry,\n  SRGBColorSpace,\n  Vector2,\n  Vector3,\n  WebGLRenderer,\n  WebGLRenderTarget,\n  type Material,\n  type Texture,\n} from \"three\"\n\n/**\n * A 75% mechanical keyboard drawn as an isometric illustration with\n * three.js: a milled case around a recessed plate, a volume knob, and 82\n * keycaps, shaded in three flat tone bands and outlined in ink traced from\n * depth and normals. Keys spring down under the real keyboard; chords are\n * recorded for a shortcut step in onboarding.\n *\n * Units are keys: 1 = one 1u keycap pitch. The desk is the XZ plane, y up,\n * +z toward the viewer.\n */\n\nexport type MechKeyboardPlatform = \"mac\" | \"pc\"\n\nexport type MechKeyboardKey = {\n  /** `KeyboardEvent.code` of the key, or `\"Fn\"` */\n  id: string\n  /** Legend, as printed */\n  label: string\n  /** Shifted legend, printed after the label (`\"1 !\"`) */\n  sub?: string\n  /** Position from the top left of the plate and width, in key units */\n  x: number\n  y: number\n  w: number\n  /** Row: 0 is the function row */\n  row: number\n}\n\nexport type MechKeyboardShortcut = {\n  /** `KeyboardEvent.code`s, modifiers first */\n  codes: string[]\n  /** Display legends, one per key: `[\"⌘\", \"⇧\", \"K\"]` */\n  keys: string[]\n  /** `\"⌘⇧K\"` on Mac, `\"Ctrl+Shift+K\"` elsewhere */\n  label: string\n}\n\nexport type MechKeyboardChordPhase = \"idle\" | \"live\" | \"done\"\n\nexport type MechKeyboardOptions = {\n  /** Offsets in px; +y is down. Default 0. */\n  x?: number\n  y?: number\n  /** Multiplies the fitted size. Default 1. */\n  scale?: number\n  /** Ink and greys only; no blue caps. Default false. */\n  monochrome?: boolean\n  /** Real key presses and clicks drive the keys. Default true. */\n  interactive?: boolean\n  /** Synthesized switch sounds. Default false. */\n  sound?: boolean\n  /** The keyboard rises into place and a wave runs across the keys. Default true. */\n  intro?: boolean\n  /** Codes to pulse. */\n  highlight?: string[]\n  /** Bottom-row legends and shortcut labels. Default: detected. */\n  platform?: MechKeyboardPlatform\n  /** Leave room at the top for the recorder. Default false. */\n  recorder?: boolean\n  onKey?: (code: string, pressed: boolean) => void\n  /** Fires when every key of a chord is released. */\n  onShortcut?: (shortcut: MechKeyboardShortcut) => void\n  /** Live chord for the recorder. */\n  onChord?: (codes: string[], phase: MechKeyboardChordPhase) => void\n}\n\nexport type MechKeyboardInstance = {\n  setOptions: (next: Partial<MechKeyboardOptions>) => void\n  /** Plays the intro again. */\n  replay: () => void\n  destroy: () => void\n}\n\nexport const DEFAULT_PLACEHOLDER = \"Press a shortcut\"\n\n/* ------------------------------------------------------------------ */\n/* Palette                                                             */\n/* ------------------------------------------------------------------ */\n\ntype Palette = {\n  case: string\n  plate: string\n  /** Caps fade from the back left to the front right. */\n  capBack: string\n  capFront: string\n  knob: string\n  /** Recorder keycaps: top face and skirt */\n  chip: string\n  chipSide: string\n}\n\n/** Outlines, legends, and the knob's notch. */\nconst INK = \"#2B3442\"\nconst HIGHLIGHT = \"#7E9BBA\"\n\nconst FROST: Palette = {\n  case: \"#E6E7E9\",\n  plate: \"#8E96A3\",\n  capBack: \"#AFC3D7\",\n  capFront: \"#F1F2F4\",\n  knob: \"#E2E4E7\",\n  chip: \"#E9EEF4\",\n  chipSide: \"#AFC3D7\",\n}\n\nconst MONO: Palette = {\n  case: \"#F2F2F3\",\n  plate: \"#A3A6AC\",\n  capBack: \"#FAFAFA\",\n  capFront: \"#FAFAFA\",\n  knob: \"#F2F2F3\",\n  chip: \"#FAFAFA\",\n  chipSide: \"#CDD0D5\",\n}\n\nconst paletteFor = (monochrome: boolean) => (monochrome ? MONO : FROST)\n\n/** CSS variables the recorder keycaps read. */\nexport function recorderVars(monochrome = false) {\n  const p = paletteFor(monochrome)\n  return { \"--chip\": p.chip, \"--chip-side\": p.chipSide, \"--ink\": INK }\n}\n\n/* ------------------------------------------------------------------ */\n/* Layout                                                              */\n/* ------------------------------------------------------------------ */\n\nconst COLS = 16\n/** The function row, a quarter-unit gap, then five rows. */\nconst LAYOUT_D = 6.25\nconst KNOB_ID = \"AudioVolumeMute\"\n\ntype Spec = [id: string, w: number, label?: string, sub?: string]\n\nconst GAP_KEY = \"__gap\"\n\nconst gap = (w: number): Spec => [GAP_KEY, w]\nconst letters = (s: string): Spec[] => s.split(\"\").map((c) => [`Key${c}`, 1, c])\nconst fkeys = (from: number): Spec[] =>\n  [0, 1, 2, 3].map((i) => [`F${from + i}`, 1, `F${from + i}`])\n\nfunction rows(platform: MechKeyboardPlatform): Spec[][] {\n  const mac = platform === \"mac\"\n  const bottom: Spec[] = mac\n    ? [\n        [\"ControlLeft\", 1.25, \"Control\"],\n        [\"AltLeft\", 1.25, \"Option\"],\n        [\"MetaLeft\", 1.25, \"Command\"],\n        [\"Space\", 6.25, \"\"],\n        [\"MetaRight\", 1, \"⌘\"],\n        [\"AltRight\", 1, \"⌥\"],\n        [\"Fn\", 1, \"Fn\"],\n      ]\n    : [\n        [\"ControlLeft\", 1.25, \"Ctrl\"],\n        [\"MetaLeft\", 1.25, \"Win\"],\n        [\"AltLeft\", 1.25, \"Alt\"],\n        [\"Space\", 6.25, \"\"],\n        [\"AltRight\", 1, \"Alt\"],\n        [\"Fn\", 1, \"Fn\"],\n        [\"ControlRight\", 1, \"Ctrl\"],\n      ]\n  return [\n    [\n      [\"Escape\", 1, \"Esc\"],\n      gap(0.25),\n      ...fkeys(1),\n      gap(0.25),\n      ...fkeys(5),\n      gap(0.25),\n      ...fkeys(9),\n      gap(0.25),\n      [\"Delete\", 1, \"Del\"],\n    ],\n    [\n      [\"Backquote\", 1, \"`\", \"~\"],\n      [\"Digit1\", 1, \"1\", \"!\"],\n      [\"Digit2\", 1, \"2\", \"@\"],\n      [\"Digit3\", 1, \"3\", \"#\"],\n      [\"Digit4\", 1, \"4\", \"$\"],\n      [\"Digit5\", 1, \"5\", \"%\"],\n      [\"Digit6\", 1, \"6\", \"^\"],\n      [\"Digit7\", 1, \"7\", \"&\"],\n      [\"Digit8\", 1, \"8\", \"*\"],\n      [\"Digit9\", 1, \"9\", \"(\"],\n      [\"Digit0\", 1, \"0\", \")\"],\n      [\"Minus\", 1, \"-\", \"_\"],\n      [\"Equal\", 1, \"=\", \"+\"],\n      [\"Backspace\", 2, \"Backspace\"],\n      [\"Home\", 1, \"Home\"],\n    ],\n    [\n      [\"Tab\", 1.5, \"Tab\"],\n      ...letters(\"QWERTYUIOP\"),\n      [\"BracketLeft\", 1, \"[\", \"{\"],\n      [\"BracketRight\", 1, \"]\", \"}\"],\n      [\"Backslash\", 1.5, \"\\\\\", \"|\"],\n      [\"PageUp\", 1, \"PgUp\"],\n    ],\n    [\n      [\"CapsLock\", 1.75, \"Caps\"],\n      ...letters(\"ASDFGHJKL\"),\n      [\"Semicolon\", 1, \";\", \":\"],\n      [\"Quote\", 1, \"'\", '\"'],\n      [\"Enter\", 2.25, \"Enter\"],\n      [\"PageDown\", 1, \"PgDn\"],\n    ],\n    [\n      [\"ShiftLeft\", 2.25, \"Shift\"],\n      ...letters(\"ZXCVBNM\"),\n      [\"Comma\", 1, \",\", \"<\"],\n      [\"Period\", 1, \".\", \">\"],\n      [\"Slash\", 1, \"/\", \"?\"],\n      [\"ShiftRight\", 1.75, \"Shift\"],\n      [\"ArrowUp\", 1, \"↑\"],\n      [\"End\", 1, \"End\"],\n    ],\n    [\n      ...bottom,\n      [\"ArrowLeft\", 1, \"←\"],\n      [\"ArrowDown\", 1, \"↓\"],\n      [\"ArrowRight\", 1, \"→\"],\n    ],\n  ]\n}\n\n/** The 82 keys of a 75% board, Mac or PC bottom row. */\nexport function buildLayout(platform: MechKeyboardPlatform): MechKeyboardKey[] {\n  const keys: MechKeyboardKey[] = []\n  rows(platform).forEach((row, r) => {\n    const y = r === 0 ? 0 : r + 0.25\n    let x = 0\n    for (const [id, w, label = \"\", sub] of row) {\n      if (id !== GAP_KEY) keys.push({ id, label, sub, x, y, w, row: r })\n      x += w\n    }\n  })\n  return keys\n}\n\n/* ------------------------------------------------------------------ */\n/* Codes, labels, shortcuts                                            */\n/* ------------------------------------------------------------------ */\n\nexport function detectPlatform(): MechKeyboardPlatform {\n  if (typeof navigator === \"undefined\") return \"pc\"\n  const nav = navigator as Navigator & {\n    userAgentData?: { platform?: string }\n  }\n  const name = nav.userAgentData?.platform || nav.platform || nav.userAgent\n  return /mac|iphone|ipad|ipod/i.test(name) ? \"mac\" : \"pc\"\n}\n\nconst MODIFIER_ORDER: Record<MechKeyboardPlatform, string[]> = {\n  mac: [\"Control\", \"Alt\", \"Shift\", \"Meta\", \"Fn\"],\n  pc: [\"Control\", \"Meta\", \"Alt\", \"Shift\", \"Fn\"],\n}\n\n/** `\"ShiftLeft\"` → `\"Shift\"`; anything else → undefined. */\nexport function modifierOf(code: string) {\n  if (code === \"Fn\") return \"Fn\"\n  const match = /^(Control|Alt|Shift|Meta|OS)(Left|Right)$/.exec(code)\n  if (!match) return undefined\n  return match[1] === \"OS\" ? \"Meta\" : match[1]\n}\n\nconst MAC_LABELS: Record<string, string> = {\n  Control: \"⌃\",\n  Alt: \"⌥\",\n  Shift: \"⇧\",\n  Meta: \"⌘\",\n  Fn: \"fn\",\n  Escape: \"esc\",\n  Tab: \"⇥\",\n  CapsLock: \"⇪\",\n  Enter: \"↩\",\n  Backspace: \"⌫\",\n  Delete: \"⌦\",\n  Space: \"Space\",\n}\n\nconst PC_LABELS: Record<string, string> = {\n  Control: \"Ctrl\",\n  Alt: \"Alt\",\n  Shift: \"Shift\",\n  Meta: \"Win\",\n  Fn: \"Fn\",\n  Escape: \"Esc\",\n  Tab: \"Tab\",\n  CapsLock: \"Caps\",\n  Enter: \"Enter\",\n  Backspace: \"Backspace\",\n  Delete: \"Del\",\n  Space: \"Space\",\n}\n\nconst SHARED_LABELS: Record<string, string> = {\n  ArrowUp: \"↑\",\n  ArrowDown: \"↓\",\n  ArrowLeft: \"←\",\n  ArrowRight: \"→\",\n  PageUp: \"PgUp\",\n  PageDown: \"PgDn\",\n  Home: \"Home\",\n  End: \"End\",\n  Insert: \"Ins\",\n  Minus: \"-\",\n  Equal: \"=\",\n  BracketLeft: \"[\",\n  BracketRight: \"]\",\n  Backslash: \"\\\\\",\n  IntlBackslash: \"\\\\\",\n  Semicolon: \";\",\n  Quote: \"'\",\n  Comma: \",\",\n  Period: \".\",\n  Slash: \"/\",\n  Backquote: \"`\",\n  NumpadEnter: \"Enter\",\n  AudioVolumeMute: \"Mute\",\n  AudioVolumeUp: \"Vol +\",\n  AudioVolumeDown: \"Vol −\",\n}\n\n/** One legend for a `KeyboardEvent.code`. */\nexport function keyLabel(code: string, platform: MechKeyboardPlatform) {\n  const table = platform === \"mac\" ? MAC_LABELS : PC_LABELS\n  const name = modifierOf(code) ?? code\n  if (table[name]) return table[name]\n  if (SHARED_LABELS[name]) return SHARED_LABELS[name]\n  const match = /^(?:Key|Digit|Numpad)(.+)$/.exec(name)\n  if (match) return match[1]!\n  return name\n}\n\n/** Modifiers first in platform order (one per kind), then keys as pressed. */\nexport function formatShortcut(\n  codes: string[],\n  platform: MechKeyboardPlatform\n): MechKeyboardShortcut {\n  const order = MODIFIER_ORDER[platform]\n  const mods = new Map<string, string>()\n  const rest: string[] = []\n  for (const code of codes) {\n    const mod = modifierOf(code)\n    if (mod) {\n      if (!mods.has(mod)) mods.set(mod, code)\n    } else if (!rest.includes(code)) {\n      rest.push(code)\n    }\n  }\n  const sorted = [\n    ...order.filter((m) => mods.has(m)).map((m) => mods.get(m)!),\n    ...rest,\n  ]\n  const keys = sorted.map((code) => keyLabel(code, platform))\n  return {\n    codes: sorted,\n    keys,\n    label: platform === \"mac\" ? keys.join(\"\") : keys.join(\"+\"),\n  }\n}\n\nconst ALIASES: Record<string, string[]> = {\n  Insert: [\"Delete\"],\n  NumpadEnter: [\"Enter\"],\n  IntlBackslash: [\"Backslash\"],\n  OSLeft: [\"MetaLeft\"],\n  OSRight: [\"MetaRight\"],\n  NumpadDecimal: [\"Period\"],\n  NumpadDivide: [\"Slash\"],\n  NumpadSubtract: [\"Minus\"],\n  NumpadAdd: [\"Equal\"],\n  AudioVolumeUp: [],\n  AudioVolumeDown: [],\n}\n\n/** Which keycaps a code moves. */\nfunction capsFor(code: string): string[] {\n  const pad = /^Numpad(\\d)$/.exec(code)\n  if (pad) return [`Digit${pad[1]}`]\n  return ALIASES[code] ?? [code]\n}\n\n/* ------------------------------------------------------------------ */\n/* Geometry                                                            */\n/* ------------------------------------------------------------------ */\n\nconst DEG = Math.PI / 180\n/** True isometric: the desk turned 45° and seen from 35.26° up. */\nconst ISO_TILT = 35.26 * DEG\nconst ISO_TURN = 45 * DEG\n/** Bezel around the plate */\nconst BEZEL = 0.48\nconst W = COLS + BEZEL * 2\nconst D = LAYOUT_D + BEZEL * 2\n/** Case height at the front; the back rises by RISE (typing angle). */\nconst CASE_H = 0.95\nconst RISE = 0.4\nconst TILT = Math.atan2(RISE, D)\n/** Bezel top down to the top of the plate */\nconst WELL = 0.5\n/** Gap around a cap in its cell, switch height under the cap, key travel */\nconst GAP = 0.035\nconst SWITCH = 0.12\nconst TRAVEL = 0.16\n/** Keycap: height, skirt taper, top edge radius, corner radius */\nconst CAP_H = 0.5\nconst CAP_TAPER = 0.07\nconst CAP_EDGE = 0.018\nconst CAP_RADIUS = 0.1\n\nfunction roundedRect<T extends Path>(path: T, w: number, h: number, r: number) {\n  const x = -w / 2\n  const y = -h / 2\n  path.moveTo(x + r, y)\n  path.lineTo(x + w - r, y)\n  path.quadraticCurveTo(x + w, y, x + w, y + r)\n  path.lineTo(x + w, y + h - r)\n  path.quadraticCurveTo(x + w, y + h, x + w - r, y + h)\n  path.lineTo(x + r, y + h)\n  path.quadraticCurveTo(x, y + h, x, y + h - r)\n  path.lineTo(x, y + r)\n  path.quadraticCurveTo(x, y, x + r, y)\n  return path\n}\n\n/**\n * The milled frame around the well: extruded with one-segment bevels, so\n * every edge is a flat chamfer the ink can trace, then sheared into a\n * wedge.\n */\nfunction caseGeometry() {\n  const chamfer = 0.05\n  const outer = roundedRect(new Shape(), W - chamfer * 2, D - chamfer * 2, 0.16)\n  outer.holes.push(\n    roundedRect(\n      new Path(),\n      COLS + 0.12 + chamfer * 2,\n      LAYOUT_D + 0.12 + chamfer * 2,\n      0.06\n    )\n  )\n  const geometry = new ExtrudeGeometry(outer, {\n    depth: CASE_H - chamfer * 2,\n    bevelEnabled: true,\n    bevelThickness: chamfer,\n    bevelSize: chamfer,\n    bevelSegments: 1,\n    curveSegments: 8,\n  })\n  geometry.rotateX(-Math.PI / 2)\n  geometry.translate(0, chamfer, 0)\n  const pos = geometry.attributes.position!\n  for (let i = 0; i < pos.count; i++) {\n    const y = pos.getY(i)\n    const back = Math.min(1, Math.max(0, (D / 2 - pos.getZ(i)) / D))\n    pos.setY(i, y + back * RISE * Math.min(1, Math.max(0, y / CASE_H)))\n  }\n  geometry.computeVertexNormals()\n  return geometry\n}\n\n/** Top of the bezel at depth z (0 is the middle). */\nconst bezelTop = (z: number) => CASE_H + ((D / 2 - z) / D) * RISE\n\n/** Points around a rounded rectangle, back right corner first. */\nfunction ring(hw: number, hd: number, r: number, seg: number) {\n  const out: Array<[number, number]> = []\n  const corners: Array<[number, number, number]> = [\n    [hw - r, -(hd - r), -90],\n    [hw - r, hd - r, 0],\n    [-(hw - r), hd - r, 90],\n    [-(hw - r), -(hd - r), 180],\n  ]\n  for (const [cx, cz, a0] of corners) {\n    for (let i = 0; i <= seg; i++) {\n      const a = (a0 + (90 * i) / seg) * DEG\n      out.push([cx + Math.cos(a) * r, cz + Math.sin(a) * r])\n    }\n  }\n  return out\n}\n\n/**\n * A keycap as one smooth surface: a tapered skirt and a crisp top edge.\n * UVs are a projection from above over the footprint, so a canvas the size\n * of the footprint prints its legend onto the top.\n */\nfunction capGeometry(w: number) {\n  const fw = w - GAP * 2\n  const fd = 1 - GAP * 2\n  const profile: Array<[inset: number, y: number]> = []\n  for (let i = 0; i <= 2; i++) {\n    const t = i / 2\n    profile.push([CAP_TAPER * t, (CAP_H - CAP_EDGE) * t])\n  }\n  for (let i = 1; i <= 3; i++) {\n    const a = (i / 3) * (Math.PI / 2)\n    profile.push([\n      CAP_TAPER + CAP_EDGE * (1 - Math.cos(a)),\n      CAP_H - CAP_EDGE + CAP_EDGE * Math.sin(a),\n    ])\n  }\n\n  const rings: Array<Array<[number, number, number]>> = []\n  for (const [inset, y] of profile) {\n    const r = Math.max(0.03, CAP_RADIUS - inset * 0.35)\n    rings.push(\n      ring(fw / 2 - inset, fd / 2 - inset, r, 5).map(([x, z]) => [x, y, z])\n    )\n  }\n  const top = rings[rings.length - 1]!\n  for (const s of [0.5]) rings.push(top.map(([x, y, z]) => [x * s, y, z * s]))\n\n  const positions: number[] = []\n  const uvs: number[] = []\n  for (const points of rings) {\n    for (const [x, y, z] of points) {\n      positions.push(x, y, z)\n      uvs.push(0.5 + x / fw, 0.5 - z / fd)\n    }\n  }\n  positions.push(0, CAP_H, 0)\n  uvs.push(0.5, 0.5)\n\n  const n = top.length\n  const index: number[] = []\n  for (let i = 0; i < rings.length - 1; i++) {\n    for (let j = 0; j < n; j++) {\n      const a = i * n + j\n      const b = i * n + ((j + 1) % n)\n      const c = (i + 1) * n + j\n      const d = (i + 1) * n + ((j + 1) % n)\n      index.push(a, c, b, b, c, d)\n    }\n  }\n  const center = rings.length * n\n  const last = (rings.length - 1) * n\n  for (let j = 0; j < n; j++) {\n    index.push(last + j, center, last + ((j + 1) % n))\n  }\n\n  const geometry = new BufferGeometry()\n  geometry.setAttribute(\"position\", new Float32BufferAttribute(positions, 3))\n  geometry.setAttribute(\"uv\", new Float32BufferAttribute(uvs, 2))\n  geometry.setIndex(index)\n  geometry.computeVertexNormals()\n  return geometry\n}\n\n/** The volume knob, turned on a lathe. */\nfunction knobGeometry() {\n  const r = 0.4\n  const h = 0.62\n  const points = [\n    new Vector2(0, 0),\n    new Vector2(r - 0.02, 0),\n    new Vector2(r, 0.02),\n    new Vector2(r, h - 0.03),\n    new Vector2(r - 0.03, h),\n    new Vector2(0, h),\n  ]\n  return new LatheGeometry(points, 64)\n}\n\n/* ------------------------------------------------------------------ */\n/* Textures                                                            */\n/* ------------------------------------------------------------------ */\n\nfunction canvas(w: number, h: number) {\n  const el = document.createElement(\"canvas\")\n  el.width = w\n  el.height = h\n  return [el, el.getContext(\"2d\")!] as const\n}\n\n/** Three flat tone bands. */\nfunction rampTexture() {\n  const texture = new DataTexture(\n    new Uint8Array([120, 196, 255]),\n    3,\n    1,\n    RedFormat\n  )\n  texture.minFilter = NearestFilter\n  texture.magFilter = NearestFilter\n  texture.generateMipmaps = false\n  texture.needsUpdate = true\n  return texture\n}\n\nconst LEGEND_PX = 256\n\n/** Arrow legends, as the angle of a right-pointing arrow. */\nconst ARROWS: Record<string, number> = {\n  \"→\": 0,\n  \"↓\": Math.PI / 2,\n  \"←\": Math.PI,\n  \"↑\": -Math.PI / 2,\n}\n\n/** The cap's color with its legend in ink, like the outlines. */\nfunction capTexture(key: MechKeyboardKey, color: string, font: string) {\n  const fw = key.w - GAP * 2\n  const fd = 1 - GAP * 2\n  const [el, ctx] = canvas(\n    Math.round(fw * LEGEND_PX),\n    Math.round(fd * LEGEND_PX)\n  )\n  ctx.fillStyle = color\n  ctx.fillRect(0, 0, el.width, el.height)\n  ctx.fillStyle = INK\n  ctx.strokeStyle = INK\n  const cx = el.width / 2\n  const cy = el.height * 0.47\n  const arrow = ARROWS[key.label]\n  if (arrow !== undefined) {\n    // Drawn, not typed: plenty of UI fonts have no ← or →.\n    const len = 0.17 * LEGEND_PX\n    ctx.save()\n    ctx.translate(cx, cy)\n    ctx.rotate(arrow)\n    ctx.lineWidth = 0.02 * LEGEND_PX\n    ctx.lineCap = \"round\"\n    ctx.lineJoin = \"round\"\n    ctx.beginPath()\n    ctx.moveTo(-len / 2, 0)\n    ctx.lineTo(len / 2, 0)\n    ctx.moveTo(len / 2 - len * 0.32, -len * 0.3)\n    ctx.lineTo(len / 2, 0)\n    ctx.lineTo(len / 2 - len * 0.32, len * 0.3)\n    ctx.stroke()\n    ctx.restore()\n  } else {\n    const single = [...key.label].length === 1 && !key.sub\n    const text = key.sub\n      ? `${key.label} ${key.sub}`\n      : single\n        ? key.label\n        : key.label.toUpperCase()\n    const size = single ? 0.22 : key.sub ? 0.17 : 0.125\n    ctx.font = `600 ${size * LEGEND_PX}px ${font}`\n    ctx.textAlign = \"center\"\n    ctx.textBaseline = \"middle\"\n    if (!single) ctx.letterSpacing = `${0.014 * LEGEND_PX}px`\n    ctx.fillText(text, cx, cy)\n  }\n  const texture = new CanvasTexture(el)\n  texture.colorSpace = SRGBColorSpace\n  texture.anisotropy = 8\n  return texture\n}\n\n/* ------------------------------------------------------------------ */\n/* Sound                                                               */\n/* ------------------------------------------------------------------ */\n\nfunction createThock() {\n  let audio: AudioContext | null = null\n  let noise: AudioBuffer | null = null\n  let master: GainNode | null = null\n  return {\n    play(code: string, down: boolean) {\n      try {\n        if (!audio) {\n          const Ctx =\n            window.AudioContext ||\n            (window as unknown as { webkitAudioContext: typeof AudioContext })\n              .webkitAudioContext\n          audio = new Ctx()\n          master = audio.createGain()\n          master.gain.value = 0.55\n          master.connect(audio.destination)\n          noise = audio.createBuffer(\n            1,\n            Math.floor(audio.sampleRate * 0.06),\n            audio.sampleRate\n          )\n          const data = noise.getChannelData(0)\n          for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1\n        }\n        if (audio.state === \"suspended\") void audio.resume()\n        const t = audio.currentTime\n        const big =\n          code === \"Space\" ||\n          code === \"Enter\" ||\n          code === \"Backspace\" ||\n          code.startsWith(\"Shift\")\n        const vary = 0.93 + Math.random() * 0.14\n\n        const body = audio.createOscillator()\n        body.type = \"sine\"\n        const f = 132 * (big ? 0.72 : 1) * (down ? 1 : 1.3) * vary\n        body.frequency.setValueAtTime(f * 1.9, t)\n        body.frequency.exponentialRampToValueAtTime(f, t + 0.03)\n        const bodyGain = audio.createGain()\n        bodyGain.gain.setValueAtTime(down ? 0.32 : 0.1, t)\n        bodyGain.gain.exponentialRampToValueAtTime(\n          0.0001,\n          t + (down ? 0.1 : 0.05)\n        )\n        body.connect(bodyGain).connect(master!)\n        body.start(t)\n        body.stop(t + 0.12)\n\n        const hit = audio.createBufferSource()\n        hit.buffer = noise\n        const band = audio.createBiquadFilter()\n        band.type = \"bandpass\"\n        band.frequency.value = 2900 * (down ? 1 : 1.25) * vary\n        band.Q.value = 1.1\n        const hitGain = audio.createGain()\n        hitGain.gain.setValueAtTime(down ? 0.5 : 0.22, t)\n        hitGain.gain.exponentialRampToValueAtTime(0.0001, t + 0.035)\n        hit.connect(band).connect(hitGain).connect(master!)\n        hit.start(t)\n        hit.stop(t + 0.06)\n      } catch {\n        /* no audio: stay silent */\n      }\n    },\n    close() {\n      void audio?.close()\n    },\n  }\n}\n\nfunction isEditable(target: EventTarget | null) {\n  if (!(target instanceof HTMLElement)) return false\n  if (target.isContentEditable) return true\n  const tag = target.tagName\n  if (tag === \"TEXTAREA\" || tag === \"SELECT\") return true\n  if (tag !== \"INPUT\") return false\n  const type = (target as HTMLInputElement).type\n  return ![\n    \"checkbox\",\n    \"radio\",\n    \"button\",\n    \"range\",\n    \"color\",\n    \"submit\",\n    \"reset\",\n  ].includes(type)\n}\n\n/* ------------------------------------------------------------------ */\n/* Engine                                                              */\n/* ------------------------------------------------------------------ */\n\ntype Resolved = Required<\n  Omit<MechKeyboardOptions, \"onKey\" | \"onShortcut\" | \"onChord\" | \"highlight\">\n> &\n  Pick<MechKeyboardOptions, \"onKey\" | \"onShortcut\" | \"onChord\"> & {\n    highlight: string[]\n  }\n\nfunction resolve(options: MechKeyboardOptions): Resolved {\n  const num = (v: number | undefined, d: number) =>\n    typeof v === \"number\" && Number.isFinite(v) ? v : d\n  return {\n    x: num(options.x, 0),\n    y: num(options.y, 0),\n    scale: Math.max(0.05, num(options.scale, 1)),\n    monochrome: options.monochrome ?? false,\n    interactive: options.interactive ?? true,\n    sound: options.sound ?? false,\n    intro: options.intro ?? true,\n    highlight: options.highlight ?? [],\n    platform:\n      options.platform === \"mac\" || options.platform === \"pc\"\n        ? options.platform\n        : detectPlatform(),\n    recorder: options.recorder ?? false,\n    onKey: options.onKey,\n    onShortcut: options.onShortcut,\n    onChord: options.onChord,\n  }\n}\n\ntype Cap = {\n  id: string\n  x: number\n  y: number\n  holder: Group\n  /** Rest height of the holder */\n  base: number\n  /** How far it goes down */\n  travel: number\n  material: MeshToonMaterial\n  pos: number\n  vel: number\n  target: number\n}\n\nconst NEAR = 0.1\nconst FAR = 200\n\n/**\n * Mounts a canvas in `stage` and listens on `root`\n * (focusable; pointer and keys). Returns a no-op instance without WebGL.\n */\nexport function createMechKeyboard(\n  root: HTMLElement,\n  stage: HTMLElement,\n  initial: MechKeyboardOptions = {}\n): MechKeyboardInstance {\n  let opts = resolve(initial)\n  let renderer: WebGLRenderer\n  try {\n    renderer = new WebGLRenderer({ alpha: true, antialias: true })\n  } catch {\n    return { setOptions() {}, replay() {}, destroy() {} }\n  }\n  renderer.setPixelRatio(Math.min(Math.max(1, window.devicePixelRatio), 2))\n  renderer.outputColorSpace = SRGBColorSpace\n  renderer.setClearColor(0x000000, 0)\n  const el = renderer.domElement\n  el.style.display = \"block\"\n  el.style.width = \"100%\"\n  el.style.height = \"100%\"\n  stage.appendChild(el)\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  let reduced = mqReduce.matches\n  let destroyed = false\n  const disposables: Array<Material | Texture | BufferGeometry> = []\n  const keep = <T extends Material | Texture | BufferGeometry>(item: T) => {\n    disposables.push(item)\n    return item\n  }\n\n  /* ---------- scene ---------- */\n\n  const scene = new Scene()\n  const camera = new OrthographicCamera(-1, 1, 1, -1, NEAR, FAR)\n\n  // desk: tipped toward the camera. board: turned 45° on the desk.\n  const desk = new Group()\n  desk.rotation.x = ISO_TILT\n  scene.add(desk)\n  const board = new Group()\n  board.rotation.y = ISO_TURN\n  board.position.y = -(CASE_H + RISE / 2) / 2\n  desk.add(board)\n\n  // Light fixed to the view, the illustrator's convention: tops lightest,\n  // left faces middle, right faces darkest.\n  const key = new DirectionalLight(0xffffff, 1.9)\n  key.position.set(-3, 6, 4)\n  scene.add(key, key.target, new AmbientLight(0xffffff, 1.1))\n\n  // A flat, hard-edged shadow, offset down and to the right.\n  const shadow = new Mesh(\n    keep(\n      new ShapeGeometry(roundedRect(new Shape(), W, D, 0.16), 8).rotateX(\n        -Math.PI / 2\n      )\n    ),\n    keep(\n      new MeshBasicMaterial({\n        color: INK,\n        transparent: true,\n        opacity: 0.1,\n        depthWrite: false,\n      })\n    )\n  )\n  shadow.rotation.y = ISO_TURN\n  shadow.position.set(0.55, board.position.y + 0.003, 0.75)\n  desk.add(shadow)\n\n  const ramp = keep(rampTexture())\n  const caseGeo = keep(caseGeometry())\n  const knobGeo = keep(knobGeometry())\n  const capGeos = new Map<number, BufferGeometry>()\n  const capGeo = (w: number) => {\n    let g = capGeos.get(w)\n    if (!g) capGeos.set(w, (g = keep(capGeometry(w))))\n    return g\n  }\n\n  /* ---------- the board, rebuilt per palette, platform, and font ---------- */\n\n  let built: {\n    group: Group\n    disposables: Array<Material | Texture | BufferGeometry>\n    knob: Mesh\n    pickable: Mesh[]\n  } | null = null\n  let builtFor = \"\"\n  const caps = new Map<string, Cap>()\n  let knobAngle = 0\n\n  const fontFamily = () =>\n    getComputedStyle(root).fontFamily || \"ui-sans-serif, system-ui, sans-serif\"\n  const plateX = (x: number) => -COLS / 2 + x\n  const plateZ = (y: number) => -LAYOUT_D / 2 + y\n\n  const build = () => {\n    const font = fontFamily()\n    const stamp = `${opts.monochrome}|${opts.platform}|${font}`\n    if (stamp === builtFor) return\n    builtFor = stamp\n    const palette = paletteFor(opts.monochrome)\n    const own: Array<Material | Texture | BufferGeometry> = []\n    const take = <T extends Material | Texture | BufferGeometry>(item: T) => {\n      own.push(item)\n      return item\n    }\n    const toon = (color: Color | string, map: Texture | null = null) =>\n      take(\n        new MeshToonMaterial({\n          color,\n          map,\n          gradientMap: ramp,\n          emissive: new Color(HIGHLIGHT),\n          emissiveIntensity: 0,\n        })\n      )\n\n    const group = new Group()\n    const caseMat = toon(palette.case)\n    group.add(new Mesh(caseGeo, caseMat))\n    const bottom = new Mesh(\n      take(new BoxGeometry(W - 0.4, 0.06, D - 0.4)),\n      caseMat\n    )\n    bottom.position.y = 0.03\n    group.add(bottom)\n\n    // Plate and keys ride the tipped top.\n    const deck = new Group()\n    deck.position.y = bezelTop(0) - WELL\n    deck.rotation.x = TILT\n    group.add(deck)\n\n    const plate = new Mesh(\n      take(new BoxGeometry(COLS + 0.2, 0.08, LAYOUT_D + 0.2)),\n      toon(palette.plate)\n    )\n    plate.position.y = -0.04\n    deck.add(plate)\n\n    const prev = new Map(caps)\n    caps.clear()\n\n    const knobMat = toon(palette.knob)\n    const knobHolder = new Group()\n    knobHolder.position.set(plateX(15.5), 0.08, plateZ(0.5))\n    deck.add(knobHolder)\n    const knob = new Mesh(knobGeo, knobMat)\n    knob.userData.id = KNOB_ID\n    knob.rotation.y = knobAngle\n    knobHolder.add(knob)\n    const notch = new Mesh(\n      take(new BoxGeometry(0.05, 0.012, 0.2)),\n      take(new MeshBasicMaterial({ color: INK }))\n    )\n    notch.position.set(0, 0.622, -0.19)\n    knob.add(notch)\n    const pickable: Mesh[] = [knob]\n\n    const next: Cap[] = [\n      {\n        id: KNOB_ID,\n        x: 15,\n        y: 0,\n        holder: knobHolder,\n        base: 0.08,\n        travel: 0.06,\n        material: knobMat,\n        pos: 0,\n        vel: 0,\n        target: 0,\n      },\n    ]\n\n    const from = new Color(palette.capBack)\n    const to = new Color(palette.capFront)\n    for (const k of buildLayout(opts.platform)) {\n      const cx = plateX(k.x + k.w / 2)\n      const cz = plateZ(k.y + 0.5)\n      const holder = new Group()\n      holder.position.set(cx, SWITCH, cz)\n      deck.add(holder)\n\n      // The back rows carry the color; it washes out toward the front right.\n      const t = Math.min(\n        1,\n        Math.max(\n          0,\n          (k.y / 5.25) * 0.82 + ((k.x + k.w / 2) / COLS) * 0.26 - 0.08\n        )\n      )\n      const color = from.clone().lerp(to, t)\n      const map = k.label ? take(capTexture(k, color.getStyle(), font)) : null\n      const material = toon(map ? \"#ffffff\" : color, map)\n      const mesh = new Mesh(capGeo(k.w), material)\n      mesh.userData.id = k.id\n      holder.add(mesh)\n      pickable.push(mesh)\n      next.push({\n        id: k.id,\n        x: k.x,\n        y: k.y,\n        holder,\n        base: SWITCH,\n        travel: TRAVEL,\n        material,\n        pos: 0,\n        vel: 0,\n        target: 0,\n      })\n    }\n\n    // Keys that were down stay down across a rebuild.\n    for (const cap of next) {\n      const old = prev.get(cap.id)\n      if (old) {\n        cap.pos = old.pos\n        cap.target = old.target\n      }\n      cap.holder.position.y = cap.base + cap.pos\n      caps.set(cap.id, cap)\n    }\n\n    board.add(group)\n    if (built) {\n      board.remove(built.group)\n      for (const item of built.disposables) item.dispose()\n    }\n    built = { group, disposables: own, knob, pickable }\n    paintHighlights()\n  }\n\n  /* ---------- ink: edges from depth and normals ---------- */\n\n  const color = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: 4 })\n  const normal = new WebGLRenderTarget(1, 1, { type: HalfFloatType })\n  normal.depthTexture = new DepthTexture(1, 1)\n  const normalMat = keep(new MeshNormalMaterial())\n  const quad = new Mesh(\n    keep(new PlaneGeometry(2, 2)),\n    keep(\n      new ShaderMaterial({\n        uniforms: {\n          tColor: { value: color.texture },\n          tNormal: { value: normal.texture },\n          tDepth: { value: normal.depthTexture },\n          texel: { value: new Vector2() },\n          ink: { value: new Color(INK) },\n          depthRange: { value: FAR - NEAR },\n        },\n        vertexShader: INK_VERTEX,\n        fragmentShader: INK_FRAGMENT,\n        depthTest: false,\n        depthWrite: false,\n        blending: NoBlending,\n      })\n    )\n  )\n  const post = new Scene()\n  post.add(quad)\n  const postCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1)\n\n  const render = () => {\n    renderer.setRenderTarget(color)\n    renderer.setClearColor(0x000000, 0)\n    renderer.render(scene, camera)\n\n    shadow.visible = false\n    scene.overrideMaterial = normalMat\n    renderer.setRenderTarget(normal)\n    renderer.setClearColor(0x8080ff, 1)\n    renderer.render(scene, camera)\n    scene.overrideMaterial = null\n    shadow.visible = true\n\n    renderer.setClearColor(0x000000, 0)\n    renderer.setRenderTarget(null)\n    renderer.render(post, postCamera)\n  }\n\n  /* ---------- fit and offset ---------- */\n\n  let width = 0\n  let height = 0\n  const current = { x: 0, y: 0 }\n  let introFrom: { x: number; y: number } | null = null\n  let introStart = 0\n  const INTRO_MS = 1300\n\n  const corners: Vector3[] = []\n  for (const x of [-W / 2, W / 2])\n    for (const y of [0, CASE_H + RISE + 0.1])\n      for (const z of [-D / 2, D / 2]) corners.push(new Vector3(x, y, z))\n  const scratch = new Vector3()\n\n  /** Frame the board exactly: measure its projected box straight on. */\n  const fit = () => {\n    if (!width || !height) return\n    desk.position.set(0, 0, 0)\n    desk.updateMatrixWorld(true)\n    let minX = Infinity\n    let maxX = -Infinity\n    let minY = Infinity\n    let maxY = -Infinity\n    for (const c of corners) {\n      scratch.copy(c).applyMatrix4(board.matrixWorld)\n      minX = Math.min(minX, scratch.x)\n      maxX = Math.max(maxX, scratch.x)\n      minY = Math.min(minY, scratch.y)\n      maxY = Math.max(maxY, scratch.y)\n    }\n    const aspect = width / height\n    const room = opts.recorder ? 0.66 : 0.82\n    const half =\n      Math.max((maxY - minY) / 2 / room, (maxX - minX) / 2 / 0.88 / aspect) /\n      opts.scale\n    camera.left = -half * aspect\n    camera.right = half * aspect\n    camera.top = half\n    camera.bottom = -half\n    camera.position.set((minX + maxX) / 2, (minY + maxY) / 2, FAR / 2)\n    camera.lookAt(camera.position.x, camera.position.y, 0)\n    camera.updateProjectionMatrix()\n    place()\n  }\n\n  function place() {\n    const perPx = (camera.top - camera.bottom) / (height || 1)\n    const drop = opts.recorder ? height * 0.04 : 0\n    desk.position.set(current.x * perPx, -(current.y + drop) * perPx, 0)\n  }\n\n  const resize = () => {\n    const w = stage.clientWidth\n    const h = stage.clientHeight\n    if (!w || !h || (w === width && h === height)) return false\n    width = w\n    height = h\n    renderer.setSize(w, h, false)\n    const pr = renderer.getPixelRatio()\n    const pw = Math.max(1, Math.round(w * pr))\n    const ph = Math.max(1, Math.round(h * pr))\n    // Normals and depth at twice the resolution on 1x screens, so the\n    // four-tap average in the ink pass has subpixels to antialias with.\n    const s = pr < 2 ? 2 : 1\n    color.setSize(pw, ph)\n    normal.setSize(pw * s, ph * s)\n    quad.material.uniforms.texel!.value.set(1 / pw, 1 / ph)\n    fit()\n    return true\n  }\n\n  /* ---------- loop ---------- */\n\n  let raf = 0\n  let last = 0\n  let onScreen = true\n  let pulse = 0\n  let knobGoal = 0\n\n  const wake = () => {\n    if (raf || destroyed || !onScreen || document.hidden) return\n    last = performance.now()\n    raf = requestAnimationFrame(frame)\n  }\n\n  const frame = (now: number) => {\n    raf = 0\n    if (destroyed) return\n    const dt = Math.min(0.05, Math.max(0, (now - last) / 1000))\n    last = now\n    let busy = false\n\n    // Offset: the intro rise, then exponential smoothing toward the props.\n    if (introFrom) {\n      const t = Math.min(1, (now - introStart) / INTRO_MS)\n      const e = 1 - Math.pow(1 - t, 4)\n      current.x = introFrom.x + (opts.x - introFrom.x) * e\n      current.y = introFrom.y + (opts.y - introFrom.y) * e\n      if (t >= 1) introFrom = null\n      busy = true\n    } else {\n      const a = reduced ? 1 : 1 - Math.exp(-dt * 7)\n      for (const k of [\"x\", \"y\"] as const) {\n        const delta = opts[k] - current[k]\n        if (Math.abs(delta) > 0.05) {\n          current[k] += delta * a\n          busy = true\n        } else {\n          current[k] = opts[k]\n        }\n      }\n    }\n    place()\n\n    // Keys: a stiff spring down, a bouncier one back up, in fixed 4 ms\n    // substeps (one Euler step this stiff blows up on a slow frame).\n    const steps = Math.max(1, Math.ceil(dt / 0.004))\n    const h = dt / steps\n    for (const cap of caps.values()) {\n      if (cap.pos === cap.target && cap.vel === 0) continue\n      const down = cap.target < cap.pos\n      const k = down ? 2600 : 900\n      const c = down ? 80 : 26\n      for (let i = 0; i < steps; i++) {\n        cap.vel += (-k * (cap.pos - cap.target) - c * cap.vel) * h\n        cap.pos += cap.vel * h\n      }\n      if (\n        reduced ||\n        (Math.abs(cap.pos - cap.target) < 0.0005 && Math.abs(cap.vel) < 0.01)\n      ) {\n        cap.pos = cap.target\n        cap.vel = 0\n      } else {\n        busy = true\n      }\n      cap.holder.position.y = cap.base + cap.pos\n    }\n\n    const turn = knobGoal - knobAngle\n    if (Math.abs(turn) > 0.0005) {\n      knobAngle += turn * (reduced ? 1 : 1 - Math.exp(-dt * 14))\n      if (built) built.knob.rotation.y = knobAngle\n      busy = true\n    }\n\n    if (opts.highlight.length) {\n      pulse += dt\n      const glow = reduced ? 0.3 : 0.2 + 0.16 * Math.sin(pulse * 4)\n      for (const id of opts.highlight) {\n        const cap = caps.get(id)\n        if (cap) cap.material.emissiveIntensity = glow\n      }\n      if (!reduced) busy = true\n    }\n\n    render()\n    if (busy) wake()\n  }\n\n  function paintHighlights() {\n    const set = new Set(opts.highlight)\n    for (const [id, cap] of caps) {\n      cap.material.emissiveIntensity = set.has(id) ? 0.3 : 0\n    }\n  }\n\n  /* ---------- keys ---------- */\n\n  const held = new Set<string>()\n  const latched = new Set<string>()\n  let chord: string[] = []\n  const thock = createThock()\n\n  const capFor = (id: string) => {\n    const cap = caps.get(id)\n    if (cap || !/(Left|Right)$/.test(id)) return cap\n    const twin = id.endsWith(\"Left\")\n      ? id.replace(/Left$/, \"Right\")\n      : id.replace(/Right$/, \"Left\")\n    return caps.get(twin)\n  }\n\n  const paint = () => {\n    const down = new Set<Cap>()\n    for (const code of [...held, ...latched]) {\n      for (const id of capsFor(code)) {\n        const cap = capFor(id)\n        if (cap) down.add(cap)\n      }\n    }\n    for (const cap of caps.values()) {\n      cap.target = down.has(cap) ? -cap.travel : 0\n    }\n    wake()\n  }\n\n  const sound = (code: string, down: boolean) => {\n    if (opts.sound) thock.play(code, down)\n  }\n\n  const press = (code: string) => {\n    if (held.has(code)) return\n    if (code === \"AudioVolumeUp\") knobGoal -= 0.35\n    if (code === \"AudioVolumeDown\") knobGoal += 0.35\n    if (held.size === 0 && latched.size === 0) chord = []\n    held.add(code)\n    if (!chord.includes(code)) chord.push(code)\n    paint()\n    sound(code, true)\n    opts.onKey?.(code, true)\n    opts.onChord?.([...chord], \"live\")\n  }\n\n  const commit = () => {\n    if (held.size || latched.size || chord.length === 0) return\n    const done = chord\n    chord = []\n    opts.onChord?.(done, \"done\")\n    opts.onShortcut?.(formatShortcut(done, opts.platform))\n  }\n\n  const release = (code: string) => {\n    if (!held.delete(code)) return\n    paint()\n    sound(code, false)\n    opts.onKey?.(code, false)\n    commit()\n  }\n\n  const releaseAll = () => {\n    const codes = [...held]\n    held.clear()\n    latched.clear()\n    paint()\n    for (const code of codes) opts.onKey?.(code, false)\n    commit()\n  }\n\n  const timers = new Set<ReturnType<typeof setTimeout>>()\n  const later = (fn: () => void, ms: number) => {\n    const id = setTimeout(() => {\n      timers.delete(id)\n      if (!destroyed) fn()\n    }, ms)\n    timers.add(id)\n  }\n\n  // The real OS, not the `platform` legends option: it decides which\n  // keyboard events arrive.\n  const onMac = detectPlatform() === \"mac\"\n\n  const focused = () =>\n    document.activeElement === root || root.contains(document.activeElement)\n\n  const onKeyDown = (event: KeyboardEvent) => {\n    if (!opts.interactive || !event.code) return\n    if (isEditable(event.target) && !root.contains(event.target as Node)) return\n    if (focused() && event.code !== \"Tab\") event.preventDefault()\n    if (event.repeat) return\n    press(event.code)\n    // macOS fires one event per Caps Lock toggle; never leave it stuck.\n    // Elsewhere Caps Lock sends a normal down and up, so it can be held.\n    if (event.code === \"CapsLock\" && onMac) {\n      later(() => release(\"CapsLock\"), 160)\n    }\n  }\n\n  const onKeyUp = (event: KeyboardEvent) => {\n    if (!event.code) return\n    if (event.code === \"CapsLock\" && !held.has(\"CapsLock\")) {\n      if (!opts.interactive) return\n      press(\"CapsLock\")\n      later(() => release(\"CapsLock\"), 120)\n      return\n    }\n    // While ⌘ is held macOS swallows other keyups; release them with it.\n    if (modifierOf(event.code) === \"Meta\") {\n      for (const code of [...held]) if (!modifierOf(code)) release(code)\n    }\n    release(event.code)\n  }\n\n  /* Pointer: modifiers latch, a non-modifier fires the chord. */\n  const raycaster = new Raycaster()\n  const ndc = new Vector2()\n  const pick = (event: { clientX: number; clientY: number }) => {\n    if (!built) return null\n    const r = el.getBoundingClientRect()\n    if (!r.width || !r.height) return null\n    ndc.set(\n      ((event.clientX - r.left) / r.width) * 2 - 1,\n      -((event.clientY - r.top) / r.height) * 2 + 1\n    )\n    raycaster.setFromCamera(ndc, camera)\n    const hit = raycaster.intersectObjects(built.pickable, false)[0]\n    return (hit?.object.userData.id as string | undefined) ?? null\n  }\n\n  /** Keys held down by each pointer, so two fingers release independently. */\n  const pointers = new Map<number, string>()\n\n  const onPointerDown = (event: PointerEvent) => {\n    if (!opts.interactive || event.button !== 0) return\n    const code = pick(event)\n    if (!code) return\n    event.preventDefault()\n    root.focus({ preventScroll: true })\n    if (modifierOf(code)) {\n      if (latched.has(code)) {\n        latched.delete(code)\n        chord = chord.filter((c) => c !== code)\n        paint()\n        opts.onChord?.([...chord], chord.length ? \"live\" : \"idle\")\n      } else {\n        if (held.size === 0 && latched.size === 0) chord = []\n        latched.add(code)\n        if (!chord.includes(code)) chord.push(code)\n        paint()\n        sound(code, true)\n        opts.onChord?.([...chord], \"live\")\n      }\n      return\n    }\n    pointers.set(event.pointerId, code)\n    press(code)\n  }\n\n  const onPointerUp = (event: PointerEvent) => {\n    const code = pointers.get(event.pointerId)\n    if (!code) return\n    pointers.delete(event.pointerId)\n    if (![...pointers.values()].includes(code)) {\n      held.delete(code)\n      sound(code, false)\n      opts.onKey?.(code, false)\n    }\n    // Latched modifiers belong to the chord until the last finger lifts.\n    if (pointers.size === 0) latched.clear()\n    paint()\n    commit()\n  }\n\n  const onPointerMove = (event: PointerEvent) => {\n    if (!opts.interactive || event.pointerType !== \"mouse\") return\n    el.style.cursor = pick(event) ? \"pointer\" : \"\"\n  }\n\n  /* The knob turns under the wheel, like the real one. */\n  const onWheel = (event: WheelEvent) => {\n    if (!opts.interactive || pick(event) !== KNOB_ID) return\n    event.preventDefault()\n    knobGoal += Math.sign(event.deltaY) * 0.26\n    wake()\n  }\n\n  const onBlur = () => {\n    if (held.size || latched.size) releaseAll()\n  }\n\n  window.addEventListener(\"keydown\", onKeyDown)\n  window.addEventListener(\"keyup\", onKeyUp)\n  window.addEventListener(\"blur\", onBlur)\n  root.addEventListener(\"pointerdown\", onPointerDown)\n  root.addEventListener(\"pointermove\", onPointerMove)\n  root.addEventListener(\"wheel\", onWheel, { passive: false })\n  window.addEventListener(\"pointerup\", onPointerUp)\n  window.addEventListener(\"pointercancel\", onPointerUp)\n\n  /* ---------- lifecycle ---------- */\n\n  const ro = new ResizeObserver(() => {\n    if (!resize() || destroyed) return\n    // Resizing cleared the canvas; draw the current frame now.\n    render()\n    wake()\n  })\n  ro.observe(stage)\n  const io = new IntersectionObserver(([entry]) => {\n    onScreen = entry?.isIntersecting ?? true\n    wake()\n  })\n  io.observe(stage)\n  const onVisibility = () => wake()\n  document.addEventListener(\"visibilitychange\", onVisibility)\n  const onReduce = () => {\n    reduced = mqReduce.matches\n    wake()\n  }\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  // Legends are printed from a canvas; print them again once fonts land.\n  void document.fonts?.ready.then(() => {\n    if (destroyed) return\n    builtFor = \"\"\n    build()\n    wake()\n  })\n\n  const wave = () => {\n    for (const cap of caps.values()) {\n      const delay = 380 + cap.x * 36 + cap.y * 24\n      later(() => {\n        if (cap.target !== 0) return\n        cap.target = -cap.travel * 0.8\n        wake()\n        later(paint, 110)\n      }, delay)\n    }\n  }\n\n  const intro = () => {\n    stage.style.transition = \"opacity 800ms ease-out\"\n    if (!opts.intro || reduced) {\n      current.x = opts.x\n      current.y = opts.y\n      stage.style.opacity = \"1\"\n      wake()\n      return\n    }\n    introFrom = { x: opts.x, y: opts.y + 60 }\n    Object.assign(current, introFrom)\n    introStart = performance.now()\n    stage.style.opacity = \"0\"\n    requestAnimationFrame(() => {\n      if (!destroyed) stage.style.opacity = \"1\"\n    })\n    wave()\n    wake()\n  }\n\n  build()\n  resize()\n  intro()\n\n  return {\n    setOptions(next) {\n      opts = resolve({ ...opts, ...next })\n      if (!opts.interactive && (held.size || latched.size)) releaseAll()\n      build()\n      fit()\n      paintHighlights()\n      wake()\n    },\n    replay() {\n      intro()\n    },\n    destroy() {\n      destroyed = true\n      cancelAnimationFrame(raf)\n      for (const id of timers) clearTimeout(id)\n      timers.clear()\n      ro.disconnect()\n      io.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      mqReduce.removeEventListener(\"change\", onReduce)\n      window.removeEventListener(\"keydown\", onKeyDown)\n      window.removeEventListener(\"keyup\", onKeyUp)\n      window.removeEventListener(\"blur\", onBlur)\n      root.removeEventListener(\"pointerdown\", onPointerDown)\n      root.removeEventListener(\"pointermove\", onPointerMove)\n      root.removeEventListener(\"wheel\", onWheel)\n      window.removeEventListener(\"pointerup\", onPointerUp)\n      window.removeEventListener(\"pointercancel\", onPointerUp)\n      thock.close()\n      if (built) for (const item of built.disposables) item.dispose()\n      for (const item of disposables) item.dispose()\n      color.dispose()\n      normal.depthTexture?.dispose()\n      normal.dispose()\n      renderer.dispose()\n      // dispose() keeps the context until garbage collection, and browsers\n      // cap live contexts; give it back now.\n      renderer.forceContextLoss()\n      el.remove()\n    },\n  }\n}\n\nconst INK_VERTEX = /* glsl */ `\nvarying vec2 vUv;\nvoid main() {\n  vUv = uv;\n  gl_Position = vec4(position.xy, 0.0, 1.0);\n}\n`\n\n/**\n * Ink where depth jumps (silhouettes, caps over the plate) or the surface\n * turns sharply (case chamfers, cap edges). Four subpixel taps averaged,\n * so the lines come out antialiased.\n */\nconst INK_FRAGMENT = /* glsl */ `\nuniform sampler2D tColor;\nuniform sampler2D tNormal;\nuniform sampler2D tDepth;\nuniform vec2 texel;\nuniform vec3 ink;\nuniform float depthRange;\nvarying vec2 vUv;\n\nfloat edgeAt(vec2 uv) {\n  float d0 = texture2D(tDepth, uv).r;\n  vec3 n0 = texture2D(tNormal, uv).rgb * 2.0 - 1.0;\n  float e = 0.0;\n  vec2 dirs[4];\n  dirs[0] = vec2(1.0, 0.0);\n  dirs[1] = vec2(-1.0, 0.0);\n  dirs[2] = vec2(0.0, 1.0);\n  dirs[3] = vec2(0.0, -1.0);\n  for (int i = 0; i < 4; i++) {\n    vec2 q = uv + dirs[i] * texel * 0.85;\n    float dd = abs(texture2D(tDepth, q).r - d0) * depthRange;\n    vec3 n1 = texture2D(tNormal, q).rgb * 2.0 - 1.0;\n    e = max(e, smoothstep(0.07, 0.14, dd));\n    e = max(e, smoothstep(0.22, 0.4, 1.0 - dot(n0, n1)));\n  }\n  return e;\n}\n\nvoid main() {\n  vec4 color = texture2D(tColor, vUv);\n  vec2 s = texel * 0.25;\n  float e = (\n    edgeAt(vUv + vec2(-s.x, -s.y)) +\n    edgeAt(vUv + vec2(s.x, -s.y)) +\n    edgeAt(vUv + vec2(-s.x, s.y)) +\n    edgeAt(vUv + vec2(s.x, s.y))\n  ) * 0.25;\n  gl_FragColor = mix(color, vec4(ink, 1.0), e);\n  #include <colorspace_fragment>\n}\n`\n\n/** Tailwind for the recorder. */\nexport const CLASSES = {\n  root: \"relative size-full touch-manipulation overflow-hidden outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\",\n  stage: \"absolute inset-0 opacity-0\",\n  recorder:\n    \"pointer-events-none absolute inset-x-0 top-[6%] z-10 flex flex-col items-center gap-3 px-4\",\n  chips: \"flex min-h-12 flex-wrap items-center justify-center gap-2\",\n  /**\n   * An illustrated keycap: an ink outline around a darker skirt, with the\n   * top face sitting on it. Held keys sink into the skirt.\n   */\n  chip: \"group/chip relative inline-flex h-12 min-w-12 flex-col rounded-[9px] border-[1.5px] border-(--ink) bg-(--chip-side) pb-[6px] font-sans transition-[padding,translate,opacity,scale] duration-200 ease-[cubic-bezier(0.3,1.5,0.5,1)] starting:-translate-y-1.5 starting:scale-90 starting:opacity-0 data-live:translate-y-[3px] data-live:pb-[3px]\",\n  chipTop:\n    \"flex flex-1 items-center justify-center rounded-[7px] border-b-[1.5px] border-(--ink) bg-(--chip) px-3 text-sm leading-none font-semibold text-(--ink)\",\n  plus: \"text-sm font-semibold text-muted-foreground\",\n  placeholder: \"text-sm text-muted-foreground\",\n  status:\n    \"flex h-4 items-center gap-1.5 text-[11px] font-semibold tracking-[0.08em] text-muted-foreground uppercase\",\n  dot: \"size-1.5 animate-pulse rounded-full bg-red-500\",\n  check: \"size-3\",\n}\n\nexport type MechKeyboardProps = {\n  /** Horizontal offset, px. */\n  x?: number\n  /** Vertical offset, px. */\n  y?: number\n  /** Multiplies the fitted size. */\n  scale?: number\n  /** Ink and greys only; no blue caps. */\n  monochrome?: boolean\n  /** Real key presses and clicks press the keys. */\n  interactive?: boolean\n  /** Shows the shortcut being pressed above the keyboard. */\n  recorder?: boolean\n  /** Recorder text before the first key. */\n  placeholder?: string\n  /** `KeyboardEvent.code`s to pulse, e.g. `[\"MetaLeft\", \"KeyK\"]`. */\n  highlight?: string[]\n  /** Bottom-row legends. `\"auto\"` detects Mac. */\n  platform?: MechKeyboardPlatform | \"auto\"\n  /** Synthesized switch sounds. */\n  sound?: boolean\n  /** Rise into place with a wave across the keys on mount. */\n  intro?: boolean\n  /** Every key down and up. */\n  onKey?: (code: string, pressed: boolean) => void\n  /** Fires when every key of a chord is released. */\n  onShortcut?: (shortcut: MechKeyboardShortcut) => void\n  className?: string\n}\n\nconst noop = () => () => {}\n\nfunction Check() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden className={CLASSES.check}>\n      <path\n        d=\"M3.5 8.5l3 3 6-7\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      />\n    </svg>\n  )\n}\n\n/**\n * A 75% mechanical keyboard drawn as an isometric illustration in\n * three.js: flat tone bands, ink outlines, a volume knob. Keys spring down\n * under your keyboard (or a click; modifiers latch), and the recorder above\n * spells out the shortcut in little illustrated keycaps, onboarding-style.\n * Honors `prefers-reduced-motion`.\n */\nexport function MechKeyboard({\n  x = 0,\n  y = 0,\n  scale = 1,\n  monochrome = false,\n  interactive = true,\n  recorder = true,\n  placeholder = DEFAULT_PLACEHOLDER,\n  highlight,\n  platform = \"auto\",\n  sound = false,\n  intro = true,\n  onKey,\n  onShortcut,\n  className,\n}: MechKeyboardProps) {\n  const rootRef = useRef<HTMLDivElement>(null)\n  const stageRef = useRef<HTMLDivElement>(null)\n  const instanceRef = useRef<MechKeyboardInstance | null>(null)\n  const callbacks = useRef({ onKey, onShortcut })\n  const detected = useSyncExternalStore(\n    noop,\n    detectPlatform,\n    (): MechKeyboardPlatform => \"pc\"\n  )\n  const [chord, setChord] = useState<{\n    codes: string[]\n    phase: MechKeyboardChordPhase\n  }>({ codes: [], phase: \"idle\" })\n\n  const resolvedPlatform = platform === \"auto\" ? detected : platform\n  const shortcut = formatShortcut(chord.codes, resolvedPlatform)\n  const highlightKey = (highlight ?? []).join(\" \")\n\n  useEffect(() => {\n    callbacks.current = { onKey, onShortcut }\n  }, [onKey, onShortcut])\n\n  useEffect(() => {\n    const root = rootRef.current\n    const stage = stageRef.current\n    if (!root || !stage) return\n    instanceRef.current = createMechKeyboard(root, stage, {\n      x,\n      y,\n      scale,\n      monochrome,\n      interactive,\n      sound,\n      intro,\n      recorder,\n      highlight,\n      platform: resolvedPlatform,\n      onKey: (code, pressed) => callbacks.current.onKey?.(code, pressed),\n      onShortcut: (s) => callbacks.current.onShortcut?.(s),\n      onChord: (codes, phase) => setChord({ codes, phase }),\n    })\n    return () => {\n      instanceRef.current?.destroy()\n      instanceRef.current = null\n    }\n    // Engine reads live options via setOptions; mount once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  useEffect(() => {\n    instanceRef.current?.setOptions({\n      x,\n      y,\n      scale,\n      monochrome,\n      interactive,\n      sound,\n      intro,\n      recorder,\n      highlight: highlightKey ? highlightKey.split(\" \") : [],\n      platform: resolvedPlatform,\n    })\n  }, [\n    x,\n    y,\n    scale,\n    monochrome,\n    interactive,\n    sound,\n    intro,\n    recorder,\n    highlightKey,\n    resolvedPlatform,\n  ])\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"mech-keyboard\"\n      tabIndex={interactive ? 0 : undefined}\n      role=\"application\"\n      aria-label=\"Mechanical keyboard\"\n      style={recorderVars(monochrome) as CSSProperties}\n      className={cn(CLASSES.root, className)}\n    >\n      <div ref={stageRef} className={CLASSES.stage} />\n      {recorder ? (\n        <div aria-live=\"polite\" className={CLASSES.recorder}>\n          <div className={CLASSES.chips}>\n            {shortcut.keys.length === 0 ? (\n              <span className={CLASSES.placeholder}>{placeholder}</span>\n            ) : (\n              shortcut.keys.map((key, i) => (\n                <Fragment key={shortcut.codes[i]}>\n                  {i > 0 ? <span className={CLASSES.plus}>+</span> : null}\n                  <kbd\n                    data-live={chord.phase === \"live\" ? \"\" : undefined}\n                    className={CLASSES.chip}\n                  >\n                    <span className={CLASSES.chipTop}>{key}</span>\n                  </kbd>\n                </Fragment>\n              ))\n            )}\n          </div>\n          <div className={CLASSES.status}>\n            {chord.phase === \"done\" ? (\n              <>\n                <Check />\n                Shortcut saved\n              </>\n            ) : chord.phase === \"live\" ? (\n              <>\n                <span className={CLASSES.dot} />\n                Recording\n              </>\n            ) : (\n              \"Listening\"\n            )}\n          </div>\n        </div>\n      ) : null}\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/mech-keyboard.tsx"
    }
  ],
  "type": "registry:ui"
}