RealtimeLog component.

This commit is contained in:
Mike Cao 2020-10-09 02:56:15 -07:00
parent db9b238585
commit b682e41aff
6 changed files with 163 additions and 123 deletions

View File

@ -3,13 +3,13 @@ import classNames from 'classnames';
import NoData from 'components/common/NoData'; import NoData from 'components/common/NoData';
import styles from './Table.module.css'; import styles from './Table.module.css';
export default function Table({ columns, rows, empty }) { export default function Table({ className, columns, rows, empty }) {
if (empty && rows.length === 0) { if (empty && rows.length === 0) {
return empty; return empty;
} }
return ( return (
<div className={styles.table}> <div className={classNames(styles.table, className)}>
<div className={classNames(styles.header, 'row')}> <div className={classNames(styles.header, 'row')}>
{columns.map(({ key, label, className, style, header }) => ( {columns.map(({ key, label, className, style, header }) => (
<div <div

View File

@ -4,6 +4,7 @@
} }
.header { .header {
display: flex;
border-bottom: 1px solid var(--gray300); border-bottom: 1px solid var(--gray300);
} }

View File

@ -1,80 +1,42 @@
import React from 'react'; import React, { useMemo } from 'react';
import { useIntl } from 'react-intl'; import { format, parseISO, startOfMinute, subMinutes } from 'date-fns';
import tinycolor from 'tinycolor2'; import PageviewsChart from './PageviewsChart';
import BarChart from './BarChart'; import { getDateArray } from 'lib/date';
import useTheme from 'hooks/useTheme';
import { THEME_COLORS } from 'lib/constants';
export default function RealtimeChart({ websiteId, data, unit, records, className, loading }) { function mapData(data) {
const intl = useIntl(); let last = 0;
const [theme] = useTheme(); const arr = [];
const primaryColor = tinycolor(THEME_COLORS[theme].primary);
const colors = {
views: {
background: primaryColor.setAlpha(0.4).toRgbString(),
border: primaryColor.setAlpha(0.5).toRgbString(),
},
visitors: {
background: primaryColor.setAlpha(0.6).toRgbString(),
border: primaryColor.setAlpha(0.7).toRgbString(),
},
};
const handleUpdate = chart => { data.reduce((obj, val) => {
const { const { created_at } = val;
data: { datasets }, const t = startOfMinute(parseISO(created_at));
} = chart; if (t.getTime() > last) {
obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
datasets[0].data = data.uniques; arr.push(obj);
datasets[0].label = intl.formatMessage({ last = t;
id: 'metrics.unique-visitors', } else {
defaultMessage: 'Unique visitors', obj.y += 1;
});
datasets[1].data = data.pageviews;
datasets[1].label = intl.formatMessage({
id: 'metrics.page-views',
defaultMessage: 'Page views',
});
chart.update();
};
if (!data) {
return null;
} }
return obj;
}, {});
return ( return arr;
<BarChart }
className={className}
chartId={`realtime-${websiteId}`} export default function RealtimeChart({ data, ...props }) {
datasets={[ const chartData = useMemo(() => {
{ if (data) {
label: intl.formatMessage({ const endDate = startOfMinute(new Date());
id: 'metrics.unique-visitors', const startDate = subMinutes(endDate, 30);
defaultMessage: 'Unique visitors', const unit = 'minute';
}),
data: data.uniques, return {
lineTension: 0, pageviews: getDateArray(mapData(data.pageviews), startDate, endDate, unit),
backgroundColor: colors.visitors.background, sessions: getDateArray(mapData(data.sessions), startDate, endDate, unit),
borderColor: colors.visitors.border, };
borderWidth: 1, }
}, return { pageviews: [], sessions: [] };
{ }, [data]);
label: intl.formatMessage({
id: 'metrics.page-views', return <PageviewsChart {...props} data={chartData} />;
defaultMessage: 'Page views',
}),
data: data.pageviews,
lineTension: 0,
backgroundColor: colors.views.background,
borderColor: colors.views.border,
borderWidth: 1,
},
]}
unit={unit}
records={records}
onUpdate={handleUpdate}
loading={loading}
/>
);
} }

View File

@ -0,0 +1,95 @@
import React, { useMemo } from 'react';
import { FormattedMessage } from 'react-intl';
import firstBy from 'thenby';
import { format } from 'date-fns';
import Table from 'components/common/Table';
import styles from './RealtimeLog.module.css';
import useLocale from '../../hooks/useLocale';
import useCountryNames from '../../hooks/useCountryNames';
import { BROWSERS } from '../../lib/constants';
export default function RealtimeLog({ data, websites }) {
const [locale] = useLocale();
const countryNames = useCountryNames(locale);
const logs = useMemo(() => {
const { pageviews, sessions, events } = data;
return [...pageviews, ...sessions, ...events].sort(firstBy('created_at', -1));
}, [data]);
const columns = [
{
key: 'time',
label: <FormattedMessage id="label.type" defaultMessage="Time" />,
className: 'col',
render: ({ created_at }) => format(new Date(created_at), 'H:mm:ss'),
},
{
key: 'website',
label: <FormattedMessage id="label.website" defaultMessage="Website" />,
className: 'col',
render: getWebsite,
},
{
key: 'type',
label: <FormattedMessage id="label.type" defaultMessage="Type" />,
className: 'col',
render: getType,
},
{
key: 'type',
className: 'col',
render: getDescription,
},
];
function getType({ view_id, session_id, event_id }) {
if (event_id) {
return <FormattedMessage id="label.event" defaultMessage="Event" />;
}
if (view_id) {
return <FormattedMessage id="label.pageview" defaultMessage="Pageview" />;
}
if (session_id) {
return <FormattedMessage id="label.visitor" defaultMessage="Visitor" />;
}
return null;
}
function getWebsite({ website_id }) {
return websites.find(n => n.website_id === website_id)?.name;
}
function getDescription({
event_type,
event_value,
view_id,
session_id,
url,
browser,
os,
country,
device,
}) {
if (event_type) {
return `${event_type}:${event_value}`;
}
if (view_id) {
return url;
}
if (session_id) {
return (
<FormattedMessage
id="message.log.visitor"
defaultMessage="A visitor from {country} using {browser} on {os} {device}"
values={{ country: countryNames[country], browser: BROWSERS[browser], os, device }}
/>
);
}
}
return (
<div className={styles.log}>
<Table className={styles.table} columns={columns} rows={logs} />
</div>
);
}

View File

@ -0,0 +1,8 @@
.table {
font-size: var(--font-size-small);
}
.row {
display: flex;
border-bottom: 1px solid var(--gray300);
}

View File

@ -1,37 +1,20 @@
import React, { useState, useEffect, useMemo } from 'react'; import React, { useState, useEffect } from 'react';
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
import { subMinutes, startOfMinute, parseISO, format } from 'date-fns'; import { subMinutes, startOfMinute } from 'date-fns';
import Page from 'components/layout/Page'; import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader'; import PageHeader from 'components/layout/PageHeader';
import DropDown from 'components/common/DropDown'; import DropDown from 'components/common/DropDown';
import useFetch from 'hooks/useFetch'; import useFetch from 'hooks/useFetch';
import PageviewsChart from '../metrics/PageviewsChart'; import RealtimeChart from '../metrics/RealtimeChart';
import { getDateArray } from '../../lib/date'; import RealtimeLog from '../metrics/RealtimeLog';
const REALTIME_RANGE = 30;
const REALTIME_INTERVAL = 5000;
function filterTime(data, time) { function filterTime(data, time) {
return data.filter(({ created_at }) => new Date(created_at).getTime() >= time); return data.filter(({ created_at }) => new Date(created_at).getTime() >= time);
} }
function mapData(data) {
let last = 0;
const arr = [];
data.reduce((obj, val) => {
const { created_at } = val;
const t = startOfMinute(parseISO(created_at));
if (t.getTime() > last) {
obj = { t: format(t, 'yyyy-LL-dd HH:mm:00'), y: 1 };
arr.push(obj);
last = t;
} else {
obj.y += 1;
}
return obj;
}, {});
return arr;
}
export default function RealtimeDashboard() { export default function RealtimeDashboard() {
const [data, setData] = useState(); const [data, setData] = useState();
const [website, setWebsite] = useState(); const [website, setWebsite] = useState();
@ -42,39 +25,25 @@ export default function RealtimeDashboard() {
{ type: 'update', start_at: lastTime }, { type: 'update', start_at: lastTime },
{ {
disabled: !init?.token, disabled: !init?.token,
interval: 5000, interval: REALTIME_INTERVAL,
headers: { 'x-umami-token': init?.token }, headers: { 'x-umami-token': init?.token },
}, },
); );
const chartData = useMemo(() => {
if (data) {
const endDate = startOfMinute(new Date());
const startDate = subMinutes(endDate, 30);
const unit = 'minute';
return {
pageviews: getDateArray(mapData(data.pageviews), startDate, endDate, unit),
sessions: getDateArray(mapData(data.sessions), startDate, endDate, unit),
};
}
return { pageviews: [], sessions: [] };
}, [data]);
useEffect(() => { useEffect(() => {
if (init && !data) { if (init && !data) {
setData(init.data); setData(init.data);
} else if (updates) { } else if (updates) {
const { pageviews, sessions, events } = updates; const { pageviews, sessions, events } = updates;
const minTime = subMinutes(startOfMinute(new Date()), 30).getTime(); const minTime = subMinutes(startOfMinute(new Date()), REALTIME_RANGE).getTime();
setData(state => ({ setData(state => ({
pageviews: filterTime(state.pageviews, minTime).concat(filterTime(pageviews, lastTime)), pageviews: filterTime(state.pageviews.concat(pageviews), minTime),
sessions: filterTime(state.sessions, minTime).concat(filterTime(sessions, lastTime)), sessions: filterTime(state.sessions.concat(sessions), minTime),
events: filterTime(state.events, minTime).concat(filterTime(events, lastTime)), events: filterTime(state.events.concat(events), minTime),
})); }));
} }
setLastTime(Date.now()); setLastTime(Date.now());
}, [updates, init]); }, [init, updates]);
if (!init || loading || !data) { if (!init || loading || !data) {
return null; return null;
@ -99,7 +68,12 @@ export default function RealtimeDashboard() {
</div> </div>
<DropDown value={selectedValue} options={options} onChange={handleSelect} /> <DropDown value={selectedValue} options={options} onChange={handleSelect} />
</PageHeader> </PageHeader>
<PageviewsChart websiteId={website?.website_id} data={chartData} unit="minute" records={30} /> <RealtimeChart websiteId={website?.website_id} data={data} unit="minute" records={30} />
<div className="row">
<div className="col-12">
<RealtimeLog data={data} websites={websites} />
</div>
</div>
</Page> </Page>
); );
} }