1"use client";2
3import React, { useCallback, useEffect, useState } from "react";4import { AnimatePresence, motion, useReducedMotion } from "motion/react";5import { cn } from "@/lib/utils";6
7export type StarRatingProps = {8 value?: number;9 defaultValue?: number;10 onChange?: (value: number) => void;11 max?: number;12 13 allowHalf?: boolean;14 15 clearable?: boolean;16 readOnly?: boolean;17 size?: "sm" | "md" | "lg";18 19 labels?: string[];20 className?: string;21 "aria-label"?: string;22};23
24const STAR_PATH =25 "M12 2.6l2.83 5.9 6.47.8-4.76 4.47 1.22 6.43L12 17.07l-5.76 3.13 1.22-6.43L2.7 9.3l6.47-.8L12 2.6z";26const SIZES = { sm: 18, md: 26, lg: 34 };27
28function useFinePointer() {29 const [fine, setFine] = useState(false);30 useEffect(() => {31 const mq = window.matchMedia("(hover: hover) and (pointer: fine)");32 const sync = () => setFine(mq.matches);33 sync();34 mq.addEventListener("change", sync);35 return () => mq.removeEventListener("change", sync);36 }, []);37 return fine;38}39
40function Burst({ size }: { size: number }) {41 return (42 <span aria-hidden className="pointer-events-none absolute inset-0">43 {Array.from({ length: 7 }, (_, i) => {44 const angle = (i / 7) * Math.PI * 2 - Math.PI / 2;45 const r = size * 0.85;46 return (47 <motion.span48 key={i}49 className="absolute top-1/2 left-1/2 size-1 rounded-full bg-(--star-fill)"50 initial={{ x: "-50%", y: "-50%", opacity: 1, scale: 1 }}51 animate={{52 x: `calc(-50% + ${Math.cos(angle) * r}px)`,53 y: `calc(-50% + ${Math.sin(angle) * r}px)`,54 opacity: 0,55 scale: 0.4,56 }}57 transition={{ duration: 0.55, ease: [0.23, 1, 0.32, 1] }}58 />59 );60 })}61 </span>62 );63}64
65export function StarRating({66 value: valueProp,67 defaultValue = 0,68 onChange,69 max = 5,70 allowHalf = false,71 clearable = false,72 readOnly = false,73 size = "md",74 labels,75 className,76 "aria-label": ariaLabel = "Rating",77}: StarRatingProps) {78 const reduce = !!useReducedMotion();79 const fine = useFinePointer();80 const count = Number.isFinite(max) ? Math.max(1, Math.floor(max)) : 5;81 const step = allowHalf ? 0.5 : 1;82 const isControlled = valueProp !== undefined;83 const [uncontrolled, setUncontrolled] = useState(defaultValue);84 const value = Math.min(count, Math.max(0, isControlled ? valueProp : uncontrolled));85 const [hover, setHover] = useState<number | null>(null);86 const [commit, setCommit] = useState<{ value: number; token: number } | null>(null);87 const px = SIZES[size];88
89 const shown = !readOnly && hover !== null ? hover : value;90 const labelFor = (v: number) => (labels && v > 0 ? labels[Math.ceil(v) - 1] : undefined);91
92 const setValue = useCallback(93 (next: number) => {94 if (readOnly) return;95 const bounded = Math.min(count, Math.max(0, Math.round(next / step) * step));96 const final = clearable && bounded === value ? 0 : bounded;97 if (!isControlled) setUncontrolled(final);98 onChange?.(final);99 setCommit(final > 0 ? { value: final, token: Date.now() } : null);100 },101 [clearable, count, isControlled, onChange, readOnly, step, value],102 );103
104 const valueAt = (e: { target: EventTarget; clientX: number }) => {105 const star = (e.target as Element).closest<HTMLElement>("[data-star]");106 if (!star) return null;107 const n = Number(star.dataset.star);108 if (!allowHalf) return n;109 const r = star.getBoundingClientRect();110 return e.clientX - r.left < r.width / 2 ? n - 0.5 : n;111 };112
113 const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {114 if (readOnly) return;115 let next: number | null = null;116 if (e.key === "ArrowRight" || e.key === "ArrowUp") next = Math.min(count, value + step);117 else if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = Math.max(step, value - step);118 else if (e.key === "Home") next = step;119 else if (e.key === "End") next = count;120 else if (/^[1-9]$/.test(e.key) && Number(e.key) <= count) next = Number(e.key);121 if (next === null) return;122 e.preventDefault();123 if (next !== value) setValue(next);124 };125
126 const text = `${value} of ${count} stars${labelFor(value) ? `, ${labelFor(value)}` : ""}`;127
128 return (129 <div className={cn("inline-flex flex-col items-center gap-2 [--star-fill:#f5b301]", className)}>130 <div131 role={readOnly ? "img" : "slider"}132 aria-label={readOnly ? `${ariaLabel}: ${text}` : ariaLabel}133 aria-valuemin={readOnly ? undefined : 0}134 aria-valuemax={readOnly ? undefined : count}135 aria-valuenow={readOnly ? undefined : value}136 aria-valuetext={readOnly ? undefined : text}137 tabIndex={readOnly ? undefined : 0}138 onKeyDown={onKeyDown}139 onPointerMove={(e) => {140 if (readOnly || !fine) return;141 const v = valueAt(e);142 if (v !== null) setHover(v);143 }}144 onPointerLeave={() => setHover(null)}145 onClick={(e) => {146 const v = valueAt(e);147 if (v !== null) setValue(v);148 }}149 className={cn(150 "inline-flex items-center rounded-[10px] outline-none",151 "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-4 focus-visible:ring-offset-(--color-paper)",152 readOnly ? "cursor-default" : "cursor-pointer",153 )}154 style={{ gap: px * 0.12 }}155 >156 {Array.from({ length: count }, (_, i) => {157 const n = i + 1;158 const fill = Math.min(1, Math.max(0, shown - i));159 const hovered = hover !== null && Math.ceil(hover) === n;160 const lit = fill > 0;161 const popped = commit && !reduce && n <= Math.ceil(commit.value);162 return (163 <motion.span164 key={`${n}-${popped ? commit.token : 0}`}165 data-star={n}166 className="relative block"167 style={{ width: px, height: px }}168 initial={popped ? { scale: 0.6 } : false}169 animate={{170 scale: hovered && !reduce ? 1.18 : lit && hover !== null && !reduce ? 1.06 : 1,171 y: hovered && !reduce ? -2 : 0,172 rotate: hovered && !reduce ? -6 : 0,173 }}174 transition={175 popped176 ? { type: "spring", bounce: 0.6, duration: 0.5, delay: i * 0.05 }177 : { type: "spring", bounce: 0.4, duration: 0.35 }178 }179 >180 {}181 <svg viewBox="0 0 24 24" className="absolute inset-0 size-full" aria-hidden>182 <path183 d={STAR_PATH}184 fill="var(--color-paper-2)"185 stroke="var(--color-rule)"186 strokeWidth="1.5"187 strokeLinejoin="round"188 />189 </svg>190 {}191 <span192 className="absolute inset-0 transition-[clip-path] duration-200 ease-out"193 style={{ clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)` }}194 >195 <svg viewBox="0 0 24 24" className="size-full drop-shadow-[0_1px_2px_rgba(245,179,1,0.35)]" aria-hidden>196 <path d={STAR_PATH} fill="var(--star-fill)" stroke="var(--star-fill)" strokeWidth="1.5" strokeLinejoin="round" />197 <path d={STAR_PATH} fill="url(#star-sheen)" opacity="0.5" />198 <defs>199 <linearGradient id="star-sheen" x1="0" y1="0" x2="0" y2="1">200 <stop offset="0" stopColor="#fff" stopOpacity="0.7" />201 <stop offset="0.55" stopColor="#fff" stopOpacity="0" />202 </linearGradient>203 </defs>204 </svg>205 </span>206 {popped && n === Math.ceil(commit.value) ? <Burst key={commit.token} size={px} /> : null}207 </motion.span>208 );209 })}210 </div>211
212 {labels ? (213 <div className="relative h-5 min-w-24 text-center text-[13px] font-medium text-(--color-ink-2)" aria-hidden>214 <AnimatePresence initial={false} mode="popLayout">215 <motion.span216 key={labelFor(shown) ?? "none"}217 initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, filter: "blur(4px)" }}218 animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}219 exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6, filter: "blur(4px)" }}220 transition={{ duration: 0.22, ease: [0.23, 1, 0.32, 1] }}221 className={cn("inline-block", !labelFor(shown) && "text-(--color-neutral)")}222 >223 {labelFor(shown) ?? (readOnly ? "No rating" : "Tap to rate")}224 </motion.span>225 </AnimatePresence>226 </div>227 ) : null}228 </div>229 );230}