Skip to content

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

[Chore] Request map styles on demand (#2134)

Igor Dykhtaf605167fcd75
diff --git a/examples/demo-app/src/data/sample-trip-data.js b/examples/demo-app/src/data/sample-trip-data.js
index 3f54d3900..f4573b095 100644
--- a/examples/demo-app/src/data/sample-trip-data.js
+++ b/examples/demo-app/src/data/sample-trip-data.js
@@ -4087,6 +4087,29 @@ export const sampleTripDataConfig = {
value: true
}
]
+ },
+ mapStyle: {
+ styleType: '41fv96u',
+ visibleLayerGroups: {
+ label: false,
+ road: false,
+ border: false,
+ building: true,
+ water: true,
+ land: true,
+ '3d building': false
+ },
+ mapStyles: {
+ '41fv96u': {
+ accessToken: null,
+ custom: true,
+ icon:
+ 'https://api.mapbox.com/styles/v1/MAPBOX_USER/cjg0ks54x300a2squ8fr9vhvq/static/-122.3391,37.7922,9,0,0/400x300?access_token=ACCESS_TOKEN&logo=false&attribution=false',
+ id: '41fv96u',
+ label: 'Outdoors',
+ url: 'mapbox://styles/MAPBOX_USER/cjhnxdcfy4ug62sn6qdfjutob'
+ }
+ }
}
}
};
diff --git a/src/actions/src/map-style-actions.ts b/src/actions/src/map-style-actions.ts
index 2a1cb0cc1..3283b86f4 100644
--- a/src/actions/src/map-style-actions.ts
+++ b/src/actions/src/map-style-actions.ts
@@ -150,22 +150,30 @@ export const loadMapStyles: (
/** LOAD_MAP_STYLE_ERR */
export type LoadMapStyleErrUpdaterAction = {
- payload: Error;
+ payload: {
+ ids: string[];
+ error: Error;
+ };
};
/**
* Callback when load map style error
* @memberof mapStyleActions
+ * @param ids
* @param error
* @public
*/
export const loadMapStyleErr: (
- error: LoadMapStyleErrUpdaterAction['payload']
+ ids: LoadMapStyleErrUpdaterAction['payload']['ids'],
+ error: LoadMapStyleErrUpdaterAction['payload']['error']
) => Merge<
LoadMapStyleErrUpdaterAction,
{type: typeof ActionTypes.LOAD_MAP_STYLE_ERR}
> = createAction(
ActionTypes.LOAD_MAP_STYLE_ERR,
- (error: LoadMapStyleErrUpdaterAction['payload']) => ({payload: error})
+ (
+ ids: LoadMapStyleErrUpdaterAction['payload']['ids'],
+ error: LoadMapStyleErrUpdaterAction['payload']['error']
+ ) => ({payload: {ids, error}})
);
/** MAP_STYLE_CHANGE */
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index 46a5ecfa8..a2513c214 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -415,18 +415,12 @@ function KeplerGlFactory(
id: ms.id || generateHashId()
}));
- const allStyles = [...customStyles, ...defaultStyles].reduce(
- (accu, style) => {
- const hasStyleObject = style.style && typeof style.style === 'object';
- accu[hasStyleObject ? 'toLoad' : 'toRequest'][style.id] = style;
-
- return accu;
- },
- {toLoad: {}, toRequest: {}}
- );
+ const allStyles = [...customStyles, ...defaultStyles].reduce((accu, style) => {
+ accu[style.id] = style;
+ return accu;
+ }, {});
- this.props.mapStyleActions.loadMapStyles(allStyles.toLoad);
- this.props.mapStyleActions.requestMapStyles(allStyles.toRequest);
+ this.props.mapStyleActions.loadMapStyles(allStyles);
};
render() {
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index b7943aa80..e5feb81bf 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -264,7 +264,8 @@ export const DEFAULT_MAP_STYLES = [
id: 'satellite',
label: 'Satellite',
url: `mapbox://styles/mapbox/satellite-v9`,
- icon: `${ICON_PREFIX}/UBER_SATELLITE.png`
+ icon: `${ICON_PREFIX}/UBER_SATELLITE.png`,
+ layerGroups: []
}
];
diff --git a/src/reducers/src/map-style-updaters.ts b/src/reducers/src/map-style-updaters.ts
index c3b103c74..14c0ace77 100644
--- a/src/reducers/src/map-style-updaters.ts
+++ b/src/reducers/src/map-style-updaters.ts
@@ -20,6 +20,7 @@
import Task, {withTask} from 'react-palm/tasks';
import cloneDeep from 'lodash.clonedeep';
+import Console from 'global/console';
// Utils
import {
@@ -31,6 +32,7 @@ import {
editBottomMapStyle,
getStyleImageIcon,
generateHashId,
+ isPlainObject,
hexToRgb
} from '@kepler.gl/utils';
import {
@@ -68,6 +70,9 @@ export type MapStyle = {
bottomMapStyle: any;
topMapStyle: any;
initialState?: MapStyle;
+ isLoading: {
+ [key: string]: boolean;
+ };
};
const DEFAULT_BLDG_COLOR = '#D1CEC7';
@@ -95,6 +100,7 @@ const getDefaultState = (): MapStyle => {
inputStyle: getInitialInputStyle(),
threeDBuildingColor: hexToRgb(DEFAULT_BLDG_COLOR),
custom3DBuildingColor: false,
+ isLoading: {},
bottomMapStyle: undefined,
topMapStyle: undefined
};
@@ -211,6 +217,7 @@ export function getMapStyles({
const topMapStyle = hasTopLayer
? editTopMapStyle({
+ id: styleType,
mapStyle,
visibleLayerGroups: topLayers
})
@@ -245,12 +252,48 @@ function get3DBuildingColor(style): RGBColor {
}
function getLayerGroupsFromStyle(style) {
- return Array.isArray(style.layers)
+ return Array.isArray(style?.layers)
? DEFAULT_LAYER_GROUPS.filter(lg => style.layers.filter(lg.filter).length)
: [];
}
// Updaters
+
+/**
+ * @memberof mapStyleUpdaters
+ * @public
+ */
+export const requestMapStylesUpdater = (
+ state: MapStyle,
+ {payload: mapStyles}: MapStyleActions.RequestMapStylesUpdaterAction
+): MapStyle => {
+ const toLoad = Object.keys(mapStyles).reduce(
+ (accu, id) => ({
+ ...accu,
+ ...(!state.isLoading[id] ? {[id]: mapStyles[id]} : {})
+ }),
+ {}
+ );
+ const loadMapStyleTasks = getLoadMapStyleTasks(
+ toLoad,
+ state.mapboxApiAccessToken,
+ state.mapboxApiUrl
+ );
+
+ const isLoading = Object.keys(toLoad).reduce(
+ (accu, key) => ({
+ ...accu,
+ [key]: true
+ }),
+ {}
+ );
+ const nextState = {
+ ...state,
+ isLoading
+ };
+ return withTask(nextState, loadMapStyleTasks);
+};
+
/**
* Propagate `mapStyle` reducer with `mapboxApiAccessToken` and `mapStylesReplaceDefault`.
* if mapStylesReplaceDefault is true mapStyles is emptied; loadMapStylesUpdater() will
@@ -285,14 +328,18 @@ export const initMapStyleUpdater = (
export const mapConfigChangeUpdater = (
state: MapStyle,
action: MapStyleActions.MapConfigChangeUpdaterAction
-): MapStyle => ({
- ...state,
- ...action.payload,
- ...getMapStyles({
+): MapStyle => {
+ return {
...state,
- ...action.payload
- })
-});
+ ...action.payload,
+ ...getMapStyles({
+ ...state,
+ ...action.payload
+ })
+ };
+};
+
+const hasStyleObject = style => isPlainObject(style?.style);
/**
* Change to another map style. The selected style should already been loaded into `mapStyle.mapStyles`
@@ -307,6 +354,22 @@ export const mapStyleChangeUpdater = (
// we might not have received the style yet
return state;
}
+
+ if (!hasStyleObject(state.mapStyles[styleType])) {
+ // style hasn't loaded yet
+ return requestMapStylesUpdater(
+ {
+ ...state,
+ styleType
+ },
+ {
+ payload: {
+ [styleType]: state.mapStyles[styleType]
+ }
+ }
+ );
+ }
+
const defaultLGVisibility = getDefaultLayerGroupVisibility(state.mapStyles[styleType]);
const visibleLayerGroups = mergeLayerGroupVisibility(
@@ -341,6 +404,7 @@ export const loadMapStylesUpdater = (
action: MapStyleActions.LoadMapStylesUpdaterAction
): MapStyle => {
const newStyles = action.payload || {};
+
const addLayerGroups = Object.keys(newStyles).reduce(
(accu, id) => ({
...accu,
@@ -351,10 +415,20 @@ export const loadMapStylesUpdater = (
}),
{}
);
-
+ // reset isLoading
+ const isLoading = Object.keys(state.isLoading).reduce(
+ (accu, key) => ({
+ ...accu,
+ ...(state.isLoading[key] && hasStyleObject(newStyles[key])
+ ? {[key]: false}
+ : {[key]: state.isLoading[key]})
+ }),
+ {}
+ );
// add new styles to state
const newState = {
...state,
+ isLoading,
mapStyles: {
...state.mapStyles,
...addLayerGroups
@@ -374,23 +448,24 @@ export const loadMapStylesUpdater = (
// do nothing for now, if didn't load, skip it
export const loadMapStyleErrUpdater = (
state: MapStyle,
- action: MapStyleActions.LoadMapStyleErrUpdaterAction
-): MapStyle => state;
-
-/**
- * @memberof mapStyleUpdaters
- * @public
- */
-export const requestMapStylesUpdater = (
- state: MapStyle,
- {payload: mapStyles}: MapStyleActions.RequestMapStylesUpdaterAction
+ {payload: {ids, error}}: MapStyleActions.LoadMapStyleErrUpdaterAction
): MapStyle => {
- const loadMapStyleTasks = getLoadMapStyleTasks(
- mapStyles,
- state.mapboxApiAccessToken,
- state.mapboxApiUrl
+ Console.error(error);
+ // reset isLoading
+ const isLoading = Object.keys(state.isLoading).reduce(
+ (accu, key) => ({
+ ...accu,
+ ...(state.isLoading[key] && (ids || []).includes(key)
+ ? {[key]: false}
+ : {[key]: state.isLoading[key]})
+ }),
+ {}
);
- return withTask(state, loadMapStyleTasks);
+
+ return {
+ ...state,
+ isLoading
+ };
};
/**
@@ -416,11 +491,6 @@ export const receiveMapConfigUpdater = (
return state;
}
- // if saved custom mapStyles load the style object
- const loadMapStyleTasks = mapStyle.mapStyles
- ? getLoadMapStyleTasks(mapStyle.mapStyles, state.mapboxApiAccessToken, state.mapboxApiUrl)
- : null;
-
// merge default mapStyles
const merged = mapStyle.mapStyles
? {
@@ -439,7 +509,7 @@ export const receiveMapConfigUpdater = (
Boolean(mapStyle.threeDBuildingColor) || merged.custom3DBuildingColor;
const newState = mapConfigChangeUpdater(state, {payload: merged});
- return loadMapStyleTasks ? withTask(newState, loadMapStyleTasks) : newState;
+ return mapStyleChangeUpdater(newState, {payload: newState.styleType});
};
function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl) {
@@ -470,7 +540,7 @@ function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl) {
)
),
// error
- loadMapStyleErr
+ err => loadMapStyleErr(Object.keys(mapStyles), err)
)
];
}
diff --git a/src/utils/src/map-style-utils/mapbox-gl-style-editor.ts b/src/utils/src/map-style-utils/mapbox-gl-style-editor.ts
index 78fbbc8ba..b4d491ef5 100644
--- a/src/utils/src/map-style-utils/mapbox-gl-style-editor.ts
+++ b/src/utils/src/map-style-utils/mapbox-gl-style-editor.ts
@@ -67,9 +67,11 @@ const resolver = ({
*/
export const editTopMapStyle = memoize(
({
+ id,
mapStyle,
visibleLayerGroups
}: {
+ id?: string;
mapStyle: BaseMapStyle;
visibleLayerGroups: {[id: string]: LayerGroup | boolean} | false;
}) => {
diff --git a/test/browser/components/kepler-gl-test.js b/test/browser/components/kepler-gl-test.js
index 086f26198..ae1055bf6 100644
--- a/test/browser/components/kepler-gl-test.js
+++ b/test/browser/components/kepler-gl-test.js
@@ -248,21 +248,21 @@ test('Components -> KeplerGl -> Mount -> Load default map style task', t => {
const actions = store.getActions();
const expectedActions = [
- {type: ActionTypes.LOAD_MAP_STYLES, payload: {}},
{
- type: ActionTypes.REQUEST_MAP_STYLES,
+ type: ActionTypes.LOAD_MAP_STYLES,
payload: DEFAULT_MAP_STYLES.reduce((accu, curr) => ({...accu, [curr.id]: curr}), {})
}
];
t.deepEqual(
actions,
expectedActions,
- 'Should mount kepler.gl and dispatch 2 actions to load map styles'
+ 'Should mount kepler.gl and dispatch 1 action to load map styles'
);
- const resultState1 = coreReducer(initialCoreState, actions[1]);
- const [task1, ...rest] = drainTasksForTesting();
- t.equal(rest.length, 0, 'should dispatch 1 tasks');
+ // const tmpState0 = coreReducer(initialCoreState, actions[0]);
+ const tmpState = coreReducer(initialCoreState, actions[0]);
+ const [actionTask1, ...more] = drainTasksForTesting();
+ t.equal(more.length, 0, 'should dispatch 1 tasks');
const expectedTask = {
payload: [
@@ -270,83 +270,63 @@ test('Components -> KeplerGl -> Mount -> Load default map style task', t => {
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'
- },
- {
- id: 'satellite',
- url:
- 'https://api.mapbox.com/styles/v1/mapbox/satellite-v9?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'}},
- {id: 'satellite', style: {satellite: 'yes'}}
- ])
+ t.deepEqual(actionTask1.payload, expectedTask.payload, 'should create task to load map styles');
+ t.deepEqual(tmpState.mapStyle.isLoading, {dark: true}, 'should set mapStyle isLoading');
+
+ const resultState1 = coreReducer(
+ tmpState,
+ succeedTaskWithValues(actionTask1, [{id: 'dark', style: {layers: [], name: 'dark'}}])
);
const expectedStateMapStyles = {
+ ...tmpState.mapStyle.mapStyles,
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'}
- },
- satellite: {
- ...DEFAULT_MAP_STYLES[4],
- style: {satellite: 'yes'},
- layerGroups: []
}
};
t.deepEqual(
- resultState2.mapStyle.mapStyles,
+ resultState1.mapStyle.mapStyles,
expectedStateMapStyles,
'should update state with loaded map styles'
);
+ t.deepEqual(
+ resultState1.mapStyle.isLoading,
+ {
+ dark: false
+ },
+ 'should update state isLoading'
+ );
+
t.end();
});
test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {
drainTasksForTesting();
// mount with empty store
- const store = mockStore(initialState);
- // mount without id or a kepler.gl state
+ // set initialState to custom styleType
+ const initialCoreState1 = {
+ ...initialCoreState,
+ mapStyle: {
+ ...initialCoreState.mapStyle,
+ styleType: 'chai'
+ }
+ };
+ const initialState1 = {
+ keplerGl: {
+ map: initialCoreState1
+ }
+ };
+ const store = mockStore(initialState1);
+
+ //
const customStyle1 = {
id: 'smoothie',
url: 'mapbox://styles/smoothie/thecat'
@@ -366,7 +346,8 @@ test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {
},
layerGroups: [
{
- slug: 'label'
+ slug: 'label',
+ defaultVisibility: true
}
]
};
@@ -389,40 +370,47 @@ test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {
{
type: ActionTypes.LOAD_MAP_STYLES,
payload: {
+ ...initialCoreState1.mapStyle.mapStyles,
milkshake: customStyle2,
- chai: customStyle3
+ chai: customStyle3,
+ smoothie: customStyle1
}
- },
- {
- type: ActionTypes.REQUEST_MAP_STYLES,
- payload: DEFAULT_MAP_STYLES.reduce(
- (accu, curr) => ({...accu, [curr.id]: curr, smoothie: customStyle1}),
- {}
- )
}
];
t.deepEqual(
actions,
expectedActions,
- 'Should mount kepler.gl and dispatch 2 actions to load map styles'
+ 'Should mount kepler.gl and dispatch 1 actions to load map styles'
);
- const resultState1 = coreReducer(initialCoreState, actions[0]);
+ const resultState1 = coreReducer(initialCoreState1, actions[0]);
const expectedMapStyleState1 = {
- ...initialCoreState.mapStyle,
+ ...initialCoreState1.mapStyle,
mapStyles: {
- ...initialCoreState.mapStyle.mapStyles,
+ ...initialCoreState1.mapStyle.mapStyles,
milkshake: {
id: 'milkshake',
style: {
id: 'mm',
layers: []
},
- layerGroups: {}
+ layerGroups: []
},
- chai: customStyle3
- }
+ chai: customStyle3,
+ smoothie: {
+ id: 'smoothie',
+ url: 'mapbox://styles/smoothie/thecat',
+ layerGroups: []
+ }
+ },
+ visibleLayerGroups: {
+ label: true
+ },
+ threeDBuildingColor: [194.6103322548211, 191.81688250953655, 185.2988331038727],
+ bottomMapStyle: {id: 'chai', layers: []},
+ topMapStyle: null,
+ editable: 1
};
t.deepEqual(
@@ -431,48 +419,19 @@ test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {
'Should load map style into reducer and create layer groups'
);
+ Object.keys(resultState1.mapStyle).forEach(key => {
+ t.deepEqual(
+ resultState1.mapStyle[key],
+ expectedMapStyleState1[key],
+ `mapStyle[${key}] should be correct`
+ );
+ });
+
// Do not remove this. Necessary for testing flow
// eslint-disable-next-line no-unused-vars
- 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'
- },
- {
- id: 'satellite',
- url:
- 'https://api.mapbox.com/styles/v1/mapbox/satellite-v9?pluginName=Keplergl&access_token=smoothie-the-cat'
- }
- ]
- };
+ const actionTask1 = drainTasksForTesting();
- t.deepEqual(task1.payload, expectedTask.payload, 'should create task to load map styles');
+ t.equal(actionTask1.length, 0, 'should not dispatch action to load styles');
t.end();
});
diff --git a/test/helpers/mock-map-styles.js b/test/helpers/mock-map-styles.js
index ccb2fe5c1..c5c54af21 100644
--- a/test/helpers/mock-map-styles.js
+++ b/test/helpers/mock-map-styles.js
@@ -18,21 +18,14 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+import {DEFAULT_LAYER_GROUPS} from '@kepler.gl/constants';
+
export const MOCK_MAP_STYLE = {
id: 'dark',
label: 'Dark',
url: 'mapbox://styles/xxxxx/abcdefg',
icon: 'https://my.icon.net/kepler.gl/test/taro.png',
- layerGroups: [
- {
- slug: 'water',
- defaultVisibility: true
- },
- {
- slug: 'land',
- defaultVisibility: true
- }
- ],
+ layerGroups: DEFAULT_LAYER_GROUPS,
style: {
version: 8,
name: 'Mock-Map-Style',
@@ -72,6 +65,100 @@ export const MOCK_MAP_STYLE = {
'fill-color': '#112330'
},
interactive: true
+ },
+ {
+ id: 'road-path-rough',
+ type: 'line',
+ source: 'composite',
+ 'source-layer': 'road'
+ },
+ {
+ minzoom: 13,
+ type: 'line',
+ source: 'composite',
+ id: 'bridge-rail',
+ 'source-layer': 'road'
+ },
+ {
+ type: 'symbol',
+ source: 'composite',
+ id: 'country-label-sm',
+ 'source-layer': 'country_label'
+ }
+ ]
+ }
+};
+
+export const MOCK_MAP_STYLE_LIGHT = {
+ id: 'light',
+ label: 'Light',
+ url: 'mapbox://styles/xxxxx/hijklmn',
+ icon: 'https://my.icon.net/kepler.gl/test/blue.png',
+ layerGroups: DEFAULT_LAYER_GROUPS,
+ style: {
+ version: 8,
+ name: 'Mock-Map-Style-LIGHT',
+ metadata: {},
+ center: [-73.96109142750214, 40.74028310359776],
+ zoom: 12.624759221889015,
+ bearing: 23.936999544510627,
+ pitch: 0,
+ light: {
+ anchor: 'viewport'
+ },
+ sources: {
+ composite: {
+ url: 'mapbox://mapbox.mapbox-terrain-v2,mapbox.mapbox-streets-v7,eklimcz.00zz64mq',
+ type: 'vector'
+ }
+ },
+ sprite: 'mapbox://sprites',
+ glyphs: 'mapbox://fonts',
+ layers: [
+ {
+ id: 'background',
+ type: 'background',
+ layout: {},
+ paint: {
+ 'background-color': '#FFFFFF'
+ },
+ interactive: true
+ },
+ {
+ id: 'water',
+ type: 'fill',
+ source: 'composite',
+ 'source-layer': 'water',
+ layout: {},
+ paint: {
+ 'fill-color': '#FEFEFE'
+ },
+ interactive: true
+ },
+ {
+ id: 'building',
+ type: 'fill',
+ paint: {
+ 'fill-color': '#C8C8C8'
+ }
+ },
+ {
+ id: 'road-major',
+ type: 'line',
+ source: 'composite',
+ 'source-layer': 'road'
+ },
+ {
+ type: 'line',
+ source: 'composite',
+ id: 'street-major',
+ 'source-layer': 'road'
+ },
+ {
+ type: 'symbol',
+ source: 'composite',
+ id: 'admin-label-lg',
+ 'source-layer': 'country_label'
}
]
}
diff --git a/test/node/reducers/map-style-test.js b/test/node/reducers/map-style-test.js
index 518e19cd9..f17c19cb9 100644
--- a/test/node/reducers/map-style-test.js
+++ b/test/node/reducers/map-style-test.js
@@ -19,7 +19,7 @@
// THE SOFTWARE.
import test from 'tape';
-import {drainTasksForTesting, succeedTaskWithValues} from 'react-palm/tasks';
+import {drainTasksForTesting, succeedTaskWithValues, errorTaskInTest} from 'react-palm/tasks';
import {
mapStyleReducer as reducer,
@@ -27,12 +27,19 @@ import {
loadMapStylesUpdater,
getInitialInputStyle
} from '@kepler.gl/reducers';
-import {keplerGlInit, receiveMapConfig} from '@kepler.gl/actions';
+import {
+ keplerGlInit,
+ receiveMapConfig,
+ loadMapStyles,
+ mapConfigChange,
+ mapStyleChange
+} from '@kepler.gl/actions';
import SchemaManager from '@kepler.gl/schemas';
import {DEFAULT_MAP_STYLES, DEFAULT_MAPBOX_API_URL} from '@kepler.gl/constants';
// helpers
import {StateWCustomMapStyle} from 'test/helpers/mock-state';
+import {MOCK_MAP_STYLE, MOCK_MAP_STYLE_LIGHT} from 'test/helpers/mock-map-styles';
const InitialMapStyle = reducer(undefined, {});
@@ -84,6 +91,56 @@ test('#mapStyleReducer -> INIT', t => {
});
test('#mapStyleReducer -> INIT & LOAD_MAP_STYLES', t => {
+ const newState = reducer(
+ InitialMapStyle,
+ keplerGlInit({
+ mapboxApiAccessToken: 'smoothies_secret_token'
+ })
+ );
+
+ t.deepEqual(
+ newState,
+ {
+ ...INITIAL_MAP_STYLE,
+ initialState: {},
+ mapboxApiAccessToken: 'smoothies_secret_token',
+ mapboxApiUrl: DEFAULT_MAPBOX_API_URL
+ },
+ 'initialize map style with mapboxApiAccessToken and mapStylesReplaceDefault; mapStyles empty'
+ );
+
+ const finalState = loadMapStylesUpdater(newState, {payload: INITIAL_MAP_STYLE.mapStyles});
+
+ // should start loading default dark style
+ t.deepEqual(
+ finalState,
+ {
+ ...newState,
+ isLoading: {
+ dark: true
+ }
+ },
+ 'user provided mapStyles are populated, defaults ignored'
+ );
+
+ const tasks = drainTasksForTesting();
+ t.equal(tasks.length, 1, 'should dispatch request map style task');
+
+ const expectedTask = {
+ payload: [
+ {
+ id: 'dark',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqbbf6l9k302sl96tyvka09?pluginName=Keplergl&access_token=smoothies_secret_token'
+ }
+ ]
+ };
+
+ t.deepEqual(tasks[0].payload, expectedTask.payload, 'should have correct load map style task');
+ t.end();
+});
+
+test('#mapStyleReducer -> INIT & LOAD_MAP_STYLES -> mapStylesReplaceDefault: true', t => {
const myMapStyle = {
id: 'default dark v9',
label: 'default dark v9',
@@ -124,6 +181,9 @@ test('#mapStyleReducer -> INIT & LOAD_MAP_STYLES', t => {
'user provided mapStyles are populated, defaults ignored'
);
+ const tasks = drainTasksForTesting();
+ t.equal(tasks.length, 0, 'should not dispatch request map style task');
+
t.end();
});
@@ -167,6 +227,9 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
},
...defaultMapStyles
},
+ isLoading: {
+ smoothie_the_cat: true
+ },
mapboxApiAccessToken: 'smoothies_secret_token',
mapboxApiUrl: DEFAULT_MAPBOX_API_URL,
mapStylesReplaceDefault: false,
@@ -180,9 +243,15 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
t.deepEqual(stateWithConfig, expectedStateWithConfig, 'should load saved map style config');
- const [task1, ...more] = drainTasksForTesting();
-
- t.equal(more.length, 0, 'should return 1 task');
+ Object.keys(stateWithConfig).forEach(key => {
+ t.deepEqual(
+ stateWithConfig[key],
+ expectedStateWithConfig[key],
+ 'should load saved map style config'
+ );
+ });
+ const [task1, ...more1] = drainTasksForTesting();
+ t.equal(more1.length, 0, 'should return 1 tasks');
const expectedTask = {
payload: [
@@ -232,7 +301,10 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
initialState: {},
bottomMapStyle: {layers: [], name: 'smoothie_the_cat'},
topMapStyle: null,
- editable: 0
+ editable: 0,
+ isLoading: {
+ smoothie_the_cat: false
+ }
};
t.deepEqual(
@@ -285,3 +357,148 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {
t.end();
});
+
+// eslint-disable-next-line max-statements
+test('#mapStyleReducer -> MAP_STYLE_CHANGE', t => {
+ const initialState = reducer(
+ InitialMapStyle,
+ keplerGlInit({
+ mapboxApiAccessToken: 'smoothies_secret_token'
+ })
+ );
+
+ // loadMapStyles
+ const nextState = reducer(initialState, loadMapStyles({dark: MOCK_MAP_STYLE}));
+ t.deepEqual(nextState.mapStyles.dark, MOCK_MAP_STYLE, 'should load map style');
+ t.deepEqual(nextState.bottomMapStyle, MOCK_MAP_STYLE.style, 'bottomMapStyle should be set');
+ t.equal(nextState.topMapStyle, null, 'topMapStyle should be set');
+ t.equal(nextState.editable, 7, 'editable should be set');
+ t.deepEqual(
+ nextState.visibleLayerGroups,
+ {
+ label: true,
+ road: true,
+ border: false,
+ building: true,
+ water: true,
+ land: true,
+ '3d building': false
+ },
+ 'should set visibleLayerGroups'
+ );
+
+ // move label to be on top
+ const nextState1 = reducer(
+ nextState,
+ mapConfigChange({topLayerGroups: {label: true, road: true}})
+ );
+ const expectedTopStyle = {
+ ...MOCK_MAP_STYLE.style,
+ layers: [
+ {
+ id: 'road-path-rough',
+ type: 'line',
+ source: 'composite',
+ 'source-layer': 'road'
+ },
+ {
+ minzoom: 13,
+ type: 'line',
+ source: 'composite',
+ id: 'bridge-rail',
+ 'source-layer': 'road'
+ },
+ {
+ type: 'symbol',
+ source: 'composite',
+ id: 'country-label-sm',
+ 'source-layer': 'country_label'
+ }
+ ]
+ };
+ t.deepEqual(nextState1.topMapStyle, expectedTopStyle, 'topMapStyle should be set correctly');
+
+ // hide road layer
+ const nextState2 = reducer(
+ nextState1,
+ mapConfigChange({visibleLayerGroups: {...nextState1.visibleLayerGroups, road: false}})
+ );
+
+ const expectedTopStyle2 = {
+ ...MOCK_MAP_STYLE.style,
+ layers: [
+ {
+ type: 'symbol',
+ source: 'composite',
+ id: 'country-label-sm',
+ 'source-layer': 'country_label'
+ }
+ ]
+ };
+
+ t.deepEqual(nextState2.topMapStyle, expectedTopStyle2, 'topMapStyle should be set correctly');
+
+ // set style type to light
+ const nextState3 = reducer(nextState2, mapStyleChange('light'));
+ const tasks = drainTasksForTesting();
+ t.equal(tasks.length, 1, 'should dispatch 1 request map style task');
+
+ const expectedNextState3 = {
+ ...nextState2,
+ styleType: 'light',
+ isLoading: {
+ light: true
+ }
+ };
+ const expectedTaskPayload = [
+ {
+ id: 'light',
+ url:
+ 'https://api.mapbox.com/styles/v1/uberdata/cjoqb9j339k1f2sl9t5ic5bn4?pluginName=Keplergl&access_token=smoothies_secret_token'
+ }
+ ];
+ t.deepEqual(nextState3, expectedNextState3, 'state should be correct');
+ t.deepEqual(tasks[0].payload, expectedTaskPayload, 'should dispatch load light map style task');
+
+ // successfully load light map style
+ const succeedState = reducer(
+ nextState3,
+ succeedTaskWithValues(tasks[0], [{id: 'light', style: MOCK_MAP_STYLE_LIGHT.style}])
+ );
+
+ const expectedMapStyles = {
+ ...nextState3.mapStyles,
+ light: {
+ ...nextState3.mapStyles.light,
+ style: MOCK_MAP_STYLE_LIGHT.style
+ }
+ };
+
+ t.deepEqual(succeedState.mapStyles, expectedMapStyles, 'should save map styles');
+
+ const expectedTopStyle3 = {
+ ...MOCK_MAP_STYLE_LIGHT.style,
+ layers: [
+ {
+ type: 'symbol',
+ source: 'composite',
+ id: 'admin-label-lg',
+ 'source-layer': 'country_label'
+ }
+ ]
+ };
+
+ t.deepEqual(succeedState.topMapStyle, expectedTopStyle3, 'topMapStyle should be set correctly');
+ t.deepEqual(succeedState.isLoading, {light: false}, 'should set isLoading correctly');
+ t.deepEqual(
+ succeedState.threeDBuildingColor,
+ [237.4432283491836, 237.4432283491836, 237.4432283491836],
+ 'should set threeDBuildingColor correctly'
+ );
+
+ // error load light map style
+ const erroredState = reducer(nextState3, errorTaskInTest(tasks[0], new Error('hello')));
+ t.deepEqual(erroredState.isLoading, {light: false}, 'should set isLoading correctly');
+
+ t.end();
+});
diff --git a/test/node/reducers/provider-state-test.js b/test/node/reducers/provider-state-test.js
index 8cfdf6b59..8fe669b18 100644
--- a/test/node/reducers/provider-state-test.js
+++ b/test/node/reducers/provider-state-test.js
@@ -64,7 +64,7 @@ test('#providerStateReducerFactory', t => {
test('#providerStateReducer -> EXPORT_FILE_TO_CLOUD', t => {
const errSpy = sinon.spy(Console, 'error');
-
+ drainTasksForTesting();
// null
reducer(undefined, exportFileToCloud({provider: null}));
t.ok(errSpy.calledOnce, 'should call console.error if provider is undefined');