{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"keycap-hint","type":"registry:component","title":"Keycap hint","description":"Keycaps that sink when you press the real keys.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/keycap-hint.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useEffect,\n  useImperativeHandle,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type Ref,\n} from \"react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\nconst subscribeNever = () => () => {};\n// null on the server and during hydration, so the modifier label is only\n// decided once we can read the platform.\nfunction usePlatformIsMac() {\n  return useSyncExternalStore<boolean | null>(\n    subscribeNever,\n    () => /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent),\n    () => null,\n  );\n}\n\ntype KeyName = \"mod\" | \"shift\" | \"alt\" | string;\n\nfunction matchesKey(k: KeyName, e: KeyboardEvent, isMac: boolean) {\n  if (k === \"mod\") return e.key === (isMac ? \"Meta\" : \"Control\");\n  if (k === \"shift\") return e.key === \"Shift\";\n  if (k === \"alt\") return e.key === \"Alt\";\n  // code, not key, so Shift or a non-Latin layout still lights the cap.\n  return e.code === `Key${k.toUpperCase()}` || e.key.toLowerCase() === k.toLowerCase();\n}\n\nfunction isHeld(k: KeyName, e: KeyboardEvent, isMac: boolean) {\n  if (k === \"mod\") return isMac ? e.metaKey : e.ctrlKey;\n  if (k === \"shift\") return e.shiftKey;\n  if (k === \"alt\") return e.altKey;\n  return matchesKey(k, e, isMac);\n}\n\nfunction labelFor(k: KeyName, isMac: boolean | null) {\n  if (isMac === null && (k === \"mod\" || k === \"shift\" || k === \"alt\")) return \"\";\n  if (k === \"mod\") return isMac ? \"⌘\" : \"Ctrl\";\n  if (k === \"shift\") return isMac ? \"⇧\" : \"Shift\";\n  if (k === \"alt\") return isMac ? \"⌥\" : \"Alt\";\n  return k.toUpperCase();\n}\n\nfunction spokenFor(k: KeyName, isMac: boolean | null) {\n  if (k === \"mod\") return isMac ? \"Command\" : \"Control\";\n  if (k === \"shift\") return \"Shift\";\n  if (k === \"alt\") return isMac ? \"Option\" : \"Alt\";\n  return k.toUpperCase();\n}\n\nconst DEFAULT_KEYS: KeyName[] = [\"mod\", \"k\"];\n\nexport type KeycapHintHandle = {\n  /** Presses the chord on screen, as a hint or a demo. Calls onTrigger. */\n  play: (opts?: { beat?: number; hold?: number }) => void;\n  /** Lets go of every key and clears the confirmation. */\n  reset: () => void;\n};\n\nexport function KeycapHint({\n  keys = DEFAULT_KEYS,\n  action = \"to search\",\n  confirmation = \"Search opened\",\n  onTrigger,\n  className,\n  ref,\n}: {\n  keys?: KeyName[];\n  action?: string;\n  confirmation?: string;\n  onTrigger?: () => void;\n  className?: string;\n  ref?: Ref<KeycapHintHandle>;\n}) {\n  const isMac = usePlatformIsMac();\n  const reduceMotion = useReducedMotion();\n  const [pressed, setPressed] = useState<Set<number>>(() => new Set());\n  const [confirmed, setConfirmed] = useState(false);\n  const confirmTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const chordTimers = useRef<ReturnType<typeof setTimeout>[]>([]);\n  const onTriggerRef = useRef(onTrigger);\n  useEffect(() => {\n    onTriggerRef.current = onTrigger;\n  });\n\n  const setKey = (i: number, down: boolean) =>\n    setPressed((prev) => {\n      if (prev.has(i) === down) return prev;\n      const next = new Set(prev);\n      if (down) next.add(i);\n      else next.delete(i);\n      return next;\n    });\n\n  const confirm = () => {\n    setConfirmed(true);\n    onTriggerRef.current?.();\n    clearTimeout(confirmTimer.current);\n    // Long enough to register, short enough to be gone before the next try.\n    confirmTimer.current = setTimeout(() => setConfirmed(false), 1400);\n  };\n  const confirmRef = useRef(confirm);\n  useEffect(() => {\n    confirmRef.current = confirm;\n  });\n\n  useEffect(() => {\n    if (isMac === null) return;\n    const down = (e: KeyboardEvent) => {\n      keys.forEach((k, i) => {\n        if (matchesKey(k, e, isMac)) setKey(i, true);\n      });\n      if (!e.repeat && keys.every((k) => isHeld(k, e, isMac))) {\n        // Claim the chord so Ctrl+K doesn't jump to the browser's search.\n        e.preventDefault();\n        confirmRef.current();\n      }\n    };\n    const up = (e: KeyboardEvent) => {\n      // macOS never sends keyup for other keys while Command is held, so\n      // letting go of Command has to release everything.\n      if (isMac && e.key === \"Meta\") {\n        setPressed(new Set());\n        return;\n      }\n      keys.forEach((k, i) => {\n        if (matchesKey(k, e, isMac)) setKey(i, false);\n      });\n    };\n    // A keyup that lands in another window never arrives.\n    const reset = () => setPressed(new Set());\n    window.addEventListener(\"keydown\", down);\n    window.addEventListener(\"keyup\", up);\n    window.addEventListener(\"blur\", reset);\n    return () => {\n      window.removeEventListener(\"keydown\", down);\n      window.removeEventListener(\"keyup\", up);\n      window.removeEventListener(\"blur\", reset);\n    };\n  }, [isMac, keys]);\n\n  useEffect(\n    () => () => {\n      clearTimeout(confirmTimer.current);\n      chordTimers.current.forEach(clearTimeout);\n    },\n    [],\n  );\n\n  // A click (or Enter on the button) plays the chord the way hands would:\n  // each key goes down a beat after the last, then they all come up.\n  const playChord = ({ beat = 70, hold = 90 } = {}) => {\n    chordTimers.current.forEach(clearTimeout);\n    chordTimers.current = [];\n    keys.forEach((_, i) =>\n      chordTimers.current.push(setTimeout(() => setKey(i, true), i * beat)),\n    );\n    chordTimers.current.push(\n      setTimeout(() => {\n        setPressed(new Set());\n        confirm();\n      }, keys.length * beat + hold),\n    );\n  };\n\n  useImperativeHandle(ref, () => ({\n    play: playChord,\n    reset: () => {\n      chordTimers.current.forEach(clearTimeout);\n      chordTimers.current = [];\n      clearTimeout(confirmTimer.current);\n      setPressed(new Set());\n      setConfirmed(false);\n    },\n  }));\n\n  const spoken = keys.map((k) => spokenFor(k, isMac)).join(\" \");\n\n  return (\n    <span\n      className={cn(\n        \"relative inline-flex items-center gap-2 text-sm text-muted-foreground\",\n        className,\n      )}\n    >\n      <span>Press</span>\n      <button\n        type=\"button\"\n        aria-label={`${spoken}, ${action.replace(/^to /, \"\")}`}\n        // Keyboard activation plays the chord; a mouse click already pressed\n        // the cap under the pointer, so it only confirms.\n        onClick={(e) => (e.detail === 0 ? playChord() : confirm())}\n        className=\"-mx-1 flex touch-manipulation items-center gap-1 rounded-lg px-1 pt-0.5 pb-1.5 outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-1 focus-visible:outline-foreground\"\n      >\n        {keys.map((k, i) => (\n          <Keycap\n            key={k + i}\n            label={labelFor(k, isMac)}\n            pressed={pressed.has(i)}\n            reduceMotion={reduceMotion}\n            onPress={(down) => setKey(i, down)}\n          />\n        ))}\n      </button>\n      <span className=\"relative\">\n        <span\n          className={cn(\n            \"inline-block transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n            confirmed\n              ? \"-translate-y-1 opacity-0 blur-[3px] duration-150 motion-reduce:translate-y-0 motion-reduce:filter-none\"\n              : \"translate-y-0 opacity-100 filter-none duration-200\",\n          )}\n        >\n          {action}\n        </span>\n        {/* Swaps in over the action text, out of flow so the row never\n            changes width. */}\n        <span\n          aria-hidden\n          className={cn(\n            \"absolute inset-y-0 left-0 inline-flex items-center gap-1.5 whitespace-nowrap text-foreground transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n            confirmed\n              ? \"translate-y-0 opacity-100 filter-none duration-200\"\n              : \"translate-y-1 opacity-0 blur-[3px] duration-150 motion-reduce:translate-y-0 motion-reduce:filter-none\",\n          )}\n        >\n          <svg\n            viewBox=\"0 0 16 16\"\n            className=\"size-3.5\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={1.75}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          >\n            <path d=\"m3.5 8.5 3 3 6-7\" />\n          </svg>\n          {confirmation}\n        </span>\n      </span>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {confirmed ? confirmation : \"\"}\n      </span>\n    </span>\n  );\n}\n\nfunction Keycap({\n  label,\n  pressed,\n  reduceMotion,\n  onPress,\n}: {\n  label: string;\n  pressed: boolean;\n  reduceMotion: boolean | null;\n  onPress: (down: boolean) => void;\n}) {\n  return (\n    <span\n      onPointerDown={(e) => {\n        if (e.button === 0) onPress(true);\n      }}\n      onPointerUp={() => onPress(false)}\n      onPointerLeave={() => onPress(false)}\n      className={cn(\n        // min-w keeps single letters square while \"Ctrl\" grows sideways.\n        \"relative inline-flex h-7 min-w-7 items-center justify-center rounded-md border border-border bg-background px-1.5 font-sans text-[13px] leading-none font-medium text-foreground dark:bg-muted\",\n        // The skirt is a hard 3px shadow in the border color: the cap sits\n        // on it at rest and drops onto it when pressed. The soft shadow\n        // under it (raw black, it is a cast shadow) collapses with it.\n        \"shadow-[0_3px_0_0_var(--border),0_4px_8px_-3px_oklch(0_0_0/0.18)]\",\n        !reduceMotion && \"transition-[translate,box-shadow]\",\n        pressed\n          ? \"translate-y-[3px] shadow-[0_0_0_0_var(--border),0_1px_2px_-1px_oklch(0_0_0/0.18)] duration-[40ms] ease-out\"\n          : // Springs back a touch slower than it goes down, like a real\n            // switch returning.\n            \"translate-y-0 duration-[140ms] ease-[cubic-bezier(0.23,1,0.32,1)]\",\n        // Holds the label's space until the platform is known.\n        label === \"\" && \"invisible\",\n      )}\n    >\n      <span className={cn(label === \"⌘\" && \"text-[15px]\")}>{label}</span>\n    </span>\n  );\n}\n\nexport default function KeycapHintDemo() {\n  const play = usePreviewPlay();\n  const hint = useRef<KeycapHintHandle>(null);\n\n  // Index card hover: a hand presses the chord at an unhurried pace, then\n  // again after the confirmation has come and gone.\n  useEffect(() => {\n    const h = hint.current;\n    if (!play || !h) return;\n    const press = () => h.play({ beat: 120, hold: 220 });\n    const first = setTimeout(press, 250);\n    const loop = setInterval(press, 3000);\n    return () => {\n      clearTimeout(first);\n      clearInterval(loop);\n      h.reset();\n    };\n  }, [play]);\n\n  return (\n    <KeycapHint\n      ref={hint}\n      action=\"to search\"\n      // The card is sized to the resting row; the full confirmation would\n      // run past its edge.\n      confirmation={play === null ? undefined : \"Opened\"}\n    />\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"categories":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/keycap-hint"}