1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import { type LucideProps, StarIcon } from "lucide-react";
5import type { KeyboardEvent, MouseEvent, ReactElement, ReactNode } from "react";
6import {
7 Children,
8 cloneElement,
9 createContext,
10 useCallback,
11 useContext,
12 useEffect,
13 useRef,
14 useState,
15} from "react";
16import { cn } from "@/lib/utils";
17
18type RatingContextValue = {
19 value: number;
20 readOnly: boolean;
21 hoverValue: number | null;
22 focusedStar: number | null;
23 handleValueChange: (
24 event: MouseEvent<HTMLButtonElement> | KeyboardEvent<HTMLButtonElement>,
25 value: number
26 ) => void;
27 handleKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => void;
28 setHoverValue: (value: number | null) => void;
29 setFocusedStar: (value: number | null) => void;
30};
31
32const RatingContext = createContext<RatingContextValue | null>(null);
33
34const useRating = () => {
35 const context = useContext(RatingContext);
36 if (!context) {
37 throw new Error("useRating must be used within a Rating component");
38 }
39 return context;
40};
41
42export type RatingButtonProps = LucideProps & {
43 index?: number;
44 icon?: ReactElement<LucideProps>;
45};
46
47export const RatingButton = ({
48 index: providedIndex,
49 size = 20,
50 className,
51 icon = <StarIcon />,
52}: RatingButtonProps) => {
53 const {
54 value,
55 readOnly,
56 hoverValue,
57 focusedStar,
58 handleValueChange,
59 handleKeyDown,
60 setHoverValue,
61 setFocusedStar,
62 } = useRating();
63
64 const index = providedIndex ?? 0;
65 const isActive = index < (hoverValue ?? focusedStar ?? value ?? 0);
66 let tabIndex = -1;
67
68 if (!readOnly) {
69 tabIndex = value === index + 1 ? 0 : -1;
70 }
71
72 const handleClick = useCallback(
73 (event: MouseEvent<HTMLButtonElement>) => {
74 handleValueChange(event, index + 1);
75 },
76 [handleValueChange, index]
77 );
78
79 const handleMouseEnter = useCallback(() => {
80 if (!readOnly) {
81 setHoverValue(index + 1);
82 }
83 }, [readOnly, setHoverValue, index]);
84
85 const handleFocus = useCallback(() => {
86 setFocusedStar(index + 1);
87 }, [setFocusedStar, index]);
88
89 const handleBlur = useCallback(() => {
90 setFocusedStar(null);
91 }, [setFocusedStar]);
92
93 return (
94 <button
95 className={cn(
96 "rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
97 "p-0.5",
98 readOnly && "cursor-default",
99 className
100 )}
101 disabled={readOnly}
102 onBlur={handleBlur}
103 onClick={handleClick}
104 onFocus={handleFocus}
105 onKeyDown={handleKeyDown}
106 onMouseEnter={handleMouseEnter}
107 tabIndex={tabIndex}
108 type="button"
109 >
110 {cloneElement(icon, {
111 size,
112 className: cn(
113 "transition-colors duration-200",
114 isActive && "fill-current",
115 !readOnly && "cursor-pointer"
116 ),
117 "aria-hidden": "true",
118 })}
119 </button>
120 );
121};
122
123export type RatingProps = {
124 defaultValue?: number;
125 value?: number;
126 onChange?: (
127 event: MouseEvent<HTMLButtonElement> | KeyboardEvent<HTMLButtonElement>,
128 value: number
129 ) => void;
130 onValueChange?: (value: number) => void;
131 readOnly?: boolean;
132 className?: string;
133 children?: ReactNode;
134};
135
136export const Rating = ({
137 value: controlledValue,
138 onValueChange: controlledOnValueChange,
139 defaultValue = 0,
140 onChange,
141 readOnly = false,
142 className,
143 children,
144 ...props
145}: RatingProps) => {
146 const [hoverValue, setHoverValue] = useState<number | null>(null);
147 const [focusedStar, setFocusedStar] = useState<number | null>(null);
148 const containerRef = useRef<HTMLDivElement>(null);
149 const [value, onValueChange] = useControllableState({
150 defaultProp: defaultValue,
151 prop: controlledValue,
152 onChange: controlledOnValueChange,
153 });
154
155 const handleValueChange = useCallback(
156 (
157 event: MouseEvent<HTMLButtonElement> | KeyboardEvent<HTMLButtonElement>,
158 newValue: number
159 ) => {
160 if (!readOnly) {
161 onChange?.(event, newValue);
162 onValueChange?.(newValue);
163 }
164 },
165 [readOnly, onChange, onValueChange]
166 );
167
168 const handleKeyDown = useCallback(
169 (event: KeyboardEvent<HTMLButtonElement>) => {
170 if (readOnly) {
171 return;
172 }
173
174 const total = Children.count(children);
175 let newValue = focusedStar !== null ? focusedStar : (value ?? 0);
176
177 switch (event.key) {
178 case "ArrowRight":
179 if (event.shiftKey || event.metaKey) {
180 newValue = total;
181 } else {
182 newValue = Math.min(total, newValue + 1);
183 }
184 break;
185 case "ArrowLeft":
186 if (event.shiftKey || event.metaKey) {
187 newValue = 1;
188 } else {
189 newValue = Math.max(1, newValue - 1);
190 }
191 break;
192 default:
193 return;
194 }
195
196 event.preventDefault();
197 setFocusedStar(newValue);
198 handleValueChange(event, newValue);
199 },
200 [focusedStar, value, children, readOnly, handleValueChange]
201 );
202
203 useEffect(() => {
204 if (focusedStar !== null && containerRef.current) {
205 const buttons = containerRef.current.querySelectorAll("button");
206 buttons[focusedStar - 1]?.focus();
207 }
208 }, [focusedStar]);
209
210 const contextValue: RatingContextValue = {
211 value: value ?? 0,
212 readOnly,
213 hoverValue,
214 focusedStar,
215 handleValueChange,
216 handleKeyDown,
217 setHoverValue,
218 setFocusedStar,
219 };
220
221 return (
222 <RatingContext.Provider value={contextValue}>
223 <div
224 aria-label="Rating"
225 className={cn("inline-flex items-center gap-0.5", className)}
226 onMouseLeave={() => setHoverValue(null)}
227 ref={containerRef}
228 role="radiogroup"
229 {...props}
230 >
231 {Children.map(children, (child, index) => {
232 if (!child) {
233 return null;
234 }
235
236 return cloneElement(child as ReactElement<RatingButtonProps>, {
237 index,
238 });
239 })}
240 </div>
241 </RatingContext.Provider>
242 );
243};
244