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

Numeric format #329

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-imask": "^7.6.1",
"react-number-format": "^5.4.3",
"react-router-dom": "^6.26.0",
"react-toastify": "^11.0.3",
"tailwind-merge": "^2.5.2",
Expand Down
60 changes: 14 additions & 46 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 57 additions & 10 deletions src/components/ui/masked-input.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,77 @@
import * as React from 'react';
import { IMaskMixin } from 'react-imask';
import { Input, InputProps } from './input';
import { NumericFormat, NumericFormatProps } from 'react-number-format';
import { toast } from 'react-toastify';
import { t } from '@lingui/core/macro';

const MaskedInput = IMaskMixin(
({ inputRef, ...props }: { inputRef: React.Ref<HTMLInputElement> }) => (
<Input {...props} ref={inputRef} />
interface MaskedInputProps extends NumericFormatProps<InputProps> {
inputRef?: React.Ref<HTMLInputElement>;
}

const MaskedInput = React.forwardRef<HTMLInputElement, MaskedInputProps>(
({ inputRef, type = 'text', onValueChange, value, ...props }, ref) => (
<NumericFormat
onValueChange={onValueChange}
customInput={Input}
getInputRef={inputRef || ref}
displayType='input'
type={type}
value={value}
onPaste={(e) => {
const pastedText = e.clipboardData.getData('text');
if (!isLocaleNumber(pastedText)) {
e.preventDefault();
toast.error(t`Invalid number ${pastedText}`);
return;
}
}}
{...props}
/>
),
);

function isLocaleNumber(stringNumber: string, locale?: string): boolean {
try {
// Use navigator.language as fallback if locale is not provided
const userLocale = locale || navigator.language;

// Get the decimal separator for this locale
const decimalSeparator = Intl.NumberFormat(userLocale)
.format(1.1)
.replace(/\p{Number}/gu, '');

// convert decimal separator to period
const normalizedNumber = stringNumber.replace(
new RegExp(`\\${decimalSeparator}`),
'.',
);

// Check if it's a valid number and not NaN
const parsedNumber = Number(normalizedNumber);
return !isNaN(parsedNumber) && isFinite(parsedNumber);
} catch (error) {
// Return false if there's any error in the parsing process
return false;
}
}

MaskedInput.displayName = 'MaskedInput';

// Extended Masked Input for XCH inputs
interface XchInputProps extends InputProps {
interface XchInputProps extends MaskedInputProps {
decimals?: number;
}

const TokenAmountInput = React.forwardRef<HTMLInputElement, XchInputProps>(
({ decimals = 12, type = 'text', ...props }, ref) => (
({ decimals = 12, ...props }, ref) => (
<MaskedInput
placeholder='0.00'
{...props}
type={type}
type='text'
inputRef={ref}
mask={Number}
radix='.'
scale={decimals}
decimalScale={decimals}
allowLeadingZeros={false}
allowNegative={false}
/>
),
);
Expand Down
23 changes: 15 additions & 8 deletions src/pages/MakeOffer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,15 +176,17 @@ export function MakeOffer() {
<Trans>Network Fee</Trans>
</Label>
<div className='relative'>
<Input
<TokenAmountInput
id='fee'
type='text'
placeholder={'0.00'}
className='pr-12'
value={state.fee}
onChange={(e) =>
useOfferState.setState({ fee: e.target.value })
}
onValueChange={(values) => {
useOfferState.setState({
fee: values.floatValue?.toString() ?? '',
});
}}
/>
<div className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3'>
<span className='text-gray-500 text-sm' id='price-currency'>
Expand Down Expand Up @@ -449,12 +451,17 @@ function AssetSelector({
<div className='mt-4 flex flex-col space-y-1.5'>
<Label htmlFor={`${prefix}-amount`}>XCH</Label>
<div className='flex'>
<Input
<TokenAmountInput
id={`${prefix}-amount`}
className='rounded-r-none z-10'
placeholder={t`Enter amount`}
value={assets.xch}
onChange={(e) => setAssets({ ...assets, xch: e.target.value })}
onValueChange={(values) => {
setAssets({
...assets,
xch: values.floatValue?.toString() ?? '',
});
}}
/>
<Button
variant='outline'
Expand Down Expand Up @@ -542,8 +549,8 @@ function AssetSelector({
className='border-l-0 z-10 rounded-l-none rounded-r-none w-[100px] h-12'
placeholder={t`Amount`}
value={cat.amount}
onChange={(e) => {
assets.cats[i].amount = e.target.value;
onValueChange={(values) => {
assets.cats[i].amount = values.floatValue?.toString() ?? '';
setAssets({ ...assets });
}}
/>
Expand Down
Loading