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

improvement: subscript decimals #2219

Merged
merged 39 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
3f208c4
improvement: subscript decimals
namgold Sep 5, 2023
d59a47c
add comments
namgold Sep 6, 2023
24d7ba6
use formatDisplayNumber
namgold Sep 6, 2023
4ff550b
use more formatDisplayNumber
namgold Sep 6, 2023
ae60c63
use more formatDisplayNumber
namgold Sep 6, 2023
12a8b8b
format for native balance
namgold Sep 6, 2023
2000ebe
use more formatDisplayNumber
namgold Sep 6, 2023
66d340f
prod env
namgold Sep 7, 2023
ab49e02
increase precision
namgold Sep 7, 2023
9d5ed5f
fix number
namgold Sep 7, 2023
788cd75
parse Price
namgold Sep 7, 2023
0539909
fix
namgold Sep 7, 2023
de88da8
trim 0 last
namgold Sep 7, 2023
20aceca
Merge branch 'main' into improvement/subscript-decimal
namgold Sep 8, 2023
7afb7eb
fallback on negative
namgold Sep 8, 2023
9432138
increase precision
namgold Sep 8, 2023
b51b9f4
increase precision
namgold Sep 8, 2023
b8dc75d
apply to classic page
namgold Sep 8, 2023
14dc622
Merge branch 'main' into improvement/subscript-decimal
namgold Sep 8, 2023
01e795b
rm log
namgold Sep 8, 2023
79ebcbb
Merge branch 'main' into improvement/subscript-decimal
namgold Sep 8, 2023
c1c56cd
cleaning code
namgold Sep 8, 2023
b4466b8
fix apr
namgold Sep 8, 2023
46a4ec5
apply add liquidity page
namgold Sep 8, 2023
4c78d06
increase decimal
namgold Sep 11, 2023
af8c8e6
fix decimal
namgold Sep 11, 2023
1518d5a
tooltip
namgold Sep 11, 2023
bc09362
redundant %
namgold Sep 11, 2023
c82a7d6
nowrap
namgold Sep 11, 2023
63fcb53
add example
namgold Sep 11, 2023
40d3264
Merge branch 'main' into improvement/subscript-decimal
namgold Sep 11, 2023
912d59d
rm log
namgold Sep 11, 2023
7a1394a
add unittest
namgold Sep 12, 2023
404455a
revert env
namgold Sep 12, 2023
7a687b1
fix testcase
namgold Sep 12, 2023
8592f09
rm async
namgold Sep 12, 2023
3978b09
add edgecase
namgold Sep 12, 2023
a8437da
add fraction testcases
namgold Sep 12, 2023
883300a
rm testcases
namgold Sep 13, 2023
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 .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ jobs:
VITE_TAG: ${{ needs.prepare.outputs.image_tag }}
CURRENT_BRANCH: ${{ needs.prepare.outputs.current_branch }}
NODE_OPTIONS: '--max_old_space_size=4096'
run: yarn build-adpr
run: yarn build-prod
namgold marked this conversation as resolved.
Show resolved Hide resolved

- name: Docker build and push
uses: docker/build-push-action@v2
Expand Down
33 changes: 5 additions & 28 deletions src/components/EarningAreaChart/TooltipContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,7 @@ import styled from 'styled-components'
import Logo, { NetworkLogo } from 'components/Logo'
import useTheme from 'hooks/useTheme'
import { EarningStatsTick } from 'types/myEarnings'
import { formattedNum } from 'utils'

const formatUSDValue = (v: number) => {
if (v === 0) {
return '$0'
}

if (v < 0.0001) {
return '< $0.0001'
}

const formatter = Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
notation: 'compact',
maximumSignificantDigits: 4,
})

return formatter.format(v)
}
import { formatDisplayNumber } from 'utils/numbers'

const TokensWrapper = styled.div`
display: flex;
Expand All @@ -37,10 +18,6 @@ const TokensWrapper = styled.div`
font-weight: 500;
`

const formatTokenAmount = (a: number | string) => {
return formattedNum(String(a), false)
}

type TokensProps = {
tokens: EarningStatsTick['tokens']
}
Expand Down Expand Up @@ -102,7 +79,7 @@ const Tokens: React.FC<TokensProps> = ({ tokens }) => {
lineHeight: '14px',
}}
>
{formatTokenAmount(token.amount)}
{formatDisplayNumber({ value: token.amount })}
</Text>
</Flex>
)
Expand Down Expand Up @@ -176,7 +153,7 @@ const TooltipContent: React.FC<Props> = ({ dataEntry, setHoverValue }) => {
whiteSpace: 'nowrap',
}}
>
<Trans>My Total Earnings</Trans>: {formatUSDValue(dataEntry.totalValue)}
<Trans>My Total Earnings</Trans>: {formatDisplayNumber({ value: dataEntry.totalValue, style: 'currency' })}
</Text>

<Text
Expand All @@ -189,7 +166,7 @@ const TooltipContent: React.FC<Props> = ({ dataEntry, setHoverValue }) => {
whiteSpace: 'nowrap',
}}
>
<Trans>Pool Fees</Trans>: {formatUSDValue(dataEntry.poolFeesValue)}
<Trans>Pool Fees</Trans>: {formatDisplayNumber({ value: dataEntry.poolFeesValue, style: 'currency' })}
</Text>

<Text
Expand All @@ -202,7 +179,7 @@ const TooltipContent: React.FC<Props> = ({ dataEntry, setHoverValue }) => {
whiteSpace: 'nowrap',
}}
>
<Trans>Farm Rewards</Trans>: {formatUSDValue(dataEntry.farmRewardsValue)}
<Trans>Farm Rewards</Trans>: {formatDisplayNumber({ value: dataEntry.farmRewardsValue, style: 'currency' })}
</Text>

<Flex
Expand Down
49 changes: 5 additions & 44 deletions src/components/EarningAreaChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import useTheme from 'hooks/useTheme'
import { TimePeriod } from 'pages/MyEarnings/MyEarningsOverTimePanel/TimePeriodSelect'
import KyberLogo from 'pages/TrueSightV2/components/chart/KyberLogo'
import { EarningStatsTick } from 'types/myEarnings'
import { toFixed } from 'utils/numbers'
import { formatDisplayNumber } from 'utils/numbers'

import TooltipContent from './TooltipContent'
import { formatUSDValue } from './utils'

const labelGapByTimePeriod: Record<TimePeriod, number> = {
['7D']: isMobile ? 2 : 1,
Expand All @@ -36,53 +35,13 @@ const CustomizedLabel = (props: any) => {
fill={theme.subText}
textAnchor="middle"
>
{formatUSDValue(value)}
{formatDisplayNumber({ value, style: 'currency', fractionDigits: 3 })}
</text>
)}
</>
)
}

const subscriptMap: { [key: string]: string } = {
'0': '₀',
'1': '₁',
'2': '₂',
'3': '₃',
'4': '₄',
'5': '₅',
'6': '₆',
'7': '₇',
'8': '₈',
'9': '₉',
}

const formatter = (value: string) => {
const num = parseFloat(value)
const numberOfZero = -Math.floor(Math.log10(num) + 1)

if (num > 0 && num < 1 && numberOfZero > 2) {
const temp = Number(toFixed(num).split('.')[1]).toString()

return `$0.0${numberOfZero
.toString()
.split('')
.map(item => subscriptMap[item])
.join('')}${temp.substring(0, 2)}`
}

const formatter = Intl.NumberFormat('en-US', {
notation: num >= 1000 ? 'compact' : 'standard',
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0,
maximumFractionDigits: 2,
minimumSignificantDigits: 1,
maximumSignificantDigits: 2,
})

return formatter.format(num)
}

type Props = {
period: TimePeriod
setHoverValue?: React.Dispatch<React.SetStateAction<number | null>>
Expand Down Expand Up @@ -123,7 +82,9 @@ const EarningAreaChart: React.FC<Props> = ({ data, setHoverValue = EMPTY_FUNCTIO
axisLine={false}
tickLine={false}
stroke={theme.subText}
tickFormatter={(value: any, _index: number) => formatter(String(value))}
tickFormatter={(value: any, _index: number) =>
formatDisplayNumber({ value, style: 'currency', fractionDigits: 2 })
}
width={54}
/>
<Customized component={KyberLogo} />
Expand Down
19 changes: 0 additions & 19 deletions src/components/EarningAreaChart/utils.ts

This file was deleted.

39 changes: 3 additions & 36 deletions src/components/EarningPieChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,7 @@ import Logo, { NetworkLogo } from 'components/Logo'
import { EMPTY_ARRAY } from 'constants/index'
import useTheme from 'hooks/useTheme'
import { Loading } from 'pages/ProAmmPool/ContentLoader'

const formatUSDValue = (v: string) => {
const num = Number(v)

if (num === 0) {
return '$0'
}

if (num < 0.01) {
return '< $0.01'
}

const formatter = Intl.NumberFormat('en-US', {
notation: 'compact',
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0,
maximumFractionDigits: num < 0.1 ? 2 : 1,
})

return formatter.format(num)
}

const formatPercent = (num: number) => {
if (num < 0.01) {
return '< 0.01%'
}

const formatter = Intl.NumberFormat('en-US', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
})

return formatter.format(num) + '%'
}
import { formatDisplayNumber } from 'utils/numbers'

const LegendsWrapper = styled.div`
display: flex;
Expand Down Expand Up @@ -179,7 +145,8 @@ const Legend: React.FC<LegendProps> = ({
whiteSpace: 'nowrap',
}}
>
{formatUSDValue(value)} ({formatPercent(percent)})
{formatDisplayNumber({ value, style: 'currency', fractionDigits: 2 })} (
{formatDisplayNumber({ value: percent / 100, style: 'percent', fractionDigits: 3 })})
</Text>
</Flex>
</Flex>
Expand Down
10 changes: 3 additions & 7 deletions src/components/Header/web3/SelectNetwork.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ApplicationModal } from 'state/application/actions'
import { useModalOpen, useNetworkModalToggle } from 'state/application/hooks'
import { useIsDarkMode } from 'state/user/hooks'
import { useNativeBalance } from 'state/wallet/hooks'
import { formatDisplayNumber } from 'utils/numbers'

const NetworkSwitchContainer = styled.div`
display: flex;
Expand Down Expand Up @@ -74,13 +75,8 @@ function SelectNetwork(): JSX.Element | null {
const userEthBalance = useNativeBalance()
const labelContent = useMemo(() => {
if (!userEthBalance) return networkInfo.name
const balanceFixedStr = userEthBalance.lessThan(1000 * 10 ** NativeCurrencies[chainId].decimals) // less than 1000
? userEthBalance.lessThan(10 ** NativeCurrencies[chainId].decimals) // less than 1
? parseFloat(userEthBalance.toSignificant(6)).toFixed(6)
: parseFloat(userEthBalance.toExact()).toFixed(4)
: parseFloat(userEthBalance.toExact()).toFixed(2)
const balanceFixed = Number(balanceFixedStr)
return `${balanceFixed} ${NativeCurrencies[chainId].symbol}`
const balanceFixedStr = formatDisplayNumber({ value: userEthBalance, significantDigits: 6 })
return `${balanceFixedStr} ${NativeCurrencies[chainId].symbol}`
}, [userEthBalance, chainId, networkInfo])
const walletSupportsChain = useWalletSupportedChains()
const disableSelectNetwork = walletSupportsChain.length <= 1
Expand Down
5 changes: 3 additions & 2 deletions src/components/ProAmm/ProAmmPriceRangeConfirm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ import useTheme from 'hooks/useTheme'
import { Bound } from 'state/mint/proamm/type'
import { useUserSlippageTolerance } from 'state/user/hooks'
import { ExternalLink, TYPE } from 'theme'
import { toSignificantOrMaxIntegerPart } from 'utils/formatCurrencyAmount'
import { formatTickPrice } from 'utils/formatTickPrice'
import { formatDisplayNumber } from 'utils/numbers'
import { checkWarningSlippage, formatSlippage } from 'utils/slippage'
import { unwrappedToken } from 'utils/wrappedCurrency'

Expand Down Expand Up @@ -80,7 +80,8 @@ export default function ProAmmPriceRangeConfirm({
</Text>
<RowFixed>
<Text fontSize={'12px'} fontWeight="500" style={{ textAlign: 'right' }}>
1 {baseCurrency.symbol} = {toSignificantOrMaxIntegerPart(price, 6)} {quoteCurrency.symbol}
1 {baseCurrency.symbol} = {formatDisplayNumber({ value: price, significantDigits: 6 })}{' '}
{quoteCurrency.symbol}
</Text>
<span onClick={handleRateChange} style={{ marginLeft: '2px', cursor: 'pointer' }}>
<RotateSwapIcon rotated={baseCurrency !== currency0} size={16} />
Expand Down
17 changes: 6 additions & 11 deletions src/components/SwapForm/TradeSummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ExternalLink, TYPE } from 'theme'
import { DetailedRouteSummary } from 'types/route'
import { formattedNum } from 'utils'
import { minimumAmountAfterSlippage } from 'utils/currencyAmount'
import { formatDisplayNumber } from 'utils/numbers'
import { checkPriceImpact, formatPriceImpact } from 'utils/prices'

const IconWrapper = styled.div<{ $flip: boolean }>`
Expand Down Expand Up @@ -64,22 +65,16 @@ const Wrapper = styled.div.attrs<WrapperProps>(props => ({
}
`

const formatPercent = (v: number) => {
const formatter = Intl.NumberFormat('en-US', {
minimumFractionDigits: 0,
maximumFractionDigits: 2,
style: 'percent',
})

return formatter.format(v)
}

type TooltipTextOfSwapFeeProps = {
feeBips: string | undefined
feeAmountText: string
}
export const TooltipTextOfSwapFee: React.FC<TooltipTextOfSwapFeeProps> = ({ feeBips, feeAmountText }) => {
const feePercent = formatPercent(Number(feeBips) / Number(BIPS_BASE.toString()))
const feePercent = formatDisplayNumber({
value: Number(feeBips) / Number(BIPS_BASE.toString()),
style: 'percent',
fractionDigits: 2,
})
const hereLink = (
<ExternalLink href="https://docs.kyberswap.com/kyberswap-solutions/kyberswap-interface/user-guides/instantly-swap-at-superior-rates#swap-fees-supporting-transactions-on-low-trading-volume-chains">
<b>
Expand Down
15 changes: 9 additions & 6 deletions src/components/YieldPools/FarmingPoolAPRCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useElasticFarms } from 'state/farms/elastic/hooks'
import { useTokenPrices } from 'state/tokenPrices/hooks'
import { MEDIA_WIDTHS } from 'theme'
import { useFarmApr } from 'utils/dmm'
import { formatDisplayNumber } from 'utils/numbers'

export const APRTooltipContent = ({
poolAPR,
Expand Down Expand Up @@ -43,7 +44,7 @@ export const APRTooltipContent = ({
<Text as="span" fontSize={'14px'}>
Total APR:{' '}
<Text as="span" color={theme.text} fontWeight={500}>
{(poolAPR + maxFarmAPR).toFixed(2)}%
{formatDisplayNumber({ value: (poolAPR + maxFarmAPR) / 100, style: 'percent', fractionDigits: 2 })}
</Text>
</Text>
<Box
Expand All @@ -65,7 +66,7 @@ export const APRTooltipContent = ({
<Text as="span">
Pool APR:{' '}
<Text as="span" color={theme.text} fontWeight={500}>
{poolAPR.toFixed(2)}%
{formatDisplayNumber({ value: poolAPR / 100, style: 'percent', fractionDigits: 2 })}
</Text>
</Text>
<Text
Expand All @@ -90,7 +91,7 @@ export const APRTooltipContent = ({
<Text as="span" color={theme.warning}>
Farm APR:{' '}
<Text as="span" fontWeight={500}>
{farmAPR.toFixed(2)}%
{formatDisplayNumber({ value: farmAPR / 100, style: 'percent', fractionDigits: 2 })}
</Text>
</Text>
<Text
Expand All @@ -116,7 +117,7 @@ export const APRTooltipContent = ({
<Text as="span" color={theme.warning}>
Farm APR:{' '}
<Text as="span" fontWeight={500}>
{farmV2APR.toFixed(2)}%
{formatDisplayNumber({ value: farmV2APR / 100, style: 'percent', fractionDigits: 2 })}
</Text>
</Text>
<Text
Expand Down Expand Up @@ -191,7 +192,7 @@ const FarmingPoolAPRCell: React.FC<Props> = ({
text={<APRTooltipContent farmAPR={farmAPR} farmV2APR={farmV2APR} poolAPR={poolAPR} />}
>
<Text as="span" marginRight="4px">
{(poolAPR + maxFarmAPR).toFixed(2)}%
{formatDisplayNumber({ value: (poolAPR + maxFarmAPR) / 100, style: 'percent', fractionDigits: 2 })}%
</Text>
<Info size={14} />
</MouseoverTooltip>
Expand All @@ -217,7 +218,9 @@ export const ClassicFarmingPoolAPRCell = ({ poolAPR, farm }: { poolAPR: number;
gap: '4px',
}}
>
<Text as="span">{(poolAPR + farmAPR).toFixed(2)}%</Text>
<Text as="span">
{formatDisplayNumber({ value: (poolAPR + farmAPR) / 100, style: 'percent', fractionDigits: 2 })}%
</Text>
<MouseoverTooltip width="fit-content" text={<APRTooltipContent farmAPR={farmAPR} poolAPR={poolAPR} />}>
<MoneyBag size={16} color={theme.apr} />
</MouseoverTooltip>
Expand Down
3 changes: 2 additions & 1 deletion src/components/swapv2/TradePrice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { CSSProperties } from 'styled-components'

import useTheme from 'hooks/useTheme'
import { useCurrencyConvertedToNative } from 'utils/dmm'
import { formatDisplayNumber } from 'utils/numbers'

import { Dots, StyledBalanceMaxMini } from './styleds'

Expand All @@ -23,7 +24,7 @@ export default function TradePrice({ price, label, icon, style = {}, color }: Tr
const [showInverted, setShowInverted] = useState<boolean>(false)
let formattedPrice
try {
formattedPrice = showInverted ? price?.invert()?.toSignificant(6) : price?.toSignificant(6)
formattedPrice = formatDisplayNumber({ value: showInverted ? price?.invert() : price, significantDigits: 7 })
} catch (error) {}

const show = Boolean(price?.baseCurrency && price?.quoteCurrency && formattedPrice)
Expand Down
Loading
Loading