Interactive interface for browsing global, full-resolution satellite imagery
wv-2820 eslint (#4599)
Tom Carielloed284cba69f1
diff --git a/web/.eslintrc b/web/.eslintrcindex feb923f59..e4be9a994 100644--- a/web/.eslintrc+++ b/web/.eslintrc@@ -91,14 +91,6 @@"props": false}],- "no-use-before-define": [ // 238 errors across 56 files- "error",- {- "functions": false,- "classes": true,- "variables": false- }- ],// Import rules overrides"import/no-cycle": "warn",// Accesibility rules overridesdiff --git a/web/js/components/animation-widget/gif-panel.js b/web/js/components/animation-widget/gif-panel.jsindex db76f391d..f7b48018a 100644--- a/web/js/components/animation-widget/gif-panel.js+++ b/web/js/components/animation-widget/gif-panel.js@@ -9,6 +9,16 @@ import { getDimensions } from '../../modules/image-download/util';const MAX_GIF_SIZE = 250;const MAX_IMAGE_DIMENSION_SIZE = 8200;+const isFileSizeValid = function(requestSize, imgHeight, imgWidth) {+ return (+ requestSize < MAX_GIF_SIZE+ && imgHeight !== 0+ && imgWidth !== 0+ && imgHeight <= MAX_IMAGE_DIMENSION_SIZE+ && imgWidth <= MAX_IMAGE_DIMENSION_SIZE+ );+};+/** A react component, Builds a rather specific* interactive widget@@ -120,12 +130,3 @@ GifPanel.propTypes = {speed: PropTypes.number,startDate: PropTypes.string,};-const isFileSizeValid = function(requestSize, imgHeight, imgWidth) {- return (- requestSize < MAX_GIF_SIZE- && imgHeight !== 0- && imgWidth !== 0- && imgHeight <= MAX_IMAGE_DIMENSION_SIZE- && imgWidth <= MAX_IMAGE_DIMENSION_SIZE- );-};diff --git a/web/js/components/animation-widget/play-queue.js b/web/js/components/animation-widget/play-queue.jsindex 207ad8731..431b762dc 100644--- a/web/js/components/animation-widget/play-queue.js+++ b/web/js/components/animation-widget/play-queue.js@@ -355,18 +355,19 @@ class PlayQueue extends React.Component {animationInterval(ms, callback) {const start = document.timeline.currentTime;- const frame = (time) => {- if (this.abortController.signal.aborted) return;- callback(time);- scheduleFrame(time);- };const scheduleFrame = (time) => {const elapsedTime = time - start;const roundedElapsedTime = Math.round(elapsedTime / ms) * ms;const targetNext = start + roundedElapsedTime + ms;const delay = targetNext - performance.now();+ // eslint-disable-next-line no-use-before-definesetTimeout(() => requestAnimationFrame(frame), delay);};+ const frame = (time) => {+ if (this.abortController.signal.aborted) return;+ callback(time);+ scheduleFrame(time);+ };scheduleFrame(start);}diff --git a/web/js/components/charting/chart-component.js b/web/js/components/charting/chart-component.jsindex 47d9088c9..41441408a 100644--- a/web/js/components/charting/chart-component.js+++ b/web/js/components/charting/chart-component.js@@ -10,11 +10,25 @@ function ChartComponent (props) {} = props;const { data } = liveData;- const yAxisValuesArr = getYAxisValues(data);// Arbitrary array of colors to useconst lineColors = ['#8884D8', '#82CA9D', 'orange', 'pink', 'green', 'red', 'yellow', 'aqua', 'maroon'];+ function formatToThreeDigits(str) {+ return parseFloat(str).toFixed(3);+ }++ /**+ * Return an array of provided min & max values buffered by 10%+ * @param {number} min | the lowest mean value of the collected data+ * @param {number} max | the highest mean value of the collected data+ */+ function bufferYAxisMinAndMax(min, max) {+ const yAxisMin = Math.floor(min * 4) / 4;+ const yAxisMax = Math.ceil(max * 4) / 4;+ return [yAxisMin - yAxisMin * 0.1, yAxisMax + yAxisMax * 0.1];+ }+/*** Process the data & determine the min & max MEAN values to establish the Y Axis Scale* @param {Object} axisData@@ -35,15 +49,16 @@ function ChartComponent (props) {return bufferYAxisMinAndMax(lowestMin, highestMax);}+ const yAxisValuesArr = getYAxisValues(data);+/**- * Return an array of provided min & max values buffered by 10%- * @param {number} min | the lowest mean value of the collected data- * @param {number} max | the highest mean value of the collected data+ * Extracts each key from the provided object & returns the list, removing 'name' from the collection+ * @param {Object} chartData*/- function bufferYAxisMinAndMax(min, max) {- const yAxisMin = Math.floor(min * 4) / 4;- const yAxisMax = Math.ceil(max * 4) / 4;- return [yAxisMin - yAxisMin * 0.1, yAxisMax + yAxisMax * 0.1];+ function getLineNames(obj) {+ // Add additional fields to the chart here!!+ const linesToInclude = ['mean'];+ return Object.keys(obj[0]).filter((val) => linesToInclude.indexOf(val) > -1);}/**@@ -64,16 +79,6 @@ function ChartComponent (props) {return chartLinesArr;}- /**- * Extracts each key from the provided object & returns the list, removing 'name' from the collection- * @param {Object} chartData- */- function getLineNames(obj) {- // Add additional fields to the chart here!!- const linesToInclude = ['mean'];- return Object.keys(obj[0]).filter((val) => linesToInclude.indexOf(val) > -1);- }-/*** Processes each date in the chart data, computes & returns the averages as "quick statistics"* @param {Object} chartData@@ -147,10 +152,6 @@ function ChartComponent (props) {);}- function formatToThreeDigits(str) {- return parseFloat(str).toFixed(3);- }-return (<div className="charting-chart-container"><div className="charting-chart-text">diff --git a/web/js/components/date-selector/date-selector.js b/web/js/components/date-selector/date-selector.jsindex fc2ad72ec..777635bf9 100644--- a/web/js/components/date-selector/date-selector.js+++ b/web/js/components/date-selector/date-selector.js@@ -43,27 +43,6 @@ function DateSelector(props) {const prevDate = usePrevious(date);- useEffect(() => {- // parent arrow clicks should override any temporary values within date selector- if (!prevDate || prevDate.getTime() !== date.getTime()) {- clearTimeValuesAndValidation();- }- }, [date]);-- useEffect(() => {- const {- year,- month,- day,- hour,- minute,- } = dateObj;- const anyPendingTimeUnits = year || month || day || hour || minute;- if (anyPendingTimeUnits) {- updateDate();- }- }, [dateObj.year, dateObj.month, dateObj.day, dateObj.hour, dateObj.minute]);-/*** @desc add individual timeunit input*@@ -252,23 +231,6 @@ function DateSelector(props) {return false;};- /**- * @desc update date with newDate if valid from check and then reset temp time values- *- * @param {String} dateIn- * @param {Boolean} isRollDate- * @returns {void}- */- const updateDate = (dateIn = date, isRollDate = false) => {- const newDate = updateDateCheck(dateIn, isRollDate);-- if (newDate) {- onDateChange(newDate);- // clear the pending timeunit inputs and reset validation- clearTimeValuesAndValidation();- }- };-/*** @desc clear temp time values and reset time validation booleans*@@ -289,6 +251,44 @@ function DateSelector(props) {});};+ useEffect(() => {+ // parent arrow clicks should override any temporary values within date selector+ if (!prevDate || prevDate.getTime() !== date.getTime()) {+ clearTimeValuesAndValidation();+ }+ }, [date]);++ /**+ * @desc update date with newDate if valid from check and then reset temp time values+ *+ * @param {String} dateIn+ * @param {Boolean} isRollDate+ * @returns {void}+ */+ const updateDate = (dateIn = date, isRollDate = false) => {+ const newDate = updateDateCheck(dateIn, isRollDate);++ if (newDate) {+ onDateChange(newDate);+ // clear the pending timeunit inputs and reset validation+ clearTimeValuesAndValidation();+ }+ };++ useEffect(() => {+ const {+ year,+ month,+ day,+ hour,+ minute,+ } = dateObj;+ const anyPendingTimeUnits = year || month || day || hour || minute;+ if (anyPendingTimeUnits) {+ updateDate();+ }+ }, [dateObj.year, dateObj.month, dateObj.day, dateObj.hour, dateObj.minute]);+const {year,month,diff --git a/web/js/components/kiosk/animation-tile-check/animation-tile-check.js b/web/js/components/kiosk/animation-tile-check/animation-tile-check.jsindex d386b176f..1d1a34d31 100644--- a/web/js/components/kiosk/animation-tile-check/animation-tile-check.js+++ b/web/js/components/kiosk/animation-tile-check/animation-tile-check.js@@ -21,12 +21,6 @@ function AnimationTileCheck(props) {const [frameDates, setFrameDates] = useState([]);- // This component is only renered when kioskMode is active & eic is subdaily or daily animation- // This means we can listen to the animation play trigger once the tileError check has completed- useEffect(() => {- if (isPlaying) getFrameDates();- }, [isPlaying]);-// Get an array of each frame date for duration of animationfunction determineFrameDates() {const getNextDate = (date) => util.dateAdd(date, interval, delta);@@ -47,6 +41,12 @@ function AnimationTileCheck(props) {setFrameDates([...frameDatesArray]);}+ // This component is only renered when kioskMode is active & eic is subdaily or daily animation+ // This means we can listen to the animation play trigger once the tileError check has completed+ useEffect(() => {+ if (isPlaying) getFrameDates();+ }, [isPlaying]);+return (<DateRangeTileCheck frameDates={frameDates} activeLayers={activeLayers} config={config} proj={proj} zoom={zoom} />);diff --git a/web/js/components/kiosk/animation-tile-check/date-range-tile-check.js b/web/js/components/kiosk/animation-tile-check/date-range-tile-check.jsindex 3e297f89f..c72c0079c 100644--- a/web/js/components/kiosk/animation-tile-check/date-range-tile-check.js+++ b/web/js/components/kiosk/animation-tile-check/date-range-tile-check.js@@ -39,12 +39,6 @@ function DateRangeTileCheck(props) {const dispatch = useDispatch();const toggleCheckedAnimationAvailability = (available) => { dispatch(toggleCheckedAnimationAvailabilityAction(available)); };- useEffect(() => {- if (frameDates.length) {- getAvailability();- }- }, [frameDates]);-const calcExtentsFromLimits = (matrixSet, matrixSetLimits, day) => {let extent;let origin;@@ -241,6 +235,12 @@ function DateRangeTileCheck(props) {}}+ useEffect(() => {+ if (frameDates.length) {+ getAvailability();+ }+ }, [frameDates]);+return null;}diff --git a/web/js/components/layer/product-picker/product-picker.js b/web/js/components/layer/product-picker/product-picker.jsindex c6793f5b9..be24aa767 100644--- a/web/js/components/layer/product-picker/product-picker.js+++ b/web/js/components/layer/product-picker/product-picker.js@@ -125,6 +125,21 @@ const mapDispatchToProps = (dispatch) => ({},});+const getModalWidth = function(width) {+ const availableWidth = width - width * 0.15;+ const gridItemWidth = 310;+ let sizeMultiplier = Math.floor(availableWidth / gridItemWidth);+ if (sizeMultiplier < 1) {+ sizeMultiplier = 1;+ }+ if (sizeMultiplier > 3) {+ sizeMultiplier = 3;+ }+ const gutterSpace = (sizeMultiplier - 1) * 10;+ const modalPadding = 26;+ return gridItemWidth * sizeMultiplier + gutterSpace + modalPadding;+};+const mapStateToProps = (state) => {const {screenSize,@@ -153,18 +168,3 @@ export default withSearch(mapStateToProps,mapDispatchToProps,)(ProductPicker));--const getModalWidth = function(width) {- const availableWidth = width - width * 0.15;- const gridItemWidth = 310;- let sizeMultiplier = Math.floor(availableWidth / gridItemWidth);- if (sizeMultiplier < 1) {- sizeMultiplier = 1;- }- if (sizeMultiplier > 3) {- sizeMultiplier = 3;- }- const gutterSpace = (sizeMultiplier - 1) * 10;- const modalPadding = 26;- return gridItemWidth * sizeMultiplier + gutterSpace + modalPadding;-};diff --git a/web/js/components/layer/settings/band-selection/band-selection-menu.js b/web/js/components/layer/settings/band-selection/band-selection-menu.jsindex 86c41622e..0d61e6ecc 100644--- a/web/js/components/layer/settings/band-selection/band-selection-menu.js+++ b/web/js/components/layer/settings/band-selection/band-selection-menu.js@@ -14,14 +14,16 @@ import { onClose } from '../../../../modules/modal/actions';export default function BandSelection({ layer }) {const dispatch = useDispatch();- const updateBandCombination = (id, bandCombo) => { dispatch(updateBandCombinationAction(id, bandCombo, layerIndex)); };- const removeLayer = (id) => { dispatch(removeLayerAction(id)); };- const closeModal = () => { dispatch(onClose()); };const { activeLayers } = useSelector((state) => ({activeLayers: getActiveLayers(state, state.compare.activeString).map((layer) => layer),}));-const layerIndex = activeLayers.findIndex((activeLayer) => activeLayer.id === layer.id);+ const updateBandCombination = (id, bandCombo) => {+ dispatch(updateBandCombinationAction(id, bandCombo, layerIndex));+ };+ const removeLayer = (id) => { dispatch(removeLayerAction(id)); };+ const closeModal = () => { dispatch(onClose()); };+const [selectedPreset, setSelectedPreset] = useState(null);const [bandSelection, setBandSelection] = useState({diff --git a/web/js/components/layer/settings/palette.js b/web/js/components/layer/settings/palette.jsindex d1f8ac8fc..599206f42 100644--- a/web/js/components/layer/settings/palette.js+++ b/web/js/components/layer/settings/palette.js@@ -22,24 +22,6 @@ function PaletteSelect (props) {const [activePalette, setActivePalette] = useState(initialActivePalette);- const renderDefault = () => {- const legend = getDefaultLegend(layer.id, index);- if (legend.type === 'continuous' || legend.type === 'discrete') {- return renderSelectorItemScale(- legend.colors,- '__default',- legend,- activePalette === '__default',- );- }- return renderSelectorItemSingle(- legend,- '__default',- 'Default',- activePalette === '__default',- );- };-/*** Clears the custom palette if Id is set to __default* @param {String} id | colormap Id@@ -54,33 +36,40 @@ function PaletteSelect (props) {};/**- * Renders as renderSelectorItemScale or renderSelectorItemSingle depending on if- * the source type is continuous or discrete.+ * Render classification customs when there is only one+ * Color in colormap+ * @param {Object} palette | Palette object* @param {String} id | colormap Id+ * @param {String} description | Colormap name+ * @param {Boolean} isSelected | is this colormap active*/- const customLegend = (id) => {- const source = getDefaultLegend(layer.id, index);- const target = getCustomPalette(id);- const targetType = target.colors.length === 1 ? 'classification' : 'continuous';+ const renderSelectorItemSingle = (palette, id, description, isSelected) => {+ const color = palette.classes+ ? palette.classes.colors[0]+ : palette.colors[0];+ const caseDefaultClassName = 'wv-palette-selector-row wv-checkbox wv-checkbox-round gray ';+ const checkedClassName = isSelected ? 'checked' : '';+ const isInvisible = color === '00000000';- if ((source.type === 'continuous' && targetType === 'continuous')- || (source.type === 'discrete' && targetType === 'continuous')) {- const translated = palettesTranslate(source.colors, target.colors);- return renderSelectorItemScale(- translated,- id,- target,- activePalette === target.id,- );- }- if (source.type === 'classification' && targetType === 'classification') {- return renderSelectorItemSingle(- target,- id,- target.name,- activePalette === target.id,- );- }+ return (+ <div key={id} className={caseDefaultClassName + checkedClassName}>+ <input+ id={`wv-palette-radio-${id}`}+ type="radio"+ name="wv-palette-radio"+ onClick={() => onChangePalette(id)}+ />+ <label htmlFor={`wv-palette-radio-${id}`}>+ <span+ className={isInvisible ? 'checkerbox-bg wv-palettes-class' : 'wv-palettes-class'}+ style={isInvisible ? null : { backgroundColor: util.hexToRGBA(color) }}+ >+ + </span>+ <span className="wv-palette-label">{description}</span>+ </label>+ </div>+ );};/**@@ -117,41 +106,52 @@ function PaletteSelect (props) {);};+ const renderDefault = () => {+ const legend = getDefaultLegend(layer.id, index);+ if (legend.type === 'continuous' || legend.type === 'discrete') {+ return renderSelectorItemScale(+ legend.colors,+ '__default',+ legend,+ activePalette === '__default',+ );+ }+ return renderSelectorItemSingle(+ legend,+ '__default',+ 'Default',+ activePalette === '__default',+ );+ };+/**- * Render classification customs when there is only one- * Color in colormap- * @param {Object} palette | Palette object+ * Renders as renderSelectorItemScale or renderSelectorItemSingle depending on if+ * the source type is continuous or discrete.* @param {String} id | colormap Id- * @param {String} description | Colormap name- * @param {Boolean} isSelected | is this colormap active*/- const renderSelectorItemSingle = (palette, id, description, isSelected) => {- const color = palette.classes- ? palette.classes.colors[0]- : palette.colors[0];- const caseDefaultClassName = 'wv-palette-selector-row wv-checkbox wv-checkbox-round gray ';- const checkedClassName = isSelected ? 'checked' : '';- const isInvisible = color === '00000000';+ const customLegend = (id) => {+ const source = getDefaultLegend(layer.id, index);+ const target = getCustomPalette(id);+ const targetType = target.colors.length === 1 ? 'classification' : 'continuous';- return (- <div key={id} className={caseDefaultClassName + checkedClassName}>- <input- id={`wv-palette-radio-${id}`}- type="radio"- name="wv-palette-radio"- onClick={() => onChangePalette(id)}- />- <label htmlFor={`wv-palette-radio-${id}`}>- <span- className={isInvisible ? 'checkerbox-bg wv-palettes-class' : 'wv-palettes-class'}- style={isInvisible ? null : { backgroundColor: util.hexToRGBA(color) }}- >- - </span>- <span className="wv-palette-label">{description}</span>- </label>- </div>- );+ if ((source.type === 'continuous' && targetType === 'continuous')+ || (source.type === 'discrete' && targetType === 'continuous')) {+ const translated = palettesTranslate(source.colors, target.colors);+ return renderSelectorItemScale(+ translated,+ id,+ target,+ activePalette === target.id,+ );+ }+ if (source.type === 'classification' && targetType === 'classification') {+ return renderSelectorItemSingle(+ target,+ id,+ target.name,+ activePalette === target.id,+ );+ }};const recommended = layer.palette.recommended || [];diff --git a/web/js/components/map/ol-measure-tool.js b/web/js/components/map/ol-measure-tool.jsindex f86466b9c..b0fa5363e 100644--- a/web/js/components/map/ol-measure-tool.js+++ b/web/js/components/map/ol-measure-tool.js@@ -62,7 +62,16 @@ function OlMeasureTool (props) {const {map, olMap, crs, unitOfMeasure, toggleMeasureActive, updateMeasurements, projections, proj,} = props;- const previousCrs = usePrevious(crs);++ const areaBgFill = new OlStyleFill({+ color: 'rgba(213, 78, 33, 0.1)',+ });++ const solidBlackLineStroke = new OlStyleStroke({+ color: 'rgba(0, 0, 0, 1)',+ lineJoin: 'round',+ width: 5,+ });function usePrevious(data) {const ref = useRef();@@ -72,69 +81,20 @@ function OlMeasureTool (props) {return ref.current;}- // Monitor for projection change & terminate any incomplete measurement from the previous projection- useEffect(() => {- if (olMap != null) {- const regionFromCrs = {- [CRS.GEOGRAPHIC]: 'geographic',- [CRS.ARCTIC]: 'arctic',- [CRS.ANTARCTIC]: 'antarctic',- };-- const geographyToTerminate = regionFromCrs[previousCrs];- terminateDraw(map.ui.proj[geographyToTerminate]);-- if (document.getElementsByClassName('tooltip-active').length > 0) {- map.ui.proj[geographyToTerminate].removeOverlay(tooltipOverlay);- }- }- }, [crs]);-- useEffect(() => {- if (!init) {- projections.forEach((key) => {- allMeasurements[key] = {};- vectorLayers[key] = null;- sources[key] = new OlVectorSource({ wrapX: false });- });- init = true;- }- }, [projections]);-- useEffect(() => {- const dlGeoJSON = () => downloadGeoJSON(allMeasurements[crs], crs);-- if (map && map.rendered) {- events.on(MEASURE_DISTANCE, initDistanceMeasurement);- events.on(MEASURE_AREA, initAreaMeasurement);- events.on(MEASURE_CLEAR, clearMeasurements);- events.on(MEASURE_DOWNLOAD_GEOJSON, dlGeoJSON);- }- return () => {- if (map && map.rendered) {- events.off(MEASURE_DISTANCE, initDistanceMeasurement);- events.off(MEASURE_AREA, initAreaMeasurement);- events.off(MEASURE_CLEAR, clearMeasurements);- events.off(MEASURE_DOWNLOAD_GEOJSON, dlGeoJSON);- }- };- }, [map, unitOfMeasure]);-- useEffect(recalculateAllMeasurements, [unitOfMeasure]);-- useEffect(recalculateAllMeasurements, [crs]);-- // we need this to make sure we have the latest version of olMap in renderToolTip()- useEffect(recalculateAllMeasurements, [olMap]);+ const previousCrs = usePrevious(crs);- const areaBgFill = new OlStyleFill({- color: 'rgba(213, 78, 33, 0.1)',- });- const solidBlackLineStroke = new OlStyleStroke({- color: 'rgba(0, 0, 0, 1)',- lineJoin: 'round',- width: 5,- });+ /**+ * End the current measurement interaction & remove the visual representation from the map+ */+ const terminateDraw = (olMapToTerminate = olMap) => {+ tooltipElement = null;+ toggleMeasureActive(false);+ olMapToTerminate.removeInteraction(draw);+ OlObservableUnByKey(drawChangeListener);+ OlObservableUnByKey(rightClickListener);+ OlObservableUnByKey(twoFingerTouchListener);+ events.trigger(MAP_ENABLE_CLICK_ZOOM);+ };/*** Call the appropriate transform function to add great circle arcs to@@ -152,7 +112,7 @@ function OlMeasureTool (props) {return geometry;};- const drawStyles = [+ const vectorStyles = [new OlStyle({fill: areaBgFill,stroke: solidBlackLineStroke,@@ -161,24 +121,14 @@ function OlMeasureTool (props) {new OlStyle({stroke: new OlStyleStroke({color: '#fff',- lineDash: [10, 20],lineJoin: 'round',width: 2,}),- image: new OlStyleCircle({- radius: 7,- stroke: new OlStyleStroke({- color: 'rgba(0, 0, 0, 0.7)',- }),- fill: new OlStyleFill({- color: 'rgba(255, 255, 255, 0.3)',- }),- }),geometry: styleGeometryFn,}),];- const vectorStyles = [+ const drawStyles = [new OlStyle({fill: areaBgFill,stroke: solidBlackLineStroke,@@ -187,9 +137,19 @@ function OlMeasureTool (props) {new OlStyle({stroke: new OlStyleStroke({color: '#fff',+ lineDash: [10, 20],lineJoin: 'round',width: 2,}),+ image: new OlStyleCircle({+ radius: 7,+ stroke: new OlStyleStroke({+ color: 'rgba(0, 0, 0, 0.7)',+ }),+ fill: new OlStyleFill({+ color: 'rgba(255, 255, 255, 0.3)',+ }),+ }),geometry: styleGeometryFn,}),];@@ -217,19 +177,6 @@ function OlMeasureTool (props) {);};- /**- * End the current measurement interaction & remove the visual representation from the map- */- const terminateDraw = (olMapToTerminate = olMap) => {- tooltipElement = null;- toggleMeasureActive(false);- olMapToTerminate.removeInteraction(draw);- OlObservableUnByKey(drawChangeListener);- OlObservableUnByKey(rightClickListener);- OlObservableUnByKey(twoFingerTouchListener);- events.trigger(MAP_ENABLE_CLICK_ZOOM);- };-const drawStartCallback = ({ feature }) => {let tooltipCoord;events.trigger(MAP_DISABLE_CLICK_ZOOM);@@ -304,25 +251,10 @@ function OlMeasureTool (props) {olMap.removeOverlay(tooltipOverlay);});}+const initDistanceMeasurement = () => initMeasurement('distance');const initAreaMeasurement = () => initMeasurement('area');- /**- * Go through every tooltip and recalculate the measurement based on- * current settings of unit of measurement- */- function recalculateAllMeasurements() {- Object.values(allMeasurements).forEach((measurementsForProj) => {- Object.values(measurementsForProj).forEach(- ({ feature, overlay }) => {- renderTooltip(feature, overlay);- feature.getGeometry().changed();- overlay.setOffset([0, -7]);- },- );- });- }-/*** Clear all existing measurements on the current map projection*/@@ -344,6 +276,77 @@ function OlMeasureTool (props) {}}+ // Monitor for projection change & terminate any incomplete measurement from the previous projection+ useEffect(() => {+ if (olMap != null) {+ const regionFromCrs = {+ [CRS.GEOGRAPHIC]: 'geographic',+ [CRS.ARCTIC]: 'arctic',+ [CRS.ANTARCTIC]: 'antarctic',+ };++ const geographyToTerminate = regionFromCrs[previousCrs];+ terminateDraw(map.ui.proj[geographyToTerminate]);++ if (document.getElementsByClassName('tooltip-active').length > 0) {+ map.ui.proj[geographyToTerminate].removeOverlay(tooltipOverlay);+ }+ }+ }, [crs]);++ useEffect(() => {+ if (!init) {+ projections.forEach((key) => {+ allMeasurements[key] = {};+ vectorLayers[key] = null;+ sources[key] = new OlVectorSource({ wrapX: false });+ });+ init = true;+ }+ }, [projections]);++ useEffect(() => {+ const dlGeoJSON = () => downloadGeoJSON(allMeasurements[crs], crs);++ if (map && map.rendered) {+ events.on(MEASURE_DISTANCE, initDistanceMeasurement);+ events.on(MEASURE_AREA, initAreaMeasurement);+ events.on(MEASURE_CLEAR, clearMeasurements);+ events.on(MEASURE_DOWNLOAD_GEOJSON, dlGeoJSON);+ }+ return () => {+ if (map && map.rendered) {+ events.off(MEASURE_DISTANCE, initDistanceMeasurement);+ events.off(MEASURE_AREA, initAreaMeasurement);+ events.off(MEASURE_CLEAR, clearMeasurements);+ events.off(MEASURE_DOWNLOAD_GEOJSON, dlGeoJSON);+ }+ };+ }, [map, unitOfMeasure]);++ /**+ * Go through every tooltip and recalculate the measurement based on+ * current settings of unit of measurement+ */+ function recalculateAllMeasurements() {+ Object.values(allMeasurements).forEach((measurementsForProj) => {+ Object.values(measurementsForProj).forEach(+ ({ feature, overlay }) => {+ renderTooltip(feature, overlay);+ feature.getGeometry().changed();+ overlay.setOffset([0, -7]);+ },+ );+ });+ }++ useEffect(recalculateAllMeasurements, [unitOfMeasure]);++ useEffect(recalculateAllMeasurements, [crs]);++ // we need this to make sure we have the latest version of olMap in renderToolTip()+ useEffect(recalculateAllMeasurements, [olMap]);+return null;}@@ -353,6 +356,9 @@ OlMeasureTool.propTypes = {crs: PropTypes.string,toggleMeasureActive: PropTypes.func,unitOfMeasure: PropTypes.string,+ updateMeasurements: PropTypes.func,+ projections: PropTypes.array,+ proj: PropTypes.object,};const mapDispatchToProps = (dispatch) => ({diff --git a/web/js/components/sidebar/charting-mode-options.js b/web/js/components/sidebar/charting-mode-options.jsindex 6de9e1251..2237ffb55 100644--- a/web/js/components/sidebar/charting-mode-options.js+++ b/web/js/components/sidebar/charting-mode-options.js@@ -67,25 +67,27 @@ function ChartingModeOptions (props) {updateRequestStatusMessage,} = props;- useEffect(() => {- if (!init) {- projections.forEach((key) => {- AOIFeatureObj[key] = {};- vectorLayers[key] = null;- sources[key] = new OlVectorSource({ wrapX: false });- });- init = true;+ function endDrawingAreaOfInterest () {+ if (draw) {+ olMap.removeInteraction(draw);}- }, [projections]);+ }- useEffect(() => {- resetAreaOfInterest();- endDrawingAreaOfInterest();- }, [isChartingActive]);+ function resetAreaOfInterest() {+ Object.values(AOIFeatureObj[crs]).forEach(+ ({ feature }) => {+ sources[crs].removeFeature(feature);+ },+ );- const { initialStartDate, initialEndDate } = initializeDates(timeSpanStartDate, timeSpanEndDate);- const primaryDate = formatDateString(initialStartDate);- const secondaryDate = formatDateString(initialEndDate);+ if (vectorLayers[crs]) {+ vectorLayers[crs].setMap(null);+ vectorLayers[crs] = null;+ }++ toggleAreaOfInterestSelected(false);+ updateAOICoordinates(null);+ }/*** Processes the start & end times & aligns them with the timeline if values are undefined@@ -98,13 +100,34 @@ function ChartingModeOptions (props) {return { initialStartDate: startDate, initialEndDate: endDate };}- const onAreaOfInterestButtonClick = (evt) => {+ /**+ * Filters the layers array & returns those with visible set to 'true'.+ */+ function getLiveLayers() {+ return activeLayers.filter((obj) => obj.visible === true);+ }++ function formatDateString(dateObj) {+ const date = new Date(dateObj);+ const year = date.getFullYear();+ const month = date.toLocaleString('default', { month: 'short' });+ const day = `0${date.getDate()}`.slice(-2);+ return `${year} ${month} ${day}`;+ }++ function getAreaOfInterestCoordinates(geometry) {+ updateAOICoordinates(geometry.getExtent());+ }++ const drawEndCallback = ({ feature }) => {+ // Add the draw feature to the collection+ AOIFeatureObj[crs][feature.ol_uid] = {+ feature,+ };+ endDrawingAreaOfInterest();toggleAreaOfInterestActive();- if (!aoiActive) {- beginDrawingAOI();- } else {- endDrawingAreaOfInterest();- }+ toggleAreaOfInterestSelected();+ getAreaOfInterestCoordinates(feature.getGeometry());};function beginDrawingAOI () {@@ -135,42 +158,35 @@ function ChartingModeOptions (props) {}}- const drawEndCallback = ({ feature }) => {- // Add the draw feature to the collection- AOIFeatureObj[crs][feature.ol_uid] = {- feature,- };- endDrawingAreaOfInterest();- toggleAreaOfInterestActive();- toggleAreaOfInterestSelected();- getAreaOfInterestCoordinates(feature.getGeometry());- };-- function endDrawingAreaOfInterest () {- if (draw) {- olMap.removeInteraction(draw);+ useEffect(() => {+ if (!init) {+ projections.forEach((key) => {+ AOIFeatureObj[key] = {};+ vectorLayers[key] = null;+ sources[key] = new OlVectorSource({ wrapX: false });+ });+ init = true;}- }+ }, [projections]);- function resetAreaOfInterest() {- Object.values(AOIFeatureObj[crs]).forEach(- ({ feature }) => {- sources[crs].removeFeature(feature);- },- );+ useEffect(() => {+ resetAreaOfInterest();+ endDrawingAreaOfInterest();+ }, [isChartingActive]);- if (vectorLayers[crs]) {- vectorLayers[crs].setMap(null);- vectorLayers[crs] = null;+ const { initialStartDate, initialEndDate } = initializeDates(timeSpanStartDate, timeSpanEndDate);+ const primaryDate = formatDateString(initialStartDate);+ const secondaryDate = formatDateString(initialEndDate);++ const onAreaOfInterestButtonClick = (evt) => {+ toggleAreaOfInterestActive();+ if (!aoiActive) {+ beginDrawingAOI();+ } else {+ endDrawingAreaOfInterest();}+ };- toggleAreaOfInterestSelected(false);- updateAOICoordinates(null);- }-- function getAreaOfInterestCoordinates(geometry) {- updateAOICoordinates(geometry.getExtent());- }function getActiveChartingLayer() {const liveLayers = getLiveLayers();@@ -181,21 +197,6 @@ function ChartingModeOptions (props) {return null;}- /**- * Filters the layers array & returns those with visible set to 'true'.- */- function getLiveLayers() {- return activeLayers.filter((obj) => obj.visible === true);- }-- function formatDateString(dateObj) {- const date = new Date(dateObj);- const year = date.getFullYear();- const month = date.toLocaleString('default', { month: 'short' });- const day = `0${date.getDate()}`.slice(-2);- return `${year} ${month} ${day}`;- }-function formatDateForImageStat(dateStr) {const dateParts = dateStr.split(' ');const year = dateParts[0];@@ -204,56 +205,6 @@ function ChartingModeOptions (props) {return `${year}-${month}-${day}`;}- async function onRequestChartClick() {- updateChartRequestStatus(true);- const layerInfo = getActiveChartingLayer();- if (layerInfo == null) {- updateChartRequestStatus(false, 'No valid layer detected for request.');- return;- }- const requestedLayerSource = layerInfo.projections.geographic.source;- if (requestedLayerSource === 'GIBS:geographic') {- const uriParameters = getImageStatRequestParameters(layerInfo, timeSpanSelection);- const requestURI = getImageStatStatsRequestURL(uriParameters);- const data = await getImageStatData(requestURI);-- if (!data.ok) {- updateChartRequestStatus(false, 'Chart request failed.');- return;- }-- // unit determination: renderedPalettes- const paletteName = layerInfo.palette.id;- const paletteLegend = renderedPalettes[paletteName].maps[0].legend;- const unitOfMeasure = Object.prototype.hasOwnProperty.call(paletteLegend, 'units') ? `(${paletteLegend.units})` : '';- console.log(unitOfMeasure);- const dataToRender = {- title: layerInfo.title,- subtitle: layerInfo.subtitle,- unit: unitOfMeasure,- ...data.body,- ...uriParameters,- };-- if (timeSpanSelection === 'range') {- const rechartsData = formatGIBSDataForRecharts(dataToRender);- displayChart({- title: dataToRender.title,- subtitle: dataToRender.subtitle,- unit: dataToRender.unit,- data: rechartsData,- });- updateChartRequestStatus(false, 'Success');- } else {- displaySimpleStats(dataToRender);- updateChartRequestStatus(false, 'Success');- }- } else {- // handle requests for layers outside of GIBS here!- updateChartRequestStatus(false, 'Unable to process non-GIBS layer.');- }- }-function updateChartRequestStatus(status, message = '') {updateRequestInProgress(status);updateRequestStatusMessage(message);@@ -276,14 +227,14 @@ function ChartingModeOptions (props) {* @param {Object} layerInfo* @param {String} timeSpanSelection | 'Date' for single date, 'Range' for date range, 'series' for time series charting*/- function getImageStatRequestParameters(layerInfo, timeSpanSelection) {+ function getImageStatRequestParameters(layerInfo, timeSpan) {const startDateForImageStat = formatDateForImageStat(primaryDate);const endDateForImageStat = formatDateForImageStat(secondaryDate);const AOIForImageStat = convertOLcoordsForImageStat(aoiCoordinates);return {timestamp: startDateForImageStat, // start dateendTimestamp: endDateForImageStat, // end date- type: timeSpanSelection === 'range' ? 'series' : 'date',+ type: timeSpan === 'range' ? 'series' : 'date',steps: 6, // the number of days selected within a given range/series. Use '1' for just the start and end date, '2' for start date, end date and middle date, etc.layer: layerInfo.id, // Layer to be pulled from gibs api. e.g. 'GHRSST_L4_MUR_Sea_Surface_Temperature'colormap: `${layerInfo.palette.id}.xml`, // Colormap to use to decipher layer. e.g. 'GHRSST_Sea_Surface_Temperature.xml'@@ -344,6 +295,10 @@ function ChartingModeOptions (props) {}}+ function getKeysFromObj(data) {+ return Object.keys(data);+ }+/*** Process the ImageStat (GIBS) data for use in the Recharts library* @param {Object} data | This contains the name (dates) & min, max, stddev, etc. for each step requested@@ -366,8 +321,54 @@ function ChartingModeOptions (props) {return rechartsData;}- function getKeysFromObj(data) {- return Object.keys(data);+ async function onRequestChartClick() {+ updateChartRequestStatus(true);+ const layerInfo = getActiveChartingLayer();+ if (layerInfo == null) {+ updateChartRequestStatus(false, 'No valid layer detected for request.');+ return;+ }+ const requestedLayerSource = layerInfo.projections.geographic.source;+ if (requestedLayerSource === 'GIBS:geographic') {+ const uriParameters = getImageStatRequestParameters(layerInfo, timeSpanSelection);+ const requestURI = getImageStatStatsRequestURL(uriParameters);+ const data = await getImageStatData(requestURI);++ if (!data.ok) {+ updateChartRequestStatus(false, 'Chart request failed.');+ return;+ }++ // unit determination: renderedPalettes+ const paletteName = layerInfo.palette.id;+ const paletteLegend = renderedPalettes[paletteName].maps[0].legend;+ const unitOfMeasure = Object.prototype.hasOwnProperty.call(paletteLegend, 'units') ? `(${paletteLegend.units})` : '';+ console.log(unitOfMeasure);+ const dataToRender = {+ title: layerInfo.title,+ subtitle: layerInfo.subtitle,+ unit: unitOfMeasure,+ ...data.body,+ ...uriParameters,+ };++ if (timeSpanSelection === 'range') {+ const rechartsData = formatGIBSDataForRecharts(dataToRender);+ displayChart({+ title: dataToRender.title,+ subtitle: dataToRender.subtitle,+ unit: dataToRender.unit,+ data: rechartsData,+ });+ updateChartRequestStatus(false, 'Success');+ } else {+ displaySimpleStats(dataToRender);+ updateChartRequestStatus(false, 'Success');+ }+ } else {+ // handle requests for layers outside of GIBS here!+ updateChartRequestStatus(false, 'Unable to process non-GIBS layer.');+ }}function onDateIconClick() {diff --git a/web/js/components/timeline/custom-interval-selector/delta-input.js b/web/js/components/timeline/custom-interval-selector/delta-input.jsindex ce4f93489..94ac7c791 100644--- a/web/js/components/timeline/custom-interval-selector/delta-input.js+++ b/web/js/components/timeline/custom-interval-selector/delta-input.js@@ -32,6 +32,19 @@ function DeltaInput(props) {}};+ const handleBlur = () => {+ if (value >= 1 && value < 1000) {+ setValid(true);+ changeDelta(value);+ } else {+ setValid(false);+ }+ };++ const handleFocus = (e) => {+ e.target.select();+ };+const handleKeyPress = (e) => {if (value === '' || regex.test(value)) {const numberValue = Number(value);@@ -49,19 +62,6 @@ function DeltaInput(props) {}};- const handleFocus = (e) => {- e.target.select();- };-- const handleBlur = () => {- if (value >= 1 && value < 1000) {- setValid(true);- changeDelta(value);- } else {- setValid(false);- }- };-return (<inputclassName="custom-interval-delta-input no-drag"diff --git a/web/js/components/timeline/mobile-date-picker.js b/web/js/components/timeline/mobile-date-picker.jsindex ca475bce2..b7e6127d1 100644--- a/web/js/components/timeline/mobile-date-picker.js+++ b/web/js/components/timeline/mobile-date-picker.js@@ -79,6 +79,12 @@ function MobileDatePicker(props) {const [maxDate, setMaxDate] = useState(convertToUTCDateObject(endDateLimit));const [isOpen, setIsOpen] = useState(false);+ const setInitDates = () => {+ setTime(convertToUTCDateObject(date));+ setMinDate(convertToUTCDateObject(startDateLimit));+ setMaxDate(convertToUTCDateObject(endDateLimit));+ };+useEffect(() => {setInitDates();}, [endDateLimit, date]);@@ -107,12 +113,6 @@ function MobileDatePicker(props) {onDateChange(getISODateFormatted(date));};- const setInitDates = () => {- setTime(convertToUTCDateObject(date));- setMinDate(convertToUTCDateObject(startDateLimit));- setMaxDate(convertToUTCDateObject(endDateLimit));- };-const getHeaderTime = (time, isSubdaily) => (<div className="datepicker-header">{getDisplayDate(new Date(convertToLocalDateObject(time)), isSubdaily)}diff --git a/web/js/containers/animation-widget/animation-widget.js b/web/js/containers/animation-widget/animation-widget.jsindex 035074746..ee758a847 100644--- a/web/js/containers/animation-widget/animation-widget.js+++ b/web/js/containers/animation-widget/animation-widget.js@@ -105,6 +105,14 @@ function AnimationWidget (props) {const prevSubDailyMode = usePrevious(subDailyMode);const prevHasFutureLayers = usePrevious(hasFutureLayers);+ const toggleCollapse = () => {+ onToggleAnimationCollapse();+ };++ const toggleAutoplay = () => {+ onToggleAnimationAutoplay();+ };+// component did mountuseEffect(() => {if (isEmbedModeActive) {@@ -148,14 +156,6 @@ function AnimationWidget (props) {return draggableTargets.some((tClass) => classList.contains(tClass));};- const toggleCollapse = () => {- onToggleAnimationCollapse();- };-- const toggleAutoplay = () => {- onToggleAnimationAutoplay();- };-const onExpandedDrag = (e, position) => {const { x, y } = position;setUserHasMovedWidget(true);diff --git a/web/js/containers/map-interactions/ol-vector-interactions.test.js b/web/js/containers/map-interactions/ol-vector-interactions.test.jsindex 930b952dd..2cccc7cf8 100644--- a/web/js/containers/map-interactions/ol-vector-interactions.test.js+++ b/web/js/containers/map-interactions/ol-vector-interactions.test.js@@ -47,6 +47,12 @@ beforeEach(() => {};});+function doAsync(c) {+ setTimeout(() => {+ c(true);+ }, 10);+}+test('if there is a feature at pixel dispatch changeCursor action', () => {map.hasFeatureAtPixel = () => true;map.forEachFeatureAtPixel = () => {};@@ -72,8 +78,3 @@ test('Check that hover changes', () => {test('Check that cursor-hover class is not present', () => {expect(component.toJSON()).toMatchSnapshot();});-function doAsync(c) {- setTimeout(() => {- c(true);- }, 10);-}diff --git a/web/js/containers/sidebar/layer-row.js b/web/js/containers/sidebar/layer-row.jsindex 0579f75c7..db1903a09 100644--- a/web/js/containers/sidebar/layer-row.js+++ b/web/js/containers/sidebar/layer-row.js@@ -346,6 +346,12 @@ function LayerRow (props) {const collectionClass = collections?.type === 'NRT' ? 'collection-title badge rounded-pill bg-secondary' : 'collection-title badge rounded-pill text-dark bg-light';+ const makeActiveForCharting = (layer) => {+ if (layer !== activeChartingLayer) {+ updateActiveChartingLayer(layer);+ }+ };+const renderLayerRow = () => (<>{(!isEmbedModeActive && !isChartingActive) && (@@ -438,11 +444,6 @@ function LayerRow (props) {</>);- const makeActiveForCharting = (layer) => {- if (layer !== activeChartingLayer) {- updateActiveChartingLayer(layer);- }- };return (<DraggableisDragDisabled={isEmbedModeActive || isAnimating}diff --git a/web/js/containers/timeline/timeline.js b/web/js/containers/timeline/timeline.jsindex b2b176dbb..3b12d403f 100644--- a/web/js/containers/timeline/timeline.js+++ b/web/js/containers/timeline/timeline.js@@ -74,6 +74,96 @@ const preventDefaultFunc = (e) => {e.preventDefault();};+// get axisWidth and parentOffset for axis, footer, and leftOffset calculations+const getOffsetValues = (innerWidth, hasSubDaily) => {+ const parentOffset = (hasSubDaily ? 414 : 310) + 10;+ const width = innerWidth - parentOffset - 88;+ return { width, parentOffset };+};++// check if left arrow should be disabled on predicted decrement+const checkLeftArrowDisabled = (+ date,+ delta,+ timeScaleChangeUnit,+ timelineStartDateLimit,+) => {+ const nextDecMoment = moment.utc(date).subtract(delta, timeScaleChangeUnit);+ const nextDecrementDate = new Date(nextDecMoment.seconds(0).format());+ const minMinusDeltaMoment = moment.utc(timelineStartDateLimit).subtract(delta, timeScaleChangeUnit);+ const minMinusDeltaDate = new Date(minMinusDeltaMoment.seconds(0).format());++ const nextDecrementDateTime = nextDecrementDate.getTime();+ const minMinusDeltaDateTime = minMinusDeltaDate.getTime();+ return nextDecrementDateTime <= minMinusDeltaDateTime;+};++// check if right arrow should be disabled on predicted increment+const checkRightArrowDisabled = (+ date,+ delta,+ timeScaleChangeUnit,+ timelineEndDateLimit,+) => {+ const nextIncMoment = moment.utc(date).add(delta, timeScaleChangeUnit);+ const nextIncrementDate = new Date(nextIncMoment.seconds(0).format());++ const nextIncrementDateTime = nextIncrementDate.getTime();+ const maxPlusDeltaDateTime = new Date(timelineEndDateLimit).getTime();+ return nextIncrementDateTime > maxPlusDeltaDateTime;+};++const checkNowButtonDisabled = (+ date,+ timelineEndDateLimit,+ hasFutureLayers,+ nowOverride,+ appNow,+) => {+ const dateTimeMoment = new Date(moment.utc(date).seconds(0).format());+ let maxDateMoment;+ if (nowOverride || hasFutureLayers) {+ maxDateMoment = new Date(moment.utc(appNow).seconds(0).format());+ } else {+ maxDateMoment = new Date(moment.utc(timelineEndDateLimit).seconds(0).format());+ }+ return dateTimeMoment.getTime() === maxDateMoment.getTime();+};++// get timelineEndDateLimit based on potential future layers+const getTimelineEndDateLimit = (state) => {+ const {+ date, layers, compare, proj,+ } = state;+ const { appNow } = date;+ const activeLayers = getActiveLayers(state);++ let layerDateRange;+ if (compare.active) {+ // use all layers to keep timeline axis range consistent when switching between A/B+ const compareALayersFiltered = filterProjLayersWithStartDate(layers.active.layers, proj.id);+ const compareBLayersFiltered = filterProjLayersWithStartDate(layers.activeB.layers, proj.id);+ layerDateRange = getDateRange({}, [...compareALayersFiltered, ...compareBLayersFiltered]);+ } else {+ const activeLayersFiltered = filterProjLayersWithStartDate(activeLayers, proj.id);+ layerDateRange = getDateRange({}, activeLayersFiltered);+ }++ let timelineEndDateLimit;+ if (layerDateRange && layerDateRange.end > appNow) {+ const layerDateRangeEndRoundedQuarterHour = util.roundTimeQuarterHour(layerDateRange.end);+ const appNowRoundedQuarterHour = util.roundTimeQuarterHour(appNow);+ if (layerDateRangeEndRoundedQuarterHour.getTime() > appNowRoundedQuarterHour.getTime()) {+ // if layerDateRange.end is after the set rounded quarter hour time, then update+ timelineEndDateLimit = getISODateFormatted(layerDateRangeEndRoundedQuarterHour);+ }+ } else {+ timelineEndDateLimit = getISODateFormatted(appNow);+ }+ return timelineEndDateLimit;+};++class Timeline extends React.Component {constructor(props) {super(props);@@ -1657,92 +1747,3 @@ Timeline.propTypes = {triggerTodayButton: PropTypes.func,updateAppNow: PropTypes.func,};--// get axisWidth and parentOffset for axis, footer, and leftOffset calculations-const getOffsetValues = (innerWidth, hasSubDaily) => {- const parentOffset = (hasSubDaily ? 414 : 310) + 10;- const width = innerWidth - parentOffset - 88;- return { width, parentOffset };-};--// check if left arrow should be disabled on predicted decrement-const checkLeftArrowDisabled = (- date,- delta,- timeScaleChangeUnit,- timelineStartDateLimit,-) => {- const nextDecMoment = moment.utc(date).subtract(delta, timeScaleChangeUnit);- const nextDecrementDate = new Date(nextDecMoment.seconds(0).format());- const minMinusDeltaMoment = moment.utc(timelineStartDateLimit).subtract(delta, timeScaleChangeUnit);- const minMinusDeltaDate = new Date(minMinusDeltaMoment.seconds(0).format());-- const nextDecrementDateTime = nextDecrementDate.getTime();- const minMinusDeltaDateTime = minMinusDeltaDate.getTime();- return nextDecrementDateTime <= minMinusDeltaDateTime;-};--// check if right arrow should be disabled on predicted increment-const checkRightArrowDisabled = (- date,- delta,- timeScaleChangeUnit,- timelineEndDateLimit,-) => {- const nextIncMoment = moment.utc(date).add(delta, timeScaleChangeUnit);- const nextIncrementDate = new Date(nextIncMoment.seconds(0).format());-- const nextIncrementDateTime = nextIncrementDate.getTime();- const maxPlusDeltaDateTime = new Date(timelineEndDateLimit).getTime();- return nextIncrementDateTime > maxPlusDeltaDateTime;-};--const checkNowButtonDisabled = (- date,- timelineEndDateLimit,- hasFutureLayers,- nowOverride,- appNow,-) => {- const dateTimeMoment = new Date(moment.utc(date).seconds(0).format());- let maxDateMoment;- if (nowOverride || hasFutureLayers) {- maxDateMoment = new Date(moment.utc(appNow).seconds(0).format());- } else {- maxDateMoment = new Date(moment.utc(timelineEndDateLimit).seconds(0).format());- }- return dateTimeMoment.getTime() === maxDateMoment.getTime();-};--// get timelineEndDateLimit based on potential future layers-const getTimelineEndDateLimit = (state) => {- const {- date, layers, compare, proj,- } = state;- const { appNow } = date;- const activeLayers = getActiveLayers(state);-- let layerDateRange;- if (compare.active) {- // use all layers to keep timeline axis range consistent when switching between A/B- const compareALayersFiltered = filterProjLayersWithStartDate(layers.active.layers, proj.id);- const compareBLayersFiltered = filterProjLayersWithStartDate(layers.activeB.layers, proj.id);- layerDateRange = getDateRange({}, [...compareALayersFiltered, ...compareBLayersFiltered]);- } else {- const activeLayersFiltered = filterProjLayersWithStartDate(activeLayers, proj.id);- layerDateRange = getDateRange({}, activeLayersFiltered);- }-- let timelineEndDateLimit;- if (layerDateRange && layerDateRange.end > appNow) {- const layerDateRangeEndRoundedQuarterHour = util.roundTimeQuarterHour(layerDateRange.end);- const appNowRoundedQuarterHour = util.roundTimeQuarterHour(appNow);- if (layerDateRangeEndRoundedQuarterHour.getTime() > appNowRoundedQuarterHour.getTime()) {- // if layerDateRange.end is after the set rounded quarter hour time, then update- timelineEndDateLimit = getISODateFormatted(layerDateRangeEndRoundedQuarterHour);- }- } else {- timelineEndDateLimit = getISODateFormatted(appNow);- }- return timelineEndDateLimit;-};diff --git a/web/js/containers/tour.js b/web/js/containers/tour.jsindex fe3d9c679..2191c02ae 100644--- a/web/js/containers/tour.js+++ b/web/js/containers/tour.js@@ -42,6 +42,15 @@ import util from '../util/util';const { HIDE_TOUR } = safeLocalStorage.keys;+const getTransitionAttr = function(transition) {+ if (!transition) return '';+ const { element, action } = transition;+ if (element === 'animation' && action === 'play') {+ return '&playanim=true';+ }+ return '';+};+class Tour extends React.Component {constructor(props) {super(props);@@ -556,15 +565,6 @@ const mapStateToProps = (state) => {};};-const getTransitionAttr = function(transition) {- if (!transition) return '';- const { element, action } = transition;- if (element === 'animation' && action === 'play') {- return '&playanim=true';- }- return '';-};-export default connect(mapStateToProps,mapDispatchToProps,diff --git a/web/js/map/compare/spy.js b/web/js/map/compare/spy.jsindex dcb3362e1..82f6934e5 100644--- a/web/js/map/compare/spy.js+++ b/web/js/map/compare/spy.js@@ -10,6 +10,127 @@ const DEFAULT_RADIUS = 140;let radius = DEFAULT_RADIUS;let label = null;+/**+ * Clip everything but the circle+ * @param {Object} event | Event object+ */+const inverseClip = function(event) {+ const ctx = event.context;+ ctx.save();+ ctx.beginPath();+ if (mousePosition) {+ // only show a circle around the mouse+ const pixel = getRenderPixel(event, mousePosition);+ const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]);+ const canvasRadius = Math.sqrt(((offset[0] - pixel[0]) ** 2) + ((offset[1] - pixel[1]) ** 2));+ ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);+ ctx.closePath();+ ctx.lineWidth = (5 * canvasRadius) / radius;+ ctx.strokeStyle = 'rgba(0,0,0,0.5)';+ ctx.clip();+ ctx.clearRect(0, 0, offset, offset);+ }+};++/**+ * Clip the circle of a layer so users can see through+ */+const clip = function(event) {+ const ctx = event.context;+ ctx.save();+ ctx.beginPath();+ if (mousePosition) {+ // only show a circle around the mouse+ const pixel = getRenderPixel(event, mousePosition);+ const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]);+ const canvasRadius = Math.sqrt(((offset[0] - pixel[0]) ** 2) + ((offset[1] - pixel[1]) ** 2));+ ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);+ ctx.lineWidth = (5 * canvasRadius) / radius;+ ctx.strokeStyle = 'rgba(0,0,0,0.5)';+ ctx.stroke();+ }+ ctx.clip();+};++const restore = function(event) {+ const ctx = event.context;+ ctx.restore();+};++/**+ * Layers need to be inversely clipped so that they can't be seen through+ * the other layergroup in cases where the layergroups layer opacity is < 100%+ * @param {Object} layer | Ol Layer object+ */+const applyReverseLayerListeners = function(layer) {+ layer.on('postrender', inverseClip);+ layer.on('postrender', restore);+ bottomLayers.push(layer);+};++/**+ * Add listeners for layer clipping+ * @param {Object} layer | Ol Layer object+ */+const applyLayerListeners = function(layer) {+ layer.on('prerender', clip);+ layer.on('postrender', restore);+ topLayers.push(layer);+};++/**+ * Remove all listeners from layer group+ * @param {Array} layers | Layer group+ */+const removeListenersFromLayers = function(layers) {+ lodashEach(layers, (layer) => {+ layer.un('prerender', clip);+ layer.un('postrender', restore);+ });+};++/**+ * Remove all listeners from layer group+ * @param {Array} layers | Layer group+ */+const removeInverseListenersFromLayers = function(layers) {+ lodashEach(layers, (layer) => {+ layer.un('prerender', inverseClip);+ layer.un('postrender', restore);+ });+};++/**+ * Recursively apply listeners to layers+ * @param {Object} layer | Layer or layer Group obj+ * @param {Object} map | OL Map Object+ * @param {Function} callback | Function that will apply event listeners to layer+ */+const applyEventsToBaseLayers = function(layer, map, callback) {+ const layers = layer.get('layers');+ if (layers) {+ lodashEach(layers.getArray(), (layer) => {+ applyEventsToBaseLayers(layer, map, callback);+ });+ } else {+ callback(layer);+ }+};++const isCompareA = (state) => state.compare.isCompareA;++const getDateText = function(state) {+ const isBInside = isCompareA(state);+ const { dateA, dateB } = getCompareDates(state);+ const isSameDate = dateA === dateB;+ let innerHtml = isBInside ? 'B' : 'A';+ if (!isSameDate) {+ const dateText = isBInside ? dateB : dateA;+ innerHtml += `: <span class="monospace">${dateText}</span>`;+ }+ return innerHtml;+};+export default class Spy {constructor(olMap, store) {this.mapCase = document.getElementById('wv-map');@@ -124,124 +245,3 @@ export default class Spy {return this.mapCase;}}--/**- * Layers need to be inversely clipped so that they can't be seen through- * the other layergroup in cases where the layergroups layer opacity is < 100%- * @param {Object} layer | Ol Layer object- */-const applyReverseLayerListeners = function(layer) {- layer.on('postrender', inverseClip);- layer.on('postrender', restore);- bottomLayers.push(layer);-};--/**- * Add listeners for layer clipping- * @param {Object} layer | Ol Layer object- */-const applyLayerListeners = function(layer) {- layer.on('prerender', clip);- layer.on('postrender', restore);- topLayers.push(layer);-};--/**- * Clip everything but the circle- * @param {Object} event | Event object- */-const inverseClip = function(event) {- const ctx = event.context;- ctx.save();- ctx.beginPath();- if (mousePosition) {- // only show a circle around the mouse- const pixel = getRenderPixel(event, mousePosition);- const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]);- const canvasRadius = Math.sqrt(((offset[0] - pixel[0]) ** 2) + ((offset[1] - pixel[1]) ** 2));- ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);- ctx.closePath();- ctx.lineWidth = (5 * canvasRadius) / radius;- ctx.strokeStyle = 'rgba(0,0,0,0.5)';- ctx.clip();- ctx.clearRect(0, 0, offset, offset);- }-};--/**- * Clip the circle of a layer so users can see through- */-const clip = function(event) {- const ctx = event.context;- ctx.save();- ctx.beginPath();- if (mousePosition) {- // only show a circle around the mouse- const pixel = getRenderPixel(event, mousePosition);- const offset = getRenderPixel(event, [mousePosition[0] + radius, mousePosition[1]]);- const canvasRadius = Math.sqrt(((offset[0] - pixel[0]) ** 2) + ((offset[1] - pixel[1]) ** 2));- ctx.arc(pixel[0], pixel[1], canvasRadius, 0, 2 * Math.PI);- ctx.lineWidth = (5 * canvasRadius) / radius;- ctx.strokeStyle = 'rgba(0,0,0,0.5)';- ctx.stroke();- }- ctx.clip();-};--const restore = function(event) {- const ctx = event.context;- ctx.restore();-};--/**- * Remove all listeners from layer group- * @param {Array} layers | Layer group- */-const removeListenersFromLayers = function(layers) {- lodashEach(layers, (layer) => {- layer.un('prerender', clip);- layer.un('postrender', restore);- });-};--/**- * Remove all listeners from layer group- * @param {Array} layers | Layer group- */-const removeInverseListenersFromLayers = function(layers) {- lodashEach(layers, (layer) => {- layer.un('prerender', inverseClip);- layer.un('postrender', restore);- });-};--/**- * Recursively apply listeners to layers- * @param {Object} layer | Layer or layer Group obj- * @param {Object} map | OL Map Object- * @param {Function} callback | Function that will apply event listeners to layer- */-const applyEventsToBaseLayers = function(layer, map, callback) {- const layers = layer.get('layers');- if (layers) {- lodashEach(layers.getArray(), (layer) => {- applyEventsToBaseLayers(layer, map, callback);- });- } else {- callback(layer);- }-};--const getDateText = function(state) {- const isBInside = isCompareA(state);- const { dateA, dateB } = getCompareDates(state);- const isSameDate = dateA === dateB;- let innerHtml = isBInside ? 'B' : 'A';- if (!isSameDate) {- const dateText = isBInside ? dateB : dateA;- innerHtml += `: <span class="monospace">${dateText}</span>`;- }- return innerHtml;-};--const isCompareA = (state) => state.compare.isCompareA;diff --git a/web/js/map/compare/swipe.js b/web/js/map/compare/swipe.jsindex 2685b51ce..e40a68ca0 100644--- a/web/js/map/compare/swipe.js+++ b/web/js/map/compare/swipe.js@@ -35,120 +35,6 @@ const applyListenersB = function(layer) {layer.on('postrender', restore);};-export default class Swipe {- constructor(- olMap,- store,- eventListenerStringObj,- valueOverride,- ) {- listenerObj = eventListenerStringObj;- this.map = olMap;- percentSwipe = valueOverride / 100;- this.create(store);- window.addEventListener('resize', () => {- if (document.querySelector('.ab-swipe-line')) {- this.destroy();- this.create(store);- }- });- }-- create(store) {- const state = store.getState();- const { dateA, dateB } = getCompareDates(state);- this.dateA = dateA;- this.dateB = dateB;- line = addLineOverlay(this.map, this.dateA, this.dateB, this.updateExtents);- this.update(store);- }-- destroy = () => {- mapCase.removeChild(line);- lodashEach(layersSideA, (layer) => {- layer.un('prerender', this.setClipMaskA);- layer.un('postrender', restore);- });- lodashEach(layersSideB, (layer) => {- layer.un('prerender', this.setClipMaskB);- layer.un('postrender', restore);- });- layersSideA = [];- layersSideB = [];- };-- getSwipeOffset = () => swipeOffset;-- update(store) {- const state = store.getState();- const { dateA, dateB } = getCompareDates(state);-- if (dateA !== this.dateA || dateB !== this.dateB) {- this.destroy();- this.create(store);- } else {- const layerGroups = this.map.getLayers().getArray();- layersSideA = layerGroups[0].getLayersArray();- layersSideB = layerGroups[1].getLayersArray();- layersSideA.forEach((l) => {- this.applyEventListeners(l, applyListenersA);- });- layersSideB.forEach((l) => {- this.applyEventListeners(l, applyListenersB);- });- }- }-- applyEventListeners(layer, callback) {- const layers = layer.get('layers');- if (layers) {- lodashEach(layers.getArray(), (l) => {- this.applyEventListeners(l, callback);- });- } else {- callback.call(this, layer);- }- }-- /**- * Set Clipping mask for the "A" side of a comparison.- * Note: The "B" side is layered above the "A" side on the DOM.- * We must mask the "A" side in case the B side has no imagery- * @param {Object} event | Openlayers Precompose event object- */- setClipMaskA = (event) => {- const ctx = event.context;- const mapSize = this.map.getSize();- const widthSideA = mapSize[0] * percentSwipe;-- const coordinates = {- topLeft: getRenderPixel(event, [0, 0]),- bottomLeft: getRenderPixel(event, [0, mapSize[1]]),- bottomRight: getRenderPixel(event, [widthSideA, mapSize[1]]),- topRight: getRenderPixel(event, [widthSideA, 0]),- };- setRectClipMask(ctx, coordinates);- };-- /**- * Set Clipping mask for the "B" side of a comparison.- * Note: The "B" side is layered above the "A" side on the DOM.- * @param {Object} event | Openlayers Precompose event object- */- setClipMaskB = (event) => {- const ctx = event.context;- const mapSize = this.map.getSize();- const widthSideB = mapSize[0] * percentSwipe;- const coordinates = {- topLeft: getRenderPixel(event, [widthSideB, 0]),- bottomLeft: getRenderPixel(event, [widthSideB, mapSize[1]]),- bottomRight: getRenderPixel(event, mapSize),- topRight: getRenderPixel(event, [mapSize[0], 0]),- };- setRectClipMask(ctx, coordinates);- };-}-/*** Apply a rectangular clipping mask from the provided coordinates* @param {CanvasRenderingContext2D} context | Canvas context requiring a clipping mask@@ -173,6 +59,46 @@ const setRectClipMask = function(context, coordinates) {context.clip();};+const dragLine = function(listenerObj, lineCaseEl, map) {+ function move(evt) {+ if (!dragging) {+ dragging = true;+ events.trigger(COMPARE_MOVE_START);+ }+ const windowWidth = window.innerWidth;+ if (listenerObj.type === 'default') evt.preventDefault();+ evt.stopPropagation();++ if (listenerObj.type === 'touch') {+ swipeOffset = evt.touches[0].pageX;+ } else {+ swipeOffset = evt.clientX;+ }+ // Prevent swiper from being swiped off screen+ swipeOffset = swipeOffset > windowWidth - SWIPE_PADDING+ ? windowWidth - SWIPE_PADDING+ : swipeOffset < SWIPE_PADDING+ ? SWIPE_PADDING+ : swipeOffset;+ percentSwipe = swipeOffset / windowWidth;+ lineCaseEl.style.transform = `translateX( ${swipeOffset}px)`;+ map.render();+ }++ function end(evt) {+ dragging = false;+ events.trigger(+ 'compare:moveend',+ lodashRound((swipeOffset / mapCase.offsetWidth) * 100, 0),+ );+ window.removeEventListener(listenerObj.move, move);+ window.removeEventListener(listenerObj.end, end);+ }++ window.addEventListener(listenerObj.move, move);+ window.addEventListener(listenerObj.end, end);+};+/*** Add Swiper* @param {Object} map | OL map object@@ -259,42 +185,116 @@ const addLineOverlay = function(map, dateA, dateB) {return lineCaseEl;};-const dragLine = function(listenerObj, lineCaseEl, map) {- function move(evt) {- if (!dragging) {- dragging = true;- events.trigger(COMPARE_MOVE_START);- }- const windowWidth = window.innerWidth;- if (listenerObj.type === 'default') evt.preventDefault();- evt.stopPropagation();+export default class Swipe {+ constructor(+ olMap,+ store,+ eventListenerStringObj,+ valueOverride,+ ) {+ listenerObj = eventListenerStringObj;+ this.map = olMap;+ percentSwipe = valueOverride / 100;+ this.create(store);+ window.addEventListener('resize', () => {+ if (document.querySelector('.ab-swipe-line')) {+ this.destroy();+ this.create(store);+ }+ });+ }- if (listenerObj.type === 'touch') {- swipeOffset = evt.touches[0].pageX;+ create(store) {+ const state = store.getState();+ const { dateA, dateB } = getCompareDates(state);+ this.dateA = dateA;+ this.dateB = dateB;+ line = addLineOverlay(this.map, this.dateA, this.dateB, this.updateExtents);+ this.update(store);+ }++ destroy = () => {+ mapCase.removeChild(line);+ lodashEach(layersSideA, (layer) => {+ layer.un('prerender', this.setClipMaskA);+ layer.un('postrender', restore);+ });+ lodashEach(layersSideB, (layer) => {+ layer.un('prerender', this.setClipMaskB);+ layer.un('postrender', restore);+ });+ layersSideA = [];+ layersSideB = [];+ };++ getSwipeOffset = () => swipeOffset;++ update(store) {+ const state = store.getState();+ const { dateA, dateB } = getCompareDates(state);++ if (dateA !== this.dateA || dateB !== this.dateB) {+ this.destroy();+ this.create(store);} else {- swipeOffset = evt.clientX;+ const layerGroups = this.map.getLayers().getArray();+ layersSideA = layerGroups[0].getLayersArray();+ layersSideB = layerGroups[1].getLayersArray();+ layersSideA.forEach((l) => {+ this.applyEventListeners(l, applyListenersA);+ });+ layersSideB.forEach((l) => {+ this.applyEventListeners(l, applyListenersB);+ });}- // Prevent swiper from being swiped off screen- swipeOffset = swipeOffset > windowWidth - SWIPE_PADDING- ? windowWidth - SWIPE_PADDING- : swipeOffset < SWIPE_PADDING- ? SWIPE_PADDING- : swipeOffset;- percentSwipe = swipeOffset / windowWidth;- lineCaseEl.style.transform = `translateX( ${swipeOffset}px)`;- map.render();}- function end(evt) {- dragging = false;- events.trigger(- 'compare:moveend',- lodashRound((swipeOffset / mapCase.offsetWidth) * 100, 0),- );- window.removeEventListener(listenerObj.move, move);- window.removeEventListener(listenerObj.end, end);+ applyEventListeners(layer, callback) {+ const layers = layer.get('layers');+ if (layers) {+ lodashEach(layers.getArray(), (l) => {+ this.applyEventListeners(l, callback);+ });+ } else {+ callback.call(this, layer);+ }}- window.addEventListener(listenerObj.move, move);- window.addEventListener(listenerObj.end, end);-};+ /**+ * Set Clipping mask for the "A" side of a comparison.+ * Note: The "B" side is layered above the "A" side on the DOM.+ * We must mask the "A" side in case the B side has no imagery+ * @param {Object} event | Openlayers Precompose event object+ */+ setClipMaskA = (event) => {+ const ctx = event.context;+ const mapSize = this.map.getSize();+ const widthSideA = mapSize[0] * percentSwipe;++ const coordinates = {+ topLeft: getRenderPixel(event, [0, 0]),+ bottomLeft: getRenderPixel(event, [0, mapSize[1]]),+ bottomRight: getRenderPixel(event, [widthSideA, mapSize[1]]),+ topRight: getRenderPixel(event, [widthSideA, 0]),+ };+ setRectClipMask(ctx, coordinates);+ };++ /**+ * Set Clipping mask for the "B" side of a comparison.+ * Note: The "B" side is layered above the "A" side on the DOM.+ * @param {Object} event | Openlayers Precompose event object+ */+ setClipMaskB = (event) => {+ const ctx = event.context;+ const mapSize = this.map.getSize();+ const widthSideB = mapSize[0] * percentSwipe;+ const coordinates = {+ topLeft: getRenderPixel(event, [widthSideB, 0]),+ bottomLeft: getRenderPixel(event, [widthSideB, mapSize[1]]),+ bottomRight: getRenderPixel(event, mapSize),+ topRight: getRenderPixel(event, [mapSize[0], 0]),+ };+ setRectClipMask(ctx, coordinates);+ };+}diff --git a/web/js/map/granule/granule-layer-builder.js b/web/js/map/granule/granule-layer-builder.jsindex 90b5be634..d966be571 100644--- a/web/js/map/granule/granule-layer-builder.js+++ b/web/js/map/granule/granule-layer-builder.js@@ -41,20 +41,21 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {dataType: 'json',timeout: 30 * 1000,};- const throttleDispathCMRErrorDialog = lodashThrottle(- dispathCMRErrorDialog.bind(this),- CMR_AJAX_OPTIONS.timeout,- { leading: true, trailing: false },- );function dispathCMRErrorDialog (title) {const bodyText = `The Common Metadata Repository (CMR) service that- provides metadata for this granule layer, ${title}, is currently unavailable.- Please try again later.`;+ provides metadata for this granule layer, ${title}, is currently unavailable.+ Please try again later.`;const modalHeader = 'Granules unavailable at this time.';store.dispatch(openBasicContent(modalHeader, bodyText));}+ const throttleDispathCMRErrorDialog = lodashThrottle(+ dispathCMRErrorDialog.bind(this),+ CMR_AJAX_OPTIONS.timeout,+ { leading: true, trailing: false },+ );+const showLoading = () => {store.dispatch(startLoading(LOADING_GRANULES));};@@ -190,6 +191,62 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {});};+ /**+ * Get granuleCount number of granules that have visible imagery based on+ * predetermined longitude bounds.+ *+ * @param {Array} availableGranules - available granules to be filtered+ * @param {number} granuleCount - number of granules to filter down to+ * @param {Date} leadingEdgeDate - timeline date+ * @returns {array}+ */+ const getVisibleGranules = (availableGranules, granuleCount, leadingEdgeDate) => {+ const { proj: { selected: { crs } } } = store.getState();+ const granules = [];+ const availableCount = availableGranules.length;+ if (!availableCount) return granules;+ const count = granuleCount > availableCount ? availableCount : granuleCount;++ for (let i = 0; granules.length < count; i += 1) {+ const item = availableGranules[i];+ if (!item) break;+ const { date } = item;+ if (new Date(date) <= leadingEdgeDate && isWithinBounds(crs, item)) {+ granules.unshift(item);+ }+ }++ if (granules.length < granuleCount) {+ console.warn('Could not find enough matching granules', `${granules.length}/${granuleCount}`);+ }+ return granules;+ };++ /**+ * @method getGranuleAttributes+ * @param {object} def+ * @param {object} options+ * @returns {object} granuleAttributes+ */+ const getGranuleAttributes = async (def, options) => {+ const state = store.getState();+ const { proj: { selected: { crs } } } = state;+ const { granuleCount, date, group } = options;+ const { count: currentCount } = getGranuleLayer(state, def.id) || {};+ const count = currentCount || granuleCount || DEFAULT_NUM_GRANULES;++ // get granule dates waiting for CMR query and filtering (if necessary)+ const availableGranules = await getQueriedGranuleDates(def, date, group);+ const visibleGranules = getVisibleGranules(availableGranules, count, date);+ const transformedGranules = transformGranulesForProj(visibleGranules, crs);++ return {+ count,+ granuleDates: transformedGranules.map((g) => g.date),+ visibleGranules: transformedGranules,+ };+ };+/*** @method createGranuleLayer* @param {object} def - Layer specs@@ -234,62 +291,6 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {return granuleLayer;};- /**- * @method getGranuleAttributes- * @param {object} def- * @param {object} options- * @returns {object} granuleAttributes- */- const getGranuleAttributes = async (def, options) => {- const state = store.getState();- const { proj: { selected: { crs } } } = state;- const { granuleCount, date, group } = options;- const { count: currentCount } = getGranuleLayer(state, def.id) || {};- const count = currentCount || granuleCount || DEFAULT_NUM_GRANULES;-- // get granule dates waiting for CMR query and filtering (if necessary)- const availableGranules = await getQueriedGranuleDates(def, date, group);- const visibleGranules = getVisibleGranules(availableGranules, count, date);- const transformedGranules = transformGranulesForProj(visibleGranules, crs);-- return {- count,- granuleDates: transformedGranules.map((g) => g.date),- visibleGranules: transformedGranules,- };- };-- /**- * Get granuleCount number of granules that have visible imagery based on- * predetermined longitude bounds.- *- * @param {Array} availableGranules - available granules to be filtered- * @param {number} granuleCount - number of granules to filter down to- * @param {Date} leadingEdgeDate - timeline date- * @returns {array}- */- const getVisibleGranules = (availableGranules, granuleCount, leadingEdgeDate) => {- const { proj: { selected: { crs } } } = store.getState();- const granules = [];- const availableCount = availableGranules.length;- if (!availableCount) return granules;- const count = granuleCount > availableCount ? availableCount : granuleCount;-- for (let i = 0; granules.length < count; i += 1) {- const item = availableGranules[i];- if (!item) break;- const { date } = item;- if (new Date(date) <= leadingEdgeDate && isWithinBounds(crs, item)) {- granules.unshift(item);- }- }-- if (granules.length < granuleCount) {- console.warn('Could not find enough matching granules', `${granules.length}/${granuleCount}`);- }- return granules;- };-return {getGranuleLayer: createGranuleLayer,};diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.jsindex 49babfe17..9badccdd2 100644--- a/web/js/map/layerbuilder.js+++ b/web/js/map/layerbuilder.js@@ -49,8 +49,6 @@ import {} from '../modules/map/constants';export default function mapLayerBuilder(config, cache, store) {- const { getGranuleLayer } = granuleLayerBuilder(cache, store, createLayerWMTS);-/*** Return a layer, or layergroup, created with the supplied function* @param {*} createLayerFunc@@ -151,122 +149,34 @@ export default function mapLayerBuilder(config, cache, store) {};/**- * Create a new OpenLayers Layer- * @param {object} def- * @param {object} key- * @param {object} options- * @param {object} dateOptions- * @param {object} granuleAttributes- * @returns {object} Openlayers TileLayer or LayerGroup- */- const createLayerWrapper = async (def, key, options, dateOptions) => {- const state = store.getState();- const { sidebar: { activeTab } } = state;- const proj = state.proj.selected;- const {- breakPointLayer,- id,- opacity,- period,- projections,- type,- wrapadjacentdays,- wrapX,- } = def;- const { nextDate, previousDate } = dateOptions;- let { date } = dateOptions;- let layer = cache.getItem(key);- const isGranule = type === 'granule';-- if (!layer || isGranule || def.type === 'ttiler') {- if (!date) date = options.date || getSelectedDate(state);- const cacheOptions = getCacheOptions(period, date);- const attributes = {- id,- key,- date,- proj: proj.id,- def,- group: options.group,- nextDate,- previousDate,- };- def = lodashCloneDeep(def);- lodashMerge(def, projections[proj.id]);- if (breakPointLayer) def = mergeBreakpointLayerAttributes(def, proj.id);- const isDataDownloadTabActive = activeTab === 'download';- const wrapDefined = wrapadjacentdays === true || wrapX;- const wrapLayer = proj.id === 'geographic' && !isDataDownloadTabActive && wrapDefined;-- if (!isGranule) {- switch (def.type) {- case 'wmts':- layer = getLayer(createLayerWMTS, def, options, attributes, wrapLayer);- break;- case 'vector':- layer = getLayer(createLayerVector, def, options, attributes, wrapLayer);- break;- case 'wms':- layer = getLayer(createLayerWMS, def, options, attributes, wrapLayer);- break;- case 'ttiler':- layer = await getLayer(createTtilerLayer, def, options, attributes, wrapLayer);- break;- default:- throw new Error(`Unknown layer type: ${type}`);- }- layer.wv = attributes;- cache.setItem(key, layer, cacheOptions);- if (def.type !== 'ttiler') layer.setVisible(false);- } else {- layer = await getGranuleLayer(def, attributes, options);- }- }- layer.setOpacity(opacity || 1.0);- if (breakPointLayer) {- layer.getLayersArray().forEach((l) => {- l.setOpacity(opacity || 1.0);- });- }- return layer;- };-- /**- * Create a new OpenLayers Layer+ * Create a layer key*- * @method createLayer+ * @function layerKey* @static- * @param {object} def - Layer Specs- * @param {object} options - Layer options- * @returns {object} OpenLayers layer+ * @param {Object} def - Layer properties+ * @param {number} options - Layer options+ * @param {boolean} precache+ * @returns {object} layer key Object*/- const createLayer = async (def, options = {}) => {- const state = store.getState();- const { compare: { activeString } } = state;- const { ui: { isKioskModeActive, displayStaticMap } } = state;-- options.group = options.group || activeString;+ const layerKey = (def, options, state) => {+ const { compare } = state;+ let date;+ const layerId = def.id;+ const projId = state.proj.id;+ let style = '';+ const activeGroupStr = options.group ? options.group : compare.activeString;- // if gibs/dns failure, display static image layer- if (displayStaticMap && isKioskModeActive) {- const layer = await createStaticImageLayer();- return layer;+ // Don't key by time if this is a static layer+ if (def.period) {+ date = util.toISOStringSeconds(util.roundTimeOneMinute(options.date));}-- const {- closestDate,- nextDate,- previousDate,- } = getRequestDates(def, options);- const date = closestDate;- if (date) {- options.date = date;+ if (isPaletteActive(def.id, activeGroupStr, state)) {+ style = getPaletteKeys(def.id, undefined, state);}- const dateOptions = { date, nextDate, previousDate };- const key = layerKey(def, options, state);- const layer = await createLayerWrapper(def, key, options, dateOptions);-- return layer;+ if (isVectorStyleActive(def.id, activeGroupStr, state)) {+ style = getVectorStyleKeys(def.id, undefined, state);+ }+ return [layerId, projId, date, style, activeGroupStr].join(':');};/**@@ -347,35 +257,60 @@ export default function mapLayerBuilder(config, cache, store) {return { closestDate, previousDate: previousLayerDate, nextDate: nextLayerDate };};+ const createStaticImageLayer = async() => {+ const state = store.getState();+ const { proj: { selected: { id, crs, maxExtent } } } = state;++ const projectionURL = `images/map/bluemarble-${id}.jpg`;++ const layer = new ImageLayer({+ source: new Static({+ url: projectionURL,+ projection: crs,+ imageExtent: maxExtent,+ }),+ });++ return layer;+ };+/**- * Create a layer key+ * Create a new OpenLayers Layer*- * @function layerKey+ * @method createLayer* @static- * @param {Object} def - Layer properties- * @param {number} options - Layer options- * @param {boolean} precache- * @returns {object} layer key Object+ * @param {object} def - Layer Specs+ * @param {object} options - Layer options+ * @returns {object} OpenLayers layer*/- const layerKey = (def, options, state) => {- const { compare } = state;- let date;- const layerId = def.id;- const projId = state.proj.id;- let style = '';- const activeGroupStr = options.group ? options.group : compare.activeString;+ const createLayer = async (def, options = {}) => {+ const state = store.getState();+ const { compare: { activeString } } = state;+ const { ui: { isKioskModeActive, displayStaticMap } } = state;- // Don't key by time if this is a static layer- if (def.period) {- date = util.toISOStringSeconds(util.roundTimeOneMinute(options.date));- }- if (isPaletteActive(def.id, activeGroupStr, state)) {- style = getPaletteKeys(def.id, undefined, state);+ options.group = options.group || activeString;++ // if gibs/dns failure, display static image layer+ if (displayStaticMap && isKioskModeActive) {+ const layer = await createStaticImageLayer();+ return layer;}- if (isVectorStyleActive(def.id, activeGroupStr, state)) {- style = getVectorStyleKeys(def.id, undefined, state);++ const {+ closestDate,+ nextDate,+ previousDate,+ } = getRequestDates(def, options);+ const date = closestDate;+ if (date) {+ options.date = date;}- return [layerId, projId, date, style, activeGroupStr].join(':');+ const dateOptions = { date, nextDate, previousDate };+ const key = layerKey(def, options, state);+ // eslint-disable-next-line no-use-before-define+ const layer = await createLayerWrapper(def, key, options, dateOptions);++ return layer;};/**@@ -435,24 +370,6 @@ export default function mapLayerBuilder(config, cache, store) {};};- const createStaticImageLayer = async() => {- const state = store.getState();- const { proj: { selected: { id, crs, maxExtent } } } = state;-- const projectionURL = `images/map/bluemarble-${id}.jpg`;-- const layer = new ImageLayer({- source: new Static({- url: projectionURL,- projection: crs,- imageExtent: maxExtent,- }),- });-- return layer;- };--/*** Create a new WMTS Layer* @method createLayerWMTS@@ -534,6 +451,96 @@ export default function mapLayerBuilder(config, cache, store) {});}+ const { getGranuleLayer } = granuleLayerBuilder(cache, store, createLayerWMTS);++ /**+ * Create a new WMS Layer+ *+ * @method createLayerWMS+ * @static+ * @param {object} def - Layer Specs+ * @param {object} options - Layer options+ * @returns {object} OpenLayers WMS layer+ */+ const createLayerWMS = function(def, options, day, state) {+ const { proj } = state;+ const selectedProj = proj.selected;+ let urlParameters;+ let date;+ let extent;+ let start;+ let res;++ const source = config.sources[def.source];+ extent = selectedProj.maxExtent;+ start = [selectedProj.maxExtent[0], selectedProj.maxExtent[3]];+ res = selectedProj.resolutions;+ if (!source) {+ throw new Error(`${def.id}: Invalid source: ${def.source}`);+ }++ const transparent = def.format === 'image/png';+ if (selectedProj.id === 'geographic') {+ res = getGeographicResolutionWMS(def.tileSize);+ }+ if (day) {+ if (day === 1) {+ extent = LEFT_WING_EXTENT;+ start = LEFT_WING_ORIGIN;+ } else {+ extent = RIGHT_WING_EXTENT;+ start = RIGHT_WING_ORIGIN;+ }+ }+ const parameters = {+ LAYERS: def.layer || def.id,+ FORMAT: def.format,+ TRANSPARENT: transparent,+ VERSION: '1.1.1',+ };+ if (def.styles) {+ parameters.STYLES = def.styles;+ }++ urlParameters = '';++ date = options.date || getSelectedDate(state);+ if (day && def.wrapadjacentdays) {+ date = util.dateAdd(date, 'day', day);+ }+ urlParameters = `?TIME=${util.toISOStringSeconds(util.roundTimeOneMinute(date))}`;++ const sourceOptions = {+ url: source.url + urlParameters,+ cacheSize: 4096,+ wrapX: true,+ style: 'default',+ crossOrigin: 'anonymous',+ params: parameters,+ transition: 0,+ tileGrid: new OlTileGridTileGrid({+ origin: start,+ resolutions: res,+ tileSize: def.tileSize || [512, 512],+ }),+ };+ if (isPaletteActive(def.id, options.group, state)) {+ const lookup = getPaletteLookup(def.id, options.group, state);+ sourceOptions.tileClass = lookupFactory(lookup, sourceOptions);+ }+ const resolutionBreakPoint = lodashGet(def, `breakPointLayer.projections.${proj.id}.resolutionBreakPoint`);+ const tileSource = new OlSourceTileWMS(sourceOptions);++ const layer = new OlLayerTile({+ preload: 0,+ extent,+ ...!!resolutionBreakPoint && { minResolution: resolutionBreakPoint },+ source: tileSource,+ });+ layer.isWMS = true;+ return layer;+ };+/**** @param {object} def - Layer Specs@@ -648,94 +655,6 @@ export default function mapLayerBuilder(config, cache, store) {return layer;};- /**- * Create a new WMS Layer- *- * @method createLayerWMS- * @static- * @param {object} def - Layer Specs- * @param {object} options - Layer options- * @returns {object} OpenLayers WMS layer- */- const createLayerWMS = function(def, options, day, state) {- const { proj } = state;- const selectedProj = proj.selected;- let urlParameters;- let date;- let extent;- let start;- let res;-- const source = config.sources[def.source];- extent = selectedProj.maxExtent;- start = [selectedProj.maxExtent[0], selectedProj.maxExtent[3]];- res = selectedProj.resolutions;- if (!source) {- throw new Error(`${def.id}: Invalid source: ${def.source}`);- }-- const transparent = def.format === 'image/png';- if (selectedProj.id === 'geographic') {- res = getGeographicResolutionWMS(def.tileSize);- }- if (day) {- if (day === 1) {- extent = LEFT_WING_EXTENT;- start = LEFT_WING_ORIGIN;- } else {- extent = RIGHT_WING_EXTENT;- start = RIGHT_WING_ORIGIN;- }- }- const parameters = {- LAYERS: def.layer || def.id,- FORMAT: def.format,- TRANSPARENT: transparent,- VERSION: '1.1.1',- };- if (def.styles) {- parameters.STYLES = def.styles;- }-- urlParameters = '';-- date = options.date || getSelectedDate(state);- if (day && def.wrapadjacentdays) {- date = util.dateAdd(date, 'day', day);- }- urlParameters = `?TIME=${util.toISOStringSeconds(util.roundTimeOneMinute(date))}`;-- const sourceOptions = {- url: source.url + urlParameters,- cacheSize: 4096,- wrapX: true,- style: 'default',- crossOrigin: 'anonymous',- params: parameters,- transition: 0,- tileGrid: new OlTileGridTileGrid({- origin: start,- resolutions: res,- tileSize: def.tileSize || [512, 512],- }),- };- if (isPaletteActive(def.id, options.group, state)) {- const lookup = getPaletteLookup(def.id, options.group, state);- sourceOptions.tileClass = lookupFactory(lookup, sourceOptions);- }- const resolutionBreakPoint = lodashGet(def, `breakPointLayer.projections.${proj.id}.resolutionBreakPoint`);- const tileSource = new OlSourceTileWMS(sourceOptions);-- const layer = new OlLayerTile({- preload: 0,- extent,- ...!!resolutionBreakPoint && { minResolution: resolutionBreakPoint },- source: tileSource,- });- layer.isWMS = true;- return layer;- };-const registerSearch = async (def, options, state) => {const { date } = state;let requestDate;@@ -850,6 +769,87 @@ export default function mapLayerBuilder(config, cache, store) {return layer;};+ /**+ * Create a new OpenLayers Layer+ * @param {object} def+ * @param {object} key+ * @param {object} options+ * @param {object} dateOptions+ * @param {object} granuleAttributes+ * @returns {object} Openlayers TileLayer or LayerGroup+ */+ const createLayerWrapper = async (def, key, options, dateOptions) => {+ const state = store.getState();+ const { sidebar: { activeTab } } = state;+ const proj = state.proj.selected;+ const {+ breakPointLayer,+ id,+ opacity,+ period,+ projections,+ type,+ wrapadjacentdays,+ wrapX,+ } = def;+ const { nextDate, previousDate } = dateOptions;+ let { date } = dateOptions;+ let layer = cache.getItem(key);+ const isGranule = type === 'granule';++ if (!layer || isGranule || def.type === 'ttiler') {+ if (!date) date = options.date || getSelectedDate(state);+ const cacheOptions = getCacheOptions(period, date);+ const attributes = {+ id,+ key,+ date,+ proj: proj.id,+ def,+ group: options.group,+ nextDate,+ previousDate,+ };+ def = lodashCloneDeep(def);+ lodashMerge(def, projections[proj.id]);+ if (breakPointLayer) def = mergeBreakpointLayerAttributes(def, proj.id);+ const isDataDownloadTabActive = activeTab === 'download';+ const wrapDefined = wrapadjacentdays === true || wrapX;+ const wrapLayer = proj.id === 'geographic' && !isDataDownloadTabActive && wrapDefined;++ if (!isGranule) {+ switch (def.type) {+ case 'wmts':+ layer = getLayer(createLayerWMTS, def, options, attributes, wrapLayer);+ break;+ case 'vector':+ layer = getLayer(createLayerVector, def, options, attributes, wrapLayer);+ break;+ case 'wms':+ layer = getLayer(createLayerWMS, def, options, attributes, wrapLayer);+ break;+ case 'ttiler':+ layer = await getLayer(createTtilerLayer, def, options, attributes, wrapLayer);+ break;+ default:+ throw new Error(`Unknown layer type: ${type}`);+ }+ layer.wv = attributes;+ cache.setItem(key, layer, cacheOptions);+ if (def.type !== 'ttiler') layer.setVisible(false);+ } else {+ layer = await getGranuleLayer(def, attributes, options);+ }+ }+ layer.setOpacity(opacity || 1.0);+ if (breakPointLayer) {+ layer.getLayersArray().forEach((l) => {+ l.setOpacity(opacity || 1.0);+ });+ }+ return layer;+ };+return {layerKey,createLayer,diff --git a/web/js/map/map.js b/web/js/map/map.jsindex 74ebebe4d..8068da831 100644--- a/web/js/map/map.js+++ b/web/js/map/map.js@@ -8,6 +8,35 @@ export const CRS_WGS_84 = 'EPSG:4326';export const CRS_WGS_84_QUERY_EXTENT = [-180, -60, 180, 60];+/**+ * Determines if an exent object contains valid values.+ *+ * @method isExtentValid+ * @static+ *+ * @param extent {OpenLayers.Bound} The extent to check.+ *+ * @return {boolean} False if any of the values is NaN, otherwise returns+ * true.+ */+export function mapIsExtentValid(extent) {+ if (lodashIsUndefined(extent)) {+ return false;+ }+ let valid = true;+ if (extent.toArray) {+ extent = extent.toArray();+ }+ lodashEach(extent, (value) => {+ // eslint-disable-next-line no-restricted-globals+ if (isNaN(value)) {+ valid = false;+ return false;+ }+ });+ return valid;+}+/** Checks to see if an extents string is found. If it exist* then it is changed from a string to an array which is then@@ -44,35 +73,6 @@ export function mapParser(state, errors) {}}-/**- * Determines if an exent object contains valid values.- *- * @method isExtentValid- * @static- *- * @param extent {OpenLayers.Bound} The extent to check.- *- * @return {boolean} False if any of the values is NaN, otherwise returns- * true.- */-export function mapIsExtentValid(extent) {- if (lodashIsUndefined(extent)) {- return false;- }- let valid = true;- if (extent.toArray) {- extent = extent.toArray();- }- lodashEach(extent, (value) => {- // eslint-disable-next-line no-restricted-globals- if (isNaN(value)) {- valid = false;- return false;- }- });- return valid;-}-/*** Sets the opacity of a layer. Since the backbuffer can interfere with* tile layers that have transparency, the transition effect is set todiff --git a/web/js/map/natural-events/event-markers.js b/web/js/map/natural-events/event-markers.jsindex 58d67d279..49da21caf 100644--- a/web/js/map/natural-events/event-markers.js+++ b/web/js/map/natural-events/event-markers.js@@ -32,6 +32,59 @@ const icons = ['Wildfires',];+const createPin = function(id, category, isSelected, title, hideTooltip) {+ const overlayEl = document.createElement('div');+ ReactDOM.render(+ React.createElement(EventIcon, {+ category: category.title,+ title,+ id,+ hideTooltip,+ isSelected,+ }),+ overlayEl,+ );+ return new OlOverlay({+ element: overlayEl,+ positioning: 'bottom-center',+ stopEvent: false,+ className: isSelected ? 'marker selected' : 'marker',+ id,+ });+};++const createBoundingBox = function(coordinates, title, proj = CRS.GEOGRAPHIC) {+ const lightStroke = new OlStyleStyle({+ stroke: new OlStyleStroke({+ color: [255, 255, 255, 0.6],+ width: 2,+ lineDash: [8, 12],+ lineDashOffset: 6,+ }),+ });+ const darkStroke = new OlStyleStyle({+ stroke: new OlStyleStroke({+ color: [0, 0, 0, 0.6],+ width: 2,+ lineDash: [8, 12],+ }),+ });+ const boxPolygon = new OlGeomPolygon(coordinates).transform(CRS.GEOGRAPHIC, proj);+ const boxFeature = new OlFeature({+ geometry: boxPolygon,+ name: title,+ });+ const vectorSource = new OlSourceVector({+ features: [boxFeature],+ wrapX: false,+ });++ return new OlLayerVector({+ source: vectorSource,+ style: [lightStroke, darkStroke],+ });+};+class EventMarkers extends React.Component {constructor(props) {super(props);@@ -207,59 +260,6 @@ class EventMarkers extends React.Component {}}-const createPin = function(id, category, isSelected, title, hideTooltip) {- const overlayEl = document.createElement('div');- ReactDOM.render(- React.createElement(EventIcon, {- category: category.title,- title,- id,- hideTooltip,- isSelected,- }),- overlayEl,- );- return new OlOverlay({- element: overlayEl,- positioning: 'bottom-center',- stopEvent: false,- className: isSelected ? 'marker selected' : 'marker',- id,- });-};--const createBoundingBox = function(coordinates, title, proj = CRS.GEOGRAPHIC) {- const lightStroke = new OlStyleStyle({- stroke: new OlStyleStroke({- color: [255, 255, 255, 0.6],- width: 2,- lineDash: [8, 12],- lineDashOffset: 6,- }),- });- const darkStroke = new OlStyleStyle({- stroke: new OlStyleStroke({- color: [0, 0, 0, 0.6],- width: 2,- lineDash: [8, 12],- }),- });- const boxPolygon = new OlGeomPolygon(coordinates).transform(CRS.GEOGRAPHIC, proj);- const boxFeature = new OlFeature({- geometry: boxPolygon,- name: title,- });- const vectorSource = new OlSourceVector({- features: [boxFeature],- wrapX: false,- });-- return new OlLayerVector({- source: vectorSource,- style: [lightStroke, darkStroke],- });-};-const mapStateToProps = (state) => {const {map, proj, events, requestedEvents, sidebar, date, screenSize,diff --git a/web/js/map/natural-events/event-track.js b/web/js/map/natural-events/event-track.jsindex eac645e18..8bc1614d6 100644--- a/web/js/map/natural-events/event-track.js+++ b/web/js/map/natural-events/event-track.js@@ -26,6 +26,14 @@ const removePointOverlays = (map, pointsAndArrows) => {});};+function addOverlayIfIsVisible (map, overlay) {+ const extent = map.getView().calculateExtent();+ const position = overlay.getPosition();+ if (olExtent.containsCoordinate(extent, position)) {+ map.addOverlay(overlay);+ }+}+const addPointOverlays = (map, pointOverlayArray) => {lodashEach(pointOverlayArray, (pointOverlay) => {addOverlayIfIsVisible(map, pointOverlay);@@ -96,14 +104,6 @@ const getTracksAndPoints = function (eventObj, proj, map, selectedDate, callback};};-function addOverlayIfIsVisible (map, overlay) {- const extent = map.getView().calculateExtent();- const position = overlay.getPosition();- if (olExtent.containsCoordinate(extent, position)) {- map.addOverlay(overlay);- }-}-function EventTrack () {const dispatch = useDispatch();const selectEvent = (id, date) => dispatch(selectEventAction(id, date));@@ -133,14 +133,22 @@ function EventTrack () {showAllTracksRef.current = showAllTracks;}, [showAllTracks]);+ const removeAllTracks = (mapArg) => {+ allTrackDetailsRef.current?.forEach((trackDetail) => {+ const { pointsAndArrows } = trackDetail.newTrackDetails;+ const { track } = trackDetail.newTrackDetails;+ mapArg.removeOverlay(track);+ removePointOverlays(mapArg, pointsAndArrows);+ });+ };- // $$$ This function merely gets the selected event data from the events data and calls the update() function with that data, will likely not need it $$$- const updateCurrentTrack = () => {- const { id, date } = selectedEvent;- if (!selectedEvent.id || !selectedEvent.date) return;- const event = (eventsData || []).find((e) => e.id === id);- if (!event) return;- update(event, date);+ const removeTrack = (mapArg) => {+ if (!mapArg) return;+ const { track, pointsAndArrows } = trackDetailsRef.current;+ mapArg.removeOverlay(track);+ removePointOverlays(mapArg, pointsAndArrows);++ return {};};const onPropertyChange = (e) => {@@ -162,24 +170,6 @@ function EventTrack () {}};- const removeTrack = (mapArg) => {- if (!mapArg) return;- const { track, pointsAndArrows } = trackDetailsRef.current;- mapArg.removeOverlay(track);- removePointOverlays(mapArg, pointsAndArrows);-- return {};- };-- const removeAllTracks = (mapArg) => {- allTrackDetailsRef.current?.forEach((trackDetail) => {- const { pointsAndArrows } = trackDetail.newTrackDetails;- const { track } = trackDetail.newTrackDetails;- mapArg.removeOverlay(track);- removePointOverlays(mapArg, pointsAndArrows);- });- };-const updateAllTracks = () => {let newTrackDetails;const allTracks = [];@@ -216,7 +206,6 @@ function EventTrack () {setAllTrackDetails(allTracks);};-const update = (event, date) => {let newTrackDetails;const sameEvent = event && trackDetailsRef.current.id === event.id;@@ -266,6 +255,15 @@ function EventTrack () {setTrackDetails(newTrackDetails);};+ // $$$ This function merely gets the selected event data from the events data and calls the update() function with that data, will likely not need it $$$+ const updateCurrentTrack = () => {+ const { id, date } = selectedEvent;+ if (!selectedEvent.id || !selectedEvent.date) return;+ const event = (eventsData || []).find((e) => e.id === id);+ if (!event) return;+ update(event, date);+ };+// debounce delays the function call by a set amount of time. in this case 50 millisecondsconst debouncedTrackUpdate = lodashDebounce(updateCurrentTrack, 50);const debouncedOnPropertyChange = lodashDebounce(diff --git a/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.js b/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.jsindex 0601a4edb..788ffa2c0 100644--- a/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.js+++ b/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.js@@ -17,12 +17,6 @@ function BufferQuickAnimate(props) {setPreload,} = props;- useEffect(() => {- if (action.value) {- bufferQuickAnimate(action.value);- }- }, [action]);-async function bufferQuickAnimate(arrowDown) {const BUFFER_SIZE = 8;const preloadPromises = [];@@ -48,6 +42,12 @@ function BufferQuickAnimate(props) {setPreload(true, nextDate);}+ useEffect(() => {+ if (action.value) {+ bufferQuickAnimate(action.value);+ }+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/create-map/createMap.js b/web/js/mapUI/components/create-map/createMap.jsindex bbad6e2f3..6bba47f9a 100644--- a/web/js/mapUI/components/create-map/createMap.js+++ b/web/js/mapUI/components/create-map/createMap.js@@ -61,18 +61,6 @@ function CreateMap(props) {duration: animationDuration,});- useEffect(() => {- if (isMapSet) return;- setMap(true);- const uiCopy = ui;- lodashForOwn(projections, (proj) => {- const map = mapCreation(proj, uiCopy);- uiCopy.proj[proj.id] = map;- });- setGranuleFootprints(granuleFootprintsObj);- setUI(uiCopy);- });-/*** Create map object*@@ -236,6 +224,18 @@ function CreateMap(props) {return map;};+ useEffect(() => {+ if (isMapSet) return;+ setMap(true);+ const uiCopy = ui;+ lodashForOwn(projections, (proj) => {+ const map = mapCreation(proj, uiCopy);+ uiCopy.proj[proj.id] = map;+ });+ setGranuleFootprints(granuleFootprintsObj);+ setUI(uiCopy);+ });+return null;}diff --git a/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.js b/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.jsindex 09f177963..b23054676 100644--- a/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.js+++ b/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.js@@ -33,6 +33,11 @@ function FindOrbitTracksMode () {}));const prevDate = usePrevious(selectedDate);+ const placeHolderLayerSelection = { id: 'Select Layer', period: 'daily' };+ const [layerSelection, setLayerSelection] = useState(placeHolderLayerSelection);+ const [searchMethod, setSearchMethod] = useState(0);+ const [dateFound, setDateFound] = useState(null);+ const [isLoading, setIsLoading] = useState(false);useEffect(() => {if (selectedDate !== prevDate && dateFound !== null) {@@ -40,12 +45,6 @@ function FindOrbitTracksMode () {}});- const placeHolderLayerSelection = { id: 'Select Layer', period: 'daily' };- const [layerSelection, setLayerSelection] = useState(placeHolderLayerSelection);- const [searchMethod, setSearchMethod] = useState(0);- const [dateFound, setDateFound] = useState(null);- const [isLoading, setIsLoading] = useState(false);-const buttonDisabled = layerSelection.id === 'Select Layer' || searchMethod === 0 || zoom < 7 || isLoading;const moveToDate = () => {@@ -83,29 +82,6 @@ function FindOrbitTracksMode () {return dateRange;};- const findOrbitalImagery = async () => {- setIsLoading(true);- const verifyQuery = verifyExtent();- if (!verifyQuery) {- setIsLoading(false);- return;- }- const dateRange = getOrbitalDateRange();- for (let i = 0; i < dateRange.length; i += 1) {- const date = dateRange[i];- // eslint-disable-next-line no-await-in-loop- const imageryRequest = await makeMeasurementRequest(date);- if (imageryRequest === 100 || !imageryRequest) {- console.log('No imagery found for ', date);- } else {- setIsLoading(false);- console.log('Imagery found for ', date, ' with ', imageryRequest, '% black pixels');- return setDateFound(date);- }- }- setIsLoading(false);- };-const makeMeasurementRequest = async (date) => {const mercatorExtent = transformExtent(currentExtent, 'EPSG:4326', 'EPSG:3857');try {@@ -138,6 +114,29 @@ function FindOrbitTracksMode () {}};+ const findOrbitalImagery = async () => {+ setIsLoading(true);+ const verifyQuery = verifyExtent();+ if (!verifyQuery) {+ setIsLoading(false);+ return;+ }+ const dateRange = getOrbitalDateRange();+ for (let i = 0; i < dateRange.length; i += 1) {+ const date = dateRange[i];+ // eslint-disable-next-line no-await-in-loop+ const imageryRequest = await makeMeasurementRequest(date);+ if (imageryRequest === 100 || !imageryRequest) {+ console.log('No imagery found for ', date);+ } else {+ setIsLoading(false);+ console.log('Imagery found for ', date, ' with ', imageryRequest, '% black pixels');+ return setDateFound(date);+ }+ }+ setIsLoading(false);+ };+const orangeStyle = { backgroundColor: '#d54e21' };return (diff --git a/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.js b/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.jsindex e9f931615..45a98aecd 100644--- a/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.js+++ b/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.js@@ -20,32 +20,11 @@ function KioskAnimations({ ui }) {const map = useSelector((state) => state.map, shallowEqual);const eicMeasurementComplete = useSelector((state) => state.ui.eicMeasurementComplete);const eicMeasurementAborted = useSelector((state) => state.ui.eicMeasurementAborted);-- const eicAnimationMode = eic === 'sa' || eic === 'da';-const [subdailyAnimationDateUpdated, setSubdailyAnimationDateUpdated] = useState(false);-- useEffect(() => {- if (!ui.selected || !isKioskModeActive || !eicMeasurementComplete || isAnimationPlaying || !eicAnimationMode || eicMeasurementAborted) return;- checkAnimationSettings();- }, [map, eicMeasurementComplete]);-+ const eicAnimationMode = eic === 'sa' || eic === 'da';const subdailyPlayCheck = eic === 'sa' && subdailyAnimationDateUpdated && !isAnimationPlaying;const dailyPlayCheck = eic === 'da' && !isAnimationPlaying;- // if subdaily animation check that date moved back one day otherwise check if animation should play- const checkAnimationSettings = () => {- if (!ui.selected.frameState_) return;- if (eic === 'sa' && !subdailyAnimationDateUpdated) {- const prevDayDate = new Date(selectedDate);- prevDayDate.setDate(prevDayDate.getDate() - 1);- selectDate(prevDayDate);- setSubdailyAnimationDateUpdated(true);- } else if (subdailyPlayCheck || dailyPlayCheck) {- handleAnimationSettings();- }- };-// zero dates for subdaily timesconst zeroDates = (start, end) => {const startDateZeroed = new Date(start);@@ -90,6 +69,24 @@ function KioskAnimations({ ui }) {playKioskAnimation(startDate, endDate);};+ // if subdaily animation check that date moved back one day otherwise check if animation should play+ const checkAnimationSettings = () => {+ if (!ui.selected.frameState_) return;+ if (eic === 'sa' && !subdailyAnimationDateUpdated) {+ const prevDayDate = new Date(selectedDate);+ prevDayDate.setDate(prevDayDate.getDate() - 1);+ selectDate(prevDayDate);+ setSubdailyAnimationDateUpdated(true);+ } else if (subdailyPlayCheck || dailyPlayCheck) {+ handleAnimationSettings();+ }+ };++ useEffect(() => {+ if (!ui.selected || !isKioskModeActive || !eicMeasurementComplete || isAnimationPlaying || !eicAnimationMode || eicMeasurementAborted) return;+ checkAnimationSettings();+ }, [map, eicMeasurementComplete]);+return null;}diff --git a/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.js b/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.jsindex 56f047dc1..7226484ad 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.js@@ -30,12 +30,6 @@ function TileMeasurement({ ui }) {const [measurementsStarted, setMeasurementsStarted] = useState(false);- useEffect(() => {- if (!measurementsStarted && activeLayers && eic && ui.selected) {- calculateMeasurements();- }- });-// #2 Filter all of the active layers that are also in the layersToMeasure arrayconst findLayersToMeasure = () => {const measurementLayersExtra = activeLayers.filter((layer) => layersToMeasure.includes(layer.id));@@ -154,7 +148,6 @@ function TileMeasurement({ ui }) {}};-// #1 Parent function that is called from useEffect.const calculateMeasurements = async () => {try {@@ -190,6 +183,12 @@ function TileMeasurement({ ui }) {}};+ useEffect(() => {+ if (!measurementsStarted && activeLayers && eic && ui.selected) {+ calculateMeasurements();+ }+ });+return null;}diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.jsindex 6889aea5f..9e0ff0c91 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.js@@ -1,10 +1,11 @@-// Return an array of dates based on the period (daily or subdaily)-// Accepts redux selectedDate value and period-export function getDates(selectedDate, period) {- if (period === 'daily') {- return getDailyDates(selectedDate);- }- return getSubdailyDates(selectedDate);+// format a single daily date+// Accepts a date object+function formatDailyDate (date) {+ const year = date.getFullYear();+ const month = (date.getMonth() + 1).toString().padStart(2, '0');+ const day = date.getDate().toString().padStart(2, '0');++ return `${year}-${month}-${day}`;}// Return an array of daily dates for the past 7 days@@ -25,14 +26,16 @@ function getDailyDates (selectedDate) {return prevDates;}-// format a single daily date-// Accepts a date object-function formatDailyDate (date) {+// format a single subdaily date+// accepts a date object+function formatSubdailyDate (date) {const year = date.getFullYear();const month = (date.getMonth() + 1).toString().padStart(2, '0');const day = date.getDate().toString().padStart(2, '0');+ const hour = date.getHours().toString().padStart(2, '0');+ const minute = date.getMinutes().toString().padStart(2, '0');- return `${year}-${month}-${day}`;+ return `${year}-${month}-${day}T${hour}:${minute}:00Z`;}// Return an array of subdaily dates for the past 2 hours in ten minute intervals@@ -60,16 +63,13 @@ function getSubdailyDates (selectedDate) {return prevDates;}-// format a single subdaily date-// accepts a date object-function formatSubdailyDate (date) {- const year = date.getFullYear();- const month = (date.getMonth() + 1).toString().padStart(2, '0');- const day = date.getDate().toString().padStart(2, '0');- const hour = date.getHours().toString().padStart(2, '0');- const minute = date.getMinutes().toString().padStart(2, '0');-- return `${year}-${month}-${day}T${hour}:${minute}:00Z`;+// Return an array of dates based on the period (daily or subdaily)+// Accepts redux selectedDate value and period+export function getDates(selectedDate, period) {+ if (period === 'daily') {+ return getDailyDates(selectedDate);+ }+ return getSubdailyDates(selectedDate);}// Format a daily redux date to be used in the WMS request@@ -96,16 +96,6 @@ export function formatReduxSubdailyDate(selectedDate) {return `${year}-${month}-${day}T${hour}:${minute}:00Z`;}-export function getOrbitalDates (selectedDate, latestDate, searchMethod) {- if (searchMethod === 1) {- return getOrbitalDatesForwards(selectedDate, latestDate);- } if (searchMethod === 2) {- return getOrbitalDatesBackwards(selectedDate);- } if (searchMethod === 3) {- return getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate);- }-}-export function getOrbitalDatesBackwards (selectedDate) {// Get the date as a string in UTCconst utcDateString = selectedDate.toLocaleString('en-US', { timeZone: 'UTC' });@@ -171,3 +161,13 @@ export function getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate) {// Trim the array down to 14 elements in case we've added too manyreturn mixedDates.slice(0, 14);}++export function getOrbitalDates (selectedDate, latestDate, searchMethod) {+ if (searchMethod === 1) {+ return getOrbitalDatesForwards(selectedDate, latestDate);+ } if (searchMethod === 2) {+ return getOrbitalDatesBackwards(selectedDate);+ } if (searchMethod === 3) {+ return getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate);+ }+}diff --git a/web/js/mapUI/components/layers/addLayer.js b/web/js/mapUI/components/layers/addLayer.jsindex d18bb0c61..a4e364e23 100644--- a/web/js/mapUI/components/layers/addLayer.js+++ b/web/js/mapUI/components/layers/addLayer.js@@ -24,32 +24,6 @@ function AddLayer(props) {ui,} = props;- useEffect(() => {- if (action.type === layerConstants.ADD_LAYER || action.type === layerConstants.UPDATE_DDV_LAYER) {- const def = lodashFind(action.layers, { id: action.id });- if (def.type === 'granule') {- return granuleLayerAdd(def);- }- clearPreload();- addLayer(def);- } else if (action.type === DISPLAY_STATIC_MAP) {- addStaticLayer();- }- }, [action]);-- // add static layer for kiosk mode in case of gibs/dns failure- const addStaticLayer = async() => {- const { createLayer } = ui;- const newLayer = await createLayer();- ui.selected.getLayers().insertAt(0, newLayer);- };-- const granuleLayerAdd = (def) => {- ui.processingPromise = new Promise((resolve) => {- resolve(addLayer(def));- });- };-/*** Initiates the adding of a layer* @param {object} def - layer Specs@@ -83,6 +57,32 @@ function AddLayer(props) {preloadNextTiles();};+ const granuleLayerAdd = (def) => {+ ui.processingPromise = new Promise((resolve) => {+ resolve(addLayer(def));+ });+ };++ // add static layer for kiosk mode in case of gibs/dns failure+ const addStaticLayer = async() => {+ const { createLayer } = ui;+ const newLayer = await createLayer();+ ui.selected.getLayers().insertAt(0, newLayer);+ };++ useEffect(() => {+ if (action.type === layerConstants.ADD_LAYER || action.type === layerConstants.UPDATE_DDV_LAYER) {+ const def = lodashFind(action.layers, { id: action.id });+ if (def.type === 'granule') {+ return granuleLayerAdd(def);+ }+ clearPreload();+ addLayer(def);+ } else if (action.type === DISPLAY_STATIC_MAP) {+ addStaticLayer();+ }+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/layers/removeLayer.js b/web/js/mapUI/components/layers/removeLayer.jsindex f6ac66bc4..7e003bc3c 100644--- a/web/js/mapUI/components/layers/removeLayer.js+++ b/web/js/mapUI/components/layers/removeLayer.js@@ -13,12 +13,6 @@ function RemoveLayer(props) {updateLayerVisibilities,} = props;- useEffect(() => {- if (action.layersToRemove) {- removeLayer(action.layersToRemove);- }- }, [action]);-const removeLayer = (layersToRemove) => {layersToRemove.forEach((def) => {const layer = findLayer(def, compare.activeString);@@ -32,6 +26,12 @@ function RemoveLayer(props) {updateLayerVisibilities();};+ useEffect(() => {+ if (action.layersToRemove) {+ removeLayer(action.layersToRemove);+ }+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/markers/markers.js b/web/js/mapUI/components/markers/markers.jsindex b82953d17..c6e225dde 100644--- a/web/js/mapUI/components/markers/markers.js+++ b/web/js/mapUI/components/markers/markers.js@@ -23,25 +23,6 @@ function Markers(props) {ui,} = props;- useEffect(() => {- switch (action.type) {- case 'LOCATION_SEARCH/REMOVE_MARKER': {- return removeCoordinatesMarker(action.coordinates);- }- case 'LOCATION_SEARCH/SET_MARKER': {- if (action.flyToExistingMarker) {- return flyToMarker(action.coordinates);- }- return addMarkerAndUpdateStore(true, action.reverseGeocodeResults, action.isCoordinatesSearchActive, action.coordinates);- }- case 'LOCATION_SEARCH/TOGGLE_DIALOG_VISIBLE': {- return addMarkerAndUpdateStore(false);- }- default:- break;- }- }, [action]);-/*** Remove coordinates marker from all projections*@@ -76,27 +57,6 @@ function Markers(props) {});};- /**- * Handle reverse geocode and add map marker with results- *- * @method handleActiveMapMarker- * @static- *- * @returns {void}- */- const handleActiveMapMarker = () => {- removeAllCoordinatesMarkers();- if (coordinates && coordinates.length > 0) {- coordinates.forEach((coordinatesObject) => {- const { longitude, latitude } = coordinatesObject;- const coord = [longitude, latitude];- if (!areCoordinatesWithinExtent(proj, coord)) return;- reverseGeocode(getNormalizedCoordinate(coord), config).then((results) => {- addMarkerAndUpdateStore(true, results, null, coordinatesObject);- });- });- }- };const flyToMarker = (coordinatesObject) => {const { sources } = config;@@ -147,10 +107,51 @@ function Markers(props) {setGeocodeResults(geocodeResults);};+ /**+ * Handle reverse geocode and add map marker with results+ *+ * @method handleActiveMapMarker+ * @static+ *+ * @returns {void}+ */+ const handleActiveMapMarker = () => {+ removeAllCoordinatesMarkers();+ if (coordinates && coordinates.length > 0) {+ coordinates.forEach((coordinatesObject) => {+ const { longitude, latitude } = coordinatesObject;+ const coord = [longitude, latitude];+ if (!areCoordinatesWithinExtent(proj, coord)) return;+ reverseGeocode(getNormalizedCoordinate(coord), config).then((results) => {+ addMarkerAndUpdateStore(true, results, null, coordinatesObject);+ });+ });+ }+ };+useEffect(() => {handleActiveMapMarker();}, [ui]);+ useEffect(() => {+ switch (action.type) {+ case 'LOCATION_SEARCH/REMOVE_MARKER': {+ return removeCoordinatesMarker(action.coordinates);+ }+ case 'LOCATION_SEARCH/SET_MARKER': {+ if (action.flyToExistingMarker) {+ return flyToMarker(action.coordinates);+ }+ return addMarkerAndUpdateStore(true, action.reverseGeocodeResults, action.isCoordinatesSearchActive, action.coordinates);+ }+ case 'LOCATION_SEARCH/TOGGLE_DIALOG_VISIBLE': {+ return addMarkerAndUpdateStore(false);+ }+ default:+ break;+ }+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/update-date/updateDate.js b/web/js/mapUI/components/update-date/updateDate.jsindex c7d172762..8e30eef9a 100644--- a/web/js/mapUI/components/update-date/updateDate.js+++ b/web/js/mapUI/components/update-date/updateDate.js@@ -35,29 +35,6 @@ function UpdateDate(props) {vectorStyleState,} = props;- useEffect(() => {- actionSwitch();- }, [action]);-- const actionSwitch = () => {- if (action.type === dateConstants.SELECT_DATE) {- if (ui.processingPromise) {- return new Promise((resolve) => {- resolve(ui.processingPromise);- }).then(() => {- ui.processingPromise = null;- return updateDate(action.outOfStep);- });- }- return updateDate(action.outOfStep);- } if (action.type === layerConstants.TOGGLE_LAYER_VISIBILITY || action.type === layerConstants.TOGGLE_OVERLAY_GROUP_VISIBILITY) {- const outOfStep = false;- // if date not changing we do not want to recreate ttiler layer- const skipTtiler = true;- return updateDate(outOfStep, skipTtiler);- }- };-function findLayerIndex({ id }) {const layerGroup = getActiveLayerGroup(layerState);const layers = layerGroup.getLayers().getArray();@@ -137,6 +114,29 @@ function UpdateDate(props) {}}+ const actionSwitch = () => {+ if (action.type === dateConstants.SELECT_DATE) {+ if (ui.processingPromise) {+ return new Promise((resolve) => {+ resolve(ui.processingPromise);+ }).then(() => {+ ui.processingPromise = null;+ return updateDate(action.outOfStep);+ });+ }+ return updateDate(action.outOfStep);+ } if (action.type === layerConstants.TOGGLE_LAYER_VISIBILITY || action.type === layerConstants.TOGGLE_OVERLAY_GROUP_VISIBILITY) {+ const outOfStep = false;+ // if date not changing we do not want to recreate ttiler layer+ const skipTtiler = true;+ return updateDate(outOfStep, skipTtiler);+ }+ };++ useEffect(() => {+ actionSwitch();+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/update-opacity/updateOpacity.js b/web/js/mapUI/components/update-opacity/updateOpacity.jsindex 0c7be066f..a815b7fd3 100644--- a/web/js/mapUI/components/update-opacity/updateOpacity.js+++ b/web/js/mapUI/components/update-opacity/updateOpacity.js@@ -20,12 +20,6 @@ function UpdateOpacity(props) {updateLayerVisibilities,} = props;- useEffect(() => {- if (action.type === layerConstants.UPDATE_OPACITY) {- updateOpacity(action);- }- }, [action]);-const updateGranuleLayerOpacity = (def, activeString, opacity, compare) => {const { id } = def;const layers = ui.selected.getLayers().getArray();@@ -77,6 +71,13 @@ function UpdateOpacity(props) {}updateLayerVisibilities();};++ useEffect(() => {+ if (action.type === layerConstants.UPDATE_OPACITY) {+ updateOpacity(action);+ }+ }, [action]);+return null;}diff --git a/web/js/mapUI/components/update-projection/updateProjection.js b/web/js/mapUI/components/update-projection/updateProjection.jsindex 1fb1b27ef..4389d6d49 100644--- a/web/js/mapUI/components/update-projection/updateProjection.js+++ b/web/js/mapUI/components/update-projection/updateProjection.js@@ -53,96 +53,23 @@ function UpdateProjection(props) {requestPalette,} = props;- useEffect(() => {- actionSwitch();- }, [action]);-- useEffect(() => {- if (projectionTrigger === 1) {- updateProjection(true);- } else if (projectionTrigger > 1) {- updateProjection();- }- }, [projectionTrigger]);-- const actionSwitch = () => {- switch (action.type) {- case STOP_ANIMATION:- case EXIT_ANIMATION:- return onStopAnimation();- case LOCATION_POP_ACTION: {- const newState = util.fromQueryString(action.payload.search);- const extent = lodashGet(map, 'extent');- const rotate = lodashGet(map, 'rotation') || 0;- setTimeout(() => {- updateProjection();- if (newState.v && !newState.e && extent) {- flyToNewExtent(extent, rotate);- }- }, 200); return;- }- case layerConstants.UPDATE_GRANULE_LAYER_OPTIONS: {- const granuleOptions = {- id: action.id,- reset: null,- };- return reloadLayers(granuleOptions);- }- case layerConstants.RESET_GRANULE_LAYER_OPTIONS: {- const granuleOptions = {- id: action.id,- reset: action.id,- };- return reloadLayers(granuleOptions);- }- case compareConstants.CHANGE_STATE:- if (compareMode === 'spy') {- return reloadLayers();- }- return;- case layerConstants.REORDER_LAYERS:- case layerConstants.REORDER_OVERLAY_GROUPS:- case compareConstants.TOGGLE_ON_OFF:- case compareConstants.CHANGE_MODE:- reloadLayers();- preloadForCompareMode();- return;- case layerConstants.TOGGLE_OVERLAY_GROUPS:- return reloadLayers();- case paletteConstants.SET_THRESHOLD_RANGE_AND_SQUASH:- case paletteConstants.SET_CUSTOM:- case paletteConstants.SET_DISABLED_CLASSIFICATION:- case paletteConstants.CLEAR_CUSTOM:- case layerConstants.ADD_LAYERS_FOR_EVENT:- return setTimeout(reloadLayers, 100);- case vectorStyleConstants.SET_FILTER_RANGE:- case vectorStyleConstants.SET_VECTORSTYLE:- case vectorStyleConstants.CLEAR_VECTORSTYLE:- case SET_SCREEN_INFO:- return onResize();- default:- break;- }- };-/**- * Collect information required & initiate a "fly" map transition- * Used in Tour Stories.- * @method flyToNewExtent- * @static- *- * @param {object} extent- * @param {number} rotation- */- const flyToNewExtent = function(extent, rotation) {- const coordinateX = extent[0] + (extent[2] - extent[0]) / 2;- const coordinateY = extent[1] + (extent[3] - extent[1]) / 2;- const coordinates = [coordinateX, coordinateY];- const resolution = ui.selected.getView().getResolutionForExtent(extent);- const zoom = ui.selected.getView().getZoomForResolution(resolution);- // Animate to extent, zoom & rotate:- // Don't animate when an event is selected (Event selection already animates)- return fly(ui.selected, proj, coordinates, zoom, rotation, isKioskModeActive);+ * Remove Layers from map+ *+ * @method clearLayers+ * @static+ *+ * @returns {void}+ */+ const clearLayers = function() {+ const activeLayersUI = ui.selected+ .getLayers()+ .getArray()+ .slice(0);+ lodashEach(activeLayersUI, (mapLayer) => {+ ui.selected.removeLayer(mapLayer);+ });+ ui.cache.clear();};/**@@ -182,25 +109,6 @@ function UpdateProjection(props) {});}- /**- * Remove Layers from map- *- * @method clearLayers- * @static- *- * @returns {void}- */- const clearLayers = function() {- const activeLayersUI = ui.selected- .getLayers()- .getArray()- .slice(0);- lodashEach(activeLayersUI, (mapLayer) => {- ui.selected.removeLayer(mapLayer);- });- ui.cache.clear();- };-/*** @method reloadLayers*@@ -251,22 +159,18 @@ function UpdateProjection(props) {};/**- * When page is resized set for mobile or desktop+ * Hide Map*- * @method onResize+ * @method hideMap* @static*+ * @param {object} map - Openlayers Map obj+ ** @returns {void}*/- function onResize() {- const mapUI = ui.selected;- if (isMobile) {- mapUI.removeControl(mapUI.wv.scaleImperial);- mapUI.removeControl(mapUI.wv.scaleMetric);- } else {- mapUI.addControl(mapUI.wv.scaleImperial);- mapUI.addControl(mapUI.wv.scaleMetric);- }+ function hideMap(map) {+ const el = document.getElementById(`${map.getTarget()}`);+ if (el) el.style.display = 'none';}/**@@ -285,21 +189,24 @@ function UpdateProjection(props) {}/**- * Hide Map+ * When page is resized set for mobile or desktop*- * @method hideMap+ * @method onResize* @static*- * @param {object} map - Openlayers Map obj- ** @returns {void}*/- function hideMap(map) {- const el = document.getElementById(`${map.getTarget()}`);- if (el) el.style.display = 'none';+ function onResize() {+ const mapUI = ui.selected;+ if (isMobile) {+ mapUI.removeControl(mapUI.wv.scaleImperial);+ mapUI.removeControl(mapUI.wv.scaleMetric);+ } else {+ mapUI.addControl(mapUI.wv.scaleImperial);+ mapUI.addControl(mapUI.wv.scaleMetric);+ }}-const updateProjection = (start) => {if (ui.selected) {// Keep track of center point on projection switch@@ -362,6 +269,98 @@ function UpdateProjection(props) {onResize();};+ /**+ * Collect information required & initiate a "fly" map transition+ * Used in Tour Stories.+ * @method flyToNewExtent+ * @static+ *+ * @param {object} extent+ * @param {number} rotation+ */+ const flyToNewExtent = function(extent, rotation) {+ const coordinateX = extent[0] + (extent[2] - extent[0]) / 2;+ const coordinateY = extent[1] + (extent[3] - extent[1]) / 2;+ const coordinates = [coordinateX, coordinateY];+ const resolution = ui.selected.getView().getResolutionForExtent(extent);+ const zoom = ui.selected.getView().getZoomForResolution(resolution);+ // Animate to extent, zoom & rotate:+ // Don't animate when an event is selected (Event selection already animates)+ return fly(ui.selected, proj, coordinates, zoom, rotation, isKioskModeActive);+ };++ const actionSwitch = () => {+ switch (action.type) {+ case STOP_ANIMATION:+ case EXIT_ANIMATION:+ return onStopAnimation();+ case LOCATION_POP_ACTION: {+ const newState = util.fromQueryString(action.payload.search);+ const extent = lodashGet(map, 'extent');+ const rotate = lodashGet(map, 'rotation') || 0;+ setTimeout(() => {+ updateProjection();+ if (newState.v && !newState.e && extent) {+ flyToNewExtent(extent, rotate);+ }+ }, 200); return;+ }+ case layerConstants.UPDATE_GRANULE_LAYER_OPTIONS: {+ const granuleOptions = {+ id: action.id,+ reset: null,+ };+ return reloadLayers(granuleOptions);+ }+ case layerConstants.RESET_GRANULE_LAYER_OPTIONS: {+ const granuleOptions = {+ id: action.id,+ reset: action.id,+ };+ return reloadLayers(granuleOptions);+ }+ case compareConstants.CHANGE_STATE:+ if (compareMode === 'spy') {+ return reloadLayers();+ }+ return;+ case layerConstants.REORDER_LAYERS:+ case layerConstants.REORDER_OVERLAY_GROUPS:+ case compareConstants.TOGGLE_ON_OFF:+ case compareConstants.CHANGE_MODE:+ reloadLayers();+ preloadForCompareMode();+ return;+ case layerConstants.TOGGLE_OVERLAY_GROUPS:+ return reloadLayers();+ case paletteConstants.SET_THRESHOLD_RANGE_AND_SQUASH:+ case paletteConstants.SET_CUSTOM:+ case paletteConstants.SET_DISABLED_CLASSIFICATION:+ case paletteConstants.CLEAR_CUSTOM:+ case layerConstants.ADD_LAYERS_FOR_EVENT:+ return setTimeout(reloadLayers, 100);+ case vectorStyleConstants.SET_FILTER_RANGE:+ case vectorStyleConstants.SET_VECTORSTYLE:+ case vectorStyleConstants.CLEAR_VECTORSTYLE:+ case SET_SCREEN_INFO:+ return onResize();+ default:+ break;+ }+ };++ useEffect(() => {+ actionSwitch();+ }, [action]);++ useEffect(() => {+ if (projectionTrigger === 1) {+ updateProjection(true);+ } else if (projectionTrigger > 1) {+ updateProjection();+ }+ }, [projectionTrigger]);+return null;}diff --git a/web/js/mapUI/mapUI.js b/web/js/mapUI/mapUI.jsindex 23b6bb3a5..44b64d926 100644--- a/web/js/mapUI/mapUI.js+++ b/web/js/mapUI/mapUI.js@@ -169,30 +169,6 @@ function MapUI(props) {}};- events.on(REDUX_ACTION_DISPATCHED, subscribeToStore);- window.addEventListener('orientationchange', () => {- setTimeout(() => { setProjectionTrigger((projectionTrigger) => projectionTrigger + 1); }, 200);- });-- // Initial hook that initiates the map after it has been created in CreateMap.js- useEffect(() => {- if (document.getElementById('app')) {- setProjectionTrigger(1);- }- }, [ui]);-- useEffect(() => {- if (vectorActions.type === vectorStyleConstants.SET_SELECTED_VECTORS) {- updateVectorSelections();- }- }, [vectorActions]);-- useEffect(() => {- if (preloadAction.type === dateConstants.CHANGE_INTERVAL) {- preloadNextTiles();- }- }, [preloadAction]);-const updateVectorSelections = () => {const type = 'selection';const newSelection = vectorActions.payload;@@ -206,6 +182,11 @@ function MapUI(props) {ui.selectedVectors = newSelection;};+ events.on(REDUX_ACTION_DISPATCHED, subscribeToStore);+ window.addEventListener('orientationchange', () => {+ setTimeout(() => { setProjectionTrigger((projectionTrigger) => projectionTrigger + 1); }, 200);+ });+const updateExtent = () => {const map = ui.selected;const view = map.getView();@@ -313,13 +294,6 @@ function MapUI(props) {};};- function preloadForCompareMode() {- preloadNextTiles(selectedDate, 'active');- if (compare.active) {- preloadNextTiles(selectedDateB, 'activeB');- }- }-async function preloadNextTiles(date, compareString) {const map = { ui };const state = {@@ -344,6 +318,32 @@ function MapUI(props) {}}+ function preloadForCompareMode() {+ preloadNextTiles(selectedDate, 'active');+ if (compare.active) {+ preloadNextTiles(selectedDateB, 'activeB');+ }+ }++ // Initial hook that initiates the map after it has been created in CreateMap.js+ useEffect(() => {+ if (document.getElementById('app')) {+ setProjectionTrigger(1);+ }+ }, [ui]);++ useEffect(() => {+ if (vectorActions.type === vectorStyleConstants.SET_SELECTED_VECTORS) {+ updateVectorSelections();+ }+ }, [vectorActions]);++ useEffect(() => {+ if (preloadAction.type === dateConstants.CHANGE_INTERVAL) {+ preloadNextTiles();+ }+ }, [preloadAction]);+return (<><CreateMapdiff --git a/web/js/modules/animation/gifstream.js b/web/js/modules/animation/gifstream.jsindex 9f9931174..04798a9c6 100644--- a/web/js/modules/animation/gifstream.js+++ b/web/js/modules/animation/gifstream.js@@ -4,6 +4,35 @@ import GifWriter from '../../lib/gifwriter';import NeuQuant from '../../lib/neuquant';Promise.config({ cancellation: true });++// part of neuquant conversion+function componentizedPaletteToArray(paletteRGB) {+ const paletteArray = [];+ let r;+ let g;+ let b;+ for (let i = 0; i < paletteRGB.length; i += 3) {+ r = paletteRGB[i];+ g = paletteRGB[i + 1];+ b = paletteRGB[i + 2];+ paletteArray.push((r << 16) | (g << 8) | b); // eslint-disable-line no-bitwise+ }+ return paletteArray;+}+// part of neuquant conversion+function dataToRGB(data, width, height) {+ let i = 0;+ const length = width * height * 4;+ const rgb = [];+ while (i < length) {+ rgb.push(data[i++]);+ rgb.push(data[i++]);+ rgb.push(data[i++]);+ i++;+ }+ return rgb;+}+export default class GifStream {constructor() {this.canvas = null;@@ -116,9 +145,6 @@ export default class GifStream {if (options.images.length < 1) {throw new Error('No images found');}- options.images.forEach((imageObj) => {- imagePromiseArray.push(this.getImagePromise(imageObj).catch(returnError));- });function returnError(e) {const callbackObj = {blob: null,@@ -126,6 +152,9 @@ export default class GifStream {};callback(callbackObj);}+ options.images.forEach((imageObj) => {+ imagePromiseArray.push(this.getImagePromise(imageObj).catch(returnError));+ });function returnCancel() {console.warn('GIF creation has been cancelled');const callbackObj = {@@ -260,31 +289,3 @@ export default class GifStream {});}}--// part of neuquant conversion-function componentizedPaletteToArray(paletteRGB) {- const paletteArray = [];- let r;- let g;- let b;- for (let i = 0; i < paletteRGB.length; i += 3) {- r = paletteRGB[i];- g = paletteRGB[i + 1];- b = paletteRGB[i + 2];- paletteArray.push((r << 16) | (g << 8) | b); // eslint-disable-line no-bitwise- }- return paletteArray;-}-// part of neuquant conversion-function dataToRGB(data, width, height) {- let i = 0;- const length = width * height * 4;- const rgb = [];- while (i < length) {- rgb.push(data[i++]);- rgb.push(data[i++]);- rgb.push(data[i++]);- i++;- }- return rgb;-}diff --git a/web/js/modules/animation/selectors.js b/web/js/modules/animation/selectors.jsindex 8927b2383..eac79bd60 100644--- a/web/js/modules/animation/selectors.js+++ b/web/js/modules/animation/selectors.js@@ -8,6 +8,39 @@ import { subdailyLayersActive, getLayers } from '../layers/selectors';import { TIME_SCALE_FROM_NUMBER } from '../date/constants';import { formatDisplayDate } from '../date/util';+/*+ * retrieves renderable layers+ *+ * @method getProducts+ * @private+ *+ * @returns {array} array of layer objects+ *+ */+function getProducts(date, state) {+ const layersArray = [];+ const products = getLayers(+ state,+ {+ reverse: true,+ renderable: true,+ date,+ },+ );+ lodashEach(products, (layer) => {+ const layerDate = new Date(date);+ if (layer.endDate) {+ if (layerDate > new Date(layer.endDate)) return;+ }+ if (layer.visible && new Date(layer.startDate) <= layerDate) {+ layersArray.push(layer);+ } else if (!layer.startDate) {+ layersArray.push(layer);+ }+ });+ return layersArray;+}+/** loops through dates and created image* download urls and pushs them to an@@ -70,35 +103,3 @@ export default function getImageArray(}return a;}-/*- * retrieves renderable layers- *- * @method getProducts- * @private- *- * @returns {array} array of layer objects- *- */-function getProducts(date, state) {- const layersArray = [];- const products = getLayers(- state,- {- reverse: true,- renderable: true,- date,- },- );- lodashEach(products, (layer) => {- const layerDate = new Date(date);- if (layer.endDate) {- if (layerDate > new Date(layer.endDate)) return;- }- if (layer.visible && new Date(layer.startDate) <= layerDate) {- layersArray.push(layer);- } else if (!layer.startDate) {- layersArray.push(layer);- }- });- return layersArray;-}diff --git a/web/js/modules/core/actions.js b/web/js/modules/core/actions.jsindex 7bea30f95..a2d64f603 100644--- a/web/js/modules/core/actions.js+++ b/web/js/modules/core/actions.js@@ -1,25 +1,3 @@-export async function requestAction(- dispatch,- actionName,- url,- mimeType,- id,- options,-) {- dispatch(startRequest(actionName, id));- try {- const response = await fetch(url, options);- const data = mimeType === 'application/json'- ? await response.json()- : await response.text();- dispatch(fetchSuccess(actionName, data, id));- return data;- } catch (error) {- dispatch(fetchFailure(actionName, error, id));- console.error(error);- }-}-export function startRequest(actionName, id) {return {type: `${actionName}_START`,@@ -42,3 +20,25 @@ export function fetchFailure(actionName, error, id) {...!!id && { id },};}++export async function requestAction(+ dispatch,+ actionName,+ url,+ mimeType,+ id,+ options,+) {+ dispatch(startRequest(actionName, id));+ try {+ const response = await fetch(url, options);+ const data = mimeType === 'application/json'+ ? await response.json()+ : await response.text();+ dispatch(fetchSuccess(actionName, data, id));+ return data;+ } catch (error) {+ dispatch(fetchFailure(actionName, error, id));+ console.error(error);+ }+}diff --git a/web/js/modules/date/actions.js b/web/js/modules/date/actions.jsindex ced370d0e..17eb81499 100644--- a/web/js/modules/date/actions.js+++ b/web/js/modules/date/actions.js@@ -59,6 +59,11 @@ export function initSecondDate() {type: INIT_SECOND_DATE,};}+export function clearPreload () {+ return {+ type: CLEAR_PRELOAD,+ };+}export function selectDate(date) {return (dispatch, getState) => {const state = getState();@@ -137,8 +142,3 @@ export function setPreload (preloaded, lastPreloadDate) {lastPreloadDate,};}-export function clearPreload () {- return {- type: CLEAR_PRELOAD,- };-}diff --git a/web/js/modules/date/util.js b/web/js/modules/date/util.jsindex 19b9c0501..23841ae6d 100644--- a/web/js/modules/date/util.js+++ b/web/js/modules/date/util.js@@ -277,6 +277,13 @@ export function mapLocationToDateState(return stateFromLocation;}+export const formatDisplayDate = (date, subdaily) => {+ if (!date) return;+ const format = subdaily ? 'YYYY MMM DD HH:mm' : 'YYYY MMM DD';+ const dateString = moment.utc(date).format(format);+ return `${dateString.toUpperCase()}${subdaily ? 'Z' : ''}`;+};+/*** @param {Number} delta Date and direction to change* @param {Number} increment Zoom level of change@@ -380,13 +387,6 @@ export const coverageDateFormatter = (dateType, date, period) => {return (<MonospaceDate date={dateString} />);};-export const formatDisplayDate = (date, subdaily) => {- if (!date) return;- const format = subdaily ? 'YYYY MMM DD HH:mm' : 'YYYY MMM DD';- const dateString = moment.utc(date).format(format);- return `${dateString.toUpperCase()}${subdaily ? 'Z' : ''}`;-};-export const formatISODate = (date) => moment(date).format('YYYY-MM-DD');const getMinDate = function() {diff --git a/web/js/modules/image-download/util.js b/web/js/modules/image-download/util.jsindex 0a3ce31bd..dcedea1e2 100644--- a/web/js/modules/image-download/util.js+++ b/web/js/modules/image-download/util.js@@ -93,62 +93,10 @@ const imageUtilProcessWrap = function(fileType, layersArray, layerWraps, opaciti};};-/**- * Get the snapshots URL to download an image- * @param {String} url- * @param {Object} proj- * @param {Array} layer(s) objects- * @param {Array} lonlats- * @param {Object} dimensions- * @param {Date} dateTime- * @param {String/Boolean} fileType (false for default 'image/jpeg')- * @param {Boolean} isWorldfile- * @param {Array} markerCoordinates- */-export function getDownloadUrl(url, proj, layerDefs, bbox, dimensions, dateTime, fileType, isWorldfile, markerCoordinates) {- const { crs } = proj.selected;- const {- layersArray,- layerWraps,- opacities,- } = imageUtilProcessWrap(- fileType,- imageUtilGetLayers(layerDefs, proj.id),- imageUtilGetLayerWrap(layerDefs),- imageUtilGetLayerOpacities(layerDefs),- );-- const imgFormat = fileType || 'image/jpeg';- const { height, width } = dimensions;- const snappedDateTime = getLatestIntervalTime(layerDefs, dateTime);- const params = [- 'REQUEST=GetSnapshot',- `TIME=${util.toISOStringSeconds(snappedDateTime)}`,- `BBOX=${bboxWMS13(bbox, crs)}`,- `CRS=${crs}`,- `LAYERS=${layersArray.join(',')}`,- `WRAP=${layerWraps.join(',')}`,- `FORMAT=${imgFormat}`,- `WIDTH=${width}`,- `HEIGHT=${height}`,- ];- if (opacities.length > 0) {- params.push(`OPACITIES=${opacities.join(',')}`);- }- if (isWorldfile) {- params.push('WORLDFILE=true');- }-- // handle adding coordinates marker- if (markerCoordinates.length > 0) {- const coords = markerCoordinates.reduce((validCoords, { longitude: lon, latitude: lat }) => {- const mCoord = transform([lon, lat], CRS.GEOGRAPHIC, crs);- // const inExtent = containsCoordinate(boundingExtent(bbox), mCoord);- return validCoords.concat([mCoord[0], mCoord[1]]);- }, []);- params.push(`MARKER=${coords.join(',')}`);- }- return `${url}?${params.join('&')}&ts=${Date.now()}`;+export function imageUtilEstimateResolution(resolution, isGeoProjection) {+ return isGeoProjection+ ? resolution / POLAR_ESTIMATION_CONSTANT+ : resolution / GEO_ESTIMATION_CONSTANT;}/*@@ -288,10 +236,79 @@ export function imageUtilGetLayerWrap(layers) {}) || [];}-export function imageUtilEstimateResolution(resolution, isGeoProjection) {- return isGeoProjection- ? resolution / POLAR_ESTIMATION_CONSTANT- : resolution / GEO_ESTIMATION_CONSTANT;+/**+ * Given a bounding box as an array of a lower left coordinate pair+ * and an upper right coordinate pair, return the BBOX parameter value+ * suitable in a WMS 1.3 call. For EPSG:4326, the coordinates are in+ * Y,X order, otherwise in X,Y order.+ */+export function bboxWMS13(lonlats, crs) {+ if (crs === CRS.GEOGRAPHIC) {+ return `${lonlats[0][1]},${lonlats[0][0]},${lonlats[1][1]},${+ lonlats[1][0]+ }`;+ }+ return `${lonlats[0][0]},${lonlats[0][1]},${lonlats[1][0]},${+ lonlats[1][1]+ }`;+}++/**+ * Get the snapshots URL to download an image+ * @param {String} url+ * @param {Object} proj+ * @param {Array} layer(s) objects+ * @param {Array} lonlats+ * @param {Object} dimensions+ * @param {Date} dateTime+ * @param {String/Boolean} fileType (false for default 'image/jpeg')+ * @param {Boolean} isWorldfile+ * @param {Array} markerCoordinates+ */+export function getDownloadUrl(url, proj, layerDefs, bbox, dimensions, dateTime, fileType, isWorldfile, markerCoordinates) {+ const { crs } = proj.selected;+ const {+ layersArray,+ layerWraps,+ opacities,+ } = imageUtilProcessWrap(+ fileType,+ imageUtilGetLayers(layerDefs, proj.id),+ imageUtilGetLayerWrap(layerDefs),+ imageUtilGetLayerOpacities(layerDefs),+ );++ const imgFormat = fileType || 'image/jpeg';+ const { height, width } = dimensions;+ const snappedDateTime = getLatestIntervalTime(layerDefs, dateTime);+ const params = [+ 'REQUEST=GetSnapshot',+ `TIME=${util.toISOStringSeconds(snappedDateTime)}`,+ `BBOX=${bboxWMS13(bbox, crs)}`,+ `CRS=${crs}`,+ `LAYERS=${layersArray.join(',')}`,+ `WRAP=${layerWraps.join(',')}`,+ `FORMAT=${imgFormat}`,+ `WIDTH=${width}`,+ `HEIGHT=${height}`,+ ];+ if (opacities.length > 0) {+ params.push(`OPACITIES=${opacities.join(',')}`);+ }+ if (isWorldfile) {+ params.push('WORLDFILE=true');+ }++ // handle adding coordinates marker+ if (markerCoordinates.length > 0) {+ const coords = markerCoordinates.reduce((validCoords, { longitude: lon, latitude: lat }) => {+ const mCoord = transform([lon, lat], CRS.GEOGRAPHIC, crs);+ // const inExtent = containsCoordinate(boundingExtent(bbox), mCoord);+ return validCoords.concat([mCoord[0], mCoord[1]]);+ }, []);+ params.push(`MARKER=${coords.join(',')}`);+ }+ return `${url}?${params.join('&')}&ts=${Date.now()}`;}export function imageUtilGetConversionFactor(proj) {@@ -324,23 +341,6 @@ export function imageUtilGetPixelValuesFromCoords(bottomLeft, topRight, map) {};}-/**- * Given a bounding box as an array of a lower left coordinate pair- * and an upper right coordinate pair, return the BBOX parameter value- * suitable in a WMS 1.3 call. For EPSG:4326, the coordinates are in- * Y,X order, otherwise in X,Y order.- */-export function bboxWMS13(lonlats, crs) {- if (crs === CRS.GEOGRAPHIC) {- return `${lonlats[0][1]},${lonlats[0][0]},${lonlats[1][1]},${- lonlats[1][0]- }`;- }- return `${lonlats[0][0]},${lonlats[0][1]},${lonlats[1][0]},${- lonlats[1][1]- }`;-}-export function imageSizeValid(imgHeight, imgWidth, maxSize) {if (imgHeight === 0 && imgWidth === 0) {return false;diff --git a/web/js/modules/layers/actions.js b/web/js/modules/layers/actions.jsindex 95f875c57..fea6aef4c 100644--- a/web/js/modules/layers/actions.js+++ b/web/js/modules/layers/actions.js@@ -283,26 +283,6 @@ export function showLayers(layers) {};}-export function updateGranuleLayerState(layer) {- return (dispatch, getState) => {- const state = getState();- const {- id, def: { endDate, subtitle }, reorderedGranules, granuleDates,- } = layer.wv;-- const mostRecentGranuleDate = granuleDates[0];- const isMostRecentDateOutOfRange = new Date(mostRecentGranuleDate) > new Date(endDate);- const updatedDates = isMostRecentDateOutOfRange ? [] : reorderedGranules || granuleDates;- const granuleFootprints = getGranuleFootprints(layer);- const existingLayer = getGranuleLayer(state, id);-- if (existingLayer) {- dispatch(updateGranuleLayerGeometry(layer, updatedDates, granuleFootprints));- }- dispatch(addGranuleLayerDates(layer, granuleFootprints, `${subtitle}`));- };-}-function updateGranuleLayerGeometry(layer, dates, granuleGeometry) {return (dispatch, getState) => {const { compare, layers } = getState();@@ -347,6 +327,26 @@ function addGranuleLayerDates(layer, granuleFootprints, granulePlatform) {};}+export function updateGranuleLayerState(layer) {+ return (dispatch, getState) => {+ const state = getState();+ const {+ id, def: { endDate, subtitle }, reorderedGranules, granuleDates,+ } = layer.wv;++ const mostRecentGranuleDate = granuleDates[0];+ const isMostRecentDateOutOfRange = new Date(mostRecentGranuleDate) > new Date(endDate);+ const updatedDates = isMostRecentDateOutOfRange ? [] : reorderedGranules || granuleDates;+ const granuleFootprints = getGranuleFootprints(layer);+ const existingLayer = getGranuleLayer(state, id);++ if (existingLayer) {+ dispatch(updateGranuleLayerGeometry(layer, updatedDates, granuleFootprints));+ }+ dispatch(addGranuleLayerDates(layer, granuleFootprints, `${subtitle}`));+ };+}+export function updateGranuleLayerOptions(dates, def, count) {return (dispatch, getState) => {const state = getState();diff --git a/web/js/modules/layers/selectors.js b/web/js/modules/layers/selectors.jsindex 37e023570..0588b1145 100644--- a/web/js/modules/layers/selectors.js+++ b/web/js/modules/layers/selectors.js@@ -21,6 +21,99 @@ const getLayerState = ({ layers }) => layers;const getConfig = ({ config }) => config;const getLayerId = (state, { layer }) => layer && layer.id;+export function addLayer(id, spec = {}, layersParam, layerConfig, overlayLength, projection, groupOverlays, bandComboParam) {+ let layers = lodashCloneDeep(layersParam);+ if (projection) {+ layers = layers.filter((layer) => layer.projections[projection]);+ }+ if (lodashFind(layers, { id })) {+ return layers;+ }+ const def = lodashCloneDeep(layerConfig[id]);+ if (!def) {+ throw new Error(`No such layer: ${id}`);+ }++ // Set layer properties+ def.visible = spec.visible || true;+ def.min = spec.min || undefined;+ def.custom = spec.custom || undefined;+ def.max = spec.max || undefined;+ def.squash = spec.squash || undefined;+ def.disabled = spec.disabled || undefined;+ def.count = spec.count || undefined;++ if (spec.bandCombo) {+ def.bandCombo = {+ r: spec.bandCombo[0],+ g: spec.bandCombo[1],+ b: spec.bandCombo[2],+ };+ } else if (bandComboParam) {+ def.bandCombo = bandComboParam;+ }++ if (!lodashIsUndefined(spec.visible)) {+ def.visible = spec.visible;+ } else if (!lodashIsUndefined(spec.hidden)) {+ def.visible = !spec.hidden;+ }+ def.opacity = lodashIsUndefined(spec.opacity) ? 1.0 : spec.opacity;++ // Place new layer in the appropriate array position+ if (def.group === 'overlays') {+ // TODO assuming first group in the array again here+ const groupIdx = layers.findIndex(({ layergroup }) => layergroup === def.layergroup);++ const findLastRefLayer = (layers) => {+ let lastRefIndex = 0;+ let index = 0;++ layers.forEach((layer) => {+ if (layer.layergroup === 'Reference' && layer.group !== 'baselayers') {+ lastRefIndex = index;+ index += 1;+ }+ });+ if (lastRefIndex === 0) {+ return lastRefIndex;+ }+ return lastRefIndex + 1;+ };++ const lastReferenceLayerIndex = findLastRefLayer(layers);++ if (groupOverlays && groupIdx >= 0) {+ layers.splice(groupIdx, 0, def);+ } else if (def.layergroup === 'Reference') {+ layers.unshift(def);+ } else {+ layers.splice(lastReferenceLayerIndex, 0, def);+ }+ } else {+ const overlaysLength = overlayLength || layers.filter((layer) => layer.group === 'overlays').length;+ layers.splice(overlaysLength, 0, def);+ }++ return layers;+}++/**+ * Reset to starting layers+ * @param {*} startingLayers+ * @param {*} layerConfig+ */+export function resetLayers(config) {+ const { defaults: { startingLayers, projection }, layers: layerConfig } = config;+ let layers = [];+ if (startingLayers) {+ lodashEach(startingLayers, (start) => {+ layers = addLayer(start.id, start, layers, layerConfig, null, projection);+ });+ }+ return layers;+}+export const getStartingLayers = createSelector([getConfig], (config) => resetLayers(config));export const isGroupingEnabled = ({ compare, layers }) => layers[compare.activeString].groupOverlays;@@ -35,6 +128,16 @@ export const getCollections = (layers, date, layer) => {}};+/**+ * Return a list of layers for the currently active compare state+ * regardless of projection (no hidden layers)+ */+const getActiveLayersEmbed = (state, activeString) => {+ const { compare, layers } = state;+ const activeLayers = layers[activeString || compare.activeString].layers;+ return activeLayers.filter((layer) => layer.visible);+};+/*** Return a list of layers for the currently active compare state* regardless of projection@@ -79,6 +182,12 @@ export const getGranuleCount = (state, id) => {return layer ? layer.count : 20;};+export const getGranulePlatform = (state, activeString) => {+ const { compare, layers } = state;+ const { granulePlatform } = layers[activeString || compare.activeString];+ return granulePlatform;+};+export const getActiveGranuleFootPrints = (state) => {const { layers, compare: { activeString } } = state;const granuleLayers = getActiveGranuleLayers(state);@@ -94,12 +203,6 @@ export const getActiveGranuleFootPrints = (state) => {return isActiveGranuleVisible.length && granuleLayers ? granuleFootprints : {};};-export const getGranulePlatform = (state, activeString) => {- const { compare, layers } = state;- const { granulePlatform } = layers[activeString || compare.activeString];- return granulePlatform;-};-export const getGranuleLayersOfActivePlatform = (platform, activeLayers) => {const activeLayersArray = Object.entries(activeLayers);const platformLayers = [];@@ -112,34 +215,16 @@ export const getGranuleLayersOfActivePlatform = (platform, activeLayers) => {};/**- * Return an array of overlay groups for the currently active compare state- * that are available for the currently active projection- */-export const getActiveOverlayGroups = (state) => {- const {- embed, compare, layers, proj,- } = state;- const { overlayGroups } = layers[compare.activeString];- if (embed && embed.isEmbedModeActive) {- return getActiveOverlayGroupsEmbed(state);- }- const activeLayersMap = getActiveLayersMap(state);- return (overlayGroups || []).filter(- (group) => group.layers.filter(- (id) => !!activeLayersMap[id].projections[proj.id],- ).length,- );-};--/**- * Return a list of layers for the currently active compare state- * regardless of projection (no hidden layers)+ * Return a map of active layers where key is layer id*/-const getActiveLayersEmbed = (state, activeString) => {- const { compare, layers } = state;- const activeLayers = layers[activeString || compare.activeString].layers;- return activeLayers.filter((layer) => layer.visible);-};+export const getActiveLayersMap = createSelector(+ [getActiveLayers],+ (activeLayers) => {+ const activeLayerMap = {};+ activeLayers.forEach((layer) => { activeLayerMap[layer.id] = layer; });+ return activeLayerMap;+ },+);/*** Return an array of filtered overlay groups for the currently active compare state@@ -163,305 +248,40 @@ const getActiveOverlayGroupsEmbed = (state) => {};/**- * Return a list of layer groups that filter out removed, hidden layers- */-export const getFilteredOverlayGroups = (overlayGroups, overlays) => {- const overlaysLayerIds = overlays.map((layer) => layer.id);- // remove reference layers and revise overlay layers group- return overlayGroups- .filter((group) => group.groupName !== 'Reference')- .map((group) => {- const filteredLayers = group.layers.filter((layer) => overlaysLayerIds.includes(layer));- const filteredGroup = { ...group };- filteredGroup.layers = filteredLayers;- return filteredGroup;- });-};--/**- * Return a map of active layers where key is layer id- */-export const getActiveLayersMap = createSelector(- [getActiveLayers],- (activeLayers) => {- const activeLayerMap = {};- activeLayers.forEach((layer) => { activeLayerMap[layer.id] = layer; });- return activeLayerMap;- },-);--export const getAllActiveLayers = createSelector(- [getProjState, getCompareState, getLayerState],- (proj, compare, layers) => getLayers({ proj, compare, layers }, {}),-);--export const getAllActiveOverlaysBaselayers = createSelector(- [getProjState, getCompareState, getLayerState],- (proj, compare, layers) => getLayers({ proj, compare, layers }, { group: 'all' }),-);--export const getActiveVisibleLayersAtDate = (state, date, activeString) => {- const { proj } = state;- const layers = getActiveLayers(state, activeString);- const baseLayers = layers.filter(({ group }) => group === 'baselayers');- return layers.filter(- (l) => !!l.projections[proj.id] && isRenderable(l.id, layers, date, baseLayers, {}),- );-};--export function hasMeasurementSource(current, config, projId) {- let hasSource;- Object.values(current.sources).forEach((source) => {- if (hasMeasurementSetting(current, source, config, projId)) {- hasSource = true;- }- });- return hasSource;-}--/**- * Look up the measurement description path for a given layer- * so that metadata can be shown in the layer info modal. Ignore- * Orbital Track layers since they will be in multiple measurements.- */-export const makeGetDescription = () => createSelector(- [getConfig, getLayerId],- ({ layers, measurements }, layerId) => {- if (!layerId) return;- const { layergroup } = layers[layerId];- if (layergroup === 'Orbital Track') {- return;- }- const [setting] = Object.keys(measurements)- .filter((key) => !key.includes('Featured'))- .map((key) => measurements[key])- .flatMap(({ sources }) => Object.values(sources))- .filter(({ settings }) => settings.find((id) => id === layerId));- return (setting || {}).description;- },-);--/**- * var hasMeasurementSetting - Checks the (current) measurement's source- * for a setting and returns true if present.- *- * @param {string} current The current config.measurements measurement.- * @param {string} source The current measurement source.- * @return {boolean} Return true if the source contains settings.- *- */-export function hasMeasurementSetting(current, source, config, projId) {- let hasSetting;- Object.values(source.settings).forEach((setting) => {- const layer = config.layers[setting];- if (layer && layer.projections) {- const proj = layer.projections;- if (layer.id === setting && Object.keys(proj).indexOf(projId) > -1) {- if (layer.layergroup === 'Orbital Track') {- if (current.id === 'orbital-track') {- hasSetting = true;- }- // Don't output sources with only orbit tracks- } else {- hasSetting = true;- }- }- }- });- return hasSetting;-}--/**- * See if an array of layers has a subdaily- * product in it- * @param {Array} layers- */-export function hasSubDaily(layers) {- if (layers && layers.length) {- for (let i = 0; i < layers.length; i += 1) {- if (layers[i].period === 'subdaily') {- return true;- }- }- }- return false;-}--export const subdailyLayersActive = createSelector(- [getActiveLayers],- (layers) => hasSubDaily(layers),-);--export function addLayer(id, spec = {}, layersParam, layerConfig, overlayLength, projection, groupOverlays, bandComboParam) {- let layers = lodashCloneDeep(layersParam);- if (projection) {- layers = layers.filter((layer) => layer.projections[projection]);- }- if (lodashFind(layers, { id })) {- return layers;- }- const def = lodashCloneDeep(layerConfig[id]);- if (!def) {- throw new Error(`No such layer: ${id}`);- }-- // Set layer properties- def.visible = spec.visible || true;- def.min = spec.min || undefined;- def.custom = spec.custom || undefined;- def.max = spec.max || undefined;- def.squash = spec.squash || undefined;- def.disabled = spec.disabled || undefined;- def.count = spec.count || undefined;-- if (spec.bandCombo) {- def.bandCombo = {- r: spec.bandCombo[0],- g: spec.bandCombo[1],- b: spec.bandCombo[2],- };- } else if (bandComboParam) {- def.bandCombo = bandComboParam;- }-- if (!lodashIsUndefined(spec.visible)) {- def.visible = spec.visible;- } else if (!lodashIsUndefined(spec.hidden)) {- def.visible = !spec.hidden;- }- def.opacity = lodashIsUndefined(spec.opacity) ? 1.0 : spec.opacity;-- // Place new layer in the appropriate array position- if (def.group === 'overlays') {- // TODO assuming first group in the array again here- const groupIdx = layers.findIndex(({ layergroup }) => layergroup === def.layergroup);-- const findLastRefLayer = (layers) => {- let lastRefIndex = 0;- let index = 0;-- layers.forEach((layer) => {- if (layer.layergroup === 'Reference' && layer.group !== 'baselayers') {- lastRefIndex = index;- index += 1;- }- });- if (lastRefIndex === 0) {- return lastRefIndex;- }- return lastRefIndex + 1;- };-- const lastReferenceLayerIndex = findLastRefLayer(layers);-- if (groupOverlays && groupIdx >= 0) {- layers.splice(groupIdx, 0, def);- } else if (def.layergroup === 'Reference') {- layers.unshift(def);- } else {- layers.splice(lastReferenceLayerIndex, 0, def);- }- } else {- const overlaysLength = overlayLength || layers.filter((layer) => layer.group === 'overlays').length;- layers.splice(overlaysLength, 0, def);- }-- return layers;-}--/**- * Reset to starting layers- * @param {*} startingLayers- * @param {*} layerConfig- */-export function resetLayers(config) {- const { defaults: { startingLayers, projection }, layers: layerConfig } = config;- let layers = [];- if (startingLayers) {- lodashEach(startingLayers, (start) => {- layers = addLayer(start.id, start, layers, layerConfig, null, projection);- });- }- return layers;-}--/**- *- * @param {*} config- * @param {*} layerId- * @param {*} projId- */-export function getTitles(config, layerId, projId) {- try {- let title;- let subtitle;- let tags;- const forProj = lodashGet(- config,- `layers.${layerId}.projections.${projId}`,- );- if (forProj) {- title = forProj.title;- subtitle = forProj.subtitle;- tags = forProj.tags;- }- const forLayer = config.layers[layerId];- title = title || forLayer.title || `[${layerId}]`;- subtitle = subtitle || forLayer.subtitle || '';- tags = tags || forLayer.tags || '';- return {- title,- subtitle,- tags,- };- } catch (err) {- throw new Error(`error in layer ${layerId}: ${err}`);- }-}--/**- *- * @param {*} layers- * @param {*} spec- * @param {*} state+ * Return an array of overlay groups for the currently active compare state+ * that are available for the currently active projection*/-export function getLayers(state, spec = {}, layersParam) {- const layers = layersParam || getActiveLayers(state);- const baselayers = forGroup('baselayers', spec, layers, state);- const overlays = forGroup('overlays', spec, layers, state);- if (spec.group === 'baselayers') {- return baselayers;- }- if (spec.group === 'overlays') {- return overlays;- }- if (spec.group === 'all') {- return { baselayers, overlays };- }- if (spec.group) {- throw new Error(`Invalid layer group: ${spec.group}`);- }- return baselayers.concat(overlays);-}--function forGroup(group, spec = {}, activeLayers, state) {- const projId = state.proj.id;- let results = [];- const defs = lodashFilter(activeLayers, { group });- lodashEach(defs, (def) => {- const notInProj = !def.projections[projId];- const notRenderable = spec.renderable- && !isRenderable(def.id, activeLayers, spec.date, null, state);- if (notInProj || notRenderable) {- return;- }- results.push(def);- });- if (spec.reverse) {- results = results.reverse();+export const getActiveOverlayGroups = (state) => {+ const {+ embed, compare, layers, proj,+ } = state;+ const { overlayGroups } = layers[compare.activeString];+ if (embed && embed.isEmbedModeActive) {+ return getActiveOverlayGroupsEmbed(state);}- return results;-}+ const activeLayersMap = getActiveLayersMap(state);+ return (overlayGroups || []).filter(+ (group) => group.layers.filter(+ (id) => !!activeLayersMap[id].projections[proj.id],+ ).length,+ );+};++/**+ * Return a list of layer groups that filter out removed, hidden layers+ */+export const getFilteredOverlayGroups = (overlayGroups, overlays) => {+ const overlaysLayerIds = overlays.map((layer) => layer.id);+ // remove reference layers and revise overlay layers group+ return overlayGroups+ .filter((group) => group.groupName !== 'Reference')+ .map((group) => {+ const filteredLayers = group.layers.filter((layer) => overlaysLayerIds.includes(layer));+ const filteredGroup = { ...group };+ filteredGroup.layers = filteredLayers;+ return filteredGroup;+ });+};/*** Build end date for future layer@@ -585,14 +405,49 @@ export function available(id, date, layers, parameters) {return true;}+function forGroup(group, spec = {}, activeLayers, state) {+ const projId = state.proj.id;+ let results = [];+ const defs = lodashFilter(activeLayers, { group });+ lodashEach(defs, (def) => {+ const notInProj = !def.projections[projId];+ // eslint-disable-next-line no-use-before-define+ const notRenderable = spec.renderable && !isRenderable(def.id, activeLayers, spec.date, null, state);+ if (notInProj || notRenderable) {+ return;+ }+ results.push(def);+ });+ if (spec.reverse) {+ results = results.reverse();+ }+ return results;+}+/**- * Determine if a given layer is available- * @param {*} id - the layer id+ *+ * @param {*} layers+ * @param {*} spec+ * @param {*} state*/-export const memoizedAvailable = createSelector(- [getSelectedDate, getActiveLayers, getConfigParameters],- (currentDate, activeLayers, parameters) => lodashMemoize((id) => available(id, currentDate, activeLayers, parameters)),-);+export function getLayers(state, spec = {}, layersParam) {+ const layers = layersParam || getActiveLayers(state);+ const baselayers = forGroup('baselayers', spec, layers, state);+ const overlays = forGroup('overlays', spec, layers, state);+ if (spec.group === 'baselayers') {+ return baselayers;+ }+ if (spec.group === 'overlays') {+ return overlays;+ }+ if (spec.group === 'all') {+ return { baselayers, overlays };+ }+ if (spec.group) {+ throw new Error(`Invalid layer group: ${spec.group}`);+ }+ return baselayers.concat(overlays);+}/*** Determine if a layer should be rendered if it would be visible@@ -635,6 +490,151 @@ export function isRenderable(id, layers, date, bLayers, state) {return !obscured;}+export const getActiveVisibleLayersAtDate = (state, date, activeString) => {+ const { proj } = state;+ const layers = getActiveLayers(state, activeString);+ const baseLayers = layers.filter(({ group }) => group === 'baselayers');+ return layers.filter(+ (l) => !!l.projections[proj.id] && isRenderable(l.id, layers, date, baseLayers, {}),+ );+};++/**+ * var hasMeasurementSetting - Checks the (current) measurement's source+ * for a setting and returns true if present.+ *+ * @param {string} current The current config.measurements measurement.+ * @param {string} source The current measurement source.+ * @return {boolean} Return true if the source contains settings.+ *+ */+export function hasMeasurementSetting(current, source, config, projId) {+ let hasSetting;+ Object.values(source.settings).forEach((setting) => {+ const layer = config.layers[setting];+ if (layer && layer.projections) {+ const proj = layer.projections;+ if (layer.id === setting && Object.keys(proj).indexOf(projId) > -1) {+ if (layer.layergroup === 'Orbital Track') {+ if (current.id === 'orbital-track') {+ hasSetting = true;+ }+ // Don't output sources with only orbit tracks+ } else {+ hasSetting = true;+ }+ }+ }+ });+ return hasSetting;+}++export function hasMeasurementSource(current, config, projId) {+ let hasSource;+ Object.values(current.sources).forEach((source) => {+ if (hasMeasurementSetting(current, source, config, projId)) {+ hasSource = true;+ }+ });+ return hasSource;+}++/**+ * Look up the measurement description path for a given layer+ * so that metadata can be shown in the layer info modal. Ignore+ * Orbital Track layers since they will be in multiple measurements.+ */+export const makeGetDescription = () => createSelector(+ [getConfig, getLayerId],+ ({ layers, measurements }, layerId) => {+ if (!layerId) return;+ const { layergroup } = layers[layerId];+ if (layergroup === 'Orbital Track') {+ return;+ }+ const [setting] = Object.keys(measurements)+ .filter((key) => !key.includes('Featured'))+ .map((key) => measurements[key])+ .flatMap(({ sources }) => Object.values(sources))+ .filter(({ settings }) => settings.find((id) => id === layerId));+ return (setting || {}).description;+ },+);++/**+ * See if an array of layers has a subdaily+ * product in it+ * @param {Array} layers+ */+export function hasSubDaily(layers) {+ if (layers && layers.length) {+ for (let i = 0; i < layers.length; i += 1) {+ if (layers[i].period === 'subdaily') {+ return true;+ }+ }+ }+ return false;+}++export const subdailyLayersActive = createSelector(+ [getActiveLayers],+ (layers) => hasSubDaily(layers),+);++/**+ *+ * @param {*} config+ * @param {*} layerId+ * @param {*} projId+ */+export function getTitles(config, layerId, projId) {+ try {+ let title;+ let subtitle;+ let tags;+ const forProj = lodashGet(+ config,+ `layers.${layerId}.projections.${projId}`,+ );+ if (forProj) {+ title = forProj.title;+ subtitle = forProj.subtitle;+ tags = forProj.tags;+ }+ const forLayer = config.layers[layerId];+ title = title || forLayer.title || `[${layerId}]`;+ subtitle = subtitle || forLayer.subtitle || '';+ tags = tags || forLayer.tags || '';+ return {+ title,+ subtitle,+ tags,+ };+ } catch (err) {+ throw new Error(`error in layer ${layerId}: ${err}`);+ }+}++export const getAllActiveLayers = createSelector(+ [getProjState, getCompareState, getLayerState],+ (proj, compare, layers) => getLayers({ proj, compare, layers }, {}),+);++export const getAllActiveOverlaysBaselayers = createSelector(+ [getProjState, getCompareState, getLayerState],+ (proj, compare, layers) => getLayers({ proj, compare, layers }, { group: 'all' }),+);++/**+ * Determine if a given layer is available+ * @param {*} id - the layer id+ */+export const memoizedAvailable = createSelector(+ [getSelectedDate, getActiveLayers, getConfigParameters],+ (currentDate, activeLayers, parameters) => lodashMemoize((id) => available(id, currentDate, activeLayers, parameters)),+);+export const findEventLayers = (originalLayers, newLayers) => {const uniqueLayers = [];@@ -743,6 +743,23 @@ export function replaceSubGroup(return pushToBottom(layerId, layers, layerSplit);}+function getZoomLevel(layer, zoom, proj, sources) {+ // Account for offset between the map's top zoom level and the+ // lowest-resolution TileMatrix in polar layers+ const zoomOffset = proj === 'arctic' || proj === 'antarctic' ? 1 : 0;+ const { matrixSet } = layer.projections[proj];++ if (matrixSet !== undefined && layer.type !== 'vector') {+ const { source } = layer.projections[proj];+ const zoomLimit = sources[source].matrixSets[matrixSet].resolutions.length - 1 + zoomOffset;+ if (zoom > zoomLimit) {+ const overZoomValue = Math.round((zoom - zoomLimit) * 100) / 100;+ return overZoomValue;+ }+ }+ return null;+}+export function getZotsForActiveLayers(state) {const {config, proj, map, notifications,@@ -766,23 +783,6 @@ export function getZotsForActiveLayers(state) {return zotObj;}-function getZoomLevel(layer, zoom, proj, sources) {- // Account for offset between the map's top zoom level and the- // lowest-resolution TileMatrix in polar layers- const zoomOffset = proj === 'arctic' || proj === 'antarctic' ? 1 : 0;- const { matrixSet } = layer.projections[proj];-- if (matrixSet !== undefined && layer.type !== 'vector') {- const { source } = layer.projections[proj];- const zoomLimit = sources[source].matrixSets[matrixSet].resolutions.length - 1 + zoomOffset;- if (zoom > zoomLimit) {- const overZoomValue = Math.round((zoom - zoomLimit) * 100) / 100;- return overZoomValue;- }- }- return null;-}-export function getMaxZoomLevelLayerCollection(layers, zoom, proj, sources) {const zoomOffset = proj === 'arctic' || proj === 'antarctic' ? 1 : 0;let maxZoom;diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.jsindex f40b54f47..78a64d2fe 100644--- a/web/js/modules/layers/util.js+++ b/web/js/modules/layers/util.js@@ -104,6 +104,28 @@ export function prevDateInDateRange(def, date, dateArray) {return { previous, next };}+export function getOverlayGroups(layers, prevGroups = []) {+ const allGroupsMap = {};+ layers.forEach(({ id, group, layergroup }) => {+ if (group !== 'overlays') {+ return;+ }+ if (allGroupsMap[layergroup]) {+ allGroupsMap[layergroup].push(id);+ } else {+ allGroupsMap[layergroup] = [id];+ }+ });+ return Object.keys(allGroupsMap).map((groupName) => {+ const prevGroup = prevGroups.find((g) => g.groupName === groupName);+ return {+ groupName,+ layers: allGroupsMap[groupName],+ collapsed: prevGroup ? prevGroup.collapsed : false,+ };+ });+}+/*** Return revised maxEndDate based on given start/end date limits*@@ -876,6 +898,139 @@ export function serializeGroupOverlays (groupOverlays, state, activeString) {return groupOverlays;}+const getLayerSpec = (attributes) => {+ let hidden = false;+ let opacity = 1.0;+ let max;+ let min;+ let squash;+ let custom;+ let disabled;+ let count;+ let bandCombo;++ lodashEach(attributes, (attr) => {+ if (attr.id === 'hidden') {+ hidden = true;+ }+ if (attr.id === 'opacity') {+ opacity = util.clamp(parseFloat(attr.value), 0, 1);+ // eslint-disable-next-line no-restricted-globals+ if (isNaN(opacity)) opacity = 0; // "opacity=0.0" is opacity in URL, resulting in NaN+ }+ if (attr.id === 'disabled') {+ const values = util.toArray(attr.value.split(';'));+ disabled = values;+ }++ if (attr.id === 'max' && typeof attr.value === 'string') {+ const maxArray = [];+ const values = util.toArray(attr.value.split(';'));+ lodashEach(values, (value, index) => {+ if (value === '') {+ maxArray.push(undefined);+ return;+ }+ const maxValue = parseFloat(value);+ if (lodashIsNaN(maxValue)) {+ // eslint-disable-next-line no-console+ console.warn(`Invalid max value: ${value}`);+ } else {+ maxArray.push(maxValue);+ }+ });+ max = maxArray.length ? maxArray : undefined;+ }+ if (attr.id === 'min' && typeof attr.value === 'string') {+ const minArray = [];+ const values = util.toArray(attr.value.split(';'));+ lodashEach(values, (value, index) => {+ if (value === '') {+ minArray.push(undefined);+ return;+ }+ const minValue = parseFloat(value);+ if (lodashIsNaN(minValue)) {+ // eslint-disable-next-line no-console+ console.warn(`Invalid min value: ${value}`);+ } else {+ minArray.push(minValue);+ }+ });+ min = minArray.length ? minArray : undefined;+ }+ if (attr.id === 'squash') {+ if (attr.value === true) {+ squash = [true];+ } else if (typeof attr.value === 'string') {+ const squashArray = [];+ const values = util.toArray(attr.value.split(';'));+ lodashEach(values, (value) => {+ squashArray.push(value === 'true');+ });+ squash = squashArray.length ? squashArray : undefined;+ }+ }++ if (attr.id === 'bands') {+ const values = util.toArray(attr.value.split(';'));+ bandCombo = values;+ }++ if (attr.id === 'palette') {+ const values = util.toArray(attr.value.split(';'));+ custom = values;+ }+ if (attr.id === 'style') {+ const values = util.toArray(attr.value.split(';'));+ custom = values;+ }+ // granule specific count (defaults to 20 if no param)+ if (attr.id === 'count') {+ count = Number(attr.value);+ }+ });++ return {+ hidden,+ opacity,+ count,+ bandCombo,++ // only include palette attributes if Array.length condition+ // is true: https://stackoverflow.com/a/40560953/4589331+ ...isArray(custom) && { custom },+ ...isArray(min) && { min },+ ...isArray(squash) && { squash },+ ...isArray(max) && { max },+ ...isArray(disabled) && { disabled },+ };+};++const createLayerArrayFromState = function(layers, config) {+ let layerArray = [];+ if (lodashIsUndefined(layers)) {+ return layerArray;+ }+ const projection = lodashGet(config, 'parameters.p') || 'geographic';+ layers.reverse().forEach((layerDef) => {+ if (!config.layers[layerDef.id]) {+ // eslint-disable-next-line no-console+ console.warn(`No such layer: ${layerDef.id}`);+ return;+ }+ layerArray = addLayer(+ layerDef.id,+ getLayerSpec(layerDef.attributes),+ layerArray,+ config.layers,+ null,+ projection,+ );+ });+ return layerArray;+};+// this function takes an array of date ranges in this format:// [{ layer.period, dateRanges.startDate: Date, dateRanges.endDate: Date, dateRanges.dateInterval: Number}]// the array is first sorted, and then checked for any overlap@@ -1061,139 +1216,6 @@ export function layersParse12(stateObj, config) {}}-const getLayerSpec = (attributes) => {- let hidden = false;- let opacity = 1.0;- let max;- let min;- let squash;- let custom;- let disabled;- let count;- let bandCombo;-- lodashEach(attributes, (attr) => {- if (attr.id === 'hidden') {- hidden = true;- }- if (attr.id === 'opacity') {- opacity = util.clamp(parseFloat(attr.value), 0, 1);- // eslint-disable-next-line no-restricted-globals- if (isNaN(opacity)) opacity = 0; // "opacity=0.0" is opacity in URL, resulting in NaN- }- if (attr.id === 'disabled') {- const values = util.toArray(attr.value.split(';'));- disabled = values;- }-- if (attr.id === 'max' && typeof attr.value === 'string') {- const maxArray = [];- const values = util.toArray(attr.value.split(';'));- lodashEach(values, (value, index) => {- if (value === '') {- maxArray.push(undefined);- return;- }- const maxValue = parseFloat(value);- if (lodashIsNaN(maxValue)) {- // eslint-disable-next-line no-console- console.warn(`Invalid max value: ${value}`);- } else {- maxArray.push(maxValue);- }- });- max = maxArray.length ? maxArray : undefined;- }- if (attr.id === 'min' && typeof attr.value === 'string') {- const minArray = [];- const values = util.toArray(attr.value.split(';'));- lodashEach(values, (value, index) => {- if (value === '') {- minArray.push(undefined);- return;- }- const minValue = parseFloat(value);- if (lodashIsNaN(minValue)) {- // eslint-disable-next-line no-console- console.warn(`Invalid min value: ${value}`);- } else {- minArray.push(minValue);- }- });- min = minArray.length ? minArray : undefined;- }- if (attr.id === 'squash') {- if (attr.value === true) {- squash = [true];- } else if (typeof attr.value === 'string') {- const squashArray = [];- const values = util.toArray(attr.value.split(';'));- lodashEach(values, (value) => {- squashArray.push(value === 'true');- });- squash = squashArray.length ? squashArray : undefined;- }- }-- if (attr.id === 'bands') {- const values = util.toArray(attr.value.split(';'));- bandCombo = values;- }-- if (attr.id === 'palette') {- const values = util.toArray(attr.value.split(';'));- custom = values;- }- if (attr.id === 'style') {- const values = util.toArray(attr.value.split(';'));- custom = values;- }- // granule specific count (defaults to 20 if no param)- if (attr.id === 'count') {- count = Number(attr.value);- }- });-- return {- hidden,- opacity,- count,- bandCombo,-- // only include palette attributes if Array.length condition- // is true: https://stackoverflow.com/a/40560953/4589331- ...isArray(custom) && { custom },- ...isArray(min) && { min },- ...isArray(squash) && { squash },- ...isArray(max) && { max },- ...isArray(disabled) && { disabled },- };-};--const createLayerArrayFromState = function(layers, config) {- let layerArray = [];- if (lodashIsUndefined(layers)) {- return layerArray;- }- const projection = lodashGet(config, 'parameters.p') || 'geographic';- layers.reverse().forEach((layerDef) => {- if (!config.layers[layerDef.id]) {- // eslint-disable-next-line no-console- console.warn(`No such layer: ${layerDef.id}`);- return;- }- layerArray = addLayer(- layerDef.id,- getLayerSpec(layerDef.attributes),- layerArray,- config.layers,- null,- projection,- );- });- return layerArray;-};-export function mapLocationToLayerState(parameters,stateFromLocation,@@ -1559,28 +1581,6 @@ export function mockFutureTimeLayerOptions(layers, mockFutureLayerParameters) {}}-export function getOverlayGroups(layers, prevGroups = []) {- const allGroupsMap = {};- layers.forEach(({ id, group, layergroup }) => {- if (group !== 'overlays') {- return;- }- if (allGroupsMap[layergroup]) {- allGroupsMap[layergroup].push(id);- } else {- allGroupsMap[layergroup] = [id];- }- });- return Object.keys(allGroupsMap).map((groupName) => {- const prevGroup = prevGroups.find((g) => g.groupName === groupName);- return {- groupName,- layers: allGroupsMap[groupName],- collapsed: prevGroup ? prevGroup.collapsed : false,- };- });-}-export function getLayersFromGroups (state, groups) {const baselayers = getLayers(state, { group: 'baselayers' });const activeLayersMap = getActiveLayersMap(state);diff --git a/web/js/modules/location-search/util.js b/web/js/modules/location-search/util.jsindex 1c1cda195..f61e170f2 100644--- a/web/js/modules/location-search/util.js+++ b/web/js/modules/location-search/util.js@@ -42,6 +42,33 @@ export function areCoordinatesWithinExtent(proj, coordinates) {return containsCoordinate(extent, coord); // expects X then Y!}+/**+ * Create Ol vector layer map pin+ * @param {Array} coordinates+ * @param {Object} pinProps+ * @param {Number} id+ */+const createPin = function(coordinates, pinProps, id, removeMarkerPin) {+ const overlayEl = document.createElement('div');+ const removeMarker = () => {+ ReactDOM.unmountComponentAtNode(overlayEl);+ removeMarkerPin();+ };+ ReactDOM.render(+ React.createElement(LocationMarker, { ...pinProps, removeMarker }),+ overlayEl,+ );+ const markerPin = new OlOverlay({+ element: overlayEl,+ position: coordinates,+ positioning: 'bottom-center',+ stopEvent: false,+ id,+ });++ return markerPin;+};+/*** Get coordinates marker* @param {Object} map@@ -73,31 +100,11 @@ export function getCoordinatesMarker(proj, coordinatesObject, results, removeMar}/**- * Create Ol vector layer map pin- * @param {Array} coordinates- * @param {Object} pinProps- * @param {Number} id+ * @return {Boolean} is Location Search local storage set to 'collapsed'*/-const createPin = function(coordinates, pinProps, id, removeMarkerPin) {- const overlayEl = document.createElement('div');- const removeMarker = () => {- ReactDOM.unmountComponentAtNode(overlayEl);- removeMarkerPin();- };- ReactDOM.render(- React.createElement(LocationMarker, { ...pinProps, removeMarker }),- overlayEl,- );- const markerPin = new OlOverlay({- element: overlayEl,- position: coordinates,- positioning: 'bottom-center',- stopEvent: false,- id,- });-- return markerPin;-};+export function getLocalStorageCollapseState() {+ return safeLocalStorage.getItem(LOCATION_SEARCH_COLLAPSED) === 'collapsed';+}/***@@ -161,13 +168,6 @@ export function serializeCoordinatesWrapper(coordinates, state) {}}-/**- * @return {Boolean} is Location Search local storage set to 'collapsed'- */-export function getLocalStorageCollapseState() {- return safeLocalStorage.getItem(LOCATION_SEARCH_COLLAPSED) === 'collapsed';-}-/*** @param {String} storageValue* @return {Void}diff --git a/web/js/modules/map/util.js b/web/js/modules/map/util.jsindex 42365ab17..5e1cdc65e 100644--- a/web/js/modules/map/util.js+++ b/web/js/modules/map/util.js@@ -12,6 +12,75 @@ import Promise from 'bluebird';import { encode } from '../link/util';import { getActiveVisibleLayersAtDate } from '../layers/selectors';+/*+ * Set default extent according to time of day:+ *+ * at 00:00 UTC, start at far eastern edge of+ * map: "20.6015625,-46.546875,179.9296875,53.015625"+ *+ * at 23:00 UTC, start at far western edge of map:+ * "-179.9296875,-46.546875,-20.6015625,53.015625"+ *+ * @method getLeadingExtent+ * @static+ * @param {Object} Time+ *+ * @returns {object} Extent Array+ */+export function getLeadingExtent(loadtime) {+ let curHour = loadtime.getUTCHours();++ // For earlier hours when data is still being filled in, force a far eastern perspective+ if (curHour < 3) {+ curHour = 23;+ } else if (curHour < 9) {+ curHour = 0;+ }++ // Compute east/west bounds+ const minLon = 20.6015625 + curHour * (-200.53125 / 23.0);+ const maxLon = minLon + 159.328125;++ const minLat = -46.546875;+ const maxLat = 53.015625;++ return [minLon, minLat, maxLon, maxLat];+}++export function getRotatedExtent(map) {+ const view = map.getView();+ return olExtent.getForViewAndSize(view.getCenter(), view.getResolution(), 0, map.getSize());+}++/**+ * Determines if an exent object contains valid values.+ *+ * @method isExtentValid+ * @static+ *+ * @param extent {OpenLayers.Bound} The extent to check.+ *+ * @return {boolean} False if any of the values is NaN, otherwise returns+ * true.+ */+export function mapIsExtentValid(extent) {+ if (lodashIsUndefined(extent)) {+ return false;+ }+ let valid = true;+ if (extent.toArray) {+ extent = extent.toArray();+ }+ lodashEach(extent, (value) => {+ // eslint-disable-next-line no-restricted-globals+ if (isNaN(value)) {+ valid = false;+ return false;+ }+ });+ return valid;+}+export function getMapParameterSetup(parameters,config,@@ -76,75 +145,6 @@ export function getMapParameterSetup(};}-export function getRotatedExtent(map) {- const view = map.getView();- return olExtent.getForViewAndSize(view.getCenter(), view.getResolution(), 0, map.getSize());-}--/**- * Determines if an exent object contains valid values.- *- * @method isExtentValid- * @static- *- * @param extent {OpenLayers.Bound} The extent to check.- *- * @return {boolean} False if any of the values is NaN, otherwise returns- * true.- */-export function mapIsExtentValid(extent) {- if (lodashIsUndefined(extent)) {- return false;- }- let valid = true;- if (extent.toArray) {- extent = extent.toArray();- }- lodashEach(extent, (value) => {- // eslint-disable-next-line no-restricted-globals- if (isNaN(value)) {- valid = false;- return false;- }- });- return valid;-}--/*- * Set default extent according to time of day:- *- * at 00:00 UTC, start at far eastern edge of- * map: "20.6015625,-46.546875,179.9296875,53.015625"- *- * at 23:00 UTC, start at far western edge of map:- * "-179.9296875,-46.546875,-20.6015625,53.015625"- *- * @method getLeadingExtent- * @static- * @param {Object} Time- *- * @returns {object} Extent Array- */-export function getLeadingExtent(loadtime) {- let curHour = loadtime.getUTCHours();-- // For earlier hours when data is still being filled in, force a far eastern perspective- if (curHour < 3) {- curHour = 23;- } else if (curHour < 9) {- curHour = 0;- }-- // Compute east/west bounds- const minLon = 20.6015625 + curHour * (-200.53125 / 23.0);- const maxLon = minLon + 159.328125;-- const minLat = -46.546875;- const maxLat = 53.015625;-- return [minLon, minLat, maxLon, maxLat];-}-/*** Calculate the current extent from the map's extent (boundaries) &* the viewport extent (boundaries).@@ -208,16 +208,12 @@ function promiseTileLayer(layer, extent, map) {currentZ = tileGrid.getZForResolution(resolution, zDirection);i = 0;- const complete = function () {- tileSource.un('tileloadend', onLoad);- tileSource.un('tileloaderror', onLoad);- resolve();- };const onLoad = function onLoad (e) {if (e.type === 'tileloadend') {i -= 1;if (i === 0) {+ // eslint-disable-next-line no-use-before-definecomplete();}} else {@@ -225,10 +221,17 @@ function promiseTileLayer(layer, extent, map) {console.error(`No response for tile request ${layer.wv.key}`);// some gibs data is not accurate and rejecting here// will break the animation if tile doesn't exist+ // eslint-disable-next-line no-use-before-definecomplete();}};+ const complete = function () {+ tileSource.un('tileloadend', onLoad);+ tileSource.un('tileloaderror', onLoad);+ resolve();+ };+const loadTile = function ([one, two, three]) {const tile = tileSource.getTile(one, two, three, pixelRatio, projection);try {diff --git a/web/js/modules/notifications/util.js b/web/js/modules/notifications/util.jsindex a96876df2..14527d59c 100644--- a/web/js/modules/notifications/util.js+++ b/web/js/modules/notifications/util.js@@ -10,6 +10,17 @@ const {// as layer notices which only show if the specified layers are in the active listconst LAYER_NOTICE = 'layer-notice';+export function transformLayerNotices(notifications) {+ return notifications.map((notice) => {+ const splitPath = notice.path.split('/');+ const layers = splitPath.slice(2, splitPath.length);+ return {+ ...notice,+ layers,+ };+ });+}+/*** Categorizes the returned array* @function separateByType@@ -51,6 +62,29 @@ export function separateByType(notifications) {};}+/**+ * Determines if most recent notification has already been seen+ * @function objectAlreadySeen+ * @private+ * @param {object} obj - object from API array+ * @returns {void}+ */+function objectAlreadySeen(obj) {+ const type = obj.notification_type;+ const idString = obj.created_at.toString();+ let fieldValueMatches = false;+ const fieldExists = !!safeLocalStorage.getItem(type);+ const localStorageValueMatches = (property, value) => {+ const oldValue = safeLocalStorage.getItem(property);+ return oldValue && new Date(value) <= new Date(oldValue);+ };++ if (fieldExists) {+ fieldValueMatches = localStorageValueMatches(type, idString);+ }+ return fieldValueMatches;+}+/*** Sets active state global values* @function getPriority@@ -79,6 +113,34 @@ export function getPriority(sortedNotifications) {return priority;}+/**+ * Determines the number of status of this type that the user is yet to see+ * @function getNumberOfTypeNotSeen+ * @private+ * @param {string} type - Status type+ * @param {object} arra - array of status of one type+ * @returns {Number} count - number of unseen messages in LocalStorage+ */+export function getNumberOfTypeNotSeen(type, arra) {+ const storageItem = safeLocalStorage.getItem(type);+ const len = arra.length;+ let count = 0;++ if (!storageItem) {+ return len;+ }++ for (let i = 0; i < len; i += 1) {+ if (new Date(storageItem) < new Date(arra[i].created_at)) {+ count += 1;+ } else {+ return count;+ }+ }++ return count;+}+/*** Gets a total count of the notifications - excluding layerNotices* @function getCount@@ -117,68 +179,6 @@ export function addToLocalStorage({ messages, outages, alerts }) {}}-/**- * Determines the number of status of this type that the user is yet to see- * @function getNumberOfTypeNotSeen- * @private- * @param {string} type - Status type- * @param {object} arra - array of status of one type- * @returns {Number} count - number of unseen messages in LocalStorage- */-export function getNumberOfTypeNotSeen(type, arra) {- const storageItem = safeLocalStorage.getItem(type);- const len = arra.length;- let count = 0;-- if (!storageItem) {- return len;- }-- for (let i = 0; i < len; i += 1) {- if (new Date(storageItem) < new Date(arra[i].created_at)) {- count += 1;- } else {- return count;- }- }-- return count;-}--/**- * Determines if most recent notification has already been seen- * @function objectAlreadySeen- * @private- * @param {object} obj - object from API array- * @returns {void}- */-function objectAlreadySeen(obj) {- const type = obj.notification_type;- const idString = obj.created_at.toString();- let fieldValueMatches = false;- const fieldExists = !!safeLocalStorage.getItem(type);- const localStorageValueMatches = (property, value) => {- const oldValue = safeLocalStorage.getItem(property);- return oldValue && new Date(value) <= new Date(oldValue);- };-- if (fieldExists) {- fieldValueMatches = localStorageValueMatches(type, idString);- }- return fieldValueMatches;-}--export function transformLayerNotices(notifications) {- return notifications.map((notice) => {- const splitPath = notice.path.split('/');- const layers = splitPath.slice(2, splitPath.length);- return {- ...notice,- layers,- };- });-}-export function getLayerNoticesForLayer(layer, notifications) {const { layerNotices } = notifications.object;const notices = (layerNotices || []).filter((notice) => notice.layers.includes(layer));diff --git a/web/js/modules/palettes/actions.js b/web/js/modules/palettes/actions.jsindex e1fd4971e..06060065a 100644--- a/web/js/modules/palettes/actions.js+++ b/web/js/modules/palettes/actions.js@@ -121,6 +121,47 @@ export function clearCustomPalette(layerId, index, groupName) {});};}++export function setToggledClassification(layerId, classIndex, index, groupName) {+ return (dispatch, getState) => {+ const state = getState();+ const newActivePalettesObj = setDisabledSelector(+ layerId,+ classIndex,+ index,+ state.palettes[groupName],+ state,+ );+ let hasDisabled = false;++ if (newActivePalettesObj[layerId] !== undefined) {+ newActivePalettesObj[layerId].maps.forEach((colorMap) => {+ if (colorMap.disabled && colorMap.disabled.length) {+ hasDisabled = true;+ }+ });+ }++ // sometimes an active palette will be related to layers that we already removed during the+ // tour process. need to check if the layer is active to prevent errors when dispatching+ const getLayerIndex = () => {+ const activeLayers = state.layers[groupName].layers;+ return lodashFindIndex(activeLayers, { id: layerId });+ };+ const layerIndex = state.layers[groupName].layers[getLayerIndex()];+ if (layerIndex) {+ dispatch({+ type: SET_DISABLED_CLASSIFICATION,+ groupName,+ activeString: groupName,+ layerId,+ palettes: newActivePalettesObj,+ props: { disabled: hasDisabled },+ });+ }+ };+}+/*** Action to remove custom palettes*@@ -161,45 +202,7 @@ export function loadedCustomPalettes(customs) {custom: customs,};}-export function setToggledClassification(layerId, classIndex, index, groupName) {- return (dispatch, getState) => {- const state = getState();- const newActivePalettesObj = setDisabledSelector(- layerId,- classIndex,- index,- state.palettes[groupName],- state,- );- let hasDisabled = false;-- if (newActivePalettesObj[layerId] !== undefined) {- newActivePalettesObj[layerId].maps.forEach((colorMap) => {- if (colorMap.disabled && colorMap.disabled.length) {- hasDisabled = true;- }- });- }- // sometimes an active palette will be related to layers that we already removed during the- // tour process. need to check if the layer is active to prevent errors when dispatching- const getLayerIndex = () => {- const activeLayers = state.layers[groupName].layers;- return lodashFindIndex(activeLayers, { id: layerId });- };- const layerIndex = state.layers[groupName].layers[getLayerIndex()];- if (layerIndex) {- dispatch({- type: SET_DISABLED_CLASSIFICATION,- groupName,- activeString: groupName,- layerId,- palettes: newActivePalettesObj,- props: { disabled: hasDisabled },- });- }- };-}export function refreshDisabledClassification(layerId, disabledArray, index, groupName) {return (dispatch, getState) => {const state = getState();diff --git a/web/js/modules/palettes/selectors.js b/web/js/modules/palettes/selectors.jsindex 7113f95d8..a78b73275 100644--- a/web/js/modules/palettes/selectors.js+++ b/web/js/modules/palettes/selectors.js@@ -9,6 +9,22 @@ import {import update from 'immutability-helper';import { getMinValue } from './util';++export function getRenderedPalette(layerId, index, state) {+ const { config, palettes } = state;+ const name = lodashGet(config, `layers['${layerId}'].palette.id`);+ let palette = palettes.rendered[name];+ if (!palette) {+ throw new Error(`${name} Is not a rendered palette`);+ }+ if (!lodashIsUndefined(index)) {+ if (palette.maps) {+ palette = palette.maps[index];+ }+ }+ return lodashCloneDeep(palette);+}+/*** Gets a single colormap (entries / legend combo)*@@ -41,29 +57,6 @@ export function getPalette(layerId, index, groupStr, state) {return getRenderedPalette(layerId, index, state);}-export function getRenderedPalette(layerId, index, state) {- const { config, palettes } = state;- const name = lodashGet(config, `layers['${layerId}'].palette.id`);- let palette = palettes.rendered[name];- if (!palette) {- throw new Error(`${name} Is not a rendered palette`);- }- if (!lodashIsUndefined(index)) {- if (palette.maps) {- palette = palette.maps[index];- }- }- return lodashCloneDeep(palette);-}--export function getPaletteLegends(layerId, groupName, state) {- const paletteLegends = [];- const count = getCount(layerId, state);- for (let i = 0; i < count; i += 1) {- paletteLegends.push(getPaletteLegend(layerId, i, groupName, state));- }- return paletteLegends;-}/*** Gets the legend of a colormap*@@ -79,6 +72,7 @@ export function getPaletteLegend(layerId, index, groupStr, state) {const value = getPalette(layerId, index, groupStr, state);return value.legend || value.entries;}+export function getCount(layerId, state) {const renderedPalette = getRenderedPalette(layerId, undefined, state);if (renderedPalette && renderedPalette.maps) {@@ -86,6 +80,16 @@ export function getCount(layerId, state) {}return 0;}++export function getPaletteLegends(layerId, groupName, state) {+ const paletteLegends = [];+ const count = getCount(layerId, state);+ for (let i = 0; i < count; i += 1) {+ paletteLegends.push(getPaletteLegend(layerId, i, groupName, state));+ }+ return paletteLegends;+}+/*** Gets the legend of a colormap*@@ -301,6 +305,24 @@ export function findIndex(layerId, value, index, groupStr, state) {return result;}+function prepare(layerId, palettesObj, state) {+ let newPalettes = lodashCloneDeep(palettesObj);+ if (!newPalettes[layerId]) newPalettes[layerId] = {};+ const active = newPalettes[layerId];+ active.maps = active.maps || [];+ lodashEach(getRenderedPalette(layerId, undefined, state).maps, (+ palette,+ index,+ ) => {+ if (!active.maps[index]) {+ newPalettes = update(newPalettes, {+ [layerId]: { maps: { [index]: { $set: palette } } },+ });+ }+ });+ return newPalettes;+}+export function setCustomSelector(layerId, paletteId, index, groupName, state) {const { config, palettes } = state;if (!config.layers[layerId]) {@@ -317,6 +339,11 @@ export function setCustomSelector(layerId, paletteId, index, groupName, state) {return updateLookup(layerId, newPalettes, state);}+export function isActive(layerId, group, state) {+ group = group || state.compare.activeString;+ return state.palettes[group][layerId];+}+export function getKey(layerId, groupStr, state) {groupStr = groupStr || state.compare.activeString;if (!isActive(layerId, groupStr, state)) {@@ -339,11 +366,6 @@ export function getKey(layerId, groupStr, state) {return keys.join(',');}-export function isActive(layerId, group, state) {- group = group || state.compare.activeString;- return state.palettes[group][layerId];-}-export function refreshDisabledSelector(layerId,disabled,@@ -474,24 +496,6 @@ export function clearCustomSelector(layerId, index, palettes, state) {return updateLookup(layerId, newPalettes, state);}-function prepare(layerId, palettesObj, state) {- let newPalettes = lodashCloneDeep(palettesObj);- if (!newPalettes[layerId]) newPalettes[layerId] = {};- const active = newPalettes[layerId];- active.maps = active.maps || [];- lodashEach(getRenderedPalette(layerId, undefined, state).maps, (- palette,- index,- ) => {- if (!active.maps[index]) {- newPalettes = update(newPalettes, {- [layerId]: { maps: { [index]: { $set: palette } } },- });- }- });- return newPalettes;-}-export function isPaletteAllowed(layerId, config) {const { palette } = config.layers[layerId];if (!palette || palette.immutable) {diff --git a/web/js/modules/palettes/util.js b/web/js/modules/palettes/util.jsindex 86cd560fc..a0e837660 100644--- a/web/js/modules/palettes/util.js+++ b/web/js/modules/palettes/util.js@@ -221,6 +221,24 @@ export function parseLegacyPalettes(return stateFromLocation;}+const createPaletteAttributeObject = function(def, value, attrObj, count) {+ const { key } = attrObj;+ 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(';'),+ });+};+/*** Serialize palette info for layer*@@ -307,24 +325,6 @@ export function getPaletteAttributeArray(layerId, palettes, state) {}}-const createPaletteAttributeObject = function(def, value, attrObj, count) {- const { key } = attrObj;- 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(';'),- });-};-/*** Initiate palette from layer information that was derived from the* permalink in the layerParserdiff --git a/web/js/modules/product-picker/search-config.js b/web/js/modules/product-picker/search-config.jsindex 6c4787abc..388b75852 100644--- a/web/js/modules/product-picker/search-config.js+++ b/web/js/modules/product-picker/search-config.js@@ -67,16 +67,29 @@ function updateFacetCounts(facetField, layer) {});}-function updateAllFacetCounts(currentFilters, searchTerm) {- resetFacetCounts();- facetFields.forEach((facetField) => {- // Start with a filtered result array that has all OTHER facets applied- const otherFilters = currentFilters.filter((f) => f.field !== facetField);- layersMatchCriteria(otherFilters, searchTerm)- .forEach((layer) => {- updateFacetCounts(facetField, layer);- });+// Check for search term match+function filterSearch (layer, val, terms) {+ if (!val) {+ return false;+ }++ let isFilteredOut = false;+ const names = getTitles(configRef, layer.id, projectionRef);+ const title = lodashToLower(names.title);+ const subtitle = lodashToLower(names.subtitle);+ const tags = lodashToLower(names.tags);+ const layerId = lodashToLower(layer.id);+ const conceptIdsArray = layer.conceptIds || [];+ const conceptIds = conceptIdsArray.map(({ value = '' }) => value.toLowerCase());+ const shortNames = conceptIdsArray.map(({ shortName = '' }) => shortName.toLowerCase());+ const matchItems = [title, subtitle, tags, layerId, conceptIds];++ lodashForEach(terms, (term) => {+ isFilteredOut = matchItems.every((item) => !item.includes(term))+ && shortNames.every((name) => name.indexOf(term) < 0);+ if (isFilteredOut) return false;});+ return isFilteredOut;}function layerMatchesFilters(layer, filters) {@@ -100,29 +113,16 @@ function layersMatchCriteria(currentFilters, searchTerm) {});}-// Check for search term match-function filterSearch (layer, val, terms) {- if (!val) {- return false;- }-- let isFilteredOut = false;- const names = getTitles(configRef, layer.id, projectionRef);- const title = lodashToLower(names.title);- const subtitle = lodashToLower(names.subtitle);- const tags = lodashToLower(names.tags);- const layerId = lodashToLower(layer.id);- const conceptIdsArray = layer.conceptIds || [];- const conceptIds = conceptIdsArray.map(({ value = '' }) => value.toLowerCase());- const shortNames = conceptIdsArray.map(({ shortName = '' }) => shortName.toLowerCase());- const matchItems = [title, subtitle, tags, layerId, conceptIds];-- lodashForEach(terms, (term) => {- isFilteredOut = matchItems.every((item) => !item.includes(term))- && shortNames.every((name) => name.indexOf(term) < 0);- if (isFilteredOut) return false;+function updateAllFacetCounts(currentFilters, searchTerm) {+ resetFacetCounts();+ facetFields.forEach((facetField) => {+ // Start with a filtered result array that has all OTHER facets applied+ const otherFilters = currentFilters.filter((f) => f.field !== facetField);+ layersMatchCriteria(otherFilters, searchTerm)+ .forEach((layer) => {+ updateFacetCounts(facetField, layer);+ });});- return isFilteredOut;}/**diff --git a/web/js/modules/vector-styles/selectors.js b/web/js/modules/vector-styles/selectors.jsindex 331f0eb4e..247acf967 100644--- a/web/js/modules/vector-styles/selectors.js+++ b/web/js/modules/vector-styles/selectors.js@@ -34,6 +34,21 @@ export function getVectorLayers(state) {}, []);}+export function getAllVectorStyles(layerId, index, state) {+ const { config, vectorStyles } = state;+ const name = lodashGet(config, `layers.${layerId}.vectorStyle.id`);+ let vectorStyle = vectorStyles.custom[name];+ if (!vectorStyle) {+ throw new Error(`${name} Is not a rendered vectorStyle`);+ }+ if (!lodashIsUndefined(index)) {+ if (vectorStyle.layers) {+ vectorStyle = vectorStyle.layers[index];+ }+ }+ return vectorStyle;+}+/*** Gets a single colormap (entries / legend combo)*@@ -55,21 +70,6 @@ export function getVectorStyle(layerId, index, groupStr, state) {return getAllVectorStyles(layerId, index, state);}-export function getAllVectorStyles(layerId, index, state) {- const { config, vectorStyles } = state;- const name = lodashGet(config, `layers.${layerId}.vectorStyle.id`);- let vectorStyle = vectorStyles.custom[name];- if (!vectorStyle) {- throw new Error(`${name} Is not a rendered vectorStyle`);- }- if (!lodashIsUndefined(index)) {- if (vectorStyle.layers) {- vectorStyle = vectorStyle.layers[index];- }- }- return vectorStyle;-}-export function findIndex(layerId, type, value, index, groupStr, state) {index = index || 0;const { values } = getVectorStyle(layerId, index, groupStr, state).entries;@@ -96,6 +96,34 @@ export function setRange(layerId, props, index, palettes, state) {};}+const updateGlStylePalette = (glStyle, rgbPalette) => {+ for (let i = 0; i < glStyle.layers.length; i += 1) {+ const thisPaintObj = glStyle.layers[i].paint;+ if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'line-color')) {+ thisPaintObj['line-color'] = rgbPalette;+ }+ if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'circle-color')) {+ thisPaintObj['circle-color'] = rgbPalette;+ }+ if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'fill-color')) {+ thisPaintObj['fill-color'] = rgbPalette;+ }+ if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'line-width')) {+ thisPaintObj['line-width'] = 2;+ }+ }+ return glStyle;+};++const shouldRenderFeature = (feature, acceptableExtent) => {+ if (!acceptableExtent) return true;+ const midpoint = feature.getFlatCoordinates+ ? feature.getFlatCoordinates()+ : feature.getGeometry().getFlatCoordinates();+ if (containsCoordinate(acceptableExtent, midpoint)) return true;+ return false;+};+/** Sets the Style Function for the layer (this styles vector features)** @param {Object} def | Layer definition@@ -172,33 +200,12 @@ export function setStyleFunction(def, vectorStyleId, vectorStyles, layer, state,return vectorStyleId;}-const shouldRenderFeature = (feature, acceptableExtent) => {- if (!acceptableExtent) return true;- const midpoint = feature.getFlatCoordinates- ? feature.getFlatCoordinates()- : feature.getGeometry().getFlatCoordinates();- if (containsCoordinate(acceptableExtent, midpoint)) return true;- return false;-};--const updateGlStylePalette = (glStyle, rgbPalette) => {- for (let i = 0; i < glStyle.layers.length; i += 1) {- const thisPaintObj = glStyle.layers[i].paint;- if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'line-color')) {- thisPaintObj['line-color'] = rgbPalette;- }- if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'circle-color')) {- thisPaintObj['circle-color'] = rgbPalette;- }- if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'fill-color')) {- thisPaintObj['fill-color'] = rgbPalette;- }- if (Object.prototype.hasOwnProperty.call(thisPaintObj, 'line-width')) {- thisPaintObj['line-width'] = 2;- }+export function isActive(layerId, group, state) {+ group = group || state.compare.activeString;+ if (state.vectorStyles.custom[layerId]) {+ return state.vectorStyles[group][layerId];}- return glStyle;-};+}export function getKey(layerId, groupStr, state) {groupStr = groupStr || state.compare.activeString;@@ -219,13 +226,6 @@ export function getKey(layerId, groupStr, state) {return keys.join(',');}-export function isActive(layerId, group, state) {- group = group || state.compare.activeString;- if (state.vectorStyles.custom[layerId]) {- return state.vectorStyles[group][layerId];- }-}-export function clearStyleFunction(def, vectorStyleId, vectorStyles, layer, state) {const layerId = def.id;const glStyle = vectorStyles[layerId];diff --git a/web/js/ol/lookupimagetile.js b/web/js/ol/lookupimagetile.jsindex 472efa11d..778003251 100644--- a/web/js/ol/lookupimagetile.js+++ b/web/js/ol/lookupimagetile.js@@ -3,6 +3,33 @@ import OlTileState from 'ol/TileState';import UPNG from 'upng-js';import { cloneDeep as lodashCloneDeep } from 'lodash';+/**+ * @method getPixelColorsToDisplay+ * @static+ * @param obj {object} - The Colormap for this product+ *+ * @returns {object} Colormap containing only active colors+ */+function getPixelColorsToDisplay(obj) {+ return Object.entries(obj).reduce((acc, [key, value]) => {+ if (!(value.r === 0 && value.g === 0 && value.b === 0 && value.a === 0)) {+ acc[key] = value;+ }+ return acc;+ }, {});+}++function getColormap(rawColormap) {+ const colorMapArr = [];+ for (let i = 0; i < rawColormap.length; i += 3) {+ colorMapArr.push(rawColormap[i]);+ colorMapArr.push(rawColormap[i + 1]);+ colorMapArr.push(rawColormap[i + 2]);+ colorMapArr.push(255);+ }+ return colorMapArr;+}+class LookupImageTile extends OlImageTile {constructor(lookup, tileCoord, state, src, crossOrigin, tileLoadFunction, sourceOptions) {super(tileCoord, state, src, crossOrigin, tileLoadFunction, sourceOptions);@@ -169,33 +196,6 @@ LookupImageTile.prototype.load = function() {}};-/**- * @method getPixelColorsToDisplay- * @static- * @param obj {object} - The Colormap for this product- *- * @returns {object} Colormap containing only active colors- */-function getPixelColorsToDisplay(obj) {- return Object.entries(obj).reduce((acc, [key, value]) => {- if (!(value.r === 0 && value.g === 0 && value.b === 0 && value.a === 0)) {- acc[key] = value;- }- return acc;- }, {});-}--function getColormap(rawColormap) {- const colorMapArr = [];- for (let i = 0; i < rawColormap.length; i += 3) {- colorMapArr.push(rawColormap[i]);- colorMapArr.push(rawColormap[i + 1]);- colorMapArr.push(rawColormap[i + 2]);- colorMapArr.push(255);- }- return colorMapArr;-}-export default function lookupFactory(lookup, sourceOptions) {return function(tileCoord, state, src, crossOrigin, tileLoadFunction) {return new LookupImageTile(