Skip to content

Commit

Permalink
fix: input glitch on mobile
Browse files Browse the repository at this point in the history
  • Loading branch information
toniocodo committed Sep 28, 2023
1 parent dea5228 commit b58e285
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions libs/shared/components/src/Inputs/BigIntInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { forwardRef, useEffect, useState } from 'react';
import { InputBase } from '@mui/material';
import { Skeleton } from '@mui/material';
import { isNilOrEmpty } from '@origin/shared/utils';
import { usePrevious } from '@react-hookz/web';
import { formatUnits, parseUnits } from 'viem';

import type { InputBaseProps } from '@mui/material';
Expand All @@ -19,6 +20,7 @@ export type BigintInputProps = {
export const BigIntInput = forwardRef<HTMLInputElement, BigintInputProps>(
({ value, decimals = 18, isLoading, isError, onChange, ...rest }, ref) => {
const [strVal, setStrVal] = useState(formatUnits(value, decimals));
const prev = usePrevious(strVal);

useEffect(() => {
if (value === 0n && (isNilOrEmpty(strVal) || strVal === '0.')) {
Expand All @@ -33,22 +35,21 @@ export const BigIntInput = forwardRef<HTMLInputElement, BigintInputProps>(
if (
isNilOrEmpty(strVal) ||
strVal === '0.' ||
value !== parseUnits(strVal, decimals)
value !== parseUnits(prev, decimals)
) {
setStrVal(formatUnits(value, decimals));
}
}, [value, decimals, strVal]);
}, [value, decimals, strVal, prev]);

const handleChange = (evt: ChangeEvent<HTMLInputElement>) => {
if (evt.target.validity.valid) {
setStrVal(evt.target.value === '.' ? '0.' : evt.target.value);
const val =
isNilOrEmpty(evt.target.value) || evt.target.value === '.'
? '0'
: evt.target.value.replace(/\.0+$/, '');

try {
const num = parseUnits(val, decimals);
setStrVal(evt.target.value === '.' ? '0.' : evt.target.value);
if (onChange && num !== value) {
onChange(num);
}
Expand All @@ -60,6 +61,7 @@ export const BigIntInput = forwardRef<HTMLInputElement, BigintInputProps>(
<Skeleton width={100} height={24} />
) : (
<InputBase
type="text"
spellCheck="false"
autoComplete="off"
autoCorrect="off"
Expand Down

0 comments on commit b58e285

Please sign in to comment.