umami/components/WebsiteChart.js

92 lines
2.5 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-04 03:12:28 +02:00
import CheckVisible from './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-07-31 05:11:43 +02:00
import DateFilter from './DateFilter';
2020-08-02 06:20:52 +02:00
import useSticky from './hooks/useSticky';
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',
2020-08-02 06:20:52 +02:00
stickHeader = false,
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-08-02 06:20:52 +02:00
const [ref, sticky] = useSticky(stickHeader);
2020-08-04 03:12:28 +02:00
const container = useRef();
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() {
setData(
await get(`/api/website/${websiteId}/pageviews`, {
start_at: +startDate,
end_at: +endDate,
unit,
tz: getTimezone(),
}),
);
}
useEffect(() => {
loadData();
}, [websiteId, startDate, endDate, unit]);
return (
2020-08-04 03:12:28 +02:00
<div ref={container}>
2020-08-02 06:20:52 +02:00
<div
ref={ref}
className={classNames(styles.header, 'row', { [styles.sticky]: sticky })}
2020-08-04 03:12:28 +02:00
style={{ width: sticky ? container.current.clientWidth : 'auto' }}
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}
/>
</div>
<div className="row">
2020-08-04 03:12:28 +02:00
<CheckVisible>
{visible => (
<PageviewsChart
className="col"
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-04 03:12:28 +02:00
</div>
);
}