umami/components/metrics/EventsChart.js

97 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-08-27 22:46:05 +02:00
import React, { useState, useEffect, useMemo } from 'react';
2020-08-26 18:58:24 +02:00
import classNames from 'classnames';
2020-08-28 03:44:20 +02:00
import tinycolor from 'tinycolor2';
2020-08-27 12:42:24 +02:00
import BarChart from './BarChart';
import { get } from 'lib/web';
2020-08-27 22:46:05 +02:00
import { getTimezone, getDateArray, getDateLength } from 'lib/date';
2020-08-28 03:44:20 +02:00
import styles from './BarChart.module.css';
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
const COLORS = [
2020-08-28 03:44:20 +02:00
'#2680eb',
'#9256d9',
'#44b556',
'#e68619',
'#e34850',
'#1b959a',
'#d83790',
'#85d044',
2020-08-27 12:42:24 +02:00
];
2020-08-26 18:58:24 +02:00
2020-08-28 03:44:20 +02:00
export default function EventsChart({ websiteId, startDate, endDate, unit }) {
2020-08-27 12:42:24 +02:00
const [data, setData] = useState();
2020-08-27 22:46:05 +02:00
const datasets = useMemo(() => {
if (!data) return [];
2020-08-28 03:44:20 +02:00
return Object.keys(data).map((key, index) => {
const color = tinycolor(COLORS[index]);
return {
label: key,
data: data[key],
lineTension: 0,
backgroundColor: color.setAlpha(0.4).toRgbString(),
borderColor: color.setAlpha(0.5).toRgbString(),
borderWidth: 1,
};
});
2020-08-27 22:46:05 +02:00
}, [data]);
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
async function loadData() {
const data = await get(`/api/website/${websiteId}/events`, {
start_at: +startDate,
end_at: +endDate,
unit,
tz: getTimezone(),
});
2020-08-27 12:42:24 +02:00
const map = data.reduce((obj, { x, t, y }) => {
if (!obj[x]) {
obj[x] = [];
2020-08-26 18:58:24 +02:00
}
2020-08-27 12:42:24 +02:00
obj[x].push({ t, y });
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
return obj;
}, {});
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
Object.keys(map).forEach(key => {
map[key] = getDateArray(map[key], startDate, endDate, unit);
});
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
setData(map);
}
2020-08-26 18:58:24 +02:00
2020-08-28 03:44:20 +02:00
function handleCreate(options) {
const legend = {
position: 'bottom',
};
options.legend = legend;
}
2020-08-27 12:42:24 +02:00
function handleUpdate(chart) {
2020-08-27 22:46:05 +02:00
chart.data.datasets = datasets;
2020-08-26 18:58:24 +02:00
2020-08-27 12:42:24 +02:00
chart.update();
2020-08-26 18:58:24 +02:00
}
useEffect(() => {
2020-08-27 12:42:24 +02:00
loadData();
}, [websiteId, startDate, endDate]);
if (!data) {
return null;
}
2020-08-26 18:58:24 +02:00
return (
2020-08-28 03:44:20 +02:00
<BarChart
chartId={`events-${websiteId}`}
datasets={datasets}
unit={unit}
records={getDateLength(startDate, endDate, unit)}
onCreate={handleCreate}
onUpdate={handleUpdate}
stacked
/>
2020-08-26 18:58:24 +02:00
);
}