deps: react-leaflet 1.8 -> 4.2 (+ leaflet 1.9) — the last legacy react-* lib

Ground-up hooks rewrite of the app's core map. Removes the final batch of
React-19-blocking warnings (legacy context on Map/LayersControl/TileLayer/
Marker/CircleMarker/Circle/Tooltip + ReactDOM.render from the old controls).

Core: <Map> -> <MapContainer>; .leafletElement refs (6 files) -> the map/
layer instances directly, via a <MapReady> child (useMap) + plain refs on
Marker/Circle/GeoJSON; controlled viewport (onViewportChanged + state.center/
zoom) -> <MapEvents> (useMapEvents moveend/zoomend) + imperative setView;
onClick -> eventHandlers={{click}}; Path styling -> pathOptions/style;
subsUnion takes the L.Map directly.

The 4 v1-only plugins reimplemented (new in-repo helpers under Maps/):
- react-leaflet-control -> MapControl (L.Control + createPortal)
- react-leaflet-google  -> GoogleMutantLayer (createLayerComponent +
  leaflet.gridlayer.googlemutant; Google Maps API already loaded by Gkeys)
- react-leaflet-fullscreen -> createControlComponent + leaflet.fullscreen
- leaflet-sleep / leaflet-graphicscale kept as vanilla (work on leaflet 1.9)

Browser-verified: /fires (tiles, OSM+Google layer switch, custom control,
fullscreen, graphic scale, pan/zoom -> re-fetch, no NaN), fire detail
(GeoJSON rect + fitBounds), home (3 maps coexist; SelectionMap draggable
marker -> updatePosition + distance circle). Console now shows 0 React
warnings on home/fires. REST smoke byte-identical.
This commit is contained in:
vjrj 2026-07-21 18:45:15 +02:00
parent e61a3a9bcb
commit bc778bfd97
18 changed files with 276 additions and 220 deletions

View file

@ -5,7 +5,7 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withTranslation } from 'react-i18next';
import { GoogleLayer } from 'react-leaflet-google/lib/';
import GoogleMutantLayer from '/imports/ui/components/Maps/GoogleMutantLayer';
import Gkeys from '/imports/startup/client/Gkeys';
import { TileLayer, LayersControl } from 'react-leaflet';
@ -54,15 +54,15 @@ class DefMapLayers extends Component {
{/* React.Fragment does not work here */}
{ this.state.gkey &&
<BaseLayer name={t('Mapa de carreteras de Google')}>
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="ROADMAP" />
<GoogleMutantLayer opacity={defOpacity} maptype="ROADMAP" />
</BaseLayer> }
{ this.state.gkey &&
<BaseLayer name={t('Mapa de terreno de Google')} checked={this.props.terrain}>
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="TERRAIN" />
<GoogleMutantLayer opacity={defOpacity} maptype="TERRAIN" />
</BaseLayer> }
{ this.state.gkey &&
<BaseLayer name={t('Mapa de satélite de Google')} checked={this.props.satellite}>
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="SATELLITE" />
<GoogleMutantLayer opacity={defOpacity} maptype="SATELLITE" />
</BaseLayer> }
</LayersControl>
);

View file

@ -31,7 +31,7 @@ class FireCircleMark extends Component {
} = this.props;
const rect = rectangleAround({ lat, lon }, track, track);
return (
<GeoJSON data={rect} color="red" stroke width="1" opacity=".4" fillOpacity="1">
<GeoJSON data={rect} style={{ color: 'red', stroke: true, weight: 1, opacity: 0.4, fillOpacity: 1 }}>
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
</GeoJSON>
);

View file

@ -33,9 +33,9 @@ class FireIconMark extends Component {
lat, lon, scan, track, nasa, id, history, falsePositives, industries, neighbour, when, t
} = this.props;
return (
<div>
<Fragment>
{ !falsePositives && !industries &&
<Marker position={[lat, lon]} icon={nasa ? this.getIcon(scan) : nFireIcon} onClick={this.onClick} >
<Marker position={[lat, lon]} icon={nasa ? this.getIcon(scan) : nFireIcon} eventHandlers={{ click: this.onClick }} >
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
</Marker> }
{ industries && <Marker position={[lat, lon]} icon={regIndustryIcon}>
@ -43,23 +43,20 @@ class FireIconMark extends Component {
</Marker> }
{ /* disabled */ industries && false && <CircleMarker
center={[lat, lon]}
color="violet"
stroke={false}
fillOpacity="1"
fill
radius={1}
pathOptions={{ color: 'violet', stroke: false, fillOpacity: 1, fill: true }}
/>}
{ falsePositives && !industries &&
<Marker position={[lat, lon]} icon={industryIcon} onClick={this.onClick}>
<Marker position={[lat, lon]} icon={industryIcon} eventHandlers={{ click: this.onClick }}>
<Tooltip><Fragment>{t('Es una industria (fuente: nuestros usuarios/as)')}</Fragment></Tooltip>
{ /* disabled because was a past fire (and can be marked multiple times) */ false && <FirePopup t={t} history={history} id={id} lat={lat} lon={lon} /> }
</Marker>
}
{ !falsePositives && !industries &&
<CircleMarker center={[lat, lon]} color={nasa ? 'red' : '#D35400'} stroke={false} fillOpacity="1" fill radius={1} onClick={this.onClick}>
<CircleMarker center={[lat, lon]} radius={1} pathOptions={{ color: nasa ? 'red' : '#D35400', stroke: false, fillOpacity: 1, fill: true }} eventHandlers={{ click: this.onClick }}>
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
</CircleMarker> }
</div>
</Fragment>
);
}
}

View file

@ -12,11 +12,8 @@ const FirePixel = ({
}) => (
<CircleMarker
center={[lat, lon]}
color={nasa ? 'red' : '#D35400'}
stroke={false}
fillOpacity="1"
fill
radius={nasa ? 1 : 2}
pathOptions={{ color: nasa ? 'red' : '#D35400', stroke: false, fillOpacity: 1, fill: true }}
>
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
</CircleMarker>

View file

@ -29,7 +29,7 @@ class FirePolygonMark extends Component {
const lon = centerid.coordinates[0];
const lat = centerid.coordinates[1];
return (
<GeoJSON data={shape} color="orange" stroke width="1" opacity=".2" fillOpacity=".0" />
<GeoJSON data={shape} style={{ color: 'orange', stroke: true, weight: 1, opacity: 0.2, fillOpacity: 0 }} />
);
/* <FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} /> */
}

View file

@ -1,25 +1,27 @@
/* eslint-disable react/jsx-indent-props */
/* eslint-disable import/no-absolute-path */
/* eslint-disable import/no-absolute-path */
import React, { Component } from 'react';
import React from 'react';
import PropTypes from 'prop-types';
import { withTranslation } from 'react-i18next';
import FullscreenControl from 'react-leaflet-fullscreen';
import 'react-leaflet-fullscreen/dist/styles.css';
import { createControlComponent } from '@react-leaflet/core';
import L from 'leaflet';
import 'leaflet.fullscreen';
import 'leaflet.fullscreen/Control.FullScreen.css';
class FullScreenMap extends Component {
render() {
const { t } = this.props;
return (
<FullscreenControl
position="topleft"
title={t('Pantalla completa')}
titleCancel={t('Salir de pantalla completa')}
/>
);
}
}
// Replacement for react-leaflet-fullscreen (v1-only): wrap the vanilla
// leaflet.fullscreen control with react-leaflet v4's control factory.
const FullscreenControl = createControlComponent(
({ position = 'topleft', title, titleCancel }) => L.control.fullscreen({ position, title, titleCancel })
);
const FullScreenMap = ({ t }) => (
<FullscreenControl
position="topleft"
title={t('Pantalla completa')}
titleCancel={t('Salir de pantalla completa')}
/>
);
FullScreenMap.propTypes = {
t: PropTypes.func.isRequired

View file

@ -0,0 +1,25 @@
import { createLayerComponent } from '@react-leaflet/core';
import L from 'leaflet';
import 'leaflet.gridlayer.googlemutant';
// Replacement for react-leaflet-google's GoogleLayer (v1-only). The Google Maps
// JS API is already loaded (with the places library) by Gkeys before any Google
// BaseLayer renders, so googlemutant can use window.google.maps directly.
function createGoogleMutant({
maptype = 'roadmap', opacity, googlekey, ...options
}, ctx) {
const instance = L.gridLayer.googleMutant({
type: String(maptype).toLowerCase(),
...(opacity != null ? { opacity } : {}),
...options
});
return { instance, context: { ...ctx } };
}
function updateGoogleMutant(instance, props, prevProps) {
if (props.opacity != null && props.opacity !== prevProps.opacity) {
instance.setOpacity(props.opacity);
}
}
export default createLayerComponent(createGoogleMutant, updateGoogleMutant);

View file

@ -0,0 +1,22 @@
import { useEffect } from 'react';
import { useMap, useMapEvents } from 'react-leaflet';
// v4 replaces the v1 `ref`/`.leafletElement` + handleLeafletLoad pattern: this
// child runs inside <MapContainer> and hands the ready Leaflet map to a class
// parent once, so the parent can drive it imperatively (setView, fitBounds,
// graphicScale, subsUnion, …).
export const MapReady = ({ onReady }) => {
const map = useMap();
useEffect(() => {
if (onReady) onReady(map);
// run once per map instance
}, [map]); // eslint-disable-line react-hooks/exhaustive-deps
return null;
};
// Bridges Leaflet map events to callbacks (replaces the v1 onMoveend /
// onViewportChanged / onZoomend props on <Map>).
export const MapEvents = ({ handlers }) => {
useMapEvents(handlers || {});
return null;
};

View file

@ -0,0 +1,32 @@
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useMap } from 'react-leaflet';
import L from 'leaflet';
// Replacement for react-leaflet-control (v1-only): mounts a Leaflet control at
// the given corner and portals arbitrary React children into it. Click/scroll
// on the control no longer pans/zooms the map underneath.
const MapControl = ({ position = 'topright', children }) => {
const map = useMap();
const [container, setContainer] = useState(null);
useEffect(() => {
const ReactControl = L.Control.extend({
onAdd: () => {
const div = L.DomUtil.create('div', 'leaflet-control leaflet-control-react');
L.DomEvent.disableClickPropagation(div);
L.DomEvent.disableScrollPropagation(div);
setContainer(div);
return div;
},
onRemove: () => setContainer(null)
});
const control = new ReactControl({ position });
control.addTo(map);
return () => control.remove();
}, [map, position]);
return container ? createPortal(children, container) : null;
};
export default MapControl;

View file

@ -12,7 +12,8 @@ const subsUnion = (union, options) => {
const interactive = options.interactive || false;
if (options.subs) {
const lmap = options.map.leafletElement;
// v4: options.map is the Leaflet map instance directly (no .leafletElement)
const lmap = options.map;
if (union) {
lmap.removeLayer(union);
}
@ -30,7 +31,7 @@ const subsUnion = (union, options) => {
if (options.fit && options.bounds) {
// console.log(options.bounds);
const bounds = JSON.parse(options.bounds);
options.map.leafletElement.fitBounds(L.latLngBounds(bounds._northEast, bounds._southWest));
lmap.fitBounds(L.latLngBounds(bounds._northEast, bounds._southWest));
}
} else if (options.subs.length > 0) {
const result = calcUnion(L, options.subs, sub => sub, true);
@ -43,7 +44,7 @@ const subsUnion = (union, options) => {
});
union.addTo(lmap);
if (options.fit) {
options.map.leafletElement.fitBounds(bounds);
lmap.fitBounds(bounds);
}
}
}

View file

@ -7,7 +7,7 @@
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Map, Marker, CircleMarker, Circle, Tooltip } from 'react-leaflet';
import { MapContainer, Marker, CircleMarker, Circle, Tooltip } from 'react-leaflet';
import Leaflet from 'leaflet';
import { withTranslation } from 'react-i18next';
import { withTracker } from 'meteor/react-meteor-data';
@ -18,7 +18,8 @@ import DefMapLayers from '/imports/ui/components/Maps/DefMapLayers';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
import 'leaflet-sleep/Leaflet.Sleep.js';
import Control from 'react-leaflet-control';
import MapControl from '/imports/ui/components/Maps/MapControl';
import { MapReady, MapEvents } from '/imports/ui/components/Maps/MapBridge';
import { Row, Col, Button, ButtonGroup } from 'react-bootstrap';
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
@ -51,13 +52,16 @@ class SelectionMap extends Component {
this.fit = this.fit.bind(this);
this.addScale = this.addScale.bind(this);
this.onFstBtn = this.onFstBtn.bind(this);
this.onViewportChanged = this.onViewportChanged.bind(this);
this.onMapMove = this.onMapMove.bind(this);
this.handleMapReady = this.handleMapReady.bind(this);
}
componentDidMount() {
if (this.isValidState()) {
this.addScale();
}
// v4: MapReady hands us the ready Leaflet map (replaces the componentDidMount
// + ref/.leafletElement wiring)
handleMapReady(map) {
this.map = map;
if (this.isValidState()) this.addScale();
this.handleLeafletLoad(map);
}
// Was UNSAFE_componentWillReceiveProps: pull center/distance from props into
@ -75,6 +79,8 @@ class SelectionMap extends Component {
marker: center[0] ? center : this.state.marker,
distance: distance || this.state.distance
});
// v4 map is uncontrolled: move it imperatively on a real center change
if (centerChanged && this.map) this.map.setView(center, this.state.zoom);
}
this.fit();
}
@ -90,7 +96,11 @@ class SelectionMap extends Component {
this.props.onSndBtn();
}
onViewportChanged(viewport) {
// v4: fed by <MapEvents> on moveend/zoomend (was the v1 onViewportChanged prop)
onMapMove() {
if (!this.map) return;
const c = this.map.getCenter();
const viewport = { center: [c.lat, c.lng], zoom: this.map.getZoom() };
if (this.props.onViewportChanged) {
this.props.onViewportChanged(viewport);
}
@ -100,7 +110,7 @@ class SelectionMap extends Component {
}
getMap() {
return this.selectionMap.leafletElement;
return this.map;
}
toggleDraggable() {
@ -108,7 +118,7 @@ class SelectionMap extends Component {
}
updatePosition() {
const { lat, lng } = this.marker.leafletElement.getLatLng();
const { lat, lng } = this.marker.getLatLng();
// console.log(`New marker lat ${lat} and lng ${lng}`);
const currentDistance = this.state.distance;
this.setState(update(this.state, { $merge: { marker: [lat, lng] } }));
@ -122,10 +132,10 @@ class SelectionMap extends Component {
// console.log("fit!");
if (this.props.currentSubs.length > 0 && this.state.subsFit && this.props.action !== action.add) {
// has autofit, do nothing
} else if (this.selectionMap && this.distanceCircle) {
if (!this.getMap().getBounds().contains(this.distanceCircle.leafletElement.getBounds())) {
} else if (this.map && this.distanceCircle) {
if (!this.getMap().getBounds().contains(this.distanceCircle.getBounds())) {
// console.log('New area circle not visible');
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds()); // padding , [70, 70]);
this.getMap().fitBounds(this.distanceCircle.getBounds()); // padding , [70, 70]);
} else {
// console.log('New area circle visible');
}
@ -133,7 +143,7 @@ class SelectionMap extends Component {
}
addScale() {
if (this.selectionMap) {
if (this.map) {
// https://www.npmjs.com/package/leaflet-graphicscale
const map = this.getMap();
const options = {
@ -170,16 +180,10 @@ class SelectionMap extends Component {
this.isValidState() ?
<Row>
<Col xs={12} sm={12} md={12} lg={12}>
<Map
ref={(map) => {
this.selectionMap = map;
this.handleLeafletLoad(map);
}}
<MapContainer
zoom={this.state.zoom}
center={this.state.center}
className="selectionmap-leaflet-container"
onViewportChanged={this.onViewportChanged}
animate
sleep={window.location.pathname === '/' && !isChrome}
sleepTime={10750}
wakeTime={750}
@ -189,6 +193,8 @@ class SelectionMap extends Component {
wakeMessageTouch={t('Pulsa para activar')}
sleepOpacity={0.6}
>
<MapReady onReady={this.handleMapReady} />
<MapEvents handlers={{ moveend: this.onMapMove, zoomend: this.onMapMove }} />
<DefMapLayers osmcolor />
{this.props.action === action.edit &&
this.props.currentSubs.map((subs, index) => (
@ -198,7 +204,7 @@ class SelectionMap extends Component {
position={[subs.location.lat, subs.location.lon]}
icon={removeIcon}
title={t('Pulsa para borrar')}
onClick={() => { onRemove(subs._id); }}
eventHandlers={{ click: () => { onRemove(subs._id); } }}
>
{index === 0 &&
<Tooltip
@ -217,7 +223,7 @@ class SelectionMap extends Component {
<Fragment>
<Marker
draggable={this.state.draggable}
onDragend={this.updatePosition}
eventHandlers={{ dragend: this.updatePosition }}
position={this.state.marker}
icon={positionIcon}
title={t('Arrastrar para seleccionar otro punto')}
@ -225,23 +231,18 @@ class SelectionMap extends Component {
/>
<CircleMarker
center={this.state.marker}
color="red"
stroke={false}
fillOpacity="1"
fill
radius={3}
pathOptions={{ color: 'red', stroke: false, fillOpacity: 1, fill: true }}
/>
<Circle
center={this.state.marker}
ref={(ref) => { this.distanceCircle = ref; }}
color="#145A32"
fillColor="green"
fillOpacity={0.1}
pathOptions={{ color: '#145A32', fillColor: 'green', fillOpacity: 0.1 }}
radius={this.state.distance * 1000}
/>
</Fragment>
}
<Control position="topright" >
<MapControl position="topright" >
<ButtonGroup>
{ this.props.sndBtn && this.props.onSndBtn &&
<Button
@ -260,9 +261,9 @@ class SelectionMap extends Component {
{this.props.fstBtn}
</Button>
</ButtonGroup>
</Control>
</MapControl>
<FullScreenMap />
</Map>
</MapContainer>
</Col>
</Row>
: