-
-
Notifications
You must be signed in to change notification settings - Fork 7k
/
VNumberInput.tsx
366 lines (317 loc) Β· 10.8 KB
/
VNumberInput.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Styles
import './VNumberInput.sass'
// Components
import { VBtn } from '../../components/VBtn'
import { VDefaultsProvider } from '../../components/VDefaultsProvider'
import { VDivider } from '../../components/VDivider'
import { makeVTextFieldProps, VTextField } from '@/components/VTextField/VTextField'
// Composables
import { useForm } from '@/composables/form'
import { forwardRefs } from '@/composables/forwardRefs'
import { useProxiedModel } from '@/composables/proxiedModel'
// Utilities
import { computed, nextTick, onMounted, ref } from 'vue'
import { clamp, genericComponent, getDecimals, omit, propsFactory, useRender } from '@/util'
// Types
import type { PropType } from 'vue'
import type { VTextFieldSlots } from '@/components/VTextField/VTextField'
type ControlSlot = {
click: (e: MouseEvent) => void
}
type VNumberInputSlots = Omit<VTextFieldSlots, 'default'> & {
increment: ControlSlot
decrement: ControlSlot
}
type ControlVariant = 'default' | 'stacked' | 'split'
const makeVNumberInputProps = propsFactory({
controlVariant: {
type: String as PropType<ControlVariant>,
default: 'default',
},
inset: Boolean,
hideInput: Boolean,
modelValue: {
type: Number as PropType<Number | null>,
default: null,
},
min: {
type: Number,
default: Number.MIN_SAFE_INTEGER,
},
max: {
type: Number,
default: Number.MAX_SAFE_INTEGER,
},
step: {
type: Number,
default: 1,
},
...omit(makeVTextFieldProps({}), ['appendInnerIcon', 'modelValue', 'prependInnerIcon']),
}, 'VNumberInput')
export const VNumberInput = genericComponent<VNumberInputSlots>()({
name: 'VNumberInput',
props: {
...makeVNumberInputProps(),
},
emits: {
'update:modelValue': (val: number) => true,
},
setup (props, { slots }) {
const _model = useProxiedModel(props, 'modelValue')
const model = computed({
get: () => _model.value,
// model.value could be empty string from VTextField
// but _model.value should be eventually kept in type Number | null
set (val: Number | null | string) {
if (val === null || val === '') {
_model.value = null
return
}
const value = Number(val)
if (!isNaN(value) && value <= props.max && value >= props.min) {
_model.value = value
}
},
})
const vTextFieldRef = ref<VTextField | undefined>()
const stepDecimals = computed(() => getDecimals(props.step))
const modelDecimals = computed(() => typeof model.value === 'number' ? getDecimals(model.value) : 0)
const form = useForm(props)
const controlsDisabled = computed(() => (
form.isDisabled.value || form.isReadonly.value
))
const canIncrease = computed(() => {
if (controlsDisabled.value) return false
return (model.value ?? 0) as number + props.step <= props.max
})
const canDecrease = computed(() => {
if (controlsDisabled.value) return false
return (model.value ?? 0) as number - props.step >= props.min
})
const controlVariant = computed(() => {
return props.hideInput ? 'stacked' : props.controlVariant
})
const incrementIcon = computed(() => controlVariant.value === 'split' ? '$plus' : '$collapse')
const decrementIcon = computed(() => controlVariant.value === 'split' ? '$minus' : '$expand')
const controlNodeSize = computed(() => controlVariant.value === 'split' ? 'default' : 'small')
const controlNodeDefaultHeight = computed(() => controlVariant.value === 'stacked' ? 'auto' : '100%')
const incrementSlotProps = computed(() => ({ click: onClickUp }))
const decrementSlotProps = computed(() => ({ click: onClickDown }))
onMounted(() => {
if (!controlsDisabled.value) {
clampModel()
}
})
function toggleUpDown (increment = true) {
if (controlsDisabled.value) return
if (model.value == null) {
model.value = clamp(0, props.min, props.max)
return
}
const decimals = Math.max(modelDecimals.value, stepDecimals.value)
if (increment) {
if (canIncrease.value) model.value = +((((model.value as number) + props.step).toFixed(decimals)))
} else {
if (canDecrease.value) model.value = +((((model.value as number) - props.step).toFixed(decimals)))
}
}
function onClickUp (e: MouseEvent) {
e.stopPropagation()
toggleUpDown()
}
function onClickDown (e: MouseEvent) {
e.stopPropagation()
toggleUpDown(false)
}
function onBeforeinput (e: InputEvent) {
if (!e.data) return
const existingTxt = (e.target as HTMLInputElement)?.value
const selectionStart = (e.target as HTMLInputElement)?.selectionStart
const selectionEnd = (e.target as HTMLInputElement)?.selectionEnd
const potentialNewInputVal =
existingTxt
? existingTxt.slice(0, selectionStart as number | undefined) + e.data + existingTxt.slice(selectionEnd as number | undefined)
: e.data
// Only numbers, "-", "." are allowed
// AND "-", "." are allowed only once
// AND "-" is only allowed at the start
if (!/^-?(\d+(\.\d*)?|(\.\d+)|\d*|\.)$/.test(potentialNewInputVal)) {
e.preventDefault()
}
}
async function onKeydown (e: KeyboardEvent) {
if (
['Enter', 'ArrowLeft', 'ArrowRight', 'Backspace', 'Delete', 'Tab'].includes(e.key) ||
e.ctrlKey
) return
if (['ArrowDown', 'ArrowUp'].includes(e.key)) {
e.preventDefault()
clampModel()
// _model is controlled, so need to wait until props['modelValue'] is updated
await nextTick()
if (e.key === 'ArrowDown') {
toggleUpDown(false)
} else {
toggleUpDown()
}
}
}
function onControlMousedown (e: MouseEvent) {
e.stopPropagation()
}
function clampModel () {
if (!vTextFieldRef.value) return
const inputText = vTextFieldRef.value.value
if (inputText && !isNaN(+inputText)) {
model.value = clamp(+(inputText), props.min, props.max)
} else {
model.value = null
}
}
useRender(() => {
const { modelValue: _, ...textFieldProps } = VTextField.filterProps(props)
function incrementControlNode () {
return !slots.increment ? (
<VBtn
disabled={ !canIncrease.value }
flat
key="increment-btn"
height={ controlNodeDefaultHeight.value }
data-testid="increment"
aria-hidden="true"
icon={ incrementIcon.value }
onClick={ onClickUp }
onMousedown={ onControlMousedown }
size={ controlNodeSize.value }
tabindex="-1"
/>
) : (
<VDefaultsProvider
key="increment-defaults"
defaults={{
VBtn: {
disabled: !canIncrease.value,
flat: true,
height: controlNodeDefaultHeight.value,
size: controlNodeSize.value,
icon: incrementIcon.value,
},
}}
>
{ slots.increment(incrementSlotProps.value) }
</VDefaultsProvider>
)
}
function decrementControlNode () {
return !slots.decrement ? (
<VBtn
disabled={ !canDecrease.value }
flat
key="decrement-btn"
height={ controlNodeDefaultHeight.value }
data-testid="decrement"
aria-hidden="true"
icon={ decrementIcon.value }
size={ controlNodeSize.value }
tabindex="-1"
onClick={ onClickDown }
onMousedown={ onControlMousedown }
/>
) : (
<VDefaultsProvider
key="decrement-defaults"
defaults={{
VBtn: {
disabled: !canDecrease.value,
flat: true,
height: controlNodeDefaultHeight.value,
size: controlNodeSize.value,
icon: decrementIcon.value,
},
}}
>
{ slots.decrement(decrementSlotProps.value) }
</VDefaultsProvider>
)
}
function controlNode () {
return (
<div class="v-number-input__control">
{ decrementControlNode() }
<VDivider
vertical={ controlVariant.value !== 'stacked' }
/>
{ incrementControlNode() }
</div>
)
}
function dividerNode () {
return !props.hideInput && !props.inset ? <VDivider vertical /> : undefined
}
const appendInnerControl =
controlVariant.value === 'split'
? (
<div class="v-number-input__control">
<VDivider vertical />
{ incrementControlNode() }
</div>
) : (props.reverse
? undefined
: <>{ dividerNode() }{ controlNode() }</>)
const hasAppendInner = slots['append-inner'] || appendInnerControl
const prependInnerControl =
controlVariant.value === 'split'
? (
<div class="v-number-input__control">
{ decrementControlNode() }
<VDivider vertical />
</div>
) : (props.reverse
? <>{ controlNode() }{ dividerNode() }</>
: undefined)
const hasPrependInner = slots['prepend-inner'] || prependInnerControl
return (
<VTextField
ref={ vTextFieldRef }
v-model={ model.value }
onBeforeinput={ onBeforeinput }
onChange={ clampModel }
onKeydown={ onKeydown }
class={[
'v-number-input',
{
'v-number-input--default': controlVariant.value === 'default',
'v-number-input--hide-input': props.hideInput,
'v-number-input--inset': props.inset,
'v-number-input--reverse': props.reverse,
'v-number-input--split': controlVariant.value === 'split',
'v-number-input--stacked': controlVariant.value === 'stacked',
},
props.class,
]}
{ ...textFieldProps }
style={ props.style }
inputmode="decimal"
>
{{
...slots,
'append-inner': hasAppendInner ? (...args) => (
<>
{ slots['append-inner']?.(...args) }
{ appendInnerControl }
</>
) : undefined,
'prepend-inner': hasPrependInner ? (...args) => (
<>
{ prependInnerControl }
{ slots['prepend-inner']?.(...args) }
</>
) : undefined,
}}
</VTextField>
)
})
return forwardRefs({}, vTextFieldRef)
},
})
export type VNumberInput = InstanceType<typeof VNumberInput>