Skip to content

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

[Enhancement] extract layers list to a separate component (#1665)

Nikola Karaklicf9ae108abc70
diff --git a/src/components/index.js b/src/components/index.js
index ba41a9b28..82a808fd7 100644
--- a/src/components/index.js
+++ b/src/components/index.js
@@ -65,6 +65,7 @@ export {default as LayerPanelHeaderFactory} from './side-panel/layer-panel/layer
export {default as LayerConfiguratorFactory} from './side-panel/layer-panel/layer-configurator';
export {default as TextLabelPanelFactory} from './side-panel/layer-panel/text-label-panel';
export {LayerConfigGroupLabelFactory} from './side-panel/layer-panel/layer-config-group';
+export {default as LayerListFactory} from './side-panel/layer-panel/layer-list';
export {default as SourceDataCatalogFactory} from './side-panel/common/source-data-catalog';
export {default as SourceDataSelectorFactory} from './side-panel/common/source-data-selector';
diff --git a/src/components/side-panel/layer-manager.js b/src/components/side-panel/layer-manager.js
index afc2506ea..947a82a7c 100644
--- a/src/components/side-panel/layer-manager.js
+++ b/src/components/side-panel/layer-manager.js
@@ -19,18 +19,13 @@
// THE SOFTWARE.
import React, {Component, useCallback} from 'react';
-import classnames from 'classnames';
import PropTypes from 'prop-types';
-import {SortableContainer, SortableElement} from 'react-sortable-hoc';
-import styled from 'styled-components';
-import {createSelector} from 'reselect';
import {injectIntl} from 'react-intl';
import {FormattedMessage} from 'localization';
-import {arrayMove} from 'utils/data-utils';
-import LayerPanelFactory from './layer-panel/layer-panel';
import SourceDataCatalogFactory from './common/source-data-catalog';
+import LayerListFactory from './layer-panel/layer-list';
import {Add} from 'components/common/icons';
import ItemSelector from 'components/common/item-selector/item-selector';
import {
@@ -72,33 +67,6 @@ const LayerBlendingSelector = ({layerBlending, updateLayerBlending, intl}) => {
);
};
-// make sure the element is always visible while is being dragged
-// item being dragged is appended in body, here to reset its global style
-const SortableStyledItem = styled.div`
- z-index: ${props => props.theme.dropdownWrapperZ + 1};
-
- &.sorting {
- pointer-events: none;
- }
-
- &.sorting-layers .layer-panel__header {
- background-color: ${props => props.theme.panelBackgroundHover};
- font-family: ${props => props.theme.fontFamily};
- font-weight: ${props => props.theme.fontWeight};
- font-size: ${props => props.theme.fontSize};
- line-height: ${props => props.theme.lineHeight};
- *,
- *:before,
- *:after {
- box-sizing: border-box;
- }
- .layer__drag-handle {
- opacity: 1;
- color: ${props => props.theme.textColorHl};
- }
- }
-`;
-
export function AddDataButtonFactory() {
const AddDataButton = ({onClick, isInactive}) => (
<Button
@@ -116,23 +84,9 @@ export function AddDataButtonFactory() {
return AddDataButton;
}
-LayerManagerFactory.deps = [AddDataButtonFactory, LayerPanelFactory, SourceDataCatalogFactory];
-
-function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
- // By wrapping layer panel using a sortable element we don't have to implement the drag and drop logic into the panel itself;
- // Developers can provide any layer panel implementation and it will still be sortable
- const SortableItem = SortableElement(({children, isSorting}) => {
- return (
- <SortableStyledItem className={classnames('sortable-layer-items', {sorting: isSorting})}>
- {children}
- </SortableStyledItem>
- );
- });
-
- const WrappedSortableContainer = SortableContainer(({children}) => {
- return <div>{children}</div>;
- });
+LayerManagerFactory.deps = [AddDataButtonFactory, LayerListFactory, SourceDataCatalogFactory];
+function LayerManagerFactory(AddDataButton, LayerList, SourceDataCatalog) {
class LayerManager extends Component {
static propTypes = {
datasets: PropTypes.object.isRequired,
@@ -145,47 +99,12 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
showDatasetTable: PropTypes.func.isRequired,
updateTableColor: PropTypes.func.isRequired
};
- state = {
- isSorting: false
- };
-
- layerClassSelector = props => props.layerClasses;
- layerTypeOptionsSelector = createSelector(this.layerClassSelector, layerClasses =>
- Object.keys(layerClasses).map(key => {
- const layer = new layerClasses[key]();
- return {
- id: key,
- label: layer.name,
- icon: layer.layerIcon,
- requireData: layer.requireData
- };
- })
- );
_addEmptyNewLayer = () => {
const {visStateActions} = this.props;
visStateActions.addLayer();
};
- _handleSort = ({oldIndex, newIndex}) => {
- const {visStateActions} = this.props;
- visStateActions.reorderLayer(arrayMove(this.props.layerOrder, oldIndex, newIndex));
- this.setState({isSorting: false});
- };
-
- _onSortStart = () => {
- this.setState({isSorting: true});
- };
-
- _updateBeforeSortStart = ({index}) => {
- // if layer config is active, close it
- const {layerOrder, layers, visStateActions} = this.props;
- const layerIdx = layerOrder[index];
- if (layers[layerIdx].config.isConfigActive) {
- visStateActions.layerConfigChange(layers[layerIdx], {isConfigActive: false});
- }
- };
-
render() {
const {
layers,
@@ -199,26 +118,8 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
uiStateActions,
visStateActions
} = this.props;
- const {toggleModal: openModal} = uiStateActions;
- const defaultDataset = Object.keys(datasets)[0];
- const layerTypeOptions = this.layerTypeOptionsSelector(this.props);
-
- const layerActions = {
- layerColorUIChange: visStateActions.layerColorUIChange,
- layerConfigChange: visStateActions.layerConfigChange,
- layerVisualChannelConfigChange: visStateActions.layerVisualChannelConfigChange,
- layerTypeChange: visStateActions.layerTypeChange,
- layerVisConfigChange: visStateActions.layerVisConfigChange,
- layerTextLabelChange: visStateActions.layerTextLabelChange,
- removeLayer: visStateActions.removeLayer,
- duplicateLayer: visStateActions.duplicateLayer
- };
- const panelProps = {
- datasets,
- openModal,
- layerTypeOptions
- };
+ const defaultDataset = Object.keys(datasets)[0];
return (
<div className="layer-manager">
@@ -232,34 +133,14 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
<AddDataButton onClick={showAddDataModal} isInactive={!defaultDataset} />
<SidePanelDivider />
<SidePanelSection>
- <WrappedSortableContainer
- onSortEnd={this._handleSort}
- onSortStart={this._onSortStart}
- updateBeforeSortStart={this._updateBeforeSortStart}
- lockAxis="y"
- helperClass="sorting-layers"
- useDragHandle
- >
- {layerOrder.map(
- (layerIdx, index) =>
- !layers[layerIdx].config.hidden && (
- <SortableItem
- key={`layer-${layerIdx}`}
- index={index}
- isSorting={this.state.isSorting}
- >
- <LayerPanel
- {...panelProps}
- {...layerActions}
- sortData={layerIdx}
- key={layers[layerIdx].id}
- idx={layerIdx}
- layer={layers[layerIdx]}
- />
- </SortableItem>
- )
- )}
- </WrappedSortableContainer>
+ <LayerList
+ layers={layers}
+ datasets={datasets}
+ layerOrder={layerOrder}
+ uiStateActions={uiStateActions}
+ visStateActions={visStateActions}
+ layerClasses={this.props.layerClasses}
+ />
</SidePanelSection>
<SidePanelSection>
{defaultDataset ? (
diff --git a/src/components/side-panel/layer-panel/layer-list.d.ts b/src/components/side-panel/layer-panel/layer-list.d.ts
new file mode 100644
index 000000000..e79a01515
--- /dev/null
+++ b/src/components/side-panel/layer-panel/layer-list.d.ts
@@ -0,0 +1,19 @@
+import React from 'react';
+import {Layer, LayerClassesType} from 'layers';
+import {Datasets} from 'reducers/vis-state-updaters';
+import * as VisStateActions from 'actions/vis-state-actions';
+import * as UIStateActions from 'actions/ui-state-actions';
+
+export type LayerListProps = {
+ datasets: Datasets;
+ layerClasses: LayerClassesType;
+ layers: Layer[];
+ layerOrder: number[];
+ uiStateActions: typeof UIStateActions;
+ visStateActions: typeof VisStateActions;
+ isSortable?: Boolean;
+};
+
+export default function LayerListFactory(
+ LayerPanel: React.Component
+): React.Component<LayerListProps>;
diff --git a/src/components/side-panel/layer-panel/layer-list.js b/src/components/side-panel/layer-panel/layer-list.js
new file mode 100644
index 000000000..2daba3f59
--- /dev/null
+++ b/src/components/side-panel/layer-panel/layer-list.js
@@ -0,0 +1,169 @@
+// Copyright (c) 2021 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, {useCallback, useMemo, useState} from 'react';
+import {arrayMove} from 'utils/data-utils';
+import styled from 'styled-components';
+import classnames from 'classnames';
+import {SortableContainer, SortableElement} from 'react-sortable-hoc';
+import LayerPanelFactory from './layer-panel';
+// make sure the element is always visible while is being dragged
+// item being dragged is appended in body, here to reset its global style
+const SortableStyledItem = styled.div`
+ z-index: ${props => props.theme.dropdownWrapperZ + 1};
+ &.sorting {
+ pointer-events: none;
+ }
+ &.sorting-layers .layer-panel__header {
+ background-color: ${props => props.theme.panelBackgroundHover};
+ font-family: ${props => props.theme.fontFamily};
+ font-weight: ${props => props.theme.fontWeight};
+ font-size: ${props => props.theme.fontSize};
+ line-height: ${props => props.theme.lineHeight};
+ *,
+ *:before,
+ *:after {
+ box-sizing: border-box;
+ }
+ .layer__drag-handle {
+ opacity: 1;
+ color: ${props => props.theme.textColorHl};
+ }
+ }
+`;
+LayerListFactory.deps = [LayerPanelFactory];
+function LayerListFactory(LayerPanel) {
+ // By wrapping layer panel using a sortable element we don't have to implement the drag and drop logic into the panel itself;
+ // Developers can provide any layer panel implementation and it will still be sortable
+ const SortableItem = SortableElement(({children, isSorting}) => {
+ return (
+ <SortableStyledItem className={classnames('sortable-layer-items', {sorting: isSorting})}>
+ {children}
+ </SortableStyledItem>
+ );
+ });
+ const WrappedSortableContainer = SortableContainer(({children}) => {
+ return <div>{children}</div>;
+ });
+ const LayerList = props => {
+ const {
+ layers,
+ datasets,
+ layerOrder,
+ uiStateActions,
+ visStateActions,
+ layerClasses,
+ isSortable = true
+ } = props;
+ const {toggleModal: openModal} = uiStateActions;
+ const [isSorting, setIsSorting] = useState(false);
+ const layerTypeOptions = useMemo(
+ () =>
+ Object.keys(layerClasses).map(key => {
+ const layer = new layerClasses[key]();
+ return {
+ id: key,
+ label: layer.name,
+ icon: layer.layerIcon,
+ requireData: layer.requireData
+ };
+ }),
+ [layerClasses]
+ );
+ const layerActions = {
+ layerColorUIChange: visStateActions.layerColorUIChange,
+ layerConfigChange: visStateActions.layerConfigChange,
+ layerVisualChannelConfigChange: visStateActions.layerVisualChannelConfigChange,
+ layerTypeChange: visStateActions.layerTypeChange,
+ layerVisConfigChange: visStateActions.layerVisConfigChange,
+ layerTextLabelChange: visStateActions.layerTextLabelChange,
+ removeLayer: visStateActions.removeLayer,
+ duplicateLayer: visStateActions.duplicateLayer
+ };
+ const panelProps = {
+ datasets,
+ openModal,
+ layerTypeOptions
+ };
+ const _handleSort = useCallback(
+ ({oldIndex, newIndex}) => {
+ visStateActions.reorderLayer(arrayMove(props.layerOrder, oldIndex, newIndex));
+ setIsSorting(false);
+ },
+ [props.layerOrder, visStateActions]
+ );
+ const _onSortStart = useCallback(() => {
+ setIsSorting(true);
+ }, []);
+ const _updateBeforeSortStart = useCallback(() => {
+ ({index}) => {
+ const layerIdx = layerOrder[index];
+ if (layers[layerIdx].config.isConfigActive) {
+ visStateActions.layerConfigChange(layers[layerIdx], {isConfigActive: false});
+ }
+ };
+ }, [layers, layerOrder, visStateActions]);
+ return isSortable ? (
+ <WrappedSortableContainer
+ onSortEnd={_handleSort}
+ onSortStart={_onSortStart}
+ updateBeforeSortStart={_updateBeforeSortStart}
+ lockAxis="y"
+ helperClass="sorting-layers"
+ useDragHandle
+ >
+ {layerOrder.map(
+ (layerIdx, index) =>
+ layers[layerIdx] &&
+ !layers[layerIdx].config.hidden && (
+ <SortableItem key={`layer-${layerIdx}`} index={index} isSorting={isSorting}>
+ <LayerPanel
+ {...panelProps}
+ {...layerActions}
+ sortData={layerIdx}
+ key={layers[layerIdx].id}
+ idx={layerIdx}
+ layer={layers[layerIdx]}
+ />
+ </SortableItem>
+ )
+ )}
+ </WrappedSortableContainer>
+ ) : (
+ <>
+ {layerOrder.map(
+ (layerIdx, index) =>
+ layers[layerIdx] &&
+ !layers[layerIdx].config.hidden && (
+ <LayerPanel
+ {...panelProps}
+ {...layerActions}
+ sortData={layerIdx}
+ key={layers[layerIdx].id}
+ idx={layerIdx}
+ layer={layers[layerIdx]}
+ />
+ )
+ )}
+ </>
+ );
+ };
+ return LayerList;
+}
+export default LayerListFactory;
diff --git a/test/browser/components/side-panel/index.js b/test/browser/components/side-panel/index.js
index 351a96bcb..282d05b2d 100644
--- a/test/browser/components/side-panel/index.js
+++ b/test/browser/components/side-panel/index.js
@@ -24,3 +24,4 @@ import './side-panel-test';
import './layer-panel-header-test';
import './filter-manager-test';
import './layer-configurator-test';
+import './layer-list-test';
diff --git a/test/browser/components/side-panel/layer-list-test.js b/test/browser/components/side-panel/layer-list-test.js
new file mode 100644
index 000000000..83e896deb
--- /dev/null
+++ b/test/browser/components/side-panel/layer-list-test.js
@@ -0,0 +1,83 @@
+import React from 'react';
+import test from 'tape';
+
+import {StateWMultiH3Layers} from 'test/helpers/mock-state';
+
+import * as VisStateActions from 'actions/vis-state-actions';
+import * as UIStateActions from 'actions/ui-state-actions';
+
+import {appInjector} from 'components/container';
+import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
+
+import LayerListFactory from 'components/side-panel/layer-panel/layer-list';
+
+const LayerList = appInjector.get(LayerListFactory);
+
+const defaultProps = {
+ datasets: StateWMultiH3Layers.visState.datasets,
+ layerClasses: StateWMultiH3Layers.visState.layerClasses,
+ layerOrder: StateWMultiH3Layers.visState.layerOrder,
+ layers: StateWMultiH3Layers.visState.layers,
+ uiStateActions: UIStateActions,
+ visStateActions: VisStateActions
+};
+
+test('Components -> SidePanel -> LayerPanel -> LayerList -> render sortable list', t => {
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <LayerList {...defaultProps} isSortable />
+ </IntlWrapper>
+ );
+ }, 'LayerList should render');
+
+ t.equal(wrapper.find('.sortable-layer-items').length, 6, 'should render 6 sortable items');
+
+ const titles = [];
+ const expectedTitles = [
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 2',
+ 'H3 Hexagon 2',
+ 'H3 Hexagon 2'
+ ];
+ wrapper.find('.layer__title__editor').forEach(item => titles.push(item.getDOMNode().value));
+ t.deepEqual(titles, expectedTitles, 'should render panels in correct order');
+
+ const layers = wrapper.find('.layer-panel');
+ t.equal(layers.length, 6, 'should render 6 layer panels');
+
+ t.end();
+});
+
+test('Components -> SidePanel -> LayerPanel -> LayerList -> render non-sortable list', t => {
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <IntlWrapper>
+ <LayerList {...defaultProps} isSortable={false} />
+ </IntlWrapper>
+ );
+ }, 'LayerList should render');
+
+ t.equal(wrapper.find('.sortable-layer-items').length, 0, 'should not render sortable items');
+
+ const titles = [];
+ const expectedTitles = [
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 1',
+ 'H3 Hexagon 2',
+ 'H3 Hexagon 2',
+ 'H3 Hexagon 2'
+ ];
+ wrapper.find('.layer__title__editor').forEach(item => titles.push(item.getDOMNode().value));
+ t.deepEqual(titles, expectedTitles, 'should render panels in correct order');
+
+ const layers = wrapper.find('.layer-panel');
+ t.equal(layers.length, 6, 'should render 6 layer panels');
+
+ t.end();
+});
diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.js
index 523f46b3d..560ea6101 100644
--- a/test/helpers/mock-state.js
+++ b/test/helpers/mock-state.js
@@ -275,6 +275,57 @@ function mockStateWithH3Layer() {
]);
return prepareState;
}
+
+function mockStateWithMultipleH3Layers() {
+ const initialState = cloneDeep(InitialState);
+
+ const prepareState = applyActions(keplerGlReducer, initialState, [
+ {
+ action: addDataToMap,
+ payload: [
+ {
+ datasets: {
+ info: {id: csvDataId},
+ data: processCsvData(testLayerData)
+ },
+ config: {
+ version: 'v1',
+ config: {
+ visState: {
+ layers: [
+ {
+ id: 'h3-layer-1',
+ type: 'hexagonId',
+ config: {
+ dataId: csvDataId,
+ label: 'H3 Hexagon 1',
+ color: [255, 153, 31],
+ columns: {hex_id: 'hex_id'},
+ isVisible: true
+ }
+ },
+ {
+ id: 'h3-layer-2',
+ type: 'hexagonId',
+ config: {
+ dataId: csvDataId,
+ label: 'H3 Hexagon 2',
+ color: [255, 153, 31],
+ columns: {hex_id: 'hex_id'},
+ isVisible: true
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ ]
+ }
+ ]);
+ return prepareState;
+}
+
/**
* Mock state will contain 1 heatmap, 1 point and 1 arc layer, 1 hexbin layer and 1 time filter
* @param {*} state
@@ -794,6 +845,7 @@ export const StateWTrips = mockStateWithTripData();
export const StateWTripGeojson = mockStateWithTripGeojson();
export const StateWTooltipFormat = mockStateWithTooltipFormat();
export const StateWH3Layer = mockStateWithH3Layer();
+export const StateWMultiH3Layers = mockStateWithMultipleH3Layers();
export const StateWithGeocoderDataset = mockStateWithGeocoderDataset();
export const expectedSavedTripLayer = {