Compare commits

...

27 Commits

Author SHA1 Message Date
Alejandro Celaya
e303a80683 Updated bootstrap to solve security issue 2019-03-04 21:05:30 +01:00
Alejandro Celaya
5defc20e9f Merge pull request #117 from acelaya/feature/error-handler
Feature/error handler
2019-03-04 20:55:48 +01:00
Alejandro Celaya
d75eff62e3 Updated changelog 2019-03-04 20:50:05 +01:00
Alejandro Celaya
ad9f0c00d0 Created ErrorHandler test 2019-03-04 20:49:18 +01:00
Alejandro Celaya
cd908fa358 Created ErrorHandler component 2019-03-04 20:41:02 +01:00
Alejandro Celaya
2bf79dbc80 Merge pull request #114 from acelaya/feature/lat-lang-error
Fixed crash when trying to load a map with just one location
2019-03-04 20:35:10 +01:00
Alejandro Celaya
4c729a405d Fixed crash when trying to load a map with just one location 2019-03-04 20:24:28 +01:00
Alejandro Celaya
28c9f9ac96 Merge pull request #112 from acelaya/feature/many-visits
Improved performance while calculating status
2019-03-04 19:37:00 +01:00
Alejandro Celaya
2820caf955 Updated changelog 2019-03-04 19:29:56 +01:00
Alejandro Celaya
ba5ea7407b Used native javascript reduce instead of ramda reduce 2019-03-04 19:28:24 +01:00
Alejandro Celaya
1bc406b0d9 Ensured requests when loading visits are made in parallel for big dataset 2019-03-04 19:21:46 +01:00
Alejandro Celaya
7e27ceb885 Ensured same timestamp is used when generating memoization ID after mounting the component 2019-03-04 18:19:50 +01:00
Alejandro Celaya
252edaa2ca Improved performance while calculating status by doing one iteration only and memoizing the result when possible 2019-03-04 18:14:45 +01:00
Alejandro Celaya
9a6fad4db5 Merge pull request #110 from acelaya/feature/swipe-map
Prevented side menu to be swipeable while a modal window is displayed
2019-03-03 12:11:28 +01:00
Alejandro Celaya
127bcc14eb Prevented side menu to be swipeable while a modal window is displayed 2019-03-03 12:05:29 +01:00
Alejandro Celaya
220d634f80 Merge pull request #109 from acelaya/feature/map-center
Fixed initial zoom and center on maps
2019-03-03 11:54:44 +01:00
Alejandro Celaya
6291af2865 Fixed initial zoom and center on maps 2019-03-03 11:47:19 +01:00
Alejandro Celaya
e9e808d339 Merge pull request #108 from acelaya/feature/not-found-page
Feature/not found page
2019-03-03 11:24:56 +01:00
Alejandro Celaya
780e4a6e9e Replaced component by render on route rendering not found component with custom props 2019-03-03 11:18:58 +01:00
Alejandro Celaya
c4bc2f24d6 Used not-found component for menu layout inner router 2019-03-03 11:15:34 +01:00
Alejandro Celaya
d23ddd0e0b Created NotFound component 2019-03-03 11:02:29 +01:00
Alejandro Celaya
4f0ee79409 Added missing changelogs 2019-03-03 10:33:37 +01:00
Alejandro Celaya
7b07445c5d Merge pull request #107 from acelaya/feature/improve-docker-image
Feature/improve docker image
2019-03-03 10:28:30 +01:00
Alejandro Celaya
dcbf4bfef8 Added missing docker dependency in travis config 2019-03-03 10:22:26 +01:00
Alejandro Celaya
6ec870bb08 Updated travis so that it tries to build the docker image, whcih in turn builds the project 2019-03-03 10:18:23 +01:00
Alejandro Celaya
2c6dbb42c1 Simplified Dockerfile using multi-stage build 2019-03-03 10:12:59 +01:00
Alejandro Celaya
98725dce04 Added missing array-related dependencies 2019-03-03 10:01:10 +01:00
27 changed files with 497 additions and 197 deletions

View File

@@ -1,4 +1,5 @@
./build
./coverage
./dist
./node_modules
./test

View File

@@ -8,13 +8,16 @@ cache:
directories:
- node_modules
services:
- docker
install:
- yarn install
script:
- yarn lint
- yarn test:ci
- if [[ -z $TRAVIS_TAG ]]; then yarn build ; fi
- if [[ -z $TRAVIS_TAG ]]; then docker build -t shlink-web-client:test . ; fi # Test docker image build only when no tag is present
after_success:
- yarn ocular coverage/clover.xml

View File

@@ -4,6 +4,57 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org).
## 2.0.2 - 2019-03-04
#### Added
* *Nothing*
#### Changed
* *Nothing*
#### Deprecated
* *Nothing*
#### Removed
* *Nothing*
#### Fixed
* [#103](https://github.com/shlinkio/shlink-web-client/issues/103) Fixed visits page getting freezed when loading large amounts of visits.
* [#111](https://github.com/shlinkio/shlink-web-client/issues/111) Fixed crash when trying to load a map modal with only one location.
* [#115](https://github.com/shlinkio/shlink-web-client/issues/115) Created `ErrorHandler` component which will prevent crashes in app to make it unusable.
## 2.0.1 - 2019-03-03
#### Added
* *Nothing*
#### Changed
* [#106](https://github.com/shlinkio/shlink-web-client/issues/106) Reduced size of docker image by using a multi-stage build Dockerfile.
* [#95](https://github.com/shlinkio/shlink-web-client/issues/95) Tested docker image build during travis executions.
#### Deprecated
* *Nothing*
#### Removed
* *Nothing*
#### Fixed
* [#104](https://github.com/shlinkio/shlink-web-client/issues/104) Fixed blank page being showed when not-found paths are loaded.
* [#94](https://github.com/shlinkio/shlink-web-client/issues/94) Fixed initial zoom and center on maps.
* [#93](https://github.com/shlinkio/shlink-web-client/issues/93) Prevented side menu to be swipeable while a modal window is displayed.
## 2.0.0 - 2019-01-13
#### Added

View File

@@ -1,21 +1,8 @@
FROM nginx:1.15.8-alpine
FROM node:10.15.2 as node
COPY . /shlink-web-client
RUN cd /shlink-web-client && yarn install && yarn build
FROM nginx:1.15.9-alpine
LABEL maintainer="Alejandro Celaya <alejandro@alejandrocelaya.com>"
# Install node and yarn
RUN apk add --no-cache nodejs && apk add --no-cache yarn
ADD . ./shlink-web-client
# Install dependencies and build project
RUN cd ./shlink-web-client && \
yarn install && \
yarn build && \
# Move build contents to document root
cd .. && \
rm -r /usr/share/nginx/html/* && \
mv ./shlink-web-client/build/* /usr/share/nginx/html && \
rm -r ./shlink-web-client && \
# Delete and uninstall build tools
yarn cache clean && apk del yarn && apk del nodejs
RUN rm -r /usr/share/nginx/html
COPY --from=node /shlink-web-client/build /usr/share/nginx/html

View File

@@ -23,8 +23,11 @@
"@fortawesome/free-regular-svg-icons": "^5.6.3",
"@fortawesome/free-solid-svg-icons": "^5.6.3",
"@fortawesome/react-fontawesome": "^0.1.3",
"array-filter": "^1.0.0",
"array-map": "^0.0.0",
"array-reduce": "^0.0.0",
"axios": "^0.18.0",
"bootstrap": "~4.1.1",
"bootstrap": "^4.3.1",
"bottlejs": "^1.7.1",
"chart.js": "^2.7.2",
"classnames": "^2.2.6",
@@ -34,7 +37,7 @@
"promise": "^8.0.1",
"prop-types": "^15.6.2",
"qs": "^6.5.2",
"ramda": "^0.25.0",
"ramda": "^0.26.1",
"react": "^16.7.0",
"react-autosuggest": "^9.4.0",
"react-chartjs-2": "^2.7.4",
@@ -42,7 +45,7 @@
"react-copy-to-clipboard": "^5.0.1",
"react-datepicker": "~1.5.0",
"react-dom": "^16.7.0",
"react-leaflet": "^2.1.4",
"react-leaflet": "^2.2.1",
"react-moment": "^0.7.6",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",

View File

@@ -1,6 +1,7 @@
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import './App.scss';
import NotFound from './common/NotFound';
const App = (MainHeader, Home, MenuLayout, CreateServer) => () => (
<div className="container-fluid app-container">
@@ -11,6 +12,7 @@ const App = (MainHeader, Home, MenuLayout, CreateServer) => () => (
<Route exact path="/server/create" component={CreateServer} />
<Route exact path="/" component={Home} />
<Route path="/server/:serverId" component={MenuLayout} />
<Route component={NotFound} />
</Switch>
</div>
</div>

View File

@@ -0,0 +1,36 @@
import React from 'react';
import * as PropTypes from 'prop-types';
import './ErrorHandler.scss';
import { Button } from 'reactstrap';
const ErrorHandler = ({ location }) => class ErrorHandler extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
};
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return (
<div className="error-handler">
<h1>Oops! This is awkward :S</h1>
<p>It seems that something went wrong. Try refreshing the page or just click this button.</p>
<br />
<Button outline color="primary" onClick={() => location.reload()}>Take me back</Button>
</div>
);
}
return this.props.children;
}
};
export default ErrorHandler;

View File

@@ -0,0 +1,9 @@
@import '../utils/mixins/vertical-align.scss';
.error-handler {
@include vertical-align();
padding: 20px;
text-align: center;
width: 100%;
}

View File

@@ -6,6 +6,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import classnames from 'classnames';
import * as PropTypes from 'prop-types';
import { serverType } from '../servers/prop-types';
import NotFound from './NotFound';
import './MenuLayout.scss';
const MenuLayout = (TagsList, ShortUrls, AsideMenu, CreateShortUrl, ShortUrlVisits) =>
@@ -38,10 +39,18 @@ const MenuLayout = (TagsList, ShortUrls, AsideMenu, CreateShortUrl, ShortUrlVisi
}
render() {
const { selectedServer } = this.props;
const { selectedServer, match } = this.props;
const { params: { serverId } } = match;
const burgerClasses = classnames('menu-layout__burger-icon', {
'menu-layout__burger-icon--active': this.state.showSideBar,
});
const swipeMenuIfNoModalExists = (showSideBar) => () => {
if (document.querySelector('.modal')) {
return;
}
this.setState({ showSideBar });
};
return (
<React.Fragment>
@@ -54,8 +63,8 @@ const MenuLayout = (TagsList, ShortUrls, AsideMenu, CreateShortUrl, ShortUrlVisi
<Swipeable
delta={40}
className="menu-layout__swipeable"
onSwipedLeft={() => this.setState({ showSideBar: false })}
onSwipedRight={() => this.setState({ showSideBar: true })}
onSwipedLeft={swipeMenuIfNoModalExists(false)}
onSwipedRight={swipeMenuIfNoModalExists(true)}
>
<div className="row menu-layout__swipeable-inner">
<AsideMenu
@@ -88,6 +97,9 @@ const MenuLayout = (TagsList, ShortUrls, AsideMenu, CreateShortUrl, ShortUrlVisi
path="/server/:serverId/manage-tags"
component={TagsList}
/>
<Route
render={() => <NotFound to={`/server/${serverId}/list-short-urls/1`} btnText="List short URLs" />}
/>
</Switch>
</div>
</div>

23
src/common/NotFound.js Normal file
View File

@@ -0,0 +1,23 @@
import React from 'react';
import { Link } from 'react-router-dom';
import * as PropTypes from 'prop-types';
const propTypes = {
to: PropTypes.string,
btnText: PropTypes.string,
};
const NotFound = ({ to = '/', btnText = 'Home' }) => (
<div className="home">
<h2>Oops! We could not find requested route.</h2>
<p>
Use your browser{'\''}s back button to navigate to the page you have previously come from, or just press this button.
</p>
<br />
<Link to={to} className="btn btn-outline-primary btn-lg">{btnText}</Link>
</div>
);
NotFound.propTypes = propTypes;
export default NotFound;

View File

@@ -3,6 +3,7 @@ import MainHeader from '../MainHeader';
import Home from '../Home';
import MenuLayout from '../MenuLayout';
import AsideMenu from '../AsideMenu';
import ErrorHandler from '../ErrorHandler';
const provideServices = (bottle, connect, withRouter) => {
bottle.constant('window', global.window);
@@ -29,6 +30,8 @@ const provideServices = (bottle, connect, withRouter) => {
bottle.decorator('MenuLayout', withRouter);
bottle.serviceFactory('AsideMenu', AsideMenu, 'DeleteServerButton');
bottle.serviceFactory('ErrorHandler', ErrorHandler, 'window');
};
export default provideServices;

View File

@@ -16,14 +16,16 @@ import './index.scss';
// This overwrites icons used for leaflet maps, fixing some issues caused by webpack while processing the CSS
fixLeafletIcons();
const { App, ScrollToTop } = container;
const { App, ScrollToTop, ErrorHandler } = container;
render(
<Provider store={store}>
<BrowserRouter basename={homepage}>
<ScrollToTop>
<App />
</ScrollToTop>
<ErrorHandler>
<ScrollToTop>
<App />
</ScrollToTop>
</ErrorHandler>
</BrowserRouter>
</Provider>,
document.getElementById('root')

View File

@@ -45,7 +45,7 @@ const ShortUrlsRowMenu = (DeleteShortUrlModal, EditTagsModal) => class ShortUrls
return (
<ButtonDropdown toggle={this.toggle} isOpen={this.state.isOpen}>
<DropdownToggle size="sm" caret className="short-urls-row-menu__dropdown-toggle btn-outline-secondary">
<DropdownToggle size="sm" caret outline className="short-urls-row-menu__dropdown-toggle">
&nbsp;<FontAwesomeIcon icon={menuIcon} />&nbsp;
</DropdownToggle>
<DropdownMenu right>

View File

@@ -20,4 +20,5 @@
@include vertical-align();
right: 15px;
cursor: pointer;
}

View File

@@ -8,20 +8,13 @@ import DateInput from '../utils/DateInput';
import MutedMessage from '../utils/MuttedMessage';
import SortableBarGraph from './SortableBarGraph';
import { shortUrlVisitsType } from './reducers/shortUrlVisits';
import { VisitsHeader } from './VisitsHeader';
import VisitsHeader from './VisitsHeader';
import GraphCard from './GraphCard';
import { shortUrlDetailType } from './reducers/shortUrlDetail';
import './ShortUrlVisits.scss';
import OpenMapModalBtn from './helpers/OpenMapModalBtn';
const ShortUrlVisits = ({
processOsStats,
processBrowserStats,
processCountriesStats,
processCitiesStats,
processReferrersStats,
processCitiesStatsForMap,
}) => class ShortUrlVisits extends React.Component {
const ShortUrlVisits = ({ processStatsFromVisits }) => class ShortUrlVisits extends React.PureComponent {
static propTypes = {
match: PropTypes.shape({
params: PropTypes.object,
@@ -35,28 +28,37 @@ const ShortUrlVisits = ({
state = { startDate: undefined, endDate: undefined };
loadVisits = () => {
const { match: { params }, getShortUrlVisits } = this.props;
getShortUrlVisits(params.shortCode, mapObjIndexed(
const { shortCode } = params;
const dates = mapObjIndexed(
(value) => value && value.format ? value.format('YYYY-MM-DD') : value,
this.state
));
);
const { startDate, endDate } = dates;
// While the "page" is loaded, use the timestamp + filtering dates as memoization IDs for stats calcs
this.memoizationId = `${this.timeWhenMounted}_${shortCode}_${startDate}_${endDate}`;
getShortUrlVisits(shortCode, dates);
};
componentDidMount() {
const { match: { params }, getShortUrlDetail } = this.props;
const { shortCode } = params;
this.timeWhenMounted = new Date().getTime();
this.loadVisits();
getShortUrlDetail(params.shortCode);
getShortUrlDetail(shortCode);
}
render() {
const { shortUrlVisits, shortUrlDetail } = this.props;
const renderVisitsContent = () => {
const { visits, loading, error } = shortUrlVisits;
const { visits, loading, loadingLarge, error } = shortUrlVisits;
if (loading) {
return <MutedMessage><FontAwesomeIcon icon={preloader} spin /> Loading...</MutedMessage>;
const message = loadingLarge ? 'This is going to take a while... :S' : 'Loading...';
return <MutedMessage><FontAwesomeIcon icon={preloader} spin /> {message}</MutedMessage>;
}
if (error) {
@@ -71,17 +73,21 @@ const ShortUrlVisits = ({
return <MutedMessage>There are no visits matching current filter :(</MutedMessage>;
}
const { os, browsers, referrers, countries, cities, citiesForMap } = processStatsFromVisits(
{ id: this.memoizationId, visits }
);
return (
<div className="row">
<div className="col-xl-4 col-lg-6">
<GraphCard title="Operating systems" stats={processOsStats(visits)} />
<GraphCard title="Operating systems" stats={os} />
</div>
<div className="col-xl-4 col-lg-6">
<GraphCard title="Browsers" stats={processBrowserStats(visits)} />
<GraphCard title="Browsers" stats={browsers} />
</div>
<div className="col-xl-4">
<SortableBarGraph
stats={processReferrersStats(visits)}
stats={referrers}
title="Referrers"
sortingItems={{
name: 'Referrer name',
@@ -91,7 +97,7 @@ const ShortUrlVisits = ({
</div>
<div className="col-lg-6">
<SortableBarGraph
stats={processCountriesStats(visits)}
stats={countries}
title="Countries"
sortingItems={{
name: 'Country name',
@@ -101,13 +107,13 @@ const ShortUrlVisits = ({
</div>
<div className="col-lg-6">
<SortableBarGraph
stats={processCitiesStats(visits)}
stats={cities}
title="Cities"
extraHeaderContent={[
() => (
<OpenMapModalBtn
modalTitle="Cities"
locations={values(processCitiesStatsForMap(visits))}
locations={values(citiesForMap)}
/>
),
]}
@@ -133,7 +139,7 @@ const ShortUrlVisits = ({
placeholderText="Since"
isClearable
maxDate={this.state.endDate}
onChange={(date) => this.setState({ startDate: date }, () => this.loadVisits())}
onChange={(date) => this.setState({ startDate: date }, this.loadVisits)}
/>
</div>
<div className="col-xl-3 col-lg-4 col-md-6">
@@ -143,7 +149,7 @@ const ShortUrlVisits = ({
placeholderText="Until"
isClearable
minDate={this.state.startDate}
onChange={(date) => this.setState({ endDate: date }, () => this.loadVisits())}
onChange={(date) => this.setState({ endDate: date }, this.loadVisits)}
/>
</div>
</div>

View File

@@ -11,7 +11,7 @@ const propTypes = {
shortUrlVisits: shortUrlVisitsType.isRequired,
};
export function VisitsHeader({ shortUrlDetail, shortUrlVisits }) {
export default function VisitsHeader({ shortUrlDetail, shortUrlVisits }) {
const { shortUrl, loading } = shortUrlDetail;
const { visits } = shortUrlVisits;
const shortLink = shortUrl && shortUrl.shortUrl ? shortUrl.shortUrl : '';

View File

@@ -1,6 +1,7 @@
import React from 'react';
import { Modal, ModalBody } from 'reactstrap';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import { prop } from 'ramda';
import * as PropTypes from 'prop-types';
import './MapModal.scss';
@@ -25,6 +26,18 @@ const OpenStreetMapTile = () => (
/>
);
const calculateMapProps = (locations) => {
if (locations.length > 1) {
return { bounds: locations.map(prop('latLong')) };
}
// When there's only one location, an error is thrown if trying to calculate the bounds.
// When that happens, we use zoom and center as a workaround
const [{ latLong: center }] = locations;
return { zoom: '10', center };
};
const MapModal = ({ toggle, isOpen, title, locations }) => (
<Modal toggle={toggle} isOpen={isOpen} className="map-modal__modal" contentClassName="map-modal__modal-content">
<ModalBody className="map-modal__modal-body">
@@ -32,7 +45,7 @@ const MapModal = ({ toggle, isOpen, title, locations }) => (
{title}
<button type="button" className="close" onClick={toggle}>&times;</button>
</h3>
<Map center={[ 0, 0 ]} zoom="3">
<Map {...calculateMapProps(locations)}>
<OpenStreetMapTile />
{locations.map(({ cityName, latLong, count }, index) => (
<Marker key={index} position={latLong}>

View File

@@ -1,9 +1,11 @@
import PropTypes from 'prop-types';
import { flatten, range, splitEvery } from 'ramda';
/* eslint-disable padding-line-between-statements, newline-after-var */
export const GET_SHORT_URL_VISITS_START = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_START';
export const GET_SHORT_URL_VISITS_ERROR = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_ERROR';
export const GET_SHORT_URL_VISITS = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS';
export const GET_SHORT_URL_VISITS_LARGE = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_LARGE';
/* eslint-enable padding-line-between-statements, newline-after-var */
export const shortUrlVisitsType = PropTypes.shape({
@@ -15,6 +17,7 @@ export const shortUrlVisitsType = PropTypes.shape({
const initialState = {
visits: [],
loading: false,
loadingLarge: false,
error: false,
};
@@ -24,19 +27,27 @@ export default function reducer(state = initialState, action) {
return {
...state,
loading: true,
loadingLarge: false,
};
case GET_SHORT_URL_VISITS_ERROR:
return {
...state,
loading: false,
loadingLarge: false,
error: true,
};
case GET_SHORT_URL_VISITS:
return {
visits: action.visits,
loading: false,
loadingLarge: false,
error: false,
};
case GET_SHORT_URL_VISITS_LARGE:
return {
...state,
loadingLarge: true,
};
default:
return state;
}
@@ -58,9 +69,36 @@ export const getShortUrlVisits = (buildShlinkApiClient) => (shortCode, dates) =>
return data;
}
return data.concat(await loadVisits(page + 1));
// If there are more pages, make requests in blocks of 4
const parallelRequestsCount = 4;
const parallelStartingPage = 2;
const pagesRange = range(parallelStartingPage, pagination.pagesCount + 1);
const pagesBlocks = splitEvery(parallelRequestsCount, pagesRange);
if (pagination.pagesCount - 1 > parallelRequestsCount) {
dispatch({ type: GET_SHORT_URL_VISITS_LARGE });
}
return data.concat(await loadPagesBlocks(pagesBlocks));
};
const loadPagesBlocks = async (pagesBlocks, index = 0) => {
const data = await loadVisitsInParallel(pagesBlocks[index]);
if (index < pagesBlocks.length - 1) {
return data.concat(await loadPagesBlocks(pagesBlocks, index + 1));
}
return data;
};
const loadVisitsInParallel = (pages) =>
Promise.all(pages.map(async (page) => {
const { data } = await getShortUrlVisits(shortCode, { ...dates, page, itemsPerPage });
return data;
})).then(flatten);
try {
const visits = await loadVisits();

View File

@@ -1,4 +1,4 @@
import { assoc, isNil, isEmpty, reduce } from 'ramda';
import { isNil, isEmpty, memoizeWith, prop } from 'ramda';
const osFromUserAgent = (userAgent) => {
const lowerUserAgent = userAgent.toLowerCase();
@@ -42,79 +42,69 @@ const extractDomain = (url) => {
return domain.split(':')[0];
};
export const processOsStats = (visits) =>
reduce(
(stats, { userAgent }) => {
const os = isNil(userAgent) ? 'Others' : osFromUserAgent(userAgent);
return assoc(os, (stats[os] || 0) + 1, stats);
},
{},
visits,
);
export const processBrowserStats = (visits) =>
reduce(
(stats, { userAgent }) => {
const browser = isNil(userAgent) ? 'Others' : browserFromUserAgent(userAgent);
return assoc(browser, (stats[browser] || 0) + 1, stats);
},
{},
visits,
);
export const processReferrersStats = (visits) =>
reduce(
(stats, visit) => {
const notHasDomain = isNil(visit.referer) || isEmpty(visit.referer);
const domain = notHasDomain ? 'Unknown' : extractDomain(visit.referer);
return assoc(domain, (stats[domain] || 0) + 1, stats);
},
{},
visits,
);
const visitLocationHasProperty = (visitLocation, propertyName) =>
!isNil(visitLocation)
&& !isNil(visitLocation[propertyName])
&& !isEmpty(visitLocation[propertyName]);
const buildLocationStatsProcessorByProperty = (propertyName) => (visits) =>
reduce(
(stats, { visitLocation }) => {
const hasLocationProperty = visitLocationHasProperty(visitLocation, propertyName);
const value = hasLocationProperty ? visitLocation[propertyName] : 'Unknown';
const updateOsStatsForVisit = (osStats, { userAgent }) => {
const os = isNil(userAgent) ? 'Others' : osFromUserAgent(userAgent);
return assoc(value, (stats[value] || 0) + 1, stats);
osStats[os] = (osStats[os] || 0) + 1;
};
const updateBrowsersStatsForVisit = (browsersStats, { userAgent }) => {
const browser = isNil(userAgent) ? 'Others' : browserFromUserAgent(userAgent);
browsersStats[browser] = (browsersStats[browser] || 0) + 1;
};
const updateReferrersStatsForVisit = (referrersStats, { referer }) => {
const notHasDomain = isNil(referer) || isEmpty(referer);
const domain = notHasDomain ? 'Unknown' : extractDomain(referer);
referrersStats[domain] = (referrersStats[domain] || 0) + 1;
};
const updateLocationsStatsForVisit = (propertyName) => (stats, { visitLocation }) => {
const hasLocationProperty = visitLocationHasProperty(visitLocation, propertyName);
const value = hasLocationProperty ? visitLocation[propertyName] : 'Unknown';
stats[value] = (stats[value] || 0) + 1;
};
const updateCountriesStatsForVisit = updateLocationsStatsForVisit('countryName');
const updateCitiesStatsForVisit = updateLocationsStatsForVisit('cityName');
const updateCitiesForMapForVisit = (citiesForMapStats, { visitLocation }) => {
if (!visitLocationHasProperty(visitLocation, 'cityName')) {
return;
}
const { cityName, latitude, longitude } = visitLocation;
const currentCity = citiesForMapStats[cityName] || {
cityName,
count: 0,
latLong: [ parseFloat(latitude), parseFloat(longitude) ],
};
currentCity.count++;
citiesForMapStats[cityName] = currentCity;
};
export const processStatsFromVisits = memoizeWith(prop('id'), ({ visits }) =>
visits.reduce(
(stats, visit) => {
// We mutate the original object because it has a big side effect when large data sets are processed
updateOsStatsForVisit(stats.os, visit);
updateBrowsersStatsForVisit(stats.browsers, visit);
updateReferrersStatsForVisit(stats.referrers, visit);
updateCountriesStatsForVisit(stats.countries, visit);
updateCitiesStatsForVisit(stats.cities, visit);
updateCitiesForMapForVisit(stats.citiesForMap, visit);
return stats;
},
{},
visits,
);
export const processCountriesStats = buildLocationStatsProcessorByProperty('countryName');
export const processCitiesStats = buildLocationStatsProcessorByProperty('cityName');
export const processCitiesStatsForMap = (visits) =>
reduce(
(stats, { visitLocation }) => {
if (!visitLocationHasProperty(visitLocation, 'cityName')) {
return stats;
}
const { cityName, latitude, longitude } = visitLocation;
const currentCity = stats[cityName] || {
cityName,
count: 0,
latLong: [ parseFloat(latitude), parseFloat(longitude) ],
};
currentCity.count++;
return assoc(cityName, currentCity, stats);
},
{},
visits,
);
{ os: {}, browsers: {}, referrers: {}, countries: {}, cities: {}, citiesForMap: {} }
));

View File

@@ -19,12 +19,17 @@ describe('<App />', () => {
it('renders app main routes', () => {
const routes = wrapper.find(Route);
const expectedRoutesCount = 3;
const second = 2;
const expectedRoutesCount = 4;
const expectedPaths = [
'/server/create',
'/',
'/server/:serverId',
];
expect.assertions(expectedPaths.length + 1);
expect(routes).toHaveLength(expectedRoutesCount);
expect(routes.at(0).prop('path')).toEqual('/server/create');
expect(routes.at(1).prop('path')).toEqual('/');
expect(routes.at(second).prop('path')).toEqual('/server/:serverId');
expectedPaths.forEach((path, index) => {
expect(routes.at(index).prop('path')).toEqual(path);
});
});
});

View File

@@ -0,0 +1,36 @@
import React from 'react';
import { shallow } from 'enzyme';
import { Button } from 'reactstrap';
import createErrorHandler from '../../src/common/ErrorHandler';
describe('<ErrorHandler />', () => {
const window = {
location: {
reload: jest.fn(),
},
};
let wrapper;
beforeEach(() => {
const ErrorHandler = createErrorHandler(window);
wrapper = shallow(<ErrorHandler children={<span>Foo</span>} />);
});
afterEach(() => wrapper.unmount());
it('renders children when no error has occurred', () => {
expect(wrapper.text()).toEqual('Foo');
expect(wrapper.find(Button)).toHaveLength(0);
});
it('renders error page when error has occurred', () => {
wrapper.setState({ hasError: true });
expect(wrapper.text()).toContain('Oops! This is awkward :S');
expect(wrapper.text()).toContain(
'It seems that something went wrong. Try refreshing the page or just click this button.'
);
expect(wrapper.find(Button)).toHaveLength(1);
});
});

View File

@@ -0,0 +1,48 @@
import React from 'react';
import { shallow } from 'enzyme';
import { Link } from 'react-router-dom';
import NotFound from '../../src/common/NotFound';
describe('<NotFound />', () => {
let wrapper;
const createWrapper = (props = {}) => {
wrapper = shallow(<NotFound {...props} />);
const content = wrapper.text();
return { wrapper, content };
};
afterEach(() => wrapper && wrapper.unmount());
it('shows expected error title', () => {
const { content } = createWrapper();
expect(content).toContain('Oops! We could not find requested route.');
});
it('shows expected error message', () => {
const { content } = createWrapper();
expect(content).toContain(
'Use your browser\'s back button to navigate to the page you have previously come from, or just press this button.'
);
});
it('shows a link to the home', () => {
const { wrapper } = createWrapper();
const link = wrapper.find(Link);
expect(link.prop('to')).toEqual('/');
expect(link.prop('className')).toEqual('btn btn-outline-primary btn-lg');
expect(link.prop('children')).toEqual('Home');
});
it('shows a link with provided props', () => {
const { wrapper } = createWrapper({ to: '/foo/bar', btnText: 'Hello' });
const link = wrapper.find(Link);
expect(link.prop('to')).toEqual('/foo/bar');
expect(link.prop('className')).toEqual('btn btn-outline-primary btn-lg');
expect(link.prop('children')).toEqual('Hello');
});
});

View File

@@ -11,21 +11,16 @@ import SortableBarGraph from '../../src/visits/SortableBarGraph';
describe('<ShortUrlVisits />', () => {
let wrapper;
const statsProcessor = () => ({});
const processStatsFromVisits = () => (
{ os: {}, browsers: {}, referrers: {}, countries: {}, cities: {}, citiesForMap: {} }
);
const getShortUrlVisitsMock = sinon.spy();
const match = {
params: { shortCode: 'abc123' },
};
const createComponent = (shortUrlVisits) => {
const ShortUrlVisits = createShortUrlVisits({
processBrowserStats: statsProcessor,
processCountriesStats: statsProcessor,
processOsStats: statsProcessor,
processReferrersStats: statsProcessor,
processCitiesStats: statsProcessor,
processCitiesStatsForMap: statsProcessor,
});
const ShortUrlVisits = createShortUrlVisits({ processStatsFromVisits });
wrapper = shallow(
<ShortUrlVisits
@@ -48,7 +43,7 @@ describe('<ShortUrlVisits />', () => {
}
});
it('Renders a preloader when visits are loading', () => {
it('renders a preloader when visits are loading', () => {
const wrapper = createComponent({ loading: true });
const loadingMessage = wrapper.find(MutedMessage);
@@ -56,6 +51,14 @@ describe('<ShortUrlVisits />', () => {
expect(loadingMessage.html()).toContain('Loading...');
});
it('renders a warning when loading large amounts of visits', () => {
const wrapper = createComponent({ loading: true, loadingLarge: true });
const loadingMessage = wrapper.find(MutedMessage);
expect(loadingMessage).toHaveLength(1);
expect(loadingMessage.html()).toContain('This is going to take a while... :S');
});
it('renders an error message when visits could not be loaded', () => {
const wrapper = createComponent({ loading: false, error: true });
const errorMessage = wrapper.find(Card);

View File

@@ -1,7 +1,7 @@
import React from 'react';
import { shallow } from 'enzyme';
import Moment from 'react-moment';
import { VisitsHeader } from '../../src/visits/VisitsHeader';
import VisitsHeader from '../../src/visits/VisitsHeader';
import ExternalLink from '../../src/utils/ExternalLink';
describe('<VisitsHeader />', () => {

View File

@@ -4,6 +4,7 @@ import reducer, {
GET_SHORT_URL_VISITS_START,
GET_SHORT_URL_VISITS_ERROR,
GET_SHORT_URL_VISITS,
GET_SHORT_URL_VISITS_LARGE,
} from '../../../src/visits/reducers/shortUrlVisits';
describe('shortUrlVisitsReducer', () => {
@@ -15,6 +16,13 @@ describe('shortUrlVisitsReducer', () => {
expect(loading).toEqual(true);
});
it('returns loadingLarge on GET_SHORT_URL_VISITS_LARGE', () => {
const state = reducer({ loadingLarge: false }, { type: GET_SHORT_URL_VISITS_LARGE });
const { loadingLarge } = state;
expect(loadingLarge).toEqual(true);
});
it('stops loading and returns error on GET_SHORT_URL_VISITS_ERROR', () => {
const state = reducer({ loading: true, error: false }, { type: GET_SHORT_URL_VISITS_ERROR });
const { loading, error } = state;

View File

@@ -1,11 +1,4 @@
import {
processOsStats,
processBrowserStats,
processReferrersStats,
processCountriesStats,
processCitiesStats,
processCitiesStatsForMap,
} from '../../../src/visits/services/VisitsParser';
import { processStatsFromVisits } from '../../../src/visits/services/VisitsParser';
describe('VisitsParser', () => {
const visits = [
@@ -50,64 +43,71 @@ describe('VisitsParser', () => {
},
];
describe('processOsStats', () => {
describe('processStatsFromVisits', () => {
let stats;
beforeAll(() => {
stats = processStatsFromVisits({ id: 'id', visits });
});
it('properly parses OS stats', () => {
expect(processOsStats(visits)).toEqual({
const { os } = stats;
expect(os).toEqual({
Linux: 3,
Windows: 1,
MacOS: 1,
});
});
});
describe('processBrowserStats', () => {
it('properly parses browser stats', () => {
expect(processBrowserStats(visits)).toEqual({
const { browsers } = stats;
expect(browsers).toEqual({
Firefox: 2,
Chrome: 2,
Opera: 1,
});
});
});
describe('processReferrersStats', () => {
it('properly parses referrer stats', () => {
expect(processReferrersStats(visits)).toEqual({
const { referrers } = stats;
expect(referrers).toEqual({
'Unknown': 2,
'google.com': 2,
'm.facebook.com': 1,
});
});
});
describe('processCountriesStats', () => {
it('properly parses countries stats', () => {
expect(processCountriesStats(visits)).toEqual({
const { countries } = stats;
expect(countries).toEqual({
'Spain': 3,
'United States': 1,
'Unknown': 1,
});
});
});
describe('processCitiesStats', () => {
it('properly parses cities stats', () => {
expect(processCitiesStats(visits)).toEqual({
const { cities } = stats;
expect(cities).toEqual({
'Zaragoza': 2,
'New York': 1,
'Unknown': 2,
});
});
});
describe('processCitiesStatsForMap', () => {
it('properly parses cities stats with lat and long', () => {
const { citiesForMap } = stats;
const zaragozaLat = 123.45;
const zaragozaLong = -543.21;
const newYorkLat = 1029;
const newYorkLong = 6758;
expect(processCitiesStatsForMap(visits)).toEqual({
expect(citiesForMap).toEqual({
'Zaragoza': {
cityName: 'Zaragoza',
count: 2,

View File

@@ -736,12 +736,19 @@
dependencies:
regenerator-runtime "^0.12.0"
"@babel/runtime@^7.1.2", "@babel/runtime@^7.2.0":
"@babel/runtime@^7.1.2":
version "7.2.0"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.2.0.tgz#b03e42eeddf5898e00646e4c840fa07ba8dcad7f"
dependencies:
regenerator-runtime "^0.12.0"
"@babel/runtime@^7.3.1":
version "7.3.4"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.3.4.tgz#73d12ba819e365fcf7fd152aed56d6df97d21c83"
integrity sha512-IvfvnMdSaLBateu0jfsYIpZTxAc2cKEXEMiezGGN75QcBcecDUKd3PgLAncT0oOgxKy8dd8hrJKj9MfzgfZd6g==
dependencies:
regenerator-runtime "^0.12.0"
"@babel/template@^7.1.0", "@babel/template@^7.1.2", "@babel/template@^7.2.2":
version "7.2.2"
resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.2.2.tgz#005b3fdf0ed96e88041330379e0da9a708eb2907"
@@ -1209,9 +1216,10 @@ array-equal@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/array-equal/-/array-equal-1.0.0.tgz#8c2a5ef2472fd9ea742b04c77a75093ba2757c93"
array-filter@~0.0.0:
version "0.0.1"
resolved "https://registry.yarnpkg.com/array-filter/-/array-filter-0.0.1.tgz#7da8cf2e26628ed732803581fd21f67cacd2eeec"
array-filter@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/array-filter/-/array-filter-1.0.0.tgz#baf79e62e6ef4c2a4c0b831232daffec251f9d83"
integrity sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=
array-find-index@^1.0.1:
version "1.0.2"
@@ -1236,13 +1244,15 @@ array-includes@^3.0.3:
define-properties "^1.1.2"
es-abstract "^1.7.0"
array-map@~0.0.0:
array-map@^0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/array-map/-/array-map-0.0.0.tgz#88a2bab73d1cf7bcd5c1b118a003f66f665fa662"
integrity sha1-iKK6tz0c97zVwbEYoAP2b2ZfpmI=
array-reduce@~0.0.0:
array-reduce@^0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/array-reduce/-/array-reduce-0.0.0.tgz#173899d3ffd1c7d9383e4479525dbe278cab5f2b"
integrity sha1-FziZ0//Rx9k4PkR5Ul2+J4yrXys=
array-union@^1.0.1:
version "1.0.2"
@@ -1722,9 +1732,10 @@ boolbase@^1.0.0, boolbase@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e"
bootstrap@~4.1.1:
version "4.1.3"
resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-4.1.3.tgz#0eb371af2c8448e8c210411d0cb824a6409a12be"
bootstrap@^4.3.1:
version "4.3.1"
resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-4.3.1.tgz#280ca8f610504d99d7b6b4bfc4b68cec601704ac"
integrity sha512-rXqOmH1VilAt2DyPzluTi2blhk17bO7ef+zLLPlWvG494pDxcM234pJ8wTc/6R40UWizAIIMgxjvxZg5kmsbag==
bottlejs@^1.7.1:
version "1.7.1"
@@ -4356,12 +4367,19 @@ hoist-non-react-statics@^2.5.0:
version "2.5.5"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz#c5903cf409c0dfd908f388e619d86b9c1174cb47"
hoist-non-react-statics@^3.1.0, hoist-non-react-statics@^3.2.1:
hoist-non-react-statics@^3.1.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.2.1.tgz#c09c0555c84b38a7ede6912b61efddafd6e75e1e"
dependencies:
react-is "^16.3.2"
hoist-non-react-statics@^3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.0.tgz#b09178f0122184fb95acf525daaecb4d8f45958b"
integrity sha512-0XsbTXxgiaCDYDIWFcwkmerZPSwywfUqYmwT4jzewKTQSWoE6FCMoUVOeBJWK3E/CrWbxRG3m5GzY4lnIwGRBA==
dependencies:
react-is "^16.7.0"
home-or-tmp@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8"
@@ -5809,11 +5827,6 @@ locate-path@^3.0.0:
p-locate "^3.0.0"
path-exists "^3.0.0"
lodash-es@^4.0.0:
version "4.17.11"
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.11.tgz#145ab4a7ac5c5e52a3531fb4f310255a152b4be0"
integrity sha512-DHb1ub+rMjjrxqlB3H56/6MXtm1lSksDp2rA2cNWjG8mlDUYFhUj3Di2Zn5IwSU87xLv8tNIQ7sSwE/YOX/D/Q==
lodash._reinterpolate@~3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d"
@@ -7907,9 +7920,10 @@ railroad-diagrams@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz#eb7e6267548ddedfb899c1b90e57374559cddb7e"
ramda@^0.25.0:
version "0.25.0"
resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.25.0.tgz#8fdf68231cffa90bc2f9460390a0cb74a29b29a9"
ramda@^0.26.1:
version "0.26.1"
resolved "https://registry.yarnpkg.com/ramda/-/ramda-0.26.1.tgz#8d41351eb8111c55353617fc3bbffad8e4d35d06"
integrity sha512-hLWjpy7EnsDBb0p+Z3B7rPi3GDeRG5ZtiI33kJhTt+ORCd38AbAIjB/9zRIUoeTbE/AVX5ZkU7m6bznsvrf8eQ==
randexp@0.4.6:
version "0.4.6"
@@ -8067,16 +8081,15 @@ react-is@^16.3.2, react-is@^16.6.0, react-is@^16.6.1, react-is@^16.7.0:
version "16.7.0"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.7.0.tgz#c1bd21c64f1f1364c6f70695ec02d69392f41bfa"
react-leaflet@^2.1.4:
version "2.1.4"
resolved "https://registry.yarnpkg.com/react-leaflet/-/react-leaflet-2.1.4.tgz#44192a972892c690d4148e48dacd613168fd8cc4"
integrity sha512-OJvLq13ID5X6H/AM7woPmuqK7qEjT7RE81kysYU3X4HACsumAmvRuWffffxQ8Fl+m2cxkqF78eRmsWj5w9r1xw==
react-leaflet@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/react-leaflet/-/react-leaflet-2.2.1.tgz#c33974f518ffc8b3b7221f72e00c28963b95314d"
integrity sha512-q95486MsoKYmHFRDJyKRY/wdlKbaiTBfq23rfcG9WwsGNxaQuHLcIhxj3m9s4PiG3DImhz3Qfov6UUrsf+yMpw==
dependencies:
"@babel/runtime" "^7.2.0"
hoist-non-react-statics "^3.2.1"
lodash "^4.0.0"
lodash-es "^4.0.0"
warning "^4.0.0"
"@babel/runtime" "^7.3.1"
fast-deep-equal "^2.0.1"
hoist-non-react-statics "^3.3.0"
warning "^4.0.3"
react-lifecycles-compat@^3.0.0, react-lifecycles-compat@^3.0.4:
version "3.0.4"
@@ -10120,12 +10133,19 @@ warning@^3.0.0:
dependencies:
loose-envify "^1.0.0"
warning@^4.0.0, warning@^4.0.1:
warning@^4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.2.tgz#aa6876480872116fa3e11d434b0d0d8d91e44607"
dependencies:
loose-envify "^1.0.0"
warning@^4.0.3:
version "4.0.3"
resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.3.tgz#16e9e077eb8a86d6af7d64aa1e05fd85b4678ca3"
integrity sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==
dependencies:
loose-envify "^1.0.0"
watch@~0.18.0:
version "0.18.0"
resolved "https://registry.yarnpkg.com/watch/-/watch-0.18.0.tgz#28095476c6df7c90c963138990c0a5423eb4b986"