Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
bjlaa committed Sep 3, 2024
2 parents f1d7dec + 726819a commit 1b1fe43
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/components/form/question/NumberInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Trans from '@/components/translation/Trans'
import { HTMLAttributes } from 'react'
import { DebounceInput } from 'react-debounce-input'
import { NumericFormat } from 'react-number-format'
import { debounce } from '@/utils/debounce'
import { HTMLAttributes, useState } from 'react'
import { NumberFormatValues, NumericFormat } from 'react-number-format'
import { twMerge } from 'tailwind-merge'

type Props = {
Expand All @@ -15,11 +15,6 @@ type Props = {
defaultValue?: string | number | null | undefined
}

function unformatNumber(number: string) {
// Supprimer les séparateurs de milliers
return Number(number.replace(/[^0-9.-]+/g, ''))
}

export default function NumberInput({
unit,
value = '',
Expand All @@ -29,27 +24,28 @@ export default function NumberInput({
id,
...props
}: HTMLAttributes<HTMLInputElement> & Props) {
const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const inputValue = event.target.value
const [localValue, setLocalValue] = useState(value)

const handleValueChange = debounce((values: NumberFormatValues) => {
setLocalValue(values.value)

if (inputValue === '') {
if (values.value === '') {
setValue(undefined)
} else {
setValue(unformatNumber(inputValue))
setValue(Number(values.value))
}
}
}, 300)

return (
<div
className={twMerge(`flex items-center justify-start gap-1`, className)}>
<NumericFormat
value={isMissing ? '' : value}
value={isMissing ? '' : localValue}
placeholder={isMissing ? '0' : ''}
className={`focus:ring-primary max-w-[8rem] rounded-xl border-2 border-primary-200 bg-white p-2 text-right transition-colors focus:border-primary-700 focus:ring-2 md:max-w-full`}
customInput={DebounceInput}
thousandSeparator={' '}
allowNegative={false}
onChange={handleValueChange}
onValueChange={handleValueChange}
id={id}
{...props}
/>
Expand Down
11 changes: 11 additions & 0 deletions src/utils/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function debounce<T extends (...args: any[]) => void>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: NodeJS.Timeout

return (...args: Parameters<T>) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => func(...args), delay)
}
}

0 comments on commit 1b1fe43

Please sign in to comment.