dxbh-uiGitHub

Star Rating

A star rating you scrub with a finger or the arrow keys. The fill follows the pointer 1:1 and commits on release. RatingDisplay shows a read-only score filled to any fraction.

Preview
Average

Install

npx shadcn@latest add @dxbh-ui/star-rating

Add the @dxbh-ui registry to components.json once:

{
  "registries": {
    "@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
  }
}

Usage

demo.tsx
"use client";

import { useState } from "react";
import { RatingDisplay, StarRating } from "@/components/ui/star-rating/star-rating";

export default function StarRatingDemo() {
  const [rating, setRating] = useState<number | null>(3.5);

  return (
    <div className="flex w-full max-w-md flex-col items-center gap-6">
      <StarRating label="Rating" value={rating} onValueChange={setRating} />
      <StarRating label="Difficulty" max={10} step={1} size="sm" defaultValue={6} />
      <div className="flex items-center gap-3 text-xs text-muted-foreground">
        <span>Average</span>
        <RatingDisplay value={4.3} />
      </div>
    </div>
  );
}

Props

PropTypeDefault
label*

Accessible name.

string—
value

Rating in stars when controlled; null when unrated.

number | null—
defaultValue

Initial rating when uncontrolled.

number | nullnull
onValueChange

Called on pointer-up, on each key press, or on clear.

(value: number | null) => void—
max

Number of stars.

number5
step

Smallest increment, in stars.

number0.5
clearable

Show the clear button and accept Delete/Backspace.

booleantrue
showNumber

Show the score beside the stars.

booleantrue
size

Star size.

"sm" | "default" | "lg""default"
disabled

Read-only and dimmed.

booleanfalse

Polish

  • Pointer capture on press, so the fill tracks the finger 1:1 even outside the stars. The value commits once, on pointer-up. pointercancel discards the scrub.
  • Hover preview only on devices with real hover ((hover: hover) and (pointer: fine)). Touch never leaves a stale preview.
  • A second pointer is ignored while one is scrubbing.
  • The track does not scale on press. Shrinking it would pull the stars out from under the finger. The clear button keeps the 0.97 press.
  • No per-star bounce or fill transition. The fill is a clip-path that follows the input exactly.
  • Configurable max and step. Values are in stars (3.5), not a 1–10 wire format.
  • ARIA slider with aria-valuetext ("3.5 stars" or "Not rated"). Arrows, PageUp/PageDown, Home/End, and Delete or Backspace to clear.
  • The score uses tabular-nums and a fixed minimum width so it doesn't jitter.
  • Neutral tokens: foreground fill on a muted outline, no brand colour.

Source

star-rating.tsx
"use client";

import {
  useEffect,
  useRef,
  useState,
  type HTMLAttributes,
  type KeyboardEvent,
  type PointerEvent,
} from "react";
import { Star, X } from "lucide-react";
import { cn } from "@/lib/utils";

const decimals = (step: number) => {
  const text = String(step);
  return text.includes(".") ? text.split(".")[1].length : 0;
};

/** "3.5 stars", "1 star". */
export function ratingText(value: number, step = 0.5): string {
  const n = Number(value.toFixed(decimals(step)));
  return `${n} star${n === 1 ? "" : "s"}`;
}

/** Snap a raw value onto the step grid inside [step, max]. */
export function snapRating(raw: number, max: number, step: number): number {
  const snapped = Math.ceil(raw / step - 1e-9) * step;
  return Number(Math.min(max, Math.max(step, snapped)).toFixed(decimals(step)));
}

const sizes = { sm: "size-3.5", default: "size-6", lg: "size-8" } as const;
type Size = keyof typeof sizes;

function Stars({ value, max, size }: { value: number; max: number; size: Size }) {
  return (
    <span className="flex" aria-hidden="true">
      {Array.from({ length: max }, (_, i) => {
        // Fraction of this star that is filled, 0–1. No transition: the fill
        // follows the finger 1:1, and stars never bounce individually.
        const fill = Math.max(0, Math.min(1, value - i));
        return (
          <span key={i} className={cn("relative shrink-0", sizes[size])}>
            <Star className={cn("absolute inset-0 text-muted-foreground/40", sizes[size])} strokeWidth={1.5} />
            {fill > 0 ? (
              <Star
                className={cn("absolute inset-0 fill-foreground text-foreground", sizes[size])}
                strokeWidth={1.5}
                style={{ clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)` }}
              />
            ) : null}
          </span>
        );
      })}
    </span>
  );
}

export type RatingDisplayProps = Omit<HTMLAttributes<HTMLSpanElement>, "children"> & {
  value: number;
  max?: number;
  /** Show the score as a number beside the stars. */
  showNumber?: boolean;
  size?: Size;
};

/** Read-only stars, filled to any fraction, with an optional score. */
export function RatingDisplay({ value, max = 5, showNumber = true, size = "sm", className, ...props }: RatingDisplayProps) {
  const clamped = Math.max(0, Math.min(max, value));
  return (
    <span
      role="img"
      aria-label={`${Number(clamped.toFixed(1))} out of ${max} stars`}
      className={cn("inline-flex items-center gap-1.5", className)}
      {...props}
    >
      <Stars value={clamped} max={max} size={size} />
      {showNumber ? (
        <span className="text-xs text-muted-foreground tabular-nums" aria-hidden="true">
          {clamped.toFixed(1)}
        </span>
      ) : null}
    </span>
  );
}

export type StarRatingProps = Omit<HTMLAttributes<HTMLDivElement>, "onChange" | "defaultValue"> & {
  /** Rating in stars, or null when unrated. Pass with `onValueChange` to control it. */
  value?: number | null;
  defaultValue?: number | null;
  /** Called once per gesture, on pointer-up, or on each key press. */
  onValueChange?: (value: number | null) => void;
  /** Accessible name. */
  label: string;
  /** Number of stars. */
  max?: number;
  /** Smallest increment, in stars. */
  step?: number;
  /** Show the × button and accept Delete/Backspace to clear. */
  clearable?: boolean;
  /** Show the score beside the stars. */
  showNumber?: boolean;
  disabled?: boolean;
  size?: Size;
};

const canHover = () =>
  typeof window !== "undefined" &&
  typeof window.matchMedia === "function" &&
  window.matchMedia("(hover: hover) and (pointer: fine)").matches;

/**
 * Stars as a slider. Press and scrub across them: the fill tracks the finger
 * 1:1 and commits on release. A mouse previews on hover; touch does not.
 */
export function StarRating({
  value: valueProp,
  defaultValue = null,
  onValueChange,
  label,
  max = 5,
  step = 0.5,
  clearable = true,
  showNumber = true,
  disabled = false,
  size = "default",
  className,
  ...props
}: StarRatingProps) {
  const [inner, setInner] = useState<number | null>(defaultValue);
  const value = valueProp !== undefined ? valueProp : inner;
  const [preview, setPreview] = useState<number | null>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const dragging = useRef<number | null>(null); // active pointer id
  const hoverable = useRef(false);

  useEffect(() => {
    hoverable.current = canHover();
  }, []);

  const commit = (next: number | null) => {
    if (next === value) return;
    if (valueProp === undefined) setInner(next);
    onValueChange?.(next);
  };

  const at = (clientX: number) => {
    const rect = trackRef.current!.getBoundingClientRect();
    const ratio = rect.width > 0 ? (clientX - rect.left) / rect.width : 0;
    return snapRating(ratio * max, max, step);
  };

  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
    if (disabled || event.button !== 0 || dragging.current !== null) return;
    dragging.current = event.pointerId;
    event.currentTarget.setPointerCapture?.(event.pointerId);
    setPreview(at(event.clientX));
  };

  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    if (disabled) return;
    if (dragging.current !== null) {
      // Ignore a second finger while one is scrubbing.
      if (event.pointerId === dragging.current) setPreview(at(event.clientX));
    } else if (event.pointerType === "mouse" && hoverable.current) {
      setPreview(at(event.clientX));
    }
  };

  const end = (event: PointerEvent<HTMLDivElement>, keep: boolean) => {
    if (dragging.current !== event.pointerId) return;
    dragging.current = null;
    event.currentTarget.releasePointerCapture?.(event.pointerId);
    const next = keep ? at(event.clientX) : null;
    setPreview(null);
    if (keep) commit(next);
  };

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (disabled) return;
    const current = value ?? 0;
    let next: number | null | undefined;
    switch (event.key) {
      case "ArrowRight":
      case "ArrowUp":
        next = snapRating(current + step, max, step);
        break;
      case "ArrowLeft":
      case "ArrowDown":
        next = snapRating(current - step, max, step);
        break;
      case "PageUp":
        next = snapRating(current + 1, max, step);
        break;
      case "PageDown":
        next = snapRating(current - 1, max, step);
        break;
      case "Home":
        next = step;
        break;
      case "End":
        next = max;
        break;
      case "Delete":
      case "Backspace":
        next = clearable ? null : undefined;
        break;
    }
    if (next === undefined) return;
    event.preventDefault();
    commit(next);
  };

  const shown = preview ?? value ?? 0;
  const places = decimals(step);

  return (
    <div className={cn("inline-flex items-center gap-1", className)} {...props}>
      <div
        ref={trackRef}
        role="slider"
        tabIndex={disabled ? -1 : 0}
        aria-label={label}
        aria-valuemin={step}
        aria-valuemax={max}
        aria-valuenow={value ?? undefined}
        aria-valuetext={value != null ? ratingText(value, step) : "Not rated"}
        aria-disabled={disabled || undefined}
        data-scrubbing={preview !== null || undefined}
        onKeyDown={onKeyDown}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={(e) => end(e, true)}
        onPointerCancel={(e) => end(e, false)}
        onLostPointerCapture={(e) => end(e, false)}
        onPointerLeave={() => {
          if (dragging.current === null) setPreview(null);
        }}
        className={cn(
          // The track never scales on press: shrinking it would pull the stars
          // out from under the finger mid-scrub.
          "flex min-h-11 cursor-pointer touch-none items-center rounded-md px-1 outline-none select-none",
          "focus-visible:ring-2 focus-visible:ring-ring/50",
          disabled && "cursor-default opacity-50",
        )}
      >
        <Stars value={shown} max={max} size={size} />
      </div>
      {showNumber ? (
        <span
          aria-hidden="true"
          className="min-w-[3ch] text-sm text-muted-foreground tabular-nums"
        >
          {shown ? shown.toFixed(places) : ""}
        </span>
      ) : null}
      {clearable && !disabled && value != null ? (
        <button
          type="button"
          onClick={() => commit(null)}
          aria-label={`Clear ${label}`}
          className={cn(
            "inline-flex size-10 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none",
            "transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97]",
            "hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",
          )}
        >
          <X className="size-4" aria-hidden="true" />
        </button>
      ) : null}
    </div>
  );
}

Extracted from Kanshelf/web/src/components/kanshelf/star-rating.tsx at e889ab6.