Skip to content

Commit

Permalink
[Chore] Request map styles on demand (#2134)
Browse files Browse the repository at this point in the history
Signed-off-by: Ihor Dykhta <dikhta.igor@gmail.com>
Co-authored-by: Wesam Manassra <wesam.manassra@gmail.com>
  • Loading branch information
igorDykhta and manassra committed Feb 27, 2023
1 parent fb82992 commit f605167
Show file tree
Hide file tree
Showing 10 changed files with 537 additions and 176 deletions.
23 changes: 23 additions & 0 deletions examples/demo-app/src/data/sample-trip-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
}
}
}
};
14 changes: 11 additions & 3 deletions src/actions/src/map-style-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
16 changes: 5 additions & 11 deletions src/components/src/kepler-gl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
3 changes: 2 additions & 1 deletion src/constants/src/default-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: []
}
];

Expand Down
132 changes: 101 additions & 31 deletions src/reducers/src/map-style-updaters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import Task, {withTask} from 'react-palm/tasks';
import cloneDeep from 'lodash.clonedeep';
import Console from 'global/console';

// Utils
import {
Expand All @@ -31,6 +32,7 @@ import {
editBottomMapStyle,
getStyleImageIcon,
generateHashId,
isPlainObject,
hexToRgb
} from '@kepler.gl/utils';
import {
Expand Down Expand Up @@ -68,6 +70,9 @@ export type MapStyle = {
bottomMapStyle: any;
topMapStyle: any;
initialState?: MapStyle;
isLoading: {
[key: string]: boolean;
};
};

const DEFAULT_BLDG_COLOR = '#D1CEC7';
Expand Down Expand Up @@ -95,6 +100,7 @@ const getDefaultState = (): MapStyle => {
inputStyle: getInitialInputStyle(),
threeDBuildingColor: hexToRgb(DEFAULT_BLDG_COLOR),
custom3DBuildingColor: false,
isLoading: {},
bottomMapStyle: undefined,
topMapStyle: undefined
};
Expand Down Expand Up @@ -211,6 +217,7 @@ export function getMapStyles({

const topMapStyle = hasTopLayer
? editTopMapStyle({
id: styleType,
mapStyle,
visibleLayerGroups: topLayers
})
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`
Expand All @@ -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(
Expand Down Expand Up @@ -341,6 +404,7 @@ export const loadMapStylesUpdater = (
action: MapStyleActions.LoadMapStylesUpdaterAction
): MapStyle => {
const newStyles = action.payload || {};

const addLayerGroups = Object.keys(newStyles).reduce(
(accu, id) => ({
...accu,
Expand All @@ -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
Expand All @@ -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
};
};

/**
Expand All @@ -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
? {
Expand All @@ -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) {
Expand Down Expand Up @@ -470,7 +540,7 @@ function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl) {
)
),
// error
loadMapStyleErr
err => loadMapStyleErr(Object.keys(mapStyles), err)
)
];
}
Expand Down
2 changes: 2 additions & 0 deletions src/utils/src/map-style-utils/mapbox-gl-style-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,11 @@ const resolver = ({
*/
export const editTopMapStyle = memoize(
({
id,
mapStyle,
visibleLayerGroups
}: {
id?: string;
mapStyle: BaseMapStyle;
visibleLayerGroups: {[id: string]: LayerGroup | boolean} | false;
}) => {
Expand Down

0 comments on commit f605167

Please sign in to comment.