umami/components/charts/MetricsBar.js

49 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-07-29 09:16:02 +02:00
import React, { useState, useEffect } from 'react';
2020-08-02 06:20:52 +02:00
import classNames from 'classnames';
import MetricCard from './MetricCard';
2020-08-02 06:20:52 +02:00
import { get } from 'lib/web';
2020-08-19 23:35:38 +02:00
import { formatShortTime, formatNumber, formatLongNumber } from 'lib/format';
2020-07-31 05:11:43 +02:00
import styles from './MetricsBar.module.css';
2020-08-02 06:20:52 +02:00
export default function MetricsBar({ websiteId, startDate, endDate, className }) {
2020-07-29 09:16:02 +02:00
const [data, setData] = useState({});
2020-08-19 23:35:38 +02:00
const [format, setFormat] = useState(true);
const { pageviews, uniques, bounces, totaltime } = data;
2020-07-29 09:16:02 +02:00
2020-08-19 23:35:38 +02:00
const formatFunc = format ? formatLongNumber : formatNumber;
2020-07-29 09:16:02 +02:00
async function loadData() {
setData(
2020-07-31 05:11:43 +02:00
await get(`/api/website/${websiteId}/metrics`, {
2020-07-29 09:16:02 +02:00
start_at: +startDate,
end_at: +endDate,
}),
);
}
2020-08-19 23:35:38 +02:00
function handleSetFormat() {
setFormat(state => !state);
}
2020-07-29 09:16:02 +02:00
useEffect(() => {
loadData();
2020-08-02 06:20:52 +02:00
}, [websiteId, startDate, endDate]);
return (
2020-08-19 23:35:38 +02:00
<div className={classNames(styles.bar, className)} onClick={handleSetFormat}>
<MetricCard label="Views" value={pageviews} format={formatFunc} />
<MetricCard label="Visitors" value={uniques} format={formatFunc} />
2020-07-30 05:09:41 +02:00
<MetricCard
label="Bounce rate"
value={uniques ? (bounces / uniques) * 100 : 0}
format={n => Number(n).toFixed(0) + '%'}
/>
<MetricCard
label="Average visit time"
value={totaltime && pageviews ? totaltime / (pageviews - bounces) : 0}
format={n => formatShortTime(n, ['m', 's'], ' ')}
/>
</div>
);
}