Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
Added: - map control, legend and layer selector - mapbox utils - heatmap - redcers mapstate and composers
Giuseppe Macri9aa7302d90a3
diff --git a/package.json b/package.jsonindex e1b9f8ae4..8a48754f7 100644--- a/package.json+++ b/package.json@@ -15,7 +15,7 @@"build-static": "cp -r ./src/static/* dist && cp index.html dist","build-script": "webpack -p --env.prod","build": "npm run build-clean && npm run build-static && npm run build-script",- "web": "(cd website && yarn start)",+ "web": "(cd website && yarn --ignore-engines && yarn start)","deploy": "(cd website && yarn build && git checkout gh-pages && cp dist/* .. && git add .. && git commit -m 'Update website' && git push origin gh-pages && git checkout master)"},"dependencies": {diff --git a/src/components/common/map-layer-selector.js b/src/components/common/map-layer-selector.jsnew file mode 100644index 000000000..46d69345e--- /dev/null+++ b/src/components/common/map-layer-selector.js@@ -0,0 +1,62 @@+// Copyright (c) 2018 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 from 'react';+import PropTypes from 'prop-types';+import styled from 'styled-components';+import Switch from 'components/common/switch';+import {generateHashId} from '../../utils/utils';++const propTypes = {+ // Required+ layers: PropTypes.array.isRequired,+ onMapToggleLayer: PropTypes.func.isRequired+};++const MapLayerSelect = styled.div`+ padding: 12px;++ .map-layer-selector__item {+ margin: 12px 0;+ }+`;++const MapLayerSelector = ({layers, onMapToggleLayer}) => (+ <MapLayerSelect className="map-layer-selector">+ {layers.map((layer, index) => (+ <div key={layer.id} className="map-layer-selector__item">+ <Switch+ checked={layer.isVisible}+ id={`${layer.id}-toggle-${generateHashId(4)}`}+ label={layer.name}+ onChange={e => {+ e.preventDefault();+ onMapToggleLayer(layer.id);+ }}+ />+ </div>+ ))}+ </MapLayerSelect>+);++MapLayerSelector.displayName = 'LayerSelector';+MapLayerSelector.propTypes = propTypes;++export default MapLayerSelector;diff --git a/src/components/map/map-control.js b/src/components/map/map-control.jsnew file mode 100644index 000000000..12c66ef95--- /dev/null+++ b/src/components/map/map-control.js@@ -0,0 +1,360 @@+// Copyright (c) 2018 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 {createSelector} from 'reselect';+import styled from 'styled-components';++import {Tooltip, IconRoundSmall} from 'components/common/styled-components';+import MapLayerSelector from 'components/common/map-layer-selector';+import MapLegend from './map-legend';+import {+ Close,+ Split,+ Legend,+ Cube3d,+ Delete,+ Layers+} from 'components/common/icons';++const StyledMapControl = styled.div`+ right: 0;+ width: ${props => props.theme.mapControl.width}px;+ padding: ${props => props.theme.mapControl.padding}px;+ z-index: 1;+ top: ${props => props.top}px;+ position: absolute;+`;++const StyledMapControlAction = styled.div`+ padding: 4px 0;+ display: flex;+ justify-content: flex-end;+`;++const StyledMapControlButton = styled.div`+ align-items: center;+ background-color: ${props =>+ props.active+ ? props.theme.secondaryBtnActBgd+ : props.theme.secondaryBtnBgd};+ border-radius: 18px;+ border: 0;+ box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.16);+ color: ${props =>+ props.active+ ? props.theme.secondaryBtnActColor+ : props.theme.secondaryBtnColor};+ cursor: pointer;+ display: flex;+ height: 36px;+ justify-content: center;+ margin: 0;+ outline: none;+ padding: 0;+ transition: ${props => props.theme.transition};+ width: 36px;++ :focus {+ outline: none;+ }++ :hover {+ cursor: pointer;+ background-color: ${props => props.theme.secondaryBtnActBgd};+ color: ${props => props.theme.secondaryBtnActColor};+ }+`;++const StyledMapControlPanel = styled.div`+ background-color: ${props => props.theme.mapPanelBackgroundColor};+ flex-grow: 1;+ z-index: 1;+ p {+ margin-bottom: 0;+ }+`;++const StyledMapControlPanelContent = styled.div`+ ${props => props.theme.dropdownScrollBar} max-height: 500px;+ min-height: 100px;+ overflow: overlay;+`;++const StyledMapControlPanelHeader = styled.div`+ display: flex;+ justify-content: space-between;+ background-color: ${props => props.theme.mapPanelHeaderBackgroundColor};+ height: 32px;+ padding: 6px 12px;+ font-size: 11px;+ color: ${props => props.theme.secondaryBtnColor};++ button {+ width: 18px;+ height: 18px;+ }+`;++const propTypes = {+ dragRotate: PropTypes.bool.isRequired,+ isSplit: PropTypes.bool.isRequired,+ onToggleFullScreen: PropTypes.func.isRequired,+ onTogglePerspective: PropTypes.func.isRequired,+ onToggleSplitMap: PropTypes.func.isRequired,+ top: PropTypes.number.isRequired+};++const defaultProps = {+ isSplit: false,+ top: 0+};++/**+ * Generates all layers available for the current map+ * TODO: this may be moved into map-container or map-control or even at the reducer level+ * @param layers+ * @param mapLayers+ * @returns {[id, label, isVisible]}+ */+const layerSelector = (layers, mapLayers) => {+ const availableItems = Object.keys(layers).reduce(+ (availableLayers, currentLayerId) => {+ // is available ? if yes add to available list+ const currentLayer = layers[currentLayerId];+ // if maplayers exists we need to make sure currentlayer+ // is contained in mapLayers in order to add onto availableLayers+ // otherwise we add all layers++ const layerConfig = mapLayers+ ? mapLayers[currentLayer.id]+ : currentLayer.config;++ const mustBeAdded =+ mapLayers && mapLayers[currentLayer.id]+ ? mapLayers[currentLayer.id].isAvailable+ : layerConfig.isVisible;++ return mustBeAdded+ ? [+ ...availableLayers,+ {+ id: currentLayer.id,+ name: currentLayer.config.label,+ isVisible:+ mapLayers && mapLayers[currentLayer.id]+ ? mapLayers[currentLayer.id].isVisible+ : layerConfig.isVisible,+ layer: currentLayer+ }+ ]+ : availableLayers;+ },+ []+ );++ return availableItems;+};++export class MapControl extends Component {+ constructor(props) {+ super(props);+ this.state = {+ areLayersVisible: false,+ isLegendVisible: false+ };+ }+ layerSelector = state => state.layers;+ mapLayersSelector = state => state.mapLayers;++ initialDataSelector = createSelector(+ this.layerSelector,+ this.mapLayersSelector,+ layerSelector+ );++ // if one panel is already open and user tries to open a new one well the previous one will be closed+ _toggleMenuPanel(panelId) {+ this.setState({+ areLayersVisible: false,+ isLegendVisible: false,+ [panelId]: !this.state[panelId]+ });+ }++ _renderLayerSelector(items) {+ const {onMapToggleLayer} = this.props;+ const {areLayersVisible} = this.state;++ return !areLayersVisible ? (+ <StyledMapControlButton+ key={1}+ onClick={e => {+ e.preventDefault();+ this._toggleMenuPanel('areLayersVisible');+ }}+ className="map-control-button toggle-layer"+ data-tip+ data-for="toggle-layer"+ >+ <Layers height="22px" />+ <MapLegendTooltip+ id="toggle-layer"+ message={areLayersVisible ? 'Hide layer panel' : 'Show layer panel'}+ />+ </StyledMapControlButton>+ ) : (+ <MapControlPanel+ header={'Visible layers'}+ onClick={() => this._toggleMenuPanel('areLayersVisible')}+ >+ <MapLayerSelector layers={items} onMapToggleLayer={onMapToggleLayer} />+ </MapControlPanel>+ );+ }++ _renderLegend(items) {+ const {isLegendVisible} = this.state;+ return !isLegendVisible ? (+ <StyledMapControlButton+ key={2}+ data-tip+ data-for="show-legend"+ className="map-control-button show-legend"+ onClick={e => {+ e.preventDefault();+ this._toggleMenuPanel('isLegendVisible');+ }}+ >+ <Legend height="22px" />+ <MapLegendTooltip id="show-legend" message={'show legend'} />+ </StyledMapControlButton>+ ) : (+ <MapControlPanel+ header={'Layer Legend'}+ onClick={() => this._toggleMenuPanel('isLegendVisible')}+ >+ <MapLegend+ layers={items.filter(item => item.isVisible).map(item => item.layer)}+ />+ </MapControlPanel>+ );+ }++ render() {+ const items = this.initialDataSelector(this.props);++ if (!items) {+ return null;+ }++ const {+ dragRotate,+ isSplit,+ mapIndex,+ onTogglePerspective,+ onToggleSplitMap+ } = this.props;++ return (+ <StyledMapControl className="map-control">+ {/* Split Map */}+ <ActionPanel key={0}>+ <StyledMapControlButton+ active={isSplit}+ onClick={e => {+ e.preventDefault();+ onToggleSplitMap(isSplit ? mapIndex : undefined);+ }}+ key={`split-${isSplit}`}+ className="map-control-button split-map"+ data-tip+ data-for="action-toggle"+ >+ {isSplit ?+ <Delete height={'18px'} /> :+ <Split height={'18px'} />+ }+ <MapLegendTooltip+ id="action-toggle"+ message={+ isSplit ? 'Close current panel' : 'Switch to dual map view'+ }+ />+ </StyledMapControlButton>+ </ActionPanel>+ {/* Map Layers */}+ {isSplit && (+ <ActionPanel key={1}>{this._renderLayerSelector(items)}</ActionPanel>+ )}+ {/* 3D Map */}+ <ActionPanel key={2}>+ <StyledMapControlButton+ onClick={e => {+ e.preventDefault();+ onTogglePerspective();+ }}+ active={dragRotate}+ data-tip+ data-for="action-3d"+ >+ <Cube3d height={'22px'} />+ {/* No icon since we are injecting through css .threeD-map class*/}+ <MapLegendTooltip+ id="action-3d"+ message={dragRotate ? 'Disable 3D Map' : '3D Map'}+ />+ </StyledMapControlButton>+ </ActionPanel>+ {/* Map Legend */}+ <ActionPanel key={3}>{this._renderLegend(items)}</ActionPanel>+ </StyledMapControl>+ );+ }+}++const MapControlPanel = ({children, header, onClick}) => (+ <StyledMapControlPanel>+ <StyledMapControlPanelHeader style={{position: 'relative'}}>+ <span style={{verticalAlign: 'middle'}}>{header}</span>+ <IconRoundSmall>+ <Close height="16px" onClick={onClick} />+ </IconRoundSmall>+ </StyledMapControlPanelHeader>+ <StyledMapControlPanelContent>{children}</StyledMapControlPanelContent>+ </StyledMapControlPanel>+);++const ActionPanel = ({children}) => (+ <StyledMapControlAction>{children}</StyledMapControlAction>+);++const MapLegendTooltip = ({id, message}) => (+ <Tooltip id={id} place="left" effect="solid">+ <span>{message}</span>+ </Tooltip>+);++MapControl.propTypes = propTypes;+MapControl.defaultProps = defaultProps;++const MapControlFactory = () => MapControl;+export default MapControlFactory;diff --git a/src/components/map/map-legend.js b/src/components/map/map-legend.jsnew file mode 100644index 000000000..eb1352f8b--- /dev/null+++ b/src/components/map/map-legend.js@@ -0,0 +1,169 @@+// Copyright (c) 2018 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 from 'react';+import PropTypes from 'prop-types';+import styled from 'styled-components';+import {rgb} from 'd3-color';+import ColorLegend from 'components/common/color-legend';+import {DIMENSIONS} from 'constants/default-settings';+import {capitalizeFirstLetter} from 'utils/utils';++const StyledMapControlLegend = styled.div`+ padding: 10px ${props => props.theme.mapControl.padding}px;+ font-size: 11px;+ border-bottom-color: ${props => props.theme.panelBorderColor};+ border-bottom-style: solid;+ border-bottom-width: ${props => (props.last ? 0 : '1px')};++ .legend--layer_name {+ font-size: 12px;+ color: ${props => props.theme.textColorHl};+ font-weight: 500;+ }+ .legend--layer_type {+ color: ${props => props.theme.subtextColor};+ font-weight: 500;+ font-size: 11px;+ }++ .legend--layer_by {+ color: ${props => props.theme.subtextColor};+ }++ .legend--layer_color_field {+ color: ${props => props.theme.textColor};+ font-weight: 500;+ }++ .legend--layer_color-legend {+ margin-top: 6px;+ }+`;++const VisualChannelMetric = ({name}) => (+ <div>+ <span className="legend--layer_by">by </span>+ <span className="legend--layer_color_field">{name}</span>+ </div>+);++const LayerSize = ({label, name}) => (+ <div className="legend--layer_size-schema">+ <p>+ <span className="legend--layer_by">{label}</span>+ </p>+ <VisualChannelMetric name={name} />+ </div>+);++const propTypes = {+ layers: PropTypes.array+};++const MapLegend = ({layers}) => (+ <div>+ {layers.map((layer, index) => {+ const enableColorBy = layer.config.colorField+ ? layer.config.colorField.name+ : layer.visualChannels.color.defaultMeasure;++ if (!layer.isValidToSave()) {+ return null;+ }++ return (+ <StyledMapControlLegend+ className="legend--layer"+ last={index === layers.length - 1}+ key={index}+ >+ <div className="legend--layer_name">{layer.config.label}</div>+ <div className="legend--layer_type">{`${capitalizeFirstLetter(+ layer.name+ )} color`}</div>+ <div className="legend--layer_color-schema">+ <div>+ {enableColorBy ? (+ <VisualChannelMetric name={enableColorBy} />+ ) : null}+ <div className="legend--layer_color-legend">+ <ColorLegend+ scaleType={+ enableColorBy ? layer.config.colorScale : 'ordinal'+ }+ displayLabel={enableColorBy}+ domain={enableColorBy ? layer.config.colorDomain : ['']}+ fieldType={+ enableColorBy+ ? (layer.config.colorField &&+ layer.config.colorField.type) ||+ 'real'+ : null+ }+ range={+ enableColorBy+ ? layer.config.visConfig.colorRange.colors+ : [rgb(...layer.config.color).toString()]+ }+ width={+ DIMENSIONS.mapControlWidth -+ 2 * DIMENSIONS.mapControl.padding+ }+ />+ </div>+ </div>+ </div>+ {Object.keys(layer.visualChannels)+ .filter(k => k !== 'color')+ .map(key => {+ const matchCondition =+ !layer.visualChannels[key].condition ||+ layer.visualChannels[key].condition(layer.config);+ const enabled =+ layer.config[layer.visualChannels[key].field] ||+ layer.visualChannels[key].defaultMeasure;+ if (matchCondition && enabled) {+ return (+ <LayerSize+ key={key}+ label={+ layer.visConfigSettings[layer.visualChannels[key].range]+ .label+ }+ name={+ layer.config[layer.visualChannels[key].field]+ ? layer.config[layer.visualChannels[key].field].name+ : layer.visualChannels[key].defaultMeasure+ }+ />+ );+ }+ return null;+ })}+ </StyledMapControlLegend>+ );+ })}+ </div>+);++MapLegend.propTypes = propTypes;++export default MapLegend;diff --git a/src/layers/mapbox-utils.js b/src/layers/mapbox-utils.jsnew file mode 100644index 000000000..846a31b9e--- /dev/null+++ b/src/layers/mapbox-utils.js@@ -0,0 +1,161 @@+// Copyright (c) 2018 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 {OVERLAY_TYPE} from './base-layer';++/**+ * This function will convert layers to mapbox layers+ * @param layers the layers to be converted+ * @param layerData extra layer information+ * @param layerOrder the order by which we should convert layers+ * @returns {*}+ */+export function generateMapboxLayers(layers = [], layerData = [], layerOrder = []) {+ if (layerData.length > 0) {+ return layerOrder.slice()+ .reverse()+ .reduce((overlays, idx) => {+ const layer = layers[idx];++ return layer.overlayType !== OVERLAY_TYPE.mapboxgl ?+ overlays+ : [+ ...overlays,+ {+ id: layer.id,+ data: layerData[idx].data,+ config: layerData[idx].config,+ datasetId: layer.config.dataId+ }+ ]+ }, []);+ }++ return [];+};++/**+ * Update mapbox layers on the given map+ * @param map+ * @param newLayers Array of new mapbox layers to be displayed+ * @param oldLayers Map of the old layers to be compare with the current ones to detect deleted layers+ * {layerId: datasetId}+ * @param mapLayers carries information about split map view+ */+export function updateMapboxLayers(map, newLayers = [], oldLayers = null, mapLayers = null, opt = {force: true}) {+ // delete non existing layers+ if (oldLayers) {+ const oldLayersKeys = Object.keys(oldLayers);+ if (newLayers.length === 0 && oldLayersKeys.length > 0) {+ oldLayersKeys.forEach(layerId => map.removeLayer(layerId));+ } else {+ // remove layers+ const currentLayersIds = newLayers.reduce((final, layer) => ({+ ...final,+ [layer.id]: true+ }), {});++ const layersToDelete = oldLayersKeys.reduce((final, layerId) => {+ // if layer doesn't exists anymore+ if (!currentLayersIds[layerId]) {+ return {+ ...final,+ [layerId]: oldLayers[layerId]+ };+ }+ return final;+ }, []);+ Object.keys(layersToDelete).forEach(layerId => map.removeLayer(layerId));+ }+ }++ // insert or update newlayer+ newLayers.forEach(overlay => {+ const {id: layerId, config, data, datasetId} = overlay;+ if (!data && !config) {+ return;+ }+ const isAvailableAndVisible =+ !(mapLayers && mapLayers[layerId]) || mapLayers[layerId].isVisible;+ // checking if source already exists++ if (data && isAvailableAndVisible) {+ const source = map.getSource(datasetId);+ if (!source) {+ map.addSource(datasetId, {+ type: 'geojson',+ data+ });+ }+ else {+ source.setData(data);+ }+ }++ const oldConfig = oldLayers[layerId];+ const mapboxLayer = map.getLayer(layerId);+ // compare with previous configs++ if (!oldConfig || oldConfig !== config || !mapboxLayer || opt.force) {+ // check if layer already is set+ // remove it if exists+ if (mapboxLayer) {+ map.removeLayer(layerId);+ }+ // add if visible and available+ if (isAvailableAndVisible) {+ map.addLayer(config);+ }+ }+ });+ // TODO: think about removing sources+};++/**+ *+ * @param points+ * @param columns {+ * lat: {fieldIdx},+ * lng: {fieldIdx},+ * alt: {fieldIdx}+ * }+ * @param properties [{label: {fieldIdx}]+ * @returns {{type: string, properties: {}, features: {type: string, properties: {}, geometry: {type: string, coordinates: *[]}}[]}}+ */+export function geojsonFromPoints(allData = [], filteredIndex = [], columns = {}, properties = []) {+ return {+ type: 'FeatureCollection',+ features: filteredIndex.map(index => allData[index]).map(point => ({+ type: 'Feature',+ properties: properties.reduce((final, property) => ({+ ...final,+ [property.name]: point[property.tableFieldIndex - 1]+ }), {}),+ geometry: {+ type: 'Point',+ coordinates: [+ columns.lng ? point[columns.lng.fieldIdx] : null, // lng+ columns.lat ? point[columns.lat.fieldIdx] : null, // lat+ columns.altitude ? point[columns.altitude.fieldIdx] : 0 // altitude+ ]+ }+ }))+ };+}diff --git a/src/layers/mapboxgl-layer.js b/src/layers/mapboxgl-layer.jsnew file mode 100644index 000000000..295b37c9e--- /dev/null+++ b/src/layers/mapboxgl-layer.js@@ -0,0 +1,85 @@+// Copyright (c) 2018 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 {CHANNEL_SCALES} from 'constants/default-settings';+import Layer, {OVERLAY_TYPE} from './base-layer';++export const mapboxRequiredColumns = ['lat', 'lng'];++class MapboxLayerGL extends Layer {++ get overlayType() {+ return OVERLAY_TYPE.mapboxgl;+ }++ get type() {+ return null;+ }++ get isAggregated() {+ return true;+ }++ get requiredLayerColumns() {+ return mapboxRequiredColumns;+ }++ get columnPairs() {+ return this.defaultPointColumnPairs;+ }++ get noneLayerDataAffectingProps() {+ return [];+ }++ get visualChannels() {+ return {+ color: {+ property: 'color',+ field: 'colorField',+ scale: 'colorScale',+ domain: 'colorDomain',+ range: 'colorRange',+ key: 'color',+ channelScaleType: CHANNEL_SCALES.colorAggr,+ defaultMeasure: 'Point Count'+ },+ weight: {+ property: 'weight',+ field: 'weightField',+ scale: 'weightScale',+ domain: 'weightDomain',+ range: 'weightRange',+ key: 'weight',+ channelScaleType: CHANNEL_SCALES.sizeAggr,+ defaultMeasure: 'Weight'+ }+ };+ }++ // this layer is rendered at mapbox level+ // todo: maybe need to find a better solution for this one+ shouldRenderLayer() {+ return false;+ }++}++export default MapboxLayerGL;diff --git a/src/reducers/composers.js b/src/reducers/composers.jsnew file mode 100644index 000000000..1e73519db--- /dev/null+++ b/src/reducers/composers.js@@ -0,0 +1,107 @@+// Copyright (c) 2018 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 ActionTypes from 'constants/action-types';+import {fitBoundsUpdater} from './map-state-updaters';+import {toggleModalUpdater} from './ui-state-updaters';+import {updateVisDataUpdater} from './vis-state-updaters';+import {receiveMapConfigUpdater as stateMapConfigUpdater} from './map-state-updaters';+import {receiveMapConfigUpdater as styleMapConfigUpdater} from './map-style-updaters';+import {findMapBounds} from 'utils/data-utils';+// compose action to apply result multiple reducers, with the output of one++/**+ * Apply map bounds to mapState from received vis data+ * @param state+ * @param action {options, config: {}}+ * @returns state new reducer state+ */+export const updateVisDataComposed = (state, action) => {+ // keep a copy of oldLayers+ const oldLayers = state.visState.layers.map(l => l.id);++ const visState = updateVisDataUpdater(state.visState, action);++ const defaultOptions = {+ centerMap: true,+ // this will hide the left panel completely+ readOnly: false+ };+ const options = {+ ...defaultOptions,+ ...action.options+ };++ let bounds;+ if (options.centerMap) {+ // find map bounds for new layers+ const newLayers = visState.layers.filter(l => !oldLayers.includes(l.id));+ bounds = findMapBounds(newLayers);+ }++ return {+ ...state,+ visState,+ mapState: bounds+ ? fitBoundsUpdater(state.mapState, {+ payload: bounds+ })+ : state.mapState,+ uiState: {+ ...toggleModalUpdater(state.uiState, {payload: null}),+ readOnly: options.readOnly+ }+ };+};++/**+ * Combine data and full configuration update in a single action+ * @param state+ * @param action {datasets, options, config}+ * @returns state+ */+export const addDataToMapComposed = (state, action) => {++ const {datasets, options, config} = action.payload;++ // Update visState store+ let mergedState = updateVisDataComposed(state, {datasets, options, config: config && config.visState});++ // Update mapState store+ mergedState = {+ ...mergedState,+ mapState: stateMapConfigUpdater(mergedState.mapState, {payload: {mapState: config && config.mapState}})+ };++ // Update mapStyle store+ mergedState = {+ ...mergedState,+ mapStyle: styleMapConfigUpdater(mergedState.mapStyle, {payload: {mapStyle: config && config.mapStyle}})+ };++ return mergedState+};++const compostedUpdaters = {+ [ActionTypes.UPDATE_VIS_DATA]: updateVisDataComposed,+ [ActionTypes.ADD_DATA_TO_MAP]: addDataToMapComposed+};++export default compostedUpdaters;diff --git a/src/reducers/map-state-updaters.js b/src/reducers/map-state-updaters.jsnew file mode 100644index 000000000..0db91a971--- /dev/null+++ b/src/reducers/map-state-updaters.js@@ -0,0 +1,93 @@+// Copyright (c) 2018 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 geoViewport from '@mapbox/geo-viewport';++/* Updaters */+export const updateMapUpdater = (state, action) => ({+ ...state,+ ...(action.payload || {})+});++export const fitBoundsUpdater = (state, action) => {+ const bounds = action.payload;+ const {center, zoom} = geoViewport.viewport(bounds, [+ state.width,+ state.height+ ]);++ return {+ ...state,+ latitude: center[1],+ longitude: center[0],+ zoom+ };+};++export const togglePerspectiveUpdater = (state, action) => ({+ ...state,+ ...{+ pitch: state.dragRotate ? 0 : 50,+ bearing: state.dragRotate ? 0 : 24+ },+ dragRotate: !state.dragRotate+});++// consider case where you have a split map and user wants to reset+export const receiveMapConfigUpdater = (state, action) => {+ const {isSplit = false} = action.payload.mapState || {};++ return {+ ...state,+ ...(action.payload.mapState || {}),+ isSplit,+ ...getMapDimForSplitMap(isSplit, state)+ };+};++export const toggleSplitMapUpdater = (state, action) => ({+ ...state,+ isSplit: !state.isSplit,+ ...getMapDimForSplitMap(!state.isSplit, state)+});++// Helpers+function getMapDimForSplitMap(isSplit, state) {+ // cases:+ // 1. state split: true - isSplit: true+ // do nothing+ // 2. state split: false - isSplit: false+ // do nothing+ if (state.isSplit === isSplit) {+ return {};+ }++ const width = state.isSplit && !isSplit ?+ // 3. state split: true - isSplit: false+ // double width+ state.width * 2+ // 4. state split: false - isSplit: true+ // split width+ : state.width / 2;++ return {+ width+ };+}diff --git a/src/reducers/map-state.js b/src/reducers/map-state.jsnew file mode 100644index 000000000..9687e9d1a--- /dev/null+++ b/src/reducers/map-state.js@@ -0,0 +1,58 @@+// Copyright (c) 2018 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 {handleActions} from 'redux-actions';+import ActionTypes from 'constants/action-types';++export const INITIAL_MAP_STATE = {+ pitch: 0,+ bearing: 0,+ latitude: 37.75043,+ longitude: -122.34679,+ zoom: 9,+ dragRotate: false,+ width: 800,+ height: 800,+ isSplit: false+};++import {+ fitBoundsUpdater,+ receiveMapConfigUpdater,+ togglePerspectiveUpdater,+ toggleSplitMapUpdater,+ updateMapUpdater+} from './map-state-updaters';++const actionHandler = {+ [ActionTypes.UPDATE_MAP]: updateMapUpdater,+ [ActionTypes.FIT_BOUNDS]: fitBoundsUpdater,+ [ActionTypes.TOGGLE_PERSPECTIVE]: togglePerspectiveUpdater,+ [ActionTypes.RECEIVE_MAP_CONFIG]: receiveMapConfigUpdater,+ [ActionTypes.TOGGLE_SPLIT_MAP]: toggleSplitMapUpdater+};++/* Reducer */+export const mapStateReducerFactory = (initialState = {}) => handleActions(+ actionHandler,+ {...INITIAL_MAP_STATE, ...initialState, initialState}+);++export default mapStateReducerFactory();diff --git a/website/src/reducers/index.js b/website/src/reducers/index.jsindex ed463964e..1012f51c9 100644--- a/website/src/reducers/index.js+++ b/website/src/reducers/index.js@@ -1,6 +1,6 @@import {createStore, combineReducers} from 'redux';import appReducer from './app';-import {routerReducer } from 'react-router-redux'+import {routerReducer} from 'react-router-redux'export default createStore(combineReducers({diff --git a/website/src/routes.js b/website/src/routes.jsindex 409e9435f..a1d52724f 100644--- a/website/src/routes.js+++ b/website/src/routes.js@@ -5,6 +5,7 @@ import store from './reducers';import Home from './components/home';import App from './components/app';+import Demo from './components/app';// eslint-disable-next-line react/display-nameexport default () => (@@ -12,5 +13,6 @@ export default () => (<Route path="*" component={App}><IndexRoute component={Home} /></Route>+ <Route path="/demo(/:id)" component={Demo} /></Router>);