/
KtFieldNumber.vue
402 lines (360 loc) · 9.38 KB
/
KtFieldNumber.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
<template>
<KtField
v-bind="{ field }"
:getEmptyValue="() => null"
:helpTextSlot="$slots.helpText"
>
<div
class="kt-field-number"
:class="{
'kt-field-number--is-hide-change-buttons': hideChangeButtons,
'kt-field-number--has-maximum': showMaximum && maximum !== null,
}"
>
<div
v-if="!hideChangeButtons"
class="kt-field-number__button"
:class="decrementButtonClasses"
@click="decrementValue"
>
<i class="yoco" v-text="Yoco.Icon.MINUS" />
</div>
<div class="kt-field-number__middle" @click="$refs.input.focus()">
<input
ref="input"
v-bind="inputProps"
@blur="handleBlur"
@input="onInput($event.target.value)"
/>
<div v-if="showMaximum" v-text="'/'" />
<div
v-if="showMaximum"
class="kt-field-number__middle__maximum"
v-text="maximum"
/>
</div>
<div
v-if="!hideChangeButtons"
class="kt-field-number__button"
:class="incrementButtonClasses"
@click="incrementValue"
>
<i class="yoco" v-text="Yoco.Icon.PLUS" />
</div>
</div>
</KtField>
</template>
<script lang="ts">
import { Yoco } from '@3yourmind/yoco'
import { defineComponent, computed, ref, watch } from '@vue/composition-api'
import Big from 'big.js'
import { KtField } from '../kotti-field'
import { KOTTI_FIELD_PROPS } from '../kotti-field/constants'
import { useField, useForceUpdate } from '../kotti-field/hooks'
import {
KOTTI_FIELD_NUMBER_PROPS,
KOTTI_FIELD_NUMBER_SUPPORTS,
LEADING_ZEROES_REGEX,
VALID_REGEX,
} from './constants'
import { KottiFieldNumber } from './types'
import {
isInRange,
isNumber,
isStepMultiple,
toNumber,
toString,
} from './utilities'
export default defineComponent({
name: 'KtFieldNumber',
components: { KtField },
props: {
...KOTTI_FIELD_PROPS,
...KOTTI_FIELD_NUMBER_PROPS,
},
setup(props: KottiFieldNumber.Props, { emit, root }) {
const field = useField<KottiFieldNumber.Value, string | null>({
emit,
isCorrectDataType: (value): value is KottiFieldNumber.Value =>
isNumber(value) || value === null,
isEmpty: (value) => value === null,
props,
supports: KOTTI_FIELD_NUMBER_SUPPORTS,
})
const { forceUpdate, forceUpdateKey } = useForceUpdate()
const isDecrementEnabled = computed(
() =>
!field.isDisabled &&
isInRange({
maximum: props.maximum,
minimum: props.minimum,
value:
field.currentValue === null
? null
: Big(field.currentValue).minus(props.step).toNumber(),
}),
)
const isIncrementEnabled = computed(
() =>
!field.isDisabled &&
isInRange({
maximum: props.maximum,
minimum: props.minimum,
value:
field.currentValue === null
? null
: Big(field.currentValue).add(props.step).toNumber(),
}),
)
const internalStringValue = ref('')
const showMaximum = computed(
() => props.maximum !== null && !props.hideMaximum,
)
watch(
() => field.currentValue,
(newNumber, oldNumber) => {
const newString = toString(newNumber)
const truncatedNumber = toNumber(newString)
if (
!isInRange({
maximum: props.maximum,
minimum: props.minimum,
value: truncatedNumber,
})
)
throw new RangeError(
`KtFieldNumber: encountered an out-of-range number "${newNumber}"`,
)
if (
!isStepMultiple({
minimum: props.minimum,
step: props.step,
value: truncatedNumber,
})
)
throw new Error(
`KtFieldNumber: encountered a value "${newNumber}" that doesn't fit ((minimum + k * step): where k is an integer)`,
)
const shouldUpdate = oldNumber !== truncatedNumber
if (shouldUpdate) internalStringValue.value = newString
},
{ immediate: true },
)
/**
* reference to input element, in order to track cursor position
* prior to feeding the value back to the input, which resets the position to the end.
*/
const input = ref<HTMLInputElement | null>(null)
const lastUserSetCursorPosition = ref<number | null>(null)
const setCursorPosition = (position: number | null) => {
if (position !== null) input.value?.setSelectionRange(position, position)
}
watch(internalStringValue, () => {
// in case the parent component accepts the @input event’s change, we need to restore the cursor position
setCursorPosition(lastUserSetCursorPosition.value)
lastUserSetCursorPosition.value = null
})
/**
* In the scenario when the user clicks the +/- buttons when the value is null
* we check if zero is in the range of accepted values, and fallback to it
*/
const canFallbackToZero = computed<boolean>(
() =>
isStepMultiple({
minimum: props.minimum,
step: props.step,
value: 0,
}) &&
isInRange({
maximum: props.maximum,
minimum: props.minimum,
value: 0,
}),
)
return {
decrementButtonClasses: computed(() => ({
'kt-field-number__button--is-disabled': !isDecrementEnabled.value,
})),
decrementValue() {
if (!isDecrementEnabled.value) return
field.setValue(
field.currentValue === null
? canFallbackToZero.value
? 0
: props.minimum ?? props.maximum ?? 0
: Big(field.currentValue).minus(props.step).toNumber(),
)
},
field,
handleBlur() {
internalStringValue.value = toString(field.currentValue)
},
incrementButtonClasses: computed(() => ({
'kt-field-number__button--is-disabled': !isIncrementEnabled.value,
})),
incrementValue() {
if (!isIncrementEnabled.value) return
field.setValue(
field.currentValue === null
? canFallbackToZero.value
? 0
: props.minimum ?? props.maximum ?? 0
: Big(field.currentValue).add(props.step).toNumber(),
)
},
internalStringValue,
input,
inputProps: computed(
(): Partial<HTMLInputElement> & {
class: Record<string, boolean>
forceUpdateKey: number
} => ({
...field.inputProps,
class: {
'kt-field-number__middle__input': true,
'kt-field-number__middle__input--has-maximum': showMaximum.value,
},
disabled: field.isDisabled,
forceUpdateKey: forceUpdateKey.value,
placeholder: props.placeholder ?? undefined,
size: 1,
type: 'text', // NOT A MISTAKE
value: internalStringValue.value,
}),
),
onInput(value: string) {
lastUserSetCursorPosition.value = input.value?.selectionStart ?? null
const { maximum, minimum, step } = props
const valueWithoutLeadingZeroes = value.replace(
LEADING_ZEROES_REGEX,
'$1',
)
const nextNumber = toNumber(valueWithoutLeadingZeroes)
const isTypedNumberValid =
VALID_REGEX.test(valueWithoutLeadingZeroes) &&
isStepMultiple({
minimum,
step,
value: nextNumber,
}) &&
isInRange({
maximum,
minimum,
value: nextNumber,
})
if (isTypedNumberValid) {
const shouldEmit = nextNumber !== field.currentValue
if (shouldEmit) field.setValue(nextNumber)
else internalStringValue.value = valueWithoutLeadingZeroes
}
forceUpdate()
/**
* Calculates new cursor position, which might be 1 character different than the last cursor position
* because we might reject the character the user just entered. Then, we’d need to -1 it to undo that change.
*
* FIXME: This may or may not move the cursor by 1 character if the parent component rejects the update.
* We decided that that’s an okay trade-off for now. If this ever needs to be fixed, it’s likely possible to fix by
* also looking at the shouldEmit to figure-out the new cursor position
*/
const newCursorPosition =
lastUserSetCursorPosition.value === null
? null
: lastUserSetCursorPosition.value - (isTypedNumberValid ? 0 : 1)
root.$nextTick(() => {
setCursorPosition(newCursorPosition)
})
},
showMaximum,
Yoco,
}
},
})
</script>
<style lang="scss">
@use 'sass:map';
@import '../kotti-field/mixins';
.kt-field__wrapper {
$sizes: (
'small': 1.3rem,
'medium': 1.6rem,
'large': 2rem,
);
&--disabled {
.kt-field-number {
&__button,
&__middle {
color: var(--text-05);
background-color: var(--ui-01);
}
}
}
@each $type in 'small', 'medium', 'large' {
&--is-#{$type} {
/* stylelint-disable */
.kt-field-number__button {
height: map.get($sizes, $type);
width: map.get($sizes, $type);
}
.kt-field-number__middle {
height: map.get($sizes, $type);
}
/* stylelint-enable */
}
}
}
.kt-field-number {
display: flex;
align-items: center;
font-variant-numeric: tabular-nums;
&--is-hide-change-buttons:not(&--has-maximum) {
.kt-field-number__middle__input {
text-align: left;
}
}
&__button {
display: flex;
align-items: center;
justify-content: center;
color: var(--icon-02);
cursor: pointer;
user-select: none;
background: var(--ui-01);
border-radius: var(--field-border-radius);
&:not(&--is-disabled):hover {
background: var(--ui-02);
}
&--is-disabled {
color: var(--text-05);
}
}
&__middle {
display: flex;
flex: 1;
align-items: center;
&__input,
&__maximum {
display: flex;
flex: 1;
align-items: center;
min-width: 0px;
padding: 0;
}
&__input {
width: 100%;
text-align: center;
border: none;
&::-webkit-outer-spin-button,
&::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
}
&--has-maximum {
text-align: right;
}
&--is-disabled {
color: var(--text-05);
}
}
}
}
</style>