Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI stays no responsive when the amount entered with many decimals #456

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
"@testing-library/jest-dom": "^6.1.6",
"@testing-library/preact": "^3.2.3",
"@testing-library/preact-hooks": "^1.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/big.js": "^6.2.2",
"@types/jest": "^29.5.11",
"@types/lodash": "^4.14.202",
Expand Down
113 changes: 48 additions & 65 deletions src/components/Form/Amount/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Input } from 'react-daisyui';
import { UseFormRegisterReturn } from 'react-hook-form';
import { roundNumber } from '../../../shared/parseNumbers/metric';
import { NumericInput } from '../From/NumericInput';

export interface AmountProps {
className?: string;
Expand Down Expand Up @@ -36,71 +36,54 @@ const Amount = ({
hideMaxButton = false,
readOnly = false,
defaultValue,
}: AmountProps): JSX.Element | null => {
return (
<>
<div
className={`rounded-lg bg-base-300 px-4 py-3 ${className || ''} ${
error ? 'border border-solid border-red-400' : ''
}`}
>
<div className="w-full flex justify-between">
<div className="flex-grow text-4xl text-accent-content font-outfit">
<Input
className="input-ghost w-full text-4xl font-outfit pl-0 focus:outline-none"
type="number"
step="any"
onKeyPress={(e: KeyboardEvent) => {
if (e.code === 'Minus' || e.code === 'KeyE') {
e.preventDefault();
}
}}
placeholder="0.0"
{...register}
value={defaultValue}
readOnly={readOnly}
/>
</div>
<div className="flex">
{hideHalfButton ? (
<></>
) : (
<>
<button
className="text-accent-content underline hover:opacity-70 mx-1 font-semibold"
onClick={() => setValue(roundNumber(Number(max) * 0.5))}
type="button"
>
50%
</button>
</>
)}
{hideMaxButton ? (
<></>
) : (
<>
<button
className="text-accent-content underline hover:opacity-70 mx-1 font-semibold"
onClick={() => setValue(calculateMaxAmount(Number(max), fullMax))}
type="button"
>
MAX
</button>
</>
)}
</div>
}: AmountProps): JSX.Element | null => (
<>
<div
className={`rounded-lg bg-base-300 px-4 py-3 ${className || ''} ${
error ? 'border border-solid border-red-400' : ''
}`}
>
<div className="w-full flex justify-between">
<div className="flex-grow text-4xl text-accent-content font-outfit">
<NumericInput
register={register}
readOnly={readOnly}
additionalStyle="input-ghost w-full text-4xl font-outfit pl-0 focus:outline-none"
defaultValue={defaultValue}
/>
</div>
<div className="flex justify-between items-center dark:text-neutral-400 text-neutral-500">
<div className="text-sm mt-px">Amount</div>
<div className="flex gap-1 text-sm">
{max !== undefined && <span className="mr-1">Available: {max.toFixed(2)}</span>}
</div>
<div className="flex">
{hideHalfButton ? null : (
<button
className="text-accent-content underline hover:opacity-70 mx-1 font-semibold"
onClick={() => setValue(roundNumber(Number(max) * 0.5))}
type="button"
>
50%
</button>
)}
{hideMaxButton ? null : (
<button
className="text-accent-content underline hover:opacity-70 mx-1 font-semibold"
onClick={() => setValue(calculateMaxAmount(Number(max), fullMax))}
type="button"
>
MAX
</button>
)}
</div>
</div>
{error ? (
<label className="label">{error && <span className="label-text text-red-400">{error}</span>}</label>
) : null}
</>
);
};
<div className="flex justify-between items-center dark:text-neutral-400 text-neutral-500">
<div className="text-sm mt-px">Amount</div>
<div className="flex gap-1 text-sm">
{max !== undefined && <span className="mr-1">Available: {max.toFixed(2)}</span>}
</div>
</div>
</div>
{error ? (
<label className="label">{error && <span className="label-text text-red-400">{error}</span>}</label>
) : null}
</>
);

export default Amount;
40 changes: 0 additions & 40 deletions src/components/Form/From/InputField/index.tsx

This file was deleted.

110 changes: 110 additions & 0 deletions src/components/Form/From/NumericInput/NumericInput.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { h } from 'preact';
import { UseFormRegisterReturn } from 'react-hook-form';
import { render } from '@testing-library/preact';
import userEvent from '@testing-library/user-event';
import { NumericInput } from '.';

const mockRegister: UseFormRegisterReturn = {
name: 'testInput',
onChange: jest.fn(),
onBlur: jest.fn(),
ref: jest.fn(),
};

describe('NumericInput Component', () => {
it('should render the component', () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0');
expect(inputElement).toBeInTheDocument();
});

it('should allow numeric input', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '1234567890');
expect(inputElement.value).toBe('1234567890');
});

it('should prevent non-numeric input', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, 'qwertyuiopasdfghjklzxcvbnm');
expect(inputElement.value).toBe('');
});

it('should prevent multiple decimal points', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '1.1.1,2.3,4');
expect(inputElement.value).toBe('1.11234');
});

it('should replace comma with period', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '1,1');
expect(inputElement.value).toBe('1.1');
});

it('should work with readOnly prop', () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} readOnly={true} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

expect(inputElement).toHaveAttribute('readOnly');
});

it('should apply additional styles', () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} additionalStyle="extra-style" />);
const inputElement = getByPlaceholderText('0.0');

expect(inputElement).toHaveClass('extra-style');
});

it('should handle leading zeros correctly', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '007');
expect(inputElement.value).toBe('007');
});

it('should allow backspace and delete', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '123');
await userEvent.type(inputElement, '{backspace}');
expect(inputElement.value).toBe('12');

await userEvent.type(inputElement, '{delete}');
expect(inputElement.value).toBe('12');
});

it('should not allow negative numbers', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '-123');
expect(inputElement.value).toBe('123');
});

it('should not allow more decimals than maxDecimals', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} maxDecimals={2} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '123.45479187249871298774985');
expect(inputElement.value).toBe('123.45');
});

it('should not allow more decimals than default maxDecimals', async () => {
const { getByPlaceholderText } = render(<NumericInput register={mockRegister} />);
const inputElement = getByPlaceholderText('0.0') as HTMLInputElement;

await userEvent.type(inputElement, '123.4567890123456789abcgdehyu0123456.2746472.93.2.7.3.5.3');
expect(inputElement.value).toBe('123.456789012343');
Sharqiewicz marked this conversation as resolved.
Show resolved Hide resolved
});
});
71 changes: 71 additions & 0 deletions src/components/Form/From/NumericInput/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Input } from 'react-daisyui';
import { UseFormRegisterReturn } from 'react-hook-form';
import { USER_INPUT_MAX_DECIMALS, exceedsMaxDecimals } from '../../../../shared/parseNumbers/decimal';

interface NumericInputProps {
register: UseFormRegisterReturn;
readOnly?: boolean;
additionalStyle?: string;
maxDecimals?: number;
defaultValue?: string;
}

function isValidNumericInput(value: string): boolean {
return /^[0-9.,]*$/.test(value);
}

function alreadyHasDecimal(e: KeyboardEvent) {
const decimalChars = ['.', ','];

// In the onInput event, "," is replaced by ".", so we check if the e.target.value already contains a "."
return decimalChars.some((char) => e.key === char && e.target && (e.target as HTMLInputElement).value.includes('.'));
}

function handleOnInput(e: KeyboardEvent): void {
const target = e.target as HTMLInputElement;
target.value = target.value.replace(/,/g, '.');
}

function handleOnKeyPress(e: KeyboardEvent, maxDecimals: number): void {
if (!isValidNumericInput(e.key) || alreadyHasDecimal(e)) {
e.preventDefault();
}
const target = e.target as HTMLInputElement;
if (exceedsMaxDecimals(target.value, maxDecimals - 1)) {
target.value = target.value.slice(0, -1);
}
}

export const NumericInput = ({
register,
readOnly = false,
additionalStyle,
maxDecimals = USER_INPUT_MAX_DECIMALS.PENDULUM,
defaultValue,
}: NumericInputProps) => (
<div className="w-full flex justify-between">
<div className="flex-grow text-4xl text-black font-outfit">
<Input
autocomplete="off"
autocorrect="off"
autocapitalize="none"
className={
'input-ghost w-full text-4xl font-outfit pl-0 focus:outline-none focus:text-accent-content text-accent-content ' +
additionalStyle
}
minlength="1"
onKeyPress={(e: KeyboardEvent) => handleOnKeyPress(e, maxDecimals)}
onInput={handleOnInput}
pattern="^[0-9]*[.,]?[0-9]*$"
placeholder="0.0"
readOnly={readOnly}
spellcheck="false"
step="any"
type="text"
inputmode="decimal"
value={defaultValue}
{...register}
/>
</div>
</div>
);
1 change: 1 addition & 0 deletions src/components/Form/From/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface FromProps {
readOnly?: boolean;
disabled?: boolean;
setValue?: (n: number) => void;
maxDecimals?: number;
};
asset: {
assets?: BlockchainAsset[];
Expand Down
Loading
Loading