umami/components/PageviewsChart.js

92 lines
2.1 KiB
JavaScript
Raw Normal View History

import React, { useRef, useEffect } from 'react';
2020-07-26 09:12:42 +02:00
import ChartJS from 'chart.js';
export default function PageviewsChart({ data }) {
2020-07-26 09:12:42 +02:00
const canvas = useRef();
const chart = useRef();
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: 'unique visitors',
data: data.uniques,
lineTension: 0,
backgroundColor: 'rgb(146, 86, 217, 0.2)',
borderColor: 'rgb(122, 66, 191, 0.3)',
borderWidth: 1,
},
2020-07-26 09:12:42 +02:00
{
label: 'page views',
data: data.pageviews,
2020-07-26 09:12:42 +02:00
lineTension: 0,
backgroundColor: 'rgb(38, 128, 235, 0.2)',
borderColor: 'rgb(13, 102, 208, 0.3)',
2020-07-28 08:52:14 +02:00
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',
},
gridLines: {
display: false,
},
stacked: true,
2020-07-26 09:12:42 +02:00
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
stacked: true,
2020-07-26 09:12:42 +02:00
},
],
},
},
});
} else {
chart.current.data.datasets[0].data = data.uniques;
chart.current.data.datasets[1].data = 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>
);
}