import { memo, useEffect, useState } from 'react'; import styled from '@emotion/styled'; import { nobel, secondary } from 'styles/colors'; import noop from 'utils/noop'; import usePrevious from 'utils/usePrevious'; import { small, medium, large, extraLarge } from './ratingSizes'; import Star from './components/Star'; const RatingContainer = styled.div` display: inline-block; `; const getValidRangeValue = (value: number) => Math.min(Math.max(value, 0), 5); interface Props { /** Star size: must be one of "small" (7), "medium" (16), "large" (21), or "extraLarge" (37). */ size?: typeof small | typeof medium | typeof large | typeof extraLarge; /** Current number of stars shown. 0 indicates no rating (all stars are gray). */ value?: number; /** Called when the user changes the rating. The callback function includes the rating's current value. */ onClick?: (_value: number) => void; } const Rating = ({ size = small, value = 0, onClick = noop }: Props) => { const [_value, setValue] = useState(getValidRangeValue(value)); const [hoverValue, setHoverValue] = useState(0); const prevValue = usePrevious(value); useEffect(() => { if (value !== prevValue) { setValue(getValidRangeValue(value)); } }, [value]); const handleClick = (i: number) => { const val = i + 1; // map from index to value setValue(getValidRangeValue(val)); onClick(val); }; const handleMouseEnter = i => { setHoverValue(i + 1); }; const handleMouseLeave = () => { setHoverValue(0); }; const colorFill = (i: number) => { const grayColor = size === extraLarge ? nobel['100'] : nobel['200']; const usedValue = hoverValue || _value; return i < usedValue ? secondary.main : grayColor; }; return ( {[0, 1, 2, 3, 4].map(i => ( handleClick(i), onMouseEnter: () => handleMouseEnter(i), onMouseLeave: () => handleMouseLeave(), } : {})} /> ))} ); }; Rating.displayName = 'Rating'; export default memo(Rating);