feat: Marker-Cleanup zur Vermeidung von Memory Leaks implementiert

- cleanupMarkers() Utility in /utils/common/cleanupMarkers.js erstellt
- Marker-Cleanup in MapComponent.js vor createAndSetDevices() integriert
- createAndSetDevices.js von Cleanup-Verantwortung befreit (reine Erzeugung)
- setupPOIs.js erweitert um cleanupMarkers() vor Layer-Neuerstellung
- poiUtils.js und markerUtils.js angepasst: cleanupMarkers() ersetzt .remove()
- Memory Leaks durch verwaiste Tooltips, Events und Marker behoben
- Grundlage für wiederverwendbare Marker-Cleanup-Logik für POIs, Geräte, Linien geschaffen
This commit is contained in:
ISA
2025-06-06 10:21:56 +02:00
parent ec31b36b3d
commit f7f7122620
10 changed files with 160 additions and 55 deletions

21
TODO.md
View File

@@ -22,3 +22,24 @@
- [x] TODO: Möglichkeit bevor in Gitea hochgeladen, .env.local anpassen, vielleicht mit husky Wenn - [x] TODO: Möglichkeit bevor in Gitea hochgeladen, .env.local anpassen, vielleicht mit husky Wenn
git push genutzt wird soll für Produktionsumgebung angepasst werden, Vorschlag ---> .env.local git push genutzt wird soll für Produktionsumgebung angepasst werden, Vorschlag ---> .env.local
und .env.production für Entwicklungsumgebung und Produktionsumgebung automatische Switch und .env.production für Entwicklungsumgebung und Produktionsumgebung automatische Switch
## 🧹 Memory Leaks prüfen
- [ ] **MapComponent.js** - [ ] `setInterval(...)` (1x) - [ ] `setTimeout(...)` (2x) - [ ]
`window.xyz = ...` (4x) globale Variablen - [ ] `map.on(...)` (2x) - [ ]
`addEventListener(...)` (1x) - 📌 Problematisch, wenn `clearInterval`, `clearTimeout`,
`map.off(...)` oder `removeEventListener(...)` nicht im useEffect-Cleanup gemacht werden. →
Speicher kann anwachsen, besonders bei Hot-Reload oder Navigation im iFrame.
- [ ] **useAreaMarkersLayer.js** - [ ] `setInterval(...)` - [ ] `addEventListener(...)` - 📌 Auch
hier muss geprüft werden, ob beim Unmounting der Komponente `clearInterval()` und
`removeEventListener()` aufgerufen wird.
- [ ] **AddPOIModal.js** - [ ] `setTimeout(...)` - 📌 Prüfen, ob der Timeout vor unmount gecleart
wird (z.B. bei schnellem Öffnen und Schließen des Modals).
- [ ] **MapLayersControlPanel.js** - [ ] `setTimeout(...)`
- [ ] **useDataUpdater.js** - [ ] `setInterval(...)` - 📌 Sehr wahrscheinlich ein regelmäßiger
Polling-Mechanismus → unbedingt prüfen, ob `clearInterval()` im useEffect-Cleanup enthalten
ist.

View File

@@ -77,6 +77,8 @@ import { updateAreaThunk } from "@/redux/thunks/database/area/updateAreaThunk";
import useDynamicDeviceLayers from "@/hooks/useDynamicDeviceLayers.js"; import useDynamicDeviceLayers from "@/hooks/useDynamicDeviceLayers.js";
import useDataUpdater from "@/hooks/useDataUpdater"; import useDataUpdater from "@/hooks/useDataUpdater";
import { cleanupPolylinesForMemory } from "@/utils/polylines/cleanupPolylinesForMemory";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";
//----------------------------------------------------------------------------------------------------- //-----------------------------------------------------------------------------------------------------
const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => { const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
//------------------------------- //-------------------------------
@@ -299,9 +301,13 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
useEffect(() => { useEffect(() => {
if (!map) return; if (!map) return;
// Entferne alte Marker und Polylinien // vorherige Marker & Polylinien vollständig bereinigen
markers.forEach(marker => marker.remove());
polylines.forEach(polyline => polyline.remove()); markers.forEach(marker => {
console.log("Marker-Typ:", marker.options);
marker.remove();
});
cleanupPolylinesForMemory(polylines, map);
// Setze neue Marker und Polylinien mit den aktuellen Daten // Setze neue Marker und Polylinien mit den aktuellen Daten
const { markers: newMarkers, polylines: newPolylines } = setupPolylines( const { markers: newMarkers, polylines: newPolylines } = setupPolylines(
@@ -358,7 +364,7 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
polyline.closeTooltip(); polyline.closeTooltip();
}); });
}); });
cleanupMarkers(markers, oms);
setMarkers(newMarkers); setMarkers(newMarkers);
setPolylines(newPolylines); setPolylines(newPolylines);
}, [ }, [
@@ -471,14 +477,15 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
} }
}, [map]); }, [map]);
//-------------------------------------------- //--------------------------------------------
let timeoutId;
useEffect(() => { useEffect(() => {
const initializeContextMenu = () => { const initializeContextMenu = () => {
if (map) { if (map) {
map.whenReady(() => { map.whenReady(() => {
setTimeout(() => { timeoutId = setTimeout(() => {
if (map.contextmenu) { if (map.contextmenu) {
if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") { if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
//console.log("Contextmenu ist vorhanden"); console.log("Contextmenu ist vorhanden");
} }
} else { } else {
console.warn("Contextmenu ist nicht verfügbar."); console.warn("Contextmenu ist nicht verfügbar.");
@@ -489,6 +496,10 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
}; };
initializeContextMenu(); initializeContextMenu();
return () => {
clearTimeout(timeoutId); // Aufräumen
};
}, [map]); }, [map]);
//--------------------------------------- //---------------------------------------
@@ -693,34 +704,28 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
} }
}, [isPolylineContextMenuOpen, countdown, countdownActive, dispatch, window.map]); }, [isPolylineContextMenuOpen, countdown, countdownActive, dispatch, window.map]);
//---------------------------------- //----------------------------------
// map in window setzen für mehr Debugging
useEffect(() => {
if (map) {
window.map = map;
if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
console.log("✅ window.map wurde gesetzt:", window.map);
}
}
}, [map]);
//---------------------------------------
// **Fehlerbehandlung für `contextmenu`** // **Fehlerbehandlung für `contextmenu`**
// damit den Fehler mit contextmenu nicht angezeigt wird und überspringt wird und die Seite neu geladen wird // damit den Fehler mit contextmenu nicht angezeigt wird und überspringt wird und die Seite neu geladen wird
useEffect(() => { useEffect(() => {
let timeoutId;
window.onerror = function (message, source, lineno, colno, error) { window.onerror = function (message, source, lineno, colno, error) {
if (message.includes("Cannot read properties of null (reading 'contextmenu')")) { if (message.includes("Cannot read properties of null (reading 'contextmenu')")) {
console.warn("⚠️ Fehler mit `contextmenu` erkannt - Neuladen der Seite."); console.warn("⚠️ Fehler mit `contextmenu` erkannt Neuladen der Seite.");
setTimeout(() => { timeoutId = setTimeout(() => {
window.location.reload(); window.location.reload();
}, 0); // **Seite nach Sekunde neu laden** }, 0);
return true; // **Fehler unterdrücken, damit React ihn nicht anzeigt** return true; // Fehler unterdrücken
} }
}; };
return () => { return () => {
window.onerror = null; // **Fehlerbehandlung entfernen, wenn Komponente unmounted wird** clearTimeout(timeoutId);
window.onerror = null; // Aufräumen beim Unmount
}; };
}, []); }, []);
//------------------------------------------------ //------------------------------------------------
useEffect(() => { useEffect(() => {
if (poiTypStatus === "succeeded" && Array.isArray(poiTypData)) { if (poiTypStatus === "succeeded" && Array.isArray(poiTypData)) {
@@ -736,7 +741,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
} }
}, [poiIconsData, poiIconsStatus]); }, [poiIconsData, poiIconsStatus]);
//----------------------------------------------------------------- //-----------------------------------------------------------------
//-----------------------------------------------------------------
useEffect(() => { useEffect(() => {
if (!map) return; if (!map) return;
@@ -761,16 +765,6 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
checkOverlappingMarkers(map, allMarkers, plusRoundIcon); checkOverlappingMarkers(map, allMarkers, plusRoundIcon);
}, [map, markerStates, mapLayersVisibility]); }, [map, markerStates, mapLayersVisibility]);
//---------------------------------------------
// 🧠 Optional für Debugging für überlappende Markers
useEffect(() => {
if (oms) {
if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
console.log("📌 OMS ready:", oms);
}
window.oms = oms; // Für Debugging global
}
}, [oms]);
//---------------------------------------------- //----------------------------------------------
useEffect(() => { useEffect(() => {
@@ -780,6 +774,12 @@ const MapComponent = ({ locations, onLocationUpdate, lineCoordinates }) => {
console.log("Production Mode aktiviert"); console.log("Production Mode aktiviert");
} }
}, []); }, []);
//-------------------------------------------
useEffect(() => {
return () => {
cleanupMarkers(markers, oms);
};
}, []);
//--------------------------------------------- //---------------------------------------------
//-------------------------------------------- //--------------------------------------------
return ( return (

View File

@@ -1,2 +1,2 @@
// /config/appVersion // /config/appVersion
export const APP_VERSION = "1.1.236"; export const APP_VERSION = "1.1.237";

View File

@@ -48,7 +48,7 @@ const useAreaMarkersLayer = (map, oms, apiUrl, onUpdateSuccess) => {
}; };
window.addEventListener("storage", handleStorageChange); window.addEventListener("storage", handleStorageChange);
const intervalId = setInterval(updateMarkersVisibility, 500); const intervalId = setInterval(updateMarkersVisibility, 5000);
return () => { return () => {
window.removeEventListener("storage", handleStorageChange); window.removeEventListener("storage", handleStorageChange);
@@ -68,6 +68,7 @@ const useAreaMarkersLayer = (map, oms, apiUrl, onUpdateSuccess) => {
const marker = L.marker([item.x, item.y], { const marker = L.marker([item.x, item.y], {
icon: customIcon, icon: customIcon,
draggable: true, draggable: true,
customType: "areaMarker",
}); });
marker.bindTooltip( marker.bindTooltip(

View File

@@ -0,0 +1,25 @@
// /utils/common/cleanupMarkers.js
/**
* Entfernt alle Leaflet-Marker vollständig aus der Karte und aus OMS egal welche Typ sind
* @param {L.Marker[]} markers - Liste der Marker
* @param {object} oms - OverlappingMarkerSpiderfier-Instanz (optional)
*/
export const cleanupMarkers = (markers = [], oms = null) => {
markers.forEach(marker => {
// Tooltip und Popup entfernen
marker.unbindTooltip?.();
marker.unbindPopup?.();
// Event-Listener entfernen (zur Sicherheit)
marker.off?.();
// Marker von Karte entfernen
marker.remove?.();
// Marker aus OMS entfernen (wenn vorhanden)
if (oms && typeof oms.removeMarker === "function") {
oms.removeMarker(marker);
}
});
};

View File

@@ -7,6 +7,7 @@ import { selectGisStationsStaticDistrict } from "@/redux/slices/webservice/gisSt
import { selectGisStationsStatusDistrict } from "@/redux/slices/webservice/gisStationsStatusDistrictSlice.js"; import { selectGisStationsStatusDistrict } from "@/redux/slices/webservice/gisStationsStatusDistrictSlice.js";
import { selectGisStationsMeasurements } from "@/redux/slices/webservice/gisStationsMeasurementsSlice.js"; import { selectGisStationsMeasurements } from "@/redux/slices/webservice/gisStationsMeasurementsSlice.js";
import { addContextMenuToMarker } from "@/utils/contextMenuUtils"; import { addContextMenuToMarker } from "@/utils/contextMenuUtils";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";
const determinePriority = (iconPath, priorityConfig) => { const determinePriority = (iconPath, priorityConfig) => {
for (let priority of priorityConfig) { for (let priority of priorityConfig) {

View File

@@ -5,8 +5,9 @@ import circleIcon from "../components/CircleIcon";
import { store } from "../redux/store"; import { store } from "../redux/store";
import { updatePolylineCoordinatesThunk } from "../redux/thunks/database/polylines/updatePolylineCoordinatesThunk"; import { updatePolylineCoordinatesThunk } from "../redux/thunks/database/polylines/updatePolylineCoordinatesThunk";
import { redrawPolyline } from "./mapUtils"; import { redrawPolyline } from "./mapUtils";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";
const savePolylineRedux = (lineData) => { const savePolylineRedux = lineData => {
return store return store
.dispatch( .dispatch(
updatePolylineCoordinatesThunk({ updatePolylineCoordinatesThunk({
@@ -16,7 +17,7 @@ const savePolylineRedux = (lineData) => {
}) })
) )
.unwrap() .unwrap()
.catch((error) => { .catch(error => {
console.error("Fehler beim Speichern der Linienkoordinaten:", error.message); console.error("Fehler beim Speichern der Linienkoordinaten:", error.message);
}); });
}; };
@@ -44,18 +45,27 @@ export const insertNewMarker = (closestPoints, newPoint, lineData, map) => {
}; };
export const removeMarker = (marker, lineData, currentZoom, currentCenter) => { export const removeMarker = (marker, lineData, currentZoom, currentCenter) => {
const index = lineData.coordinates.findIndex((coord) => L.latLng(coord[0], coord[1]).equals(marker.getLatLng())); const index = lineData.coordinates.findIndex(coord =>
L.latLng(coord[0], coord[1]).equals(marker.getLatLng())
);
if (index !== -1) { if (index !== -1) {
lineData.coordinates.splice(index, 1); lineData.coordinates.splice(index, 1);
redrawPolyline(lineData); redrawPolyline(lineData);
marker.remove(); cleanupMarkers([marker]);
savePolylineRedux(lineData); // ✅ Wiederverwendung savePolylineRedux(lineData); // ✅ Wiederverwendung
window.location.reload(); window.location.reload();
} }
}; };
export const handleEditPoi = (marker, userRights, setCurrentPoiData, setShowPoiUpdateModal, fetchPoiData, toast) => { export const handleEditPoi = (
marker,
userRights,
setCurrentPoiData,
setShowPoiUpdateModal,
fetchPoiData,
toast
) => {
if (!Array.isArray(userRights)) { if (!Array.isArray(userRights)) {
toast.error("Benutzerrechte sind ungültig.", { toast.error("Benutzerrechte sind ungültig.", {
position: "top-center", position: "top-center",
@@ -64,7 +74,7 @@ export const handleEditPoi = (marker, userRights, setCurrentPoiData, setShowPoiU
return; return;
} }
if (!userRights.some((r) => r.IdRight === 56)) { if (!userRights.some(r => r.IdRight === 56)) {
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", { toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
position: "top-center", position: "top-center",
autoClose: 5000, autoClose: 5000,

View File

@@ -6,9 +6,10 @@ import { redrawPolyline } from "./polylines/redrawPolyline.js";
import { store } from "../redux/store"; import { store } from "../redux/store";
import { updatePolylineCoordinatesThunk } from "../redux/thunks/database/polylines/updatePolylineCoordinatesThunk"; import { updatePolylineCoordinatesThunk } from "../redux/thunks/database/polylines/updatePolylineCoordinatesThunk";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";
// 🧠 Zentrale Redux-Dispatch-Hilfsfunktion // 🧠 Zentrale Redux-Dispatch-Hilfsfunktion
const savePolylineRedux = (lineData) => { const savePolylineRedux = lineData => {
return store return store
.dispatch( .dispatch(
updatePolylineCoordinatesThunk({ updatePolylineCoordinatesThunk({
@@ -18,7 +19,7 @@ const savePolylineRedux = (lineData) => {
}) })
) )
.unwrap() .unwrap()
.catch((error) => { .catch(error => {
console.error("Fehler beim Speichern der Linienkoordinaten:", error.message); console.error("Fehler beim Speichern der Linienkoordinaten:", error.message);
}); });
}; };
@@ -49,12 +50,14 @@ export const insertNewPOI = (closestPoints, newPoint, lineData, map) => {
}; };
export const removePOI = (marker, lineData, currentZoom, currentCenter) => { export const removePOI = (marker, lineData, currentZoom, currentCenter) => {
const index = lineData.coordinates.findIndex((coord) => L.latLng(coord[0], coord[1]).equals(marker.getLatLng())); const index = lineData.coordinates.findIndex(coord =>
L.latLng(coord[0], coord[1]).equals(marker.getLatLng())
);
if (index !== -1) { if (index !== -1) {
lineData.coordinates.splice(index, 1); lineData.coordinates.splice(index, 1);
redrawPolyline(lineData); redrawPolyline(lineData);
marker.remove(); cleanupMarkers([marker]);
savePolylineRedux(lineData); savePolylineRedux(lineData);
window.location.reload(); window.location.reload();
} }

View File

@@ -0,0 +1,29 @@
// /utils/polylines/cleanupPolylinesForMemory.js
/**
* Bereinigt Leaflet-Polylinien aus dem Speicher:
* - entfernt Event-Listener (off)
* - entfernt Tooltips (unbindTooltip)
* - entfernt Layer von der Karte (removeLayer)
*
* @param {L.Polyline[]} polylines - Liste der Leaflet-Polylinien
* @param {L.Map} map - Leaflet-Karteninstanz
*/
export function cleanupPolylinesForMemory(polylines = [], map) {
if (!Array.isArray(polylines)) return;
polylines.forEach(polyline => {
try {
// Events und Tooltip entfernen
polyline.off();
polyline.unbindTooltip?.();
// Von der Karte entfernen, wenn noch vorhanden
if (map && map.hasLayer(polyline)) {
map.removeLayer(polyline);
}
} catch (e) {
console.warn("Fehler beim Bereinigen einer Polyline:", e);
}
});
}

View File

@@ -3,6 +3,7 @@ import { parsePoint } from "./geometryUtils";
import { handleEditPoi } from "./poiUtils"; import { handleEditPoi } from "./poiUtils";
import { updateLocationInDatabaseService } from "../services/database/updateLocationInDatabaseService"; import { updateLocationInDatabaseService } from "../services/database/updateLocationInDatabaseService";
import { setSelectedPoi, clearSelectedPoi } from "../redux/slices/database/pois/selectedPoiSlice"; import { setSelectedPoi, clearSelectedPoi } from "../redux/slices/database/pois/selectedPoiSlice";
import { cleanupMarkers } from "@/utils/common/cleanupMarkers";
export const setupPOIs = async ( export const setupPOIs = async (
map, map,
@@ -28,13 +29,17 @@ export const setupPOIs = async (
// ✅ Mapping vorbereiten: idPoi → icon path // ✅ Mapping vorbereiten: idPoi → icon path
const iconMap = new Map(); const iconMap = new Map();
poiData.forEach((item) => { poiData.forEach(item => {
if (item.idPoi && item.path) { if (item.idPoi && item.path) {
iconMap.set(item.idPoi, item.path); iconMap.set(item.idPoi, item.path);
} }
}); });
if (map && poiLayerRef.current) { if (map && poiLayerRef.current) {
const existingMarkers = poiLayerRef.current?.getLayers?.();
if (existingMarkers?.length) {
cleanupMarkers(existingMarkers);
}
map.removeLayer(poiLayerRef.current); map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map); poiLayerRef.current = new L.LayerGroup().addTo(map);
@@ -42,11 +47,13 @@ export const setupPOIs = async (
try { try {
const { latitude, longitude } = parsePoint(poi.position); const { latitude, longitude } = parsePoint(poi.position);
const poiTypName = poiTypMap.get(poi.idPoiTyp) || "Unbekannt"; const poiTypName = poiTypMap.get(poi.idPoiTyp) || "Unbekannt";
const canDrag = userRights ? userRights.some((r) => r.IdRight === 56) : false; const canDrag = userRights ? userRights.some(r => r.IdRight === 56) : false;
// ✅ Icon korrekt über idPoi auflösen // ✅ Icon korrekt über idPoi auflösen
const iconPath = iconMap.get(poi.idPoi); const iconPath = iconMap.get(poi.idPoi);
const iconUrl = iconPath ? `/img/icons/pois/${iconPath}` : "/img/icons/pois/default-icon.png"; const iconUrl = iconPath
? `/img/icons/pois/${iconPath}`
: "/img/icons/pois/default-icon.png";
const marker = L.marker([latitude, longitude], { const marker = L.marker([latitude, longitude], {
icon: L.icon({ icon: L.icon({
@@ -72,7 +79,15 @@ export const setupPOIs = async (
{ {
text: "POI Bearbeiten", text: "POI Bearbeiten",
icon: "/img/poi-edit.png", icon: "/img/poi-edit.png",
callback: () => handleEditPoi(marker, userRights, setCurrentPoiData, setShowPoiUpdateModal, fetchPoiData, toast), callback: () =>
handleEditPoi(
marker,
userRights,
setCurrentPoiData,
setShowPoiUpdateModal,
fetchPoiData,
toast
),
}, },
], ],
}); });
@@ -80,12 +95,12 @@ export const setupPOIs = async (
marker.bindTooltip( marker.bindTooltip(
` `
<div class="bg-white text-gray-800 text-sm rounded-xl px-4 py-2 w-56"> <div class="bg-white text-gray-800 text-sm rounded-xl px-4 py-2 w-56">
<div class="font-semibold text-blue-500 mb-1">${poi.description || "Unbekannt"}</div> <div class="font-semibold text-blue-500 mb-1">${poi.description || "Unbekannt"}</div>
<div class="text-gray-600 text-sm">Gerät: ${deviceName || "unbekannt"}</div> <div class="text-gray-600 text-sm">Gerät: ${deviceName || "unbekannt"}</div>
<div class="text-gray-600 text-sm">Typ: ${poiTypName}</div> <div class="text-gray-600 text-sm">Typ: ${poiTypName}</div>
</div> </div>
`, `,
{ {
direction: "top", direction: "top",
offset: [0, -10], offset: [0, -10],
@@ -105,7 +120,7 @@ export const setupPOIs = async (
//this.closePopup(); //this.closePopup();
}); });
marker.on("dragend", (e) => { marker.on("dragend", e => {
if (canDrag) { if (canDrag) {
const newLat = e.target.getLatLng().lat; const newLat = e.target.getLatLng().lat;
const newLng = e.target.getLatLng().lng; const newLng = e.target.getLatLng().lng;