Compare commits

..

49 Commits

Author SHA1 Message Date
Alejandro Celaya
2ba86767fe Merge pull request #124 from acelaya/feature/paginated-charts
Feature/paginated charts
2019-03-16 09:11:01 +01:00
Alejandro Celaya
391424d8a1 Ensured bar charts are regenerated when their height changes 2019-03-16 09:02:40 +01:00
Alejandro Celaya
e0db6d5a57 Improved SortableBarGraph test 2019-03-10 17:55:02 +01:00
Alejandro Celaya
87dc24e8a2 Fixed and improved OpenMapModalBtn and ShortUrlVisit components tests 2019-03-10 13:05:20 +01:00
Alejandro Celaya
5233f5a07b Updated OpenMapModalBtn so that it allows showing only active cities 2019-03-10 12:09:54 +01:00
Alejandro Celaya
478ee59bb0 Updated cities chart so that map shows locations from current page when result set is paginated 2019-03-10 10:56:36 +01:00
Alejandro Celaya
b6f6b1ae9d Enabled stickiness on footer 2019-03-10 10:08:42 +01:00
Alejandro Celaya
1ad4290487 Applied some naming improvements 2019-03-10 09:54:40 +01:00
Alejandro Celaya
61480abd2e Updated charts to allow optional pagination 2019-03-10 08:28:14 +01:00
Alejandro Celaya
c094a27c97 Created PaginationDropdown component 2019-03-09 13:20:43 +01:00
Alejandro Celaya
83704ca4b5 Created rangeOf helper function which does a range + map 2019-03-09 12:19:33 +01:00
Alejandro Celaya
60576388c5 Merge pull request #122 from acelaya/feature/cancel-visits-load
Feature/cancel visits load
2019-03-08 19:56:45 +01:00
Alejandro Celaya
9f172c308c Ensured travis makes use of a working node version for builds 2019-03-08 19:50:47 +01:00
Alejandro Celaya
d7312d26f7 Added missing test for new action creator 2019-03-08 19:45:35 +01:00
Alejandro Celaya
4e6ef6ac53 Removed empty line 2019-03-08 19:43:27 +01:00
Alejandro Celaya
de563f9ebf Updated changelog 2019-03-08 19:42:07 +01:00
Alejandro Celaya
3982d77775 Ensured visits loading is cancelled when the visits page is unmounted 2019-03-08 19:40:43 +01:00
Alejandro Celaya
24bbbf6cb1 Merge pull request #121 from acelaya/feature/fix-empty-locations
Feature/fix empty locations
2019-03-05 14:33:33 +01:00
Alejandro Celaya
9ddd5de008 Updated changelog 2019-03-05 14:12:11 +01:00
Alejandro Celaya
87a4598391 Ensured maps modal btn is not rendered when the number of located cities is 0 2019-03-05 14:09:08 +01:00
Alejandro Celaya
701c143149 Updated ErrorHandler so that it logs errors in production 2019-03-05 14:04:52 +01:00
Alejandro Celaya
43097b93e5 Fixed docker build badge 2019-03-05 12:11:18 +01:00
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
47 changed files with 1019 additions and 366 deletions

View File

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

View File

@@ -26,6 +26,7 @@
"no-console": "warn",
"template-curly-spacing": ["error", "never"],
"no-warning-comments": "off",
"no-magic-numbers": "off",
"no-undefined": "off",
"indent": ["error", 2, {
"SwitchCase": 1

View File

@@ -1,20 +1,23 @@
language: node_js
node_js:
- "stable"
- "10.15.3"
cache:
yarn: true
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,82 @@ 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.3 - 2019-03-16
#### Added
* *Nothing*
#### Changed
* *Nothing*
#### Deprecated
* *Nothing*
#### Removed
* *Nothing*
#### Fixed
* [#120](https://github.com/shlinkio/shlink-web-client/issues/120) Fixed crash when visits page is loaded and there are no visits with known cities.
* [#113](https://github.com/shlinkio/shlink-web-client/issues/113) Ensured visits loading is cancelled when the visits page is unmounted. Requests on flight will still finish.
* [#118](https://github.com/shlinkio/shlink-web-client/issues/118) Fixed chart crashing when trying to render lots of bars by adding pagination.
## 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.3-alpine 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

@@ -1,7 +1,7 @@
# shlink-web-client
[![Build Status](https://img.shields.io/travis/shlinkio/shlink-web-client.svg?style=flat-square)](https://travis-ci.org/shlinkio/shlink-web-client)
[![Docker build status](https://img.shields.io/docker/build/shlinkio/shlink-web-client.svg?style=flat-square)](https://hub.docker.com/r/shlinkio/shlink-web-client/)
[![Docker build status](https://img.shields.io/docker/cloud/build/shlinkio/shlink-web-client.svg?style=flat-square)](https://hub.docker.com/r/shlinkio/shlink-web-client/)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/shlinkio/shlink-web-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/shlinkio/shlink-web-client/?branch=master)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/shlinkio/shlink-web-client.svg?style=flat-square)](https://scrutinizer-ci.com/g/shlinkio/shlink-web-client/?branch=master)
[![GitHub release](https://img.shields.io/github/release/shlinkio/shlink-web-client.svg?style=flat-square)](https://github.com/shlinkio/shlink-web-client/releases/latest)

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,15 +37,15 @@
"promise": "^8.0.1",
"prop-types": "^15.6.2",
"qs": "^6.5.2",
"ramda": "^0.25.0",
"react": "^16.7.0",
"ramda": "^0.26.1",
"react": "^16.8.0",
"react-autosuggest": "^9.4.0",
"react-chartjs-2": "^2.7.4",
"react-color": "^2.14.1",
"react-copy-to-clipboard": "^5.0.1",
"react-datepicker": "~1.5.0",
"react-dom": "^16.7.0",
"react-leaflet": "^2.1.4",
"react-dom": "^16.8.0",
"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,42 @@
import React from 'react';
import * as PropTypes from 'prop-types';
import './ErrorHandler.scss';
import { Button } from 'reactstrap';
const ErrorHandler = ({ location }, { error }) => class ErrorHandler extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
};
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(e) {
if (process.env.NODE_ENV !== 'development') {
error(e);
}
}
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,9 +3,11 @@ 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);
bottle.constant('console', global.console);
bottle.serviceFactory('ScrollToTop', ScrollToTop, 'window');
bottle.decorator('ScrollToTop', withRouter);
@@ -29,6 +31,8 @@ const provideServices = (bottle, connect, withRouter) => {
bottle.decorator('MenuLayout', withRouter);
bottle.serviceFactory('AsideMenu', AsideMenu, 'DeleteServerButton');
bottle.serviceFactory('ErrorHandler', ErrorHandler, 'window', 'console');
};
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

@@ -51,3 +51,11 @@ body,
margin: 0 auto !important;
}
}
.pagination .page-link {
cursor: pointer;
}
.paddingless {
padding: 0;
}

View File

@@ -2,7 +2,7 @@ import React from 'react';
import { Link } from 'react-router-dom';
import { Pagination, PaginationItem, PaginationLink } from 'reactstrap';
import PropTypes from 'prop-types';
import { range } from 'ramda';
import { rangeOf } from '../utils/utils';
const propTypes = {
serverId: PropTypes.string.isRequired,
@@ -20,7 +20,7 @@ export default function Paginator({ paginator = {}, serverId }) {
}
const renderPages = () =>
range(1, pagesCount + 1).map((pageNumber) => (
rangeOf(pagesCount, (pageNumber) => (
<PaginationItem key={pageNumber} active={currentPage === pageNumber}>
<PaginationLink
tag={Link}

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

@@ -0,0 +1,33 @@
import React from 'react';
import { DropdownItem, DropdownMenu, DropdownToggle, UncontrolledDropdown } from 'reactstrap';
import * as PropTypes from 'prop-types';
const propTypes = {
toggleClassName: PropTypes.string,
ranges: PropTypes.arrayOf(PropTypes.number).isRequired,
value: PropTypes.number.isRequired,
setValue: PropTypes.func.isRequired,
};
const PaginationDropdown = ({ toggleClassName, ranges, value, setValue }) => (
<UncontrolledDropdown>
<DropdownToggle caret color="link" className={toggleClassName}>
Paginate
</DropdownToggle>
<DropdownMenu right>
{ranges.map((itemsPerPage) => (
<DropdownItem key={itemsPerPage} active={itemsPerPage === value} onClick={() => setValue(itemsPerPage)}>
<b>{itemsPerPage}</b> items per page
</DropdownItem>
))}
<DropdownItem divider />
<DropdownItem disabled={value === Infinity} onClick={() => setValue(Infinity)}>
<i>Clear pagination</i>
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
);
PaginationDropdown.propTypes = propTypes;
export default PaginationDropdown;

View File

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

View File

@@ -33,7 +33,7 @@ const SortingDropdown = ({ items, orderField, orderDir, onChange, isButton, righ
<DropdownToggle
caret
color={isButton ? 'secondary' : 'link'}
className={classNames({ 'btn-block': isButton, 'btn-sm sorting-dropdown__paddingless': !isButton })}
className={classNames({ 'btn-block': isButton, 'btn-sm paddingless': !isButton })}
>
Order by
</DropdownToggle>

View File

@@ -10,7 +10,3 @@
margin: 3.5px 0 0;
float: right;
}
.sorting-dropdown__paddingless.sorting-dropdown__paddingless {
padding: 0;
}

View File

@@ -1,15 +1,11 @@
import { range } from 'ramda';
import PropTypes from 'prop-types';
import { rangeOf } from '../utils';
const HEX_COLOR_LENGTH = 6;
const { floor, random } = Math;
const letters = '0123456789ABCDEF';
const buildRandomColor = () =>
`#${
range(0, HEX_COLOR_LENGTH)
.map(() => letters[floor(random() * letters.length)])
.join('')
}`;
`#${rangeOf(HEX_COLOR_LENGTH, () => letters[floor(random() * letters.length)]).join('')}`;
const normalizeKey = (key) => key.toLowerCase().trim();
export default class ColorGenerator {

View File

@@ -2,8 +2,11 @@ import L from 'leaflet';
import marker2x from 'leaflet/dist/images/marker-icon-2x.png';
import marker from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import { range } from 'ramda';
const TEN_ROUNDING_NUMBER = 10;
const DEFAULT_TIMEOUT_DELAY = 2000;
const { ceil } = Math;
export const stateFlagTimeout = (setTimeout) => (
setState,
@@ -37,3 +40,7 @@ export const fixLeafletIcons = () => {
shadowUrl: markerShadow,
});
};
export const rangeOf = (size, mappingFn, startAt = 1) => range(startAt, size + 1).map(mappingFn);
export const roundTen = (number) => ceil(number / TEN_ROUNDING_NUMBER) * TEN_ROUNDING_NUMBER;

View File

@@ -1,18 +1,16 @@
import { Card, CardHeader, CardBody } from 'reactstrap';
import { Card, CardHeader, CardBody, CardFooter } from 'reactstrap';
import { Doughnut, HorizontalBar } from 'react-chartjs-2';
import PropTypes from 'prop-types';
import React from 'react';
import { keys, values } from 'ramda';
import './GraphCard.scss';
const propTypes = {
title: PropTypes.string,
children: PropTypes.node,
title: PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]),
footer: PropTypes.oneOfType([ PropTypes.string, PropTypes.node ]),
isBarChart: PropTypes.bool,
stats: PropTypes.object,
matchMedia: PropTypes.func,
};
const defaultProps = {
matchMedia: global.window ? global.window.matchMedia : () => {},
max: PropTypes.number,
};
const generateGraphData = (title, isBarChart, labels, data) => ({
@@ -36,62 +34,43 @@ const generateGraphData = (title, isBarChart, labels, data) => ({
],
});
const determineGraphAspectRatio = (barsCount, isBarChart, matchMedia) => {
const determineAspectRationModifier = () => {
switch (true) {
case matchMedia('(max-width: 1200px)').matches:
return 1.5; // eslint-disable-line no-magic-numbers
case matchMedia('(max-width: 992px)').matches:
return 1.75; // eslint-disable-line no-magic-numbers
case matchMedia('(max-width: 768px)').matches:
return 2; // eslint-disable-line no-magic-numbers
case matchMedia('(max-width: 576px)').matches:
return 2.25; // eslint-disable-line no-magic-numbers
default:
return 1;
}
};
const dropLabelIfHidden = (label) => label.startsWith('hidden') ? '' : label;
const MAX_BARS_WITHOUT_HEIGHT = 20;
const DEFAULT_ASPECT_RATION = 2;
const shouldCalculateAspectRatio = isBarChart && barsCount > MAX_BARS_WITHOUT_HEIGHT;
return shouldCalculateAspectRatio
? MAX_BARS_WITHOUT_HEIGHT / determineAspectRationModifier() * DEFAULT_ASPECT_RATION / barsCount
: DEFAULT_ASPECT_RATION;
};
const renderGraph = (title, isBarChart, stats, matchMedia) => {
const renderGraph = (title, isBarChart, stats, max) => {
const Component = isBarChart ? HorizontalBar : Doughnut;
const labels = keys(stats);
const labels = keys(stats).map(dropLabelIfHidden);
const data = values(stats);
const aspectRatio = determineGraphAspectRatio(labels.length, isBarChart, matchMedia);
const options = {
aspectRatio,
legend: isBarChart ? { display: false } : { position: 'right' },
scales: isBarChart ? {
scales: isBarChart && {
xAxes: [
{
ticks: { beginAtZero: true },
ticks: { beginAtZero: true, max },
},
],
} : null,
},
tooltips: {
intersect: !isBarChart,
// Do not show tooltip on items with empty label when in a bar chart
filter: ({ yLabel }) => !isBarChart || yLabel !== '',
},
};
const graphData = generateGraphData(title, isBarChart, labels, data);
const height = isBarChart && labels.length > 20 ? labels.length * 8 : null;
return <Component data={generateGraphData(title, isBarChart, labels, data)} options={options} height={null} />;
// Provide a key based on the height, so that every time the dataset changes, a new graph is rendered
return <Component key={height} data={graphData} options={options} height={height} />;
};
const GraphCard = ({ title, children, isBarChart, stats, matchMedia }) => (
const GraphCard = ({ title, footer, isBarChart, stats, max }) => (
<Card className="mt-4">
<CardHeader className="graph-card__header">{children || title}</CardHeader>
<CardBody>{renderGraph(title, isBarChart, stats, matchMedia)}</CardBody>
<CardHeader className="graph-card__header">{typeof title === 'function' ? title() : title}</CardHeader>
<CardBody>{renderGraph(title, isBarChart, stats, max)}</CardBody>
{footer && <CardFooter className="graph-card__footer--sticky">{footer}</CardFooter>}
</Card>
);
GraphCard.propTypes = propTypes;
GraphCard.defaultProps = defaultProps;
export default GraphCard;

View File

@@ -0,0 +1,4 @@
.graph-card__footer--sticky {
position: sticky;
bottom: 0;
}

View File

@@ -8,20 +8,15 @@ 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 },
OpenMapModalBtn
) => class ShortUrlVisits extends React.PureComponent {
static propTypes = {
match: PropTypes.shape({
params: PropTypes.object,
@@ -30,33 +25,47 @@ const ShortUrlVisits = ({
shortUrlVisits: shortUrlVisitsType,
getShortUrlDetail: PropTypes.func,
shortUrlDetail: shortUrlDetailType,
cancelGetShortUrlVisits: PropTypes.func,
};
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);
}
componentWillUnmount() {
this.props.cancelGetShortUrlVisits();
}
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 +80,23 @@ const ShortUrlVisits = ({
return <MutedMessage>There are no visits matching current filter :(</MutedMessage>;
}
const { os, browsers, referrers, countries, cities, citiesForMap } = processStatsFromVisits(
{ id: this.memoizationId, visits }
);
const mapLocations = values(citiesForMap);
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}
withPagination={false}
title="Referrers"
sortingItems={{
name: 'Referrer name',
@@ -91,7 +106,7 @@ const ShortUrlVisits = ({
</div>
<div className="col-lg-6">
<SortableBarGraph
stats={processCountriesStats(visits)}
stats={countries}
title="Countries"
sortingItems={{
name: 'Country name',
@@ -101,16 +116,12 @@ const ShortUrlVisits = ({
</div>
<div className="col-lg-6">
<SortableBarGraph
stats={processCitiesStats(visits)}
stats={cities}
title="Cities"
extraHeaderContent={[
() => (
<OpenMapModalBtn
modalTitle="Cities"
locations={values(processCitiesStatsForMap(visits))}
/>
),
]}
extraHeaderContent={(activeCities) =>
mapLocations.length > 0 &&
<OpenMapModalBtn modalTitle="Cities" locations={mapLocations} activeCities={activeCities} />
}
sortingItems={{
name: 'City name',
amount: 'Visits amount',
@@ -133,7 +144,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 +154,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

@@ -1,61 +1,124 @@
import React from 'react';
import PropTypes from 'prop-types';
import { fromPairs, head, keys, pipe, prop, reverse, sortBy, toLower, toPairs, type } from 'ramda';
import { fromPairs, head, keys, pipe, prop, reverse, sortBy, splitEvery, toLower, toPairs, type } from 'ramda';
import { Pagination, PaginationItem, PaginationLink } from 'reactstrap';
import SortingDropdown from '../utils/SortingDropdown';
import PaginationDropdown from '../utils/PaginationDropdown';
import { rangeOf, roundTen } from '../utils/utils';
import GraphCard from './GraphCard';
const { max } = Math;
const toLowerIfString = (value) => type(value) === 'String' ? toLower(value) : value;
const pickValueFromPair = ([ , value ]) => value;
export default class SortableBarGraph extends React.Component {
static propTypes = {
stats: PropTypes.object.isRequired,
title: PropTypes.string.isRequired,
sortingItems: PropTypes.object.isRequired,
extraHeaderContent: PropTypes.arrayOf(PropTypes.func),
extraHeaderContent: PropTypes.func,
withPagination: PropTypes.bool,
};
state = {
orderField: undefined,
orderDir: undefined,
currentPage: 1,
itemsPerPage: Infinity,
};
render() {
const { stats, sortingItems, title, extraHeaderContent } = this.props;
const sortStats = () => {
if (!this.state.orderField) {
return stats;
}
determineStats(stats, sortingItems) {
const pairs = toPairs(stats);
const sortedPairs = !this.state.orderField ? pairs : sortBy(
pipe(
prop(this.state.orderField === head(keys(sortingItems)) ? 0 : 1),
toLowerIfString
),
pairs
);
const directionalPairs = !this.state.orderDir || this.state.orderDir === 'ASC' ? sortedPairs : reverse(sortedPairs);
const sortedPairs = sortBy(
pipe(
prop(this.state.orderField === head(keys(sortingItems)) ? 0 : 1),
toLowerIfString
),
toPairs(stats)
);
if (directionalPairs.length <= this.state.itemsPerPage) {
return { currentPageStats: fromPairs(directionalPairs) };
}
return fromPairs(this.state.orderDir === 'ASC' ? sortedPairs : reverse(sortedPairs));
const pages = splitEvery(this.state.itemsPerPage, directionalPairs);
return {
currentPageStats: fromPairs(this.determineCurrentPagePairs(pages)),
pagination: this.renderPagination(pages.length),
max: roundTen(max(...directionalPairs.map(pickValueFromPair))),
};
}
determineCurrentPagePairs(pages) {
const page = pages[this.state.currentPage - 1];
if (this.state.currentPage < pages.length) {
return page;
}
const firstPageLength = pages[0].length;
// Using the "hidden" key, the chart will just replace the label by an empty string
return [ ...page, ...rangeOf(firstPageLength - page.length, (i) => [ `hidden_${i}`, 0 ]) ];
}
renderPagination(pagesCount) {
const { currentPage } = this.state;
return (
<GraphCard stats={sortStats()} isBarChart>
<Pagination listClassName="flex-wrap mb-0">
<PaginationItem disabled={currentPage === 1}>
<PaginationLink previous tag="span" onClick={() => this.setState({ currentPage: currentPage - 1 })} />
</PaginationItem>
{rangeOf(pagesCount, (page) => (
<PaginationItem key={page} active={page === currentPage}>
<PaginationLink tag="span" onClick={() => this.setState({ currentPage: page })}>{page}</PaginationLink>
</PaginationItem>
))}
<PaginationItem disabled={currentPage >= pagesCount}>
<PaginationLink next tag="span" onClick={() => this.setState({ currentPage: currentPage + 1 })} />
</PaginationItem>
</Pagination>
);
}
render() {
const { stats, sortingItems, title, extraHeaderContent, withPagination = true } = this.props;
const { currentPageStats, pagination, max } = this.determineStats(stats, sortingItems);
const activeCities = keys(currentPageStats);
const computeTitle = () => (
<React.Fragment>
{title}
<div className="float-right">
<SortingDropdown
isButton={false}
right
items={sortingItems}
orderField={this.state.orderField}
orderDir={this.state.orderDir}
items={sortingItems}
onChange={(orderField, orderDir) => this.setState({ orderField, orderDir })}
onChange={(orderField, orderDir) => this.setState({ orderField, orderDir, currentPage: 1 })}
/>
</div>
{extraHeaderContent && extraHeaderContent.map((content, index) => (
<div key={index} className="float-right">
{content()}
{withPagination && keys(stats).length > 50 && (
<div className="float-right">
<PaginationDropdown
toggleClassName="btn-sm paddingless mr-3"
ranges={[ 50, 100, 200, 500 ]}
value={this.state.itemsPerPage}
setValue={(itemsPerPage) => this.setState({ itemsPerPage, currentPage: 1 })}
/>
</div>
))}
</GraphCard>
)}
{extraHeaderContent && (
<div className="float-right">
{extraHeaderContent(pagination ? activeCities : undefined)}
</div>
)}
</React.Fragment>
);
return <GraphCard isBarChart title={computeTitle} stats={currentPageStats} footer={pagination} max={max} />;
}
}

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,22 @@ const OpenStreetMapTile = () => (
/>
);
const calculateMapProps = (locations) => {
if (locations.length === 0) {
return {};
}
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 +49,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,32 +1,60 @@
import React from 'react';
import React, { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMapMarkedAlt as mapIcon } from '@fortawesome/free-solid-svg-icons';
import { UncontrolledTooltip } from 'reactstrap';
import { Dropdown, DropdownItem, DropdownMenu, UncontrolledTooltip } from 'reactstrap';
import * as PropTypes from 'prop-types';
import MapModal from './MapModal';
import './OpenMapModalBtn.scss';
export default class OpenMapModalBtn extends React.Component {
static propTypes = {
modalTitle: PropTypes.string.isRequired,
locations: PropTypes.arrayOf(PropTypes.object),
};
const propTypes = {
modalTitle: PropTypes.string.isRequired,
locations: PropTypes.arrayOf(PropTypes.object),
activeCities: PropTypes.arrayOf(PropTypes.string),
};
state = { mapIsOpened: false };
const OpenMapModalBtn = (MapModal) => {
const OpenMapModalBtn = ({ modalTitle, locations = [], activeCities }) => {
const [ mapIsOpened, setMapIsOpened ] = useState(false);
const [ dropdownIsOpened, setDropdownIsOpened ] = useState(false);
const [ locationsToShow, setLocationsToShow ] = useState([]);
render() {
const { modalTitle, locations = [] } = this.props;
const toggleMap = () => this.setState(({ mapIsOpened }) => ({ mapIsOpened: !mapIsOpened }));
const buttonRef = React.createRef();
const filterLocations = (locations) => locations.filter(({ cityName }) => activeCities.includes(cityName));
const toggleMap = () => setMapIsOpened(!mapIsOpened);
const onClick = () => {
if (!activeCities) {
setLocationsToShow(locations);
setMapIsOpened(true);
return;
}
setDropdownIsOpened(true);
};
const openMapWithLocations = (filtered) => () => {
setLocationsToShow(filtered ? filterLocations(locations) : locations);
setMapIsOpened(true);
};
return (
<React.Fragment>
<button className="btn btn-link open-map-modal-btn__btn" ref={buttonRef} onClick={toggleMap}>
<button className="btn btn-link open-map-modal-btn__btn" ref={buttonRef} onClick={onClick}>
<FontAwesomeIcon icon={mapIcon} />
</button>
<UncontrolledTooltip placement="bottom" target={() => buttonRef.current}>Show in map</UncontrolledTooltip>
<MapModal toggle={toggleMap} isOpen={this.state.mapIsOpened} title={modalTitle} locations={locations} />
<UncontrolledTooltip placement="left" target={() => buttonRef.current}>Show in map</UncontrolledTooltip>
<Dropdown isOpen={dropdownIsOpened} toggle={() => setDropdownIsOpened(!dropdownIsOpened)} inNavbar>
<DropdownMenu right>
<DropdownItem onClick={openMapWithLocations(false)}>Show all locations</DropdownItem>
<DropdownItem onClick={openMapWithLocations(true)}>Show locations in current page</DropdownItem>
</DropdownMenu>
</Dropdown>
<MapModal toggle={toggleMap} isOpen={mapIsOpened} title={modalTitle} locations={locationsToShow} />
</React.Fragment>
);
}
}
};
OpenMapModalBtn.propTypes = propTypes;
return OpenMapModalBtn;
};
export default OpenMapModalBtn;

View File

@@ -1,9 +1,12 @@
import PropTypes from 'prop-types';
import { flatten, prop, 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';
export const GET_SHORT_URL_VISITS_CANCEL = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_CANCEL';
/* eslint-enable padding-line-between-statements, newline-after-var */
export const shortUrlVisitsType = PropTypes.shape({
@@ -15,7 +18,9 @@ export const shortUrlVisitsType = PropTypes.shape({
const initialState = {
visits: [],
loading: false,
loadingLarge: false,
error: false,
cancelLoad: false,
};
export default function reducer(state = initialState, action) {
@@ -24,18 +29,34 @@ export default function reducer(state = initialState, action) {
return {
...state,
loading: true,
loadingLarge: false,
cancelLoad: false,
};
case GET_SHORT_URL_VISITS_ERROR:
return {
...state,
loading: false,
loadingLarge: false,
error: true,
cancelLoad: false,
};
case GET_SHORT_URL_VISITS:
return {
visits: action.visits,
loading: false,
loadingLarge: false,
error: false,
cancelLoad: false,
};
case GET_SHORT_URL_VISITS_LARGE:
return {
...state,
loadingLarge: true,
};
case GET_SHORT_URL_VISITS_CANCEL:
return {
...state,
cancelLoad: true,
};
default:
return state;
@@ -58,9 +79,42 @@ 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 { shortUrlVisits: { cancelLoad } } = getState();
if (cancelLoad) {
return [];
}
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(
(page) =>
getShortUrlVisits(shortCode, { ...dates, page, itemsPerPage })
.then(prop('data'))
)).then(flatten);
try {
const visits = await loadVisits();
@@ -69,3 +123,5 @@ export const getShortUrlVisits = (buildShlinkApiClient) => (shortCode, dates) =>
dispatch({ type: GET_SHORT_URL_VISITS_ERROR });
}
};
export const cancelGetShortUrlVisits = () => ({ type: GET_SHORT_URL_VISITS_CANCEL });

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

@@ -1,14 +1,18 @@
import ShortUrlVisits from '../ShortUrlVisits';
import { getShortUrlVisits } from '../reducers/shortUrlVisits';
import { cancelGetShortUrlVisits, getShortUrlVisits } from '../reducers/shortUrlVisits';
import { getShortUrlDetail } from '../reducers/shortUrlDetail';
import OpenMapModalBtn from '../helpers/OpenMapModalBtn';
import MapModal from '../helpers/MapModal';
import * as visitsParser from './VisitsParser';
const provideServices = (bottle, connect) => {
// Components
bottle.serviceFactory('ShortUrlVisits', ShortUrlVisits, 'VisitsParser');
bottle.serviceFactory('OpenMapModalBtn', OpenMapModalBtn, 'MapModal');
bottle.serviceFactory('MapModal', () => MapModal);
bottle.serviceFactory('ShortUrlVisits', ShortUrlVisits, 'VisitsParser', 'OpenMapModalBtn');
bottle.decorator('ShortUrlVisits', connect(
[ 'shortUrlVisits', 'shortUrlDetail' ],
[ 'getShortUrlVisits', 'getShortUrlDetail' ]
[ 'getShortUrlVisits', 'getShortUrlDetail', 'cancelGetShortUrlVisits' ]
));
// Services
@@ -17,6 +21,7 @@ const provideServices = (bottle, connect) => {
// Actions
bottle.serviceFactory('getShortUrlVisits', getShortUrlVisits, 'buildShlinkApiClient');
bottle.serviceFactory('getShortUrlDetail', getShortUrlDetail, 'buildShlinkApiClient');
bottle.serviceFactory('cancelGetShortUrlVisits', () => cancelGetShortUrlVisits);
};
export default provideServices;

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,37 @@
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(),
},
};
const console = { error: jest.fn() };
let wrapper;
beforeEach(() => {
const ErrorHandler = createErrorHandler(window, console);
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

@@ -53,7 +53,7 @@ describe('<ShortUrlsRow />', () => {
});
it('renders long URL in third row', () => {
const col = wrapper.find('td').at(2); // eslint-disable-line no-magic-numbers
const col = wrapper.find('td').at(2);
const link = col.find(ExternalLink);
expect(link.prop('href')).toEqual(shortUrl.longUrl);
@@ -61,7 +61,7 @@ describe('<ShortUrlsRow />', () => {
describe('renders list of tags in fourth row', () => {
it('with tags', () => {
const col = wrapper.find('td').at(3); // eslint-disable-line no-magic-numbers
const col = wrapper.find('td').at(3);
const tags = col.find(Tag);
expect(tags).toHaveLength(shortUrl.tags.length);
@@ -75,20 +75,20 @@ describe('<ShortUrlsRow />', () => {
it('without tags', () => {
wrapper.setProps({ shortUrl: assoc('tags', [], shortUrl) });
const col = wrapper.find('td').at(3); // eslint-disable-line no-magic-numbers
const col = wrapper.find('td').at(3);
expect(col.text()).toContain('No tags');
});
});
it('renders visits count in fifth row', () => {
const col = wrapper.find('td').at(4); // eslint-disable-line no-magic-numbers
const col = wrapper.find('td').at(4);
expect(col.text()).toEqual(toString(shortUrl.visitsCount));
});
it('updates state when copied to clipboard', () => {
const col = wrapper.find('td').at(5); // eslint-disable-line no-magic-numbers
const col = wrapper.find('td').at(5);
const menu = col.find(ShortUrlsRowMenu);
expect(menu).toHaveLength(1);
@@ -98,7 +98,6 @@ describe('<ShortUrlsRow />', () => {
});
it('shows copy hint when state prop is true', () => {
// eslint-disable-next-line no-magic-numbers
const isHidden = () => wrapper.find('td').at(5).find('.short-urls-row__copy-hint').prop('hidden');
expect(isHidden()).toEqual(true);

View File

@@ -1,10 +1,11 @@
import React from 'react';
import { shallow } from 'enzyme';
import { identity, range } from 'ramda';
import { identity } from 'ramda';
import * as sinon from 'sinon';
import createTagsList from '../../src/tags/TagsList';
import MuttedMessage from '../../src/utils/MuttedMessage';
import SearchField from '../../src/utils/SearchField';
import { rangeOf } from '../../src/utils/utils';
describe('<TagsList />', () => {
let wrapper;
@@ -53,7 +54,7 @@ describe('<TagsList />', () => {
it('renders the proper amount of groups and cards based on the amount of tags', () => {
const amountOfTags = 10;
const amountOfGroups = 4;
const wrapper = createWrapper({ filteredTags: range(0, amountOfTags).map((i) => `tag_${i}`) });
const wrapper = createWrapper({ filteredTags: rangeOf(amountOfTags, (i) => `tag_${i}`) });
const cards = wrapper.find(TagCard);
const groups = wrapper.find('.col-md-6');

View File

@@ -3,7 +3,13 @@ import L from 'leaflet';
import marker2x from 'leaflet/dist/images/marker-icon-2x.png';
import marker from 'leaflet/dist/images/marker-icon.png';
import markerShadow from 'leaflet/dist/images/marker-shadow.png';
import { stateFlagTimeout as stateFlagTimeoutFactory, determineOrderDir, fixLeafletIcons } from '../../src/utils/utils';
import {
stateFlagTimeout as stateFlagTimeoutFactory,
determineOrderDir,
fixLeafletIcons,
rangeOf,
roundTen,
} from '../../src/utils/utils';
describe('utils', () => {
describe('stateFlagTimeout', () => {
@@ -57,4 +63,46 @@ describe('utils', () => {
expect(shadowUrl).toEqual(markerShadow);
});
});
describe('rangeOf', () => {
const func = (i) => `result_${i}`;
const size = 5;
it('builds a range of specified size invike provided function', () => {
expect(rangeOf(size, func)).toEqual([
'result_1',
'result_2',
'result_3',
'result_4',
'result_5',
]);
});
it('builds a range starting at provided pos', () => {
const startAt = 3;
expect(rangeOf(size, func, startAt)).toEqual([
'result_3',
'result_4',
'result_5',
]);
});
});
describe('roundTen', () => {
it('rounds provided number to the next multiple of ten', () => {
const expectationsPairs = [
[ 10, 10 ],
[ 12, 20 ],
[ 158, 160 ],
[ 5, 10 ],
[ -42, -40 ],
];
expect.assertions(expectationsPairs.length);
expectationsPairs.forEach(([ number, expected ]) => {
expect(roundTen(number)).toEqual(expected);
});
});
});
});

View File

@@ -39,7 +39,7 @@ describe('<GraphCard />', () => {
]);
expect(borderColor).toEqual('white');
expect(legend).toEqual({ position: 'right' });
expect(scales).toBeNull();
expect(scales).toBeUndefined();
});
it('renders HorizontalBar when is not a bar chart', () => {

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
@@ -34,6 +29,7 @@ describe('<ShortUrlVisits />', () => {
match={match}
shortUrlVisits={shortUrlVisits}
shortUrlDetail={{}}
cancelGetShortUrlVisits={identity}
/>
);
@@ -48,7 +44,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 +52,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);
@@ -100,6 +104,6 @@ describe('<ShortUrlVisits />', () => {
const extraHeaderContent = citiesGraph.prop('extraHeaderContent');
expect(extraHeaderContent).toHaveLength(1);
expect(typeof extraHeaderContent[0]).toEqual('function');
expect(typeof extraHeaderContent).toEqual('function');
});
});

View File

@@ -1,9 +1,11 @@
import React from 'react';
import { shallow } from 'enzyme';
import { keys, values } from 'ramda';
import { keys, range, values } from 'ramda';
import SortableBarGraph from '../../src/visits/SortableBarGraph';
import GraphCard from '../../src/visits/GraphCard';
import SortingDropdown from '../../src/utils/SortingDropdown';
import PaginationDropdown from '../../src/utils/PaginationDropdown';
import { rangeOf } from '../../src/utils/utils';
describe('<SortableBarGraph />', () => {
let wrapper;
@@ -15,9 +17,14 @@ describe('<SortableBarGraph />', () => {
Foo: 100,
Bar: 50,
};
const createWrapper = (extraHeaderContent = []) => {
const createWrapper = (withPagination = false, extraStats = {}) => {
wrapper = shallow(
<SortableBarGraph title="Foo" stats={stats} sortingItems={sortingItems} extraHeaderContent={extraHeaderContent} />
<SortableBarGraph
title="Foo"
stats={{ ...stats, ...extraStats }}
sortingItems={sortingItems}
withPagination={withPagination}
/>
);
return wrapper;
@@ -37,7 +44,7 @@ describe('<SortableBarGraph />', () => {
beforeEach(() => {
const wrapper = createWrapper();
const dropdown = wrapper.find(SortingDropdown);
const dropdown = wrapper.renderProp('title')().find(SortingDropdown);
assert = (sortName, sortDir, expectedKeys, expectedValues, done) => {
dropdown.prop('onChange')(sortName, sortDir);
@@ -53,26 +60,62 @@ describe('<SortableBarGraph />', () => {
};
});
// eslint-disable-next-line no-magic-numbers
it('name - ASC', (done) => assert('name', 'ASC', [ 'Bar', 'Foo' ], [ 50, 100 ], done));
// eslint-disable-next-line no-magic-numbers
it('name - DESC', (done) => assert('name', 'DESC', [ 'Foo', 'Bar' ], [ 100, 50 ], done));
// eslint-disable-next-line no-magic-numbers
it('value - ASC', (done) => assert('value', 'ASC', [ 'Bar', 'Foo' ], [ 50, 100 ], done));
// eslint-disable-next-line no-magic-numbers
it('value - DESC', (done) => assert('value', 'DESC', [ 'Foo', 'Bar' ], [ 100, 50 ], done));
});
it('renders extra header functions', () => {
const wrapper = createWrapper([
() => <span className="foo-span">Foo</span>,
() => <span className="bar-span">Bar</span>,
]);
describe('renders properly paginated stats when pagination is set', () => {
let assert;
expect(wrapper.find('.foo-span')).toHaveLength(1);
expect(wrapper.find('.bar-span')).toHaveLength(1);
beforeEach(() => {
const wrapper = createWrapper(true, range(1, 159).reduce((accum, value) => {
accum[`key_${value}`] = value;
return accum;
}, {}));
const dropdown = wrapper.renderProp('title')().find(PaginationDropdown);
assert = (itemsPerPage, expectedStats, done) => {
dropdown.prop('setValue')(itemsPerPage);
setImmediate(() => {
const graphCard = wrapper.find(GraphCard);
const statsKeys = keys(graphCard.prop('stats'));
expect(statsKeys).toEqual(expectedStats);
done();
});
};
});
const buildExpected = (size) => [ 'Foo', 'Bar', ...rangeOf(size - 2, (i) => `key_${i}`) ];
it('50 items per page', (done) => assert(50, buildExpected(50), done));
it('100 items per page', (done) => assert(100, buildExpected(100), done));
it('200 items per page', (done) => assert(200, buildExpected(160), done));
it('500 items per page', (done) => assert(500, buildExpected(160), done));
});
it('renders extra header content', () => {
wrapper = shallow(
<span>
<SortableBarGraph
title="Foo"
stats={stats}
sortingItems={sortingItems}
extraHeaderContent={() => (
<span>
<span className="foo-span">Foo</span>
<span className="bar-span">Bar</span>
</span>
)}
/>
</span>
).find(SortableBarGraph);
const header = wrapper.renderProp('extraHeaderContent')();
expect(header.find('.foo-span')).toHaveLength(1);
expect(header.find('.bar-span')).toHaveLength(1);
});
});

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

@@ -1,42 +1,97 @@
import React from 'react';
import { shallow } from 'enzyme';
import { UncontrolledTooltip } from 'reactstrap';
import OpenMapModalBtn from '../../../src/visits/helpers/OpenMapModalBtn';
import MapModal from '../../../src/visits/helpers/MapModal';
import { mount } from 'enzyme';
import { Dropdown, DropdownItem, UncontrolledTooltip } from 'reactstrap';
import createOpenMapModalBtn from '../../../src/visits/helpers/OpenMapModalBtn';
describe('<OpenMapModalBtn />', () => {
let wrapper;
const title = 'Foo';
const locations = [];
const locations = [
{
cityName: 'foo',
count: 30,
},
{
cityName: 'bar',
count: 45,
},
];
const MapModal = () => '';
const OpenMapModalBtn = createOpenMapModalBtn(MapModal);
const createWrapper = (activeCities) => {
wrapper = mount(<OpenMapModalBtn modalTitle={title} locations={locations} activeCities={activeCities} />);
beforeEach(() => {
wrapper = shallow(<OpenMapModalBtn modalTitle={title} locations={locations} />);
});
return wrapper;
};
afterEach(() => wrapper.unmount());
afterEach(() => wrapper && wrapper.unmount());
it('Renders expected content', () => {
it('renders expected content', () => {
const wrapper = createWrapper();
const button = wrapper.find('.open-map-modal-btn__btn');
const tooltip = wrapper.find(UncontrolledTooltip);
const dropdown = wrapper.find(Dropdown);
const modal = wrapper.find(MapModal);
expect(button).toHaveLength(1);
expect(tooltip).toHaveLength(1);
expect(dropdown).toHaveLength(1);
expect(modal).toHaveLength(1);
});
it('changes modal visibility when toggled', () => {
const modal = wrapper.find(MapModal);
it('sets provided props to the map', (done) => {
const wrapper = createWrapper();
const button = wrapper.find('.open-map-modal-btn__btn');
expect(wrapper.state('mapIsOpened')).toEqual(false);
modal.prop('toggle')();
expect(wrapper.state('mapIsOpened')).toEqual(true);
button.simulate('click');
setImmediate(() => {
const modal = wrapper.find(MapModal);
expect(modal.prop('title')).toEqual(title);
expect(modal.prop('locations')).toEqual(locations);
expect(modal.prop('isOpen')).toEqual(true);
done();
});
});
it('sets provided props to the map', () => {
const modal = wrapper.find(MapModal);
it('opens dropdown instead of modal when a list of active cities has been provided', (done) => {
const wrapper = createWrapper([ 'bar' ]);
const button = wrapper.find('.open-map-modal-btn__btn');
expect(modal.prop('title')).toEqual(title);
expect(modal.prop('locations')).toEqual(locations);
button.simulate('click');
setImmediate(() => {
const dropdown = wrapper.find(Dropdown);
const modal = wrapper.find(MapModal);
expect(dropdown.prop('isOpen')).toEqual(true);
expect(modal.prop('isOpen')).toEqual(false);
done();
});
});
it('filters out non-active cities from list of locations', (done) => {
const wrapper = createWrapper([ 'bar' ]);
const button = wrapper.find('.open-map-modal-btn__btn');
button.simulate('click');
setImmediate(() => {
const dropdown = wrapper.find(Dropdown);
const item = dropdown.find(DropdownItem).at(1);
item.simulate('click');
setImmediate(() => {
const modal = wrapper.find(MapModal);
expect(modal.prop('title')).toEqual(title);
expect(modal.prop('locations')).toEqual([
{
cityName: 'bar',
count: 45,
},
]);
done();
});
});
});
});

View File

@@ -1,9 +1,12 @@
import * as sinon from 'sinon';
import reducer, {
getShortUrlVisits,
cancelGetShortUrlVisits,
GET_SHORT_URL_VISITS_START,
GET_SHORT_URL_VISITS_ERROR,
GET_SHORT_URL_VISITS,
GET_SHORT_URL_VISITS_LARGE,
GET_SHORT_URL_VISITS_CANCEL,
} from '../../../src/visits/reducers/shortUrlVisits';
describe('shortUrlVisitsReducer', () => {
@@ -15,6 +18,20 @@ 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('returns cancelLoad on GET_SHORT_URL_VISITS_CANCEL', () => {
const state = reducer({ cancelLoad: false }, { type: GET_SHORT_URL_VISITS_CANCEL });
const { cancelLoad } = state;
expect(cancelLoad).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;
@@ -50,7 +67,9 @@ describe('shortUrlVisitsReducer', () => {
getShortUrlVisits: typeof returned === 'function' ? sinon.fake(returned) : sinon.fake.returns(returned),
});
const dispatchMock = sinon.spy();
const getState = () => ({});
const getState = () => ({
shortUrlVisits: { cancelVisits: false },
});
beforeEach(() => dispatchMock.resetHistory());
@@ -118,4 +137,9 @@ describe('shortUrlVisitsReducer', () => {
expect(visits).toEqual([{}, {}, {}, {}, {}, {}]);
});
});
describe('cancelGetShortUrlVisits', () => {
it('just returns the action with proper type', () =>
expect(cancelGetShortUrlVisits()).toEqual({ type: GET_SHORT_URL_VISITS_CANCEL }));
});
});

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,

102
yarn.lock
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"
@@ -8050,14 +8064,15 @@ react-dev-utils@^7.0.1:
strip-ansi "4.0.0"
text-table "0.2.0"
react-dom@^16.7.0:
version "16.7.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.7.0.tgz#a17b2a7ca89ee7390bc1ed5eb81783c7461748b8"
react-dom@^16.8.0:
version "16.8.4"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.8.4.tgz#1061a8e01a2b3b0c8160037441c3bf00a0e3bc48"
integrity sha512-Ob2wK7XG2tUDt7ps7LtLzGYYB6DXMCLj0G5fO6WeEICtT4/HdpOi7W/xLzZnR6RCG1tYza60nMdqtxzA8FaPJQ==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.12.0"
scheduler "^0.13.4"
react-error-overlay@^5.1.2:
version "5.1.2"
@@ -8067,16 +8082,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"
@@ -8174,14 +8188,15 @@ react-transition-group@^2.3.1:
prop-types "^15.6.2"
react-lifecycles-compat "^3.0.4"
react@^16.7.0:
version "16.7.0"
resolved "https://registry.yarnpkg.com/react/-/react-16.7.0.tgz#b674ec396b0a5715873b350446f7ea0802ab6381"
react@^16.8.0:
version "16.8.4"
resolved "https://registry.yarnpkg.com/react/-/react-16.8.4.tgz#fdf7bd9ae53f03a9c4cd1a371432c206be1c4768"
integrity sha512-0GQ6gFXfUH7aZcjGVymlPOASTuSjlQL4ZtVC5YKH+3JL6bBLCVO21DknzmaPlI90LN253ojj02nsapy+j7wIjg==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.12.0"
scheduler "^0.13.4"
reactcss@^1.2.0:
version "1.2.3"
@@ -8718,6 +8733,14 @@ scheduler@^0.12.0:
loose-envify "^1.1.0"
object-assign "^4.1.1"
scheduler@^0.13.4:
version "0.13.4"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.13.4.tgz#8fef05e7a3580c76c0364d2df5e550e4c9140298"
integrity sha512-cvSOlRPxOHs5dAhP9yiS/6IDmVAVxmk33f0CtTJRkmUWcb1Us+t7b1wqdzoC0REw2muC9V5f1L/w5R5uKGaepA==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
schema-utils@^0.4.4:
version "0.4.7"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-0.4.7.tgz#ba74f597d2be2ea880131746ee17d0a093c68187"
@@ -10120,12 +10143,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"