Skip to content

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

[Feat] Visual channel refactor generalize get accessor and updateTrigger (#1338)

Shan He524fc591861d
diff --git a/examples/demo-app/src/data/sample-trip-data.js b/examples/demo-app/src/data/sample-trip-data.js
index e59a03981..6b0b5d8a9 100644
--- a/examples/demo-app/src/data/sample-trip-data.js
+++ b/examples/demo-app/src/data/sample-trip-data.js
@@ -4002,7 +4002,25 @@ export const sampleTripDataConfig = {
},
color: [255, 0, 0],
label: 'pickup',
- isVisible: true
+ isVisible: true,
+ visConfig: {
+ colorRange: {
+ colorMap: [
+ ['apple tree', '#FF000'],
+ ['banana peel', '#00FF00'],
+ ['banana peel 2', '#0000FF'],
+ ['mango mint pineapple juice', '#555555'],
+ ['orange peel', '#111111'],
+ ['orange peel 0', '#222222']
+ ]
+ }
+ }
+ },
+ visualChannels: {
+ colorField: {
+ name: 'fare_type',
+ type: 'string'
+ }
}
},
{
diff --git a/src/components/common/action-panel.js b/src/components/common/action-panel.js
index 36832c295..0a15c0b2e 100644
--- a/src/components/common/action-panel.js
+++ b/src/components/common/action-panel.js
@@ -36,9 +36,7 @@ const StyledItem = styled.div`
background-color: ${props => props.theme.dropdownListBgd};
width: ${props => props.theme.actionPanelWidth}px;
position: relative;
- ${props => (props.color ? `border-left: 3px solid rgb(${props.color});` : '')}
-
- :hover {
+ ${props => (props.color ? `border-left: 3px solid rgb(${props.color});` : '')} :hover {
cursor: pointer;
color: ${props => props.theme.textColorHl};
.nested-group {
@@ -150,9 +148,7 @@ const StyledActionPanel = styled.div`
${props =>
props.direction === 'column'
? `border-bottom: 1px solid ${props.theme.panelHeaderIcon}`
- : `border-right: 1px solid ${props.theme.panelHeaderIcon}`}
-
- &:last-of-type {
+ : `border-right: 1px solid ${props.theme.panelHeaderIcon}`} &:last-of-type {
border-bottom: 0;
}
}
diff --git a/src/components/common/color-legend.js b/src/components/common/color-legend.js
index 4ae4b2942..107f9ac90 100644
--- a/src/components/common/color-legend.js
+++ b/src/components/common/color-legend.js
@@ -26,6 +26,7 @@ import {format} from 'd3-format';
import moment from 'moment';
import {SCALE_TYPES, SCALE_FUNC, ALL_FIELD_TYPES} from 'constants/default-settings';
import {getTimeWidgetHintFormatter} from 'utils/filter-utils';
+import {isObject} from 'utils/utils';
const ROW_H = 10;
const GAP = 4;
@@ -105,7 +106,7 @@ export default class ColorLegend extends Component {
scaleType: PropTypes.string,
domain: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
fieldType: PropTypes.string,
- range: PropTypes.arrayOf(PropTypes.string),
+ range: PropTypes.object,
labelFormat: PropTypes.func
};
@@ -122,28 +123,48 @@ export default class ColorLegend extends Component {
this.labelFormatSelector,
this.fieldTypeSelector,
(domain, range, scaleType, labelFormat, fieldType) => {
- const scaleFunction = SCALE_FUNC[scaleType];
- // color scale can only be quantize, quantile or ordinal
- const scale = scaleFunction()
- .domain(domain)
- .range(range);
-
- if (scaleType === SCALE_TYPES.ordinal) {
- return getOrdinalLegends(scale);
+ const empty = {
+ data: [],
+ labels: []
+ };
+ if (!range) {
+ return empty;
}
-
- const formatLabel = labelFormat || getQuantLabelFormat(scale.domain(), fieldType);
-
- return getQuantLegends(scale, formatLabel);
+ if (isObject(range.colorLegends)) {
+ return {
+ data: Object.keys(range.colorLegends),
+ labels: Object.values(range.colorLegends)
+ };
+ } else if (Array.isArray(range.colorMap)) {
+ return {
+ data: range.colorMap.map(cm => cm[1]),
+ labels: range.colorMap.map(cm => cm[0])
+ };
+ } else if (Array.isArray(range.colors)) {
+ if (!domain || !scaleType) {
+ return empty;
+ }
+
+ const scaleFunction = SCALE_FUNC[scaleType];
+ // color scale can only be quantize, quantile or ordinal
+ const scale = scaleFunction()
+ .domain(domain)
+ .range(range.colors);
+
+ if (scaleType === SCALE_TYPES.ordinal) {
+ return getOrdinalLegends(scale);
+ }
+
+ const formatLabel = labelFormat || getQuantLabelFormat(scale.domain(), fieldType);
+
+ return getQuantLegends(scale, formatLabel);
+ }
+ return empty;
}
);
render() {
- const {width, scaleType, domain, range, displayLabel = true} = this.props;
-
- if (!domain || !range || !scaleType) {
- return null;
- }
+ const {width, displayLabel = true} = this.props;
const legends = this.legendsSelector(this.props);
const height = legends.data.length * (ROW_H + GAP);
diff --git a/src/components/common/file-uploader/file-upload.js b/src/components/common/file-uploader/file-upload.js
index 31236caa5..0c82b39c8 100644
--- a/src/components/common/file-uploader/file-upload.js
+++ b/src/components/common/file-uploader/file-upload.js
@@ -51,7 +51,7 @@ const StyledUploadMessage = styled.div`
${media.portable`
font-size: 12px;
- `}
+ `};
`;
export const WarningMsg = styled.span`
@@ -139,7 +139,7 @@ const StyledDragFileWrapper = styled.div`
`};
${media.portable`
margin-bottom: 16px;
- `}
+ `};
`;
const StyledDisclaimer = styled(StyledMessage)`
diff --git a/src/components/common/item-selector/chickleted-input.js b/src/components/common/item-selector/chickleted-input.js
index f6bf154de..7a236421a 100644
--- a/src/components/common/item-selector/chickleted-input.js
+++ b/src/components/common/item-selector/chickleted-input.js
@@ -120,6 +120,8 @@ const ChickletedInput = ({
disabled,
key: `${displayOption(item)}_${i}`,
name: displayOption(item),
+ displayOption,
+ item,
remove: e => removeItem(item, e)
};
return CustomChickletComponent ? (
diff --git a/src/components/index.js b/src/components/index.js
index 056f147b3..4efcd5b5a 100644
--- a/src/components/index.js
+++ b/src/components/index.js
@@ -180,7 +180,6 @@ export {
// map components
export {default as MapLegend} from 'components/map/map-legend';
-
export * from './common/styled-components';
import * as Icons from './common/icons';
export {Icons};
diff --git a/src/components/map-container.js b/src/components/map-container.js
index e43e39068..ef632dd26 100644
--- a/src/components/map-container.js
+++ b/src/components/map-container.js
@@ -38,7 +38,7 @@ import {generateMapboxLayers, updateMapboxLayers} from 'layers/mapbox-utils';
import {OVERLAY_TYPE} from 'layers/base-layer';
import {setLayerBlending} from 'utils/gl-utils';
import {transformRequest} from 'utils/map-style-utils/mapbox-utils';
-import {getLayerHoverProp} from 'utils/layer-utils';
+import {getLayerHoverProp, renderDeckGlLayer} from 'utils/layer-utils';
// default-settings
import ThreeDBuildingLayer from 'deckgl-layers/3d-building-layer/3d-building-layer';
@@ -345,41 +345,6 @@ export default function MapContainerFactory(MapPopover, MapControl, Editor) {
return screenCoord && {x: screenCoord[0], y: screenCoord[1]};
}
- _renderLayer = (overlays, idx) => {
- const {
- datasets,
- layers,
- layerData,
- hoverInfo,
- clicked,
- mapState,
- interactionConfig,
- animationConfig
- } = this.props;
- const layer = layers[idx];
- const data = layerData[idx];
- const {gpuFilter} = datasets[layer.config.dataId] || {};
-
- const objectHovered = clicked || hoverInfo;
- const layerCallbacks = {
- onSetLayerDomain: val => this._onLayerSetDomain(idx, val)
- };
-
- // Layer is Layer class
- const layerOverlay = layer.renderLayer({
- data,
- gpuFilter,
- idx,
- interactionConfig,
- layerCallbacks,
- mapState,
- animationConfig,
- objectHovered
- });
-
- return overlays.concat(layerOverlay || []);
- };
-
_renderDeckOverlay(layersToRender) {
const {
mapState,
@@ -402,7 +367,13 @@ export default function MapContainerFactory(MapPopover, MapControl, Editor) {
.filter(
idx => layers[idx].overlayType === OVERLAY_TYPE.deckgl && layersToRender[layers[idx].id]
)
- .reduce(this._renderLayer, []);
+ .reduce((overlays, idx) => {
+ const layerCallbacks = {
+ onSetLayerDomain: val => this._onLayerSetDomain(idx, val)
+ };
+ const layerOverlay = renderDeckGlLayer(this.props, layerCallbacks, idx);
+ return overlays.concat(layerOverlay || []);
+ }, []);
}
if (mapStyle.visibleLayerGroups['3d building']) {
diff --git a/src/components/map/layer-hover-info.js b/src/components/map/layer-hover-info.js
index e10fcffea..cec9db031 100644
--- a/src/components/map/layer-hover-info.js
+++ b/src/components/map/layer-hover-info.js
@@ -119,7 +119,7 @@ const EntryInfoRow = ({item, fields, data, primaryData, compareType}) => {
compareType
});
- return <Row name={item.name} value={displayValue} deltaValue={displayDeltaValue} />;
+ return <Row name={field.name} value={displayValue} deltaValue={displayDeltaValue} />;
};
// TODO: supporting comparative value for aggregated cells as well
diff --git a/src/components/map/map-legend.js b/src/components/map/map-legend.js
index 97c417c17..a6f356320 100644
--- a/src/components/map/map-legend.js
+++ b/src/components/map/map-legend.js
@@ -27,16 +27,18 @@ import {CHANNEL_SCALES, DIMENSIONS} from 'constants/default-settings';
import {FormattedMessage} from 'localization';
export const StyledMapControlLegend = styled.div`
- padding: 10px 0 10px ${props => props.theme.mapControl.padding}px;
+ padding: 10px ${props => props.theme.mapControl.padding}px 10px
+ ${props => props.theme.mapControl.padding}px;
font-size: 11px;
border-bottom-color: ${props => props.theme.panelBorderColor};
border-bottom-style: solid;
border-bottom-width: ${props => (props.last ? 0 : '1px')};
+ width: ${props => props.width}px;
.legend--layer_name {
font-size: 12px;
padding-right: ${props => props.theme.mapControl.padding}px;
- color: ${props => props.theme.textColorHl};
+ color: ${props => props.theme.textColor};
font-weight: 500;
}
.legend--layer_type {
@@ -55,7 +57,7 @@ export const StyledMapControlLegend = styled.div`
}
.legend--layer_color_field {
- color: ${props => props.theme.textColor};
+ color: ${props => props.theme.textColorHl};
font-weight: 500;
}
@@ -67,7 +69,6 @@ export const StyledMapControlLegend = styled.div`
export const VisualChannelMetric = ({name}) => {
return (
<div className="legend--layer__title">
- <span className="legend--layer_by">by </span>
<span className="legend--layer_color_field">
<FormattedMessage id={name} />
</span>
@@ -81,6 +82,7 @@ export const LayerSizeLegend = ({label, name}) => (
<span className="legend--layer_by">
<FormattedMessage id={label} />
</span>
+ <span className="legend--layer_by"> by </span>
</p>
<VisualChannelMetric name={name} />
</div>
@@ -97,28 +99,13 @@ export const SingleColorLegend = React.memo(({width, color}) => (
displayLabel={false}
domain={SingleColorDomain}
fieldType={null}
- range={[rgb(...color).toString()]}
+ range={{colors: [rgb(...color).toString()]}}
width={width}
/>
));
SingleColorLegend.displayName = 'SingleColorLegend';
-export const MultiColorLegend = React.memo(
- ({colorRange, colorScale, colorDomain, colorField, width}) => (
- <ColorLegend
- scaleType={colorScale}
- displayLabel
- domain={colorDomain}
- fieldType={(colorField && colorField.type) || 'real'}
- range={colorRange.colors}
- width={width}
- />
- )
-);
-
-MultiColorLegend.displayName = 'MultiColorLegend';
-
export const LayerColorLegend = React.memo(({description, config, width, colorChannel}) => {
const enableColorBy = description.measure;
const {scale, field, domain, range, property} = colorChannel;
@@ -132,11 +119,12 @@ export const LayerColorLegend = React.memo(({description, config, width, colorCh
{enableColorBy ? <VisualChannelMetric name={enableColorBy} /> : null}
<div className="legend--layer_color-legend">
{enableColorBy ? (
- <MultiColorLegend
- colorScale={colorScale}
- colorField={colorField}
- colorDomain={colorDomain}
- colorRange={colorRange}
+ <ColorLegend
+ scaleType={colorScale}
+ displayLabel
+ domain={colorDomain}
+ fieldType={(colorField && colorField.type) || 'real'}
+ range={colorRange}
width={width}
/>
) : (
@@ -157,15 +145,19 @@ LayerColorLegend.displayName = 'LayerColorLegend';
const isColorChannel = visualChannel =>
[CHANNEL_SCALES.color, CHANNEL_SCALES.colorAggr].includes(visualChannel.channelScaleType);
-const MAP_LEGEND_WIDTH = DIMENSIONS.mapControl.width - 2 * DIMENSIONS.mapControl.padding;
-
-const MapLegend = ({layers = []}) => (
+/**
+ * @param {Layer[]} layers
+ * @param {number} width
+ * @param {object} options
+ * @param {boolean} options.showLayerName
+ */
+const MapLegend = ({layers = [], width, options = {}}) => (
<div className="map-legend">
{layers.map((layer, index) => {
- if (!layer.isValidToSave()) {
+ if (!layer.isValidToSave() || layer.config.hidden) {
return null;
}
-
+ const containerW = width || DIMENSIONS.mapControl.width;
const colorChannels = Object.values(layer.visualChannels).filter(isColorChannel);
const nonColorChannels = Object.values(layer.visualChannels).filter(
vc => !isColorChannel(vc)
@@ -176,15 +168,18 @@ const MapLegend = ({layers = []}) => (
className="legend--layer"
last={index === layers.length - 1}
key={index}
+ width={containerW}
>
- <div className="legend--layer_name">{layer.config.label}</div>
+ {options.showLayerName !== false ? (
+ <div className="legend--layer_name">{layer.config.label}</div>
+ ) : null}
{colorChannels.map(colorChannel =>
!colorChannel.condition || colorChannel.condition(layer.config) ? (
<LayerColorLegend
key={colorChannel.key}
description={layer.getVisualChannelDescription(colorChannel.key)}
config={layer.config}
- width={MAP_LEGEND_WIDTH}
+ width={containerW - 2 * DIMENSIONS.mapControl.padding}
colorChannel={colorChannel}
/>
) : null
diff --git a/src/components/modal-container.js b/src/components/modal-container.js
index f5a340a67..46fbc448b 100644
--- a/src/components/modal-container.js
+++ b/src/components/modal-container.js
@@ -71,12 +71,10 @@ const DataTableModalStyle = css`
${media.portable`
padding: 0;
- `}
-
- ${media.palm`
+ `} ${media.palm`
padding: 0;
margin: 0 auto;
- `}
+ `};
`;
const smallModalCss = css`
width: 40%;
@@ -302,7 +300,7 @@ export default function ModalContainerFactory(
${DataTableModalStyle};
${media.palm`
width: ${width}px;
- `}
+ `};
`;
break;
case DELETE_DATA_ID:
diff --git a/src/components/side-panel/filter-panel/filter-panel-header.js b/src/components/side-panel/filter-panel/filter-panel-header.js
index 1d5409be5..3e0adac10 100644
--- a/src/components/side-panel/filter-panel/filter-panel-header.js
+++ b/src/components/side-panel/filter-panel/filter-panel-header.js
@@ -37,7 +37,7 @@ export const StyledFilterHeader = styled(StyledPanelHeader)`
${props =>
props.labelRCGColorValues && props.labelRCGColorValues.length > 0
? `border-image: ${createLinearGradient('bottom', props.labelRCGColorValues)} 3;`
- : 'border-color: transparent;'}
+ : 'border-color: transparent;'};
`;
const StyledChildrenContainer = styled.div`
diff --git a/src/components/side-panel/interaction-panel/tooltip-config.js b/src/components/side-panel/interaction-panel/tooltip-config.js
index c7536e2a2..a23d6f642 100644
--- a/src/components/side-panel/interaction-panel/tooltip-config.js
+++ b/src/components/side-panel/interaction-panel/tooltip-config.js
@@ -18,7 +18,7 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import React, {Component} from 'react';
+import React from 'react';
import styled from 'styled-components';
import {injectIntl} from 'react-intl';
import {FormattedMessage} from 'localization';
@@ -69,116 +69,120 @@ const CompareSwitchWrapper = styled.div`
TooltipConfigFactory.deps = [DatasetTagFactory, FieldSelectorFactory];
function TooltipConfigFactory(DatasetTag, FieldSelector) {
- class TooltipConfig extends Component {
- render() {
- const {config, datasets, onChange, intl} = this.props;
- return (
- <TooltipConfigWrapper>
- {Object.keys(config.fieldsToShow).map(dataId => (
- <SidePanelSection key={dataId}>
- <SBFlexboxNoMargin>
- <DatasetTag dataset={datasets[dataId]} />
- {Boolean(config.fieldsToShow[dataId].length) && (
- <ButtonWrapper>
- <Button
- className="clear-all"
- onClick={() => {
- const newConfig = {
- ...config,
- fieldsToShow: {
- ...config.fieldsToShow,
- [dataId]: []
- }
- };
- onChange(newConfig);
- }}
- width="54px"
- secondary
- >
- <FormattedMessage id="fieldSelector.clearAll" />
- </Button>
- </ButtonWrapper>
- )}
- </SBFlexboxNoMargin>
- <FieldSelector
- fields={datasets[dataId].fields}
- value={config.fieldsToShow[dataId]}
- onSelect={selected => {
+ const DatasetTooltipConfig = ({config, onChange, dataset}) => {
+ const dataId = dataset.id;
+ return (
+ <SidePanelSection key={dataId}>
+ <SBFlexboxNoMargin>
+ <DatasetTag dataset={dataset} />
+ {Boolean(config.fieldsToShow[dataId].length) && (
+ <ButtonWrapper>
+ <Button
+ className="clear-all"
+ onClick={() => {
const newConfig = {
...config,
fieldsToShow: {
...config.fieldsToShow,
- [dataId]: selected.map(
- f =>
- config.fieldsToShow[dataId].find(
- tooltipField => tooltipField.name === f.name
- ) || {
- name: f.name,
- // default initial tooltip is null
- format: null
- }
- )
+ [dataId]: []
}
};
onChange(newConfig);
}}
- closeOnSelect={false}
- multiSelect
- inputTheme="secondary"
- CustomChickletComponent={TooltipChickletFactory(
- dataId,
- config,
- onChange,
- datasets[dataId].fields
- )}
- />
- </SidePanelSection>
- ))}
- <CompareSwitchWrapper>
- <FormattedMessage id="compare.modeLabel" />
- <Switch
- checked={config.compareMode}
- id="compare-mode-toggle"
- onChange={() => {
- const newConfig = {
- ...config,
- compareMode: !config.compareMode
- };
- onChange(newConfig);
- }}
- secondary
- />
- </CompareSwitchWrapper>
- <SidePanelSection>
- <PanelLabel>
- <FormattedMessage id="compare.typeLabel" />
- </PanelLabel>
- <ItemSelector
- disabled={!config.compareMode}
- displayOption={d =>
- intl.formatMessage({
- id: `compare.types.${d}`
- })
+ width="54px"
+ secondary
+ >
+ <FormattedMessage id="fieldSelector.clearAll" />
+ </Button>
+ </ButtonWrapper>
+ )}
+ </SBFlexboxNoMargin>
+ <FieldSelector
+ fields={dataset.fields}
+ value={config.fieldsToShow[dataId]}
+ onSelect={selected => {
+ const newConfig = {
+ ...config,
+ fieldsToShow: {
+ ...config.fieldsToShow,
+ [dataId]: selected.map(
+ f =>
+ config.fieldsToShow[dataId].find(
+ tooltipField => tooltipField.name === f.name
+ ) || {
+ name: f.name,
+ // default initial tooltip is null
+ format: null
+ }
+ )
}
- selectedItems={config.compareType}
- options={Object.values(COMPARE_TYPES)}
- multiSelect={false}
- searchable={false}
- inputTheme={'secondary'}
- getOptionValue={d => d}
- onChange={option => {
- const newConfig = {
- ...config,
- compareType: option
- };
- onChange(newConfig);
- }}
- />
- </SidePanelSection>
- </TooltipConfigWrapper>
- );
- }
- }
+ };
+ onChange(newConfig);
+ }}
+ closeOnSelect={false}
+ multiSelect
+ inputTheme="secondary"
+ CustomChickletComponent={TooltipChickletFactory(dataId, config, onChange, dataset.fields)}
+ />
+ </SidePanelSection>
+ );
+ };
+
+ const TooltipConfig = ({config, datasets, onChange, intl}) => {
+ return (
+ <TooltipConfigWrapper>
+ {Object.keys(config.fieldsToShow).map(dataId => (
+ <DatasetTooltipConfig
+ key={dataId}
+ config={config}
+ onChange={onChange}
+ dataset={datasets[dataId]}
+ />
+ ))}
+ <CompareSwitchWrapper>
+ <FormattedMessage id="compare.modeLabel" />
+ <Switch
+ checked={config.compareMode}
+ id="compare-mode-toggle"
+ onChange={() => {
+ const newConfig = {
+ ...config,
+ compareMode: !config.compareMode
+ };
+ onChange(newConfig);
+ }}
+ secondary
+ />
+ </CompareSwitchWrapper>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="compare.typeLabel" />
+ </PanelLabel>
+ <ItemSelector
+ disabled={!config.compareMode}
+ displayOption={d =>
+ intl.formatMessage({
+ id: `compare.types.${d}`
+ })
+ }
+ selectedItems={config.compareType}
+ options={Object.values(COMPARE_TYPES)}
+ multiSelect={false}
+ searchable={false}
+ inputTheme={'secondary'}
+ getOptionValue={d => d}
+ onChange={option => {
+ const newConfig = {
+ ...config,
+ compareType: option
+ };
+ onChange(newConfig);
+ }}
+ />
+ </SidePanelSection>
+ </TooltipConfigWrapper>
+ );
+ };
return injectIntl(TooltipConfig);
}
diff --git a/src/components/side-panel/layer-panel/custom-palette.js b/src/components/side-panel/layer-panel/custom-palette.js
index d4d32e28f..c326f888f 100644
--- a/src/components/side-panel/layer-panel/custom-palette.js
+++ b/src/components/side-panel/layer-panel/custom-palette.js
@@ -49,13 +49,13 @@ const StyledSortableItem = styled.div`
:not(.sorting) {
:hover {
background-color: ${props => props.theme.panelBackgroundHover};
- ${dragHandleActive}
+ ${dragHandleActive};
}
}
&.sorting-colors {
background-color: ${props => props.theme.panelBackgroundHover};
- ${dragHandleActive}
+ ${dragHandleActive};
}
`;
diff --git a/src/deckgl-layers/layer-utils/cpu-aggregator.js b/src/deckgl-layers/layer-utils/cpu-aggregator.js
index b8d44ebe9..a86859311 100644
--- a/src/deckgl-layers/layer-utils/cpu-aggregator.js
+++ b/src/deckgl-layers/layer-utils/cpu-aggregator.js
@@ -19,10 +19,9 @@
// THE SOFTWARE.
/* eslint-disable guard-for-in */
-import {AGGREGATION_OPERATION} from '@deck.gl/aggregation-layers';
+import {AGGREGATION_OPERATION, _BinSorter as BinSorter} from '@deck.gl/aggregation-layers';
import {console as Console} from 'global/window';
-import EnhancedBinSorter from './enhanced-bin-sorter';
import {aggregate} from 'utils/aggregate-utils';
import {AGGREGATION_TYPES, SCALE_FUNC} from 'constants/default-settings';
@@ -73,7 +72,7 @@ export function getDimensionSortedBins(step, props, dimensionUpdater) {
const {key} = dimensionUpdater;
const {getValue} = this.state.dimensions[key];
- const sortedBins = new EnhancedBinSorter(this.state.layerData.data || [], {
+ const sortedBins = new BinSorter(this.state.layerData.data || [], {
getValue,
filterData: props._filterData
});
diff --git a/src/deckgl-layers/layer-utils/enhanced-bin-sorter.js b/src/deckgl-layers/layer-utils/enhanced-bin-sorter.js
deleted file mode 100644
index 1bf49352e..000000000
--- a/src/deckgl-layers/layer-utils/enhanced-bin-sorter.js
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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 {_BinSorter as BinSorter} from '@deck.gl/aggregation-layers';
-
-export default class EnhancedBinSorter extends BinSorter {
- getValueRange(percentileRange) {
- if (!this.sortedBins) {
- this.sortedBins = this.aggregatedBins.sort((a, b) =>
- a.value > b.value ? 1 : a.value < b.value ? -1 : 0
- );
- }
- if (!this.sortedBins.length) {
- return [];
- }
- let lowerIdx = 0;
- let upperIdx = this.sortedBins.length - 1;
-
- if (Array.isArray(percentileRange)) {
- const idxRange = this._percentileToIndex(percentileRange);
- lowerIdx = idxRange[0];
- upperIdx = idxRange[1];
- }
-
- return [this.sortedBins[lowerIdx].value, this.sortedBins[upperIdx].value];
- }
-
- getValueDomainByScale(scale, [lower = 0, upper = 100] = []) {
- if (!this.sortedBins) {
- this.sortedBins = this.aggregatedBins.sort((a, b) =>
- a.value > b.value ? 1 : a.value < b.value ? -1 : 0
- );
- }
- if (!this.sortedBins.length) {
- return [];
- }
- const indexEdge = this._percentileToIndex([lower, upper]);
-
- return this._getScaleDomain(scale, indexEdge);
- }
-}
diff --git a/src/layers/aggregation-layer.js b/src/layers/aggregation-layer.js
index efdd2e4c1..8751ed2ca 100644
--- a/src/layers/aggregation-layer.js
+++ b/src/layers/aggregation-layer.js
@@ -123,7 +123,7 @@ export default class AggregationLayer extends Layer {
return {
label: this.visConfigSettings[range].label,
measure: this.config[field]
- ? `${this.config.visConfig[aggregation]} of ${this.config[field].name}`
+ ? `${this.config.visConfig[aggregation]} of ${this.config[field].displayName}`
: defaultMeasure
};
}
diff --git a/src/layers/arc-layer/arc-layer.js b/src/layers/arc-layer/arc-layer.js
index ec2f00789..b543030ce 100644
--- a/src/layers/arc-layer/arc-layer.js
+++ b/src/layers/arc-layer/arc-layer.js
@@ -84,9 +84,23 @@ export default class ArcLayer extends Layer {
get visualChannels() {
return {
- ...super.visualChannels,
+ sourceColor: {
+ ...super.visualChannels.color,
+ property: 'color',
+ key: 'sourceColor',
+ accessor: 'getSourceColor',
+ defaultValue: config => config.color
+ },
+ targetColor: {
+ ...super.visualChannels.color,
+ property: 'targetColor',
+ key: 'targetColor',
+ accessor: 'getTargetColor',
+ defaultValue: config => config.visConfig.targetColor || config.color
+ },
size: {
...super.visualChannels.size,
+ accessor: 'getWidth',
property: 'stroke'
}
};
@@ -116,7 +130,6 @@ export default class ArcLayer extends Layer {
calculateDataAttribute({allData, filteredIndex}, getPosition) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
- // data = filteredIndex.reduce((accu, index) => {
const index = filteredIndex[i];
const pos = getPosition({data: allData[index]});
@@ -135,49 +148,14 @@ export default class ArcLayer extends Layer {
return data;
}
- // TODO: fix complexity
- /* eslint-disable complexity */
- formatLayerData(datasets, oldLayerData, opt = {}) {
- const {
- colorScale,
- colorDomain,
- colorField,
- color,
- sizeField,
- sizeScale,
- sizeDomain,
- visConfig: {sizeRange, colorRange, targetColor}
- } = this.config;
-
+ formatLayerData(datasets, oldLayerData) {
const {gpuFilter} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
-
- // arc color
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
-
- // arc thickness
- const sScale = sizeField && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange);
-
- const getStrokeWidth = sScale
- ? d => this.getEncodedChannelValue(sScale, d.data, sizeField, 0)
- : 1;
-
- const getSourceColor = cScale
- ? d => this.getEncodedChannelValue(cScale, d.data, colorField)
- : color;
-
- const getTargetColor = cScale
- ? d => this.getEncodedChannelValue(cScale, d.data, colorField)
- : targetColor || color;
-
+ const accessors = this.getAttributeAccessors();
return {
data,
- getSourceColor,
- getTargetColor,
- getWidth: getStrokeWidth,
- getFilterValue: gpuFilter.filterValueAccessor()
+ getFilterValue: gpuFilter.filterValueAccessor(),
+ ...accessors
};
}
/* eslint-enable complexity */
@@ -210,15 +188,11 @@ export default class ArcLayer extends Layer {
renderLayer(opts) {
const {data, gpuFilter, objectHovered, interactionConfig} = opts;
-
- const colorUpdateTriggers = {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: this.config.visConfig.colorRange,
- colorScale: this.config.colorScale,
- targetColor: this.config.visConfig.targetColor
+ const updateTriggers = {
+ getPosition: this.config.columns,
+ getFilterValue: gpuFilter.filterValueUpdateTriggers,
+ ...this.getVisualChannelUpdateTriggers()
};
-
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
return [
@@ -227,16 +201,7 @@ export default class ArcLayer extends Layer {
...this.getBrushingExtensionProps(interactionConfig, 'source_target'),
...data,
widthScale: this.config.visConfig.thickness,
- updateTriggers: {
- getFilterValue: gpuFilter.filterValueUpdateTriggers,
- getWidth: {
- sizeField: this.config.sizeField,
- sizeScale: this.config.sizeScale,
- sizeRange: this.config.visConfig.sizeRange
- },
- getSourceColor: colorUpdateTriggers,
- getTargetColor: colorUpdateTriggers
- },
+ updateTriggers,
extensions: [...defaultLayerProps.extensions, new BrushingExtension()]
}),
// hover layer
diff --git a/src/layers/base-layer.js b/src/layers/base-layer.js
index 05b54a651..c2703831a 100644
--- a/src/layers/base-layer.js
+++ b/src/layers/base-layer.js
@@ -39,7 +39,12 @@ import {
} from 'constants/default-settings';
import {COLOR_RANGES} from 'constants/color-ranges';
import {DataVizColors} from 'constants/custom-color-ranges';
-import {LAYER_VIS_CONFIGS, DEFAULT_TEXT_LABEL, DEFAULT_COLOR_UI} from './layer-factory';
+import {
+ LAYER_VIS_CONFIGS,
+ DEFAULT_TEXT_LABEL,
+ DEFAULT_COLOR_UI,
+ UNKNOWN_COLOR_KEY
+} from './layer-factory';
import {generateHashId, isPlainObject} from 'utils/utils';
@@ -64,8 +69,10 @@ import {hexToRgb, getColorGroupByName, reverseColorRange} from 'utils/color-util
* @type {number}
*/
const MAX_SAMPLE_SIZE = 5000;
+const defaultDomain = [0, 1];
const dataFilterExtension = new DataFilterExtension({filterSize: MAX_GPU_FILTERS});
const identity = d => d;
+const defaultDataAccessor = d => d.data;
export const OVERLAY_TYPE = keymirror({
deckgl: null,
@@ -143,7 +150,9 @@ export default class Layer {
domain: 'colorDomain',
range: 'colorRange',
key: 'color',
- channelScaleType: CHANNEL_SCALES.color
+ channelScaleType: CHANNEL_SCALES.color,
+ nullValue: NO_VALUE_COLOR,
+ defaultValue: config => config.color
},
size: {
property: 'size',
@@ -152,7 +161,9 @@ export default class Layer {
domain: 'sizeDomain',
range: 'sizeRange',
key: 'size',
- channelScaleType: CHANNEL_SCALES.size
+ channelScaleType: CHANNEL_SCALES.size,
+ nullValue: 0,
+ defaultValue: 1
}
};
}
@@ -708,6 +719,78 @@ export default class Layer {
);
}
+ getColorScale(colorScale, colorDomain, colorRange) {
+ if (Array.isArray(colorRange.colorMap)) {
+ const cMap = new Map();
+ colorRange.colorMap.forEach(([k, v]) => {
+ cMap.set(k, typeof v === 'string' ? hexToRgb(v) : v);
+ });
+
+ const scale = SCALE_FUNC[SCALE_TYPES.ordinal]()
+ .domain(cMap.keys())
+ .range(cMap.values())
+ .unknown(cMap.get(UNKNOWN_COLOR_KEY) || NO_VALUE_COLOR);
+ return scale;
+ }
+
+ return this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
+ }
+
+ /**
+ * Mapping from visual channels to deck.gl accesors
+ * @param {Function} dataAccessor - access kepler.gl layer data from deck.gl layer
+ * @return {Object} attributeAccessors - deck.gl layer attribute accessors
+ */
+ getAttributeAccessors(dataAccessor = defaultDataAccessor) {
+ const attributeAccessors = {};
+
+ Object.keys(this.visualChannels).forEach(channel => {
+ const {
+ field,
+ fixed,
+ scale,
+ domain,
+ range,
+ accessor,
+ defaultValue,
+ getAttributeValue,
+ nullValue,
+ channelScaleType
+ } = this.visualChannels[channel];
+
+ const shouldGetScale = this.config[field];
+
+ if (shouldGetScale) {
+ const args = [this.config[scale], this.config[domain], this.config.visConfig[range]];
+ const isFixed = fixed && this.config.visConfig[fixed];
+
+ const scaleFunction =
+ channelScaleType === CHANNEL_SCALES.color
+ ? this.getColorScale(...args)
+ : this.getVisChannelScale(...args, isFixed);
+
+ attributeAccessors[accessor] = d =>
+ this.getEncodedChannelValue(
+ scaleFunction,
+ dataAccessor(d),
+ this.config[field],
+ nullValue
+ );
+ } else if (typeof getAttributeValue === 'function') {
+ attributeAccessors[accessor] = getAttributeValue(this.config);
+ } else {
+ attributeAccessors[accessor] =
+ typeof defaultValue === 'function' ? defaultValue(this.config) : defaultValue;
+ }
+
+ if (!attributeAccessors[accessor]) {
+ Console.warn(`Failed to provide accesso function for ${accessor || channel}`);
+ }
+ });
+
+ return attributeAccessors;
+ }
+
getVisChannelScale(scale, domain, range, fixed) {
return SCALE_FUNC[fixed ? 'linear' : scale]()
.domain(domain)
@@ -831,7 +914,6 @@ export default class Layer {
if (!newFilter || scaleType !== SCALE_TYPES.ordinal) {
const {domain} = channel;
const updatedDomain = this.calculateLayerDomain(dataset, channel);
-
this.updateLayerConfig({[domain]: updatedDomain});
}
});
@@ -912,9 +994,26 @@ export default class Layer {
this.updateLayerConfig({[visualChannel.domain]: updatedDomain});
}
+ getVisualChannelUpdateTriggers() {
+ const updateTriggers = {};
+ Object.values(this.visualChannels).forEach(visualChannel => {
+ // field range scale domain
+ const {accessor, field, scale, domain, range, defaultValue, fixed} = visualChannel;
+
+ updateTriggers[accessor] = {
+ [field]: this.config[field],
+ [scale]: this.config[scale],
+ [domain]: this.config[domain],
+ [range]: this.config.visConfig[range],
+ defaultValue: typeof defaultValue === 'function' ? defaultValue(this.config) : defaultValue,
+ ...(fixed ? {[fixed]: this.config.visConfig[fixed]} : {})
+ };
+ });
+ return updateTriggers;
+ }
+
calculateLayerDomain(dataset, visualChannel) {
const {allData, filteredIndexForDomain} = dataset;
- const defaultDomain = [0, 1];
const {scale} = visualChannel;
const scaleType = this.config[scale];
diff --git a/src/layers/geojson-layer/geojson-layer.js b/src/layers/geojson-layer/geojson-layer.js
index 1123ce4b6..bb82ef99b 100644
--- a/src/layers/geojson-layer/geojson-layer.js
+++ b/src/layers/geojson-layer/geojson-layer.js
@@ -23,7 +23,6 @@ import {DATA_TYPES} from 'type-analyzer';
import Layer, {colorMaker} from '../base-layer';
import {GeoJsonLayer as DeckGLGeoJsonLayer} from '@deck.gl/layers';
-import {hexToRgb} from 'utils/color-utils';
import {getGeojsonDataMaps, getGeojsonBounds, getGeojsonFeatureTypes} from './geojson-utils';
import GeojsonLayerIcon from './geojson-layer-icon';
import {GEOJSON_FIELDS, HIGHLIGH_COLOR_3D, CHANNEL_SCALES} from 'constants/default-settings';
@@ -62,6 +61,7 @@ export const geojsonVisConfigs = {
export const geoJsonRequiredColumns = ['geojson'];
export const featureAccessor = ({geojson}) => d => d[geojson.fieldIdx];
+// access feature properties from geojson sub layer
export const defaultElevation = 500;
export const defaultLineWidth = 1;
export const defaultRadius = 1;
@@ -92,8 +92,17 @@ export default class GeoJsonLayer extends Layer {
}
get visualChannels() {
+ const visualChannels = super.visualChannels;
return {
- ...super.visualChannels,
+ color: {
+ ...visualChannels.color,
+ accessor: 'getFillColor',
+ condition: config => config.visConfig.filled,
+ nullValue: visualChannels.color.nullValue,
+ getAttributeValue: config => d => d.properties.fillColor || config.color,
+ // used this to get updateTriggers
+ defaultValue: config => config.color
+ },
strokeColor: {
property: 'strokeColor',
field: 'strokeColorField',
@@ -102,12 +111,21 @@ export default class GeoJsonLayer extends Layer {
range: 'strokeColorRange',
key: 'strokeColor',
channelScaleType: CHANNEL_SCALES.color,
- condition: config => config.visConfig.stroked
+ accessor: 'getLineColor',
+ condition: config => config.visConfig.stroked,
+ nullValue: visualChannels.color.nullValue,
+ getAttributeValue: config => d =>
+ d.properties.lineColor || config.visConfig.strokeColor || config.color,
+ // used this to get updateTriggers
+ defaultValue: config => config.visConfig.strokeColor || config.color
},
size: {
- ...super.visualChannels.size,
+ ...visualChannels.size,
property: 'stroke',
- condition: config => config.visConfig.stroked
+ accessor: 'getLineWidth',
+ condition: config => config.visConfig.stroked,
+ nullValue: 0,
+ getAttributeValue: () => d => d.properties.lineWidth || defaultLineWidth
},
height: {
property: 'height',
@@ -117,7 +135,10 @@ export default class GeoJsonLayer extends Layer {
range: 'heightRange',
key: 'height',
channelScaleType: CHANNEL_SCALES.size,
- condition: config => config.visConfig.enable3d
+ accessor: 'getElevation',
+ condition: config => config.visConfig.enable3d,
+ nullValue: 0,
+ getAttributeValue: () => d => d.properties.elevation || defaultElevation
},
radius: {
property: 'radius',
@@ -126,7 +147,10 @@ export default class GeoJsonLayer extends Layer {
domain: 'radiusDomain',
range: 'radiusRange',
key: 'radius',
- channelScaleType: CHANNEL_SCALES.radius
+ channelScaleType: CHANNEL_SCALES.radius,
+ accessor: 'getRadius',
+ nullValue: 0,
+ getAttributeValue: () => d => d.properties.radius || defaultRadius
}
};
}
@@ -187,98 +211,20 @@ export default class GeoJsonLayer extends Layer {
calculateDataAttribute({allData, filteredIndex}, getPosition) {
return filteredIndex.map(i => this.dataToFeature[i]).filter(d => d);
}
- // TODO: fix complexity
- /* eslint-disable complexity */
- formatLayerData(datasets, oldLayerData, opt = {}) {
- const {
- colorScale,
- colorField,
- colorDomain,
- strokeColorField,
- strokeColorScale,
- strokeColorDomain,
- color,
- sizeScale,
- sizeDomain,
- sizeField,
- heightField,
- heightDomain,
- heightScale,
- radiusField,
- radiusDomain,
- radiusScale,
- visConfig
- } = this.config;
-
- const {
- enable3d,
- stroked,
- colorRange,
- heightRange,
- sizeRange,
- radiusRange,
- strokeColorRange,
- strokeColor
- } = visConfig;
+ formatLayerData(datasets, oldLayerData) {
const {allData, gpuFilter} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
-
- // fill color
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
-
- // stroke color
- const scScale =
- strokeColorField &&
- this.getVisChannelScale(
- strokeColorScale,
- strokeColorDomain,
- strokeColorRange.colors.map(hexToRgb)
- );
-
- // calculate stroke scale - if stroked = true
- const sScale =
- sizeField && stroked && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange);
-
- // calculate elevation scale - if extruded = true
- const eScale =
- heightField && enable3d && this.getVisChannelScale(heightScale, heightDomain, heightRange);
-
- // point radius
- const rScale = radiusField && this.getVisChannelScale(radiusScale, radiusDomain, radiusRange);
-
- // access feature properties from geojson sub layer
- const getDataForGpuFilter = f => allData[f.properties.index];
- const getIndexForGpuFilter = f => f.properties.index;
+ const valueAccessor = f => allData[f.properties.index];
+ const indexAccessor = f => f.properties.index;
+ const accessors = this.getAttributeAccessors(valueAccessor);
return {
data,
- getFilterValue: gpuFilter.filterValueAccessor(getIndexForGpuFilter, getDataForGpuFilter),
- getFillColor: d =>
- cScale
- ? this.getEncodedChannelValue(cScale, allData[d.properties.index], colorField)
- : d.properties.fillColor || color,
- getLineColor: d =>
- scScale
- ? this.getEncodedChannelValue(scScale, allData[d.properties.index], strokeColorField)
- : d.properties.lineColor || strokeColor || color,
- getLineWidth: d =>
- sScale
- ? this.getEncodedChannelValue(sScale, allData[d.properties.index], sizeField, 0)
- : d.properties.lineWidth || defaultLineWidth,
- getElevation: d =>
- eScale
- ? this.getEncodedChannelValue(eScale, allData[d.properties.index], heightField, 0)
- : d.properties.elevation || defaultElevation,
- getRadius: d =>
- rScale
- ? this.getEncodedChannelValue(rScale, allData[d.properties.index], radiusField, 0)
- : d.properties.radius || defaultRadius
+ getFilterValue: gpuFilter.filterValueAccessor(indexAccessor, valueAccessor),
+ ...accessors
};
}
- /* eslint-enable complexity */
updateLayerMeta(allData) {
const getFeature = this.getPositionAccessor();
@@ -335,31 +281,7 @@ export default class GeoJsonLayer extends Layer {
};
const updateTriggers = {
- getElevation: {
- heightField: this.config.heightField,
- heightScaleType: this.config.heightScale,
- heightRange: visConfig.heightRange
- },
- getFillColor: {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: visConfig.colorRange,
- colorScale: this.config.colorScale
- },
- getLineColor: {
- color: visConfig.strokeColor,
- colorField: this.config.strokeColorField,
- colorRange: visConfig.strokeColorRange,
- colorScale: this.config.strokeColorScale
- },
- getLineWidth: {
- sizeField: this.config.sizeField,
- sizeRange: visConfig.sizeRange
- },
- getRadius: {
- radiusField: this.config.radiusField,
- radiusRange: visConfig.radiusRange
- },
+ ...this.getVisualChannelUpdateTriggers(),
getFilterValue: gpuFilter.filterValueUpdateTriggers
};
diff --git a/src/layers/h3-hexagon-layer/h3-hexagon-layer.js b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
index 1b1c1cca4..5630e2c95 100644
--- a/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
+++ b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
@@ -25,7 +25,6 @@ import EnhancedColumnLayer from 'deckgl-layers/column-layer/enhanced-column-laye
import {getCentroid, idToPolygonGeo, h3IsValid, getHexFields} from './h3-utils';
import H3HexagonLayerIcon from './h3-hexagon-layer-icon';
import {CHANNEL_SCALES, HIGHLIGH_COLOR_3D} from 'constants/default-settings';
-import {hexToRgb} from 'utils/color-utils';
const DEFAULT_LINE_SCALE_VALUE = 8;
@@ -69,11 +68,19 @@ export default class HexagonIdLayer extends Layer {
}
get visualChannels() {
+ const visualChannels = super.visualChannels;
return {
- ...super.visualChannels,
+ color: {
+ ...visualChannels.color,
+ accessor: 'getFillColor'
+ },
size: {
- ...super.visualChannels.size,
- property: 'height'
+ ...visualChannels.size,
+ property: 'height',
+ accessor: 'getElevation',
+ nullValue: 0,
+ condition: config => config.visConfig.enable3d,
+ defaultValue: defaultElevation
},
coverage: {
property: 'coverage',
@@ -82,7 +89,10 @@ export default class HexagonIdLayer extends Layer {
domain: 'coverageDomain',
range: 'coverageRange',
key: 'coverage',
- channelScaleType: CHANNEL_SCALES.radius
+ channelScaleType: CHANNEL_SCALES.radius,
+ accessor: 'getCoverage',
+ nullValue: 0,
+ defaultValue: defaultCoverage
}
};
}
@@ -142,58 +152,16 @@ export default class HexagonIdLayer extends Layer {
// TODO: fix complexity
/* eslint-disable complexity */
formatLayerData(datasets, oldLayerData, opt = {}) {
- const {
- colorScale,
- colorDomain,
- colorField,
- color,
- sizeField,
- sizeScale,
- sizeDomain,
- coverageField,
- coverageScale,
- coverageDomain,
- visConfig: {sizeRange, colorRange, coverageRange, enable3d}
- } = this.config;
-
const {gpuFilter} = datasets[this.config.dataId];
const getHexId = this.getPositionAccessor();
const {data} = this.updateData(datasets, oldLayerData);
- // color
- const cScale =
- colorField &&
- this.getVisChannelScale(
- colorScale,
- colorDomain,
- colorRange.colors.map(c => hexToRgb(c))
- );
- // height
- const sScale =
- sizeField && enable3d && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange, 0);
-
- // coverage
- const coScale =
- coverageField && this.getVisChannelScale(coverageScale, coverageDomain, coverageRange, 0);
-
- const getElevation = sScale
- ? d => this.getEncodedChannelValue(sScale, d.data, sizeField, 0)
- : defaultElevation;
-
- const getFillColor = cScale
- ? d => this.getEncodedChannelValue(cScale, d.data, colorField)
- : color;
-
- const getCoverage = coScale
- ? d => this.getEncodedChannelValue(coScale, d.data, coverageField, 0)
- : defaultCoverage;
+ const accessors = this.getAttributeAccessors();
return {
data,
- getElevation,
- getFillColor,
getHexId,
- getCoverage,
- getFilterValue: gpuFilter.filterValueAccessor()
+ getFilterValue: gpuFilter.filterValueAccessor(),
+ ...accessors
};
}
/* eslint-enable complexity */
@@ -221,28 +189,17 @@ export default class HexagonIdLayer extends Layer {
const eleZoomFactor = this.getElevationZoomFactor(mapState);
const {config} = this;
const {visConfig} = config;
+ const updateTriggers = this.getVisualChannelUpdateTriggers();
const h3HexagonLayerTriggers = {
- getFillColor: {
- color: config.color,
- colorField: config.colorField,
- colorRange: visConfig.colorRange,
- colorScale: config.colorScale
- },
- getElevation: {
- sizeField: config.sizeField,
- sizeRange: visConfig.sizeRange,
- sizeScale: config.sizeScale,
- enable3d: visConfig.enable3d
- },
+ getHexagon: this.config.columns,
+ getFillColor: updateTriggers.getFillColor,
+ getElevation: updateTriggers.getElevation,
getFilterValue: gpuFilter.filterValueUpdateTriggers
};
const columnLayerTriggers = {
- getCoverage: {
- coverageField: config.coverageField,
- coverageRange: visConfig.coverageRange
- }
+ getCoverage: updateTriggers.getCoverage
};
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
diff --git a/src/layers/icon-layer/icon-layer.js b/src/layers/icon-layer/icon-layer.js
index 9fde08c48..3c0cc0fba 100644
--- a/src/layers/icon-layer/icon-layer.js
+++ b/src/layers/icon-layer/icon-layer.js
@@ -21,7 +21,6 @@
import window from 'global/window';
import {BrushingExtension} from '@deck.gl/extensions';
-import {hexToRgb} from 'utils/color-utils';
import SvgIconLayer from 'deckgl-layers/svg-icon-layer/svg-icon-layer';
import IconLayerIcon from './icon-layer-icon';
import {ICON_FIELDS, CLOUDFRONT} from 'constants/default-settings';
@@ -90,12 +89,18 @@ export default class IconLayer extends Layer {
get visualChannels() {
return {
- ...super.visualChannels,
+ color: {
+ ...super.visualChannels.color,
+ accessor: 'getFillColor',
+ defaultValue: config => config.color
+ },
size: {
...super.visualChannels.size,
- range: 'radiusRange',
property: 'radius',
- channelScaleType: 'radius'
+ range: 'radiusRange',
+ channelScaleType: 'radius',
+ accessor: 'getRadius',
+ defaultValue: 1
}
};
}
@@ -196,37 +201,13 @@ export default class IconLayer extends Layer {
return data;
}
- formatLayerData(datasets, oldLayerData, opt = {}) {
- const {
- colorScale,
- colorDomain,
- colorField,
- color,
- sizeField,
- sizeScale,
- sizeDomain,
- textLabel,
- visConfig: {radiusRange, colorRange}
- } = this.config;
+ formatLayerData(datasets, oldLayerData) {
+ const {textLabel} = this.config;
const getPosition = this.getPositionAccessor();
const {gpuFilter} = datasets[this.config.dataId];
const {data, triggerChanged} = this.updateData(datasets, oldLayerData);
- // point color
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
-
- // point radius
- const rScale = sizeField && this.getVisChannelScale(sizeScale, sizeDomain, radiusRange, 0);
-
- const getRadius = rScale ? d => this.getEncodedChannelValue(rScale, d.data, sizeField) : 1;
-
- const getFillColor = cScale
- ? d => this.getEncodedChannelValue(cScale, d.data, colorField)
- : color;
-
// get all distinct characters in the text labels
const textLabels = formatTextLabelData({
textLabel,
@@ -235,13 +216,14 @@ export default class IconLayer extends Layer {
data
});
+ const accessors = this.getAttributeAccessors();
+
return {
data,
getPosition,
- getFillColor,
getFilterValue: gpuFilter.filterValueAccessor(),
- getRadius,
- textLabels
+ textLabels,
+ ...accessors
};
}
@@ -261,18 +243,9 @@ export default class IconLayer extends Layer {
};
const updateTriggers = {
+ getPosition: this.config.columns,
getFilterValue: gpuFilter.filterValueUpdateTriggers,
- getRadius: {
- sizeField: this.config.colorField,
- radiusRange: this.config.visConfig.radiusRange,
- sizeScale: this.config.sizeScale
- },
- getFillColor: {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: this.config.visConfig.colorRange,
- colorScale: this.config.colorScale
- }
+ ...this.getVisualChannelUpdateTriggers()
};
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
diff --git a/src/layers/layer-factory.js b/src/layers/layer-factory.js
index cd02802b2..73007b6b2 100644
--- a/src/layers/layer-factory.js
+++ b/src/layers/layer-factory.js
@@ -55,6 +55,8 @@ export const DEFAULT_CUSTOM_PALETTE = {
colors: []
};
+export const UNKNOWN_COLOR_KEY = '__unknownColor__';
+
/** @type {import('./layer-factory').ColorUI} */
export const DEFAULT_COLOR_UI = {
// customPalette in edit
diff --git a/src/layers/line-layer/line-layer.js b/src/layers/line-layer/line-layer.js
index efc9c3e1b..77f9ab976 100644
--- a/src/layers/line-layer/line-layer.js
+++ b/src/layers/line-layer/line-layer.js
@@ -33,6 +33,17 @@ export default class LineLayer extends ArcLayer {
return LineLayerIcon;
}
+ get visualChannels() {
+ const visualChannels = super.visualChannels;
+ return {
+ ...visualChannels,
+ sourceColor: {
+ ...visualChannels.sourceColor,
+ accessor: 'getColor'
+ }
+ };
+ }
+
static findDefaultLayerProps({fieldPairs = []}) {
if (fieldPairs.length < 2) {
return {props: []};
@@ -58,14 +69,11 @@ export default class LineLayer extends ArcLayer {
widthScale: this.config.visConfig.thickness
};
- const colorUpdateTriggers = {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: this.config.visConfig.colorRange,
- colorScale: this.config.colorScale,
- targetColor: this.config.visConfig.targetColor
+ const updateTriggers = {
+ getPosition: this.config.columns,
+ getFilterValue: gpuFilter.filterValueUpdateTriggers,
+ ...this.getVisualChannelUpdateTriggers()
};
-
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
return [
// base layer
@@ -74,17 +82,7 @@ export default class LineLayer extends ArcLayer {
...this.getBrushingExtensionProps(interactionConfig, 'source_target'),
...data,
...layerProps,
- getColor: data.getSourceColor,
- updateTriggers: {
- getFilterValue: gpuFilter.filterValueUpdateTriggers,
- getWidth: {
- sizeField: this.config.sizeField,
- sizeRange: this.config.visConfig.sizeRange,
- sizeScale: this.config.sizeScale
- },
- getColor: colorUpdateTriggers,
- getTargetColor: colorUpdateTriggers
- },
+ updateTriggers,
extensions: [...defaultLayerProps.extensions, new BrushingExtension()]
}),
// hover layer
diff --git a/src/layers/point-layer/point-layer.js b/src/layers/point-layer/point-layer.js
index 31792bb6b..41b35e556 100644
--- a/src/layers/point-layer/point-layer.js
+++ b/src/layers/point-layer/point-layer.js
@@ -98,23 +98,30 @@ export default class PointLayer extends Layer {
return {
color: {
...super.visualChannels.color,
- condition: config => config.visConfig.filled
+ accessor: 'getFillColor',
+ condition: config => config.visConfig.filled,
+ defaultValue: config => config.color
},
strokeColor: {
property: 'strokeColor',
+ key: 'strokeColor',
field: 'strokeColorField',
scale: 'strokeColorScale',
domain: 'strokeColorDomain',
range: 'strokeColorRange',
- key: 'strokeColor',
channelScaleType: CHANNEL_SCALES.color,
- condition: config => config.visConfig.outline
+ accessor: 'getLineColor',
+ condition: config => config.visConfig.outline,
+ defaultValue: config => config.visConfig.strokeColor || config.color
},
size: {
...super.visualChannels.size,
- range: 'radiusRange',
property: 'radius',
- channelScaleType: 'radius'
+ range: 'radiusRange',
+ fixed: 'fixedRadius',
+ channelScaleType: 'radius',
+ accessor: 'getRadius',
+ defaultValue: 1
}
};
}
@@ -188,52 +195,10 @@ export default class PointLayer extends Layer {
}
formatLayerData(datasets, oldLayerData) {
- const {
- colorScale,
- colorDomain,
- colorField,
- strokeColorField,
- strokeColorScale,
- strokeColorDomain,
- color,
- sizeField,
- sizeScale,
- sizeDomain,
- textLabel,
- visConfig: {radiusRange, fixedRadius, colorRange, strokeColorRange, strokeColor}
- } = this.config;
-
+ const {textLabel} = this.config;
const {gpuFilter} = datasets[this.config.dataId];
const {data, triggerChanged} = this.updateData(datasets, oldLayerData);
const getPosition = this.getPositionAccessor();
- // point color
-
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
-
- // stroke color
- const scScale =
- strokeColorField &&
- this.getVisChannelScale(
- strokeColorScale,
- strokeColorDomain,
- strokeColorRange.colors.map(hexToRgb)
- );
-
- // point radius
- const rScale =
- sizeField && this.getVisChannelScale(sizeScale, sizeDomain, radiusRange, fixedRadius);
-
- const getRadius = rScale ? d => this.getEncodedChannelValue(rScale, d.data, sizeField, 0) : 1;
-
- const getFillColor = cScale
- ? d => this.getEncodedChannelValue(cScale, d.data, colorField)
- : color;
-
- const getLineColor = scScale
- ? d => this.getEncodedChannelValue(scScale, d.data, strokeColorField)
- : strokeColor || color;
// get all distinct characters in the text labels
const textLabels = formatTextLabelData({
@@ -243,14 +208,14 @@ export default class PointLayer extends Layer {
data
});
+ const accessors = this.getAttributeAccessors();
+
return {
data,
getPosition,
- getFillColor,
- getLineColor,
getFilterValue: gpuFilter.filterValueAccessor(),
- getRadius,
- textLabels
+ textLabels,
+ ...accessors
};
}
/* eslint-enable complexity */
@@ -263,7 +228,6 @@ export default class PointLayer extends Layer {
renderLayer(opts) {
const {data, gpuFilter, objectHovered, mapState, interactionConfig} = opts;
-
const radiusScale = this.getRadiusScaleByZoom(mapState);
const layerProps = {
@@ -276,25 +240,8 @@ export default class PointLayer extends Layer {
const updateTriggers = {
getPosition: this.config.columns,
- getRadius: {
- sizeField: this.config.sizeField,
- radiusRange: this.config.visConfig.radiusRange,
- fixedRadius: this.config.visConfig.fixedRadius,
- sizeScale: this.config.sizeScale
- },
- getFillColor: {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: this.config.visConfig.colorRange,
- colorScale: this.config.colorScale
- },
- getLineColor: {
- color: this.config.visConfig.strokeColor,
- colorField: this.config.strokeColorField,
- colorRange: this.config.visConfig.strokeColorRange,
- colorScale: this.config.strokeColorScale
- },
- getFilterValue: gpuFilter.filterValueUpdateTriggers
+ getFilterValue: gpuFilter.filterValueUpdateTriggers,
+ ...this.getVisualChannelUpdateTriggers()
};
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
diff --git a/src/layers/s2-geometry-layer/s2-geometry-layer.js b/src/layers/s2-geometry-layer/s2-geometry-layer.js
index 0fd8767b5..bfb75bd91 100644
--- a/src/layers/s2-geometry-layer/s2-geometry-layer.js
+++ b/src/layers/s2-geometry-layer/s2-geometry-layer.js
@@ -19,7 +19,6 @@
// THE SOFTWARE.
import {S2Layer} from '@deck.gl/geo-layers';
-import {hexToRgb} from 'utils/color-utils';
import {HIGHLIGH_COLOR_3D, CHANNEL_SCALES} from 'constants/default-settings';
import {LAYER_VIS_CONFIGS} from 'layers/layer-factory';
import Layer from '../base-layer';
@@ -33,7 +32,7 @@ export const S2_TOKEN_FIELDS = {
};
export const s2RequiredColumns = ['token'];
-export const S2TokenAccessor = ({token}) => d => d[token.fieldIdx];
+export const S2TokenAccessor = ({token}) => d => d.data[token.fieldIdx];
export const defaultElevation = 500;
export const defaultLineWidth = 1;
@@ -91,21 +90,18 @@ export default class S2GeometryLayer extends Layer {
}
get visualChannels() {
+ const visualChannels = super.visualChannels;
return {
- ...super.visualChannels,
color: {
- property: 'color',
- field: 'colorField',
- scale: 'colorScale',
- domain: 'colorDomain',
- range: 'colorRange',
- key: 'color',
- channelScaleType: CHANNEL_SCALES.color
+ ...visualChannels.color,
+ accessor: 'getFillColor'
},
size: {
- ...super.visualChannels.size,
+ ...visualChannels.size,
property: 'stroke',
- condition: config => config.visConfig.stroked
+ accessor: 'getLineWidth',
+ condition: config => config.visConfig.stroked,
+ defaultValue: defaultLineWidth
},
strokeColor: {
property: 'strokeColor',
@@ -115,7 +111,10 @@ export default class S2GeometryLayer extends Layer {
range: 'strokeColorRange',
key: 'strokeColor',
channelScaleType: CHANNEL_SCALES.color,
- condition: config => config.visConfig.stroked
+ accessor: 'getLineColor',
+ condition: config => config.visConfig.stroked,
+ nullValue: visualChannels.color.nullValue,
+ defaultValue: config => config.visConfig.strokeColor || config.color
},
height: {
property: 'height',
@@ -125,7 +124,10 @@ export default class S2GeometryLayer extends Layer {
range: 'heightRange',
key: 'height',
channelScaleType: CHANNEL_SCALES.size,
- condition: config => config.visConfig.enable3d
+ accessor: 'getElevation',
+ condition: config => config.visConfig.enable3d,
+ nullValue: 0,
+ defaultValue: defaultElevation
}
};
}
@@ -165,7 +167,7 @@ export default class S2GeometryLayer extends Layer {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const token = getS2Token(allData[index]);
+ const token = getS2Token({data: allData[index]});
if (token) {
data.push({
@@ -181,7 +183,7 @@ export default class S2GeometryLayer extends Layer {
updateLayerMeta(allData, getS2Token) {
const centroids = allData.reduce((acc, entry) => {
- const s2Token = getS2Token(entry);
+ const s2Token = getS2Token({data: entry});
return s2Token ? [...acc, getS2Center(s2Token)] : acc;
}, []);
@@ -190,76 +192,20 @@ export default class S2GeometryLayer extends Layer {
this.updateMeta({bounds});
}
- /* eslint-disable complexity */
formatLayerData(datasets, oldLayerData, opt = {}) {
- const {
- colorScale,
- colorDomain,
- colorField,
- color,
- heightField,
- heightDomain,
- heightScale,
- strokeColorField,
- strokeColorScale,
- strokeColorDomain,
- sizeScale,
- sizeDomain,
- sizeField,
- visConfig
- } = this.config;
-
- const {
- enable3d,
- stroked,
- colorRange,
- heightRange,
- sizeRange,
- strokeColorRange,
- strokeColor
- } = visConfig;
-
const {gpuFilter} = datasets[this.config.dataId];
const getS2Token = this.getPositionAccessor();
const {data} = this.updateData(datasets, oldLayerData);
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
-
- // calculate elevation scale - if extruded = true
- const eScale =
- heightField && enable3d && this.getVisChannelScale(heightScale, heightDomain, heightRange);
-
- // stroke color
- const scScale =
- strokeColorField &&
- this.getVisChannelScale(
- strokeColorScale,
- strokeColorDomain,
- strokeColorRange.colors.map(hexToRgb)
- );
-
- // calculate stroke scale - if stroked = true
- const sScale =
- sizeField && stroked && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange);
+ const accessors = this.getAttributeAccessors();
return {
data,
getS2Token,
- getLineColor: d =>
- scScale
- ? this.getEncodedChannelValue(scScale, d.data, strokeColorField)
- : strokeColor || color,
- getLineWidth: d =>
- sScale ? this.getEncodedChannelValue(sScale, d.data, sizeField, 0) : defaultLineWidth,
- getFillColor: d => (cScale ? this.getEncodedChannelValue(cScale, d.data, colorField) : color),
- getElevation: d =>
- eScale ? this.getEncodedChannelValue(eScale, d.data, heightField, 0) : defaultElevation,
- getFilterValue: gpuFilter.filterValueAccessor()
+ getFilterValue: gpuFilter.filterValueAccessor(),
+ ...accessors
};
}
- /* eslint-enable complexity */
renderLayer(opts) {
const {data, gpuFilter, interactionConfig, mapState} = opts;
@@ -272,27 +218,7 @@ export default class S2GeometryLayer extends Layer {
const {visConfig} = config;
const updateTriggers = {
- getLineColor: {
- color: visConfig.strokeColor,
- colorField: config.strokeColorField,
- colorRange: visConfig.strokeColorRange,
- colorScale: config.strokeColorScale
- },
- getLineWidth: {
- sizeField: config.sizeField,
- sizeRange: visConfig.sizeRange
- },
- getFillColor: {
- color: config.color,
- colorField: config.colorField,
- colorRange: visConfig.colorRange,
- colorScale: config.colorScale
- },
- getElevation: {
- heightField: config.heightField,
- heightScaleType: config.heightScale,
- heightRange: visConfig.heightRange
- },
+ ...this.getVisualChannelUpdateTriggers(),
getFilterValue: gpuFilter.filterValueUpdateTriggers
};
diff --git a/src/layers/trip-layer/trip-layer.js b/src/layers/trip-layer/trip-layer.js
index 220ddd6ac..d430ead08 100644
--- a/src/layers/trip-layer/trip-layer.js
+++ b/src/layers/trip-layer/trip-layer.js
@@ -33,14 +33,12 @@ import {
} from 'layers/geojson-layer/geojson-utils';
import {isTripGeoJsonField, parseTripGeoJsonTimestamp} from './trip-utils';
-
-import {hexToRgb} from 'utils/color-utils';
import TripInfoModalFactory from './trip-info-modal';
const zoomFactorValue = 8;
export const defaultThickness = 0.5;
-export const defaultWidth = 1;
+export const defaultLineWidth = 1;
export const tripVisConfigs = {
opacity: 'opacity',
@@ -91,13 +89,25 @@ export default class TripLayer extends Layer {
}
get visualChannels() {
- return {
- ...super.visualChannels,
+ const visualChannels = super.visualChannels;
+ return {
+ ...visualChannels,
+ color: {
+ ...visualChannels.color,
+ accessor: 'getColor',
+ nullValue: visualChannels.color.nullValue,
+ getAttributeValue: config => d => d.properties.lineColor || config.color,
+ // used this to get updateTriggers
+ defaultValue: config => config.color
+ },
size: {
- ...super.visualChannels.size,
+ ...visualChannels.size,
property: 'stroke',
- condition: config => config.visConfig.stroked
+ accessor: 'getWidth',
+ condition: config => config.visConfig.stroked,
+ nullValue: 0,
+ getAttributeValue: () => d => d.properties.lineWidth || defaultLineWidth
}
};
}
@@ -177,45 +187,19 @@ export default class TripLayer extends Layer {
formatLayerData(datasets, oldLayerData) {
// to-do: parse segment from allData
-
- const {
- colorScale,
- colorField,
- colorDomain,
- color,
- sizeScale,
- sizeDomain,
- sizeField,
- visConfig
- } = this.config;
-
- const {colorRange, sizeRange} = visConfig;
const {allData, gpuFilter} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- // color
- const cScale =
- colorField &&
- this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
- // calculate stroke scale - if stroked = true
- const sScale = sizeField && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange);
- // access feature properties from geojson sub layer
- const getDataForGpuFilter = f => allData[f.properties.index];
- const getIndexForGpuFilter = f => f.properties.index;
+ const valueAccessor = f => allData[f.properties.index];
+ const indexAccessor = f => f.properties.index;
+ const accessors = this.getAttributeAccessors(valueAccessor);
return {
data,
- getFilterValue: gpuFilter.filterValueAccessor(getIndexForGpuFilter, getDataForGpuFilter),
+ getFilterValue: gpuFilter.filterValueAccessor(indexAccessor, valueAccessor),
getPath: d => d.geometry.coordinates,
getTimestamps: d => this.dataToTimeStamp[d.properties.index],
- getColor: d =>
- cScale
- ? this.getEncodedChannelValue(cScale, allData[d.properties.index], colorField)
- : d.properties.fillColor || color,
- getWidth: d =>
- sScale
- ? this.getEncodedChannelValue(sScale, allData[d.properties.index], sizeField, 0)
- : d.properties.lineWidth || defaultWidth
+ ...accessors
};
}
@@ -262,16 +246,7 @@ export default class TripLayer extends Layer {
const zoomFactor = this.getZoomFactor(mapState);
const updateTriggers = {
- getColor: {
- color: this.config.color,
- colorField: this.config.colorField,
- colorRange: visConfig.colorRange,
- colorScale: this.config.colorScale
- },
- getWidth: {
- sizeField: this.config.sizeField,
- sizeRange: visConfig.sizeRange
- },
+ ...this.getVisualChannelUpdateTriggers(),
getTimestamps: {
columns: this.config.columns,
domain0: animationConfig.domain[0]
diff --git a/src/localization/ca.js b/src/localization/ca.js
index a5d293492..ad0d717eb 100644
--- a/src/localization/ca.js
+++ b/src/localization/ca.js
@@ -317,7 +317,8 @@ export default {
tokenPlaceholder: "Enganxa el teu token d'accés a Mapbox",
tokenMisuseWarning:
'* Si no proporciones el teu propi token, el mapa podria fallar en qualsevol moment quan reemplacem el nostre token per evitar abusos. ',
- tokenDisclaimer: 'Pots canviar el toke de Mapbox més endavant fent servir aquestes instruccions: ',
+ tokenDisclaimer:
+ 'Pots canviar el toke de Mapbox més endavant fent servir aquestes instruccions: ',
tokenUpdate: 'Com actualitzar un token preexistent.',
modeTitle: 'Mode mapa',
modeSubtitle1: 'Selecciona mode app. Més ',
diff --git a/src/localization/en.js b/src/localization/en.js
index 772babded..da9119fe6 100644
--- a/src/localization/en.js
+++ b/src/localization/en.js
@@ -400,6 +400,7 @@ export default {
altitude: 'altitude',
icon: 'icon',
geojson: 'geojson',
+ token: 'token',
arc: {
lat0: 'source lat',
lng0: 'source lng',
diff --git a/src/localization/es.js b/src/localization/es.js
index 75373aedc..1c759fba8 100644
--- a/src/localization/es.js
+++ b/src/localization/es.js
@@ -150,7 +150,8 @@ export default {
highPrecisionRendering: 'Representación de alta precisión',
highPrecisionRenderingDescription: 'La precisión alta tendrá un rendimiento más bajo',
height: 'Altura',
- heightDescription: 'Haz clic en el botón de arriba a la derecha del mapa per cambiar a vista 3D',
+ heightDescription:
+ 'Haz clic en el botón de arriba a la derecha del mapa per cambiar a vista 3D',
fill: 'Rellenar',
enablePolygonHeight: 'Activar la altura del polígono',
showWireframe: 'Muestra esquemàtico',
@@ -317,7 +318,8 @@ export default {
tokenPlaceholder: 'Enganchar tu token de acceso a Mapbox',
tokenMisuseWarning:
'* Si no proporcionas tu propio token, el mapa podría fallar en cualquier momento cuando reemplacemos nuestro token para evitar abusos. ',
- tokenDisclaimer: 'Puedes cambiar el token de Mapbox posteriormente utilizando estas instrucciones: ',
+ tokenDisclaimer:
+ 'Puedes cambiar el token de Mapbox posteriormente utilizando estas instrucciones: ',
tokenUpdate: 'Como actualitzar un token preexistente.',
modeTitle: 'Modo mapa',
modeSubtitle1: 'Seleccionar modo app. Más ',
diff --git a/src/processors/index.js b/src/processors/index.js
index b7ddcd241..3ee4bf589 100644
--- a/src/processors/index.js
+++ b/src/processors/index.js
@@ -31,6 +31,11 @@ export {
} from './data-processor';
// File Handlers
-export {readFileInBatches, processFileData, filesToDataPayload, isKeplerGlMap} from './file-handler';
+export {
+ readFileInBatches,
+ processFileData,
+ filesToDataPayload,
+ isKeplerGlMap
+} from './file-handler';
export {Processors as default} from './data-processor';
diff --git a/src/reducers/map-state.js b/src/reducers/map-state.js
index 34d3ac34f..90bb33daf 100644
--- a/src/reducers/map-state.js
+++ b/src/reducers/map-state.js
@@ -37,6 +37,7 @@ const actionHandler = {
/* Reducer */
export const mapStateReducerFactory = (initialState = {}) =>
+ // @ts-ignore
handleActions(actionHandler, {
...mapStateUpdaters.INITIAL_MAP_STATE,
...initialState,
diff --git a/src/reducers/map-style.js b/src/reducers/map-style.js
index 5fe123b62..acf8441b3 100644
--- a/src/reducers/map-style.js
+++ b/src/reducers/map-style.js
@@ -43,6 +43,7 @@ const actionHandler = {
};
export const mapStyleReducerFactory = (initialState = {}) =>
+ // @ts-ignore
handleActions(actionHandler, {
...mapStyleUpdaters.INITIAL_MAP_STYLE,
...initialState,
diff --git a/src/reducers/provider-state.js b/src/reducers/provider-state.js
index 47712c020..d243003ea 100644
--- a/src/reducers/provider-state.js
+++ b/src/reducers/provider-state.js
@@ -43,6 +43,7 @@ const actionHandler = {
// construct provider-state reducer
export const providerStateReducerFactory = (initialState = {}) =>
+ // @ts-ignore
handleActions(actionHandler, {
...providerStateUpdaters.INITIAL_PROVIDER_STATE,
...initialState,
diff --git a/src/reducers/root.js b/src/reducers/root.js
index 2bc14485d..dcce7e97c 100644
--- a/src/reducers/root.js
+++ b/src/reducers/root.js
@@ -84,14 +84,14 @@ export function provideInitialState(initialState) {
});
// perform additional state reducing (e.g. switch action.type etc...)
- return handleActions(
- {
- [ActionTypes.REGISTER_ENTRY]: handleRegisterEntry,
- [ActionTypes.DELETE_ENTRY]: handleDeleteEntry,
- [ActionTypes.RENAME_ENTRY]: handleRenameEntry
- },
- initialCoreState
- )(state, action);
+ const handlers = {
+ [ActionTypes.REGISTER_ENTRY]: handleRegisterEntry,
+ [ActionTypes.DELETE_ENTRY]: handleDeleteEntry,
+ [ActionTypes.RENAME_ENTRY]: handleRenameEntry
+ };
+
+ // @ts-ignore
+ return handleActions(handlers, initialCoreState)(state, action);
};
}
diff --git a/src/reducers/ui-state.js b/src/reducers/ui-state.js
index 1d940a616..3185adc13 100644
--- a/src/reducers/ui-state.js
+++ b/src/reducers/ui-state.js
@@ -61,6 +61,7 @@ const actionHandler = {
/* Reducer */
export const uiStateReducerFactory = (initialState = {}) =>
+ // @ts-ignore
handleActions(actionHandler, {
...uiStateUpdaters.INITIAL_UI_STATE,
...initialState,
diff --git a/src/reducers/vis-state-updaters.d.ts b/src/reducers/vis-state-updaters.d.ts
index e6a81a00c..229013021 100644
--- a/src/reducers/vis-state-updaters.d.ts
+++ b/src/reducers/vis-state-updaters.d.ts
@@ -548,7 +548,7 @@ export function receiveMapConfigUpdater(
type?: ActionTypes.RECEIVE_MAP_CONFIG;
payload: ReceiveMapConfigPayload;
}
-);
+): VisState;
export const INITIAL_VIS_STATE: VisState;
export const DEFAULT_ANIMATION_CONFIG: AnimationConfig;
export const DEFAULT_EDITOR: Editor;
diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.js
index 377cdeebf..bac0541d4 100644
--- a/src/reducers/vis-state-updaters.js
+++ b/src/reducers/vis-state-updaters.js
@@ -728,9 +728,16 @@ export const addFilterUpdater = (state, action) =>
* @type {typeof import('./vis-state-updaters').layerColorUIChangeUpdater}
*/
export const layerColorUIChangeUpdater = (state, {oldLayer, prop, newConfig}) => {
+ const oldVixConfig = oldLayer.config.visConfig[prop];
const newLayer = oldLayer.updateLayerColorUI(prop, newConfig);
- if (prop === 'colorRange') {
- return layerVisConfigChangeUpdater(state, {oldLayer, newVisConfig: newLayer.config.visConfig});
+ const newVisConfig = newLayer.config.visConfig[prop];
+ if (oldVixConfig !== newVisConfig) {
+ return layerVisConfigChangeUpdater(state, {
+ oldLayer,
+ newVisConfig: {
+ [prop]: newVisConfig
+ }
+ });
}
return {
...state,
diff --git a/src/reducers/vis-state.js b/src/reducers/vis-state.js
index 5574ff82b..ffc27f435 100644
--- a/src/reducers/vis-state.js
+++ b/src/reducers/vis-state.js
@@ -134,6 +134,7 @@ const actionHandler = {
// construct vis-state reducer
export const visStateReducerFactory = (initialState = {}) =>
+ // @ts-ignore
handleActions(actionHandler, {
...visStateUpdaters.INITIAL_VIS_STATE,
...initialState,
diff --git a/src/schemas/vis-state-schema.js b/src/schemas/vis-state-schema.js
index 1c1b28070..4f6848752 100644
--- a/src/schemas/vis-state-schema.js
+++ b/src/schemas/vis-state-schema.js
@@ -309,22 +309,6 @@ class TextLabelSchemaV1 extends Schema {
}
const visualChannelModificationV1 = {
- point: (vc, parents, accumulator) => {
- const [layer] = parents.slice(-1);
-
- if (layer.config.visConfig.outline && vc.colorField && !vc.hasOwnProperty('strokeColorField')) {
- // point layer now supports both outline and fill
- // for older schema where filled has not been added to point layer
- // copy colorField, colorScale to strokeColorField, and strokeColorScale
- return {
- strokeColorField: vc.colorField,
- strokeColorScale: vc.colorScale,
- colorField: null,
- colorScale: 'quantile'
- };
- }
- return {};
- },
geojson: (vc, parents, accumulator) => {
const [layer] = parents.slice(-1);
const isOld = !vc.hasOwnProperty('strokeColorField');
diff --git a/src/utils/interaction-utils.js b/src/utils/interaction-utils.js
index 82e0ef3ba..b38df5cc8 100644
--- a/src/utils/interaction-utils.js
+++ b/src/utils/interaction-utils.js
@@ -152,7 +152,7 @@ export function getTooltipDisplayDeltaValue({
const deltaFormat =
compareType === COMPARE_TYPES.RELATIVE
? TOOLTIP_FORMATS.DECIMAL_PERCENT_FULL_2[TOOLTIP_KEY]
- : (item.format || TOOLTIP_FORMATS.DECIMAL_DECIMAL_FIXED_3[TOOLTIP_KEY]);
+ : item.format || TOOLTIP_FORMATS.DECIMAL_DECIMAL_FIXED_3[TOOLTIP_KEY];
displayDeltaValue = getFormatter(deltaFormat)(deltaValue);
diff --git a/src/utils/layer-utils.js b/src/utils/layer-utils.js
index e9dd7873d..2f9a8c0fc 100644
--- a/src/utils/layer-utils.js
+++ b/src/utils/layer-utils.js
@@ -107,3 +107,33 @@ export function getLayerHoverProp({
return null;
}
+
+export function renderDeckGlLayer(props, layerCallbacks, idx) {
+ const {
+ datasets,
+ layers,
+ layerData,
+ hoverInfo,
+ clicked,
+ mapState,
+ interactionConfig,
+ animationConfig
+ } = props;
+ const layer = layers[idx];
+ const data = layerData[idx];
+ const {gpuFilter} = datasets[layer.config.dataId] || {};
+
+ const objectHovered = clicked || hoverInfo;
+
+ // Layer is Layer class
+ return layer.renderLayer({
+ data,
+ gpuFilter,
+ idx,
+ interactionConfig,
+ layerCallbacks,
+ mapState,
+ animationConfig,
+ objectHovered
+ });
+}
diff --git a/test/browser.js b/test/browser.js
index e4a52e92c..a52ff851a 100644
--- a/test/browser.js
+++ b/test/browser.js
@@ -29,8 +29,8 @@ test.onFinish(window.browserTestDriver_finish);
test.onFailure(window.browserTestDriver_fail);
test('Browser tests', t => {
- require('./node/index.js');
- // require('./browser/index.js');
+ // require('./node/index.js');
+ require('./browser/index.js');
t.end();
});
diff --git a/test/browser/components/common/color-legend-test.js b/test/browser/components/common/color-legend-test.js
index 0c769a1fa..21b94db9b 100644
--- a/test/browser/components/common/color-legend-test.js
+++ b/test/browser/components/common/color-legend-test.js
@@ -33,7 +33,9 @@ test('Components -> ColorLegend.render', t => {
const fieldType = 'real';
const domain = [0, 20];
const scaleType = 'quantize';
- const range = ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300'];
+ const range = {
+ colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
+ };
const displayLabel = true;
const props = {
@@ -78,3 +80,61 @@ test('Components -> ColorLegend.render', t => {
t.end();
});
+
+test('Components -> ColorLegend.render', t => {
+ t.doesNotThrow(() => {
+ mountWithTheme(<ColorLegend />);
+ }, 'Show not fail without props');
+
+ const width = 180;
+ const range = {
+ colorMap: [
+ ['apple', '#C1C9CC'],
+ ['pear', '#DFB02F'],
+ ['car', '#7F8120'],
+ ['dog', '#DCD0A4'],
+ ['chicken', '#AD5633']
+ ]
+ };
+
+ const props = {
+ displayLabel: true,
+ range,
+ width
+ };
+
+ let wrapper = mountWithTheme(<ColorLegend {...props} />);
+ t.equal(wrapper.find(LegendRow).length, 5, 'Should render 5 legends');
+ let row1 = wrapper
+ .find(LegendRow)
+ .at(0)
+ .find('rect')
+ .at(0)
+ .html();
+
+ t.ok(row1.indexOf('fill: #C1C9CC'), 'should render color rect based on colorMap');
+ t.ok(row1.indexOf('apple'), 'should render color text based on colorMap');
+
+ props.range = {
+ colorLegends: {
+ '#DFB02F': 'Apple',
+ '#7F8120': 'Pear',
+ '#DCD0A4': 'Car',
+ '#AD5633': 'Dog',
+ '#C1C9CC': 'Chicken'
+ }
+ };
+
+ wrapper = mountWithTheme(<ColorLegend {...props} />);
+ t.equal(wrapper.find(LegendRow).length, 5, 'Should render 5 legends');
+ row1 = wrapper
+ .find(LegendRow)
+ .at(0)
+ .find('rect')
+ .at(0)
+ .html();
+
+ t.ok(row1.indexOf('fill: #DFB02F'), 'should render color rect based on colorMap');
+ t.ok(row1.indexOf('Apple'), 'should render color text based on colorMap');
+ t.end();
+});
diff --git a/test/browser/layer-tests/h3-hexagon-layer-specs.js b/test/browser/layer-tests/h3-hexagon-layer-specs.js
index eaa630d42..345b846b1 100644
--- a/test/browser/layer-tests/h3-hexagon-layer-specs.js
+++ b/test/browser/layer-tests/h3-hexagon-layer-specs.js
@@ -223,7 +223,7 @@ test('#H3Layer -> renderLayer', t => {
const TEST_CASES = [
{
- name: 'Test render h3.2 -> has icon geometry',
+ name: 'Test render h3.2',
layer: {
id: 'test_layer_1',
type: 'hexagonId',
diff --git a/test/browser/layer-tests/line-layer-specs.js b/test/browser/layer-tests/line-layer-specs.js
index 4f1147cbc..11bb7ffa1 100644
--- a/test/browser/layer-tests/line-layer-specs.js
+++ b/test/browser/layer-tests/line-layer-specs.js
@@ -107,7 +107,7 @@ test('#LineLayer -> formatLayerData', t => {
}
],
getFilterValue: () => {},
- getSourceColor: () => {},
+ getColor: () => {},
getTargetColor: () => {},
getWidth: () => {}
};
@@ -119,12 +119,8 @@ test('#LineLayer -> formatLayerData', t => {
'layerData should have 6 keys'
);
t.deepEqual(layerData.data, expectedLayerData.data, 'should format correct line layerData');
- // getSourceColor
- t.deepEqual(
- layerData.getSourceColor,
- layer.config.color,
- 'getSourceColor should be a constant'
- );
+ // getColor
+ t.deepEqual(layerData.getColor, layer.config.color, 'getColor should be a constant');
// getTargetColor
t.deepEqual(
layerData.getTargetColor,
@@ -171,7 +167,7 @@ test('#LineLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [],
getFilterValue: () => {},
- getSourceColor: () => {},
+ getColor: () => {},
getTargetColor: () => {},
getWidth: () => {}
};
@@ -182,13 +178,9 @@ test('#LineLayer -> formatLayerData', t => {
expectedDataKeys,
'layerData should have 6 keys'
);
- // getSourceColor
- t.deepEqual(
- layerData.getSourceColor,
- layer.config.color,
- 'getSourceColor should be a constant'
- );
- // getSourceColor
+ // getColor
+ t.deepEqual(layerData.getColor, layer.config.color, 'getColor should be a constant');
+ // getColor
t.deepEqual(layerData.getTargetColor, [1, 2, 3], 'getTargetColors should be a constant');
}
},
@@ -245,7 +237,7 @@ test('#LineLayer -> formatLayerData', t => {
}
],
getFilterValue: () => {},
- getSourceColor: () => {},
+ getColor: () => {},
getTargetColor: () => {},
getWidth: () => {}
};
@@ -261,16 +253,16 @@ test('#LineLayer -> formatLayerData', t => {
expectedLayerData.data,
'should format correct line layerData data'
);
- // getSourceColor
+ // getColor
// domain: ['driver_analytics', 'driver_analytics_0', 'driver_gps']
// range ['#010101', '#020202', '#030303']
t.deepEqual(
- layerData.data.map(layerData.getSourceColor),
+ layerData.data.map(layerData.getColor),
[
[2, 2, 2],
[1, 1, 1]
],
- 'getSourceColor should be correct'
+ 'getColor should be correct'
);
// getTargetColor
// domain: ['driver_analytics', 'driver_analytics_0', 'driver_gps']
diff --git a/test/browser/layer-tests/point-layer-specs.js b/test/browser/layer-tests/point-layer-specs.js
index 8ad8273a4..196380497 100644
--- a/test/browser/layer-tests/point-layer-specs.js
+++ b/test/browser/layer-tests/point-layer-specs.js
@@ -25,6 +25,7 @@ import {
testCreateCases,
testFormatLayerDataCases,
testRenderLayerCases,
+ testUpdateLayer,
preparedDataset,
dataId,
testRows,
@@ -632,3 +633,46 @@ test('#PointLayer -> renderLayer', t => {
testRenderLayerCases(t, PointLayer, TEST_CASES);
t.end();
});
+
+test('#PointLayer -> updateLayer', t => {
+ const layerConfig = {
+ id: 'test1',
+ type: 'point',
+ config: {
+ dataId,
+ label: 'some point file',
+ columns: {
+ lat: 'lat',
+ lng: 'lng'
+ },
+ visConfig: {
+ outline: true,
+ filled: true,
+ colorRange: {
+ colors: ['#010101', '#020202', '#030303']
+ },
+ strokeColor: [4, 5, 6]
+ }
+ },
+ visualChannels: {
+ // color by id(integer)
+ colorField: {
+ type: 'string',
+ name: 'types'
+ },
+ // size by id(integer)
+ sizeField: {
+ type: 'integer',
+ name: 'id'
+ }
+ }
+ };
+
+ const shouldUpdate = {
+ gpuFilter: {},
+ dynamicGpuFilter: {instanceRadius: true}
+ };
+
+ testUpdateLayer(t, {layerConfig, shouldUpdate});
+ t.end();
+});
diff --git a/test/browser/layer-tests/s2-geometry-layer-specs.js b/test/browser/layer-tests/s2-geometry-layer-specs.js
index db8a24f29..61de87ea2 100644
--- a/test/browser/layer-tests/s2-geometry-layer-specs.js
+++ b/test/browser/layer-tests/s2-geometry-layer-specs.js
@@ -19,15 +19,18 @@
// THE SOFTWARE.
import test from 'tape';
+import moment from 'moment';
+
import {
testCreateCases,
testFormatLayerDataCases,
- testRenderLayerCases
+ testRenderLayerCases,
+ preparedDataset,
+ dataId,
+ testRows,
+ preparedFilterDomain0
} from 'test/helpers/layer-utils';
-import {getGpuFilterProps} from 'utils/gpu-filter-utils';
-import {data} from 'test/fixtures/s2-geometry';
import S2GeometryLayer, {defaultElevation} from 'layers/s2-geometry-layer/s2-geometry-layer';
-import {processCsvData} from 'processors/data-processor';
test('#S2Geometry -> constructor', t => {
const TEST_CASES = [
@@ -67,86 +70,36 @@ test('#S2Geometry -> constructor', t => {
});
test('#S2Geometry -> formatLayerData', t => {
- const {rows, fields} = processCsvData(data);
-
- t.deepEqual(
- fields,
- [
- {
- name: 's2',
- format: '',
- tableFieldIndex: 1,
- type: 'string',
- analyzerType: 'STRING'
- },
- {
- name: 'value',
- format: '',
- tableFieldIndex: 2,
- type: 'real',
- analyzerType: 'FLOAT'
- }
- ],
- 'Should compute fields correctly'
- );
-
const filteredIndex = [0, 2, 4];
- const dataId = 'puppy';
-
- const nullRows = [
- [null, 12345],
- [null, 3456]
- ];
-
- const invalidRows = [
- [0, 12345],
- [1234, 3456],
- ['abcd', 123]
- ];
-
- const allRows = nullRows.concat(rows).concat(invalidRows);
- const dataset = {
- fields,
- rows,
- id: dataId,
- data: allRows,
- allData: allRows,
- filteredIndexForDomain: filteredIndex,
- filteredIndex,
- gpuFilter: getGpuFilterProps([], dataId, fields)
- };
-
- const props = {
- name: 's2 layer',
- layer: {
- type: 's2',
- id: 'test_layer_1',
- config: {
- dataId,
- label: 'S2',
- color: [255, 203, 153],
- columns: {
- token: 's2'
- },
- isVisible: true
- }
- },
- datasets: {
- [dataId]: dataset
- }
- };
-
const TEST_CASES = [
{
- ...props,
- data: [data, rows, filteredIndex, undefined],
+ name: 's2 layer',
+ layer: {
+ type: 's2',
+ id: 'test_layer_1',
+ config: {
+ dataId,
+ label: 'S2',
+ color: [2, 3, 4],
+ columns: {
+ token: 's2x'
+ },
+ isVisible: true
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
assert: result => {
const {layerData, layer} = result;
const expectedLayerData = {
data: [
- {index: 2, token: rows[0][0], data: rows[0]},
- {index: 4, token: rows[2][0], data: rows[2]}
+ {index: 0, token: '80858004', data: testRows[0]},
+ {index: 4, token: '8085801c', data: testRows[4]}
],
getElevation: () => {},
getFillColor: () => {},
@@ -156,17 +109,11 @@ test('#S2Geometry -> formatLayerData', t => {
getLineWidth: () => {}
};
- t.equal(
- layerData.getElevation(),
- defaultElevation,
- `Elevation should be set to ${defaultElevation}`
- );
-
// test layer.meta
t.deepEqual(
layer.meta,
{
- bounds: [-122.39575481805574, -50.18582525999928, 143.41537625914856, 37.81968456730113]
+ bounds: [-122.38442501650697, 37.79109908631398, -122.3617617587711, 37.81968456730113]
},
'should format correct S2 layer meta'
);
@@ -182,52 +129,110 @@ test('#S2Geometry -> formatLayerData', t => {
Object.keys(expectedLayerData).sort(),
`layerData should have ${expectedLayerData.length} keys`
);
+
+ t.deepEqual(layerData.getFillColor, [2, 3, 4], 'getFillColor should be a constant');
+ t.deepEqual(layerData.getElevation, defaultElevation, 'getElevation should be a constant');
+ t.deepEqual(
+ layerData.data.map(layerData.getS2Token),
+ ['80858004', '8085801c'],
+ 'getS2Token should return correct token'
+ );
+ // getFilterValue
+ t.deepEqual(
+ layerData.data.map(layerData.getFilterValue),
+ [
+ [Number.MIN_SAFE_INTEGER, 0, 0, 0],
+ [moment.utc(testRows[4][0]).valueOf() - preparedFilterDomain0, 0, 0, 0]
+ ],
+ 'getFilterValue should return [value, 0, 0, 0]'
+ );
}
},
{
- ...props,
- updates: [
- {method: 'updateLayerConfig', args: [{colorField: fields[1]}]},
- {method: 'updateLayerConfig', args: [{sizeField: fields[1]}]},
- {
- method: 'updateLayerVisualChannel',
- args: [dataset, 'color']
+ name: 's2 layer',
+ layer: {
+ type: 's2',
+ id: 'test_layer_1',
+ config: {
+ dataId,
+ label: 'S2',
+ color: [2, 3, 4],
+ columns: {
+ token: 's2x'
+ },
+ isVisible: true,
+ // color by types(string)
+ colorField: {
+ type: 'string',
+ name: 'types'
+ },
+ // size by id(integer)
+ heightField: {
+ type: 'real',
+ name: 'trip_distance'
+ },
+ sizeField: {
+ type: 'real',
+ name: 'trip_distance'
+ },
+ visConfig: {
+ colorRange: {
+ colors: ['#010101', '#020202', '#030303']
+ },
+ elevationRange: [10, 20],
+ sizeRange: [10, 20],
+ enable3d: true
+ }
}
- ],
- data: [allRows, allRows, filteredIndex, undefined],
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
assert: result => {
const {layerData} = result;
- const expectedLayerData = {
- data: [
- {index: 2, token: rows[0][0], data: rows[0]},
- {index: 4, token: rows[2][0], data: rows[2]}
+ // getFillColor
+ // domain: ['driver_analytics', 'driver_analytics_0', 'driver_gps']
+ // range ['#010101', '#020202', '#030303']
+ t.deepEqual(
+ layerData.data.map(layerData.getFillColor),
+ [
+ [2, 2, 2],
+ [1, 1, 1]
],
- getElevation: () => {},
- getFillColor: () => {},
- getFilterValue: () => {},
- getS2Token: () => {},
- getLineColor: () => {},
- getLineWidth: () => {}
- };
-
- t.ok(typeof layerData.getFillColor === 'function', 'should have getFillColor');
-
- t.ok(typeof layerData.getElevation === 'function', 'should have getElevation');
-
- t.ok(typeof layerData.getFilterValue === 'function', 'should have getFilterValue');
+ 'getFillColor should be correct'
+ );
- t.ok(typeof layerData.getS2Token === 'function', 'should have getS2Token');
+ // getElevation
+ // domain: [1.59, 11]
+ // range: [0, 500]
+ // value [1.59, 2.37]
+ t.deepEqual(
+ layerData.data.map(layerData.getElevation),
+ [0, 41.445270988310305],
+ 'getElevation should correct'
+ );
+ // getLineWidth
+ // domain: [1.59, 11]
+ // range: [10, 20]
+ // value [1.59, 2.37]
t.deepEqual(
- layerData.data,
- expectedLayerData.data,
- 'should format correct s2-geometry layerData and remove null values'
+ layerData.data.map(layerData.getLineWidth),
+ [10, (2.37 - 1.59) * (10 / 9.41) + 10],
+ 'getLineWidth should be correct'
);
+ // getFilterValue
t.deepEqual(
- Object.keys(layerData).sort(),
- Object.keys(expectedLayerData).sort(),
- `layerData should have ${Object.keys(expectedLayerData).length} keys`
+ layerData.data.map(layerData.getFilterValue),
+ [
+ [Number.MIN_SAFE_INTEGER, 0, 0, 0],
+ [moment.utc(testRows[4][0]).valueOf() - preparedFilterDomain0, 0, 0, 0]
+ ],
+ 'getFilterValue should return [value, 0, 0, 0]'
);
}
}
@@ -239,58 +244,30 @@ test('#S2Geometry -> formatLayerData', t => {
});
test('#S2Geometry -> renderLayer', t => {
- const {rows, fields} = processCsvData(data);
const filteredIndex = [0, 2, 4];
- const dataId = 'puppy';
-
- const nullRows = [
- [null, 12345],
- [null, 3456]
- ];
- const invalidRows = [
- [0, 12345],
- [1234, 3456],
- ['abcd', 123]
- ];
-
- const allRows = nullRows.concat(rows).concat(invalidRows);
-
- const dataset = {
- fields,
- rows,
- id: dataId,
- data: allRows,
- allData: allRows,
- filteredIndexForDomain: filteredIndex,
- filteredIndex,
- gpuFilter: getGpuFilterProps([], dataId, fields)
- };
-
- const props = {
- name: 's2 layer',
- layer: {
- type: 's2',
- id: 'test_layer_1',
- config: {
- dataId,
- label: 'S2',
- color: [255, 203, 153],
- columns: {
- token: 's2'
- },
- isVisible: true
- }
- },
- datasets: {
- [dataId]: dataset
- }
- };
-
const TEST_CASES = [
{
- ...props,
- data: [data, rows, filteredIndex, undefined],
+ name: 's2 layer',
+ layer: {
+ type: 's2',
+ id: 'test_layer_1',
+ config: {
+ dataId,
+ label: 'S2',
+ color: [2, 3, 4],
+ columns: {
+ token: 's2x'
+ },
+ isVisible: true
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
assert: (deckLayers, layer) => {
t.equal(layer.type, 's2', 'should create 1 s2 layer');
t.equal(deckLayers.length, 4, 'Should create 4 deck.gl layers');
@@ -312,12 +289,7 @@ test('#S2Geometry -> renderLayer', t => {
const expectedProps = {
opacity: layer.config.visConfig.opacity,
- filterRange: [
- [0, 0],
- [0, 0],
- [0, 0],
- [0, 0]
- ],
+ filterRange: preparedDataset.gpuFilter.filterRange,
filled: true,
wrapLongitude: false,
autoHighlight: false,
diff --git a/test/browser/layer-tests/trip-layer-specs.js b/test/browser/layer-tests/trip-layer-specs.js
index 551ea561d..cdc6b2d9f 100644
--- a/test/browser/layer-tests/trip-layer-specs.js
+++ b/test/browser/layer-tests/trip-layer-specs.js
@@ -22,7 +22,7 @@
import test from 'tape';
import cloneDeep from 'lodash.clonedeep';
-import TripLayer, {defaultWidth} from 'layers/trip-layer/trip-layer';
+import TripLayer, {defaultLineWidth} from 'layers/trip-layer/trip-layer';
import {
dataId,
@@ -127,7 +127,7 @@ test('#TripLayer -> formatLayerData', t => {
);
t.deepEqual(
layerData.data.map(layerData.getWidth),
- [defaultWidth, defaultWidth, defaultWidth],
+ [defaultLineWidth, defaultLineWidth, defaultLineWidth],
'getWidth should return correct value'
);
t.deepEqual(
diff --git a/test/fixtures/test-layer-data.js b/test/fixtures/test-layer-data.js
index 4ce428651..169b22653 100644
--- a/test/fixtures/test-layer-data.js
+++ b/test/fixtures/test-layer-data.js
@@ -18,16 +18,16 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-export default `utc_timestamp,lat,lng,lat_1,lng_1,types,has_result,id,hex_id,trip_distance,icon
-Null,37.778564,-122.39096,37.769897,-122.41168,driver_analytics_0,FALSE,1,89283082c2fffff,1.59,accel
-2016-09-17 00:10:56,37.78824,-122.40894,37.798237,-122.41889,null,FALSE,null,8928308288fffff,2.38,add-person
-2016-09-17 00:11:56,38.281445,NaN,37.76018,NaN,driver_analytics,FALSE,3,,2.83,alert
-2016-09-17 00:12:58,37.79354,-122.40121,37.37006,-121.96353,driver_gps,FALSE,4,89283082817ffff,8.33,android
-2016-09-17 00:14:00,37.456535,-122.136795,37.418655,-122.149734,driver_analytics,1,5,89283082c3bffff,2.37,
-2016-09-17 00:15:01,37.40066,-122.10239,37.787052,-122.41089,driver_analytics,FALSE,34,89283082883ffff,7.13,attach
-2016-09-17 00:16:03,Null,-122.42459,Null,-122.40495,driver_analytics,FALSE,222,89283082c33ffff,3.22,
-2016-09-17 00:17:05,37.879066,-122.26108,37.753033,-122.42929,driver_analytics,TRUE,345,89283082c23ffff,11,car-suv
-2016-09-17 00:18:09,37.775578,-122.39363,37.749577,-122.41829,driver_analytics,FALSE,43,89283082887ffff,4.12,car-taxi
+export default `utc_timestamp,lat,lng,lat_1,lng_1,types,has_result,id,hex_id,trip_distance,icon,s2x
+Null,37.778564,-122.39096,37.769897,-122.41168,driver_analytics_0,FALSE,1,89283082c2fffff,1.59,accel,80858004
+2016-09-17 00:10:56,37.78824,-122.40894,37.798237,-122.41889,null,FALSE,null,8928308288fffff,2.38,add-person,8085800c
+2016-09-17 00:11:56,38.281445,NaN,37.76018,NaN,driver_analytics,FALSE,3,,2.83,alert,
+2016-09-17 00:12:58,37.79354,-122.40121,37.37006,-121.96353,driver_gps,FALSE,4,89283082817ffff,8.33,android,80858014
+2016-09-17 00:14:00,37.456535,-122.136795,37.418655,-122.149734,driver_analytics,1,5,89283082c3bffff,2.37,,8085801c
+2016-09-17 00:15:01,37.40066,-122.10239,37.787052,-122.41089,driver_analytics,FALSE,34,89283082883ffff,7.13,attach,80858024
+2016-09-17 00:16:03,Null,-122.42459,Null,-122.40495,driver_analytics,FALSE,222,89283082c33ffff,3.22,,80858034
+2016-09-17 00:17:05,37.879066,-122.26108,37.753033,-122.42929,driver_analytics,TRUE,345,89283082c23ffff,11,car-suv,8085803c
+2016-09-17 00:18:09,37.775578,-122.39363,37.749577,-122.41829,driver_analytics,FALSE,43,89283082887ffff,4.12,car-taxi,80858044
`;
export const iconGeometry = {
diff --git a/test/helpers/layer-utils.js b/test/helpers/layer-utils.js
index 56c9e9404..f2d82fad3 100644
--- a/test/helpers/layer-utils.js
+++ b/test/helpers/layer-utils.js
@@ -29,14 +29,16 @@ import cloneDeep from 'lodash.clonedeep';
import {INITIAL_MAP_STATE} from 'reducers/map-state-updaters';
import {INITIAL_VIS_STATE} from 'reducers/vis-state-updaters';
import * as VisStateActions from 'actions/vis-state-actions';
+import {addDataToMap} from 'actions/actions';
import {colorMaker, layerColors} from 'layers/base-layer';
import {getGpuFilterProps} from 'utils/gpu-filter-utils';
+import {renderDeckGlLayer} from 'utils/layer-utils';
import {validateLayerWithData} from 'reducers/vis-state-merger';
import {LayerClasses} from 'layers';
import {processCsvData, processGeojson} from 'processors/data-processor';
-import {applyActions} from 'test/helpers/mock-state';
-import {visStateReducer} from 'reducers';
+import {applyActions, InitialState} from 'test/helpers/mock-state';
+import {visStateReducer, keplerGlReducerCore} from 'reducers';
// Fixtures
import csvData, {wktCsv} from 'test/fixtures/test-csv-data';
import testLayerData, {bounds, fieldDomain, iconGeometry} from 'test/fixtures/test-layer-data';
@@ -45,6 +47,10 @@ import tripGeoJson from 'test/fixtures/trip-geojson';
import {logStep} from '../../scripts/log';
import {IntlWrapper} from './component-utils';
+import mapState from '../../src/reducers/map-state';
+
+export const dataId = '0dj3h';
+export const timeFilter = [{name: 'utc_timestamp', value: [1474071095000, 1474071608000]}];
export function testCreateLayer(t, LayerClass, props = {}) {
let layer;
@@ -62,8 +68,7 @@ export function testCreateLayerFromConfig(t, tc) {
let layer;
t.doesNotThrow(() => {
- const {dataId} = layerConfig.config;
- layer = validateLayerWithData(datasets[dataId], layerConfig, LayerClasses);
+ layer = validateLayerWithData(datasets[layerConfig.config.dataId], layerConfig, LayerClasses);
t.ok(layer instanceof LayerClasses[layerConfig.type], `${layerConfig.type} layer created`);
layer.updateLayerDomain(datasets);
if (tc.afterLayerInitialized) {
@@ -112,17 +117,6 @@ export function testCreateCases(t, LayerClass, testCases) {
});
}
-export function testUpdateLayer(t, layer, updateMethod, updateArgs) {
- let result;
-
- t.doesNotThrow(() => {
- result = layer[updateMethod](...updateArgs);
- t.ok(layer, `layer ${updateMethod} called`);
- }, 'update layer should not fail');
-
- return {result, layer};
-}
-
export function testFormatLayerDataCases(t, LayerClass, testCases) {
testCases.forEach(tc => {
logStep(`---> Test Format Layer Data ${tc.name}`);
@@ -135,7 +129,7 @@ export function testFormatLayerDataCases(t, LayerClass, testCases) {
// apply 1 or multiple updates
applyUpdates.forEach(update => {
- const updated = testUpdateLayer(t, updatedLayer, update.method, update.args);
+ const updated = testLayerUpdate(t, updatedLayer, update.method, update.args);
updatedLayer = updated.layer;
});
}
@@ -184,7 +178,7 @@ export function testRenderLayerCases(t, LayerClass, testCases) {
}
if (deckLayers) {
- const initialDeckLayers = testInitializeDeckLayer(t, layer.type, deckLayers, {viewport});
+ const initialDeckLayers = testRenderDeckLayer(t, layer.type, deckLayers, {viewport});
if (tc.assert) {
tc.assert(initialDeckLayers, layer, result);
@@ -193,18 +187,21 @@ export function testRenderLayerCases(t, LayerClass, testCases) {
});
}
-export function testInitializeDeckLayer(t, layerType, deckLayers, {viewport}) {
- const testViewport = new MapView().makeViewport({
- width: viewport.width,
- height: viewport.height,
- viewState: viewport
- });
+export function testRenderDeckLayer(t, layerType, deckLayers, {viewport, layerManager}) {
+ let deckLayerManager = layerManager;
+ if (!layerManager) {
+ const testViewport = new MapView().makeViewport({
+ width: viewport.width,
+ height: viewport.height,
+ viewState: viewport
+ });
+ deckLayerManager = new LayerManager(gl, {viewport: testViewport});
+ }
- const layerManager = new LayerManager(gl, {viewport: testViewport});
const spy = sinon.spy(Console, 'error');
t.doesNotThrow(
- () => layerManager.setLayers(Array.isArray(deckLayers) ? deckLayers : [deckLayers]),
+ () => deckLayerManager.setLayers(Array.isArray(deckLayers) ? deckLayers : [deckLayers]),
`initialization of ${layerType} layer render should not fail`
);
@@ -212,7 +209,130 @@ export function testInitializeDeckLayer(t, layerType, deckLayers, {viewport}) {
t.deepEqual(spy.args, [], 'should not call console.error during layer initialization');
spy.restore();
- return layerManager.layers;
+ return deckLayerManager.getLayers();
+}
+
+export function testLayerUpdate(t, layer, updateMethod, updateArgs) {
+ let result;
+ t.doesNotThrow(() => {
+ result = layer[updateMethod](...updateArgs);
+ t.ok(layer, `layer ${updateMethod} called`);
+ }, 'update layer should not fail');
+
+ return {result, layer};
+}
+
+function testAttributeUpdate(t, attributeValues, layer, shouldUpdate) {
+ Object.keys(attributeValues).forEach(key => {
+ const newValue = layer.state.attributeManager.attributes[key].value;
+ if (shouldUpdate[key]) {
+ t.notDeepEqual(attributeValues[key], newValue, `attribute${key} should update`);
+ } else {
+ t.deepEqual(attributeValues[key], newValue, `attribute${key} should not update`);
+ }
+
+ attributeValues[key] = [...newValue];
+ });
+}
+
+export function renderLayerByState(t, state, layerManager) {
+ const layerCallbacks = () => {};
+ const layer = state.visState.layers[0];
+
+ let layerOverlay;
+ t.doesNotThrow(() => {
+ layerOverlay = renderDeckGlLayer(
+ {
+ ...state.visState,
+ mapState: state.mapState
+ },
+ layerCallbacks,
+ 0
+ );
+ }, `${layer.type}.renderLayer should not fail`);
+ testRenderDeckLayer(t, layer.type, layerOverlay, {layerManager});
+
+ return {
+ layerManager,
+ deckGlLayers: layerManager.getLayers()
+ };
+}
+
+export function testUpdateLayer(t, {layerConfig, shouldUpdate}) {
+ const initialState = cloneDeep(InitialState);
+ const filter0 = {
+ dataId,
+ id: 'me',
+ type: 'timeRange',
+ ...timeFilter[0]
+ };
+ const filter1 = {
+ dataId,
+ id: 'me2',
+ type: 'range',
+ name: 'trip_distance',
+ value: [3, 8.33]
+ };
+
+ const stateWithLayer = keplerGlReducerCore(
+ initialState,
+ addDataToMap({
+ datasets: {
+ info: {id: dataId},
+ data: processCsvData(testLayerData)
+ },
+ config: {
+ version: 'v1',
+ config: {
+ visState: {
+ layers: [layerConfig],
+ filters: [filter0, filter1]
+ }
+ }
+ }
+ })
+ );
+
+ const layer = stateWithLayer.visState.layers[0];
+ t.ok(layer, 'should create layer');
+
+ const testViewport = new MapView().makeViewport({
+ width: mapState.width,
+ height: mapState.height,
+ viewState: mapState
+ });
+
+ const layerManager = new LayerManager(gl, {viewport: testViewport});
+
+ let rendered = renderLayerByState(t, stateWithLayer, layerManager);
+ const attributeValues = Object.keys(
+ rendered.deckGlLayers[0].state.attributeManager.attributes
+ ).reduce(
+ (accu, key) => ({
+ ...accu,
+ [key]: [...rendered.deckGlLayers[0].state.attributeManager.attributes[key].value]
+ }),
+ {}
+ );
+
+ // update Gpu Filter
+ let stateWithFilterUpdate = keplerGlReducerCore(
+ stateWithLayer,
+ VisStateActions.setFilter(0, 'value', [filter0.value[0] + 1, filter0.value[1]], 0)
+ );
+
+ rendered = renderLayerByState(t, stateWithFilterUpdate, rendered.layerManager);
+ logStep(`---> test: set GPU filter value`);
+ testAttributeUpdate(t, attributeValues, rendered.deckGlLayers[0], shouldUpdate.gpuFilter);
+
+ // update dynamic domain gpu Filter
+ stateWithFilterUpdate = keplerGlReducerCore(
+ stateWithFilterUpdate,
+ VisStateActions.setFilter(1, 'value', [filter1.value[0] + 0.5, filter1.value[1]], 0)
+ );
+ rendered = renderLayerByState(t, stateWithFilterUpdate, rendered.layerManager);
+ logStep(`---> test: set dynamic domain GPU filter value`);
+ testAttributeUpdate(t, attributeValues, rendered.deckGlLayers[0], shouldUpdate.dynamicGpuFilter);
}
/**
@@ -268,7 +388,6 @@ function addFilterToData(data, id, filters) {
export const {rows, fields} = processCsvData(csvData);
export const {rows: testRows, fields: testFields} = processCsvData(testLayerData);
-export const dataId = '0dj3h';
export {
dataId as tripDataId,
fields as tripFields,
@@ -278,7 +397,6 @@ export {
/*
* point, arc, hex, csv dataset from with gpu time filter
*/
-const timeFilter = [{name: 'utc_timestamp', value: [1474071095000, 1474071608000]}];
const stateWithTimeFilter = addFilterToData(
{fields: testFields, rows: testRows},
diff --git a/website/src/components/common/styles.js b/website/src/components/common/styles.js
index 42bca1b62..d0b054fcf 100644
--- a/website/src/components/common/styles.js
+++ b/website/src/components/common/styles.js
@@ -90,7 +90,7 @@ export const Container = styled.div`
${media.palm`
padding-top: ${props => props.theme.margins.large};
- `}
+ `};
`;
export const Content = styled.div`
diff --git a/website/src/components/walkthrough.js b/website/src/components/walkthrough.js
index 1d3f5cfa5..81f7d0c1e 100644
--- a/website/src/components/walkthrough.js
+++ b/website/src/components/walkthrough.js
@@ -40,8 +40,7 @@ const VideoContainer = styled.div`
width: 640px;
${media.portable`
width: 500px;
- `}
- ${media.palm`
+ `} ${media.palm`
width: 100%;
`};