{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"star-rating","type":"registry:component","title":"Star rating","description":"Hover to preview, click to commit with a little pop.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/star-rating.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  AnimatePresence,\n  motion,\n  type AnimationPlaybackControls,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Starting at rest and kicked upward, the spring peaks near 1.15 about 50ms\n// in and settles with one faint dip, all inside ~350ms.\nconst POP = { type: \"spring\", stiffness: 600, damping: 20 } as const;\nconst POP_VELOCITY = 6.3;\n// The stars behind the clicked one echo it at half strength (about 1.07).\nconst ECHO_VELOCITY = 3;\nconst ECHO_STAGGER = 0.03;\nconst WORDS = [\"Not rated\", \"Poor\", \"Fair\", \"Good\", \"Great\", \"Excellent\"];\n// Slow enough to read as the value settling rather than blinking, while\n// still well under the time it takes to sweep across the next star.\nconst FADE = { duration: 0.25, ease: [0.23, 1, 0.32, 1] } as const;\nconst FADE_OUT = { duration: 0.15, ease: [0.23, 1, 0.32, 1] } as const;\n\nfunction wordFor(value: number, max: number) {\n  // Maps any scale onto the five words, rounding halves up.\n  return WORDS[Math.ceil((value / max) * (WORDS.length - 1))];\n}\n\nexport function StarRating({\n  value,\n  onChange,\n  max = 5,\n  label = \"Rating\",\n  className,\n}: {\n  value: number;\n  onChange: (value: number) => void;\n  max?: number;\n  label?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [hover, setHover] = useState<number | null>(null);\n  const stars = useRef<(HTMLSpanElement | null)[]>([]);\n  const pops = useRef<AnimationPlaybackControls[]>([]);\n\n  useEffect(() => () => pops.current.forEach((p) => p.stop()), []);\n\n  const shown = hover ?? value;\n  const previewing = hover !== null && hover !== value;\n  const number = shown > 0 ? shown.toFixed(1) : \"\";\n\n  const valueAt = (clientX: number, box: DOMRect) => {\n    const raw = ((clientX - box.left) / box.width) * max;\n    // Left half of a star is a half point.\n    return Math.min(Math.max(Math.ceil(raw * 2) / 2, 0.5), max);\n  };\n\n  const pop = (next: number, echo: boolean) => {\n    if (reduceMotion || next <= 0) return;\n    pops.current.forEach((p) => p.stop());\n    const last = Math.ceil(next) - 1;\n    const first = echo ? 0 : last;\n    pops.current = [];\n    for (let i = last; i >= first; i--) {\n      const el = stars.current[i];\n      if (!el) continue;\n      // Targets the resting scale with an initial kick, so a second click\n      // mid-pop continues from wherever the star is instead of restarting.\n      pops.current.push(\n        animate(\n          el,\n          { scale: 1 },\n          {\n            ...POP,\n            velocity: i === last ? POP_VELOCITY : ECHO_VELOCITY,\n            delay: (last - i) * ECHO_STAGGER,\n          },\n        ),\n      );\n    }\n  };\n\n  const commit = (next: number, echo: boolean) => {\n    const clamped = Math.min(Math.max(next, 0), max);\n    if (clamped !== value) onChange(clamped);\n    pop(clamped, echo);\n  };\n\n  return (\n    <div className={cn(\"flex items-center gap-3\", className)}>\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-valuemin={0}\n        aria-valuemax={max}\n        aria-valuenow={value}\n        aria-valuetext={`${value} out of ${max}, ${wordFor(value, max)}`}\n        className=\"flex cursor-pointer touch-manipulation rounded-md outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\"\n        onPointerMove={(e) => {\n          // Touch has no hover; a tap goes straight to commit.\n          if (e.pointerType === \"touch\") return;\n          const box = e.currentTarget.getBoundingClientRect();\n          setHover(valueAt(e.clientX, box));\n        }}\n        onPointerLeave={() => setHover(null)}\n        onClick={(e) => {\n          const box = e.currentTarget.getBoundingClientRect();\n          commit(valueAt(e.clientX, box), true);\n        }}\n        onKeyDown={(e) => {\n          const delta = {\n            ArrowRight: 0.5,\n            ArrowUp: 0.5,\n            ArrowLeft: -0.5,\n            ArrowDown: -0.5,\n            PageUp: 1,\n            PageDown: -1,\n            Home: -max,\n            End: max,\n          }[e.key];\n          if (delta === undefined) return;\n          e.preventDefault();\n          // Keys retarget the hover preview too, so the two never disagree.\n          setHover(null);\n          // Arrows repeat while held, so only the landing star pops.\n          commit(value + delta, false);\n        }}\n      >\n        {Array.from({ length: max }, (_, i) => {\n          const fill = Math.min(Math.max(shown - i, 0), 1);\n          return (\n            // Padding instead of gaps, so there's no dead zone between stars.\n            <span key={i} className=\"p-0.5\">\n              <span\n                ref={(el) => {\n                  stars.current[i] = el;\n                }}\n                className=\"relative block size-6\"\n              >\n                <Star className=\"text-foreground/15\" />\n                {/* A short glide rather than a snap, so sweeping across the\n                    stars fills them like a pour. A CSS transition retargets\n                    mid-flight, so a fast sweep never lags behind the pointer. */}\n                <Star\n                  className=\"absolute inset-0 text-foreground transition-[clip-path] duration-200 ease-out motion-reduce:transition-none\"\n                  style={{ clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)` }}\n                />\n              </span>\n            </span>\n          );\n        })}\n      </div>\n\n      {/* Fixed width, so the stars never shift as the words change. */}\n      <div\n        aria-hidden\n        className={cn(\n          \"flex w-28 items-baseline gap-1.5 text-sm transition-[color] duration-250 ease-out\",\n          previewing ? \"text-muted-foreground\" : \"text-foreground\",\n        )}\n      >\n        <Crossfade id={number} reduceMotion={reduceMotion}>\n          <span className=\"font-medium tabular-nums\">{number}</span>\n        </Crossfade>\n        <Crossfade id={wordFor(shown, max)} reduceMotion={reduceMotion}>\n          <span className={cn(shown === 0 && \"text-muted-foreground\")}>\n            {wordFor(shown, max)}\n          </span>\n        </Crossfade>\n      </div>\n    </div>\n  );\n}\n\nfunction Crossfade({\n  id,\n  reduceMotion,\n  children,\n}: {\n  id: string;\n  reduceMotion: boolean | null;\n  children: React.ReactNode;\n}) {\n  // The new value rises into place as the old one drifts up and out, like a\n  // counter rolling over.\n  const enter = reduceMotion\n    ? { opacity: 0 }\n    : { opacity: 0, y: 4, filter: \"blur(4px)\" };\n  const leave = reduceMotion\n    ? { opacity: 0 }\n    : { opacity: 0, y: -4, filter: \"blur(4px)\" };\n  return (\n    // Both versions share one grid cell while they cross.\n    <span className=\"grid\">\n      <AnimatePresence initial={false}>\n        <motion.span\n          key={id}\n          className=\"col-start-1 row-start-1 whitespace-nowrap\"\n          initial={enter}\n          animate={{ opacity: 1, y: 0, filter: \"blur(0px)\", transition: FADE }}\n          exit={{ ...leave, transition: FADE_OUT }}\n        >\n          {children}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction Star({\n  className,\n  style,\n}: {\n  className?: string;\n  style?: React.CSSProperties;\n}) {\n  return (\n    <svg\n      viewBox=\"0 0 24 24\"\n      className={cn(\"size-6\", className)}\n      style={style}\n      fill=\"currentColor\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinejoin=\"round\"\n      aria-hidden\n    >\n      <path d=\"M12 3.2l2.7 5.47 6.03.88-4.36 4.25 1.03 6-5.4-2.84-5.4 2.84 1.03-6-4.36-4.25 6.03-.88L12 3.2z\" />\n    </svg>\n  );\n}\n\nexport default function StarRatingDemo() {\n  const [rating, setRating] = useState(3.5);\n  return (\n    <div className=\"flex flex-col items-start gap-2\">\n      <p className=\"text-sm text-muted-foreground\">How was your stay?</p>\n      <StarRating value={rating} onChange={setRating} label=\"Stay rating\" />\n    </div>\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"}],"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/star-rating"}