Skip to content

Commit

Permalink
Upgrade to react-leaflet 5
Browse files Browse the repository at this point in the history
  • Loading branch information
K-Markopoulos committed Jan 7, 2025
1 parent 1ca5134 commit e1df9c1
Show file tree
Hide file tree
Showing 14 changed files with 110 additions and 117 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@
"prettier": "2.5.1",
"typescript": "^4.9.5"
},
"resolutions": {
"react-leaflet": "^5.0.0-rc.1",
"@react-leaflet/core": "^3.0.0-rc.1"
},
"engines": {
"node": "18",
"yarn": "^1.22"
Expand Down
8 changes: 4 additions & 4 deletions packages/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@
"firebase-tools": "^13.28.0",
"geolib": "^3.3.4",
"immutable": "^4.0.0-rc.12",
"leaflet": "^1.7.1",
"leaflet.locatecontrol": "^0.79.0",
"leaflet": "^1.9.4",
"leaflet.locatecontrol": "^0.83.0",
"lodash": "^4.17.15",
"luxon": "^3.3.0",
"mutationobserver-shim": "^0.3.7",
Expand All @@ -55,8 +55,8 @@
"react-ga4": "^2.1.0",
"react-hook-form": "^7.41.5",
"react-jwt": "^1.1.8",
"react-leaflet": "^2.7.0",
"react-leaflet-markercluster": "^2.0.0",
"react-leaflet": "5.0.0-rc.1",
"react-leaflet-markercluster": "^4.2.1",
"react-material-ui-carousel": "3.4.2",
"react-redux": "^7.2.0",
"react-router-dom": "^6.0.0",
Expand Down
37 changes: 14 additions & 23 deletions packages/website/src/common/SiteDetails/Map/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
/* eslint-disable no-underscore-dangle */
import React from 'react';
import { Provider } from 'react-redux';
import { render } from '@testing-library/react';
import configureStore from 'redux-mock-store';

import { mockUser } from 'mocks/mockUser';
import { Provider } from 'react-redux';
import { render } from '@testing-library/react';
import Map from '.';

jest.mock('react-leaflet');

const mockStore = configureStore([]);

describe('Site Map', () => {
let element: HTMLElement;
beforeEach(() => {
const store = mockStore({
user: {
userInfo: mockUser,
},
selectedSite: {
draft: null,
},
});

store.dispatch = jest.fn();
const store = mockStore({
user: {
userInfo: mockUser,
},
selectedSite: {
draft: null,
},
});

element = render(
it('should render with given state from Redux store', () => {
const { container } = render(
<Provider store={store}>
<Map
polygon={{
Expand All @@ -36,10 +30,7 @@ describe('Site Map', () => {
surveyPoints={[]}
/>
</Provider>,
).container;
});

it('should render with given state from Redux store', () => {
expect(element).toMatchSnapshot();
);
expect(container).toMatchSnapshot();
});
});
47 changes: 26 additions & 21 deletions packages/website/src/common/SiteDetails/Map/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useRef, useEffect, useCallback, useState } from 'react';
import { Map, TileLayer, Polygon, Marker } from 'react-leaflet';
import { TileLayer, Polygon, Marker, MapContainer } from 'react-leaflet';
import { useDispatch, useSelector } from 'react-redux';
import L, { LatLngTuple } from 'leaflet';
import L, { LatLngTuple, Map, Marker as LeafletMarker } from 'leaflet';
import { WithStyles } from '@mui/styles';
import withStyles from '@mui/styles/withStyles';
import createStyles from '@mui/styles/createStyles';
Expand All @@ -17,7 +17,7 @@ import {
} from 'store/Sites/types';
import { siteDraftSelector, setSiteDraft } from 'store/Sites/selectedSiteSlice';
import { userInfoSelector } from 'store/User/userSlice';
import { samePosition } from 'helpers/map';
import { getMiddlePoint, samePosition, toLatLng } from 'helpers/map';
import { isManager } from 'helpers/user';
import SurveyPointPopup from './SurveyPointPopup';

Expand Down Expand Up @@ -62,8 +62,8 @@ const SiteMap = ({
}: SiteMapProps) => {
const dispatch = useDispatch();
const mapRef = useRef<Map>(null);
const markerRef = useRef<Marker>(null);
const editPointMarkerRer = useRef<Marker>(null);
const markerRef = useRef<LeafletMarker>(null);
const editPointMarkerRer = useRef<LeafletMarker>(null);
const draftSite = useSelector(siteDraftSelector);
const user = useSelector(userInfoSelector);
const [focusedPoint, setFocusedPoint] = useState<SurveyPoints>();
Expand Down Expand Up @@ -110,19 +110,17 @@ const SiteMap = ({
);

useEffect(() => {
if (
mapRef?.current?.leafletElement &&
focusedPoint?.polygon?.type === 'Point'
) {
if (mapRef?.current && focusedPoint?.polygon?.type === 'Point') {
const [lng, lat] = focusedPoint.polygon.coordinates;
setCenter(mapRef.current.leafletElement, [lat, lng], 15);
setCenter(mapRef.current, [lat, lng], 15);
}
}, [focusedPoint]);

useEffect(() => {
const { current } = mapRef;
if (current?.leafletElement) {
const map = current.leafletElement;
if (current) {
const map = current;
console.log({ map });

Check warning on line 123 in packages/website/src/common/SiteDetails/Map/index.tsx

View workflow job for this annotation

GitHub Actions / website_test_build_and_deploy

Unexpected console statement
// Initialize map's position to fit the given polygon
if (polygon.type === 'Polygon') {
map.fitBounds(L.polygon(polygon.coordinates).getBounds());
Expand All @@ -143,8 +141,8 @@ const SiteMap = ({

const handleDragChange = () => {
const { current } = markerRef;
if (current?.leafletElement) {
const mapMarker = current.leafletElement;
if (current) {
const mapMarker = current;
const { lat, lng } = mapMarker.getLatLng().wrap();
dispatch(
setSiteDraft({
Expand All @@ -159,16 +157,17 @@ const SiteMap = ({

const handleEditPointDragChange = () => {
const { current } = editPointMarkerRer;
if (current && current.leafletElement && onEditPointCoordinatesChange) {
const mapMarker = current.leafletElement;
if (current && current && onEditPointCoordinatesChange) {
const mapMarker = current;
const { lat, lng } = mapMarker.getLatLng().wrap();
onEditPointCoordinatesChange(lat.toString(), lng.toString());
}
};

return (
<Map
<MapContainer
ref={mapRef}
center={toLatLng(getMiddlePoint(polygon))}
minZoom={1}
maxZoom={17}
zoom={13}
Expand All @@ -189,7 +188,6 @@ const SiteMap = ({
<Marker
ref={editPointMarkerRer}
draggable={surveyPointEditModeEnabled}
ondragend={handleEditPointDragChange}
icon={surveyPointIcon(true)}
zIndexOffset={100}
position={[
Expand All @@ -202,17 +200,22 @@ const SiteMap = ({
selectedSurveyPoint.polygon.coordinates[0]) ||
polygon.coordinates[0],
]}
eventHandlers={{
dragend: handleEditPointDragChange,
}}
/>
)}
<Marker
ref={markerRef}
draggable={Boolean(draftSite)}
ondragend={handleDragChange}
icon={pinIcon}
position={[
draftSite?.coordinates?.latitude || polygon.coordinates[1],
draftSite?.coordinates?.longitude || polygon.coordinates[0],
]}
eventHandlers={{
dragend: handleDragChange,
}}
/>
{surveyPoints.map(
(point) =>
Expand All @@ -226,7 +229,9 @@ const SiteMap = ({
point.polygon.coordinates[1],
point.polygon.coordinates[0],
]}
onclick={() => setFocusedPoint(point)}
eventHandlers={{
click: () => setFocusedPoint(point),
}}
>
<SurveyPointPopup siteId={siteId} point={point} />
</Marker>
Expand All @@ -240,7 +245,7 @@ const SiteMap = ({
position={[spotterPosition.latitude, spotterPosition.longitude]}
/>
)}
</Map>
</MapContainer>
);
};

Expand Down
4 changes: 4 additions & 0 deletions packages/website/src/helpers/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export const getMiddlePoint = (point: Point | Polygon): Position => {
return [lngMean, latMean];
};

export const toLatLng = (point: Position): LatLng => {
return new LatLng(point[1], point[0]);
};

export const samePosition = (
polygon1: Polygon | Point,
polygon2: Polygon | Point,
Expand Down
14 changes: 8 additions & 6 deletions packages/website/src/routes/HomeMap/Map/Markers/SiteMarker.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Marker, useLeaflet } from 'react-leaflet';
import { Marker, useMap } from 'react-leaflet';
import { useDispatch, useSelector } from 'react-redux';
import React from 'react';
import { Site } from 'store/Sites/types';
Expand Down Expand Up @@ -29,7 +29,7 @@ interface SiteMarkerProps {
*/
export default function SiteMarker({ site, setCenter }: SiteMarkerProps) {
const siteOnMap = useSelector(siteOnMapSelector);
const { map } = useLeaflet();
const map = useMap();
const dispatch = useDispatch();
const { tempWeeklyAlert } = site.collectionData || {};
const markerIcon = useMarkerIcon(
Expand All @@ -48,10 +48,12 @@ export default function SiteMarker({ site, setCenter }: SiteMarkerProps) {
{LNG_OFFSETS.map((offset) => {
return (
<Marker
onClick={() => {
if (map) setCenter(map, [lat, lng], 6);
dispatch(setSearchResult());
dispatch(setSiteOnMap(site));
eventHandlers={{
click: () => {
if (map) setCenter(map, [lat, lng], 6);
dispatch(setSearchResult());
dispatch(setSiteOnMap(site));
},
}}
key={`${site.id}-${offset}`}
icon={markerIcon}
Expand Down
5 changes: 2 additions & 3 deletions packages/website/src/routes/HomeMap/Map/Markers/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { useSelector } from 'react-redux';
import { LayerGroup, useLeaflet } from 'react-leaflet';
import { LayerGroup, useMap } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import L from 'leaflet';
import { sitesToDisplayListSelector } from 'store/Sites/sitesListSlice';
import { Site } from 'store/Sites/types';
import { siteOnMapSelector } from 'store/Homepage/homepageSlice';
import 'leaflet/dist/leaflet.css';
import 'react-leaflet-markercluster/dist/styles.min.css';
import { CollectionDetails } from 'store/Collection/types';
import {
findIntervalByLevel,
Expand Down Expand Up @@ -39,7 +38,7 @@ export const SiteMarkers = ({ collection }: SiteMarkersProps) => {
[collection?.sites, storedSites],
);
const siteOnMap = useSelector(siteOnMapSelector);
const { map } = useLeaflet();
const map = useMap();
const [visibleSites, setVisibleSites] = useState(sitesList);

const setCenter = useCallback(
Expand Down
13 changes: 1 addition & 12 deletions packages/website/src/routes/HomeMap/Map/Popup/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,8 @@ import { mockSite } from 'mocks/mockSite';
import { renderWithProviders } from 'utils/test-utils';
import Popup from '.';

jest.mock('react-leaflet', () => ({
__esModule: true,
useLeaflet: () => {
return {
map: jest.requireActual('react').createElement('mock-LeafletPopup', {}),
};
},
Popup: (props: any) =>
jest.requireActual('react').createElement('mock-LeafletPopup', props),
}));

const mockStore = configureStore([]);
describe('Popup', () => {
const mockStore = configureStore([]);
let element: HTMLElement;
beforeEach(() => {
const store = mockStore({
Expand Down
11 changes: 5 additions & 6 deletions packages/website/src/routes/HomeMap/Map/Popup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import { WithStyles } from '@mui/styles';
import createStyles from '@mui/styles/createStyles';
import withStyles from '@mui/styles/withStyles';
import { Link } from 'react-router-dom';
import { Popup as LeafletPopup, useLeaflet } from 'react-leaflet';
import { Popup as LeafletPopup, useMap } from 'react-leaflet';
import { useSelector } from 'react-redux';

import type { LatLngTuple } from 'leaflet';
import type { LatLngTuple, Popup as LeafletPopupType } from 'leaflet';
import type { Site } from 'store/Sites/types';
import { getSiteNameAndRegion } from 'store/Sites/helpers';
import { siteOnMapSelector } from 'store/Homepage/homepageSlice';
Expand All @@ -27,9 +27,9 @@ import { colors } from 'layout/App/theme';
import { GaCategory, GaAction, trackButtonClick } from 'utils/google-analytics';

const Popup = ({ site, classes, autoOpen = true }: PopupProps) => {
const { map } = useLeaflet();
const map = useMap();
const siteOnMap = useSelector(siteOnMapSelector);
const popupRef = useRef<LeafletPopup>(null);
const popupRef = useRef<LeafletPopupType>(null);
const { name, region } = getSiteNameAndRegion(site);
const isNameLong = name?.length && name.length > maxLengths.SITE_NAME_POPUP;

Expand All @@ -51,11 +51,10 @@ const Popup = ({ site, classes, autoOpen = true }: PopupProps) => {
siteOnMap?.polygon.type === 'Point' &&
autoOpen
) {
const { leafletElement: popup } = popupRef.current;
const [lng, lat] = siteOnMap.polygon.coordinates;

const point: LatLngTuple = [lat, lng];
popup.setLatLng(point).openOn(map);
popupRef.current.setLatLng(point).openOn(map);
}
}, [autoOpen, map, site.id, siteOnMap]);

Expand Down
Loading

0 comments on commit e1df9c1

Please sign in to comment.