From ec784ccb369137766a831bbe2e283a736f83f19c Mon Sep 17 00:00:00 2001 From: Jack Short Date: Tue, 26 Sep 2023 12:33:15 -0500 Subject: [PATCH] chore: updating input currency panel to handle comma separator (#7336) --- src/components/NumericalInput/index.tsx | 19 ++++++++++++++++++- src/utils/formatNumbers.ts | 2 +- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/components/NumericalInput/index.tsx b/src/components/NumericalInput/index.tsx index 119a1d73d0..f619dd496f 100644 --- a/src/components/NumericalInput/index.tsx +++ b/src/components/NumericalInput/index.tsx @@ -1,6 +1,8 @@ +import { SupportedLocale } from 'constants/locales' import React, { forwardRef } from 'react' import styled from 'styled-components' import { escapeRegExp } from 'utils' +import { useFormatterLocales } from 'utils/formatNumbers' const StyledInput = styled.input<{ error?: boolean; fontSize?: string; align?: string; disabled?: boolean }>` color: ${({ error, theme }) => (error ? theme.critical : theme.neutral1)}; @@ -39,6 +41,12 @@ const StyledInput = styled.input<{ error?: boolean; fontSize?: string; align?: s } ` +function localeUsesComma(locale: SupportedLocale): boolean { + const decimalSeparator = new Intl.NumberFormat(locale).format(1.1)[1] + + return decimalSeparator === ',' +} + const inputRegex = RegExp(`^\\d*(?:\\\\[.])?\\d*$`) // match escaped "." characters via in a non-capturing group interface InputProps extends Omit, 'ref' | 'onChange' | 'as'> { @@ -52,17 +60,26 @@ interface InputProps extends Omit, 'ref' | 'on const Input = forwardRef( ({ value, onUserInput, placeholder, prependSymbol, ...rest }: InputProps, ref) => { + const { formatterLocale } = useFormatterLocales() + const enforcer = (nextUserInput: string) => { if (nextUserInput === '' || inputRegex.test(escapeRegExp(nextUserInput))) { onUserInput(nextUserInput) } } + const formatValueWithLocale = (value: string | number) => { + const [searchValue, replaceValue] = localeUsesComma(formatterLocale) ? [/\./g, ','] : [/,/g, '.'] + return value.toString().replace(searchValue, replaceValue) + } + + const valueFormattedWithLocale = formatValueWithLocale(value) + return ( { if (prependSymbol) { const value = event.target.value diff --git a/src/utils/formatNumbers.ts b/src/utils/formatNumbers.ts index f2a48c515c..50eea7d381 100644 --- a/src/utils/formatNumbers.ts +++ b/src/utils/formatNumbers.ts @@ -579,7 +579,7 @@ function formatReviewSwapCurrencyAmount( return formattedAmount } -function useFormatterLocales(): { +export function useFormatterLocales(): { formatterLocale: SupportedLocale formatterLocalCurrency: SupportedLocalCurrency } {