Skip to content

Commit

Permalink
Merge pull request #283 from acelaya-forks/feature/chart-legend
Browse files Browse the repository at this point in the history
Feature/chart legend
  • Loading branch information
acelaya committed Jun 6, 2020
2 parents 72dd2bd + fa54aa3 commit e26cdc1
Show file tree
Hide file tree
Showing 6 changed files with 324 additions and 182 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Expand Up @@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org).

## [Unreleased]
## 2.5.1 - 2020-06-06

#### Added

Expand All @@ -26,6 +26,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

* [#276](https://github.com/shlinkio/shlink-web-client/issues/276) Fixed default grouping used for visits line chart, making it be dynamic depending on how old the short URL is.
* [#280](https://github.com/shlinkio/shlink-web-client/issues/280) Fixed shlink-web-client version not being properly passed when building stable tags of the docker image.
* [#269](https://github.com/shlinkio/shlink-web-client/issues/269) Fixed doughnut chart legends getting to big and hiding charts on mobile devices.


## 2.5.0 - 2020-05-31
Expand Down
159 changes: 159 additions & 0 deletions src/visits/helpers/DefaultChart.js
@@ -0,0 +1,159 @@
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
import { keys, values } from 'ramda';
import classNames from 'classnames';
import { fillTheGaps } from '../../utils/helpers/visits';
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,
};

const generateGraphData = (title, isBarChart, labels, data, highlightedData, highlightedLabel) => ({
labels,
datasets: [
{
title,
label: highlightedData ? 'Non-selected' : 'Visits',
data,
backgroundColor: isBarChart ? 'rgba(70, 150, 229, 0.4)' : [
'#97BBCD',
'#F7464A',
'#46BFBD',
'#FDB45C',
'#949FB1',
'#57A773',
'#414066',
'#08B2E3',
'#B6C454',
'#DCDCDC',
'#463730',
],
borderColor: isBarChart ? 'rgba(70, 150, 229, 1)' : 'white',
borderWidth: 2,
},
highlightedData && {
title,
label: highlightedLabel || 'Selected',
data: highlightedData,
backgroundColor: 'rgba(247, 127, 40, 0.4)',
borderColor: '#F77F28',
borderWidth: 2,
},
].filter(Boolean),
});

const dropLabelIfHidden = (label) => label.startsWith('hidden') ? '' : label;

const determineHeight = (isBarChart, labels) => {
if (!isBarChart) {
return 300;
}

return isBarChart && labels.length > 20 ? labels.length * 8 : null;
};

/* eslint-disable react/prop-types */
const renderPieChartLegend = ({ config }) => {
const { labels, datasets } = config.data;
const { defaultColor } = config.options;
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">
<div
className="default-chart__pie-chart-legend-item-color"
style={{ backgroundColor: colors[index] || defaultColor }}
/>
<small className="default-chart__pie-chart-legend-item-text flex-fill">{label}</small>
</li>
))}
</ul>
);
};
/* eslint-enable react/prop-types */

const chartElementAtEvent = (onClick) => ([ chart ]) => {
if (!onClick || !chart) {
return;
}

const { _index, _chart: { data } } = chart;
const { labels } = data;

onClick(labels[_index]);
};

const DefaultChart = ({ title, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick }) => {
const hasHighlightedStats = highlightedStats && Object.keys(highlightedStats).length > 0;
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];
}

return acc;
}, { ...stats }));
const highlightedData = hasHighlightedStats && fillTheGaps(highlightedStats, labels);
const chartRef = useRef();

const options = {
legend: { display: false },
legendCallback: !isBarChart && renderPieChartLegend,
scales: isBarChart && {
xAxes: [
{
ticks: { beginAtZero: true, precision: 0, max },
stacked: true,
},
],
yAxes: [{ stacked: true }],
},
tooltips: {
intersect: !isBarChart,

// Do not show tooltip on items with empty label when in a bar chart
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
},
onHover: isBarChart && (({ target }, chartElement) => {
target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}),
};
const graphData = generateGraphData(title, isBarChart, labels, data, highlightedData, highlightedLabel);
const height = determineHeight(isBarChart, labels);

// Provide a key based on the height, so that every time the dataset changes, a new graph is rendered
return (
<div className="row">
<div className={classNames('col-sm-12', { 'col-md-7': !isBarChart })}>
<Component
ref={chartRef}
key={height}
data={graphData}
options={options}
height={height}
getElementAtEvent={chartElementAtEvent(onClick)}
/>
</div>
{!isBarChart && (
<div className="col-sm-12 col-md-5">
{chartRef.current && chartRef.current.chartInstance.generateLegend()}
</div>
)}
</div>
);
};

DefaultChart.propTypes = propTypes;

export default DefaultChart;
29 changes: 29 additions & 0 deletions src/visits/helpers/DefaultChart.scss
@@ -0,0 +1,29 @@
@import '../../utils/base';

.default-chart__pie-chart-legend {
list-style-type: none;
padding: 0;
margin: 0;

@media (max-width: $smMax) {
margin-top: 1rem;
}
}

.default-chart__pie-chart-legend-item:not(:first-child) {
margin-top: .3rem;
}

.default-chart__pie-chart-legend-item-color {
width: 20px;
min-width: 20px;
height: 20px;
margin-right: 5px;
border-radius: 10px;
}

.default-chart__pie-chart-legend-item-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
112 changes: 5 additions & 107 deletions src/visits/helpers/GraphCard.js
@@ -1,9 +1,7 @@
import { Card, CardHeader, CardBody, CardFooter } from 'reactstrap';
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
import PropTypes from 'prop-types';
import React from 'react';
import { keys, values } from 'ramda';
import { fillTheGaps } from '../../utils/helpers/visits';
import DefaultChart from './DefaultChart';
import './GraphCard.scss';

const propTypes = {
Expand All @@ -17,112 +15,12 @@ const propTypes = {
onClick: PropTypes.func,
};

const generateGraphData = (title, isBarChart, labels, data, highlightedData, highlightedLabel) => ({
labels,
datasets: [
{
title,
label: highlightedData ? 'Non-selected' : 'Visits',
data,
backgroundColor: isBarChart ? 'rgba(70, 150, 229, 0.4)' : [
'#97BBCD',
'#F7464A',
'#46BFBD',
'#FDB45C',
'#949FB1',
'#57A773',
'#414066',
'#08B2E3',
'#B6C454',
'#DCDCDC',
'#463730',
],
borderColor: isBarChart ? 'rgba(70, 150, 229, 1)' : 'white',
borderWidth: 2,
},
highlightedData && {
title,
label: highlightedLabel || 'Selected',
data: highlightedData,
backgroundColor: 'rgba(247, 127, 40, 0.4)',
borderColor: '#F77F28',
borderWidth: 2,
},
].filter(Boolean),
});

const dropLabelIfHidden = (label) => label.startsWith('hidden') ? '' : label;

const determineHeight = (isBarChart, labels) => {
if (!isBarChart && labels.length > 8) {
return 200;
}

return isBarChart && labels.length > 20 ? labels.length * 8 : null;
};

const renderGraph = (title, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick) => {
const hasHighlightedStats = highlightedStats && Object.keys(highlightedStats).length > 0;
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];
}

return acc;
}, { ...stats }));
const highlightedData = hasHighlightedStats && fillTheGaps(highlightedStats, labels);

const options = {
legend: isBarChart ? { display: false } : { position: 'right' },
scales: isBarChart && {
xAxes: [
{
ticks: { beginAtZero: true, precision: 0, max },
stacked: true,
},
],
yAxes: [{ stacked: true }],
},
tooltips: {
intersect: !isBarChart,

// Do not show tooltip on items with empty label when in a bar chart
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
},
onHover: isBarChart && (({ target }, chartElement) => {
target.style.cursor = chartElement[0] ? 'pointer' : 'default';
}),
};
const graphData = generateGraphData(title, isBarChart, labels, data, highlightedData, highlightedLabel);
const height = determineHeight(isBarChart, labels);

// Provide a key based on the height, so that every time the dataset changes, a new graph is rendered
return (
<Component
key={height}
data={graphData}
options={options}
height={height}
getElementAtEvent={([ chart ]) => {
if (!onClick || !chart) {
return;
}

const { _index, _chart: { data } } = chart;
const { labels } = data;

onClick(labels[_index]);
}}
/>
);
};

const GraphCard = ({ title, footer, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick }) => (
const GraphCard = ({ title, footer, ...rest }) => (
<Card>
<CardHeader className="graph-card__header">{typeof title === 'function' ? title() : title}</CardHeader>
<CardBody>{renderGraph(title, isBarChart, stats, max, highlightedStats, highlightedLabel, onClick)}</CardBody>
<CardBody>
<DefaultChart title={title} {...rest} />
</CardBody>
{footer && <CardFooter className="graph-card__footer--sticky">{footer}</CardFooter>}
</Card>
);
Expand Down

0 comments on commit e26cdc1

Please sign in to comment.