Skip to content

Commit

Permalink
More updates to realtime.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Feb 15, 2023
1 parent 28921a7 commit 93b7767
Show file tree
Hide file tree
Showing 28 changed files with 215 additions and 260 deletions.
File renamed without changes.
28 changes: 28 additions & 0 deletions components/input/WebsiteSelect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useIntl } from 'react-intl';
import { Dropdown, Item } from 'react-basics';
import { labels } from 'components/messages';
import useApi from 'hooks/useApi';

export default function WebsiteSelect({ websiteId, onSelect }) {
const { formatMessage } = useIntl();
const { get, useQuery } = useApi();
const { data } = useQuery(['websites:me'], () => get('/me/websites'));

const renderValue = value => {
return data?.find(({ id }) => id === value)?.name;
};

return (
<Dropdown
items={data}
value={websiteId}
renderValue={renderValue}
onChange={onSelect}
alignment="end"
placeholder={formatMessage(labels.selectWebsite)}
style={{ width: 200 }}
>
{item => <Item key={item.id}>{item.name}</Item>}
</Dropdown>
);
}
4 changes: 2 additions & 2 deletions components/layout/PageHeader.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
.title {
display: flex;
align-items: center;
font-size: 18px;
font-weight: bold;
font-size: 24px;
font-weight: 700;
gap: 20px;
}
1 change: 1 addition & 0 deletions components/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export const labels = defineMessages({
selectWebsite: { id: 'label.select-website', defaultMessage: 'Select website' },
all: { id: 'label.all', defaultMessage: 'All' },
sessions: { id: 'label.sessions', defaultMessage: 'Sessions' },
pageNotFound: { id: 'message.page-not-found', defaultMessage: 'Page not found' },
});

export const messages = defineMessages({
Expand Down
2 changes: 1 addition & 1 deletion components/metrics/DataTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { formatNumber, formatLongNumber } from 'lib/format';
import styles from './DataTable.module.css';

export default function DataTable({
data,
data = [],
title,
metric,
className,
Expand Down
2 changes: 1 addition & 1 deletion components/metrics/EventDataForm.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation } from '@tanstack/react-query';
import classNames from 'classnames';
import DateFilter from 'components/common/DateFilter';
import DateFilter from 'components/input/DateFilter';
import DataTable from 'components/metrics/DataTable';
import FilterTags from 'components/metrics/FilterTags';
import useApi from 'hooks/useApi';
Expand Down
2 changes: 1 addition & 1 deletion components/metrics/WebsiteChart.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Link from 'next/link';
import PageviewsChart from './PageviewsChart';
import MetricsBar from './MetricsBar';
import WebsiteHeader from './WebsiteHeader';
import DateFilter from 'components/common/DateFilter';
import DateFilter from 'components/input/DateFilter';
import StickyHeader from 'components/helpers/StickyHeader';
import ErrorMessage from 'components/common/ErrorMessage';
import FilterTags from 'components/metrics/FilterTags';
Expand Down
13 changes: 3 additions & 10 deletions components/pages/console/TestConsole.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader';
import EventsChart from 'components/metrics/EventsChart';
import WebsiteChart from 'components/metrics/WebsiteChart';
import WebsiteSelect from 'components/input/WebsiteSelect';
import useApi from 'hooks/useApi';
import styles from './TestConsole.module.css';

export default function TestConsole() {
const { get, useQuery } = useApi();
const { data, isLoading, error } = useQuery(['websites:test-console'], () => get('/websites'));
const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));
const router = useRouter();
const {
basePath,
Expand Down Expand Up @@ -50,15 +51,7 @@ export default function TestConsole() {
)}
</Head>
<PageHeader title="Test console">
<Dropdown
items={data}
renderValue={() => website?.name || 'Select website'}
value={website?.id}
onChange={handleChange}
style={{ width: 300 }}
>
{({ id, name }) => <Item key={id}>{name}</Item>}
</Dropdown>
<WebsiteSelect websiteId={website?.id} onSelect={handleChange} />
</PageHeader>
{website && (
<>
Expand Down
135 changes: 53 additions & 82 deletions components/pages/realtime/RealtimeDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,38 @@ import Page from 'components/layout/Page';
import RealtimeChart from 'components/metrics/RealtimeChart';
import RealtimeLog from 'components/pages/realtime/RealtimeLog';
import RealtimeHeader from 'components/pages/realtime/RealtimeHeader';
import StickyHeader from 'components/helpers/StickyHeader';
import PageHeader from 'components/layout/PageHeader';
import WorldMap from 'components/common/WorldMap';
import DataTable from 'components/metrics/DataTable';
import RealtimeViews from 'components/pages/realtime/RealtimeViews';
import RealtimeUrls from 'components/pages/realtime/RealtimeUrls';
import useApi from 'hooks/useApi';
import useLocale from 'hooks/useLocale';
import useCountryNames from 'hooks/useCountryNames';
import { percentFilter } from 'lib/filters';
import { labels } from 'components/messages';
import { SHARE_TOKEN_HEADER, REALTIME_RANGE, REALTIME_INTERVAL } from 'lib/constants';
import { REALTIME_RANGE, REALTIME_INTERVAL } from 'lib/constants';
import styles from './RealtimeDashboard.module.css';
import StickyHeader from 'components/helpers/StickyHeader';
import PageHeader from 'components/layout/PageHeader';
import ActiveUsers from 'components/metrics/ActiveUsers';
import WebsiteSelect from '../../input/WebsiteSelect';
import { useRouter } from 'next/router';

function mergeData(state, data, time) {
function mergeData(state = [], data, time) {
const ids = state.map(({ __id }) => __id);
return state
.concat(data.filter(({ __id }) => !ids.includes(__id)))
.filter(({ createdAt }) => new Date(createdAt).getTime() >= time);
}

function filterWebsite(data, id) {
return data.filter(({ websiteId }) => websiteId === id);
}

export default function RealtimeDashboard() {
export default function RealtimeDashboard({ websiteId }) {
const { formatMessage } = useIntl();
const { locale } = useLocale();
const router = useRouter();
const countryNames = useCountryNames(locale);
const [data, setData] = useState();
const [websiteId, setWebsiteId] = useState();
const [currentData, setCurrentData] = useState();
const { get, useQuery } = useApi();
const { data: websites, isLoading } = useQuery(['websites:me'], () => get('/me/websites'));

const { data: updates } = useQuery(
['realtime:updates'],
() => get('/realtime/update', { startAt: data?.timestamp }),
const { data, isLoading, error } = useQuery(
['realtime', websiteId],
() => get(`/realtime/${websiteId}`, { startAt: currentData?.timestamp }),
{
enabled: !!websiteId,
retryInterval: REALTIME_INTERVAL,
Expand All @@ -55,104 +50,80 @@ export default function RealtimeDashboard() {
[countryNames],
);

const realtimeData = useMemo(() => {
useEffect(() => {
if (data) {
const { pageviews, sessions, events } = data;
const { pageviews, sessions, events, timestamp } = data;
const time = subMinutes(startOfMinute(new Date()), REALTIME_RANGE).getTime();

if (websiteId) {
const { id } = websites.find(n => n.id === websiteId);
return {
pageviews: filterWebsite(pageviews, id),
sessions: filterWebsite(sessions, id),
events: filterWebsite(events, id),
};
}
setCurrentData(state => ({
...state,
pageviews: mergeData(state?.pageviews, pageviews, time),
sessions: mergeData(state?.sessions, sessions, time),
events: mergeData(state?.events, events, time),
timestamp,
}));
}
}, [data]);

return data;
}, [data, websiteId]);

const count = useMemo(() => {
if (data) {
const { sessions } = data;
return sessions.filter(
({ createdAt }) => differenceInMinutes(new Date(), new Date(createdAt)) <= 5,
).length;
const realtimeData = useMemo(() => {
if (!currentData) {
return { pageviews: [], sessions: [], events: [], countries: [] };
}
}, [data, websiteId]);

const countries = useMemo(() => {
if (realtimeData?.sessions) {
return percentFilter(
realtimeData.sessions
.reduce((arr, { country }) => {
if (country) {
const row = arr.find(({ x }) => x === country);
currentData.countries = percentFilter(
currentData.sessions
.reduce((arr, { country }) => {
if (country) {
const row = arr.find(({ x }) => x === country);

if (!row) {
arr.push({ x: country, y: 1 });
} else {
row.y += 1;
}
if (!row) {
arr.push({ x: country, y: 1 });
} else {
row.y += 1;
}
return arr;
}, [])
.sort(firstBy('y', -1)),
);
}
return [];
}, [realtimeData?.sessions]);
}
return arr;
}, [])
.sort(firstBy('y', -1)),
);

useEffect(() => {
if (updates) {
const { pageviews, sessions, events, timestamp } = updates;
const time = subMinutes(startOfMinute(new Date()), REALTIME_RANGE).getTime();
return currentData;
}, [currentData]);

setData(state => ({
...state,
pageviews: mergeData(state.pageviews, pageviews, time),
sessions: mergeData(state.sessions, sessions, time),
events: mergeData(state.events, events, time),
timestamp,
}));
}
}, [updates]);
const handleSelect = id => {
router.push(`/realtime/${id}`);
};

return (
<Page loading={isLoading || !websites}>
<Page loading={isLoading} error={error}>
<PageHeader title={formatMessage(labels.realtime)}>
<ActiveUsers value={count} />
<WebsiteSelect websiteId={websiteId} onSelect={handleSelect} />
</PageHeader>
<StickyHeader stickyClassName={styles.sticky}>
<RealtimeHeader
websites={websites}
websiteId={websiteId}
data={{ ...realtimeData, countries }}
onSelect={setWebsiteId}
/>
<RealtimeHeader websiteId={websiteId} data={currentData} />
</StickyHeader>
<div className={styles.chart}>
<RealtimeChart data={realtimeData} unit="minute" records={REALTIME_RANGE} />
</div>
<GridRow>
<GridColumn xs={12} sm={12} md={12} lg={4} xl={4}>
<RealtimeViews websiteId={websiteId} data={realtimeData} websites={websites} />
<RealtimeUrls websiteId={websiteId} data={realtimeData} />
</GridColumn>
<GridColumn xs={12} sm={12} md={12} lg={8} xl={8}>
<RealtimeLog websiteId={websiteId} data={realtimeData} websites={websites} />
<RealtimeLog websiteId={websiteId} data={realtimeData} />
</GridColumn>
</GridRow>
<GridRow>
<GridColumn xs={12} lg={4}>
<DataTable
title={formatMessage(labels.countries)}
metric={formatMessage(labels.visitors)}
data={countries}
data={realtimeData?.countries}
renderLabel={renderCountryName}
/>
</GridColumn>
<GridColumn xs={12} lg={8}>
<WorldMap data={countries} />
<WorldMap data={realtimeData?.countries} />
</GridColumn>
</GridRow>
</Page>
Expand Down
20 changes: 2 additions & 18 deletions components/pages/realtime/RealtimeHeader.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { useIntl } from 'react-intl';
import { Dropdown, Item } from 'react-basics';
import MetricCard from 'components/metrics/MetricCard';
import { labels } from 'components/messages';
import styles from './RealtimeHeader.module.css';

export default function RealtimeHeader({ data, websiteId, websites, onSelect }) {
export default function RealtimeHeader({ data = {} }) {
const { formatMessage } = useIntl();

const { pageviews, sessions, events, countries } = data;

const renderValue = value => {
return websites?.find(({ id }) => id === value)?.name;
};

return (
<div className={styles.header}>
<div className={styles.metrics}>
Expand All @@ -25,20 +19,10 @@ export default function RealtimeHeader({ data, websiteId, websites, onSelect })
<MetricCard label={formatMessage(labels.events)} value={events?.length} hideComparison />
<MetricCard
label={formatMessage(labels.countries)}
value={countries.length}
value={countries?.length}
hideComparison
/>
</div>
<Dropdown
items={websites}
value={websiteId}
renderValue={renderValue}
onChange={onSelect}
alignment="end"
placeholder={formatMessage(labels.selectWebsite)}
>
{item => <Item key={item.id}>{item.name}</Item>}
</Dropdown>
</div>
);
}
28 changes: 28 additions & 0 deletions components/pages/realtime/RealtimeHome.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { useIntl } from 'react-intl';
import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader';
import useApi from 'hooks/useApi';
import { labels, messages } from 'components/messages';
import EmptyPlaceholder from 'components/common/EmptyPlaceholder';

export default function RealtimeHome() {
const { formatMessage } = useIntl();
const { get, useQuery } = useApi();
const router = useRouter();
const { data, isLoading, error } = useQuery(['websites:me'], () => get('/me/websites'));

useEffect(() => {
if (data?.length) {
router.push(`realtime/${data[0].id}`);
}
}, [data]);

return (
<Page loading={isLoading || !data} error={error}>
<PageHeader title={formatMessage(labels.realtime)} />
{data?.length === 0 && <EmptyPlaceholder message={formatMessage(messages.noWebsites)} />}
</Page>
);
}
Loading

0 comments on commit 93b7767

Please sign in to comment.