Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

WIP

Benjamin Kingd770874e2fb5
diff --git a/package-lock.json b/package-lock.json
index dbc4bab6b..92f4119fc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10803,6 +10803,11 @@
"integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=",
"dev": true
},
+ "mediaquery": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/mediaquery/-/mediaquery-0.0.3.tgz",
+ "integrity": "sha1-OH1hwQqpX/TWkH9qq90i16iY4D4="
+ },
"mem": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/mem/-/mem-1.1.0.tgz",
@@ -16972,6 +16977,14 @@
"lodash.isplainobject": "4.0.6"
}
},
+ "redux-responsive": {
+ "version": "4.3.8",
+ "resolved": "https://registry.npmjs.org/redux-responsive/-/redux-responsive-4.3.8.tgz",
+ "integrity": "sha512-h+q9KTfaOdgXxFhqwHhAIHT/1ZiARFmM3iLMOnjpc79BUXlW24N3qJmUR5kOQYicIKKL0usIjNuNa+2HFTnxLg==",
+ "requires": {
+ "mediaquery": "0.0.3"
+ }
+ },
"redux-thunk": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.3.0.tgz",
diff --git a/package.json b/package.json
index 3a6293292..7d77b6b03 100644
--- a/package.json
+++ b/package.json
@@ -186,6 +186,7 @@
"react-redux": "^6.0.0",
"reactstrap": "^7.0.0",
"redux": "^4.0.1",
+ "redux-responsive": "^4.3.8",
"redux-thunk": "^2.3.0",
"simplebar": "^3.0.0-beta.1",
"supercluster": "3.0.2",
diff --git a/web/js/app.js b/web/js/app.js
index f362b6a0b..ddce9ef42 100644
--- a/web/js/app.js
+++ b/web/js/app.js
@@ -8,6 +8,7 @@ import util from './util/util';
import OlCoordinates from './components/map/ol-coordinates';
// Toolbar
import Toolbar from './containers/toolbar';
+import Sidebar from './containers/sidebar';
// Modal
import Modal from './containers/modal';
@@ -16,6 +17,11 @@ import Brand from './brand';
// Crutch between state systems
import { updateLegacyInitComplete } from './modules/migration/actions';
+
+// actions
+// import { screenResize } from './modules/browser/actions';
+import { calculateResponsiveState } from 'redux-responsive';
+
// Dependency CSS
import '../../node_modules/bootstrap/dist/css/bootstrap.css';
import '../../node_modules/jquery-ui-bundle/jquery-ui.structure.css';
@@ -78,7 +84,7 @@ class App extends React.Component {
return (
<div className="wv-content" id="wv-content" data-role="content">
<Toolbar />
- <section id="wv-sidebar" />
+ <Sidebar />
<div id="layer-modal" className="layer-modal" />
<div id="layer-settings-modal" />
<div id="wv-map" className="wv-map" />
@@ -205,8 +211,6 @@ class App extends React.Component {
if (config.features.googleTagManager) {
googleTagManager.init(config.features.googleTagManager.id); // Insert google tag manager
}
- document.activeElement.blur();
- $('input').blur();
// Console notifications
if (Brand.release()) {
@@ -220,7 +224,10 @@ class App extends React.Component {
} else {
console.warn('Development version');
}
-
+ window.addEventListener('resize', () => {
+ self.props.screenResize(window);
+ });
+ self.props.screenResize(window);
models.wv.events.trigger('startup');
self.props.updateLegacyInitComplete(); // notify state that legacy initiation has finished
};
@@ -240,6 +247,9 @@ function mapStateToProps(state, ownProps) {
const mapDispatchToProps = dispatch => ({
updateLegacyInitComplete: () => {
dispatch(updateLegacyInitComplete());
+ },
+ screenResize: (width, height) => {
+ dispatch(calculateResponsiveState(window));
}
});
diff --git a/web/js/combine-ui.js b/web/js/combine-ui.js
index 40a611a03..fc23dd723 100644
--- a/web/js/combine-ui.js
+++ b/web/js/combine-ui.js
@@ -20,7 +20,6 @@ import { tourUi } from './tour/ui';
import { layersModal } from './layers/modal';
import { layersActive } from './layers/active';
import { layersOptions } from './layers/options';
-import { sidebarUi } from './sidebar/ui';
import { mapui } from './map/ui';
import { MapRotate } from './map/rotation';
import { MapRunningData } from './map/runningdata';
@@ -55,14 +54,13 @@ export function combineUi(models, config, MapMouseEvents) {
};
ui.map = mapui(models, config, mapComponents);
ui.map.animate = mapAnimate(models, config, ui);
- ui.sidebar = sidebarUi(models, config, ui);
if (config.features.tour) {
ui.alert = alertUi(ui, config);
ui.tour = tourUi(models, ui, config);
}
ui.activeLayers = layersActive(models, ui, config);
ui.addModal = layersModal(models, ui, config);
- ui.layerSettingsModal = layersOptions(models, ui, config);
+ // ui.layerSettingsModal = layersOptions(models, ui, config);
// Test via a getter in the options object to see if the passive property is accessed
ui.supportsPassive = false;
try {
diff --git a/web/js/components/sidebar/events/events.js b/web/js/components/sidebar/events/events.js
index 5bdad1948..03d0f6ddb 100644
--- a/web/js/components/sidebar/events/events.js
+++ b/web/js/components/sidebar/events/events.js
@@ -1,6 +1,5 @@
import React from 'react';
import PropTypes from 'prop-types';
-// import { Scrollbars } from 'react-custom-scrollbars';
import Event from './event';
import Scrollbars from '../../util/scrollbar';
diff --git a/web/js/components/sidebar/products/layer-list.js b/web/js/components/sidebar/products/layer-list.js
index c03328ab3..be69fd245 100644
--- a/web/js/components/sidebar/products/layer-list.js
+++ b/web/js/components/sidebar/products/layer-list.js
@@ -1,9 +1,16 @@
import React from 'react';
import PropTypes from 'prop-types';
+import { connect } from 'react-redux';
import Layer from './layer';
-import { SidebarContext } from '../provider';
import { Droppable, DragDropContext } from 'react-beautiful-dnd';
-import lodashIsEqual from 'lodash/isEqual';
+import {
+ replaceSubGroup,
+ getZotsForActiveLayers,
+ getTitles,
+ available
+} from '../../../modules/layers/selectors';
+import { palettePromise } from '../../../modules/palettes/selectors';
+import { reorderLayers } from '../../../modules/layers/actions';
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
@@ -20,12 +27,6 @@ class LayerList extends React.Component {
};
this.promises = {};
}
-
- componentWillReceiveProps(props) {
- if (!lodashIsEqual(props.layers, this.state.layers)) {
- this.setState({ layers: props.layers });
- }
- }
/**
* Get Palette and setState with promise results when palette is retrieved
* @param {Object} layer | Layer
@@ -56,7 +57,7 @@ class LayerList extends React.Component {
* @param {Object} result | Result of layer drag
*/
onDragEnd(replaceSubGroup, result) {
- const { layerGroupName, groupId } = this.props;
+ const { layerGroupName, groupId, reorderLayers } = this.props;
const { layers } = this.state;
if (!result.destination) {
return;
@@ -78,82 +79,64 @@ class LayerList extends React.Component {
if (nextIndex < newLayerArray.length) {
nextLayerId = newLayerArray[nextIndex].id;
}
- replaceSubGroup(layerId, nextLayerId, layerGroupName, groupId);
+ reorderLayers(
+ replaceSubGroup(layerId, nextLayerId, layerGroupName, groupId)
+ );
}
render() {
- const { groupId, title, layerGroupName } = this.props;
- const { layers } = this.state;
+ const {
+ groupId,
+ title,
+ layerGroupName,
+ zots,
+ layers,
+ runningLayers,
+ projId,
+ checkerBoardPattern,
+ getNames,
+ available
+ } = this.props;
return (
- <SidebarContext.Consumer>
- {context => (
- <div className="layer-group-case">
- <h3 className="head">{title}</h3>
- <DragDropContext
- onDragEnd={this.onDragEnd.bind(this, context.replaceSubGroup)}
- >
- <Droppable
- droppableId={layerGroupName + '-' + groupId}
- type="layerSubGroup"
- direction="vertical"
- >
- {(provided, snapshot) => {
- return (
- <ul
- id={groupId}
- className="category"
- ref={provided.innerRef}
- >
- {layers.map((object, i) => (
- <Layer
- layer={object}
- groupId={groupId}
- layerGroupName={layerGroupName}
- isInProjection={
- !!object.projections[context.projection]
- }
- getLegend={context.getLegend}
- key={i}
- index={i}
- layerClasses="item productsitem"
- zot={
- context.zotsObject[object.id]
- ? context.zotsObject[object.id].value
- : null
- }
- isMobile={context.isMobile}
- names={context.getNames(object.id)}
- checkerBoardPattern={context.checkerBoardPattern}
- getPalette={context.getPalette}
- palette={this.getPalette(
- object,
- context.palettePromise
- )}
- isDisabled={
- !context.getAvailability(
- object.id,
- undefined,
- layerGroupName
- )
- }
- isVisible={object.visible}
- updateLayer={context.updateLayer}
- runningObject={
- context.runningLayers &&
- context.runningLayers[object.id]
- ? context.runningLayers[object.id]
- : null
- }
- />
- ))}
- {provided.placeholder}
- </ul>
- );
- }}
- </Droppable>
- </DragDropContext>
- </div>
- )}
- </SidebarContext.Consumer>
+ <div className="layer-group-case">
+ <h3 className="head">{title}</h3>
+ <DragDropContext onDragEnd={this.onDragEnd.bind(this, replaceSubGroup)}>
+ <Droppable
+ droppableId={layerGroupName + '-' + groupId}
+ type="layerSubGroup"
+ direction="vertical"
+ >
+ {(provided, snapshot) => {
+ return (
+ <ul id={groupId} className="category" ref={provided.innerRef}>
+ {layers.map((object, i) => (
+ <Layer
+ layer={object}
+ groupId={groupId}
+ layerGroupName={layerGroupName}
+ isInProjection={!!object.projections[projId]}
+ key={i}
+ index={i}
+ layerClasses="item productsitem"
+ zot={zots[object.id] ? zots[object.id].value : null}
+ names={getNames(object.id)}
+ checkerBoardPattern={checkerBoardPattern}
+ palette={this.getPalette(object, palettePromise)}
+ isDisabled={!available(object.id)}
+ isVisible={object.visible}
+ runningObject={
+ runningLayers && runningLayers[object.id]
+ ? runningLayers[object.id]
+ : null
+ }
+ />
+ ))}
+ {provided.placeholder}
+ </ul>
+ );
+ }}
+ </Droppable>
+ </DragDropContext>
+ </div>
);
}
}
@@ -163,5 +146,44 @@ LayerList.propTypes = {
title: PropTypes.string,
layerGroupName: PropTypes.string
};
+function mapStateToProps(state, ownProps) {
+ const {
+ layers,
+ groupId,
+ title,
+ layerGroupName,
+ checkerBoardPattern
+ } = ownProps;
+ const { runningLayers } = state.layers;
+ const { id } = state.proj;
+ const zoom = state.legacy.map.getZoom();
+ const zots = getZotsForActiveLayers(layers, zoom) || {};
-export default LayerList;
+ return {
+ zots,
+ layers,
+ groupId,
+ title,
+ layerGroupName,
+ runningLayers,
+ projId: id,
+ checkerBoardPattern,
+ getNames: (layerId, proj) => {
+ return getTitles(state.config, layerId, proj, state);
+ },
+ available: id => {
+ const date = state.legacy.date['active'];
+ return available(id, date, layers, state.config, state);
+ }
+ };
+}
+const mapDispatchToProps = dispatch => ({
+ reorderLayers: newLayerArray => {
+ dispatch(reorderLayers(newLayerArray));
+ },
+ palettePromise: () => {}
+});
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(LayerList);
diff --git a/web/js/components/sidebar/products/layer.js b/web/js/components/sidebar/products/layer.js
index 8aa23c524..7da718d89 100644
--- a/web/js/components/sidebar/products/layer.js
+++ b/web/js/components/sidebar/products/layer.js
@@ -3,6 +3,13 @@ import PropTypes from 'prop-types';
import Legend from './legend';
import { Draggable } from 'react-beautiful-dnd';
import util from '../../../util/util';
+import { get } from '../../../modules/palettes/selectors';
+import {
+ toggleVisibility,
+ removeLayer,
+ layerHover
+} from '../../../modules/layers/actions';
+import { connect } from 'react-redux';
const visibilityButtonClasses = 'hdanchor hide hideReg bank-item-img';
const getItemStyle = (isDragging, draggableStyle) => ({
@@ -29,26 +36,6 @@ class Layer extends React.Component {
this.setState({ isInProjection: props.isInProjection });
}
}
- hover(value) {
- const { updateLayer, layer } = this.props;
- updateLayer(layer.id, 'hover', value);
- }
- toggleVisibility(e) {
- const { updateLayer, layer } = this.props;
- updateLayer(layer.id, 'visibility');
- }
- onRemoveClick(e) {
- const { updateLayer, layer } = this.props;
- updateLayer(layer.id, 'remove');
- }
- onOptionsClick() {
- const { updateLayer, layer } = this.props;
- updateLayer(layer.id, 'options');
- }
- onInfoClick() {
- const { updateLayer, layer } = this.props;
- updateLayer(layer.id, 'info');
- }
getLegend() {
const {
layer,
@@ -110,19 +97,22 @@ class Layer extends React.Component {
return 'No data on selected date for this layer';
}
}
- onLayerHover() {}
- getPalette() {}
render() {
const { zot, isInProjection } = this.state;
const {
layerGroupName,
+ onRemoveClick,
+ toggleVisibility,
+ onInfoClick,
+ hover,
layer,
isDisabled,
isVisible,
layerClasses,
names,
isMobile,
- index
+ index,
+ onOptionsClick
} = this.props;
return (
@@ -151,8 +141,8 @@ class Layer extends React.Component {
? layerClasses + ' layer-enabled layer-visible zotted'
: layerClasses + ' layer-enabled layer-visible'
}
- onMouseEnter={this.hover.bind(this, true)}
- onMouseLeave={this.hover.bind(this, false)}
+ onMouseEnter={() => hover(layer.id, true)}
+ onMouseLeave={() => hover(layer.id, false)}
>
<a
className={
@@ -163,7 +153,7 @@ class Layer extends React.Component {
: visibilityButtonClasses + ' layer-enabled layer-visible'
}
id={'hide' + util.encodeId(layer.id)}
- onClick={this.toggleVisibility.bind(this)}
+ onClick={() => toggleVisibility(layer.id)}
title={
!isVisible && !isDisabled
? 'Show Layer'
@@ -200,7 +190,7 @@ class Layer extends React.Component {
id={'close' + layerGroupName + util.encodeId(layer.id)}
title={'Remove Layer'}
className="button wv-layers-close"
- onClick={this.onRemoveClick.bind(this)}
+ onClick={() => onRemoveClick(layer.id)}
>
<i className="fa fa-times" />
</a>
@@ -209,7 +199,7 @@ class Layer extends React.Component {
className={
isMobile ? 'hidden wv-layers-options' : 'wv-layers-options'
}
- onClick={this.onOptionsClick.bind(this)}
+ onClick={() => onOptionsClick(layer.id)}
>
<i className="fas fa-sliders-h wv-layers-options-icon" />
</a>
@@ -218,7 +208,7 @@ class Layer extends React.Component {
className={
isMobile ? 'hidden wv-layers-info' : 'wv-layers-info'
}
- onClick={this.onInfoClick.bind(this)}
+ onClick={() => onInfoClick(layer.id)}
>
<i className="fa fa-info wv-layers-info-icon" />
</a>
@@ -264,6 +254,59 @@ Layer.propTypes = {
index: PropTypes.number,
checkerBoardPattern: PropTypes.object,
isInProjection: PropTypes.bool,
- zot: PropTypes.number
+ zot: PropTypes.number,
+ onRemoveClick: PropTypes.func,
+ toggleVisibility: PropTypes.func,
+ onInfoClick: PropTypes.func,
+ hover: PropTypes.func
};
-export default Layer;
+function mapStateToProps(state, ownProps) {
+ const {
+ layer,
+ isDisabled,
+ isVisible,
+ layerClasses,
+ names,
+ index,
+ layerGroupName
+ } = ownProps;
+
+ return {
+ layer,
+ isDisabled,
+ isVisible,
+ layerClasses,
+ names,
+ index,
+ layerGroupName,
+ isMobile: state.browser.is.small,
+ getPalette: () => {
+ get(layer.id, index, layerGroupName, state);
+ }
+ };
+}
+
+const mapDispatchToProps = dispatch => ({
+ hover: (id, value) => {
+ dispatch(layerHover(id, value));
+ },
+ toggleVisibility: id => {
+ dispatch(toggleVisibility(id));
+ },
+ onRemoveClick: id => {
+ dispatch(removeLayer(id));
+ },
+ onOptionsClick: id => {
+ // dispatch(layerOptions(id));
+ },
+ onInfoClick: id => {
+ // googleTagManager.pushEvent({
+ // event: 'sidebar_layer_info'
+ // });
+ // dispatch(layerInfo(id));
+ }
+});
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(Layer);
diff --git a/web/js/components/sidebar/products/products.js b/web/js/components/sidebar/products/products.js
index c059ba966..c396295ee 100644
--- a/web/js/components/sidebar/products/products.js
+++ b/web/js/components/sidebar/products/products.js
@@ -1,11 +1,20 @@
import React from 'react';
+import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import LayerList from './layer-list';
+import { getLayers } from '../../../modules/layers/selectors';
import Scrollbars from '../../util/scrollbar';
class Products extends React.Component {
render() {
- const { activeOverlays, isActive, layerGroupName, height } = this.props;
+ const {
+ overlays,
+ baselayers,
+ isActive,
+ layerGroupName,
+ height,
+ checkerBoardPattern
+ } = this.props;
const outterClass = 'layer-container sidebar-panel';
return (
<Scrollbars style={{ maxHeight: height + 'px' }}>
@@ -17,25 +26,49 @@ class Products extends React.Component {
title="Overlays"
groupId="overlays"
layerGroupName={layerGroupName}
- layers={activeOverlays.overlays}
+ layers={baselayers}
+ checkerBoardPattern={checkerBoardPattern}
/>
<LayerList
title="Base Layers"
groupId="baselayers"
layerGroupName={layerGroupName}
- layers={activeOverlays.baselayers}
+ layers={overlays}
+ checkerBoardPattern={checkerBoardPattern}
/>
</div>
</Scrollbars>
);
}
}
+
+function mapStateToProps(state, ownProps) {
+ const { layers, proj } = state;
+ const { activeString } = layers;
+ const { isActive, layerGroupName, height, checkerBoardPattern } = ownProps;
+ const group = 'layers' + layerGroupName;
+ const componentLayers = layers[group] || layers['layers' + activeString];
+ const layerObj = getLayers(componentLayers, { proj: proj.id, group: 'all' });
+
+ return {
+ baselayers: layerObj.baselayers,
+ overlays: layerObj.overlays,
+ layerGroupName,
+ height,
+ isActive,
+ checkerBoardPattern
+ };
+}
+const mapDispatchToProps = dispatch => ({});
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(Products);
+
Products.propTypes = {
- activeOverlays: PropTypes.object,
- palettePromise: PropTypes.func,
+ overlays: PropTypes.array,
+ baselayers: PropTypes.array,
isActive: PropTypes.bool,
layerGroupName: PropTypes.string,
height: PropTypes.number
};
-
-export default Products;
diff --git a/web/js/components/sidebar/sidebar.js b/web/js/components/sidebar/sidebar.js
deleted file mode 100644
index 95877b35c..000000000
--- a/web/js/components/sidebar/sidebar.js
+++ /dev/null
@@ -1,362 +0,0 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import Products from './products/products';
-import Events from './events/events';
-import Data from './data/data';
-import CompareCase from './compare';
-import FooterContent from './footer-content';
-import { TabContent, TabPane } from 'reactstrap';
-import { SidebarProvider as Provider } from './provider';
-import CollapsedButton from './collapsed-button';
-import NavCase from './nav/nav-case';
-import googleTagManager from 'googleTagManager';
-import util from '../../util/util';
-
-class Sidebar extends React.Component {
- constructor(props) {
- super(props);
- var wasCollapsedRequested = this.wasCollapsedRequested();
- this.state = {
- activeTab: props.activeTab,
- isCompareMode: props.isCompareMode,
- isCollapsed: wasCollapsedRequested || props.isMobile,
- layers: props.layers,
- firstDateObject: props.firstDateObject,
- secondDateObject: props.secondDateObject,
- isCompareA: props.isCompareA,
- isCollapsedRequested: wasCollapsedRequested,
- comparisonType: props.comparisonType,
- runningLayers: props.runningLayers,
- zotsObject: props.zotsObject,
- isMobile: props.isMobile,
- windowHeight: window.innerHeight,
- subComponentHeight: 700,
- visibleEvents: props.visibleEvents,
- showListAllButton: props.showListAllButton,
- eventsData: props.eventsData,
- selectedEvent: props.selectedEvent,
- selectEvent: props.selectEvent,
- deselectEvent: props.deselectEvent,
- filterEventList: props.filterEventList,
- getDataSelectionCounts: props.getDataSelectionCounts,
- dataDownloadObject: {},
- selectedDataProduct: props.selectedDataProduct,
- showDataUnavailableReason: props.showDataUnavailableReason,
- projection: props.projection,
- modalOpen: false
- };
- }
- componentDidMount() {
- this.updateDimensions();
- // prevent browserzooming in safari
- if (util.browser.safari) {
- let onGestureCallback = e => {
- e.preventDefault();
- e.stopPropagation();
- };
- this.iconElement.addEventListener('gesturestart', onGestureCallback);
- this.sideBarCase.addEventListener('gesturestart', onGestureCallback);
- }
- }
- componentDidUpdate() {
- this.updateDimensions();
- }
- updateDimensions() {
- const { isMobile, subComponentHeight, windowHeight } = this.state;
-
- if (!isMobile) {
- let newHeight;
- let iconHeight = this.iconElement.clientHeight;
- let topOffset = Math.abs(this.iconElement.getBoundingClientRect().top);
- let footerHeight = this.footerElement.clientHeight;
- let tabHeight = 32;
- let basePadding = 110;
- newHeight =
- windowHeight -
- (iconHeight + topOffset + tabHeight + basePadding + footerHeight);
- // Issue #1415: This was checking for subComponentHeight !== newHeight.
- // Sometimes it would get stuck in a loop in which the newHeight
- // would vary by a single pixel on each render. Hack fix is to
- // only update when changed by more than a single pixel. This probably
- // needs a refactoring.
- if (Math.abs(subComponentHeight - newHeight) > 1) {
- this.setState({ subComponentHeight: newHeight });
- }
- } else {
- let newHeight;
- let tabHeight = 32;
- let footerHeight = this.footerElement.clientHeight;
- newHeight = windowHeight - (tabHeight + footerHeight);
- // See note above
- if (Math.abs(subComponentHeight - newHeight) > 1) {
- this.setState({ subComponentHeight: newHeight });
- }
- }
- }
- selectEvent(id, date) {
- this.state.selectEvent(id, date);
- if (this.state.isMobile) {
- this.setState({ isCollapsed: true });
- }
- }
- wasCollapsedRequested() {
- if (this.props.localStorage) {
- return localStorage.getItem('sidebarState') === 'collapsed';
- }
- return false;
- }
- toggleSidebar() {
- var isNowCollapsed = !this.state.isCollapsed;
- googleTagManager.pushEvent({
- event: 'sidebar_chevron'
- });
- if (this.props.localStorage) {
- let storageValue = isNowCollapsed ? 'collapsed' : 'expanded';
- localStorage.setItem('sidebarState', storageValue);
- }
- this.setState({
- isCollapsed: isNowCollapsed,
- isCollapsedRequested: isNowCollapsed
- });
- }
- getProductsToRender(activeTab, isCompareMode) {
- const {
- layers,
- firstDateObject,
- secondDateObject,
- isCompareA,
- subComponentHeight,
- isMobile
- } = this.state;
- const { toggleComparisonObject } = this.props;
- if (isCompareMode) {
- return (
- <CompareCase
- isActive={activeTab === 'layers'}
- firstDateObject={firstDateObject}
- secondDateObject={secondDateObject}
- height={subComponentHeight}
- toggleComparisonObject={toggleComparisonObject}
- isCompareA={isCompareA}
- />
- );
- } else if (!isCompareMode) {
- return (
- <Products
- height={subComponentHeight}
- isActive={activeTab === 'layers'}
- activeOverlays={layers}
- isMobile={isMobile}
- layerGroupName={isCompareA ? 'active' : 'activeB'}
- />
- );
- }
- }
-
- render() {
- const {
- activeTab,
- isCompareMode,
- runningLayers,
- zotsObject,
- isMobile,
- isCollapsed,
- layers,
- visibleEvents,
- eventsData,
- selectedEvent,
- subComponentHeight,
- secondDateObject,
- firstDateObject,
- deselectEvent,
- isCompareA,
- dataDownloadObject,
- selectedDataProduct,
- showDataUnavailableReason,
- showListAllButton,
- comparisonType,
- onGetData,
- windowHeight,
- filterEventList,
- projection
- } = this.state;
- const {
- onTabClick,
- palettePromise,
- updateLayer,
- getNames,
- getAvailability,
- getLegend,
- replaceSubGroup,
- getDataSelectionCounts,
- selectDataProduct,
- toggleMode,
- addLayers,
- getDataSelectionSize,
- changeCompareMode,
- checkerBoardPattern,
- compareFeature,
- tabTypes,
- getPalette
- } = this.props;
- const wheelCallBack = util.browser.chrome ? util.preventPinch : null;
- return (
- <Provider
- palettePromise={palettePromise}
- getPalette={getPalette}
- updateLayer={updateLayer}
- getNames={getNames}
- getAvailability={getAvailability}
- runningLayers={runningLayers}
- getLegend={getLegend}
- zotsObject={zotsObject}
- replaceSubGroup={replaceSubGroup}
- isMobile={isMobile}
- checkerBoardPattern={checkerBoardPattern}
- projection={projection}
- >
- <a
- href="/"
- title="Click to Reset Worldview to Defaults"
- id="wv-logo"
- ref={iconElement => (this.iconElement = iconElement)}
- onWheel={wheelCallBack}
- />
- <CollapsedButton
- isCollapsed={isCollapsed}
- onclick={this.toggleSidebar.bind(this)}
- numberOfLayers={
- !isCompareMode
- ? layers.baselayers.length + layers.overlays.length
- : isCompareA
- ? firstDateObject.layers.overlays.length +
- firstDateObject.layers.baselayers.length
- : secondDateObject.layers.overlays.length +
- secondDateObject.layers.baselayers.length
- }
- />
- <div
- id="productsHolder"
- className="products-holder-case"
- ref={el => {
- this.sideBarCase = el;
- }}
- style={
- isCollapsed
- ? { maxHeight: '0' }
- : { maxHeight: windowHeight + 'px' }
- }
- onWheel={wheelCallBack}
- >
- <NavCase
- tabTypes={tabTypes}
- isMobile={isMobile}
- isCompareMode={isCompareMode}
- onTabClick={onTabClick}
- activeTab={activeTab}
- toggleSidebar={this.toggleSidebar.bind(this)}
- />
- <TabContent activeTab={activeTab}>
- <TabPane tabId="layers">
- {this.getProductsToRender(activeTab, isCompareMode)}
- </TabPane>
- <TabPane tabId="events">
- <Events
- isActive={activeTab === 'events'}
- visibleEvents={visibleEvents}
- events={eventsData.events}
- sources={eventsData.sources}
- selectedEvent={selectedEvent}
- selectEvent={this.selectEvent.bind(this)}
- deselectEvent={deselectEvent}
- height={subComponentHeight}
- tabTypes={tabTypes}
- />
- </TabPane>
- <TabPane tabId="download">
- <Data
- isActive={activeTab === 'download'}
- data={dataDownloadObject}
- getCounts={getDataSelectionCounts}
- selected={selectedDataProduct}
- selectProduct={selectDataProduct}
- showUnavailableReason={showDataUnavailableReason}
- height={subComponentHeight}
- tabTypes={tabTypes}
- />
- </TabPane>
- <footer ref={footerElement => (this.footerElement = footerElement)}>
- <FooterContent
- showListAllButton={showListAllButton}
- isCompareMode={isCompareMode}
- comparisonType={comparisonType}
- isMobile={isMobile}
- eventsData={eventsData}
- activeTab={activeTab}
- filterEventList={filterEventList}
- onGetData={onGetData}
- changeCompareMode={changeCompareMode}
- addLayers={addLayers}
- toggleMode={toggleMode}
- getDataSelectionCounts={getDataSelectionCounts}
- getDataSelectionSize={getDataSelectionSize}
- compareFeature={compareFeature}
- />
- </footer>
- </TabContent>
- </div>
- </Provider>
- );
- }
-}
-Sidebar.defaultProps = {
- maxHeight: 700,
- visibleEvents: {}
-};
-Sidebar.propTypes = {
- activeTab: PropTypes.string,
- isCompareMode: PropTypes.bool,
- isCollapsed: PropTypes.bool,
- toggleSidebar: PropTypes.func,
- updateLayer: PropTypes.func,
- onTabClick: PropTypes.func,
- tabTypes: PropTypes.object,
- layers: PropTypes.object,
- getNames: PropTypes.func,
- firstDateObject: PropTypes.object,
- secondDateObject: PropTypes.object,
- addLayers: PropTypes.func,
- toggleComparisonMode: PropTypes.func,
- getAvailability: PropTypes.func,
- isCompareA: PropTypes.bool,
- toggleComparisonObject: PropTypes.func,
- comparisonType: PropTypes.string,
- toggleMode: PropTypes.func,
- runningLayers: PropTypes.object,
- changeCompareMode: PropTypes.func,
- palettePromise: PropTypes.func,
- getPalette: PropTypes.func,
- localStorage: PropTypes.bool,
- getLegend: PropTypes.func,
- zotsObject: PropTypes.object,
- isMobile: PropTypes.bool,
- replaceSubGroup: PropTypes.func,
- maxHeight: PropTypes.number,
- getDataSelectionCounts: PropTypes.func,
- selectDataProduct: PropTypes.func,
- getDataSelectionSize: PropTypes.func,
- checkerBoardPattern: PropTypes.object,
- visibleEvents: PropTypes.object,
- showListAllButton: PropTypes.bool,
- eventsData: PropTypes.object,
- selectedEvent: PropTypes.object,
- selectEvent: PropTypes.func,
- deselectEvent: PropTypes.func,
- filterEventList: PropTypes.func,
- selectedDataProduct: PropTypes.string,
- showDataUnavailableReason: PropTypes.func,
- compareFeature: PropTypes.bool,
- projection: PropTypes.string
-};
-
-export default Sidebar;
diff --git a/web/js/containers/sidebar.js b/web/js/containers/sidebar.js
new file mode 100644
index 000000000..d922a1ad9
--- /dev/null
+++ b/web/js/containers/sidebar.js
@@ -0,0 +1,233 @@
+import React from 'react';
+import { connect } from 'react-redux';
+import PropTypes from 'prop-types';
+import Products from '../components/sidebar/products/products';
+import Events from '../components/sidebar/events/events';
+import Data from '../components/sidebar/data/data';
+import CompareCase from '../components/sidebar/compare';
+import FooterContent from '../components/sidebar/footer-content';
+import { TabContent, TabPane } from 'reactstrap';
+import CollapsedButton from '../components/sidebar/collapsed-button';
+import NavCase from '../components/sidebar/nav/nav-case';
+import googleTagManager from 'googleTagManager';
+import { getCheckerboard } from '../modules/palettes/util';
+import { getLayers } from '../modules/layers/selectors';
+
+import util from '../util/util';
+import {
+ changeTab,
+ toggleSidebarCollapse,
+ collapseSidebar,
+ expandSidebar
+} from '../modules/sidebar/actions';
+
+class Sidebar extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = { subComponentHeight: 700 };
+ this.checkerBoardPattern = getCheckerboard();
+ }
+ componentDidMount() {
+ // this.updateDimensions();
+ // prevent browserzooming in safari
+ if (util.browser.safari) {
+ let onGestureCallback = e => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ this.iconElement.addEventListener('gesturestart', onGestureCallback);
+ this.sideBarCase.addEventListener('gesturestart', onGestureCallback);
+ }
+ }
+ componentDidUpdate() {
+ // this.updateDimensions();
+ }
+ updateDimensions() {
+ const { subComponentHeight } = this.state;
+ const { isMobile, screenHeight } = this.props;
+
+ if (!isMobile) {
+ let newHeight;
+ let iconHeight = this.iconElement.clientHeight;
+ let topOffset = Math.abs(this.iconElement.getBoundingClientRect().top);
+ let footerHeight = this.footerElement.clientHeight;
+ let tabHeight = 32;
+ let basePadding = 110;
+ newHeight =
+ screenHeight -
+ (iconHeight + topOffset + tabHeight + basePadding + footerHeight);
+ // Issue #1415: This was checking for subComponentHeight !== newHeight.
+ // Sometimes it would get stuck in a loop in which the newHeight
+ // would vary by a single pixel on each render. Hack fix is to
+ // only update when changed by more than a single pixel. This probably
+ // needs a refactoring.
+ if (Math.abs(subComponentHeight - newHeight) > 1) {
+ this.setState({ subComponentHeight: newHeight });
+ }
+ } else {
+ let newHeight;
+ let tabHeight = 32;
+ let footerHeight = this.footerElement.clientHeight;
+ newHeight = screenHeight - (tabHeight + footerHeight);
+ // See note above
+ if (Math.abs(subComponentHeight - newHeight) > 1) {
+ this.setState({ subComponentHeight: newHeight });
+ }
+ }
+ }
+ selectEvent(id, date) {
+ this.state.selectEvent(id, date);
+ if (this.props.isMobile) {
+ this.props.collapseSidebar();
+ }
+ }
+ toggleSidebar() {
+ const { isCollapsed, collapseExpandToggle, hasLocalStorage } = this.props;
+ var isNowCollapsed = !isCollapsed;
+ googleTagManager.pushEvent({
+ event: 'sidebar_chevron'
+ });
+ if (hasLocalStorage) {
+ let storageValue = isNowCollapsed ? 'collapsed' : 'expanded';
+ localStorage.setItem('sidebarState', storageValue);
+ }
+ collapseExpandToggle();
+ }
+ getProductsToRender(activeTab, isCompareMode) {
+ const { subComponentHeight } = this.state;
+ if (isCompareMode) {
+ return (
+ <CompareCase
+ isActive={activeTab === 'layers'}
+ height={subComponentHeight}
+ checkerBoardPattern={this.checkerBoardPattern}
+ />
+ );
+ } else if (!isCompareMode) {
+ return (
+ <Products
+ height={subComponentHeight}
+ isActive={activeTab === 'layers'}
+ layerGroupName="A"
+ checkerBoardPattern={this.checkerBoardPattern}
+ />
+ );
+ }
+ }
+
+ render() {
+ const { subComponentHeight } = this.state;
+ const {
+ onTabClick,
+ numberOfLayers,
+ screenHeight,
+ isCollapsed,
+ isCompareMode,
+ activeTab
+ } = this.props;
+ const wheelCallBack = util.browser.chrome ? util.preventPinch : null;
+ return (
+ <section id="wv-sidebar">
+ <a
+ href="/"
+ title="Click to Reset Worldview to Defaults"
+ id="wv-logo"
+ ref={iconElement => (this.iconElement = iconElement)}
+ onWheel={wheelCallBack}
+ />
+ <CollapsedButton
+ isCollapsed={isCollapsed}
+ onclick={this.toggleSidebar.bind(this)}
+ numberOfLayers={numberOfLayers}
+ />
+ <div
+ id="productsHolder"
+ className="products-holder-case"
+ ref={el => {
+ this.sideBarCase = el;
+ }}
+ style={
+ isCollapsed
+ ? { maxHeight: '0' }
+ : { maxHeight: screenHeight + 'px' }
+ }
+ onWheel={wheelCallBack}
+ >
+ {/* <NavCase activeTab={activeTab} onTabClick={onTabClick} /> */}
+ <TabContent activeTab={activeTab}>
+ <TabPane tabId="layers">
+ {this.getProductsToRender(activeTab, isCompareMode)}
+ </TabPane>
+ {/* <TabPane tabId="events">
+ <Events
+ isActive={activeTab === 'events'}
+ height={subComponentHeight}
+ />
+ </TabPane>
+ <TabPane tabId="download">
+ <Data
+ isActive={activeTab === 'download'}
+ height={subComponentHeight}
+ />
+ </TabPane>
+ <footer ref={footerElement => (this.footerElement = footerElement)}>
+ <FooterContent />
+ </footer> */}
+ </TabContent>
+ </div>
+ </section>
+ );
+ }
+}
+function mapStateToProps(state) {
+ const { browser, sidebar, compare, layers } = state;
+ const { screenHeight } = browser;
+ const { activeTab } = sidebar;
+ const { activeString } = layers;
+ const numberOfLayers = getLayers(layers[activeString], {}, state).length;
+ return {
+ activeTab,
+ isMobile: browser.is.small,
+ hasLocalStorage: util.browser.localStorage,
+ screenHeight: screenHeight,
+ isCompareMode: compare.active,
+ numberOfLayers
+ };
+}
+const mapDispatchToProps = dispatch => ({
+ onTabClick: str => {
+ dispatch(changeTab(str));
+ },
+ collapseExpandToggle: () => {
+ dispatch(toggleSidebarCollapse());
+ },
+ collapseSidebar: () => {
+ dispatch(collapseSidebar());
+ },
+ expandSidebar: () => {
+ dispatch(expandSidebar());
+ }
+});
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps
+)(Sidebar);
+
+Sidebar.defaultProps = {
+ maxHeight: 700,
+ visibleEvents: {}
+};
+Sidebar.propTypes = {
+ isMobile: PropTypes.bool,
+ hasLocalStorage: PropTypes.bool,
+ screenHeight: PropTypes.number,
+ screenWidth: PropTypes.number,
+ onTabClick: PropTypes.func,
+ numberOfLayers: PropTypes.number,
+ activeTab: PropTypes.string,
+ isCollapsed: PropTypes.bool,
+ isCompareMode: PropTypes.bool,
+ collapseSidebar: PropTypes.func,
+ collapseExpandToggle: PropTypes.func
+};
diff --git a/web/js/layers/util.js b/web/js/layers/util.js
index 8a078f6e8..dd39f5996 100644
--- a/web/js/layers/util.js
+++ b/web/js/layers/util.js
@@ -1,4 +1,9 @@
-import lodashEach from 'lodash/each';
+import {
+ findIndex as lodashFindIndex,
+ each as lodashEach,
+ get as lodashGet
+} from 'lodash';
+import update from 'immutability-helper';
export function addZoomLevel(config, models, ui, layer, zoomObj) {
var newObj = zoomObj;
diff --git a/web/js/main.js b/web/js/main.js
index 1d32be956..b74021743 100644
--- a/web/js/main.js
+++ b/web/js/main.js
@@ -4,8 +4,9 @@ import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
-import { createStore, applyMiddleware } from 'redux';
+import { createStore, applyMiddleware, compose } from 'redux';
import { each as lodashEach, debounce as lodashDebounce } from 'lodash';
+import { responsiveStoreEnhancer } from 'redux-responsive';
import { getMiddleware } from './combine-middleware';
import {
createReduxLocationActions,
@@ -89,7 +90,10 @@ const render = (config, parameters, legacyState) => {
const store = createStore(
reducersWithLocation,
getInitialState(models, config, parameters),
- applyMiddleware(...middleware)
+ compose(
+ responsiveStoreEnhancer,
+ applyMiddleware(...middleware)
+ )
);
lodashEach(models, function(component, key) {
if (component.load && !component.loaded) {
diff --git a/web/js/modules/browser/actions.js b/web/js/modules/browser/actions.js
new file mode 100644
index 000000000..9d06871ed
--- /dev/null
+++ b/web/js/modules/browser/actions.js
@@ -0,0 +1,9 @@
+import { SCREEN_RESIZE } from './constants';
+
+export function screenResize(width, height) {
+ return {
+ type: SCREEN_RESIZE,
+ screenWidth: width,
+ screenHeight: height
+ };
+}
diff --git a/web/js/modules/browser/constants.js b/web/js/modules/browser/constants.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/web/js/modules/browser/reducers.js b/web/js/modules/browser/reducers.js
new file mode 100644
index 000000000..46bee7304
--- /dev/null
+++ b/web/js/modules/browser/reducers.js
@@ -0,0 +1,18 @@
+import { assign as lodashAssign } from 'lodash';
+import { SCREEN_RESIZE } from './constants';
+
+// https://stackoverflow.com/a/39670754
+const initialState = {
+ screenWidth: typeof window === 'object' ? window.innerWidth : null,
+ screenHeight: typeof window === 'object' ? window.innerHeight : null
+};
+export function browserReducer(state = initialState, action) {
+ switch (action.type) {
+ case SCREEN_RESIZE:
+ return lodashAssign({}, state, {
+ screenWidth: action.screenWidth,
+ screenHeight: action.screenHeight
+ });
+ }
+ return state;
+}
diff --git a/web/js/modules/combine-reducers.js b/web/js/modules/combine-reducers.js
index 1f5cb2f60..624d798e7 100644
--- a/web/js/modules/combine-reducers.js
+++ b/web/js/modules/combine-reducers.js
@@ -1,22 +1,45 @@
import { combineReducers } from 'redux';
+import { createResponsiveStateReducer } from 'redux-responsive';
import { modalReducer, modalAboutPage } from './modal/reducers';
import legacyReducer from './migration/reducers';
import feedbackReducer from './feedback/reducers';
import projectionReducer from './projection/reducer';
+import sidebarReducer from './sidebar/reducers';
import { shortLink, linkReducer } from './link/reducers';
import {
notificationsRequest,
notificationsReducer
} from './notifications/reducers';
import { getProjInitialState } from './projection/util';
+import { compareReducer } from './compare/reducers';
+import {
+ layerReducer,
+ getInitialState as getLayersInitialState
+} from './layers/reducers';
+const responsiveStateReducer = createResponsiveStateReducer(
+ {
+ extraSmall: 500,
+ small: 740,
+ medium: 1000,
+ large: 1280,
+ extraLarge: 1400
+ },
+ {
+ extraFields: () => ({
+ screenWidth: window.innerWidth,
+ sreenHeight: window.innerHeight
+ })
+ }
+);
export function getInitialState(models, config, parameters) {
return {
parameters,
config,
models,
legacy: models,
- proj: getProjInitialState(config)
+ proj: getProjInitialState(config),
+ layers: getLayersInitialState(config)
};
}
const defaultReducer = (state = {}) => state;
@@ -30,6 +53,10 @@ const reducers = {
config: defaultReducer,
models: defaultReducer,
parameters: defaultReducer,
+ browser: responsiveStateReducer,
+ sidebar: sidebarReducer,
+ compare: compareReducer,
+ layers: layerReducer,
modalAboutPage,
shortLink,
notificationsRequest
diff --git a/web/js/modules/compare/actions.js b/web/js/modules/compare/actions.js
new file mode 100644
index 000000000..1e08a591e
--- /dev/null
+++ b/web/js/modules/compare/actions.js
@@ -0,0 +1,44 @@
+import {
+ CHANGE_STATE,
+ TOGGLE,
+ ACTIVATE,
+ DEACTIVATE,
+ CHANGE_VALUE,
+ CHANGE_MODE
+} from './constants';
+
+export function toggleActiveCompareState(str) {
+ return {
+ type: CHANGE_STATE,
+ stateStr: str
+ };
+}
+export function toggleCompare() {
+ return {
+ type: TOGGLE
+ };
+}
+
+export function activateCompare(isActive) {
+ return {
+ type: ACTIVATE
+ };
+}
+
+export function deactivateCompare(str) {
+ return {
+ type: DEACTIVATE
+ };
+}
+export function setNumber(num) {
+ return {
+ type: CHANGE_VALUE,
+ value: num
+ };
+}
+export function changeMode(str) {
+ return {
+ type: CHANGE_MODE,
+ mode: str
+ };
+}
diff --git a/web/js/modules/compare/constants.js b/web/js/modules/compare/constants.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/web/js/modules/compare/reducers.js b/web/js/modules/compare/reducers.js
new file mode 100644
index 000000000..56fee5963
--- /dev/null
+++ b/web/js/modules/compare/reducers.js
@@ -0,0 +1,45 @@
+import { assign as lodashAssign } from 'lodash';
+import {
+ CHANGE_STATE,
+ TOGGLE,
+ ACTIVATE,
+ DEACTIVATE,
+ CHANGE_VALUE,
+ CHANGE_MODE
+} from './constants';
+const initialState = {
+ active: false,
+ isActiveA: true,
+ mode: 'swipe',
+ value: 50
+};
+export function compareReducer(state = initialState, action) {
+ switch (action.type) {
+ case CHANGE_STATE:
+ return lodashAssign({}, state, {
+ isActiveA: action.stateStr === 'A'
+ });
+ case TOGGLE:
+ return lodashAssign({}, state, {
+ active: !state.active
+ });
+ case ACTIVATE:
+ return lodashAssign({}, state, {
+ active: true
+ });
+ case DEACTIVATE:
+ return lodashAssign({}, state, {
+ active: false
+ });
+ case CHANGE_MODE:
+ return lodashAssign({}, state, {
+ mode: action.mode,
+ value: 50
+ });
+ case CHANGE_VALUE:
+ return lodashAssign({}, state, {
+ value: action.value
+ });
+ }
+ return state;
+}
diff --git a/web/js/modules/layers/actions.js b/web/js/modules/layers/actions.js
new file mode 100644
index 000000000..91b395bd6
--- /dev/null
+++ b/web/js/modules/layers/actions.js
@@ -0,0 +1,58 @@
+import {
+ RESET_LAYERS,
+ ADD_LAYER,
+ INIT_SECOND_LAYER_GROUP,
+ REORDER_LAYER_GROUP,
+ TOGGLE_ACTIVE_STATE,
+ ON_LAYER_HOVER,
+ TOGGLE_LAYER_VISIBILITY,
+ REMOVE_LAYER
+} from './constants';
+
+export function addLayer(layerId) {
+ return {
+ type: ADD_LAYER,
+ layerId: layerId
+ };
+}
+export function resetLayers(stateStr) {
+ return {
+ type: RESET_LAYERS,
+ stateStr: stateStr || 'A'
+ };
+}
+export function initSecondLayerGroup() {
+ return {
+ type: INIT_SECOND_LAYER_GROUP
+ };
+}
+export function reorderLayers(layerArray) {
+ return {
+ type: REORDER_LAYER_GROUP,
+ layerArray: layerArray
+ };
+}
+export function toggleActiveState() {
+ return {
+ type: TOGGLE_ACTIVE_STATE
+ };
+}
+export function layerHover(id, isMouseOver) {
+ return {
+ type: ON_LAYER_HOVER,
+ id: id,
+ active: isMouseOver
+ };
+}
+export function toggleVisibility(id) {
+ return {
+ type: TOGGLE_LAYER_VISIBILITY,
+ id: id
+ };
+}
+export function removeLayer(id) {
+ return {
+ type: REMOVE_LAYER,
+ id: id
+ };
+}
diff --git a/web/js/modules/layers/constants.js b/web/js/modules/layers/constants.js
index e69de29bb..828ac1a85 100644
--- a/web/js/modules/layers/constants.js
+++ b/web/js/modules/layers/constants.js
@@ -0,0 +1,8 @@
+export const RESET_LAYERS = 'LAYERS/RESET_LAYERS_IN_LAYER_GROUP';
+export const ADD_LAYER = 'LAYERS/ADD_LAYER_TO_LAYER_GROUP';
+export const REORDER_LAYER_GROUP = 'LAYERS/REORDER_LAYERS_IN_LAYER_GROUP';
+export const INIT_SECOND_LAYER_GROUP = 'LAYERS/INIT_SECOND_LAYER_GROUP_FOR_AB';
+export const TOGGLE_ACTIVE_STATE = 'LAYERS/TOGGLE_ACTIVE_LAYER_STATE';
+export const ON_LAYER_HOVER = 'LAYERS/ON_LAYER_HOVER';
+export const TOGGLE_LAYER_VISIBILITY = 'LAYERS/TOGGLE_LAYER_VISIBILITY';
+export const REMOVE_LAYER = 'LAYERS/REMOVE_LAYER';
diff --git a/web/js/modules/layers/reducers.js b/web/js/modules/layers/reducers.js
new file mode 100644
index 000000000..887f0b6ca
--- /dev/null
+++ b/web/js/modules/layers/reducers.js
@@ -0,0 +1,77 @@
+import {
+ RESET_LAYERS,
+ TOGGLE_ACTIVE_STATE,
+ ADD_LAYER,
+ INIT_SECOND_LAYER_GROUP,
+ REORDER_LAYER_GROUP,
+ ON_LAYER_HOVER,
+ TOGGLE_LAYER_VISIBILITY,
+ REMOVE_LAYER
+} from './constants';
+import { resetLayers, addLayer } from './selectors';
+import { toggleVisibility, removeLayer } from './util';
+import { cloneDeep as lodashCloneDeep, assign as lodashAssign } from 'lodash';
+
+export const initialState = {
+ layersA: [],
+ layersB: [],
+ layersConfig: {},
+ activeString: 'A',
+ hoveredLayer: ''
+};
+export function getInitialState(config) {
+ return lodashAssign({}, initialState, {
+ layersA: resetLayers(config)
+ });
+}
+
+export function layerReducer(state = initialState, action) {
+ const layerGroupStr = 'layers' + state.activeString;
+ switch (action.type) {
+ case RESET_LAYERS:
+ if (
+ (action.stateStr && action.stateStr === 'B') ||
+ state.activeString === 'B'
+ ) {
+ return lodashAssign({}, state, {
+ layersB: resetLayers()
+ });
+ } else {
+ return lodashAssign({}, state, {
+ layersA: resetLayers()
+ });
+ }
+
+ case ADD_LAYER:
+ return lodashAssign({}, state, {
+ [layerGroupStr]: addLayer(action.id, state[layerGroupStr])
+ });
+ case INIT_SECOND_LAYER_GROUP:
+ if (state.layersB.length > 0) return state;
+ return lodashAssign({}, state, {
+ layersB: lodashCloneDeep(state.layersA)
+ });
+ case REORDER_LAYER_GROUP:
+ return lodashAssign({}, state, {
+ [layerGroupStr]: action.layerArray
+ });
+ case TOGGLE_ACTIVE_STATE:
+ return lodashAssign({}, state, {
+ activeString: state.activeString === 'A' ? 'B' : 'A'
+ });
+ case ON_LAYER_HOVER:
+ return lodashAssign({}, state, {
+ hoveredLayer: action.active ? action.id : ''
+ });
+ case TOGGLE_LAYER_VISIBILITY:
+ return lodashAssign({}, state, {
+ [layerGroupStr]: toggleVisibility(action.id, state[layerGroupStr])
+ });
+ case REMOVE_LAYER:
+ return lodashAssign({}, state, {
+ [layerGroupStr]: removeLayer(action.id, state[layerGroupStr]) // returns new object
+ });
+ default:
+ return state;
+ }
+}
diff --git a/web/js/modules/layers/selectors.js b/web/js/modules/layers/selectors.js
new file mode 100644
index 000000000..9f271434f
--- /dev/null
+++ b/web/js/modules/layers/selectors.js
@@ -0,0 +1,300 @@
+import {
+ each as lodashEach,
+ get as lodashGet,
+ filter as lodashFilter,
+ find as lodashFind,
+ cloneDeep as lodashCloneDeep,
+ isUndefined as lodashIsUndefined
+} from 'lodash';
+
+import util from '../../util/util';
+
+/**
+ * See if an array of layers has a subdaily
+ * product in it
+ * @param {Array} layers
+ */
+export function hasSubDaily(layers) {
+ if (layers && layers.length) {
+ for (var i = 0; i < layers.length; i++) {
+ if (layers[i].period === 'subdaily') {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+export function addLayer(id, spec, layers, config) {
+ if (
+ lodashFind(layers, {
+ id: id
+ })
+ ) {
+ return layers;
+ }
+ spec = spec || {};
+ var def = lodashCloneDeep(config.layers[id]);
+ if (!def) {
+ throw new Error('No such layer: ' + id);
+ }
+ def.visible = true;
+ if (!lodashIsUndefined(spec.visible)) {
+ def.visible = spec.visible;
+ } else if (!lodashIsUndefined(spec.hidden)) {
+ def.visible = !spec.hidden;
+ }
+ def.opacity = lodashIsUndefined(spec.opacity) ? 1.0 : spec.opacity;
+ if (def.group === 'overlays') {
+ layers.unshift(def);
+ } else {
+ layers.splice(layers, 0, def);
+ }
+ return layers;
+}
+export function resetLayers(config) {
+ let layers = [];
+ const startingLayers = lodashGet(config, 'defaults.startingLayers');
+ if (startingLayers) {
+ lodashEach(startingLayers, function(start) {
+ layers = addLayer(start.id, start, layers, config);
+ });
+ }
+ return layers;
+}
+export function getTitles(config, layerId, proj, state) {
+ try {
+ proj = proj || state.proj.id;
+ var title, subtitle, tags;
+ const forProj = lodashGet(config, `layers.${layerId}.projections.${proj}`);
+ if (forProj) {
+ title = forProj.title;
+ subtitle = forProj.subtitle;
+ tags = forProj.tags;
+ }
+ const forLayer = lodashGet(config, `layers.${layerId}`);
+ title = title || forLayer.title || '[' + layerId + ']';
+ subtitle = subtitle || forLayer.subtitle || '';
+ tags = tags || forLayer.tags || '';
+ return {
+ title: title,
+ subtitle: subtitle,
+ tags: tags
+ };
+ } catch (err) {
+ throw new Error(`error in layer ${layerId}: ${err}`);
+ }
+}
+export function getLayers(layers, spec, state) {
+ spec = spec || {};
+ var baselayers = forGroup('baselayers', spec, layers, state);
+ var overlays = forGroup('overlays', spec, layers, state);
+ if (spec.group === 'baselayers') {
+ return baselayers;
+ }
+ if (spec.group === 'overlays') {
+ return overlays;
+ }
+ if (spec.group === 'all') {
+ return {
+ baselayers: baselayers,
+ overlays: overlays
+ };
+ }
+ if (spec.group) {
+ throw new Error('Invalid layer group: ' + spec.group);
+ }
+ return baselayers.concat(overlays);
+}
+function forGroup(group, spec, activeLayers, state) {
+ spec = spec || {};
+ var projId = spec.proj || state.proj.id;
+ var results = [];
+ var defs = lodashFilter(activeLayers, {
+ group: group
+ });
+ lodashEach(defs, function(def) {
+ // Skip if this layer isn't available for the selected projection
+ if (!def.projections[projId] && projId !== 'all') {
+ return;
+ }
+ if (
+ spec.dynamic &&
+ !['subdaily', 'daily', 'monthly', 'yearly'].includes(def.period)
+ ) {
+ return;
+ }
+ if (spec.renderable && !self.isRenderable(def.id, activeLayers)) {
+ return;
+ }
+ if (spec.visible && !def.visible) {
+ return;
+ }
+ results.push(def);
+ });
+ if (spec.reverse) {
+ results = results.reverse();
+ }
+ return results;
+}
+export function available(id, date, layers, config) {
+ var range = dateRange(
+ {
+ layer: id
+ },
+ layers,
+ config
+ );
+
+ if (range) {
+ if (date < range.start || date > range.end) {
+ return false;
+ }
+ }
+ return true;
+}
+export function replaceSubGroup(layerId, nextLayerId, layers, subGroup) {
+ if (nextLayerId) {
+ return moveBefore(layerId, nextLayerId, layers);
+ } else {
+ return pushToBottom(layerId, layers);
+ }
+}
+function dateRange(spec, activeLayers, config) {
+ var layers = spec.layer
+ ? [
+ lodashFind(activeLayers, {
+ id: spec.layer
+ })
+ ]
+ : activeLayers;
+ var ignoreRange =
+ config.parameters &&
+ (config.parameters.debugGIBS || config.parameters.ignoreDateRange);
+ if (ignoreRange) {
+ return {
+ start: new Date(Date.UTC(1970, 0, 1)),
+ end: util.now()
+ };
+ }
+ var min = Number.MAX_VALUE;
+ var max = 0;
+ var range = false;
+ var maxDates = [];
+ lodashEach(layers, function(def) {
+ if (def) {
+ if (def.startDate) {
+ range = true;
+ var start = util.parseDateUTC(def.startDate).getTime();
+ min = Math.min(min, start);
+ }
+ // For now, we assume that any layer with an end date is
+ // an ongoing product unless it is marked as inactive.
+ if (def.futureLayer && def.endDate) {
+ range = true;
+ max = util.parseDateUTC(def.endDate).getTime();
+ maxDates.push(new Date(max));
+ } else if (def.inactive && def.endDate) {
+ range = true;
+ var end = util.parseDateUTC(def.endDate).getTime();
+ max = Math.max(max, end);
+ maxDates.push(new Date(max));
+ } else if (def.endDate) {
+ range = true;
+ max = util.now().getTime();
+ maxDates.push(new Date(max));
+ }
+ // If there is a start date but no end date, this is a
+ // product that is currently being created each day, set
+ // the max day to today.
+ if (def.futureLayer && def.futureTime && !def.endDate) {
+ // Calculate endDate + parsed futureTime from layer JSON
+ max = new Date();
+ var futureTime = def.futureTime;
+ var dateType = futureTime.slice(-1);
+ var dateInterval = futureTime.slice(0, -1);
+ if (dateType === 'D') {
+ max.setDate(max.getDate() + parseInt(dateInterval));
+ maxDates.push(new Date(max));
+ } else if (dateType === 'M') {
+ max.setMonth(max.getMonth() + parseInt(dateInterval));
+ maxDates.push(new Date(max));
+ } else if (dateType === 'Y') {
+ max.setYear(max.getYear() + parseInt(dateInterval));
+ maxDates.push(new Date(max));
+ }
+ } else if (def.startDate && !def.endDate) {
+ max = util.now().getTime();
+ maxDates.push(new Date(max));
+ }
+ }
+ });
+ if (range) {
+ if (max === 0) {
+ max = util.now().getTime();
+ maxDates.push(max);
+ }
+ var maxDate = Math.max.apply(max, maxDates);
+ return {
+ start: new Date(min),
+ end: new Date(maxDate)
+ };
+ }
+}
+function pushToBottom(id, activeLayersString) {
+ // activeLayersString = activeLayersString || self.activeLayers;
+ // var oldIndex = lodashFindIndex(self[activeLayersString], {
+ // id: id
+ // });
+ // if (oldIndex < 0) {
+ // throw new Error('Layer is not active: ' + id);
+ // }
+ // var def = self[activeLayersString][oldIndex];
+ // self[activeLayersString].splice(oldIndex, 1);
+ // if (def.group === 'baselayers') {
+ // self[activeLayersString].push(def);
+ // } else {
+ // self[activeLayersString].splice(split[activeLayersString] - 1, 0, def);
+ // }
+}
+
+function moveBefore(sourceId, targetId, activeLayersString) {
+ // activeLayersString = activeLayersString || self.activeLayers;
+ // var sourceIndex = lodashFindIndex(self[activeLayersString], {
+ // id: sourceId
+ // });
+ // if (sourceIndex < 0) {
+ // throw new Error('Layer is not active: ' + sourceId);
+ // }
+ // var sourceDef = self[activeLayersString][sourceIndex];
+ // var targetIndex = lodashFindIndex(self[activeLayersString], {
+ // id: targetId
+ // });
+ // if (targetIndex < 0) {
+ // throw new Error('Layer is not active: ' + targetId);
+ // }
+ // self[activeLayersString].splice(targetIndex, 0, sourceDef);
+ // if (sourceIndex > targetIndex) {
+ // sourceIndex++;
+ // }
+ // self[activeLayersString].splice(sourceIndex, 1);
+ // self.events.trigger('update', sourceDef, targetIndex);
+ // self.events.trigger('change');
+}
+export function getZotsForActiveLayers(config, models, ui) {
+ // var zotObj = {};
+ // var sources = config.sources;
+ // var proj = models.proj.selected.id;
+ // var layerGroupStr = models.layers.activeLayers;
+ // var layers = models.layers[layerGroupStr];
+ // var zoom = ui.map.selected.getView().getZoom();
+ // lodashEach(layers, layer => {
+ // if (layer.projections[proj]) {
+ // let overZoomValue = getZoomLevel(layer, zoom, proj, sources);
+ // if (overZoomValue) {
+ // zotObj[layer.id] = { value: overZoomValue };
+ // }
+ // }
+ // });
+ // return zotObj;
+}
diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.js
index d1d55d3c6..d325c13ba 100644
--- a/web/js/modules/layers/util.js
+++ b/web/js/modules/layers/util.js
@@ -1,4 +1,12 @@
-import { cloneDeep as lodashCloneDeep, get } from 'lodash';
+import {
+ cloneDeep as lodashCloneDeep,
+ get as lodashGet,
+ find as lodashFind,
+ findIndex as lodashFindIndex,
+ each as lodashEach
+} from 'lodash';
+
+import update from 'immutability-helper';
import util from '../../util/util';
export function getLayersParameterSetup(
@@ -23,10 +31,10 @@ export function getLayersParameterSetup(
return layerModelLoaded.active ? layerModelLoaded.active : initialState;
},
(currentItemState, state) => {
- const isActive = get(models, 'compare.active');
- const isCompareA = get(models, 'compare.isCompareA');
- const layersB = get(models, 'layers.activeB');
- const layersA = get(models, 'layers.active');
+ const isActive = lodashGet(models, 'compare.active');
+ const isCompareA = lodashGet(models, 'compare.isCompareA');
+ const layersB = lodashGet(models, 'layers.activeB');
+ const layersA = lodashGet(models, 'layers.active');
return !isActive && !isCompareA
? serializeLayers(layersB, models, 'activeB')
: serializeLayers(layersA, models, 'active');
@@ -39,8 +47,8 @@ export function getLayersParameterSetup(
return layerModelLoaded.activeB;
},
(currentItemState, state) => {
- const isActive = get(models, 'compare.active');
- const layersB = get(models, 'layers.activeB');
+ const isActive = lodashGet(models, 'compare.active');
+ const layersB = lodashGet(models, 'layers.activeB');
return isActive
? serializeLayers(layersB, models, 'activeB')
: undefined;
@@ -105,6 +113,7 @@ function serializeLayers(layers, models, groupStr) {
return util.appendAttributesForURL(item);
});
}
+
function getPermalinkManagementObject(
initialState,
stateKey,
@@ -123,3 +132,24 @@ function getPermalinkManagementObject(
}
};
}
+
+export function toggleVisibility(id, layers) {
+ var index = lodashFindIndex(layers, {
+ id: id
+ });
+ if (index === -1) {
+ throw new Error('Invalid layer ID: ' + id);
+ }
+ var visibility = !layers[index].visible;
+
+ return update(layers, { [index]: { visible: { $set: visibility } } });
+}
+export function removeLayer(id, layers) {
+ var index = lodashFindIndex(layers, {
+ id: id
+ });
+ if (index === -1) {
+ throw new Error('Invalid layer ID: ' + id);
+ }
+ return update(layers, { $splice: [[index, 1]] });
+}
diff --git a/web/js/modules/palettes/selectors.js b/web/js/modules/palettes/selectors.js
new file mode 100644
index 000000000..64e6a4c1f
--- /dev/null
+++ b/web/js/modules/palettes/selectors.js
@@ -0,0 +1,70 @@
+import { get as lodashGet, isUndefined as lodashIsUndefined } from 'lodash';
+import util from '../../util/util';
+
+export function getCustomPalette(config, id) {
+ var palette = lodashGet(config, `palettes.custom.${id}`);
+
+ if (!palette) {
+ throw new Error('Invalid palette: ' + id);
+ }
+ return palette;
+}
+/**
+ * Gets a single colormap (entries / legend combo)
+ *
+ *
+ * @method get
+ * @static
+ * @param str {string} The ID of the layer
+ * @param number {Number} The index of the colormap for this layer, default 0
+ * object.
+ * @return {object} object including the entries and legend
+ */
+self.get = function(layerId, index, activeGroupString, state) {
+ activeGroupString = activeGroupString || state.layers.activeString;
+ index = lodashIsUndefined(index) ? 0 : index;
+ const palette = lodashGet(state, `palettes.${activeGroupString}.${layerId}`);
+ if (palette) {
+ return palette.maps[index];
+ }
+ return getRenderedPalette(layerId, index);
+};
+export function getRenderedPalette(config, layerId, index) {
+ var name = lodashGet(config, `layers.${layerId}.palette.id`);
+ var palette = lodashGet(config, `palettes.rendered.${name}`);
+ if (!palette) {
+ throw new Error(name + ' Is not a rendered palette');
+ }
+ if (!lodashIsUndefined(index)) {
+ if (palette.maps) {
+ palette = palette.maps[index];
+ }
+ }
+ return palette;
+}
+export function loadCustom(config) {
+ return util.load.config(
+ config.palettes,
+ 'custom',
+ 'config/palettes-custom.json'
+ );
+}
+export function palettePromise(config, layerId, paletteId) {
+ return new Promise((resolve, reject) => {
+ if (config.palettes.rendered[paletteId]) {
+ resolve();
+ } else {
+ loadRenderedPalette(config, layerId).done(function(result) {
+ resolve(result);
+ });
+ }
+ });
+}
+function loadRenderedPalette(config, layerId) {
+ var layer = config.layers[layerId];
+ return util.load.config(
+ config.palettes.rendered,
+ layer.palette.id,
+ 'config/palettes/' + layer.palette.id + '.json'
+ );
+}
diff --git a/web/js/modules/palettes/util.js b/web/js/modules/palettes/util.js
new file mode 100644
index 000000000..8bd73bfc6
--- /dev/null
+++ b/web/js/modules/palettes/util.js
@@ -0,0 +1,80 @@
+import lodashEach from 'lodash/each';
+import util from '../../util/util';
+export function getCheckerboard() {
+ var size = 2;
+ var canvas = document.createElement('canvas');
+
+ canvas.width = size * 2;
+ canvas.height = size * 2;
+
+ var g = canvas.getContext('2d');
+
+ // g.fillStyle = "rgb(102, 102, 102)";
+ g.fillStyle = 'rgb(200, 200, 200)';
+ g.fillRect(0, 0, size, size);
+ g.fillRect(size, size, size, size);
+
+ // g.fillStyle = "rgb(153, 153, 153)";
+ g.fillStyle = 'rgb(240, 240, 240)';
+ g.fillRect(0, size, size, size);
+ g.fillRect(size, 0, size, size);
+
+ return g.createPattern(canvas, 'repeat');
+}
+export function palettesTranslate(source, target) {
+ var translation = [];
+ lodashEach(source, function(color, index) {
+ var sourcePercent = index / source.length;
+ var targetIndex = Math.floor(sourcePercent * target.length);
+ translation.push(target[targetIndex]);
+ });
+ return translation;
+}
+/**
+ * Redraw canvas with selected colormap
+ * @param {String} ctxStr | String of wanted cavnas
+ * @param {Object} checkerBoardPattern | Background for canvas threshold
+ * @param {Array} colors | array of color values
+ */
+export function drawPaletteOnCanvas(
+ ctx,
+ checkerBoardPattern,
+ colors,
+ width,
+ height
+) {
+ ctx.fillStyle = checkerBoardPattern;
+ ctx.fillRect(0, 0, width, height);
+
+ if (colors) {
+ var bins = colors.length;
+ var binWidth = width / bins;
+ var drawWidth = Math.ceil(binWidth);
+ colors.forEach((color, i) => {
+ ctx.fillStyle = util.hexToRGBA(color);
+ ctx.fillRect(Math.floor(binWidth * i), 0, drawWidth, height);
+ });
+ }
+}
+export function lookup(sourcePalette, targetPalette) {
+ var lookup = {};
+ lodashEach(sourcePalette.colors, function(sourceColor, index) {
+ var source =
+ parseInt(sourceColor.substring(0, 2), 16) +
+ ',' +
+ parseInt(sourceColor.substring(2, 4), 16) +
+ ',' +
+ parseInt(sourceColor.substring(4, 6), 16) +
+ ',' +
+ '255';
+ var targetColor = targetPalette.colors[index];
+ var target = {
+ r: parseInt(targetColor.substring(0, 2), 16),
+ g: parseInt(targetColor.substring(2, 4), 16),
+ b: parseInt(targetColor.substring(4, 6), 16),
+ a: 255
+ };
+ lookup[source] = target;
+ });
+ return lookup;
+}
diff --git a/web/js/modules/sidebar/actions.js b/web/js/modules/sidebar/actions.js
new file mode 100644
index 000000000..2b82d21fb
--- /dev/null
+++ b/web/js/modules/sidebar/actions.js
@@ -0,0 +1,30 @@
+import {
+ CHANGE_TAB,
+ TOGGLE_COLLAPSE,
+ COLLAPSE_SIDEBAR,
+ EXPAND_SIDEBAR
+} from './constants';
+
+export function changeTab(str) {
+ return {
+ type: CHANGE_TAB,
+ activeTab: str
+ };
+}
+export function toggleSidebarCollapse(str) {
+ return {
+ type: TOGGLE_COLLAPSE
+ };
+}
+
+export function collapseSidebar(str) {
+ return {
+ type: COLLAPSE_SIDEBAR
+ };
+}
+
+export function expandSidebar(str) {
+ return {
+ type: EXPAND_SIDEBAR
+ };
+}
diff --git a/web/js/modules/sidebar/constants.js b/web/js/modules/sidebar/constants.js
new file mode 100644
index 000000000..7a9c482f5
--- /dev/null
+++ b/web/js/modules/sidebar/constants.js
@@ -0,0 +1,5 @@
+export const CHANGE_TAB = 'CHANGE_ACTIVE_SIDEBAR_TAB';
+
+export const TOGGLE_COLLAPSE = 'TOGGLE_SIDEBAR_COLLAPSE_EXAPND';
+export const COLLAPSE_SIDEBAR = 'SIDEBAR_COLLAPSE_NOW';
+export const EXPAND_SIDEBAR = 'SIDEBAR_EXPAND_NOW';
diff --git a/web/js/modules/sidebar/reducers.js b/web/js/modules/sidebar/reducers.js
new file mode 100644
index 000000000..ec0c4c378
--- /dev/null
+++ b/web/js/modules/sidebar/reducers.js
@@ -0,0 +1,40 @@
+import {
+ CHANGE_TAB,
+ TOGGLE_COLLAPSE,
+ COLLAPSE_SIDEBAR,
+ EXPAND_SIDEBAR
+} from './constants';
+import { assign as lodashAssign } from 'lodash';
+import util from '../../util/util';
+
+const wasCallapseRequested = util.browser.localStorage
+ ? localStorage.getItem('sidebarState') === 'collapsed'
+ : false;
+export const sidebarState = {
+ isCollapsed: util.browser.small ? true : wasCallapseRequested || false,
+ wasCallapseRequested: wasCallapseRequested,
+ activeTab: 'layers'
+};
+
+export default function sidebarReducer(state = sidebarState, action) {
+ switch (action.type) {
+ case CHANGE_TAB:
+ return lodashAssign({}, state, {
+ activeTab: action.activeTab
+ });
+ case TOGGLE_COLLAPSE:
+ return lodashAssign({}, state, {
+ isCollapsed: !state.isCollapsed
+ });
+ case COLLAPSE_SIDEBAR:
+ return lodashAssign({}, state, {
+ isCollapsed: true
+ });
+ case EXPAND_SIDEBAR:
+ return lodashAssign({}, state, {
+ isCollapsed: false
+ });
+ default:
+ return state;
+ }
+}