Skip to content

Commit

Permalink
Fix the InputNumber behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
thesan committed Apr 8, 2024
1 parent 18ea9c5 commit 0af834b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
19 changes: 13 additions & 6 deletions packages/ui/src/common/components/forms/InputNumber.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useFormContext, Controller } from 'react-hook-form'
import NumberFormat, { NumberFormatValues, SourceInfo } from 'react-number-format'
import styled from 'styled-components'

import { asBN, powerOf10, whenDefined } from '@/common/utils'
import { asBN, divToNum, whenDefined } from '@/common/utils'

import { Input, InputProps } from './InputComponent'

Expand Down Expand Up @@ -55,7 +55,7 @@ export const InputNumber = React.memo(({ name, isInBN = false, ...props }: Numbe
return <BasedInputNumber {...props} />
}

const exp = props.decimalScale ?? 0
const exp = 10 ** (props.decimalScale ?? 0)

return (
<Controller
Expand All @@ -65,11 +65,18 @@ export const InputNumber = React.memo(({ name, isInBN = false, ...props }: Numbe
<BasedInputNumber
{...props}
value={whenDefined(field.value, (value) => {
const num = isInBN ? asBN(value).toNumber() : value // TODO convert to number safely
return String(num / 10 ** exp)
if (value === undefined || value === null) {
return ''
}
const numValue = isInBN ? divToNum(asBN(value), exp) : value / exp
return numValue.toFixed(props.decimalScale ?? 0)
})}
onChange={(_, numValue) => {
const value = isInBN ? new BN(numValue).mul(powerOf10(exp)) : numValue * 10 ** exp
onChange={(event, numValue) => {
if (!event) return
if (event.target.value === '') {
return field.onChange(null)
}
const value = isInBN ? new BN(numValue).muln(exp) : numValue * exp
return field.onChange(value)
}}
onBlur={field.onBlur}
Expand Down
5 changes: 5 additions & 0 deletions packages/ui/src/common/utils/bn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ export const sumBN = (a: BN | undefined, b: BN | undefined): BN => new BN(a ?? 0
export const powerOf10 = (value: any) => BN_TEN.pow(asBN(value))

export const powerOf2 = (value: any) => BN_TWO.pow(asBN(value))

export const divToNum = (dividend: BN, divisor: number): number => {
const div = dividend.divmod(new BN(divisor))
return div.div.toNumber() + div.mod.toNumber() / divisor
}

0 comments on commit 0af834b

Please sign in to comment.