-
-
Notifications
You must be signed in to change notification settings - Fork 14.7k
/
input-number.vue
executable file
Β·350 lines (334 loc) Β· 9.56 KB
/
input-number.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<template>
<div
:class="[
ns.b(),
ns.m(inputNumberSize),
ns.is('disabled', inputNumberDisabled),
ns.is('without-controls', !controls),
ns.is('controls-right', controlsAtRight),
]"
@dragstart.prevent
>
<span
v-if="controls"
v-repeat-click="decrease"
role="button"
:aria-label="t('el.inputNumber.decrease')"
:class="[ns.e('decrease'), ns.is('disabled', minDisabled)]"
@keydown.enter="decrease"
>
<slot name="decrease-icon">
<el-icon>
<arrow-down v-if="controlsAtRight" />
<minus v-else />
</el-icon>
</slot>
</span>
<span
v-if="controls"
v-repeat-click="increase"
role="button"
:aria-label="t('el.inputNumber.increase')"
:class="[ns.e('increase'), ns.is('disabled', maxDisabled)]"
@keydown.enter="increase"
>
<slot name="increase-icon">
<el-icon>
<arrow-up v-if="controlsAtRight" />
<plus v-else />
</el-icon>
</slot>
</span>
<el-input
:id="id"
ref="input"
type="number"
:step="step"
:model-value="displayValue"
:placeholder="placeholder"
:readonly="readonly"
:disabled="inputNumberDisabled"
:size="inputNumberSize"
:max="max"
:min="min"
:name="name"
:label="label"
:validate-event="false"
@wheel="handleWheel"
@keydown.up.prevent="increase"
@keydown.down.prevent="decrease"
@blur="handleBlur"
@focus="handleFocus"
@input="handleInput"
@change="handleInputChange"
/>
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, onUpdated, reactive, ref, watch } from 'vue'
import { isNil } from 'lodash-unified'
import { ElInput } from '@element-plus/components/input'
import { ElIcon } from '@element-plus/components/icon'
import {
useFormDisabled,
useFormItem,
useFormSize,
} from '@element-plus/components/form'
import { vRepeatClick } from '@element-plus/directives'
import { useLocale, useNamespace } from '@element-plus/hooks'
import {
debugWarn,
isNumber,
isString,
isUndefined,
throwError,
} from '@element-plus/utils'
import { ArrowDown, ArrowUp, Minus, Plus } from '@element-plus/icons-vue'
import {
CHANGE_EVENT,
INPUT_EVENT,
UPDATE_MODEL_EVENT,
} from '@element-plus/constants'
import { inputNumberEmits, inputNumberProps } from './input-number'
import type { InputInstance } from '@element-plus/components/input'
defineOptions({
name: 'ElInputNumber',
})
const props = defineProps(inputNumberProps)
const emit = defineEmits(inputNumberEmits)
const { t } = useLocale()
const ns = useNamespace('input-number')
const input = ref<InputInstance>()
interface Data {
currentValue: number | null | undefined
userInput: null | number | string
}
const data = reactive<Data>({
currentValue: props.modelValue,
userInput: null,
})
const { formItem } = useFormItem()
const minDisabled = computed(
() => isNumber(props.modelValue) && props.modelValue <= props.min
)
const maxDisabled = computed(
() => isNumber(props.modelValue) && props.modelValue >= props.max
)
const numPrecision = computed(() => {
const stepPrecision = getPrecision(props.step)
if (!isUndefined(props.precision)) {
if (stepPrecision > props.precision) {
debugWarn(
'InputNumber',
'precision should not be less than the decimal places of step'
)
}
return props.precision
} else {
return Math.max(getPrecision(props.modelValue), stepPrecision)
}
})
const controlsAtRight = computed(() => {
return props.controls && props.controlsPosition === 'right'
})
const inputNumberSize = useFormSize()
const inputNumberDisabled = useFormDisabled()
const displayValue = computed(() => {
if (data.userInput !== null) {
return data.userInput
}
let currentValue: number | string | undefined | null = data.currentValue
if (isNil(currentValue)) return ''
if (isNumber(currentValue)) {
if (Number.isNaN(currentValue)) return ''
if (!isUndefined(props.precision)) {
currentValue = currentValue.toFixed(props.precision)
}
}
return currentValue
})
const toPrecision = (num: number, pre?: number) => {
if (isUndefined(pre)) pre = numPrecision.value
if (pre === 0) return Math.round(num)
let snum = String(num)
const pointPos = snum.indexOf('.')
if (pointPos === -1) return num
const nums = snum.replace('.', '').split('')
const datum = nums[pointPos + pre]
if (!datum) return num
const length = snum.length
if (snum.charAt(length - 1) === '5') {
snum = `${snum.slice(0, Math.max(0, length - 1))}6`
}
return Number.parseFloat(Number(snum).toFixed(pre))
}
const getPrecision = (value: number | null | undefined) => {
if (isNil(value)) return 0
const valueString = value.toString()
const dotPosition = valueString.indexOf('.')
let precision = 0
if (dotPosition !== -1) {
precision = valueString.length - dotPosition - 1
}
return precision
}
const ensurePrecision = (val: number, coefficient: 1 | -1 = 1) => {
if (!isNumber(val)) return data.currentValue
// Solve the accuracy problem of JS decimal calculation by converting the value to integer.
return toPrecision(val + props.step * coefficient)
}
const increase = () => {
if (props.readonly || inputNumberDisabled.value || maxDisabled.value) return
const value = Number(displayValue.value) || 0
const newVal = ensurePrecision(value)
setCurrentValue(newVal)
emit(INPUT_EVENT, data.currentValue)
setCurrentValueToModelValue()
}
const decrease = () => {
if (props.readonly || inputNumberDisabled.value || minDisabled.value) return
const value = Number(displayValue.value) || 0
const newVal = ensurePrecision(value, -1)
setCurrentValue(newVal)
emit(INPUT_EVENT, data.currentValue)
setCurrentValueToModelValue()
}
const verifyValue = (
value: number | string | null | undefined,
update?: boolean
): number | null | undefined => {
const { max, min, step, precision, stepStrictly, valueOnClear } = props
if (max < min) {
throwError('InputNumber', 'min should not be greater than max.')
}
let newVal = Number(value)
if (isNil(value) || Number.isNaN(newVal)) {
return null
}
if (value === '') {
if (valueOnClear === null) {
return null
}
newVal = isString(valueOnClear) ? { min, max }[valueOnClear] : valueOnClear
}
if (stepStrictly) {
newVal = toPrecision(Math.round(newVal / step) * step, precision)
}
if (!isUndefined(precision)) {
newVal = toPrecision(newVal, precision)
}
if (newVal > max || newVal < min) {
newVal = newVal > max ? max : min
update && emit(UPDATE_MODEL_EVENT, newVal)
}
return newVal
}
const setCurrentValue = (
value: number | string | null | undefined,
emitChange = true
) => {
const oldVal = data.currentValue
const newVal = verifyValue(value)
if (!emitChange) {
emit(UPDATE_MODEL_EVENT, newVal!)
return
}
if (oldVal === newVal && value) return
data.userInput = null
emit(UPDATE_MODEL_EVENT, newVal!)
if (oldVal !== newVal) {
emit(CHANGE_EVENT, newVal!, oldVal!)
}
if (props.validateEvent) {
formItem?.validate?.('change').catch((err) => debugWarn(err))
}
data.currentValue = newVal
}
const handleInput = (value: string) => {
data.userInput = value
const newVal = value === '' ? null : Number(value)
emit(INPUT_EVENT, newVal)
setCurrentValue(newVal, false)
}
const handleInputChange = (value: string) => {
const newVal = value !== '' ? Number(value) : ''
if ((isNumber(newVal) && !Number.isNaN(newVal)) || value === '') {
setCurrentValue(newVal)
}
setCurrentValueToModelValue()
data.userInput = null
}
const focus = () => {
input.value?.focus?.()
}
const blur = () => {
input.value?.blur?.()
}
const handleFocus = (event: MouseEvent | FocusEvent) => {
emit('focus', event)
}
const handleBlur = (event: MouseEvent | FocusEvent) => {
data.userInput = null
emit('blur', event)
if (props.validateEvent) {
formItem?.validate?.('blur').catch((err) => debugWarn(err))
}
}
const setCurrentValueToModelValue = () => {
if (data.currentValue !== props.modelValue) {
data.currentValue = props.modelValue
}
}
const handleWheel = (e: MouseEvent) => {
if (document.activeElement === e.target) e.preventDefault()
}
watch(
() => props.modelValue,
(value, oldValue) => {
const newValue = verifyValue(value, true)
if (data.userInput === null && newValue !== oldValue) {
data.currentValue = newValue
}
},
{ immediate: true }
)
onMounted(() => {
const { min, max, modelValue } = props
const innerInput = input.value?.input as HTMLInputElement
innerInput.setAttribute('role', 'spinbutton')
if (Number.isFinite(max)) {
innerInput.setAttribute('aria-valuemax', String(max))
} else {
innerInput.removeAttribute('aria-valuemax')
}
if (Number.isFinite(min)) {
innerInput.setAttribute('aria-valuemin', String(min))
} else {
innerInput.removeAttribute('aria-valuemin')
}
innerInput.setAttribute(
'aria-valuenow',
data.currentValue || data.currentValue === 0
? String(data.currentValue)
: ''
)
innerInput.setAttribute('aria-disabled', String(inputNumberDisabled.value))
if (!isNumber(modelValue) && modelValue != null) {
let val: number | null = Number(modelValue)
if (Number.isNaN(val)) {
val = null
}
emit(UPDATE_MODEL_EVENT, val!)
}
})
onUpdated(() => {
const innerInput = input.value?.input
innerInput?.setAttribute('aria-valuenow', `${data.currentValue ?? ''}`)
})
defineExpose({
/** @description get focus the input component */
focus,
/** @description remove focus the input component */
blur,
})
</script>