Added number formatting to charts

This commit is contained in:
Alejandro Celaya 2020-09-15 22:22:56 +02:00
parent fc9341f631
commit 67495fa302
2 changed files with 29 additions and 4 deletions

View file

@ -2,10 +2,11 @@ import React, { ChangeEvent, useRef } from 'react';
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
import { keys, values } from 'ramda';
import classNames from 'classnames';
import Chart, { ChartData, ChartDataSets, ChartOptions } from 'chart.js';
import Chart, { ChartData, ChartDataSets, ChartOptions, ChartTooltipItem } from 'chart.js';
import { fillTheGaps } from '../../utils/helpers/visits';
import { Stats } from '../types';
import './DefaultChart.scss';
import { prettify } from '../../utils/helpers/numbers';
export interface DefaultChartProps {
title: Function | string;
@ -124,7 +125,13 @@ const DefaultChart = (
scales: !isBarChart ? undefined : {
xAxes: [
{
ticks: { beginAtZero: true, precision: 0, max } as any,
ticks: {
beginAtZero: true,
// @ts-expect-error
precision: 0,
callback: prettify,
max,
},
stacked: true,
},
],
@ -132,9 +139,27 @@ const DefaultChart = (
},
tooltips: {
intersect: !isBarChart,
// Do not show tooltip on items with empty label when in a bar chart
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
callbacks: {
...isBarChart ? {} : {
label({ datasetIndex, index }: ChartTooltipItem, { labels, datasets }: ChartData) {
const datasetLabel = index !== undefined && labels?.[index] || '';
const value = datasetIndex !== undefined && index !== undefined
&& datasets?.[datasetIndex]?.data?.[index]
|| '';
return `${datasetLabel}: ${prettify(Number(value))}`;
},
},
...!isBarChart ? {} : {
label({ datasetIndex, xLabel }: ChartTooltipItem, { datasets }: ChartData) {
const datasetLabel = datasetIndex !== undefined && datasets?.[datasetIndex]?.label || '';
return `${datasetLabel}: ${prettify(Number(xLabel))}`;
},
},
},
},
onHover: !isBarChart ? undefined : ((e: ChangeEvent<HTMLElement>, chartElement: HorizontalBar[] | Doughnut[]) => {
const { target } = e;

View file

@ -17,8 +17,8 @@ import { fillTheGaps } from '../../utils/helpers/visits';
import { useToggle } from '../../utils/helpers/hooks';
import { rangeOf } from '../../utils/utils';
import ToggleSwitch from '../../utils/ToggleSwitch';
import './LineChartCard.scss';
import { prettify } from '../../utils/helpers/numbers';
import './LineChartCard.scss';
interface LineChartCardProps {
title: string;