humus-old/client/ui/debug/connection/throughput.js
2019-04-14 17:14:13 -05:00

113 lines
2.4 KiB
JavaScript

// 3rd party.
import classnames from 'classnames';
import React, {useEffect, useState} from 'react';
// 2nd party.
import {compose} from '@avocado/core';
import {Vector} from '@avocado/math';
import contempo from 'contempo';
const decorate = compose(
contempo(`
.throughput {
background-color: rgba(0, 0, 0, .3);
color: white;
line-height: 1em;
width: 9em;
padding: 0.125em;
font-family: monospace;
}
.throughput .kbps:before {
color: rgb(0, 255, 0);
content: 'kb/s ';
}
.throughput .mbps:before {
color: rgb(255, 180, 0);
content: 'mb/s ';
}
.throughput .input:before {
content: '\\a0in: ';
}
.throughput .output:before {
content: 'out: ';
}
.throughput p {
font-size: 0.8em;
margin: 0.25em;
}
`),
);
function formatKbps(bps) {
const kbps = bps / 1000;
return Math.floor(kbps * 100) / 100;
}
function formatMbps(bps) {
const mbps = bps / 1000000;
return Math.floor(mbps * 100) / 100;
}
function format(bps) {
const unit = preferredUnit(bps);
switch (unit) {
case 'kbps':
return formatKbps(bps);
case 'mbps':
return formatMbps(bps);
}
}
function preferredUnit(bps) {
if (bps > 1000000) {
return 'mbps';
}
else {
return 'kbps';
}
}
const ThroughputComponent = ({Parser}) => {
const [throughput, setThroughput] = useState([0, 0]);
const [inUnit, setInUnit] = useState('kbps');
const [outUnit, setOutUnit] = useState('kbps');
useEffect(() => {
const {Decoder, Encoder} = Parser;
const throughputSampleTime = 0.5;
// Throughput ticker.
const throughputHandle = setInterval(() => {
const throughput = Vector.scale([
Decoder.throughput || 0,
Encoder.throughput || 0,
], 8 * (1 / throughputSampleTime));
setThroughput(throughput);
setInUnit(preferredUnit(throughput[0]));
setOutUnit(preferredUnit(throughput[1]));
Decoder.throughput = 0;
Encoder.throughput = 0;
}, throughputSampleTime * 1000);
return () => {
clearInterval(throughputHandle);
};
}, []);
return <div className="throughput unselectable">
<p className={classnames(
'unit',
inUnit,
)}>
<span className="input">
{format(throughput[0])}
</span>
</p>
<p className={classnames(
'unit',
outUnit,
)}>
<span className="output">
{format(throughput[1])}
</span>
</p>
</div>;
}
export default decorate(ThroughputComponent);