umami/components/metrics/MetricsBar.js

56 lines
1.7 KiB
JavaScript
Raw Normal View History

import React, { useState } from 'react';
2020-08-02 06:20:52 +02:00
import classNames from 'classnames';
import MetricCard from './MetricCard';
import Loading from 'components/common/Loading';
import useFetch from 'hooks/useFetch';
import { formatShortTime, formatNumber, formatLongNumber } from 'lib/format';
2020-07-31 05:11:43 +02:00
import styles from './MetricsBar.module.css';
2020-09-01 00:02:32 +02:00
import { useDateRange } from '../../hooks/useDateRange';
2020-09-01 00:02:32 +02:00
export default function MetricsBar({ websiteId, className }) {
const dateRange = useDateRange(websiteId);
const { startDate, endDate, modified } = dateRange;
2020-08-31 23:11:30 +02:00
const { data } = useFetch(
`/api/website/${websiteId}/metrics`,
{
start_at: +startDate,
end_at: +endDate,
},
{
update: [modified],
},
);
2020-08-19 23:35:38 +02:00
const [format, setFormat] = useState(true);
2020-07-29 09:16:02 +02:00
2020-08-19 23:35:38 +02:00
const formatFunc = format ? formatLongNumber : formatNumber;
function handleSetFormat() {
setFormat(state => !state);
}
const { pageviews, uniques, bounces, totaltime } = data || {};
return (
2020-08-19 23:35:38 +02:00
<div className={classNames(styles.bar, className)} onClick={handleSetFormat}>
{!data ? (
<Loading />
) : (
<>
<MetricCard label="Views" value={pageviews} format={formatFunc} />
<MetricCard label="Visitors" value={uniques} format={formatFunc} />
<MetricCard
label="Bounce rate"
value={pageviews ? (bounces / pageviews) * 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>
);
}