Skip to content

Commit

Permalink
Refactor components. Add refresh button.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Aug 31, 2020
1 parent d0ca081 commit d06c077
Show file tree
Hide file tree
Showing 12 changed files with 85 additions and 56 deletions.
1 change: 1 addition & 0 deletions assets/redo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 16 additions & 3 deletions components/WebsiteDetails.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@ import DevicesTable from './metrics/DevicesTable';
import CountriesTable from './metrics/CountriesTable';
import EventsTable from './metrics/EventsTable';
import EventsChart from './metrics/EventsChart';
import useFetch from '../hooks/useFetch';
import useFetch from 'hooks/useFetch';
import Loading from 'components/common/Loading';

export default function WebsiteDetails({ websiteId, defaultDateRange = '7day' }) {
const [chartLoaded, setChartLoaded] = useState(false);
const [countryData, setCountryData] = useState();
const [eventsData, setEventsData] = useState();
const [expand, setExpand] = useState();
const [refresh, setRefresh] = useState(0);
const [dateRange, setDateRange] = useState(getDateRange(defaultDateRange));
const { startDate, endDate, unit } = dateRange;
const { data } = useFetch(`/api/website/${websiteId}`, { websiteId });
const { data } = useFetch(`/api/website/${websiteId}`);

const BackButton = () => (
<Button
Expand Down Expand Up @@ -92,6 +94,10 @@ export default function WebsiteDetails({ websiteId, defaultDateRange = '7day' })
setExpand(getSelectedMenuOption(value));
}

function handleRefresh() {
setRefresh(state => state + 1);
}

if (!data) {
return null;
}
Expand All @@ -100,15 +106,22 @@ export default function WebsiteDetails({ websiteId, defaultDateRange = '7day' })
<Page>
<div className="row">
<div className={classNames(styles.chart, 'col')}>
<WebsiteHeader websiteId={websiteId} name={data.name} showLink={false} />
<WebsiteHeader
websiteId={websiteId}
title={data.name}
onRefresh={handleRefresh}
showLink={false}
/>
<WebsiteChart
key={refresh}
websiteId={websiteId}
onDataLoad={handleDataLoad}
onDateChange={handleDateChange}
stickyHeader
/>
</div>
</div>
{!chartLoaded && <Loading />}
{chartLoaded && !expand && (
<>
<div className={classNames(styles.row, 'row')}>
Expand Down
6 changes: 3 additions & 3 deletions components/WebsiteList.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export default function WebsiteList() {

return (
<Page>
{data?.map(({ website_id, name }) => (
{data.map(({ website_id, name }) => (
<div key={website_id} className={styles.website}>
<WebsiteHeader websiteId={website_id} name={name} showLink />
<WebsiteChart key={website_id} title={name} websiteId={website_id} />
<WebsiteHeader websiteId={website_id} title={name} showLink />
<WebsiteChart websiteId={website_id} />
</div>
))}
{data.length === 0 && (
Expand Down
7 changes: 7 additions & 0 deletions components/common/RefreshButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from 'react';
import Button from './Button';
import Refresh from 'assets/redo.svg';

export default function RefreshButton({ onClick }) {
return <Button icon={<Refresh />} size="small" onClick={onClick} />;
}
12 changes: 9 additions & 3 deletions components/metrics/BarChart.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import classNames from 'classnames';
import ChartJS from 'chart.js';
import styles from './BarChart.module.css';
import { format } from 'date-fns';
import { formatLongNumber } from '../../lib/format';

export default function BarChart({
chartId,
Expand All @@ -21,7 +22,7 @@ export default function BarChart({
const chart = useRef();
const [tooltip, setTooltip] = useState({});

const renderLabel = (label, index, values) => {
const renderXLabel = (label, index, values) => {
const d = new Date(values[index].value);
const n = records;

Expand All @@ -40,6 +41,10 @@ export default function BarChart({
}
};

const renderYLabel = label => {
return +label > 1 ? formatLongNumber(label) : label;
};

const renderTooltip = model => {
const { opacity, title, body, labelColors } = model;

Expand Down Expand Up @@ -82,7 +87,7 @@ export default function BarChart({
tooltipFormat: 'ddd MMMM DD YYYY',
},
ticks: {
callback: renderLabel,
callback: renderXLabel,
minRotation: 0,
maxRotation: 0,
},
Expand All @@ -96,6 +101,7 @@ export default function BarChart({
yAxes: [
{
ticks: {
callback: renderYLabel,
beginAtZero: true,
},
stacked,
Expand All @@ -119,7 +125,7 @@ export default function BarChart({
const { options } = chart.current;

options.scales.xAxes[0].time.unit = unit;
options.scales.xAxes[0].ticks.callback = renderLabel;
options.scales.xAxes[0].ticks.callback = renderXLabel;
options.animation.duration = animationDuration;

onUpdate(chart.current);
Expand Down
39 changes: 21 additions & 18 deletions components/metrics/MetricsBar.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useState } from 'react';
import classNames from 'classnames';
import MetricCard from './MetricCard';
import { formatShortTime, formatNumber, formatLongNumber } from 'lib/format';
import Loading from 'components/common/Loading';
import useFetch from 'hooks/useFetch';
import { formatShortTime, formatNumber, formatLongNumber } from 'lib/format';
import styles from './MetricsBar.module.css';

export default function MetricsBar({ websiteId, startDate, endDate, className }) {
Expand All @@ -18,26 +19,28 @@ export default function MetricsBar({ websiteId, startDate, endDate, className })
setFormat(state => !state);
}

if (!data) {
return null;
}

const { pageviews, uniques, bounces, totaltime } = data;
const { pageviews, uniques, bounces, totaltime } = data || {};

return (
<div className={classNames(styles.bar, className)} onClick={handleSetFormat}>
<MetricCard label="Views" value={pageviews} format={formatFunc} />
<MetricCard label="Visitors" value={uniques} format={formatFunc} />
<MetricCard
label="Bounce rate"
value={pageviews ? (bounces / pageviews) * 100 : 0}
format={n => Number(n).toFixed(0) + '%'}
/>
<MetricCard
label="Average visit time"
value={totaltime && pageviews ? totaltime / (pageviews - bounces) : 0}
format={n => formatShortTime(n, ['m', 's'], ' ')}
/>
{!data ? (
<Loading />
) : (
<>
<MetricCard label="Views" value={pageviews} format={formatFunc} />
<MetricCard label="Visitors" value={uniques} format={formatFunc} />
<MetricCard
label="Bounce rate"
value={pageviews ? (bounces / pageviews) * 100 : 0}
format={n => Number(n).toFixed(0) + '%'}
/>
<MetricCard
label="Average visit time"
value={totaltime && pageviews ? totaltime / (pageviews - bounces) : 0}
format={n => formatShortTime(n, ['m', 's'], ' ')}
/>
</>
)}
</div>
);
}
2 changes: 1 addition & 1 deletion components/metrics/MetricsBar.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
}

@media only screen and (max-width: 992px) {
.container > div:last-child {
.bar > div:last-child {
display: none;
}
}
5 changes: 3 additions & 2 deletions components/metrics/PageviewsChart.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React from 'react';
import CheckVisible from 'components/helpers/CheckVisible';
import BarChart from './BarChart';
import { getDateLength } from '../../lib/date';

export default function PageviewsChart({ websiteId, data, unit, className }) {
export default function PageviewsChart({ websiteId, data, startDate, endDate, unit, className }) {
const handleUpdate = chart => {
const {
data: { datasets },
Expand Down Expand Up @@ -43,7 +44,7 @@ export default function PageviewsChart({ websiteId, data, unit, className }) {
},
]}
unit={unit}
records={data.pageviews.length}
records={getDateLength(startDate, endDate, unit)}
animationDuration={visible ? 300 : 0}
onUpdate={handleUpdate}
/>
Expand Down
42 changes: 20 additions & 22 deletions components/metrics/WebsiteHeader.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,36 @@
import React from 'react';
import { useRouter } from 'next/router';
import PageHeader from 'components/layout/PageHeader';
import Link from 'components/common/Link';
import Button from 'components/common/Button';
import ActiveUsers from './ActiveUsers';
import Arrow from 'assets/arrow-right.svg';
import styles from './WebsiteHeader.module.css';
import RefreshButton from '../common/RefreshButton';
import ButtonLayout from '../layout/ButtonLayout';

export default function WebsiteHeader({ websiteId, name, showLink = false }) {
export default function WebsiteHeader({ websiteId, title, showLink = false, onRefresh }) {
const router = useRouter();

return (
<PageHeader>
{showLink ? (
<Link href="/website/[...id]" as={`/website/${websiteId}/${name}`} className={styles.title}>
{name}
</Link>
) : (
<div className={styles.title}>{name}</div>
)}
<div className={styles.title}>{title}</div>
<ActiveUsers className={styles.active} websiteId={websiteId} />
{showLink && (
<Button
icon={<Arrow />}
onClick={() =>
router.push('/website/[...id]', `/website/${websiteId}/${name}`, {
shallow: true,
})
}
size="small"
>
<div>View details</div>
</Button>
)}
<ButtonLayout>
<RefreshButton onClick={onRefresh} />
{showLink && (
<Button
icon={<Arrow />}
onClick={() =>
router.push('/website/[...id]', `/website/${websiteId}/${name}`, {
shallow: true,
})
}
size="small"
>
<div>View details</div>
</Button>
)}
</ButtonLayout>
</PageHeader>
);
}
2 changes: 1 addition & 1 deletion hooks/useFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ export default function useFetch(url, params = {}, options = {}) {
}
}, [url, ...keys, ...update]);

return { data, error };
return { data, error, loadData };
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@
],
"**/*.css": [
"stylelint --fix",
"prettier --write",
"eslint"
"prettier --write"
]
},
"husky": {
Expand All @@ -53,6 +52,7 @@
"dotenv": "^8.2.0",
"formik": "^2.1.5",
"geolite2-redist": "^1.0.7",
"immer": "^7.0.8",
"is-localhost-ip": "^1.4.0",
"jose": "^1.28.0",
"maxmind": "^4.1.4",
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4456,7 +4456,7 @@ ignore@^5.1.4, ignore@^5.1.8:
resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.1.8.tgz#f150a8b50a34289b33e22f5889abd4d8016f0e57"
integrity sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==

immer@^7.0.3:
immer@^7.0.3, immer@^7.0.8:
version "7.0.8"
resolved "https://registry.yarnpkg.com/immer/-/immer-7.0.8.tgz#41dcbc5669a76500d017bef3ad0d03ce0a1d7c1e"
integrity sha512-XnpIN8PXBBaOD43U8Z17qg6RQiKQYGDGGCIbz1ixmLGwBkSWwmrmx5X7d+hTtXDM8ur7m5OdLE0PiO+y5RB3pw==
Expand Down

0 comments on commit d06c077

Please sign in to comment.