Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[Feat] Unlocked split map viewports (#2170)
Igor Dykhta9fc98e86e1be
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 5f87435f0..c7c54e5b0 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -120,8 +120,9 @@ export const ActionTypes = {UPDATE_MAP: `${ACTION_PREFIX}UPDATE_MAP`,FIT_BOUNDS: `${ACTION_PREFIX}FIT_BOUNDS`,TOGGLE_PERSPECTIVE: `${ACTION_PREFIX}TOGGLE_PERSPECTIVE`,- TOGGLE_SPLIT_MAP: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP`,TOGGLE_FULLSCREEN: `${ACTION_PREFIX}TOGGLE_FULLSCREEN`,+ TOGGLE_SPLIT_MAP: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP`,+ TOGGLE_SPLIT_MAP_VIEWPORT: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP_VIEWPORT`,// mapStyleMAP_CONFIG_CHANGE: `${ACTION_PREFIX}MAP_CONFIG_CHANGE`,diff --git a/src/actions/src/map-state-actions.ts b/src/actions/src/map-state-actions.tsindex 819908587..7fd134261 100644--- a/src/actions/src/map-state-actions.ts+++ b/src/actions/src/map-state-actions.ts@@ -54,7 +54,7 @@ export const fitBounds: ({type: typeof ActionTypes.FIT_BOUNDS}> = createAction(ActionTypes.FIT_BOUNDS, (bounds: Bounds) => ({payload: bounds}));-export type UpdateMapUpdaterAction = {payload: Viewport};+export type UpdateMapUpdaterAction = {payload: {viewport: Viewport; mapIndex?: number}};/*** Update map viewport* @memberof mapStateActions@@ -67,18 +67,25 @@ export type UpdateMapUpdaterAction = {payload: Viewport};* @param {Number} [viewport.latitude] Latitude center of viewport on map in mercator projection* @param {Number} [viewport.longitude] Longitude Center of viewport on map in mercator projection* @param {boolean} [viewport.dragRotate] Whether to enable drag and rotate map into perspective viewport+ * @param {number} mapIndex Index of which map to update the viewport of* @public* @example* import {updateMap} from 'kepler.gl/actions';- * this.props.dispatch(updateMap({latitude: 37.75043, longitude: -122.34679, width: 800, height: 1200}));+ * this.props.dispatch(updateMap({latitude: 37.75043, longitude: -122.34679, width: 800, height: 1200}, 0));*/export const updateMap: (- payload: Viewport-) => Merge<- UpdateMapUpdaterAction,- {type: typeof ActionTypes.UPDATE_MAP}-> = createAction(ActionTypes.UPDATE_MAP, (viewport: Viewport) => ({payload: viewport}));+ viewport: Viewport,+ mapIndex?: number+) => Merge<UpdateMapUpdaterAction, {type: typeof ActionTypes.UPDATE_MAP}> = createAction(+ ActionTypes.UPDATE_MAP,+ (viewport: Viewport, mapIndex?: number) => ({+ payload: {+ viewport,+ mapIndex+ }+ })+);export type ToggleSplitMapUpdaterAction = {payload: number;@@ -99,6 +106,31 @@ export const toggleSplitMap: ({type: typeof ActionTypes.TOGGLE_SPLIT_MAP}> = createAction(ActionTypes.TOGGLE_SPLIT_MAP, (index: number) => ({payload: index}));+export type ToggleSplitMapViewportUpdaterAction = {+ payload: {+ isViewportSynced?: boolean;+ isZoomLocked?: boolean;+ };+};++/**+ * For split maps, toggle between having (un)synced viewports and (un)locked zooms+ * @memberof mapStateActions+ * @param {Object} syncInfo+ * @param {boolean} [syncInfo.isViewportSynced] Are the 2 split maps having synced viewports?+ * @param {boolean} [syncInfo.isZoomLocked] If split, are the zooms locked to each other or independent?+ */+export const toggleSplitMapViewport: (payload: {+ isViewportSynced?: boolean;+ isZoomLocked?: boolean;+}) => Merge<+ ToggleSplitMapViewportUpdaterAction,+ {type: typeof ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT}+> = createAction(+ ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT,+ (syncInfo: ToggleSplitMapViewportUpdaterAction['payload']) => ({payload: syncInfo})+);+/*** This declaration is needed to group actions in docs*/diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.tsindex e1f1c1afa..58b82bc24 100644--- a/src/actions/src/vis-state-actions.ts+++ b/src/actions/src/vis-state-actions.ts@@ -876,17 +876,17 @@ export function toggleFilterFeature(}export type OnLayerHoverUpdaterAction = {- info: PickInfo<any> | null;+ info: (PickInfo<any> & {mapIndex?: number}) | null;};/*** Trigger layer hover event with hovered object* @memberof visStateActions- * @param info - Object hovered, returned by deck.gl+ * @param info - Object hovered, returned by deck.gl. Includes an optional `mapIndex` property for limiting the display of the `<MapPopover>` to the `<MapContainer>` the user is interacting with.* @returns action* @public*/export function onLayerHover(- info: PickInfo<any> | null+ info: (PickInfo<any> & {mapIndex?: number}) | null): Merge<OnLayerHoverUpdaterAction, {type: typeof ActionTypes.LAYER_HOVER}> {return {type: ActionTypes.LAYER_HOVER,diff --git a/src/components/src/common/switch.tsx b/src/components/src/common/switch.tsxindex 2816df8d3..3c0c1c0d8 100644--- a/src/components/src/common/switch.tsx+++ b/src/components/src/common/switch.tsx@@ -32,6 +32,7 @@ interface SwitchProps {onFocus?: FocusEventHandler<HTMLInputElement>;value?: string;secondary?: boolean;+ disabled?: boolean;}const Switch = (props: SwitchProps) => {diff --git a/src/components/src/geocoder-panel.tsx b/src/components/src/geocoder-panel.tsxindex 0dcc46974..8047de8be 100644--- a/src/components/src/geocoder-panel.tsx+++ b/src/components/src/geocoder-panel.tsx@@ -68,12 +68,21 @@ const PARSED_CONFIG = KeplerGlSchema.parseSavedConfig({interface StyledGeocoderPanelProps {width?: number;+ unsyncedViewports: any;+ index: any;}const StyledGeocoderPanel = styled.div<StyledGeocoderPanelProps>`position: absolute;top: ${props => props.theme.geocoderTop}px;- right: ${props => props.theme.geocoderRight}px;+ right: ${props =>+ props.unsyncedViewports+ ? // 2 geocoders: split mode and unsynced viewports+ Number.isFinite(props.index) && props.index === 0+ ? `calc(50% + ${props.theme.geocoderRight}px)` // unsynced left geocoder (index 0)+ : `${props.theme.geocoderRight}px` // unsynced right geocoder (index 1)+ : // 1 geocoder: single mode OR split mode and synced viewports+ `${props.theme.geocoderRight}px`};width: ${props => (Number.isFinite(props.width) ? props.width : props.theme.geocoderWidth)}px;box-shadow: ${props => props.theme.boxShadow};z-index: 100;@@ -125,6 +134,8 @@ interface GeocoderPanelProps {width?: number;appWidth: number;className?: string;+ index: number;+ unsyncedViewports: boolean;}export default function GeocoderPanelFactory(): ComponentType<GeocoderPanelProps> {@@ -161,17 +172,20 @@ export default function GeocoderPanelFactory(): ComponentType<GeocoderPanelPropsreturn;}- this.props.updateMap({- latitude: centerAndZoom.center[1],- longitude: centerAndZoom.center[0],- // For marginal or invalid bounds, zoom may be NaN. Make sure to provide a valid value in order- // to avoid corrupt state and potential crashes as zoom is expected to be a number- ...(Number.isFinite(centerAndZoom.zoom) ? {zoom: centerAndZoom.zoom} : {}),- pitch: 0,- bearing: 0,- transitionDuration: this.props.transitionDuration,- transitionInterpolator: new FlyToInterpolator()- });+ this.props.updateMap(+ {+ latitude: centerAndZoom.center[1],+ longitude: centerAndZoom.center[0],+ // For marginal or invalid bounds, zoom may be NaN. Make sure to provide a valid value in order+ // to avoid corrupt state and potential crashes as zoom is expected to be a number+ ...(Number.isFinite(centerAndZoom.zoom) ? {zoom: centerAndZoom.zoom} : {}),+ pitch: 0,+ bearing: 0,+ transitionDuration: this.props.transitionDuration,+ transitionInterpolator: new FlyToInterpolator()+ },+ this.props.index+ );};removeMarker = () => {@@ -179,11 +193,20 @@ export default function GeocoderPanelFactory(): ComponentType<GeocoderPanelProps};render() {- const {isGeocoderEnabled, mapboxApiAccessToken, width, className} = this.props;+ const {+ className,+ isGeocoderEnabled,+ mapboxApiAccessToken,+ width,+ index,+ unsyncedViewports+ } = this.props;return (<StyledGeocoderPanelclassName={classnames('geocoder-panel', className)}width={width}+ index={index}+ unsyncedViewports={unsyncedViewports}style={{display: isGeocoderEnabled ? 'block' : 'none'}}>{isValid(mapboxApiAccessToken) && (diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsxindex 6b30d5dba..09b82e20e 100644--- a/src/components/src/kepler-gl.tsx+++ b/src/components/src/kepler-gl.tsx@@ -127,11 +127,34 @@ const BottomWidgetOuter = styled.div<BottomWidgetOuterProps>(}`);-export const mapFieldsSelector = (props: KeplerGLProps) => ({+export const isViewportDisjointed = props => {+ return (+ props.mapState.isSplit &&+ !props.mapState.isViewportSynced &&+ props.mapState.splitMapViewports.length > 1+ );+};++export const mapStateSelector = (props, index) => {+ if (!Number.isFinite(index)) {+ // either no index arg or an invalid index was provided+ // it is expected to be either 0 or 1 when in split mode+ // only use the mapState+ return props.mapState;+ }++ return isViewportDisjointed(props)+ ? // mix together the viewport properties intended for this disjointed <MapContainer> with the other necessary mapState properties+ {...props.mapState, ...props.mapState.splitMapViewports[index]}+ : // otherwise only use the mapState+ props.mapState;+};++export const mapFieldsSelector = (props: KeplerGLProps, index: number = 0) => ({getMapboxRef: props.getMapboxRef,mapboxApiAccessToken: props.mapboxApiAccessToken,mapboxApiUrl: props.mapboxApiUrl ? props.mapboxApiUrl : DEFAULT_KEPLER_GL_PROPS.mapboxApiUrl,- mapState: props.mapState,+ mapState: mapStateSelector(props, index),mapStyle: props.mapStyle,onDeckInitialized: props.onDeckInitialized,onViewStateChange: props.onViewStateChange,@@ -449,7 +472,6 @@ function KeplerGlFactory(const isExportingImage = uiState.exportImage.exporting;const availableProviders = this.availableProviders(this.props);- const mapFields = mapFieldsSelector(this.props);const filteredDatasets = this.filteredDatasetsSelector(this.props);const sideFields = sidePanelSelector(this.props, availableProviders, filteredDatasets);const plotContainerFields = plotContainerSelector(this.props);@@ -459,9 +481,14 @@ function KeplerGlFactory(const notificationPanelFields = notificationPanelSelector(this.props);const mapContainers = !isSplit- ? [<MapContainer primary={true} key={0} index={0} {...mapFields} />]+ ? [<MapContainer primary={true} key={0} index={0} {...mapFieldsSelector(this.props)} />]: splitMaps.map((settings, index) => (- <MapContainer key={index} index={index} primary={index === 1} {...mapFields} />+ <MapContainer+ key={index}+ index={index}+ primary={index === 1}+ {...mapFieldsSelector(this.props, index)}+ />));return (@@ -485,7 +512,21 @@ function KeplerGlFactory({!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}<MapsLayout className="maps">{mapContainers}</MapsLayout>{isExportingImage && <PlotContainer {...plotContainerFields} />}- {interactionConfig.geocoder.enabled && <GeoCoderPanel {...geoCoderPanelFields} />}+ {/* 1 geocoder: single mode OR split mode and synced viewports */}+ {!isViewportDisjointed(this.props) && interactionConfig.geocoder.enabled && (+ <GeoCoderPanel {...geoCoderPanelFields} index={0} unsyncedViewports={false} />+ )}+ {/* 2 geocoders: split mode and unsynced viewports */}+ {isViewportDisjointed(this.props) &&+ interactionConfig.geocoder.enabled &&+ mapContainers.map((_mapContainer, index) => (+ <GeoCoderPanel+ key={index}+ {...geoCoderPanelFields}+ index={index}+ unsyncedViewports={true}+ />+ ))}<BottomWidgetOuter absolute={!hasPortableWidth(breakPointValues)}><BottomWidgetrootRef={this.bottomWidgetRef}diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 7cfe16d6e..b6e843568 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -330,11 +330,11 @@ export default function MapContainerFactory(};_handleResize = dimensions => {- const {primary} = this.props;+ const {primary, index} = this.props;if (primary) {const {mapStateActions} = this.props;if (dimensions && dimensions.width > 0 && dimensions.height > 0) {- mapStateActions.updateMap(dimensions);+ mapStateActions.updateMap(dimensions, index);}}};@@ -521,6 +521,12 @@ export default function MapContainerFactory(/* eslint-disable complexity */_renderMapPopover() {+ // this check is for limiting the display of the `<MapPopover>` to the `<MapContainer>` the user is interacting with+ // the DeckGL onHover event handler adds a `mapIndex` property which is available in the `hoverInfo` object of `visState`+ if (this.props.index !== this.props.visState.hoverInfo?.mapIndex) {+ return null;+ }+// TODO: move this into reducer so it can be testedconst {mapState,@@ -733,6 +739,11 @@ export default function MapContainerFactory(});if (res) return;+ // add `mapIndex` property which will end up in the the `hoverInfo` object of `visState`+ // this is for limiting the display of the `<MapPopover>` to the `<MapContainer>` the user is interacting with+ // @ts-ignore (does not fail with local yarn-test)+ data.mapIndex = index;+visStateActions.onLayerHover(data);}}onClick={(data, event) => {@@ -790,7 +801,8 @@ export default function MapContainerFactory(viewState,this.props.mapStateActions.updateMap,this.props.onViewStateChange,- this.props.primary+ this.props.primary,+ this.props.index);};@@ -846,6 +858,7 @@ export default function MapContainerFactory(return (<><MapControl+ mapState={mapState}datasets={datasets}availableLocales={LOCALE_CODES_ARRAY}dragRotate={mapState.dragRotate}@@ -869,6 +882,7 @@ export default function MapContainerFactory(onToggleSplitMap={mapStateActions.toggleSplitMap}onMapToggleLayer={this._handleMapToggleLayer}onToggleMapControl={this._toggleMapControl}+ onToggleSplitMapViewport={mapStateActions.toggleSplitMapViewport}onSetEditorMode={visStateActions.setEditorMode}onSetLocale={uiStateActions.setLocale}onToggleEditorVisibility={visStateActions.toggleEditorVisibility}diff --git a/src/components/src/map/map-control-panel.tsx b/src/components/src/map/map-control-panel.tsxindex d25a0fb8c..f385e5e40 100644--- a/src/components/src/map/map-control-panel.tsx+++ b/src/components/src/map/map-control-panel.tsx@@ -18,11 +18,14 @@// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN// THE SOFTWARE.-import React from 'react';+import React, {useCallback} from 'react';import styled from 'styled-components';import {FormattedMessage} from '@kepler.gl/localization';-import {IconRoundSmall} from '../common/styled-components';+import {CenterFlexbox, IconRoundSmall} from '../common/styled-components';import {Close, Pin} from '../common/icons';+import Switch from '../common/switch';+import {MapState} from '@kepler.gl/types';+import {ActionHandler, toggleSplitMapViewport} from '@kepler.gl/actions';const StyledMapControlPanel = styled.div`background-color: ${props => props.theme.mapPanelBackgroundColor};@@ -63,6 +66,25 @@ const StyledMapControlPanelHeader = styled.div.attrs({}`;+const StyledMapControlPanelHeaderSplitViewportsTools = styled(StyledMapControlPanelHeader)`+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ align-items: self-start;+ height: unset;+`;++const StyledSBCenterFlexbox = styled(CenterFlexbox)`+ width: 100%;+ justify-content: space-between;+ flex-direction: row;+`;++const StyledDisableableSwitch = styled(Switch)`+ opacity: ${props => (props.disabled ? 0.4 : 1)};+ pointer-events: ${props => (props.disabled ? 'none' : 'all')};+`;+const StyledIcon = styled(IconRoundSmall)`color: ${props => props.theme.activeColor};background-color: transparent;@@ -83,10 +105,11 @@ export type MapControlPanelProps = {disableClose?: boolean;isExport?: boolean;logoComponent?: Element;+ mapState?: MapState;+ onToggleSplitMapViewport?: ActionHandler<typeof toggleSplitMapViewport>;};function MapControlPanelFactory() {- /** @type {import('./map-control-panel').MapControlPanelComponent} */const MapControlPanel: React.FC<MapControlPanelProps> = React.memo(({children,@@ -97,41 +120,76 @@ function MapControlPanelFactory() {onClick,scale = 1,isExport,- logoComponent- }) => (- <StyledMapControlPanel- className="map-control-panel"- style={{- transform: `scale(${scale})`,- marginBottom: '8px !important'- }}- >- <StyledMapControlPanelHeader>- {isExport && logoComponent ? (- logoComponent- ) : header ? (- <span style={{verticalAlign: 'middle'}}>- <FormattedMessage id={header} />- </span>+ logoComponent,+ mapState,+ onToggleSplitMapViewport+ }) => {+ const {isViewportSynced, isZoomLocked} = mapState || {};+ const onUnlockViewportChange = useCallback(() => {+ onToggleSplitMapViewport?.({isViewportSynced: !isViewportSynced});+ }, [isViewportSynced, onToggleSplitMapViewport]);++ const onSyncZoomChange = useCallback(() => {+ onToggleSplitMapViewport?.({isZoomLocked: !isZoomLocked});+ }, [isZoomLocked, onToggleSplitMapViewport]);++ return (+ <StyledMapControlPanel+ className="map-control-panel"+ style={{+ transform: `scale(${scale})`,+ marginBottom: '8px !important'+ }}+ >+ {mapState?.isSplit ? (+ <StyledMapControlPanelHeaderSplitViewportsTools>+ <StyledSBCenterFlexbox style={{paddingBottom: '6px'}}>+ <FormattedMessage id="Unlock Viewport" />+ <StyledDisableableSwitch+ checked={!mapState?.isViewportSynced}+ id="unlock-viewport-toggle"+ onChange={onUnlockViewportChange}+ />+ </StyledSBCenterFlexbox>+ <StyledSBCenterFlexbox>+ <FormattedMessage id="Sync Zoom" />+ <StyledDisableableSwitch+ checked={mapState?.isZoomLocked}+ id="sync-zoom-toggle"+ onChange={onSyncZoomChange}+ disabled={mapState?.isViewportSynced}+ />+ </StyledSBCenterFlexbox>+ </StyledMapControlPanelHeaderSplitViewportsTools>) : null}- {isExport ? null : (- <>- {pinnable && (- <StyledIcon className="pin-map-control-item" onClick={onPinClick}>- <Pin height="16px" />- </StyledIcon>- )}- {disableClose ? null : (- <StyledIcon className="close-map-control-item" onClick={onClick}>- <Close height="16px" />- </StyledIcon>- )}- </>- )}- </StyledMapControlPanelHeader>- <StyledMapControlPanelContent>{children}</StyledMapControlPanelContent>- </StyledMapControlPanel>- )++ <StyledMapControlPanelHeader>+ {isExport && logoComponent ? (+ logoComponent+ ) : header ? (+ <span style={{verticalAlign: 'middle'}}>+ <FormattedMessage id={header} />+ </span>+ ) : null}+ {isExport ? null : (+ <>+ {pinnable && (+ <StyledIcon className="pin-map-control-item" onClick={onPinClick}>+ <Pin height="16px" />+ </StyledIcon>+ )}+ {disableClose ? null : (+ <StyledIcon className="close-map-control-item" onClick={onClick}>+ <Close height="16px" />+ </StyledIcon>+ )}+ </>+ )}+ </StyledMapControlPanelHeader>+ <StyledMapControlPanelContent>{children}</StyledMapControlPanelContent>+ </StyledMapControlPanel>+ );+ });MapControlPanel.displayName = 'MapControlPanel';diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsxindex 011e7ba47..f047fcc80 100644--- a/src/components/src/map/map-control.tsx+++ b/src/components/src/map/map-control.tsx@@ -30,7 +30,7 @@ import MapLegendPanelFactory from './map-legend-panel';import MapDrawPanelFactory from './map-draw-panel';import LocalePanelFactory from './locale-panel';import {Layer} from '@kepler.gl/layers';-import {Editor, MapControls} from '@kepler.gl/types';+import {Editor, MapControls, MapState} from '@kepler.gl/types';import {Datasets} from '@kepler.gl/table';interface StyledMapControlProps {@@ -67,6 +67,13 @@ export type MapControlProps = {mapControls: MapControls;onTogglePerspective: () => void;onToggleSplitMap: () => void;+ onToggleSplitMapViewport: ({+ isViewportSynced,+ isZoomLocked+ }: {+ isViewportSynced: boolean;+ isZoomLocked: boolean;+ }) => void;onToggleMapControl: (control: string) => void;onSetEditorMode: (mode: string) => void;onToggleEditorVisibility: () => void;@@ -76,6 +83,7 @@ export type MapControlProps = {logoComponent: React.FC | React.ReactNode;// optional+ mapState?: MapState;readOnly?: boolean;scale?: number;mapLayers?: {[key: string]: boolean};diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsxindex 81380af32..6ac0d1cc9 100644--- a/src/components/src/map/map-legend-panel.tsx+++ b/src/components/src/map/map-legend-panel.tsx@@ -29,9 +29,10 @@ import MapLegendFactory from './map-legend';import LazyTippy from './lazy-tippy';import {createPortal} from 'react-dom';import {DIMENSIONS} from '@kepler.gl/constants';-import {MapControl, MapControls} from '@kepler.gl/types';+import {MapControl, MapControls, MapState} from '@kepler.gl/types';import {Layer} from '@kepler.gl/layers';import {media} from '@kepler.gl/styles';+import {ActionHandler, toggleSplitMapViewport} from '@kepler.gl/actions';MapLegendPanelFactory.deps = [MapControlTooltipFactory, MapControlPanelFactory, MapLegendFactory];@@ -66,8 +67,10 @@ export type MapLegendPanelProps = {logoComponent: Element;actionIcons: MapLegendPanelIcons;mapControls: MapControls;+ mapState?: MapState;mapHeight?: number;offsetRight?: number;+ onToggleSplitMapViewport?: ActionHandler<typeof toggleSplitMapViewport>;};function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {@@ -75,7 +78,6 @@ function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {legend: Legend};- /** @type {import('./map-legend-panel').MapLegendPanelComponent} */const MapLegendPanel: React.FC<MapLegendPanelProps> = ({layers,mapControls,@@ -84,8 +86,10 @@ function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {isExport,logoComponent,actionIcons = defaultActionIcons,+ mapState,mapHeight,- offsetRight+ offsetRight,+ onToggleSplitMapViewport}) => {const mapLegend = mapControls?.mapLegend || ({} as MapControl);const {active: isPinned} = mapLegend || {};@@ -130,6 +134,8 @@ function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {})}isExport={isExport}logoComponent={logoComponent}+ mapState={mapState}+ onToggleSplitMapViewport={onToggleSplitMapViewport}><MapLegend layers={layers} mapHeight={mapHeight} /></MapControlPanel>diff --git a/src/reducers/src/map-state-updaters.ts b/src/reducers/src/map-state-updaters.tsindex 4298ccf34..32d2c98ec 100644--- a/src/reducers/src/map-state-updaters.ts+++ b/src/reducers/src/map-state-updaters.ts@@ -23,6 +23,7 @@ import booleanWithin from '@turf/boolean-within';import bboxPolygon from '@turf/bbox-polygon';import {fitBounds} from '@math.gl/web-mercator';import deepmerge from 'deepmerge';+import pick from 'lodash.pick';import {getCenterAndZoomFromBounds, validateBounds, MAPBOX_TILE_SIZE} from '@kepler.gl/utils';import {MapStateActions, ReceiveMapConfigPayload, ActionTypes} from '@kepler.gl/actions';@@ -80,7 +81,13 @@ const mapStateUpdaters = null;* @property dragRotate Default: `false`* @property width Default: `800`* @property height Default: `800`- * @property isSplit Default: `false`+ * @property minZoom: `undefined`,+ * @property maxZoom: `undefined`,+ * @property maxBounds: `undefined`,+ * @property isSplit: `false`,+ * @property isViewportSynced: `true`,+ * @property isZoomLocked: `false`,+ * @property splitMapViewports: `[]`* @public*/export const INITIAL_MAP_STATE: MapState = {@@ -92,10 +99,13 @@ export const INITIAL_MAP_STATE: MapState = {dragRotate: false,width: 800,height: 800,- isSplit: false,minZoom: undefined,maxZoom: undefined,- maxBounds: undefined+ maxBounds: undefined,+ isSplit: false,+ isViewportSynced: true,+ isZoomLocked: false,+ splitMapViewports: []};/* Updaters */@@ -108,24 +118,46 @@ export const updateMapUpdater = (state: MapState,action: MapStateActions.UpdateMapUpdaterAction): MapState => {- let newMapState = {- ...state,- ...(action.payload || {})- };+ const {viewport, mapIndex = 0} = action.payload;- // Make sure zoom level doesn't go bellow minZoom if defined- if (newMapState.minZoom && newMapState.zoom < newMapState.minZoom) {- newMapState.zoom = newMapState.minZoom;- }- // Make sure zoom level doesn't go above maxZoom if defined- if (newMapState.maxZoom && newMapState.zoom > newMapState.maxZoom) {- newMapState.zoom = newMapState.maxZoom;+ if (state.isViewportSynced) {+ return updateViewport(state, viewport);}- // Limit viewport update based on maxBounds- if (newMapState.maxBounds && validateBounds(newMapState.maxBounds)) {- newMapState = updateViewportBasedOnBounds(state, newMapState);++ let otherViewportMapIndex = -1;+ const splitMapViewports = state.splitMapViewports.map((currentViewport, i) => {+ if (i === mapIndex) {+ // update the matching viewport with the newViewport info in the action payload+ return updateViewport(currentViewport, viewport);+ }++ otherViewportMapIndex = i;+ // make no changes to the other viewport (yet)+ return currentViewport;+ });++ // make conditional updates to the other viewport not matching this payload's `mapIndex`+ if (Number.isFinite(otherViewportMapIndex) && otherViewportMapIndex > -1) {+ // width and height are a special case and are always updated+ splitMapViewports[otherViewportMapIndex].width = splitMapViewports[mapIndex].width;+ splitMapViewports[otherViewportMapIndex].height = splitMapViewports[mapIndex].height;++ if (state.isZoomLocked) {+ // update the other viewport with the new zoom from the split viewport that was updated with this payload's `mapIndex`+ splitMapViewports[otherViewportMapIndex].zoom = splitMapViewports[mapIndex].zoom;+ }}- return newMapState;++ return {+ // update the top-level mapState viewport with the most recently interacted-with split viewport+ // WHY? this avoids zoom and bounds "jumping" due to a "stale" top-level mapState viewport when:+ // 1. toggling off the unsynced viewports mode to switch to the synced viewports mode+ // 2. toggling on the zoom lock during an unsynced viewports mode+ ...state,+ ...splitMapViewports[mapIndex],+ // update the mapState with the new array of split viewports+ splitMapViewports+ };};/**@@ -146,7 +178,7 @@ export const fitBoundsUpdater = (return state;}- return {+ const newState = {...state,latitude: centerAndZoom.center[1],longitude: centerAndZoom.center[0],@@ -154,6 +186,19 @@ export const fitBoundsUpdater = (// to avoid corrupt state and potential crashes as zoom is expected to be a number...(Number.isFinite(centerAndZoom.zoom) ? {zoom: centerAndZoom.zoom} : {})};++ // if fitting to bounds while split and unsynced+ // copy the new latitude, longitude, and zoom values to each split viewport+ if (newState.splitMapViewports.length) {+ newState.splitMapViewports = newState.splitMapViewports.map(currentViewport => ({+ ...currentViewport,+ latitude: newState.latitude,+ longitude: newState.longitude,+ zoom: newState.zoom+ }));+ }++ return newState;};/**@@ -164,14 +209,29 @@ export const fitBoundsUpdater = (export const togglePerspectiveUpdater = (state: MapState,action: MapStateActions.TogglePerspectiveUpdaterAction-): MapState => ({- ...state,- ...{- pitch: state.dragRotate ? 0 : 50,- bearing: state.dragRotate ? 0 : 24- },- dragRotate: !state.dragRotate-});+): MapState => {+ const newState = {+ ...state,+ ...{+ pitch: state.dragRotate ? 0 : 50,+ bearing: state.dragRotate ? 0 : 24+ },+ dragRotate: !state.dragRotate+ };++ // if toggling 3d and 2d while split and unsynced+ // copy the new pitch, bearing, and dragRotate values to each split viewport+ if (newState.splitMapViewports.length) {+ newState.splitMapViewports = newState.splitMapViewports.map(currentViewport => ({+ ...currentViewport,+ pitch: newState.pitch,+ bearing: newState.bearing,+ dragRotate: newState.dragRotate+ }));+ }++ return newState;+};/*** reset mapState to initial State@@ -239,10 +299,85 @@ export const toggleSplitMapUpdater = (action: MapStateActions.ToggleSplitMapUpdaterAction): MapState => ({...state,+ ...getMapDimForSplitMap(!state.isSplit, state),isSplit: !state.isSplit,- ...getMapDimForSplitMap(!state.isSplit, state)+ ...(!state.isSplit === false+ ? {+ // if toggling to no longer split (single mode) then reset a few properties+ isViewportSynced: true,+ isZoomLocked: false,+ splitMapViewports: []+ }+ : {})});+/**+ * Toggle between locked and unlocked split viewports+ * @memberof mapStateUpdaters+ * @public+ */+export const toggleSplitMapViewportUpdater = (+ state: MapState,+ action: MapStateActions.ToggleSplitMapViewportUpdaterAction+) => {+ // new map state immediately gets the new payload values for isViewportSynced and isZoomLocked+ const newMapState = {+ ...state,+ ...(action.payload || {})+ };++ if (newMapState.isViewportSynced) {+ // switching from unsynced to synced viewports+ newMapState.splitMapViewports = [];+ } else {+ // switching from synced to unsynced viewports+ // or already in unsynced mode and toggling locked zoom++ if (state.isZoomLocked && !newMapState.isZoomLocked) {+ // switching off locked zoom while unsynced+ // don't copy the mapStates to left and right viewports because there will be zoom "jumping"+ return newMapState;+ }++ if (!state.isZoomLocked && newMapState.isZoomLocked) {+ // switching on locked zoom while unsynced+ // only copy zoom viewport property from the most recently interacted-with viewport to the other+ // TODO: do we want to check for a match a different way, such as a combo of `latitude` and `longitude`?+ const lastUpdatedViewportIndex = newMapState.splitMapViewports.findIndex(+ v => newMapState.zoom === v.zoom+ );++ const splitMapViewports = newMapState.splitMapViewports.map((currentViewport, i) => {+ if (i === lastUpdatedViewportIndex) {+ // no zoom to modify here+ return currentViewport;+ }+ // the other viewport gets the most recently interacted-with viewport's zoom+ // WHY? the viewport the user was last interacting with will set zoom across the board for smooth UX+ return {+ ...currentViewport,+ zoom: newMapState.splitMapViewports[lastUpdatedViewportIndex].zoom+ };+ });++ newMapState.splitMapViewports = splitMapViewports;++ return newMapState;+ }++ // if current viewport is synced, and we are unsyncing it+ // or already in unsynced mode and NOT toggling locked zoom+ // make a fresh copy of the current viewport object, assign it to splitMapViewports[]+ // getViewportFromMapState is called twice to avoid memory allocation conflicts+ const leftViewport = getViewportFromMapState(newMapState);+ const rightViewport = getViewportFromMapState(newMapState);+ newMapState.splitMapViewports = [leftViewport, rightViewport];+ }++ // return new state+ return newMapState;+};+// Helpersexport function getMapDimForSplitMap(isSplit, state) {// cases:@@ -322,3 +457,41 @@ function updateViewportBasedOnBounds(state: MapState, newMapState: MapState) {return newMapState;}++function getViewportFromMapState(state) {+ return pick(state, [+ 'width',+ 'height',+ 'zoom',+ 'pitch',+ 'bearing',+ 'latitude',+ 'longitude',+ 'dragRotate',+ 'minZoom',+ 'maxZoom',+ 'maxBounds'+ ]);+}++function updateViewport(originalViewport, viewportUpdates) {+ let newViewport = {+ ...originalViewport,+ ...(viewportUpdates || {})+ };++ // Make sure zoom level doesn't go bellow minZoom if defined+ if (newViewport.minZoom && newViewport.zoom < newViewport.minZoom) {+ newViewport.zoom = newViewport.minZoom;+ }+ // Make sure zoom level doesn't go above maxZoom if defined+ if (newViewport.maxZoom && newViewport.zoom > newViewport.maxZoom) {+ newViewport.zoom = newViewport.maxZoom;+ }+ // Limit viewport update based on maxBounds+ if (newViewport.maxBounds && validateBounds(newViewport.maxBounds)) {+ newViewport = updateViewportBasedOnBounds(originalViewport, newViewport);+ }++ return newViewport;+}diff --git a/src/reducers/src/map-state.ts b/src/reducers/src/map-state.tsindex 70b224a32..f1c79b8c4 100644--- a/src/reducers/src/map-state.ts+++ b/src/reducers/src/map-state.ts@@ -32,7 +32,8 @@ const actionHandler = {[ActionTypes.TOGGLE_PERSPECTIVE]: mapStateUpdaters.togglePerspectiveUpdater,[ActionTypes.RECEIVE_MAP_CONFIG]: mapStateUpdaters.receiveMapConfigUpdater,[ActionTypes.RESET_MAP_CONFIG]: mapStateUpdaters.resetMapConfigUpdater,- [ActionTypes.TOGGLE_SPLIT_MAP]: mapStateUpdaters.toggleSplitMapUpdater+ [ActionTypes.TOGGLE_SPLIT_MAP]: mapStateUpdaters.toggleSplitMapUpdater,+ [ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT]: mapStateUpdaters.toggleSplitMapViewportUpdater};/* Reducer */diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.tsindex 427f7afbd..d3e804bf3 100644--- a/src/reducers/src/vis-state-merger.ts+++ b/src/reducers/src/vis-state-merger.ts@@ -291,19 +291,25 @@ export function mergeSplitMaps<S extends VisState>(const merged = [...state.splitMaps];const unmerged = [];splitMaps.forEach((sm, i) => {- Object.entries(sm.layers).forEach(([id, value]) => {- // check if layer exists- const pushTo = state.layers.find(l => l.id === id) ? merged : unmerged;-- // create map panel if current map is not split- pushTo[i] = pushTo[i] || {- layers: pushTo === merged ? getInitialMapLayersForSplitMap(state.layers) : []- };- pushTo[i].layers = {- ...pushTo[i].layers,- [id]: value- };- });+ const entries = Object.entries(sm.layers);+ if (entries.length > 0) {+ entries.forEach(([id, value]) => {+ // check if layer exists+ const pushTo = state.layers.find(l => l.id === id) ? merged : unmerged;++ // create map panel if current map is not split+ pushTo[i] = pushTo[i] || {+ layers: pushTo === merged ? getInitialMapLayersForSplitMap(state.layers) : []+ };+ pushTo[i].layers = {+ ...pushTo[i].layers,+ [id]: value+ };+ });+ } else {+ // We are merging if there are no layers in both split map+ merged.push(sm);+ }});return {diff --git a/src/schemas/src/map-state-schema.ts b/src/schemas/src/map-state-schema.tsindex d8f987b4a..3b676a443 100644--- a/src/schemas/src/map-state-schema.ts+++ b/src/schemas/src/map-state-schema.ts@@ -33,7 +33,10 @@ export const propertiesV0 = {export const propertiesV1 = {...propertiesV0,- isSplit: null+ isSplit: null,+ isViewportSynced: null,+ isZoomLocked: null,+ splitMapViewports: null};const mapStateSchema = {diff --git a/src/schemas/src/schema-manager.ts b/src/schemas/src/schema-manager.tsindex e3197c8f1..bc74404ea 100644--- a/src/schemas/src/schema-manager.ts+++ b/src/schemas/src/schema-manager.ts@@ -40,6 +40,9 @@ export type SavedMapState = {pitch: number;zoom: number;isSplit: boolean;+ isViewportSynced: true;+ isZoomLocked: false;+ splitMapViewports: [];};export type SavedLayerGroups = {diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex b56ae9ee9..81bca6795 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -9,12 +9,21 @@ export type MapState = {dragRotate: boolean;width: number;height: number;- isSplit: boolean;minZoom?: number;maxZoom?: number;maxBounds?: Bounds;initialState?: any;scale?: number;++ // the following 4 properties assist with split viewports that can optionally have (un)synced viewports and zooms+ /** Is the application split into 2 maps? */+ isSplit: boolean;+ /** Are the 2 split maps having synced viewports? */+ isViewportSynced: boolean;+ /** If split, are the zooms locked to each other or independent? */+ isZoomLocked: boolean;+ /** An array of either 0 or 2 Viewport objects (index 0 for left map; index 1 for right map) */+ splitMapViewports: Viewport[];};export type Bounds = [number, number, number, number];diff --git a/src/utils/src/map-utils.ts b/src/utils/src/map-utils.tsindex bcee61a85..9a5620f25 100644--- a/src/utils/src/map-utils.ts+++ b/src/utils/src/map-utils.ts@@ -5,9 +5,10 @@ import {SplitMapLayers, SplitMap, Viewport, MapState} from '@kepler.gl/types';export const onViewPortChange = (viewState: Viewport,- onUpdateMap: (next: any) => any,+ onUpdateMap: (next: any, mapIndex: number) => any,onViewStateChange?: (next: any) => void | null,- primary: boolean = false+ primary: boolean = false,+ mapIndex: number = 0): void => {const {width = 0, height = 0, ...restViewState} = viewState;// react-map-gl sends 0,0 dimensions during initialization@@ -21,7 +22,7 @@ export const onViewPortChange = (onViewStateChange(next);}- onUpdateMap(next);+ onUpdateMap(next, mapIndex);};export const getMapLayersFromSplitMaps = (diff --git a/test/browser-headless/component/map-container-test.js b/test/browser-headless/component/map-container-test.jsindex c36da83f3..9e83f3c87 100644--- a/test/browser-headless/component/map-container-test.js+++ b/test/browser-headless/component/map-container-test.js@@ -144,6 +144,7 @@ test('MapContainerFactory - _renderDeckOverlay', t => {height: 800,onClick: (info, event) => clickEvents.push({info, event}),onHover: (info, event) => {+ info.mapIndex = 0;hoverEvents.push({info, event});}},@@ -157,14 +158,17 @@ test('MapContainerFactory - _renderDeckOverlay', t => {assert.is(hoverEvents.length, 1, 'onHover is called');assert.is(hoverEvents[0].info.index, 15, 'object is picked');assert.is(hoverEvents[0].info.picked, true, 'object is picked');+ assert.is(hoverEvents[0].info.mapIndex, 0, 'onHover includes mapIndex value');assert.deepEqual(layers[0].state.model.getUniforms().picking_uSelectedColor,[16, 0, 0],'autoHighlight parameter is set');- // test picking info- ['color', 'coordinate', 'pixel', 'x', 'y'].forEach(key => {+ [+ // test picking info+ ('color', 'coordinate', 'pixel', 'x', 'y')+ ].forEach(key => {assert.deepEqual(hoverEvents[0].info[key],expectedInfo[key],diff --git a/test/node/reducers/map-state-test.js b/test/node/reducers/map-state-test.jsindex 912ec6b35..0f416a9ce 100644--- a/test/node/reducers/map-state-test.js+++ b/test/node/reducers/map-state-test.js@@ -25,6 +25,7 @@ import {togglePerspective,fitBounds,toggleSplitMap,+ toggleSplitMapViewport,receiveMapConfig} from '@kepler.gl/actions';@@ -68,7 +69,7 @@ test('#mapStateReducer -> UPDATE_MAP', t => {};const expectedState = {...InitialMapState, ...mapUpdate};- const newState = reducer(undefined, updateMap(mapUpdate));+ const newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'should update map longitude and latitude');@@ -82,7 +83,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 12};let expectedState = {...InitialMapState, ...mapUpdate};- let newState = reducer(undefined, updateMap(mapUpdate));+ let newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'If zoom < maxZoom - zoom should stay the same');mapUpdate = {@@ -90,7 +91,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 12};expectedState = {...InitialMapState, ...mapUpdate, ...{zoom: mapUpdate.maxZoom}};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'If zoom > maxZoom - zoom should be equal to maxZoom');mapUpdate = {@@ -98,7 +99,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {minZoom: 12};expectedState = {...InitialMapState, ...mapUpdate};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'If zoom > minZoom - zoom should stay the same');mapUpdate = {@@ -106,7 +107,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {minZoom: 12};expectedState = {...InitialMapState, ...mapUpdate, ...{zoom: mapUpdate.minZoom}};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'If zoom < minZoom - zoom should be equal to minZoom');mapUpdate = {@@ -115,7 +116,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 15};expectedState = {...InitialMapState, ...mapUpdate};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'If minZoom < zoom < maxZoom - zoom should stay the same');mapUpdate = {@@ -124,7 +125,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 9};expectedState = {...InitialMapState, ...mapUpdate};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState,expectedState,@@ -137,7 +138,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 12};expectedState = {...InitialMapState, ...mapUpdate, ...{zoom: mapUpdate.maxZoom}};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState,expectedState,@@ -150,7 +151,7 @@ test('#mapStateReducer -> UPDATE_MAP - minZoom/maxZoom', t => {maxZoom: 12};expectedState = {...InitialMapState, ...mapUpdate, ...{zoom: mapUpdate.minZoom}};- newState = reducer(undefined, updateMap(mapUpdate));+ newState = reducer(undefined, updateMap(mapUpdate, 0));t.deepEqual(newState,expectedState,@@ -181,7 +182,7 @@ test('#mapStateReducer -> UPDATE_MAP - maxBounds', t => {zoom: 9.699465540852673}};- let newState = reducer(state, updateMap(mapUpdate));+ let newState = reducer(state, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'maxBounds is snapped to the viewport');state = {@@ -197,7 +198,7 @@ test('#mapStateReducer -> UPDATE_MAP - maxBounds', t => {zoom: 12};expectedState = {...state, ...mapUpdate};- newState = reducer(state, updateMap(mapUpdate));+ newState = reducer(state, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'Viewport is within maxBounds - zoomed in');state = {@@ -213,12 +214,80 @@ test('#mapStateReducer -> UPDATE_MAP - maxBounds', t => {zoom: 8};expectedState = {...state};- newState = reducer(state, updateMap(mapUpdate));+ newState = reducer(state, updateMap(mapUpdate, 0));t.deepEqual(newState, expectedState, 'Viewport is outside the maxBounds - zoomed out');t.end();});+test('#mapStateReducer -> UPDATE_MAP - split map and unsynced viewports', t => {+ // toggle to split mode+ let newState = reducer(INITIAL_MAP_STATE, toggleSplitMap());+ // change to unsynced viewports and retain default isZoomLocked+ newState = reducer(newState, toggleSplitMapViewport({isViewportSynced: false}));+ // and then update map for unsynced viewport of mapIndex 0+ let mapUpdate = {+ latitude: 24.123,+ longitude: 120.839,+ zoom: 2.3+ };+ const firstUnsyncedSplitMapViewportBeforeUpdatingMapState = {...newState.splitMapViewports[0]};+ newState = reducer(newState, updateMap(mapUpdate, 0));++ t.notDeepEqual(+ newState.splitMapViewports[0],+ firstUnsyncedSplitMapViewportBeforeUpdatingMapState,+ 'unlocked zoom: updating mapIndex 0 should change the same split map viewport'+ );++ t.deepEqual(+ newState.splitMapViewports[1],+ firstUnsyncedSplitMapViewportBeforeUpdatingMapState,+ 'unlocked zoom: updating mapIndex 0 should not change the other split map viewport'+ );++ t.notEqual(+ newState.splitMapViewports[0].zoom,+ newState.splitMapViewports[1].zoom,+ 'unlocked zoom: should not set both viewports to the same zoom prop'+ );++ // retain unsycned viewports and change to isZoomLocked true+ newState = reducer(newState, toggleSplitMapViewport({isZoomLocked: true}));+ // and then update map for unsynced viewport and locked zoom of mapIndex 1+ mapUpdate = {+ latitude: 25,+ longitude: 123,+ zoom: 10+ };+ const expectedFistUnsyncedSplitMapViewportWithLockedZoom = {+ ...newState.splitMapViewports[0],+ zoom: mapUpdate.zoom+ };+ const secondUnsyncedSplitMapViewportBeforeUpdatingMapState = {...newState.splitMapViewports[1]};+ newState = reducer(newState, updateMap(mapUpdate, 1));++ t.notDeepEqual(+ newState.splitMapViewports[1],+ secondUnsyncedSplitMapViewportBeforeUpdatingMapState,+ 'locked zoom: updating mapIndex 1 should change the same split map viewport'+ );++ t.deepEqual(+ newState.splitMapViewports[0],+ expectedFistUnsyncedSplitMapViewportWithLockedZoom,+ 'locked zoom: updating mapIndex 1 should only change the zoom property of the other split map viewport but not other properties'+ );++ t.equal(+ newState.splitMapViewports[0].zoom,+ newState.splitMapViewports[1].zoom,+ 'locked zoom: should set both viewports to the same zoom'+ );++ t.end();+});+test('#mapStateReducer -> TOGGLE_PERSPECTIVE', t => {const newState = reducer(undefined, {});t.equal(newState.dragRotate, false, 'dragRotate should default to false');@@ -236,6 +305,51 @@ test('#mapStateReducer -> TOGGLE_PERSPECTIVE', t => {t.end();});+test('#mapStateReducer -> TOGGLE_PERSPECTIVE - split map and unsynced viewports', t => {+ // toggle to split mode+ let newState = reducer(INITIAL_MAP_STATE, toggleSplitMap());+ // change to unsynced viewports+ newState = reducer(+ newState,+ toggleSplitMapViewport({isViewportSynced: false, isZoomLocked: false})+ );+ // and then toggle perspective+ newState = reducer(newState, togglePerspective());++ t.equal(+ newState.dragRotate,+ newState.splitMapViewports[0].dragRotate,+ 'split map with unsynced viewports: dragRotate should be copied to the first split viewport'+ );+ t.equal(+ newState.dragRotate,+ newState.splitMapViewports[1].dragRotate,+ 'split map with unsynced viewports: dragRotate should be copied to the second split viewport'+ );+ t.equal(+ newState.pitch,+ newState.splitMapViewports[0].pitch,+ 'split map with unsynced viewports: pitch should be copied to the first split viewport'+ );+ t.equal(+ newState.pitch,+ newState.splitMapViewports[1].pitch,+ 'split map with unsynced viewports: pitch should be copied to the second split viewport'+ );+ t.equal(+ newState.bearing,+ newState.splitMapViewports[0].bearing,+ 'split map with unsynced viewports: bearing should be copied to the first split viewport'+ );+ t.equal(+ newState.bearing,+ newState.splitMapViewports[1].bearing,+ 'split map with unsynced viewports: bearing should be copied to the second split viewport'+ );++ t.end();+});+test('#mapStateReducer -> FIT_BOUNDS', t => {// default input and output in @mapbox/geo-viewport// https://github.com/mapbox/geo-viewport@@ -252,7 +366,7 @@ test('#mapStateReducer -> FIT_BOUNDS', t => {zoom: 10};- const stateWidthMapDimension = reducer(undefined, updateMap(mapUpdate));+ const stateWidthMapDimension = reducer(undefined, updateMap(mapUpdate, 0));const updatedState = reducer(stateWidthMapDimension, fitBounds(bounds));t.equal(updatedState.latitude, expected.center[1], 'should fit latitude');@@ -262,6 +376,56 @@ test('#mapStateReducer -> FIT_BOUNDS', t => {t.end();});+test('#mapStateReducer -> FIT_BOUNDS - split map and unsynced viewports', t => {+ // default input and output in @mapbox/geo-viewport+ // https://github.com/mapbox/geo-viewport++ const bounds = [5.668343999999995, 45.111511000000014, 5.852471999999996, 45.26800200000002];++ // toggle to split mode+ let newState = reducer(INITIAL_MAP_STATE, toggleSplitMap());+ // change to unsynced viewports+ newState = reducer(+ newState,+ toggleSplitMapViewport({isViewportSynced: false, isZoomLocked: false})+ );+ // and then fit bounds+ newState = reducer(newState, fitBounds(bounds));++ t.equal(+ newState.latitude,+ newState.splitMapViewports[0].latitude,+ 'split map with unsynced viewports: latitude should be copied to the first split viewport'+ );+ t.equal(+ newState.latitude,+ newState.splitMapViewports[1].latitude,+ 'split map with unsynced viewports: latitude should be copied to the second split viewport'+ );+ t.equal(+ newState.longitude,+ newState.splitMapViewports[0].longitude,+ 'split map with unsynced viewports: longitude should be copied to the first split viewport'+ );+ t.equal(+ newState.longitude,+ newState.splitMapViewports[1].longitude,+ 'split map with unsynced viewports: longitude should be copied to the second split viewport'+ );+ t.equal(+ newState.zoom,+ newState.splitMapViewports[0].zoom,+ 'split map with unsynced viewports: zoom should be copied to the first split viewport'+ );+ t.equal(+ newState.zoom,+ newState.splitMapViewports[1].zoom,+ 'split map with unsynced viewports: zoom should be copied to the second split viewport'+ );++ t.end();+});+test('#mapStateReducer -> FIT_BOUNDS.invalid', t => {// default input and output in @mapbox/geo-viewport// https://github.com/mapbox/geo-viewport@@ -271,7 +435,7 @@ test('#mapStateReducer -> FIT_BOUNDS.invalid', t => {height: 480};- const stateWidthMapDimension = reducer(undefined, updateMap(mapUpdate));+ const stateWidthMapDimension = reducer(undefined, updateMap(mapUpdate, 0));const updatedState = reducer(stateWidthMapDimension, fitBounds(null));t.equal(updatedState, stateWidthMapDimension, 'should not update state when bounds is invalid');const updatedState2 = reducer(stateWidthMapDimension, fitBounds([500, -100, 322, 9]));@@ -388,3 +552,110 @@ test('#mapStateReducer -> SPLIT_MAP: close map at specific point', t => {t.end();});++test('#mapStateReducer -> TOGGLE_SPLIT_MAP_VIEWPORT', t => {+ let newState = reducer(INITIAL_MAP_STATE, {});++ let expectedState = {+ ...INITIAL_MAP_STATE,+ isSplit: false,+ isViewportSynced: true,+ isZoomLocked: false,+ splitMapViewports: []+ };++ // validate defaults before making state changes+ t.deepEqual(+ newState,+ expectedState,+ 'should retain default initial state values for isSplit, isViewportSynced, isZoomLocked, and splitMapViewports'+ );++ // toggle to split mode and retain defaults of synced viewports and unlocked zoom+ newState = reducer(newState, toggleSplitMap());+ newState = reducer(+ newState,+ toggleSplitMapViewport({isViewportSynced: true, isZoomLocked: false})+ );++ expectedState = {+ ...newState,+ isSplit: true,+ isViewportSynced: true,+ isZoomLocked: false,+ splitMapViewports: []+ };++ t.deepEqual(+ newState,+ expectedState,+ 'toggling isSplit to true and setting isViewportSynced to true and isZoomLocked to false should retain default related initial state values'+ );++ // keep split mode and change synced viewports, but keep zoom lock as false+ const splitMapViewportsBeforeOnlyChangingIsViewportSyncedFalse = [...newState.splitMapViewports];+ newState = reducer(newState, toggleSplitMapViewport({isViewportSynced: false}));++ t.equal(+ newState.isViewportSynced,+ false,+ 'changing isViewportSynced to false should update the same prop in next state'+ );++ t.notDeepEqual(+ newState.splitMapViewports,+ splitMapViewportsBeforeOnlyChangingIsViewportSyncedFalse,+ 'changing isViewportSynced to false while retaining isZoomLocked as false should modify the splitMapViewports array'+ );++ // change one of the split viewports' zoom levels+ // then switch on locked zoom while retaining unsynced+ newState = reducer(newState, updateMap({zoom: 5}, 1));+ newState = reducer(newState, toggleSplitMapViewport({isZoomLocked: true}));++ t.equal(+ newState.isZoomLocked,+ true,+ 'changing isZoomLocked to true should update the same prop in next state'+ );++ // and test if they both now have the same zoom+ t.equal(+ newState.splitMapViewports[0].zoom,+ newState.splitMapViewports[1].zoom,+ 'while isViewportSynced is false, changing isZoomLocked to true should modify the splitMapViewports array to have matching zoom values'+ );++ // switch off locked zoom while retaining unsynced+ const splitMapViewportsBeforeOnlyChangingIsZoomLockedFalse = [...newState.splitMapViewports];+ newState = reducer(newState, toggleSplitMapViewport({isZoomLocked: false}));++ t.equal(+ newState.isZoomLocked,+ false,+ 'changing isZoomLocked to false should update the same prop in next state'+ );++ t.deepEqual(+ newState.splitMapViewports,+ splitMapViewportsBeforeOnlyChangingIsZoomLockedFalse,+ 'while isViewportSynced is false, changing isZoomLocked to false should not modify the splitMapViewports array'+ );++ // toggle from unsynced to synced viewports while retaining zoom lock as false+ newState = reducer(newState, toggleSplitMapViewport({isViewportSynced: true}));++ t.deepEqual(+ newState.splitMapViewports,+ [],+ 'changing isViewportSynced to false should change the splitMapViewports array to be empty'+ );++ t.equal(+ newState.isZoomLocked,+ false,+ 'changing isViewportSynced to false should also retain isZoomLocked as false'+ );++ t.end();+});diff --git a/test/node/schemas/map-state-schema-test.js b/test/node/schemas/map-state-schema-test.jsindex f7441f13b..4e8a51a03 100644--- a/test/node/schemas/map-state-schema-test.js+++ b/test/node/schemas/map-state-schema-test.js@@ -33,7 +33,18 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {t.deepEqual(Object.keys(msToSave),- ['bearing', 'dragRotate', 'latitude', 'longitude', 'pitch', 'zoom', 'isSplit'],+ [+ 'bearing',+ 'dragRotate',+ 'latitude',+ 'longitude',+ 'pitch',+ 'zoom',+ 'isSplit',+ 'isViewportSynced',+ 'isZoomLocked',+ 'splitMapViewports'+ ],'mapState should have all 6 entries');@@ -44,7 +55,10 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {longitude: -122.34679,zoom: 9,dragRotate: false,- isSplit: false+ isSplit: false,+ isViewportSynced: true,+ isZoomLocked: false,+ splitMapViewports: []};t.deepEqual(msToSave, expected, 'save mapState should be current');