Skip to content

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

feat: swipe view mode (#3487)

Igor Dykhta2c787caa2850
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index dd5b00738..de21eddd4 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -125,6 +125,8 @@ export const ActionTypes = {
TOGGLE_FULLSCREEN: `${ACTION_PREFIX}TOGGLE_FULLSCREEN`,
TOGGLE_SPLIT_MAP: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP`,
TOGGLE_SPLIT_MAP_VIEWPORT: `${ACTION_PREFIX}TOGGLE_SPLIT_MAP_VIEWPORT`,
+ SET_MAP_SPLIT_MODE: `${ACTION_PREFIX}SET_MAP_SPLIT_MODE`,
+ SET_SWIPE_COMPARE_PERCENTAGE: `${ACTION_PREFIX}SET_SWIPE_COMPARE_PERCENTAGE`,
// mapStyle
MAP_CONFIG_CHANGE: `${ACTION_PREFIX}MAP_CONFIG_CHANGE`,
diff --git a/src/actions/src/map-state-actions.ts b/src/actions/src/map-state-actions.ts
index 84bbd17cb..daf932ce3 100644
--- a/src/actions/src/map-state-actions.ts
+++ b/src/actions/src/map-state-actions.ts
@@ -4,6 +4,7 @@
import {createAction} from '@reduxjs/toolkit';
import {default as ActionTypes} from './action-types';
import {Bounds, Merge, Viewport} from '@kepler.gl/types';
+import {MapSplitMode} from '@kepler.gl/constants';
export type TogglePerspectiveUpdaterAction = void;
/**
@@ -114,6 +115,46 @@ export const toggleSplitMapViewport: (payload: {
(syncInfo: ToggleSplitMapViewportUpdaterAction['payload']) => ({payload: syncInfo})
);
+export type SetMapSplitModeUpdaterAction = {
+ payload: {
+ mapSplitMode: MapSplitMode;
+ };
+};
+/**
+ * Set map split mode (single, dual, or swipe)
+ * @memberof mapStateActions
+ * @param {Object} payload
+ * @param {MapSplitMode} payload.mapSplitMode The split mode to set
+ * @public
+ */
+export const setMapSplitMode: (payload: {
+ mapSplitMode: MapSplitMode;
+}) => Merge<SetMapSplitModeUpdaterAction, {type: typeof ActionTypes.SET_MAP_SPLIT_MODE}> =
+ createAction(ActionTypes.SET_MAP_SPLIT_MODE, (payload: {mapSplitMode: MapSplitMode}) => ({payload}));
+
+export type SetSwipeComparePercentageUpdaterAction = {
+ payload: {
+ percentage: number;
+ };
+};
+/**
+ * Set the swipe compare divider position
+ * @memberof mapStateActions
+ * @param {Object} payload
+ * @param {number} payload.percentage The percentage position (0-100)
+ * @public
+ */
+export const setSwipeComparePercentage: (payload: {
+ percentage: number;
+}) => Merge<
+ SetSwipeComparePercentageUpdaterAction,
+ {type: typeof ActionTypes.SET_SWIPE_COMPARE_PERCENTAGE}
+> =
+ createAction(
+ ActionTypes.SET_SWIPE_COMPARE_PERCENTAGE,
+ (payload: {percentage: number}) => ({payload})
+ );
+
/**
* This declaration is needed to group actions in docs
*/
diff --git a/src/components/src/common/layout-splitter.tsx b/src/components/src/common/layout-splitter.tsx
new file mode 100644
index 000000000..f1eed6e1f
--- /dev/null
+++ b/src/components/src/common/layout-splitter.tsx
@@ -0,0 +1,264 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {scaleLinear} from 'd3-scale';
+import React, {Component, createRef, ReactElement} from 'react';
+import styled from 'styled-components';
+
+import {observeDimensions, unobserveDimensions} from '@kepler.gl/utils';
+
+export enum LayoutSplitterMode {
+ VERTICAL = 'VERTICAL',
+ HORIZONTAL = 'HORIZONTAL'
+}
+
+export interface VirtualElement {
+ top: number;
+ left: number;
+ bottom: number;
+ right: number;
+}
+
+export interface LayoutSplitterProps {
+ size?: number;
+ color?: string;
+ shadowColor?: string;
+ mode: LayoutSplitterMode;
+ referenceElement: HTMLElement | VirtualElement;
+ renderHandle?: () => ReactElement;
+ percentageSplit: number;
+ resizeThrottleDelay?: number;
+ onMove?: (percentageSplit: number) => void;
+ onRelease?: (percentageSplit: number) => void;
+}
+
+const Layout = styled.div<{mode: LayoutSplitterMode; shadowColor?: string}>(
+ props => `
+ position: absolute;
+ z-index: 3;
+ touch-action: none;
+ & > .splitter {
+ box-shadow: 0 0 2px ${props.shadowColor || 'rgba(0, 0, 0, 0.3)'};
+ transition: box-shadow 0.3s ease;
+ }
+ &:hover > .splitter {
+ box-shadow: 0 0 10px ${props.shadowColor || 'rgba(0, 0, 0, 0.3)'};
+ }
+ ${
+ props.mode === LayoutSplitterMode.VERTICAL
+ ? `width: 20px;
+ margin-left: -10px;
+ height: 100%;
+ top: 0;
+ cursor: ew-resize;`
+ : `width: 100%;
+ height: 20px;
+ margin-top: -10px;
+ left: 0;
+ cursor: ns-resize;`
+ }
+`
+);
+
+type SplitterLineProps = {
+ mode: LayoutSplitterMode;
+ size?: number;
+ color?: React.CSSProperties['color'];
+};
+
+const SplitterLine = styled.div<SplitterLineProps>(
+ props => `
+ position: absolute;
+ background: ${props.color || '#FFFFFF'};
+ ${
+ props.mode === LayoutSplitterMode.VERTICAL
+ ? `left: 50%;
+ transform: translateX(-50%);
+ width: ${props.size}px;
+ height: 100%;
+ `
+ : `top: 50%;
+ transform: translateY(-50%);
+ height: ${props.size}px;
+ width: 100%;
+ `
+ }`
+);
+
+const HandleWrapper = styled.div<{mode: LayoutSplitterMode}>(
+ ({mode}) => `
+ position: absolute;
+ left: 50%;
+ transform: translate(-50%,-50%);
+ ${mode === LayoutSplitterMode.VERTICAL ? 'top: 50%;' : 'left: 50%;'}
+`
+);
+
+const Handle = styled.div`
+ display: flex;
+ width: 36px;
+ height: 36px;
+ align-items: center;
+ justify-content: center;
+ padding: 4px;
+ background-color: ${props => props.theme.panelBackground || '#29323C'};
+ color: ${props => props.theme.textColor || '#FFFFFF'};
+ border: 2px solid #FFFFFF;
+ border-radius: 50%;
+ background-position: center;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
+`;
+
+const ArrowIcon: React.FC<{size?: number; mode: LayoutSplitterMode}> = ({size = 20, mode}) => (
+ <svg width={size} height={size} viewBox="-15 -15 30 30">
+ <g transform={mode === LayoutSplitterMode.HORIZONTAL ? 'rotate(90)' : ''}>
+ <path d="M-15,0 L-5,-6 L-5,6Z" fill="currentColor" />
+ <path d="M15,0 L5,-6 L5,6Z" fill="currentColor" />
+ </g>
+ </svg>
+);
+
+export default class LayoutSplitter extends Component<LayoutSplitterProps> {
+ static defaultProps = {
+ mode: LayoutSplitterMode.VERTICAL,
+ size: 2,
+ resizeThrottleDelay: 50
+ };
+
+ componentDidMount(): void {
+ const {referenceElement, resizeThrottleDelay} = this.props;
+ if (referenceElement instanceof HTMLElement) {
+ observeDimensions(referenceElement, this.handleResize, resizeThrottleDelay);
+ }
+ }
+
+ componentWillUnmount(): void {
+ const {referenceElement} = this.props;
+ if (referenceElement instanceof HTMLElement) {
+ unobserveDimensions(referenceElement);
+ }
+ }
+
+ ref = createRef<HTMLDivElement>();
+ dragging = false;
+
+ getReferenceBoundingBox(): VirtualElement | undefined {
+ const {referenceElement} = this.props;
+ if (referenceElement instanceof HTMLElement) {
+ if (referenceElement.getBoundingClientRect) {
+ return referenceElement.getBoundingClientRect();
+ }
+ return undefined;
+ }
+ return referenceElement as VirtualElement;
+ }
+
+ getNextValue(clientX: number, clientY: number): number {
+ const {mode} = this.props;
+ const bbox = this.getReferenceBoundingBox();
+ if (!bbox) return this.props.percentageSplit;
+
+ const {left, right, top, bottom} = bbox;
+ const scale = scaleLinear().domain([0, 100]).clamp(true);
+
+ if (mode === LayoutSplitterMode.VERTICAL) {
+ scale.range([left, right]);
+ return scale.invert(clientX);
+ } else {
+ scale.range([top, bottom]);
+ return scale.invert(clientY);
+ }
+ }
+
+ handlePointerDown = (evt: React.PointerEvent): void => {
+ evt.stopPropagation();
+ evt.preventDefault();
+ this.dragging = true;
+ (evt.currentTarget as HTMLElement).setPointerCapture(evt.pointerId);
+ };
+
+ handlePointerMove = (evt: React.PointerEvent): void => {
+ if (!this.dragging) return;
+ evt.stopPropagation();
+ evt.preventDefault();
+ const nextValue = this.getNextValue(evt.clientX, evt.clientY);
+ const {percentageSplit, onMove} = this.props;
+ if (nextValue !== percentageSplit && onMove) {
+ onMove(nextValue);
+ }
+ };
+
+ handlePointerUp = (evt: React.PointerEvent): void => {
+ if (!this.dragging) return;
+ evt.stopPropagation();
+ evt.preventDefault();
+ this.dragging = false;
+ (evt.currentTarget as HTMLElement).releasePointerCapture(evt.pointerId);
+
+ const nextValue = this.getNextValue(evt.clientX, evt.clientY);
+ const {percentageSplit, onMove, onRelease} = this.props;
+ if (nextValue !== percentageSplit && onMove) {
+ onMove(nextValue);
+ }
+ if (onRelease) onRelease(nextValue);
+ };
+
+ handleResize = (): void => {
+ this.forceUpdate();
+ };
+
+ renderHandle(): React.ReactNode {
+ const {mode, renderHandle} = this.props;
+ return (
+ <HandleWrapper mode={mode}>
+ {renderHandle ? (
+ renderHandle()
+ ) : (
+ <Handle>
+ <ArrowIcon mode={mode} />
+ </Handle>
+ )}
+ </HandleWrapper>
+ );
+ }
+
+ getPositioningStyle(): {[x: string]: number} {
+ const {mode, percentageSplit} = this.props;
+ const bbox = this.getReferenceBoundingBox();
+ if (!bbox) return {[mode === LayoutSplitterMode.VERTICAL ? 'left' : 'top']: 0};
+
+ const {left, right, top, bottom} = bbox;
+ const scale = scaleLinear().domain([0, 100]).clamp(true);
+
+ if (mode === LayoutSplitterMode.VERTICAL) {
+ scale.range([0, right - left]);
+ } else {
+ scale.range([0, bottom - top]);
+ }
+
+ return {
+ [mode === LayoutSplitterMode.VERTICAL ? 'left' : 'top']: scale(percentageSplit)
+ };
+ }
+
+ render(): React.ReactNode {
+ const {mode, size, color, shadowColor} = this.props;
+ return (
+ <Layout
+ className="layout-splitter"
+ ref={this.ref}
+ mode={mode}
+ shadowColor={shadowColor}
+ style={this.getPositioningStyle()}
+ onPointerDown={this.handlePointerDown}
+ onPointerMove={this.handlePointerMove}
+ onPointerUp={this.handlePointerUp}
+ onPointerCancel={this.handlePointerUp}
+ onClick={e => e.stopPropagation()}
+ >
+ <SplitterLine className="splitter" mode={mode} size={size} color={color} />
+ {this.renderHandle()}
+ </Layout>
+ );
+ }
+}
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index 9d1ccc5f6..cd6404bb1 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -57,6 +57,7 @@ export {
export {default as LayerAnimationControllerFactory} from './layer-animation-controller';
export {Attribution, default as MapContainerFactory} from './map-container';
export {default as MapsLayoutFactory} from './maps-layout';
+export {default as LayoutSplitter, LayoutSplitterMode} from './common/layout-splitter';
export {default as ModalContainerFactory} from './modal-container';
export {default as PlotContainerFactory} from './plot-container';
export {default as SidePanelFactory} from './side-panel';
@@ -151,7 +152,6 @@ export {default as MapStyleSelectorFactory} from './side-panel/map-style-panel/m
// map factories
export {default as CoordinateInfoFactory} from './map/coordinate-info';
export {default as LayerHoverInfoFactory} from './map/layer-hover-info';
-export {default as LayerSelectorPanelFactory} from './map/layer-selector-panel';
export {default as LazyTippy} from './map/lazy-tippy';
export {default as LocalePanelFactory} from './map/locale-panel';
export {default as MapControlFactory} from './map/map-control';
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index 281fa64d7..80530f37e 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -687,7 +687,11 @@ function KeplerGlFactory(
<NotificationPanel {...notificationPanelFields} />
<DndContext visState={visState}>
{!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}
- <MapsLayout className="maps" mapState={this.props.mapState}>
+ <MapsLayout
+ className="maps"
+ mapState={this.props.mapState}
+ onSetSwipeComparePercentage={this.props.mapStateActions.setSwipeComparePercentage}
+ >
{mapContainers}
</MapsLayout>
</DndContext>
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index ce66a7329..e29510be2 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -1376,6 +1376,8 @@ export default function MapContainerFactory(
mapHeight={mapState.height}
setMapControlSettings={uiStateActions.setMapControlSettings}
activeSidePanel={activeSidePanel}
+ splitMaps={this.props.visState.splitMaps}
+ onToggleLayerForMap={visStateActions.toggleLayerForMap}
/>
{isSplitSelector(this.props) && <Droppable containerId={containerId} />}
diff --git a/src/components/src/map/layer-selector-panel.tsx b/src/components/src/map/layer-selector-panel.tsx
deleted file mode 100644
index 589014b3d..000000000
--- a/src/components/src/map/layer-selector-panel.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-// SPDX-License-Identifier: MIT
-// Copyright contributors to the kepler.gl project
-
-import React, {useCallback, useMemo} from 'react';
-import classnames from 'classnames';
-
-import {MapControlButton} from '../common/styled-components';
-import {Layers} from '../common/icons';
-import MapLayerSelector from '../common/map-layer-selector';
-import MapControlTooltipFactory from './map-control-tooltip';
-import MapControlPanelFactory from './map-control-panel';
-import {Layer} from '@kepler.gl/layers';
-import {MapControlItem, MapControls} from '@kepler.gl/types';
-
-LayerSelectorPanelFactory.deps = [MapControlTooltipFactory, MapControlPanelFactory];
-
-export type LayerSelectorPanelProps = {
- onMapToggleLayer: (layerId: string) => void;
- onToggleMapControl: (control: string) => void;
- layers: ReadonlyArray<Layer>;
- layersToRender: {[key: string]: boolean};
- isSplit: boolean;
- mapControls: MapControls;
- readOnly: boolean;
-};
-
-function LayerSelectorPanelFactory(
- MapControlTooltip: ReturnType<typeof MapControlTooltipFactory>,
- MapControlPanel: ReturnType<typeof MapControlPanelFactory>
-) {
- /** @type {import('./layer-selector-panel').LayerSelectorPanelComponent} */
- const LayerSelectorPanel: React.FC<LayerSelectorPanelProps> = ({
- onMapToggleLayer,
- onToggleMapControl,
- layers,
- layersToRender,
- isSplit,
- mapControls,
- readOnly
- }) => {
- const visibleLayers = mapControls?.visibleLayers || ({} as MapControlItem);
- const {active: isActive, show, disableClose} = visibleLayers || {};
-
- const legendLayers = useMemo(
- () =>
- layers
- .filter(({config}) => config.isVisible)
- .map(({id, config}) => ({
- id,
- name: config.label,
- // layer
- isVisible: layersToRender[id]
- })),
- [layers, layersToRender]
- );
-
- const isVisible = useMemo(
- () => isSplit && show && readOnly !== true,
- [isSplit, show, readOnly]
- );
-
- const onToggleMenuPanel = useCallback(
- event => {
- event.preventDefault();
- onToggleMapControl('visibleLayers');
- },
- [onToggleMapControl]
- );
-
- return isVisible ? (
- !isActive ? (
- <MapControlButton
- key={1}
- onClick={onToggleMenuPanel}
- className={classnames('map-control-button', 'toggle-layer', {isActive})}
- data-tip
- data-for="toggle-layer"
- >
- <Layers height="16px" />
- <MapControlTooltip
- id="toggle-layer"
- message={isActive ? 'tooltip.hideLayerPanel' : 'tooltip.showLayerPanel'}
- />
- </MapControlButton>
- ) : (
- <MapControlPanel
- header="header.visibleLayers"
- onClick={onToggleMenuPanel}
- disableClose={disableClose}
- >
- <MapLayerSelector layers={legendLayers} onMapToggleLayer={onMapToggleLayer} />
- </MapControlPanel>
- )
- ) : null;
- };
-
- LayerSelectorPanel.displayName = 'LayerSelectorPanel';
-
- return React.memo(LayerSelectorPanel);
-}
-
-export default LayerSelectorPanelFactory;
diff --git a/src/components/src/map/map-control-panel.tsx b/src/components/src/map/map-control-panel.tsx
index d8fb2d573..73dc30ed5 100644
--- a/src/components/src/map/map-control-panel.tsx
+++ b/src/components/src/map/map-control-panel.tsx
@@ -9,6 +9,7 @@ import {Close, Pin} from '../common/icons';
import Switch from '../common/switch';
import {MapState} from '@kepler.gl/types';
import {ActionHandler, toggleSplitMapViewport} from '@kepler.gl/actions';
+import {MapSplitMode} from '@kepler.gl/constants';
import classNames from 'classnames';
const StyledMapControlPanel = styled.div`
@@ -150,7 +151,7 @@ function MapControlPanelFactory() {
}}
className={classNames('map-control-panel', className)}
>
- {mapState?.isSplit && isViewportUnsyncAllowed ? (
+ {mapState?.isSplit && isViewportUnsyncAllowed && mapState?.mapSplitMode !== MapSplitMode.SWIPE_COMPARE ? (
<StyledMapControlPanelHeaderSplitViewportsTools>
<StyledSBCenterFlexbox style={{paddingBottom: '6px'}}>
<FormattedMessage id="Unlock Viewport" />
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index a2385271d..78407b81b 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -8,7 +8,6 @@ import KeplerGlLogo from '../common/logo';
// factories
import SplitMapButtonFactory from './split-map-button';
import Toggle3dButtonFactory from './toggle-3d-button';
-import LayerSelectorPanelFactory from './layer-selector-panel';
import MapLegendPanelFactory from './map-legend-panel';
import MapDrawPanelFactory from './map-draw-panel';
import LocalePanelFactory from './locale-panel';
@@ -17,6 +16,7 @@ import {Layer} from '@kepler.gl/layers';
import {Editor, LayerVisConfig, MapControls, MapState} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {MapStateActions, UIStateActions} from '@kepler.gl/actions';
+import {getApplicationConfig} from '@kepler.gl/utils';
import AnnotationControlFactory from './annotations/annotation-control';
@@ -53,6 +53,7 @@ export type MapControlProps = {
mapControls: MapControls;
onTogglePerspective: () => void;
onToggleSplitMap: typeof MapStateActions.toggleSplitMap;
+ onSetMapSplitMode?: typeof MapStateActions.setMapSplitMode;
onToggleSplitMapViewport: ({
isViewportSynced,
isZoomLocked
@@ -85,12 +86,13 @@ export type MapControlProps = {
editor: Editor;
actionComponents?: React.ComponentType<any>[];
mapHeight?: number;
+ splitMaps?: {layers: {[key: string]: boolean}}[];
+ onToggleLayerForMap?: (mapIndex: number, layerId: string) => void;
};
MapControlFactory.deps = [
SplitMapButtonFactory,
Toggle3dButtonFactory,
- LayerSelectorPanelFactory,
MapLegendPanelFactory,
MapDrawPanelFactory,
LocalePanelFactory,
@@ -101,7 +103,6 @@ MapControlFactory.deps = [
function MapControlFactory(
SplitMapButton: ReturnType<typeof SplitMapButtonFactory>,
Toggle3dButton: ReturnType<typeof Toggle3dButtonFactory>,
- LayerSelectorPanel: ReturnType<typeof LayerSelectorPanelFactory>,
MapLegendPanel: ReturnType<typeof MapLegendPanelFactory>,
MapDrawPanel: ReturnType<typeof MapDrawPanelFactory>,
LocalePanel: ReturnType<typeof LocalePanelFactory>,
@@ -110,7 +111,6 @@ function MapControlFactory(
) {
const DEFAULT_ACTIONS = [
SplitMapButton,
- LayerSelectorPanel,
Toggle3dButton,
MapDrawPanel,
AnnotationControl,
@@ -135,6 +135,9 @@ function MapControlFactory(
mapIndex,
logoComponent,
mapState,
+ onSetMapSplitMode: getApplicationConfig().enableSwipeMode
+ ? mapStateActions?.setMapSplitMode
+ : undefined,
...restProps
};
return (
diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsx
index 3295a0671..c2f806713 100644
--- a/src/components/src/map/map-legend-panel.tsx
+++ b/src/components/src/map/map-legend-panel.tsx
@@ -19,6 +19,7 @@ import {CSS} from '@dnd-kit/utilities';
import {useMergeRefs} from '@floating-ui/react';
import {ActionHandler, setMapControlSettings, toggleSplitMapViewport} from '@kepler.gl/actions';
+import {MapSplitMode} from '@kepler.gl/constants';
import {Layer} from '@kepler.gl/layers';
import {breakPointValues} from '@kepler.gl/styles';
import {LayerVisConfig, MapControlMapLegend, MapControls, MapState} from '@kepler.gl/types';
@@ -329,6 +330,10 @@ export type MapLegendPanelProps = {
isSidePanelShown: boolean;
activeSidePanel: string | null;
setMapControlSettings: any;
+ isSplit?: boolean;
+ splitMaps?: {layers: {[key: string]: boolean}}[];
+ onToggleLayerForMap?: (mapIndex: number, layerId: string) => void;
+ mapIndex?: number;
};
type MapLegendPanelComponents = {
@@ -360,10 +365,15 @@ const MapLegendPanelComponent = ({
setMapControlSettings,
isViewportUnsyncAllowed = true,
className,
+ isSplit,
+ splitMaps,
+ onToggleLayerForMap,
+ mapIndex,
MapControlTooltip,
MapControlPanel,
MapLegend
}: MapLegendPanelProps & MapLegendPanelComponents) => {
+ const isSwipeMode = mapState?.mapSplitMode === MapSplitMode.SWIPE_COMPARE;
const isSidePanelShown = Boolean(activeSidePanel);
const settings = mapControls?.mapLegend?.settings;
@@ -386,6 +396,13 @@ const MapLegendPanelComponent = ({
[onToggleMapControl]
);
+ if (isSplit && !isSwipeMode && mapIndex !== 0) {
+ return null;
+ }
+ if (isSwipeMode && mapIndex !== 1) {
+ return null;
+ }
+
if (!mapLegend.show) {
return null;
}
@@ -409,6 +426,9 @@ const MapLegendPanelComponent = ({
isExport={isExport}
onLayerVisConfigChange={onLayerVisConfigChange}
onToggleLayerVisibility={onToggleLayerVisibility}
+ isSplit={isSplit}
+ splitMaps={splitMaps}
+ onMapToggleLayer={onToggleLayerForMap}
/>
</MapControlPanel>
) : null;
diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsx
index 4b4b2d372..933d49f2c 100644
--- a/src/components/src/map/map-legend.tsx
+++ b/src/components/src/map/map-legend.tsx
@@ -93,6 +93,37 @@ const StyledVisibilityToggle = styled.div<{$isVisible: boolean}>`
}
`;
+const StyledSplitVisibilityControls = styled.div`
+ display: flex;
+ align-items: center;
+ margin-left: 8px;
+ gap: 4px;
+
+ ${StyledVisibilityToggle} {
+ margin-left: 0;
+ }
+`;
+
+const StyledSplitSeparator = styled.div<{$isVisible: boolean}>`
+ width: 1px;
+ height: 12px;
+ background: ${props => (props.$isVisible ? props.theme.textColor : props.theme.subtextColor)};
+ opacity: 0.3;
+`;
+
+const StyledExpandToggle = styled.div`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ margin-left: 6px;
+ color: ${props => props.theme.textColor};
+ opacity: 0.7;
+
+ &:hover {
+ opacity: 1;
+ }
+`;
+
export const VisualChannelMetric = ({name}) => {
return (
<div className="legend--layer__title">
@@ -321,6 +352,11 @@ export type LayerLegendHeaderProps = {
};
isExport?: boolean;
onToggleLayerVisibility?: (layer: Layer) => void;
+ isSplit?: boolean;
+ splitMaps?: {layers: {[key: string]: boolean}}[];
+ onMapToggleLayer?: (mapIndex: number, layerId: string) => void;
+ isExpanded?: boolean;
+ onToggleExpanded?: () => void;
};
const isRadiusChannel = visualChannel =>
@@ -330,25 +366,69 @@ export function LayerLegendHeaderFactory() {
const LayerLegendHeader: React.FC<LayerLegendHeaderProps> = ({
options,
layer,
- onToggleLayerVisibility
+ isExport,
+ onToggleLayerVisibility,
+ isSplit,
+ splitMaps,
+ onMapToggleLayer,
+ isExpanded,
+ onToggleExpanded
}) => {
const isVisible = layer.config.isVisible;
+
const onToggle = useCallback(() => {
if (onToggleLayerVisibility) {
onToggleLayerVisibility(layer);
}
}, [layer, onToggleLayerVisibility]);
+ const onToggleLeft = useCallback(() => {
+ if (onMapToggleLayer) {
+ onMapToggleLayer(0, layer.id);
+ }
+ }, [layer, onMapToggleLayer]);
+
+ const onToggleRight = useCallback(() => {
+ if (onMapToggleLayer) {
+ onMapToggleLayer(1, layer.id);
+ }
+ }, [layer, onMapToggleLayer]);
+
if (options?.showLayerName === false) {
return null;
}
+ const isLeftVisible =
+ isSplit && splitMaps && splitMaps.length > 1
+ ? isVisible && Boolean(splitMaps[0]?.layers?.[layer.id])
+ : isVisible;
+ const isRightVisible =
+ isSplit && splitMaps && splitMaps.length > 1
+ ? isVisible && Boolean(splitMaps[1]?.layers?.[layer.id])
+ : isVisible;
+ const isAnyVisible = isLeftVisible || isRightVisible;
+
return (
<StyledLegendHeaderRow>
- <div className="legend--layer_name" style={{opacity: isVisible ? 1 : 0.5}}>
+ <div className="legend--layer_name" style={{opacity: isAnyVisible ? 1 : 0.5, flex: 1}}>
{layer.config.label}
</div>
- {onToggleLayerVisibility ? (
+ {onToggleExpanded ? (
+ <StyledExpandToggle onClick={onToggleExpanded}>
+ {isExpanded ? <ArrowDown height="12px" /> : <ArrowRight height="12px" />}
+ </StyledExpandToggle>
+ ) : null}
+ {!isExport && onMapToggleLayer && isSplit && splitMaps && splitMaps.length > 1 ? (
+ <StyledSplitVisibilityControls>
+ <StyledVisibilityToggle $isVisible={isLeftVisible} onClick={onToggleLeft}>
+ {isLeftVisible ? <EyeSeen height="12px" /> : <EyeUnseen height="12px" />}
+ </StyledVisibilityToggle>
+ <StyledSplitSeparator $isVisible={isAnyVisible} />
+ <StyledVisibilityToggle $isVisible={isRightVisible} onClick={onToggleRight}>
+ {isRightVisible ? <EyeSeen height="12px" /> : <EyeUnseen height="12px" />}
+ </StyledVisibilityToggle>
+ </StyledSplitVisibilityControls>
+ ) : !isExport && onToggleLayerVisibility ? (
<StyledVisibilityToggle $isVisible={isVisible} onClick={onToggle}>
{isVisible ? <EyeSeen height="12px" /> : <EyeUnseen height="12px" />}
</StyledVisibilityToggle>
@@ -467,6 +547,9 @@ export type MapLegendProps = {
isExport?: boolean;
onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
onToggleLayerVisibility?: (layer: Layer) => void;
+ onMapToggleLayer?: (mapIndex: number, layerId: string) => void;
+ isSplit?: boolean;
+ splitMaps?: {layers: {[key: string]: boolean}}[];
actionIcons?: MapLegendIcons;
};
@@ -476,6 +559,70 @@ function MapLegendFactory(
LayerLegendHeader: ReturnType<typeof LayerLegendHeaderFactory>,
LayerLegendContent: ReturnType<typeof LayerLegendContentFactory>
) {
+ const LayerLegendItem: React.FC<{
+ layer: Layer;
+ containerW: number;
+ isLast: boolean;
+ isLayerVisible: boolean;
+ isExport?: boolean;
+ options?: {showLayerName?: boolean};
+ mapState?: MapState;
+ disableEdit?: boolean;
+ onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
+ onToggleLayerVisibility?: (layer: Layer) => void;
+ onMapToggleLayer?: (mapIndex: number, layerId: string) => void;
+ isSplit?: boolean;
+ splitMaps?: {layers: {[key: string]: boolean}}[];
+ actionIcons: MapLegendIcons;
+ }> = ({
+ layer,
+ containerW,
+ isLast,
+ isLayerVisible,
+ isExport,
+ options,
+ mapState,
+ disableEdit,
+ onLayerVisConfigChange,
+ onToggleLayerVisibility,
+ onMapToggleLayer,
+ isSplit,
+ splitMaps,
+ actionIcons
+ }) => {
+ const [isExpanded, setIsExpanded] = useState(true);
+ const handleToggleExpanded = useCallback(() => setIsExpanded(prev => !prev), []);
+
+ return (
+ <StyledMapControlLegend className="legend--layer" $last={isLast} width={containerW}>
+ <LayerLegendHeader
+ isExport={isExport}
+ options={options}
+ layer={layer}
+ onToggleLayerVisibility={onToggleLayerVisibility}
+ isSplit={isSplit}
+ splitMaps={splitMaps}
+ onMapToggleLayer={onMapToggleLayer}
+ isExpanded={isExpanded}
+ onToggleExpanded={isExport ? undefined : handleToggleExpanded}
+ />
+ {isExpanded ? (
+ <div style={{opacity: isLayerVisible ? 1 : 0.5}}>
+ <LayerLegendContent
+ containerW={containerW}
+ layer={layer}
+ mapState={mapState}
+ disableEdit={disableEdit}
+ isExport={isExport}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ actionIcons={actionIcons}
+ />
+ </div>
+ ) : null}
+ </StyledMapControlLegend>
+ );
+ };
+
const MapLegend: React.FC<MapLegendProps> = ({
layers = [],
width,
@@ -485,6 +632,9 @@ function MapLegendFactory(
isExport,
onLayerVisConfigChange,
onToggleLayerVisibility,
+ onMapToggleLayer,
+ isSplit,
+ splitMaps,
actionIcons = defaultActionIcons
}) => (
<div className="map-legend">
@@ -494,29 +644,31 @@ function MapLegendFactory(
}
const containerW = width || DIMENSIONS.mapControl.width;
+ const isLayerVisible =
+ isSplit && splitMaps && splitMaps.length > 1
+ ? layer.config.isVisible &&
+ (Boolean(splitMaps[0]?.layers?.[layer.id]) ||
+ Boolean(splitMaps[1]?.layers?.[layer.id]))
+ : layer.config.isVisible;
+
return (
- <StyledMapControlLegend
- className="legend--layer"
- $last={index === layers.length - 1}
- key={index}
- width={containerW}
- >
- <LayerLegendHeader
- isExport={isExport}
- options={options}
- layer={layer}
- onToggleLayerVisibility={onToggleLayerVisibility}
- />
- <LayerLegendContent
- containerW={containerW}
- layer={layer}
- mapState={mapState}
- disableEdit={disableEdit}
- isExport={isExport}
- onLayerVisConfigChange={onLayerVisConfigChange}
- actionIcons={actionIcons}
- />
- </StyledMapControlLegend>
+ <LayerLegendItem
+ key={layer.id}
+ layer={layer}
+ containerW={containerW}
+ isLast={index === layers.length - 1}
+ isLayerVisible={isLayerVisible}
+ isExport={isExport}
+ options={options}
+ mapState={mapState}
+ disableEdit={disableEdit}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ onToggleLayerVisibility={onToggleLayerVisibility}
+ onMapToggleLayer={onMapToggleLayer}
+ isSplit={isSplit}
+ splitMaps={splitMaps}
+ actionIcons={actionIcons}
+ />
);
})}
</div>
diff --git a/src/components/src/map/split-map-button.tsx b/src/components/src/map/split-map-button.tsx
index 1f39337db..73d1342d6 100644
--- a/src/components/src/map/split-map-button.tsx
+++ b/src/components/src/map/split-map-button.tsx
@@ -1,12 +1,14 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {ComponentType, useCallback, useMemo} from 'react';
+import React, {ComponentType, useCallback, useMemo, useState, useRef, useEffect} from 'react';
import classnames from 'classnames';
+import styled from 'styled-components';
import {MapControlButton} from '../common/styled-components';
import {Delete, Split} from '../common/icons';
import MapControlTooltipFactory from './map-control-tooltip';
-import {MapControlItem, MapControls} from '@kepler.gl/types';
+import {MapControlItem, MapControls, MapState} from '@kepler.gl/types';
+import {MapSplitMode} from '@kepler.gl/constants';
SplitMapButtonFactory.deps = [MapControlTooltipFactory];
@@ -19,11 +21,59 @@ export type SplitMapButtonProps = {
isSplit: boolean;
mapIndex: number;
onToggleSplitMap: (index?: number) => void;
+ onSetMapSplitMode?: (payload: {mapSplitMode: MapSplitMode}) => void;
actionIcons: SplitMapButtonIcons;
readOnly: boolean;
mapControls: MapControls;
+ mapState?: MapState;
};
+const StyledSplitModeMenu = styled.div`
+ position: absolute;
+ top: 0;
+ left: -160px;
+ background: ${props => props.theme.dropdownListBgd || '#3A414C'};
+ border-radius: 4px;
+ box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.16);
+ padding: 4px 0;
+ z-index: 1000;
+ min-width: 140px;
+`;
+
+const StyledMenuItem = styled.div<{$active?: boolean}>`
+ padding: 8px 16px;
+ color: ${props =>
+ props.$active
+ ? props.theme.activeColor || '#1FBAD6'
+ : props.theme.textColor || '#A0A7B4'};
+ cursor: pointer;
+ font-size: 12px;
+ font-weight: ${props => (props.$active ? 500 : 400)};
+ &:hover {
+ background: ${props => props.theme.dropdownListHighlightBg || '#4B5464'};
+ color: ${props => props.theme.textColorHl || '#FFFFFF'};
+ }
+`;
+
+const SwipeCompareIcon: React.FC<{height?: string}> = ({height = '18px'}) => (
+ <svg height={height} viewBox="0 0 16 16" fill="currentColor">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 2h12v12H2V2zm1 1v10h10V3H3z"
+ />
+ <path d="M7.5 3v10h1V3z" />
+ <path d="M5 8l2-2v4l-2-2z" />
+ <path d="M11 8l-2-2v4l2-2z" />
+ </svg>
+);
+
+const SPLIT_MODE_OPTIONS = [
+ {id: MapSplitMode.SINGLE_MAP, label: 'Single'},
+ {id: MapSplitMode.DUAL_MAP, label: 'Dual'},
+ {id: MapSplitMode.SWIPE_COMPARE, label: 'Swipe'}
+];
+
function SplitMapButtonFactory(MapControlTooltip) {
const defaultActionIcons = {
delete: Delete,
@@ -35,37 +85,99 @@ function SplitMapButtonFactory(MapControlTooltip) {
isSplit,
mapIndex,
onToggleSplitMap,
+ onSetMapSplitMode,
actionIcons = defaultActionIcons,
mapControls,
- readOnly
+ readOnly,
+ mapState
}) => {
const splitMap = mapControls?.splitMap || ({} as MapControlItem);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const menuRef = useRef<HTMLDivElement>(null);
+
+ const currentMode = mapState?.mapSplitMode || MapSplitMode.SINGLE_MAP;
+
const onClick = useCallback(
event => {
event.preventDefault();
- onToggleSplitMap(isSplit ? mapIndex : undefined);
+ if (onSetMapSplitMode) {
+ setMenuOpen(prev => !prev);
+ } else {
+ onToggleSplitMap(isSplit ? mapIndex : undefined);
+ }
},
- [isSplit, mapIndex, onToggleSplitMap]
+ [isSplit, mapIndex, onToggleSplitMap, onSetMapSplitMode]
);
+ const handleModeSelect = useCallback(
+ (mode: string) => {
+ if (onSetMapSplitMode) {
+ onSetMapSplitMode({mapSplitMode: mode as MapSplitMode});
+ }
+ setMenuOpen(false);
+ },
+ [onSetMapSplitMode]
+ );
+
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
+ setMenuOpen(false);
+ }
+ };
+ if (menuOpen) {
+ document.addEventListener('mousedown', handleClickOutside);
+ }
+ return () => {
+ document.removeEventListener('mousedown', handleClickOutside);
+ };
+ }, [menuOpen]);
+
const isVisible = useMemo(() => splitMap.show && readOnly !== true, [splitMap.show, readOnly]);
if (!splitMap.show) {
return null;
}
return isVisible ? (
- <MapControlTooltip
- id="action-toggle"
- message={isSplit ? 'tooltip.closePanel' : 'tooltip.switchToDualView'}
- >
- <MapControlButton
- active={isSplit}
- onClick={onClick}
- className={classnames('map-control-button', 'split-map', {'close-map': isSplit})}
+ <div style={{position: 'relative'}} ref={menuRef}>
+ <MapControlTooltip
+ id="action-toggle"
+ message={
+ onSetMapSplitMode
+ ? 'tooltip.selectSplitMode'
+ : isSplit
+ ? 'tooltip.closePanel'
+ : 'tooltip.switchToDualView'
+ }
>
- {isSplit ? <actionIcons.delete height="18px" /> : <actionIcons.split height="18px" />}
- </MapControlButton>
- </MapControlTooltip>
+ <MapControlButton
+ active={isSplit}
+ onClick={onClick}
+ className={classnames('map-control-button', 'split-map', {'close-map': isSplit})}
+ >
+ {currentMode === MapSplitMode.SWIPE_COMPARE ? (
+ <SwipeCompareIcon height="18px" />
+ ) : isSplit ? (
+ <actionIcons.delete height="18px" />
+ ) : (
+ <actionIcons.split height="18px" />
+ )}
+ </MapControlButton>
+ </MapControlTooltip>
+ {menuOpen && onSetMapSplitMode && (
+ <StyledSplitModeMenu>
+ {SPLIT_MODE_OPTIONS.map(option => (
+ <StyledMenuItem
+ key={option.id}
+ $active={currentMode === option.id}
+ onClick={() => handleModeSelect(option.id)}
+ >
+ {option.label}
+ </StyledMenuItem>
+ ))}
+ </StyledSplitModeMenu>
+ )}
+ </div>
) : null;
};
diff --git a/src/components/src/maps-layout.tsx b/src/components/src/maps-layout.tsx
index b59e5082d..780839457 100644
--- a/src/components/src/maps-layout.tsx
+++ b/src/components/src/maps-layout.tsx
@@ -2,11 +2,13 @@
// Copyright contributors to the kepler.gl project
import styled from 'styled-components';
-import React from 'react';
+import React, {useRef, useState, useCallback, useEffect} from 'react';
import {MapState} from '@kepler.gl/types';
+import {MapSplitMode} from '@kepler.gl/constants';
import {MapViewStateContextProvider} from './map-view-state-context';
+import LayoutSplitter, {LayoutSplitterMode} from './common/layout-splitter';
const Outer = styled.div`
position: relative;
@@ -15,25 +17,116 @@ const Outer = styled.div`
height: 100%;
`;
+type MapWrapperProps = {
+ $relative?: boolean;
+};
+
+const MapWrapper = styled.div<MapWrapperProps>`
+ position: ${props => (props.$relative ? 'relative' : 'absolute')};
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+`;
+
+const SwipeInputBlock = styled.div`
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ z-index: 2;
+`;
+
MapsLayoutFactory.deps = [];
interface MapsLayoutProps {
mapState: MapState;
className?: string;
children?: React.ReactNode;
+ onSetSwipeComparePercentage?: (payload: {percentage: number}) => void;
}
export default function MapsLayoutFactory(): React.ComponentType<MapsLayoutProps> {
- class MapsLayout extends React.Component<MapsLayoutProps> {
- render() {
- return (
- <Outer className={this.props.className}>
- <MapViewStateContextProvider mapState={this.props.mapState}>
- {this.props.children}
- </MapViewStateContextProvider>
- </Outer>
- );
- }
- }
+ const MapsLayout: React.FC<MapsLayoutProps> = ({
+ mapState,
+ className,
+ children,
+ onSetSwipeComparePercentage
+ }) => {
+ const containerElementRef = useRef<HTMLDivElement>(null);
+ const [containerMounted, setContainerMounted] = useState(false);
+ const childrenArray = React.Children.toArray(children);
+ const isSwipe =
+ childrenArray.length > 1 && mapState.mapSplitMode === MapSplitMode.SWIPE_COMPARE;
+
+ const percentage = mapState.swipeComparePercentage ?? 50;
+ const [internalPercentage, setInternalPercentage] = useState(percentage);
+ const [isSwiping, setSwiping] = useState(false);
+
+ useEffect(() => {
+ if (containerElementRef.current) {
+ setContainerMounted(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!isSwiping) {
+ setInternalPercentage(percentage);
+ }
+ }, [percentage, isSwiping]);
+
+ const handleMove = useCallback((v: number) => {
+ setSwiping(true);
+ setInternalPercentage(v);
+ }, []);
+
+ const handleRelease = useCallback(
+ (v: number) => {
+ setSwiping(false);
+ if (v !== percentage && onSetSwipeComparePercentage) {
+ onSetSwipeComparePercentage({percentage: v});
+ }
+ },
+ [percentage, onSetSwipeComparePercentage]
+ );
+
+ const splitMapStyle = {
+ clipPath: `polygon(0 0, 0 100%, ${internalPercentage}% 100%, ${internalPercentage}% 0)`,
+ overflow: 'hidden' as const
+ };
+
+ return (
+ <Outer className={className} ref={containerElementRef}>
+ <MapViewStateContextProvider mapState={mapState}>
+ {isSwipe ? (
+ <>
+ <MapWrapper key={1}>{childrenArray[1]}</MapWrapper>
+ <MapWrapper key={0} style={splitMapStyle}>
+ {childrenArray[0]}
+ </MapWrapper>
+ {containerMounted && containerElementRef.current && (
+ <>
+ {isSwiping && <SwipeInputBlock />}
+ <LayoutSplitter
+ mode={LayoutSplitterMode.VERTICAL}
+ referenceElement={containerElementRef.current}
+ percentageSplit={internalPercentage}
+ onMove={handleMove}
+ onRelease={handleRelease}
+ />
+ </>
+ )}
+ </>
+ ) : (
+ childrenArray
+ )}
+ </MapViewStateContextProvider>
+ </Outer>
+ );
+ };
+
return MapsLayout;
}
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index ddc7dc3ff..3d32c2c3d 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1344,6 +1344,12 @@ export const MAP_CONTROLS = keyMirror({
aiAssistant: null
});
+export enum MapSplitMode {
+ SINGLE_MAP = 'SINGLE_MAP',
+ DUAL_MAP = 'DUAL_MAP',
+ SWIPE_COMPARE = 'SWIPE_COMPARE'
+}
+
/**
* A multiplier for screen-space width/scale for Arc, Line, Icon and Text layers.
* Required in order to maintain the same appearance after upgrading to deck.gl v8.5.
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 3cd5d6012..1e187cf3e 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -313,6 +313,7 @@ export default {
layerSettings: 'Configuració de capa',
closePanel: 'Tanca panel actual',
switchToDualView: 'Canvia a la vista de mapa dual',
+ selectSplitMode: "Selecciona el mode de vista del mapa",
showLegend: 'mostra llegenda',
disable3DMap: 'Desactiva mapa 3D',
DrawOnMap: 'Dibuixa al mapa',
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index daa26a300..63a45c0a8 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -300,6 +300,7 @@ export default {
layerSettings: '图层设置',
closePanel: '关闭当前面板',
switchToDualView: '切换到双地图视图',
+ selectSplitMode: '选择地图视图模式',
showLegend: '显示图例',
disable3DMap: '禁用 3D 地图',
DrawOnMap: '在地图上绘制',
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index c70e03c65..9e6807792 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -344,6 +344,7 @@ export default {
layerSettings: 'Layer settings',
closePanel: 'Close current panel',
switchToDualView: 'Switch to dual map view',
+ selectSplitMode: 'Select map view mode',
showLegend: 'Show legend',
disable3DMap: 'Disable 3D Map',
DrawOnMap: 'Draw on map',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index 520d41326..cb4928db1 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -314,6 +314,7 @@ export default {
layerSettings: 'Configuración de capa',
closePanel: 'Cerrar el panel actual',
switchToDualView: 'Cambiar a la vista de mapa dual',
+ selectSplitMode: 'Seleccionar modo de vista del mapa',
showLegend: 'Mostrar leyenda',
disable3DMap: 'Desactivar mapa 3D',
DrawOnMap: 'Dibujar en el mapa',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index e80c29d88..cb9fc7579 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -312,6 +312,7 @@ export default {
layerSettings: 'Tason asetukset',
closePanel: 'Sulje paneeli',
switchToDualView: 'Vaihda kaksoiskarrtanäkymään',
+ selectSplitMode: 'Valitse karttanäkymätila',
showLegend: 'Näytä selite',
disable3DMap: 'Poistu 3D-näkymästä',
DrawOnMap: 'Piirrä kartalle',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index fe08f68f9..f3beb3f3f 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -309,6 +309,7 @@ export default {
layerSettings: 'レイヤ設定',
closePanel: 'このパネルを閉じる',
switchToDualView: 'デュアルビューに切り替え',
+ selectSplitMode: 'マップ表示モードを選択',
showLegend: '凡例を表示',
disable3DMap: '3D地図を無効化',
DrawOnMap: '地図上に図形を描画',
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index c6a796914..604b99923 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -314,6 +314,7 @@ export default {
layerSettings: 'Configurações de Camada',
closePanel: 'Fechar painel atual',
switchToDualView: 'Trocar para visualização dupla de mapa',
+ selectSplitMode: 'Selecionar modo de visualização do mapa',
showLegend: 'mostrar legenda',
disable3DMap: 'Desabilitar Mapa 3D',
DrawOnMap: 'Desenhar no mapa',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 8723ece4a..f25214a00 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -311,6 +311,7 @@ export default {
layerSettings: 'Настройки слоя',
closePanel: 'Закрыть текущую панель',
switchToDualView: 'Перейти в режим двойной карты',
+ selectSplitMode: 'Выбрать режим отображения карты',
showLegend: 'Показать легенду',
disable3DMap: 'Отключить 3D Карту',
DrawOnMap: 'Рисовать на карте',
diff --git a/src/reducers/src/combined-updaters.ts b/src/reducers/src/combined-updaters.ts
index 0ccb6e091..70ba7a406 100644
--- a/src/reducers/src/combined-updaters.ts
+++ b/src/reducers/src/combined-updaters.ts
@@ -17,7 +17,8 @@ import {
} from './vis-state-updaters';
import {
receiveMapConfigUpdater as stateMapConfigUpdater,
- toggleSplitMapUpdater as mapStateToggleSplitMapUpdater
+ toggleSplitMapUpdater as mapStateToggleSplitMapUpdater,
+ setMapSplitModeUpdater as mapStateSetMapSplitModeUpdater
} from './map-state-updaters';
import {
mapStyleChangeUpdater,
@@ -33,13 +34,14 @@ import {
MapStyleChangeUpdaterAction,
LayerTypeChangeUpdaterAction,
ToggleSplitMapUpdaterAction,
- ReplaceDataInMapPayload
+ ReplaceDataInMapPayload,
+ MapStateActions
} from '@kepler.gl/actions';
import {VisState} from '@kepler.gl/schemas';
import {Layer} from '@kepler.gl/layers';
-import {isPlainObject} from '@kepler.gl/utils';
+import {isPlainObject, computeSplitMapLayers} from '@kepler.gl/utils';
import {findMapBounds} from './data-utils';
-import {BASE_MAP_COLOR_MODES, OVERLAY_BLENDINGS} from '@kepler.gl/constants';
+import {BASE_MAP_COLOR_MODES, OVERLAY_BLENDINGS, MapSplitMode} from '@kepler.gl/constants';
export type KeplerGlState = {
visState: VisState;
@@ -389,6 +391,64 @@ export const toggleSplitMapUpdater = (
return newState;
};
+/**
+ * Set map split mode updater - coordinates state changes across visState, mapState, and uiState
+ */
+export const setMapSplitModeUpdater = (
+ state: KeplerGlState,
+ action: MapStateActions.SetMapSplitModeUpdaterAction
+): KeplerGlState => {
+ const {mapSplitMode} = action.payload;
+ const prevMode = state.mapState.mapSplitMode;
+
+ if (mapSplitMode === prevMode) {
+ return state;
+ }
+
+ const newMapState = mapStateSetMapSplitModeUpdater(state.mapState, action);
+
+ let newVisState = {...state.visState};
+
+ switch (mapSplitMode) {
+ case MapSplitMode.SINGLE_MAP:
+ newVisState = {
+ ...newVisState,
+ splitMaps: []
+ };
+ break;
+ case MapSplitMode.DUAL_MAP:
+ case MapSplitMode.SWIPE_COMPARE:
+ if (prevMode === MapSplitMode.SINGLE_MAP) {
+ newVisState = {
+ ...newVisState,
+ splitMaps: computeSplitMapLayers(newVisState.layers, {
+ duplicate: mapSplitMode === MapSplitMode.SWIPE_COMPARE
+ })
+ };
+ }
+ break;
+ default:
+ break;
+ }
+
+ let newUiState = uiStateToggleSplitMapUpdater(state.uiState);
+
+ const isSplit = newVisState.splitMaps.length !== 0;
+ const isLegendActive = newUiState.mapControls?.mapLegend?.active;
+ if (isSplit && !isLegendActive) {
+ newUiState = toggleMapControlUpdater(newUiState, {
+ payload: {panelId: 'mapLegend', index: 0}
+ });
+ }
+
+ return {
+ ...state,
+ mapState: newMapState,
+ visState: newVisState,
+ uiState: newUiState
+ };
+};
+
const defaultReplaceDataToMapOptions = {
keepExistingConfig: true,
centerMap: true,
diff --git a/src/reducers/src/composers.ts b/src/reducers/src/composers.ts
index e511a8dd4..7b3c9ec2d 100644
--- a/src/reducers/src/composers.ts
+++ b/src/reducers/src/composers.ts
@@ -14,6 +14,7 @@ const actionHandler = {
[ActionTypes.LAYER_TYPE_CHANGE]: combinedUpdaters.combinedLayerTypeChangeUpdater,
[ActionTypes.LOAD_FILES_SUCCESS]: combinedUpdaters.loadFilesSuccessUpdater,
[ActionTypes.TOGGLE_SPLIT_MAP]: combinedUpdaters.toggleSplitMapUpdater,
+ [ActionTypes.SET_MAP_SPLIT_MODE]: combinedUpdaters.setMapSplitModeUpdater,
[ActionTypes.REPLACE_DATA_IN_MAP]: combinedUpdaters.replaceDataInMapUpdater
};
diff --git a/src/reducers/src/map-state-updaters.ts b/src/reducers/src/map-state-updaters.ts
index fdf357822..350b76539 100644
--- a/src/reducers/src/map-state-updaters.ts
+++ b/src/reducers/src/map-state-updaters.ts
@@ -16,6 +16,7 @@ import {
} from '@kepler.gl/utils';
import {MapStateActions, ReceiveMapConfigPayload, ActionTypes} from '@kepler.gl/actions';
import {MapState, Bounds, Viewport} from '@kepler.gl/types';
+import {MapSplitMode} from '@kepler.gl/constants';
/**
* Updaters for `mapState` reducer. Can be used in your root reducer to directly modify kepler.gl's state.
@@ -95,7 +96,9 @@ export const INITIAL_MAP_STATE: MapState = {
isSplit: false,
isViewportSynced: true,
isZoomLocked: false,
- splitMapViewports: []
+ splitMapViewports: [],
+ mapSplitMode: MapSplitMode.SINGLE_MAP,
+ swipeComparePercentage: 50
};
/* Updaters */
@@ -299,6 +302,7 @@ export const toggleSplitMapUpdater = (state: MapState): MapState => ({
...state,
...getMapDimForSplitMap(!state.isSplit, state),
isSplit: !state.isSplit,
+ mapSplitMode: !state.isSplit ? MapSplitMode.DUAL_MAP : MapSplitMode.SINGLE_MAP,
...(!state.isSplit === false
? {
// if toggling to no longer split (single mode) then reset a few properties
@@ -309,6 +313,84 @@ export const toggleSplitMapUpdater = (state: MapState): MapState => ({
: {})
});
+/**
+ * Set the map split mode (single, dual, or swipe)
+ * @memberof mapStateUpdaters
+ * @public
+ */
+export const setMapSplitModeUpdater = (
+ state: MapState,
+ action: MapStateActions.SetMapSplitModeUpdaterAction
+): MapState => {
+ const {mapSplitMode} = action.payload;
+ const prevMode = state.mapSplitMode;
+
+ if (mapSplitMode === prevMode) {
+ return state;
+ }
+
+ switch (mapSplitMode) {
+ case MapSplitMode.SINGLE_MAP:
+ return {
+ ...state,
+ mapSplitMode,
+ isSplit: false,
+ ...(prevMode === MapSplitMode.DUAL_MAP && {
+ width: state.width * 2
+ }),
+ isViewportSynced: true,
+ isZoomLocked: false,
+ splitMapViewports: []
+ };
+ case MapSplitMode.DUAL_MAP:
+ return {
+ ...state,
+ mapSplitMode,
+ isSplit: true,
+ ...(prevMode === MapSplitMode.SINGLE_MAP && {
+ width: state.width / 2
+ }),
+ ...(prevMode === MapSplitMode.SWIPE_COMPARE && {
+ width: state.width / 2
+ })
+ };
+ case MapSplitMode.SWIPE_COMPARE:
+ return {
+ ...state,
+ mapSplitMode,
+ isSplit: true,
+ ...(prevMode === MapSplitMode.DUAL_MAP && {
+ width: state.width * 2
+ }),
+ isViewportSynced: true,
+ isZoomLocked: false,
+ splitMapViewports: []
+ };
+ default:
+ return state;
+ }
+};
+
+/**
+ * Set the swipe compare percentage
+ * @memberof mapStateUpdaters
+ * @public
+ */
+export const setSwipeComparePercentageUpdater = (
+ state: MapState,
+ action: MapStateActions.SetSwipeComparePercentageUpdaterAction
+): MapState => {
+ const {percentage} = action.payload;
+ const clamped = Math.min(100, Math.max(0, percentage));
+ if (clamped === state.swipeComparePercentage) {
+ return state;
+ }
+ return {
+ ...state,
+ swipeComparePercentage: clamped
+ };
+};
+
/**
* Toggle between locked and unlocked split viewports
* @memberof mapStateUpdaters
@@ -318,6 +400,11 @@ export const toggleSplitMapViewportUpdater = (
state: MapState,
action: MapStateActions.ToggleSplitMapViewportUpdaterAction
) => {
+ // Swipe mode always uses synced viewports
+ if (state.mapSplitMode === MapSplitMode.SWIPE_COMPARE) {
+ return state;
+ }
+
// new map state immediately gets the new, optional payload values for isViewportSynced and/or isZoomLocked
const newMapState = {
...state,
@@ -387,6 +474,11 @@ export function getMapDimForSplitMap(isSplit, state) {
return {};
}
+ // In swipe mode, both maps use full width (overlapping with clip)
+ if (state.mapSplitMode === MapSplitMode.SWIPE_COMPARE) {
+ return {};
+ }
+
const width =
state.isSplit && !isSplit
? // 3. state split: true - isSplit: false
diff --git a/src/reducers/src/map-state.ts b/src/reducers/src/map-state.ts
index e296b718e..64090335f 100644
--- a/src/reducers/src/map-state.ts
+++ b/src/reducers/src/map-state.ts
@@ -16,7 +16,9 @@ const actionHandler = {
[ActionTypes.RECEIVE_MAP_CONFIG]: mapStateUpdaters.receiveMapConfigUpdater,
[ActionTypes.RESET_MAP_CONFIG]: mapStateUpdaters.resetMapConfigUpdater,
[ActionTypes.TOGGLE_SPLIT_MAP]: mapStateUpdaters.toggleSplitMapUpdater,
- [ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT]: mapStateUpdaters.toggleSplitMapViewportUpdater
+ [ActionTypes.TOGGLE_SPLIT_MAP_VIEWPORT]: mapStateUpdaters.toggleSplitMapViewportUpdater,
+ [ActionTypes.SET_MAP_SPLIT_MODE]: mapStateUpdaters.setMapSplitModeUpdater,
+ [ActionTypes.SET_SWIPE_COMPARE_PERCENTAGE]: mapStateUpdaters.setSwipeComparePercentageUpdater
};
/* Reducer */
diff --git a/src/schemas/src/map-state-schema.ts b/src/schemas/src/map-state-schema.ts
index f2c53ecd5..ea9794b2e 100644
--- a/src/schemas/src/map-state-schema.ts
+++ b/src/schemas/src/map-state-schema.ts
@@ -20,7 +20,9 @@ export const propertiesV1 = {
isViewportSynced: null,
isZoomLocked: null,
splitMapViewports: null,
- maxPitch: null
+ maxPitch: null,
+ mapSplitMode: null,
+ swipeComparePercentage: null
};
const mapStateSchema = {
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index 799bba313..1a0110ed1 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -2,6 +2,7 @@
// Copyright contributors to the kepler.gl project
import {Field, Millisecond} from './types';
+import {MapSplitMode} from '@kepler.gl/constants';
type MapViewState = {
latitude: number;
longitude: number;
@@ -38,6 +39,10 @@ export type MapState = {
isZoomLocked: boolean;
/** An array of either 0 or 2 Viewport objects (index 0 for left map; index 1 for right map) */
splitMapViewports: Viewport[];
+ /** The current split map mode (single, dual, swipe) */
+ mapSplitMode: MapSplitMode;
+ /** Swipe compare divider position as a percentage (0-100) */
+ swipeComparePercentage: number;
};
export type Bounds = [number, number, number, number];
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index ba3491401..3dec769c4 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -105,6 +105,9 @@ export type KeplerApplicationConfig = {
/** Whether to show the map navigation control (zoom buttons and compass). Enabled by default. */
enableMapNavigationControl?: boolean;
+
+ /** Whether to enable the swipe compare mode in split map view. Enabled by default. */
+ enableSwipeMode?: boolean;
};
const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
@@ -175,7 +178,9 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableAnnotations: true,
- enableMapNavigationControl: true
+ enableMapNavigationControl: true,
+
+ enableSwipeMode: true
};
const applicationConfig: Required<KeplerApplicationConfig> = DEFAULT_APPLICATION_CONFIG;
diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.js
index 6d0143955..3196d0fd1 100644
--- a/test/browser/components/map/map-control-test.js
+++ b/test/browser/components/map/map-control-test.js
@@ -14,7 +14,6 @@ import {
ToolbarItem,
mapFieldsSelector,
appInjector,
- MapLayerSelector,
MapContainerFactory,
MapLegendFactory,
MapControlFactory,
@@ -34,7 +33,7 @@ import {
StateWFiles
} from '../../../helpers/mock-state';
-const {Cube3d, Split, Legend, DrawPolygon, Layers, Delete} = Icons;
+const {Cube3d, Split, Legend, DrawPolygon, Delete} = Icons;
const MapControl = appInjector.get(MapControlFactory);
const MapContainer = appInjector.get(MapContainerFactory);
const MapLegend = appInjector.get(MapLegendFactory);
@@ -76,7 +75,7 @@ test('MapControlFactory - display all options', t => {
onSetLocale={onSetLocale}
/>
);
- t.equal($.find('.map-control-action').length, 7, 'Should show 7 action panels');
+ t.equal($.find('.map-control-action').length, 6, 'Should show 6 action panels');
t.end();
});
@@ -126,11 +125,10 @@ test('MapControlFactory - display options', t => {
)
});
- // 7 control buttons as legend is opened automatically in split map mode
- t.equal(wrapper.find(MapControlButton).length, 7, 'Should show 7 MapControlButton');
+ // 6 control buttons as legend is opened automatically in split map mode
+ t.equal(wrapper.find(MapControlButton).length, 6, 'Should show 6 MapControlButton');
t.equal(wrapper.find(Split).length, 0, 'Should show 0 split map split button');
t.equal(wrapper.find(Delete).length, 1, 'Should show 1 split map delete button');
- t.equal(wrapper.find(Layers).length, 1, 'Should show 1 Layer button');
// with 0 mapcontrols
wrapper.setProps({
@@ -194,13 +192,13 @@ test('MapControlFactory - click options', t => {
}, 'MapContainer should not fail without props');
// layer selector is not active
- t.equal(wrapper.find(MapControlButton).length, 7, 'Should show 7 MapControlButton');
+ t.equal(wrapper.find(MapControlButton).length, 6, 'Should show 6 MapControlButton');
t.equal(wrapper.find(Delete).length, 1, 'Should show 1 delete split map button');
- // click split Map
+ // click split Map - now opens mode menu since enableSwipeMode is true
wrapper.find('.map-control-button.split-map').at(0).simulate('click');
- t.ok(onToggleSplitMap.calledOnce, 'should call onToggleSplitMap');
- t.deepEqual(onToggleSplitMap.args[0], [0], 'should call onToggleSplitMap with mapindex');
+ // onToggleSplitMap is not called directly when mode menu is available
+ t.notOk(onToggleSplitMap.calledOnce, 'should not call onToggleSplitMap when mode menu is enabled');
// click toggle3d
wrapper.find('.map-control-button.toggle-3d').at(0).simulate('click');
@@ -271,41 +269,6 @@ test('MapControlFactory - show panels', t => {
// show legend
t.equal(wrapper.find(MapLegend).length, 1, 'should render 1 MapLegend');
- // show layer selector
- const toggleLayerForMap = sinon.spy();
- const visStateActions = {
- toggleLayerForMap
- };
- updateState = keplerGlReducerCore(StateWSplitMaps, toggleMapControl('visibleLayers', 1));
- mapContainerProps = mapFieldsSelector(
- mockKeplerPropsWithState({state: updateState, visStateActions})
- );
- wrapper.setProps({
- children: (
- <Provider store={store}>
- <MapViewStateContextProvider mapState={mapContainerProps.mapState}>
- <MapContainer {...mapContainerProps} index={1} />
- </MapViewStateContextProvider>
- </Provider>
- )
- });
-
- // click layer selector
- t.equal(wrapper.find(MapLayerSelector).length, 1, 'should render 1 MapLayerSelector');
-
- t.equal(
- wrapper.find('.map-layer-selector__item').length,
- Object.keys(updateState.visState.splitMaps[1].layers).length,
- 'MapLayerSelector should render correct number of layers'
- );
-
- wrapper.find('input').at(0).simulate('change');
- t.ok(toggleLayerForMap.calledOnce, 'should call toggleLayerForMap');
- t.deepEqual(
- toggleLayerForMap.args[0],
- [1, 'point-0'],
- 'should call toggleLayerForMap with mapIndex and layerid'
- );
// show map draw panel
updateState = keplerGlReducerCore(StateWSplitMaps, toggleMapControl('mapDraw', 1));
mapContainerProps = mapFieldsSelector(mockKeplerPropsWithState({state: updateState}));
diff --git a/test/node/reducers/map-state-test.js b/test/node/reducers/map-state-test.js
index 6a06c93d2..89c0d511c 100644
--- a/test/node/reducers/map-state-test.js
+++ b/test/node/reducers/map-state-test.js
@@ -9,7 +9,9 @@ import {
fitBounds,
toggleSplitMap,
toggleSplitMapViewport,
- receiveMapConfig
+ receiveMapConfig,
+ setMapSplitMode,
+ setSwipeComparePercentage
} from '@kepler.gl/actions';
import {
@@ -433,7 +435,8 @@ test('#mapStateReducer -> SPLIT_MAP: toggle', t => {
const expectedState = {
...INITIAL_MAP_STATE,
isSplit: true,
- width: 400
+ width: 400,
+ mapSplitMode: 'DUAL_MAP'
};
// validate the first split
@@ -523,7 +526,8 @@ test('#mapStateReducer -> SPLIT_MAP: close map at specific point', t => {
const expectedState = {
...INITIAL_MAP_STATE,
isSplit: true,
- width: 400
+ width: 400,
+ mapSplitMode: 'DUAL_MAP'
};
// validate the first split
@@ -642,3 +646,104 @@ test('#mapStateReducer -> TOGGLE_SPLIT_MAP_VIEWPORT', t => {
t.end();
});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: single to swipe', t => {
+ const newState = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'SWIPE_COMPARE'}));
+
+ t.equal(newState.isSplit, true, 'should set isSplit to true');
+ t.equal(newState.mapSplitMode, 'SWIPE_COMPARE', 'should set mapSplitMode to SWIPE_COMPARE');
+ t.equal(newState.swipeComparePercentage, 50, 'should keep default swipe percentage');
+ t.equal(newState.isViewportSynced, true, 'should force viewport sync in swipe mode');
+ t.equal(newState.width, 800, 'should NOT halve width in swipe mode');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: single to dual', t => {
+ const newState = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'DUAL_MAP'}));
+
+ t.equal(newState.isSplit, true, 'should set isSplit to true');
+ t.equal(newState.mapSplitMode, 'DUAL_MAP', 'should set mapSplitMode to DUAL_MAP');
+ t.equal(newState.width, 400, 'should halve width in dual mode');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: swipe to single', t => {
+ let state = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'SWIPE_COMPARE'}));
+ state = reducer(state, setMapSplitMode({mapSplitMode: 'SINGLE_MAP'}));
+
+ t.equal(state.isSplit, false, 'should set isSplit to false');
+ t.equal(state.mapSplitMode, 'SINGLE_MAP', 'should set mapSplitMode to SINGLE_MAP');
+ t.equal(state.width, 800, 'should restore full width');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: dual to swipe', t => {
+ let state = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'DUAL_MAP'}));
+ t.equal(state.width, 400, 'dual mode should halve width');
+
+ state = reducer(state, setMapSplitMode({mapSplitMode: 'SWIPE_COMPARE'}));
+
+ t.equal(state.isSplit, true, 'should remain split');
+ t.equal(state.mapSplitMode, 'SWIPE_COMPARE', 'should switch to SWIPE_COMPARE');
+ t.equal(state.width, 800, 'should restore full width in swipe mode');
+ t.equal(state.isViewportSynced, true, 'should force viewport sync');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: swipe to dual', t => {
+ let state = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'SWIPE_COMPARE'}));
+ state = reducer(state, setMapSplitMode({mapSplitMode: 'DUAL_MAP'}));
+
+ t.equal(state.isSplit, true, 'should remain split');
+ t.equal(state.mapSplitMode, 'DUAL_MAP', 'should switch to DUAL_MAP');
+ t.equal(state.width, 400, 'should halve width in dual mode');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_MAP_SPLIT_MODE: same mode is no-op', t => {
+ const state = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'SINGLE_MAP'}));
+
+ t.equal(state, INITIAL_MAP_STATE, 'should return same state reference when mode unchanged');
+
+ t.end();
+});
+
+test('#mapStateReducer -> SET_SWIPE_COMPARE_PERCENTAGE', t => {
+ let state = reducer(INITIAL_MAP_STATE, setSwipeComparePercentage({percentage: 30}));
+
+ t.equal(state.swipeComparePercentage, 30, 'should update swipe percentage');
+
+ // same value is no-op
+ const state2 = reducer(state, setSwipeComparePercentage({percentage: 30}));
+ t.equal(state2, state, 'should return same state reference when percentage unchanged');
+
+ // clamps to 0
+ state = reducer(INITIAL_MAP_STATE, setSwipeComparePercentage({percentage: -10}));
+ t.equal(state.swipeComparePercentage, 0, 'should clamp negative values to 0');
+
+ // clamps to 100
+ state = reducer(INITIAL_MAP_STATE, setSwipeComparePercentage({percentage: 150}));
+ t.equal(state.swipeComparePercentage, 100, 'should clamp values above 100 to 100');
+
+ t.end();
+});
+
+test('#mapStateReducer -> toggleSplitMapViewport in SWIPE_COMPARE mode', t => {
+ let state = reducer(INITIAL_MAP_STATE, setMapSplitMode({mapSplitMode: 'SWIPE_COMPARE'}));
+
+ const stateBeforeToggle = state;
+ state = reducer(state, toggleSplitMapViewport({isViewportSynced: false}));
+
+ t.equal(
+ state,
+ stateBeforeToggle,
+ 'should not allow unsyncing viewports in swipe mode'
+ );
+
+ t.end();
+});
diff --git a/test/node/schemas/map-state-schema-test.js b/test/node/schemas/map-state-schema-test.js
index 9dbf0a659..5a4cf4cd9 100644
--- a/test/node/schemas/map-state-schema-test.js
+++ b/test/node/schemas/map-state-schema-test.js
@@ -27,9 +27,11 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {
'isViewportSynced',
'isZoomLocked',
'splitMapViewports',
- 'maxPitch'
+ 'maxPitch',
+ 'mapSplitMode',
+ 'swipeComparePercentage'
],
- 'mapState should have all 6 entries'
+ 'mapState should have all 12 entries'
);
const expected = {
@@ -43,7 +45,9 @@ test('#mapStateSchema -> v1 -> save load mapState', t => {
isViewportSynced: true,
isZoomLocked: false,
splitMapViewports: [],
- maxPitch: undefined
+ maxPitch: undefined,
+ mapSplitMode: 'SINGLE_MAP',
+ swipeComparePercentage: 50
};
t.deepEqual(msToSave, expected, 'save mapState should be current');