Interactive interface for browsing global, full-resolution satellite imagery
WV-4041: Modernizing VectorFilter, VectorStyleSelect, VectorInteractions, and VectorDialog Components (#6792)
christof-wittreich90d3cec63b69
diff --git a/web/js/components/layer/settings/vector-filter.js b/web/js/components/layer/settings/vector-filter.jsindex da98124cd..57c4d8582 100644--- a/web/js/components/layer/settings/vector-filter.js+++ b/web/js/components/layer/settings/vector-filter.js@@ -1,46 +1,41 @@-import React from 'react';+import { useState } from 'react';import PropTypes from 'prop-types';import lodashDebounce from 'lodash/debounce';-class VectorFilter extends React.Component {- constructor(props) {- super(props);- this.state = {- start: props.start,- end: props.end,- };- this.debounceSetRange = lodashDebounce(props.setFilterRange, 300);- this.updateFilter = this.updateFilter.bind(this);- }+function VectorFilter(props) {+ const {+ start,+ end,+ layerId,+ index,+ groupName,+ min,+ max,+ } = props;++ const [startState, setStartState] = useState(start);+ const [endState, setEndState] = useState(end);++ const debounceSetRange = lodashDebounce(props.setFilterRange, 300);/*** Update filter values* @param {Array} thresholdArray | Array of start/end indexs for colormap*/- updateFilter(thresholdArray) {- const { layerId, index, groupName } = this.props;- const { start, end } = this.state;-+ function updateFilter(thresholdArray) {const newStart = Math.ceil(Number(thresholdArray[0]));const newEnd = Math.ceil(Number(thresholdArray[1]));- if (newStart !== start && newEnd !== end) {- this.setState({- start: newStart,- end: newEnd,- });- } else if (newStart !== start) {- this.setState({- start: newStart,- });- } else if (newEnd !== end) {- this.setState({- end: newEnd,- });- } else {+ if (newStart === startState && newEnd === endState) {return;}+ if (newStart !== startState) {+ setStartState(newStart);+ }+ if (newEnd !== endState) {+ setEndState(newEnd);+ }// Update local state on every range-selector change but debounce threshold model update- this.debounceSetRange(+ debounceSetRange(layerId,parseFloat(newStart),parseFloat(newEnd),@@ -49,39 +44,36 @@ class VectorFilter extends React.Component {);}- render() {- const { start, end } = this.state;- const { index, min, max } = this.props;- const startLabel = 0; // Placeholder- const endLabel = 100; // Placeholder- return (- <div className="layer-threshold-select settings-component">- <h2 className="wv-header">Filters</h2>- <div- id={`wv-layer-options-threshold${index}`}- className="wv-layer-options-threshold"- >- <input- type="range"- className="form-range"- defaultValue={end}- min={min}- max={max}- onChange={(e) => this.updateFilter([start, parseInt(e.target.value, 10)])}- style={{ '--value-percent': `${index}%` }}- />- <div className="wv-label">- <span className="wv-label-range-min wv-label-range">- {startLabel}- </span>- <span className="wv-label-range-max wv-label-range">- {endLabel}- </span>- </div>+ const startLabel = 0; // Placeholder+ const endLabel = 100; // Placeholder++ return (+ <div className="layer-threshold-select settings-component">+ <h2 className="wv-header">Filters</h2>+ <div+ id={`wv-layer-options-threshold${index}`}+ className="wv-layer-options-threshold"+ >+ <input+ type="range"+ className="form-range"+ defaultValue={endState}+ min={min}+ max={max}+ onChange={(e) => updateFilter([startState, parseInt(e.target.value, 10)])}+ style={{ '--value-percent': `${index}%` }}+ />+ <div className="wv-label">+ <span className="wv-label-range-min wv-label-range">+ {startLabel}+ </span>+ <span className="wv-label-range-max wv-label-range">+ {endLabel}+ </span></div></div>- );- }+ </div>+ );}VectorFilter.propTypes = {end: PropTypes.number,diff --git a/web/js/components/layer/settings/vector-style.js b/web/js/components/layer/settings/vector-style.jsindex ef75ce6ab..90cab1acf 100644--- a/web/js/components/layer/settings/vector-style.js+++ b/web/js/components/layer/settings/vector-style.js@@ -1,24 +1,26 @@-import React from 'react';+import { useState } from 'react';import PropTypes from 'prop-types';import Scrollbar from '../../util/scrollbar';import { isConditional } from '../../../modules/vector-styles/util';-class VectorStyleSelect extends React.Component {- constructor(props) {- super(props);- this.state = {- activeVectorStyle: props.activeVectorStyle,- };- }+function VectorStyleSelect(props) {+ const {+ activeVectorStyle,+ layer,+ clearStyle,+ setStyle,+ groupName,+ index,+ vectorStyles,+ } = props;++ const [activeVectorStyleState, setActiveVectorStyleState] = useState(activeVectorStyle);/*** Pass vector style to model after selection* @param {String} id | custom VectorStyle Id*/- onChangeVectorStyle(vectorStyleId) {- const {- layer, clearStyle, setStyle, groupName,- } = this.props;+ function onChangeVectorStyle(vectorStyleId) {setTimeout(() => {if (vectorStyleId === layer.id) {clearStyle(layer, vectorStyleId, groupName);@@ -26,29 +28,28 @@ class VectorStyleSelect extends React.Component {setStyle(layer, vectorStyleId, groupName);}}, 0);- this.setState({ activeVectorStyle: vectorStyleId });+ setActiveVectorStyleState(vectorStyleId);}/*** Apply logic to render correct vectorStyle selection* @param {String} id | Legend Id*/- customLegend(styleLayerObject) {- const { activeVectorStyle } = this.state;+ function customLegend(styleLayerObject) {const description = styleLayerObject['source-description'] || styleLayerObject.id;const isConditionalStyling = styleLayerObject.paint ? isConditional(styleLayerObject.paint['line-color'] || styleLayerObject.paint['circle-color'] || styleLayerObject.paint['fill-color']) : false;return isConditionalStyling- ? this.renderLegendMultiItem(+ ? renderLegendMultiItem(styleLayerObject,styleLayerObject.id,description,)- : this.renderSelectorItemSingle(+ : renderSelectorItemSingle(styleLayerObject,styleLayerObject.id,description,- activeVectorStyle === styleLayerObject.id,+ activeVectorStyleState === styleLayerObject.id,);}@@ -59,7 +60,7 @@ class VectorStyleSelect extends React.Component {* @param {String} description | Colormap name*/- renderLegendMultiItem(vectorStyle, vectorStyleId, description) {+ function renderLegendMultiItem(vectorStyle, vectorStyleId, description) {const caseDefaultClassName = 'wv-palette-selector-row ';const array = Array.from(vectorStyle.paint['line-color'] || vectorStyle.paint['circle-color'] || vectorStyle.paint['fill-color']);array.shift();@@ -110,7 +111,7 @@ class VectorStyleSelect extends React.Component {* @param {String} description | Colormap name* @param {Boolean} isSelected | is this colormap active*/- renderSelectorItemSingle(vectorStyle, vectorStyleId, description, isSelected) {+ function renderSelectorItemSingle(vectorStyle, vectorStyleId, description, isSelected) {const color = vectorStyle.paint? vectorStyle.paint['line-color'] || vectorStyle.paint['circle-color'] || vectorStyle.paint['fill-color']: 'rgb(255, 255, 255)';@@ -122,7 +123,7 @@ class VectorStyleSelect extends React.Component {id={`wv-palette-radio-${vectorStyleId}`}type="radio"name="wv-palette-radio"- onClick={() => this.onChangeVectorStyle(vectorStyleId)}+ onClick={() => onChangeVectorStyle(vectorStyleId)}/>{isSelected && (<span className="dot" />@@ -140,40 +141,38 @@ class VectorStyleSelect extends React.Component {);}- render() {- const { index, vectorStyles, layer } = this.props;- const vectorStyleId = layer.vectorStyle.id;- const vectorStyle = vectorStyles[vectorStyleId];- const vectorStyleLayers = vectorStyle.layers;+ const vectorStyleId = layer.vectorStyle.id;+ const vectorStyle = vectorStyles[vectorStyleId];+ const vectorStyleLayers = vectorStyle.layers;- const uniqueStyleLayers = vectorStyleLayers.filter((a) => {- if (!this[a.id]) {- this[a.id] = true;- return true;- }- return false;- }, Object.create(null));- return (- <div- className="wv-palette-selector settings-component noselect"- id={`wv-palette-selector${index}`}- >- <h2 className="wv-header">Vector Styles</h2>- <Scrollbar style={{ maxHeight: '200px' }}>- {+ const unqiueLayersSeen = new Set();- uniqueStyleLayers.map((styleLayerObject) => {- if (styleLayerObject && styleLayerObject) {- const item = this.customLegend(styleLayerObject);- return item;- }- return false;- })+ const uniqueStyleLayers = vectorStyleLayers.filter((a) => {+ if (!unqiueLayersSeen.has(a.id)) {+ unqiueLayersSeen.add(a.id);+ return true;+ }+ return false;+ }, Object.create(null));++ return (+ <div+ className="wv-palette-selector settings-component noselect"+ id={`wv-palette-selector${index}`}+ >+ <h2 className="wv-header">Vector Styles</h2>+ {vectorStyleLayers.length}+ <Scrollbar style={{ maxHeight: '200px' }}>+ {uniqueStyleLayers && uniqueStyleLayers.map((styleLayerObject) => {+ if (styleLayerObject && styleLayerObject) {+ const item = customLegend(styleLayerObject);+ return item;}- </Scrollbar>- </div>- );- }+ return false;+ })}+ </Scrollbar>+ </div>+ );}VectorStyleSelect.propTypes = {diff --git a/web/js/containers/map-interactions/ol-vector-interactions.js b/web/js/containers/map-interactions/ol-vector-interactions.jsindex 0a4c76adc..a6fd28904 100644--- a/web/js/containers/map-interactions/ol-vector-interactions.js+++ b/web/js/containers/map-interactions/ol-vector-interactions.js@@ -5,7 +5,7 @@ import {includes as lodashIncludes,groupBy as lodashGroupBy,} from 'lodash';-import React from 'react';+import { useState, useEffect, useRef } from 'react';import PropTypes from 'prop-types';import * as olExtent from 'ol/extent';import { transform } from 'ol/proj';@@ -25,6 +25,7 @@ import { changeCursor as changeCursorActionCreator } from '../../modules/map/actimport { ACTIVATE_VECTOR_ZOOM_ALERT, ACTIVATE_VECTOR_EXCEEDED_ALERT, DISABLE_VECTOR_EXCEEDED_ALERT } from '../../modules/alerts/constants';import util from '../../util/util';import { CRS, FULL_MAP_EXTENT } from '../../modules/map/constants';+import usePrevious from '../../util/customHooks';import {GRANULE_HOVERED,GRANULE_HOVER_UPDATE,@@ -36,44 +37,108 @@ import {const { events } = util;-export class VectorInteractions extends React.Component {- constructor(props) {- super(props);- this.state = {- granuleDate: null,- granulePlatform: null,- };- const options = { leading: true, trailing: true };- this.mouseMove = lodashThrottle(this.mouseMove.bind(this), 200, options);- this.mouseOut = lodashThrottle(this.mouseOut.bind(this), 200, options);- this.moveEnd = this.moveEnd.bind(this);- this.singleClick = this.singleClick.bind(this);- }+export function VectorInteractions(props) {+ const {+ granuleFootprints,+ compareState,+ granulePlatform,+ swipeOffset,+ visibleExtent,+ isShowingClick,+ changeCursor,+ measureIsActive,+ proj,+ isCoordinateSearchActive,+ isMobile,+ screenSize,+ lastSelected,+ openVectorDialog,+ onCloseModal,+ selectVectorFeatures,+ modalState,+ getDialogObject,+ activeLayers,+ activateVectorZoomAlert,+ activateVectorExceededResultsAlert,+ clearVectorExceededResultsAlert,+ isEmbedModeActive,+ isVectorExceededAlertPresent,+ } = props;- componentDidMount() {- events.on(MAP_MOVE_END, this.moveEnd);- events.on(MAP_MOUSE_MOVE, this.mouseMove);- events.on(MAP_MOUSE_OUT, this.mouseOut);- events.on(MAP_SINGLE_CLICK, this.singleClick);- }+ const [granuleDate, setGranuleDate] = useState(null);+ const [, setGranulePlatformState] = useState(null);- componentDidUpdate(prevProps) {- const { granuleFootprints } = this.props;- const { granuleDate } = this.state;- if (granuleDate && prevProps.granuleFootprints !== granuleFootprints) {- this.clearGranuleFootprint();+ const granuleDateRef = useRef(granuleDate);+ const granulePlatformRef = useRef(granulePlatform);+ const granuleFootprintsRef = useRef(granuleFootprints);+ const isShowingClickRef = useRef(isShowingClick);++ const prevGranuleFootprints = usePrevious(granuleFootprints);++ function mouseOut() {+ mouseMoveThrottled.cancel();+ events.trigger(GRANULE_HOVERED, null);+ };++ function mouseMove({ pixel }, map, crs) {+ const coord = map.getCoordinateFromPixel(pixel);+ const [lon, lat] = transform(coord, crs, CRS.GEOGRAPHIC);++ if (measureIsActive || isCoordinateSearchActive) {+ return;+ }+ if (lon < -250 || lon > 250 || lat < -90 || lat > 90) {+ return;+ }+ if (granuleFootprints && !isMobile) {+ handleGranuleHover(pixel, coord);}+ handleCursorChange(pixel, map, lon, lat);}- componentWillUnmount() {- events.off(MAP_MOVE_END, this.moveEnd);- events.off(MAP_MOUSE_MOVE, this.mouseMove);- events.off(MAP_MOUSE_OUT, this.mouseOut);- events.off(MAP_SINGLE_CLICK, this.singleClick);- }+ const options = { leading: true, trailing: true };+ const mouseMoveThrottled = lodashThrottle(mouseMove, 200, options);+ const mouseOutThrottled = lodashThrottle(mouseOut, 200, options);++ useEffect(() => {+ events.on(MAP_MOVE_END, moveEnd);+ events.on(MAP_MOUSE_MOVE, mouseMoveThrottled);+ events.on(MAP_MOUSE_OUT, mouseOutThrottled);+ events.on(MAP_SINGLE_CLICK, singleClick);++ return () => {+ events.off(MAP_MOVE_END, moveEnd);+ events.off(MAP_MOUSE_MOVE, mouseMoveThrottled);+ events.off(MAP_MOUSE_OUT, mouseOutThrottled);+ events.off(MAP_SINGLE_CLICK, singleClick);+ };+ }, []);++ useEffect(() => {+ if (granuleDate && prevGranuleFootprints !== granuleFootprints) {+ clearGranuleFootprint();+ }+ }, [granuleDate, granuleFootprints]);++ useEffect(() => {+ granuleDateRef.current = granuleDate;+ }, [granuleDate]);++ useEffect(() => {+ granulePlatformRef.current = granulePlatform;+ }, [granulePlatform]);- clearGranuleFootprint() {- this.setState({ granuleDate: null, granulePlatform: null });+ useEffect(() => {+ granuleFootprintsRef.current = granuleFootprints;+ }, [granuleFootprints]);++ useEffect(() => {+ isShowingClickRef.current = isShowingClick;+ }, [isShowingClick]);++ function clearGranuleFootprint() {+ setGranuleDate(null);+ setGranulePlatformState(null);events.trigger(GRANULE_HOVERED, null);}@@ -83,14 +148,7 @@ export class VectorInteractions extends React.Component {* @param {Array} pixels* @param {Array} coord*/- handleGranuleHover = (pixels, mouseCoords) => {- const {- compareState,- granulePlatform,- granuleFootprints,- swipeOffset,- visibleExtent,- } = this.props;+ function handleGranuleHover(pixels, mouseCoords) {const { active: compareActive, activeString } = compareState;let toggledGranuleFootprint;@@ -103,9 +161,9 @@ export class VectorInteractions extends React.Component {// check if coordinates and polygon extent are within and not exceeding max extentObject- .keys(granuleFootprints)+ .keys(granuleFootprintsRef.current).forEach((date) => {- const points = granuleFootprints[date];+ const points = granuleFootprintsRef.current[date];const isValidPolygon = areCoordinatesAndPolygonExtentValid(points,mouseCoords,@@ -113,23 +171,21 @@ export class VectorInteractions extends React.Component {);if (isValidPolygon) {toggledGranuleFootprint = true;- events.trigger(GRANULE_HOVERED, granulePlatform, date);- this.setState({ granulePlatform, granuleDate: date });+ events.trigger(GRANULE_HOVERED, granulePlatformRef.current, date);+ setGranuleDate(date);+ setGranulePlatformState(granulePlatformRef.current);}});if (!toggledGranuleFootprint) {- this.clearGranuleFootprint();+ clearGranuleFootprint();}};- handleCursorChange(pixel, map, lon, lat) {- const {- isShowingClick, changeCursor, measureIsActive, compareState, swipeOffset, proj,- } = this.props;+ function handleCursorChange(pixel, map, lon, lat) {const hasFeatures = map.hasFeatureAtPixel(pixel);- if (hasFeatures && !isShowingClick && !measureIsActive) {+ if (hasFeatures && !isShowingClickRef.current && !measureIsActive) {let isActiveLayer = false;let isReferenceLayer = false;map.forEachFeatureAtPixel(pixel, (feature, layer) => {@@ -156,50 +212,18 @@ export class VectorInteractions extends React.Component {if (isActiveLayer && !isReferenceLayer) {changeCursor(true);}- } else if (!hasFeatures && isShowingClick) {+ } else if (!hasFeatures && isShowingClickRef.current) {changeCursor(false);}}- moveEnd() {- const { granuleDate, granulePlatform } = this.state;- if (granuleDate && granulePlatform) {- events.trigger(GRANULE_HOVER_UPDATE, granulePlatform, granuleDate);- }- }-- mouseOut = () => {- this.mouseMove.cancel();- events.trigger(GRANULE_HOVERED, null);- };-- mouseMove({ pixel }, map, crs) {- const {- isCoordinateSearchActive, measureIsActive, granuleFootprints, isMobile,- } = this.props;- const coord = map.getCoordinateFromPixel(pixel);- const [lon, lat] = transform(coord, crs, CRS.GEOGRAPHIC);-- if (measureIsActive || isCoordinateSearchActive) {- return;+ function moveEnd() {+ if (granuleDateRef.current && granulePlatformRef.current) {+ events.trigger(GRANULE_HOVER_UPDATE, granulePlatformRef.current, granuleDateRef.current);}- if (lon < -250 || lon > 250 || lat < -90 || lat > 90) {- return;- }- if (granuleFootprints && !isMobile) {- this.handleGranuleHover(pixel, coord);- }- this.handleCursorChange(pixel, map, lon, lat);}- singleClick(e, map) {- const {- screenSize, lastSelected, openVectorDialog, onCloseModal, selectVectorFeatures,- modalState, getDialogObject, measureIsActive, activeLayers, isCoordinateSearchActive,- activateVectorZoomAlert, activateVectorExceededResultsAlert, clearVectorExceededResultsAlert,- proj, isEmbedModeActive, isVectorExceededAlertPresent, isMobile,- } = this.props;-+ function singleClick(e, map) {if (measureIsActive || isCoordinateSearchActive) return;const isVectorModalOpen = modalState.id.includes('vector_dialog') && modalState.isOpen;const pixels = e.pixel;@@ -230,7 +254,7 @@ export class VectorInteractions extends React.Component {if (isMobile) {const coord = map.getCoordinateFromPixel(pixels);- this.handleGranuleHover(pixels, coord);+ handleGranuleHover(pixels, coord);}if (metaArray.length) {@@ -265,9 +289,7 @@ export class VectorInteractions extends React.Component {}}- render() {- return null;- }+ return null;}function mapStateToProps(state) {diff --git a/web/js/containers/map-interactions/ol-vector-interactions.test.js b/web/js/containers/map-interactions/ol-vector-interactions.test.jsindex eced20571..7f0d8153d 100644--- a/web/js/containers/map-interactions/ol-vector-interactions.test.js+++ b/web/js/containers/map-interactions/ol-vector-interactions.test.js@@ -90,6 +90,9 @@ beforeEach(() => {isMobile={false}proj={{ id: 'geographic' }}activeLayers={[{ def: { type: 'vector' } }]}+ granulePlatform="MODIS"+ granuleFootprints={{ '2024-01-15': [[[0, 0], [1, 0], [1, 1], [0, 1]]] }}+ compareState={{ active: {}, activeString: 'active' }}/>,);});@@ -176,15 +179,12 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {proj={{ id: 'geographic' }}activeLayers={[]}granuleFootprints={initialFootprints}+ compareState={{ active: {}, activeString: 'active' }}/>,);});- // Simulate having a hovered granule by setting internal state- const instance = granuleComponent.getInstance();- act(() => {- instance.setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });- });+ events.trigger(MAP_MOUSE_MOVE, { pixel: [0, 0] }, map, 'EPSG:4326');// Update granuleFootprints prop to simulate date changeact(() => {@@ -205,13 +205,11 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {proj={{ id: 'geographic' }}activeLayers={[]}granuleFootprints={updatedFootprints}+ compareState={{ active: {}, activeString: 'active' }}/>,);});- // Verify state was cleared- expect(instance.state.granuleDate).toBeNull();- expect(instance.state.granulePlatform).toBeNull();// Verify GRANULE_HOVERED event was triggered with nullexpect(granuleHoveredSpy).toHaveBeenCalledWith(null);});@@ -242,9 +240,6 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {);});- // granuleDate is null (no hover) — should NOT trigger clear- const instance = granuleComponent.getInstance();-act(() => {granuleComponent.update(<VectorInteractions@@ -268,7 +263,6 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {});expect(granuleHoveredSpy).not.toHaveBeenCalled();- expect(instance.state.granuleDate).toBeNull();});test('does NOT clear granule footprint when granuleFootprints prop is the same reference', () => {@@ -296,11 +290,6 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {);});- const instance = granuleComponent.getInstance();- act(() => {- instance.setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });- });-// Re-render with the SAME object referenceact(() => {granuleComponent.update(@@ -326,7 +315,6 @@ describe('componentDidUpdate - clear orphaned granule footprint', () => {// Should NOT clear because same referenceexpect(granuleHoveredSpy).not.toHaveBeenCalled();- expect(instance.state.granuleDate).toBe('2024-01-15');});});@@ -366,8 +354,9 @@ describe('moveEnd', () => {test('triggers GRANULE_HOVER_UPDATE when granuleDate and granulePlatform are set', () => {const spy = jest.fn();events.on(GRANULE_HOVER_UPDATE, spy);+ areCoordinatesAndPolygonExtentValid.mockReturnValue(true);act(() => {- component.getInstance().setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });+ events.trigger(MAP_MOUSE_MOVE, { pixel: [0, 0] }, map, 'EPSG:4326');});events.trigger(MAP_MOVE_END);expect(spy).toHaveBeenCalledWith('MODIS', '2024-01-15');@@ -651,9 +640,6 @@ describe('handleGranuleHover', () => {visibleExtent: [-180, -90, 180, 90],isMobile: false,});- act(() => {- testComp.getInstance().setState({ granuleDate: '2024-01-15', granulePlatform: 'MODIS' });- });spy.mockClear();events.trigger(MAP_MOUSE_MOVE, { pixel: [0, 0] }, map, 'EPSG:4326');expect(spy).toHaveBeenCalledWith(null);diff --git a/web/js/containers/vector-dialog.js b/web/js/containers/vector-dialog.jsindex 3791f0d7a..d857a7114 100644--- a/web/js/containers/vector-dialog.js+++ b/web/js/containers/vector-dialog.js@@ -1,5 +1,4 @@-import React from 'react';-import { connect } from 'react-redux';+import { useState } from 'react';import PropTypes from 'prop-types';import {ModalBody, ModalHeader, Nav, NavItem, NavLink,@@ -7,140 +6,135 @@ import {import Scrollbars from '../components/util/scrollbar';import VectorMetaTable from '../components/vector-metadata/table';-class VectorDialog extends React.Component {- constructor(props) {- super(props);- this.state = { activeIndex: 0 };- this.updateIndex = this.updateIndex.bind(this);- }+function VectorDialog(props) {+ const {+ toggleWithClose,+ vectorMetaObject,+ modalHeight,+ dialogKey,+ } = props;++ const [activeIndex, setActiveIndex] = useState(0);- updateIndex(activeIndex) {- if (activeIndex === this.state.activeIndex) return;- this.setState({ activeIndex });+ function updateIndex(activeIndexIn) {+ if (activeIndexIn === activeIndex) return;+ setActiveIndex(activeIndexIn);}- render() {- const {- toggleWithClose, vectorMetaObject, modalHeight, dialogKey,- } = this.props;- const { activeIndex } = this.state;- const navArray = [];- const keyArray = [];- let i = 0;- for (const [key, value] of Object.entries(vectorMetaObject)) {- const stringLength = 20;- const title = value[0].title || key;- const { subTitle } = value[0];- const titleText = title.length > stringLength ? `${title.substring(0, stringLength)}...` : title;- const combinedTitles = subTitle ? `${title} - ${subTitle}` : title;- const index = i;- keyArray.push(key);- navArray.push(- <NavItem- key={key}- className="vector-meta-nav-item"- active={activeIndex === i}- >- <NavLink onClick={() => this.updateIndex(index)} title={combinedTitles}>- {`${titleText} [${value.length}]`}- </NavLink>- </NavItem>,- );- i += 1;- }- const activeMetaArray = vectorMetaObject[keyArray[activeIndex]];- const closeBtn = (- <button onClick={toggleWithClose} type="button" className="vector-close-btn">- ×- </button>+ const navArray = [];+ const keyArray = [];+ let i = 0;++ for (const [key, value] of Object.entries(vectorMetaObject)) {+ const stringLength = 20;+ const title = value[0].title || key;+ const { subTitle } = value[0];+ const titleText = title.length > stringLength ? `${title.substring(0, stringLength)}...` : title;+ const combinedTitles = subTitle ? `${title} - ${subTitle}` : title;+ const index = i;+ keyArray.push(key);+ navArray.push(+ <NavItem+ key={key}+ className="vector-meta-nav-item"+ active={activeIndex === i}+ >+ <NavLink onClick={() => updateIndex(index)} title={combinedTitles}>+ {`${titleText} [${value.length}]`}+ </NavLink>+ </NavItem>,);- return (- <div className="draggable-modal-content">- {activeMetaArray[0].id.includes('AERONET')- ? (- <div style={{ padding: '10px', position: 'relative' }}>- <span style={{ position: 'absolute', right: '0px', top: '3px' }}>{closeBtn}</span>- <div style={{ marginBottom: '5px', fontSize: '16px', color: '#2222aa' }}>- <a- style={{ color: '#2222aa' }}- href={- `https://aeronet.gsfc.nasa.gov/new_web/photo_db_v3/${activeMetaArray[0].features.name}.html`- }- rel="noreferrer"- target="_blank"- >- {activeMetaArray[0].features.name}- </a>- </div>- <div style={{ marginBottom: '15px', color: '#666666' }}>- {` (${activeMetaArray[0].features.coordinates[0]}, ${activeMetaArray[0].features.coordinates[1]})`}- </div>+ i += 1;+ }++ const activeMetaArray = vectorMetaObject[keyArray[activeIndex]];+ const closeBtn = (+ <button onClick={toggleWithClose} type="button" className="vector-close-btn">+ ×+ </button>+ );++ return (+ <div className="draggable-modal-content">+ {activeMetaArray[0].id.includes('AERONET')+ ? (+ <div style={{ padding: '10px', position: 'relative' }}>+ <span style={{ position: 'absolute', right: '0px', top: '3px' }}>{closeBtn}</span>+ <div style={{ marginBottom: '5px', fontSize: '16px', color: '#2222aa' }}>+ <a+ style={{ color: '#2222aa' }}+ href={+ `https://aeronet.gsfc.nasa.gov/new_web/photo_db_v3/${activeMetaArray[0].features.name}.html`+ }+ rel="noreferrer"+ target="_blank"+ >+ {activeMetaArray[0].features.name}+ </a>+ </div>+ <div style={{ marginBottom: '15px', color: '#666666' }}>+ {` (${activeMetaArray[0].features.coordinates[0]}, ${activeMetaArray[0].features.coordinates[1]})`}+ </div>+ <div style={{ marginBottom: '5px' }}>+ {`Site is ${activeMetaArray[0].features.active ? 'online' : 'currently offline'}`}+ </div>+ {activeMetaArray[0].features.active && (<div style={{ marginBottom: '5px' }}>- {`Site is ${activeMetaArray[0].features.active ? 'online' : 'currently offline'}`}+ <b>+ {`Most recent reading: ${activeMetaArray[0].features.value}`}+ </b></div>- {activeMetaArray[0].features.active && (- <div style={{ marginBottom: '5px' }}>- <b>- {`Most recent reading: ${activeMetaArray[0].features.value}`}- </b>- </div>- )}- {activeMetaArray[0].features.active && (- <div style={{ marginBottom: '15px' }}>- {`As of ${activeMetaArray[0].features.date.toUTCString().split(' ')- .slice(1)- .join(' ')- .replace('GMT', 'UTC')}`}- </div>- )}- <div>- <a- style={{ color: '#2222aa' }}- href={- `https://aeronet.gsfc.nasa.gov/cgi-bin/data_display_aod_v3?site=${activeMetaArray[0].features.name}&nachal=0&year=${activeMetaArray[0].features.date.getUTCFullYear()}&month=${activeMetaArray[0].features.date.getUTCMonth() + 1}&day=${activeMetaArray[0].features.date.getUTCDate()}&aero_water=0&level=1&if_day=0&if_err=0&place_code=10&year_or_month=0`- }- rel="noreferrer"- target="_blank"- >- View More Data- </a>+ )}+ {activeMetaArray[0].features.active && (+ <div style={{ marginBottom: '15px' }}>+ {`As of ${activeMetaArray[0].features.date.toUTCString().split(' ')+ .slice(1)+ .join(' ')+ .replace('GMT', 'UTC')}`}</div>- </div>- )- : (+ )}<div>- <ModalHeader toggle={toggleWithClose} close={closeBtn}>- <Nav tabs id="vector-meta-nav" className="vector-meta-nav">- {navArray}- </Nav>- </ModalHeader>-- <ModalBody>- <Scrollbars style={{ maxHeight: `${modalHeight - 70}px` }}>- <VectorMetaTable- id={dialogKey}- metaArray={activeMetaArray}- title={keyArray[activeIndex]}- />- </Scrollbars>- </ModalBody>+ <a+ style={{ color: '#2222aa' }}+ href={+ `https://aeronet.gsfc.nasa.gov/cgi-bin/data_display_aod_v3?site=${activeMetaArray[0].features.name}&nachal=0&year=${activeMetaArray[0].features.date.getUTCFullYear()}&month=${activeMetaArray[0].features.date.getUTCMonth() + 1}&day=${activeMetaArray[0].features.date.getUTCDate()}&aero_water=0&level=1&if_day=0&if_err=0&place_code=10&year_or_month=0`+ }+ rel="noreferrer"+ target="_blank"+ >+ View More Data+ </a></div>- )}- </div>- );- }-}+ </div>+ )+ : (+ <div>+ <ModalHeader toggle={toggleWithClose} close={closeBtn}>+ <Nav tabs id="vector-meta-nav" className="vector-meta-nav">+ {navArray}+ </Nav>+ </ModalHeader>-function mapStateToProps(state) {- return {};+ <ModalBody>+ <Scrollbars style={{ maxHeight: `${modalHeight - 70}px` }}>+ <VectorMetaTable+ id={dialogKey}+ metaArray={activeMetaArray}+ title={keyArray[activeIndex]}+ />+ </Scrollbars>+ </ModalBody>+ </div>+ )}+ </div>+ );}-export default connect(- mapStateToProps,- null,-)(VectorDialog);+VectorDialog.propTypes = {dialogKey: PropTypes.number,modalHeight: PropTypes.number,toggleWithClose: PropTypes.func,vectorMetaObject: PropTypes.oneOfType([PropTypes.object, PropTypes.oneOf(['null'])]),};++export default VectorDialog;diff --git a/web/js/containers/vector-dialog.test.js b/web/js/containers/vector-dialog.test.jsindex c4d147204..6784c463b 100644--- a/web/js/containers/vector-dialog.test.js+++ b/web/js/containers/vector-dialog.test.js@@ -3,10 +3,8 @@import { render, fireEvent } from '@testing-library/react';import '@testing-library/jest-dom';-let capturedMapState;jest.mock('react-redux', () => ({connect: (mapState, mapDispatch) => {- capturedMapState = mapState;return (Component) => Component;},}));@@ -144,9 +142,3 @@ describe('VectorDialog (AERONET)', () => {expect(toggleWithClose).toHaveBeenCalled();});});--describe('mapStateToProps', () => {- it('returns an empty object', () => {- expect(capturedMapState({ anything: true })).toEqual({});- });-});