Skip to content
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
27 changes: 24 additions & 3 deletions ui/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -684,14 +684,23 @@ button .loading-value {
opacity: 1;
}

.currency-value-wrap {
display: inline-block;
position: relative;
max-width: 100%;
min-width: 0;
vertical-align: bottom;
}

.currency-value {
display: inline-flex;
align-items: center;
gap: 0.35rem;
display: inline-block;
max-width: 100%;
min-width: 0;
overflow: hidden;
font: inherit;
color: inherit;
text-overflow: ellipsis;
vertical-align: bottom;
white-space: nowrap;
}

Expand Down Expand Up @@ -728,6 +737,18 @@ button.currency-value.copyable:hover:not(:disabled) {
color: var(--danger);
}

.currency-value-measure {
position: absolute;
top: 0;
left: 0;
max-width: none;
overflow: visible;
text-overflow: clip;
visibility: hidden;
white-space: nowrap;
pointer-events: none;
}

.timestamp-value {
font: inherit;
color: inherit;
Expand Down
27 changes: 24 additions & 3 deletions ui/dist/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -684,14 +684,23 @@ button .loading-value {
opacity: 1;
}

.currency-value-wrap {
display: inline-block;
position: relative;
max-width: 100%;
min-width: 0;
vertical-align: bottom;
}

.currency-value {
display: inline-flex;
align-items: center;
gap: 0.35rem;
display: inline-block;
max-width: 100%;
min-width: 0;
overflow: hidden;
font: inherit;
color: inherit;
text-overflow: ellipsis;
vertical-align: bottom;
white-space: nowrap;
}

Expand Down Expand Up @@ -728,6 +737,18 @@ button.currency-value.copyable:hover:not(:disabled) {
color: var(--danger);
}

.currency-value-measure {
position: absolute;
top: 0;
left: 0;
max-width: none;
overflow: visible;
text-overflow: clip;
visibility: hidden;
white-space: nowrap;
pointer-events: none;
}

.timestamp-value {
font: inherit;
color: inherit;
Expand Down
75 changes: 62 additions & 13 deletions ui/ts/components/CurrencyValue.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useEffect } from 'preact/hooks'
import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks'
import { LoadingText } from './LoadingText.js'
import { useCopyToClipboard } from '../hooks/useCopyToClipboard.js'
import { formatCurrencyBalance, formatRoundedCurrencyBalance } from '../lib/formatters.js'
import { formatCompactCurrencyBalance, formatCurrencyBalance, formatRoundedCurrencyBalance } from '../lib/formatters.js'
import { getMetricPlaceholderPresentation } from '../lib/userCopy.js'

type CurrencyValueProps = {
className?: string
compactWhenOverflow?: boolean
decimals?: number
loading?: boolean
copyable?: boolean
Expand All @@ -14,40 +15,88 @@ type CurrencyValueProps = {
value: bigint | undefined
}

export function CurrencyValue({ className = '', copyable = true, decimals = 2, loading = false, suffix = '', units = 18, value }: CurrencyValueProps) {
export function CurrencyValue({ className = '', compactWhenOverflow = false, copyable = true, decimals = 2, loading = false, suffix = '', units = 18, value }: CurrencyValueProps) {
const { copied, copyText } = useCopyToClipboard()
const buttonRef = useRef<HTMLButtonElement>(null)
const spanRef = useRef<HTMLSpanElement>(null)
const measureRef = useRef<HTMLSpanElement>(null)
const [shouldCompact, setShouldCompact] = useState(false)
const copiedValue = copied.value
const exactValue = value === undefined ? undefined : formatCurrencyBalance(value, units)
const exactSuffix = suffix === '' ? '' : ` ${suffix}`

useEffect(() => {
copied.value = false
}, [exactValue])

const displayValue = value === undefined ? undefined : `≈ ${formatRoundedCurrencyBalance(value, units, decimals)}${exactSuffix}`
const compactDisplayValue = value === undefined ? undefined : `≈ ${formatCompactCurrencyBalance(value, units)}${exactSuffix}`

useLayoutEffect(() => {
if (!compactWhenOverflow || value === undefined || displayValue === undefined) {
setShouldCompact(false)
return
}

const element = buttonRef.current ?? spanRef.current
const measureElement = measureRef.current
if (element === null || measureElement === null) {
setShouldCompact(false)
return
}

const updateCompaction = () => {
if (copied.value) return
measureElement.textContent = displayValue
const shouldUseCompactValue = measureElement.getBoundingClientRect().width > element.clientWidth + 1
measureElement.textContent = ''
setShouldCompact(shouldUseCompactValue)
}

updateCompaction()

if (typeof ResizeObserver === 'undefined') return

const observer = new ResizeObserver(() => {
updateCompaction()
})
observer.observe(element)

return () => {
observer.disconnect()
}
}, [compactWhenOverflow, copiedValue, displayValue, value])

if (loading) {
return <LoadingText className={`currency-value loading ${className}`}>Loading...</LoadingText>
}

if (value === undefined) {
if (value === undefined || exactValue === undefined || displayValue === undefined || compactDisplayValue === undefined) {
return <span className={`currency-value unavailable ${className}`}>{getMetricPlaceholderPresentation(value)?.placeholder}</span>
}

const resolvedExactValue = exactValue ?? formatCurrencyBalance(value, units)
const roundedValue = formatRoundedCurrencyBalance(value, units, decimals)
const displayValue = `≈ ${roundedValue}${exactSuffix}`
const exactTitle = `${resolvedExactValue}${exactSuffix}`
const resolvedDisplayValue = compactWhenOverflow && shouldCompact && !copiedValue ? compactDisplayValue : displayValue
const exactTitle = `${exactValue}${exactSuffix}`
const valueClassName = `currency-value${copyable ? ' copyable' : ''} ${className}`
const measureClassName = `currency-value currency-value-measure ${className}`

if (!copyable) {
return (
<span className={valueClassName} title={exactTitle}>
{displayValue}
<span className='currency-value-wrap'>
<span ref={spanRef} className={valueClassName} title={exactTitle}>
{resolvedDisplayValue}
</span>
<span ref={measureRef} aria-hidden='true' className={measureClassName} />
</span>
)
}

return (
<button type='button' className={valueClassName} title={exactTitle} aria-label={`Copy exact value ${resolvedExactValue}`} onClick={() => copyText(resolvedExactValue)}>
{copied.value ? 'Copied' : displayValue}
</button>
<span className='currency-value-wrap'>
<button ref={buttonRef} type='button' className={valueClassName} title={exactTitle} aria-label={`Copy exact value ${exactValue}`} onClick={() => copyText(exactValue)}>
{copiedValue ? 'Copied' : resolvedDisplayValue}
</button>
<span ref={measureRef} aria-hidden='true' className={measureClassName} />
</span>
)
}
6 changes: 3 additions & 3 deletions ui/ts/components/OverviewPanels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ export function OverviewPanels({
{showAccountBalances ? (
<>
<MetricField label='ETH'>
<CurrencyValue value={accountState.ethBalance} loading={isRefreshing && accountState.ethBalance === undefined} suffix='ETH' />
<CurrencyValue value={accountState.ethBalance} loading={isRefreshing && accountState.ethBalance === undefined} suffix='ETH' compactWhenOverflow />
</MetricField>
<MetricField label='WETH'>
<CurrencyValue value={accountState.wethBalance} loading={isRefreshing && accountState.wethBalance === undefined} suffix='WETH' />
<CurrencyValue value={accountState.wethBalance} loading={isRefreshing && accountState.wethBalance === undefined} suffix='WETH' compactWhenOverflow />
</MetricField>
<MetricField label='REP'>
<CurrencyValue value={universeRepBalance} loading={isLoadingUniverseRepBalance} suffix='REP' />
<CurrencyValue value={universeRepBalance} loading={isLoadingUniverseRepBalance} suffix='REP' compactWhenOverflow />
</MetricField>
</>
) : undefined}
Expand Down
65 changes: 65 additions & 0 deletions ui/ts/lib/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const MILLISECONDS_PER_SECOND = 1000
const SECONDS_PER_MINUTE = 60n
const SECONDS_PER_HOUR = 60n * SECONDS_PER_MINUTE
const SECONDS_PER_DAY = 24n * SECONDS_PER_HOUR
const SI_SUFFIXES = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] as const

function formatGroupedInteger(value: bigint) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
Expand All @@ -27,6 +28,41 @@ function assertNonNegativeInteger(value: number, label: string) {
if (value < 0) throw new RangeError(`${label} must be non-negative`)
}

function formatTrimmedDecimal(integerPart: bigint, fractionalPart: bigint, decimals: number) {
if (decimals === 0 || fractionalPart === 0n) return integerPart.toString()

return `${integerPart}.${fractionalPart.toString().padStart(decimals, '0').replace(/0+$/, '')}`
}

function formatRoundedScaledValue(value: bigint, divisor: bigint, decimals: number) {
const scale = 10n ** BigInt(decimals)
const rounded = (value * scale + divisor / 2n) / divisor
const integerPart = rounded / scale
const fractionalPart = rounded % scale

return {
integerPart,
text: formatTrimmedDecimal(integerPart, fractionalPart, decimals),
}
}

function formatScientificCurrencyBalance(value: bigint, units: number, decimals: number) {
const isNegative = value < 0n
const absoluteValue = isNegative ? -value : value
const unitBase = 10n ** BigInt(units)
const wholeUnits = absoluteValue / unitBase
let exponent = wholeUnits.toString().length - 1

while (true) {
const divisor = 10n ** BigInt(exponent) * unitBase
const rounded = formatRoundedScaledValue(absoluteValue, divisor, decimals)
if (rounded.integerPart < 10n) {
return `${isNegative ? '-' : ''}${rounded.text}E${exponent}`
}
exponent += 1
}
}

function formatTimestampPart(value: number) {
return value.toString().padStart(2, '0')
}
Expand Down Expand Up @@ -76,6 +112,35 @@ export function formatRoundedCurrencyBalance(value: bigint | undefined, units: n
return `${prefix}${formatGroupedInteger(integerPart)}.${fractionalPart.toString().padStart(effectiveDecimals, '0')}`
}

export function formatCompactCurrencyBalance(value: bigint | undefined, units: number = 18, decimals: number = 1) {
if (value === undefined) return '—'
assertNonNegativeInteger(units, 'Units')
assertInteger(decimals, 'Decimals')
if (decimals < 0) return formatCurrencyBalance(value, units)

const isNegative = value < 0n
const absoluteValue = isNegative ? -value : value
const unitBase = 10n ** BigInt(units)

if (absoluteValue < 1000n * unitBase) {
return formatRoundedCurrencyBalance(value, units, decimals)
}

const wholeUnits = absoluteValue / unitBase
let suffixIndex = Math.floor((wholeUnits.toString().length - 1) / 3) - 1

while (suffixIndex < SI_SUFFIXES.length) {
const divisor = 1000n ** BigInt(suffixIndex + 1) * unitBase
const rounded = formatRoundedScaledValue(absoluteValue, divisor, decimals)
if (rounded.integerPart < 1000n) {
return `${isNegative ? '-' : ''}${rounded.text}${SI_SUFFIXES[suffixIndex]}`
}
suffixIndex += 1
}

return formatScientificCurrencyBalance(value, units, decimals)
}

export function formatTimestamp(timestamp: bigint) {
if (timestamp === 0n) return 'Immediate'
return formatUtcTimestamp(timestamp)
Expand Down
Loading
Loading