Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Enhancement] Cleanup load map style tasks (#472)

Shan He7348f8044495
diff --git a/src/actions/map-style-actions.js b/src/actions/map-style-actions.js
index d84b07294..0f341cc49 100644
--- a/src/actions/map-style-actions.js
+++ b/src/actions/map-style-actions.js
@@ -61,6 +61,16 @@ export const mapConfigChange = createAction(
mapStyle => mapStyle
);
+/**
+ * Request map style style object based on style.url.
+ * @memberof mapStyleActions
+ * @param {Array<Object>} mapStyles
+ * @public
+ */
+export const requestMapStyles = createAction(
+ ActionTypes.REQUEST_MAP_STYLES,
+ mapStyles => mapStyles
+);
/**
* Callback when load map style success
* @memberof mapStyleActions
diff --git a/src/components/kepler-gl.js b/src/components/kepler-gl.js
index db3827b31..945461ebf 100644
--- a/src/components/kepler-gl.js
+++ b/src/components/kepler-gl.js
@@ -21,11 +21,9 @@
import React, {Component} from 'react';
import {console as Console} from 'global/window';
import {bindActionCreators} from 'redux';
-import {json as requestJson} from 'd3-request';
import styled, {ThemeProvider, withTheme} from 'styled-components';
import {createSelector} from 'reselect';
import {connect as keplerGlConnect} from 'connect/keplergl-connect';
-import {isValidStyleUrl, getStyleDownloadUrl} from 'utils/map-style-utils/mapbox-gl-style-editor';
import * as VisStateActions from 'actions/vis-state-actions';
import * as MapStateActions from 'actions/map-state-actions';
@@ -100,7 +98,8 @@ function KeplerGlFactory(
width: 800,
height: 800,
appName: KEPLER_GL_NAME,
- version: KEPLER_GL_VERSION
+ version: KEPLER_GL_VERSION,
+ theme: {}
};
componentWillMount() {
@@ -125,7 +124,7 @@ function KeplerGlFactory(
themeSelector = props => props.theme;
availableThemeSelector = createSelector(
this.themeSelector,
- (theme) => ({
+ theme => ({
...basicTheme,
...theme
})
@@ -145,39 +144,21 @@ function KeplerGlFactory(
_loadMapStyle = () => {
const defaultStyles = Object.values(this.props.mapStyle.mapStyles);
// add id to custom map styles if not given
- const customeStyles = (this.props.mapStyles || []).map(ms => ({
+ const customStyles = (this.props.mapStyles || []).map(ms => ({
...ms,
id: ms.id || generateHashId()
}));
- [...customeStyles, ...defaultStyles].forEach(
- style => {
- if (style.style) {
- this.props.mapStyleActions.loadMapStyles({
- [style.id]: style
- })
- } else {
- this._requestMapStyle(style);
- }
- }
- );
- };
-
- _requestMapStyle = (mapStyle) => {
- const {url, id} = mapStyle;
+ const allStyles = [...customStyles, ...defaultStyles].reduce((accu, style) => {
+ const hasStyleObject = style.style && typeof style.style === 'object';
+ accu[hasStyleObject ? 'toLoad' : 'toRequest'][style.id] = style;
- const downloadUrl = isValidStyleUrl(url) ?
- getStyleDownloadUrl(url, this.props.mapboxApiAccessToken) : url;
+ return accu;
+ }, {toLoad: {}, toRequest: {}}
+ );
- requestJson(downloadUrl, (error, result) => {
- if (error) {
- Console.warn(`Error loading map style ${url}`);
- } else {
- this.props.mapStyleActions.loadMapStyles({
- [id]: {...mapStyle, style: result}
- });
- }
- });
+ this.props.mapStyleActions.loadMapStyles(allStyles.toLoad);
+ this.props.mapStyleActions.requestMapStyles(allStyles.toRequest);
};
render() {
diff --git a/src/components/modals/export-config-modal.js b/src/components/modals/export-config-modal.js
index c56956b37..a63d0e7e4 100644
--- a/src/components/modals/export-config-modal.js
+++ b/src/components/modals/export-config-modal.js
@@ -27,7 +27,7 @@ import JSONPretty from 'react-json-pretty';
import {StyledModalContent} from 'components/common/styled-components';
const propTypes = {
- config: PropTypes.object.required
+ config: PropTypes.object
};
const StyledExportConfigSection = styled.div`
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index c9e3a9d11..e518fdefe 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -103,6 +103,7 @@ const ActionTypes = keyMirror({
INPUT_MAP_STYLE: null,
LOAD_CUSTOM_MAP_STYLE: null,
ADD_CUSTOM_MAP_STYLE: null,
+ REQUEST_MAP_STYLES: null,
// uiState
TOGGLE_SIDE_PANEL: null,
diff --git a/src/reducers/map-style-updaters.js b/src/reducers/map-style-updaters.js
index a83435b83..2e9142959 100644
--- a/src/reducers/map-style-updaters.js
+++ b/src/reducers/map-style-updaters.js
@@ -20,6 +20,7 @@
import Immutable from 'immutable';
import Task, {withTask} from 'react-palm/tasks';
+import cloneDeep from 'lodash.clonedeep';
// Utils
import {
@@ -30,12 +31,15 @@ import {
editTopMapStyle,
editBottomMapStyle
} from 'utils/map-style-utils/mapbox-gl-style-editor';
-import {DEFAULT_MAP_STYLES, DEFAULT_LAYER_GROUPS} from 'constants/default-settings';
+import {
+ DEFAULT_MAP_STYLES,
+ DEFAULT_LAYER_GROUPS
+} from 'constants/default-settings';
import {generateHashId} from 'utils/utils';
import {LOAD_MAP_STYLE_TASK} from 'tasks/tasks';
import {loadMapStyles, loadMapStyleErr} from 'actions/map-style-actions';
import {rgb} from 'd3-color';
-import { hexToRgb } from 'utils/color-utils';
+import {hexToRgb} from 'utils/color-utils';
const DEFAULT_BLDG_COLOR = '#D1CEC7';
@@ -48,10 +52,13 @@ const getDefaultState = () => {
styleType,
visibleLayerGroups,
topLayerGroups,
- mapStyles: DEFAULT_MAP_STYLES.reduce((accu, curr) => ({
- ...accu,
- [curr.id]: curr
- }), {}),
+ mapStyles: DEFAULT_MAP_STYLES.reduce(
+ (accu, curr) => ({
+ ...accu,
+ [curr.id]: curr
+ }),
+ {}
+ ),
// save mapbox access token
mapboxApiAccessToken: null,
inputStyle: getInitialInputStyle(),
@@ -171,17 +178,26 @@ function getMapStyles({
function get3DBuildingColor(style) {
// set building color to be the same as the background color.
- const backgroundLayer = (style.style.layers || []).find(({id}) => id === 'background');
- const buildingColor = backgroundLayer && backgroundLayer.paint && backgroundLayer.paint['background-color'] ?
- backgroundLayer.paint['background-color'] : DEFAULT_BLDG_COLOR;
+ const backgroundLayer = (style.style.layers || []).find(
+ ({id}) => id === 'background'
+ );
+ const buildingColor =
+ backgroundLayer &&
+ backgroundLayer.paint &&
+ backgroundLayer.paint['background-color']
+ ? backgroundLayer.paint['background-color']
+ : DEFAULT_BLDG_COLOR;
// brighten or darken building based on style
- const operation = style.id.match(/(?=(dark|night))/) ? 'brighter': 'darker';
- const rgbObj = rgb(buildingColor)[operation]([0.2]);
+ const operation = style.id.match(/(?=(dark|night))/) ? 'brighter' : 'darker';
+ const alpha = 0.2;
+ const rgbObj = rgb(buildingColor)[operation]([alpha]);
return [rgbObj.r, rgbObj.g, rgbObj.b];
}
function getLayerGroupsFromStyle(style) {
- return DEFAULT_LAYER_GROUPS.filter(lg => style.layers.filter(lg.filter).length);
+ return Array.isArray(style.layers) ? DEFAULT_LAYER_GROUPS.filter(
+ lg => style.layers.filter(lg.filter).length
+ ) : [];
}
// Updaters
@@ -237,7 +253,10 @@ export const mapStyleChangeUpdater = (state, {payload: styleType}) => {
state.mapStyles[styleType]
);
- const visibleLayerGroups = mergeLayerGroupVisibility(defaultLGVisibility, state.visibleLayerGroups);
+ const visibleLayerGroups = mergeLayerGroupVisibility(
+ defaultLGVisibility,
+ state.visibleLayerGroups
+ );
return {
...state,
@@ -261,14 +280,22 @@ export const mapStyleChangeUpdater = (state, {payload: styleType}) => {
* @public
*/
export const loadMapStylesUpdater = (state, action) => {
- const newStyles = action.payload;
+ const newStyles = action.payload || {};
+ const addLayerGroups = Object.keys(newStyles).reduce((accu, id) => ({
+ ...accu,
+ [id]: {
+ ...newStyles[id],
+ layerGroups:
+ newStyles[id].layerGroups || getLayerGroupsFromStyle(newStyles[id].style)
+ }
+ }), {});
// add new styles to state
const newState = {
...state,
mapStyles: {
...state.mapStyles,
- ...newStyles
+ ...addLayerGroups
}
};
@@ -287,7 +314,12 @@ export const loadMapStylesUpdater = (state, action) => {
* @public
*/
// do nothing for now, if didn't load, skip it
-export const loadMapStyleErrUpdater = (state, action) => state;
+export const loadMapStyleErrUpdater = (state) => state;
+
+export const requestMapStylesUpdater = (state, {payload: mapStyles}) => {
+ const loadMapStyleTasks = getLoadMapStyleTasks(mapStyles, state.mapboxApiAccessToken);
+ return withTask(state, loadMapStyleTasks);
+};
/**
* Load map style object when pass in saved map config
@@ -303,40 +335,44 @@ export const receiveMapConfigUpdater = (state, {payload: {mapStyle}}) => {
}
// if saved custom mapStyles load the style object
- const loadMapStyleTasks = mapStyle.mapStyles ? [
+ const loadMapStyleTasks = mapStyle.mapStyles
+ ? getLoadMapStyleTasks(mapStyle.mapStyles, state.mapboxApiAccessToken)
+ : null;
+
+ const newState = mapConfigChangeUpdater(state, {payload: mapStyle});
+
+ return loadMapStyleTasks ? withTask(newState, loadMapStyleTasks) : newState;
+};
+
+function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken) {
+ return [
Task.all(
- Object.values(mapStyle.mapStyles)
- .map(({id, url, accessToken}) => ({
- id, url: getStyleDownloadUrl(url, accessToken || state.mapboxApiAccessToken)
- }))
- .map(LOAD_MAP_STYLE_TASK))
- .bimap(
- // success
- results => (
- loadMapStyles(
- results.reduce((accu, {id, style}) => ({
+ Object.values(mapStyles)
+ .map(({id, url, accessToken}) => ({
+ id,
+ url: isValidStyleUrl(url) ? getStyleDownloadUrl(url, accessToken || mapboxApiAccessToken) : url
+ }))
+ .map(LOAD_MAP_STYLE_TASK)
+ ).bimap(
+ // success
+ results =>
+ loadMapStyles(
+ results.reduce(
+ (accu, {id, style}) => ({
...accu,
[id]: {
- ...mapStyle.mapStyles[id],
- layerGroups: getLayerGroupsFromStyle(style),
+ ...mapStyles[id],
style
}
- }), {})
+ }),
+ {}
)
),
- // error
- error => loadMapStyleErr(error)
- )
- ] : null;
-
- const newState = mapConfigChangeUpdater(state, {payload: mapStyle});
-
- return loadMapStyleTasks ? withTask(
- newState,
- loadMapStyleTasks
- ) : newState;
-};
-
+ // error
+ loadMapStyleErr
+ )
+ ];
+}
/**
* Reset map style config to initial state
* @memberof mapStyleUpdaters
@@ -344,7 +380,7 @@ export const receiveMapConfigUpdater = (state, {payload: {mapStyle}}) => {
* @returns {Object} nextState
* @public
*/
-export const resetMapConfigMapStyleUpdater = (state) => {
+export const resetMapConfigMapStyleUpdater = state => {
const emptyConfig = {
...INITIAL_MAP_STYLE,
mapboxApiAccessToken: state.mapboxApiAccessToken,
@@ -368,19 +404,24 @@ export const resetMapConfigMapStyleUpdater = (state) => {
* @returns {Object} nextState
* @public
*/
-export const loadCustomMapStyleUpdater = (state, {payload: {icon, style, error}}) => ({
+export const loadCustomMapStyleUpdater = (
+ state,
+ {payload: {icon, style, error}}
+) => ({
...state,
inputStyle: {
...state.inputStyle,
// style json and icon will load asynchronously
- ...(style ? {
- id: style.id || generateHashId(),
- // make a copy of the style object
- style: JSON.parse(JSON.stringify(style)),
- label: style.name,
- // gathering layer group info from style json
- layerGroups: getLayerGroupsFromStyle(style)
- } : {}),
+ ...(style
+ ? {
+ id: style.id || generateHashId(),
+ // make a copy of the style object
+ style: cloneDeep(style),
+ label: style.name,
+ // gathering layer group info from style json
+ layerGroups: getLayerGroupsFromStyle(style)
+ }
+ : {}),
...(icon ? {icon} : {}),
...(error !== undefined ? {error} : {})
}
@@ -417,7 +458,7 @@ export const inputMapStyleUpdater = (state, {payload: inputStyle}) => ({
* @param {Object} state `mapStyle`
* @returns {Object} nextState
*/
-export const addCustomMapStyleUpdater = (state) => {
+export const addCustomMapStyleUpdater = state => {
const styleId = state.inputStyle.id;
const newState = {
...state,
diff --git a/src/reducers/map-style.js b/src/reducers/map-style.js
index c8386eb40..5baf0ef20 100644
--- a/src/reducers/map-style.js
+++ b/src/reducers/map-style.js
@@ -31,6 +31,7 @@ const actionHandler = {
[ActionTypes.INPUT_MAP_STYLE]: mapStyleUpdaters.inputMapStyleUpdater,
[ActionTypes.MAP_CONFIG_CHANGE]: mapStyleUpdaters.mapConfigChangeUpdater,
[ActionTypes.MAP_STYLE_CHANGE]: mapStyleUpdaters.mapStyleChangeUpdater,
+ [ActionTypes.REQUEST_MAP_STYLES]: mapStyleUpdaters.requestMapStylesUpdater,
[ActionTypes.LOAD_MAP_STYLES]: mapStyleUpdaters.loadMapStylesUpdater,
[ActionTypes.LOAD_MAP_STYLE_ERR]: mapStyleUpdaters.loadMapStyleErrUpdater,
[ActionTypes.RECEIVE_MAP_CONFIG]: mapStyleUpdaters.receiveMapConfigUpdater,
diff --git a/test/browser/components/container-test.js b/test/browser/components/container-test.js
index 89de76097..9314f5386 100644
--- a/test/browser/components/container-test.js
+++ b/test/browser/components/container-test.js
@@ -18,6 +18,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+/* eslint-disable max-statements */
import React from 'react';
import test from 'tape';
import {mount} from 'enzyme';
@@ -322,3 +323,4 @@ test('Components -> Container -> Mount then rename', t => {
t.end();
});
+/* eslint-enable max-statements */
diff --git a/test/browser/components/index.js b/test/browser/components/index.js
index 496e6c0b3..e958ddd01 100644
--- a/test/browser/components/index.js
+++ b/test/browser/components/index.js
@@ -27,3 +27,4 @@ import './injector-test';
import './container-test';
import './data-table-model-test';
import './notifications';
+import './kepler-gl-test';
diff --git a/test/browser/components/kepler-gl-test.js b/test/browser/components/kepler-gl-test.js
new file mode 100644
index 000000000..a1e6b3619
--- /dev/null
+++ b/test/browser/components/kepler-gl-test.js
@@ -0,0 +1,464 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import React from 'react';
+import test from 'tape';
+import {mount} from 'enzyme';
+import {drainTasksForTesting, succeedTaskWithValues} from 'react-palm/tasks';
+import configureStore from 'redux-mock-store';
+import {Provider} from 'react-redux';
+
+import coreReducer from 'reducers/core';
+import {keplerGlInit} from 'actions/actions';
+import {appInjector} from 'components/container';
+import {
+ KeplerGlFactory,
+ SidePanelFactory,
+ MapContainerFactory,
+ BottomWidgetFactory,
+ ModalContainerFactory,
+ PlotContainerFactory
+} from 'components';
+import NotificationPanelFactory from 'components/notification-panel';
+import {ActionTypes} from 'actions';
+import {DEFAULT_MAP_STYLES, EXPORT_IMAGE_ID} from 'constants';
+
+const KeplerGl = appInjector.get(KeplerGlFactory);
+const SidePanel = appInjector.get(SidePanelFactory);
+const MapContainer = appInjector.get(MapContainerFactory);
+const BottomWidget = appInjector.get(BottomWidgetFactory);
+const ModalContainer = appInjector.get(ModalContainerFactory);
+const PlotContainer = appInjector.get(PlotContainerFactory);
+const NotificationPanel = appInjector.get(NotificationPanelFactory);
+
+const initialCoreState = coreReducer(
+ undefined,
+ keplerGlInit({mapboxApiAccessToken: 'smoothie-the-cat'})
+);
+
+const initialState = {
+ keplerGl: {
+ map: initialCoreState
+ }
+};
+
+const mockStore = configureStore();
+
+test('Components -> KeplerGl -> Mount', t => {
+
+ // mount with empty store
+ const store = mockStore(initialState);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ t.equal(wrapper.find(KeplerGl).length, 1, 'should render KeplerGl');
+ t.equal(wrapper.find(SidePanel).length, 1, 'should render SidePanel');
+ t.equal(wrapper.find(MapContainer).length, 1, 'should render MapContainer');
+ t.equal(wrapper.find(BottomWidget).length, 1, 'should render BottomWidget');
+ t.equal(wrapper.find(ModalContainer).length, 1, 'should render ModalContainer');
+ t.equal(wrapper.find(PlotContainer).length, 0, 'should not render PlotContainer');
+ t.equal(wrapper.find(NotificationPanel).length, 1, 'should render NotificationPanel');
+
+ t.end();
+});
+
+test('Components -> KeplerGl -> Mount -> readOnly', t => {
+
+ // mount with readOnly true
+ const initialStateReadonly = {
+ keplerGl: {
+ map: {
+ ...initialCoreState,
+ uiState: {
+ ...initialCoreState.uiState,
+ readOnly: true
+ }
+ }
+ }
+ };
+
+ const store = mockStore(initialStateReadonly);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ t.equal(wrapper.find(KeplerGl).length, 1, 'should render KeplerGl');
+ t.equal(wrapper.find(SidePanel).length, 0, 'should not render SidePanel');
+ t.equal(wrapper.find(MapContainer).length, 1, 'should render MapContainer');
+ t.equal(wrapper.find(BottomWidget).length, 1, 'should render BottomWidget');
+ t.equal(wrapper.find(ModalContainer).length, 1, 'should render ModalContainer');
+ t.equal(wrapper.find(PlotContainer).length, 0, 'should not render PlotContainer');
+ t.equal(wrapper.find(NotificationPanel).length, 1, 'should render NotificationPanel');
+
+ t.end();
+});
+
+test('Components -> KeplerGl -> Mount -> Plot', t => {
+
+ // mount with readOnly true
+ const initialStatePlots = {
+ keplerGl: {
+ map: {
+ ...initialCoreState,
+ uiState: {
+ ...initialCoreState.uiState,
+ currentModal: EXPORT_IMAGE_ID
+ }
+ }
+ }
+ };
+
+ const store = mockStore(initialStatePlots);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ t.equal(wrapper.find(KeplerGl).length, 1, 'should render KeplerGl');
+ t.equal(wrapper.find(SidePanel).length, 1, 'should render SidePanel');
+ t.equal(wrapper.find(MapContainer).length, 2, 'should render 2 MapContainer');
+ t.equal(wrapper.find(BottomWidget).length, 1, 'should render BottomWidget');
+ t.equal(wrapper.find(ModalContainer).length, 1, 'should render ModalContainer');
+ t.equal(wrapper.find(PlotContainer).length, 1, 'should render PlotContainer');
+ t.equal(wrapper.find(NotificationPanel).length, 1, 'should render NotificationPanel');
+
+ t.end();
+});
+
+test('Components -> KeplerGl -> Mount -> Split Maps', t => {
+ // mount with readOnly true
+ const initialStateSplitMap = {
+ keplerGl: {
+ map: {
+ ...initialCoreState,
+ visState: {
+ ...initialCoreState.visState,
+ splitMaps: [
+ {layers: {}},
+ {layers: {}}
+ ]
+ }
+ }
+ }
+ };
+
+ const store = mockStore(initialStateSplitMap);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ t.equal(wrapper.find(KeplerGl).length, 1, 'should render KeplerGl');
+ t.equal(wrapper.find(SidePanel).length, 1, 'should render SidePanel');
+ t.equal(wrapper.find(MapContainer).length, 2, 'should render 2 MapContainer');
+ t.equal(wrapper.find(BottomWidget).length, 1, 'should render BottomWidget');
+ t.equal(wrapper.find(ModalContainer).length, 1, 'should render ModalContainer');
+ t.equal(wrapper.find(PlotContainer).length, 0, 'should render PlotContainer');
+ t.equal(wrapper.find(NotificationPanel).length, 1, 'should render NotificationPanel');
+
+ t.end();
+});
+
+test('Components -> KeplerGl -> Mount -> Load default map style task', t => {
+ // mount with empty store
+ const store = mockStore(initialState);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ const actions = store.getActions();
+ const expectedActions = [
+ {type: ActionTypes.LOAD_MAP_STYLES, payload: {}},
+ {
+ type: ActionTypes.REQUEST_MAP_STYLES,
+ payload: DEFAULT_MAP_STYLES.reduce(
+ (accu, curr) => ({...accu, [curr.id]: curr}),
+ {}
+ )
+ },
+ {type: ActionTypes.UPDATE_MAP, payload: {width: 800, height: 800}}
+ ];
+ t.deepEqual(
+ actions,
+ expectedActions,
+ 'Should mount kepler.gl and dispatch 2 actions to load map styles'
+ );
+
+ const resultState1 = coreReducer(initialCoreState, actions[1]);
+ const [task1, ...rest] = drainTasksForTesting();
+ t.equal(rest.length, 0, 'should dispatch 1 tasks');
+
+ const expectedTask = {
+ payload: [
+ {
+ id: 'dark',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqbbf6l9k302sl96tyvka09?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'light',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqb9j339k1f2sl9t5ic5bn4?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'muted',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjfyl03kp1tul2smf5v2tbdd4?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'muted_night',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjfxhlikmaj1b2soyzevnywgs?pluginName=Keplergl&access_token=smoothie-the-cat'
+ }
+ ]
+ };
+
+ t.deepEqual(
+ task1.payload,
+ expectedTask.payload,
+ 'should create task to load map styles'
+ );
+ t.deepEqual(resultState1, initialCoreState, 'state should be the same');
+
+ const resultState2 = coreReducer(
+ resultState1,
+ succeedTaskWithValues(task1, [
+ {id: 'dark', style: {layers: [], name: 'dark'}},
+ {id: 'light', style: {layers: [], name: 'light'}},
+ {id: 'muted', style: {hello: 'world'}},
+ {id: 'muted_night', style: {world: 'hello'}}
+ ])
+ );
+
+ const expectedStateMapStyles = {
+ dark: {
+ ...DEFAULT_MAP_STYLES[0],
+ style: {layers: [], name: 'dark'}
+ },
+ light: {
+ ...DEFAULT_MAP_STYLES[1],
+ style: {layers: [], name: 'light'}
+ },
+ muted: {
+ ...DEFAULT_MAP_STYLES[2],
+ style: {hello: 'world'}
+ },
+ muted_night: {
+ ...DEFAULT_MAP_STYLES[3],
+ style: {world: 'hello'}
+ }
+ };
+
+ t.deepEqual(
+ resultState2.mapStyle.mapStyles,
+ expectedStateMapStyles,
+ 'should update state with loaded map styles'
+ );
+
+ t.end();
+});
+
+test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {
+ // mount with empty store
+ const store = mockStore(initialState);
+ // mount without id or a kepler.gl state
+ let wrapper;
+
+ const customStyle1 = {
+ id: 'smoothie',
+ url: 'mapbox://styles/smoothie/thecat'
+ };
+ const customStyle2 = {
+ id: 'milkshake',
+ style: {
+ id: 'mm',
+ layers: []
+ }
+ };
+ const customStyle3 = {
+ id: 'chai',
+ style: {
+ id: 'chai',
+ layers: []
+ },
+ layerGroups: [
+ {
+ slug: 'label'
+ }
+ ]
+ };
+ t.doesNotThrow(() => {
+ wrapper = mount(
+ <Provider store={store}>
+ <KeplerGl
+ id="map"
+ mapboxApiAccessToken="smoothie-the-cat"
+ selector={state => state.keplerGl.map}
+ dispatch={store.dispatch}
+ mapStyles={[customStyle1, customStyle2, customStyle3]}
+ />
+ </Provider>
+ );
+ }, 'Should not throw error when mount KeplerGl');
+
+ const actions = store.getActions();
+ const expectedActions = [
+ {
+ type: ActionTypes.LOAD_MAP_STYLES,
+ payload: {
+ milkshake: customStyle2,
+ chai: customStyle3
+ }
+ },
+ {
+ type: ActionTypes.REQUEST_MAP_STYLES,
+ payload: DEFAULT_MAP_STYLES.reduce(
+ (accu, curr) => ({...accu, [curr.id]: curr, smoothie: customStyle1}),
+ {}
+ )
+ },
+ {type: ActionTypes.UPDATE_MAP, payload: {width: 800, height: 800}}
+ ];
+ t.deepEqual(
+ actions,
+ expectedActions,
+ 'Should mount kepler.gl and dispatch 2 actions to load map styles'
+ );
+
+ const resultState1 = coreReducer(initialCoreState, actions[0]);
+
+ const expectedMapStyleState1 = {
+ ...initialCoreState.mapStyle,
+ mapStyles: {
+ ...initialCoreState.mapStyle.mapStyles,
+ milkshake: {
+ id: 'milkshake',
+ style: {
+ id: 'mm',
+ layers: []
+ },
+ layerGroups: {}
+ },
+ chai: customStyle3
+ }
+ };
+
+ t.deepEqual(
+ resultState1.mapStyle,
+ expectedMapStyleState1,
+ 'Should load map style into reducer and create layer groups'
+ );
+
+ const resultState2 = coreReducer(resultState1, actions[1]);
+ const [task1, ...rest] = drainTasksForTesting();
+ t.equal(rest.length, 0, 'should dispatch 1 tasks');
+
+ const expectedTask = {
+ payload: [
+ {
+ id: 'smoothie',
+ url:
+ 'https://api.mapbox.com/styles/v1/smoothie/thecat?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'dark',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqbbf6l9k302sl96tyvka09?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'light',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqb9j339k1f2sl9t5ic5bn4?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'muted',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjfyl03kp1tul2smf5v2tbdd4?pluginName=Keplergl&access_token=smoothie-the-cat'
+ },
+ {
+ id: 'muted_night',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjfxhlikmaj1b2soyzevnywgs?pluginName=Keplergl&access_token=smoothie-the-cat'
+ }
+ ]
+ };
+
+ t.deepEqual(
+ task1.payload,
+ expectedTask.payload,
+ 'should create task to load map styles'
+ );
+
+ t.end();
+});
diff --git a/test/node/reducers/map-style-test.js b/test/node/reducers/map-style-test.js
index 23ad2806c..f29334f69 100644
--- a/test/node/reducers/map-style-test.js
+++ b/test/node/reducers/map-style-test.js
@@ -19,14 +19,12 @@
// THE SOFTWARE.
import test from 'tape';
+import {drainTasksForTesting, succeedTaskWithValues} from 'react-palm/tasks';
import reducer from 'reducers/map-style';
import {INITIAL_MAP_STYLE} from 'reducers/map-style-updaters';
import {keplerGlInit, receiveMapConfig} from 'actions/actions';
import SchemaManager from 'schemas';
-import {
- drainTasksForTesting
-} from 'react-palm/tasks';
// helpers
import {StateWCustomMapStyle} from 'test/helpers/mock-state';
@@ -36,28 +34,42 @@ const InitialMapStyle = reducer(undefined, {});
test('#mapStyleReducer', t => {
const newState = reducer(undefined, {});
- t.deepEqual(newState, {
- ...INITIAL_MAP_STYLE,
- initialState: {}
- }, 'should return the initial map style');
+ t.deepEqual(
+ newState,
+ {
+ ...INITIAL_MAP_STYLE,
+ initialState: {}
+ },
+ 'should return the initial map style'
+ );
t.end();
});
test('#mapStyleReducer -> INIT', t => {
- const newState = reducer(InitialMapStyle, keplerGlInit({mapboxApiAccessToken: 'smoothies_secret_token'}));
+ const newState = reducer(
+ InitialMapStyle,
+ keplerGlInit({mapboxApiAccessToken: 'smoothies_secret_token'})
+ );
- t.deepEqual(newState, {
- ...INITIAL_MAP_STYLE,
- initialState: {},
- mapboxApiAccessToken: 'smoothies_secret_token'
- }, 'initialie map style with mapboxApiAccessToken');
+ t.deepEqual(
+ newState,
+ {
+ ...INITIAL_MAP_STYLE,
+ initialState: {},
+ mapboxApiAccessToken: 'smoothies_secret_token'
+ },
+ 'initialie map style with mapboxApiAccessToken'
+ );
t.end();
});
test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
- const stateWithToken = reducer(InitialMapStyle, keplerGlInit({mapboxApiAccessToken: 'smoothies_secret_token'}));
+ const stateWithToken = reducer(
+ InitialMapStyle,
+ keplerGlInit({mapboxApiAccessToken: 'smoothies_secret_token'})
+ );
const stateToSave = StateWCustomMapStyle.toJS();
// save state
@@ -65,17 +77,91 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
// load state
const stateLoaded = SchemaManager.parseSavedConfig(savedState);
- console.log(stateLoaded);
const stateWithConfig = reducer(
stateWithToken,
receiveMapConfig(stateLoaded)
);
+
+ const expectedStateWithConfig = {
+ styleType: 'smoothie_the_cat',
+ visibleLayerGroups: {label: true, road: true},
+ topLayerGroups: {},
+ mapStyles: {
+ smoothie_the_cat: {
+ accessToken: 'secret_token',
+ custom: true,
+ icon: 'data:image/png;base64,xyz',
+ id: 'smoothie_the_cat',
+ label: 'Smoothie the Cat',
+ url: 'mapbox://styles/shanhe/smoothie.the.cat'
+ }
+ },
+ mapboxApiAccessToken: 'smoothies_secret_token',
+ inputStyle: {
+ accessToken: null,
+ error: false,
+ isValid: false,
+ label: null,
+ style: null,
+ url: null,
+ custom: true
+ },
+ threeDBuildingColor: [209, 206, 199],
+ initialState: {}
+ };
+
+ t.deepEqual(
+ stateWithConfig,
+ expectedStateWithConfig,
+ 'should load saved map style config'
+ );
+
const [task1, ...more] = drainTasksForTesting();
t.equal(more.length, 0, 'should return 1 task');
- // TODO: ask btford how to test Task.all
+ const expectedTask = {
+ payload: [
+ {
+ id: 'smoothie_the_cat',
+ url:
+ 'https://api.mapbox.com/styles/v1/shanhe/smoothie.the.cat?pluginName=Keplergl&access_token=secret_token'
+ }
+ ]
+ };
+
+ t.deepEqual(
+ task1.payload,
+ expectedTask.payload,
+ 'should create task to load map styles'
+ );
+
+ const resultState1 = reducer(
+ stateWithConfig,
+ succeedTaskWithValues(task1, [
+ {id: 'smoothie_the_cat', style: {layers: [], name: 'smoothie_the_cat'}}
+ ])
+ );
+
+ const expectedMapStyles = {
+ smoothie_the_cat: {
+ accessToken: 'secret_token',
+ custom: true,
+ icon: 'data:image/png;base64,xyz',
+ id: 'smoothie_the_cat',
+ label: 'Smoothie the Cat',
+ url: 'mapbox://styles/shanhe/smoothie.the.cat',
+ style: {layers: [], name: 'smoothie_the_cat'},
+ layerGroups: []
+ }
+ };
+
+ t.deepEqual(
+ resultState1.mapStyles,
+ expectedMapStyles,
+ 'should update state with loaded map styles'
+ );
t.end();
});