{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"star-rating-interactive","type":"registry:component","title":"Interactive Star Rating","description":"A star rating input with half-step precision: drag or tap across the stars, hover to preview, and a chosen rating pops in a wave with a burst of sparks and a changing word label. Radio-group keyboard support, a fractional read-only mode, controlled or not. No dependencies.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/star-rating-interactive.tsx","content":"\"use client\";\n\nimport { useId, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent, type KeyboardEvent as ReactKeyboardEvent } from \"react\";\n\nconst SAFE_COLOR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\\([\\d\\s.,%/-]+\\))$/i;\nconst SAFE_SIZE = /^(\\d+(\\.\\d+)?(px|rem|em|cqw|vw)|(min|max|clamp|calc)\\([\\d\\s.,%+*/()a-z-]+\\))$/i;\n\nconst STAR = \"M12 2.6l2.9 5.9 6.5.95-4.7 4.58 1.1 6.47L12 17.45l-5.8 3.05 1.1-6.47L2.6 9.45l6.5-.95z\";\nconst DEFAULT_LABELS = [\"Poor\", \"Fair\", \"Good\", \"Great\", \"Excellent\"];\nconst SPARKS = [0, 1, 2, 3, 4, 5];\n\nconst CSS = [\n  \":where(.sr){display:flex;align-items:center;gap:14px;-webkit-tap-highlight-color:transparent}\",\n  \".sr[data-disabled]{opacity:.45}\",\n  \".sr-row{position:relative;display:flex;gap:var(--sr-gap,4px);padding:6px 0;margin:-6px 0;touch-action:pan-y;user-select:none;-webkit-user-select:none}\",\n  \".sr[data-live] .sr-row{cursor:pointer}\",\n  \".sr-star{position:relative;flex:none;width:var(--sr-size,28px);height:var(--sr-size,28px);transition:transform .38s cubic-bezier(.34,1.56,.64,1)}\",\n  \".sr-star[data-hot]{transform:scale(1.13)}\",\n  \".sr-star[data-hot][data-down]{transform:scale(.94);transition-duration:.12s}\",\n  \".sr-in{position:absolute;inset:0}\",\n  \".sr-in[data-pop]{animation:sr-pop .6s cubic-bezier(.34,1.56,.64,1) both}\",\n  \".sr-svg{display:block;width:var(--sr-size,28px);height:var(--sr-size,28px);overflow:visible}\",\n  \".sr-back{position:absolute;left:0;top:0;opacity:.5}\",\n  \".sr-clip{position:absolute;left:0;top:0;bottom:0;overflow:hidden;transition:width .22s cubic-bezier(.2,.8,.2,1),opacity .2s}\",\n  \".sr[data-preview] .sr-clip{opacity:.78}\",\n  \".sr-r{position:absolute;inset:-3px;margin:0;padding:0;border:0;border-radius:30%;background:none;appearance:none;-webkit-appearance:none;pointer-events:none;color:inherit}\",\n  \".sr-r:focus{outline:none}\",\n  \".sr-r:focus-visible{outline:2px solid currentColor;outline-offset:1px;border-radius:30%}\",\n  \".sr-sp{position:absolute;left:50%;top:50%;width:calc(var(--sr-size,28px)*.26);height:calc(var(--sr-size,28px)*.26);min-width:6px;min-height:6px;background:currentColor;clip-path:polygon(50% 0,63% 37%,100% 50%,63% 63%,50% 100%,37% 63%,0 50%,37% 37%);pointer-events:none;animation:sr-spark .62s cubic-bezier(.2,.8,.2,1) both}\",\n  \".sr-label{display:flex;align-items:baseline;gap:.5em;min-width:7.4em;font-size:max(13px,calc(var(--sr-size,28px)*.36));line-height:1.2;font-variant-numeric:tabular-nums}\",\n  \".sr-word{display:inline-block;font-weight:600;animation:sr-word .3s cubic-bezier(.2,.8,.2,1) both}\",\n  \".sr-word[data-empty]{font-weight:500;opacity:.55}\",\n  \".sr-num{opacity:.5;font-size:.85em}\",\n  \".sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}\",\n  \"@keyframes sr-pop{0%{transform:scale(.7) rotate(-14deg)}45%{transform:scale(1.34) rotate(6deg)}100%{transform:scale(1) rotate(0)}}\",\n  \"@keyframes sr-spark{0%{opacity:1;transform:translate(-50%,-50%) rotate(var(--a)) translateX(calc(var(--sr-size,28px)*.28)) scale(.35)}70%{opacity:1}100%{opacity:0;transform:translate(-50%,-50%) rotate(var(--a)) translateX(calc(var(--sr-size,28px)*var(--d,.95))) scale(1) rotate(80deg)}}\",\n  \"@keyframes sr-word{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\",\n  \"@media (prefers-reduced-motion:reduce){.sr-star,.sr-clip{transition-duration:.01ms!important}.sr-star[data-hot]{transform:none}.sr-in[data-pop],.sr-sp,.sr-word{animation:none!important}.sr-sp{display:none}}\",\n].join(\"\\n\");\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));\nconst fmt = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(1));\n\nexport interface StarRatingProps {\n  /** Number of stars. Default 5. */\n  max?: number;\n  /** Starting rating when uncontrolled. Default 0. */\n  defaultRating?: number;\n  /** Controlled rating. */\n  value?: number;\n  /** Called with the new rating on every commit. */\n  onChange?: (rating: number) => void;\n  /** 1 = whole stars (default), 0.5 = half stars. */\n  precision?: 1 | 0.5;\n  /** Display only. Fractional ratings (4.3) draw a partly filled star. */\n  readOnly?: boolean;\n  disabled?: boolean;\n  /** Star size: a number of px, or a CSS length like \"min(10cqw, 56px)\". Default 28. */\n  size?: number | string;\n  /** Hex / rgb / hsl. Default #ef4444. */\n  color?: string;\n  /** Show the word label (\"Great\") beside the stars. Default false. */\n  showLabel?: boolean;\n  /** Words for the label, lowest to highest. */\n  labels?: string[];\n  /** Label while nothing is rated. */\n  emptyLabel?: string;\n  /** Accessible name of the group. */\n  label?: string;\n  className?: string;\n}\n\ntype Burst = { id: number; from: number; to: number };\n\nexport function StarRating({\n  max = 5,\n  defaultRating = 0,\n  value,\n  onChange,\n  precision = 1,\n  readOnly = false,\n  disabled = false,\n  size,\n  color = \"#ef4444\",\n  showLabel = false,\n  labels = DEFAULT_LABELS,\n  emptyLabel = \"Tap to rate\",\n  label = \"Rating\",\n  className = \"\",\n}: StarRatingProps) {\n  const n = clamp(Math.round(Number.isFinite(max) ? max : 5), 1, 12);\n  const step = precision === 0.5 ? 0.5 : 1;\n  const isControlled = value !== undefined;\n  const [inner, setInner] = useState(defaultRating);\n  const rating = clamp((isControlled ? value : inner) || 0, 0, n);\n  const [hover, setHover] = useState<number | null>(null);\n  const [drag, setDrag] = useState<number | null>(null);\n  const [burst, setBurst] = useState<Burst | null>(null);\n  const rowRef = useRef<HTMLDivElement>(null);\n  const gid = \"sr\" + useId().replace(/[^a-zA-Z0-9]/g, \"\");\n\n  const live = !readOnly && !disabled;\n  const pointed = live ? (drag ?? hover) : null;\n  const shown = pointed ?? rating;\n  const accent = SAFE_COLOR.test(color) ? color : \"#ef4444\";\n  const vars: CSSProperties = {};\n  if (size !== undefined) {\n    const s = typeof size === \"number\" ? (size > 0 ? size + \"px\" : \"\") : SAFE_SIZE.test(size) ? size : \"\";\n    if (s) (vars as Record<string, string>)[\"--sr-size\"] = s;\n  }\n\n  const wordFor = (v: number) =>\n    v <= 0 || labels.length === 0\n      ? emptyLabel\n      : (labels[Math.min(labels.length - 1, Math.max(0, Math.ceil((v / n) * labels.length) - 1))] ?? \"\");\n\n  const commit = (v: number) => {\n    const to = Math.ceil(v) - 1;\n    const from = v > rating ? Math.max(0, Math.floor(rating)) : to;\n    setBurst((b) => ({ id: (b?.id ?? 0) + 1, from: Math.min(from, to), to }));\n    if (!isControlled) setInner(v);\n    onChange?.(v);\n  };\n\n  const valueAt = (clientX: number): number => {\n    const stars = rowRef.current?.children;\n    if (!stars || stars.length === 0) return step;\n    const first = stars[0]!.getBoundingClientRect();\n    const second = stars[1]?.getBoundingClientRect();\n    const gap = second ? Math.max(0, second.left - first.right) : 0;\n    for (let i = 0; i < stars.length; i++) {\n      const r = stars[i]!.getBoundingClientRect();\n      if (clientX <= r.right + gap / 2) {\n        const f = clamp((clientX - r.left) / r.width, 0, 1);\n        return i + (step === 0.5 ? (f <= 0.5 ? 0.5 : 1) : 1);\n      }\n    }\n    return n;\n  };\n\n  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {\n    if (!live || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    setDrag(valueAt(e.clientX));\n  };\n  const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {\n    if (!live) return;\n    if (drag !== null) setDrag(valueAt(e.clientX));\n    else if (e.pointerType === \"mouse\") setHover(valueAt(e.clientX));\n  };\n  const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {\n    if (drag === null) return;\n    const v = valueAt(e.clientX);\n    setDrag(null);\n    setHover(e.pointerType === \"mouse\" ? v : null);\n    commit(v);\n  };\n\n  const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {\n    if (!live) return;\n    const cur = rating > 0 ? Math.ceil(rating / step) * step : 0;\n    let next: number | null = null;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowUp\") next = Math.min(n, cur + step);\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowDown\") next = Math.max(step, cur - step);\n    else if (e.key === \"Home\") next = step;\n    else if (e.key === \"End\") next = n;\n    if (next === null) return;\n    e.preventDefault();\n    commit(next);\n    rowRef.current?.querySelector<HTMLElement>('[data-v=\"' + next + '\"]')?.focus();\n  };\n\n  const tabTarget = rating > 0 ? Math.ceil(rating / step) * step : step;\n  const hotIndex = pointed !== null && pointed > 0 ? Math.ceil(pointed) - 1 : -1;\n  const radioValues = (i: number) => (step === 0.5 ? [i + 0.5, i + 1] : [i + 1]);\n\n  const stars = Array.from({ length: n }, (_, i) => {\n    const fill = clamp(shown - i, 0, 1);\n    const inWave = burst !== null && i >= burst.from && i <= burst.to;\n    return (\n      <span key={i} className=\"sr-star\" data-hot={i === hotIndex ? \"\" : undefined} data-down={i === hotIndex && drag !== null ? \"\" : undefined}>\n        <span\n          key={inWave ? burst.id : 0}\n          className=\"sr-in\"\n          data-pop={inWave ? \"\" : undefined}\n          style={inWave ? { animationDelay: (i - burst.from) * 55 + \"ms\" } : undefined}\n        >\n          <svg className=\"sr-svg sr-back\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n            <path d={STAR} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinejoin=\"round\" />\n          </svg>\n          <span className=\"sr-clip\" style={{ width: fill * 100 + \"%\" }}>\n            <svg className=\"sr-svg\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n              <defs>\n                <linearGradient id={gid} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                  <stop offset=\"0\" stopColor=\"#fff\" stopOpacity=\"0.5\" />\n                  <stop offset=\"0.55\" stopColor=\"#fff\" stopOpacity=\"0\" />\n                </linearGradient>\n              </defs>\n              <path d={STAR} fill=\"currentColor\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinejoin=\"round\" />\n              <path d={STAR} fill={\"url(#\" + gid + \")\"} />\n            </svg>\n          </span>\n        </span>\n        {live &&\n          radioValues(i).map((v) => (\n            <button\n              key={v}\n              type=\"button\"\n              role=\"radio\"\n              className=\"sr-r\"\n              data-v={v}\n              aria-checked={Math.abs(v - rating) < 1e-6}\n              aria-label={\"Rate \" + fmt(v) + \" out of \" + n}\n              tabIndex={v === tabTarget ? 0 : -1}\n              onClick={() => commit(v)}\n            />\n          ))}\n        {burst !== null && burst.to === i && rating > 0\n          ? SPARKS.map((k) => (\n              <span\n                key={burst.id + \"-\" + k}\n                className=\"sr-sp\"\n                style={{ \"--a\": k * 60 + 18 + \"deg\", \"--d\": k % 2 ? 0.82 : 1.1, animationDelay: \"40ms\" } as CSSProperties}\n              />\n            ))\n          : null}\n      </span>\n    );\n  });\n\n  return (\n    <>\n      <style>{CSS}</style>\n      <div\n        className={\"sr \" + className}\n        data-live={live ? \"\" : undefined}\n        data-disabled={disabled ? \"\" : undefined}\n        data-preview={pointed !== null && pointed !== rating ? \"\" : undefined}\n        style={vars}\n      >\n        {live ? (\n          <div\n            ref={rowRef}\n            role=\"radiogroup\"\n            aria-label={label}\n            className=\"sr-row\"\n            style={{ color: accent }}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={() => setDrag(null)}\n            onPointerLeave={() => setHover(null)}\n            onKeyDown={onKeyDown}\n          >\n            {stars}\n          </div>\n        ) : (\n          <div\n            ref={rowRef}\n            role=\"img\"\n            aria-label={label + \": \" + fmt(Math.round(rating * 10) / 10) + \" out of \" + n}\n            className=\"sr-row\"\n            style={{ color: accent }}\n          >\n            {stars}\n          </div>\n        )}\n        {showLabel ? (\n          <span className=\"sr-label\" aria-hidden=\"true\">\n            <span key={wordFor(shown)} className=\"sr-word\" data-empty={shown <= 0 ? \"\" : undefined}>\n              {wordFor(shown)}\n            </span>\n            {shown > 0 ? <span className=\"sr-num\">{fmt(Math.round(shown * 10) / 10)}</span> : null}\n          </span>\n        ) : null}\n        <span className=\"sr-only\" aria-live=\"polite\" role=\"status\">\n          {live && rating > 0 ? fmt(rating) + \" out of \" + n + \", \" + wordFor(rating) : \"\"}\n        </span>\n      </div>\n    </>\n  );\n}\n","type":"registry:component","target":"components/viberdy/star-rating-interactive.tsx"}],"meta":{"tier":"free","tags":["rating","stars","form","hover","review","half-star","micro-interaction"],"href":"https://viberdy.dev/library/star-rating-interactive","aiPrompt":"Create a dependency-free React + Tailwind-compatible component named StarRating (\"use client\", one file, no framer-motion, no icon library). It must run on React 18 and 19.\n\nProps (all optional): max = 5 (clamped 1 to 12), defaultRating = 0, value (controlled; undefined = uncontrolled), onChange(rating), precision 1 | 0.5 = 1, readOnly = false, disabled = false, size (number of px or a validated CSS length such as \"min(10cqw, 56px)\", default 28), color = \"#ef4444\" (hex/rgb/hsl, validate with a regex and fall back), showLabel = false, labels = [\"Poor\",\"Fair\",\"Good\",\"Great\",\"Excellent\"], emptyLabel = \"Tap to rate\", label = \"Rating\" (the group's aria-label), className.\n\nStructure: a fragment with a plain <style> element (static CSS string, never inside the control) and a root div (flex, items-center, gap 14px, via :where() so className overrides it) holding the star row and the optional label. The star size is a CSS custom property --sr-size (fallback 28px) set inline only when the size prop is given; the gap is --sr-gap (fallback 4px). Both can be set from className.\n\nStar: inline SVG viewBox 24, path \"M12 2.6l2.9 5.9 6.5.95-4.7 4.58 1.1 6.47L12 17.45l-5.8 3.05 1.1-6.47L2.6 9.45l6.5-.95z\", stroke-width 1.6, round joins. Two layers: an outline (currentColor stroke, no fill, 50% opacity) and, over it, a span clipped with overflow hidden to width fill*100% (fill = clamp(shown - index, 0, 1), width transition 0.22s cubic-bezier(.2,.8,.2,1)) holding the solid star plus a white-to-transparent vertical gradient overlay (0.5 to 0 by 55%) for a soft gloss. Use a gradient id built from useId with non-alphanumerics stripped. Fractional read-only ratings fall out of the clip width.\n\nState: committed rating (internal or value), hover (number | null, mouse pointers only), drag (number | null). shown = drag ?? hover ?? rating. While hover or drag differs from rating the fill layers dim to 0.78 opacity (a preview, not a choice).\n\nPointer: the row is one surface (touch-action: pan-y, user-select none, 6px vertical padding with an equal negative margin so the target is at least 40px tall). A function maps clientX to a value by walking the star rects: the first star whose right edge plus half the gap is past the pointer; within it, precision 1 gives index+1, precision 0.5 gives index+0.5 for the left half and index+1 for the right half; left of the row gives the smallest step, right of it gives max. pointerdown captures the pointer and sets drag, pointermove updates drag (or hover for a mouse), pointerup commits the value under the pointer, pointercancel clears, pointerleave clears hover. The hovered star scales to 1.13 on cubic-bezier(.34,1.56,.64,1) 0.38s and to 0.94 in 0.12s while pressed.\n\nCommit: sets the rating, calls onChange, and records a burst {id, from, to}: from = floor of the previous rating when rising, else the target star; to = the star holding the new value. Stars from..to remount (key = burst id) and run a 0.6s keyframe pop (scale .7 rotate -14deg, then 1.34 rotate 6deg at 45%, then 1) on cubic-bezier(.34,1.56,.64,1), delayed 55ms per star from the first. The target star also emits six sparks: 26% of the star size (min 6px) four-point diamonds (clip-path polygon) in the star colour, angles 18 + 60k degrees, travelling from 0.28x to 0.95x or 1.1x the star size (alternating) while spinning 80 degrees and fading over 0.62s, 40ms delay.\n\nLabel (showLabel): word = labels[ceil(shown / max * labels.length) - 1], or emptyLabel at 0, swapped with a keyed 0.3s slide-up fade, followed by the value at 50% opacity; font-size max(13px, size * 0.36), min-width 7.4em; aria-hidden. A separate visually hidden role=\"status\" aria-live=\"polite\" region announces the committed rating (\"4 out of 5, Great\").\n\nSemantics: interactive = a radiogroup (aria-label) with real <button role=\"radio\"> per value (whole values, or halves too at precision 0.5), absolutely positioned over each star with pointer-events none, aria-label \"Rate 3.5 out of 5\", aria-checked, roving tabindex (the committed value, else the first, is tabindex 0). ArrowRight/ArrowUp add one step, ArrowLeft/ArrowDown subtract (never below one step), Home and End jump, each commits and moves focus to that value's radio; Space/Enter on a radio commits via click. Focus ring: .sr-r:focus-visible outline 2px solid currentColor, offset 1px, radius 30%. readOnly renders the row as role=\"img\" with aria-label \"Rating: 4.3 out of 5\" and no radios. disabled drops opacity to 0.45 and removes the radios.\n\nColour: stars and ring take the color prop; the label inherits the page text colour, so it works on light and dark pages. prefers-reduced-motion: no pop, sparks, label slide or hover scale, transitions near-instant.","license":"https://viberdy.dev/license"}}