umami/components/charts/WebsiteChart.js

91 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-08-02 06:20:52 +02:00
import React, { useState, useEffect, useMemo, useRef } from 'react';
import classNames from 'classnames';
import PageviewsChart from './PageviewsChart';
2020-08-07 11:27:12 +02:00
import CheckVisible from '../helpers/CheckVisible';
2020-07-31 05:11:43 +02:00
import MetricsBar from './MetricsBar';
2020-07-30 10:08:21 +02:00
import QuickButtons from './QuickButtons';
2020-08-07 11:27:12 +02:00
import DateFilter from '../common/DateFilter';
import StickyHeader from '../helpers/StickyHeader';
2020-08-04 03:12:28 +02:00
import { get } from 'lib/web';
import { getDateArray, getDateRange, getTimezone } from 'lib/date';
import styles from './WebsiteChart.module.css';
2020-08-01 04:05:14 +02:00
export default function WebsiteChart({
websiteId,
defaultDateRange = '7day',
stickyHeader = false,
onDataLoad = () => {},
2020-08-01 04:05:14 +02:00
onDateChange = () => {},
}) {
const [data, setData] = useState();
2020-08-01 04:05:14 +02:00
const [dateRange, setDateRange] = useState(getDateRange(defaultDateRange));
2020-07-31 07:40:16 +02:00
const { startDate, endDate, unit, value } = dateRange;
2020-07-30 10:08:21 +02:00
const [pageviews, uniques] = useMemo(() => {
if (data) {
return [
getDateArray(data.pageviews, startDate, endDate, unit),
getDateArray(data.uniques, startDate, endDate, unit),
];
}
return [[], []];
}, [data]);
2020-07-30 10:08:21 +02:00
function handleDateChange(values) {
setDateRange(values);
2020-08-01 04:05:14 +02:00
onDateChange(values);
2020-07-30 10:08:21 +02:00
}
async function loadData() {
const data = await get(`/api/website/${websiteId}/pageviews`, {
start_at: +startDate,
end_at: +endDate,
unit,
tz: getTimezone(),
});
setData(data);
onDataLoad(data);
}
useEffect(() => {
loadData();
}, [websiteId, startDate, endDate, unit]);
return (
2020-08-06 04:04:02 +02:00
<>
<StickyHeader
className={classNames(styles.header, 'row')}
stickyClassName={styles.sticky}
enabled={stickyHeader}
2020-08-02 06:20:52 +02:00
>
<MetricsBar
className="col-12 col-md-9 col-lg-10"
websiteId={websiteId}
startDate={startDate}
endDate={endDate}
/>
<DateFilter
className="col-12 col-md-3 col-lg-2"
value={value}
onChange={handleDateChange}
/>
</StickyHeader>
2020-08-02 06:20:52 +02:00
<div className="row">
<CheckVisible className="col">
2020-08-04 03:12:28 +02:00
{visible => (
<PageviewsChart
websiteId={websiteId}
data={{ pageviews, uniques }}
unit={unit}
animationDuration={visible ? 300 : 0}
>
<QuickButtons value={value} onChange={handleDateChange} />
</PageviewsChart>
)}
</CheckVisible>
2020-07-30 10:08:21 +02:00
</div>
2020-08-06 04:04:02 +02:00
</>
);
}