"use client" import * as React from "react" import { StarIcon } from "lucide-react" import { cn } from "@/lib/utils" export type RatingProps = Omit, "onChange"> & { value?: number defaultValue?: number onValueChange?: (value: number) => void count?: number allowClear?: boolean disabled?: boolean readOnly?: boolean labels?: { rate?: (value: number) => string clear?: string } icon?: React.ReactNode } function Rating({ value, defaultValue = 0, onValueChange, count = 5, allowClear = true, disabled = false, readOnly = false, labels, icon, className, ...props }: RatingProps) { const [internalValue, setInternalValue] = React.useState(defaultValue) const [hoverValue, setHoverValue] = React.useState(null) const currentValue = value ?? internalValue const displayValue = hoverValue ?? currentValue const interactive = !disabled && !readOnly const setRating = (nextValue: number) => { if (!interactive) return const resolvedValue = allowClear && nextValue === currentValue ? 0 : nextValue if (value === undefined) setInternalValue(resolvedValue) onValueChange?.(resolvedValue) } const handleKeyDown = (event: React.KeyboardEvent, nextValue: number) => { if (!interactive) return if (event.key === "Enter" || event.key === " ") { event.preventDefault() setRating(nextValue) } } return (
setHoverValue(null)} {...props} > {Array.from({ length: count }, (_, index) => { const nextValue = index + 1 const selected = nextValue <= displayValue return ( ) })} {allowClear && currentValue > 0 && interactive && ( )}
) } export { Rating }