umami/components/metrics/PageviewsChart.js

106 lines
2.6 KiB
JavaScript
Raw Normal View History

import { useCallback, useMemo } from 'react';
import { StatusLight } from 'react-basics';
2020-08-26 18:58:24 +02:00
import BarChart from './BarChart';
2023-03-22 22:05:55 +01:00
import useTheme from 'hooks/useTheme';
import useMessages from 'hooks/useMessages';
2023-04-19 20:41:31 +02:00
import useLocale from 'hooks/useLocale';
import { dateFormat } from 'lib/date';
import { formatLongNumber } from 'lib/format';
2020-07-26 09:12:42 +02:00
export function PageviewsChart({ websiteId, data, unit, className, loading, ...props }) {
2023-03-22 22:05:55 +01:00
const { formatMessage, labels } = useMessages();
const { colors } = useTheme();
2023-04-19 20:41:31 +02:00
const { locale } = useLocale();
const renderXLabel = useCallback(
(label, index, values) => {
const d = new Date(values[index].value);
switch (unit) {
case 'minute':
return dateFormat(d, 'h:mm', locale);
case 'hour':
return dateFormat(d, 'p', locale);
case 'day':
return dateFormat(d, 'MMM d', locale);
case 'month':
return dateFormat(d, 'MMM', locale);
case 'year':
return dateFormat(d, 'YYY', locale);
default:
return label;
}
},
[locale, unit],
);
const renderTooltip = useCallback(
(setTooltip, model) => {
const { opacity, labelColors, dataPoints } = model.tooltip;
if (!dataPoints?.length || !opacity) {
setTooltip(null);
return;
}
const formats = {
millisecond: 'T',
second: 'pp',
minute: 'p',
hour: 'h:mm aaa - PP',
day: 'PPPP',
week: 'PPPP',
month: 'LLLL yyyy',
quarter: 'qqq',
year: 'yyyy',
};
setTooltip(
<>
<div>{dateFormat(new Date(dataPoints[0].raw.x), formats[unit], locale)}</div>
<div>
<StatusLight color={labelColors?.[0]?.backgroundColor}>
{formatLongNumber(dataPoints[0].raw.y)} {dataPoints[0].dataset.label}
</StatusLight>
</div>
</>,
);
},
[unit],
);
2020-09-06 02:27:01 +02:00
2023-03-26 13:15:08 +02:00
const datasets = useMemo(() => {
if (!data) return [];
2020-07-29 06:50:29 +02:00
2023-03-26 13:15:08 +02:00
return [
{
label: formatMessage(labels.uniqueVisitors),
data: data.sessions,
borderWidth: 1,
...colors.chart.visitors,
2023-03-26 13:15:08 +02:00
},
{
label: formatMessage(labels.pageViews),
data: data.pageviews,
borderWidth: 1,
...colors.chart.views,
2023-03-26 13:15:08 +02:00
},
];
2023-04-19 20:41:31 +02:00
}, [data, locale, colors]);
2020-07-26 09:12:42 +02:00
return (
2023-04-03 12:12:12 +02:00
<BarChart
{...props}
key={websiteId}
className={className}
datasets={datasets}
unit={unit}
loading={loading}
renderXLabel={renderXLabel}
renderTooltip={renderTooltip}
2023-04-03 12:12:12 +02:00
/>
2020-07-26 09:12:42 +02:00
);
}
2023-04-21 17:00:42 +02:00
export default PageviewsChart;