{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"mood-slider","type":"registry:component","title":"Mood slider","description":"The thumb is a face that frowns, grins and leans into the drag as you rate your day.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/mood-slider.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  useSpring,\n  useTransform,\n  useVelocity,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst MOODS = [\"Rough\", \"Meh\", \"Okay\", \"Good\", \"Great\"];\nconst moodOf = (v: number) => Math.min(4, Math.floor(v / 20));\n// The mood's colours are the point of it, so raw values: a cool dusk blue,\n// a neutral grey, a warm amber. Going through the grey keeps the in-between\n// colours clean instead of muddy.\nconst COOL = \"#8ea6c8\";\nconst NEUTRAL = \"#bdbdbd\";\nconst WARM = \"#f2b24e\";\n\n// The thumb is a face: its mouth bends from frown to grin with the value,\n// worried brows fade in at the low end, and the eyes smile shut at the top.\nfunction Face({\n  value,\n  blink,\n  tilt,\n  color,\n}: {\n  value: MotionValue<number>;\n  blink: MotionValue<number>;\n  tilt: MotionValue<number>;\n  color: MotionValue<string>;\n}) {\n  const mouth = useTransform(value, (v) => {\n    const t = v / 100;\n    const corners = 27.5 - t * 2.5; // corners lift as the smile grows\n    const mid = 23 + t * 12; // the mouth's belly, above the corners for a frown\n    return `M13 ${corners} Q21 ${mid} 29 ${corners}`;\n  });\n  const brows = useTransform(value, [0, 35], [1, 0]);\n  const squint = useTransform(value, [80, 100], [1, 0.62]);\n  const eyes = useTransform([squint, blink], ([s, b]: number[]) => s * b);\n\n  return (\n    <motion.svg\n      viewBox=\"0 0 42 42\"\n      className=\"size-11 drop-shadow-[0_2px_4px_oklch(0_0_0/0.2)]\"\n      style={{ rotate: tilt }}\n      aria-hidden\n    >\n      <motion.circle cx=\"21\" cy=\"21\" r=\"20\" style={{ fill: color }} />\n      <circle cx=\"21\" cy=\"21\" r=\"20\" fill=\"none\" stroke=\"#000\" strokeOpacity=\"0.08\" />\n      <motion.g style={{ opacity: brows }} stroke=\"#1c1c1c\" strokeWidth=\"1.6\" strokeLinecap=\"round\">\n        <path d=\"M12 13.5l5-1.8\" />\n        <path d=\"M30 13.5l-5-1.8\" />\n      </motion.g>\n      <motion.g style={{ scaleY: eyes, originY: \"17px\" }} fill=\"#1c1c1c\">\n        <ellipse cx=\"15.5\" cy=\"17\" rx=\"1.9\" ry=\"2.2\" />\n        <ellipse cx=\"26.5\" cy=\"17\" rx=\"1.9\" ry=\"2.2\" />\n      </motion.g>\n      <motion.path\n        d={mouth}\n        fill=\"none\"\n        stroke=\"#1c1c1c\"\n        strokeWidth=\"1.9\"\n        strokeLinecap=\"round\"\n      />\n    </motion.svg>\n  );\n}\n\nexport function MoodSlider({\n  question = \"How was your day?\",\n  defaultValue = 60,\n  value: external,\n  onChange,\n  className,\n}: {\n  question?: string;\n  defaultValue?: number;\n  // A motion value to drive it from outside (the card preview).\n  value?: MotionValue<number>;\n  onChange?: (value: number) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const own = useMotionValue(defaultValue);\n  const value = external ?? own;\n  const input = useRef<HTMLInputElement>(null);\n  const [mood, setMood] = useState(moodOf(value.get()));\n\n  // Only the word re-renders, and only when it changes; everything else\n  // follows the value frame by frame without React.\n  useEffect(\n    () =>\n      value.on(\"change\", (v) => {\n        setMood(moodOf(v));\n        if (input.current && Number(input.current.value) !== Math.round(v)) {\n          input.current.value = String(Math.round(v));\n        }\n      }),\n    [value],\n  );\n\n  const color = useTransform(value, [0, 50, 100], [COOL, NEUTRAL, WARM]);\n  const fill = useTransform(value, (v) => `${v}%`);\n  const left = useTransform(value, (v) => `calc(${v / 100} * (100% - 44px))`);\n  // Leans into the drag a little, and rights itself when you stop.\n  const speed = useVelocity(value);\n  const tilt = useSpring(\n    useTransform(speed, (s) => (reduceMotion ? 0 : Math.max(-16, Math.min(16, s * 0.06)))),\n    { stiffness: 300, damping: 18 },\n  );\n  const blink = useMotionValue(1);\n  const doBlink = () => {\n    if (reduceMotion) return;\n    animate(blink, [1, 0.1, 1], { duration: 0.22, times: [0, 0.45, 1] });\n  };\n\n  return (\n    <div\n      className={cn(\n        \"w-[min(380px,100%)] rounded-2xl bg-background p-6 shadow-raised\",\n        className,\n      )}\n    >\n      <p className=\"text-[14px] text-muted-foreground\">{question}</p>\n      <div className=\"relative mt-1 h-8\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.p\n            key={mood}\n            initial={{ opacity: 0, y: 6, filter: \"blur(4px)\" }}\n            animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={{ opacity: 0, y: -6, filter: \"blur(4px)\", transition: { duration: 0.12 } }}\n            transition={reduceMotion ? { duration: 0 } : { duration: 0.22, ease: EASE_OUT }}\n            className=\"text-[24px] font-semibold tracking-tight text-foreground\"\n          >\n            {MOODS[mood]}\n          </motion.p>\n        </AnimatePresence>\n      </div>\n\n      <div className=\"relative mt-5 h-11\">\n        <div className=\"absolute inset-x-[22px] top-1/2 h-2 -translate-y-1/2 overflow-hidden rounded-full bg-muted shadow-[inset_0_0_0_1px_var(--border)]\">\n          <motion.div className=\"h-full rounded-full\" style={{ width: fill, backgroundColor: color }} />\n        </div>\n        <motion.div className=\"pointer-events-none absolute top-0\" style={{ left }}>\n          <Face value={value} blink={blink} tilt={tilt} color={color} />\n        </motion.div>\n        {/* The real control: a native range, invisible, with a thumb the\n            size of the face so dragging lines up exactly. */}\n        <input\n          ref={input}\n          type=\"range\"\n          min={0}\n          max={100}\n          defaultValue={defaultValue}\n          aria-label={question}\n          aria-valuetext={MOODS[mood]}\n          onInput={(e) => {\n            const v = Number(e.currentTarget.value);\n            value.set(v);\n            onChange?.(v);\n          }}\n          onPointerUp={doBlink}\n          onKeyUp={doBlink}\n          className=\"peer absolute inset-0 h-full w-full cursor-grab appearance-none bg-transparent opacity-0 active:cursor-grabbing [&::-moz-range-thumb]:size-11 [&::-moz-range-thumb]:border-0 [&::-webkit-slider-thumb]:size-11 [&::-webkit-slider-thumb]:appearance-none\"\n        />\n        {/* Focus shows on the face, since the real thumb is invisible. */}\n        <motion.div\n          aria-hidden\n          className=\"pointer-events-none absolute top-0 size-11 rounded-full outline-2 outline-offset-2 outline-transparent peer-focus-visible:outline-solid peer-focus-visible:outline-[var(--focus-ring)]\"\n          style={{ left }}\n        />\n      </div>\n      <div className=\"mt-2 flex justify-between px-1 text-[12px] text-muted-foreground\">\n        <span>Rough</span>\n        <span>Great</span>\n      </div>\n    </div>\n  );\n}\n\nexport default function MoodSliderDemo() {\n  const play = usePreviewPlay();\n  const value = useMotionValue(60);\n\n  // The card's hover show: a slow slide down to a rough day, a quick swing\n  // up to a great one, then settling at good.\n  useEffect(() => {\n    if (play !== true) return;\n    let stopped = false;\n    let current: ReturnType<typeof animate> | undefined;\n    const to = (v: number, duration: number) =>\n      new Promise<void>((done) => {\n        current = animate(value, v, { duration, ease: [0.45, 0, 0.55, 1], onComplete: done });\n      });\n    const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));\n    (async () => {\n      while (!stopped) {\n        await pause(300);\n        if (stopped) break;\n        await to(12, 1.3);\n        await pause(700);\n        if (stopped) break;\n        await to(92, 0.9);\n        await pause(900);\n        if (stopped) break;\n        await to(66, 0.8);\n        await pause(1200);\n      }\n    })();\n    return () => {\n      stopped = true;\n      current?.stop();\n      animate(value, 60, { duration: 0.4, ease: EASE_OUT });\n    };\n  }, [play, value]);\n\n  return <MoodSlider value={value} defaultValue={60} />;\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"}],"cssVars":{"light":{"focus-ring":"oklch(0.2 0 0 / 0.38)","shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"focus-ring":"oklch(0.95 0 0 / 0.45)","shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/mood-slider"}