Skip to content

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

[Feat] add custom color editor (#601)

hannah yan han533af2db9b22
diff --git a/docs/user-guides/a-introduction.md b/docs/user-guides/a-introduction.md
index b6561cc93..8f37d9fb6 100644
--- a/docs/user-guides/a-introduction.md
+++ b/docs/user-guides/a-introduction.md
@@ -38,6 +38,8 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da
#### [Layer attributes](./d-layer-attributes.md)
+#### [Layer color](./d-color-attributes.md)
+
#### [Filters](./e-filters.md)
#### Map styles
@@ -50,8 +52,8 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da
#### [Map settings](./g-map-settings.md)
-#### [Time Playback](./h-playback.md)
+#### [Time playback](./h-playback.md)
-#### [Save and Export](./k-save-and-export.md)
+#### [Save and export](./k-save-and-export.md)
#### [FAQ](./i-FAQ.md)
diff --git a/docs/user-guides/d-layer-attributes.md b/docs/user-guides/d-layer-attributes.md
index 3be7f8fc3..01a551d81 100644
--- a/docs/user-guides/d-layer-attributes.md
+++ b/docs/user-guides/d-layer-attributes.md
@@ -1,6 +1,7 @@
# Layer Attributes
+
| Layer Attribute | Description | Available in |
-|------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------|
+| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------- |
| Color/Color based on | Choose the color of your layer or assign color based on a field from your dataset(s). | All layers |
| High-precision rendering | Activate high-precision rendering when zooming in closely on a layer. High-precision rendering sometimes results in a performance cost. | Point, Arc, Line, Icon, GeoJSON, Hexagon, Grid |
| Radius/Radius based on | Change the radius of points or assign radius values based on a field from your dataset(s). | Point, Icon, GeoJSON |
@@ -10,14 +11,14 @@
| Stroke width/stroke width based on | Change the thickness of lines and arcs, or assign a width based on a field from your dataset(s). | Arc, line, Geojson |
| Stroke width range | Set a lower and upper threshold for projected stroke width. | Arc, Line, Geojson |
| Grid size | Change the number of square kilometers covered by each grid square. | Grid |
-| Color Palette | Choose from multiple, predefined color palettes to apply to your layer. Palettes are either Uber or ColorBrewer colors. | All layers |
+| Color Palette | Choose from multiple, predefined or customized color palettes to apply to your layer. Predefined palettes are either Uber or ColorBrewer colors. | All layers |
| Color Scale | Choose either a quantile or quantized color scale. A quantile color scale is determined by rank, while a quantized color scale is determined by value. | All layers |
| Height based on | Assign grid square height based on a field from your dataset. | Grid, Hexagon |
| Filter by count percentile | Increase or decrease the number of grid squares by choosing a range of percentiles to display. | Grid, Hexagon |
| Coverage | Change what portion of each grid cell is covered by a color square. | Grid, Hexagon |
| Height Scale | Change the height of the grid squares or hexagons when in 3D mode. | Grid, Hexagon |
| Stroked | When activated, draws outlines around geoshapes. | GeoJSON, Point |
-| Filled | When activated, geo shapes are filled in with colors. | GeoJSON |
+| Filled | When activated, geo shapes are filled in with colors. | GeoJSON |
| Extruded | In 3D mode, assign polygon height values based on some value from your dataset. | GeoJSON |
| Wireframe | Create outlines around extruded polygons. | GeoJSON |
| Stroke or radius based on | Control the radius/thickness of GeoJSON line and point features. | GeoJSON |
diff --git a/docs/user-guides/l-color-attributes.md b/docs/user-guides/l-color-attributes.md
new file mode 100644
index 000000000..a9a260744
--- /dev/null
+++ b/docs/user-guides/l-color-attributes.md
@@ -0,0 +1,21 @@
+# Color Palettes
+
+Color palettes pride both predefined and customized options and can be applied to either fill or stroke. Predefined palettes comes in diverging, sequential and qualitative types.
+
+To choose a palette:
+
+1. Expand layer pane and click on the color bar from either filled color or stroke color section. Click on the three dots to select the field to color by.
+
+<img src="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/l-color-attributes-0.png" alt="expand" width="500"/>
+
+2. To choose a custom palette, toggle on custom button. Click on each color to pick new color either by clicking on the color picker or inputting HEX/RGB values. Colors steps can be added, removed or shuffled.
+
+<img src="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/l-color-attributes-1.png" alt="toggle" width="300"/>
+<img src="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/l-color-attributes-2.png" alt="toggle" width="300"/>
+
+
+3) Your color is applied to your map as soon as you select the predefined palette or confirm the choices of customized colors.
+
+<img src="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/l-color-attributes-3.png" alt="toggle" width="500"/>
+
+[Back to table of contents](./a-introduction.md)
diff --git a/package.json b/package.json
index 9da45e312..e546c659b 100644
--- a/package.json
+++ b/package.json
@@ -73,7 +73,6 @@
"@mapbox/geojson-extent": "^0.3.2",
"@mapbox/geojson-normalize": "0.0.1",
"@mapbox/vector-tile": "^1.3.1",
- "array-move": "^2.0.0",
"classnames": "^2.2.1",
"colorbrewer": "^1.0.0",
"d3-array": "^1.2.0",
@@ -103,6 +102,7 @@
"moment": "^2.10.6",
"pbf": "^3.1.0",
"prop-types": "^15.6.0",
+ "react-color": "^2.17.3",
"react-file-drop": "^0.1.9",
"react-json-pretty": "^1.7.9",
"react-map-gl": "^5.0.3",
@@ -210,7 +210,9 @@
"sourceMap": false,
"instrument": false,
"exclude": [
- "test/**/*.js"
+ "test/**/*.js",
+ "src/tasks/*.js",
+ "src/templates/*.js"
]
},
"maintainers": [
diff --git a/src/actions/ui-state-actions.js b/src/actions/ui-state-actions.js
index 53b84e107..e2d6e1e66 100644
--- a/src/actions/ui-state-actions.js
+++ b/src/actions/ui-state-actions.js
@@ -233,7 +233,7 @@ export const setUserMapboxAccessToken = createAction(
);
/**
- * Set the expor tmap format (html, json)
+ * Set the export map format (html, json)
* @memberOf uiStateActions
* @param {string} payload - map format
* @public
diff --git a/src/actions/vis-state-actions.js b/src/actions/vis-state-actions.js
index 1929c52dd..fd26460df 100644
--- a/src/actions/vis-state-actions.js
+++ b/src/actions/vis-state-actions.js
@@ -107,6 +107,23 @@ export function layerVisConfigChange(oldLayer, newVisConfig) {
};
}
+/**
+ * Set the color palette ui for layer color
+ * @memberOf visStateActions
+ * @param {Object} oldLayer - layer to be updated
+ * @param {String} prop - which color prop
+ * @param {object} newConfig - to be merged
+ * @public
+ */
+export function layerColorUIChange(oldLayer, prop, newConfig) {
+ return {
+ type: ActionTypes.LAYER_COLOR_UI_CHANGE,
+ oldLayer,
+ prop,
+ newConfig
+ };
+};
+
/**
* Update layer blending mode
* @memberof visStateActions
diff --git a/src/components/common/item-selector/item-selector.js b/src/components/common/item-selector/item-selector.js
index 2291e8b4d..33b73abbd 100644
--- a/src/components/common/item-selector/item-selector.js
+++ b/src/components/common/item-selector/item-selector.js
@@ -51,7 +51,9 @@ function _toArray(item) {
return [item];
}
-const StyledDropdownSelect = styled.div`
+const StyledDropdownSelect = styled.div.attrs({
+ className: 'item-selector__dropdown'
+})`
${props =>
props.inputTheme === 'secondary'
? props.theme.secondaryInput
@@ -79,7 +81,7 @@ const DropdownWrapper = styled.div`
border: 0;
width: 100%;
left: 0;
- z-index: 100;
+ z-index: ${props => props.theme.dropdownWrapperZ};
position: absolute;
bottom: ${props =>
props.placement === 'top' ? props.theme.inputBoxHeight : 'auto'};
@@ -253,7 +255,7 @@ class ItemSelector extends Component {
);
const dropdownSelectProps = {
- className: classnames(`item-selector__dropdown`, {
+ className: classnames({
active: this.state.showTypeahead
}),
disabled: this.props.disabled,
diff --git a/src/components/common/modal.js b/src/components/common/modal.js
index 129ed8870..d34a29ed5 100644
--- a/src/components/common/modal.js
+++ b/src/components/common/modal.js
@@ -43,22 +43,22 @@ const ModalContentWrapper = styled.div`
box-sizing: border-box;
font-size: 12px;
color: ${props => props.theme.labelColorLT};
-
+
${media.portable`
padding: 12px 36px 24px;
max-width: 80vw;
`}
-
+
${media.palm`
max-width: 100vw;
`}
-
+
${props => props.cssStyle || ''};
`;
const ModalContent = styled.div`
position: relative;
- z-index: 10002;
+ z-index: ${props => props.theme.modalContentZ};
`;
export const ModalTitle = styled.div`
@@ -66,7 +66,7 @@ export const ModalTitle = styled.div`
color: ${props => props.theme.modalTitleColor};
margin-bottom: 10px;
position: relative;
- z-index: 10003;
+ z-index: ${props => props.theme.modalTitleZ};
`;
const StyledModalFooter = styled.div`
@@ -84,14 +84,14 @@ const StyledModalFooter = styled.div`
${media.palm`
padding-top: 16px;
`};
- z-index: 10001;
+ z-index: ${props => props.theme.modalFooterZ};
`;
const CloseButton = styled.div`
color: ${props => props.theme.titleColorLT};
display: flex;
justify-content: flex-end;
- z-index: 10005;
+ z-index: ${props => props.theme.modalButtonZ};
position: absolute;
top: 24px;
right: 24px;
@@ -172,8 +172,8 @@ class ModalDialog extends Component {
ariaHideApp={false}
style={{
overlay: {
- backgroundColor: 'rgba(0, 0, 0, 0.5)',
- zIndex: 1000,
+ backgroundColor: (props.theme && props.theme.modalOverlayBgd) || 'rgba(0, 0, 0, 0.5)',
+ zIndex: (props.theme && props.theme.modalOverLayZ) || 1000,
// in case we want to override the modal dialog style
...props.style
}
diff --git a/src/components/kepler-gl.js b/src/components/kepler-gl.js
index bfc876eb6..cf58276ae 100644
--- a/src/components/kepler-gl.js
+++ b/src/components/kepler-gl.js
@@ -49,10 +49,10 @@ import {theme as basicTheme, themeLT} from 'styles/base';
// Maybe we should think about exporting this or creating a variable
// as part of the base.js theme
const GlobalStyle = styled.div`
- font-family: ff-clan-web-pro, 'Helvetica Neue', Helvetica, sans-serif;
- font-weight: 400;
- font-size: 0.875em;
- line-height: 1.71429;
+ font-family: ${props => props.theme.fontFamily};
+ font-weight: ${props => props.theme.fontWeight};
+ font-size: ${props => props.theme.fontSize};
+ line-height: ${props => props.theme.lineHeight};
*,
*:before,
diff --git a/src/components/side-panel.js b/src/components/side-panel.js
index 076d509a7..a1b9ff1f8 100644
--- a/src/components/side-panel.js
+++ b/src/components/side-panel.js
@@ -43,7 +43,7 @@ import {
const SidePanelContent = styled.div`
${props => props.theme.sidePanelScrollBar};
flex-grow: 1;
- padding: 16px;
+ padding: ${props => props.theme.sidePanelInnerPadding}px;
overflow-y: scroll;
overflow-x: hidden;
`;
@@ -150,6 +150,7 @@ export default function SidePanelFactory(
const layerManagerActions = {
addLayer: visStateActions.addLayer,
layerConfigChange: visStateActions.layerConfigChange,
+ layerColorUIChange: visStateActions.layerColorUIChange,
layerTextLabelChange: visStateActions.layerTextLabelChange,
layerVisualChannelConfigChange:
visStateActions.layerVisualChannelConfigChange,
@@ -160,7 +161,8 @@ export default function SidePanelFactory(
showDatasetTable: this._showDatasetTable,
showAddDataModal: this._showAddDataModal,
removeLayer: visStateActions.removeLayer,
- removeDataset: this._removeDataset
+ removeDataset: this._removeDataset,
+ openModal: uiStateActions.toggleModal
};
const filterManagerActions = {
@@ -223,7 +225,7 @@ export default function SidePanelFactory(
layerClasses={layerClasses}
layerOrder={layerOrder}
layerBlending={layerBlending}
- openModal={uiStateActions.toggleModal}
+ colorPalette={uiState.colorPalette}
/>
)}
{activeSidePanel === 'filter' && (
diff --git a/src/components/side-panel/layer-manager.js b/src/components/side-panel/layer-manager.js
index db1147958..b443a6b46 100644
--- a/src/components/side-panel/layer-manager.js
+++ b/src/components/side-panel/layer-manager.js
@@ -19,11 +19,13 @@
// THE SOFTWARE.
import React, {Component} from 'react';
+import classnames from 'classnames';
+
import PropTypes from 'prop-types';
import {sortableContainer, sortableElement} from 'react-sortable-hoc';
import styled from 'styled-components';
import {createSelector} from 'reselect';
-import arrayMove from 'array-move';
+import {arrayMove} from 'utils/data-utils';
import LayerPanelFactory from './layer-panel/layer-panel';
import SourceDataCatalogFactory from './common/source-data-catalog';
@@ -38,46 +40,6 @@ import {
import {LAYER_BLENDINGS} from 'constants/default-settings';
-const StyledSortable = styled.div`
- .ui-sortable {
- display: block;
- position: relative;
- overflow: visible;
- user-select: none;
-
- :before {
- content: ' ';
- display: table;
- }
-
- :after {
- content: ' ';
- display: table;
- }
- }
-
- .ui-sortable-item.ui-sortable-dragging {
- position: absolute;
- z-index: 1688;
- cursor: move;
- }
-
- .ui-sortable-item.ui-sortable-dragging:hover {
- cursor: move;
- opacity: 0.5;
- }
-
- .ui-sortable-placeholder {
- display: none;
- }
-
- .ui-sortable-placeholder.visible {
- display: block;
- opacity: 0;
- z-index: -1;
- }
-`;
-
const LayerBlendingSelector = ({layerBlending, updateLayerBlending}) => (
<SidePanelSection>
<PanelLabel>Layer Blending</PanelLabel>
@@ -92,8 +54,30 @@ const LayerBlendingSelector = ({layerBlending, updateLayerBlending}) => (
);
// make sure the element is always visible while is being dragged
+// item being dragged is appended in body, here to reset its global style
const SortableStyledItem = styled.div`
- z-index: 100;
+ z-index: ${props => props.theme.dropdownWrapperZ + 1};
+
+ &.sorting {
+ pointer-events: none;
+ }
+
+ &.sorting-layers .layer-panel__header {
+ background-color: ${props => props.theme.panelBackgroundHover};
+ font-family: ${props => props.theme.fontFamily};
+ font-weight: ${props => props.theme.fontWeight};
+ font-size: ${props => props.theme.fontSize};
+ line-height: ${props => props.theme.lineHeight};
+ *,
+ *:before,
+ *:after {
+ box-sizing: border-box;
+ }
+ .layer__drag-handle {
+ opacity: 1;
+ color: ${props => props.theme.textColorHl};
+ }
+ }
`;
export function AddDataButtonFactory() {
@@ -120,10 +104,11 @@ LayerManagerFactory.deps = [
function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
// By wrapping layer panel using a sortable element we don't have to implement the drag and drop logic into the panel itself;
// Developers can provide any layer panel implementation and it will still be sortable
- const SortableItem = sortableElement(({layer}) => {
+ const SortableItem = sortableElement(({children, isSorting}) => {
return (
- <SortableStyledItem>
- <LayerPanel {...layer} />
+ <SortableStyledItem
+ className={classnames('sortable-layer-items', {sorting: isSorting})}>
+ {children}
</SortableStyledItem>
);
});
@@ -134,11 +119,13 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
return class LayerManager extends Component {
static propTypes = {
- addLayer: PropTypes.func.isRequired,
datasets: PropTypes.object.isRequired,
layerBlending: PropTypes.string.isRequired,
layerClasses: PropTypes.object.isRequired,
layers: PropTypes.arrayOf(PropTypes.any).isRequired,
+ // functions
+ addLayer: PropTypes.func.isRequired,
+ layerColorUIChange: PropTypes.func.isRequired,
layerConfigChange: PropTypes.func.isRequired,
layerTextLabelChange: PropTypes.func.isRequired,
layerVisualChannelConfigChange: PropTypes.func.isRequired,
@@ -151,6 +138,9 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
updateLayerBlending: PropTypes.func.isRequired,
updateLayerOrder: PropTypes.func.isRequired
};
+ state = {
+ isSorting: false
+ }
layerClassSelector = props => props.layerClasses;
layerTypeOptionsSelector = createSelector(
@@ -170,14 +160,29 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
_handleSort = ({oldIndex, newIndex}) => {
this.props.updateLayerOrder(arrayMove(this.props.layerOrder, oldIndex, newIndex));
+ this.setState({isSorting: false});
};
+ _onSortStart = () => {
+ this.setState({isSorting: true});
+ };
+
+ _updateBeforeSortStart = ({index}) => {
+ // if layer config is active, close it
+ const {layerOrder, layers, layerConfigChange} = this.props;
+ const layerIdx = layerOrder[index];
+ if (layers[layerIdx].config.isConfigActive) {
+ layerConfigChange(layers[layerIdx], {isConfigActive: false});
+ }
+ }
+
render() {
const {layers, datasets, layerOrder, openModal} = this.props;
const defaultDataset = Object.keys(datasets)[0];
const layerTypeOptions = this.layerTypeOptionsSelector(this.props);
const layerActions = {
+ layerColorUIChange: this.props.layerColorUIChange,
layerConfigChange: this.props.layerConfigChange,
layerVisualChannelConfigChange: this.props.layerVisualChannelConfigChange,
layerTypeChange: this.props.layerTypeChange,
@@ -189,7 +194,7 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
const panelProps = {datasets, openModal, layerTypeOptions};
return (
- <StyledSortable className="layer-manager">
+ <div className="layer-manager">
<SourceDataCatalog
datasets={datasets}
showDatasetTable={this.props.showDatasetTable}
@@ -204,26 +209,28 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
<SidePanelSection>
<SortableContainer
onSortEnd={this._handleSort}
+ onSortStart={this._onSortStart}
+ updateBeforeSortStart={this._updateBeforeSortStart}
lockAxis="y"
- useDragHandle={true}
+ helperClass="sorting-layers"
+ useDragHandle
>
- {layerOrder.map((layerIdx, index) => {
- const layer = {
- ...panelProps,
- ...layerActions,
- sortData: layerIdx,
- key: layers[layerIdx].id,
- idx: layerIdx,
- layer: layers[layerIdx]
- };
- return (
- <SortableItem
- key={`layer-${layerIdx}`}
- index={index}
- layer={layer}
+ {layerOrder.map((layerIdx, index) => (
+ <SortableItem
+ key={`layer-${layerIdx}`}
+ index={index}
+ isSorting={this.state.isSorting}
+ >
+ <LayerPanel
+ {...panelProps}
+ {...layerActions}
+ sortData={layerIdx}
+ key={layers[layerIdx].id}
+ idx={layerIdx}
+ layer={layers[layerIdx]}
/>
- );
- })}
+ </SortableItem>
+ ))}
</SortableContainer>
</SidePanelSection>
<SidePanelSection>
@@ -237,7 +244,7 @@ function LayerManagerFactory(AddDataButton, LayerPanel, SourceDataCatalog) {
layerBlending={this.props.layerBlending}
updateLayerBlending={this.props.updateLayerBlending}
/>
- </StyledSortable>
+ </div>
);
}
}
diff --git a/src/components/side-panel/layer-panel/color-palette.js b/src/components/side-panel/layer-panel/color-palette.js
index 0713a77e4..2fb40ae3c 100644
--- a/src/components/side-panel/layer-panel/color-palette.js
+++ b/src/components/side-panel/layer-panel/color-palette.js
@@ -38,7 +38,9 @@ const defaultProps = {
isReversed: false
};
-const PaletteWrapper = styled.div`
+const PaletteWrapper = styled.div.attrs({
+ className: 'color-range-palette__inner'
+})`
border-radius: 2px;
display: flex;
flex-direction: row;
@@ -47,7 +49,9 @@ const PaletteWrapper = styled.div`
overflow: hidden;
`;
-const PaletteContainer = styled.div`
+const PaletteContainer = styled.div.attrs({
+ className: 'color-range-palette'
+})`
display: flex;
flex-grow: 1;
border-width: 1px;
@@ -57,21 +61,21 @@ const PaletteContainer = styled.div`
border-radius: 4px;
`;
-const ColorBlock = styled.div`
+const StyledColorBlock = styled.div.attrs({
+ className: 'color-range-palette__block'
+})`
flex-grow: 1;
`;
const ColorPalette = ({colors, height, className, isSelected, isReversed}) => (
<PaletteContainer
- className={`color-range-palette ${className}`}
+ className={className}
isSelected={isSelected}
>
- <PaletteWrapper className="color-range-palette__inner"
- style={{height, transform: `scale(${isReversed ? -1 : 1}, 1)`}}>
- {colors.map(color => (
- <ColorBlock
- className="color-range-palette__block"
- key={color}
+ <PaletteWrapper style={{height, transform: `scale(${isReversed ? -1 : 1}, 1)`}}>
+ {colors.map((color, index) => (
+ <StyledColorBlock
+ key={`${color}-${index}`}
style={{backgroundColor: color}}
/>
))}
diff --git a/src/components/side-panel/layer-panel/color-range-selector.js b/src/components/side-panel/layer-panel/color-range-selector.js
index 1036ca8df..5681b1e3f 100644
--- a/src/components/side-panel/layer-panel/color-range-selector.js
+++ b/src/components/side-panel/layer-panel/color-range-selector.js
@@ -22,117 +22,186 @@ import React, {Component} from 'react';
import PropTypes from 'prop-types';
import uniq from 'lodash.uniq';
import styled from 'styled-components';
+import {createSelector} from 'reselect';
+
import ItemSelector from 'components/common/item-selector/item-selector';
import {PanelLabel} from 'components/common/styled-components';
-import RangeSlider from 'components/common/range-slider';
import Switch from 'components/common/switch';
import ColorPalette from './color-palette';
-
+import CustomPalette from './custom-palette';
import {COLOR_RANGES} from 'constants/color-ranges';
import {numberSort} from 'utils/data-utils';
+import {reverseColorRange} from 'utils/color-utils';
-const ALL_TYPES = uniq(COLOR_RANGES.map(c => c.type).concat(['all']));
-const ALL_STEPS = uniq(COLOR_RANGES.map(d => d.colors.length)).sort(numberSort);
+export const ALL_TYPES = uniq(
+ COLOR_RANGES.map(c => c.type)
+ .filter(ctype => ctype)
+ .concat(['all', 'custom'])
+);
+
+export const ALL_STEPS = uniq(COLOR_RANGES.map(d => d.colors.length)).sort(numberSort);
const StyledColorConfig = styled.div`
padding: 12px 12px 0 12px;
`;
-const ColorRangeSelector = styled.div`
+const StyledColorRangeSelector = styled.div.attrs({
+ className: 'color-range-selector'
+})`
padding-bottom: 12px;
`;
+
+const StyledPaletteConfig = styled.div`
+ margin-bottom: 8px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ .color-palette__config__label {
+ flex-grow: 1;
+ }
+ .color-palette__config__select {
+ flex-grow: 1;
+ }
+ .item-selector .item-selector__dropdown {
+ ${props => props.theme.secondaryInput};
+ }
+`;
+
+const CONFIG_SETTINGS = {
+ type: {
+ type: 'select',
+ options: ALL_TYPES
+ },
+ steps: {
+ type: 'select',
+ options: ALL_STEPS
+ },
+ reversed: {
+ type: 'switch',
+ options: [true, false]
+ },
+ custom: {
+ label: 'Custom Palette',
+ type: 'switch',
+ options: [true, false]
+ }
+};
+
export default class ColorRangeSelect extends Component {
static propTypes = {
- colorRanges: PropTypes.arrayOf(PropTypes.any),
- selectedColorRange: PropTypes.object,
- onSelectColorRange: PropTypes.func.isRequired
+ colorPaletteUI: PropTypes.object.isRequired,
+ selectedColorRange: PropTypes.object.isRequired,
+ onSelectColorRange: PropTypes.func.isRequired,
+ setColorPaletteUI: PropTypes.func.isRequired,
+ // optional
+ colorRanges: PropTypes.arrayOf(PropTypes.any)
};
static defaultProps = {
colorRanges: COLOR_RANGES,
- onSelectColorRange: () => {}
+ onSelectColorRange: () => {},
+ setColorPaletteUI: () => {}
};
- state = {
- config: {
- type: {
- type: 'select',
- value: 'all',
- options: ALL_TYPES
- },
- steps: {
- type: 'select',
- value: 6,
- options: ALL_STEPS
- },
- reversed: {
- type: 'switch',
- value: false,
- options: [true, false]
- }
- }
- };
+ colorRangesSelector = props => props.colorRanges;
+ configTypeSelector = props => props.colorPaletteUI.colorRangeConfig.type;
+ configStepSelector = props => props.colorPaletteUI.colorRangeConfig.steps;
+ filteredColorRange = createSelector(
+ this.colorRangesSelector,
+ this.configTypeSelector,
+ this.configStepSelector,
+ (colorRanges, type, steps) => {
+ return colorRanges.filter(colorRange => {
+ const isType = type === 'all' || type === colorRange.type;
+ const isStep = Number(steps) === colorRange.colors.length;
- _updateConfig = ({key, value}) => {
- const currentValue = this.state.config[key].value;
- if (value !== currentValue) {
- this.setState({
- config: {
- ...this.state.config,
- [key]: {
- ...this.state.config[key],
- value
- }
- }
+ return isType && isStep;
});
}
+ );
+
+ _updateConfig = ({key, value}) => {
+ this._setColorRangeConfig({[key]: value});
+ };
+
+ _onSetCustomPalette = config => {
+ this.props.setColorPaletteUI({
+ customPalette: config
+ });
+ };
+
+ _setColorRangeConfig = newConfig => {
+ this.props.setColorPaletteUI({
+ colorRangeConfig: newConfig
+ });
+ };
+
+ _onCustomPaletteCancel = newConfig => {
+ this.props.setColorPaletteUI({
+ showSketcher: false,
+ colorRangeConfig: {custom: false}
+ });
+ };
+
+ _onToggleSketcher = val => {
+ this.props.setColorPaletteUI({
+ showSketcher: val
+ });
};
render() {
- const {config} = this.state;
+ const {
+ customPalette,
+ showSketcher,
+ colorRangeConfig
+ } = this.props.colorPaletteUI;
+
+ const filteredColorRanges = this.filteredColorRange(this.props);
+
return (
- <ColorRangeSelector className="color-range-selector">
+ <StyledColorRangeSelector>
<StyledColorConfig>
- {Object.keys(config).map(key => (
+ {(colorRangeConfig.custom
+ ? ['custom']
+ : Object.keys(colorRangeConfig)
+ ).map(key => (
<PaletteConfig
key={key}
- label={key}
- config={config[key]}
+ label={CONFIG_SETTINGS[key].label || key}
+ config={CONFIG_SETTINGS[key]}
+ value={colorRangeConfig[key]}
onChange={value => this._updateConfig({key, value})}
/>
))}
</StyledColorConfig>
- <ColorPaletteGroup
- config={config}
- colorRanges={this.props.colorRanges}
- onSelect={this.props.onSelectColorRange}
- selected={this.props.selectedColorRange}
- />
- </ColorRangeSelector>
+
+ {colorRangeConfig.custom ? (
+ <CustomPalette
+ customPalette={customPalette}
+ showSketcher={showSketcher}
+ selected={this.props.selectedColorRange}
+ onApply={this.props.onSelectColorRange}
+ onToggleSketcher={this._onToggleSketcher}
+ setCustomPalette={this._onSetCustomPalette}
+ onCancel={this._onCustomPaletteCancel}
+ />
+ ) : (
+ <ColorPaletteGroup
+ colorRanges={filteredColorRanges}
+ onSelect={this.props.onSelectColorRange}
+ selected={this.props.selectedColorRange}
+ reversed={colorRangeConfig.reversed}
+ />
+ )}
+ </StyledColorRangeSelector>
);
}
}
-const StyledPaletteConfig = styled.div`
- margin-bottom: 8px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- .color-palette__config__label {
- flex-grow: 1;
- }
- .color-palette__config__select {
- flex-grow: 1;
- }
- .item-selector .item-selector__dropdown {
- ${props => props.theme.secondaryInput};
- }
-`;
-
-const PaletteConfig = ({
- category,
+export const PaletteConfig = ({
label,
- config: {type, value, options},
+ value,
+ config: {type, options},
onChange
}) => (
<StyledPaletteConfig
@@ -153,26 +222,10 @@ const PaletteConfig = ({
/>
</div>
)}
- {type === 'slider' && (
- <div className="color-palette__config__slider">
- <div className="color-palette__config__slider__slider">
- <RangeSlider
- range={options}
- value0={options[0]}
- value1={value}
- step={1}
- isRanged={false}
- showInput={false}
- onChange={val => onChange(val[1])}
- />
- </div>
- <div className="color-palette__config__slider__number">{value}</div>
- </div>
- )}
{type === 'switch' && (
<Switch
checked={value}
- id={`${category}-${label}-toggle`}
+ id={`${label}-toggle`}
onChange={() => onChange(!value)}
secondary
/>
@@ -180,7 +233,9 @@ const PaletteConfig = ({
</StyledPaletteConfig>
);
-const StyledColorRange = styled.div`
+const StyledColorRange = styled.div.attrs({
+ className: 'color-palette-outer'
+})`
padding: 0 8px;
:hover {
background-color: ${props => props.theme.panelBackgroundHover};
@@ -188,48 +243,28 @@ const StyledColorRange = styled.div`
}
`;
-const ColorPaletteGroup = ({config = {}, onSelect, selected, colorRanges}) => {
- const {steps, reversed, type} = config;
-
- const filtered = colorRanges.filter(colorRange => {
- const isType =
- !type || type.value === 'all' || type.value === colorRange.type;
- const isStep = !steps || Number(steps.value) === colorRange.colors.length;
-
- return isType && isStep;
- });
-
- const isReversed = Boolean(reversed && reversed.value);
-
- return (
- <div className="color-palette__group">
- {filtered.map(colorRange => (
- <StyledColorRange
- className="color-ranges"
- key={colorRange.name}
- onClick={e =>
- onSelect(
- {
- ...colorRange,
- reversed: isReversed,
- colors: isReversed
- ? colorRange.colors.slice().reverse()
- : colorRange.colors
- },
- e
- )
+export const ColorPaletteGroup = ({reversed, onSelect, selected, colorRanges}) => (
+ <div className="color-palette__group">
+ {colorRanges.map((colorRange, i) => (
+ <StyledColorRange
+
+ key={`${colorRange.name}-${i}`}
+ onClick={e =>
+ onSelect(
+ reversed ? reverseColorRange(true, colorRange) : colorRange,
+ e
+ )
+ }
+ >
+ <ColorPalette
+ colors={colorRange.colors}
+ isReversed={reversed}
+ isSelected={
+ colorRange.name === selected.name &&
+ reversed === Boolean(selected.reversed)
}
- >
- <ColorPalette
- colors={colorRange.colors}
- isReversed={isReversed}
- isSelected={
- colorRange.name === selected.name &&
- isReversed === Boolean(selected.reversed)
- }
- />
- </StyledColorRange>
- ))}
- </div>
- );
-};
+ />
+ </StyledColorRange>
+ ))}
+ </div>
+);
diff --git a/src/components/side-panel/layer-panel/color-selector.js b/src/components/side-panel/layer-panel/color-selector.js
index 7e0bce486..220b43092 100644
--- a/src/components/side-panel/layer-panel/color-selector.js
+++ b/src/components/side-panel/layer-panel/color-selector.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, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import {rgbToHex} from 'utils/color-utils';
@@ -28,14 +28,14 @@ import ColorPalette from 'components/side-panel/layer-panel/color-palette';
import {StyledPanelDropdown} from 'components/common/styled-components';
import onClickOutside from 'react-onclickoutside';
-const ColorBlock = styled.div`
+export const ColorBlock = styled.div`
width: 32px;
height: 18px;
border-radius: 1px;
background-color: ${props => `rgb(${props.color.slice(0, 3).join(',')})`};
`;
-const ColorSelectorInput = styled.div`
+export const ColorSelectorInput = styled.div`
${props =>
props.inputTheme === 'secondary'
? props.theme.secondaryInput
@@ -50,7 +50,7 @@ const ColorSelectorInput = styled.div`
}
`;
-const InputBoxContainer = styled.div`
+export const InputBoxContainer = styled.div`
display: flex;
justify-content: space-between;
@@ -66,14 +66,24 @@ class ColorSelector extends Component {
static propTypes = {
colorSets: PropTypes.arrayOf(
PropTypes.shape({
- selectedColor: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.any), PropTypes.object]),
+ selectedColor: PropTypes.oneOfType([
+ PropTypes.arrayOf(PropTypes.any),
+ PropTypes.object
+ ]),
setColor: PropTypes.func.isRequired,
isRange: PropTypes.bool,
label: PropTypes.string
})
),
+ colorUI: PropTypes.shape({
+ customPalette: PropTypes.object,
+ showSketcher: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
+ showDropdown: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
+ colorRangeConfig: PropTypes.object
+ }),
inputTheme: PropTypes.string,
- disabled: PropTypes.bool
+ disabled: PropTypes.bool,
+ setColorUI: PropTypes.func
};
static defaultProps = {
@@ -81,40 +91,69 @@ class ColorSelector extends Component {
};
state = {
- editing: false
+ showDropdown: false
};
+ node = createRef();
+
handleClickOutside = e => {
- if (this.state.editing !== false) {
- this.setState({editing: false});
+ if (this.props.colorUI && this.props.colorUI.showSketcher) {
+ // if sketcher is open, let sketch to close itself first
+ return;
+ }
+ this._closePanelDropdown();
+ };
+
+ _getEditing = () => {
+ return this.props.colorUI ? this.props.colorUI.showDropdown : this.state.showDropdown;
+ }
+
+ _closePanelDropdown = () => {
+ if (this._getEditing() === false) {
+ return;
+ }
+ if (this.props.setColorUI) {
+ this.props.setColorUI({showDropdown: false, showSketcher: false});
+ } else {
+ this.setState({showDropdown: false});
}
};
_onSelectColor = (color, e) => {
e.stopPropagation();
- if (this.props.colorSets[this.state.editing]) {
- this.props.colorSets[this.state.editing].setColor(color);
+ const editing = this._getEditing();
+ if (this.props.colorSets[editing]) {
+ this.props.colorSets[editing].setColor(color);
}
};
_showDropdown = (e, i) => {
e.stopPropagation();
e.preventDefault();
- this.setState({editing: i});
+ if (this.props.setColorUI) {
+ this.props.setColorUI({showDropdown: i});
+ } else {
+ this.setState({showDropdown: i});
+ }
};
render() {
- const {colorSets, disabled, inputTheme} = this.props;
- const {editing} = this.state;
+ const {
+ colorSets,
+ disabled,
+ inputTheme,
+ colorUI
+ } = this.props;
+
+ const editing = this._getEditing();
const currentEditing =
colorSets[editing] && typeof colorSets[editing] === 'object';
return (
- <div className="color-selector">
+ <div className="color-selector" ref={this.node}>
<InputBoxContainer>
{colorSets.map((cSet, i) => (
<div className="color-select__input-group" key={i}>
-
<ColorSelectorInput
className="color-selector__selector"
active={editing === i}
@@ -130,7 +169,11 @@ class ColorSelector extends Component {
color={cSet.selectedColor}
/>
)}
- {cSet.label ? <div className="color-selector__selector__label">{cSet.label}</div> : null}
+ {cSet.label ? (
+ <div className="color-selector__selector__label">
+ {cSet.label}
+ </div>
+ ) : null}
</ColorSelectorInput>
</div>
))}
@@ -141,6 +184,8 @@ class ColorSelector extends Component {
<ColorRangeSelector
selectedColorRange={colorSets[editing].selectedColor}
onSelectColorRange={this._onSelectColor}
+ setColorPaletteUI={this.props.setColorUI}
+ colorPaletteUI={colorUI}
/>
) : (
<SingleColorPalette
@@ -153,6 +198,6 @@ class ColorSelector extends Component {
</div>
);
}
-};
+}
export default onClickOutside(ColorSelector);
diff --git a/src/components/side-panel/layer-panel/custom-palette.js b/src/components/side-panel/layer-panel/custom-palette.js
new file mode 100644
index 000000000..7fd6b5134
--- /dev/null
+++ b/src/components/side-panel/layer-panel/custom-palette.js
@@ -0,0 +1,374 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import React, {Component, createRef} from 'react';
+import classnames from 'classnames';
+import PropTypes from 'prop-types';
+import {createSelector} from 'reselect';
+import styled, {withTheme, css} from 'styled-components';
+import {
+ sortableContainer,
+ sortableElement,
+ sortableHandle
+} from 'react-sortable-hoc';
+import Modal from 'react-modal';
+
+import {Button, InlineInput} from 'components/common/styled-components';
+import {VertDots, Trash} from 'components/common/icons';
+import ColorPalette from './color-palette';
+import CustomPicker from './custom-picker';
+import {arrayMove} from 'utils/data-utils';
+
+const dragHandleActive = css`
+ .layer__drag-handle {
+ color: ${props => props.theme.textColorHl};
+ opacity: 1;
+ cursor: move;
+ }
+`;
+
+const StyledSortableItem = styled.div`
+ display: flex;
+ align-items: center;
+ padding-top: 6px;
+ padding-bottom: 6px;
+ z-index: ${props => props.theme.dropdownWrapperZ + 1};
+
+ :not(.sorting) {
+ :hover {
+ background-color: ${props => props.theme.panelBackgroundHover};
+ ${dragHandleActive}
+ }
+ }
+
+ &.sorting-colors {
+ background-color: ${props => props.theme.panelBackgroundHover};
+ ${dragHandleActive}
+ }
+`;
+
+const StyledDragHandle = styled.div`
+ display: flex;
+ align-items: center;
+ opacity: 0;
+`;
+
+const StyledTrash = styled.div`
+ color: ${props => props.theme.textColor};
+ svg {
+ :hover {
+ color: ${props => props.theme.subtextColorActive};
+ }
+ }
+ height: 12px;
+ margin-left: auto;
+ margin-right: 12px;
+ :hover {
+ cursor: pointer;
+ }
+`;
+
+const StyledLine = styled.div`
+ width: calc(100% - 16px);
+ height: 1px;
+ background-color: ${props => props.theme.labelColor};
+ margin-top: 8px;
+ margin-left: 8px;
+`;
+
+const StyledSwatch = styled.div.attrs({
+ className: 'custom-palette__swatch'
+})`
+ background-color: ${props => props.color};
+ width: 32px;
+ height: 18px;
+ display: inline-block;
+ :hover {
+ box-shadow: ${props => props.theme.boxShadow};
+ cursor: pointer;
+ }
+`;
+
+const StyledColorRange = styled.div`
+ padding: 0 8px;
+ :hover {
+ background-color: ${props => props.theme.panelBackgroundHover};
+ cursor: pointer;
+ }
+`;
+
+const StyledButtonContainer = styled.div`
+ margin-top: 11px;
+ display: flex;
+ direction: rtl;
+`;
+
+const StyledInlineInput = styled.div`
+ margin-left: 12px;
+ input {
+ color: ${props => props.theme.textColorHl};
+ font-size: 10px;
+ }
+`;
+
+const SortableItem = sortableElement(({children, isSorting}) => (
+ <StyledSortableItem
+ className={classnames('custom-palette__sortable-items', {sorting: isSorting})}
+ >
+ {children}
+ </StyledSortableItem>
+));
+
+const SortableContainer = sortableContainer(({children}) => (
+ <div>{children}</div>
+));
+
+const DragHandle = sortableHandle(({className, children}) => (
+ <StyledDragHandle className={className}>{children}</StyledDragHandle>
+));
+
+class CustomPalette extends Component {
+ static propTypes = {
+ customPalette: PropTypes.shape({
+ name: PropTypes.string,
+ type: PropTypes.string,
+ category: PropTypes.string,
+ colors: PropTypes.arrayOf(PropTypes.string)
+ }),
+ setCustomPalette: PropTypes.func,
+ showSketcher: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
+ theme: PropTypes.object,
+ defaultSketcherPos: PropTypes.object,
+ sketcherHeight: PropTypes.number,
+ bottomBuffer: PropTypes.number
+ };
+
+ static defaultProps = {
+ defaultSketcherPos: {top: '320px', left: '320px'},
+ sketcherHeight: 228,
+ bottomBuffer: 212
+ };
+
+ state = {
+ // currentSwatchIndex: null,
+ isSorting: false
+ };
+
+ root = createRef();
+
+ // derive sketcher position based on root component
+ showSketcherSelector = props => props.showSketcher;
+ themeSelector = props => props.theme;
+ sketcherPosSelector = createSelector(
+ this.showSketcherSelector,
+ (showSketcher, theme = {}) => {
+ const {defaultSketcherPos, bottomBuffer, sketcherHeight} = this.props;
+ if (showSketcher === false || !this.root || !this.root.current)
+ return defaultSketcherPos;
+ const {sidePanelInnerPadding = 16, sidePanel = {}, sidePanelScrollBarWidth = 10} = theme;
+ const sidePanelLeft = (sidePanel.margin || {}).left || 20;
+ const offsetX = sidePanelInnerPadding + sidePanelLeft + sidePanelScrollBarWidth;
+ // find component Root position
+ const bounding = this.root.current.getBoundingClientRect();
+ const {x, y, width} = bounding;
+
+ // set the top so it won't collide with bottom widget
+ const top =
+ y + sketcherHeight <= window.innerHeight - bottomBuffer
+ ? y
+ : window.innerHeight - bottomBuffer - sketcherHeight;
+
+ return {top: `${top}px`, left: `${x + width + offsetX}px`};
+ }
+ );
+
+ modalStylesSelector = createSelector(
+ this.themeSelector,
+ this.sketcherPosSelector,
+ (theme, sketcherPos) => ({
+ content: {
+ top: 0,
+ left: 0,
+ border: 0,
+ right: 'auto',
+ bottom: 'auto',
+ padding: '0px 0px 0px 0px',
+ borderRadius: theme.panelBorderRadius || '2px'
+ },
+ overlay: {
+ ...sketcherPos,
+ right: 'auto',
+ bottom: 'auto',
+ backgroundColor: 'rgba(0, 0, 0, 0)'
+ }
+ })
+ )
+ _setColorPaletteUI(colors) {
+ this.props.setCustomPalette({
+ colors
+ });
+ }
+
+ _onPickerUpdate = color => {
+ const {colors} = this.props.customPalette;
+ const newColors = [...colors];
+ newColors[this.props.showSketcher] = color.hex;
+ this._setColorPaletteUI(newColors);
+ };
+
+ _onColorDelete = index => {
+ const {colors} = this.props.customPalette;
+ const newColors = [...colors];
+ if (newColors.length > 1) {
+ newColors.splice(index, 1);
+ }
+ this._setColorPaletteUI(newColors);
+ };
+
+ _onColorAdd = () => {
+ const {colors} = this.props.customPalette;
+ // add the last color
+ const newColors = [...colors, colors[colors.length - 1]];
+ this._setColorPaletteUI(newColors);
+ };
+
+ _onSwatchClick = (index) => {
+ this.props.onToggleSketcher(index);
+ };
+
+ _onSwatchClose = () => {
+ this.props.onToggleSketcher(false);
+ };
+
+ _onApply = event => {
+ event.stopPropagation();
+ event.preventDefault();
+ this.props.onCancel();
+ this.props.onApply(this.props.customPalette, event);
+ };
+
+ _onSortEnd = ({oldIndex, newIndex}) => {
+ const {colors} = this.props.customPalette;
+ const newColors = arrayMove(colors, oldIndex, newIndex);
+ this._setColorPaletteUI(newColors);
+ this.setState({isSorting: false});
+ };
+
+ _onSortStart = () => {
+ this.setState({isSorting: true});
+ };
+
+ _inputColorHex = (index, {target: {value}}) => {
+ const {colors} = this.props.customPalette;
+ const newColors = [...colors];
+ newColors[index] = value.toUpperCase();
+ this._setColorPaletteUI(newColors);
+ };
+
+ render() {
+ const {colors} = this.props.customPalette;
+ const modalStyles = this.modalStylesSelector(this.props);
+
+ return (
+ <div className="custom-palette-panel" ref={this.root}>
+ <StyledColorRange>
+ <ColorPalette colors={colors} />
+ </StyledColorRange>
+ <SortableContainer
+ className="custom-palette-container"
+ onSortEnd={this._onSortEnd}
+ onSortStart={this._onSortStart}
+ lockAxis="y"
+ helperClass="sorting-colors"
+ useDragHandle
+ >
+ {colors.map((color, index) => (
+ <SortableItem
+ key={index}
+ index={index}
+ isSorting={this.state.isSorting}
+ >
+ <DragHandle className="layer__drag-handle">
+ <VertDots height="20px" />
+ </DragHandle>
+ <StyledSwatch
+ color={color}
+ onClick={e => this._onSwatchClick(index, e)}
+ />
+ <StyledInlineInput>
+ <InlineInput
+ type="text"
+ className="custom-palette-hex__input"
+ value={color.toUpperCase()}
+ onClick={e => {
+ e.stopPropagation();
+ }}
+ onChange={e => this._inputColorHex(index, e)}
+ id="input-layer-label"
+ />
+ </StyledInlineInput>
+ <StyledTrash onClick={() => this._onColorDelete(index)}>
+ <Trash className="trashbin" />
+ </StyledTrash>
+ </SortableItem>
+ ))}
+ </SortableContainer>
+ {/* Add Step Button */}
+ <Button className="add-step__button" link onClick={this._onColorAdd}>
+ + Add Step
+ </Button>
+ <StyledLine />
+ {/* Cancel or Confirm Buttons */}
+ <StyledButtonContainer>
+ <Button className="confirm-apply__button" link onClick={this._onApply}>
+ Confirm
+ </Button>
+ <Button link onClick={this.props.onCancel}>
+ {' '}
+ Cancel
+ </Button>
+ </StyledButtonContainer>
+ {this.props.showSketcher !== false ? (
+ <Modal
+ isOpen
+ style={modalStyles}
+ ariaHideApp={false}
+ parentSelector={() => {
+ // React modal issue: https://github.com/reactjs/react-modal/issues/769
+ // failed to execute removeChild on parent node when it is already unmounted
+ return this.root.current || {
+ removeChild: () => {},
+ appendChild: () => {}
+ }
+ }}
+ >
+ <CustomPicker
+ color={colors[this.props.showSketcher]}
+ onChange={this._onPickerUpdate}
+ onSwatchClose={this._onSwatchClose}
+ />
+ </Modal>
+ ) : null}
+ </div>
+ );
+ }
+}
+
+export default withTheme(CustomPalette);
diff --git a/src/components/side-panel/layer-panel/custom-picker.js b/src/components/side-panel/layer-panel/custom-picker.js
new file mode 100644
index 000000000..763854917
--- /dev/null
+++ b/src/components/side-panel/layer-panel/custom-picker.js
@@ -0,0 +1,90 @@
+// Copyright (c) 2019 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import React, {Component} from 'react';
+import PropTypes from 'prop-types';
+import styled, {withTheme} from 'styled-components';
+import {SketchPicker} from 'react-color';
+import onClickOutside from 'react-onclickoutside';
+import {createSelector} from 'reselect';
+// This was put in because 3rd party library react-color doesn't yet cater for customized color of child component <SketchField> which contains HEX/RGB input text box
+// Issue raised: https://github.com/casesandberg/react-color/issues/631
+
+const StyledPicker = styled.div`
+ .sketch-picker {
+ span {
+ color: ${props => props.theme.labelColor} !important;
+ font-family: ${props => props.theme.fontFamily};
+ }
+ input {
+ text-align: center;
+ font-family: ${props => props.theme.fontFamily};
+ color: ${props => props.theme.inputColor} !important;
+ border-color: ${props => props.theme.secondaryInputBgd} !important;
+ box-shadow: none !important;
+ background-color: ${props => props.theme.inputBgdHover} !important;
+ }
+ }
+`;
+
+const PRESET_COLORS = [];
+
+class CustomPicker extends Component {
+ static propTypes = {
+ color: PropTypes.string,
+ onChange: PropTypes.func,
+ onSwatchClose: PropTypes.func
+ };
+
+ themeSelector = props => props.theme;
+ pickerStyleSelector = createSelector(
+ this.themeSelector,
+ theme => ({
+ picker: {
+ width: '200px',
+ padding: '10px 10px 8px',
+ boxSizing: 'initial',
+ background: theme.panelBackground
+ }
+ })
+ );
+
+ handleClickOutside = e => {
+ this.props.onSwatchClose();
+ };
+
+ render() {
+ const {color, onChange} = this.props;
+ const pickerStyle = this.pickerStyleSelector(this.props);
+ return (
+ <StyledPicker>
+ <SketchPicker
+ color={color}
+ onChange={onChange}
+ presetColors={PRESET_COLORS}
+ styles={pickerStyle}
+ disableAlpha
+ />
+ </StyledPicker>
+ );
+ }
+}
+
+export default withTheme(onClickOutside(CustomPicker));
diff --git a/src/components/side-panel/layer-panel/layer-config-group.js b/src/components/side-panel/layer-panel/layer-config-group.js
index c9de933b5..cf18e3197 100644
--- a/src/components/side-panel/layer-panel/layer-config-group.js
+++ b/src/components/side-panel/layer-panel/layer-config-group.js
@@ -57,7 +57,7 @@ export const ConfigGroupCollapsibleHeader = styled.div.attrs({
overflow: visible;
overflow: hidden;
max-height: 0;
-`
+`;
export const StyledLayerConfigGroup = styled.div`
padding-left: 18px;
@@ -92,7 +92,7 @@ export const StyledConfigGroupHeader = styled.div`
}
.layer-config-group__action {
- color: ${props => props.theme.textColorHl};
+ color: ${props => props.theme.textColorHl};
}
}
`;
@@ -108,7 +108,6 @@ const ConfigGroupContent = styled.div`
`;
export default class LayerConfigGroup extends Component {
-
static defaultProps = {
collapsible: false,
expanded: false,
@@ -147,8 +146,11 @@ export default class LayerConfigGroup extends Component {
const {collapsed} = this.state;
return (
- <StyledLayerConfigGroup className={classnames('layer-config-group', {collapsed})}>
- <StyledConfigGroupHeader className="layer-config-group__header"
+ <StyledLayerConfigGroup
+ className={classnames('layer-config-group', {collapsed})}
+ >
+ <StyledConfigGroupHeader
+ className="layer-config-group__header"
onClick={() => this.setState({collapsed: !this.state.collapsed})}
>
<StyledLayerConfigGroupLabel className="layer-config-group__label">
@@ -164,7 +166,7 @@ export default class LayerConfigGroup extends Component {
}
/>
) : null}
- {collapsible ? <VertThreeDots height="18px"/> : null}
+ {collapsible ? <VertThreeDots height="18px" /> : null}
</StyledLayerConfigGroupAction>
</StyledConfigGroupHeader>
<ConfigGroupContent
@@ -178,4 +180,3 @@ export default class LayerConfigGroup extends Component {
);
}
}
-
diff --git a/src/components/side-panel/layer-panel/layer-configurator.js b/src/components/side-panel/layer-panel/layer-configurator.js
index 59e0e906b..8ae7687a4 100644
--- a/src/components/side-panel/layer-panel/layer-configurator.js
+++ b/src/components/side-panel/layer-panel/layer-configurator.js
@@ -66,6 +66,31 @@ const StyledLayerVisualConfigurator = styled.div.attrs({
margin-top: 12px;
`;
+export const getLayerFields = (datasets, layer) =>
+ datasets[layer.config.dataId] ?
+ datasets[layer.config.dataId].fields
+ : [];
+
+export const getLayerConfiguratorProps = props => ({
+ layer: props.layer,
+ fields: getLayerFields(props.datasets, props.layer),
+ onChange: props.updateLayerConfig,
+ setColorUI: props.updateLayerColorUI
+});
+
+export const getVisConfiguratorProps = props => ({
+ layer: props.layer,
+ fields: getLayerFields(props.datasets, props.layer),
+ onChange: props.updateLayerVisConfig,
+ setColorUI: props.updateLayerColorUI
+});
+
+export const getLayerChannelConfigProps = props => ({
+ layer: props.layer,
+ fields: getLayerFields(props.datasets, props.layer),
+ onChange: props.updateLayerVisualChannelConfig
+})
+
LayerConfiguratorFactory.deps = [SourceDataSelectorFactory];
export default function LayerConfiguratorFactory(SourceDataSelector) {
class LayerConfigurator extends Component {
@@ -77,7 +102,8 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
updateLayerConfig: PropTypes.func.isRequired,
updateLayerType: PropTypes.func.isRequired,
updateLayerVisConfig: PropTypes.func.isRequired,
- updateLayerVisualChannelConfig: PropTypes.func.isRequired
+ updateLayerVisualChannelConfig: PropTypes.func.isRequired,
+ updateLayerColorUI: PropTypes.func.isRequired
};
_renderPointLayerConfig(props) {
@@ -103,7 +129,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
collapsible
>
{layer.config.colorField ? (
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
@@ -127,7 +153,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
collapsible
>
{layer.config.strokeColorField ? (
- <ColorRangeConfig
+ <LayerColorRangeSelector
{...visConfiguratorProps}
property="strokeColorRange"
/>
@@ -191,6 +217,8 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
fields={visConfiguratorProps.fields}
updateLayerTextLabel={this.props.updateLayerTextLabel}
textLabel={layer.config.textLabel}
+ colorPalette={visConfiguratorProps.colorPalette}
+ setColorPaletteUI={visConfiguratorProps.setColorPaletteUI}
/>
</StyledLayerVisualConfigurator>
);
@@ -206,7 +234,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'color'} collapsible>
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<AggrScaleSelector
{...layerConfiguratorProps}
@@ -259,7 +287,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'color'} collapsible>
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<VisConfigSlider
{...layer.visConfigSettings.opacity}
@@ -312,7 +340,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
<StyledLayerVisualConfigurator>
{/* Color */}
<LayerConfigGroup label={'color'} collapsible>
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<AggrScaleSelector
{...layerConfiguratorProps}
@@ -422,7 +450,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
{/* Color */}
<LayerConfigGroup label={'color'} collapsible>
{layer.config.colorField ? (
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
@@ -498,10 +526,11 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
{/* Color */}
<LayerConfigGroup label={'color'} collapsible>
{layer.config.colorField ? (
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<ArcLayerColorSelector
layer={layer}
+ setColorUI={layerConfiguratorProps.setColorUI}
onChangeConfig={layerConfiguratorProps.onChange}
onChangeVisConfig={visConfiguratorProps.onChange}
/>
@@ -567,7 +596,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
collapsible
>
{layer.config.colorField ? (
- <ColorRangeConfig {...visConfiguratorProps} />
+ <LayerColorRangeSelector {...visConfiguratorProps} />
) : (
<LayerColorSelector {...layerConfiguratorProps} />
)}
@@ -592,7 +621,7 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
collapsible
>
{layer.config.strokeColorField ? (
- <ColorRangeConfig
+ <LayerColorRangeSelector
{...visConfiguratorProps}
property="strokeColorRange"
/>
@@ -759,25 +788,9 @@ export default function LayerConfiguratorFactory(SourceDataSelector) {
: {};
const {config} = layer;
- const commonConfigProp = {
- layer,
- fields
- };
-
- const visConfiguratorProps = {
- ...commonConfigProp,
- onChange: this.props.updateLayerVisConfig
- };
-
- const layerConfiguratorProps = {
- ...commonConfigProp,
- onChange: updateLayerConfig
- };
-
- const layerChannelConfigProps = {
- ...commonConfigProp,
- onChange: this.props.updateLayerVisualChannelConfig
- };
+ const visConfiguratorProps = getVisConfiguratorProps(this.props);
+ const layerConfiguratorProps = getLayerConfiguratorProps(this.props);
+ const layerChannelConfigProps = getLayerChannelConfigProps(this.props);
const renderTemplate =
layer.type && `_render${capitalizeFirstLetter(layer.type)}LayerConfig`;
@@ -855,7 +868,8 @@ export const LayerColorSelector = ({
onChange,
label,
selectedColor,
- property = 'color'
+ property = 'color',
+ setColorUI
}) => (
<SidePanelSection>
<ColorSelector
@@ -865,6 +879,8 @@ export const LayerColorSelector = ({
setColor: rgbValue => onChange({[property]: rgbValue})
}
]}
+ colorUI={layer.config.colorUI[property]}
+ setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
@@ -872,7 +888,9 @@ export const LayerColorSelector = ({
export const ArcLayerColorSelector = ({
layer,
onChangeConfig,
- onChangeVisConfig
+ onChangeVisConfig,
+ property = 'color',
+ setColorUI
}) => (
<SidePanelSection>
<ColorSelector
@@ -889,14 +907,17 @@ export const ArcLayerColorSelector = ({
label: 'Target'
}
]}
+ colorUI={layer.config.colorUI[property]}
+ setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
-export const ColorRangeConfig = ({
+export const LayerColorRangeSelector = ({
layer,
onChange,
- property = 'colorRange'
+ property = 'colorRange',
+ setColorUI
}) => (
<SidePanelSection>
<ColorSelector
@@ -907,6 +928,8 @@ export const ColorRangeConfig = ({
setColor: colorRange => onChange({[property]: colorRange})
}
]}
+ colorUI={layer.config.colorUI[property]}
+ setColorUI={newConfig => setColorUI(property, newConfig)}
/>
</SidePanelSection>
);
diff --git a/src/components/side-panel/layer-panel/layer-panel-header.js b/src/components/side-panel/layer-panel/layer-panel-header.js
index 52f3b86f9..1e88f5487 100644
--- a/src/components/side-panel/layer-panel/layer-panel-header.js
+++ b/src/components/side-panel/layer-panel/layer-panel-header.js
@@ -113,7 +113,7 @@ const StyledDragHandle = styled.div`
`;
const DragHandle = sortableHandle(({className, children}) =>
- <StyledDragHandle classname={className}>
+ <StyledDragHandle className={className}>
{children}
</StyledDragHandle>
);
diff --git a/src/components/side-panel/layer-panel/layer-panel.js b/src/components/side-panel/layer-panel/layer-panel.js
index c5beb0eb3..691ccb05b 100644
--- a/src/components/side-panel/layer-panel/layer-panel.js
+++ b/src/components/side-panel/layer-panel/layer-panel.js
@@ -52,8 +52,9 @@ function LayerPanelFactory(LayerConfigurator) {
onCloseConfig: PropTypes.func,
layerTypeOptions: PropTypes.arrayOf(PropTypes.any),
- layerVisConfigChange: PropTypes.func,
- layerVisualChannelConfigChange: PropTypes.func
+ layerVisConfigChange: PropTypes.func.isRequired,
+ layerVisualChannelConfigChange: PropTypes.func.isRequired,
+ layerColorUIChange: PropTypes.func.isRequired
};
updateLayerConfig = newProp => {
@@ -68,6 +69,10 @@ function LayerPanelFactory(LayerConfigurator) {
this.props.layerVisConfigChange(this.props.layer, newVisConfig);
};
+ updateLayerColorUI = (...args) => {
+ this.props.layerColorUIChange(this.props.layer, ...args);
+ };
+
updateLayerTextLabel = (...args) => {
this.props.layerTextLabelChange(this.props.layer, ...args);
};
@@ -83,7 +88,7 @@ function LayerPanelFactory(LayerConfigurator) {
_updateLayerLabel = ({target: {value}}) => {
this.updateLayerConfig({label: value});
- };
+ }
_toggleVisibility = e => {
e.stopPropagation();
@@ -134,6 +139,7 @@ function LayerPanelFactory(LayerConfigurator) {
datasets={datasets}
layerTypeOptions={layerTypeOptions}
openModal={this.props.openModal}
+ updateLayerColorUI={this.updateLayerColorUI}
updateLayerConfig={this.updateLayerConfig}
updateLayerVisualChannelConfig={this.updateLayerVisualChannelConfig}
updateLayerType={this.updateLayerType}
diff --git a/src/components/side-panel/layer-panel/single-color-palette.js b/src/components/side-panel/layer-panel/single-color-palette.js
index c9176dc54..83970dd7a 100644
--- a/src/components/side-panel/layer-panel/single-color-palette.js
+++ b/src/components/side-panel/layer-panel/single-color-palette.js
@@ -33,7 +33,7 @@ const propTypes = {
};
const PALETTE_HEIGHT = '8px';
-const ROWS = 16;
+const ROWS = 22;
const StyledColorPalette = styled.div`
display: flex;
@@ -63,23 +63,24 @@ const StyledColorBlock = styled.div`
const SingleColorPalette = ({selectedColor, onSelectColor}) => (
<StyledColorPalette className="single-color-palette">
{Themes.map((theme, col) => (
- <StyledColorColumn key={theme}>
+ <StyledColorColumn key={theme} className="single-color-palette__column">
{range(1, ROWS + 1, 1).map((key, i) => (
<StyledColorBlock
+ className="single-color-palette__block"
style={{
- backgroundColor: ColorsByTheme[theme][String(key)],
+ backgroundColor: ColorsByTheme[theme][key],
borderColor:
selectedColor ===
- ColorsByTheme[theme][String(key)].toUpperCase()
+ ColorsByTheme[theme][key].toUpperCase()
? 'white'
- : ColorsByTheme[theme][String(key)]
+ : ColorsByTheme[theme][key]
}}
key={`${theme}_${key}`}
selected={
- selectedColor === ColorsByTheme[theme][String(key)].toUpperCase()
+ selectedColor === ColorsByTheme[theme][key].toUpperCase()
}
onClick={e =>
- onSelectColor(hexToRgb(ColorsByTheme[theme][String(key)]), e)
+ onSelectColor(hexToRgb(ColorsByTheme[theme][key]), e)
}
/>
))}
diff --git a/src/constants/action-types.js b/src/constants/action-types.js
index ba3feadf2..f2e49f73a 100644
--- a/src/constants/action-types.js
+++ b/src/constants/action-types.js
@@ -88,6 +88,7 @@ const ActionTypes = keyMirror({
SET_FILTER_PLOT: null,
LOAD_FILES: null,
LOAD_FILES_ERR: null,
+ LAYER_COLOR_UI_CHANGE: null,
// mapState
UPDATE_MAP: null,
diff --git a/src/constants/color-ranges.js b/src/constants/color-ranges.js
index d9050f5d3..744a7656d 100644
--- a/src/constants/color-ranges.js
+++ b/src/constants/color-ranges.js
@@ -19,62 +19,32 @@
// THE SOFTWARE.
import colorbrewer from 'colorbrewer';
-import {SEQ, QUA, DIV, VizColorPalette} from './custom-color-ranges';
-
-const colorBrewerMap = {
- YlGn: SEQ,
- YlGnBu: SEQ,
- GnBu: SEQ,
- BuGn: SEQ,
- PuBuGn: SEQ,
- PuBu: SEQ,
- BuPu: SEQ,
- RdPu: SEQ,
- PuRd: SEQ,
- OrRd: SEQ,
- YlOrRd: SEQ,
- YlOrBr: SEQ,
- Purples: SEQ,
- Blues: SEQ,
- Greens: SEQ,
- Oranges: SEQ,
- Reds: SEQ,
- Greys: SEQ,
- PuOr: DIV,
- BrBG: DIV,
- PRGn: DIV,
- PiYG: DIV,
- RdBu: DIV,
- RdGy: DIV,
- RdYlBu: DIV,
- Spectral: DIV,
- RdYlGn: DIV,
- Accent: QUA,
- Dark2: QUA,
- Paired: QUA,
- Pastel1: QUA,
- Pastel2: QUA,
- Set1: QUA,
- Set2: QUA,
- Set3: QUA
-};
-
-const colorRanges = [...VizColorPalette];
+import {VizColorPalette} from './custom-color-ranges';
// Add colorbrewer color schemes (Data Science requirement)
// See http://colorbrewer2.org/
-function entries(obj) {
- return Object.keys(obj).map(k => [k, obj[k]]);
-}
-for (const [keyName, colorScheme] of entries(colorbrewer)) {
- for (const [lenKey, colors] of entries(colorScheme)) {
- colorRanges.push({
- name: `ColorBrewer ${keyName}-${lenKey}`,
- type: colorBrewerMap[keyName],
- category: 'ColorBrewer',
- colors
- });
+const colorBrewerMap = Object.entries(colorbrewer.schemeGroups)
+ .reduce((accu, [type, palettes]) => ({
+ ...accu,
+ ...palettes.reduce((group, name) => ({
+ ...group,
+ [name]: type
+ }), {})
+ }), {});
+
+const colorRanges = [...VizColorPalette];
+
+for (const [keyName, colorScheme] of Object.entries(colorbrewer)) {
+ if (keyName !== 'schemeGroups') {
+ for (const [lenKey, colors] of Object.entries(colorScheme)) {
+ colorRanges.push({
+ name: `ColorBrewer ${keyName}-${lenKey}`,
+ type: colorBrewerMap[keyName],
+ category: 'ColorBrewer',
+ colors
+ });
+ }
}
}
diff --git a/src/constants/custom-color-ranges.js b/src/constants/custom-color-ranges.js
index db3a299ed..5e3bf218f 100644
--- a/src/constants/custom-color-ranges.js
+++ b/src/constants/custom-color-ranges.js
@@ -25,6 +25,7 @@
*/
export const SEQ = 'sequential';
+export const SIN = 'singlehue';
export const QUA = 'qualitative';
export const DIV = 'diverging';
diff --git a/src/layers/base-layer.js b/src/layers/base-layer.js
index 6dc7287d9..eaf3366e3 100644
--- a/src/layers/base-layer.js
+++ b/src/layers/base-layer.js
@@ -18,7 +18,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
-import {hexToRgb} from 'utils/color-utils';
import {console as Console} from 'global/window';
import keymirror from 'keymirror';
import DefaultLayerIcon from './default-layer-icon';
@@ -33,8 +32,13 @@ import {
SCALE_FUNC,
CHANNEL_SCALE_SUPPORTED_FIELDS
} 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} from './layer-factory';
+import {
+ LAYER_VIS_CONFIGS,
+ DEFAULT_TEXT_LABEL,
+ DEFAULT_COLOR_UI
+} from './layer-factory';
import {generateHashId, isPlainObject} from 'utils/utils';
@@ -52,6 +56,11 @@ import {
getLogDomain,
getLinearDomain
} from 'utils/data-scale-utils';
+import {
+ hexToRgb,
+ getColorGroupByName,
+ reverseColorRange
+} from 'utils/color-utils';
/**
* Approx. number of points to sample in a large data set
@@ -215,14 +224,15 @@ export default class Layer {
// find all matched fields for each required col
const requiredColumns = Object.keys(defaultFields).reduce((prev, key) => {
const requiredFields = allFields.filter(
- f => f.name === defaultFields[key] || defaultFields[key].includes(f.name)
+ f =>
+ f.name === defaultFields[key] || defaultFields[key].includes(f.name)
);
prev[key] = requiredFields.length
? requiredFields.map(f => ({
- value: f.name,
- fieldIdx: f.tableFieldIndex - 1
- }))
+ value: f.name,
+ fieldIdx: f.tableFieldIndex - 1
+ }))
: null;
return prev;
}, {});
@@ -301,7 +311,12 @@ export default class Layer {
visConfig: {},
- textLabel: [DEFAULT_TEXT_LABEL]
+ textLabel: [DEFAULT_TEXT_LABEL],
+
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ }
};
}
@@ -317,7 +332,7 @@ export default class Layer {
measure: this.config[this.visualChannels[key].field]
? this.config[this.visualChannels[key].field].name
: this.visualChannels[key].defaultMeasure
- }
+ };
}
/**
@@ -366,7 +381,7 @@ export default class Layer {
};
}
- /**
+ /**
* Calculate a radius zoom multiplier to render points, so they are visible in all zoom level
* @param mapState
* @param mapState.zoom - actual zoom
@@ -377,7 +392,7 @@ export default class Layer {
return Math.pow(2, Math.max(14 - zoom + zoomOffset, 0));
}
- /**
+ /**
* Calculate a elevation zoom multiplier to render points, so they are visible in all zoom level
* @param mapState
* @param mapState.zoom - actual zoom
@@ -423,14 +438,21 @@ export default class Layer {
// if range is for the same property group copy it, otherwise, not to copy
Object.values(this.visualChannels).forEach(v => {
- if (configToCopy.visConfig[v.range] && visConfigSettings[v.range].group !== this.visConfigSettings[v.range].group) {
+ if (
+ configToCopy.visConfig[v.range] &&
+ visConfigSettings[v.range].group !==
+ this.visConfigSettings[v.range].group
+ ) {
notToCopy.push(v.range);
}
});
// don't copy over visualChannel range
const currentConfig = this.config;
- const copied = this.copyLayerConfig(currentConfig, configToCopy, {notToDeepMerge, notToCopy});
+ const copied = this.copyLayerConfig(currentConfig, configToCopy, {
+ notToDeepMerge,
+ notToCopy
+ });
this.updateLayerConfig(copied);
// validate visualChannel field type and scale types
@@ -449,7 +471,11 @@ export default class Layer {
* @param {string[]} notToCopy - array of properties not to copy
* @returns {object} - copied config
*/
- copyLayerConfig(currentConfig, configToCopy, {notToDeepMerge = [], notToCopy = []} = {}) {
+ copyLayerConfig(
+ currentConfig,
+ configToCopy,
+ {notToDeepMerge = [], notToCopy = []} = {}
+ ) {
const copied = {};
Object.keys(currentConfig).forEach(key => {
if (
@@ -459,7 +485,11 @@ export default class Layer {
!notToCopy.includes(key)
) {
// recursively assign object value
- copied[key] = this.copyLayerConfig(currentConfig[key], configToCopy[key], {notToDeepMerge, notToCopy});
+ copied[key] = this.copyLayerConfig(
+ currentConfig[key],
+ configToCopy[key],
+ {notToDeepMerge, notToCopy}
+ );
} else if (
notNullorUndefined(configToCopy[key]) &&
!notToCopy.includes(key)
@@ -486,7 +516,9 @@ export default class Layer {
LAYER_VIS_CONFIGS[layerVisConfigs[item]].defaultValue;
this.visConfigSettings[item] = LAYER_VIS_CONFIGS[layerVisConfigs[item]];
} else if (
- ['type', 'defaultValue'].every(p => layerVisConfigs[item].hasOwnProperty(p))
+ ['type', 'defaultValue'].every(p =>
+ layerVisConfigs[item].hasOwnProperty(p)
+ )
) {
// if provided customized visConfig, and has type && defaultValue
// TODO: further check if customized visConfig is valid
@@ -524,6 +556,141 @@ export default class Layer {
this.config.visConfig = {...this.config.visConfig, ...newVisConfig};
return this;
}
+
+ updateLayerColorUI(prop, newConfig) {
+ const {colorUI: previous, visConfig} = this.config;
+
+ if (!isPlainObject(newConfig) || typeof prop !== 'string') {
+ return this;
+ }
+
+ const colorUIProp = Object.entries(newConfig).reduce(
+ (accu, [key, value]) => {
+ return {
+ ...accu,
+ [key]:
+ isPlainObject(accu[key]) && isPlainObject(value)
+ ? {...accu[key], ...value}
+ : value
+ };
+ },
+ previous[prop] || DEFAULT_COLOR_UI
+ );
+
+ const colorUI = {
+ ...previous,
+ [prop]: colorUIProp
+ };
+
+ this.updateLayerConfig({colorUI});
+ // if colorUI[prop] is colorRange
+ const isColorRange = visConfig[prop] && visConfig[prop].colors;
+
+ if (isColorRange) {
+ this.updateColorUIByColorRange(newConfig, prop);
+ this.updateColorRangeByColorUI(newConfig, previous, prop);
+ this.updateCustomPalette(newConfig, previous, prop);
+ }
+
+ return this;
+ }
+
+ updateCustomPalette(newConfig, previous, prop) {
+ if (
+ !newConfig.colorRangeConfig ||
+ !newConfig.colorRangeConfig.custom
+ ) {
+ return;
+ }
+
+ const {colorUI, visConfig} = this.config;
+
+ if (!visConfig[prop]) return;
+ const {colors} = visConfig[prop];
+ const customPalette = {
+ ...colorUI[prop].customPalette,
+ name: 'Custom Palette',
+ colors: [...colors]
+ };
+ this.updateLayerConfig({
+ colorUI: {
+ ...colorUI,
+ [prop]: {
+ ...colorUI[prop],
+ customPalette
+ }
+ }
+ });
+ }
+ /**
+ * if open dropdown and prop is color range
+ * Automatically set colorRangeConfig's step and reversed
+ * @param {*} newConfig
+ * @param {*} prop
+ */
+ updateColorUIByColorRange(newConfig, prop) {
+ if (typeof newConfig.showDropdown !== 'number') return;
+
+ const {colorUI, visConfig} = this.config;
+ this.updateLayerConfig({
+ colorUI: {
+ ...colorUI,
+ [prop]: {
+ ...colorUI[prop],
+ colorRangeConfig: {
+ ...colorUI[prop].colorRangeConfig,
+ steps: visConfig[prop].colors.length,
+ reversed: Boolean(visConfig[prop].reversed)
+ }
+ }
+ }
+ });
+ }
+
+ updateColorRangeByColorUI(newConfig, previous, prop) {
+ // only update colorRange if changes in UI is made to 'reversed', 'steps' or steps
+ const shouldUpdate =
+ newConfig.colorRangeConfig &&
+ ['reversed', 'steps'].some(
+ key =>
+ newConfig.colorRangeConfig.hasOwnProperty(key) &&
+ newConfig.colorRangeConfig[key] !==
+ (previous[prop] || DEFAULT_COLOR_UI).colorRangeConfig[key]
+ );
+ if (!shouldUpdate) return;
+
+ const {colorUI, visConfig} = this.config;
+ const {steps, reversed} = colorUI[prop].colorRangeConfig;
+ const colorRange = visConfig[prop];
+ // find based on step or reversed
+ let update;
+ if (newConfig.colorRangeConfig.hasOwnProperty('steps')) {
+ const group = getColorGroupByName(colorRange);
+
+ if (group) {
+ const sameGroup = COLOR_RANGES.filter(
+ cr => getColorGroupByName(cr) === group
+ );
+
+ update = sameGroup.find(
+ cr => cr.colors.length === steps
+ );
+
+ if (update && colorRange.reversed) {
+ update = reverseColorRange(true, update);
+ }
+ }
+ }
+
+ if (newConfig.colorRangeConfig.hasOwnProperty('reversed')) {
+ update = reverseColorRange(reversed, update || colorRange);
+ };
+
+ if (update) {
+ this.updateLayerVisConfig({[prop]: update});
+ }
+ }
+
/**
* Check whether layer has all columns
*
@@ -685,7 +852,8 @@ export default class Layer {
if (this.config[field]) {
// if field is selected, check if field type is supported
- const channelSupportedFieldTypes = supportedFieldTypes || CHANNEL_SCALE_SUPPORTED_FIELDS[channelScaleType];
+ const channelSupportedFieldTypes =
+ supportedFieldTypes || CHANNEL_SCALE_SUPPORTED_FIELDS[channelScaleType];
if (!channelSupportedFieldTypes.includes(this.config[field].type)) {
// field type is not supported, set it back to null
@@ -722,16 +890,16 @@ export default class Layer {
const visualChannel = this.visualChannels[channel];
const {field, scale, channelScaleType} = visualChannel;
- return this.config[field] ?
- FIELD_OPTS[this.config[field].type].scale[channelScaleType] :
- [this.getDefaultLayerConfig()[scale]];
+ return this.config[field]
+ ? FIELD_OPTS[this.config[field].type].scale[channelScaleType]
+ : [this.getDefaultLayerConfig()[scale]];
}
updateLayerVisualChannel(dataset, channel) {
const visualChannel = this.visualChannels[channel];
this.validateVisualChannel(channel);
- // calculate layer channel domain
+ // calculate layer channel domain
const updatedDomain = this.calculateLayerDomain(dataset, visualChannel);
this.updateLayerConfig({[visualChannel.domain]: updatedDomain});
@@ -775,7 +943,11 @@ export default class Layer {
return getOrdinalDomain(allData, valueAccessor);
case SCALE_TYPES.quantile:
- return getQuantileDomain(filteredIndexForDomain, indexValueAccessor, sortFunction);
+ return getQuantileDomain(
+ filteredIndexForDomain,
+ indexValueAccessor,
+ sortFunction
+ );
case SCALE_TYPES.log:
return getLogDomain(filteredIndexForDomain, indexValueAccessor);
diff --git a/src/layers/layer-factory.js b/src/layers/layer-factory.js
index 17b45ce5b..6e2bd364e 100644
--- a/src/layers/layer-factory.js
+++ b/src/layers/layer-factory.js
@@ -386,3 +386,26 @@ export const DEFAULT_TEXT_LABEL = {
anchor: 'start',
alignment: 'center'
};
+
+export const DEFAULT_CUSTOM_PALETTE = {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: []
+}
+
+export const DEFAULT_COLOR_UI = {
+ // customPalette in edit
+ customPalette: DEFAULT_CUSTOM_PALETTE,
+ // show color sketcher modal
+ showSketcher: false,
+ // show color range selection panel
+ showDropdown: false,
+ // color range selector config
+ colorRangeConfig: {
+ type: 'all',
+ steps: 6,
+ reversed: false,
+ custom: false
+ }
+};
diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.js
index 000230c71..ade720692 100644
--- a/src/reducers/vis-state-updaters.js
+++ b/src/reducers/vis-state-updaters.js
@@ -594,6 +594,22 @@ export const addFilterUpdater = (state, action) =>
filters: [...state.filters, getDefaultFilter(action.dataId)]
};
+/**
+ * Set layer color palette ui state
+ * @memberof visStateUpdaters
+ * @param {Object} state
+ * @param {Object} action
+ * @param {Object} action.prop
+ * @param {Object} action.newConfig
+ */
+export const layerColorUIChangeUpdater = (state, {oldLayer, prop, newConfig}) => {
+ const newLayer = oldLayer.updateLayerColorUI(prop, newConfig);
+ return {
+ ...state,
+ layers: state.layers.map(l => l.id === oldLayer.id ? newLayer : l)
+ };
+};
+
/**
* Start and end filter animation
* @memberof visStateUpdaters
diff --git a/src/reducers/vis-state.js b/src/reducers/vis-state.js
index af7bac272..1efc483ab 100644
--- a/src/reducers/vis-state.js
+++ b/src/reducers/vis-state.js
@@ -49,6 +49,8 @@ const actionHandler = {
[ActionTypes.LAYER_VISUAL_CHANNEL_CHANGE]: visStateUpdaters.layerVisualChannelChangeUpdater,
+ [ActionTypes.LAYER_COLOR_UI_CHANGE]: visStateUpdaters.layerColorUIChangeUpdater,
+
[ActionTypes.LOAD_FILES]: visStateUpdaters.loadFilesUpdater,
[ActionTypes.LOAD_FILES_ERR]: visStateUpdaters.loadFilesErrUpdater,
diff --git a/src/styles/base.js b/src/styles/base.js
index aa41140eb..575f04195 100644
--- a/src/styles/base.js
+++ b/src/styles/base.js
@@ -32,6 +32,10 @@ export const borderColor = '#3A414C';
export const borderColorLight = '#F1F1F1';
// TEXT
+export const fontFamily = `ff-clan-web-pro, 'Helvetica Neue', Helvetica, sans-serif`;
+export const fontWeight = 400;
+export const fontSize = '0.875em';
+export const lineHeight = 1.71429;
export const labelColor = '#6A7485';
export const labelHoverColor = '#C6C6C6';
export const labelColorLT = '#6A7485';
@@ -45,7 +49,7 @@ export const subtextColorLT = '#A0A7B4';
export const subtextColorActive = '#FFFFFF';
export const titleTextColor = '#FFFFFF';
-export const textColorHl = '#D3D8E0';
+export const textColorHl = '#F0F0F0';
export const textColorHlLT = '#F1F1F1';
export const activeColor = '#1FBAD6';
export const activeColorHover = '#108188';
@@ -124,7 +128,7 @@ export const dropdownListHighlightBg = '#6A7485';
export const dropdownListShadow = '0 6px 12px 0 rgba(0,0,0,0.16)';
export const dropdownListBgd = '#3A414C';
export const dropdownListBorderTop = '#242730';
-
+export const dropdownWrapperZ = 100;
// Switch
export const switchWidth = 24;
export const switchHeight = 12;
@@ -155,7 +159,10 @@ export const checkboxBoxBgdChecked = primaryBtnBgd;
// Side Panel
export const sidePanelHeaderBg = '#29323C';
+export const sidePanelInnerPadding = 16;
export const sidePanelBg = '#242730';
+export const sidePanelScrollBarWidth = 10;
+export const sidePanelScrollBarHeight = 10;
export const sideBarCloseBtnBgd = secondaryBtnBgd;
export const sideBarCloseBtnColor = '#29323C';
export const sideBarCloseBtnBgdHover = secondaryBtnActBgd;
@@ -190,6 +197,13 @@ export const modalPadding = '10px 0';
export const modalLateralPadding = '72px';
export const modalPortableLateralPadding = '36px';
+export const modalOverLayZ = 1000;
+export const modalOverlayBgd = 'rgba(0, 0, 0, 0.5)';
+export const modalContentZ = 10002;
+export const modalFooterZ = 10001;
+export const modalTitleZ = 10003;
+export const modalButtonZ = 10005;
+
// Modal Dialog (Dark)
export const modalDialogBgd = '#3A414C';
export const modalDialogColor = textColorHl;
@@ -625,8 +639,8 @@ const dropdownList = css`
const sidePanelScrollBar = css`
::-webkit-scrollbar {
- height: 10px;
- width: 10px;
+ height: ${props => props.theme.sidePanelScrollBarHeight}px;
+ width: ${props => props.theme.sidePanelScrollBarWidth}px;
}
::-webkit-scrollbar-corner {
@@ -758,6 +772,7 @@ export const theme = {
dropdownListHeader,
dropdownListSection,
dropdownListShadow,
+ dropdownWrapperZ,
modalScrollBar,
scrollBar,
sidePanelScrollBar,
@@ -896,14 +911,22 @@ export const theme = {
modalLateralPadding,
modalPortableLateralPadding,
+ modalOverLayZ,
+ modalOverlayBgd,
+ modalContentZ,
+ modalFooterZ,
+ modalTitleZ,
+ modalButtonZ,
// Side Panel
sidePanelBg,
-
+ sidePanelInnerPadding,
sideBarCloseBtnBgd,
sideBarCloseBtnColor,
sideBarCloseBtnBgdHover,
sidePanelHeaderBg,
+ sidePanelScrollBarWidth,
+ sidePanelScrollBarHeight,
// Side Panel Panel
panelActiveBg,
@@ -921,6 +944,10 @@ export const theme = {
panelDropdownScrollBar,
// Text
+ fontFamily,
+ fontWeight,
+ fontSize,
+ lineHeight,
textColor,
textColorLT,
textColorHl,
diff --git a/src/utils/color-utils.js b/src/utils/color-utils.js
index e0714b8de..d530045b9 100644
--- a/src/utils/color-utils.js
+++ b/src/utils/color-utils.js
@@ -25,7 +25,11 @@
* @returns {array} array of r g bs
*/
export function hexToRgb(hex) {
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ const result = isHexColor(hex);
+
+ if (!result) {
+ return [0, 0, 0];
+ }
const r = parseInt(result[1], 16);
const g = parseInt(result[2], 16);
@@ -34,6 +38,12 @@ export function hexToRgb(hex) {
return [r, g, b];
}
+export function isHexColor(hex) {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+
+ return result;
+}
+
function PadNum(c) {
const hex = c.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
@@ -48,3 +58,33 @@ function PadNum(c) {
export function rgbToHex([r, g, b]) {
return `#${[r, g, b].map(n => PadNum(n)).join('')}`.toUpperCase();
}
+
+/**
+ * Get color group name by parsing name, discard step in the name
+ * e.g. Global Warming 6 -> Global Warming
+ *
+ * @param {Object} colorRange
+ * @return {string}
+ */
+export function getColorGroupByName(colorRange) {
+ if (!colorRange || typeof colorRange.name !== 'string') {
+ return null;
+ }
+
+ return colorRange.name.replace(/\b[^a-zA-Z]+$/, '');
+}
+
+/**
+ * Get a reversed colorRange
+ * @param {Boolean} reversed
+ * @param {Object} colorRange
+ */
+export function reverseColorRange(reversed, colorRange) {
+ if (!colorRange) return null;
+ // if (colorRange.reversed) return colorRange;
+ return {
+ ...colorRange,
+ reversed,
+ colors: colorRange.colors.slice().reverse()
+ };
+}
diff --git a/src/utils/data-utils.js b/src/utils/data-utils.js
index db94dc23b..8cf1ded87 100644
--- a/src/utils/data-utils.js
+++ b/src/utils/data-utils.js
@@ -243,3 +243,13 @@ export const parseFieldValue = (value, type) => {
return value;
}
};
+
+const arrayMoveMutate = (array, from, to) => {
+ array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
+};
+
+export const arrayMove = (array, from, to) => {
+ array = array.slice();
+ arrayMoveMutate(array, from, to);
+ return array;
+};
diff --git a/test/browser/components/index.js b/test/browser/components/index.js
index 2178fe0ac..6260a580e 100644
--- a/test/browser/components/index.js
+++ b/test/browser/components/index.js
@@ -29,3 +29,4 @@ import './data-table-modal-test';
import './notifications';
import './kepler-gl-test';
import './map';
+import './side-panel';
diff --git a/test/browser/components/side-panel/color-selector-test.js b/test/browser/components/side-panel/color-selector-test.js
new file mode 100644
index 000000000..bd05f8557
--- /dev/null
+++ b/test/browser/components/side-panel/color-selector-test.js
@@ -0,0 +1,799 @@
+// Copyright (c) 2019 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.
+
+/* eslint-disable max-statements */import React from 'react';
+import test from 'tape';
+import {mount} from 'enzyme';
+import sinon from 'sinon';
+import cloneDeep from 'lodash.clonedeep';
+
+import ColorSelector, {
+ ColorSelectorInput,
+ ColorBlock
+} from 'components/side-panel/layer-panel/color-selector';
+import {
+ LayerColorSelector,
+ LayerColorRangeSelector,
+ ArcLayerColorSelector,
+ getLayerConfiguratorProps,
+ getVisConfiguratorProps
+} from 'components/side-panel/layer-panel/layer-configurator';
+import SingleColorPalette from 'components/side-panel/layer-panel/single-color-palette';
+import ColorRangeSelector, {
+ PaletteConfig,
+ ColorPaletteGroup,
+ ALL_TYPES
+} from 'components/side-panel/layer-panel/color-range-selector';
+import ColorPalette from 'components/side-panel/layer-panel/color-palette';
+import CustomPalette from 'components/side-panel/layer-panel/custom-palette';
+import CustomPicker from 'components/side-panel/layer-panel/custom-picker';
+
+import ItemSelector from 'components/common/item-selector/item-selector';
+import {Button, InlineInput} from 'components/common/styled-components';
+
+import {COLOR_RANGES} from 'constants/color-ranges';
+
+import {
+ StateWFilesFiltersLayerColor,
+ StateWTrips
+} from 'test/helpers/mock-state';
+import {mountWithTheme} from 'test/helpers/component-utils';
+import {hexToRgb} from 'utils/color-utils';
+
+test('Components -> ColorSelector.render', t => {
+ t.doesNotThrow(() => {
+ mount(<ColorSelector />);
+ }, 'Should not fail without props');
+
+ t.end();
+});
+
+test('Components -> LayerColorSelector.render -> render layer color', t => {
+ const initialState = cloneDeep(StateWFilesFiltersLayerColor.visState);
+ const {layers} = initialState;
+ const pointLayer = layers[0];
+
+ let wrapper;
+
+ // create spies
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+
+ const layerConfiguratorProps = getLayerConfiguratorProps(mockProps);
+
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorSelector {...layerConfiguratorProps} />
+ );
+ }, 'Should not fail with layers');
+ const CSInstance = wrapper.find(ColorSelector);
+
+ t.equal(CSInstance.length, 1, 'should render 1 ColorSelector');
+
+ const cSProps = CSInstance.at(0).props();
+ const expectedColorSets = [
+ {
+ selectedColor: pointLayer.config.color,
+ setColor: () => {}
+ }
+ ];
+ t.equal(
+ cSProps.colorSets.length,
+ expectedColorSets.length,
+ 'should pass correct colorSets'
+ );
+ t.deepEqual(
+ Object.keys(cSProps.colorSets[0]),
+ Object.keys(expectedColorSets[0]),
+ 'should pass correct colorSets[0]'
+ );
+ t.equal(
+ cSProps.colorSets[0].selectedColor,
+ expectedColorSets[0].selectedColor,
+ 'should pass correct colorSets.selectedColor'
+ );
+
+ // color block
+ const cblk = wrapper.find(ColorBlock);
+ t.equal(cblk.length, 1, 'should render 1 ColorBlock');
+
+ const csInput = wrapper.find(ColorSelectorInput);
+ t.equal(csInput.length, 1, 'should render 1 ColorSelectorInput');
+ csInput.simulate('mousedown');
+
+ t.ok(updateLayerColorUI.calledOnce, 'should call updateLayerColorUI');
+ t.ok(updateLayerVisConfig.notCalled, 'should not call updateLayerColorUI');
+ t.ok(updateLayerConfig.notCalled, 'should not call updateLayerConfig');
+
+ // should open dropdown
+ t.ok(updateLayerColorUI.calledWith('color', {showDropdown: 0}));
+
+ t.end();
+});
+
+test('Components -> LayerColorSelector.render -> render single color click', t => {
+ const initialState = cloneDeep(StateWFilesFiltersLayerColor.visState);
+ const {layers} = initialState;
+ // should dropdown for layer color select
+ const pointLayer = layers[0].updateLayerColorUI('color', {showDropdown: 0});
+
+ let wrapper;
+
+ // create spies
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+
+ const layerConfiguratorProps = getLayerConfiguratorProps(mockProps);
+
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorSelector {...layerConfiguratorProps} />
+ );
+ }, 'Should not fail render color select');
+ const CSInstance = wrapper.find(ColorSelector);
+
+ t.equal(CSInstance.length, 1, 'should render 1 ColorSelector');
+
+ // open color dropdown
+ const scp = wrapper.find(SingleColorPalette);
+ t.equal(scp.length, 1, 'should render 1 SingleColorPalette');
+
+ t.ok(
+ wrapper.find('.single-color-palette__block'),
+ 'should render color blocks'
+ );
+
+ // click color block
+ wrapper
+ .find('.single-color-palette__block')
+ .at(0)
+ .simulate('click');
+
+ t.ok(updateLayerConfig.calledOnce, 'should call updateLayerConfig');
+ t.ok(updateLayerConfig.calledWith({color: [255, 254, 230]}));
+
+ t.end();
+});
+
+test('Components -> ArcLayerColorSelector.render -> render single color', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+ const arcLayer = layers.find(l => l.type === 'arc');
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: arcLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+
+ const layerConfiguratorProps = getLayerConfiguratorProps(mockProps);
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <ArcLayerColorSelector
+ layer={arcLayer}
+ setColorUI={layerConfiguratorProps.setColorUI}
+ onChangeConfig={layerConfiguratorProps.onChange}
+ onChangeVisConfig={visConfiguratorProps.onChange}
+ />
+ );
+ }, 'Should not fail render arc color select');
+
+ const CSInstance = wrapper.find(ColorSelector);
+ t.equal(CSInstance.length, 1, 'should render 1 ColorSelector');
+
+ const cSProps = CSInstance.at(0).props();
+ const expectedColorSets = [
+ {
+ selectedColor: arcLayer.config.color,
+ setColor: () => {},
+ label: 'Source'
+ },
+ {
+ selectedColor: arcLayer.config.color,
+ setColor: () => {},
+ label: 'Target'
+ }
+ ];
+ t.equal(
+ cSProps.colorSets.length,
+ expectedColorSets.length,
+ 'should pass correct colorSets'
+ );
+ t.deepEqual(
+ Object.keys(cSProps.colorSets[0]),
+ Object.keys(expectedColorSets[0]),
+ 'should pass correct colorSets[0]'
+ );
+ t.equal(
+ cSProps.colorSets[0].selectedColor,
+ expectedColorSets[0].selectedColor,
+ 'should pass correct colorSets.selectedColor'
+ );
+
+ // color block
+ const cblk = wrapper.find(ColorBlock);
+ t.equal(cblk.length, 2, 'should render 2 ColorBlocks');
+
+ const csInput = wrapper.find(ColorSelectorInput);
+ t.equal(csInput.length, 2, 'should render 2 ColorSelectorInput');
+ csInput.at(1).simulate('mousedown');
+
+ t.ok(
+ updateLayerColorUI.calledOnce,
+ 'should call updateLayerColorUI when mousedown 2nd block'
+ );
+ t.ok(
+ updateLayerVisConfig.notCalled,
+ 'should not call updateLayerColorUI when mousedown 2nd block'
+ );
+ t.ok(
+ updateLayerConfig.notCalled,
+ 'should not call updateLayerConfig when mousedown 2nd block'
+ );
+
+ // should open dropdown
+ t.ok(updateLayerColorUI.calledWith('color', {showDropdown: 1}));
+
+ t.end();
+});
+
+test('Components -> ArcLayerColorSelector.render -> render single color click', t => {
+ const initialState = cloneDeep(StateWFilesFiltersLayerColor.visState);
+ const {layers} = initialState;
+ // should dropdown for arc layer target color select
+ const arcLayer = layers[1].updateLayerColorUI('color', {showDropdown: 1});
+
+ // create spies
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: arcLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+
+ const layerConfiguratorProps = getLayerConfiguratorProps(mockProps);
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <ArcLayerColorSelector
+ layer={arcLayer}
+ setColorUI={layerConfiguratorProps.setColorUI}
+ onChangeConfig={layerConfiguratorProps.onChange}
+ onChangeVisConfig={visConfiguratorProps.onChange}
+ />
+ );
+ }, 'Should not fail render arc color select');
+ const CSInstance = wrapper.find(ColorSelector);
+ t.equal(CSInstance.length, 1, 'should render 1 ColorSelector');
+
+ // open color dropdown
+ const scp = wrapper.find(SingleColorPalette);
+ t.equal(scp.length, 1, 'should render 1 SingleColorPalette');
+
+ t.ok(
+ wrapper.find('.single-color-palette__block'),
+ 'should render color blocks'
+ );
+
+ // click color block
+ wrapper
+ .find('.single-color-palette__block')
+ .at(0)
+ .simulate('click');
+
+ t.ok(updateLayerVisConfig.calledOnce, 'should call updateLayerVisConfig');
+ t.ok(updateLayerVisConfig.calledWith({targetColor: [255, 254, 230]}));
+
+ t.end();
+});
+
+test('Components -> LayerColorRangeSelector.render -> ColorSelector', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+ const pointLayer = layers.find(l => l.type === 'point');
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorRangeSelector {...visConfiguratorProps} />
+ );
+ }, 'Should not fail render color range select');
+ const CPInstance = wrapper.find(ColorPalette);
+ t.equal(CPInstance.length, 1, 'should render 1 ColorPalette');
+
+ // render color blocks
+ const cblks = CPInstance.at(0).find('.color-range-palette__block');
+ t.equal(cblks.length, 8, 'should render 8 ColorBlocks');
+
+ const expectedColor = `rgb(${hexToRgb('#7F1941').join(', ')})`;
+ const firstColor = cblks
+ .at(0)
+ .getDOMNode()
+ .style.getPropertyValue('background-color');
+
+ t.equal(firstColor, expectedColor, 'should render correct background color');
+
+ // simulate click
+ const csInput = wrapper.find(ColorSelectorInput);
+ t.equal(csInput.length, 1, 'should render 2 ColorSelectorInput');
+ csInput.at(0).simulate('mousedown');
+
+ t.ok(
+ updateLayerColorUI.calledOnce,
+ 'should call updateLayerColorUI when mousedown 2nd block'
+ );
+ t.ok(
+ updateLayerVisConfig.notCalled,
+ 'should not call updateLayerColorUI when mousedown 2nd block'
+ );
+ t.ok(
+ updateLayerConfig.notCalled,
+ 'should not call updateLayerConfig when mousedown 2nd block'
+ );
+
+ // should open dropdown
+ t.ok(updateLayerColorUI.calledWith('colorRange', {showDropdown: 0}));
+
+ t.end();
+});
+
+test('Components -> LayerColorRangeSelector.render -> ColorSelector -> ColorRangeSelector -> select type', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+
+ // set showDropdown to true
+ const pointLayer = layers
+ .find(l => l.type === 'point')
+ .updateLayerColorUI('colorRange', {showDropdown: 0});
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+ let wrapper;
+
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorRangeSelector {...visConfiguratorProps} />
+ );
+ }, 'Should not fail render color range select');
+
+ // open color dropdown
+ t.equal(
+ wrapper.find('.color-range-selector').length,
+ 1,
+ 'should render 1 color-range-selector'
+ );
+
+ const crs = wrapper.find(ColorRangeSelector);
+ t.equal(crs.length, 1, 'should render 1 ColorRangeSelector');
+
+ const pc = crs.find(PaletteConfig);
+ t.equal(pc.length, 4, 'should render 4 PaletteConfig');
+
+ const cpg = crs.find(ColorPaletteGroup);
+ t.equal(cpg.length, 1, 'should render 1 ColorPaletteGroup');
+
+ const expectedGroups =
+ COLOR_RANGES.filter(cr => cr.colors.length === 6).length + 1;
+
+ t.equal(
+ wrapper.find(ColorPalette).length,
+ expectedGroups,
+ `should render ${expectedGroups} ColorPalette`
+ );
+ const typeSelect = crs.find(PaletteConfig).at(0);
+ t.equal(
+ typeSelect.find('.side-panel-panel__label').text(),
+ 'type',
+ 'should render type'
+ );
+
+ // click on type select
+ t.equal(
+ typeSelect.find('.item-selector__dropdown').length,
+ 1,
+ 'should render item selector dropdown input'
+ );
+
+ typeSelect
+ .find('.item-selector__dropdown')
+ .at(0)
+ .simulate('click');
+
+ wrapper.update();
+
+ const listItem = wrapper.find('.list__item');
+ t.equal(listItem.length, 6, 'should render item selector typeahead');
+
+ t.deepEqual(
+ listItem.map(nd =>
+ nd
+ .at(0)
+ .find('.list__item__anchor')
+ .at(0)
+ .text()
+ ),
+ ALL_TYPES,
+ 'should render all types'
+ );
+
+ // click on 1 type
+ listItem.at(2).simulate('click');
+ t.ok(updateLayerColorUI.calledOnce, 'updateLayerColorUI should be called');
+ const expectedArgs = [
+ 'colorRange',
+ {
+ colorRangeConfig: {
+ type: 'qualitative'
+ }
+ }
+ ];
+
+ t.deepEqual(
+ updateLayerColorUI.args[0],
+ expectedArgs,
+ 'should call updateLayerColorUI with correct args'
+ );
+
+ const reverseSwitch = crs.find(PaletteConfig).at(2);
+ t.equal(
+ reverseSwitch.find('.side-panel-panel__label').text(),
+ 'reversed',
+ 'should render reversed switch'
+ );
+
+ const switchInput = reverseSwitch.find('input').at(0);
+ switchInput.simulate('change');
+
+ t.ok(
+ updateLayerColorUI.calledTwice,
+ 'updateLayerColorUI should be called when click reserved switch'
+ );
+ const expectedArgs1 = [
+ 'colorRange',
+ {
+ colorRangeConfig: {
+ reversed: false
+ }
+ }
+ ];
+ t.deepEqual(
+ updateLayerColorUI.args[1],
+ expectedArgs1,
+ 'should call updateLayerColorUI with reversed: true'
+ );
+
+ const customSwitch = crs.find(PaletteConfig).at(3);
+ t.equal(
+ customSwitch.find('.side-panel-panel__label').text(),
+ 'Custom Palette',
+ 'should render custom switch'
+ );
+
+ customSwitch
+ .find('input')
+ .at(0)
+ .simulate('change');
+
+ t.ok(
+ updateLayerColorUI.callCount === 3,
+ 'updateLayerColorUI should be called when click custom switch'
+ );
+ const expectedArgs3 = [
+ 'colorRange',
+ {
+ colorRangeConfig: {
+ custom: true
+ }
+ }
+ ];
+ t.deepEqual(
+ updateLayerColorUI.args[2],
+ expectedArgs3,
+ 'should call updateLayerColorUI with custom: true'
+ );
+ t.end();
+});
+
+test('Components -> LayerColorRangeSelector.render -> ColorSelector -> ColorRangeSelector -> CustomPalette.render', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+
+ // set showDropdown to true
+ const pointLayer = layers
+ .find(l => l.type === 'point')
+ .updateLayerColorUI('colorRange', {showDropdown: 0})
+ .updateLayerColorUI('colorRange', {colorRangeConfig: {custom: true}});
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorRangeSelector {...visConfiguratorProps} />
+ );
+ }, 'Should not fail render color range select');
+
+ // open color dropdown
+ t.equal(
+ wrapper.find('.color-range-selector').length,
+ 1,
+ 'should render 1 color-range-selector'
+ );
+ const crs = wrapper.find(ColorRangeSelector);
+ t.equal(crs.length, 1, 'should render 1 ColorRangeSelector');
+
+ const pc = crs.find(PaletteConfig);
+ t.equal(pc.length, 1, 'should render 1 PaletteConfig');
+
+ const cp = crs.find(CustomPalette);
+ t.equal(cp.length, 1, 'should render 1 CustomPalette');
+
+ t.equal(
+ cp.find('.custom-palette__sortable-items').length,
+ pointLayer.config.colorUI.colorRange.customPalette.colors.length * 3,
+ 'should render same number of custom palette swatch'
+ );
+
+ t.end();
+});
+
+test('Components -> LayerColorRangeSelector.render -> ColorSelector -> ColorRangeSelector -> CustomPalette.update', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+
+ // set showDropdown to true
+ const pointLayer = layers
+ .find(l => l.type === 'point')
+ .updateLayerColorUI('colorRange', {showDropdown: 0})
+ .updateLayerColorUI('colorRange', {colorRangeConfig: {custom: true}});
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorRangeSelector {...visConfiguratorProps} />
+ );
+ }, 'Should not fail render color range select');
+ // current colorRange
+ // { name: 'Ice And Fire 8',
+ // type: 'diverging',
+ // category: 'Uber',
+ // colors:
+ // [ '#7F1941',
+ // '#D50255',
+ // '#FEAD54',
+ // '#FEEDB1',
+ // '#E8FEB5',
+ // '#49E3CE',
+ // '#0198BD',
+ // '#007A99' ],
+ // reversed: true }
+ const cp = wrapper.find(CustomPalette);
+ t.equal(cp.length, 1, 'should render 1 CustomPalette');
+
+ // add step
+ t.equal(cp.find(Button).length, 3, 'should render 3 buttons');
+
+ // click add step
+ cp.find(Button)
+ .at(0)
+ .simulate('click');
+
+ t.deepEqual(
+ updateLayerColorUI.args[0], ['colorRange', {
+ customPalette: {
+ colors: [
+ '#7F1941',
+ '#D50255',
+ '#FEAD54',
+ '#FEEDB1',
+ '#E8FEB5',
+ '#49E3CE',
+ '#0198BD',
+ '#007A99',
+ '#007A99'
+ ]
+ }
+ }],
+ 'should add color to custom palette when click add step'
+ );
+
+ // click cancel
+ cp.find(Button)
+ .at(1)
+ .simulate('click');
+
+ t.deepEqual(
+ updateLayerColorUI.args[1], ['colorRange', {
+ colorRangeConfig: {custom: false},
+ showSketcher: false
+ }],
+ 'should set custom: false when cancel'
+ );
+
+ // click apply
+ cp.find(Button)
+ .at(2)
+ .simulate('click');
+
+ t.deepEqual(
+ updateLayerColorUI.args[2], ['colorRange', {
+ colorRangeConfig: {custom: false},
+ showSketcher: false
+ }],
+ 'should set custom to false when click apply'
+ );
+
+ t.deepEqual(
+ updateLayerVisConfig.args[0], [{
+ colorRange: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: [
+ '#7F1941',
+ '#D50255',
+ '#FEAD54',
+ '#FEEDB1',
+ '#E8FEB5',
+ '#49E3CE',
+ '#0198BD',
+ '#007A99'
+ ]
+ }
+ }],
+ 'should set colorRange to custom'
+ );
+
+ // click swatch
+ wrapper
+ .find('.custom-palette__swatch')
+ .at(3)
+ .simulate('click');
+
+ t.ok(
+ updateLayerColorUI.calledWith('colorRange', {
+ showSketcher: 3
+ }),
+ 'should set showSketcher to swatch index'
+ );
+
+ wrapper.update();
+
+ t.end();
+});
+
+test('Components -> LayerColorRangeSelector.render -> ColorSelector -> ColorRangeSelector -> CustomPalette -> CustomPicker', t => {
+ const initialState = StateWTrips.visState;
+ const {layers} = initialState;
+
+ // set showSketcher to true
+ const pointLayer = layers
+ .find(l => l.type === 'point')
+ .updateLayerColorUI('colorRange', {showDropdown: 0})
+ .updateLayerColorUI('colorRange', {colorRangeConfig: {custom: true}})
+ .updateLayerColorUI('colorRange', {showSketcher: 2});
+
+ const updateLayerConfig = sinon.spy();
+ const updateLayerVisConfig = sinon.spy();
+ const updateLayerColorUI = sinon.spy();
+
+ const mockProps = {
+ layer: pointLayer,
+ datasets: initialState.datasets,
+ updateLayerConfig,
+ updateLayerVisConfig,
+ updateLayerColorUI
+ };
+
+ const visConfiguratorProps = getVisConfiguratorProps(mockProps);
+ let wrapper;
+ t.doesNotThrow(() => {
+ wrapper = mountWithTheme(
+ <LayerColorRangeSelector {...visConfiguratorProps} />
+ );
+ }, 'Should not fail render color range select');
+
+ const cp = wrapper.find(CustomPalette);
+ t.equal(cp.length, 1, 'should render 1 CustomPalette');
+
+ const picker = cp.find(CustomPicker);
+ t.equal(picker.length, 1, 'should render 1 CustomPicker');
+
+ t.end();
+});
diff --git a/test/browser/components/side-panel/index.js b/test/browser/components/side-panel/index.js
new file mode 100644
index 000000000..fe78a2e7d
--- /dev/null
+++ b/test/browser/components/side-panel/index.js
@@ -0,0 +1,21 @@
+// Copyright (c) 2019 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 './color-selector-test';
diff --git a/test/fixtures/state-saved-v0.js b/test/fixtures/state-saved-v0.js
index 8424cf511..b03df5beb 100644
--- a/test/fixtures/state-saved-v0.js
+++ b/test/fixtures/state-saved-v0.js
@@ -21,7 +21,7 @@
import {KeplerGlLayers} from 'layers';
const {PointLayer, ArcLayer, HexagonLayer, GeojsonLayer} = KeplerGlLayers;
import {getDefaultInteraction} from 'utils/interaction-utils';
-import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';
+import {DEFAULT_TEXT_LABEL, DEFAULT_COLOR_UI} from 'layers/layer-factory';
export const savedStateV0 = {
config: {
@@ -1037,6 +1037,7 @@ mergedLayer0.config = {
sizeScale: 'linear',
sizeDomain: [0, 1],
textLabel: [DEFAULT_TEXT_LABEL],
+
visConfig: {
radius: 270.4,
opacity: 0.8,
@@ -1115,6 +1116,10 @@ mergedLayer1.config = {
sizeScale: 'linear',
sizeDomain: [0, 1],
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
opacity: 0.41,
thickness: 2,
@@ -1177,6 +1182,10 @@ mergedLayer2.config = {
sizeDomain: [78, 694],
sizeScale: 'linear',
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
radius: 10,
opacity: 0.8,
@@ -1256,6 +1265,10 @@ mergedLayer3.config = {
sizeScale: 'linear',
sizeDomain: [0, 1],
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
colorAggregation: 'maximum',
sizeAggregation: 'average',
@@ -1327,6 +1340,10 @@ mergedLayer4.config = {
sizeScale: 'linear',
sizeDomain: [0, 1],
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
heightField: null,
heightDomain: [0, 1],
heightScale: 'linear',
diff --git a/test/fixtures/state-saved-v1-1.js b/test/fixtures/state-saved-v1-1.js
index 4e19a9221..fedc64628 100644
--- a/test/fixtures/state-saved-v1-1.js
+++ b/test/fixtures/state-saved-v1-1.js
@@ -20,7 +20,7 @@
import GeojsonLayer from 'layers/geojson-layer/geojson-layer';
import {Messages, Crosshairs} from 'components/common/icons';
-import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';
+import {DEFAULT_TEXT_LABEL, DEFAULT_COLOR_UI} from 'layers/layer-factory';
import {getDefaultInteraction} from 'utils/interaction-utils';
export const savedStateV1 = {
@@ -911,6 +911,10 @@ mergedLayer0.config = {
radiusField: null,
radiusScale: 'linear',
radiusDomain: [0, 1],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
opacity: 0.8,
thickness: 2,
@@ -2717,6 +2721,10 @@ mergedLayer1.config = {
radiusField: null,
radiusScale: 'linear',
radiusDomain: [0, 1],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
opacity: 0.8,
thickness: 7.6,
diff --git a/test/fixtures/state-saved-v1-3.js b/test/fixtures/state-saved-v1-3.js
index f195acb62..a16e3fda8 100644
--- a/test/fixtures/state-saved-v1-3.js
+++ b/test/fixtures/state-saved-v1-3.js
@@ -20,7 +20,7 @@
import {KeplerGlLayers} from 'layers';
const {PointLayer, HexagonLayer} = KeplerGlLayers;
-import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';
+import {DEFAULT_TEXT_LABEL, DEFAULT_COLOR_UI} from 'layers/layer-factory';
// saved state v1 with split maps
export const savedStateV1 = {
@@ -399,6 +399,10 @@ mergedLayer0.config = {
sizeScale: 'sqrt',
sizeDomain: [1000, 3000],
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
radius: 10,
fixedRadius: true,
@@ -467,6 +471,10 @@ mergedLayer1.config = {
sizeScale: 'linear',
sizeDomain: [0, 1],
textLabel: [DEFAULT_TEXT_LABEL],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
opacity: 0.8,
worldUnitSize: 2.73,
diff --git a/test/fixtures/state-saved-v1-4.js b/test/fixtures/state-saved-v1-4.js
index 5991d7bf4..9a7bbfff7 100644
--- a/test/fixtures/state-saved-v1-4.js
+++ b/test/fixtures/state-saved-v1-4.js
@@ -20,6 +20,7 @@
import {KeplerGlLayers} from 'layers';
const {PointLayer} = KeplerGlLayers;
+import {DEFAULT_COLOR_UI} from 'layers/layer-factory';
export const stateSavedV1 = {
datasets: [
@@ -245,6 +246,10 @@ mergedLayer0.config = {
anchor: 'end',
alignment: 'center'
}],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ },
visConfig: {
radius: 12.5,
fixedRadius: false,
diff --git a/test/fixtures/test-hex-id-data.js b/test/fixtures/test-hex-id-data.js
index 3bce77258..5db6a9526 100644
--- a/test/fixtures/test-hex-id-data.js
+++ b/test/fixtures/test-hex-id-data.js
@@ -20,6 +20,7 @@
import {KeplerGlLayers} from 'layers';
const {H3Layer} = KeplerGlLayers;
+import {DEFAULT_COLOR_UI} from 'layers/layer-factory';
export default `hex_id,value
89283082c2fffff,64
@@ -274,7 +275,11 @@ mergedH3Layer.config = {
anchor: 'start',
alignment: 'center'
}
- ]
+ ],
+ colorUI: {
+ color: DEFAULT_COLOR_UI,
+ colorRange: DEFAULT_COLOR_UI
+ }
};
export const mergedFilters = [
diff --git a/test/fixtures/test-trip-data.js b/test/fixtures/test-trip-data.js
new file mode 100644
index 000000000..2ce4ab41b
--- /dev/null
+++ b/test/fixtures/test-trip-data.js
@@ -0,0 +1,483 @@
+// Copyright (c) 2019 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.
+
+export const fields = [
+ {
+ name: 'tpep_pickup_datetime',
+ format: 'YYYY-M-D H:m:s',
+ type: 'timestamp'
+ },
+ {
+ name: 'tpep_dropoff_datetime',
+ format: 'YYYY-M-D H:m:s',
+ type: 'timestamp'
+ },
+ {
+ name: 'passenger_count',
+ format: '',
+ type: 'integer'
+ },
+ {name: 'trip_distance', format: '', type: 'real'},
+ {name: 'pickup_longitude', format: '', type: 'real'},
+ {name: 'pickup_latitude', format: '', type: 'real'},
+ {name: 'dropoff_longitude', format: '', type: 'real'},
+ {name: 'dropoff_latitude', format: '', type: 'real'},
+ {name: 'fare_amount', format: '', type: 'real'},
+ {name: 'is_completed', format: '', type: 'boolean'},
+ {name: 'fare_type', format: '', type: 'string'}
+];
+
+export const rows = [
+ [
+ '2015-01-15 19:05:39 +00:00',
+ '2015-01-15 19:23:42 +00:00',
+ 1,
+ 1.59,
+ -73.99389648,
+ 40.75011063,
+ -73.97478485,
+ 40.75061798,
+ 12,
+ true,
+ 'orange peel'
+ ],
+ [
+ '2015-01-15 19:05:39 +00:00',
+ '2015-01-15 19:32:00 +00:00',
+ 0,
+ 2.38,
+ -73.97642517,
+ 40.73981094,
+ -73.98397827,
+ 40.75788879,
+ 16.5,
+ false,
+ 'banana peel'
+ ],
+ [
+ '2015-01-15 19:05:40 +00:00',
+ '2015-01-15 19:21:00 +00:00',
+ 5,
+ 2.83,
+ -73.96870422,
+ 40.75424576,
+ -73.9551239,
+ 40.7868576,
+ 12.5,
+ false,
+ 'apple tree'
+ ],
+ [
+ '2015-01-15 19:05:40 +00:00',
+ '2015-01-15 19:28:18 +00:00',
+ 5,
+ 8.33,
+ -73.86306,
+ 40.76958084,
+ -73.95271301,
+ 40.78578186,
+ 26,
+ true,
+ 'orange peel'
+ ],
+ [
+ '2015-01-15 19:05:41 +00:00',
+ '2015-01-15 19:20:36 +00:00',
+ 1,
+ 2.37,
+ -73.94554138,
+ 40.77942276,
+ -73.98085022,
+ 40.78608322,
+ 11.5,
+ true,
+ 'apple tree'
+ ],
+ [
+ '2015-01-15 19:05:41 +00:00',
+ '2015-01-15 19:20:22 +00:00',
+ 2,
+ 7.13,
+ -73.87445831,
+ 40.7740097,
+ -73.95237732,
+ 40.71858978,
+ 21.5,
+ true,
+ 'orange peel'
+ ]
+];
+
+export const dataId = 'test_trip_data';
+export const config = {
+ version: 'v1',
+ config: {
+ visState: {
+ layers: [
+ {
+ type: 'heatmap',
+ config: {
+ dataId,
+ columns: {
+ lat: 'pickup_latitude',
+ lng: 'pickup_longitude'
+ },
+ isVisible: true
+ }
+ },
+ {
+ type: 'point',
+ config: {
+ dataId,
+ columns: {
+ lat: 'pickup_latitude',
+ lng: 'pickup_longitude'
+ },
+ isVisible: true,
+ visConfig: {
+ colorRange: {
+ name: 'Ice And Fire 8',
+ type: 'diverging',
+ category: 'Uber',
+ colors: [
+ '#7F1941',
+ '#D50255',
+ '#FEAD54',
+ '#FEEDB1',
+ '#E8FEB5',
+ '#49E3CE',
+ '#0198BD',
+ '#007A99'
+ ],
+ reversed: true
+ },
+ strokeColorRange: {
+ name: 'Global Warming',
+ type: 'sequential',
+ category: 'Uber',
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
+ }
+ }
+ },
+ visualChannels: {
+ colorField: {
+ name: 'trip_distance',
+ type: 'real'
+ },
+ sizeField: {
+ name: 'passenger_count',
+ type: 'integer'
+ }
+ }
+ },
+ {
+ type: 'arc',
+ config: {
+ dataId,
+ columns: {
+ lat0: 'pickup_latitude',
+ lng0: 'pickup_longitude',
+ lat1: 'dropoff_latitude',
+ lng1: 'dropoff_longitude'
+ },
+ isVisible: true
+ }
+ },
+ {
+ id: '38f7j6',
+ type: 'hexagon',
+ config: {
+ dataId,
+ label: 'new layer',
+ columns: {
+ lat: 'pickup_latitude',
+ lng: 'pickup_longitude'
+ },
+ isVisible: true,
+ visConfig: {
+ opacity: 0.76,
+ worldUnitSize: 0.3,
+ colorRange: {
+ name: 'ColorBrewer PuOr-10',
+ type: 'diverging',
+ category: 'ColorBrewer',
+ colors: [
+ '#7f3b08',
+ '#b35806',
+ '#e08214',
+ '#fdb863',
+ '#fee0b6',
+ '#d8daeb',
+ '#b2abd2',
+ '#8073ac',
+ '#542788',
+ '#2d004b'
+ ]
+ }
+ }
+ }
+ }
+ ],
+ filters: [
+ {
+ id: 'me',
+ dataId,
+ name: 'tpep_pickup_datetime',
+ type: 'timeRange',
+ enlarged: true
+ }
+ ],
+ interactionConfig: {
+ tooltip: {
+ fieldsToShow: {
+ [dataId]: ['tpep_pickup_datetime', 'tpep_dropoff_datetime']
+ },
+ enabled: true
+ }
+ }
+ }
+ }
+};
+
+const exported = {
+ version: 'v1',
+ config: {
+ visState: {
+ layers: [
+ {
+ id: 'rsgg2rj',
+ type: 'point',
+ config: {
+ dataId: 'test_trip_data',
+ label: 'new layer',
+ color: [221, 178, 124],
+ columns: {
+ lat: 'pickup_latitude',
+ lng: 'pickup_longitude',
+ altitude: null
+ },
+ isVisible: true,
+ visConfig: {
+ radius: 10,
+ fixedRadius: false,
+ opacity: 0.8,
+ outline: false,
+ thickness: 2,
+ strokeColor: null,
+ colorRange: {
+ name: 'Ice And Fire 8',
+ type: 'diverging',
+ category: 'Uber',
+ colors: [
+ '#7F1941',
+ '#D50255',
+ '#FEAD54',
+ '#FEEDB1',
+ '#E8FEB5',
+ '#49E3CE',
+ '#0198BD',
+ '#007A99'
+ ],
+ reversed: true
+ },
+ strokeColorRange: {
+ name: 'Global Warming',
+ type: 'sequential',
+ category: 'Uber',
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
+ },
+ radiusRange: [0, 50],
+ filled: true
+ },
+ textLabel: [
+ {
+ field: null,
+ color: [255, 255, 255],
+ size: 18,
+ offset: [0, 0],
+ anchor: 'start',
+ alignment: 'center'
+ }
+ ]
+ },
+ visualChannels: {
+ colorField: {
+ name: 'trip_distance',
+ type: 'real'
+ },
+ colorScale: 'quantile',
+ strokeColorField: null,
+ strokeColorScale: 'quantile',
+ sizeField: {
+ name: 'passenger_count',
+ type: 'integer'
+ },
+ sizeScale: 'sqrt'
+ }
+ },
+ {
+ id: 'a9i93lg',
+ type: 'arc',
+ config: {
+ dataId: 'test_trip_data',
+ label: 'new layer',
+ color: [136, 87, 44],
+ columns: {
+ lat0: 'pickup_latitude',
+ lng0: 'pickup_longitude',
+ lat1: 'dropoff_latitude',
+ lng1: 'dropoff_longitude'
+ },
+ isVisible: true,
+ visConfig: {
+ opacity: 0.8,
+ thickness: 2,
+ colorRange: {
+ name: 'Global Warming',
+ type: 'sequential',
+ category: 'Uber',
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
+ },
+ sizeRange: [0, 10],
+ targetColor: null
+ },
+ textLabel: [
+ {
+ field: null,
+ color: [255, 255, 255],
+ size: 18,
+ offset: [0, 0],
+ anchor: 'start',
+ alignment: 'center'
+ }
+ ]
+ },
+ visualChannels: {
+ colorField: null,
+ colorScale: 'quantile',
+ sizeField: null,
+ sizeScale: 'linear'
+ }
+ },
+ {
+ id: '38f7j6',
+ type: 'hexagon',
+ config: {
+ dataId: 'test_trip_data',
+ label: 'new layer',
+ color: [183, 136, 94],
+ columns: {
+ lat: 'pickup_latitude',
+ lng: 'pickup_longitude'
+ },
+ isVisible: true,
+ visConfig: {
+ opacity: 0.76,
+ worldUnitSize: 0.3,
+ resolution: 8,
+ colorRange: {
+ name: 'ColorBrewer PuOr-10',
+ type: 'diverging',
+ category: 'ColorBrewer',
+ colors: [
+ '#7f3b08',
+ '#b35806',
+ '#e08214',
+ '#fdb863',
+ '#fee0b6',
+ '#d8daeb',
+ '#b2abd2',
+ '#8073ac',
+ '#542788',
+ '#2d004b'
+ ]
+ },
+ coverage: 1,
+ sizeRange: [0, 500],
+ percentile: [0, 100],
+ elevationPercentile: [0, 100],
+ elevationScale: 5,
+ colorAggregation: 'count',
+ sizeAggregation: 'count',
+ enable3d: false
+ },
+ textLabel: [
+ {
+ field: null,
+ color: [255, 255, 255],
+ size: 18,
+ offset: [0, 0],
+ anchor: 'start',
+ alignment: 'center'
+ }
+ ]
+ },
+ visualChannels: {
+ colorField: null,
+ colorScale: 'quantile',
+ sizeField: null,
+ sizeScale: 'linear'
+ }
+ }
+ ],
+ interactionConfig: {
+ tooltip: {
+ fieldsToShow: {
+ test_trip_data: [
+ 'tpep_pickup_datetime',
+ 'tpep_dropoff_datetime',
+ 'passenger_count',
+ 'trip_distance',
+ 'fare_amount'
+ ]
+ },
+ enabled: true
+ },
+ brush: {
+ size: 0.5,
+ enabled: false
+ }
+ },
+ layerBlending: 'normal',
+ splitMaps: []
+ }
+ }
+};
diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.js
index 61e7ec0fd..197a4edcf 100644
--- a/test/helpers/mock-state.js
+++ b/test/helpers/mock-state.js
@@ -26,11 +26,18 @@ import keplerGlReducer from 'reducers/core';
import * as VisStateActions from 'actions/vis-state-actions';
import * as MapStyleActions from 'actions/map-style-actions';
import * as MapStateActions from 'actions/map-state-actions';
+import {addDataToMap} from 'actions/actions';
import {DEFAULT_TEXT_LABEL} from 'layers/layer-factory';
// fixtures
import {testFields, testAllData} from 'test/fixtures/test-csv-data';
import {fields, rows} from 'test/fixtures/geojson';
+import {
+ fields as tripFields,
+ rows as tripRows,
+ config as tripConfig,
+ dataId as tripDataId
+} from 'test/fixtures/test-trip-data';
const geojsonFields = cloneDeep(fields);
const geojsonRows = cloneDeep(rows);
@@ -132,6 +139,25 @@ function mockStateWithFilters(state) {
return prepareState;
}
+/**
+ * Mock state will contain 1 heatmap, 1 point and 1 arc layer, 1 hexbin layer and 1 time filter
+ * @param {*} state
+ */
+function mockStateWithTripData() {
+ const initialState = cloneDeep(InitialState);
+
+ return keplerGlReducer(initialState, addDataToMap({
+ datasets: {
+ info: {
+ label: 'Sample Trips',
+ id: tripDataId
+ },
+ data: {fields: tripFields, rows: tripRows}
+ },
+ config: tripConfig
+ }));
+}
+
function mockStateWithLayerDimensions(state) {
const initialState = state || mockStateWithFileUpload();
@@ -151,22 +177,12 @@ function mockStateWithLayerDimensions(state) {
'color'
];
- const textLabelField = initialState.visState.datasets['190vdll3di'].fields.find(
- f => f.name === 'date'
- );
+ const textLabelField = initialState.visState.datasets[
+ '190vdll3di'
+ ].fields.find(f => f.name === 'date');
- const textLabelPayload1 = [
- layer0,
- 0,
- 'field',
- textLabelField
- ];
- const textLabelPayload2 = [
- layer0,
- 0,
- 'color',
- [255, 0, 0]
- ];
+ const textLabelPayload1 = [layer0, 0, 'field', textLabelField];
+ const textLabelPayload2 = [layer0, 0, 'color', [255, 0, 0]];
// layers = [ 'point', 'geojson', 'hexagon' ]
const reorderPayload = [[2, 0, 1]];
@@ -285,14 +301,6 @@ function mockStateWithSplitMaps(state) {
return prepareState;
}
-export const StateWFiles = mockStateWithFileUpload();
-export const StateWFilters = mockStateWithFilters();
-export const StateWFilesFiltersLayerColor = mockStateWithLayerDimensions(
- StateWFilters
-);
-
-export const StateWCustomMapStyle = mockStateWithCustomMapStyle();
-export const StateWSplitMaps = mockStateWithSplitMaps();
// saved hexagon layer
export const expectedSavedLayer0 = {
id: 'hexagon-2',
@@ -400,14 +408,16 @@ export const expectedSavedLayer1 = {
lng: 'gps_data.lng',
altitude: null
},
- textLabel: [{
- ...DEFAULT_TEXT_LABEL,
- field: {
- name: 'date',
- type: 'date'
- },
- color: [255, 0, 0]
- }],
+ textLabel: [
+ {
+ ...DEFAULT_TEXT_LABEL,
+ field: {
+ name: 'date',
+ type: 'date'
+ },
+ color: [255, 0, 0]
+ }
+ ],
isVisible: true,
visConfig: {
radius: 10,
@@ -426,7 +436,14 @@ export const expectedSavedLayer1 = {
name: 'Global Warming',
type: 'sequential',
category: 'Uber',
- colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
},
strokeColor: null,
radiusRange: [0, 50]
@@ -474,7 +491,14 @@ export const expectedLoadedLayer1 = {
name: 'Global Warming',
type: 'sequential',
category: 'Uber',
- colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
},
filled: true,
strokeColor: null,
@@ -489,14 +513,16 @@ export const expectedLoadedLayer1 = {
strokeColorScale: 'quantile',
sizeField: null,
sizeScale: 'linear',
- textLabel: [{
- ...DEFAULT_TEXT_LABEL,
- field: {
- name: 'date',
- type: 'date'
- },
- color: [255, 0, 0]
- }]
+ textLabel: [
+ {
+ ...DEFAULT_TEXT_LABEL,
+ field: {
+ name: 'date',
+ type: 'date'
+ },
+ color: [255, 0, 0]
+ }
+ ]
}
};
@@ -531,7 +557,14 @@ export const expectedSavedLayer2 = {
name: 'Global Warming',
type: 'sequential',
category: 'Uber',
- colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
},
strokeColor: [11, 11, 11],
radius: 10,
@@ -591,7 +624,14 @@ export const expectedLoadedLayer2 = {
name: 'Global Warming',
type: 'sequential',
category: 'Uber',
- colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300']
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
},
strokeColor: [11, 11, 11],
radius: 10,
@@ -617,3 +657,13 @@ export const expectedLoadedLayer2 = {
textLabel: [DEFAULT_TEXT_LABEL]
}
};
+
+export const StateWFiles = mockStateWithFileUpload();
+export const StateWFilters = mockStateWithFilters();
+export const StateWFilesFiltersLayerColor = mockStateWithLayerDimensions(
+ StateWFilters
+);
+
+export const StateWCustomMapStyle = mockStateWithCustomMapStyle();
+export const StateWSplitMaps = mockStateWithSplitMaps();
+export const StateWTrips = mockStateWithTripData();
diff --git a/test/node/reducers/vis-state-merger-test.js b/test/node/reducers/vis-state-merger-test.js
index b7e2677d4..05c8a5c90 100644
--- a/test/node/reducers/vis-state-merger-test.js
+++ b/test/node/reducers/vis-state-merger-test.js
@@ -57,24 +57,6 @@ import {
stateSavedV1 as savedStateV1Label,
mergedLayers as mergedLayersV1Label
} from 'test/fixtures/state-saved-v1-4';
-/*
-import {
- mergedFiltersV0,
- expectedMergedLayers,
- expectedMergedInteractions
-} from 'test/fixtures/app-state-parsed';
-
-import {
- mergedFiltersV1,
- mergedLayersV1,
- mergedInteractionV1
-} from 'test/fixtures/app-state-parsed-v1';
-
-import {
- mergedLayersV1Split,
- mergedSplitMapsV1
-} from 'test/fixtures/app-state-parsed-v1-split';
-*/
// helpers
import {cmpFilters, cmpLayers} from 'test/helpers/comparison-utils';
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index 7add6b0fe..ffb5edd42 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -19,7 +19,6 @@
// THE SOFTWARE.
/* eslint-disable max-statements */
-
import test from 'tape-catch';
import CloneDeep from 'lodash.clonedeep';
@@ -53,8 +52,9 @@ import {
cmpDataset
} from 'test/helpers/comparison-utils';
import {applyActions} from 'test/helpers/mock-state';
-import {LAYER_VIS_CONFIGS} from 'layers/layer-factory';
+import {LAYER_VIS_CONFIGS, DEFAULT_COLOR_UI} from 'layers/layer-factory';
import {getNextColorMakerValue} from 'test/helpers/layer-utils';
+import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';
const mockData = {
fields: [
@@ -200,11 +200,14 @@ test('#visStateReducer -> ADD_LAYER.1', t => {
layers: [{id: 'existing_layer'}],
layerData: [[{data: [1, 2, 3]}, {data: [4, 5, 6]}]],
layerOrder: [0],
- splitMaps: [{
- layers: {existing_layer: false}
- },{
- layers: {existing_layer: false}
- }]
+ splitMaps: [
+ {
+ layers: {existing_layer: false}
+ },
+ {
+ layers: {existing_layer: false}
+ }
+ ]
};
const newReducer = reducer(oldState, VisStateActions.addLayer());
@@ -212,7 +215,7 @@ test('#visStateReducer -> ADD_LAYER.1', t => {
const expectedSplitMaps = [
{
layers: {
- existing_layer:false,
+ existing_layer: false,
[newId]: true
}
},
@@ -406,11 +409,7 @@ test('#visStateReducer -> LAYER_TYPE_CHANGE.2', t => {
const newLayer3 = nextState3.layers[0];
t.equal(newLayer3.type, 'hexagon', 'should change type to hexagon');
- t.equal(
- newLayer3.config.colorField,
- stringField,
- 'should keep colorField'
- );
+ t.equal(newLayer3.config.colorField, stringField, 'should keep colorField');
t.deepEqual(
newLayer3.config.colorDomain,
[0, 1],
@@ -1009,7 +1008,11 @@ test('#visStateReducer -> UPDATE_VIS_DATA.4.Geojson -> geojson data', t => {
color: layer1Color
});
- expectedLayer.updateLayerVisConfig({stroked: true, filled: true, strokeColor: layer1StrokeColor});
+ expectedLayer.updateLayerVisConfig({
+ stroked: true,
+ filled: true,
+ strokeColor: layer1StrokeColor
+ });
expectedLayer.dataToFeature = dataToFeature;
expectedLayer.meta = {
bounds: geoBounds,
@@ -1081,14 +1084,16 @@ test('#visStateReducer -> UPDATE_VIS_DATA.4.Geojson -> with config', t => {
// add data and config again
- // data
- const datasets = [{
- info: {
- id: 'milkshake2',
- label: 'king milkshake'
- },
- data: {fields, rows}
- }];
+ // data
+ const datasets = [
+ {
+ info: {
+ id: 'milkshake2',
+ label: 'king milkshake'
+ },
+ data: {fields, rows}
+ }
+ ];
const config = {
visState: {
@@ -1105,16 +1110,24 @@ test('#visStateReducer -> UPDATE_VIS_DATA.4.Geojson -> with config', t => {
}
]
}
- }
+ };
const testState = reducer(
initialState,
VisStateActions.updateVisData(datasets, {}, config)
);
- t.deepEqual(Object.keys(testState.datasets), ['milkshake2'], 'should reset state, and load dataset');
+ t.deepEqual(
+ Object.keys(testState.datasets),
+ ['milkshake2'],
+ 'should reset state, and load dataset'
+ );
t.equal(testState.layers.length, 1, 'should create 1 layer');
- t.equal(testState.layers[0].id, 'test_layer_2', 'should merge 1 layer from config');
+ t.equal(
+ testState.layers[0].id,
+ 'test_layer_2',
+ 'should merge 1 layer from config'
+ );
t.end();
});
@@ -1902,24 +1915,23 @@ test('#visStateReducer -> setFilter', t => {
// receive Vis Data will add id to fields
// filter will add filterProps to fields
- fields: geojsonFields.map(
- f =>
- f.name === 'TRIPS'
- ? {
- ...f,
- id: f.name,
- filterProp: {
- domain: [4, 20],
- fieldType: 'integer',
- histogram: expectedHistogram,
- enlargedHistogram: expectedEnlarged,
- step: 0.01,
- type: 'range',
- typeOptions: ['range'],
- value: [4, 20]
- }
+ fields: geojsonFields.map(f =>
+ f.name === 'TRIPS'
+ ? {
+ ...f,
+ id: f.name,
+ filterProp: {
+ domain: [4, 20],
+ fieldType: 'integer',
+ histogram: expectedHistogram,
+ enlargedHistogram: expectedEnlarged,
+ step: 0.01,
+ type: 'range',
+ typeOptions: ['range'],
+ value: [4, 20]
}
- : {...f, id: f.name}
+ }
+ : {...f, id: f.name}
),
filteredIndex: [0, 2],
filteredIndexForDomain: [0, 2]
@@ -2044,25 +2056,25 @@ test('#visStateReducer -> setFilter.fixedDomain', t => {
const expectedDatasetSmoothie = {
...datasetSmoothie,
// add filter prop to fields
- fields: datasetSmoothie.fields.map(
- f =>
- f.name === 'gps_data.utc_timestamp'
- ? {
- ...f,
- filterProp: {
- domain: [1474070995000, 1474072208000],
- step: 1000,
- mappedValue: expectedFilterTs.mappedValue,
- histogram: stateWidthTsFilter.filters[0].histogram,
- enlargedHistogram: stateWidthTsFilter.filters[0].enlargedHistogram,
- fieldType: 'timestamp',
- type: 'timeRange',
- enlarged: true,
- fixedDomain: true,
- value: [1474070995000, 1474072208000]
- }
+ fields: datasetSmoothie.fields.map(f =>
+ f.name === 'gps_data.utc_timestamp'
+ ? {
+ ...f,
+ filterProp: {
+ domain: [1474070995000, 1474072208000],
+ step: 1000,
+ mappedValue: expectedFilterTs.mappedValue,
+ histogram: stateWidthTsFilter.filters[0].histogram,
+ enlargedHistogram:
+ stateWidthTsFilter.filters[0].enlargedHistogram,
+ fieldType: 'timestamp',
+ type: 'timeRange',
+ enlarged: true,
+ fixedDomain: true,
+ value: [1474070995000, 1474072208000]
}
- : f
+ }
+ : f
),
data: [7, 8, 9, 10, 11, 12, 13].map(i => datasetSmoothie.allData[i]),
filteredIndex: [7, 8, 9, 10, 11, 12, 13],
@@ -2091,10 +2103,9 @@ test('#visStateReducer -> setFilter.fixedDomain', t => {
const expectedFilteredDataset = {
...stateWidthTsFilter.datasets.smoothie,
- fields: stateWidthTsFilter.datasets.smoothie.fields.map(
- f =>
- f.name === 'date'
- ? {
+ fields: stateWidthTsFilter.datasets.smoothie.fields.map(f =>
+ f.name === 'date'
+ ? {
...f,
filterProp: {
domain: ['2016-09-23', '2016-09-24', '2016-10-10'],
@@ -2103,14 +2114,18 @@ test('#visStateReducer -> setFilter.fixedDomain', t => {
value: []
}
}
- : f
+ : f
),
data: [7, 8, 9, 10, 11, 12].map(i => datasetSmoothie.allData[i]),
filteredIndex: [7, 8, 9, 10, 11, 12],
filteredIndexForDomain: [7, 8, 9, 10, 11, 12, 17, 18, 19, 20, 21, 22]
};
- cmpDataset(t, expectedFilteredDataset, stateWidthTsAndNameFilter.datasets.smoothie);
+ cmpDataset(
+ t,
+ expectedFilteredDataset,
+ stateWidthTsAndNameFilter.datasets.smoothie
+ );
t.end();
});
@@ -2611,7 +2626,6 @@ test('#visStateReducer -> SPLIT_MAP: TOGGLE_SPLIT_MAP', t => {
});
test('#visStateReducer -> SPLIT_MAP: HIDE LAYER', t => {
-
const oldState = {
splitMaps: [
{
@@ -2648,7 +2662,522 @@ test('#visStateReducer -> SPLIT_MAP: HIDE LAYER', t => {
]
};
- t.deepEqual(newState.splitMaps, expectedState.splitMaps, 'should hide layer B in split map');
+ t.deepEqual(
+ newState.splitMaps,
+ expectedState.splitMaps,
+ 'should hide layer B in split map'
+ );
+
+ t.end();
+});
+
+test('#visStateReducer -> LAYER_COLOR_UI_CHANGE. show dropdown', t => {
+ const initialState = CloneDeep(StateWFilesFiltersLayerColor.visState);
+ const pointLayer = initialState.layers[0];
+
+ const oldColorRange = CloneDeep(pointLayer.config.visConfig.colorRange);
+ // show dropdown
+ const nextState = reducer(
+ initialState,
+ VisStateActions.layerColorUIChange(pointLayer, 'color', {
+ showDropdown: 0
+ })
+ );
+
+ const expectedColorUI = {
+ color: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0
+ },
+ colorRange: DEFAULT_COLOR_UI
+ };
+
+ t.deepEqual(
+ nextState.layers[0].config.colorUI,
+ expectedColorUI,
+ 'should update colorUI.showDropdown'
+ );
+ t.deepEqual(
+ nextState.layers[0].config.visConfig.colorRange,
+ oldColorRange,
+ 'should not change colorRange'
+ );
+
+ const nextState1 = reducer(
+ nextState,
+ VisStateActions.layerColorUIChange(pointLayer, 'color', {
+ showDropdown: false
+ })
+ );
+ t.deepEqual(
+ nextState1.layers[0].config.colorUI,
+ {color: DEFAULT_COLOR_UI, colorRange: DEFAULT_COLOR_UI},
+ 'should update colorUI.showDropdown'
+ );
+
+ const nextState2 = reducer(
+ nextState1,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ showDropdown: 0
+ })
+ );
+
+ const expectedColorUI2 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: false
+ }
+ }
+ };
+ t.deepEqual(
+ nextState2.layers[0].config.colorUI,
+ expectedColorUI2,
+ 'should update colorUI.showDropdown, set colorRangeConfig step and reversed'
+ );
+
+ t.end();
+});
+
+// eslint-disable-next-line max-statements
+test('#visStateReducer -> LAYER_COLOR_UI_CHANGE. colorRangeConfig.step', t => {
+ const initialState = CloneDeep(StateWFilesFiltersLayerColor.visState);
+ const pointLayer = initialState.layers[0];
+
+ const oldColorRange = CloneDeep(pointLayer.config.visConfig.colorRange);
+
+ t.equal(
+ oldColorRange.colors.length,
+ 4,
+ 'old color range should have 4 colors'
+ );
+ // show dropdown
+ const prepareState = reducer(
+ initialState,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ showDropdown: 0
+ })
+ );
+
+ const {colorRangeConfig} = prepareState.layers[0].config.colorUI.colorRange;
+
+ // set color range steps
+ const nextState = reducer(
+ prepareState,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ colorRangeConfig: {steps: 6}
+ })
+ );
+
+ const expectedColorUI = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 6,
+ reversed: false,
+ custom: false
+ }
+ }
+ };
+
+ const expectedColorRange = {
+ name: 'Uber Viz Sequential 4',
+ type: 'sequential',
+ category: 'Uber',
+ colors: ['#E6FAFA', '#C1E5E6', '#9DD0D4', '#75BBC1', '#4BA7AF', '#00939C']
+ };
+ t.deepEqual(
+ nextState.layers[0].config.colorUI,
+ expectedColorUI,
+ 'should update colorUI.colorRangeConfig.steps'
+ );
+ t.deepEqual(
+ nextState.layers[0].config.visConfig.colorRange,
+ expectedColorRange,
+ 'should update visConfig.colorRange based on step'
+ );
+
+ // set color range reverse
+ const nextState2 = reducer(
+ nextState,
+ VisStateActions.layerColorUIChange(nextState.layers[0], 'colorRange', {
+ colorRangeConfig: {reversed: true}
+ })
+ );
+
+ const expectedColorUI2 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 6,
+ reversed: true,
+ custom: false
+ }
+ }
+ };
+
+ const expectedColorRange2 = {
+ name: 'Uber Viz Sequential 4',
+ type: 'sequential',
+ category: 'Uber',
+ colors: ['#00939C', '#4BA7AF', '#75BBC1', '#9DD0D4', '#C1E5E6', '#E6FAFA'],
+ reversed: true
+ };
+
+ t.deepEqual(
+ nextState2.layers[0].config.colorUI,
+ expectedColorUI2,
+ 'should update colorUI.colorRangeConfig.reversed'
+ );
+ t.deepEqual(
+ nextState2.layers[0].config.visConfig.colorRange,
+ expectedColorRange2,
+ 'should update visConfig.colorRange based on reversed'
+ );
+
+ // update step when reversed is true
+ const nextState3 = reducer(
+ nextState,
+ VisStateActions.layerColorUIChange(nextState2.layers[0], 'colorRange', {
+ colorRangeConfig: {steps: 8}
+ })
+ );
+
+ const expectedColorUI3 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 8,
+ reversed: true,
+ custom: false
+ }
+ }
+ };
+
+ const expectedColorRange3 = {
+ name: 'Uber Viz Sequential 6',
+ type: 'sequential',
+ category: 'Uber',
+ colors: [
+ '#E6FAFA',
+ '#C1E5E6',
+ '#9DD0D4',
+ '#75BBC1',
+ '#4BA7AF',
+ '#00939C',
+ '#108188',
+ '#0E7077'
+ ].reverse(),
+ reversed: true
+ };
+
+ t.deepEqual(
+ nextState3.layers[0].config.colorUI,
+ expectedColorUI3,
+ 'should update colorUI.colorRangeConfig.steps'
+ );
+ t.deepEqual(
+ nextState3.layers[0].config.visConfig.colorRange,
+ expectedColorRange3,
+ 'should update visConfig.colorRange based on match and set reversed'
+ );
+
+ // set to a step that has no match
+ const nextState4 = reducer(
+ nextState,
+ VisStateActions.layerColorUIChange(nextState3.layers[0], 'colorRange', {
+ colorRangeConfig: {steps: 11}
+ })
+ );
+
+ const expectedColorUI4 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 11,
+ reversed: true,
+ custom: false
+ }
+ }
+ };
+ t.deepEqual(
+ nextState4.layers[0].config.colorUI,
+ expectedColorUI4,
+ 'should update colorUI.colorRangeConfig to step 11'
+ );
+ t.deepEqual(
+ nextState4.layers[0].config.visConfig.colorRange,
+ expectedColorRange3,
+ 'should note update visConfig.colorRange when no match'
+ );
+
+ t.end();
+});
+
+test('#visStateReducer -> LAYER_COLOR_UI_CHANGE. custom Palette', t => {
+ const initialState = CloneDeep(StateWFilesFiltersLayerColor.visState);
+ const pointLayer = initialState.layers[0];
+
+ const oldColorRange = CloneDeep(pointLayer.config.visConfig.colorRange);
+ // show dropdown
+ const prepareState = reducer(
+ initialState,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ showDropdown: 0
+ })
+ );
+
+ // enable custom
+ const nextState = reducer(
+ prepareState,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ colorRangeConfig: {custom: true}
+ })
+ );
+
+ const expectedColorUI = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: oldColorRange.colors
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: true
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState.layers[0].config.colorUI,
+ expectedColorUI,
+ 'should update colorUI.customPalette with current colorRange colors'
+ );
+
+ const nextState2 = reducer(
+ prepareState,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ customPalette: {colors: ['aaa', 'bbb', 'ccc']}
+ })
+ );
+
+ const expectedColorUI2 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ ...DEFAULT_COLOR_UI,
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['aaa', 'bbb', 'ccc']
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: true
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState2.layers[0].config.colorUI,
+ expectedColorUI2,
+ 'should update colorUI.customPalette colors'
+ );
+
+ // show sketcher
+ const nextState3 = reducer(
+ nextState2,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ showSketcher: 1
+ })
+ );
+
+ const expectedColorUI3 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ showSketcher: 1,
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['aaa', 'bbb', 'ccc']
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: true
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState3.layers[0].config.colorUI,
+ expectedColorUI3,
+ 'should set showSketcher: 1'
+ );
+
+ // edit color
+ const nextState4 = reducer(
+ nextState3,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ customPalette: {
+ colors: ['bbb', 'ccc', 'aaa']
+ }
+ })
+ );
+
+ const expectedColorUI4 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ showSketcher: 1,
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['bbb', 'ccc', 'aaa']
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: true
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState4.layers[0].config.colorUI,
+ expectedColorUI4,
+ 'should update colorUI.customPalette colors'
+ );
+
+ // apply color
+ const nextState5 = reducer(
+ nextState4,
+ VisStateActions.layerVisConfigChange(nextState4.layers[0], {
+ colorRange: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['bbb', 'ccc', 'aaa']
+ }
+ })
+ );
+
+ // close custom palette
+ const nextState6 = reducer(
+ nextState5,
+ VisStateActions.layerColorUIChange(nextState5.layers[0], 'colorRange', {
+ colorRangeConfig: {
+ custom: false
+ }
+ })
+ );
+
+ const expectedColorUI6 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ showSketcher: 1,
+ // keep the customPalette
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['bbb', 'ccc', 'aaa']
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: false
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState6.layers[0].config.colorUI,
+ expectedColorUI6,
+ 'should set colorRangeConfig.custom false'
+ );
+
+ t.deepEqual(
+ nextState6.layers[0].config.visConfig.colorRange,
+ {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['bbb', 'ccc', 'aaa']
+ },
+ 'should set visConfig.colorRange'
+ );
+
+ // open it again
+ const nextState7 = reducer(
+ nextState6,
+ VisStateActions.layerColorUIChange(pointLayer, 'colorRange', {
+ colorRangeConfig: {
+ custom: true
+ }
+ })
+ );
+
+ const expectedColorUI7 = {
+ color: DEFAULT_COLOR_UI,
+ colorRange: {
+ showSketcher: 1,
+ // keep the customPalette
+ customPalette: {
+ name: 'Custom Palette',
+ type: 'custom',
+ category: 'Custom',
+ colors: ['bbb', 'ccc', 'aaa']
+ },
+ showDropdown: 0,
+ colorRangeConfig: {
+ type: 'all',
+ steps: 4,
+ reversed: false,
+ custom: true
+ }
+ }
+ };
+
+ t.deepEqual(
+ nextState7.layers[0].config.colorUI,
+ expectedColorUI7,
+ 'should set colorRangeConfig.custom true'
+ );
t.end();
});
diff --git a/test/setup-browser-env.js b/test/setup-browser-env.js
index 4d3af1391..b02c5bb20 100644
--- a/test/setup-browser-env.js
+++ b/test/setup-browser-env.js
@@ -19,15 +19,57 @@
// THE SOFTWARE.
/* setup.js */
-import {JSDOM} from 'jsdom';
+import {JSDOM, VirtualConsole} from 'jsdom';
import global from 'global';
+const virtualConsole = new VirtualConsole();
+virtualConsole.sendTo(console);
+
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
// JSDom 11.12 causes SecurityError: localStorage is not available for opaque origins
// https://github.com/jsdom/jsdom/issues/2304
- url: 'http://localhost'
+ url: 'http://localhost',
+ virtualConsole
});
const {window} = dom;
+mockCanvas(window);
+
+const nop = () => {};
+
+function mockCanvas(globalWindow) {
+ globalWindow.HTMLCanvasElement.prototype.getContext = function mockGetContext() {
+ return {
+ fillRect: nop,
+ clearRect: nop,
+ getImageData: (x, y, w, h) => ({
+ data: new Array(w * h * 4)
+ }),
+ putImageData: nop,
+ createImageData: () => [],
+ setTransform: nop,
+ drawImage: nop,
+ save: nop,
+ fillText: nop,
+ restore: nop,
+ beginPath: nop,
+ moveTo: nop,
+ lineTo: nop,
+ closePath: nop,
+ stroke: nop,
+ translate: nop,
+ scale: nop,
+ rotate: nop,
+ arc: nop,
+ fill: nop,
+ measureText: () => ({width: 0}),
+ transform: nop,
+ rect: nop,
+ clip: nop
+ };
+ };
+
+ globalWindow.HTMLCanvasElement.prototype.toDataURL = () => '';
+}
global.window = window;
global.document = window.document;
diff --git a/website/src/components/common/styles.js b/website/src/components/common/styles.js
index afb964732..a1d20da54 100644
--- a/website/src/components/common/styles.js
+++ b/website/src/components/common/styles.js
@@ -116,6 +116,7 @@ export const Logo = styled.img`
`};
`;
+/* eslint-disable react/display-name */
export const HeroImage = React.forwardRef((props, ref) => (
<BackgroundImage {...props} ref={ref} src={cdnUrl('hero/kepler.gl-background.png')}/>
));
@@ -123,4 +124,4 @@ export const HeroImage = React.forwardRef((props, ref) => (
export const LogoImage = React.forwardRef((props, ref) => (
<Logo {...props} src={cdnUrl('icons/kepler.gl-logo.png')} />
));
-
+/* eslint-enable react/display-name */
diff --git a/yarn.lock b/yarn.lock
index 527f53388..cb241d51d 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -971,6 +971,10 @@
version "0.7.4"
resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.7.4.tgz#a87b4b04e5ae14a88d48ebef15015f6b7d1f5677"
+"@icons/material@^0.2.4":
+ version "0.2.4"
+ resolved "https://registry.yarnpkg.com/@icons/material/-/material-0.2.4.tgz#e90c9f71768b3736e76d7dd6783fc6c2afa88bc8"
+
"@loaders.gl/[email protected]", "@loaders.gl/core@^1.0.3":
version "1.2.2"
resolved "https://registry.yarnpkg.com/@loaders.gl/core/-/core-1.2.2.tgz#2c87b09e2e2a0d07c029d88d637757b85ce3dd38"
@@ -1528,10 +1532,6 @@ array-includes@^3.0.3:
define-properties "^1.1.2"
es-abstract "^1.7.0"
-array-move@^2.0.0:
- version "2.1.0"
- resolved "https://registry.yarnpkg.com/array-move/-/array-move-2.1.0.tgz#b4e9fc8d6a580bc97dcad408e0539c61b4b7ed7e"
-
array-union@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39"
@@ -5729,7 +5729,7 @@ lodash@^3.6.0:
version "3.10.1"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6"
-lodash@^4.15.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.4, lodash@^4.2.1, lodash@^4.6.1:
+lodash@^4.0.1, lodash@^4.15.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.4, lodash@^4.2.1, lodash@^4.6.1:
version "4.17.15"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548"
@@ -5847,6 +5847,10 @@ markdown-table@^1.1.0:
version "1.1.3"
resolved "https://registry.yarnpkg.com/markdown-table/-/markdown-table-1.1.3.tgz#9fcb69bcfdb8717bfd0398c6ec2d93036ef8de60"
+material-colors@^1.2.1:
+ version "1.2.6"
+ resolved "https://registry.yarnpkg.com/material-colors/-/material-colors-1.2.6.tgz#6d1958871126992ceecc72f4bcc4d8f010865f46"
+
math-random@^1.0.1:
version "1.0.4"
resolved "https://registry.yarnpkg.com/math-random/-/math-random-1.0.4.tgz#5dd6943c938548267016d4e34f057583080c514c"
@@ -7430,6 +7434,17 @@ re-emitter@^1.0.0:
version "1.1.4"
resolved "https://registry.yarnpkg.com/re-emitter/-/re-emitter-1.1.4.tgz#15bdefca3d47e05d6442838fd26759c8a4eaa236"
+react-color@^2.17.3:
+ version "2.17.3"
+ resolved "https://registry.yarnpkg.com/react-color/-/react-color-2.17.3.tgz#b8556d744f95193468c7061d2aa19180118d4a48"
+ dependencies:
+ "@icons/material" "^0.2.4"
+ lodash "^4.17.11"
+ material-colors "^1.2.1"
+ prop-types "^15.5.10"
+ reactcss "^1.2.0"
+ tinycolor2 "^1.4.1"
+
react-deep-force-update@^2.1.1:
version "2.1.3"
resolved "https://registry.yarnpkg.com/react-deep-force-update/-/react-deep-force-update-2.1.3.tgz#740612322e617bcced38f61794a4af75dc3d98e7"
@@ -7627,6 +7642,12 @@ react@^16.8.4:
object-assign "^4.1.1"
prop-types "^15.6.2"
+reactcss@^1.2.0:
+ version "1.2.3"
+ resolved "https://registry.yarnpkg.com/reactcss/-/reactcss-1.2.3.tgz#c00013875e557b1cf0dfd9a368a1c3dab3b548dd"
+ dependencies:
+ lodash "^4.0.1"
+
read-all-stream@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/read-all-stream/-/read-all-stream-3.1.0.tgz#35c3e177f2078ef789ee4bfafa4373074eaef4fa"
@@ -9076,6 +9097,10 @@ tiny-lr@^1.1.0:
object-assign "^4.1.0"
qs "^6.4.0"
+tinycolor2@^1.4.1:
+ version "1.4.1"
+ resolved "https://registry.yarnpkg.com/tinycolor2/-/tinycolor2-1.4.1.tgz#f4fad333447bc0b07d4dc8e9209d8f39a8ac77e8"
+
tinyqueue@^2.0.0:
version "2.0.3"
resolved "https://registry.yarnpkg.com/tinyqueue/-/tinyqueue-2.0.3.tgz#64d8492ebf39e7801d7bd34062e29b45b2035f08"