umami/components/pages/realtime/RealtimeUrls.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

2023-02-15 11:27:18 +01:00
import { useMemo, useState } from 'react';
import { ButtonGroup, Button, Flexbox } from 'react-basics';
2020-10-13 01:31:51 +02:00
import firstBy from 'thenby';
import { percentFilter } from 'lib/filters';
import DataTable from 'components/metrics/DataTable';
import { FILTER_PAGES, FILTER_REFERRERS } from 'lib/constants';
2023-03-22 22:05:55 +01:00
import useMessages from 'hooks/useMessages';
2020-10-13 01:31:51 +02:00
2023-02-15 11:27:18 +01:00
export default function RealtimeUrls({ websiteDomain, data = {} }) {
2023-03-22 22:05:55 +01:00
const { formatMessage, labels } = useMessages();
2020-10-13 01:31:51 +02:00
const { pageviews } = data;
const [filter, setFilter] = useState(FILTER_REFERRERS);
const buttons = [
{
label: formatMessage(labels.referrers),
key: FILTER_REFERRERS,
2020-10-13 01:31:51 +02:00
},
{
label: formatMessage(labels.pages),
key: FILTER_PAGES,
2020-10-13 01:31:51 +02:00
},
];
2020-11-07 02:39:25 +01:00
const renderLink = ({ x }) => {
2023-02-15 11:27:18 +01:00
const domain = x.startsWith('/') ? websiteDomain : '';
2020-11-07 02:39:25 +01:00
return (
<a href={`//${domain}${x}`} target="_blank" rel="noreferrer noopener">
{x}
</a>
);
};
const [referrers = [], pages = []] = useMemo(() => {
2020-10-13 01:31:51 +02:00
if (pageviews) {
const referrers = percentFilter(
pageviews
.reduce((arr, { referrer }) => {
if (referrer?.startsWith('http')) {
const hostname = new URL(referrer).hostname.replace(/^www\./, '');
2023-02-15 11:27:18 +01:00
if (hostname) {
2020-10-13 01:31:51 +02:00
const row = arr.find(({ x }) => x === hostname);
if (!row) {
arr.push({ x: hostname, y: 1 });
} else {
row.y += 1;
}
}
}
return arr;
}, [])
.sort(firstBy('y', -1)),
);
const pages = percentFilter(
pageviews
2023-02-15 11:27:18 +01:00
.reduce((arr, { url }) => {
2020-10-13 01:31:51 +02:00
if (url?.startsWith('/')) {
const row = arr.find(({ x }) => x === url);
if (!row) {
arr.push({ x: url, y: 1 });
} else {
row.y += 1;
}
}
return arr;
}, [])
.sort(firstBy('y', -1)),
);
return [referrers, pages];
}
2020-10-13 01:31:51 +02:00
return [];
}, [pageviews]);
return (
<>
2023-02-15 11:27:18 +01:00
<Flexbox justifyContent="center">
<ButtonGroup items={buttons} selectedKey={filter} onSelect={setFilter}>
{({ key, label }) => <Button key={key}>{label}</Button>}
</ButtonGroup>
</Flexbox>
2020-10-13 01:31:51 +02:00
{filter === FILTER_REFERRERS && (
<DataTable
title={formatMessage(labels.referrers)}
metric={formatMessage(labels.views)}
2022-03-02 04:41:37 +01:00
renderLabel={renderLink}
2020-10-13 01:31:51 +02:00
data={referrers}
/>
)}
{filter === FILTER_PAGES && (
<DataTable
title={formatMessage(labels.pages)}
metric={formatMessage(labels.views)}
2020-11-07 02:39:25 +01:00
renderLabel={renderLink}
2020-10-13 01:31:51 +02:00
data={pages}
/>
)}
</>
);
}