-
-
Notifications
You must be signed in to change notification settings - Fork 14.5k
/
rate.vue
295 lines (279 loc) Β· 8.3 KB
/
rate.vue
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
<template>
<div
:id="inputId"
:class="[rateClasses, ns.is('disabled', rateDisabled)]"
role="slider"
:aria-label="!isLabeledByFormItem ? label || 'rating' : undefined"
:aria-labelledby="
isLabeledByFormItem ? formItemContext?.labelId : undefined
"
:aria-valuenow="currentValue"
:aria-valuetext="text || undefined"
aria-valuemin="0"
:aria-valuemax="max"
tabindex="0"
:style="rateStyles"
@keydown="handleKey"
>
<span
v-for="(item, key) in max"
:key="key"
:class="ns.e('item')"
@mousemove="setCurrentValue(item, $event)"
@mouseleave="resetCurrentValue"
@click="selectValue(item)"
>
<el-icon
:class="[
ns.e('icon'),
{ hover: hoverIndex === item },
ns.is('active', item <= currentValue),
]"
>
<template v-if="!showDecimalIcon(item)">
<component :is="activeComponent" v-show="item <= currentValue" />
<component :is="voidComponent" v-show="!(item <= currentValue)" />
</template>
<el-icon
v-if="showDecimalIcon(item)"
:style="decimalStyle"
:class="[ns.e('icon'), ns.e('decimal')]"
>
<component :is="decimalIconComponent" />
</el-icon>
</el-icon>
</span>
<span v-if="showText || showScore" :class="ns.e('text')">
{{ text }}
</span>
</div>
</template>
<script lang="ts" setup>
import { computed, inject, markRaw, ref, watch } from 'vue'
import { EVENT_CODE, UPDATE_MODEL_EVENT } from '@element-plus/constants'
import { hasClass, isArray, isObject, isString } from '@element-plus/utils'
import { formContextKey, formItemContextKey } from '@element-plus/tokens'
import { ElIcon } from '@element-plus/components/icon'
import { useFormItemInputId, useNamespace, useSize } from '@element-plus/hooks'
import { rateEmits, rateProps } from './rate'
import type { iconPropType } from '@element-plus/utils'
import type { CSSProperties, Component } from 'vue'
function getValueFromMap<T>(
value: number,
map: Record<string, T | { excluded?: boolean; value: T }>
) {
const isExcludedObject = (
val: unknown
): val is { excluded?: boolean } & Record<any, unknown> => isObject(val)
const matchedKeys = Object.keys(map)
.map((key) => +key)
.filter((key) => {
const val = map[key]
const excluded = isExcludedObject(val) ? val.excluded : false
return excluded ? value < key : value <= key
})
.sort((a, b) => a - b)
const matchedValue = map[matchedKeys[0]]
return (isExcludedObject(matchedValue) && matchedValue.value) || matchedValue
}
defineOptions({
name: 'ElRate',
})
const props = defineProps(rateProps)
const emit = defineEmits(rateEmits)
const formContext = inject(formContextKey, undefined)
const formItemContext = inject(formItemContextKey, undefined)
const rateSize = useSize()
const ns = useNamespace('rate')
const { inputId, isLabeledByFormItem } = useFormItemInputId(props, {
formItemContext,
})
const currentValue = ref(props.modelValue)
const hoverIndex = ref(-1)
const pointerAtLeftHalf = ref(true)
const rateClasses = computed(() => [ns.b(), ns.m(rateSize.value)])
const rateDisabled = computed(() => props.disabled || formContext?.disabled)
const rateStyles = computed(() => {
return ns.cssVarBlock({
'void-color': props.voidColor,
'disabled-void-color': props.disabledVoidColor,
'fill-color': activeColor.value,
}) as CSSProperties
})
const text = computed(() => {
let result = ''
if (props.showScore) {
result = props.scoreTemplate.replace(
/\{\s*value\s*\}/,
rateDisabled.value ? `${props.modelValue}` : `${currentValue.value}`
)
} else if (props.showText) {
result = props.texts[Math.ceil(currentValue.value) - 1]
}
return result
})
const valueDecimal = computed(
() => props.modelValue * 100 - Math.floor(props.modelValue) * 100
)
const colorMap = computed(() =>
isArray(props.colors)
? {
[props.lowThreshold]: props.colors[0],
[props.highThreshold]: { value: props.colors[1], excluded: true },
[props.max]: props.colors[2],
}
: props.colors
)
const activeColor = computed(() => {
const color = getValueFromMap(currentValue.value, colorMap.value)
// {value: '', excluded: true} returned
return isObject(color) ? '' : color
})
const decimalStyle = computed(() => {
let width = ''
if (rateDisabled.value) {
width = `${valueDecimal.value}%`
} else if (props.allowHalf) {
width = '50%'
}
return {
color: activeColor.value,
width,
}
})
const componentMap = computed(() => {
let icons = isArray(props.icons) ? [...props.icons] : { ...props.icons }
icons = markRaw(icons) as
| Array<string | Component>
| Record<number, string | Component>
return isArray(icons)
? {
[props.lowThreshold]: icons[0],
[props.highThreshold]: {
value: icons[1],
excluded: true,
},
[props.max]: icons[2],
}
: icons
})
const decimalIconComponent = computed(() =>
getValueFromMap(props.modelValue, componentMap.value)
)
const voidComponent = computed(() =>
rateDisabled.value
? isString(props.disabledVoidIcon)
? props.disabledVoidIcon
: (markRaw(props.disabledVoidIcon) as typeof iconPropType)
: isString(props.voidIcon)
? props.voidIcon
: (markRaw(props.voidIcon) as typeof iconPropType)
)
const activeComponent = computed(() =>
getValueFromMap(currentValue.value, componentMap.value)
)
function showDecimalIcon(item: number) {
const showWhenDisabled =
rateDisabled.value &&
valueDecimal.value > 0 &&
item - 1 < props.modelValue &&
item > props.modelValue
const showWhenAllowHalf =
props.allowHalf &&
pointerAtLeftHalf.value &&
item - 0.5 <= currentValue.value &&
item > currentValue.value
return showWhenDisabled || showWhenAllowHalf
}
function selectValue(value: number) {
if (rateDisabled.value) {
return
}
if (props.allowHalf && pointerAtLeftHalf.value) {
emit(UPDATE_MODEL_EVENT, currentValue.value)
if (props.modelValue !== currentValue.value) {
emit('change', currentValue.value)
}
} else {
emit(UPDATE_MODEL_EVENT, value)
if (props.modelValue !== value) {
emit('change', value)
}
}
}
function handleKey(e: KeyboardEvent) {
if (rateDisabled.value) {
return
}
let _currentValue = currentValue.value
const code = e.code
if (code === EVENT_CODE.up || code === EVENT_CODE.right) {
if (props.allowHalf) {
_currentValue += 0.5
} else {
_currentValue += 1
}
e.stopPropagation()
e.preventDefault()
} else if (code === EVENT_CODE.left || code === EVENT_CODE.down) {
if (props.allowHalf) {
_currentValue -= 0.5
} else {
_currentValue -= 1
}
e.stopPropagation()
e.preventDefault()
}
_currentValue = _currentValue < 0 ? 0 : _currentValue
_currentValue = _currentValue > props.max ? props.max : _currentValue
emit(UPDATE_MODEL_EVENT, _currentValue)
emit('change', _currentValue)
return _currentValue
}
function setCurrentValue(value: number, event: MouseEvent) {
if (rateDisabled.value) {
return
}
if (props.allowHalf) {
// TODO: use cache via computed https://github.com/element-plus/element-plus/pull/5456#discussion_r786472092
let target = event.target as HTMLElement
if (hasClass(target, ns.e('item'))) {
target = target.querySelector(`.${ns.e('icon')}`)!
}
if (target.clientWidth === 0 || hasClass(target, ns.e('decimal'))) {
target = target.parentNode as HTMLElement
}
pointerAtLeftHalf.value = event.offsetX * 2 <= target.clientWidth
currentValue.value = pointerAtLeftHalf.value ? value - 0.5 : value
} else {
currentValue.value = value
}
hoverIndex.value = value
}
function resetCurrentValue() {
if (rateDisabled.value) {
return
}
if (props.allowHalf) {
pointerAtLeftHalf.value = props.modelValue !== Math.floor(props.modelValue)
}
currentValue.value = props.modelValue
hoverIndex.value = -1
}
watch(
() => props.modelValue,
(val) => {
currentValue.value = val
pointerAtLeftHalf.value = props.modelValue !== Math.floor(props.modelValue)
}
)
if (!props.modelValue) {
emit(UPDATE_MODEL_EVENT, 0)
}
defineExpose({
/** @description set current value */
setCurrentValue,
/** @description reset current value */
resetCurrentValue,
})
</script>