umami/components/metrics/RealtimeChart.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useMemo, useRef } from 'react';
2020-10-09 20:14:42 +02:00
import { format, parseISO, startOfMinute, subMinutes, isBefore } from 'date-fns';
2020-10-09 11:56:15 +02:00
import PageviewsChart from './PageviewsChart';
import { getDateArray } from 'lib/date';
2020-10-13 01:31:51 +02:00
import { DEFAULT_ANIMATION_DURATION, REALTIME_RANGE } from 'lib/constants';
2020-10-09 11:56:15 +02:00
function mapData(data) {
let last = 0;
const arr = [];
2020-10-09 11:56:15 +02:00
data.reduce((obj, val) => {
const { createdAt } = val;
const t = startOfMinute(parseISO(createdAt));
2020-10-09 11:56:15 +02:00
if (t.getTime() > last) {
obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
arr.push(obj);
last = t;
} else {
obj.y += 1;
}
return obj;
}, {});
2020-10-09 11:56:15 +02:00
return arr;
}
2020-10-09 20:14:42 +02:00
export default function RealtimeChart({ data, unit, ...props }) {
const endDate = startOfMinute(new Date());
2020-10-13 01:31:51 +02:00
const startDate = subMinutes(endDate, REALTIME_RANGE);
2020-10-09 20:14:42 +02:00
const prevEndDate = useRef(endDate);
2020-10-09 11:56:15 +02:00
const chartData = useMemo(() => {
if (data) {
return {
pageviews: getDateArray(mapData(data.pageviews), startDate, endDate, unit),
sessions: getDateArray(mapData(data.sessions), startDate, endDate, unit),
};
}
return { pageviews: [], sessions: [] };
}, [data]);
2020-10-09 20:14:42 +02:00
// Don't animate the bars shifting over because it looks weird
const animationDuration = useMemo(() => {
if (isBefore(prevEndDate.current, endDate)) {
prevEndDate.current = endDate;
return 0;
}
2020-10-09 21:39:03 +02:00
return DEFAULT_ANIMATION_DURATION;
2020-10-09 20:14:42 +02:00
}, [data]);
return (
2020-10-10 02:58:27 +02:00
<PageviewsChart
{...props}
2020-10-13 01:31:51 +02:00
height={200}
2020-10-10 02:58:27 +02:00
unit={unit}
data={chartData}
animationDuration={animationDuration}
/>
2020-10-09 20:14:42 +02:00
);
}