umami/components/PageviewsChart.js

85 lines
1.9 KiB
JavaScript
Raw Normal View History

import React, { useRef, useEffect, useMemo } from 'react';
2020-07-26 09:12:42 +02:00
import ChartJS from 'chart.js';
import { getLocalTime } from 'lib/date';
2020-07-26 09:12:42 +02:00
export default function PageviewsChart({ data }) {
2020-07-26 09:12:42 +02:00
const canvas = useRef();
const chart = useRef();
const pageviews = useMemo(() => {
2020-07-26 09:12:42 +02:00
if (data) {
2020-07-28 08:52:14 +02:00
return data.pageviews.map(({ t, y }) => ({ t: getLocalTime(t), y }));
2020-07-26 09:12:42 +02:00
}
return [];
2020-07-26 09:12:42 +02:00
}, [data]);
function draw() {
if (!canvas.current) return;
if (!chart.current) {
2020-07-26 09:12:42 +02:00
chart.current = new ChartJS(canvas.current, {
type: 'bar',
data: {
datasets: [
{
label: 'page views',
data: pageviews,
2020-07-26 09:12:42 +02:00
lineTension: 0,
2020-07-28 08:52:14 +02:00
backgroundColor: 'rgb(38, 128, 235, 0.1)',
borderColor: 'rgb(13, 102, 208, 0.2)',
borderWidth: 1,
2020-07-26 09:12:42 +02:00
},
],
},
options: {
animation: {
duration: 300,
},
tooltips: {
intersect: false,
},
hover: {
animationDuration: 0,
},
scales: {
xAxes: [
{
type: 'time',
distribution: 'series',
2020-07-28 08:52:14 +02:00
offset: true,
2020-07-26 09:12:42 +02:00
time: {
displayFormats: {
2020-07-28 08:52:14 +02:00
day: 'ddd M/DD',
2020-07-26 09:12:42 +02:00
},
tooltipFormat: 'ddd M/DD hA',
},
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
} else {
chart.current.data.datasets[0].data = pageviews;
chart.current.update();
2020-07-26 09:12:42 +02:00
}
}
useEffect(() => {
if (data) {
2020-07-26 09:12:42 +02:00
draw();
}
}, [data]);
2020-07-26 09:12:42 +02:00
return (
<div>
<canvas ref={canvas} width={960} height={400} />
</div>
);
}