Merge pull request #92 from acelaya/feature/map

Created component to show a map on a modal window
This commit is contained in:
Alejandro Celaya 2019-01-09 20:39:59 +01:00 committed by GitHub
commit b96ea89f90
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 479 additions and 52 deletions

View file

@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
#### Added
* [#54](https://github.com/shlinkio/shlink-web-client/issues/54) Added stats by city graphic in visits page.
* [#55](https://github.com/shlinkio/shlink-web-client/issues/55) Added map in visits page locating cities from which visits have occurred.
#### Changed

View file

@ -29,6 +29,7 @@
"chart.js": "^2.7.2",
"classnames": "^2.2.6",
"csvjson": "^5.1.0",
"leaflet": "^1.4.0",
"moment": "^2.22.2",
"promise": "^8.0.1",
"prop-types": "^15.6.2",
@ -41,6 +42,7 @@
"react-copy-to-clipboard": "^5.0.1",
"react-datepicker": "~1.5.0",
"react-dom": "^16.7.0",
"react-leaflet": "^2.1.4",
"react-moment": "^0.7.6",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",

View file

@ -1,5 +1,4 @@
@import '../utils/base';
@import '../utils/mixins/box-shadow';
@import '../utils/mixins/vertical-align';
$asideMenuMobileWidth: 280px;
@ -26,8 +25,7 @@ $asideMenuMobileWidth: 280px;
width: $asideMenuMobileWidth !important;
transition: left 300ms;
top: $headerHeight - 3px;
@include box-shadow(-10px 0 50px 11px rgba(0, 0, 0, .55));
box-shadow: -10px 0 50px 11px rgba(0, 0, 0, .55);
}
}

View file

@ -7,10 +7,15 @@ import { homepage } from '../package.json';
import registerServiceWorker from './registerServiceWorker';
import container from './container';
import store from './container/store';
import '../node_modules/react-datepicker/dist/react-datepicker.css';
import { fixLeafletIcons } from './utils/utils';
import 'react-datepicker/dist/react-datepicker.css';
import 'leaflet/dist/leaflet.css';
import './common/react-tagsinput.scss';
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;
render(

View file

@ -2,12 +2,11 @@ import { assoc, dissoc, pipe } from 'ramda';
import React from 'react';
import { v4 as uuid } from 'uuid';
import PropTypes from 'prop-types';
import { stateFlagTimeout } from '../utils/utils';
import './CreateServer.scss';
const SHOW_IMPORT_MSG_TIME = 4000;
const CreateServer = (ImportServersBtn) => class CreateServer extends React.Component {
const CreateServer = (ImportServersBtn, stateFlagTimeout) => class CreateServer extends React.Component {
static propTypes = {
createServer: PropTypes.func,
history: PropTypes.shape({

View file

@ -12,7 +12,7 @@ import ServersExporter from './ServersExporter';
const provideServices = (bottle, connect, withRouter) => {
// Components
bottle.serviceFactory('CreateServer', CreateServer, 'ImportServersBtn');
bottle.serviceFactory('CreateServer', CreateServer, 'ImportServersBtn', 'stateFlagTimeout');
bottle.decorator('CreateServer', connect([ 'selectedServer' ], [ 'createServer', 'resetSelectedServer' ]));
bottle.serviceFactory('ServersDropdown', ServersDropdown, 'ServersExporter');

View file

@ -5,13 +5,12 @@ import React from 'react';
import { Collapse } from 'reactstrap';
import * as PropTypes from 'prop-types';
import DateInput from '../utils/DateInput';
import CreateShortUrlResult from './helpers/CreateShortUrlResult';
import { createShortUrlResultType } from './reducers/shortUrlCreation';
const normalizeTag = pipe(trim, replace(/ /g, '-'));
const formatDate = (date) => isNil(date) ? date : date.format();
const CreateShortUrl = (TagsSelector) => class CreateShortUrl extends React.Component {
const CreateShortUrl = (TagsSelector, CreateShortUrlResult) => class CreateShortUrl extends React.Component {
static propTypes = {
createShortUrl: PropTypes.func,
shortUrlCreationResult: createShortUrlResultType,

View file

@ -6,10 +6,9 @@ import { CopyToClipboard } from 'react-copy-to-clipboard';
import { Card, CardBody, Tooltip } from 'reactstrap';
import PropTypes from 'prop-types';
import { createShortUrlResultType } from '../reducers/shortUrlCreation';
import { stateFlagTimeout } from '../../utils/utils';
import './CreateShortUrlResult.scss';
export default class CreateShortUrlResult extends React.Component {
const CreateShortUrlResult = (stateFlagTimeout) => class CreateShortUrlResult extends React.Component {
static propTypes = {
resetCreateShortUrl: PropTypes.func,
error: PropTypes.bool,
@ -61,4 +60,6 @@ export default class CreateShortUrlResult extends React.Component {
</Card>
);
}
}
};
export default CreateShortUrlResult;

View file

@ -6,11 +6,14 @@ import { shortUrlsListParamsType } from '../reducers/shortUrlsListParams';
import { serverType } from '../../servers/prop-types';
import ExternalLink from '../../utils/ExternalLink';
import { shortUrlType } from '../reducers/shortUrlsList';
import { stateFlagTimeout } from '../../utils/utils';
import Tag from '../../tags/helpers/Tag';
import './ShortUrlsRow.scss';
const ShortUrlsRow = (ShortUrlsRowMenu, colorGenerator) => class ShortUrlsRow extends React.Component {
const ShortUrlsRow = (
ShortUrlsRowMenu,
colorGenerator,
stateFlagTimeout
) => class ShortUrlsRow extends React.Component {
static propTypes = {
refreshList: PropTypes.func,
shortUrlsListParams: shortUrlsListParamsType,

View file

@ -8,6 +8,7 @@ import ShortUrlsRowMenu from '../helpers/ShortUrlsRowMenu';
import CreateShortUrl from '../CreateShortUrl';
import DeleteShortUrlModal from '../helpers/DeleteShortUrlModal';
import EditTagsModal from '../helpers/EditTagsModal';
import CreateShortUrlResult from '../helpers/CreateShortUrlResult';
import { listShortUrls } from '../reducers/shortUrlsList';
import { createShortUrl, resetCreateShortUrl } from '../reducers/shortUrlCreation';
import { deleteShortUrl, resetDeleteShortUrl, shortUrlDeleted } from '../reducers/shortUrlDeletion';
@ -30,11 +31,12 @@ const provideServices = (bottle, connect) => {
[ 'listShortUrls', 'resetShortUrlParams' ]
));
bottle.serviceFactory('ShortUrlsRow', ShortUrlsRow, 'ShortUrlsRowMenu', 'ColorGenerator');
bottle.serviceFactory('ShortUrlsRow', ShortUrlsRow, 'ShortUrlsRowMenu', 'ColorGenerator', 'stateFlagTimeout');
bottle.serviceFactory('ShortUrlsRowMenu', ShortUrlsRowMenu, 'DeleteShortUrlModal', 'EditTagsModal');
bottle.serviceFactory('CreateShortUrlResult', CreateShortUrlResult, 'stateFlagTimeout');
bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'TagsSelector');
bottle.serviceFactory('CreateShortUrl', CreateShortUrl, 'TagsSelector', 'CreateShortUrlResult');
bottle.decorator(
'CreateShortUrl',
connect([ 'shortUrlCreationResult' ], [ 'createShortUrl', 'resetCreateShortUrl' ])

View file

@ -1,4 +0,0 @@
@mixin border-radius($radius) {
border-radius: $radius;
-webkit-border-radius: $radius;
}

View file

@ -1,4 +0,0 @@
@mixin box-shadow($shadow) {
-webkit-box-shadow: $shadow;
box-shadow: $shadow;
}

View file

@ -0,0 +1,8 @@
@mixin fit-with-margin($margin) {
$offset: $margin * 2;
width: calc(100% - #{$offset});
max-width: calc(100% - #{$offset});
height: calc(100% - #{$offset});
margin: $margin;
}

View file

@ -1,4 +1,5 @@
import axios from 'axios';
import { stateFlagTimeout } from '../utils';
import Storage from './Storage';
import ColorGenerator from './ColorGenerator';
import buildShlinkApiClient from './ShlinkApiClientBuilder';
@ -10,6 +11,9 @@ const provideServices = (bottle) => {
bottle.constant('axios', axios);
bottle.serviceFactory('buildShlinkApiClient', buildShlinkApiClient, 'axios');
bottle.constant('setTimeout', global.setTimeout);
bottle.serviceFactory('stateFlagTimeout', stateFlagTimeout, 'setTimeout');
};
export default provideServices;

View file

@ -1,6 +1,16 @@
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';
const DEFAULT_TIMEOUT_DELAY = 2000;
export const stateFlagTimeout = (setState, flagName, initialValue = true, delay = DEFAULT_TIMEOUT_DELAY) => {
export const stateFlagTimeout = (setTimeout) => (
setState,
flagName,
initialValue = true,
delay = DEFAULT_TIMEOUT_DELAY
) => {
setState({ [flagName]: initialValue });
setTimeout(() => setState({ [flagName]: !initialValue }), delay);
};
@ -17,3 +27,13 @@ export const determineOrderDir = (clickedField, currentOrderField, currentOrderD
return currentOrderDir ? newOrderMap[currentOrderDir] : 'ASC';
};
export const fixLeafletIcons = () => {
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: marker2x,
iconUrl: marker,
shadowUrl: markerShadow,
});
};

View file

@ -1,6 +1,6 @@
import { faCircleNotch as preloader } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { isEmpty, mapObjIndexed } from 'ramda';
import { isEmpty, mapObjIndexed, values } from 'ramda';
import React from 'react';
import { Card } from 'reactstrap';
import PropTypes from 'prop-types';
@ -12,6 +12,7 @@ import { VisitsHeader } from './VisitsHeader';
import GraphCard from './GraphCard';
import { shortUrlDetailType } from './reducers/shortUrlDetail';
import './ShortUrlVisits.scss';
import OpenMapModalBtn from './helpers/OpenMapModalBtn';
const ShortUrlVisits = ({
processOsStats,
@ -19,6 +20,7 @@ const ShortUrlVisits = ({
processCountriesStats,
processCitiesStats,
processReferrersStats,
processCitiesStatsForMap,
}) => class ShortUrlVisits extends React.Component {
static propTypes = {
match: PropTypes.shape({
@ -101,6 +103,14 @@ const ShortUrlVisits = ({
<SortableBarGraph
stats={processCitiesStats(visits)}
title="Cities"
extraHeaderContent={[
() => (
<OpenMapModalBtn
modalTitle="Cities"
locations={values(processCitiesStatsForMap(visits))}
/>
),
]}
sortingItems={{
name: 'City name',
amount: 'Visits amount',

View file

@ -1,14 +1,17 @@
import React from 'react';
import PropTypes from 'prop-types';
import { fromPairs, head, identity, keys, pipe, prop, reverse, sortBy, toLower, toPairs, type } from 'ramda';
import { fromPairs, head, keys, pipe, prop, reverse, sortBy, toLower, toPairs, type } from 'ramda';
import SortingDropdown from '../utils/SortingDropdown';
import GraphCard from './GraphCard';
const toLowerIfString = (value) => type(value) === 'String' ? toLower(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),
};
state = {
@ -17,13 +20,12 @@ export default class SortableBarGraph extends React.Component {
};
render() {
const { stats, sortingItems, title } = this.props;
const { stats, sortingItems, title, extraHeaderContent } = this.props;
const sortStats = () => {
if (!this.state.orderField) {
return stats;
}
const toLowerIfString = (value) => type(value) === 'String' ? toLower(value) : identity(value);
const sortedPairs = sortBy(
pipe(
prop(this.state.orderField === head(keys(sortingItems)) ? 0 : 1),
@ -48,6 +50,11 @@ export default class SortableBarGraph extends React.Component {
onChange={(orderField, orderDir) => this.setState({ orderField, orderDir })}
/>
</div>
{extraHeaderContent && extraHeaderContent.map((content, index) => (
<div key={index} className="float-right">
{content()}
</div>
))}
</GraphCard>
);
}

View file

@ -0,0 +1,50 @@
import React from 'react';
import { Modal, ModalBody } from 'reactstrap';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import * as PropTypes from 'prop-types';
import './MapModal.scss';
const propTypes = {
toggle: PropTypes.func,
isOpen: PropTypes.bool,
title: PropTypes.string,
locations: PropTypes.arrayOf(PropTypes.shape({
cityName: PropTypes.string.isRequired,
latLong: PropTypes.arrayOf(PropTypes.number).isRequired,
count: PropTypes.number.isRequired,
})),
};
const defaultProps = {
locations: [],
};
const OpenStreetMapTile = () => (
<TileLayer
attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
);
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">
<h3 className="map-modal__modal-title">
{title}
<button type="button" className="close" onClick={toggle}>&times;</button>
</h3>
<Map center={[ 0, 0 ]} zoom="3">
<OpenStreetMapTile />
{locations.map(({ cityName, latLong, count }, index) => (
<Marker key={index} position={latLong}>
<Popup><b>{count}</b> visit{count > 1 ? 's' : ''} from <b>{cityName}</b></Popup>
</Marker>
))}
</Map>
</ModalBody>
</Modal>
);
MapModal.propTypes = propTypes;
MapModal.defaultProps = defaultProps;
export default MapModal;

View file

@ -0,0 +1,45 @@
@import '../../utils/base';
@import '../../utils/mixins/fit-with-margin';
.map-modal__modal {
@media (min-width: $mdMin) {
$margin: 20px;
@include fit-with-margin($margin);
}
@media (max-width: $smMax) {
$margin: 10px;
@include fit-with-margin($margin);
}
}
.map-modal__modal-content {
height: 100%;
}
.map-modal__modal-title {
position: absolute;
width: 100%;
z-index: 1001;
padding: .5rem 1rem 1rem;
margin: 0;
color: #fff;
background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, 0));
}
.map-modal__modal-body {
padding: 0;
display: flex;
overflow: hidden;
}
.map-modal__modal .leaflet-container {
flex: 1 1 auto;
border-radius: .3rem;
}
.map-modal__modal .leaflet-top .leaflet-control {
margin-top: 60px;
}

View file

@ -0,0 +1,32 @@
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMapMarkedAlt as mapIcon } from '@fortawesome/free-solid-svg-icons';
import { 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),
};
state = { mapIsOpened: false };
render() {
const { modalTitle, locations = [] } = this.props;
const toggleMap = () => this.setState(({ mapIsOpened }) => ({ mapIsOpened: !mapIsOpened }));
const buttonRef = React.createRef();
return (
<React.Fragment>
<button className="btn btn-link open-map-modal-btn__btn" ref={buttonRef} onClick={toggleMap}>
<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} />
</React.Fragment>
);
}
}

View file

@ -0,0 +1,4 @@
.open-map-modal-btn__btn {
padding: 0;
margin-right: 1rem;
}

View file

@ -76,15 +76,18 @@ export const processReferrersStats = (visits) =>
visits,
);
const visitLocationHasProperty = (visitLocation, propertyName) =>
!isNil(visitLocation)
&& !isNil(visitLocation[propertyName])
&& !isEmpty(visitLocation[propertyName]);
const buildLocationStatsProcessorByProperty = (propertyName) => (visits) =>
reduce(
(stats, { visitLocation }) => {
const notHasCountry = isNil(visitLocation)
|| isNil(visitLocation[propertyName])
|| isEmpty(visitLocation[propertyName]);
const country = notHasCountry ? 'Unknown' : visitLocation[propertyName];
const hasLocationProperty = visitLocationHasProperty(visitLocation, propertyName);
const value = hasLocationProperty ? visitLocation[propertyName] : 'Unknown';
return assoc(country, (stats[country] || 0) + 1, stats);
return assoc(value, (stats[value] || 0) + 1, stats);
},
{},
visits,
@ -93,3 +96,25 @@ const buildLocationStatsProcessorByProperty = (propertyName) => (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,
);

View file

@ -3,17 +3,24 @@ import { shallow } from 'enzyme';
import { identity } from 'ramda';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { Tooltip } from 'reactstrap';
import CreateShortUrlResult from '../../../src/short-urls/helpers/CreateShortUrlResult';
import * as sinon from 'sinon';
import createCreateShortUrlResult from '../../../src/short-urls/helpers/CreateShortUrlResult';
describe('<CreateShortUrlResult />', () => {
let wrapper;
const stateFlagTimeout = sinon.spy();
const createWrapper = (result, error = false) => {
const CreateShortUrlResult = createCreateShortUrlResult(stateFlagTimeout);
wrapper = shallow(<CreateShortUrlResult resetCreateShortUrl={identity} result={result} error={error} />);
return wrapper;
};
afterEach(() => wrapper && wrapper.unmount());
afterEach(() => {
stateFlagTimeout.resetHistory();
wrapper && wrapper.unmount();
});
it('renders an error when error is true', () => {
const wrapper = createWrapper({}, true);
@ -37,12 +44,12 @@ describe('<CreateShortUrlResult />', () => {
expect(wrapper.find(Tooltip)).toHaveLength(1);
});
it('Shows tooltip when copy to clipboard button is clicked', () => {
it('Invokes tooltip timeout when copy to clipboard button is clicked', () => {
const wrapper = createWrapper({ shortUrl: 'https://doma.in/abc123' });
const copyBtn = wrapper.find(CopyToClipboard);
expect(wrapper.state('showCopyTooltip')).toEqual(false);
expect(stateFlagTimeout.callCount).toEqual(0);
copyBtn.simulate('copy');
expect(wrapper.state('showCopyTooltip')).toEqual(true);
expect(stateFlagTimeout.callCount).toEqual(1);
});
});

60
test/utils/utils.test.js Normal file
View file

@ -0,0 +1,60 @@
import * as sinon from 'sinon';
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';
describe('utils', () => {
describe('stateFlagTimeout', () => {
it('sets state and initializes timeout with provided delay', () => {
const setTimeout = sinon.fake((callback) => callback());
const setState = sinon.spy();
const stateFlagTimeout = stateFlagTimeoutFactory(setTimeout);
const delay = 5000;
const expectedSetStateCalls = 2;
stateFlagTimeout(setState, 'foo', false, delay);
expect(setState.callCount).toEqual(expectedSetStateCalls);
expect(setState.getCall(0).args).toEqual([{ foo: false }]);
expect(setState.getCall(1).args).toEqual([{ foo: true }]);
expect(setTimeout.callCount).toEqual(1);
expect(setTimeout.getCall(0).args[1]).toEqual(delay);
});
});
describe('determineOrderDir', () => {
it('returns ASC when current order field and selected field are different', () => {
expect(determineOrderDir('foo', 'bar')).toEqual('ASC');
expect(determineOrderDir('bar', 'foo')).toEqual('ASC');
});
it('returns ASC when no current order dir is provided', () => {
expect(determineOrderDir('foo', 'foo')).toEqual('ASC');
expect(determineOrderDir('bar', 'bar')).toEqual('ASC');
});
it('returns DESC when current order field and selected field are equal and current order dir is ASC', () => {
expect(determineOrderDir('foo', 'foo', 'ASC')).toEqual('DESC');
expect(determineOrderDir('bar', 'bar', 'ASC')).toEqual('DESC');
});
it('returns undefined when current order field and selected field are equal and current order dir is DESC', () => {
expect(determineOrderDir('foo', 'foo', 'DESC')).toBeUndefined();
expect(determineOrderDir('bar', 'bar', 'DESC')).toBeUndefined();
});
});
describe('fixLeafletIcons', () => {
it('updates icons used by leaflet', () => {
fixLeafletIcons();
const { iconRetinaUrl, iconUrl, shadowUrl } = L.Icon.Default.prototype.options;
expect(iconRetinaUrl).toEqual(marker2x);
expect(iconUrl).toEqual(marker);
expect(shadowUrl).toEqual(markerShadow);
});
});
});

View file

@ -24,6 +24,7 @@ describe('<ShortUrlVisits />', () => {
processOsStats: statsProcessor,
processReferrersStats: statsProcessor,
processCitiesStats: statsProcessor,
processCitiesStatsForMap: statsProcessor,
});
wrapper = shallow(
@ -92,4 +93,13 @@ describe('<ShortUrlVisits />', () => {
expect(getShortUrlVisitsMock.callCount).toEqual(expectedGetShortUrlVisitsCalls);
expect(wrapper.state('startDate')).toEqual('2016-01-03T00:00:00+01:00');
});
it('holds the map button content generator on cities graph extraHeaderContent', () => {
const wrapper = createComponent({ loading: false, error: false, visits: [{}, {}, {}] });
const citiesGraph = wrapper.find(SortableBarGraph).find('[title="Cities"]');
const extraHeaderContent = citiesGraph.prop('extraHeaderContent');
expect(extraHeaderContent).toHaveLength(1);
expect(typeof extraHeaderContent[0]).toEqual('function');
});
});

View file

@ -0,0 +1,61 @@
import React from 'react';
import { shallow } from 'enzyme';
import { Modal } from 'reactstrap';
import { Marker, Popup } from 'react-leaflet';
import MapModal from '../../../src/visits/helpers/MapModal';
describe('<MapModal />', () => {
let wrapper;
const toggle = () => '';
const isOpen = true;
const title = 'Foobar';
const zaragozaLat = 41.6563497;
const zaragozaLong = -0.876566;
const newYorkLat = 40.730610;
const newYorkLong = -73.935242;
const locations = [
{
cityName: 'Zaragoza',
count: 54,
latLong: [ zaragozaLat, zaragozaLong ],
},
{
cityName: 'New York',
count: 7,
latLong: [ newYorkLat, newYorkLong ],
},
];
beforeEach(() => {
wrapper = shallow(<MapModal toggle={toggle} isOpen={isOpen} title={title} locations={locations} />);
});
afterEach(() => wrapper.unmount());
it('renders modal with provided props', () => {
const modal = wrapper.find(Modal);
const headerheader = wrapper.find('.map-modal__modal-title');
expect(modal.prop('toggle')).toEqual(toggle);
expect(modal.prop('isOpen')).toEqual(isOpen);
expect(headerheader.find('.close').prop('onClick')).toEqual(toggle);
expect(headerheader.text()).toContain(title);
});
it('renders open street map tile', () => {
expect(wrapper.find('OpenStreetMapTile')).toHaveLength(1);
});
it('renders proper amount of markers', () => {
const markers = wrapper.find(Marker);
expect(markers).toHaveLength(locations.length);
locations.forEach(({ latLong, count, cityName }, index) => {
const marker = markers.at(index);
const popup = marker.find(Popup);
expect(marker.prop('position')).toEqual(latLong);
expect(popup.text()).toEqual(`${count} visits from ${cityName}`);
});
});
});

View file

@ -0,0 +1,42 @@
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';
describe('<OpenMapModalBtn />', () => {
let wrapper;
const title = 'Foo';
const locations = [];
beforeEach(() => {
wrapper = shallow(<OpenMapModalBtn modalTitle={title} locations={locations} />);
});
afterEach(() => wrapper.unmount());
it('Renders expected content', () => {
const button = wrapper.find('.open-map-modal-btn__btn');
const tooltip = wrapper.find(UncontrolledTooltip);
const modal = wrapper.find(MapModal);
expect(button).toHaveLength(1);
expect(tooltip).toHaveLength(1);
expect(modal).toHaveLength(1);
});
it('changes modal visibility when toggled', () => {
const modal = wrapper.find(MapModal);
expect(wrapper.state('mapIsOpened')).toEqual(false);
modal.prop('toggle')();
expect(wrapper.state('mapIsOpened')).toEqual(true);
});
it('sets provided props to the map', () => {
const modal = wrapper.find(MapModal);
expect(modal.prop('title')).toEqual(title);
expect(modal.prop('locations')).toEqual(locations);
});
});

View file

@ -4,6 +4,7 @@ import {
processReferrersStats,
processCountriesStats,
processCitiesStats,
processCitiesStatsForMap,
} from '../../../src/visits/services/VisitsParser';
describe('VisitsParser', () => {
@ -14,6 +15,8 @@ describe('VisitsParser', () => {
visitLocation: {
countryName: 'Spain',
cityName: 'Zaragoza',
latitude: '123.45',
longitude: '-543.21',
},
},
{
@ -22,6 +25,8 @@ describe('VisitsParser', () => {
visitLocation: {
countryName: 'United States',
cityName: 'New York',
latitude: '1029',
longitude: '6758',
},
},
{
@ -36,6 +41,8 @@ describe('VisitsParser', () => {
visitLocation: {
countryName: 'Spain',
cityName: 'Zaragoza',
latitude: '123.45',
longitude: '-543.21',
},
},
{
@ -92,4 +99,26 @@ describe('VisitsParser', () => {
});
});
});
describe('processCitiesStatsForMap', () => {
it('properly parses cities stats with lat and long', () => {
const zaragozaLat = 123.45;
const zaragozaLong = -543.21;
const newYorkLat = 1029;
const newYorkLong = 6758;
expect(processCitiesStatsForMap(visits)).toEqual({
'Zaragoza': {
cityName: 'Zaragoza',
count: 2,
latLong: [ zaragozaLat, zaragozaLong ],
},
'New York': {
cityName: 'New York',
count: 1,
latLong: [ newYorkLat, newYorkLong ],
},
});
});
});
});

View file

@ -736,7 +736,7 @@
dependencies:
regenerator-runtime "^0.12.0"
"@babel/runtime@^7.1.2":
"@babel/runtime@^7.1.2", "@babel/runtime@^7.2.0":
version "7.2.0"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.2.0.tgz#b03e42eeddf5898e00646e4c840fa07ba8dcad7f"
dependencies:
@ -4356,7 +4356,7 @@ 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.1.0, hoist-non-react-statics@^3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.2.1.tgz#c09c0555c84b38a7ede6912b61efddafd6e75e1e"
dependencies:
@ -5720,6 +5720,11 @@ lcid@^2.0.0:
dependencies:
invert-kv "^2.0.0"
leaflet@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/leaflet/-/leaflet-1.4.0.tgz#d5f56eeb2aa32787c24011e8be4c77e362ae171b"
integrity sha512-x9j9tGY1+PDLN9pcWTx9/y6C5nezoTMB8BLK5jTakx+H7bPlnbCHfi9Hjg+Qt36sgDz/cb9lrSpNQXmk45Tvhw==
left-pad@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.3.0.tgz#5b8a3a7765dfe001261dde915589e782f8c94d1e"
@ -5804,6 +5809,11 @@ 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"
@ -7589,11 +7599,6 @@ postcss-reduce-initial@^4.0.2:
postcss-reduce-transforms@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/postcss-reduce-transforms/-/postcss-reduce-transforms-4.0.1.tgz#8600d5553bdd3ad640f43bff81eb52f8760d4561"
dependencies:
cssnano-util-get-match "^4.0.0"
has "^1.0.0"
postcss "^7.0.0"
postcss-value-parser "^3.0.0"
postcss-replace-overflow-wrap@^3.0.0:
version "3.0.0"
@ -8062,6 +8067,17 @@ 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==
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"
react-lifecycles-compat@^3.0.0, react-lifecycles-compat@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz#4f1a273afdfc8f3488a8c516bfda78f872352362"
@ -8897,11 +8913,6 @@ shebang-regex@^1.0.0:
shell-quote@1.6.1:
version "1.6.1"
resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.6.1.tgz#f4781949cce402697127430ea3b3c5476f481767"
dependencies:
array-filter "~0.0.0"
array-map "~0.0.0"
array-reduce "~0.0.0"
jsonify "~0.0.0"
shellwords@^0.1.1:
version "0.1.1"
@ -10109,7 +10120,7 @@ warning@^3.0.0:
dependencies:
loose-envify "^1.0.0"
warning@^4.0.1:
warning@^4.0.0, warning@^4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.2.tgz#aa6876480872116fa3e11d434b0d0d8d91e44607"
dependencies: