Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Remove old vector style & palette files, begin redux vector styles

ZachTRice175beb63f6ea
diff --git a/web/js/combine-ui.js b/web/js/combine-ui.js
index 0a636b9a2..65dde9396 100644
--- a/web/js/combine-ui.js
+++ b/web/js/combine-ui.js
@@ -3,6 +3,10 @@ import { mapui } from './map/ui';
import { mapAnimate } from './map/animate';
import { dataUi } from './map/data/ui';
import naturalEventsUI from './map/natural-events/ui';
+
+// Vector Metadata UI
+import { vectorMetaUi } from './vector-metadata/ui';
+
/**
* Legacy UI Rendering
* @param {Object} models | Legacy Models Object
@@ -38,6 +42,7 @@ export function combineUi(models, config, MapMouseEvents, store) {
if (config.features.naturalEvents) {
ui.naturalEvents = naturalEventsUI(ui, config, store, models);
}
+ ui.vectorMeta = vectorMetaUi(models, ui, config);
registerMapMouseHandlers(ui.map.proj, MapMouseEvents);
// Sink all focus on inputs if click unhandled
$(document).click(function(event) {
diff --git a/web/js/components/layer/product-picker/measurement-row.js b/web/js/components/layer/product-picker/measurement-row.js
index 3de366f5b..a48f5b753 100644
--- a/web/js/components/layer/product-picker/measurement-row.js
+++ b/web/js/components/layer/product-picker/measurement-row.js
@@ -117,7 +117,7 @@ class LayerRow extends React.Component {
/>
);
}
- } else if (layer.title && layer.title.indexOf('Orbital Track') !== -1) {
+ } else if (layer && layer.title && layer.title.indexOf('Orbital Track') !== -1) {
// The following complex if statement is a placeholder
// for truncating the layer names, until the rest of
// the interface is implemented
diff --git a/web/js/components/layer/settings/settings.js b/web/js/components/layer/settings/settings.js
index d6346d3d4..b12b0f2e1 100644
--- a/web/js/components/layer/settings/settings.js
+++ b/web/js/components/layer/settings/settings.js
@@ -4,6 +4,7 @@ import { each as lodashEach } from 'lodash';
import { TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import { connect } from 'react-redux';
import Palette from './palette';
+import VectorStyle from './vector-styles';
import Opacity from './opacity';
import Threshold from './threshold';
import {
@@ -23,6 +24,10 @@ import {
setCustom,
clearCustom
} from '../../../modules/palettes/actions';
+
+import {
+ getVectorStyle
+} from '../../../modules/vector-styles/selectors';
import { setOpacity } from '../../../modules/layers/actions';
class LayerSettings extends React.Component {
@@ -117,6 +122,11 @@ class LayerSettings extends React.Component {
index={i}
paletteOrder={paletteOrder}
/>
+ <VectorStyle
+ activePalette={'default_style'}
+ layer={layer}
+ index={i}
+ />
</TabPane>
);
}
@@ -250,6 +260,9 @@ function mapStateToProps(state, ownProps) {
},
getPalette: (layerId, index) => {
return getPalette(layerId, index, groupName, state);
+ },
+ getVectorStyle: (layerId, index) => {
+ return getVectorStyle(layerId, index, groupName, state);
}
};
}
diff --git a/web/js/components/layer/settings/vector-styles.js b/web/js/components/layer/settings/vector-styles.js
index 9a14d6885..9352c07e8 100644
--- a/web/js/components/layer/settings/vector-styles.js
+++ b/web/js/components/layer/settings/vector-styles.js
@@ -29,9 +29,9 @@ class VectorStyleSelect extends React.Component {
}
/**
* Pass palette to model after selection
- * @param {String} id | custom Palette Id
+ * @param {String} id | custom VectorStyle Id
*/
- onChangePalette(id) {
+ onChangeVectorStyle(id) {
const { layer, clearCustom, setCustom, index } = this.props;
// Applying customs takes a while and
@@ -53,14 +53,14 @@ class VectorStyleSelect extends React.Component {
customLegend(id) {
const {
getDefaultLegend,
- getCustomPalette,
+ getCustomVectorStyle,
layer,
index
// palettesTranslate
} = this.props;
const { activeVectorStyle } = this.state;
var source = getDefaultLegend(layer.id, index);
- var target = getCustomPalette(id);
+ var target = getCustomVectorStyle(id);
var targetType =
target.colors.length === 1 ? 'classification' : 'continuous';
@@ -77,7 +77,7 @@ class VectorStyleSelect extends React.Component {
/**
* Render classification customs when there is only one
* Color in colormap
- * @param {Object} palette | Palette object
+ * @param {Object} palette | VectorStyle object
* @param {String} id | colormap Id
* @param {String} description | Colormap name
* @param {Boolean} isSelected | is this colormap active
@@ -95,7 +95,7 @@ class VectorStyleSelect extends React.Component {
id={'wv-palette-radio-' + id}
type="radio"
name="wv-palette-radio"
- onClick={() => this.onChangePalette(id)}
+ onClick={() => this.onChangeVectorStyle(id)}
/>
<label htmlFor={'wv-palette-radio-' + id}>
<span
@@ -142,7 +142,7 @@ VectorStyleSelect.propTypes = {
paletteOrder: PropTypes.array,
palettesTranslate: PropTypes.func,
getDefaultLegend: PropTypes.func,
- getCustomPalette: PropTypes.func,
+ getCustomVectorStyle: PropTypes.func,
canvas: PropTypes.object,
checkerBoard: PropTypes.object,
activeVectorStyle: PropTypes.string
diff --git a/web/js/components/sidebar/provider.js b/web/js/components/sidebar/provider.js
deleted file mode 100644
index 826b51546..000000000
--- a/web/js/components/sidebar/provider.js
+++ /dev/null
@@ -1,64 +0,0 @@
-import React from 'react';
-import lodashIsEqual from 'lodash/isEqual';
-import PropTypes from 'prop-types';
-
-export const SidebarContext = React.createContext();
-export class SidebarProvider extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- updateLayer: props.updateLayer,
- checkerBoardPattern: props.checkerBoardPattern,
- getAvailability: props.getAvailability,
- getNames: props.getNames,
- palettePromise: props.palettePromise,
- getPalette: props.getPalette,
- vectorStylePromise: props.vectorStylePromise,
- getVectorStyle: props.getVectorStyle,
- runningLayers: props.runningLayers,
- getLegend: props.getLegend,
- zotsObject: props.zotsObject,
- replaceSubGroup: props.replaceSubGroup,
- isMobile: props.isMobile,
- projection: props.projection
- };
- }
- componentWillReceiveProps(props) {
- if (this.state.runningLayers !== props.runningLayers) {
- this.setState({ runningLayers: props.runningLayers });
- }
- if (!lodashIsEqual(this.state.zotsObject, props.zotsObject)) {
- this.setState({ zotsObject: props.zotsObject });
- }
- if (this.state.isMobile !== props.isMobile) {
- this.setState({ isMobile: props.isMobile });
- }
- if (this.state.projection !== props.projection) {
- this.setState({ projection: props.projection });
- }
- }
- render() {
- return (
- <SidebarContext.Provider value={this.state}>
- {this.props.children};
- </SidebarContext.Provider>
- );
- }
-}
-SidebarProvider.propTypes = {
- children: PropTypes.array,
- isMobile: PropTypes.bool,
- replaceSubGroup: PropTypes.func,
- updateLayer: PropTypes.func,
- checkerBoardPattern: PropTypes.object,
- getAvailability: PropTypes.func,
- getNames: PropTypes.func,
- palettePromise: PropTypes.func,
- getPalette: PropTypes.func,
- vectorStylePromise: PropTypes.func,
- getVectorStyle: PropTypes.func,
- runningLayers: PropTypes.object,
- getLegend: PropTypes.func,
- zotsObject: PropTypes.object,
- projection: PropTypes.string
-};
diff --git a/web/js/components/sidebar/sidebar.js b/web/js/components/sidebar/sidebar.js
deleted file mode 100644
index b1c9f9b65..000000000
--- a/web/js/components/sidebar/sidebar.js
+++ /dev/null
@@ -1,368 +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,
- vectorStylePromise,
- updateLayer,
- getNames,
- getAvailability,
- getLegend,
- replaceSubGroup,
- getDataSelectionCounts,
- selectDataProduct,
- toggleMode,
- addLayers,
- getDataSelectionSize,
- changeCompareMode,
- checkerBoardPattern,
- compareFeature,
- tabTypes,
- getPalette,
- getVectorStyle
- } = this.props;
- const wheelCallBack = util.browser.chrome ? util.preventPinch : null;
- return (
- <Provider
- palettePromise={palettePromise}
- getPalette={getPalette}
- vectorStylePromise={vectorStylePromise}
- getVectorStyle={getVectorStyle}
- 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,
- vectorStylePromise: PropTypes.func,
- getVectorStyle: 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/layers/options.js b/web/js/layers/options.js
deleted file mode 100644
index 4dc8c3e5c..000000000
--- a/web/js/layers/options.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import React from 'react';
-import { render } from 'react-dom';
-import styles from '../styles/styles';
-import { palettesTranslate, getCheckerboard } from '../styles/util';
-import LayerSettings from '../components/layer/settings/settings';
-import Promise from 'bluebird';
-
-export function layersOptions(models, ui, config) {
- var self = {};
- self.layerId = null;
- var canvas, checkerboard;
-
- var init = function() {
- canvas = document.createElement('canvas');
- canvas.width = 120;
- canvas.height = 10;
- checkerboard = getCheckerboard();
-
- if (config.features.customPalettes) {
- styles.loadCustom(config).done(loaded);
- } else {
- loaded();
- }
- };
- self.close = function(timeout) {
- timeout = timeout || 0;
- self.reactComponent.setState({ isOpen: false });
- self.layerId = null;
- return new Promise(resolve => {
- setTimeout(() => {
- resolve();
- }, timeout);
- });
- };
- /**
- * Open react component with new layer info
- * @param {Object} layer | Active layer object
- */
- self.createNewLayer = function(layer) {
- if (layer.id === self.layerId) {
- self.close();
- return;
- }
- const timeout = layer.id ? 300 : 0;
- self.close(timeout).then(() => {
- const names = models.layers.getTitles(layer.id);
- self.layerId = layer.id;
- self.reactComponent.setState({
- layer: layer,
- title: names.title,
- palettedAllowed: models.palettes.allowed(layer.id),
- isOpen: true
- });
- });
- };
- /**
- * Mount component once customs Config is loaded
- */
- var loaded = function() {
- self.reactComponent = render(
- <LayerSettings
- setCustom={models.palettes.setCustom}
- clearCustom={models.palettes.clearCustom}
- getLegends={models.palettes.getLegends}
- getPalette={models.palettes.get}
- getLegend={models.palettes.getLegend}
- getDefaultLegend={models.palettes.getDefaultLegend}
- getCustomPalette={models.palettes.getCustomPalette}
- setRange={models.palettes.setRange}
- palettedAllowed={false}
- canvas={canvas}
- isOpen={false}
- checkerboard={checkerboard}
- setOpacity={models.layers.setOpacity}
- customPalettesIsActive={!!config.features.customPalettes}
- palettesTranslate={palettesTranslate}
- paletteOrder={config.paletteOrder}
- close={self.close}
- />,
- document.getElementById('layer-settings-modal')
- );
- models.layers.events.on('remove', onLayerRemoved);
- models.proj.events.on('change', self.close);
- ui.sidebar.events.on('selectTab', self.close);
- if (models.compare) models.compare.events.on('change', self.close);
- };
-
- var onLayerRemoved = function(removedLayer) {
- if (self.layerId === removedLayer.id) {
- self.close();
- }
- };
- init();
- return self;
-}
diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.js
index 791ded4dd..b3109d861 100644
--- a/web/js/map/layerbuilder.js
+++ b/web/js/map/layerbuilder.js
@@ -1,5 +1,5 @@
import util from '../util/util';
-import styles from '../styles/styles';
+import vectorStyles from '../modules/vector-styles/util';
import OlTileGridWMTS from 'ol/tilegrid/WMTS';
import OlSourceWMTS from 'ol/source/WMTS';
import OlSourceTileWMS from 'ol/source/TileWMS';
@@ -80,6 +80,12 @@ export function mapLayerBuilder(models, config, cache, mapUi, store) {
});
}
} else if (def.type === 'vector') {
+ // Add vector layer style to config.rendered object
+ console.log(config);
+ // if (config.layers[def.id] && config.layers[def.id].vectorStyle) {
+ // vectorStyles.loadRenderedVectorStyle(config, def.id);
+ // }
+
layer = createLayerVector(def, options, null, state);
if (
proj.id === 'geographic' &&
@@ -377,155 +383,155 @@ export function mapLayerBuilder(models, config, cache, mapUi, store) {
source: sourceOptions
});
- if (config.vectorStyles && def.vectorStyle && def.vectorStyle.id) {
- var styleFunction;
- var vectorStyles = config.vectorStyles.rendered;
- var vectorStyle = def.vectorStyle.id;
- var glStyle = vectorStyles[vectorStyle];
- if (glStyle === undefined) {
- glStyle = vectorStyles['OrbitTracks'];
- }
- styleFunction = stylefunction(layer, glStyle, 'default_style');
-
- $(document).ready(function() {
- function getVals() {
- // Get slider values
- var parent = this.parentNode;
- var slides = parent.getElementsByTagName('input');
- var slide1 = parseFloat(slides[0].value);
- var slide2 = parseFloat(slides[1].value);
- // Neither slider will clip the other, so make sure we determine which is larger
- if (slide1 > slide2) { var tmp = slide2; slide2 = slide1; slide1 = tmp; }
-
- var displayElement = parent.getElementsByClassName('rangeValues')[0];
- displayElement.innerHTML = slide1 + ' - ' + slide2;
- }
-
- window.onload = function() {
- styleFunction = stylefunction(layer, glStyle, 'default_style');
- // Initialize Sliders
- var sliderSections = document.getElementsByClassName('range-slider');
- for (var x = 0; x < sliderSections.length; x++) {
- var sliders = sliderSections[x].getElementsByTagName('input');
- for (var y = 0; y < sliders.length; y++) {
- if (sliders[y].type === 'range') {
- sliders[y].oninput = getVals;
- // Manually trigger event first time to display values
- sliders[y].oninput();
- }
- }
- }
-
- let confidenceMinFilter = document.getElementById('confidenceMinFilter');
- let confidenceMaxFilter = document.getElementById('confidenceMaxFilter');
-
- document.getElementById('confidenceMinFilterLabel').innerHTML = confidenceMinFilter.value;
- document.getElementById('confidenceMaxFilterLabel').innerHTML = confidenceMaxFilter.value;
- };
-
- // TODO: Add check for date change and re-apply
- // TODO: Change this on chang to target the controls
- $(document).on('change', function(e) {
- glStyle = vectorStyles[vectorStyle];
- if (glStyle.name === 'FIRMS') {
- styleFunction = stylefunction(layer, glStyle, 'default_style');
-
- // FIRMS Style based on Confidence / FRP
- if (document.getElementById('frpCheckbox').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'MODIS_Fire_Points_FRP');
- } else if (document.getElementById('confidenceCheckbox').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'MODIS_Fire_Points_Confidence');
- } else {
- styleFunction = stylefunction(layer, glStyle, 'default_style');
- }
-
- // FIRMS Filters
- let confidenceMinFilter = document.getElementById('confidenceMinFilter');
- let confidenceMaxFilter = document.getElementById('confidenceMaxFilter');
-
- document.getElementById('confidenceMinFilterLabel').innerHTML = confidenceMinFilter.value;
- document.getElementById('confidenceMaxFilterLabel').innerHTML = confidenceMaxFilter.value;
-
- // Filter by a feature
- layer.setStyle(function(feature, resolution) {
- if (feature.get('CONFIDENCE') >= confidenceMinFilter.value && feature.get('CONFIDENCE') <= confidenceMaxFilter.value) {
- return styleFunction(feature, resolution);
- }
- });
- } else if (glStyle.name === 'Orbit Tracks') {
- if (document.getElementById('orbit-track-controls_yellow1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'yellow1');
- } else if (document.getElementById('orbit-track-controls_yellow2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'yellow2');
- } else if (document.getElementById('orbit-track-controls_orange1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'orange1');
- } else if (document.getElementById('orbit-track-controls_orange2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'orange2');
- } else if (document.getElementById('orbit-track-controls_orange3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'orange3');
- } else if (document.getElementById('orbit-track-controls_red1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'red1');
- } else if (document.getElementById('orbit-track-controls_red2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'red2');
- } else if (document.getElementById('orbit-track-controls_red3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'red3');
- } else if (document.getElementById('orbit-track-controls_pink1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'pink1');
- } else if (document.getElementById('orbit-track-controls_pink2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'pink2');
- } else if (document.getElementById('orbit-track-controls_pink3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'pink3');
- } else if (document.getElementById('orbit-track-controls_pink4').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'pink4');
- } else if (document.getElementById('orbit-track-controls_pink5').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'pink5');
- } else if (document.getElementById('orbit-track-controls_purple1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'purple1');
- } else if (document.getElementById('orbit-track-controls_purple2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'purple2');
- } else if (document.getElementById('orbit-track-controls_purple3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'purple3');
- } else if (document.getElementById('orbit-track-controls_blue1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue1');
- } else if (document.getElementById('orbit-track-controls_blue2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue2');
- } else if (document.getElementById('orbit-track-controls_blue3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue3');
- } else if (document.getElementById('orbit-track-controls_blue4').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue4');
- } else if (document.getElementById('orbit-track-controls_blue5').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue5');
- } else if (document.getElementById('orbit-track-controls_blue6').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'blue6');
- } else if (document.getElementById('orbit-track-controls_brown1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'brown1');
- } else if (document.getElementById('orbit-track-controls_brown2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'brown2');
- } else if (document.getElementById('orbit-track-controls_green1').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'green1');
- } else if (document.getElementById('orbit-track-controls_green2').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'green2');
- } else if (document.getElementById('orbit-track-controls_green3').checked === true) {
- styleFunction = stylefunction(layer, glStyle, 'green3');
- } else {
- styleFunction = stylefunction(layer, glStyle, 'default_style');
- }
-
- // Filter time by 5 mins
- layer.setStyle(function(feature, resolution) {
- var minute;
- var minutes = feature.get('label');
- if (minutes) {
- minute = minutes.split(':');
- }
- if ((minute && minute[1] % 5 === 0) || feature.type_ === 'LineString') {
- return styleFunction(feature, resolution);
- }
- });
- }
- });
- });
- }
+ // if (config.vectorStyles && def.vectorStyle && def.vectorStyle.id) {
+ // var styleFunction;
+ // var vectorStyles = config.vectorStyles.rendered;
+ // var vectorStyle = def.vectorStyle.id;
+ // var glStyle = vectorStyles[vectorStyle];
+ // if (glStyle === undefined) {
+ // glStyle = vectorStyles['OrbitTracks'];
+ // }
+ // styleFunction = stylefunction(layer, glStyle, 'default_style');
+
+ // $(document).ready(function() {
+ // function getVals() {
+ // // Get slider values
+ // var parent = this.parentNode;
+ // var slides = parent.getElementsByTagName('input');
+ // var slide1 = parseFloat(slides[0].value);
+ // var slide2 = parseFloat(slides[1].value);
+ // // Neither slider will clip the other, so make sure we determine which is larger
+ // if (slide1 > slide2) { var tmp = slide2; slide2 = slide1; slide1 = tmp; }
+
+ // var displayElement = parent.getElementsByClassName('rangeValues')[0];
+ // displayElement.innerHTML = slide1 + ' - ' + slide2;
+ // }
+
+ // window.onload = function() {
+ // styleFunction = stylefunction(layer, glStyle, 'default_style');
+ // // Initialize Sliders
+ // var sliderSections = document.getElementsByClassName('range-slider');
+ // for (var x = 0; x < sliderSections.length; x++) {
+ // var sliders = sliderSections[x].getElementsByTagName('input');
+ // for (var y = 0; y < sliders.length; y++) {
+ // if (sliders[y].type === 'range') {
+ // sliders[y].oninput = getVals;
+ // // Manually trigger event first time to display values
+ // sliders[y].oninput();
+ // }
+ // }
+ // }
+
+ // let confidenceMinFilter = document.getElementById('confidenceMinFilter');
+ // let confidenceMaxFilter = document.getElementById('confidenceMaxFilter');
+
+ // document.getElementById('confidenceMinFilterLabel').innerHTML = confidenceMinFilter.value;
+ // document.getElementById('confidenceMaxFilterLabel').innerHTML = confidenceMaxFilter.value;
+ // };
+
+ // // TODO: Add check for date change and re-apply
+ // // TODO: Change this on chang to target the controls
+ // $(document).on('change', function(e) {
+ // glStyle = vectorStyles[vectorStyle];
+ // if (glStyle.name === 'FIRMS') {
+ // styleFunction = stylefunction(layer, glStyle, 'default_style');
+
+ // // FIRMS Style based on Confidence / FRP
+ // if (document.getElementById('frpCheckbox').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'MODIS_Fire_Points_FRP');
+ // } else if (document.getElementById('confidenceCheckbox').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'MODIS_Fire_Points_Confidence');
+ // } else {
+ // styleFunction = stylefunction(layer, glStyle, 'default_style');
+ // }
+
+ // // FIRMS Filters
+ // let confidenceMinFilter = document.getElementById('confidenceMinFilter');
+ // let confidenceMaxFilter = document.getElementById('confidenceMaxFilter');
+
+ // document.getElementById('confidenceMinFilterLabel').innerHTML = confidenceMinFilter.value;
+ // document.getElementById('confidenceMaxFilterLabel').innerHTML = confidenceMaxFilter.value;
+
+ // // Filter by a feature
+ // layer.setStyle(function(feature, resolution) {
+ // if (feature.get('CONFIDENCE') >= confidenceMinFilter.value && feature.get('CONFIDENCE') <= confidenceMaxFilter.value) {
+ // return styleFunction(feature, resolution);
+ // }
+ // });
+ // } else if (glStyle.name === 'Orbit Tracks') {
+ // if (document.getElementById('orbit-track-controls_yellow1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'yellow1');
+ // } else if (document.getElementById('orbit-track-controls_yellow2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'yellow2');
+ // } else if (document.getElementById('orbit-track-controls_orange1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'orange1');
+ // } else if (document.getElementById('orbit-track-controls_orange2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'orange2');
+ // } else if (document.getElementById('orbit-track-controls_orange3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'orange3');
+ // } else if (document.getElementById('orbit-track-controls_red1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'red1');
+ // } else if (document.getElementById('orbit-track-controls_red2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'red2');
+ // } else if (document.getElementById('orbit-track-controls_red3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'red3');
+ // } else if (document.getElementById('orbit-track-controls_pink1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'pink1');
+ // } else if (document.getElementById('orbit-track-controls_pink2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'pink2');
+ // } else if (document.getElementById('orbit-track-controls_pink3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'pink3');
+ // } else if (document.getElementById('orbit-track-controls_pink4').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'pink4');
+ // } else if (document.getElementById('orbit-track-controls_pink5').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'pink5');
+ // } else if (document.getElementById('orbit-track-controls_purple1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'purple1');
+ // } else if (document.getElementById('orbit-track-controls_purple2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'purple2');
+ // } else if (document.getElementById('orbit-track-controls_purple3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'purple3');
+ // } else if (document.getElementById('orbit-track-controls_blue1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue1');
+ // } else if (document.getElementById('orbit-track-controls_blue2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue2');
+ // } else if (document.getElementById('orbit-track-controls_blue3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue3');
+ // } else if (document.getElementById('orbit-track-controls_blue4').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue4');
+ // } else if (document.getElementById('orbit-track-controls_blue5').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue5');
+ // } else if (document.getElementById('orbit-track-controls_blue6').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'blue6');
+ // } else if (document.getElementById('orbit-track-controls_brown1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'brown1');
+ // } else if (document.getElementById('orbit-track-controls_brown2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'brown2');
+ // } else if (document.getElementById('orbit-track-controls_green1').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'green1');
+ // } else if (document.getElementById('orbit-track-controls_green2').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'green2');
+ // } else if (document.getElementById('orbit-track-controls_green3').checked === true) {
+ // styleFunction = stylefunction(layer, glStyle, 'green3');
+ // } else {
+ // styleFunction = stylefunction(layer, glStyle, 'default_style');
+ // }
+
+ // // Filter time by 5 mins
+ // layer.setStyle(function(feature, resolution) {
+ // var minute;
+ // var minutes = feature.get('label');
+ // if (minutes) {
+ // minute = minutes.split(':');
+ // }
+ // if ((minute && minute[1] % 5 === 0) || feature.type_ === 'LineString') {
+ // return styleFunction(feature, resolution);
+ // }
+ // });
+ // }
+ // });
+ // });
+ // }
return layer;
};
diff --git a/web/js/modules/combine-reducers.js b/web/js/modules/combine-reducers.js
index 80c579abb..3349e1e16 100644
--- a/web/js/modules/combine-reducers.js
+++ b/web/js/modules/combine-reducers.js
@@ -30,6 +30,7 @@ import {
} from './date/reducers';
import { animationReducer } from './animation/reducers';
import { paletteReducer, getInitialPaletteState } from './palettes/reducers';
+import { vectorStyleReducer, getInitialVectorStyleState } from './vector-styles/reducers';
import dataDownloadReducer from './data/reducers';
import { get as lodashGet } from 'lodash';
@@ -79,7 +80,8 @@ export function getInitialState(models, config, parameters) {
requestedEvents: eventRequestResponse(eventsIgnoreArray),
requestedEventSources: eventRequestResponse(eventsIgnoreArray),
requestedEventCategories: eventRequestResponse(eventsIgnoreArray),
- palettes: getInitialPaletteState(config)
+ palettes: getInitialPaletteState(config),
+ vectorStyles: getInitialVectorStyleState(config)
};
}
const defaultReducer = (state = {}) => state;
@@ -99,6 +101,7 @@ const reducers = {
events: eventsReducer,
data: dataDownloadReducer,
palettes: paletteReducer,
+ vectorStyles: vectorStyleReducer,
tour: tourReducer,
map: mapReducer,
animation: animationReducer,
diff --git a/web/js/modules/vector-styles/actions.js b/web/js/modules/vector-styles/actions.js
new file mode 100644
index 000000000..c96b185a1
--- /dev/null
+++ b/web/js/modules/vector-styles/actions.js
@@ -0,0 +1,123 @@
+import { requestAction } from '../core/actions';
+import {
+ REQUEST_VECTORSTYLE,
+ SET_RANGE_AND_SQUASH,
+ CLEAR_CUSTOM,
+ SET_CUSTOM,
+ LOADED_CUSTOM_VECTORSTYLES
+} from './constants';
+import {
+ setRange as setRangeSelector,
+ setCustom as setCustomSelector,
+ clearCustom as clearCustomSelector
+} from './selectors';
+
+/**
+ * Request vectorStyle using core request utility
+ *
+ * @param {String} id | Layer Id
+ */
+export function requestVectorStyle(id) {
+ return (dispatch, getState) => {
+ const config = getState().config;
+ var layer = config.layers[id];
+ const vectorStyleID = layer.vectorStyle.id;
+ const location = 'config/vectorStyles/' + vectorStyleID + '.json';
+ return requestAction(
+ dispatch,
+ REQUEST_VECTORSTYLE,
+ location,
+ 'application/json',
+ vectorStyleID
+ );
+ };
+}
+
+/**
+ * @param {String} layerId
+ * @param {Object} props | contains min max and squash attributes
+ * @param {Number} index | VectorStyle index value for multi-vectorStyled layers
+ * @param {String} groupName | layer group string
+ */
+export function setRangeAndSquash(layerId, props, index, groupName) {
+ return (dispatch, getState) => {
+ const state = getState();
+ const newActiveVectorStylesObj = setRangeSelector(
+ layerId,
+ props,
+ index,
+ state.vectorStyles[groupName],
+ state
+ );
+ dispatch({
+ type: SET_RANGE_AND_SQUASH,
+ groupName: groupName,
+ activeString: groupName,
+ layerId,
+ vectorStyles: newActiveVectorStylesObj,
+ props
+ });
+ };
+}
+/**
+ * Action to set custom vectorStyle
+ *
+ * @param {String} layerId
+ * @param {String} vectorStyleId
+ * @param {Number} index | VectorStyle index value for multi-vectorStyled layers
+ * @param {String} groupName | layer group string
+ */
+export function setCustom(layerId, vectorStyleId, index, groupName) {
+ return (dispatch, getState) => {
+ const state = getState();
+ const newActiveVectorStylesObj = setCustomSelector(
+ layerId,
+ vectorStyleId,
+ index,
+ groupName,
+ state
+ );
+ dispatch({
+ type: SET_CUSTOM,
+ layerId: layerId,
+ vectorStyleId: vectorStyleId,
+ groupName: groupName,
+ activeString: groupName,
+ vectorStyles: newActiveVectorStylesObj
+ });
+ };
+}
+/**
+ * Action to remove custom vectorStyle
+ *
+ * @param {String} layerId
+ * @param {Number} index | VectorStyle index value for multi-vectorStyled layers
+ * @param {String} groupName | layer group string
+ */
+export function clearCustom(layerId, index, groupName) {
+ return (dispatch, getState) => {
+ const { vectorStyles } = getState();
+ const newActiveVectorStylesObj = clearCustomSelector(
+ layerId,
+ index,
+ vectorStyles[groupName]
+ );
+
+ dispatch({
+ type: CLEAR_CUSTOM,
+ groupName: groupName,
+ vectorStyles: newActiveVectorStylesObj
+ });
+ };
+}
+/**
+ * Action signifying custom vectorStyles have been loaded
+ *
+ * @param {Object} customs | Custom VectorStyles from Config
+ */
+export function loadedCustomVectorStyles(customs) {
+ return {
+ type: LOADED_CUSTOM_VECTORSTYLES,
+ custom: customs
+ };
+}
diff --git a/web/js/modules/vector-styles/constants.js b/web/js/modules/vector-styles/constants.js
new file mode 100644
index 000000000..ec221134f
--- /dev/null
+++ b/web/js/modules/vector-styles/constants.js
@@ -0,0 +1,10 @@
+export const REQUEST_VECTORSTYLE = 'VECTORSTYLES/REQUEST_VECTORSTYLE';
+export const REQUEST_VECTORSTYLE_START = 'VECTORSTYLES/REQUEST_VECTORSTYLE_START';
+export const REQUEST_VECTORSTYLE_SUCCESS = 'VECTORSTYLES/REQUEST_VECTORSTYLE_SUCCESS';
+export const REQUEST_VECTORSTYLE_FAILURE = 'VECTORSTYLES/REQUEST_VECTORSTYLE_FAILURE';
+
+export const VECTORSTYLE_CHANGE = 'VECTORSTYLES/CHANGE_OF_ACTIVE_VECTORSTYLE';
+export const SET_RANGE_AND_SQUASH = 'VECTORSTYLES/SET_RANGE_AND_SQUASH';
+export const CLEAR_CUSTOM = 'VECTORSTYLES/CLEAR_CUSTOM';
+export const SET_CUSTOM = 'VECTORSTYLES/SET_CUSTOM';
+export const LOADED_CUSTOM_VECTORSTYLES = 'VECTORSTYLES/LOADED_CUSTOM_VECTORSTYLES';
diff --git a/web/js/modules/vector-styles/reducers.js b/web/js/modules/vector-styles/reducers.js
new file mode 100644
index 000000000..dc8a76ba3
--- /dev/null
+++ b/web/js/modules/vector-styles/reducers.js
@@ -0,0 +1,61 @@
+import { assign as lodashAssign, get as lodashGet } from 'lodash';
+import {
+ REQUEST_VECTORSTYLE_SUCCESS,
+ SET_CUSTOM,
+ REQUEST_VECTORSTYLE_START,
+ SET_RANGE_AND_SQUASH,
+ LOADED_CUSTOM_VECTORSTYLES
+} from './constants';
+import update from 'immutability-helper';
+import util from '../../util/util';
+const browser = util.browser;
+export const defaultVectorStyleState = {
+ rendered: {},
+ custom: {},
+ active: {},
+ activeB: {},
+ isLoading: {},
+ supported: !(browser.ie || !browser.webWorkers || !browser.cors)
+};
+export function getInitialVectorStyleState(config) {
+ const rendered = lodashGet(config, 'vectorStyles.rendered') || {};
+ const custom = lodashGet(config, 'vectorStyles.custom') || {};
+ return lodashAssign({}, defaultVectorStyleState, {
+ rendered,
+ custom
+ });
+}
+
+export function vectorStyleReducer(state = defaultVectorStyleState, action) {
+ const groupName = action.groupName || 'active';
+ switch (action.type) {
+ case REQUEST_VECTORSTYLE_START:
+ return lodashAssign({}, state, {
+ isLoading: update(state.isLoading, {
+ [action.id]: { $set: true }
+ })
+ });
+ case REQUEST_VECTORSTYLE_SUCCESS:
+ let isLoading = update(state.isLoading, { $unset: [action.id] });
+ return lodashAssign({}, state, {
+ rendered: lodashAssign({}, state.rendered, {
+ [action.id]: action.response
+ }),
+ isLoading
+ });
+ case SET_RANGE_AND_SQUASH:
+ return lodashAssign({}, state, {
+ [groupName]: action.vectorStyles
+ });
+ case SET_CUSTOM:
+ return lodashAssign({}, state, {
+ [groupName]: action.vectorStyles
+ });
+ case LOADED_CUSTOM_VECTORSTYLES:
+ return lodashAssign({}, state, {
+ custom: action.custom
+ });
+ default:
+ return state;
+ }
+}
diff --git a/web/js/modules/vector-styles/selectors.js b/web/js/modules/vector-styles/selectors.js
new file mode 100644
index 000000000..5e37cf890
--- /dev/null
+++ b/web/js/modules/vector-styles/selectors.js
@@ -0,0 +1,342 @@
+import {
+ get as lodashGet,
+ isUndefined as lodashIsUndefined,
+ each as lodashEach,
+ parseInt as lodashParseInt,
+ cloneDeep as lodashCloneDeep
+} from 'lodash';
+import { getMinValue, getMaxValue } from './util';
+import update from 'immutability-helper';
+
+/**
+ * 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
+ */
+export function getVectorStyle(layerId, index, groupStr, state) {
+ groupStr = groupStr || state.compare.activeString;
+ index = lodashIsUndefined(index) ? 0 : index;
+ const renderedVectorStyle = lodashGet(
+ state,
+ `vectorStyles.rendered.${layerId}.maps.${index}`
+ );
+ const customVectorStyle = lodashGet(
+ state,
+ `vectorStyles.${groupStr}.${layerId}.maps.${index}`
+ );
+
+ if (customVectorStyle) {
+ return customVectorStyle;
+ }
+ if (renderedVectorStyle) {
+ return renderedVectorStyle;
+ }
+ return getRenderedVectorStyle(layerId, index, state);
+}
+
+export function getRenderedVectorStyle(layerId, index, state) {
+ const { config, vectorStyles } = state;
+ var name = lodashGet(config, `layers.${layerId}.vectorStyle.id`);
+ var vectorStyle = vectorStyles.rendered[name];
+ if (!vectorStyle) {
+ throw new Error(name + ' Is not a rendered vectorStyle');
+ }
+ if (!lodashIsUndefined(index)) {
+ if (vectorStyle.maps) {
+ vectorStyle = vectorStyle.maps[index];
+ }
+ }
+ return vectorStyle;
+}
+
+export function getLegends(layerId, groupName, state) {
+ var legends = [];
+ var count = getCount(layerId, state);
+ for (var i = 0; i < count; i++) {
+ legends.push(getLegend(layerId, i, groupName, state));
+ }
+ return legends;
+}
+/**
+ * Gets the legend of a colormap
+ *
+ *
+ * @method getLegend
+ * @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 of the legend
+ */
+export function getLegend(layerId, index, groupStr, state) {
+ var value = getVectorStyle(layerId, index, groupStr, state);
+ return value.legend || value.entries;
+}
+export function getCount(layerId, state) {
+ const renderedVectorStyle = getRenderedVectorStyle(layerId, undefined, state);
+ if (renderedVectorStyle && renderedVectorStyle.maps) {
+ return renderedVectorStyle.maps.length;
+ } else {
+ return 0;
+ }
+}
+/**
+ * Gets the legend of a colormap
+ *
+ *
+ * @method getDefaultLegend
+ * @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 of the legend
+ */
+export function getDefaultLegend(layerId, index, state) {
+ var vectorStyle = getRenderedVectorStyle(layerId, index, state);
+ return vectorStyle.legend || vectorStyle.entries || {};
+}
+
+export function getCustomVectorStyle(vectorStyleId, customsVectorStyleConfig) {
+ var vectorStyle = customsVectorStyleConfig[vectorStyleId];
+ if (!vectorStyle) {
+ throw new Error('Invalid vectorStyle: ' + vectorStyleId);
+ }
+ return vectorStyle;
+}
+var useLookup = function(layerId, vectorStylesObj, state) {
+ var use = false;
+ var active = vectorStylesObj[layerId].maps;
+
+ lodashEach(active, function(vectorStyle, index) {
+ if (vectorStyle.custom) {
+ use = true;
+ return false;
+ }
+ var rendered = getRenderedVectorStyle(layerId, index, state);
+ if (vectorStyle.type !== 'classification') {
+ if (vectorStyle.min <= 0) {
+ delete vectorStyle.min;
+ }
+ if (vectorStyle.max >= rendered.entries.values.length) {
+ delete vectorStyle.max;
+ }
+ if (!lodashIsUndefined(vectorStyle.min) || !lodashIsUndefined(vectorStyle.max)) {
+ use = true;
+ return false;
+ }
+ }
+ });
+ return use;
+};
+// Looks up options/colormaps/layer.xml colormap entry
+export function getLookup(layerId, groupstr, state) {
+ groupstr = groupstr || state.compare.activeString;
+ return state.vectorStyles[groupstr][layerId].lookup;
+}
+var updateLookup = function(layerId, vectorStylesObj, state) {
+ let newVectorStyles = vectorStylesObj;
+ if (!useLookup(layerId, newVectorStyles, state)) {
+ delete newVectorStyles[layerId];
+ return newVectorStyles;
+ }
+ var lookup = {};
+ var active = newVectorStyles[layerId].maps;
+ lodashEach(active, function(vectorStyle, index) {
+ var oldLegend = vectorStyle.legend;
+ var entries = vectorStyle.entries;
+ var legend = {
+ colors: [],
+ minLabel: oldLegend.minLabel,
+ maxLabel: oldLegend.maxLabel,
+ tooltips: oldLegend.tooltips,
+ units: oldLegend.units,
+ type: entries.type,
+ title: entries.title,
+ id: oldLegend.id
+ };
+ var source = entries.colors;
+ var target = vectorStyle.custom
+ ? getCustomVectorStyle(vectorStyle.custom, state.vectorStyles.custom).colors
+ : source;
+
+ var min = vectorStyle.min || 0;
+ var max = vectorStyle.max || source.length;
+
+ var sourceCount = source.length;
+ var targetCount = target.length;
+ lodashEach(source, function(color, index) {
+ var targetColor;
+ if (index < min || index > max) {
+ targetColor = '00000000';
+ } else {
+ var sourcePercent, targetIndex;
+ if (vectorStyle.squash) {
+ sourcePercent = (index - min) / (max - min);
+ if (index === max) {
+ sourcePercent = 1.0;
+ }
+ targetIndex = Math.floor(sourcePercent * targetCount);
+ if (targetIndex >= targetCount) {
+ targetIndex = targetCount - 1;
+ }
+ } else {
+ sourcePercent = index / sourceCount;
+ targetIndex = Math.floor(sourcePercent * targetCount);
+ }
+ targetColor = target[targetIndex];
+ }
+ legend.colors.push(targetColor);
+ var lookupSource =
+ lodashParseInt(color.substring(0, 2), 16) +
+ ',' +
+ lodashParseInt(color.substring(2, 4), 16) +
+ ',' +
+ lodashParseInt(color.substring(4, 6), 16) +
+ ',' +
+ lodashParseInt(color.substring(6, 8), 16);
+ var lookupTarget = {
+ r: lodashParseInt(targetColor.substring(0, 2), 16),
+ g: lodashParseInt(targetColor.substring(2, 4), 16),
+ b: lodashParseInt(targetColor.substring(4, 6), 16),
+ a: lodashParseInt(targetColor.substring(6, 8), 16)
+ };
+ lookup[lookupSource] = lookupTarget;
+ });
+
+ newVectorStyles = update(newVectorStyles, {
+ [layerId]: {
+ maps: { [index]: { legend: { $set: legend } } }
+ }
+ });
+ });
+ return update(newVectorStyles, { [layerId]: { lookup: { $set: lookup } } });
+};
+
+export function findIndex(layerId, type, value, index, groupStr, state) {
+ index = index || 0;
+ var values = getVectorStyle(layerId, index, groupStr, state).entries.values;
+ var result;
+ lodashEach(values, function(check, index) {
+ var min = getMinValue(check);
+ var max = getMaxValue(check);
+ if (type === 'min' && value === min) {
+ result = index;
+ return false;
+ }
+ if (type === 'max' && value === max) {
+ result = index;
+ return false;
+ }
+ });
+ return result;
+}
+export function setCustom(layerId, vectorStyleId, index, groupName, state) {
+ const { config, vectorStyles } = state;
+ if (!config.layers[layerId]) {
+ throw new Error('Invalid layer: ' + layerId);
+ }
+ let newVectorStyles = prepare(layerId, vectorStyles[groupName], state);
+ index = lodashIsUndefined(index) ? 0 : index;
+ var active = newVectorStyles[layerId];
+ var vectorStyle = active.maps[index];
+ if (vectorStyle.custom === vectorStyleId) {
+ return;
+ }
+ vectorStyle.custom = vectorStyleId;
+ return updateLookup(layerId, newVectorStyles, state);
+}
+export function getKey(layerId, groupStr, state) {
+ groupStr = groupStr || state.compare.activeString;
+ if (!isActive(layerId, groupStr, state)) {
+ return '';
+ }
+ var def = getVectorStyle(layerId, undefined, groupStr, state);
+ var keys = [];
+ if (def.custom) {
+ keys.push('vectorStyle=' + def.custom);
+ }
+ if (def.min) {
+ keys.push('min=' + def.min);
+ }
+ if (def.max) {
+ keys.push('max=' + def.max);
+ }
+ if (def.squash) {
+ keys.push('squash');
+ }
+ return keys.join(',');
+}
+export function isActive(layerId, group, state) {
+ group = group || state.compare.activeString;
+ return state.vectorStyles[group][layerId];
+}
+export function setRange(layerId, props, index, vectorStyles, state) {
+ let min = props.min;
+ let max = props.max;
+ let squash = props.squash;
+ let newVectorStyles = prepare(layerId, vectorStyles, state);
+ index = lodashIsUndefined(index) ? 0 : index;
+ if (min === 0) {
+ min = undefined;
+ }
+ const legend = getVectorStyle(layerId, index, undefined, state);
+ if (
+ legend.entries &&
+ legend.entries.values &&
+ max === legend.entries.values.length - 1
+ ) {
+ max = undefined;
+ }
+
+ // Merge custom vectorStyle props with correct colormap
+ newVectorStyles = update(newVectorStyles, {
+ [layerId]: {
+ maps: {
+ [index]: {
+ $merge: {
+ max,
+ min,
+ squash
+ }
+ }
+ }
+ }
+ });
+
+ return updateLookup(layerId, newVectorStyles, state);
+}
+export function clearCustom(layerId, index, vectorStyles) {
+ index = lodashIsUndefined(index) ? 0 : index;
+ var active = vectorStyles[layerId];
+ if (!active) {
+ return vectorStyles;
+ }
+ var vectorStyle = active.maps[index];
+ if (!vectorStyle.custom) {
+ return vectorStyles;
+ }
+ return update(vectorStyles, { layerId: { maps: { $unset: ['custom'] } } }); // remove custom key
+}
+var prepare = function(layerId, vectorStylesObj, state) {
+ var newVectorStyles = lodashCloneDeep(vectorStylesObj);
+ if (!newVectorStyles[layerId]) newVectorStyles[layerId] = {};
+ var active = newVectorStyles[layerId];
+ active.maps = active.maps || [];
+ lodashEach(getRenderedVectorStyle(layerId, undefined, state).maps, function(
+ vectorStyle,
+ index
+ ) {
+ if (!active.maps[index]) {
+ newVectorStyles = update(newVectorStyles, {
+ [layerId]: { maps: { [index]: { $set: vectorStyle } } }
+ });
+ }
+ });
+ return newVectorStyles;
+};
diff --git a/web/js/modules/vector-styles/util.js b/web/js/modules/vector-styles/util.js
new file mode 100644
index 000000000..5d8270c34
--- /dev/null
+++ b/web/js/modules/vector-styles/util.js
@@ -0,0 +1,236 @@
+import update from 'immutability-helper';
+import {
+ each as lodashEach,
+ find as lodashFind,
+ assign as lodashAssign
+} from 'lodash';
+import {
+ setCustom as setCustomSelector,
+ getCount,
+ setRange as setRangeSelector,
+ findIndex as findVectorStyleExtremeIndex
+} from './selectors';
+import util from '../../util/util';
+
+export function loadRenderedVectorStyle(config, layerId) {
+ var layer = config.layers[layerId];
+ return util.load.config(config.vectorStyles.rendered,
+ layer.vectorStyle.id, 'config/vectorstyles/' + layer.vectorStyle.id + '.json');
+}
+// export function loadCustom(config) {
+// return util.load.config(
+// config.vectorStyles,
+// 'custom',
+// 'config/vectorStyles-custom.json'
+// );
+// }
+
+export function parseVectorStyles(state, errors, config) {
+ if (state.vectorStyles) {
+ var parts = state.vectorStyles.split('~');
+ lodashEach(parts, function(part) {
+ var items = part.split(',');
+ var layerId = items[0];
+ var vectorStyleId = items[1];
+ if (!config.layers[layerId]) {
+ errors.push({
+ message: 'Invalid layer for vectorStyle ' + vectorStyleId + ': ' + layerId
+ });
+ } else if (!config.layers[layerId].vectorStyle) {
+ errors.push({
+ message: 'Layer ' + layerId + ' does not ' + 'support vectorStyles'
+ });
+ } else {
+ var layer = lodashFind(state.l, {
+ id: layerId
+ });
+ if (layer) {
+ layer.attributes.push({
+ id: 'vectorStyle',
+ value: vectorStyleId
+ });
+ } else {
+ errors.push({
+ message: 'Layer ' + layerId + ' is not ' + 'active'
+ });
+ }
+ }
+ });
+ delete state.vectorStyles;
+ }
+}
+
+// export function getVectorStyleAttributeArray(layerId, vectorStyles, state) {
+// const count = getCount(layerId, state);
+// const DEFAULT_OBJ = { isActive: false, value: undefined };
+// let palObj = lodashAssign({}, { key: 'custom', array: [] }, DEFAULT_OBJ);
+// let minObj = lodashAssign({}, { key: 'min', array: [] }, DEFAULT_OBJ);
+// let maxObj = lodashAssign({}, { key: 'max', array: [] }, DEFAULT_OBJ);
+// let squashObj = lodashAssign({}, { key: 'squash', array: [] }, DEFAULT_OBJ);
+// let attrArray = [];
+// for (var i = 0; i < count; i++) {
+// let vectorStyleDef = vectorStyles[layerId].maps[i];
+// let entryLength = vectorStyleDef.entries.values.length;
+// let maxValue = vectorStyleDef.max
+// ? vectorStyleDef.entries.values[vectorStyleDef.max || entryLength]
+// : undefined;
+// let minValue = vectorStyleDef.min
+// ? vectorStyleDef.entries.values[vectorStyleDef.min || 0]
+// : undefined;
+// palObj = createVectorStyleAttributeObject(
+// vectorStyleDef,
+// vectorStyleDef.custom,
+// palObj,
+// count
+// );
+// maxObj = createVectorStyleAttributeObject(vectorStyleDef, maxValue, maxObj, count);
+// minObj = createVectorStyleAttributeObject(vectorStyleDef, minValue, minObj, count);
+
+// squashObj = createVectorStyleAttributeObject(
+// vectorStyleDef,
+// true,
+// squashObj,
+// count
+// );
+// }
+
+// [palObj, minObj, maxObj, squashObj].forEach(obj => {
+// if (obj.isActive) {
+// attrArray.push({
+// id: obj.key === 'custom' ? 'vectorStyle' : obj.key,
+// value: obj.value
+// });
+// }
+// });
+// return attrArray;
+// }
+// const createVectorStyleAttributeObject = function(def, value, attrObj, count) {
+// const key = attrObj.key;
+// const attrArray = attrObj.array;
+// let hasAtLeastOnePair = attrObj.isActive;
+// value = isArray(value) ? value.join(',') : value;
+// if (def[key] && value) {
+// attrArray.push(value);
+// hasAtLeastOnePair = true;
+// } else if (count > 1) {
+// attrArray.push('');
+// }
+// return lodashAssign({}, attrObj, {
+// array: attrArray,
+// isActive: hasAtLeastOnePair,
+// value: attrArray.join(';')
+// });
+// };
+export function loadVectorStyles(permlinkState, state) {
+ var stateArray = [{ stateStr: 'l', groupStr: 'active' }];
+ if (permlinkState.l1) {
+ stateArray = [
+ { stateStr: 'l', groupStr: 'active' },
+ { stateStr: 'l1', groupStr: 'activeB' }
+ ];
+ }
+ lodashEach(stateArray, stateObj => {
+ lodashEach(state.layers[stateObj.groupStr], function(layerDef) {
+ var layerId = layerDef.id;
+ var min = [];
+ var max = [];
+ var squash = [];
+ var count = 0;
+ if (layerDef.custom) {
+ lodashEach(layerDef.custom, function(value, index) {
+ try {
+ let newVectorStyles = setCustomSelector(
+ layerId,
+ value,
+ index,
+ stateObj.groupStr,
+ state
+ );
+ state = update(state, {
+ vectorStyles: { [stateObj.groupStr]: { $set: newVectorStyles } }
+ });
+ } catch (error) {
+ console.warn(' Invalid vectorStyle: ' + value);
+ }
+ });
+ }
+ if (layerDef.min) {
+ lodashEach(layerDef.min, function(value, index) {
+ try {
+ min.push(
+ findVectorStyleExtremeIndex(
+ layerId,
+ 'min',
+ value,
+ index,
+ stateObj.groupStr,
+ state
+ )
+ );
+ } catch (error) {
+ console.warn('Unable to set min: ' + value);
+ }
+ });
+ }
+ if (layerDef.max) {
+ lodashEach(layerDef.max, function(value, index) {
+ try {
+ max.push(
+ findVectorStyleExtremeIndex(
+ layerId,
+ 'max',
+ value,
+ index,
+ stateObj.groupStr,
+ state
+ )
+ );
+ } catch (error) {
+ console.warn('Unable to set max index: ' + value);
+ }
+ });
+ }
+ if (layerDef.squash) {
+ squash = layerDef.squash;
+ }
+
+ if (min.length > 0 || max.length > 0) {
+ count = getCount(layerId, state);
+ for (var i = 0; i < count; i++) {
+ var vmin = min.length > 0 ? min[i] : undefined;
+ var vmax = max.length > 0 ? max[i] : undefined;
+ var vsquash = squash.length > 0 ? squash[i] : undefined;
+ let props = { min: vmin, max: vmax, squash: vsquash };
+ let newVectorStyles = setRangeSelector(
+ layerId,
+ props,
+ i,
+ state.vectorStyles[stateObj.groupStr],
+ state
+ );
+ state = update(state, {
+ vectorStyles: { [stateObj.groupStr]: { $set: newVectorStyles } }
+ });
+ }
+ }
+ });
+ });
+ return state;
+}
+export function mapLocationToVectorStyleState(
+ parameters,
+ stateFromLocation,
+ state,
+ config
+) {
+ if (parameters.l1 || parameters.l) {
+ stateFromLocation = loadVectorStyles(
+ parameters,
+ lodashAssign({}, stateFromLocation, {
+ vectorStyles: state.vectorStyles,
+ config
+ })
+ );
+ }
+ return stateFromLocation;
+}
diff --git a/web/js/sidebar/ui.js b/web/js/sidebar/ui.js
deleted file mode 100644
index f70637511..000000000
--- a/web/js/sidebar/ui.js
+++ /dev/null
@@ -1,417 +0,0 @@
-import 'jquery-ui-bundle/jquery-ui';
-import lodashFind from 'lodash/find';
-import lodashDebounce from 'lodash/debounce';
-import util from '../util/util';
-import Sidebar from '../components/sidebar/sidebar';
-import React from 'react';
-import ReactDOM from 'react-dom';
-import { getCompareObjects } from '../compare/util';
-import { getCheckerboard } from '../styles/util';
-import { layersInfo } from '../layers/info';
-import { getZotsForActiveLayers } from '../layers/util';
-import { timelineDataHightlight } from '../date/util';
-import wvui from '../ui/ui';
-import googleTagManager from 'googleTagManager';
-
-export function sidebarUi(models, config, ui) {
- var isCollapsed = false;
- var activeTab = 'layers';
- var self = {};
- var model = models.layers;
- var compareObj = {};
- var compareModeType = 'swipe';
-
- self.events = util.events();
-
- var init = function() {
- self.reactComponent = ReactDOM.render(
- React.createElement(Sidebar, getInitialProps()),
- document.getElementById('wv-sidebar')
- );
-
- var debounceUpdateData = lodashDebounce(updateData, 300, { leading: true });
- var debounceUpdateEventsList = lodashDebounce(updateEventsList, 300, {
- leading: true,
- trailing: true
- });
- var layerAdd = function(layer) {
- if (!ui.naturalEvents.selecting) {
- updateLayers();
- }
- };
-
- // Set Event Listeners
- if (models.data) {
- models.data.events
- .on('activate', () => {
- self.selectTab('download');
- debounceUpdateData();
- })
- .on('productSelect', onProductSelect)
- .on('layerUpdate', debounceUpdateData)
- .on('granuleSelect', debounceUpdateData)
- .on('granuleUnselect', debounceUpdateData);
- }
- models.layers.events
- .on('add', layerAdd)
- .on('remove', updateLayers)
- .on('modal', val => {
- self.reactComponent.setState({
- modalOpen: val
- });
- })
- .on('update', updateLayers);
-
- models.palettes.events
- .on('set-custom', updateLayers)
- .on('clear-custom', updateLayers)
- .on('range', updateLayers)
- .on('update', updateLayers);
- if (models.naturalEvents) {
- models.naturalEvents.events
- .on('activate', () => self.selectTab('events'))
- .on('list-change', debounceUpdateEventsList)
- .on('selection-done', updateLayers)
- .on('selected-event', selected => {
- self.reactComponent.setState({ selectedEvent: selected });
- });
- }
- if (models.compare) {
- models.compare.events
- .on('toggle', () => {
- updateState('isCompareMode');
- updateState('layerObjects');
- updateState('layers');
- })
- .on('toggle-state', () => {
- updateState('isCompareA');
- updateData();
- });
- }
- models.date.events.on('select', updateLayers);
- if (models.proj) {
- models.proj.events.on('select', updateLayers).on('select', () => {
- self.reactComponent.setState({ projection: models.proj.selected.id });
- });
- }
- models.map.events.on('data-running', runningLayers => {
- self.reactComponent.setState({ runningLayers: runningLayers });
- });
- models.compare.events.on('mode', () => {
- self.reactComponent.setState({ comparisonType: models.compare.mode });
- });
- $(window).resize(resize);
- ui.map.events.on(
- 'zooming',
- lodashDebounce(() => {
- updateState('zotsObject', getZotsForActiveLayers(config, models, ui));
- }, 300)
- );
- };
- self.renderEvents = function() {
- self.reactComponent.setState({
- eventsData: models.naturalEvents.data,
- selectEvent: ui.naturalEvents.selectEvent,
- deselectEvent: ui.naturalEvents.deselectEvent,
- filterEventList: ui.naturalEvents.filterEventList
- });
- };
- var getInitialProps = function() {
- var compareModel;
- activeTab =
- models.naturalEvents && models.naturalEvents.active
- ? 'events'
- : models.data && models.data.active
- ? 'download'
- : 'layers';
- if (config.features.compare) {
- compareModel = models.compare;
- if (models.compare.active) {
- compareObj = getCompareObjects(models);
- compareModeType = compareModel.mode;
- }
- }
- return {
- activeTab: activeTab,
- isCompareMode:
- compareModel && compareModel.active ? compareModel.active : false,
- isCollapsed: isCollapsed,
- layers: model.get({ group: 'all' }),
- onTabClick: self.selectTab,
- toggleSidebar: toggleSidebar,
- toggleLayerVisibility: toggleLayerVisibility,
- compareFeature: config.features.compare,
- tabTypes: getActiveTabs(),
- getNames: model.getTitles,
- firstDateObject: compareObj.a,
- secondDateObject: compareObj.b,
- getAvailability: getAvailability,
- toggleComparisonObject: toggleComparisonObject,
- toggleMode: toggleComparisonMode,
- isCompareA: compareModel && compareModel.isCompareA,
- updateLayer: updateLayer,
- addLayers: onAddLayerCLick,
- comparisonType: compareModeType,
- changeCompareMode: compareModel ? compareModel.setMode : null,
- checkerBoardPattern: getCheckerboard(),
- palettePromise: models.palettes.palettePromise,
- vectorStylePromise: models.vectorStyles.vectorStylePromise,
- getPalette: models.palettes.get,
- getVectorStyle: models.vectorStyles.get,
- getLegend: models.palettes.getLegends,
- replaceSubGroup: model.replaceSubGroup,
- runningLayers: null,
- selectedDataProduct: models.data ? models.data.selectedProduct : null,
- isMobile: util.browser.small,
- localStorage: util.browser.localStorage,
- zotsObject: getZotsForActiveLayers(config, models, ui),
- eventsData: { sources: [], events: [] },
- visibleEvents: { all: true },
- filterEventList: null,
- selectEvent: null,
- deselectEvent: null,
- projection:
- models.proj && models.proj.selected.id
- ? models.proj.selected.id
- : 'geographic',
- selectedEvent:
- models.naturalEvents && models.naturalEvents.selected
- ? models.naturalEvents.selected
- : {},
- getDataSelectionCounts: models.data
- ? models.data.getSelectionCounts
- : null,
- selectDataProduct: models.data ? models.data.selectProduct : null,
- showListAllButton: true,
- getDataSelectionSize: models.data ? models.data.getSelectionSize : null,
- onGetData: null,
- showDataUnavailableReason: null
- };
- };
- var updateEventsList = function(visibleEvents, showListAll) {
- self.reactComponent.setState({
- visibleEvents: visibleEvents,
- showListAllButton: showListAll
- });
- };
- var updateData = function() {
- self.reactComponent.setState({
- dataDownloadObject: models.data.groupByProducts(),
- onGetData: ui.data.showDownloadList,
- showDataUnavailableReason: ui.data.showUnavailableReason
- });
- };
- /**
- * Update layer when something happens (Event listeners)
- */
- var updateLayers = function() {
- if (models.compare && models.compare.active) {
- let compareObj = getCompareObjects(models);
- return self.reactComponent.setState({
- firstDateObject: compareObj.a,
- secondDateObject: compareObj.b,
- zotsObject: getZotsForActiveLayers(config, models, ui)
- });
- } else {
- self.reactComponent.setState({
- layers: models.layers.get(
- { group: 'all', proj: models.proj.selected.id },
- models.layers[models.layers.activeLayers]
- ),
- zotsObject: getZotsForActiveLayers(config, models, ui)
- });
- }
- };
- var onProductSelect = function(product) {
- self.reactComponent.setState({ selectedDataProduct: product });
- };
- var getAvailability = function(id, date, groupStr) {
- return model.available(id, date, model[groupStr]);
- };
- /**
- * Update collapse state based on window width on resize
- */
- var resize = function() {
- var state = self.reactComponent.state;
- var isMobile = state.isMobile;
- if (!isMobile && util.browser.small) {
- if (models.compare.active) toggleComparisonMode();
- self.reactComponent.setState({
- isMobile: true,
- isCollapsed: true
- });
- } else if (isMobile && !util.browser.small) {
- self.reactComponent.setState({
- isMobile: false,
- isCollapsed: state.isCollapsedRequested
- });
- }
- self.reactComponent.setState({ windowHeight: window.innerHeight });
- };
- var toggleComparisonObject = function() {
- models.compare.toggleState();
- };
- var onAddLayerCLick = function() {
- ui.addModal.open();
- };
-
- /**
- * Toggle A|B and init layer and date values if not already created
- */
- var toggleComparisonMode = function() {
- if (!models.layers.activeB || !models.date.selectedB) {
- if (!models.date.selectedB) {
- models.date.initCompare();
- }
- if (!models.layers.activeB) {
- models.layers.initCompare();
- }
- }
- models.compare.toggle();
- };
- var getActiveTabs = function() {
- const features = config.features;
- return {
- download: features.dataDownload,
- layers: true,
- events: features.naturalEvents
- };
- };
- /**
- * Update react component state
- * @param {String} type | State key to update
- * @param {Object} value
- */
- var updateState = function(type, value) {
- switch (type) {
- case 'isCollapsed':
- return self.reactComponent.setState({ isCollapsed: isCollapsed });
- case 'activeTab':
- return self.reactComponent.setState({ activeTab: activeTab });
- case 'layers':
- return self.reactComponent.setState({
- layers: models.layers.get(
- { group: 'all', proj: 'all' },
- models.layers[models.layers.activeLayers]
- )
- });
- case 'isCompareMode':
- return self.reactComponent.setState({
- isCompareMode: models.compare ? models.compare.active : false
- });
- case 'isCompareA': {
- return self.reactComponent.setState({
- isCompareA: models.compare ? models.compare.isCompareA : true
- });
- }
- case 'zotsObject':
- return self.reactComponent.setState({ zotsObject: value });
- case 'layerObjects':
- compareObj = getCompareObjects(models);
- return self.reactComponent.setState({
- firstDateObject: compareObj.a,
- secondDateObject: compareObj.b
- });
- }
- };
- /**
- * Force Timeline expand
- */
- self.expandNow = function() {
- isCollapsed = false;
- updateState('isCollapsed');
- };
- /**
- * Toggle sidebar collapsed state
- */
- var toggleSidebar = function() {
- isCollapsed = !isCollapsed;
- updateState('isCollapsed');
- };
- /**
- * Select a tab
- * @param {String} tab | Tab to activate
- */
- self.selectTab = function(tab) {
- if (activeTab === tab) return;
- activeTab = tab;
- wvui.close();
- self.events.trigger('selectTab', tab);
- updateState('activeTab');
- };
- /**
- * Trigger correct callback based on layer event
- * @param {String} layerId
- * @param {String} typeOfUpdate | Type of Layer event
- * @param {Boolean} value | Value related to type of event
- */
- var updateLayer = function(layerId, typeOfUpdate, value) {
- var layer;
- var layerGroupString = models.layers.activeLayers;
- var isCompareMode = models.compare && models.compare.active;
-
- switch (typeOfUpdate) {
- case 'remove':
- models.layers.remove(layerId, layerGroupString);
- break;
- case 'add':
- models.layers.add(layerId, {}, layerGroupString);
- break;
- case 'visibility':
- models.layers.toggleVisibility(layerId, layerGroupString);
- updateState(getStateType(isCompareMode));
- break;
- case 'info':
- googleTagManager.pushEvent({
- event: 'sidebar_layer_info'
- });
- let $infoDialog = $('#wv-layers-info-dialog');
- ui.layerSettingsModal.close();
- if (
- $infoDialog.attr('data-layer') !== layerId ||
- $infoDialog.length === 0
- ) {
- layer = lodashFind(models.layers[layerGroupString], { id: layerId });
- layersInfo(config, models, layer);
- } else {
- wvui.close();
- }
-
- break;
- case 'options':
- googleTagManager.pushEvent({
- event: 'sidebar_layer_options'
- });
- wvui.close();
- layer = lodashFind(models.layers[layerGroupString], { id: layerId });
- ui.layerSettingsModal.createNewLayer(layer);
- break;
- case 'hover':
- timelineDataHightlight(layerId, value);
- break;
- default:
- updateState(getStateType(isCompareMode));
- }
- };
- var getStateType = function(isCompareActive) {
- return isCompareActive ? 'layers' : 'layerObjects';
- };
- /**
- * Update visibility of layer (on eye click)
- * @param {String} layerId
- * @param {Boolean} isVisible
- */
- var toggleLayerVisibility = function(layerId, isVisible) {
- var layerGroupString = models.layers.activeLayers;
- models.layers.setVisibility(layerId, isVisible, layerGroupString);
- // Update correct layer object
- if (layerGroupString === 'active') {
- updateState('layers');
- } else {
- updateState('layerObjects');
- }
- };
-
- init();
- return self;
-}
diff --git a/web/js/styles/rasterPalettes/model.js b/web/js/styles/rasterPalettes/model.js
deleted file mode 100644
index 7497180bf..000000000
--- a/web/js/styles/rasterPalettes/model.js
+++ /dev/null
@@ -1,635 +0,0 @@
-import lodashEach from 'lodash/each';
-import lodashFind from 'lodash/find';
-import lodashCloneDeep from 'lodash/cloneDeep';
-import lodashIsNaN from 'lodash/isNaN';
-import lodashIsUndefined from 'lodash/isUndefined';
-import lodashParseInt from 'lodash/parseInt';
-import lodashFindIndex from 'lodash/findIndex';
-import util from '../../util/util';
-import styles from '../styles';
-import Promise from 'bluebird';
-
-export function palettesModel(models, config) {
- config.palettes = config.palettes || {
- rendered: {},
- custom: {}
- };
-
- var self = {};
- self.events = util.events();
- self.active = {};
- self.activeB = {};
-
- self.getRenderedPalette = function(layerId, index) {
- var name = config.layers[layerId].palette.id;
- var palette = config.palettes.rendered[name];
- if (!lodashIsUndefined(index)) {
- if (palette && palette.maps) {
- palette = palette.maps[index];
- }
- }
- return palette;
- };
-
- self.getCustomPalette = function(paletteId) {
- var palette = config.palettes.custom[paletteId];
- if (!palette) {
- throw new Error('Invalid palette: ' + paletteId);
- }
- return palette;
- };
-
- var prepare = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- self[groupStr][layerId] = self[groupStr][layerId] || {};
- var active = self[groupStr][layerId];
- active.maps = active.maps || [];
- lodashEach(self.getRenderedPalette(layerId).maps, function(palette, index) {
- if (!active.maps[index]) {
- active.maps[index] = lodashCloneDeep(palette);
- }
- });
- };
-
- self.allowed = function(layerId) {
- if (!styles.supported) {
- return false;
- }
- let palette = config.layers[layerId].palette;
- if (!palette || palette.immutable) {
- return false;
- }
- return config.layers[layerId].palette;
- };
-
- self.setCustom = function(layerId, paletteId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!config.layers[layerId]) {
- throw new Error('Invalid layer: ' + layerId);
- }
- prepare(layerId, groupStr);
- index = lodashIsUndefined(index) ? 0 : index;
- var active = self[groupStr][layerId];
- var palette = active.maps[index];
- if (palette.custom === paletteId) {
- return;
- }
- palette.custom = paletteId;
- updateLookup(layerId, groupStr);
- self.events.trigger('set-custom', layerId, active, groupStr);
- self.events.trigger('change');
- const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });
- if (layerIndex >= 0) {
- models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
- models.layers.events.trigger('change');
- }
- };
-
- self.clearCustom = function(layerId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = lodashIsUndefined(index) ? 0 : index;
- var active = self[groupStr][layerId];
- if (!active) {
- return;
- }
- var palette = active.maps[index];
- if (!palette.custom) {
- return;
- }
- delete palette.custom;
- updateLookup(layerId, groupStr);
- self.events.trigger('clear-custom', layerId, groupStr);
- self.events.trigger('change');
- const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });
- if (layerIndex >= 0) {
- models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
- models.layers.events.trigger('change');
- }
- };
-
- self.setRange = function(layerId, min, max, squash, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- prepare(layerId);
- index = lodashIsUndefined(index) ? 0 : index;
- var palette = self[groupStr][layerId].maps[index];
- if (min === 0) {
- min = undefined;
- }
- const legend = self.get(layerId, index, groupStr);
- if (legend.entries && legend.entries.values && max === legend.entries.values.length - 1) {
- max = undefined;
- }
- palette.min = min;
- palette.max = max;
- palette.squash = squash;
- updateLookup(layerId, groupStr);
- self.events.trigger('range', layerId, palette.min, palette.max, groupStr);
- self.events.trigger('change');
- const layerIndex = lodashFindIndex(models.layers[groupStr], { id: layerId });
- if (layerIndex >= 0) {
- models.layers[groupStr][layerIndex].custom = self[groupStr][layerId];
- models.layers.events.trigger('change');
- }
- };
-
- self.getCount = function(layerId) {
- if (self.getRenderedPalette(layerId).maps) {
- return self.getRenderedPalette(layerId).maps.length;
- } else {
- return 0;
- }
- };
- /**
- * 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, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = lodashIsUndefined(index) ? 0 : index;
- if (self[groupStr][layerId]) {
- return self[groupStr][layerId].maps[index];
- }
- return self.getRenderedPalette(layerId, index);
- };
- /**
- * Gets the legend of a colormap
- *
- *
- * @method getLegend
- * @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 of the legend
- */
- self.getLegend = function(layerId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var value = self.get(layerId, index, groupStr);
- return value.legend || value.entries;
- };
- /**
- * Gets the legend of a colormap
- *
- *
- * @method getDefaultLegend
- * @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 of the legend
- */
- self.getDefaultLegend = function(layerId, index) {
- var palette = self.getRenderedPalette(layerId, index);
- return palette.legend || palette.entries;
- };
-
- self.getLegends = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var legends = [];
- var count = self.getCount(layerId);
- for (var i = 0; i < count; i++) {
- legends.push(self.getLegend(layerId, i, groupStr));
- }
- return legends;
- };
-
- // Is a canvas required?
- self.isActive = function(layerId, group) {
- group = group || models.layers.activeLayers;
- return self[group][layerId];
- };
-
- // Looks up options/colormaps/layer.xml colormap entry
- self.getLookup = function(layerId, groupstr) {
- groupstr = groupstr || models.layers.activeLayers;
- return self[groupstr][layerId].lookup;
- };
-
- self.clear = function() {
- self.active = {};
- self.events.trigger('update');
- };
-
- self.restore = function(active) {
- self.active = active;
- self.events.trigger('update');
- };
-
- var getMinValue = function(v) {
- return v.length ? v[0] : v;
- };
-
- var getMaxValue = function(v) {
- return v.length ? v[v.length - 1] : v;
- };
-
- self.save = function(state) {
- var groupArray = [models.layers.activeLayers];
- if (self.inUse() && !state.l) {
- throw new Error('No layers in state');
- }
- if (models.compare && models.compare.active) {
- groupArray = ['active', 'activeB'];
- }
- lodashEach(groupArray, groupStr => {
- lodashEach(self[groupStr], function(def, layerId) {
- if (
- !lodashFind(models.layers.get({}, models.layers[groupStr]), {
- id: layerId
- })
- ) {
- return;
- }
- if (self.getCount(layerId) > 1) {
- self.saveMulti(state, layerId, groupStr);
- } else {
- self.saveSingle(state, layerId, groupStr);
- }
- });
- });
- };
- self.palettePromise = function(layerId, paletteId) {
- return new Promise((resolve, reject) => {
- if (config.palettes.rendered[paletteId]) {
- resolve();
- } else {
- styles.loadRenderedPalette(config, layerId).done(function(result) {
- resolve(result);
- });
- }
- });
- };
- self.saveSingle = function(state, layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var stateStr = 'l';
- if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';
- var attr = lodashFind(state[stateStr], {
- id: layerId
- }).attributes;
- var def = self.get(layerId, undefined, groupStr);
-
- if (def.custom) {
- attr.push({
- id: 'palette',
- value: def.custom
- });
- }
- if (def.min) {
- var minValue = def.entries.values[def.min];
- attr.push({
- id: 'min',
- value: minValue
- });
- }
- if (def.max) {
- var maxValue = def.entries.values[def.max];
- attr.push({
- id: 'max',
- value: maxValue
- });
- }
- if (def.squash) {
- attr.push({
- id: 'squash'
- });
- }
- };
-
- self.saveMulti = function(state, layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var stateStr = 'l';
- var palettes = [];
- var hasPalettes = false;
- var min = [];
- var hasMin = false;
- var max = [];
- var hasMax = false;
- var squash = [];
- var hasSquash = false;
- if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';
-
- for (var i = 0; i < self.getCount(layerId); i++) {
- var def = self.get(layerId, i, groupStr);
- if (def.custom) {
- palettes.push(def.custom);
- hasPalettes = true;
- } else {
- palettes.push('');
- }
-
- if (def.min) {
- min.push(getMinValue(def.entries.values[def.min]));
- hasMin = true;
- } else {
- min.push('');
- }
-
- if (def.max) {
- max.push(getMaxValue(def.entries.values[def.max]));
- hasMax = true;
- } else {
- max.push('');
- }
-
- if (def.squash) {
- squash.push(def.squash);
- hasSquash = true;
- } else {
- squash.push('');
- }
- }
-
- var attr = lodashFind(state[stateStr], {
- id: layerId
- }).attributes;
- if (hasPalettes) {
- attr.push({
- id: 'palette',
- value: palettes.join(';')
- });
- }
- if (hasMin) {
- attr.push({
- id: 'min',
- value: min.join(';')
- });
- }
- if (hasMax) {
- attr.push({
- id: 'max',
- value: max.join(';')
- });
- }
- if (hasSquash) {
- attr.push({
- id: 'squash',
- value: squash.join(';')
- });
- }
- };
-
- self.key = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!self.isActive(layerId, groupStr)) {
- return '';
- }
- var def = self.get(layerId, undefined, groupStr);
- var keys = [];
- if (def.custom) {
- keys.push('palette=' + def.custom);
- }
- if (def.min) {
- keys.push('min=' + def.min);
- }
- if (def.max) {
- keys.push('max=' + def.max);
- }
- if (def.squash) {
- keys.push('squash');
- }
- return keys.join(',');
- };
-
- self.load = function(state, errors) {
- var stateArray = [{ stateStr: 'l', groupStr: 'active' }];
- if (!styles.supported) {
- return self;
- }
- if (state.l1) {
- stateArray = [
- { stateStr: 'l', groupStr: 'active' },
- { stateStr: 'l1', groupStr: 'activeB' }
- ];
- }
- lodashEach(stateArray, stateObj => {
- lodashEach(state[stateObj.stateStr], function(layerDef) {
- var layerId = layerDef.id;
- var minValue, maxValue;
- var min = [];
- var max = [];
- var squash = [];
- var count = 0;
- lodashEach(layerDef.attributes, function(attr) {
- var values;
- if (attr.id === 'palette') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- try {
- self.setCustom(layerId, value, index, stateObj.groupStr);
- } catch (error) {
- errors.push('Invalid palette: ' + value);
- }
- });
- }
- if (attr.id === 'min') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- if (value === '') {
- min.push(undefined);
- return;
- }
- minValue = parseFloat(value);
- if (lodashIsNaN(minValue)) {
- errors.push('Invalid min value: ' + value);
- } else {
- min.push(
- findIndex(layerId, 'min', minValue, index, stateObj.groupStr)
- );
- }
- });
- }
- if (attr.id === 'max') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- if (value === '') {
- max.push(undefined);
- return;
- }
- maxValue = parseFloat(value);
- if (lodashIsNaN(maxValue)) {
- errors.push('Invalid max value: ' + value);
- } else {
- max.push(
- findIndex(layerId, 'max', maxValue, index, stateObj.groupStr)
- );
- }
- });
- }
- if (attr.id === 'squash') {
- count = self.getCount(layerId);
- if (attr.value === true) {
- squash[0] = true;
- } else {
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value) {
- squash.push(value === 'true');
- });
- }
- }
- });
- if (min.length > 0 || max.length > 0) {
- for (var i = 0; i < count; i++) {
- var vmin = min.length > 0 ? min[i] : undefined;
- var vmax = max.length > 0 ? max[i] : undefined;
- var vsquash = squash.length > 0 ? squash[i] : undefined;
- self.setRange(layerId, vmin, vmax, vsquash, i, stateObj.groupStr);
- }
- }
- });
- });
- self.loaded = true;
- return self;
- };
-
- var findIndex = function(layerId, type, value, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = index || 0;
- var values = self.get(layerId, index, groupStr).entries.values;
- var result;
- lodashEach(values, function(check, index) {
- var min = getMinValue(check);
- var max = getMaxValue(check);
- if (type === 'min' && value === min) {
- result = index;
- return false;
- }
- if (type === 'max' && value === max) {
- result = index;
- return false;
- }
- });
- return result;
- };
-
- // If any custom rendering is being used, image download must turn it
- // off
- self.inUse = function(groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var layers = models.layers.get({}, models.layers[groupStr]);
- var found = false;
- lodashEach(layers, function(layer) {
- if (self[groupStr][layer.id]) {
- found = true;
- return false;
- }
- });
- return found;
- };
-
- var useLookup = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var use = false;
- var active = self[groupStr][layerId].maps;
-
- lodashEach(active, function(palette, index) {
- if (palette.custom) {
- use = true;
- return false;
- }
- var rendered = self.getRenderedPalette(layerId, index);
- if (palette.type !== 'classification') {
- if (palette.min <= 0) {
- delete palette.min;
- }
- if (palette.max >= rendered.entries.values.length) {
- delete palette.max;
- }
- if (
- !lodashIsUndefined(palette.min) ||
- !lodashIsUndefined(palette.max)
- ) {
- use = true;
- return false;
- }
- }
- });
- return use;
- };
-
- var updateLookup = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!useLookup(layerId, groupStr)) {
- delete self[groupStr][layerId];
- return;
- }
- var lookup = {};
- var active = self[groupStr][layerId].maps;
- lodashEach(active, function(palette, index) {
- var oldLegend = palette.legend;
- var entries = palette.entries;
- var legend = {
- colors: [],
- minLabel: oldLegend.minLabel,
- maxLabel: oldLegend.maxLabel,
- tooltips: oldLegend.tooltips,
- units: oldLegend.units,
- type: entries.type,
- title: entries.title,
- id: oldLegend.id
- };
- var source = entries.colors;
- var target = palette.custom
- ? self.getCustomPalette(palette.custom).colors
- : source;
-
- var min = palette.min || 0;
- var max = palette.max || source.length;
-
- var sourceCount = source.length;
- var targetCount = target.length;
-
- lodashEach(source, function(color, index) {
- var targetColor;
- if (index < min || index > max) {
- targetColor = '00000000';
- } else {
- var sourcePercent, targetIndex;
- if (palette.squash) {
- sourcePercent = (index - min) / (max - min);
- if (index === max) {
- sourcePercent = 1.0;
- }
- targetIndex = Math.floor(sourcePercent * targetCount);
- if (targetIndex >= targetCount) {
- targetIndex = targetCount - 1;
- }
- } else {
- sourcePercent = index / sourceCount;
- targetIndex = Math.floor(sourcePercent * targetCount);
- }
- targetColor = target[targetIndex];
- }
- legend.colors.push(targetColor);
- var lookupSource =
- lodashParseInt(color.substring(0, 2), 16) +
- ',' +
- lodashParseInt(color.substring(2, 4), 16) +
- ',' +
- lodashParseInt(color.substring(4, 6), 16) +
- ',' +
- lodashParseInt(color.substring(6, 8), 16);
- var lookupTarget = {
- r: lodashParseInt(targetColor.substring(0, 2), 16),
- g: lodashParseInt(targetColor.substring(2, 4), 16),
- b: lodashParseInt(targetColor.substring(4, 6), 16),
- a: lodashParseInt(targetColor.substring(6, 8), 16)
- };
- lookup[lookupSource] = lookupTarget;
- });
- palette.legend = legend;
- });
- self[groupStr][layerId].lookup = lookup;
- };
-
- return self;
-}
diff --git a/web/js/styles/rasterPalettes/model.test.js b/web/js/styles/rasterPalettes/model.test.js
deleted file mode 100644
index 43436dd7b..000000000
--- a/web/js/styles/rasterPalettes/model.test.js
+++ /dev/null
@@ -1,372 +0,0 @@
-import jQuery from 'jquery';
-import styles from '../styles';
-import fixtures from '../../fixtures';
-
-var unmocked = {};
-
-beforeAll(() => {
- unmocked.getJSON = jQuery.getJSON;
- unmocked.supported = styles.supported;
-});
-
-beforeEach(() => { styles.supported = true; });
-
-afterEach(() => {
- jQuery.getJSON = unmocked.getJSON;
- styles.supported = unmocked.supported;
-});
-
-function testData() {
- let config = fixtures.config();
- let models = fixtures.models(config);
- return { config, models };
-};
-
-test('set a custom palette', (done) => {
- let { models } = testData();
- models.palettes.events.on('set-custom', function (layerId) {
- var palette = models.palettes.get(layerId);
- var colors = palette.legend.colors;
- var labels = palette.legend.tooltips;
-
- expect(colors).toEqual([
- fixtures.light_blue,
- fixtures.blue,
- fixtures.dark_blue
- ]);
- expect(labels).toEqual(['0', '1', '2']);
- done();
- });
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
-});
-
-test('palettte compresses color range', () => {
- let { models, config } = testData();
- config.palettes.custom['blue-1'].colors = ['1', '2', '3', '4', '5', '6'];
- models = fixtures.models(config);
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- var palette = models.palettes.get('terra-aod');
-
- expect(palette.legend.colors).toEqual(['1', '3', '5']);
-});
-
-test('palette expands color range', () => {
- let { models, config } = testData();
- config.palettes.rendered['terra-aod'].maps[0].entries.colors = [
- '1',
- '2',
- '3',
- '4',
- '5',
- '6'
- ];
- models = fixtures.models(config);
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- let palette = models.palettes.get('terra-aod');
- let colors = palette.legend.colors;
-
- expect(colors).toEqual([
- fixtures.light_blue,
- fixtures.light_blue,
- fixtures.blue,
- fixtures.blue,
- fixtures.dark_blue,
- fixtures.dark_blue
- ]);
-});
-
-test('exception setting a custom palette when no layer exists', () => {
- let { models } = testData();
- expect(() => models.palettes.setCustom('no-layer', 'blue-1')).toThrow();
-});
-
-test('exception setting an unvakud custom palette', () => {
- let { models } = testData();
- expect(() => models.palettes.setCustom('terra-aod', 'no-palette')).toThrow();
-});
-
-test('exception setting a custom palette on a imagery layer', () => {
- let { models } = testData();
- expect(() => models.palettes.setCustom('terra0cr', 'blue-1')).toThrow();
-});
-
-test('clear a custom palette', () => {
- let { models } = testData();
- let trigger = jest.fn();
- models.palettes.events.trigger = trigger;
-
- models.layers.add('aqua-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- models.palettes.clearCustom('terra-aod');
- let palette = models.palettes.get('terra-aod');
-
- expect(palette.entries.colors[0]).toBe(fixtures.green);
- expect(palette.legend.tooltips[0]).toBe('0');
-
- expect(trigger).toBeCalledWith('clear-custom', 'terra-aod', 'active');
- expect(trigger).toBeCalledWith('change');
-});
-
-test('set a minimum threshold', () => {
- let { models } = testData();
- let trigger = jest.fn();
- models.palettes.events.trigger = trigger;
-
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 1, 2);
- let palette = models.palettes.get('terra-aod');
-
- expect(palette.min).toBe(1);
- expect(palette.max).not.toBeDefined();
- expect(palette.legend.colors).toEqual([
- '00000000',
- fixtures.yellow,
- fixtures.red
- ]);
-
- expect(trigger).toBeCalledWith('range', 'terra-aod', 1, undefined, 'active');
- expect(trigger).toBeCalledWith('change');
-});
-
-test('set a maximum threshold', () => {
- let { models } = testData();
- let trigger = jest.fn();
- models.palettes.events.trigger = trigger;
-
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 0, 1);
- let palette = models.palettes.get('terra-aod');
-
- expect(palette.max).toBe(1);
- expect(palette.min).not.toBeDefined();
- expect(palette.legend.colors).toEqual([
- fixtures.green,
- fixtures.yellow,
- '00000000'
- ]);
-
- expect(trigger).toBeCalledWith('range', 'terra-aod', undefined, 1, 'active');
- expect(trigger).toBeCalledWith('change');
-});
-
-test('save custom palette', () => {
- let { models } = testData();
- models.layers.add('aqua-aod');
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- models.palettes.setCustom('aqua-aod', 'red-1');
-
- let state = {};
- models.layers.save(state);
- models.palettes.save(state);
- expect(state.l).toEqual([
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'palette',
- value: 'blue-1'
- }
- ]
- },
- {
- id: 'aqua-aod',
- attributes: [
- {
- id: 'palette',
- value: 'red-1'
- }
- ]
- }
- ]);
-});
-
-test('save threshold minimum', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 1, 2);
-
- var state = {};
- models.layers.save(state);
- models.palettes.save(state);
- expect(state.l).toEqual([
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'min',
- value: 1
- }
- ]
- }
- ]);
-});
-
-test('save threshold maximum', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 0, 1);
-
- var state = {};
- models.layers.save(state);
- models.palettes.save(state);
- expect(state.l).toEqual([
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'max',
- value: 1
- }
- ]
- }
- ]);
-});
-
-test('save threshold range', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 1, 1);
-
- var state = {};
- models.layers.save(state);
- models.palettes.save(state);
- expect(state.l).toEqual([
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'min',
- value: 1
- },
- {
- id: 'max',
- value: 1
- }
- ]
- }
- ]);
-});
-
-test('no save when not active', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
-
- var state = {};
- models.layers.save(state);
- models.palettes.save(state);
- expect(state.l).toEqual([
- {
- id: 'terra-aod',
- attributes: []
- }
- ]);
-});
-
-test('load state', () => {
- let { models } = testData();
- let state = {
- l: [
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'palette',
- value: 'blue-1'
- },
- {
- id: 'min',
- value: '1'
- },
- {
- id: 'max',
- value: '1'
- }
- ]
- }
- ]
- };
- let errors = [];
- models.layers.load(state, errors);
- models.palettes.load(state, errors);
- let palette = models.palettes.get('terra-aod');
-
- expect(palette.custom).toBe('blue-1');
- expect(palette.min).toBe(1);
- expect(palette.max).toBe(1);
- expect(errors).toHaveLength(0);
-});
-
-test('error loading invalid minimum', () => {
- let { models } = testData();
- let state = {
- l: [
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'min',
- value: 'x'
- }
- ]
- }
- ]
- };
- let errors = [];
- models.layers.load(state, errors);
- models.palettes.load(state, errors);
-
- expect(errors).toHaveLength(1);
-});
-
-test('error loading invalid maximum', () => {
- let { models } = testData();
- let state = {
- l: [
- {
- id: 'terra-aod',
- attributes: [
- {
- id: 'max',
- value: 'x'
- }
- ]
- }
- ]
- };
- let errors = [];
- models.layers.load(state, errors);
- models.palettes.load(state, errors);
-
- expect(errors).toHaveLength(1);
-});
-
-test('canvas not in use', () => {
- let { models } = testData();
- expect(models.palettes.inUse()).toBe(false);
-});
-
-test('canvas in use with custom palette', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- expect(models.palettes.inUse()).toBe(true);
-});
-
-test('canvas in use with threshold ranges', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setRange('terra-aod', 1);
- expect(models.palettes.inUse()).toBe(true);
-});
-
-test('canvas not in use when not active layers have a palette', () => {
- let { models } = testData();
- models.layers.add('terra-aod');
- models.palettes.setCustom('terra-aod', 'blue-1');
- models.layers.remove('terra-aod');
- expect(models.palettes.inUse()).toBe(false);
-});
diff --git a/web/js/styles/styles.js b/web/js/styles/styles.js
deleted file mode 100644
index bf92c87b6..000000000
--- a/web/js/styles/styles.js
+++ /dev/null
@@ -1,206 +0,0 @@
-import lodashEach from 'lodash/each';
-import lodashFind from 'lodash/find';
-import util from '../util/util';
-import wvui from '../ui/ui';
-
-export default (function(self) {
- var checkerboard;
-
- self.supported = true;
-
- var init = function() {
- var browser = util.browser;
- if (browser.ie || !browser.webWorkers || !browser.cors) {
- self.supported = false;
- } else {
- drawCheckerboard();
- }
- };
-
- self.colorbar = function(target, colors) {
- var canvas;
- if (target.length) {
- canvas = $(target).get(0);
- } else {
- canvas = target;
- }
- if (!canvas) {
- return;
- }
- var g = canvas.getContext('2d');
-
- g.fillStyle = checkerboard;
- g.fillRect(0, 0, canvas.width, canvas.height);
- if (colors) {
- var bins = colors.length;
- var binWidth = canvas.width / bins;
- var drawWidth = Math.ceil(binWidth);
- lodashEach(colors, function(color, i) {
- g.fillStyle = util.hexToRGBA(color);
- g.fillRect(Math.floor(binWidth * i), 0, drawWidth, canvas.height);
- });
- }
- };
-
- var drawCheckerboard = function() {
- 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);
-
- checkerboard = g.createPattern(canvas, 'repeat');
- };
-
- self.translate = function(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;
- };
-
- self.lookup = function(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;
- };
-
- self.loadCustom = function(config) {
- return util.load.config(
- config.palettes,
- 'custom',
- 'config/palettes-custom.json'
- );
- };
-
- self.loadRenderedPalette = function(config, layerId) {
- var layer = config.layers[layerId];
- return util.load.config(
- config.palettes.rendered,
- layer.palette.id,
- 'config/palettes/' + layer.palette.id + '.json'
- );
- };
-
- self.loadRenderedVectorStyle = function (config, layerId) {
- var layer = config.layers[layerId];
- return util.load.config(config.vectorStyles.rendered,
- layer.vectorStyle.id, 'config/vectorstyles/' + layer.vectorStyle.id + '.json');
- };
-
- self.requirements = function(state, config, startup) {
- var promises = [];
- if (startup || !state.tr) {
- config.vectorStyles = {
- rendered: {}
- };
- config.palettes = {
- rendered: {},
- custom: {}
- };
- }
- lodashEach(state.l, function(qsLayer) {
- var layerId = qsLayer.id;
- if (config.layers[layerId] && config.layers[layerId].palette) {
- promises.push(self.loadRenderedPalette(config, layerId));
- } else if (config.layers[layerId] && config.layers[layerId].vectorStyle) {
- promises.push(self.loadRenderedVectorStyle(config, layerId));
- }
- var custom = lodashFind(qsLayer.attributes, {
- id: 'palette'
- });
- if (custom) {
- promises.push(self.loadCustom(config));
- }
- });
- if (promises.length > 0) {
- var promise = $.Deferred();
- $.when
- .apply(null, promises)
- .then(promise.resolve)
- .fail(promise.reject);
- return promise;
- }
- };
-
- // Only for permalink 1.1 support
- self.parse = function(state, errors, config) {
- if (state.palettes) {
- if (!self.supported) {
- // FIXME: This should go in errors
- delete state.palettes;
- wvui.notify(
- 'The custom palette feature is not supported ' +
- 'with your web browser. Upgrade or try again in a ' +
- 'different browser'
- );
- return;
- }
- var parts = state.palettes.split('~');
- lodashEach(parts, function(part) {
- var items = part.split(',');
- var layerId = items[0];
- var paletteId = items[1];
- if (!config.layers[layerId]) {
- errors.push({
- message: 'Invalid layer for palette ' + paletteId + ': ' + layerId
- });
- } else if (!config.layers[layerId].palette) {
- errors.push({
- message: 'Layer ' + layerId + ' does not ' + 'support palettes'
- });
- } else {
- var layer = lodashFind(state.l, {
- id: layerId
- });
- if (layer) {
- layer.attributes.push({
- id: 'palette',
- value: paletteId
- });
- } else {
- errors.push({
- message: 'Layer ' + layerId + ' is not ' + 'active'
- });
- }
- }
- });
- delete state.paletes;
- }
- };
-
- init();
- return self;
-})({});
diff --git a/web/js/styles/styles.test.js b/web/js/styles/styles.test.js
deleted file mode 100644
index fd78c0ae4..000000000
--- a/web/js/styles/styles.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-import fixtures from '../fixtures';
-import { parse as layersParse } from '../layers/layers';
-import styles from './styles';
-
-var unmocked = {};
-
-beforeAll(() => {
- unmocked.supported = styles.supported;
-});
-
-beforeEach(() => { styles.supported = true; });
-
-afterEach(() => {
- styles.supported = unmocked.supported;
-});
-
-function testData() {
- let config = fixtures.config();
- return { config };
-};
-
-describe('permalink 1.2', () => {
- test('parses palette for valid layer', () => {
- let { config } = testData();
- let errors = [];
- let state = {
- l: 'terra-aod(palette=blue-1)'
- };
- layersParse(state, errors, config);
- let attr = state.l[0].attributes[0];
-
- expect(attr.id).toBe('palette');
- expect(attr.value).toBe('blue-1');
- expect(errors).toHaveLength(0);
- });
-});
-
-describe('permalink 1.1', () => {
- test('parses palette for valid layer', () => {
- let { config } = testData();
- let errors = [];
- let state = {
- l: 'terra-aod',
- palettes: 'terra-aod,blue-1'
- };
- layersParse(state, errors, config);
- styles.parse(state, errors, config);
- var attr = state.l[0].attributes[0];
-
- expect(attr.id).toBe('palette');
- expect(attr.value).toBe('blue-1');
- expect(errors).toHaveLength(0);
- });
-
- test('parses palette for two valid layers', () => {
- let { config } = testData();
- let errors = [];
- let state = {
- l: 'terra-aod,aqua-aod',
- palettes: 'terra-aod,blue-1~aqua-aod,red-1'
- };
- layersParse(state, errors, config);
- styles.parse(state, errors, config);
-
- let attr1 = state.l[0].attributes[0];
- expect(attr1.id).toBe('palette');
- expect(attr1.value).toBe('blue-1');
-
- let attr2 = state.l[1].attributes[0];
- expect(attr2.id).toBe('palette');
- expect(attr2.value).toBe('red-1');
-
- expect(errors).toHaveLength(0);
- });
-
- test('error if palette assigned to a layer that is not active', () => {
- let { config } = testData();
- let errors = [];
- var state = {
- l: 'terra-aod',
- palettes: 'aqua-aod,red-1'
- };
- layersParse(state, errors, config);
- styles.parse(state, errors, config);
- expect(errors).toHaveLength(1);
- });
-});
diff --git a/web/js/styles/util.js b/web/js/styles/util.js
deleted file mode 100644
index 3639aa99c..000000000
--- a/web/js/styles/util.js
+++ /dev/null
@@ -1,58 +0,0 @@
-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 {*} ctxStr | String of wanted cavnas
- * @param {*} checkerBoardPattern | Background for canvas threshold
- * @param {*} 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);
- });
- }
-}
diff --git a/web/js/styles/vectorStyles/model.js b/web/js/styles/vectorStyles/model.js
deleted file mode 100644
index 4b490152f..000000000
--- a/web/js/styles/vectorStyles/model.js
+++ /dev/null
@@ -1,610 +0,0 @@
-import lodashEach from 'lodash/each';
-import lodashFind from 'lodash/find';
-import lodashCloneDeep from 'lodash/cloneDeep';
-import lodashIsNaN from 'lodash/isNaN';
-import lodashIsUndefined from 'lodash/isUndefined';
-import lodashParseInt from 'lodash/parseInt';
-import util from '../../util/util';
-import styles from '../styles';
-import Promise from 'bluebird';
-
-export function vectorStylesModel(models, config) {
- config.vectorStyles = config.vectorStyles || {
- rendered: {},
- custom: {}
- };
-
- var self = {};
- self.events = util.events();
- self.active = {};
- self.activeB = {};
-
- self.getRenderedVectorStyle = function(layerId, index) {
- var name = config.layers[layerId].vectorStyle.id;
- var vectorStyle = config.vectorStyles.rendered[name];
- if (!lodashIsUndefined(index)) {
- if (vectorStyle.maps) {
- vectorStyle = vectorStyle.maps[index];
- }
- }
- return vectorStyle;
- };
-
- self.getCustomVectorStyle = function(vectorStyleId) {
- var vectorStyle = config.vectorStyles.custom[vectorStyleId];
- if (!vectorStyle) {
- throw new Error('Invalid vectorStyle: ' + vectorStyleId);
- }
- return vectorStyle;
- };
-
- var prepare = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- self[groupStr][layerId] = self[groupStr][layerId] || {};
- var active = self[groupStr][layerId];
- active.maps = active.maps || [];
- lodashEach(self.getRenderedVectorStyle(layerId).maps, function(vectorStyle, index) {
- if (!active.maps[index]) {
- active.maps[index] = lodashCloneDeep(vectorStyle);
- }
- });
- };
-
- self.allowed = function(layerId) {
- let vectorStyle = config.layers[layerId].vectorStyle;
- if (!vectorStyle || vectorStyle.immutable) {
- return false;
- }
- return config.layers[layerId].vectorStyle;
- };
-
- self.setCustom = function(layerId, vectorStyleId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!config.layers[layerId]) {
- throw new Error('Invalid layer: ' + layerId);
- }
- prepare(layerId, groupStr);
- index = lodashIsUndefined(index) ? 0 : index;
- var active = self[groupStr][layerId];
- var vectorStyle = active.maps[index];
- if (vectorStyle.custom === vectorStyleId) {
- return;
- }
- vectorStyle.custom = vectorStyleId;
- updateLookup(layerId, groupStr);
- self.events.trigger('set-custom', layerId, active, groupStr);
- self.events.trigger('change');
- };
-
- self.clearCustom = function(layerId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = lodashIsUndefined(index) ? 0 : index;
- var active = self[groupStr][layerId];
- if (!active) {
- return;
- }
- var vectorStyle = active.maps[index];
- if (!vectorStyle.custom) {
- return;
- }
- delete vectorStyle.custom;
- updateLookup(layerId, groupStr);
- self.events.trigger('clear-custom', layerId, groupStr);
- self.events.trigger('change');
- };
-
- self.setRange = function(layerId, min, max, squash, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- prepare(layerId);
- index = lodashIsUndefined(index) ? 0 : index;
- var vectorStyle = self[groupStr][layerId].maps[index];
- if (min === 0) {
- min = undefined;
- }
- const legend = self.get(layerId, index, groupStr);
- if (legend.entries && legend.entries.values && max === legend.entries.values.length - 1) {
- max = undefined;
- }
- vectorStyle.min = min;
- vectorStyle.max = max;
- vectorStyle.squash = squash;
- updateLookup(layerId, groupStr);
- self.events.trigger('range', layerId, vectorStyle.min, vectorStyle.max, groupStr);
- self.events.trigger('change');
- };
-
- self.getCount = function(layerId) {
- if (self.getRenderedVectorStyle(layerId).maps) {
- return self.getRenderedVectorStyle(layerId).maps.length;
- } else {
- return 0;
- }
- };
-
- /**
- * 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, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = lodashIsUndefined(index) ? 0 : index;
- if (self[groupStr][layerId]) {
- return self[groupStr][layerId].maps[index];
- }
- return self.getRenderedVectorStyle(layerId, index);
- };
-
- /**
- * Gets the legend of a colormap
- *
- * @method getLegend
- * @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 of the legend
- */
- self.getLegend = function(layerId, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var value = self.get(layerId, index, groupStr);
- return value.legend || value.entries;
- };
-
- /**
- * Gets the legend of a colormap
- *
- * @method getDefaultLegend
- * @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 of the legend
- */
- self.getDefaultLegend = function(layerId, index) {
- var vectorStyle = self.getRenderedVectorStyle(layerId, index);
- return vectorStyle.legend || vectorStyle.entries;
- };
-
- self.getLegends = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var legends = [];
- var count = self.getCount(layerId);
- for (var i = 0; i < count; i++) {
- legends.push(self.getLegend(layerId, i, groupStr));
- }
- return legends;
- };
-
- // Is a canvas required?
- self.isActive = function(layerId, group) {
- group = group || models.layers.activeLayers;
- return self[group][layerId];
- };
-
- // Looks up options/colormaps/layer.xml colormap entry
- self.getLookup = function(layerId, groupstr) {
- groupstr = groupstr || models.layers.activeLayers;
- return self[groupstr][layerId].lookup;
- };
-
- self.clear = function() {
- self.active = {};
- self.events.trigger('update');
- };
-
- self.restore = function(active) {
- self.active = active;
- self.events.trigger('update');
- };
-
- var getMinValue = function(v) {
- return v.length ? v[0] : v;
- };
-
- var getMaxValue = function(v) {
- return v.length ? v[v.length - 1] : v;
- };
-
- self.save = function(state) {
- var groupArray = [models.layers.activeLayers];
- if (self.inUse() && !state.l) {
- throw new Error('No layers in state');
- }
- if (models.compare && models.compare.active) {
- groupArray = ['active', 'activeB'];
- }
- lodashEach(groupArray, groupStr => {
- lodashEach(self[groupStr], function(def, layerId) {
- if (
- !lodashFind(models.layers.get({}, models.layers[groupStr]), {
- id: layerId
- })
- ) {
- return;
- }
- if (self.getCount(layerId) > 1) {
- self.saveMulti(state, layerId, groupStr);
- } else {
- self.saveSingle(state, layerId, groupStr);
- }
- });
- });
- };
- self.vectorStylePromise = function(layerId, vectorStyleId) {
- return new Promise((resolve, reject) => {
- if (config.vectorStyles.rendered[vectorStyleId]) {
- resolve();
- } else {
- styles.loadRenderedVectorStyle(config, layerId).done(function(result) {
- resolve(result);
- });
- }
- });
- };
- self.saveSingle = function(state, layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var stateStr = 'l';
- if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';
- var attr = lodashFind(state[stateStr], {
- id: layerId
- }).attributes;
- var def = self.get(layerId, undefined, groupStr);
- if (def.custom) {
- attr.push({
- id: 'vectorStyle',
- value: def.custom
- });
- }
- if (def.min) {
- var minValue = def.entries.values[def.min];
- attr.push({
- id: 'min',
- value: minValue
- });
- }
- if (def.max) {
- var maxValue = def.entries.values[def.max];
- attr.push({
- id: 'max',
- value: maxValue
- });
- }
- if (def.squash) {
- attr.push({
- id: 'squash'
- });
- }
- };
-
- self.saveMulti = function(state, layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var stateStr = 'l';
- var vectorStyles = [];
- var hasVectorStyles = false;
- var min = [];
- var hasMin = false;
- var max = [];
- var hasMax = false;
- var squash = [];
- var hasSquash = false;
- if (groupStr === 'activeB' && models.compare && models.compare.active) stateStr = 'l1';
-
- for (var i = 0; i < self.getCount(layerId); i++) {
- var def = self.get(layerId, i, groupStr);
- if (def.custom) {
- vectorStyles.push(def.custom);
- hasVectorStyles = true;
- } else {
- vectorStyles.push('');
- }
-
- if (def.min) {
- min.push(getMinValue(def.entries.values[def.min]));
- hasMin = true;
- } else {
- min.push('');
- }
-
- if (def.max) {
- max.push(getMaxValue(def.entries.values[def.max]));
- hasMax = true;
- } else {
- max.push('');
- }
-
- if (def.squash) {
- squash.push(def.squash);
- hasSquash = true;
- } else {
- squash.push('');
- }
- }
-
- var attr = lodashFind(state[stateStr], {
- id: layerId
- }).attributes;
- if (hasVectorStyles) {
- attr.push({
- id: 'vectorStyle',
- value: vectorStyles.join(';')
- });
- }
- if (hasMin) {
- attr.push({
- id: 'min',
- value: min.join(';')
- });
- }
- if (hasMax) {
- attr.push({
- id: 'max',
- value: max.join(';')
- });
- }
- if (hasSquash) {
- attr.push({
- id: 'squash',
- value: squash.join(';')
- });
- }
- };
-
- self.key = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!self.isActive(layerId, groupStr)) {
- return '';
- }
- var def = self.get(layerId, undefined, groupStr);
- var keys = [];
- if (def.custom) {
- keys.push('vectorStyle=' + def.custom);
- }
- if (def.min) {
- keys.push('min=' + def.min);
- }
- if (def.max) {
- keys.push('max=' + def.max);
- }
- if (def.squash) {
- keys.push('squash');
- }
- return keys.join(',');
- };
-
- self.load = function(state, errors) {
- var stateArray = [{ stateStr: 'l', groupStr: 'active' }];
- if (state.l1) {
- stateArray = [
- { stateStr: 'l', groupStr: 'active' },
- { stateStr: 'l1', groupStr: 'activeB' }
- ];
- }
- lodashEach(stateArray, stateObj => {
- lodashEach(state[stateObj.stateStr], function(layerDef) {
- var layerId = layerDef.id;
- var minValue, maxValue;
- var min = [];
- var max = [];
- var squash = [];
- var count = 0;
- lodashEach(layerDef.attributes, function(attr) {
- var values;
- if (attr.id === 'vectorStyle') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- try {
- self.setCustom(layerId, value, index, stateObj.groupStr);
- } catch (error) {
- errors.push('Invalid vectorStyle: ' + value);
- }
- });
- }
- if (attr.id === 'min') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- if (value === '') {
- min.push(undefined);
- return;
- }
- minValue = parseFloat(value);
- if (lodashIsNaN(minValue)) {
- errors.push('Invalid min value: ' + value);
- } else {
- min.push(
- findIndex(layerId, 'min', minValue, index, stateObj.groupStr)
- );
- }
- });
- }
- if (attr.id === 'max') {
- count = self.getCount(layerId);
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value, index) {
- if (value === '') {
- max.push(undefined);
- return;
- }
- maxValue = parseFloat(value);
- if (lodashIsNaN(maxValue)) {
- errors.push('Invalid max value: ' + value);
- } else {
- max.push(
- findIndex(layerId, 'max', maxValue, index, stateObj.groupStr)
- );
- }
- });
- }
- if (attr.id === 'squash') {
- count = self.getCount(layerId);
- if (attr.value === true) {
- squash[0] = true;
- } else {
- values = util.toArray(attr.value.split(';'));
- lodashEach(values, function(value) {
- squash.push(value === 'true');
- });
- }
- }
- });
- if (min.length > 0 || max.length > 0) {
- for (var i = 0; i < count; i++) {
- var vmin = min.length > 0 ? min[i] : undefined;
- var vmax = max.length > 0 ? max[i] : undefined;
- var vsquash = squash.length > 0 ? squash[i] : undefined;
- self.setRange(layerId, vmin, vmax, vsquash, i, stateObj.groupStr);
- }
- }
- });
- });
- };
-
- var findIndex = function(layerId, type, value, index, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- index = index || 0;
- var values = self.get(layerId, index, groupStr).entries.values;
- var result;
- lodashEach(values, function(check, index) {
- var min = getMinValue(check);
- var max = getMaxValue(check);
- if (type === 'min' && value === min) {
- result = index;
- return false;
- }
- if (type === 'max' && value === max) {
- result = index;
- return false;
- }
- });
- return result;
- };
-
- // If any custom rendering is being used, image download must turn it
- // off
- self.inUse = function(groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var layers = models.layers.get({}, models.layers[groupStr]);
- var found = false;
- lodashEach(layers, function(layer) {
- if (self[groupStr][layer.id]) {
- found = true;
- return false;
- }
- });
- return found;
- };
-
- var useLookup = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- var use = false;
- var active = self[groupStr][layerId].maps;
-
- lodashEach(active, function(vectorStyle, index) {
- if (vectorStyle.custom) {
- use = true;
- return false;
- }
- var rendered = self.getRenderedVectorStyle(layerId, index);
- if (vectorStyle.type !== 'classification') {
- if (vectorStyle.min <= 0) {
- delete vectorStyle.min;
- }
- if (vectorStyle.max >= rendered.entries.values.length) {
- delete vectorStyle.max;
- }
- if (
- !lodashIsUndefined(vectorStyle.min) ||
- !lodashIsUndefined(vectorStyle.max)
- ) {
- use = true;
- return false;
- }
- }
- });
- return use;
- };
-
- var updateLookup = function(layerId, groupStr) {
- groupStr = groupStr || models.layers.activeLayers;
- if (!useLookup(layerId, groupStr)) {
- delete self[groupStr][layerId];
- return;
- }
- var lookup = {};
- var active = self[groupStr][layerId].maps;
- lodashEach(active, function(vectorStyle, index) {
- var oldLegend = vectorStyle.legend;
- var entries = vectorStyle.entries;
- var legend = {
- colors: [],
- minLabel: oldLegend.minLabel,
- maxLabel: oldLegend.maxLabel,
- tooltips: oldLegend.tooltips,
- units: oldLegend.units,
- type: entries.type,
- title: entries.title,
- id: oldLegend.id
- };
- var source = entries.colors;
- var target = vectorStyle.custom
- ? self.getCustomVectorStyle(vectorStyle.custom).colors
- : source;
-
- var min = vectorStyle.min || 0;
- var max = vectorStyle.max || source.length;
-
- var sourceCount = source.length;
- var targetCount = target.length;
-
- lodashEach(source, function(color, index) {
- var targetColor;
- if (index < min || index > max) {
- targetColor = '00000000';
- } else {
- var sourcePercent, targetIndex;
- if (vectorStyle.squash) {
- sourcePercent = (index - min) / (max - min);
- if (index === max) {
- sourcePercent = 1.0;
- }
- targetIndex = Math.floor(sourcePercent * targetCount);
- if (targetIndex >= targetCount) {
- targetIndex = targetCount - 1;
- }
- } else {
- sourcePercent = index / sourceCount;
- targetIndex = Math.floor(sourcePercent * targetCount);
- }
- targetColor = target[targetIndex];
- }
- legend.colors.push(targetColor);
- var lookupSource =
- lodashParseInt(color.substring(0, 2), 16) +
- ',' +
- lodashParseInt(color.substring(2, 4), 16) +
- ',' +
- lodashParseInt(color.substring(4, 6), 16) +
- ',' +
- lodashParseInt(color.substring(6, 8), 16);
- var lookupTarget = {
- r: lodashParseInt(targetColor.substring(0, 2), 16),
- g: lodashParseInt(targetColor.substring(2, 4), 16),
- b: lodashParseInt(targetColor.substring(4, 6), 16),
- a: lodashParseInt(targetColor.substring(6, 8), 16)
- };
- lookup[lookupSource] = lookupTarget;
- });
- vectorStyle.legend = legend;
- });
- self[groupStr][layerId].lookup = lookup;
- };
-
- return self;
-}