Skip to content

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

[Feat] Duplicate layer and add layer from config (#1401)

Shan He9e5bfdca2951
diff --git a/src/actions/vis-state-actions.d.ts b/src/actions/vis-state-actions.d.ts
index 3438111cf..3283042f7 100644
--- a/src/actions/vis-state-actions.d.ts
+++ b/src/actions/vis-state-actions.d.ts
@@ -156,10 +156,10 @@ export function addFilter(
): Merge<AddFilterUpdaterAction, {type: ActionTypes.ADD_FILTER}>;
export type AddLayerUpdaterAction = {
- props: object;
+ config: object;
};
export function addLayer(
- props: object
+ config: object
): Merge<AddLayerUpdaterAction, {type: ActionTypes.ADD_LAYER}>;
export type ReorderLayerUpdaterAction = {
@@ -183,6 +183,13 @@ export function removeLayer(
idx: number
): Merge<RemoveLayerUpdaterAction, {type: ActionTypes.REMOVE_LAYER}>;
+export type DuplicateLayerUpdaterAction = {
+ idx: number;
+};
+export function duplicateLayer(
+ idx: number
+): Merge<DuplicateLayerUpdaterAction, {type: ActionTypes.DUPLICATE_LAYER}>;
+
export type RemoveDatasetUpdaterAction = {
dataId: string;
};
diff --git a/src/actions/vis-state-actions.js b/src/actions/vis-state-actions.js
index 5bbcaa9ba..d21f19cf2 100644
--- a/src/actions/vis-state-actions.js
+++ b/src/actions/vis-state-actions.js
@@ -231,15 +231,15 @@ export function addFilter(dataId) {
/**
* Add a new layer
* @memberof visStateActions
- * @param props - new layer props
+ * @param config - new layer config
* @returns action
* @type {typeof import('./vis-state-actions').addLayer}
* @public
*/
-export function addLayer(props) {
+export function addLayer(config) {
return {
type: ActionTypes.ADD_LAYER,
- props
+ config
};
}
@@ -293,6 +293,21 @@ export function removeLayer(idx) {
};
}
+/**
+ * Duplicate a layer
+ * @memberof visStateActions
+ * @param idx idx of layer to be duplicated
+ * @returns action
+ * @type {typeof import('./vis-state-actions').duplicateLayer}
+ * @public
+ */
+export function duplicateLayer(idx) {
+ return {
+ type: ActionTypes.DUPLICATE_LAYER,
+ idx
+ };
+}
+
/**
* Remove a dataset and all layers, filters, tooltip configs that based on it
* @memberof visStateActions
diff --git a/src/components/common/icons/copy.js b/src/components/common/icons/copy.js
new file mode 100644
index 000000000..67364d181
--- /dev/null
+++ b/src/components/common/icons/copy.js
@@ -0,0 +1,44 @@
+// Copyright (c) 2020 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import React, {Component} from 'react';
+import PropTypes from 'prop-types';
+import Base from './base';
+
+export default class Copy extends Component {
+ static propTypes = {
+ /** Set the height of the icon, ex. '16px' */
+ height: PropTypes.string
+ };
+
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-copy'
+ };
+
+ render() {
+ return (
+ <Base viewBox="0 0 64 64" {...this.props}>
+ <path d="M37.2402913,45.4271845 L37.2402913,53.2402913 L9.66990291,53.2402913 L9.66990291,25.6699029 L17.4830097,25.6699029 L17.4830097,21 L8.59223301,21 C6.61650485,21 5,22.6165049 5,24.592233 L5,54.407767 C5,56.3834951 6.61650485,58 8.59223301,58 L38.407767,58 C40.3834951,58 42,56.3834951 42,54.407767 L42,45.5169903 L37.2402913,45.5169903 L37.2402913,45.4271845 Z" />
+ <path d="M52.407767,7 L22.592233,7 C20.6165049,7 19,8.61650485 19,10.592233 L19,40.407767 C19,42.3834951 20.6165049,44 22.592233,44 L52.407767,44 C54.3834951,44 56,42.3834951 56,40.407767 L56,10.592233 C56,8.61650485 54.3834951,7 52.407767,7 Z M51.3300971,39.2402913 L23.7597087,39.2402913 L23.7597087,11.6699029 L51.4199029,11.6699029 L51.4199029,39.2402913 L51.3300971,39.2402913 Z" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/common/icons/index.js b/src/components/common/icons/index.js
index 9ff905fff..b95212559 100644
--- a/src/components/common/icons/index.js
+++ b/src/components/common/icons/index.js
@@ -35,6 +35,7 @@ export {default as Checkmark} from './checkmark';
export {default as Clipboard} from './clipboard';
export {default as Clock} from './clock';
export {default as Close} from './close';
+export {default as Copy} from './copy';
export {default as Crosshairs} from './crosshairs';
export {default as Cube3d} from './cube-3d';
export {default as CursorClick} from './cursor-click';
diff --git a/src/components/side-panel.js b/src/components/side-panel.js
index ba5925738..ef45f2c5e 100644
--- a/src/components/side-panel.js
+++ b/src/components/side-panel.js
@@ -204,6 +204,7 @@ export default function SidePanelFactory(
showDatasetTable: this._showDatasetTable,
showAddDataModal: this._showAddDataModal,
removeLayer: visStateActions.removeLayer,
+ duplicateLayer: visStateActions.duplicateLayer,
removeDataset: this._removeDataset,
openModal: uiStateActions.toggleModal
};
diff --git a/src/components/side-panel/layer-manager.js b/src/components/side-panel/layer-manager.js
index 8704269a1..1f020aef2 100644
--- a/src/components/side-panel/layer-manager.js
+++ b/src/components/side-panel/layer-manager.js
@@ -149,6 +149,7 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
layerVisConfigChange: PropTypes.func.isRequired,
openModal: PropTypes.func.isRequired,
removeLayer: PropTypes.func.isRequired,
+ duplicateLayer: PropTypes.func.isRequired,
removeDataset: PropTypes.func.isRequired,
showDatasetTable: PropTypes.func.isRequired,
updateLayerBlending: PropTypes.func.isRequired,
@@ -205,7 +206,8 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
layerTypeChange: this.props.layerTypeChange,
layerVisConfigChange: this.props.layerVisConfigChange,
layerTextLabelChange: this.props.layerTextLabelChange,
- removeLayer: this.props.removeLayer
+ removeLayer: this.props.removeLayer,
+ duplicateLayer: this.props.duplicateLayer
};
const panelProps = {
diff --git a/src/components/side-panel/layer-panel/layer-panel-header.js b/src/components/side-panel/layer-panel/layer-panel-header.js
index 68b64c946..6aba2c471 100644
--- a/src/components/side-panel/layer-panel/layer-panel-header.js
+++ b/src/components/side-panel/layer-panel/layer-panel-header.js
@@ -24,7 +24,7 @@ import classnames from 'classnames';
import styled from 'styled-components';
import {SortableHandle} from 'react-sortable-hoc';
import PanelHeaderActionFactory from 'components/side-panel/panel-header-action';
-import {ArrowDown, EyeSeen, EyeUnseen, Trash, VertDots} from 'components/common/icons';
+import {Copy, ArrowDown, EyeSeen, EyeUnseen, Trash, VertDots} from 'components/common/icons';
import {InlineInput, StyledPanelHeader} from 'components/common/styled-components';
import {FormattedMessage} from 'localization';
@@ -37,6 +37,7 @@ const propTypes = {
onUpdateLayerLabel: PropTypes.func.isRequired,
onToggleEnableConfig: PropTypes.func.isRequired,
onRemoveLayer: PropTypes.func.isRequired,
+ onDuplicateLayer: PropTypes.func.isRequired,
isConfigActive: PropTypes.bool.isRequired,
// optional
@@ -140,7 +141,8 @@ const defaultActionIcons = {
remove: Trash,
visible: EyeSeen,
hidden: EyeUnseen,
- enableConfig: ArrowDown
+ enableConfig: ArrowDown,
+ duplicate: Copy
};
function LayerPanelHeaderFactory(LayerTitleSection, PanelHeaderAction) {
const LayerPanelHeader = ({
@@ -154,6 +156,7 @@ function LayerPanelHeaderFactory(LayerTitleSection, PanelHeaderAction) {
onToggleVisibility,
onUpdateLayerLabel,
onToggleEnableConfig,
+ onDuplicateLayer,
onRemoveLayer,
showRemoveLayer,
actionIcons = defaultActionIcons
@@ -203,6 +206,13 @@ function LayerPanelHeaderFactory(LayerTitleSection, PanelHeaderAction) {
onClick={onToggleVisibility}
IconComponent={isVisible ? actionIcons.visible : actionIcons.hidden}
/>
+ <PanelHeaderAction
+ className="layer__duplicate"
+ id={layerId}
+ tooltip={'tooltip.duplicateLayer'}
+ onClick={onDuplicateLayer}
+ IconComponent={actionIcons.duplicate}
+ />
<PanelHeaderAction
className={classnames('layer__enable-config ', {
'is-open': isOpen
diff --git a/src/components/side-panel/layer-panel/layer-panel.js b/src/components/side-panel/layer-panel/layer-panel.js
index ecfc366d2..30bc282ae 100644
--- a/src/components/side-panel/layer-panel/layer-panel.js
+++ b/src/components/side-panel/layer-panel/layer-panel.js
@@ -48,6 +48,7 @@ function LayerPanelFactory(LayerConfigurator, LayerPanelHeader) {
layerTypeChange: PropTypes.func.isRequired,
openModal: PropTypes.func.isRequired,
removeLayer: PropTypes.func.isRequired,
+ duplicateLayer: PropTypes.func.isRequired,
onCloseConfig: PropTypes.func,
layerTypeOptions: PropTypes.arrayOf(PropTypes.any),
layerVisConfigChange: PropTypes.func.isRequired,
@@ -106,6 +107,11 @@ function LayerPanelFactory(LayerConfigurator, LayerPanelHeader) {
this.props.removeLayer(this.props.idx);
};
+ _duplicateLayer = e => {
+ e.stopPropagation();
+ this.props.duplicateLayer(this.props.idx);
+ };
+
render() {
const {layer, datasets, layerTypeOptions} = this.props;
const {config} = layer;
@@ -130,6 +136,7 @@ function LayerPanelFactory(LayerConfigurator, LayerPanelHeader) {
onToggleVisibility={this._toggleVisibility}
onUpdateLayerLabel={this._updateLayerLabel}
onRemoveLayer={this._removeLayer}
+ onDuplicateLayer={this._duplicateLayer}
/>
{isConfigActive && (
<LayerConfigurator
diff --git a/src/constants/action-types.d.ts b/src/constants/action-types.d.ts
index 24a991589..3299b98ab 100644
--- a/src/constants/action-types.d.ts
+++ b/src/constants/action-types.d.ts
@@ -20,6 +20,7 @@ export type ActionType = {
MOUSE_MOVE: string;
REMOVE_FILTER: string;
REMOVE_LAYER: string;
+ DUPLICATE_LAYER: string;
REMOVE_DATASET: string;
REORDER_LAYER: string;
SET_FILTER: string;
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index 31c341429..cee62b2b2 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -60,6 +60,7 @@ const ActionTypes = {
ADD_DATA: `${ACTION_PREFIX}ADD_DATA`,
ADD_FILTER: `${ACTION_PREFIX}ADD_FILTER`,
ADD_LAYER: `${ACTION_PREFIX}ADD_LAYER`,
+ DUPLICATE_LAYER: `${ACTION_PREFIX}DUPLICATE_LAYER`,
INTERACTION_CONFIG_CHANGE: `${ACTION_PREFIX}INTERACTION_CONFIG_CHANGE`,
LAYER_CONFIG_CHANGE: `${ACTION_PREFIX}LAYER_CONFIG_CHANGE`,
LAYER_VISUAL_CHANNEL_CHANGE: `${ACTION_PREFIX}LAYER_VISUAL_CHANNEL_CHANGE`,
diff --git a/src/layers/base-layer.js b/src/layers/base-layer.js
index 13546d8fd..6c8948ff7 100644
--- a/src/layers/base-layer.js
+++ b/src/layers/base-layer.js
@@ -58,6 +58,8 @@ import {hexToRgb, getColorGroupByName, reverseColorRange} from 'utils/color-util
* Approx. number of points to sample in a large data set
* @type {number}
*/
+export const LAYER_ID_LENGTH = 6;
+
const MAX_SAMPLE_SIZE = 5000;
const defaultDomain = [0, 1];
const dataFilterExtension = new DataFilterExtension({filterSize: MAX_GPU_FILTERS});
@@ -86,7 +88,7 @@ const defaultGetFieldValue = (field, d) => field.valueAccessor(d);
/** @type {LayerClass} */
class Layer {
constructor(props = {}) {
- this.id = props.id || generateHashId(6);
+ this.id = props.id || generateHashId(LAYER_ID_LENGTH);
// meta
this.meta = {};
diff --git a/src/layers/index.d.ts b/src/layers/index.d.ts
index 4bfa120c5..3827723ad 100644
--- a/src/layers/index.d.ts
+++ b/src/layers/index.d.ts
@@ -105,3 +105,4 @@ export type LayerClassesType = {
export const LayerClasses: LayerClassesType;
export type OVERLAY_TYPE = {[key: string]: string}
+export const LAYER_ID_LENGTH: number;
diff --git a/src/localization/en.js b/src/localization/en.js
index c7a0e5014..51245fac3 100644
--- a/src/localization/en.js
+++ b/src/localization/en.js
@@ -190,6 +190,7 @@ export default {
hide: 'hide',
show: 'show',
removeLayer: 'Remove layer',
+ duplicateLayer: 'Duplicate layer',
layerSettings: 'Layer settings',
closePanel: 'Close current panel',
switchToDualView: 'Switch to dual map view',
diff --git a/src/reducers/vis-state-merger.d.ts b/src/reducers/vis-state-merger.d.ts
index 0b40527d7..c19743254 100644
--- a/src/reducers/vis-state-merger.d.ts
+++ b/src/reducers/vis-state-merger.d.ts
@@ -70,6 +70,9 @@ export function validateColumn(
allFields: Dataset['fields']
): boolean;
+export function createLayerFromConfig(state: VisState, layerConfig: any): Layer;
+export function serializeLayer(Layer): ParsedLayer
+
export type VisStateMergers = Merger[];
export const VIS_STATE_MERGERS: VisStateMergers;
diff --git a/src/reducers/vis-state-merger.js b/src/reducers/vis-state-merger.js
index 1da05858e..13dfc453e 100644
--- a/src/reducers/vis-state-merger.js
+++ b/src/reducers/vis-state-merger.js
@@ -27,6 +27,7 @@ import {applyFiltersToDatasets, validateFiltersUpdateDatasets} from 'utils/filte
import {getInitialMapLayersForSplitMap} from 'utils/split-map-utils';
import {resetFilterGpuMode, assignGpuChannels} from 'utils/gpu-filter-utils';
import {LAYER_BLENDINGS} from 'constants/default-settings';
+import {CURRENT_VERSION, visStateSchema} from 'schemas';
/**
* Merge loaded filters with current state, if no fields or data are loaded
@@ -63,6 +64,31 @@ export function mergeFilters(state, filtersToMerge) {
};
}
+export function createLayerFromConfig(state, layerConfig) {
+ // first validate config against dataset
+ const {validated, failed} = validateLayersByDatasets(state.datasets, state.layerClasses, [
+ layerConfig
+ ]);
+
+ if (failed.length || !validated.length) {
+ // failed
+ return null;
+ }
+
+ const newLayer = validated[0];
+ newLayer.updateLayerDomain(state.datasets);
+ return newLayer;
+}
+
+export function serializeLayer(newLayer) {
+ const savedVisState = visStateSchema[CURRENT_VERSION].save({
+ layers: [newLayer],
+ layerOrder: [0]
+ }).visState;
+ const loadedLayer = visStateSchema[CURRENT_VERSION].load(savedVisState).visState.layers[0];
+ return loadedLayer;
+}
+
/**
* Merge layers from de-serialized state, if no fields or data are loaded
* save it for later
@@ -410,8 +436,9 @@ export function validateSavedVisualChannels(fields, newLayer, savedLayer) {
};
if (Object.keys(foundChannel).length) {
newLayer.updateLayerConfig(foundChannel);
- newLayer.validateVisualChannel(key);
}
+
+ newLayer.validateVisualChannel(key);
}
});
return newLayer;
diff --git a/src/reducers/vis-state-updaters.d.ts b/src/reducers/vis-state-updaters.d.ts
index 8a573e181..f51afe945 100644
--- a/src/reducers/vis-state-updaters.d.ts
+++ b/src/reducers/vis-state-updaters.d.ts
@@ -344,6 +344,10 @@ export function removeLayerUpdater(
state: VisState,
action: VisStateActions.RemoveLayerUpdaterAction
): VisState;
+export function duplicateLayerUpdater(
+ state: VisState,
+ action: VisStateActions.DuplicateLayerUpdaterAction
+): VisState;
export function removeDatasetUpdater(
state: VisState,
action: VisStateActions.RemoveDatasetUpdaterAction
diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.js
index 930f6c638..ebad8014d 100644
--- a/src/reducers/vis-state-updaters.js
+++ b/src/reducers/vis-state-updaters.js
@@ -56,11 +56,17 @@ import {
import {assignGpuChannel, setFilterGpuMode} from 'utils/gpu-filter-utils';
import {createNewDataEntry} from 'utils/dataset-utils';
import {sortDatasetByColumn} from 'utils/table-utils/kepler-table';
-import {set, toArray} from 'utils/utils';
+import {set, toArray, arrayInsert, generateHashId} from 'utils/utils';
import {calculateLayerData, findDefaultLayer} from 'utils/layer-utils';
-import {isValidMerger, VIS_STATE_MERGERS, validateLayerWithData} from './vis-state-merger';
+import {
+ isValidMerger,
+ VIS_STATE_MERGERS,
+ validateLayerWithData,
+ createLayerFromConfig,
+ serializeLayer
+} from './vis-state-merger';
import {
addNewLayersToSplitMap,
@@ -68,13 +74,13 @@ import {
removeLayerFromSplitMaps
} from 'utils/split-map-utils';
-import {Layer, LayerClasses} from 'layers';
+import {Layer, LayerClasses, LAYER_ID_LENGTH} from 'layers';
import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';
import {EDITOR_MODES, SORT_ORDER} from 'constants/default-settings';
import {pick_, merge_} from './composer-helpers';
import {processFileContent} from 'actions/vis-state-actions';
-import KeplerGLSchema, {CURRENT_VERSION, visStateSchema} from 'schemas';
+import KeplerGLSchema from 'schemas';
// type imports
/** @typedef {import('./vis-state-updaters').Field} Field */
@@ -364,18 +370,10 @@ export function layerTextLabelChangeUpdater(state, action) {
}
function validateExistingLayerWithData(dataset, layerClasses, layer) {
- let newLayer = layer;
-
- const savedVisState = visStateSchema[CURRENT_VERSION].save({
- layers: [newLayer],
- layerOrder: [0]
- }).visState;
- const loadedLayer = visStateSchema[CURRENT_VERSION].load(savedVisState).visState.layers[0];
- newLayer = validateLayerWithData(dataset, loadedLayer, layerClasses, {
+ const loadedLayer = serializeLayer(layer);
+ return validateLayerWithData(dataset, loadedLayer, layerClasses, {
allowEmptyColumn: true
});
-
- return newLayer;
}
/**
@@ -396,10 +394,16 @@ export function layerDataIdChangeUpdater(state, action) {
let newLayer = oldLayer.updateLayerConfig({dataId});
// this may happen when a layer is new (type: null and no columns) but it's not ready to be saved
if (newLayer.isValidToSave()) {
- newLayer = validateExistingLayerWithData(state.datasets[dataId], state.layerClasses, newLayer);
+ const validated = validateExistingLayerWithData(
+ state.datasets[dataId],
+ state.layerClasses,
+ newLayer
+ );
// if cant validate it with data create a new one
- if (!newLayer) {
+ if (!validated) {
newLayer = new state.layerClasses[oldLayer.type]({dataId, id: oldLayer.id});
+ } else {
+ newLayer = validated;
}
}
@@ -893,18 +897,35 @@ export const removeFilterUpdater = (state, action) => {
* @public
*/
export const addLayerUpdater = (state, action) => {
- const defaultDataset = Object.keys(state.datasets)[0];
- const newLayer = new Layer({
- isVisible: true,
- isConfigActive: true,
- dataId: defaultDataset,
- ...action.props
- });
+ let newLayer;
+ let newLayerData;
+ if (action.config) {
+ newLayer = createLayerFromConfig(state, action.config);
+ if (!newLayer) {
+ Console.warn(
+ 'Failed to create layer from config, it usually means the config is not be in correct format',
+ action.config
+ );
+ return state;
+ }
+ const result = calculateLayerData(newLayer, state);
+ newLayer = result.layer;
+ newLayerData = result.layerData;
+ } else {
+ // create an empty layer with the first available dataset
+ const defaultDataset = Object.keys(state.datasets)[0];
+ newLayer = new Layer({
+ isVisible: true,
+ isConfigActive: true,
+ dataId: defaultDataset
+ });
+ newLayerData = {};
+ }
return {
...state,
layers: [...state.layers, newLayer],
- layerData: [...state.layerData, {}],
+ layerData: [...state.layerData, newLayerData],
layerOrder: [...state.layerOrder, state.layerOrder.length],
splitMaps: addNewLayersToSplitMap(state.splitMaps, newLayer)
};
@@ -935,6 +956,57 @@ export const removeLayerUpdater = (state, {idx}) => {
return updateAnimationDomain(newState);
};
+/**
+ * duplicate layer
+ * @memberof visStateUpdaters
+ * @type {typeof import('./vis-state-updaters').duplicateLayerUpdater}
+ * @public
+ */
+export const duplicateLayerUpdater = (state, {idx}) => {
+ const {layers} = state;
+ const original = state.layers[idx];
+ const originalLayerOrderIdx = state.layerOrder.findIndex(i => i === idx);
+
+ if (!original) {
+ Console.warn(`layer.${idx} is undefined`);
+ return state;
+ }
+ let newLabel = `Copy of ${original.config.label}`;
+ let postfix = 0;
+ // eslint-disable-next-line no-loop-func
+ while (layers.find(l => l.config.label === newLabel)) {
+ newLabel = `Copy of ${original.config.label} ${++postfix}`;
+ }
+
+ // collect layer config from original
+ const loadedLayer = serializeLayer(original);
+
+ // assign new id and label to copied layer
+ if (!loadedLayer.config) {
+ return state;
+ }
+ loadedLayer.config.label = newLabel;
+ loadedLayer.id = generateHashId(LAYER_ID_LENGTH);
+
+ // add layer to state
+ let nextState = addLayerUpdater(state, {config: loadedLayer});
+
+ // new added layer are at the end, move it to be on top of original layer
+ const newLayerOrderIdx = nextState.layerOrder.length - 1;
+ const newLayerOrder = arrayInsert(
+ nextState.layerOrder.slice(0, newLayerOrderIdx),
+ originalLayerOrderIdx,
+ newLayerOrderIdx
+ );
+
+ nextState = {
+ ...nextState,
+ layerOrder: newLayerOrder
+ };
+
+ return updateAnimationDomain(nextState);
+};
+
/**
* Reorder layer
* @memberof visStateUpdaters
diff --git a/src/reducers/vis-state.js b/src/reducers/vis-state.js
index ccfbf86e3..343fb2138 100644
--- a/src/reducers/vis-state.js
+++ b/src/reducers/vis-state.js
@@ -31,6 +31,8 @@ const actionHandler = {
[ActionTypes.ADD_LAYER]: visStateUpdaters.addLayerUpdater,
+ [ActionTypes.DUPLICATE_LAYER]: visStateUpdaters.duplicateLayerUpdater,
+
[ActionTypes.ENLARGE_FILTER]: visStateUpdaters.enlargeFilterUpdater,
[ActionTypes.INTERACTION_CONFIG_CHANGE]: visStateUpdaters.interactionConfigChangeUpdater,
diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.js
index fdd5bae4c..e059e0c06 100644
--- a/test/helpers/mock-state.js
+++ b/test/helpers/mock-state.js
@@ -308,9 +308,6 @@ function mockStateWithLayerDimensions(state) {
const textLabelPayload1 = [layer0, 0, 'field', textLabelField];
const textLabelPayload2 = [layer0, 0, 'color', [255, 0, 0]];
- // layers = [ 'point', 'geojson', 'hexagon' ]
- const reorderPayload = [[2, 0, 1]];
-
const prepareState = applyActions(keplerGlReducer, initialState, [
// change colorField
{
@@ -325,39 +322,30 @@ function mockStateWithLayerDimensions(state) {
{action: VisStateActions.layerTextLabelChange, payload: textLabelPayload1},
{action: VisStateActions.layerTextLabelChange, payload: textLabelPayload2},
- // add layer
+ // add layer from config
{
action: VisStateActions.addLayer,
- payload: [{id: 'hexagon-2', color: [2, 2, 2]}]
+ payload: [
+ {
+ id: 'hexagon-2',
+ type: 'hexagon',
+ config: {
+ color: [2, 2, 2],
+ isVisible: true,
+ dataId: testCsvDataId,
+ columns: {
+ lat: 'gps_data.lat',
+ lng: 'gps_data.lng'
+ }
+ }
+ }
+ ]
}
]);
- const newLayer = prepareState.visState.layers[2];
-
- // set new layer to hexagon
- const updateState = applyActions(keplerGlReducer, prepareState, [
- {action: VisStateActions.layerTypeChange, payload: [newLayer, 'hexagon']}
- ]);
-
- const hexagonLayer = updateState.visState.layers[2];
- hexagonLayer.id = 'hexagon-2';
-
- const updateLayerConfig = {
- dataId: testCsvDataId,
- columns: {
- lat: {value: 'gps_data.lat', fieldIdx: 1},
- lng: {value: 'gps_data.lng', fieldIdx: 2}
- },
- isConfigActive: false
- };
-
- const resultState = applyActions(keplerGlReducer, updateState, [
- // select hexagon layer columns
- {
- action: VisStateActions.layerConfigChange,
- payload: [hexagonLayer, updateLayerConfig]
- },
+ const reorderPayload = [[2, 0, 1]];
+ const resultState = applyActions(keplerGlReducer, prepareState, [
// reorder Layer
{action: VisStateActions.reorderLayer, payload: reorderPayload}
]);
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 119171769..ff90117a7 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -31,7 +31,7 @@ import * as MapStateActions from 'actions/map-state-actions';
import reducer from 'reducers/vis-state';
import {INITIAL_VIS_STATE, DEFAULT_ANIMATION_CONFIG} from 'reducers/vis-state-updaters';
-
+import {serializeLayer} from 'reducers/vis-state-merger';
import {getDefaultInteraction} from 'utils/interaction-utils';
import {getDefaultFilter} from 'utils/filter-utils';
import {createNewDataEntry} from 'utils/dataset-utils';
@@ -991,6 +991,82 @@ test('#visStateReducer -> REMOVE_LAYER', t => {
t.end();
});
+test('#visStateReducer -> DUPLICATE_LAYER', t => {
+ const oldState = CloneDeep(StateWFilesFiltersLayerColor.visState);
+ // layers: ['point-0', 'geojson-1', 'hexagon-2'],
+ const layerToCopy = serializeLayer(oldState.layers[0]);
+ t.equal(oldState.layers.length, 3, 'should have 3 layers to begin');
+ t.deepEqual(oldState.layerOrder, [2, 0, 1], 'should have 3 layers to begin');
+
+ const nextState = reducer(oldState, VisStateActions.duplicateLayer(0));
+ t.equal(nextState.layers.length, 4, 'should add 1 layer');
+ const layerCopied = serializeLayer(nextState.layers[3]);
+
+ const expectedLayer = {
+ ...layerToCopy,
+ id: layerCopied.id,
+ config: {
+ ...layerToCopy.config,
+ label: 'Copy of gps data'
+ }
+ };
+
+ t.deepEqual(layerCopied, expectedLayer, 'should copy layer config correctly');
+ t.deepEqual(
+ nextState.layerData[3].data,
+ nextState.layerData[0].data,
+ 'should copy layer data correctly'
+ );
+ t.deepEqual(
+ nextState.layerOrder,
+ [2, 3, 0, 1],
+ 'should insert copied layer in front of older layer'
+ );
+
+ // copy again
+ const nextState1 = reducer(nextState, VisStateActions.duplicateLayer(0));
+ t.equal(nextState1.layers.length, 5, 'should add 1 layer');
+ const layerCopied1 = serializeLayer(nextState1.layers[4]);
+
+ const expectedLayer1 = {
+ ...layerToCopy,
+ id: layerCopied1.id,
+ config: {
+ ...layerToCopy.config,
+ label: 'Copy of gps data 1'
+ }
+ };
+ t.deepEqual(layerCopied1, expectedLayer1, 'should copy layer config correctly');
+ t.deepEqual(
+ nextState1.layerData[4].data,
+ nextState1.layerData[0].data,
+ 'should copy layer data correctly'
+ );
+ t.deepEqual(
+ nextState1.layerOrder,
+ [2, 3, 4, 0, 1],
+ 'should insert copied layer in front of older layer'
+ );
+
+ // copy again
+ const nextState2 = reducer(nextState1, VisStateActions.duplicateLayer(0));
+ t.equal(nextState2.layers.length, 6, 'should add 1 layer');
+ const layerCopied2 = serializeLayer(nextState2.layers[5]);
+
+ const expectedLayer2 = {
+ ...layerToCopy,
+ id: layerCopied2.id,
+ config: {
+ ...layerToCopy.config,
+ label: 'Copy of gps data 2'
+ }
+ };
+ t.deepEqual(layerCopied2, expectedLayer2, 'should copy layer config correctly');
+
+ // test remove
+ t.end();
+});
+
test('#visStateReducer -> UPDATE_VIS_DATA.1 -> No data', t => {
const oldState = CloneDeep(InitialState).visState;
diff --git a/test/node/utils/data-utils-test.js b/test/node/utils/data-utils-test.js
index 8d02ca84b..1c3aa67af 100644
--- a/test/node/utils/data-utils-test.js
+++ b/test/node/utils/data-utils-test.js
@@ -34,11 +34,11 @@ import {
import {ALL_FIELD_TYPES} from 'constants';
test('dataUtils -> clamp', t => {
- t.equal(clamp([0,1], 2), 1, 'should clamp 2 to 1 for [0,1]');
- t.equal(clamp([0,1], 0.5), 0.5, 'should not clamp 0.5 for [0,1]');
- t.equal(clamp([-1,1], -2), -1, 'should clamp -2 to -1 for [-1,1]');
- t.equal(clamp([0,10], 11), 10, 'should clamp 11 to 10 for [0,10]');
- t.equal(clamp([0,0], 1), 0, 'should clamp 1 to 0 for [0,0]');
+ t.equal(clamp([0, 1], 2), 1, 'should clamp 2 to 1 for [0,1]');
+ t.equal(clamp([0, 1], 0.5), 0.5, 'should not clamp 0.5 for [0,1]');
+ t.equal(clamp([-1, 1], -2), -1, 'should clamp -2 to -1 for [-1,1]');
+ t.equal(clamp([0, 10], 11), 10, 'should clamp 11 to 10 for [0,10]');
+ t.equal(clamp([0, 0], 1), 0, 'should clamp 1 to 0 for [0,0]');
t.end();
});