2022-12-29 00:43:22 +01:00
|
|
|
import { useMemo, useRef } from 'react';
|
2023-02-18 06:42:42 +01:00
|
|
|
import { format, 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 00:02:48 +02:00
|
|
|
|
2020-10-09 11:56:15 +02:00
|
|
|
function mapData(data) {
|
|
|
|
let last = 0;
|
|
|
|
const arr = [];
|
2020-10-09 00:02:48 +02:00
|
|
|
|
2023-02-23 05:59:59 +01:00
|
|
|
data?.reduce((obj, { timestamp }) => {
|
2023-02-18 06:42:42 +01:00
|
|
|
const t = startOfMinute(new Date(timestamp));
|
2020-10-09 11:56:15 +02:00
|
|
|
if (t.getTime() > last) {
|
2023-04-10 18:44:25 +02:00
|
|
|
obj = { x: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
|
2020-10-09 11:56:15 +02:00
|
|
|
arr.push(obj);
|
2023-02-18 06:42:42 +01:00
|
|
|
last = t.getTime();
|
2020-10-09 11:56:15 +02:00
|
|
|
} else {
|
|
|
|
obj.y += 1;
|
|
|
|
}
|
|
|
|
return obj;
|
|
|
|
}, {});
|
2020-10-09 00:02:48 +02:00
|
|
|
|
2020-10-09 11:56:15 +02:00
|
|
|
return arr;
|
|
|
|
}
|
2020-10-09 00:02:48 +02:00
|
|
|
|
2023-04-21 17:00:42 +02:00
|
|
|
export function RealtimeChart({ data, unit, ...props }) {
|
2020-10-09 20:14:42 +02:00
|
|
|
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(() => {
|
2023-02-18 06:42:42 +01:00
|
|
|
if (!data) {
|
|
|
|
return { pageviews: [], sessions: [] };
|
2020-10-09 11:56:15 +02:00
|
|
|
}
|
2023-02-18 06:42:42 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
pageviews: getDateArray(mapData(data.pageviews), startDate, endDate, unit),
|
2023-02-23 05:59:59 +01:00
|
|
|
sessions: getDateArray(mapData(data.visitors), startDate, endDate, unit),
|
2023-02-18 06:42:42 +01:00
|
|
|
};
|
|
|
|
}, [data, startDate, endDate, unit]);
|
2020-10-09 00:02:48 +02:00
|
|
|
|
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;
|
2023-02-18 06:42:42 +01:00
|
|
|
}, [data, endDate]);
|
2020-10-09 20:14:42 +02:00
|
|
|
|
|
|
|
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
|
|
|
);
|
2020-10-09 00:02:48 +02:00
|
|
|
}
|
2023-04-21 17:00:42 +02:00
|
|
|
|
|
|
|
export default RealtimeChart;
|