{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"pixel-keycap","type":"registry:component","title":"Pixel Keycap","description":"A soft-touch keycap with your logo and legend, and a strip of pixels down its right edge that light up one by one until it's full, blink, and start again. It lifts on hover and presses down when clicked.","dependencies":[],"files":[{"path":"registry/dot/pixel-keycap.tsx","type":"registry:component","target":"components/dot/pixel-keycap.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from \"react\";\n\nexport interface PixelKeycapProps {\n  /** The legend in the bottom-right corner */\n  label?: string;\n  /** Your logo (SVG or transparent PNG) in the top-left corner; leave empty for the Dot mark */\n  logo?: string;\n  /** Logo size as a share of the key top (0.1–0.4) */\n  logoSize?: number;\n  /** How many pixels are in the strip on the right edge (3–8) */\n  pixels?: number;\n  /**\n   * \"fill\": the pixels light up one by one until the strip is full, blink, and start again.\n   * \"chase\": one pixel at a time runs down the strip.\n   */\n  pattern?: \"fill\" | \"chase\";\n  /** Milliseconds between one pixel and the next */\n  speed?: number;\n  /** Width of the key in px */\n  size?: number;\n  accentColor?: string;\n  keyColor?: string;\n  /** The legend text */\n  legendColor?: string;\n  /** The built-in Dot mark */\n  logoColor?: string;\n  /** Behind the key; \"transparent\" for none */\n  background?: string;\n  className?: string;\n  style?: CSSProperties;\n}\n\nconst subscribeReducedMotion = (cb: () => void) => {\n  const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  mq.addEventListener(\"change\", cb);\n  return () => mq.removeEventListener(\"change\", cb);\n};\nconst useReducedMotion = () =>\n  useSyncExternalStore(subscribeReducedMotion, () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches, () => false);\n\n/**\n * Mix the key colour towards white (k > 0) or black (k < 0). Mixed by the browser, so any CSS colour\n * works (hex with or without alpha, rgb(), hsl(), a name, a CSS variable; Framer hands over rgba())\n */\nfunction tone(color: string, k: number) {\n  const base = color.trim() || \"#161616\";\n  return `color-mix(in srgb, ${base}, ${k >= 0 ? \"white\" : \"black\"} ${Math.round(Math.abs(k) * 100)}%)`;\n}\n\n/** The Dot mark */\nfunction DotMark({ color, width }: { color: string; width: string }) {\n  return (\n    <svg aria-hidden viewBox=\"0 0 24 28\" fill={color} style={{ display: \"block\", width, height: \"auto\", aspectRatio: \"24 / 28\" }}>\n      <path d=\"M17.4545 0H13.0908V25.5769H17.4545V0Z\" />\n      <path d=\"M0 23.6923L0 28H17.4545V23.6923H0Z\" />\n      <path d=\"M4.36364 21.5385H0V16.1539C0 13.1801 2.44208 10.7693 5.45455 10.7693H21.8182V15.077H5.45455C4.85206 15.077 4.36364 15.5591 4.36364 16.1539V21.5385Z\" />\n      <path d=\"M23.9999 25.8462C23.9999 24.6567 23.023 23.6924 21.818 23.6924C20.6131 23.6924 19.6362 24.6567 19.6362 25.8462C19.6362 27.0358 20.6131 28.0001 21.818 28.0001C23.023 28.0001 23.9999 27.0358 23.9999 25.8462Z\" />\n    </svg>\n  );\n}\n\n/**\n * Which pixels are lit at each step of the loop. Fill: one more pixel each step until the strip\n * is full, a pause, three blinks of the full strip, then a short dark pause before it fills again.\n * Chase: one pixel at a time, bottom to top.\n */\nfunction buildFrames(n: number, pattern: \"fill\" | \"chase\"): number[][] {\n  const range = (k: number) => Array.from({ length: k }, (_, i) => i);\n  if (pattern === \"chase\") return [...range(n).map((i) => [i]), [], []];\n  const all = range(n);\n  return [\n    [],\n    ...range(n).map((i) => range(i + 1)),\n    all, all, all, // hold full\n    [], all, [], all, [], all, // three blinks\n    all, all,\n    [], [], // dark before refilling\n  ];\n}\n\n/**\n * A soft-touch keycap with your logo and legend, and a strip of pixels down its right edge that\n * light up one by one until it's full, blink, and start again. It lifts on hover and presses down\n * when clicked; a click also starts the fill over.\n */\nexport function PixelKeycap({\n  label = \"dot\",\n  logo,\n  logoSize = 0.2,\n  pixels = 5,\n  pattern = \"fill\",\n  speed = 180,\n  size = 360,\n  accentColor = \"#C6F432\",\n  keyColor = \"#161616\",\n  legendColor = \"#8A8A8A\",\n  logoColor = \"#6F6F6F\",\n  background = \"#141414\",\n  className,\n  style,\n}: PixelKeycapProps) {\n  const n = Math.round(Math.min(8, Math.max(3, pixels)));\n  const step = Math.max(60, speed);\n  const reduced = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [frame, setFrame] = useState(0);\n  const [hover, setHover] = useState(false);\n  const [pressed, setPressed] = useState(false);\n  const [run, setRun] = useState(0);\n  const [onScreen, setOnScreen] = useState(true);\n  const frames = buildFrames(n, pattern);\n  const count = frames.length;\n\n  // Only step the pixels while the key is on screen\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const io = new IntersectionObserver(([entry]) => setOnScreen(entry.isIntersecting));\n    io.observe(root);\n    return () => io.disconnect();\n  }, []);\n\n  useEffect(() => {\n    if (reduced || !onScreen) return;\n    let f = 0;\n    const id = window.setInterval(() => {\n      f = (f + 1) % count;\n      setFrame(f);\n    }, step);\n    return () => window.clearInterval(id);\n  }, [count, step, reduced, run, onScreen]);\n\n  const lit = reduced ? null : new Set(frames[frame % count]);\n  const logoShare = Math.min(0.4, Math.max(0.1, logoSize));\n  const restart = () => {\n    setFrame(0);\n    setRun((r) => r + 1);\n  };\n  const isKey = (key: string) => key === \"Enter\" || key === \" \";\n\n  return (\n    <div\n      ref={rootRef}\n      className={className}\n      style={{\n        position: \"relative\",\n        width: \"100%\",\n        height: \"100%\",\n        display: \"flex\",\n        alignItems: \"center\",\n        justifyContent: \"center\",\n        background,\n        // The design is drawn at 360px; --u is one of those pixels at the size shown. The key\n        // shrinks to fit narrow parents (90% of the width) instead of being cut off.\n        containerType: \"inline-size\",\n        [\"--u\" as string]: `calc(min(${Math.max(80, size)}px, 90cqw) / 360)`,\n        ...style,\n      }}\n    >\n      <button\n        type=\"button\"\n        aria-label={`${label || \"Key\"} key`}\n        onPointerEnter={() => setHover(true)}\n        onPointerLeave={() => {\n          setHover(false);\n          setPressed(false);\n        }}\n        onPointerDown={() => setPressed(true)}\n        onPointerUp={() => setPressed(false)}\n        onKeyDown={(e) => {\n          if (isKey(e.key)) setPressed(true);\n        }}\n        onKeyUp={(e) => {\n          if (isKey(e.key)) setPressed(false);\n        }}\n        onBlur={() => setPressed(false)}\n        onClick={restart}\n        style={{\n          position: \"relative\",\n          width: u(360),\n          height: u(360),\n          flexShrink: 0,\n          borderRadius: u(72),\n          border: 0,\n          padding: u(22),\n          cursor: \"pointer\",\n          background: `linear-gradient(160deg, ${tone(keyColor, 0.1)} 0%, ${tone(keyColor, -0.12)} 45%, ${tone(keyColor, -0.55)} 100%)`,\n          boxShadow: `0 ${u(29)} ${u(58)} rgba(0,0,0,0.65), inset 0 1px 0 rgba(255,255,255,0.14), inset 0 -2px 0 rgba(0,0,0,0.6)`,\n          transform: pressed ? `translateY(${u(3)}) scale(0.985)` : hover ? `translateY(${u(-2)})` : \"none\",\n          transition: reduced ? \"none\" : \"transform 0.12s ease\",\n          outlineOffset: u(6),\n        }}\n      >\n        {/* The dished top, with the logo and the legend */}\n        <span\n          style={{\n            display: \"flex\",\n            flexDirection: \"column\",\n            justifyContent: \"space-between\",\n            boxSizing: \"border-box\",\n            width: \"100%\",\n            height: \"100%\",\n            borderRadius: u(58),\n            padding: `${u(28)} ${u(30)}`,\n            background: `radial-gradient(120% 90% at 30% 15%, ${tone(keyColor, 0.07)} 0%, ${tone(keyColor, -0.02)} 55%, ${tone(keyColor, -0.25)} 100%)`,\n            boxShadow: `inset 0 1px 0 rgba(255,255,255,0.08), inset 0 ${u(-7)} ${u(18)} rgba(0,0,0,0.7), 0 0 0 1px ${tone(keyColor, -0.7)}`,\n          }}\n        >\n          {logo ? (\n            // eslint-disable-next-line @next/next/no-img-element\n            <img src={logo} alt=\"\" style={{ width: u(360 * logoShare), height: \"auto\", display: \"block\", objectFit: \"contain\", objectPosition: \"left top\" }} />\n          ) : (\n            <DotMark color={logoColor} width={u(360 * logoShare)} />\n          )}\n          <span\n            style={{\n              alignSelf: \"flex-end\",\n              fontFamily: \"Inter, ui-sans-serif, system-ui, sans-serif\",\n              fontSize: u(44),\n              fontWeight: 500,\n              letterSpacing: \"-0.01em\",\n              lineHeight: 1,\n              color: legendColor,\n            }}\n          >\n            {label}\n          </span>\n        </span>\n\n        {/* The pixel strip on the right edge: pixel 0 sits at the bottom, so the light climbs up */}\n        <span aria-hidden style={{ position: \"absolute\", right: u(7), top: u(92), display: \"flex\", flexDirection: \"column-reverse\", gap: u(3) }}>\n          {Array.from({ length: n }, (_, i) => {\n            const on = lit ? lit.has(i) : true;\n            return (\n              <span\n                key={i}\n                style={{\n                  display: \"block\",\n                  width: u(7),\n                  height: u(7),\n                  borderRadius: `max(1px, ${u(1)})`,\n                  background: accentColor,\n                  opacity: on ? 1 : 0.12,\n                  boxShadow: on ? `0 0 ${u(8)} ${accentColor}` : \"none\",\n                  transition: \"opacity 60ms linear\",\n                }}\n              />\n            );\n          })}\n        </span>\n      </button>\n    </div>\n  );\n}\n\n/** A length in the 360px design, scaled to the size shown */\nconst u = (px: number) => `calc(var(--u) * ${Math.round(px * 100) / 100})`;\n"}],"docs":"Pixel Keycap is ready. Props and a live canvas: https://bydot.co/component/pixel-keycap","meta":{"tier":"free","category":"UI Elements","version":"1.0.0"}}