mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2026-02-27 04:06:39 +00:00
Allowed visits to be selected on charts so that they get highlighted on the rest of the charts
This commit is contained in:
@@ -12,6 +12,7 @@ const propTypes = {
|
||||
stats: PropTypes.object,
|
||||
max: PropTypes.number,
|
||||
highlightedStats: PropTypes.object,
|
||||
onClick: PropTypes.func,
|
||||
};
|
||||
|
||||
const generateGraphData = (title, isBarChart, labels, data, highlightedData) => ({
|
||||
@@ -19,6 +20,7 @@ const generateGraphData = (title, isBarChart, labels, data, highlightedData) =>
|
||||
datasets: [
|
||||
{
|
||||
title,
|
||||
label: '',
|
||||
data,
|
||||
backgroundColor: isBarChart ? 'rgba(70, 150, 229, 0.4)' : [
|
||||
'#97BBCD',
|
||||
@@ -45,17 +47,20 @@ const generateGraphData = (title, isBarChart, labels, data, highlightedData) =>
|
||||
|
||||
const dropLabelIfHidden = (label) => label.startsWith('hidden') ? '' : label;
|
||||
|
||||
const renderGraph = (title, isBarChart, stats, max, highlightedStats) => {
|
||||
const renderGraph = (title, isBarChart, stats, max, highlightedStats, onClick) => {
|
||||
const hasHighlightedStats = highlightedStats && Object.keys(highlightedStats).length > 0;
|
||||
const Component = isBarChart ? HorizontalBar : Doughnut;
|
||||
const labels = keys(stats).map(dropLabelIfHidden);
|
||||
const data = values(!highlightedStats ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
||||
const data = values(!hasHighlightedStats ? stats : keys(highlightedStats).reduce((acc, highlightedKey) => {
|
||||
if (acc[highlightedKey]) {
|
||||
acc[highlightedKey] -= highlightedStats[highlightedKey];
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, { ...stats }));
|
||||
const highlightedData = highlightedStats && values({ ...zipObj(labels, labels.map(() => 0)), ...highlightedStats });
|
||||
const highlightedData = hasHighlightedStats && values(
|
||||
{ ...zipObj(labels, labels.map(() => 0)), ...highlightedStats }
|
||||
);
|
||||
|
||||
const options = {
|
||||
legend: isBarChart ? { display: false } : { position: 'right' },
|
||||
@@ -79,13 +84,30 @@ const renderGraph = (title, isBarChart, stats, max, highlightedStats) => {
|
||||
const height = isBarChart && labels.length > 20 ? labels.length * 8 : null;
|
||||
|
||||
// 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} />;
|
||||
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 }) => (
|
||||
const GraphCard = ({ title, footer, isBarChart, stats, max, highlightedStats, onClick }) => (
|
||||
<Card className="mt-4">
|
||||
<CardHeader className="graph-card__header">{typeof title === 'function' ? title() : title}</CardHeader>
|
||||
<CardBody>{renderGraph(title, isBarChart, stats, max, highlightedStats)}</CardBody>
|
||||
<CardBody>{renderGraph(title, isBarChart, stats, max, highlightedStats, onClick)}</CardBody>
|
||||
{footer && <CardFooter className="graph-card__footer--sticky">{footer}</CardFooter>}
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isEmpty, values } from 'ramda';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { isEmpty, propEq, values } from 'ramda';
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { Button, Card, Collapse } from 'reactstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import qs from 'qs';
|
||||
@@ -41,10 +41,8 @@ const highlightedVisitsToStats = (highlightedVisits, prop) => highlightedVisits.
|
||||
return acc;
|
||||
}, {});
|
||||
const format = formatDate();
|
||||
let memoizationId;
|
||||
let timeWhenMounted;
|
||||
|
||||
const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
const ShortUrlVisits = ({ processStatsFromVisits, normalizeVisits }, OpenMapModalBtn) => {
|
||||
const ShortUrlVisitsComp = ({
|
||||
match,
|
||||
location,
|
||||
@@ -62,23 +60,28 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
const [ highlightedVisits, setHighlightedVisits ] = useState([]);
|
||||
const [ isMobileDevice, setIsMobileDevice ] = useState(false);
|
||||
const determineIsMobileDevice = () => setIsMobileDevice(matchMedia('(max-width: 991px)').matches);
|
||||
const highlightVisitsForProp = (prop) => (value) => setHighlightedVisits(
|
||||
highlightedVisits.length === 0 ? normalizedVisits.filter(propEq(prop, value)) : []
|
||||
);
|
||||
|
||||
const { params } = match;
|
||||
const { shortCode } = params;
|
||||
const { search } = location;
|
||||
const { domain } = qs.parse(search, { ignoreQueryPrefix: true });
|
||||
|
||||
const loadVisits = () => {
|
||||
const start = format(startDate);
|
||||
const end = format(endDate);
|
||||
const { visits, loading, loadingLarge, error } = shortUrlVisits;
|
||||
const showTableControls = !loading && visits.length > 0;
|
||||
const normalizedVisits = useMemo(() => normalizeVisits(visits), [ visits ]);
|
||||
const { os, browsers, referrers, countries, cities, citiesForMap } = useMemo(
|
||||
() => processStatsFromVisits(visits),
|
||||
[ visits ]
|
||||
);
|
||||
const mapLocations = values(citiesForMap);
|
||||
|
||||
// While the "page" is loaded, use the timestamp + filtering dates as memoization IDs for stats calculations
|
||||
memoizationId = `${timeWhenMounted}_${shortCode}_${start}_${end}`;
|
||||
getShortUrlVisits(shortCode, { startDate: start, endDate: end, domain });
|
||||
};
|
||||
const loadVisits = () =>
|
||||
getShortUrlVisits(shortCode, { startDate: format(startDate), endDate: format(endDate), domain });
|
||||
|
||||
useEffect(() => {
|
||||
timeWhenMounted = new Date().getTime();
|
||||
getShortUrlDetail(shortCode, domain);
|
||||
determineIsMobileDevice();
|
||||
window.addEventListener('resize', determineIsMobileDevice);
|
||||
@@ -92,9 +95,6 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
loadVisits();
|
||||
}, [ startDate, endDate ]);
|
||||
|
||||
const { visits, loading, loadingLarge, error } = shortUrlVisits;
|
||||
const showTableControls = !loading && visits.length > 0;
|
||||
|
||||
const renderVisitsContent = () => {
|
||||
if (loading) {
|
||||
const message = loadingLarge ? 'This is going to take a while... :S' : 'Loading...';
|
||||
@@ -114,11 +114,6 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
return <Message>There are no visits matching current filter :(</Message>;
|
||||
}
|
||||
|
||||
const { os, browsers, referrers, countries, cities, citiesForMap } = processStatsFromVisits(
|
||||
{ id: memoizationId, visits }
|
||||
);
|
||||
const mapLocations = values(citiesForMap);
|
||||
|
||||
return (
|
||||
<div className="row">
|
||||
<div className="col-xl-4 col-lg-6">
|
||||
@@ -137,6 +132,7 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
name: 'Referrer name',
|
||||
amount: 'Visits amount',
|
||||
}}
|
||||
onClick={highlightVisitsForProp('referer')}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-lg-6">
|
||||
@@ -148,6 +144,7 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
name: 'Country name',
|
||||
amount: 'Visits amount',
|
||||
}}
|
||||
onClick={highlightVisitsForProp('country')}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-lg-6">
|
||||
@@ -163,6 +160,7 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
name: 'City name',
|
||||
amount: 'Visits amount',
|
||||
}}
|
||||
onClick={highlightVisitsForProp('city')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -185,11 +183,7 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
</div>
|
||||
<div className="col-lg-4 col-xl-6 mt-4 mt-lg-0">
|
||||
{showTableControls && (
|
||||
<Button
|
||||
outline
|
||||
block={isMobileDevice}
|
||||
onClick={toggleTable}
|
||||
>
|
||||
<Button outline block={isMobileDevice} onClick={toggleTable}>
|
||||
{showTable ? 'Hide' : 'Show'} table{' '}
|
||||
<FontAwesomeIcon icon={chevronDown} rotation={showTable ? 180 : undefined} />
|
||||
</Button>
|
||||
@@ -201,12 +195,16 @@ const ShortUrlVisits = ({ processStatsFromVisits }, OpenMapModalBtn) => {
|
||||
{showTableControls && (
|
||||
<Collapse
|
||||
isOpen={showTable}
|
||||
|
||||
// Enable stickiness only when there's no CSS animation, to avoid weird rendering effects
|
||||
onEntered={setSticky}
|
||||
onExiting={unsetSticky}
|
||||
>
|
||||
<VisitsTable visits={visits} isSticky={tableIsSticky} onVisitsSelected={setHighlightedVisits} />
|
||||
<VisitsTable
|
||||
visits={normalizedVisits}
|
||||
selectedVisits={highlightedVisits}
|
||||
setSelectedVisits={setHighlightedVisits}
|
||||
isSticky={tableIsSticky}
|
||||
/>
|
||||
</Collapse>
|
||||
)}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ export default class SortableBarGraph extends React.Component {
|
||||
sortingItems: PropTypes.object.isRequired,
|
||||
extraHeaderContent: PropTypes.func,
|
||||
withPagination: PropTypes.bool,
|
||||
onClick: PropTypes.func,
|
||||
};
|
||||
|
||||
state = {
|
||||
@@ -74,7 +75,7 @@ export default class SortableBarGraph extends React.Component {
|
||||
}
|
||||
|
||||
render() {
|
||||
const { stats, sortingItems, title, extraHeaderContent, highlightedStats, withPagination = true } = this.props;
|
||||
const { stats, sortingItems, title, extraHeaderContent, withPagination = true, ...rest } = this.props;
|
||||
const { currentPageStats, pagination, max } = this.determineStats(stats, sortingItems);
|
||||
const activeCities = keys(currentPageStats);
|
||||
const computeTitle = () => (
|
||||
@@ -115,7 +116,7 @@ export default class SortableBarGraph extends React.Component {
|
||||
stats={currentPageStats}
|
||||
footer={pagination}
|
||||
max={max}
|
||||
highlightedStats={highlightedStats}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import Moment from 'react-moment';
|
||||
import classNames from 'classnames';
|
||||
import { map, min, splitEvery } from 'ramda';
|
||||
import { min, splitEvery } from 'ramda';
|
||||
import {
|
||||
faCaretDown as caretDownIcon,
|
||||
faCaretUp as caretUpIcon,
|
||||
@@ -11,15 +11,18 @@ import {
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import SimplePaginator from '../common/SimplePaginator';
|
||||
import SearchField from '../utils/SearchField';
|
||||
import { browserFromUserAgent, extractDomain, osFromUserAgent } from '../utils/helpers/visits';
|
||||
import { determineOrderDir } from '../utils/utils';
|
||||
import { prettify } from '../utils/helpers/numbers';
|
||||
import { visitType } from './reducers/shortUrlVisits';
|
||||
import './VisitsTable.scss';
|
||||
|
||||
const NormalizedVisitType = PropTypes.shape({
|
||||
|
||||
});
|
||||
|
||||
const propTypes = {
|
||||
visits: PropTypes.arrayOf(visitType).isRequired,
|
||||
onVisitsSelected: PropTypes.func,
|
||||
visits: PropTypes.arrayOf(NormalizedVisitType).isRequired,
|
||||
selectedVisits: PropTypes.arrayOf(NormalizedVisitType),
|
||||
setSelectedVisits: PropTypes.func.isRequired,
|
||||
isSticky: PropTypes.bool,
|
||||
matchMedia: PropTypes.func,
|
||||
};
|
||||
@@ -35,34 +38,30 @@ const sortVisits = ({ field, dir }, visits) => visits.sort((a, b) => {
|
||||
return a[field] > b[field] ? greaterThan : smallerThan;
|
||||
});
|
||||
const calculateVisits = (allVisits, searchTerm, order) => {
|
||||
const filteredVisits = searchTerm ? searchVisits(searchTerm, allVisits) : allVisits;
|
||||
const filteredVisits = searchTerm ? searchVisits(searchTerm, allVisits) : [ ...allVisits ];
|
||||
const sortedVisits = order.dir ? sortVisits(order, filteredVisits) : filteredVisits;
|
||||
const total = sortedVisits.length;
|
||||
const visitsGroups = splitEvery(PAGE_SIZE, sortedVisits);
|
||||
|
||||
return { visitsGroups, total };
|
||||
};
|
||||
const normalizeVisits = map(({ userAgent, date, referer, visitLocation }) => ({
|
||||
date,
|
||||
browser: browserFromUserAgent(userAgent),
|
||||
os: osFromUserAgent(userAgent),
|
||||
referer: extractDomain(referer),
|
||||
country: (visitLocation && visitLocation.countryName) || 'Unknown',
|
||||
city: (visitLocation && visitLocation.cityName) || 'Unknown',
|
||||
}));
|
||||
|
||||
const VisitsTable = ({ visits, onVisitsSelected, isSticky = false, matchMedia = window.matchMedia }) => {
|
||||
const allVisits = normalizeVisits(visits);
|
||||
const VisitsTable = ({
|
||||
visits,
|
||||
selectedVisits = [],
|
||||
setSelectedVisits,
|
||||
isSticky = false,
|
||||
matchMedia = window.matchMedia,
|
||||
}) => {
|
||||
const headerCellsClass = classNames('visits-table__header-cell', {
|
||||
'visits-table__sticky': isSticky,
|
||||
});
|
||||
const matchMobile = () => matchMedia('(max-width: 767px)').matches;
|
||||
|
||||
const [ selectedVisits, setSelectedVisits ] = useState([]);
|
||||
const [ isMobileDevice, setIsMobileDevice ] = useState(matchMobile());
|
||||
const [ searchTerm, setSearchTerm ] = useState(undefined);
|
||||
const [ order, setOrder ] = useState({ field: undefined, dir: undefined });
|
||||
const resultSet = useMemo(() => calculateVisits(allVisits, searchTerm, order), [ searchTerm, order ]);
|
||||
const resultSet = useMemo(() => calculateVisits(visits, searchTerm, order), [ searchTerm, order ]);
|
||||
|
||||
const [ page, setPage ] = useState(1);
|
||||
const end = page * PAGE_SIZE;
|
||||
@@ -76,9 +75,6 @@ const VisitsTable = ({ visits, onVisitsSelected, isSticky = false, matchMedia =
|
||||
/>
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onVisitsSelected && onVisitsSelected(selectedVisits);
|
||||
}, [ selectedVisits ]);
|
||||
useEffect(() => {
|
||||
const listener = () => setIsMobileDevice(matchMobile());
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isEmpty, isNil, memoizeWith, prop } from 'ramda';
|
||||
import { isEmpty, isNil, map } from 'ramda';
|
||||
import { browserFromUserAgent, extractDomain, osFromUserAgent } from '../../utils/helpers/visits';
|
||||
|
||||
const visitLocationHasProperty = (visitLocation, propertyName) =>
|
||||
@@ -51,7 +51,7 @@ const updateCitiesForMapForVisit = (citiesForMapStats, { visitLocation }) => {
|
||||
citiesForMapStats[cityName] = currentCity;
|
||||
};
|
||||
|
||||
export const processStatsFromVisits = memoizeWith(prop('id'), ({ visits }) =>
|
||||
export const processStatsFromVisits = (visits) =>
|
||||
visits.reduce(
|
||||
(stats, visit) => {
|
||||
// We mutate the original object because it has a big side effect when large data sets are processed
|
||||
@@ -65,4 +65,13 @@ export const processStatsFromVisits = memoizeWith(prop('id'), ({ visits }) =>
|
||||
return stats;
|
||||
},
|
||||
{ os: {}, browsers: {}, referrers: {}, countries: {}, cities: {}, citiesForMap: {} }
|
||||
));
|
||||
);
|
||||
|
||||
export const normalizeVisits = map(({ userAgent, date, referer, visitLocation }) => ({
|
||||
date,
|
||||
browser: browserFromUserAgent(userAgent),
|
||||
os: osFromUserAgent(userAgent),
|
||||
referer: extractDomain(referer),
|
||||
country: (visitLocation && visitLocation.countryName) || 'Unknown',
|
||||
city: (visitLocation && visitLocation.cityName) || 'Unknown',
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user