-
Notifications
You must be signed in to change notification settings - Fork 30
/
Rating.tsx
315 lines (282 loc) · 8.43 KB
/
Rating.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import React, { useMemo, useReducer, useCallback, Fragment } from 'react'
import { StarIcon } from './StarIcon'
/**
* check for touch devices
*
* @returns `boolean`
*/
const isTouchDevice = () => 'ontouchstart' in window || navigator.maxTouchPoints > 0
function calculateCurrentPosition(totalIcons: number, positionX: number, width: number) {
const iconWidth = width / totalIcons
let currentValue = totalIcons
for (let i = 0; i < totalIcons; i += 1) {
// if position less then quarter icon
if (positionX <= iconWidth * i + iconWidth / 4) {
// if there is no value return 0
if (i === 0 && positionX < iconWidth / 2) currentValue = 0
else currentValue = i
break
}
}
return currentValue
}
type State = {
defaultValue: number | null
hoverValue: number | null
}
type Action =
| { type: 'PointerMove'; payload: number | null }
| { type: 'PointerLeave' }
| { type: 'MouseClick'; payload: number }
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'PointerMove':
return {
...state,
hoverValue: action.payload
}
case 'PointerLeave':
return {
defaultValue: state.defaultValue,
hoverValue: null
}
case 'MouseClick':
return {
...state,
defaultValue: action.payload
}
default:
return state
}
}
export interface Props {
onClick?: (value: number) => void
initialValue?: number
ratingValue: number
iconsCount?: number
size?: number
readonly?: boolean
fillColor?: string
fillColorArray?: string[]
emptyColor?: string
fullIcon?: React.ReactElement | null
emptyIcon?: React.ReactElement | null
customIcons?: {
icon: React.ReactElement
}[]
rtl?: boolean
allowHalfIcon?: boolean
allowHover?: boolean
transition?: boolean
className?: string
style?: React.CSSProperties
fullClassName?: string
emptyClassName?: string
fullStyle?: React.CSSProperties
emptyStyle?: React.CSSProperties
showTooltip?: boolean
tooltipDefaultText?: string
tooltipArray?: string[]
tooltipClassName?: string
tooltipStyle?: React.CSSProperties
}
export function Rating({
onClick,
initialValue = 0,
ratingValue = 0,
iconsCount = 5,
size = 40,
readonly = false,
fillColor = '#ffbc0b',
fillColorArray = [],
emptyColor = '#cccccc',
fullIcon = null,
emptyIcon = null,
customIcons = [],
rtl = false,
allowHalfIcon = false,
allowHover = true,
transition = false,
className = 'react-simple-star-rating',
style,
fullClassName = 'filled-icons',
emptyClassName = 'empty-icons',
fullStyle,
emptyStyle,
showTooltip = false,
tooltipDefaultText = 'Your Rate',
tooltipArray = [],
tooltipClassName = 'react-simple-star-rating-tooltip',
tooltipStyle
}: Props) {
const [{ defaultValue, hoverValue }, dispatch] = useReducer(reducer, {
defaultValue: ratingValue,
hoverValue: null
})
// re-render when ratingValue changes
React.useEffect(() => dispatch({ type: 'MouseClick', payload: ratingValue }), [ratingValue])
/**
* use pointer event rather than mouse event
*
* @param event
* @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent
* @returns `void`
*/
const onPointerMove = (event: React.PointerEvent<HTMLSpanElement>) => {
const { clientX, currentTarget } = event
// get main span element position and width
const { left, right, width } = currentTarget.children[0].getBoundingClientRect()
// set for RTL
const positionX = rtl ? right - clientX : clientX - left
// Get current pointer position while moves over the icons
const currentValue = calculateCurrentPosition(totalIcons, positionX, width)
// set the value to state
if (currentValue > 0 && hoverValue !== currentValue) {
dispatch({ type: 'PointerMove', payload: currentValue * 100 / totalIcons })
}
}
/**
* handle onEnter
* @param event
* @returns `void`
*/
const onPointerEnter = (event: React.PointerEvent<HTMLSpanElement>) => {
// enable only on touch devices
if (!isTouchDevice()) return
// call to get the value
onPointerMove(event)
}
/**
* handle onClick
* @returns `void`
*/
const onRate = () => {
if (hoverValue) {
dispatch({ type: 'MouseClick', payload: hoverValue })
// update value on click
if (onClick) onClick(hoverValue)
}
}
/**
* handle onLeave
* @returns `void`
*/
const onPointerLeave = () => {
if (isTouchDevice()) onRate()
dispatch({ type: 'PointerLeave' })
}
// if there is a local rating value, convert it to precentage
const localRating = useMemo(() => Math.round((initialValue / iconsCount) * 100), [initialValue, iconsCount])
/**
* convert rating value to percentage value
* @returns `hover value` | `rating value` | `local rating`
*/
const valuePercentage = useMemo(
() => (allowHover && hoverValue && hoverValue) || (defaultValue && defaultValue) || localRating,
[allowHover, hoverValue, defaultValue, localRating]
)
// handle total icons
const totalIcons = useMemo(() => (allowHalfIcon ? iconsCount * 2 : iconsCount), [allowHalfIcon, iconsCount])
// convert value to index
const valueIndex = useCallback(
(value: number) => {
let index = 1
if (value) {
index = Math.round(value / 100 * totalIcons) + 1
}
return Math.round(index - 1)
},
[totalIcons]
)
// convert value to render value
const renderValue = useCallback(
(value: number) => {
const rvalue = valueIndex(value)
return allowHalfIcon ? rvalue / 2 : rvalue
},
[allowHalfIcon, valueIndex]
)
// handle tooltip values
const handleTooltip = (value: number) =>
tooltipArray.length > 0 ? tooltipArray[valueIndex(value)] : renderValue(value) || 0
return (
<span style={{ display: 'inline-block', direction: `${rtl ? 'rtl' : 'ltr'}`, touchAction: 'none' }}>
<span
className={className}
style={{
position: 'relative',
display: 'inline-block',
overflow: 'hidden',
whiteSpace: 'nowrap',
cursor: readonly ? '' : 'pointer',
verticalAlign: 'middle',
userSelect: 'none',
...style
}}
onPointerMove={readonly ? undefined : onPointerMove}
onPointerEnter={readonly ? undefined : onPointerEnter}
onPointerLeave={readonly ? undefined : onPointerLeave}
onClick={readonly ? undefined : onRate}
aria-hidden='true'
>
<span
className={emptyClassName}
style={{
display: 'inline-block',
color: emptyColor,
...emptyStyle
}}
>
{[...Array(iconsCount)].map((_, index) => (
<Fragment key={index}>
{customIcons[index]?.icon || emptyIcon || <StarIcon key={index} size={size} />}
</Fragment>
))}
</span>
<span
className={fullClassName}
style={{
position: 'absolute',
top: 0,
[rtl ? 'right' : 'left']: 0,
color:
(allowHover && hoverValue && fillColorArray[valueIndex(hoverValue)]) ||
(defaultValue && fillColorArray[valueIndex(defaultValue)]) ||
fillColor,
overflow: 'hidden',
whiteSpace: 'nowrap',
display: 'inline-block',
transition: transition ? 'width .2s ease, color .2s ease' : '',
width: `${valuePercentage}%`,
...fullStyle
}}
title={`${(hoverValue && renderValue(hoverValue)) || renderValue(localRating)} out of ${iconsCount}`}
>
{[...Array(iconsCount)].map((_, index) => (
<Fragment key={index}>{customIcons[index]?.icon || fullIcon || <StarIcon size={size} />}</Fragment>
))}
</span>
</span>
{showTooltip && (
<span
className={tooltipClassName}
style={{
display: 'inline-block',
padding: '5px 15px',
backgroundColor: '#333',
color: '#fff',
[rtl ? 'marginRight' : 'marginLeft']: 20,
verticalAlign: 'middle',
borderRadius: 5,
...tooltipStyle
}}
>
{(hoverValue && handleTooltip(hoverValue)) ||
(defaultValue && handleTooltip(defaultValue)) ||
(localRating && handleTooltip(localRating)) ||
tooltipDefaultText}
</span>
)}
</span>
)
}