mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2024-12-23 09:30:31 +03:00
Migrated first charts to TS
This commit is contained in:
parent
4083592212
commit
8a146021dd
7 changed files with 102 additions and 89 deletions
9
package-lock.json
generated
9
package-lock.json
generated
|
@ -3047,6 +3047,15 @@
|
|||
"@babel/types": "^7.3.0"
|
||||
}
|
||||
},
|
||||
"@types/chart.js": {
|
||||
"version": "2.9.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/chart.js/-/chart.js-2.9.24.tgz",
|
||||
"integrity": "sha512-AQI7X+ow3SaONl44JrHoL/5B+lCsJyG31UHZ5RP98Uh15hI/zjEkDsAb4EIm4P9TGfNhZLXw/nMc5w0u10+/fQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"moment": "^2.10.2"
|
||||
}
|
||||
},
|
||||
"@types/cheerio": {
|
||||
"version": "0.22.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/cheerio/-/cheerio-0.22.21.tgz",
|
||||
|
|
|
@ -75,6 +75,7 @@
|
|||
"@stryker-mutator/javascript-mutator": "^3.2.4",
|
||||
"@stryker-mutator/jest-runner": "^3.2.4",
|
||||
"@svgr/webpack": "^4.3.3",
|
||||
"@types/chart.js": "^2.8.0",
|
||||
"@types/classnames": "^2.2.10",
|
||||
"@types/enzyme": "^3.10.5",
|
||||
"@types/jest": "^26.0.10",
|
||||
|
|
|
@ -1,22 +1,30 @@
|
|||
import React, { useRef } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
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 { fillTheGaps } from '../../utils/helpers/visits';
|
||||
import { Stats } from '../types';
|
||||
import './DefaultChart.scss';
|
||||
|
||||
const propTypes = {
|
||||
title: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
|
||||
isBarChart: PropTypes.bool,
|
||||
stats: PropTypes.object,
|
||||
max: PropTypes.number,
|
||||
highlightedStats: PropTypes.object,
|
||||
highlightedLabel: PropTypes.string,
|
||||
onClick: PropTypes.func,
|
||||
};
|
||||
export interface DefaultChartProps {
|
||||
title: Function | string;
|
||||
stats: Stats;
|
||||
isBarChart?: boolean;
|
||||
max?: number;
|
||||
highlightedStats?: Stats;
|
||||
highlightedLabel?: string;
|
||||
onClick?: (label: string) => void;
|
||||
}
|
||||
|
||||
const generateGraphData = (title, isBarChart, labels, data, highlightedData, highlightedLabel) => ({
|
||||
const generateGraphData = (
|
||||
title: Function | string,
|
||||
isBarChart: boolean,
|
||||
labels: string[],
|
||||
data: number[],
|
||||
highlightedData?: number[],
|
||||
highlightedLabel?: string,
|
||||
): ChartData => ({
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
|
@ -39,40 +47,40 @@ const generateGraphData = (title, isBarChart, labels, data, highlightedData, hig
|
|||
borderColor: isBarChart ? 'rgba(70, 150, 229, 1)' : 'white',
|
||||
borderWidth: 2,
|
||||
},
|
||||
highlightedData && {
|
||||
(highlightedData && {
|
||||
title,
|
||||
label: highlightedLabel || 'Selected',
|
||||
label: highlightedLabel ?? 'Selected',
|
||||
data: highlightedData,
|
||||
backgroundColor: 'rgba(247, 127, 40, 0.4)',
|
||||
borderColor: '#F77F28',
|
||||
borderWidth: 2,
|
||||
},
|
||||
}) as unknown as ChartDataSets,
|
||||
].filter(Boolean),
|
||||
});
|
||||
|
||||
const dropLabelIfHidden = (label) => label.startsWith('hidden') ? '' : label;
|
||||
const dropLabelIfHidden = (label: string) => label.startsWith('hidden') ? '' : label;
|
||||
|
||||
const determineHeight = (isBarChart, labels) => {
|
||||
const determineHeight = (isBarChart: boolean, labels: string[]): number | undefined => {
|
||||
if (!isBarChart) {
|
||||
return 300;
|
||||
}
|
||||
|
||||
return isBarChart && labels.length > 20 ? labels.length * 8 : null;
|
||||
return isBarChart && labels.length > 20 ? labels.length * 8 : undefined;
|
||||
};
|
||||
|
||||
/* eslint-disable react/prop-types */
|
||||
const renderPieChartLegend = ({ config }) => {
|
||||
const { labels, datasets } = config.data;
|
||||
const { defaultColor } = config.options;
|
||||
const renderPieChartLegend = ({ config }: Chart) => {
|
||||
const { labels = [], datasets = [] } = config.data ?? {};
|
||||
const { defaultColor } = config.options ?? {} as any;
|
||||
const [{ backgroundColor: colors }] = datasets;
|
||||
|
||||
return (
|
||||
<ul className="default-chart__pie-chart-legend">
|
||||
{labels.map((label, index) => (
|
||||
<li key={label} className="default-chart__pie-chart-legend-item d-flex">
|
||||
<li key={label as string} className="default-chart__pie-chart-legend-item d-flex">
|
||||
<div
|
||||
className="default-chart__pie-chart-legend-item-color"
|
||||
style={{ backgroundColor: colors[index] || defaultColor }}
|
||||
style={{ backgroundColor: (colors as string[])[index] || defaultColor }}
|
||||
/>
|
||||
<small className="default-chart__pie-chart-legend-item-text flex-fill">{label}</small>
|
||||
</li>
|
||||
|
@ -82,7 +90,7 @@ const renderPieChartLegend = ({ config }) => {
|
|||
};
|
||||
/* eslint-enable react/prop-types */
|
||||
|
||||
const chartElementAtEvent = (onClick) => ([ chart ]) => {
|
||||
const chartElementAtEvent = (onClick?: (label: string) => void) => ([ chart ]: [{ _index: number; _chart: Chart }]) => {
|
||||
if (!onClick || !chart) {
|
||||
return;
|
||||
}
|
||||
|
@ -90,30 +98,35 @@ const chartElementAtEvent = (onClick) => ([ chart ]) => {
|
|||
const { _index, _chart: { data } } = chart;
|
||||
const { labels } = data;
|
||||
|
||||
onClick(labels[_index]);
|
||||
onClick(labels?.[_index] as string);
|
||||
};
|
||||
|
||||
const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick }) => {
|
||||
const hasHighlightedStats = highlightedStats && Object.keys(highlightedStats).length > 0;
|
||||
const statsAreDefined = (stats: Stats | undefined): stats is Stats => !!stats && Object.keys(stats).length > 0;
|
||||
|
||||
const DefaultChart = (
|
||||
{ title, isBarChart = false, stats, max, highlightedStats, highlightedLabel, onClick }: DefaultChartProps,
|
||||
) => {
|
||||
const Component = isBarChart ? HorizontalBar : Doughnut;
|
||||
const labels = keys(stats).map(dropLabelIfHidden);
|
||||
const data = values(!hasHighlightedStats ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
||||
if (acc[highlightedKey]) {
|
||||
acc[highlightedKey] -= highlightedStats[highlightedKey];
|
||||
}
|
||||
const data = values(
|
||||
!statsAreDefined(highlightedStats) ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
||||
if (acc[highlightedKey]) {
|
||||
acc[highlightedKey] -= highlightedStats[highlightedKey];
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, { ...stats }));
|
||||
const highlightedData = hasHighlightedStats && fillTheGaps(highlightedStats, labels);
|
||||
const chartRef = useRef();
|
||||
return acc;
|
||||
}, { ...stats }),
|
||||
);
|
||||
const highlightedData = statsAreDefined(highlightedStats) ? fillTheGaps(highlightedStats, labels) : undefined;
|
||||
const chartRef = useRef<HorizontalBar | Doughnut>();
|
||||
|
||||
const options = {
|
||||
const options: ChartOptions = {
|
||||
legend: { display: false },
|
||||
legendCallback: !isBarChart && renderPieChartLegend,
|
||||
scales: isBarChart && {
|
||||
legendCallback: !isBarChart && renderPieChartLegend as any,
|
||||
scales: !isBarChart ? undefined : {
|
||||
xAxes: [
|
||||
{
|
||||
ticks: { beginAtZero: true, precision: 0, max },
|
||||
ticks: { beginAtZero: true, precision: 0, max } as any,
|
||||
stacked: true,
|
||||
},
|
||||
],
|
||||
|
@ -125,9 +138,11 @@ const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlig
|
|||
// Do not show tooltip on items with empty label when in a bar chart
|
||||
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
|
||||
},
|
||||
onHover: isBarChart && (({ target }, chartElement) => {
|
||||
onHover: !isBarChart ? undefined : ((e: ChangeEvent<HTMLElement>, chartElement: HorizontalBar[] | Doughnut[]) => {
|
||||
const { target } = e;
|
||||
|
||||
target.style.cursor = chartElement[0] ? 'pointer' : 'default';
|
||||
}),
|
||||
}) as any, // TODO Types seem to be incorrectly defined
|
||||
};
|
||||
const graphData = generateGraphData(title, isBarChart, labels, data, highlightedData, highlightedLabel);
|
||||
const height = determineHeight(isBarChart, labels);
|
||||
|
@ -137,7 +152,7 @@ const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlig
|
|||
<div className="row">
|
||||
<div className={classNames('col-sm-12', { 'col-md-7': !isBarChart })}>
|
||||
<Component
|
||||
ref={chartRef}
|
||||
ref={chartRef as any}
|
||||
key={height}
|
||||
data={graphData}
|
||||
options={options}
|
||||
|
@ -147,13 +162,11 @@ const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlig
|
|||
</div>
|
||||
{!isBarChart && (
|
||||
<div className="col-sm-12 col-md-5">
|
||||
{chartRef.current && chartRef.current.chartInstance.generateLegend()}
|
||||
{chartRef.current?.chartInstance.generateLegend()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
DefaultChart.propTypes = propTypes;
|
||||
|
||||
export default DefaultChart;
|
|
@ -1,30 +0,0 @@
|
|||
import { Card, CardHeader, CardBody, CardFooter } from 'reactstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import React from 'react';
|
||||
import DefaultChart from './DefaultChart';
|
||||
import './GraphCard.scss';
|
||||
|
||||
const propTypes = {
|
||||
title: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
|
||||
footer: PropTypes.oneOfType([ PropTypes.string, PropTypes.node ]),
|
||||
isBarChart: PropTypes.bool,
|
||||
stats: PropTypes.object,
|
||||
max: PropTypes.number,
|
||||
highlightedStats: PropTypes.object,
|
||||
highlightedLabel: PropTypes.string,
|
||||
onClick: PropTypes.func,
|
||||
};
|
||||
|
||||
const GraphCard = ({ title, footer, ...rest }) => (
|
||||
<Card>
|
||||
<CardHeader className="graph-card__header">{typeof title === 'function' ? title() : title}</CardHeader>
|
||||
<CardBody>
|
||||
<DefaultChart title={title} {...rest} />
|
||||
</CardBody>
|
||||
{footer && <CardFooter className="graph-card__footer--sticky">{footer}</CardFooter>}
|
||||
</Card>
|
||||
);
|
||||
|
||||
GraphCard.propTypes = propTypes;
|
||||
|
||||
export default GraphCard;
|
20
src/visits/helpers/GraphCard.tsx
Normal file
20
src/visits/helpers/GraphCard.tsx
Normal file
|
@ -0,0 +1,20 @@
|
|||
import { Card, CardHeader, CardBody, CardFooter } from 'reactstrap';
|
||||
import React, { ReactNode } from 'react';
|
||||
import DefaultChart, { DefaultChartProps } from './DefaultChart';
|
||||
import './GraphCard.scss';
|
||||
|
||||
interface GraphCardProps extends DefaultChartProps {
|
||||
footer?: ReactNode;
|
||||
}
|
||||
|
||||
const GraphCard = ({ title, footer, ...rest }: GraphCardProps) => (
|
||||
<Card>
|
||||
<CardHeader className="graph-card__header">{typeof title === 'function' ? title() : title}</CardHeader>
|
||||
<CardBody>
|
||||
<DefaultChart title={title} {...rest} />
|
||||
</CardBody>
|
||||
{footer && <CardFooter className="graph-card__footer--sticky">{footer}</CardFooter>}
|
||||
</Card>
|
||||
);
|
||||
|
||||
export default GraphCard;
|
|
@ -1,17 +1,17 @@
|
|||
import React from 'react';
|
||||
import { shallow } from 'enzyme';
|
||||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
|
||||
import { keys, values } from 'ramda';
|
||||
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
||||
|
||||
describe('<DefaultChart />', () => {
|
||||
let wrapper;
|
||||
let wrapper: ShallowWrapper;
|
||||
const stats = {
|
||||
foo: 123,
|
||||
bar: 456,
|
||||
};
|
||||
|
||||
afterEach(() => wrapper && wrapper.unmount());
|
||||
afterEach(() => wrapper?.unmount());
|
||||
|
||||
it('renders Doughnut when is not a bar chart', () => {
|
||||
wrapper = shallow(<DefaultChart title="The chart" stats={stats} />);
|
||||
|
@ -22,9 +22,9 @@ describe('<DefaultChart />', () => {
|
|||
expect(doughnut).toHaveLength(1);
|
||||
expect(horizontal).toHaveLength(0);
|
||||
|
||||
const { labels, datasets } = doughnut.prop('data');
|
||||
const { labels, datasets } = doughnut.prop('data') as any;
|
||||
const [{ title, data, backgroundColor, borderColor }] = datasets;
|
||||
const { legend, legendCallback, scales } = doughnut.prop('options');
|
||||
const { legend, legendCallback, scales } = doughnut.prop('options') ?? {};
|
||||
|
||||
expect(title).toEqual('The chart');
|
||||
expect(labels).toEqual(keys(stats));
|
||||
|
@ -59,8 +59,8 @@ describe('<DefaultChart />', () => {
|
|||
expect(doughnut).toHaveLength(0);
|
||||
expect(horizontal).toHaveLength(1);
|
||||
|
||||
const { datasets: [{ backgroundColor, borderColor }] } = horizontal.prop('data');
|
||||
const { legend, legendCallback, scales } = horizontal.prop('options');
|
||||
const { datasets: [{ backgroundColor, borderColor }] } = horizontal.prop('data') as any;
|
||||
const { legend, legendCallback, scales } = horizontal.prop('options') ?? {};
|
||||
|
||||
expect(backgroundColor).toEqual('rgba(70, 150, 229, 0.4)');
|
||||
expect(borderColor).toEqual('rgba(70, 150, 229, 1)');
|
||||
|
@ -88,7 +88,7 @@ describe('<DefaultChart />', () => {
|
|||
wrapper = shallow(<DefaultChart isBarChart title="The chart" stats={stats} highlightedStats={highlightedStats} />);
|
||||
const horizontal = wrapper.find(HorizontalBar);
|
||||
|
||||
const { datasets: [{ data, label }, highlightedData ] } = horizontal.prop('data');
|
||||
const { datasets: [{ data, label }, highlightedData ] } = horizontal.prop('data') as any;
|
||||
|
||||
expect(label).toEqual(highlightedStats ? 'Non-selected' : 'Visits');
|
||||
expect(data).toEqual(expectedData);
|
|
@ -1,18 +1,18 @@
|
|||
import React from 'react';
|
||||
import { shallow } from 'enzyme';
|
||||
import React, { ReactNode } from 'react';
|
||||
import { shallow, ShallowWrapper } from 'enzyme';
|
||||
import { Card, CardBody, CardHeader, CardFooter } from 'reactstrap';
|
||||
import GraphCard from '../../../src/visits/helpers/GraphCard';
|
||||
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
||||
|
||||
describe('<GraphCard />', () => {
|
||||
let wrapper;
|
||||
const createWrapper = (title = '', footer) => {
|
||||
wrapper = shallow(<GraphCard title={title} footer={footer} />);
|
||||
let wrapper: ShallowWrapper;
|
||||
const createWrapper = (title: Function | string = '', footer?: ReactNode) => {
|
||||
wrapper = shallow(<GraphCard title={title} footer={footer} stats={{}} />);
|
||||
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
afterEach(() => wrapper && wrapper.unmount());
|
||||
afterEach(() => wrapper?.unmount());
|
||||
|
||||
it('renders expected components', () => {
|
||||
const wrapper = createWrapper();
|
Loading…
Reference in a new issue