ghost-portal/packages/page-staking/src/Query/ChartPoints.tsx
Jaco Greeff a0b82d88a4
Use import type { ... } (#4052)
* Use import type { ... }

* value imports

* TypeDefInfo

* Apply suggestions from code review

* fixes... am going blind.
2020-11-19 16:20:14 +01:00

75 lines
1.9 KiB
TypeScript

// Copyright 2017-2020 @polkadot/app-staking authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { DeriveStakerPoints } from '@polkadot/api-derive/types';
import type { ChartInfo, LineDataEntry, Props } from './types';
import React, { useMemo, useRef } from 'react';
import { Chart, Spinner } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { useTranslation } from '../translate';
const COLORS_POINTS = [undefined, '#acacac'];
function extractPoints (points: DeriveStakerPoints[] = []): ChartInfo {
const labels: string[] = [];
const avgSet: LineDataEntry = [];
const idxSet: LineDataEntry = [];
let avgCount = 0;
let total = 0;
points.forEach(({ era, points }): void => {
total += points.toNumber();
labels.push(era.toHuman());
if (points.gtn(0)) {
avgCount++;
}
avgSet.push((avgCount ? Math.ceil(total * 100 / avgCount) : 0) / 100);
idxSet.push(points);
});
return {
chart: [idxSet, avgSet],
labels
};
}
function ChartPoints ({ validatorId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const params = useMemo(() => [validatorId, false], [validatorId]);
const stakerPoints = useCall<DeriveStakerPoints[]>(api.derive.staking.stakerPoints, params);
const { chart, labels } = useMemo(
() => extractPoints(stakerPoints),
[stakerPoints]
);
const legendsRef = useRef([
t<string>('points'),
t<string>('average')
]);
return (
<div className='staking--Chart'>
<h1>{t<string>('era points')}</h1>
{labels.length
? (
<Chart.Line
colors={COLORS_POINTS}
labels={labels}
legends={legendsRef.current}
values={chart}
/>
)
: <Spinner />
}
</div>
);
}
export default React.memo(ChartPoints);