// redux/slices/mapLayersSlice.js import { createSlice } from "@reduxjs/toolkit"; const initialState = {}; const mapLayersSlice = createSlice({ name: "mapLayers", initialState, reducers: { toggleLayer: (state, action) => { const layer = action.payload; if (state[layer] !== undefined) { state[layer] = !state[layer]; // Toggle Sichtbarkeit } }, setLayerVisibility: (state, action) => { const { layer, visibility } = action.payload; state[layer] = visibility; // Sicher setzen }, setInitialLayers: (state, action) => { const systems = action.payload; // Array of GisSystem const mapId = typeof localStorage !== "undefined" ? localStorage.getItem("currentMapId") : null; const userId = typeof localStorage !== "undefined" ? localStorage.getItem("currentUserId") : null; const mapStorageKey = mapId && userId ? `mapLayersVisibility_m${mapId}_u${userId}` : "mapLayersVisibility"; let existingVisibility = {}; if (typeof localStorage !== "undefined") { try { const stored = localStorage.getItem(mapStorageKey); if (stored) { existingVisibility = JSON.parse(stored) || {}; } } catch (error) { console.error("Error loading stored visibility:", error); } } // Baue ein Set der gültigen Keys (nur Systeme mit Map===1) const validKeys = new Set(); systems.forEach(system => { if (system.Map !== 1) return; // Komplett überspringen, wenn Map==0 const key = `system-${system.IdSystem}`; validKeys.add(key); if (Object.prototype.hasOwnProperty.call(existingVisibility, key)) { state[key] = existingVisibility[key]; } else { state[key] = system.Allow === 1 && system.Map === 1; // Allow + Map Bedingung } }); // Entferne aus dem State alle Keys, die nicht mehr gültig sind (Map wurde evtl. auf 0 gesetzt) Object.keys(state).forEach(k => { if (!validKeys.has(k)) { delete state[k]; } }); // Bereinige auch den gespeicherten localStorage-Eintrag if (typeof localStorage !== "undefined") { const cleaned = {}; Object.keys(state).forEach(k => { cleaned[k] = state[k]; }); try { localStorage.setItem(mapStorageKey, JSON.stringify(cleaned)); } catch (e) { console.warn("Could not persist cleaned map layer visibility", e); } } }, }, }); export const { toggleLayer, setLayerVisibility, setInitialLayers } = mapLayersSlice.actions; export const selectMapLayersState = state => state.mapLayers || initialState; export default mapLayersSlice.reducer;