/
use-counter.ts
211 lines (185 loc) · 5.1 KB
/
use-counter.ts
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
import { useCallbackRef, useControllableProp } from "@chakra-ui/hooks"
import {
clampValue,
countDecimalPlaces,
maxSafeInteger,
minSafeInteger,
StringOrNumber,
toPrecision,
} from "@chakra-ui/utils"
import { useCallback, useState } from "react"
export interface UseCounterProps {
/**
* The callback fired when the value changes
*/
onChange?(valueAsString: string, valueAsNumber: number): void
/**
* The number of decimal points used to round the value
*/
precision?: number
/**
* The initial value of the counter. Should be less than `max` and greater than `min`
*/
defaultValue?: StringOrNumber
/**
* The value of the counter. Should be less than `max` and greater than `min`
*/
value?: StringOrNumber
/**
* The step used to increment or decrement the value
* @default 1
*/
step?: number
/**
* The minimum value of the counter
* @default Number.MIN_SAFE_INTEGER
*/
min?: number
/**
* The maximum value of the counter
* @default Number.MAX_SAFE_INTEGER
*/
max?: number
/**
* This controls the value update behavior in general.
*
* - If `true` and you use the stepper or up/down arrow keys,
* the value will not exceed the `max` or go lower than `min`
*
* - If `false`, the value will be allowed to go out of range.
*
* @default true
*/
keepWithinRange?: boolean
}
export function useCounter(props: UseCounterProps = {}) {
const {
onChange,
precision: precisionProp,
defaultValue,
value: valueProp,
step: stepProp = 1,
min = minSafeInteger,
max = maxSafeInteger,
keepWithinRange = true,
} = props
const onChangeProp = useCallbackRef(onChange)
const [valueState, setValue] = useState<StringOrNumber>(() => {
if (defaultValue == null) return ""
return cast(defaultValue, stepProp, precisionProp) ?? ""
})
/**
* Because the component that consumes this hook can be controlled or uncontrolled
* we'll keep track of that
*/
const [isControlled, value] = useControllableProp(valueProp, valueState)
const decimalPlaces = getDecimalPlaces(parse(value), stepProp)
const precision = precisionProp ?? decimalPlaces
const update = useCallback(
(next: StringOrNumber) => {
if (next === value) return
if (!isControlled) {
setValue(next.toString())
}
onChangeProp?.(next.toString(), parse(next))
},
[onChangeProp, isControlled, value],
)
// Function to clamp the value and round it to the precision
const clamp = useCallback(
(value: number) => {
let nextValue = value
if (keepWithinRange) {
nextValue = clampValue(nextValue, min, max)
}
return toPrecision(nextValue, precision)
},
[precision, keepWithinRange, max, min],
)
const increment = useCallback(
(step = stepProp) => {
let next: StringOrNumber
/**
* Let's follow the native browser behavior for
* scenarios where the input starts empty ("")
*/
if (value === "") {
/**
* If `min` is set, native input, starts at the `min`.
* Else, it starts at `step`
*/
next = parse(step)
} else {
next = parse(value) + step
}
next = clamp(next as number)
update(next)
},
[clamp, stepProp, update, value],
)
const decrement = useCallback(
(step = stepProp) => {
let next: StringOrNumber
// Same thing here. We'll follow native implementation
if (value === "") {
next = parse(-step)
} else {
next = parse(value) - step
}
next = clamp(next as number)
update(next)
},
[clamp, stepProp, update, value],
)
const reset = useCallback(() => {
let next: StringOrNumber
if (defaultValue == null) {
next = ""
} else {
next = cast(defaultValue, stepProp, precisionProp) ?? min
}
update(next)
}, [defaultValue, precisionProp, stepProp, update, min])
const castValue = useCallback(
(value: StringOrNumber) => {
const nextValue = cast(value, stepProp, precision) ?? min
update(nextValue)
},
[precision, stepProp, update, min],
)
const valueAsNumber = parse(value)
/**
* Common range checks
*/
const isOutOfRange = valueAsNumber > max || valueAsNumber < min
const isAtMax = valueAsNumber === max
const isAtMin = valueAsNumber === min
return {
isOutOfRange,
isAtMax,
isAtMin,
precision,
value,
valueAsNumber,
update,
reset,
increment,
decrement,
clamp,
cast: castValue,
setValue,
}
}
export type UseCounterReturn = ReturnType<typeof useCounter>
function parse(value: StringOrNumber) {
return parseFloat(value.toString().replace(/[^\w.-]+/g, ""))
}
function getDecimalPlaces(value: number, step: number) {
return Math.max(countDecimalPlaces(step), countDecimalPlaces(value))
}
function cast(value: StringOrNumber, step: number, precision?: number) {
const parsedValue = parse(value)
if (Number.isNaN(parsedValue)) return undefined
const decimalPlaces = getDecimalPlaces(parsedValue, step)
return toPrecision(parsedValue, precision ?? decimalPlaces)
}