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"
|
"@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": {
|
"@types/cheerio": {
|
||||||
"version": "0.22.21",
|
"version": "0.22.21",
|
||||||
"resolved": "https://registry.npmjs.org/@types/cheerio/-/cheerio-0.22.21.tgz",
|
"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/javascript-mutator": "^3.2.4",
|
||||||
"@stryker-mutator/jest-runner": "^3.2.4",
|
"@stryker-mutator/jest-runner": "^3.2.4",
|
||||||
"@svgr/webpack": "^4.3.3",
|
"@svgr/webpack": "^4.3.3",
|
||||||
|
"@types/chart.js": "^2.8.0",
|
||||||
"@types/classnames": "^2.2.10",
|
"@types/classnames": "^2.2.10",
|
||||||
"@types/enzyme": "^3.10.5",
|
"@types/enzyme": "^3.10.5",
|
||||||
"@types/jest": "^26.0.10",
|
"@types/jest": "^26.0.10",
|
||||||
|
|
|
@ -1,22 +1,30 @@
|
||||||
import React, { useRef } from 'react';
|
import React, { ChangeEvent, useRef } from 'react';
|
||||||
import PropTypes from 'prop-types';
|
|
||||||
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
|
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
|
||||||
import { keys, values } from 'ramda';
|
import { keys, values } from 'ramda';
|
||||||
import classNames from 'classnames';
|
import classNames from 'classnames';
|
||||||
|
import Chart, { ChartData, ChartDataSets, ChartOptions } from 'chart.js';
|
||||||
import { fillTheGaps } from '../../utils/helpers/visits';
|
import { fillTheGaps } from '../../utils/helpers/visits';
|
||||||
|
import { Stats } from '../types';
|
||||||
import './DefaultChart.scss';
|
import './DefaultChart.scss';
|
||||||
|
|
||||||
const propTypes = {
|
export interface DefaultChartProps {
|
||||||
title: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
|
title: Function | string;
|
||||||
isBarChart: PropTypes.bool,
|
stats: Stats;
|
||||||
stats: PropTypes.object,
|
isBarChart?: boolean;
|
||||||
max: PropTypes.number,
|
max?: number;
|
||||||
highlightedStats: PropTypes.object,
|
highlightedStats?: Stats;
|
||||||
highlightedLabel: PropTypes.string,
|
highlightedLabel?: string;
|
||||||
onClick: PropTypes.func,
|
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,
|
labels,
|
||||||
datasets: [
|
datasets: [
|
||||||
{
|
{
|
||||||
|
@ -39,40 +47,40 @@ const generateGraphData = (title, isBarChart, labels, data, highlightedData, hig
|
||||||
borderColor: isBarChart ? 'rgba(70, 150, 229, 1)' : 'white',
|
borderColor: isBarChart ? 'rgba(70, 150, 229, 1)' : 'white',
|
||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
},
|
},
|
||||||
highlightedData && {
|
(highlightedData && {
|
||||||
title,
|
title,
|
||||||
label: highlightedLabel || 'Selected',
|
label: highlightedLabel ?? 'Selected',
|
||||||
data: highlightedData,
|
data: highlightedData,
|
||||||
backgroundColor: 'rgba(247, 127, 40, 0.4)',
|
backgroundColor: 'rgba(247, 127, 40, 0.4)',
|
||||||
borderColor: '#F77F28',
|
borderColor: '#F77F28',
|
||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
},
|
}) as unknown as ChartDataSets,
|
||||||
].filter(Boolean),
|
].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) {
|
if (!isBarChart) {
|
||||||
return 300;
|
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 */
|
/* eslint-disable react/prop-types */
|
||||||
const renderPieChartLegend = ({ config }) => {
|
const renderPieChartLegend = ({ config }: Chart) => {
|
||||||
const { labels, datasets } = config.data;
|
const { labels = [], datasets = [] } = config.data ?? {};
|
||||||
const { defaultColor } = config.options;
|
const { defaultColor } = config.options ?? {} as any;
|
||||||
const [{ backgroundColor: colors }] = datasets;
|
const [{ backgroundColor: colors }] = datasets;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="default-chart__pie-chart-legend">
|
<ul className="default-chart__pie-chart-legend">
|
||||||
{labels.map((label, index) => (
|
{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
|
<div
|
||||||
className="default-chart__pie-chart-legend-item-color"
|
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>
|
<small className="default-chart__pie-chart-legend-item-text flex-fill">{label}</small>
|
||||||
</li>
|
</li>
|
||||||
|
@ -82,7 +90,7 @@ const renderPieChartLegend = ({ config }) => {
|
||||||
};
|
};
|
||||||
/* eslint-enable react/prop-types */
|
/* eslint-enable react/prop-types */
|
||||||
|
|
||||||
const chartElementAtEvent = (onClick) => ([ chart ]) => {
|
const chartElementAtEvent = (onClick?: (label: string) => void) => ([ chart ]: [{ _index: number; _chart: Chart }]) => {
|
||||||
if (!onClick || !chart) {
|
if (!onClick || !chart) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -90,30 +98,35 @@ const chartElementAtEvent = (onClick) => ([ chart ]) => {
|
||||||
const { _index, _chart: { data } } = chart;
|
const { _index, _chart: { data } } = chart;
|
||||||
const { labels } = data;
|
const { labels } = data;
|
||||||
|
|
||||||
onClick(labels[_index]);
|
onClick(labels?.[_index] as string);
|
||||||
};
|
};
|
||||||
|
|
||||||
const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick }) => {
|
const statsAreDefined = (stats: Stats | undefined): stats is Stats => !!stats && Object.keys(stats).length > 0;
|
||||||
const hasHighlightedStats = highlightedStats && Object.keys(highlightedStats).length > 0;
|
|
||||||
|
const DefaultChart = (
|
||||||
|
{ title, isBarChart = false, stats, max, highlightedStats, highlightedLabel, onClick }: DefaultChartProps,
|
||||||
|
) => {
|
||||||
const Component = isBarChart ? HorizontalBar : Doughnut;
|
const Component = isBarChart ? HorizontalBar : Doughnut;
|
||||||
const labels = keys(stats).map(dropLabelIfHidden);
|
const labels = keys(stats).map(dropLabelIfHidden);
|
||||||
const data = values(!hasHighlightedStats ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
const data = values(
|
||||||
if (acc[highlightedKey]) {
|
!statsAreDefined(highlightedStats) ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
||||||
acc[highlightedKey] -= highlightedStats[highlightedKey];
|
if (acc[highlightedKey]) {
|
||||||
}
|
acc[highlightedKey] -= highlightedStats[highlightedKey];
|
||||||
|
}
|
||||||
|
|
||||||
return acc;
|
return acc;
|
||||||
}, { ...stats }));
|
}, { ...stats }),
|
||||||
const highlightedData = hasHighlightedStats && fillTheGaps(highlightedStats, labels);
|
);
|
||||||
const chartRef = useRef();
|
const highlightedData = statsAreDefined(highlightedStats) ? fillTheGaps(highlightedStats, labels) : undefined;
|
||||||
|
const chartRef = useRef<HorizontalBar | Doughnut>();
|
||||||
|
|
||||||
const options = {
|
const options: ChartOptions = {
|
||||||
legend: { display: false },
|
legend: { display: false },
|
||||||
legendCallback: !isBarChart && renderPieChartLegend,
|
legendCallback: !isBarChart && renderPieChartLegend as any,
|
||||||
scales: isBarChart && {
|
scales: !isBarChart ? undefined : {
|
||||||
xAxes: [
|
xAxes: [
|
||||||
{
|
{
|
||||||
ticks: { beginAtZero: true, precision: 0, max },
|
ticks: { beginAtZero: true, precision: 0, max } as any,
|
||||||
stacked: true,
|
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
|
// Do not show tooltip on items with empty label when in a bar chart
|
||||||
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
|
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';
|
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 graphData = generateGraphData(title, isBarChart, labels, data, highlightedData, highlightedLabel);
|
||||||
const height = determineHeight(isBarChart, labels);
|
const height = determineHeight(isBarChart, labels);
|
||||||
|
@ -137,7 +152,7 @@ const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlig
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<div className={classNames('col-sm-12', { 'col-md-7': !isBarChart })}>
|
<div className={classNames('col-sm-12', { 'col-md-7': !isBarChart })}>
|
||||||
<Component
|
<Component
|
||||||
ref={chartRef}
|
ref={chartRef as any}
|
||||||
key={height}
|
key={height}
|
||||||
data={graphData}
|
data={graphData}
|
||||||
options={options}
|
options={options}
|
||||||
|
@ -147,13 +162,11 @@ const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlig
|
||||||
</div>
|
</div>
|
||||||
{!isBarChart && (
|
{!isBarChart && (
|
||||||
<div className="col-sm-12 col-md-5">
|
<div className="col-sm-12 col-md-5">
|
||||||
{chartRef.current && chartRef.current.chartInstance.generateLegend()}
|
{chartRef.current?.chartInstance.generateLegend()}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
DefaultChart.propTypes = propTypes;
|
|
||||||
|
|
||||||
export default DefaultChart;
|
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 React from 'react';
|
||||||
import { shallow } from 'enzyme';
|
import { shallow, ShallowWrapper } from 'enzyme';
|
||||||
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
|
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
|
||||||
import { keys, values } from 'ramda';
|
import { keys, values } from 'ramda';
|
||||||
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
||||||
|
|
||||||
describe('<DefaultChart />', () => {
|
describe('<DefaultChart />', () => {
|
||||||
let wrapper;
|
let wrapper: ShallowWrapper;
|
||||||
const stats = {
|
const stats = {
|
||||||
foo: 123,
|
foo: 123,
|
||||||
bar: 456,
|
bar: 456,
|
||||||
};
|
};
|
||||||
|
|
||||||
afterEach(() => wrapper && wrapper.unmount());
|
afterEach(() => wrapper?.unmount());
|
||||||
|
|
||||||
it('renders Doughnut when is not a bar chart', () => {
|
it('renders Doughnut when is not a bar chart', () => {
|
||||||
wrapper = shallow(<DefaultChart title="The chart" stats={stats} />);
|
wrapper = shallow(<DefaultChart title="The chart" stats={stats} />);
|
||||||
|
@ -22,9 +22,9 @@ describe('<DefaultChart />', () => {
|
||||||
expect(doughnut).toHaveLength(1);
|
expect(doughnut).toHaveLength(1);
|
||||||
expect(horizontal).toHaveLength(0);
|
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 [{ 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(title).toEqual('The chart');
|
||||||
expect(labels).toEqual(keys(stats));
|
expect(labels).toEqual(keys(stats));
|
||||||
|
@ -59,8 +59,8 @@ describe('<DefaultChart />', () => {
|
||||||
expect(doughnut).toHaveLength(0);
|
expect(doughnut).toHaveLength(0);
|
||||||
expect(horizontal).toHaveLength(1);
|
expect(horizontal).toHaveLength(1);
|
||||||
|
|
||||||
const { datasets: [{ backgroundColor, borderColor }] } = horizontal.prop('data');
|
const { datasets: [{ backgroundColor, borderColor }] } = horizontal.prop('data') as any;
|
||||||
const { legend, legendCallback, scales } = horizontal.prop('options');
|
const { legend, legendCallback, scales } = horizontal.prop('options') ?? {};
|
||||||
|
|
||||||
expect(backgroundColor).toEqual('rgba(70, 150, 229, 0.4)');
|
expect(backgroundColor).toEqual('rgba(70, 150, 229, 0.4)');
|
||||||
expect(borderColor).toEqual('rgba(70, 150, 229, 1)');
|
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} />);
|
wrapper = shallow(<DefaultChart isBarChart title="The chart" stats={stats} highlightedStats={highlightedStats} />);
|
||||||
const horizontal = wrapper.find(HorizontalBar);
|
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(label).toEqual(highlightedStats ? 'Non-selected' : 'Visits');
|
||||||
expect(data).toEqual(expectedData);
|
expect(data).toEqual(expectedData);
|
|
@ -1,18 +1,18 @@
|
||||||
import React from 'react';
|
import React, { ReactNode } from 'react';
|
||||||
import { shallow } from 'enzyme';
|
import { shallow, ShallowWrapper } from 'enzyme';
|
||||||
import { Card, CardBody, CardHeader, CardFooter } from 'reactstrap';
|
import { Card, CardBody, CardHeader, CardFooter } from 'reactstrap';
|
||||||
import GraphCard from '../../../src/visits/helpers/GraphCard';
|
import GraphCard from '../../../src/visits/helpers/GraphCard';
|
||||||
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
import DefaultChart from '../../../src/visits/helpers/DefaultChart';
|
||||||
|
|
||||||
describe('<GraphCard />', () => {
|
describe('<GraphCard />', () => {
|
||||||
let wrapper;
|
let wrapper: ShallowWrapper;
|
||||||
const createWrapper = (title = '', footer) => {
|
const createWrapper = (title: Function | string = '', footer?: ReactNode) => {
|
||||||
wrapper = shallow(<GraphCard title={title} footer={footer} />);
|
wrapper = shallow(<GraphCard title={title} footer={footer} stats={{}} />);
|
||||||
|
|
||||||
return wrapper;
|
return wrapper;
|
||||||
};
|
};
|
||||||
|
|
||||||
afterEach(() => wrapper && wrapper.unmount());
|
afterEach(() => wrapper?.unmount());
|
||||||
|
|
||||||
it('renders expected components', () => {
|
it('renders expected components', () => {
|
||||||
const wrapper = createWrapper();
|
const wrapper = createWrapper();
|
Loading…
Reference in a new issue