umami/components/metrics/EventsChart.js

86 lines
2.1 KiB
JavaScript
Raw Normal View History

import React, { useMemo } from 'react';
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 { getDateArray, getDateLength } from 'lib/date';
import useFetch from 'hooks/useFetch';
import useDateRange from 'hooks/useDateRange';
import useTimezone from 'hooks/useTimezone';
2020-10-08 03:24:53 +02:00
import usePageQuery from 'hooks/usePageQuery';
2020-10-11 11:29:55 +02:00
import useShareToken from 'hooks/useShareToken';
import { EVENT_COLORS, TOKEN_HEADER } from 'lib/constants';
2020-08-26 18:58:24 +02:00
2020-10-10 05:37:24 +02:00
export default function EventsChart({ websiteId, className, token }) {
const [dateRange] = useDateRange(websiteId);
2020-09-01 00:02:32 +02:00
const { startDate, endDate, unit, modified } = dateRange;
const [timezone] = useTimezone();
2020-09-26 07:31:18 +02:00
const { query } = usePageQuery();
2020-10-11 11:29:55 +02:00
const shareToken = useShareToken();
2020-08-31 23:11:30 +02:00
const { data } = useFetch(
`/api/website/${websiteId}/events`,
{
2020-10-09 21:39:03 +02:00
params: {
start_at: +startDate,
end_at: +endDate,
unit,
tz: timezone,
url: query.url,
token,
},
2020-10-11 11:29:55 +02:00
headers: { [TOKEN_HEADER]: shareToken?.token },
2020-08-31 23:11:30 +02:00
},
2020-10-09 21:39:03 +02:00
[modified],
2020-08-31 23:11:30 +02:00
);
2020-08-27 22:46:05 +02:00
const datasets = useMemo(() => {
if (!data) return [];
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
return Object.keys(map).map((key, index) => {
2020-10-08 03:24:53 +02:00
const color = tinycolor(EVENT_COLORS[index % EVENT_COLORS.length]);
return {
label: key,
data: map[key],
lineTension: 0,
backgroundColor: color.setAlpha(0.6).toRgbString(),
borderColor: color.setAlpha(0.7).toRgbString(),
borderWidth: 1,
};
});
}, [data]);
2020-08-26 18:58:24 +02:00
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
}
2020-08-27 12:42:24 +02:00
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}`}
2020-10-10 05:37:24 +02:00
className={className}
2020-08-28 03:44:20 +02:00
datasets={datasets}
unit={unit}
records={getDateLength(startDate, endDate, unit)}
onUpdate={handleUpdate}
stacked
/>
2020-08-26 18:58:24 +02:00
);
}