2
0
Files
bot/apps/builder/components/shared/SmartNumberInput.tsx

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-12-23 13:49:24 +01:00
import {
NumberInputProps,
NumberInput,
NumberInputField,
NumberInputStepper,
NumberIncrementStepper,
NumberDecrementStepper,
} from '@chakra-ui/react'
2022-03-09 15:12:00 +01:00
import { useEffect, useState } from 'react'
import { useDebouncedCallback } from 'use-debounce'
import { isEmpty } from 'utils'
2021-12-23 13:49:24 +01:00
export const SmartNumberInput = ({
value,
2021-12-23 13:49:24 +01:00
onValueChange,
debounceTimeout = 1000,
2021-12-23 13:49:24 +01:00
...props
}: {
value?: number
debounceTimeout?: number
2022-01-08 07:40:55 +01:00
onValueChange: (value?: number) => void
2021-12-23 13:49:24 +01:00
} & NumberInputProps) => {
const [currentValue, setCurrentValue] = useState(value?.toString() ?? '')
const debounced = useDebouncedCallback(
onValueChange,
isEmpty(process.env.NEXT_PUBLIC_E2E_TEST) ? debounceTimeout : 0
2022-03-09 15:12:00 +01:00
)
useEffect(
() => () => {
debounced.flush()
},
2022-03-09 15:12:00 +01:00
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
2021-12-23 13:49:24 +01:00
const handleValueChange = (value: string) => {
setCurrentValue(value)
2021-12-23 13:49:24 +01:00
if (value.endsWith('.') || value.endsWith(',')) return
if (value === '') return debounced(undefined)
2021-12-23 13:49:24 +01:00
const newValue = parseFloat(value)
if (isNaN(newValue)) return
debounced(newValue)
}
2021-12-23 13:49:24 +01:00
return (
<NumberInput onChange={handleValueChange} value={currentValue} {...props}>
2022-05-24 14:25:15 -07:00
<NumberInputField placeholder={props.placeholder} />
2021-12-23 13:49:24 +01:00
<NumberInputStepper>
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
)
}