Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Enhancement] Save and load custom map style (#60)
Shan Hed28f5a63d7de
diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.jsindex 69ee34491..6d7344e4e 100644--- a/examples/demo-app/src/app.js+++ b/examples/demo-app/src/app.js@@ -62,10 +62,6 @@ class App extends Component {}componentDidMount() {- /**- * ENABLE THE FOLLOWING CODE TO PRE-POLUATE KEPLER.GL INSTANCE- */-// load trip based data with config// this._loadSampleData();}diff --git a/src/components/container.js b/src/components/container.jsindex d5afb71f5..3ffe5497f 100644--- a/src/components/container.js+++ b/src/components/container.js@@ -72,9 +72,9 @@ export function ContainerFactory(KeplerGl) {}componentWillMount() {- const {id, mint} = this.props;+ const {id, mint, mapboxApiAccessToken} = this.props;// add a new entry to reducer- this.props.dispatch(registerEntry({id, mint}));+ this.props.dispatch(registerEntry({id, mint, mapboxApiAccessToken}));}componentWillReceiveProps(nextProps) {diff --git a/src/components/map-container.js b/src/components/map-container.jsindex cda8752cc..dcd41cf78 100644--- a/src/components/map-container.js+++ b/src/components/map-container.js@@ -33,7 +33,7 @@ import {StyledMapContainer} from 'components/common/styled-components';// Overlay typeimport {generateMapboxLayers, updateMapboxLayers} from '../layers/mapbox-utils';-import {transformRequest} from 'utils/mapbox-utils';+import {transformRequest} from 'utils/map-style-utils/mapbox-utils';// default-settingsimport {LAYER_BLENDINGS} from 'constants/default-settings';diff --git a/src/components/modals/add-map-style-modal.js b/src/components/modals/add-map-style-modal.jsindex 2fabe5df1..395fb6b19 100644--- a/src/components/modals/add-map-style-modal.js+++ b/src/components/modals/add-map-style-modal.js@@ -27,12 +27,12 @@ import {findDOMNode} from 'react-dom';import {StyledModalContent, InputLight, StyledMapContainer} from 'components/common/styled-components';// Utils-import {transformRequest} from 'utils/mapbox-utils';+import {transformRequest} from 'utils/map-style-utils/mapbox-utils';const MapH = 190;const MapW = 264;const ErrorMsg = {- styleError : 'Failed to load map style, make sure it is published'+ styleError : 'Failed to load map style, make sure it is published. For private style, paste in your access token.'};const InstructionPanel = styled.div`@@ -72,7 +72,8 @@ const PreviewMap = styled.div`justify-content: center;margin-left: 116px;flex-shrink: 0;-+ width: ${MapW}px;+.preview-title {font-weight: 500;font-size: 10px;@@ -114,7 +115,6 @@ const InlineLink = styled.a``;class AddMapStyleModal extends Component {-static propTypes = {mapState: PropTypes.object.isRequired,inputMapStyle: PropTypes.func.isRequired,@@ -122,6 +122,21 @@ class AddMapStyleModal extends Component {inputStyle: PropTypes.object.isRequired};+ state = {+ reRenderKey: 0+ };++ componentWillReceiveProps(nextProps) {+ if (this.props.inputStyle.accessToken !== nextProps.inputStyle.accessToken) {+ // toke has changed+ // ReactMapGl doesn't re-create map when token has changed+ // here we force the map to update+ this.setState({+ reRenderKey: this.state.reRenderKey + 1+ });+ }+ }+componentDidUpdate() {const map = this.mapRef && this.mapRef.getMap();if (map && this._map !== map) {@@ -149,11 +164,13 @@ class AddMapStyleModal extends Component {};loadMapStyleIcon = () => {- const canvas = findDOMNode(this.mapRef).querySelector('.mapboxgl-canvas');- const dataUri = canvas.toDataURL();- this.props.loadCustomMapStyle({- icon: dataUri- });+ if (this.mapRef) {+ const canvas = findDOMNode(this.mapRef).querySelector('.mapboxgl-canvas');+ const dataUri = canvas.toDataURL();+ this.props.loadCustomMapStyle({+ icon: dataUri+ });+ }};loadMaoStyleError = () => {@@ -166,7 +183,7 @@ class AddMapStyleModal extends Component {const mapProps = {...mapState,preserveDrawingBuffer: true,- mapboxApiAccessToken: this.props.mapboxApiAccessToken,+ mapboxApiAccessToken: inputStyle.accessToken || this.props.mapboxApiAccessToken,transformRequest};@@ -175,12 +192,22 @@ class AddMapStyleModal extends Component {<StyledModalContent><InstructionPanel><div className="modal-section">- <div className="modal-section-title">1. Publish your style at mapbox</div>+ <div className="modal-section-title">1. Publish your style at mapbox or provide access token</div><div className="modal-section-subtitle">You can create your own map style at<InlineLink target="_blank" href="https://www.mapbox.com/studio/styles/"> mapbox</InlineLink> and<InlineLink target="_blank" href="https://www.mapbox.com/help/studio-manual-publish/"> publish</InlineLink> it.</div>+ <div className="modal-section-subtitle">+ To use private style, paste your+ <InlineLink target="_blank" href="https://www.mapbox.com/help/how-access-tokens-work/"> access token</InlineLink> here. *kepler.gl is a client-side application, data stays in your browser..+ </div>+ <InputLight+ type="text"+ value={inputStyle.accessToken || ''}+ onChange={({target: {value}}) => this.props.inputMapStyle({...inputStyle, accessToken: value})}+ placeholder="e.g. pk.abcdefg.xxxxxx"+ /></div><div className="modal-section"><div className="modal-section-title">2. Paste style url</div>@@ -217,6 +244,7 @@ class AddMapStyleModal extends Component {ref={el => {this.mapRef = el;}}+ key={this.state.reRenderKey}width={MapW}height={MapH}mapStyle={inputStyle.url}/>diff --git a/src/reducers/map-style-updaters.js b/src/reducers/map-style-updaters.jsindex 323e4da78..65a366dff 100644--- a/src/reducers/map-style-updaters.js+++ b/src/reducers/map-style-updaters.js@@ -19,16 +19,21 @@// THE SOFTWARE.import Immutable from 'immutable';+import {Task, withTask} from 'react-palm';// Utilsimport {getDefaultLayerGroupVisibility,isValidStyleUrl,+ getStyleDownloadUrl,+ mergeLayerGroupVisibility,editTopMapStyle,editBottomMapStyle} from 'utils/map-style-utils/mapbox-gl-style-editor';import {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';/*** Create two map styles from preset map style, one for top map one for bottom@@ -86,7 +91,17 @@ function getMapStyles({return {bottomMapStyle, topMapStyle, editable};}+function getLayerGroupsFromStyle(style) {+ return DEFAULT_LAYER_GROUPS.filter(lg => style.layers.filter(lg.filter).length);+}+// Updaters+export const initMapStyleUpdater = (state, action) => ({+ ...state,+ // save mapbox access token to map style state+ mapboxApiAccessToken: (action.payload || {}).mapboxApiAccessToken+});+export const mapConfigChangeUpdater = (state, action) => ({...state,...action.payload,@@ -97,10 +112,12 @@ export const mapConfigChangeUpdater = (state, action) => ({});export const mapStyleChangeUpdater = (state, {payload: styleType}) => {- const visibleLayerGroups = getDefaultLayerGroupVisibility(+ const defaultLGVisibility = getDefaultLayerGroupVisibility(state.mapStyles[styleType]);+ const visibleLayerGroups = mergeLayerGroupVisibility(defaultLGVisibility, state.visibleLayerGroups);+return {...state,styleType,@@ -132,10 +149,45 @@ export const loadMapStylesUpdater = (state, action) => {// do nothing for now, if didn't load, skip itexport const loadMapStyleErrUpdater = (state, action) => state;-export const receiveMapConfigUpdater = (state, action) =>- action.payload.mapStyle- ? mapConfigChangeUpdater(state, {payload: action.payload.mapStyle})- : state;+export const receiveMapConfigUpdater = (state, {payload: {mapStyle}}) => {+ if (!mapStyle) {+ return state;+ }++ // if saved custom mapStyles load the style object+ const loadMapStyleTasks = mapStyle.mapStyles ? [+ 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}) => ({+ ...accu,+ [id]: {+ ...mapStyle.mapStyles[id],+ layerGroups: getLayerGroupsFromStyle(style),+ style+ }+ }), {})+ )+ ),+ // error+ error => loadMapStyleErr(error)+ )+ ] : null;++ const newState = mapConfigChangeUpdater(state, {payload: mapStyle});++ return loadMapStyleTasks ? withTask(+ newState,+ loadMapStyleTasks+ ) : newState;+};export const loadCustomMapStyleUpdater = (state, {payload: {icon, style, error}}) => ({...state,@@ -144,9 +196,11 @@ export const loadCustomMapStyleUpdater = (state, {payload: {icon, style, error}}// style json and icon will load asynchronously...(style ? {id: style.id || generateHashId(),- style,+ // make a copy of the style object+ style: JSON.parse(JSON.stringify(style)),label: style.name,- layerGroups: DEFAULT_LAYER_GROUPS.filter(lg => style.layers.filter(lg.filter).length)+ // gathering layer group info from style json+ layerGroups: getLayerGroupsFromStyle(style)} : {}),...(icon ? {icon} : {}),...(error !== undefined ? {error} : {})@@ -170,13 +224,20 @@ export const addCustomMapStyleUpdater = (state, action) => {[styleId]: state.inputStyle},// set to default- inputStyle: {- url: null,- isValid: false,- label: null,- style: null- }+ inputStyle: getInitialInputStyle()};// set new stylereturn mapStyleChangeUpdater(newState, {payload: styleId});};++export function getInitialInputStyle() {+ return {+ accessToken: null,+ error: false,+ isValid: false,+ label: null,+ style: null,+ url: null,+ custom: true+ };+}diff --git a/src/reducers/map-style.js b/src/reducers/map-style.jsindex 5fed23f24..e0c90f14e 100644--- a/src/reducers/map-style.js+++ b/src/reducers/map-style.js@@ -24,7 +24,9 @@ import {handleActions} from 'redux-actions';import ActionTypes from 'constants/action-types';import {+ getInitialInputStyle,inputMapStyleUpdater,+ initMapStyleUpdater,mapConfigChangeUpdater,mapStyleChangeUpdater,loadMapStylesUpdater,@@ -46,19 +48,16 @@ const getDefaultState = () => {visibleLayerGroups,topLayerGroups,mapStyles: {},-- inputStyle: {- url: null,- isValid: false,- label: null,- style: null- }+ // save mapbox access token+ mapboxApiAccessToken: null,+ inputStyle: getInitialInputStyle()};};export const INITIAL_MAP_STYLE = getDefaultState();const actionHandler = {+ [ActionTypes.INIT]: initMapStyleUpdater,[ActionTypes.INPUT_MAP_STYLE]: inputMapStyleUpdater,[ActionTypes.MAP_CONFIG_CHANGE]: mapConfigChangeUpdater,[ActionTypes.MAP_STYLE_CHANGE]: mapStyleChangeUpdater,diff --git a/src/reducers/root.js b/src/reducers/root.jsindex ce341f59f..95f70759f 100644--- a/src/reducers/root.js+++ b/src/reducers/root.js@@ -41,13 +41,13 @@ const initialCoreState = {};export function provideInitialState(initialState) {const coreReducer = coreReducerFactory(initialState);- const handleRegisterEntry = (state, {payload: {id, mint}}) => ({+ const handleRegisterEntry = (state, {payload: {id, mint, mapboxApiAccessToken}}) => ({// register a new entry to voyager reducer// by default, always create a mint state even if the same id already exist// if state.id exist and mint=false, keep the existing state...state,[id]: state[id] && mint === false ? state[id] : {- ...coreReducer(undefined, keplerGlInit())+ ...coreReducer(undefined, keplerGlInit({mapboxApiAccessToken}))}});diff --git a/src/schemas/map-style-schema.js b/src/schemas/map-style-schema.jsindex 6ce8cdcb3..5988f3817 100644--- a/src/schemas/map-style-schema.js+++ b/src/schemas/map-style-schema.js@@ -21,12 +21,48 @@import {VERSIONS} from './versions';import Schema from './schema';+export const customMapStylePropsV1 = {+ accessToken: null,+ custom: null,+ icon: null,+ id: null,+ label: null,+ url: null+};++const CustomMapStyleSchema = new Schema({+ version: VERSIONS.v1,+ key: 'customStyle',+ properties: customMapStylePropsV1+});++class MapStyleSchemaV1 extends Schema {+ version = VERSIONS.v1;+ key = 'mapStyles';+ save(mapStyles, mapStyle) {++ // save all custom styles+ const saveCustomStyle = Object.keys(mapStyles).reduce((accu, key) => ({+ ...(mapStyles[key].custom ?+ {[key]: CustomMapStyleSchema.save(mapStyles[key]).customStyle} : {}+ )+ }), {});++ return {[this.key]: saveCustomStyle};+ }++ load(mapStyles) {+ return {[this.key]: mapStyles}+ }+}+// version v0export const propertiesV0 = {styleType: null,topLayerGroups: null,visibleLayerGroups: null,- buildingLayer: null+ buildingLayer: null,+ mapStyles: new MapStyleSchemaV1()};const mapStyleSchema = {diff --git a/src/tasks/tasks.js b/src/tasks/tasks.jsindex 0399394fe..0a92c9149 100644--- a/src/tasks/tasks.js+++ b/src/tasks/tasks.js@@ -19,6 +19,7 @@// THE SOFTWARE.import {taskCreator} from 'react-palm/tasks';+import {json as requestJson} from 'd3-request';export const LOAD_FILE_TASK = taskCreator(({fileBlob, info, handler, processor}, success, error) =>@@ -35,3 +36,19 @@ export const LOAD_FILE_TASK = taskCreator('LOAD_FILE_TASK');++export const LOAD_MAP_STYLE_TASK = taskCreator(+ ({url, id}, success, error) =>+ requestJson(url, (err, result) => {+ if (err) {+ error(err);+ } else {+ if (!result) {+ error(new Error('Map style response is empty'));+ }+ success({id, style: result})+ }+ }),++ 'LOAD_MAP_STYLE_TASK'+);diff --git a/src/utils/map-style-utils/mapbox-gl-style-editor.js b/src/utils/map-style-utils/mapbox-gl-style-editor.jsindex a32b5bc96..51fe6c7a6 100644--- a/src/utils/map-style-utils/mapbox-gl-style-editor.js+++ b/src/utils/map-style-utils/mapbox-gl-style-editor.js@@ -85,6 +85,7 @@ export const editBottomMapStyle = memoize(invisibleFilters.every(match => !match(layer)));+ // console.log(filteredLayers)return Immutable.fromJS({...mapStyle.style,layers: filteredLayers@@ -94,12 +95,31 @@ export const editBottomMapStyle = memoize();const mapUrlRg = /^mapbox:\/\/styles\/[-a-z0-9]{2,256}\/[-a-z0-9]{2,256}/;+const httpRg = /^(?=(http:|https:))/;+const mapboxStyleApiUrl = 'https://api.mapbox.com/styles/v1/';// valid style url// mapbox://styles/uberdata/cjfyl03kp1tul2smf5v2tbdd4// lowercase letters, numbers and dashes only.export function isValidStyleUrl(url) {- return typeof url === 'string' && Boolean(url.match(mapUrlRg));+ return typeof url === 'string' && Boolean(url.match(mapUrlRg) || url.match(httpRg));+}++export function getStyleDownloadUrl(styleUrl, accessToken) {+ if (styleUrl.startsWith('http')) {+ return styleUrl;+ }++ // mapbox://styles/jckr/cjhcl0lxv13di2rpfoytdbdyj+ if (styleUrl.startsWith('mapbox://styles')) {+ const styleId = styleUrl.replace('mapbox://styles/', '');++ // https://api.mapbox.com/styles/v1/heshan0131/cjg1bfumo1cwm2rlrjxkinfgw?pluginName=Keplergl&access_token=<token>+ return `${mapboxStyleApiUrl}${styleId}?pluginName=Keplergl&access_token=${accessToken}`+ }++ // style url not recognized+ return null;}export function scaleMapStyleByResolution(mapboxStyle, resolution) {@@ -143,3 +163,19 @@ export function scaleMapStyleByResolution(mapboxStyle, resolution) {return mapboxStyle;}++/**+ * When switch to a new style, try to keep current layer group visibility+ * by merging default and current+ * @param {object} defaultLayerGroup+ * @param {object} currentLayerGroup+ * @return {object} mergedLayerGroups+ */+export function mergeLayerGroupVisibility(defaultLayerGroup, currentLayerGroup) {+ return Object.keys(currentLayerGroup)+ .reduce((accu, key) => ({+ ...accu,+ ...(defaultLayerGroup.hasOwnProperty(key) ? {[key]: currentLayerGroup[key]} : {})+ }), defaultLayerGroup);+}+diff --git a/src/utils/mapbox-utils.js b/src/utils/map-style-utils/mapbox-utils.jssimilarity index 100%rename from src/utils/mapbox-utils.jsrename to src/utils/map-style-utils/mapbox-utils.jsdiff --git a/test/browser/components/container-test.js b/test/browser/components/container-test.jsindex 4675f4c3e..6b8a5a4ea 100644--- a/test/browser/components/container-test.js+++ b/test/browser/components/container-test.js@@ -74,7 +74,7 @@ test('Components -> Container -> Mount with mint:true', t => {let actions = store.getActions();- let expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'map', mint: true}};+ let expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'map', mint: true, mapboxApiAccessToken: undefined}};t.deepEqual(actions,@@ -104,21 +104,22 @@ test('Components -> Container -> Mount with mint:true', t => {let wrapper;const testId = {- id: 'milkshake'+ id: 'milkshake',+ mapboxApiAccessToken: 'pk.smoothie'};// mount with mint: truet.doesNotThrow(() => {wrapper = mount(<Provider store={store}>- <Container getState={s => s.smoothie} id={testId.id} />+ <Container getState={s => s.smoothie} id={testId.id} mapboxApiAccessToken={testId.mapboxApiAccessToken}/></Provider>);}, 'Should not throw error when mount');actions = store.getActions();- expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'milkshake', mint: true}};+ expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'milkshake', mint: true, mapboxApiAccessToken: 'pk.smoothie'}};t.deepEqual(actions,@@ -130,7 +131,13 @@ test('Components -> Container -> Mount with mint:true', t => {nextState = appReducer({}, expectedActions0);expectedState = {smoothie: {- milkshake: initialCoreState+ milkshake: {+ ...initialCoreState,+ mapStyle: {+ ...initialCoreState.mapStyle,+ mapboxApiAccessToken: 'pk.smoothie'+ }+ }}};t.deepEqual(@@ -178,14 +185,14 @@ test('Components -> Container -> Mount with mint:false', t => {t.doesNotThrow(() => {wrapper = mount(<Provider store={store}>- <Container getState={s => s.smoothie} id={testId.id} mint={false}/>+ <Container getState={s => s.smoothie} id={testId.id} mint={false} mapboxApiAccessToken="hello.world"/></Provider>);}, 'Should not throw error when mount');let actions = store.getActions();- let expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'milkshake', mint: false}};+ let expectedActions0 = {type: '@@kepler.gl/REGISTER_ENTRY', payload: {id: 'milkshake', mint: false, mapboxApiAccessToken: 'hello.world'}};t.deepEqual(actions,@@ -197,7 +204,14 @@ test('Components -> Container -> Mount with mint:false', t => {let nextState = appReducer({}, expectedActions0);let expectedState = {smoothie: {- milkshake: initialCoreState+ milkshake: {+ ...initialCoreState,+ mapStyle: {+ ...initialCoreState.mapStyle,+ // should replace access token+ mapboxApiAccessToken: 'hello.world'+ }+ }}};t.deepEqual(diff --git a/test/browser/components/injector-test.js b/test/browser/components/injector-test.jsindex 51e587c69..ba02cd9f4 100644--- a/test/browser/components/injector-test.js+++ b/test/browser/components/injector-test.js@@ -33,7 +33,7 @@ import {errorMsg} from 'components/injector';import {visStateLens, uiStateLens, mapStateLens, mapStyleLens} from 'reducers';const mockStore = configureStore();-const initialCoreState = coreReducer(undefined, keplerGlInit());+const initialCoreState = coreReducer(undefined, keplerGlInit({}));test('Components -> injector -> injectComponents', t => {const CustomHeader = () => <div className="my-test-header">smoothie</div>;diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.jsindex 62496d7be..f46c94135 100644--- a/test/helpers/mock-state.js+++ b/test/helpers/mock-state.js@@ -21,9 +21,11 @@import Immutable from 'immutable';import cloneDeep from 'lodash.clonedeep';import {VizColorPalette} from 'constants/custom-color-ranges';+import {getInitialInputStyle} from 'reducers/map-style-updaters';import keplerGlReducer from 'reducers/core';import * as VisStateActions from 'actions/vis-state-actions';+import * as MapStyleActions from 'actions/map-style-actions';// fixturesimport {testFields, testAllData} from 'test/fixtures/test-csv-data';@@ -206,12 +208,49 @@ function mockStateWithLayerDimensions(state) {return Immutable.fromJS(resultState);}+function mockStateWithCustomMapStyle(state) {+ const initialState = InitialState.toJS();+ const testCustomMapStyle = {+ ...getInitialInputStyle(),+ accessToken: 'secret_token',+ isValid: true,+ label: 'Smoothie the Cat',+ icon: 'data:image/png;base64,xyz',+ style: {version: 'v8', id: 'smoothie_the_cat', layers: [+ {id: 'background'}, {id: 'road'}, {id: 'label'}+ ], name: 'Smoothie the Cat'},+ url: 'mapbox://styles/shanhe/smoothie.the.cat'+ };++ // add custom map style+ const updatedState = applyActions(keplerGlReducer, initialState, [+ {+ action: MapStyleActions.inputMapStyle,+ payload: [testCustomMapStyle]+ },+ {+ action: MapStyleActions.loadCustomMapStyle,+ payload: [{+ style: testCustomMapStyle.style+ }]+ },+ {+ action: MapStyleActions.addCustomMapStyle,+ payload: [{}]+ },+ ]);++ return Immutable.fromJS(updatedState);+}+export const StateWFiles = mockStateWithFileUpload();export const StateWFilters = mockStateWithFilters();export const StateWFilesFiltersLayerColor = mockStateWithLayerDimensions(StateWFilters);+export const StateWCustomMapStyle = mockStateWithCustomMapStyle();+// saved hexagon layerexport const expectedSavedLayer0 = {id: 'hexagon-2',diff --git a/test/node/index.js b/test/node/index.jsindex f9608156f..3b6021898 100644--- a/test/node/index.js+++ b/test/node/index.js@@ -25,9 +25,11 @@ import './utils/filter-utils-test';import './utils/layer-utils-test';import './utils/data-scale-utils-test';import './utils/interaction-utils-test';+import './utils/mapbox-gl-style-editor-test';// test reducerimport './reducers/map-state-test';+import './reducers/map-style-test';import './reducers/vis-state-test';import './reducers/ui-state-test';import './reducers/composer-state-test';diff --git a/test/node/reducers/map-style-test.js b/test/node/reducers/map-style-test.jsnew file mode 100644index 000000000..9642808b2--- /dev/null+++ b/test/node/reducers/map-style-test.js@@ -0,0 +1,62 @@+import test from 'tape';++import reducer, {INITIAL_MAP_STYLE} from 'reducers/map-style';+import {keplerGlInit, receiveMapConfig} from 'actions/actions';+import SchemaManager from 'schemas';+import {+ drainTasksForTesting,+ succeedTaskInTest,+ errorTaskInTest+} from 'react-palm/tasks';++// helpers+import {StateWCustomMapStyle} from 'test/helpers/mock-state';++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.end();+});++test('#mapStyleReducer -> INIT', t => {+ 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.end();+});++test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {+ const stateWithToken = reducer(InitialMapStyle, keplerGlInit({mapboxApiAccessToken: 'smoothies_secret_token'}));++ const stateToSave = StateWCustomMapStyle.toJS();+ // save state+ const savedState = SchemaManager.getConfigToSave(stateToSave);++ // load state+ const stateLoaded = SchemaManager.parseSavedConfig(savedState);+ console.log(stateLoaded);++ const stateWithConfig= reducer(+ stateWithToken,+ receiveMapConfig(stateLoaded)+ );+ const [task1, ...more] = drainTasksForTesting();++ t.equal(more.length, 0, 'should return 1 task');++ // TODO: ask btford how to test Task.all++ t.end();+});diff --git a/test/node/schemas/map-style-schema-test.js b/test/node/schemas/map-style-schema-test.jsindex 23403c3e0..dfcb7c42a 100644--- a/test/node/schemas/map-style-schema-test.js+++ b/test/node/schemas/map-style-schema-test.js@@ -21,7 +21,7 @@import test from 'tape';import SchemaManager from 'schemas';-import {InitialState} from 'test/helpers/mock-state';+import {InitialState, StateWCustomMapStyle} from 'test/helpers/mock-state';test('#mapStyleSchema -> v1 -> save load mapStyle', t => {const initialState = InitialState.toJS();@@ -32,13 +32,46 @@ test('#mapStyleSchema -> v1 -> save load mapStyle', t => {const msLoaded = SchemaManager.parseSavedConfig(savedState).mapStyle;t.deepEqual(Object.keys(msToSave),- ['styleType', 'topLayerGroups', 'visibleLayerGroups'],- 'mapStyle should have all 6 entries');+ ['styleType', 'topLayerGroups', 'visibleLayerGroups', 'mapStyles'],+ 'mapStyle should have all 4 entries');const expectedSaved = {styleType: 'dark',topLayerGroups: {},- visibleLayerGroups: {}+ visibleLayerGroups: {},+ mapStyles: {}+ };++ t.deepEqual(msToSave, expectedSaved, 'saved mapStyle should be current');+ t.deepEqual(msLoaded, expectedSaved, 'loaded mapStyle should be current');+ t.end();+});++test('#mapStyleSchema -> v1 -> save load mapStyle with custom style', t => {+ const initialState = StateWCustomMapStyle.toJS();+ const savedState = SchemaManager.getConfigToSave(initialState);++ // save state+ const msToSave = savedState.config.mapStyle;+ const msLoaded = SchemaManager.parseSavedConfig(savedState).mapStyle;++ const expectedSaved = {+ styleType: 'smoothie_the_cat',+ topLayerGroups: {},+ visibleLayerGroups: {+ label: true,+ road: true+ },+ mapStyles: {+ 'smoothie_the_cat': {+ id: 'smoothie_the_cat',+ accessToken: 'secret_token',+ label: 'Smoothie the Cat',+ icon: 'data:image/png;base64,xyz',+ custom: true,+ url: 'mapbox://styles/shanhe/smoothie.the.cat'+ }+ }};t.deepEqual(msToSave, expectedSaved, 'saved mapStyle should be current');diff --git a/test/node/utils/mapbox-gl-style-editor-test.js b/test/node/utils/mapbox-gl-style-editor-test.jsnew file mode 100644index 000000000..1089772e3--- /dev/null+++ b/test/node/utils/mapbox-gl-style-editor-test.js@@ -0,0 +1,36 @@+import test from 'tape';+import {mergeLayerGroupVisibility} from 'utils/map-style-utils/mapbox-gl-style-editor';++test('mapbox.gl Style Editor -> mergeLayerGroupVisibility', t => {+ const defaultLG = {+ label: true,+ road: true,+ border: false,+ building: true,+ water: true,+ land: true+ };++ const currentLG = {+ label: false,+ road: false,+ border: true+ };++ const expected = {+ label: false,+ road: false,+ border: true,+ building: true,+ water: true,+ land: true+ };++ t.deepEqual(+ mergeLayerGroupVisibility(defaultLG, currentLG),+ expected,+ 'Should override default layer group visibility'+ );++ t.end();+});