Interactive interface for browsing global, full-resolution satellite imagery
WV-4046 Modernize Coordinates Components (#6830)
vicgonzalez25ae8cf1b8198a
diff --git a/web/js/components/map/coordinates.js b/web/js/components/map/coordinates.jsindex 6941ce960..3a2176464 100644--- a/web/js/components/map/coordinates.js+++ b/web/js/components/map/coordinates.js@@ -1,4 +1,3 @@-import React from 'react';import PropTypes from 'prop-types';import util from '../../util/util';@@ -9,55 +8,41 @@ const formatOrder = {'latlon-dms': 'latlon-dd',};-export default class Coordinates extends React.Component {- constructor(props) {- super(props);- this.changeFormat = this.changeFormat.bind(this);- }-- changeFormat() {- const { format, onFormatChange } = this.props;+export default function Coordinates({ latitude, longitude, format, crs, onFormatChange }) {+ const changeFormat = () => {const nextFormat = formatOrder[format];onFormatChange(nextFormat);- }+ };- render() {- const {- latitude, longitude, format, crs,- } = this.props;- if (latitude === null) {- return null;- }- if (longitude === null) {- return null;- }+ if (latitude === null || longitude === null) {+ return null;+ }- const coords = util.formatCoordinate(- [longitude, latitude],- format,- );+ const coords = util.formatCoordinate(+ [longitude, latitude],+ format,+ );- return (- <button- type="button"- id="coords-panel"- className="wv-coords-map wv-coords-map-btn"- onClick={this.changeFormat}- >+ return (+ <button+ type="button"+ id="coords-panel"+ className="wv-coords-map wv-coords-map-btn"+ onClick={changeFormat}+ >+ <span className="map-coord">+ {coords}+ </span>+ <div className="map-coord-format"><span className="map-coord">- {coords}+ {crs}</span>- <div className="map-coord-format">- <span className="map-coord">- {crs}- </span>- <div aria-label="Change coordinates format" className="coord-btn">- <i className="coord-switch" />- </div>+ <div aria-label="Change coordinates format" className="coord-btn">+ <i className="coord-switch" /></div>- </button>- );- }+ </div>+ </button>+ );}Coordinates.propTypes = {diff --git a/web/js/components/map/ol-coordinates.js b/web/js/components/map/ol-coordinates.jsindex 9a4d706ce..50465db64 100644--- a/web/js/components/map/ol-coordinates.js+++ b/web/js/components/map/ol-coordinates.js@@ -1,5 +1,5 @@-import React from 'react';-import { connect } from 'react-redux';+import { useState, useEffect, useRef } from 'react';+import { useSelector, useDispatch } from 'react-redux';import PropTypes from 'prop-types';import {throttle as lodashThrottle,@@ -12,6 +12,7 @@ import { getNormalizedCoordinate } from '../location-search/util';import { changeCoordinateFormat as changeCoordinateFormatAction } from '../../modules/settings/actions';import { MAP_MOUSE_MOVE, MAP_MOUSE_OUT } from '../../util/constants';import { CRS } from '../../modules/map/constants';+import usePrevious from '../../util/customHooks';const { events } = util;const getContainerWidth = (format) => {@@ -23,168 +24,134 @@ const getContainerWidth = (format) => {return formatWidth[format];};-class OlCoordinates extends React.Component {- constructor(props) {- super(props);- this.state = {- hasMouse: false,- latitude: null,- longitude: null,- crs: null,- format: null,- width: 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.changeFormat = this.changeFormat.bind(this);- this.setInitFormat = this.setInitFormat.bind(this);- }+function OlCoordinates({ show }) {+ const coordinateFormat = useSelector((state) => state.settings.coordinateFormat);+ const isMobile = useSelector((state) => state.screenSize.isMobileDevice);+ const dispatch = useDispatch();- componentDidMount() {- events.on(MAP_MOUSE_MOVE, this.mouseMove);- events.on(MAP_MOUSE_OUT, this.mouseOut);- this.setInitFormat();- }+ const [hasMouse, setHasMouse] = useState(false);+ const [latitude, setLatitude] = useState(null);+ const [longitude, setLongitude] = useState(null);+ const [crs, setCrs] = useState(null);+ const [format, setFormat] = useState(null);+ const [width, setWidth] = useState(null);- // listening to state changes from the settings menu- componentDidUpdate(prevProps) {- const { coordinateFormat } = this.props;- if (prevProps.coordinateFormat !== coordinateFormat) {- this.changeFormat(coordinateFormat);- }- }+ const prevCoordinateFormat = usePrevious(coordinateFormat);- componentWillUnmount() {- events.off(MAP_MOUSE_MOVE, this.mouseMove);- events.off(MAP_MOUSE_OUT, this.mouseOut);- }+ const clearCoord = () => {+ setLatitude(null);+ setLongitude(null);+ };- mouseMove({ pixel }, map, crs) {- const coord = map.getCoordinateFromPixel(pixel);- if (!coord) {- this.clearCoord();- return;- }- let pcoord = transform(coord, crs, CRS.GEOGRAPHIC);+ const changeFormat = (newFormat) => {+ dispatch(changeCoordinateFormatAction(newFormat));+ util.setCoordinateFormat(newFormat);+ setFormat(newFormat);+ setWidth(getContainerWidth(newFormat));+ };- const [lon, lat] = pcoord;- if (Math.abs(lat) > 90) {- this.clearCoord();- return;- }- if (Math.abs(lon) > 180) {- if (crs === CRS.GEOGRAPHIC && Math.abs(lon) < 250) {- pcoord = getNormalizedCoordinate([lon, lat]);- } else {- this.clearCoord();+ const mouseMoveRef = useRef();+ const mouseOutRef = useRef();++ if (!mouseMoveRef.current) {+ const options = { leading: true, trailing: true };+ mouseMoveRef.current = lodashThrottle(({ pixel }, map, eventCrs) => {+ const coord = map.getCoordinateFromPixel(pixel);+ if (!coord) {+ clearCoord();return;}- }- this.setState({- hasMouse: true,- latitude: pcoord[1],- longitude: pcoord[0],- crs,- });- }+ let pcoord = transform(coord, eventCrs, CRS.GEOGRAPHIC);- mouseOut(event) {- if (event.relatedTarget && event.relatedTarget.classList) {- const cl = event.relatedTarget.classList;- // Ignore when the mouse goes over the coordinate display. Clearing- // the coordinates in this situation causes a flicker.- if (cl.contains('wv-coords-map')) {+ const [lon, lat] = pcoord;+ if (Math.abs(lat) > 90) {+ clearCoord();return;}- }- this.clearCoord();+ if (Math.abs(lon) > 180) {+ if (eventCrs === CRS.GEOGRAPHIC && Math.abs(lon) < 250) {+ pcoord = getNormalizedCoordinate([lon, lat]);+ } else {+ clearCoord();+ return;+ }+ }+ setHasMouse(true);+ setLatitude(pcoord[1]);+ setLongitude(pcoord[0]);+ setCrs(eventCrs);+ }, 200, options);++ mouseOutRef.current = lodashThrottle((event) => {+ if (event.relatedTarget && event.relatedTarget.classList) {+ const cl = event.relatedTarget.classList;+ if (cl.contains('wv-coords-map')) {+ return;+ }+ }+ clearCoord();+ }, 200, options);}- clearCoord() {- this.setState({ latitude: null, longitude: null });- }+ // Subscribe to map events+ useEffect(() => {+ const mouseMove = mouseMoveRef.current;+ const mouseOut = mouseOutRef.current;+ events.on(MAP_MOUSE_MOVE, mouseMove);+ events.on(MAP_MOUSE_OUT, mouseOut);++ // Initialize format+ const initFormat = util.getCoordinateFormat();+ setFormat(initFormat);+ setWidth(getContainerWidth(initFormat));++ return () => {+ events.off(MAP_MOUSE_MOVE, mouseMove);+ events.off(MAP_MOUSE_OUT, mouseOut);+ mouseMove.cancel();+ mouseOut.cancel();+ };+ }, []);- setInitFormat() {- const format = util.getCoordinateFormat();- const width = getContainerWidth(format);- this.setState({- format,- width,- });- }+ // Sync format when coordinateFormat prop changes from settings+ useEffect(() => {+ if (prevCoordinateFormat !== undefined && prevCoordinateFormat !== coordinateFormat) {+ changeFormat(coordinateFormat);+ }+ }, [coordinateFormat]);- changeFormat = (format) => {- const { changeCoordinateFormat } = this.props;- changeCoordinateFormat(format);- util.setCoordinateFormat(format);- const width = getContainerWidth(format);- this.setState({- format,+ const coordContainerStyle = isMobile+ ? {+ display: 'none',+ }+ : {width,- });- };-- render() {- const {- hasMouse, format, latitude, longitude, crs, width,- } = this.state;- const { show, isMobile } = this.props;- const coordContainerStyle = isMobile- ? {- display: 'none',- }- : {- width,- };-- return (- <div id="ol-coords-case" className="wv-coords-container" style={coordContainerStyle}>- {hasMouse && show && (- <>- <Coordinates- format={format}- latitude={latitude}- longitude={longitude}- crs={crs}- onFormatChange={this.changeFormat}- />- {latitude && latitude && (- <UncontrolledTooltip id="center-align-tooltip" placement="bottom" target="ol-coords-case">- Change coordinates format- </UncontrolledTooltip>- )}- </>- )}- </div>- );- }-}+ };-function mapStateToProps (state) {- const { settings, screenSize } = state;- const { coordinateFormat } = settings;- const isMobile = screenSize.isMobileDevice;- return {- coordinateFormat,- isMobile,- };+ return (+ <div id="ol-coords-case" className="wv-coords-container" style={coordContainerStyle}>+ {hasMouse && show && (+ <>+ <Coordinates+ format={format}+ latitude={latitude}+ longitude={longitude}+ crs={crs}+ onFormatChange={changeFormat}+ />+ {latitude && latitude && (+ <UncontrolledTooltip id="center-align-tooltip" placement="bottom" target="ol-coords-case">+ Change coordinates format+ </UncontrolledTooltip>+ )}+ </>+ )}+ </div>+ );}-const mapDispatchToProps = (dispatch) => ({- changeCoordinateFormat: (value) => {- dispatch(changeCoordinateFormatAction(value));- },-});-OlCoordinates.propTypes = {show: PropTypes.bool,- changeCoordinateFormat: PropTypes.func,- coordinateFormat: PropTypes.string,- isMobile: PropTypes.bool,};-export default connect(- mapStateToProps,- mapDispatchToProps,-)(OlCoordinates);+export default OlCoordinates;diff --git a/web/js/components/map/ol-coordinates.test.js b/web/js/components/map/ol-coordinates.test.jsindex 29b76b1ac..1258be886 100644--- a/web/js/components/map/ol-coordinates.test.js+++ b/web/js/components/map/ol-coordinates.test.js@@ -5,7 +5,14 @@ import OlCoordinates from './ol-coordinates';import { registerProjections } from '../../fixtures';import { MAP_MOUSE_MOVE, MAP_MOUSE_OUT } from '../../util/constants';-jest.mock('react-redux', () => ({ connect: () => (OlCoordinatesMock) => OlCoordinatesMock }));+const mockDispatch = jest.fn();+jest.mock('react-redux', () => ({+ useSelector: jest.fn((selector) => selector({+ settings: { coordinateFormat: 'latlon-dd' },+ screenSize: { isMobileDevice: false },+ })),+ useDispatch: () => mockDispatch,+}));const { events } = util;let container;@@ -34,6 +41,7 @@ afterEach(() => {});container.remove();container = null;+ mockDispatch.mockClear();});test('shows coordinates of (10, 20) when moving the mouse', () => {@@ -118,16 +126,28 @@ test('does not clear coordinates when mouseOut target has wv-coords-map class',});test('hides coordinates container on mobile (display none)', () => {+ const { useSelector } = require('react-redux');+ useSelector.mockImplementation((selector) => selector({+ settings: { coordinateFormat: 'latlon-dd' },+ screenSize: { isMobileDevice: true },+ }));+const mobileContainer = document.createElement('div');document.body.appendChild(mobileContainer);const mobileRoot = createRoot(mobileContainer);act(() => {- mobileRoot.render(<OlCoordinates show isMobile />);+ mobileRoot.render(<OlCoordinates show />);});const coordsCase = mobileContainer.querySelector('#ol-coords-case');expect(coordsCase.style.display).toBe('none');act(() => { mobileRoot.unmount(); });mobileContainer.remove();++ // Reset mock+ useSelector.mockImplementation((selector) => selector({+ settings: { coordinateFormat: 'latlon-dd' },+ screenSize: { isMobileDevice: false },+ }));});test('renders coordinates container element', () => {