1"use client";
2
3import { Star } from "lucide-react";
4import {
5 Direction as DirectionPrimitive,
6 Slot as SlotPrimitive,
7} from "radix-ui";
8import * as React from "react";
9import { useComposedRefs } from "@/lib/compose-refs";
10import { cn } from "@/lib/utils";
11import { VisuallyHiddenInput } from "@/registry/bases/radix/components/visually-hidden-input";
12import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
13import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
14import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
15
16type Direction = "ltr" | "rtl";
17type Orientation = "horizontal" | "vertical";
18type ActivationMode = "automatic" | "manual";
19type Size = "default" | "sm" | "lg";
20type Step = 0.5 | 1;
21type DataState = "full" | "partial" | "empty";
22type FocusIntent = "first" | "last" | "prev" | "next";
23
24type RootElement = React.ComponentRef<typeof Rating>;
25type ItemElement = React.ComponentRef<typeof RatingItem>;
26
27const ROOT_NAME = "Rating";
28const ITEM_NAME = "RatingItem";
29
30const ENTRY_FOCUS = "ratingFocusGroup.onEntryFocus";
31const EVENT_OPTIONS = { bubbles: false, cancelable: true };
32
33function getItemId(id: string, value: number) {
34 return `${id}-item-${value}`;
35}
36
37function getPartialFillGradientId(id: string, step: Step) {
38 return `partial-fill-gradient-${id}-${step}`;
39}
40
41const MAP_KEY_TO_FOCUS_INTENT: Record<string, FocusIntent> = {
42 ArrowLeft: "prev",
43 ArrowUp: "prev",
44 ArrowRight: "next",
45 ArrowDown: "next",
46 Home: "first",
47 End: "last",
48};
49
50function getDirectionAwareKey(key: string, dir?: Direction) {
51 if (dir !== "rtl") return key;
52 return key === "ArrowLeft"
53 ? "ArrowRight"
54 : key === "ArrowRight"
55 ? "ArrowLeft"
56 : key;
57}
58
59function getFocusIntent(
60 event: React.KeyboardEvent<ItemElement>,
61 dir?: Direction,
62 orientation?: Orientation,
63) {
64 const key = getDirectionAwareKey(event.key, dir);
65 if (orientation === "horizontal" && ["ArrowUp", "ArrowDown"].includes(key))
66 return undefined;
67 if (orientation === "vertical" && ["ArrowLeft", "ArrowRight"].includes(key))
68 return undefined;
69 return MAP_KEY_TO_FOCUS_INTENT[key];
70}
71
72function focusFirst(
73 candidates: React.RefObject<ItemElement | null>[],
74 preventScroll = false,
75) {
76 const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
77 for (const candidateRef of candidates) {
78 const candidate = candidateRef.current;
79 if (!candidate) continue;
80 if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
81 candidate.focus({ preventScroll });
82 if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
83 }
84}
85
86interface StoreState {
87 value: number;
88 hoveredValue: number | null;
89}
90
91interface Store {
92 subscribe: (callback: () => void) => () => void;
93 getState: () => StoreState;
94 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
95 notify: () => void;
96}
97
98const StoreContext = React.createContext<Store | null>(null);
99
100function useStoreContext(consumerName: string) {
101 const context = React.useContext(StoreContext);
102 if (!context) {
103 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
104 }
105 return context;
106}
107
108function useStore<T>(
109 selector: (state: StoreState) => T,
110 ogStore?: Store | null,
111): T {
112 const contextStore = React.useContext(StoreContext);
113
114 const store = ogStore ?? contextStore;
115
116 if (!store) {
117 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
118 }
119
120 const getSnapshot = React.useCallback(
121 () => selector(store.getState()),
122 [store, selector],
123 );
124
125 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
126}
127
128interface ItemData {
129 id: string;
130 ref: React.RefObject<ItemElement | null>;
131 value: number;
132 disabled: boolean;
133}
134
135interface RatingContextValue {
136 rootId: string;
137 dir: Direction;
138 orientation: Orientation;
139 activationMode: ActivationMode;
140 size: Size;
141 max: number;
142 step: Step;
143 clearable: boolean;
144 disabled: boolean;
145 readOnly: boolean;
146 getAutoIndex: (instanceId: string) => number;
147}
148
149const RatingContext = React.createContext<RatingContextValue | null>(null);
150
151function useRatingContext(consumerName: string) {
152 const context = React.useContext(RatingContext);
153 if (!context) {
154 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
155 }
156 return context;
157}
158
159interface FocusContextValue {
160 tabStopId: string | null;
161 onItemFocus: (tabStopId: string) => void;
162 onItemShiftTab: () => void;
163 onFocusableItemAdd: () => void;
164 onFocusableItemRemove: () => void;
165 onItemRegister: (item: ItemData) => void;
166 onItemUnregister: (id: string) => void;
167 getItems: () => ItemData[];
168}
169
170const FocusContext = React.createContext<FocusContextValue | null>(null);
171
172function useFocusContext(consumerName: string) {
173 const context = React.useContext(FocusContext);
174 if (!context) {
175 throw new Error(
176 `\`${consumerName}\` must be used within \`FocusProvider\``,
177 );
178 }
179 return context;
180}
181
182interface RatingProps extends React.ComponentProps<"div"> {
183 value?: number;
184 defaultValue?: number;
185 onValueChange?: (value: number) => void;
186 onHover?: (value: number | null) => void;
187 max?: number;
188 activationMode?: ActivationMode;
189 dir?: Direction;
190 orientation?: Orientation;
191 size?: Size;
192 asChild?: boolean;
193 step?: Step;
194 clearable?: boolean;
195 disabled?: boolean;
196 readOnly?: boolean;
197 required?: boolean;
198 name?: string;
199}
200
201function Rating(props: RatingProps) {
202 const {
203 value: valueProp,
204 defaultValue = 0,
205 onValueChange,
206 onHover,
207 onFocus: onFocusProp,
208 onMouseDown: onMouseDownProp,
209 dir: dirProp,
210 orientation = "horizontal",
211 activationMode = "automatic",
212 size = "default",
213 max = 5,
214 step = 1,
215 clearable = false,
216 asChild,
217 disabled = false,
218 readOnly = false,
219 required = false,
220 className,
221 id,
222 name,
223 ref,
224 ...rootProps
225 } = props;
226
227 const dir = DirectionPrimitive.useDirection(dirProp);
228 const instanceId = React.useId();
229 const rootId = id ?? instanceId;
230
231 const listenersRef = useLazyRef(() => new Set<() => void>());
232 const stateRef = useLazyRef<StoreState>(() => ({
233 value: valueProp ?? defaultValue,
234 hoveredValue: null,
235 }));
236
237 const propsRef = useAsRef({
238 onValueChange,
239 onHover,
240 onFocus: onFocusProp,
241 onMouseDown: onMouseDownProp,
242 step,
243 });
244
245 const store = React.useMemo<Store>(() => {
246 return {
247 subscribe: (cb) => {
248 listenersRef.current.add(cb);
249 return () => listenersRef.current.delete(cb);
250 },
251 getState: () => stateRef.current,
252 setState: (key, value) => {
253 if (Object.is(stateRef.current[key], value)) return;
254
255 if (key === "value" && typeof value === "number") {
256 stateRef.current.value = value;
257 propsRef.current.onValueChange?.(value);
258 } else if (key === "hoveredValue") {
259 stateRef.current.hoveredValue = value as number | null;
260 propsRef.current.onHover?.(value as number | null);
261 } else {
262 stateRef.current[key] = value;
263 }
264
265 store.notify();
266 },
267 notify: () => {
268 for (const cb of listenersRef.current) {
269 cb();
270 }
271 },
272 };
273 }, [listenersRef, stateRef, propsRef]);
274
275 useIsomorphicLayoutEffect(() => {
276 if (valueProp !== undefined) {
277 store.setState("value", valueProp);
278 }
279 }, [valueProp]);
280
281 const value = useStore((state) => state.value, store);
282
283 const [formTrigger, setFormTrigger] = React.useState<RootElement | null>(
284 null,
285 );
286 const composedRef = useComposedRefs(ref, (node) => setFormTrigger(node));
287 const isFormControl = formTrigger ? !!formTrigger.closest("form") : true;
288
289 const [tabStopId, setTabStopId] = React.useState<string | null>(null);
290 const [isTabbingBackOut, setIsTabbingBackOut] = React.useState(false);
291 const [focusableItemCount, setFocusableItemCount] = React.useState(0);
292 const isClickFocusRef = React.useRef(false);
293 const itemsRef = React.useRef<Map<string, ItemData>>(new Map());
294
295 const autoIndexMapRef = React.useRef(new Map<string, number>());
296 const nextAutoIndexRef = React.useRef(0);
297
298 const getAutoIndex = React.useCallback((instanceId: string) => {
299 const existingIndex = autoIndexMapRef.current.get(instanceId);
300 if (existingIndex !== undefined) {
301 return existingIndex;
302 }
303
304 const newIndex = nextAutoIndexRef.current++;
305 autoIndexMapRef.current.set(instanceId, newIndex);
306 return newIndex;
307 }, []);
308
309 const onItemFocus = React.useCallback((tabStopId: string) => {
310 setTabStopId(tabStopId);
311 }, []);
312
313 const onItemShiftTab = React.useCallback(() => {
314 setIsTabbingBackOut(true);
315 }, []);
316
317 const onFocusableItemAdd = React.useCallback(() => {
318 setFocusableItemCount((prevCount) => prevCount + 1);
319 }, []);
320
321 const onFocusableItemRemove = React.useCallback(() => {
322 setFocusableItemCount((prevCount) => prevCount - 1);
323 }, []);
324
325 const onItemRegister = React.useCallback((item: ItemData) => {
326 itemsRef.current.set(item.id, item);
327 }, []);
328
329 const onItemUnregister = React.useCallback((id: string) => {
330 itemsRef.current.delete(id);
331 }, []);
332
333 const getItems = React.useCallback(() => {
334 return Array.from(itemsRef.current.values())
335 .filter((item) => item.ref.current)
336 .sort((a, b) => {
337 const elementA = a.ref.current;
338 const elementB = b.ref.current;
339 if (!elementA || !elementB) return 0;
340 const position = elementA.compareDocumentPosition(elementB);
341 if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
342 return -1;
343 }
344 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
345 return 1;
346 }
347 return 0;
348 });
349 }, []);
350
351 const onBlur = React.useCallback(
352 (event: React.FocusEvent<HTMLDivElement>) => {
353 rootProps.onBlur?.(event);
354 if (event.defaultPrevented) return;
355
356 setIsTabbingBackOut(false);
357 },
358 [rootProps.onBlur],
359 );
360
361 const onFocus = React.useCallback(
362 (event: React.FocusEvent<HTMLDivElement>) => {
363 propsRef.current.onFocus?.(event);
364 if (event.defaultPrevented) return;
365
366 const isKeyboardFocus = !isClickFocusRef.current;
367 if (
368 event.target === event.currentTarget &&
369 isKeyboardFocus &&
370 !isTabbingBackOut
371 ) {
372 const entryFocusEvent = new CustomEvent(ENTRY_FOCUS, EVENT_OPTIONS);
373 event.currentTarget.dispatchEvent(entryFocusEvent);
374
375 if (!entryFocusEvent.defaultPrevented) {
376 const items = Array.from(itemsRef.current.values()).filter(
377 (item) => !item.disabled,
378 );
379 // For half-step ratings, find the item that represents the selected value
380 // by looking for the ceiling value (e.g., 3.5 → find item with value 4)
381 const selectedItem =
382 propsRef.current.step < 1
383 ? items.find((item) => item.value === Math.ceil(value))
384 : items.find((item) => item.value === value);
385 const currentItem = items.find((item) => item.id === tabStopId);
386
387 const candidateItems = [selectedItem, currentItem, ...items].filter(
388 Boolean,
389 ) as ItemData[];
390 const candidateRefs = candidateItems.map((item) => item.ref);
391 focusFirst(candidateRefs, false);
392 }
393 }
394 isClickFocusRef.current = false;
395 },
396 [propsRef, isTabbingBackOut, value, tabStopId],
397 );
398
399 const onMouseDown = React.useCallback(
400 (event: React.MouseEvent<HTMLDivElement>) => {
401 propsRef.current.onMouseDown?.(event);
402
403 if (event.defaultPrevented) return;
404
405 isClickFocusRef.current = true;
406 },
407 [propsRef],
408 );
409
410 const contextValue = React.useMemo<RatingContextValue>(
411 () => ({
412 rootId,
413 dir,
414 orientation,
415 activationMode,
416 disabled,
417 readOnly,
418 size,
419 max,
420 step,
421 clearable,
422 getAutoIndex,
423 }),
424 [
425 rootId,
426 dir,
427 orientation,
428 activationMode,
429 disabled,
430 readOnly,
431 size,
432 max,
433 step,
434 clearable,
435 getAutoIndex,
436 ],
437 );
438
439 const focusContextValue = React.useMemo<FocusContextValue>(
440 () => ({
441 tabStopId,
442 onItemFocus,
443 onItemShiftTab,
444 onFocusableItemAdd,
445 onFocusableItemRemove,
446 onItemRegister,
447 onItemUnregister,
448 getItems,
449 }),
450 [
451 tabStopId,
452 onItemFocus,
453 onItemShiftTab,
454 onFocusableItemAdd,
455 onFocusableItemRemove,
456 onItemRegister,
457 onItemUnregister,
458 getItems,
459 ],
460 );
461
462 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
463
464 return (
465 <StoreContext.Provider value={store}>
466 <RatingContext.Provider value={contextValue}>
467 <FocusContext.Provider value={focusContextValue}>
468 <RootPrimitive
469 id={rootId}
470 role="radiogroup"
471 aria-orientation={orientation}
472 data-disabled={disabled ? "" : undefined}
473 data-readonly={readOnly ? "" : undefined}
474 data-orientation={orientation}
475 data-slot="rating"
476 dir={dir}
477 tabIndex={isTabbingBackOut || focusableItemCount === 0 ? -1 : 0}
478 {...rootProps}
479 ref={composedRef}
480 className={cn(
481 "flex gap-1 text-primary outline-none",
482 orientation === "horizontal"
483 ? "flex-row items-center"
484 : "flex-col items-start",
485 className,
486 )}
487 onBlur={onBlur}
488 onFocus={onFocus}
489 onMouseDown={onMouseDown}
490 />
491 <svg width="0" height="0" style={{ position: "absolute" }}>
492 <defs>
493 <linearGradient id={getPartialFillGradientId(rootId, step)}>
494 {dir === "rtl" ? (
495 <>
496 <stop offset="50%" stopColor="transparent" />
497 <stop offset="50%" stopColor="currentColor" />
498 </>
499 ) : (
500 <>
501 <stop offset="50%" stopColor="currentColor" />
502 <stop offset="50%" stopColor="transparent" />
503 </>
504 )}
505 </linearGradient>
506 </defs>
507 </svg>
508 {isFormControl && (
509 <VisuallyHiddenInput
510 type="hidden"
511 control={formTrigger}
512 name={name}
513 value={value}
514 disabled={disabled}
515 readOnly={readOnly}
516 required={required}
517 />
518 )}
519 </FocusContext.Provider>
520 </RatingContext.Provider>
521 </StoreContext.Provider>
522 );
523}
524
525interface RatingItemProps
526 extends Omit<React.ComponentProps<"button">, "children"> {
527 index?: number;
528 asChild?: boolean;
529 children?: React.ReactNode | ((dataState: DataState) => React.ReactNode);
530}
531
532function RatingItem(props: RatingItemProps) {
533 const {
534 index,
535 asChild,
536 onClick: onClickProp,
537 onFocus: onFocusProp,
538 onKeyDown: onKeyDownProp,
539 onMouseDown: onMouseDownProp,
540 onMouseEnter: onMouseEnterProp,
541 onMouseMove: onMouseMoveProp,
542 onMouseLeave: onMouseLeaveProp,
543 disabled,
544 className,
545 children,
546 ref,
547 ...itemProps
548 } = props;
549
550 const itemRef = React.useRef<ItemElement>(null);
551 const composedRef = useComposedRefs(ref, itemRef);
552
553 const context = useRatingContext(ITEM_NAME);
554
555 const instanceId = React.useId();
556
557 const actualIndex = React.useMemo(() => {
558 if (index !== undefined) {
559 return index;
560 }
561
562 return context.getAutoIndex(instanceId);
563 }, [index, context, instanceId]);
564
565 const itemValue = actualIndex + 1;
566 const store = useStoreContext(ITEM_NAME);
567 const focusContext = useFocusContext(ITEM_NAME);
568 const value = useStore((state) => state.value);
569 const hoveredValue = useStore((state) => state.hoveredValue);
570 const clearable = context.clearable;
571 const step = context.step;
572 const activationMode = context.activationMode;
573
574 const itemId = getItemId(context.rootId, itemValue);
575 const isDisabled = context.disabled || disabled;
576 const isReadOnly = context.readOnly;
577 const isTabStop = focusContext.tabStopId === itemId;
578
579 const displayValue = hoveredValue ?? value;
580 const isFilled = displayValue >= itemValue;
581 const isPartiallyFilled =
582 step < 1 && displayValue >= itemValue - step && displayValue < itemValue;
583 const isHovered = hoveredValue !== null && hoveredValue < itemValue;
584
585 const isMouseClickRef = React.useRef(false);
586
587 const propsRef = useAsRef({
588 onClick: onClickProp,
589 onFocus: onFocusProp,
590 onKeyDown: onKeyDownProp,
591 onMouseDown: onMouseDownProp,
592 onMouseEnter: onMouseEnterProp,
593 onMouseMove: onMouseMoveProp,
594 onMouseLeave: onMouseLeaveProp,
595 });
596
597 useIsomorphicLayoutEffect(() => {
598 focusContext.onItemRegister({
599 id: itemId,
600 ref: itemRef,
601 value: itemValue,
602 disabled: !!isDisabled,
603 });
604
605 if (!isDisabled) {
606 focusContext.onFocusableItemAdd();
607 }
608
609 return () => {
610 focusContext.onItemUnregister(itemId);
611 if (!isDisabled) {
612 focusContext.onFocusableItemRemove();
613 }
614 };
615 }, [focusContext, itemId, itemValue, isDisabled]);
616
617 const onClick = React.useCallback(
618 (event: React.MouseEvent<ItemElement>) => {
619 propsRef.current.onClick?.(event);
620 if (event.defaultPrevented) return;
621
622 if (!isDisabled && !isReadOnly) {
623 let newValue = itemValue;
624
625 if (step < 1) {
626 const rect = event.currentTarget.getBoundingClientRect();
627 const clickX = event.clientX - rect.left;
628 const isLeftHalf = clickX < rect.width / 2;
629
630 if (context.dir === "rtl") {
631 if (!isLeftHalf) {
632 newValue = itemValue - step;
633 }
634 } else {
635 if (isLeftHalf) {
636 newValue = itemValue - step;
637 }
638 }
639 }
640
641 if (clearable && value === newValue) {
642 newValue = 0;
643 }
644
645 store.setState("value", newValue);
646 }
647 },
648 [
649 isDisabled,
650 isReadOnly,
651 clearable,
652 step,
653 value,
654 itemValue,
655 store,
656 context.dir,
657 propsRef,
658 ],
659 );
660
661 const onFocus = React.useCallback(
662 (event: React.FocusEvent<ItemElement>) => {
663 propsRef.current.onFocus?.(event);
664 if (event.defaultPrevented) return;
665
666 focusContext.onItemFocus(itemId);
667
668 const isKeyboardFocus = !isMouseClickRef.current;
669
670 if (
671 !isDisabled &&
672 !isReadOnly &&
673 activationMode !== "manual" &&
674 isKeyboardFocus
675 ) {
676 // For half-step mode, check if the current value is a half-step that belongs to this item
677 // e.g., if value is 3.5 and itemValue is 4, don't change it
678 const isHalfStepValue = step < 1 && value === itemValue - step;
679
680 if (!isHalfStepValue) {
681 const newValue = clearable && value === itemValue ? 0 : itemValue;
682 store.setState("value", newValue);
683 }
684 }
685
686 isMouseClickRef.current = false;
687 },
688 [
689 focusContext,
690 itemId,
691 activationMode,
692 isDisabled,
693 isReadOnly,
694 clearable,
695 value,
696 itemValue,
697 step,
698 store,
699 propsRef,
700 ],
701 );
702
703 const onKeyDown = React.useCallback(
704 (event: React.KeyboardEvent<ItemElement>) => {
705 propsRef.current.onKeyDown?.(event);
706 if (event.defaultPrevented) return;
707
708 if (
709 (event.key === "Enter" || event.key === " ") &&
710 activationMode === "manual"
711 ) {
712 event.preventDefault();
713 if (!isDisabled && !isReadOnly && itemRef.current) {
714 itemRef.current.click();
715 }
716 return;
717 }
718
719 if (event.key === "Tab" && event.shiftKey) {
720 focusContext.onItemShiftTab();
721 return;
722 }
723
724 if (event.target !== event.currentTarget) return;
725
726 const focusIntent = getFocusIntent(
727 event,
728 context.dir,
729 context.orientation,
730 );
731
732 if (focusIntent !== undefined) {
733 if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
734 return;
735 event.preventDefault();
736
737 // For half-step mode, increment/decrement by step value instead of jumping to next item
738 if (step < 1 && (focusIntent === "prev" || focusIntent === "next")) {
739 if (!isDisabled && !isReadOnly) {
740 let newValue = value;
741
742 if (focusIntent === "next") {
743 newValue = Math.min(value + step, context.max);
744 } else {
745 newValue = Math.max(value - step, 0);
746 }
747
748 store.setState("value", newValue);
749
750 // Find and focus the item that represents this value
751 const items = focusContext
752 .getItems()
753 .filter((item) => !item.disabled);
754 const targetItem = items.find(
755 (item) => item.value === Math.ceil(newValue),
756 );
757 if (targetItem?.ref.current) {
758 queueMicrotask(() => targetItem.ref.current?.focus());
759 }
760 }
761 return;
762 }
763
764 // For full-step mode or Home/End keys, use the original navigation
765 const items = focusContext.getItems().filter((item) => !item.disabled);
766 let candidateRefs = items.map((item) => item.ref);
767
768 if (focusIntent === "last") {
769 candidateRefs.reverse();
770 } else if (focusIntent === "prev" || focusIntent === "next") {
771 if (focusIntent === "prev") candidateRefs.reverse();
772 const currentIndex = candidateRefs.findIndex(
773 (ref) => ref.current === event.currentTarget,
774 );
775 candidateRefs = candidateRefs.slice(currentIndex + 1);
776 }
777
778 queueMicrotask(() => focusFirst(candidateRefs));
779 }
780 },
781 [
782 focusContext,
783 context.dir,
784 context.orientation,
785 activationMode,
786 isDisabled,
787 isReadOnly,
788 step,
789 value,
790 context.max,
791 store,
792 propsRef,
793 ],
794 );
795
796 const onMouseDown = React.useCallback(
797 (event: React.MouseEvent<ItemElement>) => {
798 propsRef.current.onMouseDown?.(event);
799 if (event.defaultPrevented) return;
800
801 isMouseClickRef.current = true;
802
803 if (isDisabled) {
804 event.preventDefault();
805 } else {
806 focusContext.onItemFocus(itemId);
807 }
808 },
809 [focusContext, itemId, isDisabled, propsRef],
810 );
811
812 const onMouseEnter = React.useCallback(
813 (event: React.MouseEvent<ItemElement>) => {
814 propsRef.current.onMouseEnter?.(event);
815 if (event.defaultPrevented) return;
816
817 if (!isDisabled && !isReadOnly) {
818 let hoverValue = itemValue;
819
820 if (step < 1) {
821 const rect = event.currentTarget.getBoundingClientRect();
822 const mouseX = event.clientX - rect.left;
823 const isLeftHalf = mouseX < rect.width / 2;
824
825 if (context.dir === "rtl") {
826 if (!isLeftHalf) {
827 hoverValue = itemValue - step;
828 }
829 } else {
830 if (isLeftHalf) {
831 hoverValue = itemValue - step;
832 }
833 }
834 }
835
836 store.setState("hoveredValue", hoverValue);
837 }
838 },
839 [isDisabled, isReadOnly, step, itemValue, store, context.dir, propsRef],
840 );
841
842 const onMouseLeave = React.useCallback(
843 (event: React.MouseEvent<ItemElement>) => {
844 propsRef.current.onMouseLeave?.(event);
845 if (event.defaultPrevented) return;
846
847 if (!isDisabled && !isReadOnly) {
848 store.setState("hoveredValue", null);
849 }
850 },
851 [isDisabled, isReadOnly, store, propsRef],
852 );
853
854 const onMouseMove = React.useCallback(
855 (event: React.MouseEvent<ItemElement>) => {
856 propsRef.current.onMouseMove?.(event);
857 if (event.defaultPrevented) return;
858
859 if (!isDisabled && !isReadOnly && step < 1) {
860 const rect = event.currentTarget.getBoundingClientRect();
861 const mouseX = event.clientX - rect.left;
862 const isLeftHalf = mouseX < rect.width / 2;
863
864 let hoverValue = itemValue;
865 if (context.dir === "rtl") {
866 hoverValue = !isLeftHalf ? itemValue - step : itemValue;
867 } else {
868 hoverValue = isLeftHalf ? itemValue - step : itemValue;
869 }
870
871 store.setState("hoveredValue", hoverValue);
872 }
873 },
874 [isDisabled, isReadOnly, step, itemValue, store, context.dir, propsRef],
875 );
876
877 const dataState: DataState = isFilled
878 ? "full"
879 : isPartiallyFilled
880 ? "partial"
881 : "empty";
882
883 const ItemPrimitive = asChild ? SlotPrimitive.Slot : "button";
884
885 return (
886 <ItemPrimitive
887 role="radio"
888 type="button"
889 id={itemId}
890 aria-checked={isFilled}
891 aria-posinset={itemValue}
892 aria-setsize={context.max}
893 data-disabled={isDisabled ? "" : undefined}
894 data-readonly={isReadOnly ? "" : undefined}
895 data-state={isFilled ? "full" : isPartiallyFilled ? "partial" : "empty"}
896 data-hovered={isHovered ? "" : undefined}
897 data-slot="rating-item"
898 disabled={isDisabled}
899 tabIndex={isTabStop ? 0 : -1}
900 {...itemProps}
901 ref={composedRef}
902 style={{
903 ...itemProps.style,
904 ...(isPartiallyFilled && {
905 "--partial-fill": `url(#${getPartialFillGradientId(context.rootId, step)})`,
906 }),
907 }}
908 className={cn(
909 "inline-flex items-center justify-center rounded transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
910 "[&_svg:not([class*='size-'])]:size-full [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:transition-colors [&_svg]:duration-200 data-[state=empty]:[&_svg]:fill-transparent data-[state=full]:[&_svg]:fill-current data-[state=partial]:[&_svg]:fill-(--partial-fill)",
911 context.size === "sm"
912 ? "size-4"
913 : context.size === "lg"
914 ? "size-6"
915 : "size-5",
916 className,
917 )}
918 onClick={onClick}
919 onFocus={onFocus}
920 onKeyDown={onKeyDown}
921 onMouseDown={onMouseDown}
922 onMouseEnter={onMouseEnter}
923 onMouseMove={onMouseMove}
924 onMouseLeave={onMouseLeave}
925 >
926 {typeof children === "function"
927 ? children(dataState)
928 : (children ?? <Star />)}
929 </ItemPrimitive>
930 );
931}
932
933export { Rating, RatingItem, useStore as useRating };
934