|
| 1 | +import * as React from 'react'; |
| 2 | +import { TouchableOpacity, View } from 'react-native'; |
| 3 | +import { DeepPartial } from 'ts-essentials'; |
| 4 | + |
| 5 | +import { ControlSize, TextColor, useTheme } from '../../theme'; |
| 6 | +import { mergeStyles, ReplaceReturnType } from '../../utils/mergeStyles'; |
| 7 | +import { |
| 8 | + GetRatingStyles, |
| 9 | + getRatingStyles, |
| 10 | + RatingStyles, |
| 11 | +} from './Rating.styles'; |
| 12 | +import { Star } from './Star'; |
| 13 | + |
| 14 | +export interface RatingProps { |
| 15 | + value?: number; |
| 16 | + maxRating?: number; |
| 17 | + size?: ControlSize; |
| 18 | + getStyles?: ReplaceReturnType<GetRatingStyles, DeepPartial<RatingStyles>>; |
| 19 | + onChange?: (value: number) => void; |
| 20 | + color?: TextColor; |
| 21 | +} |
| 22 | + |
| 23 | +export const Rating = (props: RatingProps) => { |
| 24 | + const { |
| 25 | + value = 0, |
| 26 | + maxRating = 5, |
| 27 | + size = 'medium', |
| 28 | + getStyles, |
| 29 | + onChange = () => undefined, |
| 30 | + color = 'primary', |
| 31 | + } = props; |
| 32 | + const theme = useTheme(); |
| 33 | + |
| 34 | + const { containerStyle, starColor, starSize, touchableStyle } = mergeStyles( |
| 35 | + getRatingStyles, |
| 36 | + getStyles, |
| 37 | + )({ size, color }, theme); |
| 38 | + |
| 39 | + return ( |
| 40 | + <View style={containerStyle}> |
| 41 | + {new Array(maxRating).fill(0).map((_, index) => { |
| 42 | + const currentValue = index + 1; |
| 43 | + const isWithinRating = currentValue <= value; |
| 44 | + const isLast = currentValue === maxRating; |
| 45 | + |
| 46 | + return ( |
| 47 | + <TouchableOpacity |
| 48 | + key={currentValue} |
| 49 | + style={{ |
| 50 | + ...touchableStyle, |
| 51 | + ...(isLast ? { paddingRight: 0 } : {}), |
| 52 | + }} |
| 53 | + onPress={() => onChange(currentValue)} |
| 54 | + > |
| 55 | + <Star color={starColor} size={starSize} isFilled={isWithinRating} /> |
| 56 | + </TouchableOpacity> |
| 57 | + ); |
| 58 | + })} |
| 59 | + </View> |
| 60 | + ); |
| 61 | +}; |
0 commit comments