Elapsed formatting (#4216)

This commit is contained in:
Jaco Greeff 2020-12-15 12:17:18 +01:00 committed by GitHub
parent 96a00eaba9
commit abcc9ca206
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,6 +3,7 @@
import BN from 'bn.js';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { bnToBn } from '@polkadot/util';
@ -30,25 +31,39 @@ function tick (): void {
setTimeout(tick, TICK_TIMEOUT);
}
function getDisplayValue (now = 0, value: BN | Date | number = 0): string {
function formatValue (value: number, type = 's', withDecimal = false): React.ReactNode {
const [pre, post] = value.toFixed(1).split('.');
const before = pre.split('').map((d, index) => (
<div
className='digit'
key={index}
>{d}</div>
));
return withDecimal
? <>{before}.<div className='digit'>{post}</div> {type}</>
: <>{before} s</>;
}
function getDisplayValue (now = 0, value: BN | Date | number = 0): React.ReactNode {
const tsValue = (
value && (value as Date).getTime
? (value as Date).getTime()
: bnToBn(value as number).toNumber()
) || 0;
let display = '0.0 s';
let display = formatValue(0, 's', true);
if (now && tsValue) {
const elapsed = Math.max(Math.abs(now - tsValue), 0) / 1000;
if (elapsed < 15) {
display = `${elapsed.toFixed(1)} s`;
display = formatValue(elapsed, 's', true);
} else if (elapsed < 60) {
display = `${elapsed | 0} s`;
display = formatValue(elapsed);
} else if (elapsed < 3600) {
display = `${elapsed / 60 | 0} min`;
display = formatValue(elapsed, 'min');
} else {
display = `${elapsed / 3600 | 0} hr`;
display = formatValue(elapsed / 3600, 'hr');
}
}
@ -77,4 +92,9 @@ function Elapsed ({ children, className = '', value }: Props): React.ReactElemen
);
}
export default React.memo(Elapsed);
export default React.memo(styled(Elapsed)`
.digit {
display: inline-block;
width: 1ch;
}
`);