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 8 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
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.45');
expect(inputElement.value).toBe('123.45');
Sharqiewicz marked this conversation as resolved.
Show resolved Hide resolved
});

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
});
});
68 changes: 68 additions & 0 deletions src/components/Form/From/NumericInput/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
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;
}

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,
}: 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"
{...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
14 changes: 10 additions & 4 deletions src/components/Form/From/variants/StandardFrom.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
import { FromProps } from '..';
import { InputField } from '../InputField';
import { NumericInput } from '../NumericInput';
import { AssetSelector } from '../../../Selector';
import { AssetSelectorOnChange } from '../../../Selector/AssetSelector/helpers';
import { FromDescription } from '../Description';
import { AvailableActions } from '../AvailableActions';

export const StandardFrom = ({
className,
formControl: { max, register, readOnly, error, setValue },
formControl: { max, register, readOnly, error, setValue, maxDecimals, disabled },
asset: { assetSuffix, assets, selectedAsset, setSelectedAsset },
description: { customText, network },
}: FromProps) => (
<>
<div
className={`rounded-lg bg-base-300 px-4 py-3 ${className || ''} ${
className={`rounded-lg ${disabled ? 'bg-base-100' : 'bg-base-300'} px-4 py-3 ${className || ''} ${
error ? 'border border-solid border-red-400' : ''
}`}
>
<div className="w-full flex justify-between">
<InputField register={register} readOnly={readOnly} />
<NumericInput
additionalStyle={disabled ? 'text-gray-400 focus:text-gray-400' : ''}
maxDecimals={maxDecimals}
register={register}
readOnly={readOnly}
/>
{assets && setSelectedAsset && (
<AssetSelector
disabled={disabled}
selectedAsset={selectedAsset}
assets={assets}
onChange={setSelectedAsset as AssetSelectorOnChange}
Expand Down
9 changes: 5 additions & 4 deletions src/components/Form/From/variants/SwapFrom.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { FromProps } from '..';
import { Badges } from '../Badges';
import { FromDescription } from '../Description';
import { InputField } from '../InputField';
import { NumericInput } from '../NumericInput';
import { AssetSelector } from '../../../Selector';
import { AssetSelectorOnChange } from '../../../Selector/AssetSelector/helpers';

export const SwapFrom = ({
className,
formControl: { register, readOnly = false, error, disabled = false },
formControl: { register, readOnly = false, error, disabled = false, maxDecimals },
asset: { assetSuffix, assets, selectedAsset, setSelectedAsset },
description: { customText, network },
badges: { minBadge, maxBadge },
Expand Down Expand Up @@ -37,10 +37,11 @@ export const SwapFrom = ({
</div>
</div>

<InputField
<NumericInput
additionalStyle={disabled ? 'text-gray-400 focus:text-gray-400' : ''}
maxDecimals={maxDecimals}
register={register}
readOnly={readOnly}
additionalStyle={disabled ? 'text-gray-400 focus:text-gray-400' : ''}
/>

{error ? (
Expand Down
3 changes: 1 addition & 2 deletions src/helpers/yup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export const transformNumber = (value: any, originalValue: any) => {
export const transformNumber = (value: unknown, originalValue: unknown) => {
if (!originalValue) return 0;
if (typeof originalValue === 'string' && originalValue !== '') value = Number(originalValue) ?? 0;
return value;
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/spacewalk/useIssuePallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useMemo } from 'preact/hooks';
import { useNodeInfoState } from '../../NodeInfoProvider';
import { Compact, u128 } from '@polkadot/types-codec';
import Big from 'big.js';
import { isU128 } from '../../shared/parseNumbers/isU128';
import { isU128Compatible } from '../../shared/parseNumbers/isU128Compatible';

export interface RichIssueRequest {
id: H256;
Expand Down Expand Up @@ -51,7 +51,7 @@ export function useIssuePallet() {

const u128Amount = Big(amount)

if(!isU128(u128Amount)) return;
if(!isU128Compatible(u128Amount)) return;

const compactAmount: Compact<u128> = api.createType('Compact<u128>', u128Amount.toString());

Expand Down
15 changes: 10 additions & 5 deletions src/pages/bridge/Issue/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useEffect, useCallback, useMemo, useState } from 'preact/compat';
import { yupResolver } from '@hookform/resolvers/yup';
import { Signer } from '@polkadot/types/types';
import Big from 'big.js';
import { isEmpty } from 'lodash';
import { useCallback, useMemo, useState } from 'preact/hooks';
import { Button } from 'react-daisyui';
import { FieldErrors, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router';
Expand All @@ -25,8 +26,8 @@ import { prioritizeXLMAsset } from '../helpers';
import { ConfirmationDialog } from './ConfirmationDialog';
import Disclaimer from './Disclaimer';
import { getIssueValidationSchema } from './IssueValidationSchema';
import { Signer } from '@polkadot/types/types';
import { isU128 } from '../../../shared/parseNumbers/isU128';
import { isU128Compatible } from '../../../shared/parseNumbers/isU128Compatible';
import { USER_INPUT_MAX_DECIMALS } from '../../../shared/parseNumbers/decimal';

interface IssueProps {
network: string;
Expand Down Expand Up @@ -152,6 +153,7 @@ function Issue(props: IssueProps): JSX.Element {
// We only expect one event but loop over all of them just in case
for (const requestIssueEvent of requestIssueEvents) {
// We do not have a proper type for this event, so we have to cast it to any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const issueId = (requestIssueEvent.data as any).issueId;

getIssueRequest(issueId).then((issueRequest) => {
Expand Down Expand Up @@ -201,9 +203,12 @@ function Issue(props: IssueProps): JSX.Element {
<From
{...{
formControl: {
maxDecimals: USER_INPUT_MAX_DECIMALS.STELLAR,
register: register('amount'),
setValue: (n: number) => setValue('amount', n),
error: getFirstErrorMessage(formState, ['amount', 'securityDeposit']) || (!isU128(amountNative) ? 'Invalid value' : ''),
error:
getFirstErrorMessage(formState, ['amount', 'securityDeposit']) ||
(!isU128Compatible(amountNative) ? 'Exceeds the max allowed value.' : ''),
},
asset: {
assets: prioritizeXLMAsset(wrappedAssets),
Expand Down Expand Up @@ -236,7 +241,7 @@ function Issue(props: IssueProps): JSX.Element {
color="primary"
loading={submissionPending}
type="submit"
disabled={!isEmpty(formState.errors) || !isU128(amountNative)}
disabled={!isEmpty(formState.errors) || !isU128Compatible(amountNative) || submissionPending}
>
Bridge
</Button>
Expand Down
2 changes: 2 additions & 0 deletions src/pages/bridge/Redeem/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ConfirmationDialog } from './ConfirmationDialog';
import { getRedeemValidationSchema } from './RedeemValidationSchema';
import { ToastMessage, showToast } from '../../../shared/showToast';
import { prioritizeXLMAsset } from '../helpers';
import { USER_INPUT_MAX_DECIMALS } from '../../../shared/parseNumbers/decimal';

export type RedeemFormValues = {
amount: number;
Expand Down Expand Up @@ -146,6 +147,7 @@ function Redeem(props: RedeemProps): JSX.Element {
register: register('amount'),
setValue: (n: number) => setValue('amount', n),
error: formState.errors.amount?.message,
maxDecimals: USER_INPUT_MAX_DECIMALS.STELLAR,
},
asset: {
assets: prioritizeXLMAsset(wrappedAssets),
Expand Down
Loading
Loading