{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"memo-pill","type":"registry:ui","title":"Memo Pill","description":"A voice-note recorder pill that springs open into live waveform bars and a timer, then collapses the take into a playable, sendable waveform. Input is simulated.","dependencies":["motion","lucide-react"],"registryDependencies":[],"files":[{"path":"registry/ui/memo-pill.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useEffectEvent, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useTransform } from \"motion/react\";\nimport { Mic, Pause, Play, Send, Square, Trash2 } from \"lucide-react\";\n\ntype Mode = \"idle\" | \"recording\" | \"recorded\";\n\nexport interface MemoPillProps {\n  /** Number of waveform bars. */\n  bars?: number;\n  /** Recording accent color. */\n  color?: string;\n  /** Recording stops by itself after this many seconds. */\n  maxSeconds?: number;\n  onStart?: () => void;\n  /** Called with the recorded length in seconds. */\n  onStop?: (seconds: number) => void;\n  onSend?: (seconds: number) => void;\n  onDiscard?: () => void;\n  className?: string;\n}\n\nconst fmt = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, \"0\")}`;\nconst pop = { initial: { opacity: 0, scale: 0.6 }, animate: { opacity: 1, scale: 1 }, exit: { opacity: 0, scale: 0.6 } };\n\nexport function MemoPill({\n  bars = 28,\n  color = \"#ef4444\",\n  maxSeconds = 60,\n  onStart,\n  onStop,\n  onSend,\n  onDiscard,\n  className,\n}: MemoPillProps) {\n  const reduce = useReducedMotion();\n  const [mode, setMode] = useState<Mode>(\"idle\");\n  const [secs, setSecs] = useState(0);\n  const [wave, setWave] = useState<number[]>([]);\n  const [playing, setPlaying] = useState(false);\n  const barRefs = useRef<(HTMLSpanElement | null)[]>([]);\n  const history = useRef<number[]>([]);\n  const elapsed = useRef(0);\n  const playback = useRef<ReturnType<typeof animate> | null>(null);\n  const progress = useMotionValue(0);\n  const clip = useTransform(progress, (p) => `inset(0 ${(1 - p) * 100}% 0 0)`);\n\n  const finish = () => {\n    // Squash the whole take into `bars` peaks for the playback waveform.\n    const h = history.current.length ? history.current : [0.1];\n    const peaks = Array.from({ length: bars }, (_, i) => {\n      const a = Math.floor((i * h.length) / bars);\n      const b = Math.max(a + 1, Math.floor(((i + 1) * h.length) / bars));\n      return Math.max(...h.slice(a, b), 0);\n    });\n    const top = Math.max(...peaks) || 1;\n    setWave(peaks.map((v) => Math.max(0.1, v / top))); // normalized so the loudest bar fills the pill\n    const s = Math.max(1, Math.round(elapsed.current));\n    setSecs(s);\n    setMode(\"recorded\");\n    onStop?.(s);\n  };\n  const onLimit = useEffectEvent(finish);\n\n  // Simulated microphone: a speech-like envelope (words and pauses) with jitter,\n  // scrolled right-to-left. Writes straight to the bars, React only sees the seconds.\n  useEffect(() => {\n    if (mode !== \"recording\") return;\n    const levels = new Array<number>(bars).fill(0.08);\n    history.current = [];\n    let env = 0.3;\n    let target = 0.6;\n    let last = 0;\n    let shown = 0;\n    let raf = 0;\n    const t0 = performance.now();\n    const tick = (now: number) => {\n      elapsed.current = (now - t0) / 1000;\n      if (elapsed.current >= maxSeconds) return onLimit();\n      if (now - last > 75) {\n        last = now;\n        if (Math.random() < 0.14) target = Math.random() < 0.25 ? 0.05 : 0.35 + Math.random() * 0.65;\n        env += (target - env) * 0.35;\n        const lv = Math.min(1, Math.max(0.08, env * (0.5 + Math.random() * 0.5)));\n        levels.shift();\n        levels.push(lv);\n        history.current.push(lv);\n        levels.forEach((l, i) => {\n          const el = barRefs.current[i];\n          if (el) el.style.transform = `scaleY(${l})`;\n        });\n      }\n      const s = Math.floor(elapsed.current);\n      if (s !== shown) setSecs((shown = s));\n      raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [mode, bars, maxSeconds]);\n\n  useEffect(() => () => playback.current?.stop(), []);\n\n  const start = () => {\n    setSecs(0);\n    setMode(\"recording\");\n    onStart?.();\n  };\n\n  const togglePlay = () => {\n    if (playing) {\n      playback.current?.stop();\n      return setPlaying(false);\n    }\n    if (progress.get() >= 1) progress.set(0);\n    setPlaying(true);\n    playback.current = animate(progress, 1, { duration: secs * (1 - progress.get()), ease: \"linear\" });\n    playback.current.then(() => {\n      setPlaying(false);\n      progress.set(0);\n    });\n  };\n\n  const reset = () => {\n    playback.current?.stop();\n    progress.set(0);\n    setPlaying(false);\n    setMode(\"idle\");\n  };\n\n  const iconBtn =\n    \"grid size-9 shrink-0 place-items-center rounded-full outline-none transition-transform active:scale-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card\";\n  const spring = reduce ? { duration: 0 } : { type: \"spring\" as const, stiffness: 420, damping: 24 };\n\n  return (\n    <motion.div\n      layout\n      transition={spring}\n      style={{ borderRadius: 999 }}\n      className={`inline-flex h-12 items-center gap-2 border border-border bg-card p-1.5 shadow-lg shadow-black/20 ${className ?? \"\"}`}\n    >\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {mode === \"recording\" ? \"Recording\" : mode === \"recorded\" ? `Recorded ${fmt(secs)}` : \"\"}\n      </span>\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        {mode === \"idle\" && (\n          <motion.div key=\"idle\" layout {...pop} transition={spring} className=\"flex items-center gap-2 pr-3\">\n            <button type=\"button\" onClick={start} aria-label=\"Start recording\" className={`${iconBtn} bg-primary text-primary-foreground`}>\n              <Mic className=\"size-4\" />\n            </button>\n            <span className=\"text-sm font-medium text-foreground\">Record a voice note</span>\n          </motion.div>\n        )}\n\n        {mode === \"recording\" && (\n          <motion.div key=\"rec\" layout {...pop} transition={spring} className=\"flex items-center gap-3 pr-3\">\n            <button\n              type=\"button\"\n              onClick={finish}\n              aria-label=\"Stop recording\"\n              className={`${iconBtn} relative text-white`}\n              style={{ background: color }}\n            >\n              {!reduce && (\n                <motion.span\n                  aria-hidden\n                  className=\"absolute inset-0 rounded-full\"\n                  style={{ background: color }}\n                  animate={{ scale: [1, 1.6], opacity: [0.5, 0] }}\n                  transition={{ duration: 1.2, repeat: Infinity, ease: \"easeOut\" }}\n                />\n              )}\n              <Square className=\"relative size-3.5 fill-current\" />\n            </button>\n            <span aria-hidden className=\"flex h-7 items-center gap-[3px]\" style={{ color }}>\n              {Array.from({ length: bars }, (_, i) => (\n                <span\n                  key={i}\n                  ref={(el) => {\n                    barRefs.current[i] = el;\n                  }}\n                  className=\"h-full w-[3px] rounded-full bg-current transition-transform duration-75\"\n                  style={{ transform: \"scaleY(0.08)\" }}\n                />\n              ))}\n            </span>\n            <span role=\"timer\" className=\"w-9 text-right text-sm font-medium text-foreground tabular-nums\">\n              {fmt(secs)}\n            </span>\n          </motion.div>\n        )}\n\n        {mode === \"recorded\" && (\n          <motion.div key=\"done\" layout {...pop} transition={spring} className=\"flex items-center gap-3\">\n            <button\n              type=\"button\"\n              onClick={togglePlay}\n              aria-label={playing ? \"Pause\" : \"Play recording\"}\n              className={`${iconBtn} bg-primary text-primary-foreground`}\n            >\n              {playing ? <Pause className=\"size-4 fill-current\" /> : <Play className=\"size-4 translate-x-px fill-current\" />}\n            </button>\n            <span aria-hidden className=\"relative grid h-7\">\n              {[false, true].map((lit) => (\n                <motion.span\n                  key={String(lit)}\n                  className={`col-start-1 row-start-1 flex h-full items-center gap-[3px] ${lit ? \"text-foreground\" : \"text-muted-foreground/50\"}`}\n                  style={lit ? { clipPath: clip } : undefined}\n                >\n                  {wave.map((l, i) => (\n                    <motion.span\n                      key={i}\n                      className=\"h-full w-[3px] origin-center rounded-full bg-current\"\n                      initial={{ scaleY: 0.08 }}\n                      animate={{ scaleY: l }}\n                      transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 14, delay: i * 0.012 }}\n                    />\n                  ))}\n                </motion.span>\n              ))}\n            </span>\n            <span className=\"w-9 text-right text-sm font-medium text-foreground tabular-nums\">{fmt(secs)}</span>\n            <button\n              type=\"button\"\n              onClick={() => {\n                reset();\n                onDiscard?.();\n              }}\n              aria-label=\"Discard recording\"\n              className={`${iconBtn} text-muted-foreground hover:bg-muted hover:text-foreground`}\n            >\n              <Trash2 className=\"size-4\" />\n            </button>\n            <button\n              type=\"button\"\n              onClick={() => {\n                reset();\n                onSend?.(secs);\n              }}\n              aria-label=\"Send recording\"\n              className={`${iconBtn} text-white`}\n              style={{ background: color }}\n            >\n              <Send className=\"size-4 -translate-x-px\" />\n            </button>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </motion.div>\n  );\n}\n"}]}