Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Feat] Add "No Basemap" option with map background color control (#2136)
Igor Dykhtae2848008509d
diff --git a/docs/api-reference/localization/README.md b/docs/api-reference/localization/README.mdindex 2f181e6b4..217381eae 100644--- a/docs/api-reference/localization/README.md+++ b/docs/api-reference/localization/README.md@@ -6,7 +6,7 @@ Current supported languages are:| locale code | Language | Default? ||-------------|------------|----------|| en | English | default |-| fi | Finish | |+| fi | Finnish | || pt | Portuguese | || ca | Catalan | || es | Spanish | |diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 7751ca97b..b350b331b 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -133,6 +133,7 @@ const ActionTypes = {ADD_CUSTOM_MAP_STYLE: `${ACTION_PREFIX}ADD_CUSTOM_MAP_STYLE`,REQUEST_MAP_STYLES: `${ACTION_PREFIX}REQUEST_MAP_STYLES`,SET_3D_BUILDING_COLOR: `${ACTION_PREFIX}SET_3D_BUILDING_COLOR`,+ SET_BACKGROUND_COLOR: `${ACTION_PREFIX}SET_BACKGROUND_COLOR`,// uiStateTOGGLE_SIDE_PANEL: `${ACTION_PREFIX}TOGGLE_SIDE_PANEL`,diff --git a/src/actions/src/map-style-actions.ts b/src/actions/src/map-style-actions.tsindex 3283b86f4..190693fb7 100644--- a/src/actions/src/map-style-actions.ts+++ b/src/actions/src/map-style-actions.ts@@ -101,16 +101,21 @@ export const mapConfigChange: ((mapStyle: MapConfigChangeUpdaterAction['payload']) => ({payload: mapStyle}));+type OnLoadMapStyleSuccessCallback = (payload: {styleType: string}) => any;+/** REQUEST_MAP_STYLES */export type RequestMapStylesUpdaterAction = {payload: {- [key: string]: {- id: string;- label?: string;- url: string;- icon?: string;- layerGroups?: LayerGroup[];+ mapStyles: {+ [key: string]: {+ id: string;+ label?: string;+ url: string;+ icon?: string;+ layerGroups?: LayerGroup[];+ };};+ onSuccess?: OnLoadMapStyleSuccessCallback;};};/**@@ -119,18 +124,25 @@ export type RequestMapStylesUpdaterAction = {* @public*/export const requestMapStyles: (- mapStyles: RequestMapStylesUpdaterAction['payload']+ mapStyles: RequestMapStylesUpdaterAction['payload']['mapStyles'],+ onSuccess?: RequestMapStylesUpdaterAction['payload']['onSuccess']) => Merge<RequestMapStylesUpdaterAction,{type: typeof ActionTypes.REQUEST_MAP_STYLES}> = createAction(ActionTypes.REQUEST_MAP_STYLES,- (mapStyles: RequestMapStylesUpdaterAction['payload']) => ({payload: mapStyles})+ (+ mapStyles: RequestMapStylesUpdaterAction['payload']['mapStyles'],+ onSuccess?: RequestMapStylesUpdaterAction['payload']['onSuccess']+ ) => ({payload: {mapStyles, onSuccess}}));/** LOAD_MAP_STYLES */export type LoadMapStylesUpdaterAction = {- payload: MapStyles;+ payload: {+ newStyles: MapStyles;+ onSuccess?: OnLoadMapStyleSuccessCallback;+ };};/*** Callback when load map style success@@ -139,13 +151,17 @@ export type LoadMapStylesUpdaterAction = {* @public*/export const loadMapStyles: (- newStyles: LoadMapStylesUpdaterAction['payload']+ newStyles: LoadMapStylesUpdaterAction['payload']['newStyles'],+ onSuccess?: LoadMapStylesUpdaterAction['payload']['onSuccess']) => Merge<LoadMapStylesUpdaterAction,{type: typeof ActionTypes.LOAD_MAP_STYLES}> = createAction(ActionTypes.LOAD_MAP_STYLES,- (newStyles: LoadMapStylesUpdaterAction['payload']) => ({payload: newStyles})+ (+ newStyles: LoadMapStylesUpdaterAction['payload']['newStyles'],+ onSuccess?: LoadMapStylesUpdaterAction['payload']['onSuccess']+ ) => ({payload: {newStyles, onSuccess}}));/** LOAD_MAP_STYLE_ERR */@@ -178,22 +194,30 @@ export const loadMapStyleErr: (/** MAP_STYLE_CHANGE */export type MapStyleChangeUpdaterAction = {- payload: string;+ payload: {+ styleType: string;+ onSuccess?: OnLoadMapStyleSuccessCallback;+ };};/*** Change to another map style. The selected style should already been loaded into `mapStyle.mapStyles`* @memberof mapStyleActions* @param styleType the style to change to+ * @param onSuccess optional success callback function when an asynchronous basemap syle has loaded* @public*/export const mapStyleChange: (- styleType: MapStyleChangeUpdaterAction['payload']+ styleType: MapStyleChangeUpdaterAction['payload']['styleType'],+ onSuccess?: MapStyleChangeUpdaterAction['payload']['onSuccess']) => Merge<MapStyleChangeUpdaterAction,{type: typeof ActionTypes.MAP_STYLE_CHANGE}> = createAction(ActionTypes.MAP_STYLE_CHANGE,- (styleType: MapStyleChangeUpdaterAction['payload']) => ({payload: styleType})+ (+ styleType: MapStyleChangeUpdaterAction['payload']['styleType'],+ onSuccess?: MapStyleChangeUpdaterAction['payload']['onSuccess']+ ) => ({payload: {styleType, onSuccess}}));/** LOAD_CUSTOM_MAP_STYLE */@@ -244,6 +268,24 @@ export const set3dBuildingColor: ((color: Set3dBuildingColorUpdaterAction['payload']) => ({payload: color}));+/** SET_BACKGROUND_COLOR */+export type SetBackgroundColorUpdaterAction = {+ payload: RGBColor;+};++/**+ * Set background color+ * @memberof mapStyleActions+ * @param color - [r, g, b]+ * @public+ */+export const setBackgroundColor: (+ color: SetBackgroundColorUpdaterAction['payload']+) => Merge<+ SetBackgroundColorUpdaterAction,+ {type: typeof ActionTypes.SET_BACKGROUND_COLOR}+> = createAction(ActionTypes.SET_BACKGROUND_COLOR, (color: RGBColor) => ({payload: color}));+/*** Actions handled mostly by `mapStyle` reducer.* They manage the display of base map, such as loading and receiving base map styles,diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex ecfdb0486..9b8801ff9 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -52,11 +52,11 @@ import {observeDimensions,unobserveDimensions,hasMobileWidth,- EMPTY_MAPBOX_STYLE,getMapLayersFromSplitMaps,onViewPortChange,getViewportFromMapState,- normalizeEvent+ normalizeEvent,+ rgbToHex} from '@kepler.gl/utils';import {breakPointValues} from '@kepler.gl/styles';@@ -65,7 +65,9 @@ import {FILTER_TYPES,GEOCODER_LAYER_ID,THROTTLE_NOTIFICATION_TIME,- DEFAULT_PICKING_RADIUS+ DEFAULT_PICKING_RADIUS,+ NO_MAP_ID,+ EMPTY_MAPBOX_STYLE} from '@kepler.gl/constants';import ErrorBoundary from './common/error-boundary';@@ -334,6 +336,19 @@ export default function MapContainerFactory(generateMapboxLayers);+ // merge in a background-color style if the basemap choice is NO_MAP_ID+ // used by <StyledMap> inline style prop+ mapStyleTypeSelector = props => props.mapStyle.styleType;+ mapStyleBackgroundColorSelector = props => props.mapStyle.backgroundColor;+ styleSelector = createSelector(+ this.mapStyleTypeSelector,+ this.mapStyleBackgroundColorSelector,+ (styleType, backgroundColor) => ({+ ...MAP_STYLE.container,+ ...(styleType === NO_MAP_ID ? {backgroundColor: rgbToHex(backgroundColor)} : {})+ })+ );+/* component private functions */_onCloseMapPopover = () => {this.props.visStateActions.onLayerClick(null);@@ -855,7 +870,7 @@ export default function MapContainerFactory(return (<StyledMapref={this._ref}- style={MAP_STYLE.container}+ style={this.styleSelector(this.props)}onContextMenu={event => event.preventDefault()}mixBlendMode={visState.overlayBlending}>diff --git a/src/components/src/side-panel/map-manager.tsx b/src/components/src/side-panel/map-manager.tsxindex 3f2ed0c4e..221480040 100644--- a/src/components/src/side-panel/map-manager.tsx+++ b/src/components/src/side-panel/map-manager.tsx@@ -20,15 +20,13 @@import React, {Component} from 'react';-import {Button, SidePanelSection} from '../common/styled-components';+import {Button} from '../common/styled-components';import MapStyleSelectorFactory from './map-style-panel/map-style-selector';import LayerGroupSelectorFactory from './map-style-panel/map-layer-selector';import PanelTitleFactory from '../side-panel/panel-title';import {Add} from '../common/icons';import {PanelMeta} from './common/types';-import ColorSelector from './layer-panel/color-selector';-import {createSelector} from 'reselect';import {injectIntl, WrappedComponentProps} from 'react-intl';import {FormattedMessage} from '@kepler.gl/localization';import {MapStyle} from '@kepler.gl/reducers';@@ -53,9 +51,6 @@ function MapManagerFactory(isSelecting: false};- buildingColorSelector = (props: MapManagerProps) => props.mapStyle.threeDBuildingColor;- setColorSelector = (props: MapManagerProps) => props.mapStyleActions.set3dBuildingColor;-_toggleSelecting = () => {this.setState({isSelecting: !this.state.isSelecting});};@@ -70,22 +65,7 @@ function MapManagerFactory(render() {const {mapStyle, intl, mapStyleActions, showAddMapStyleModal, panelMetadata} = this.props;const currentStyle = mapStyle.mapStyles[mapStyle.styleType] || {};- const editableLayers = (currentStyle.layerGroups || []).map(lg => lg.slug);- const hasBuildingLayer = mapStyle.visibleLayerGroups['3d building'];- const colorSetSelector = createSelector(- this.buildingColorSelector,- this.setColorSelector,- (selectedColor, setColor) => [- {- selectedColor,- setColor,- isRange: false,- label: intl.formatMessage({id: 'mapManager.3dBuildingColor'})- }- ]- );-- const colorSets = colorSetSelector(this.props);+ const editableLayers = currentStyle.layerGroups || [];return (<div className="map-style-panel">@@ -111,11 +91,12 @@ function MapManagerFactory(editableLayers={editableLayers}topLayers={mapStyle.topLayerGroups}onChange={mapStyleActions.mapConfigChange}+ threeDBuildingColor={mapStyle.threeDBuildingColor}+ on3dBuildingColorChange={mapStyleActions.set3dBuildingColor}+ backgroundColor={mapStyle.backgroundColor}+ onBackgroundColorChange={mapStyleActions.setBackgroundColor}/>) : null}- <SidePanelSection>- <ColorSelector colorSets={colorSets} disabled={!hasBuildingLayer} />- </SidePanelSection></div></div>);diff --git a/src/components/src/side-panel/map-style-panel/map-layer-group-color-picker.tsx b/src/components/src/side-panel/map-style-panel/map-layer-group-color-picker.tsxnew file mode 100644index 000000000..de4ede776--- /dev/null+++ b/src/components/src/side-panel/map-style-panel/map-layer-group-color-picker.tsx@@ -0,0 +1,93 @@+import React, {useCallback, useState} from 'react';+import styled, {css} from 'styled-components';++import {rgbToHex} from '@kepler.gl/utils';+import {FormattedMessage} from '@kepler.gl/localization';+import {RGBColor} from '@kepler.gl/types';++import {Portaled} from '../..';+import {Tooltip} from '../../common/styled-components';+import CustomPicker from '../layer-panel/custom-picker';+import {ColorBlock} from '../layer-panel/color-selector';++const LayerGroupColorPickerWrapper = styled.div<{extraMarginRight?: boolean; disabled?: boolean}>`+ margin-right: ${props => (props.extraMarginRight ? 0 : 24)}px;+ cursor: pointer;+ ${props =>+ props.disabled &&+ css`+ cursor: none;+ pointer-events: none;+ opacity: 0.3;+ `}+`;++export type LayerGroupColorPickerProps = {+ slug: string;+ color: RGBColor;+ onColorChange: (pd: RGBColor) => void;+ extraMarginRight: boolean;+ disabled: boolean;+};++LayerGroupColorPickerFactory.deps = [];++function LayerGroupColorPickerFactory() {+ const LayerGroupColorPicker: React.FC<LayerGroupColorPickerProps> = ({+ slug,+ color,+ onColorChange,+ extraMarginRight,+ disabled+ }) => {+ const [displayColorPicker, setDisplayColorPicker] = useState(false);++ const onColorBlockClick = useCallback(() => {+ setDisplayColorPicker(!displayColorPicker);+ }, [setDisplayColorPicker, displayColorPicker]);++ const onClosePicker = useCallback(() => {+ setDisplayColorPicker(false);+ }, [setDisplayColorPicker]);++ const onCustomPickerChange = useCallback(+ newColor => {+ onColorChange([newColor.rgb.r, newColor.rgb.g, newColor.rgb.b]);+ },+ [onColorChange]+ );++ return (+ <LayerGroupColorPickerWrapper extraMarginRight={extraMarginRight} disabled={disabled}>+ <ColorBlock+ backgroundcolor={color}+ onClick={onColorBlockClick}+ className="color-selector__selector__block"+ data-tip+ data-for={`update-color-${slug}`}+ />+ <Tooltip id={`update-color-${slug}`} effect="solid" delayShow={500}>+ <span>+ <FormattedMessage id={'Update color'} />+ </span>+ </Tooltip>+ <Portaled+ isOpened={displayColorPicker !== false}+ left={110}+ top={-50}+ onClose={onClosePicker}+ >+ <CustomPicker+ color={rgbToHex(color)}+ onChange={onCustomPickerChange}+ onSwatchClose={onClosePicker}+ />+ </Portaled>+ </LayerGroupColorPickerWrapper>+ );+ };++ return LayerGroupColorPicker;+}++export default LayerGroupColorPickerFactory;diff --git a/src/components/src/side-panel/map-style-panel/map-layer-group-item.tsx b/src/components/src/side-panel/map-style-panel/map-layer-group-item.tsxnew file mode 100644index 000000000..77b22ade7--- /dev/null+++ b/src/components/src/side-panel/map-style-panel/map-layer-group-item.tsx@@ -0,0 +1,138 @@+import React, {useCallback} from 'react';+import styled from 'styled-components';++import {FormattedMessage} from '@kepler.gl/localization';+import {camelize} from '@kepler.gl/utils';+import {RGBColor} from '@kepler.gl/types';+import {MapConfigChangeUpdaterAction} from '@kepler.gl/actions';+import {MapStyle} from '@kepler.gl/reducers';++import LayerGroupColorPickerFactory from './map-layer-group-color-picker';+import {PanelHeaderActionProps, PanelHeaderActionIcon} from '../panel-header-action';+import {PanelLabelBold, CenterFlexbox, PanelLabelWrapper} from '../../common/styled-components';++const StyledLayerGroupItem = styled.div`+ margin-bottom: 10px;+ display: flex;+ justify-content: space-between;++ &:last-child {+ margin-bottom: 0;+ }++ .layer-group__visibility-toggle {+ margin-right: 12px;+ }+`;++const LayerLabel = styled(PanelLabelBold)<{active: boolean}>`+ color: ${props => (props.active ? props.theme.textColor : props.theme.labelColor)};+`;++export type LayerGroupItemActionIcons = {+ visible: PanelHeaderActionIcon;+ hidden: PanelHeaderActionIcon;+ top: PanelHeaderActionIcon;+};++export type LayerGroupItemProps = {+ PanelHeaderAction: React.FC<PanelHeaderActionProps>;+ onChange: (pd: MapConfigChangeUpdaterAction['payload']) => void;+ slug: string;+ layers: MapStyle['visibleLayerGroups'];+ topLayers: MapStyle['topLayerGroups'];+ actionIcons: LayerGroupItemActionIcons;+ color: RGBColor | null;+ onColorChange: (pd: RGBColor) => void;+ isVisibilityToggleAvailable?: boolean;+ isMoveToTopAvailable?: boolean;+ isColorPickerAvailable?: boolean;+};++LayerGroupItemFactory.deps = [LayerGroupColorPickerFactory];++function LayerGroupItemFactory(LayerGroupColorPicker) {+ const LayerGroupItem: React.FC<LayerGroupItemProps> = ({+ PanelHeaderAction,+ onChange,+ slug,+ layers,+ topLayers,+ actionIcons,+ color,+ onColorChange,+ isVisibilityToggleAvailable = true,+ isMoveToTopAvailable = true,+ isColorPickerAvailable = false+ }) => {+ const onVisibilityToggle = useCallback(() => {+ onChange({+ visibleLayerGroups: {+ ...layers,+ [slug]: !layers[slug]+ }+ });+ }, [onChange, layers, slug]);++ const onMoveToTopToggle = useCallback(() => {+ onChange({+ topLayerGroups: {+ ...topLayers,+ [slug]: !topLayers[slug]+ }+ });+ }, [onChange, topLayers, slug]);++ return (+ <StyledLayerGroupItem className="layer-group__select">+ {isVisibilityToggleAvailable ? (+ <PanelLabelWrapper>+ <PanelHeaderAction+ className="layer-group__visibility-toggle"+ id={`${slug}-toggle`}+ tooltip={layers[slug] ? 'tooltip.hide' : 'tooltip.show'}+ onClick={onVisibilityToggle}+ IconComponent={layers[slug] ? actionIcons.visible : actionIcons.hidden}+ active={layers[slug]}+ flush+ />+ <LayerLabel active={layers[slug]}>+ <FormattedMessage id={`mapLayers.${camelize(slug)}`} />+ </LayerLabel>+ </PanelLabelWrapper>+ ) : (+ <CenterFlexbox>+ <LayerLabel style={{marginLeft: '28px'}} active={true}>+ <FormattedMessage id={`mapLayers.${camelize(slug)}`} />+ </LayerLabel>+ </CenterFlexbox>+ )}+ <CenterFlexbox className="layer-group__trailing-actions">+ {isColorPickerAvailable && color ? (+ <LayerGroupColorPicker+ slug={slug}+ color={color}+ onColorChange={onColorChange}+ extraMarginRight={isMoveToTopAvailable}+ disabled={isVisibilityToggleAvailable && !layers[slug]}+ />+ ) : null}+ {isMoveToTopAvailable ? (+ <PanelHeaderAction+ id={`${slug}-top`}+ tooltip="tooltip.moveToTop"+ disabled={!layers[slug]}+ IconComponent={actionIcons.top}+ active={topLayers[slug]}+ onClick={onMoveToTopToggle}+ />+ ) : null}+ </CenterFlexbox>+ </StyledLayerGroupItem>+ );+ };++ return LayerGroupItem;+}++export default LayerGroupItemFactory;diff --git a/src/components/src/side-panel/map-style-panel/map-layer-selector.tsx b/src/components/src/side-panel/map-style-panel/map-layer-selector.tsxindex f839f5149..38c49b0b4 100644--- a/src/components/src/side-panel/map-style-panel/map-layer-selector.tsx+++ b/src/components/src/side-panel/map-style-panel/map-layer-selector.tsx@@ -18,127 +18,110 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React, {ComponentType} from 'react';+import React from 'react';import styled from 'styled-components';import PanelHeaderActionFactory from '../panel-header-action';+import LayerGroupItemFactory, {LayerGroupItemActionIcons} from './map-layer-group-item';import {EyeSeen, EyeUnseen} from '../../common/icons';-import {- CenterFlexbox,- PanelLabel,- PanelContent,- PanelLabelBold,- PanelLabelWrapper-} from '../../common/styled-components';+import {PanelLabel, PanelContent} from '../../common/styled-components';import {FormattedMessage} from '@kepler.gl/localization';-import {camelize} from '@kepler.gl/utils';import {VisibleLayerGroups} from '@kepler.gl/types';-import {BaseProps} from '../../common/icons';import {Upload} from '@kepler.gl/cloud-providers';+import {+ THREE_D_BUILDING_LAYER_GROUP_SLUG,+ BACKGROUND_LAYER_GROUP_SLUG,+ DEFAULT_LAYER_GROUP+} from '@kepler.gl/constants';+import {+ MapConfigChangeUpdaterAction,+ Set3dBuildingColorUpdaterAction,+ SetBackgroundColorUpdaterAction+} from '@kepler.gl/actions';+import {MapStyle} from '@kepler.gl/reducers';++function noop() {}const StyledInteractionPanel = styled.div`padding-bottom: 12px;`;-const StyledLayerGroupItem = styled.div`- margin-bottom: 10px;- display: flex;- justify-content: space-between;-- &:last-child {- margin-bottom: 0;- }-- .layer-group__visibility-toggle {- margin-right: 12px;- }-`;--interface LayerLabelProps {- active: boolean;-}--const LayerLabel = styled(PanelLabelBold)<LayerLabelProps>`- color: ${props => (props.active ? props.theme.textColor : props.theme.labelColor)};-`;-export type LayerGroupSelectorProps = {layers: VisibleLayerGroups;- editableLayers: string[];- onChange: (payload: {- visibleLayerGroups?: VisibleLayerGroups;- topLayerGroups?: VisibleLayerGroups;- }) => void;- topLayers: VisibleLayerGroups;- actionIcons?: Record<string, ComponentType<Partial<BaseProps>>>;+ editableLayers: DEFAULT_LAYER_GROUP[];+ onChange: (payload: MapConfigChangeUpdaterAction['payload']) => void;+ topLayers: MapStyle['topLayerGroups'];+ threeDBuildingColor: MapStyle['threeDBuildingColor'];+ on3dBuildingColorChange: (pd: Set3dBuildingColorUpdaterAction['payload']) => void;+ backgroundColor: MapStyle['backgroundColor'];+ onBackgroundColorChange: (pd: SetBackgroundColorUpdaterAction['payload']) => void;+ actionIcons?: LayerGroupItemActionIcons;};-LayerGroupSelectorFactory.deps = [PanelHeaderActionFactory];+LayerGroupSelectorFactory.deps = [PanelHeaderActionFactory, LayerGroupItemFactory];-function LayerGroupSelectorFactory(PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>) {- const defaultActionIcons = {+function LayerGroupSelectorFactory(+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>,+ LayerGroupItem: ReturnType<typeof LayerGroupItemFactory>+) {+ const defaultActionIcons: LayerGroupItemActionIcons = {visible: EyeSeen,- hidden: EyeUnseen+ hidden: EyeUnseen,+ top: Upload};const LayerGroupSelector = ({layers,editableLayers,onChange,topLayers,+ threeDBuildingColor,+ on3dBuildingColorChange,+ backgroundColor,+ onBackgroundColorChange,actionIcons = defaultActionIcons- }: LayerGroupSelectorProps) => (- <StyledInteractionPanel className="map-style__layer-group__selector">- <div className="layer-group__header">- <PanelLabel>- <FormattedMessage id={'mapLayers.title'} />- </PanelLabel>- </div>- <PanelContent className="map-style__layer-group">- {editableLayers.map(slug => (- <StyledLayerGroupItem className="layer-group__select" key={slug}>- <PanelLabelWrapper>- <PanelHeaderAction- className="layer-group__visibility-toggle"- id={`${slug}-toggle`}- tooltip={layers[slug] ? 'tooltip.hide' : 'tooltip.show'}- onClick={() =>- onChange({- visibleLayerGroups: {- ...layers,- [slug]: !layers[slug]- }- })+ }: LayerGroupSelectorProps) => {+ return (+ <StyledInteractionPanel className="map-style__layer-group__selector">+ <div className="layer-group__header">+ <PanelLabel>+ <FormattedMessage id={'mapLayers.title'} />+ </PanelLabel>+ </div>+ <PanelContent className="map-style__layer-group">+ {editableLayers.map(+ ({slug, isVisibilityToggleAvailable, isMoveToTopAvailable, isColorPickerAvailable}) => (+ <LayerGroupItem+ key={slug}+ PanelHeaderAction={PanelHeaderAction}+ onChange={onChange}+ slug={slug}+ layers={layers}+ topLayers={topLayers}+ actionIcons={actionIcons}+ isVisibilityToggleAvailable={isVisibilityToggleAvailable}+ isMoveToTopAvailable={isMoveToTopAvailable}+ isColorPickerAvailable={isColorPickerAvailable}+ color={+ isColorPickerAvailable && slug === THREE_D_BUILDING_LAYER_GROUP_SLUG+ ? threeDBuildingColor+ : slug === BACKGROUND_LAYER_GROUP_SLUG+ ? backgroundColor+ : null}- IconComponent={layers[slug] ? actionIcons.visible : actionIcons.hidden}- active={layers[slug]}- flush- />- <LayerLabel active={layers[slug]}>- <FormattedMessage id={`mapLayers.${camelize(slug)}`} />- </LayerLabel>- </PanelLabelWrapper>- <CenterFlexbox className="layer-group__bring-top">- <PanelHeaderAction- id={`${slug}-top`}- tooltip="tooltip.moveToTop"- disabled={!layers[slug]}- IconComponent={Upload}- active={topLayers[slug]}- onClick={() =>- onChange({- topLayerGroups: {- ...topLayers,- [slug]: !topLayers[slug]- }- })+ onColorChange={+ isColorPickerAvailable && slug === THREE_D_BUILDING_LAYER_GROUP_SLUG+ ? on3dBuildingColorChange+ : slug === BACKGROUND_LAYER_GROUP_SLUG+ ? onBackgroundColorChange+ : noop}/>- </CenterFlexbox>- </StyledLayerGroupItem>- ))}- </PanelContent>- </StyledInteractionPanel>- );+ )+ )}+ </PanelContent>+ </StyledInteractionPanel>+ );+ };return LayerGroupSelector;}diff --git a/src/components/src/side-panel/panel-header-action.tsx b/src/components/src/side-panel/panel-header-action.tsxindex b5bd5427a..b4742d6ac 100644--- a/src/components/src/side-panel/panel-header-action.tsx+++ b/src/components/src/side-panel/panel-header-action.tsx@@ -26,7 +26,9 @@ import {FormattedMessage} from '@kepler.gl/localization';import {Tooltip} from '../common/styled-components';import {BaseProps} from '../common/icons';-interface PanelHeaderActionProps {+export type PanelHeaderActionIcon = ComponentType<Partial<BaseProps>>;++export interface PanelHeaderActionProps {id?: string;tooltip?: string;hoverColor?: string;@@ -36,7 +38,7 @@ interface PanelHeaderActionProps {disabled?: boolean;onClick?: MouseEventHandler;tooltipType?: TooltipProps['type'];- IconComponent: ComponentType<Partial<BaseProps>>;+ IconComponent: PanelHeaderActionIcon;}type HeaderActionWrapperProps = {diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex fca1bc7c2..07ed64857 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -187,47 +187,91 @@ export const PANELS = SIDEBAR_PANELS;// MAP STYLES-type DEFAULT_LAYER_GROUP = {+export const DEFAULT_BLDG_COLOR = '#D1CEC7';++export const DEFAULT_BACKGROUND_COLOR = '#FFFFFF';++// assists in identifying basemap background layers when auto-determining the backgroundColor+export const BASE_MAP_BACKGROUND_LAYER_IDS = ['background', 'bg', 'land', 'water'];++export const BACKGROUND_LAYER_GROUP_SLUG = 'Background';++export const THREE_D_BUILDING_LAYER_GROUP_SLUG = '3d building';++export type DEFAULT_LAYER_GROUP = {slug: string;filter: (value) => boolean;defaultVisibility: boolean;+ isVisibilityToggleAvailable?: boolean;+ isMoveToTopAvailable?: boolean;+ isColorPickerAvailable?: boolean;+};++export const BACKGROUND_LAYER_GROUP: DEFAULT_LAYER_GROUP = {+ slug: BACKGROUND_LAYER_GROUP_SLUG,+ filter: () => false,+ defaultVisibility: false,+ isVisibilityToggleAvailable: false,+ isMoveToTopAvailable: false,+ isColorPickerAvailable: true};export const DEFAULT_LAYER_GROUPS: DEFAULT_LAYER_GROUP[] = [{slug: 'label',filter: ({id}) => id.match(/(?=(label|place-|poi-))/),- defaultVisibility: true+ defaultVisibility: true,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{slug: 'road',filter: ({id}) => id.match(/(?=(road|railway|tunnel|street|bridge))(?!.*label)/),- defaultVisibility: true+ defaultVisibility: true,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{slug: 'border',filter: ({id}) => id.match(/border|boundaries|boundary/),- defaultVisibility: false+ defaultVisibility: false,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{slug: 'building',filter: ({id}) => id.match(/building/),- defaultVisibility: true+ defaultVisibility: true,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{slug: 'water',filter: ({id}) => id.match(/(?=(water|stream|ferry))/),- defaultVisibility: true+ defaultVisibility: true,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{slug: 'land',filter: ({id}) => id.match(/(?=(parks|landcover|industrial|sand|hillshade))/),- defaultVisibility: true+ defaultVisibility: true,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: false},{- slug: '3d building',+ slug: THREE_D_BUILDING_LAYER_GROUP_SLUG,filter: () => false,- defaultVisibility: false+ defaultVisibility: false,+ isVisibilityToggleAvailable: true,+ isMoveToTopAvailable: true,+ isColorPickerAvailable: true}];@@ -237,7 +281,26 @@ export const BASE_MAP_COLOR_MODES = keyMirror({LIGHT: null});+export const NO_MAP_ID = 'no_map';++// Fallback style to use when styles are being fetched, or when+// a style fails to fetch+export const EMPTY_MAPBOX_STYLE = {+ version: 8,+ sources: {},+ layers: []+};+export const DEFAULT_MAP_STYLES = [+ {+ id: NO_MAP_ID,+ label: 'No Basemap',+ url: null,+ icon: 'https://storage.googleapis.com/unfolded_public/statics/keplergl/geodude/NO_BASEMAP.png',+ layerGroups: [BACKGROUND_LAYER_GROUP],+ colorMode: BASE_MAP_COLOR_MODES.NONE,+ style: EMPTY_MAPBOX_STYLE+ },{id: 'dark',label: 'Dark',diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex 2fa077d1c..b985cbfa2 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -61,7 +61,8 @@ export default {building: 'Edifici',water: 'Aigua',land: 'Terra',- '3dBuilding': 'Edifici 3D'+ '3dBuilding': 'Edifici 3D',+ background: 'Fons'},panel: {text: {@@ -173,7 +174,8 @@ export default {mapManager: {mapStyle: 'Estil de mapa',addMapStyle: 'Afegeix estils de mapa',- '3dBuildingColor': 'Color edifici 3D'+ '3dBuildingColor': 'Color edifici 3D',+ backgroundColor: 'Color de fons'},layerConfiguration: {defaultDescription: 'Calcula {property} segons el camp seleccionat',diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 802643b3d..fa3ccf49f 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -62,7 +62,8 @@ export default {building: 'Building',water: 'Water',land: 'Land',- '3dBuilding': '3d Building'+ '3dBuilding': '3d Building',+ background: 'Background'},panel: {text: {@@ -179,7 +180,8 @@ export default {mapManager: {mapStyle: 'Map style',addMapStyle: 'Add Map Style',- '3dBuildingColor': '3D Building Color'+ '3dBuildingColor': '3D Building Color',+ backgroundColor: 'Background Color'},layerConfiguration: {defaultDescription: 'Calculate {property} based on selected field',diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex 001cae921..bc00ae95b 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -61,7 +61,8 @@ export default {building: 'Edificio',water: 'Agua',land: 'Tierra',- '3dBuilding': 'Edificio 3D'+ '3dBuilding': 'Edificio 3D',+ background: 'Fondo'},panel: {text: {@@ -174,7 +175,8 @@ export default {mapManager: {mapStyle: 'Estilo de mapa',addMapStyle: 'Añadir estilo de mapa',- '3dBuildingColor': 'Color edificios 3D'+ '3dBuildingColor': 'Color edificios 3D',+ backgroundColor: 'Color de fondo'},layerConfiguration: {defaultDescription: 'Calcular {property} según el campo seleccionado',diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex 6548333a9..459d0c9fe 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -60,7 +60,8 @@ export default {building: 'Rakennukset',water: 'Vesi',land: 'Maa',- '3dBuilding': '3d-rakennukset'+ '3dBuilding': '3d-rakennukset',+ background: 'Tausta'},panel: {text: {@@ -171,7 +172,8 @@ export default {mapManager: {mapStyle: 'Kartan tyyli',addMapStyle: 'Lisää tyyli kartalle',- '3dBuildingColor': '3D-rakennusten väri'+ '3dBuildingColor': '3D-rakennusten väri',+ backgroundColor: 'Taustaväri'},layerConfiguration: {defaultDescription: 'Laske suureen {property} arvo valitun kentän perusteella',diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex db6033694..077bf88c0 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -61,7 +61,8 @@ export default {building: '建物',water: '水',land: '地面',- '3dBuilding': '3D建物'+ '3dBuilding': '3D建物',+ background: '背景'},panel: {text: {@@ -170,7 +171,8 @@ export default {mapManager: {mapStyle: 'マップスタイル',addMapStyle: 'マップスタイル追加',- '3dBuildingColor': '3D建物の色'+ '3dBuildingColor': '3D建物の色',+ backgroundColor: '背景色'},layerConfiguration: {defaultDescription: '選択されたフィールドに基づいて{property}を計算します',diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex be345964e..12a5b7750 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -60,7 +60,8 @@ export default {building: 'Edifícios',water: 'Água',land: 'Terra',- '3dBuilding': 'Edifícios em 3d'+ '3dBuilding': 'Edifícios em 3d',+ background: 'Fundo'},panel: {text: {@@ -172,7 +173,8 @@ export default {mapManager: {mapStyle: 'Estilo do Mapa',addMapStyle: 'Adicionar Estilo de Mapa',- '3dBuildingColor': 'Cor do Edifício 3D'+ '3dBuildingColor': 'Cor do Edifício 3D',+ backgroundColor: 'Cor de Fundo'},layerConfiguration: {defaultDescription: 'Calcular {property} baseada no campo selecionado',diff --git a/src/reducers/package.json b/src/reducers/package.jsonindex 4e7910f8f..0842e9a7a 100644--- a/src/reducers/package.json+++ b/src/reducers/package.json@@ -53,6 +53,7 @@"copy-to-clipboard": "^3.3.1","d3-color": "^2.0.0","d3-dsv": "^2.0.0",+ "deepmerge": "^4.2.2","global": "^4.3.0","lodash.clonedeep": "^4.0.1","lodash.flattendeep": "^4.2.0",diff --git a/src/reducers/src/combined-updaters.ts b/src/reducers/src/combined-updaters.tsindex 91d82602c..c136505e5 100644--- a/src/reducers/src/combined-updaters.ts+++ b/src/reducers/src/combined-updaters.ts@@ -281,7 +281,7 @@ export const combinedMapStyleChangeUpdater = (const {mapStyle} = state;const getColorMode = key => mapStyle.mapStyles[key]?.colorMode;const prevColorMode = getColorMode(mapStyle.styleType);- const nextColorMode = getColorMode(payload);+ const nextColorMode = getColorMode(payload.styleType);let {visState} = state;if (nextColorMode !== prevColorMode) {switch (nextColorMode) {@@ -304,7 +304,7 @@ export const combinedMapStyleChangeUpdater = (return {...state,visState,- mapStyle: mapStyleChangeUpdater(mapStyle, {payload})+ mapStyle: mapStyleChangeUpdater(mapStyle, {payload: {styleType: payload.styleType}})};};diff --git a/src/reducers/src/map-state-updaters.ts b/src/reducers/src/map-state-updaters.tsindex b6dd498b9..4298ccf34 100644--- a/src/reducers/src/map-state-updaters.ts+++ b/src/reducers/src/map-state-updaters.ts@@ -22,6 +22,7 @@ import geoViewport from '@mapbox/geo-viewport';import booleanWithin from '@turf/boolean-within';import bboxPolygon from '@turf/bbox-polygon';import {fitBounds} from '@math.gl/web-mercator';+import deepmerge from 'deepmerge';import {getCenterAndZoomFromBounds, validateBounds, MAPBOX_TILE_SIZE} from '@kepler.gl/utils';import {MapStateActions, ReceiveMapConfigPayload, ActionTypes} from '@kepler.gl/actions';@@ -199,10 +200,19 @@ export const receiveMapConfigUpdater = (payload: ReceiveMapConfigPayload;}): MapState => {- const {mapState} = config || {};+ /**+ * @type {Partial<MapState>}+ */+ const mapState = (config || {}).mapState || {};+ // merged received mapState with previous state+ // state also may include properties that are new to an existing, saved project's mapState- // merged received mapstate with previous state- let mergedState = {...state, ...mapState};+ let mergedState = deepmerge<MapState>(state, mapState, {+ // note: deepmerge by default will merge arrays by concatenating them+ // but we need to overwrite destination arrays with source arrays, if present+ // https://github.com/TehShrike/deepmerge#arraymerge-example-overwrite-target-array+ arrayMerge: (_destinationArray, sourceArray) => sourceArray+ });// if center map// center map will override mapState configdiff --git a/src/reducers/src/map-style-updaters.ts b/src/reducers/src/map-style-updaters.tsindex 14c0ace77..9ce466e96 100644--- a/src/reducers/src/map-style-updaters.ts+++ b/src/reducers/src/map-style-updaters.ts@@ -33,17 +33,29 @@ import {getStyleImageIcon,generateHashId,isPlainObject,- hexToRgb+ hexToRgb,+ colorMaybeToRGB} from '@kepler.gl/utils';import {DEFAULT_MAP_STYLES,DEFAULT_LAYER_GROUPS,- DEFAULT_MAPBOX_API_URL+ DEFAULT_MAPBOX_API_URL,+ NO_MAP_ID,+ DEFAULT_BLDG_COLOR,+ DEFAULT_BACKGROUND_COLOR,+ BASE_MAP_BACKGROUND_LAYER_IDS} from '@kepler.gl/constants';-import {LOAD_MAP_STYLE_TASK} from '@kepler.gl/tasks';+import {ACTION_TASK, LOAD_MAP_STYLE_TASK} from '@kepler.gl/tasks';import {rgb} from 'd3-color';-import {RGBColor, LayerGroup, MapStyles, InputStyle, VisibleLayerGroups} from '@kepler.gl/types';+import {+ RGBColor,+ LayerGroup,+ BaseMapStyle,+ MapStyles,+ InputStyle,+ VisibleLayerGroups+} from '@kepler.gl/types';import {ActionTypes,ReceiveMapConfigPayload,@@ -66,6 +78,7 @@ export type MapStyle = {mapStylesReplaceDefault: boolean;inputStyle: InputStyle;threeDBuildingColor: RGBColor;+ backgroundColor: RGBColor;custom3DBuildingColor: boolean;bottomMapStyle: any;topMapStyle: any;@@ -75,8 +88,6 @@ export type MapStyle = {};};-const DEFAULT_BLDG_COLOR = '#D1CEC7';-const getDefaultState = (): MapStyle => {const visibleLayerGroups = {};const styleType = 'dark';@@ -100,6 +111,7 @@ const getDefaultState = (): MapStyle => {inputStyle: getInitialInputStyle(),threeDBuildingColor: hexToRgb(DEFAULT_BLDG_COLOR),custom3DBuildingColor: false,+ backgroundColor: hexToRgb(DEFAULT_BACKGROUND_COLOR),isLoading: {},bottomMapStyle: undefined,topMapStyle: undefined@@ -159,6 +171,7 @@ const mapStyleUpdaters = null;* @Property mapStylesReplaceDefault - Default: `false`* @property inputStyle - Default: `{}`* @property threeDBuildingColor - Default: `[r, g, b]`+ * @property backgroundColor - Default: `[r, g, b]`* @public*/export const INITIAL_MAP_STYLE: MapStyle = getDefaultState();@@ -251,6 +264,56 @@ function get3DBuildingColor(style): RGBColor {return [rgbObj.r, rgbObj.g, rgbObj.b];}+function getBackgroundColorFromStyleBaseLayer(+ style: BaseMapStyle,+ backupBackgroundColor: RGBColor+): RGBColor {+ if (!style.style) {+ return colorMaybeToRGB(backupBackgroundColor) || backupBackgroundColor;+ }++ // @ts-expect-error style.style not typed+ const baseLayer = (style.style.layers || []).find(({id}) =>+ BASE_MAP_BACKGROUND_LAYER_IDS.includes(id)+ );++ const backgroundColorOfBaseLayer = findLayerFillColor(baseLayer);++ // need to be careful because some basemap layer.paint['background-color'] values may be an interpolate array expression instead of a color string+ // and that results in colorMaybeToRGB(backgroundColorOfBaseLayer) returning null+ // https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#paint-background-background-color+ // https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#interpolate+ const newBackgroundColor =+ typeof backgroundColorOfBaseLayer === 'string'+ ? backgroundColorOfBaseLayer+ : backupBackgroundColor;++ const newBackgroundColorAsRGBArray = colorMaybeToRGB(newBackgroundColor)+ // if newBackgroundColor was in string HSL format it can introduce RGB numbers with decimals,+ // which may render the background-color CSS of the <StyledMap> container incorrectly when using our own color utils `rgbToHex()`+ // so we attempt to round to nearest integer here+ ?.map(channelNumber => Math.round(channelNumber)) as RGBColor | null;++ return newBackgroundColorAsRGBArray || backupBackgroundColor;+}++// determine new backgroundColor from either previous state basemap style, previous state backgroundColor, or the DEFAULT_BACKGROUND_COLOR+function getBackgroundColor(previousState: MapStyle, styleType: string) {+ const previousStateMapStyle = previousState.mapStyles[previousState.styleType];+ const backupBackgroundColor = previousState.backgroundColor || DEFAULT_BACKGROUND_COLOR;+ const backgroundColor =+ styleType === NO_MAP_ID+ ? // if the style has switched to the "no basemap" style,+ // attempt to detect backgroundColor of the previous basemap if it was a mapbox basemap+ // and set it as the "no basemap" backgroundColor+ getBackgroundColorFromStyleBaseLayer(previousStateMapStyle, backupBackgroundColor)+ : // otherwise leave it alone and rely on the previous state's preexisting backgroundColor+ // or DEFAULT_BACKGROUND_COLOR as a last resort+ backupBackgroundColor;++ return backgroundColor;+}+function getLayerGroupsFromStyle(style) {return Array.isArray(style?.layers)? DEFAULT_LAYER_GROUPS.filter(lg => style.layers.filter(lg.filter).length)@@ -265,7 +328,7 @@ function getLayerGroupsFromStyle(style) {*/export const requestMapStylesUpdater = (state: MapStyle,- {payload: mapStyles}: MapStyleActions.RequestMapStylesUpdaterAction+ {payload: {mapStyles, onSuccess}}: MapStyleActions.RequestMapStylesUpdaterAction): MapStyle => {const toLoad = Object.keys(mapStyles).reduce((accu, id) => ({@@ -277,7 +340,8 @@ export const requestMapStylesUpdater = (const loadMapStyleTasks = getLoadMapStyleTasks(toLoad,state.mapboxApiAccessToken,- state.mapboxApiUrl+ state.mapboxApiUrl,+ onSuccess);const isLoading = Object.keys(toLoad).reduce(@@ -348,7 +412,7 @@ const hasStyleObject = style => isPlainObject(style?.style);*/export const mapStyleChangeUpdater = (state: MapStyle,- {payload: styleType}: MapStyleActions.MapStyleChangeUpdaterAction+ {payload: {styleType, onSuccess}}: MapStyleActions.MapStyleChangeUpdaterAction): MapStyle => {if (!state.mapStyles[styleType]) {// we might not have received the style yet@@ -364,7 +428,10 @@ export const mapStyleChangeUpdater = (},{payload: {- [styleType]: state.mapStyles[styleType]+ mapStyles: {+ [styleType]: state.mapStyles[styleType]+ },+ onSuccess}});@@ -381,11 +448,15 @@ export const mapStyleChangeUpdater = (? state.threeDBuildingColor: get3DBuildingColor(state.mapStyles[styleType]);+ // determine new backgroundColor from either previous state basemap style, previous state backgroundColor, or the DEFAULT_BACKGROUND_COLOR+ const backgroundColor = getBackgroundColor(state, styleType);+return {...state,styleType,visibleLayerGroups,threeDBuildingColor,+ backgroundColor,...getMapStyles({...state,visibleLayerGroups,@@ -403,7 +474,7 @@ export const loadMapStylesUpdater = (state: MapStyle,action: MapStyleActions.LoadMapStylesUpdaterAction): MapStyle => {- const newStyles = action.payload || {};+ const {newStyles, onSuccess} = action.payload || {};const addLayerGroups = Object.keys(newStyles).reduce((accu, id) => ({@@ -435,11 +506,23 @@ export const loadMapStylesUpdater = (}};- return newStyles[state.styleType]- ? mapStyleChangeUpdater(newState, {payload: state.styleType})+ const tasks = createActionTask(onSuccess, {styleType: state.styleType});++ const nextState = newStyles[state.styleType]+ ? mapStyleChangeUpdater(newState, {payload: {styleType: state.styleType}}): newState;++ return tasks ? withTask(nextState, tasks) : nextState;};+function createActionTask(action, payload) {+ if (typeof action === 'function') {+ return ACTION_TASK().map(_ => action(payload));+ }++ return null;+}+/*** Callback when load map style error* @memberof mapStyleUpdaters@@ -509,10 +592,10 @@ export const receiveMapConfigUpdater = (Boolean(mapStyle.threeDBuildingColor) || merged.custom3DBuildingColor;const newState = mapConfigChangeUpdater(state, {payload: merged});- return mapStyleChangeUpdater(newState, {payload: newState.styleType});+ return mapStyleChangeUpdater(newState, {payload: {styleType: newState.styleType}});};-function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl) {+function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl, onSuccess) {return [Task.all(Object.values(mapStyles)@@ -537,7 +620,8 @@ function getLoadMapStyleTasks(mapStyles, mapboxApiAccessToken, mapboxApiUrl) {}}),{}- )+ ),+ onSuccess),// errorerr => loadMapStyleErr(Object.keys(mapStyles), err)@@ -562,7 +646,7 @@ export const resetMapConfigMapStyleUpdater = (state: MapStyle): MapStyle => {initialState: state.initialState};- return mapStyleChangeUpdater(emptyConfig, {payload: emptyConfig.styleType});+ return mapStyleChangeUpdater(emptyConfig, {payload: {styleType: emptyConfig.styleType}});};/**@@ -649,7 +733,7 @@ export const addCustomMapStyleUpdater = (state: MapStyle): MapStyle => {inputStyle: getInitialInputStyle()};// set new style- return mapStyleChangeUpdater(newState, {payload: styleId});+ return mapStyleChangeUpdater(newState, {payload: {styleType: styleId}});};/**@@ -665,6 +749,18 @@ export const set3dBuildingColorUpdater = (custom3DBuildingColor: true});+/**+ * Updates background color+ * @memberof mapStyleUpdaters+ */+export const setBackgroundColorUpdater = (+ state: MapStyle,+ {payload: color}: MapStyleActions.SetBackgroundColorUpdaterAction+): MapStyle => ({+ ...state,+ backgroundColor: color+});+/*** Return the initial input style* @return Objectdiff --git a/src/reducers/src/map-style.ts b/src/reducers/src/map-style.tsindex 668ff5cc3..7ce703f1f 100644--- a/src/reducers/src/map-style.ts+++ b/src/reducers/src/map-style.ts@@ -39,6 +39,7 @@ const actionHandler = {[ActionTypes.ADD_CUSTOM_MAP_STYLE]: mapStyleUpdaters.addCustomMapStyleUpdater,[ActionTypes.RESET_MAP_CONFIG]: mapStyleUpdaters.resetMapConfigMapStyleUpdater,[ActionTypes.SET_3D_BUILDING_COLOR]: mapStyleUpdaters.set3dBuildingColorUpdater,+ [ActionTypes.SET_BACKGROUND_COLOR]: mapStyleUpdaters.setBackgroundColorUpdater,[ActionTypes.RESET_MAP_CONFIG]: mapStyleUpdaters.resetMapConfigMapStyleUpdater};diff --git a/src/schemas/src/index.ts b/src/schemas/src/index.tsindex 00cb1c9ab..2212a523a 100644--- a/src/schemas/src/index.ts+++ b/src/schemas/src/index.ts@@ -31,7 +31,8 @@ export type {ParsedConfig,SavedConfigV1,SavedMap,- LoadedMap+ LoadedMap,+ SavedMapState} from './schema-manager';export {CURRENT_VERSION, VERSIONS} from './versions';export {diff --git a/src/schemas/src/map-style-schema.ts b/src/schemas/src/map-style-schema.tsindex 8d343e57c..9922edbe3 100644--- a/src/schemas/src/map-style-schema.ts+++ b/src/schemas/src/map-style-schema.ts@@ -76,6 +76,7 @@ export const propertiesV1 = {topLayerGroups: null,visibleLayerGroups: null,threeDBuildingColor: null,+ backgroundColor: null,mapStyles: new MapStyleSchemaV1()};diff --git a/src/utils/src/color-utils.ts b/src/utils/src/color-utils.tsindex 30001f88e..11bda2c45 100644--- a/src/utils/src/color-utils.ts+++ b/src/utils/src/color-utils.ts@@ -18,6 +18,7 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.+import {rgb as d3Rgb} from 'd3-color';import {ColorRange} from '@kepler.gl/constants';import {HexColor, RGBColor} from '@kepler.gl/types';@@ -108,6 +109,24 @@ export function createLinearGradient(direction: string, colors: RGBColor[]) {return `linear-gradient(to ${direction}, ${bands.join(',')})`;}+/**+ * Convert color to RGB+ */+export function colorMaybeToRGB(color: unknown): RGBColor | null {+ if (isRgbColor(color)) {+ return color as RGBColor;+ }++ if (typeof color === 'string') {+ const rgbObj = d3Rgb(color);+ if (Number.isFinite(rgbObj?.r) && Number.isFinite(rgbObj?.g) && Number.isFinite(rgbObj?.b)) {+ return [rgbObj.r, rgbObj.g, rgbObj.b];+ }+ }++ return null;+}+/*** Whether color is rgb* @returnsdiff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 3270ecbd6..41a3cbbb5 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -27,6 +27,7 @@ export {getColorGroupByName,reverseColorRange,createLinearGradient,+ colorMaybeToRGB,isRgbColor} from './color-utils';export {errorNotification} from './notifications-utils';@@ -116,8 +117,7 @@ export {getStyleDownloadUrl,getStyleImageIcon,scaleMapStyleByResolution,- mergeLayerGroupVisibility,- EMPTY_MAPBOX_STYLE+ mergeLayerGroupVisibility} from './map-style-utils/mapbox-gl-style-editor';export {isValidMapInfo} from './map-info-utils';export {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.tsindex b4d491ef5..33459c088 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@@ -20,20 +20,17 @@import memoize from 'lodash.memoize';import clondDeep from 'lodash.clonedeep';-import {DEFAULT_LAYER_GROUPS, DEFAULT_MAPBOX_API_URL} from '@kepler.gl/constants';+import {+ DEFAULT_LAYER_GROUPS,+ DEFAULT_MAPBOX_API_URL,+ NO_MAP_ID,+ EMPTY_MAPBOX_STYLE+} from '@kepler.gl/constants';import {BaseMapStyle, LayerGroup, MapState} from '@kepler.gl/types';const mapUrlRg = /^mapbox:\/\/styles\/[-a-z0-9]{2,256}\/[-a-z0-9]{2,256}/;const httpRg = /^(?=(http:|https:))/;-// Fallback style to use when styles are being fetched, or when-// a style fails to fetch-export const EMPTY_MAPBOX_STYLE = {- version: 8,- sources: {},- layers: []-};-export function getDefaultLayerGroupVisibility({layerGroups = []}: {layerGroups: LayerGroup[]}) {return layerGroups.reduce((accu, layer) => ({@@ -102,6 +99,10 @@ export const editTopMapStyle = memoize(* @returns {Object} bottom map style*/export const editBottomMapStyle = memoize(({id, mapStyle, visibleLayerGroups}) => {+ if (id === NO_MAP_ID) {+ return EMPTY_MAPBOX_STYLE;+ }+const invisibleFilters = (mapStyle.layerGroups || []).filter(lg => !visibleLayerGroups[lg.slug]).map(lg => lg.filter);diff --git a/test/browser/components/kepler-gl-test.js b/test/browser/components/kepler-gl-test.jsindex ae1055bf6..d70ac0f37 100644--- a/test/browser/components/kepler-gl-test.js+++ b/test/browser/components/kepler-gl-test.js@@ -250,7 +250,10 @@ test('Components -> KeplerGl -> Mount -> Load default map style task', t => {const expectedActions = [{type: ActionTypes.LOAD_MAP_STYLES,- payload: DEFAULT_MAP_STYLES.reduce((accu, curr) => ({...accu, [curr.id]: curr}), {})+ payload: {+ newStyles: DEFAULT_MAP_STYLES.reduce((accu, curr) => ({...accu, [curr.id]: curr}), {}),+ onSuccess: undefined+ }}];t.deepEqual(@@ -285,7 +288,7 @@ test('Components -> KeplerGl -> Mount -> Load default map style task', t => {const expectedStateMapStyles = {...tmpState.mapStyle.mapStyles,dark: {- ...DEFAULT_MAP_STYLES[0],+ ...DEFAULT_MAP_STYLES[1],style: {layers: [], name: 'dark'}}};@@ -370,10 +373,13 @@ test('Components -> KeplerGl -> Mount -> Load custom map style task', t => {{type: ActionTypes.LOAD_MAP_STYLES,payload: {- ...initialCoreState1.mapStyle.mapStyles,- milkshake: customStyle2,- chai: customStyle3,- smoothie: customStyle1+ newStyles: {+ ...initialCoreState1.mapStyle.mapStyles,+ milkshake: customStyle2,+ chai: customStyle3,+ smoothie: customStyle1+ },+ onSuccess: undefined}}];diff --git a/test/node/reducers/map-style-test.js b/test/node/reducers/map-style-test.jsindex f17c19cb9..be15599f2 100644--- a/test/node/reducers/map-style-test.js+++ b/test/node/reducers/map-style-test.js@@ -35,7 +35,7 @@ import {mapStyleChange} from '@kepler.gl/actions';import SchemaManager from '@kepler.gl/schemas';-import {DEFAULT_MAP_STYLES, DEFAULT_MAPBOX_API_URL} from '@kepler.gl/constants';+import {DEFAULT_MAP_STYLES, DEFAULT_MAPBOX_API_URL, NO_MAP_ID} from '@kepler.gl/constants';// helpersimport {StateWCustomMapStyle} from 'test/helpers/mock-state';@@ -109,7 +109,9 @@ test('#mapStyleReducer -> INIT & LOAD_MAP_STYLES', t => {'initialize map style with mapboxApiAccessToken and mapStylesReplaceDefault; mapStyles empty');- const finalState = loadMapStylesUpdater(newState, {payload: INITIAL_MAP_STYLE.mapStyles});+ const finalState = loadMapStylesUpdater(newState, {+ payload: {newStyles: INITIAL_MAP_STYLE.mapStyles}+ });// should start loading default dark stylet.deepEqual(@@ -173,7 +175,7 @@ test('#mapStyleReducer -> INIT & LOAD_MAP_STYLES -> mapStylesReplaceDefault: tr[myMapStyle.id]: myMapStyle};- const finalState = loadMapStylesUpdater(newState, {payload: mapStyles});+ const finalState = loadMapStylesUpdater(newState, {payload: {newStyles: mapStyles}});t.deepEqual(finalState,@@ -236,6 +238,7 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {inputStyle: getInitialInputStyle(),threeDBuildingColor: [1, 2, 3],custom3DBuildingColor: true,+ backgroundColor: [255, 255, 255],bottomMapStyle: undefined,topMapStyle: undefined,initialState: {}@@ -298,6 +301,7 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {inputStyle: getInitialInputStyle(),threeDBuildingColor: [1, 2, 3],custom3DBuildingColor: true,+ backgroundColor: [255, 255, 255],initialState: {},bottomMapStyle: {layers: [], name: 'smoothie_the_cat'},topMapStyle: null,@@ -330,6 +334,7 @@ test('#mapStyleReducer -> RECEIVE_MAP_CONFIG', t => {topLayerGroups: {},visibleLayerGroups: {},threeDBuildingColor: [1, 2, 3],+ backgroundColor: [255, 255, 255],mapStyles: {smoothie_the_cat: {accessToken: 'secret_token',@@ -502,3 +507,44 @@ test('#mapStyleReducer -> MAP_STYLE_CHANGE', t => {t.end();});++test('#mapStyleReducer -> MAP_STYLE_CHANGE -> dark basemap to no basemap', t => {+ const initialState = reducer(+ InitialMapStyle,+ keplerGlInit({+ mapboxApiAccessToken: 'smoothies_secret_token'+ })+ );++ // loadMapStyles+ const nextState = reducer(initialState, loadMapStyles({dark: MOCK_MAP_STYLE}));++ t.deepEqual(+ initialState.backgroundColor,+ nextState.backgroundColor,+ 'backgroundColor should remain the same when NOT switching to the no basemap option'+ );++ // set style type to no basemap+ const nextState2 = reducer(nextState, mapStyleChange(NO_MAP_ID));++ const expectedNextState2 = {+ ...nextState2,+ styleType: NO_MAP_ID+ };++ t.deepEqual(+ nextState2,+ expectedNextState2,+ 'state should be correct when switching to no basemap option'+ );++ t.notDeepEqual(+ nextState.backgroundColor,+ nextState2.backgroundColor,+ 'backgroundColor should be changed when switching to no basemap option (map-style-updates.js: getBackgroundColorFromStyleBaseLayer())'+ );++ t.end();+});+diff --git a/test/node/schemas/map-style-schema-test.js b/test/node/schemas/map-style-schema-test.jsindex e5afe025e..d12ac9c88 100644--- a/test/node/schemas/map-style-schema-test.js+++ b/test/node/schemas/map-style-schema-test.js@@ -33,8 +33,15 @@ test('#mapStyleSchema -> v1 -> save load mapStyle', t => {t.deepEqual(Object.keys(msToSave),- ['styleType', 'topLayerGroups', 'visibleLayerGroups', 'threeDBuildingColor', 'mapStyles'],- 'mapStyle should have all 4 entries'+ [+ 'styleType',+ 'topLayerGroups',+ 'visibleLayerGroups',+ 'threeDBuildingColor',+ 'backgroundColor',+ 'mapStyles'+ ],+ 'mapStyle should have all 6 entries');const expectedSaved = {@@ -42,14 +49,16 @@ test('#mapStyleSchema -> v1 -> save load mapStyle', t => {topLayerGroups: {},visibleLayerGroups: {},mapStyles: {},- threeDBuildingColor: [209, 206, 199]+ threeDBuildingColor: [209, 206, 199],+ backgroundColor: [255, 255, 255]};const expectedLoaded = {styleType: 'dark',topLayerGroups: {},visibleLayerGroups: {},- threeDBuildingColor: [209, 206, 199]+ threeDBuildingColor: [209, 206, 199],+ backgroundColor: [255, 255, 255]};t.deepEqual(msToSave, expectedSaved, 'saved mapStyle should be current');@@ -73,6 +82,7 @@ test('#mapStyleSchema -> v1 -> save load mapStyle with custom style', t => {road: true},threeDBuildingColor: [1, 2, 3],+ backgroundColor: [255, 255, 255],mapStyles: {smoothie_the_cat: {id: 'smoothie_the_cat',