Rating
Star or custom-glyph rating with hover preview, half steps and radiogroup keyboard, plus a read-only summary, a five-bar distribution and an emoji-face variant.
Preview
Rate this release
Half steps
Custom glyph
How was onboarding?
Good
Workspace templates
4.4(1,284)
4.41,284 reviews
Select a row to filter reviews
Install
Add the editable source with the shadcn CLI. Your project also needs the shared theme tokens this component uses. Setup and requirements. The Pebble installer is not published yet.
npx shadcn@latest add https://pebbleui.com/r/rating.jsonProps
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue | number | 0 | Current rating; 0 means unrated. |
| onValueChange | (value: number) => void | — | Called on click or arrow keys. |
| max | number | 5 | Number of glyphs. |
| step | 1 | 0.5 | 1 | Whole or half glyph steps. |
| glyph | ReactNode | star | Custom 16×16 glyph using currentColor. |
| size | "sm" | "md" | "lg" | "md" | Glyph size. |
| readOnly / disabled / required | boolean | false | Read-only blocks input; required stops a second click from clearing. |
| labels | string[] | — | Word per whole value, shown after the row and in radio names. |
| RatingDisplay | { value, max?, count?, size?, locale? } | — | Read-only stars with average and review count. |
| RatingBreakdown | { counts, onSelect?, selected? } | — | Average plus five distribution bars (highest first); rows can filter. |
| RatingFaces | { value?, defaultValue?, onValueChange?, labels? } | — | “How was it?” radiogroup of five faces (1–5). |
Build notes
- Each glyph is two stacked copies: a muted base and an ember copy with `clip-path: inset(0 X% 0 0)` where X = (1 − fill) × 100, so halves and fractions are exact without masks or gradients. - Radios are transparent hit areas laid over the glyph row (one or two per glyph), so the visuals stay simple and the pointer half is precise. - Keyboard moves focus the new radio on the next animation frame (after the tab stop moves). - The face mouth is a quadratic curve whose control point moves from −3.2 (frown) to +3.4 (grin); the grin closes into a filled smile and the worst face adds slanted brows. <!-- PEBBLE-LICENSE -->
View source
registry/input/rating/rating.tsx
"use client";
/* PEBBLE-LICENSE
Built by Pebble. Component: rating.
First-party license: MIT
The following first-party terms apply only to original Pebble material.
MIT License
Copyright (c) 2026 Praxys Solutions LLC (Pebble)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
END PEBBLE-LICENSE */
import * as React from "react";
import { AnimatePresence, MotionConfig, motion } from "motion/react";
import { cn } from "@/lib/utils";
/* -------------------------------------------------------------------------- */
/* Glyphs */
/* -------------------------------------------------------------------------- */
// A five-point star computed from polar points (rounded joins come from the
// stroke), so the path is ours rather than copied from an icon set.
const STAR = (() => {
const pts: string[] = [];
for (let i = 0; i < 10; i++) {
const r = i % 2 === 0 ? 7 : 3.1;
const a = (Math.PI / 5) * i - Math.PI / 2;
pts.push(`${(8 + r * Math.cos(a)).toFixed(2)} ${(8.4 + r * Math.sin(a)).toFixed(2)}`);
}
return `M${pts.join("L")}Z`;
})();
export function StarGlyph({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" aria-hidden className={className}>
<path
d={STAR}
fill="currentColor"
stroke="currentColor"
strokeWidth={1.2}
strokeLinejoin="round"
/>
</svg>
);
}
const sizes = { sm: "size-4", md: "size-5", lg: "size-7" } as const;
/** One glyph filled to `fill` (0–1): a muted base with an ember copy clipped on top. */
function FilledGlyph({
fill,
glyph,
size,
preview,
}: {
fill: number;
glyph: React.ReactNode;
size: keyof typeof sizes;
preview?: boolean;
}) {
return (
<span
className={cn("relative grid shrink-0 place-items-center", sizes[size], "[&_svg]:size-full")}
>
<span className="absolute inset-0 text-muted-foreground/25 dark:text-muted-foreground/30">
{glyph}
</span>
<span
className={cn(
"absolute inset-0 transition-[clip-path,color] duration-(--motion-fast) ease-enter motion-reduce:transition-none",
preview ? "text-accent/70" : "text-accent",
)}
style={{ clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)` }}
>
{glyph}
</span>
</span>
);
}
/* -------------------------------------------------------------------------- */
/* Rating (input) */
/* -------------------------------------------------------------------------- */
export type RatingProps = Omit<React.ComponentProps<"div">, "defaultValue" | "onChange"> & {
value?: number;
defaultValue?: number;
onValueChange?: (value: number) => void;
max?: number;
/** 1 for whole glyphs, 0.5 for halves. */
step?: 1 | 0.5;
/** Replace the star with your own 16×16 glyph (uses currentColor). */
glyph?: React.ReactNode;
size?: keyof typeof sizes;
readOnly?: boolean;
disabled?: boolean;
/** Clicking the current value again does not clear it. */
required?: boolean;
/** Words per whole value, e.g. ["Poor", …, "Excellent"]; shown and announced. */
labels?: string[];
/** Hidden input name for forms. */
name?: string;
};
export function Rating({
value: valueProp,
defaultValue = 0,
onValueChange,
max = 5,
step = 1,
glyph = <StarGlyph />,
size = "md",
readOnly = false,
disabled = false,
required = false,
labels,
name,
className,
"aria-label": ariaLabel = "Rating",
...props
}: RatingProps) {
const [internal, setInternal] = React.useState(defaultValue);
const value = valueProp ?? internal;
const [hover, setHover] = React.useState<number | null>(null);
const shown = hover ?? value;
const groupRef = React.useRef<HTMLDivElement>(null);
const interactive = !readOnly && !disabled;
const set = (v: number) => {
const next = !required && v === value ? 0 : v;
setInternal(next);
onValueChange?.(next);
};
const textFor = (v: number) => {
const word = labels?.[Math.ceil(v) - 1];
const n = `${v} ${v === 1 ? "star" : "stars"}`;
return word ? `${n}, ${word}` : n;
};
const steps = Array.from({ length: max / step }, (_, i) => (i + 1) * step);
const focusValue = value > 0 ? value : steps[0];
const move = (to: number) => {
const v = Math.min(max, Math.max(step, to));
setInternal(v);
onValueChange?.(v);
requestAnimationFrame(() =>
groupRef.current?.querySelector<HTMLElement>(`[data-value="${v}"]`)?.focus(),
);
};
return (
<div
data-slot="rating"
data-readonly={readOnly || undefined}
className={cn("inline-flex items-center gap-2.5", disabled && "opacity-50", className)}
{...props}
>
<div
ref={groupRef}
role="radiogroup"
aria-label={ariaLabel}
aria-readonly={readOnly || undefined}
aria-disabled={disabled || undefined}
className="relative flex gap-1"
onPointerLeave={() => setHover(null)}
>
{Array.from({ length: max }, (_, i) => {
const fill = Math.min(1, Math.max(0, shown - i));
return (
<span key={i} className="relative">
<FilledGlyph fill={fill} glyph={glyph} size={size} preview={hover != null} />
</span>
);
})}
{/* Hit areas: one radio per step, laid over the glyphs. */}
<div className="absolute inset-0 flex gap-1">
{Array.from({ length: max }, (_, i) => (
<span key={i} className={cn("flex", sizes[size])}>
{steps
.filter((v) => v > i && v <= i + 1)
.map((v) => {
const checked = v === value;
return (
<span
key={v}
role="radio"
data-value={v}
aria-checked={checked}
aria-label={textFor(v)}
aria-disabled={!interactive || undefined}
tabIndex={interactive && v === focusValue ? 0 : -1}
onClick={() => interactive && set(v)}
onPointerEnter={() => interactive && setHover(v)}
onKeyDown={(e) => {
if (!interactive) return;
const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
if (e.key === "ArrowRight" || e.key === "ArrowUp")
move(value + (rtl && e.key === "ArrowRight" ? -step : step));
else if (e.key === "ArrowLeft" || e.key === "ArrowDown")
move(value - (rtl && e.key === "ArrowLeft" ? -step : step));
else if (e.key === "Home") move(step);
else if (e.key === "End") move(max);
else if (e.key === " " || e.key === "Enter") set(v);
else return;
e.preventDefault();
}}
className={cn(
"h-full flex-1 rounded-sm outline-none",
interactive && "cursor-pointer",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
)}
/>
);
})}
</span>
))}
</div>
</div>
{labels && (
<span aria-hidden className="min-w-16 text-[13px] text-muted-foreground tabular-nums">
{shown > 0 ? labels[Math.ceil(shown) - 1] : " "}
</span>
)}
{name && <input type="hidden" name={name} value={value} />}
</div>
);
}
/* -------------------------------------------------------------------------- */
/* Read-only display */
/* -------------------------------------------------------------------------- */
export type RatingDisplayProps = React.ComponentProps<"div"> & {
value: number;
max?: number;
count?: number;
size?: keyof typeof sizes;
locale?: string;
glyph?: React.ReactNode;
};
export function RatingDisplay({
value,
max = 5,
count,
size = "sm",
locale = "en-US",
glyph = <StarGlyph />,
className,
...props
}: RatingDisplayProps) {
const nf = new Intl.NumberFormat(locale);
const avg = new Intl.NumberFormat(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
return (
<div
role="img"
aria-label={`Rated ${avg.format(value)} out of ${max}${count != null ? `, ${nf.format(count)} reviews` : ""}`}
data-slot="rating-display"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
>
<span className="flex gap-0.5">
{Array.from({ length: max }, (_, i) => (
<FilledGlyph
key={i}
fill={Math.min(1, Math.max(0, value - i))}
glyph={glyph}
size={size}
/>
))}
</span>
<span className="text-[13px] font-medium text-foreground tabular-nums">
{avg.format(value)}
</span>
{count != null && (
<span className="text-[13px] text-muted-foreground tabular-nums">({nf.format(count)})</span>
)}
</div>
);
}
/* -------------------------------------------------------------------------- */
/* Distribution breakdown */
/* -------------------------------------------------------------------------- */
export type RatingBreakdownProps = Omit<React.ComponentProps<"div">, "onSelect"> & {
/** Counts per star, highest first: [fives, fours, threes, twos, ones]. */
counts: number[];
locale?: string;
/** Make rows buttons that filter by star; receives the star value. */
onSelect?: (stars: number) => void;
selected?: number | null;
};
export function RatingBreakdown({
counts,
locale = "en-US",
onSelect,
selected = null,
className,
...props
}: RatingBreakdownProps) {
const total = counts.reduce((a, b) => a + b, 0);
const max = counts.length;
const average = total ? counts.reduce((sum, c, i) => sum + c * (max - i), 0) / total : 0;
const nf = new Intl.NumberFormat(locale);
const pf = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 });
return (
<MotionConfig reducedMotion="user">
<div
data-slot="rating-breakdown"
className={cn("flex items-center gap-6", className)}
{...props}
>
<div className="flex flex-col items-start gap-1">
<span className="text-3xl font-semibold tracking-[-0.02em] tabular-nums">
{new Intl.NumberFormat(locale, {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
}).format(average)}
</span>
<span aria-hidden className="flex gap-0.5">
{Array.from({ length: max }, (_, i) => (
<FilledGlyph
key={i}
fill={Math.min(1, Math.max(0, average - i))}
glyph={<StarGlyph />}
size="sm"
/>
))}
</span>
<span className="text-xs text-muted-foreground tabular-nums">
{nf.format(total)} reviews
</span>
</div>
<ul aria-label="Rating distribution" className="flex min-w-0 flex-1 flex-col gap-1">
{counts.map((c, i) => {
const stars = max - i;
const share = total ? c / total : 0;
const active = selected === stars;
const row = (
<>
<span className="flex w-7 shrink-0 items-center gap-0.5 text-xs text-muted-foreground tabular-nums">
{stars}
<StarGlyph className="size-3 text-muted-foreground/60" />
</span>
<span className="relative h-2 flex-1 overflow-hidden rounded-full bg-muted inset-shadow-xs">
<motion.span
className={cn(
"absolute inset-y-0 start-0 rounded-full",
active || selected == null ? "bg-accent" : "bg-muted-foreground/40",
)}
initial={false}
animate={{ width: `${share * 100}%` }}
transition={{ type: "spring", stiffness: 420, damping: 32, mass: 0.8 }}
/>
</span>
<span className="w-9 shrink-0 text-end font-mono text-[11px] text-muted-foreground tabular-nums">
{pf.format(share)}
</span>
<span className="sr-only">
{stars} stars: {nf.format(c)} reviews
</span>
</>
);
return (
<li key={stars}>
{onSelect ? (
<button
type="button"
aria-pressed={active}
onClick={() => onSelect(stars)}
className={cn(
"flex w-full cursor-pointer items-center gap-2.5 rounded-md px-1.5 py-1 transition-colors duration-(--motion-fast) hover:bg-muted/70",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
active && "bg-muted",
)}
>
{row}
</button>
) : (
<div className="flex items-center gap-2.5 px-1.5 py-1">{row}</div>
)}
</li>
);
})}
</ul>
</div>
</MotionConfig>
);
}
/* -------------------------------------------------------------------------- */
/* Faces ("how was it?") */
/* -------------------------------------------------------------------------- */
const faceLabels = ["Awful", "Not great", "Okay", "Good", "Great"];
/** Mouth curves from frown to grin; brows tilt on the extremes. Ours. */
function Face({ mood }: { mood: number }) {
const curve = [-3.2, -1.6, 0, 1.8, 3.4][mood];
const mouth =
mood === 4
? `M10.5 19.5 Q16 ${19.5 + curve * 1.6} 21.5 19.5 Z`
: `M11 20 Q16 ${20 + curve} 21 20`;
return (
<svg viewBox="0 0 32 32" aria-hidden className="size-full">
<circle cx="16" cy="16" r="13" fill="currentColor" opacity={0.14} />
<circle cx="16" cy="16" r="13" fill="none" stroke="currentColor" strokeWidth={1.5} />
<circle cx="11.75" cy="13.5" r="1.5" fill="currentColor" />
<circle cx="20.25" cy="13.5" r="1.5" fill="currentColor" />
{mood === 0 && (
<path
d="M9.5 10.5 13 11.5M22.5 10.5 19 11.5"
stroke="currentColor"
strokeWidth={1.4}
strokeLinecap="round"
/>
)}
<path
d={mouth}
fill={mood === 4 ? "currentColor" : "none"}
stroke="currentColor"
strokeWidth={1.6}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
export type RatingFacesProps = Omit<React.ComponentProps<"div">, "defaultValue"> & {
value?: number | null;
defaultValue?: number | null;
/** 1–5. */
onValueChange?: (value: number) => void;
labels?: string[];
};
export function RatingFaces({
value: valueProp,
defaultValue = null,
onValueChange,
labels = faceLabels,
className,
"aria-label": ariaLabel = "How was it?",
...props
}: RatingFacesProps) {
const [internal, setInternal] = React.useState(defaultValue);
const value = valueProp !== undefined ? valueProp : internal;
const ref = React.useRef<HTMLDivElement>(null);
const set = (v: number) => {
setInternal(v);
onValueChange?.(v);
};
const focusAt = (v: number) =>
requestAnimationFrame(() =>
ref.current?.querySelector<HTMLElement>(`[data-value="${v}"]`)?.focus(),
);
return (
<MotionConfig reducedMotion="user">
<div
data-slot="rating-faces"
className={cn("inline-flex flex-col items-center gap-2", className)}
{...props}
>
<div ref={ref} role="radiogroup" aria-label={ariaLabel} className="flex gap-1.5">
{labels.map((label, i) => {
const v = i + 1;
const checked = value === v;
return (
<motion.button
key={v}
type="button"
role="radio"
data-value={v}
aria-checked={checked}
aria-label={label}
tabIndex={checked || (value == null && i === 0) ? 0 : -1}
onClick={() => set(v)}
onKeyDown={(e) => {
let next: number | null = null;
if (e.key === "ArrowRight" || e.key === "ArrowDown")
next = v === labels.length ? 1 : v + 1;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp")
next = v === 1 ? labels.length : v - 1;
else if (e.key === "Home") next = 1;
else if (e.key === "End") next = labels.length;
if (next == null) return;
e.preventDefault();
set(next);
focusAt(next);
}}
animate={{ scale: checked ? 1.12 : 1, y: checked ? -2 : 0 }}
whileTap={{ scale: 0.92 }}
transition={{ type: "spring", stiffness: 420, damping: 22, mass: 0.8 }}
className={cn(
"grid size-11 cursor-pointer place-items-center rounded-full p-1.5 transition-[color,background-color,box-shadow] duration-(--motion-fast)",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
checked
? "bg-card text-accent-strong shadow-raised-sm ring-1 inset-shadow-highlight ring-hairline"
: "text-muted-foreground/70 hover:bg-muted hover:text-foreground",
)}
>
<Face mood={i} />
</motion.button>
);
})}
</div>
<span className="relative h-5 w-full overflow-hidden text-center text-[13px] font-medium">
<AnimatePresence mode="popLayout" initial={false}>
<motion.span
key={value ?? "none"}
initial={{ opacity: 0, y: 6, filter: "blur(2px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: -6, filter: "blur(2px)" }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
className={cn("block", value == null && "font-normal text-muted-foreground")}
>
{value == null ? "Tap a face" : labels[value - 1]}
</motion.span>
</AnimatePresence>
</span>
</div>
</MotionConfig>
);
}
