eurometeo / src /components /Map.tsx
alexdum's picture
Improve mobile embedded UX with quick parameter switcher and drawer contrast
c9b0d0b
Raw History Blame Contribute Delete
60.4 kB
import React, { useEffect, useRef, useState, useCallback, useMemo } from "react"; import maplibregl from "maplibre-gl"; import "maplibre-gl/dist/maplibre-gl.css"; import { Layers, ShieldAlert, Home, Info, ChevronDown, StepBack, StepForward, Clock, X } from "lucide-react"; import { formatMapValue, getColorFromPalette, getUnitForParam, PRECIPITATION_ZERO_STYLE } from "@/utils/colors"; import { countryMatches, isEuropeanStation, computeStationBounds } from "@/utils/country"; import { filterMapObservations } from "@/utils/qc"; import { countPrecipitationPeriods, extractPrecipitationObservation, precipitationNumber } from "@/utils/precipitation"; import type { PrecipitationAvailability, PrecipitationHours, PrecipitationParameter } from "@/utils/precipitation"; import { MapLegend } from "./MapLegend"; import { Tooltip } from "./Tooltip"; interface Station { id: string; name: string; country: string; longitude: number; latitude: number; elevation: number | null; available_params: string; } interface MapProps { stations: Station[]; selectedCountry: string; selectedStation: string; setSelectedStation: (stationId: string) => void; setSelectedCountry: (country: string) => void; parameter: string; precipitationHours: PrecipitationHours; setPrecipitationHours: (hours: PrecipitationHours) => void; startDate: string; endDate: string; observations: Record<string, number[]>; setObservations: (obs: Record<string, number[]>) => void; selectedHour: number; setSelectedHour: (hour: number | ((prev: number) => number)) => void; isLoadingStations?: boolean; onStationClick?: (stationId: string) => void; resetMapView?: number; onResetMap?: () => void; } interface AreaObservation { stationId: string; value: number; sourceParameter?: "rainfall_amount"; } function buildStationHoverPopupContent( props: Record<string, unknown>, param: string ): HTMLDivElement { const valueDisplay = props.value !== null && props.value !== undefined ? `${param.includes("precipitation") ? String(props.label ?? props.value) : String(props.value)} ${getUnitForParam(param)}` : "No data"; const paramLabel = param.includes("precipitation") ? `${props.sourceParameter === "rainfall_amount" ? "Rainfall" : "Precipitation"} (${String(props.precipitationHours ?? "")} h):` : `${param.replace(/_/g, " ")}:`; const elevationDisplay = props.elevation !== null && props.elevation !== undefined && props.elevation !== "null" ? `${String(props.elevation)}m` : "Unknown"; const container = document.createElement("div"); container.style.cssText = "padding:10px;font-family:system-ui,sans-serif;min-width:170px"; const title = document.createElement("h4"); title.style.cssText = "font-weight:700;color:#1e293b;font-size:13px;margin:0 0 3px 0"; title.textContent = String(props.name ?? ""); container.appendChild(title); const idEl = document.createElement("p"); idEl.style.cssText = "font-size:10px;color:#64748b;font-weight:500;margin:0 0 8px 0"; idEl.textContent = String(props.id ?? ""); container.appendChild(idEl); const valueRow = document.createElement("div"); valueRow.style.cssText = "display:flex;justify-content:space-between;align-items:center;font-size:11px;border-top:1px solid #f1f5f9;padding-top:6px"; const valueLabelSpan = document.createElement("span"); valueLabelSpan.style.cssText = "font-weight:500;color:#94a3b8"; valueLabelSpan.textContent = paramLabel; const valueValSpan = document.createElement("span"); valueValSpan.style.cssText = "font-weight:700;color:#1e293b"; valueValSpan.textContent = valueDisplay; valueRow.append(valueLabelSpan, valueValSpan); container.appendChild(valueRow); const elevRow = document.createElement("div"); elevRow.style.cssText = "display:flex;justify-content:space-between;align-items:center;font-size:11px;padding-top:4px"; const elevLabelSpan = document.createElement("span"); elevLabelSpan.style.cssText = "font-weight:500;color:#94a3b8"; elevLabelSpan.textContent = "Elevation:"; const elevValSpan = document.createElement("span"); elevValSpan.style.cssText = "font-weight:500;color:#475569"; elevValSpan.textContent = elevationDisplay; elevRow.append(elevLabelSpan, elevValSpan); container.appendChild(elevRow); const footer = document.createElement("div"); footer.style.cssText = "margin-top:8px;padding-top:6px;border-top:1px solid #f1f5f9;text-align:center"; const footerSpan = document.createElement("span"); footerSpan.style.cssText = "font-size:10px;color:#3b82f6;font-weight:600"; footerSpan.textContent = "Click to view dashboard →"; footer.appendChild(footerSpan); container.appendChild(footer); return container; } interface LegacyCoverageRange { values?: unknown[]; } interface LegacyCoverage { parameters?: Record<string, PrecipitationParameter>; "metocean:wigosId"?: string; domain?: { axes?: { t?: { values?: string[]; }; }; }; ranges?: Record<string, LegacyCoverageRange>; } interface AreaObservationsResponse { success: boolean; message?: string; observations?: AreaObservation[]; coverages?: LegacyCoverage[]; apiUnavailable?: boolean; precipitationHours?: PrecipitationHours; precipitationAvailability?: PrecipitationAvailability; availabilityComplete?: boolean; } const SOURCE_ID = "stations-source"; const CIRCLE_LAYER = "stations-circles"; const TEXT_LAYER = "stations-labels"; const SELECTED_LAYER = "stations-selected"; const OBSERVATION_FETCH_DEBOUNCE_MS = 250; function getErrorName(error: unknown): string { return error instanceof Error ? error.name : ""; } function getPointCoordinates(geometry: GeoJSON.Geometry | null | undefined): [number, number] | null { if (!geometry || geometry.type !== "Point") return null; const [longitude, latitude] = geometry.coordinates; if (typeof longitude !== "number" || typeof latitude !== "number") return null; return [longitude, latitude]; } const WeatherMapComponent: React.FC<MapProps> = ({ stations, selectedCountry, selectedStation, setSelectedStation, setSelectedCountry, parameter, precipitationHours, setPrecipitationHours, endDate, observations, setObservations, selectedHour, setSelectedHour, isLoadingStations, onStationClick, resetMapView = 0, onResetMap }) => { const mapContainer = useRef<HTMLDivElement>(null); const map = useRef<maplibregl.Map | null>(null); const popupRef = useRef<maplibregl.Popup | null>(null); const isPrecipitation = parameter.includes("precipitation"); const observationRequestKey = useMemo( () => `${parameter}|${endDate}|${selectedHour}|${isPrecipitation ? precipitationHours : "point"}`, [parameter, endDate, selectedHour, isPrecipitation, precipitationHours] ); const [activeObservationKey, setActiveObservationKey] = useState<string>(""); const [periodAvailability, setPeriodAvailability] = useState<{ key: string; periods: PrecipitationAvailability } | null>(null); const [rainfallStationIds, setRainfallStationIds] = useState<Set<string>>(new Set()); const scopedStations = useMemo(() => stations.filter(station => !selectedCountry || countryMatches(station.country, selectedCountry)), [stations, selectedCountry]); const periodCounts = useMemo(() => { if (!isPrecipitation || periodAvailability?.key !== observationRequestKey) return null; return countPrecipitationPeriods(periodAvailability.periods, scopedStations.map(station => station.id)); }, [isPrecipitation, periodAvailability, observationRequestKey, scopedStations]); const rainfallReportCount = activeObservationKey === observationRequestKey ? scopedStations.filter(station => rainfallStationIds.has(station.id)).length : 0; // ── Extract the actual values present on the map for the legend ── const currentValues = useMemo(() => { if (activeObservationKey !== observationRequestKey) return []; const vals: number[] = []; stations.forEach(st => { const val = observations[st.id]?.[selectedHour]; if (val !== undefined && val !== null && !isNaN(val)) { vals.push(val); } }); return vals; }, [activeObservationKey, observationRequestKey, stations, observations, selectedHour]); const sourceReadyRef = useRef(false); const idleTimeoutRef = useRef<number | null>(null); const onMapIdleRef = useRef<(() => void) | null>(null); const isPendingIdleSyncRef = useRef<boolean>(false); const clearIdleSync = useCallback(() => { if (idleTimeoutRef.current !== null) { window.clearTimeout(idleTimeoutRef.current); idleTimeoutRef.current = null; } if (onMapIdleRef.current !== null && map.current) { map.current.off('idle', onMapIdleRef.current); onMapIdleRef.current = null; } }, []); const fallbackTimerRef = useRef<number | null>(null); const clearFallbackTimer = useCallback(() => { if (fallbackTimerRef.current !== null) { window.clearTimeout(fallbackTimerRef.current); fallbackTimerRef.current = null; } }, []); const [basemap, setBasemap] = useState<string>("positron"); const [showLabels, setShowLabels] = useState<boolean>(true); const [isLoading, setIsLoading] = useState<boolean>(true); const [errorMsg, setErrorMsg] = useState<string | null>(null); const triggerIdleSync = useCallback((m: maplibregl.Map) => { if (!isPendingIdleSyncRef.current) return; isPendingIdleSyncRef.current = false; clearIdleSync(); const mExtended = m as unknown as { isIdle?: () => boolean }; const isMapCurrentlyIdle = typeof mExtended.isIdle === "function" ? mExtended.isIdle() : (typeof m.loaded === "function" ? m.loaded() : false); if (isMapCurrentlyIdle) { setIsLoading(false); clearFallbackTimer(); } else { const handleIdle = () => { setIsLoading(false); clearIdleSync(); clearFallbackTimer(); }; onMapIdleRef.current = handleIdle; m.once('idle', handleIdle); // Bounded fallback of 5s (generous buffer for rendering 3,500+ stations) idleTimeoutRef.current = window.setTimeout(() => { console.warn("[Map] Idle event timed out. Dismissing loader."); setErrorMsg("The map is taking longer than usual to load all stations. If data does not display properly, please refresh after 30 seconds."); setIsLoading(false); clearIdleSync(); clearFallbackTimer(); }, 5000); } }, [clearIdleSync, clearFallbackTimer]); const triggerIdleSyncRef = useRef(triggerIdleSync); useEffect(() => { triggerIdleSyncRef.current = triggerIdleSync; }, [triggerIdleSync]); const [visibleBounds, setVisibleBounds] = useState<maplibregl.LngLatBounds | null>(null); const [isStatsExpanded, setIsStatsExpanded] = useState<boolean>(() => { if (typeof window !== "undefined") { return window.innerWidth >= 768; } return true; }); const maxAllowedHour = useMemo(() => { const todayStr = new Date().toISOString().split("T")[0]; if (endDate === todayStr) { return new Date().getUTCHours(); } return 23; }, [endDate]); // Clamp selected hour if it exceeds max allowed (e.g. when changing date to today) useEffect(() => { if (selectedHour > maxAllowedHour) { setSelectedHour(maxAllowedHour); } }, [maxAllowedHour, selectedHour, setSelectedHour]); // ── Stable refs for all values used inside map event handlers ── // This avoids stale closures in the one-time-registered event handlers. const setSelectedStationRef = useRef(setSelectedStation); const setSelectedCountryRef = useRef(setSelectedCountry); const selectedStationValueRef = useRef(selectedStation); const selectedCountryValueRef = useRef(selectedCountry); const onStationClickRef = useRef(onStationClick); const parameterRef = useRef(parameter); const showLabelsRef = useRef(showLabels); const basemapRef = useRef(basemap); const pendingFitBoundsRef = useRef<{ bounds: [number, number, number, number]; duration: number } | null>(null); useEffect(() => { setSelectedStationRef.current = setSelectedStation; setSelectedCountryRef.current = setSelectedCountry; selectedStationValueRef.current = selectedStation; selectedCountryValueRef.current = selectedCountry; onStationClickRef.current = onStationClick; parameterRef.current = parameter; showLabelsRef.current = showLabels; basemapRef.current = basemap; }, [setSelectedStation, setSelectedCountry, selectedStation, selectedCountry, onStationClick, parameter, showLabels, basemap]); // ── 1. Fetch area observations whenever period, parameter, or hour changes ── useEffect(() => { if (stations.length === 0) return; const abortController = new AbortController(); const requestKey = observationRequestKey; const fetchObservations = async () => { setIsLoading(true); setErrorMsg(null); setObservations({}); setActiveObservationKey(""); clearFallbackTimer(); fallbackTimerRef.current = window.setTimeout(() => { console.warn("[Map] Loading fallback timed out. Dismissing loader."); setErrorMsg("Map loading is taking longer than expected. Please wait a moment or refresh after 30 seconds."); setIsLoading(false); }, 20000); try { const bounds = stations.reduce( (acc, st) => ({ lng_min: Math.min(acc.lng_min, st.longitude), lng_max: Math.max(acc.lng_max, st.longitude), lat_min: Math.min(acc.lat_min, st.latitude), lat_max: Math.max(acc.lat_max, st.latitude), }), { lng_min: 180, lng_max: -180, lat_min: 90, lat_max: -90 } ); // Match MeteoGate R: request a 1-hour window for the selected hour const hourStr = selectedHour.toString().padStart(2, "0"); const endMinute = `${hourStr}:59`; const startMinute = `${hourStr}:00`; const datetimeRange = `${endDate}T${startMinute}Z/${endDate}T${endMinute}Z`; const stationLocations = stations.map((st) => ({ longitude: st.longitude, latitude: st.latitude, })); const res = await fetch("/api/observations/area", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ parameter, datetimeRange, ...(isPrecipitation ? { precipitationHours } : {}), bounds, stations: stationLocations }), signal: abortController.signal }); if (abortController.signal.aborted) return; const json = await res.json() as AreaObservationsResponse; if (!res.ok || !json.success) throw new Error(json.message || "Failed to fetch observations"); if (isPrecipitation && json.precipitationHours !== precipitationHours) { throw new Error("The precipitation response does not match the selected period."); } const newObs: Record<string, number[]> = {}; const rainfallIds = new Set<string>(); if (Array.isArray(json.observations)) { json.observations.forEach((observation: AreaObservation) => { const stationId = observation.stationId; const numVal = isPrecipitation ? precipitationNumber(observation.value) : Number(observation.value); if (!stationId || numVal === null || !Number.isFinite(numVal)) return; const hourlyVals = new Array(24).fill(NaN); hourlyVals[selectedHour] = numVal; newObs[stationId] = hourlyVals; if (observation.sourceParameter === "rainfall_amount") rainfallIds.add(stationId); }); } else if (Array.isArray(json.coverages)) { json.coverages.forEach((coverage) => { if (isPrecipitation) { const report = extractPrecipitationObservation(coverage, parameter, Date.parse(`${endDate}T${hourStr}:00:00Z`), precipitationHours); if (report) { const hourlyVals = new Array(24).fill(NaN); hourlyVals[selectedHour] = report.value; newObs[report.stationId] = hourlyVals; if (report.sourceParameter === "rainfall_amount") rainfallIds.add(report.stationId); } return; } const wigosId = coverage["metocean:wigosId"]; if (!wigosId) return; const domain = coverage.domain || {}; const axes = domain.axes || {}; const tAxis = axes.t || {}; const timestamps: string[] = tAxis.values || []; const ranges = coverage.ranges || {}; const rangeKeys = Object.keys(ranges); let bestKey = rangeKeys[0]; if (!parameter.includes("precipitation")) { const pt0s = rangeKeys.find(k => k.includes("PT0S")); if (pt0s) bestKey = pt0s; } if (bestKey) { const values: unknown[] = ranges[bestKey]?.values || []; const hourlyVals = new Array(24).fill(NaN); const len = Math.min(values.length, timestamps.length); for (let i = 0; i < len; i++) { const val = values[i]; if (val !== null && val !== undefined) { try { const date = new Date(timestamps[i]); const hour = date.getUTCHours(); if (hour >= 0 && hour < 24) { const numVal = Number(val); hourlyVals[hour] = numVal; } } catch { // Ignore parse errors } } } newObs[wigosId] = hourlyVals; } }); } if (abortController.signal.aborted) return; // Apply the shared bounds for the selected accumulation duration. const filteredObs = filterMapObservations(newObs, selectedHour, isPrecipitation ? `precipitation${precipitationHours}h` : parameter); isPendingIdleSyncRef.current = true; setObservations(filteredObs); setRainfallStationIds(rainfallIds); setPeriodAvailability(json.precipitationAvailability && json.availabilityComplete !== false ? { key: requestKey, periods: json.precipitationAvailability } : null); setActiveObservationKey(requestKey); // Show banner when the live API is completely unreachable if (json.apiUnavailable) { setErrorMsg("Connection to the MeteoGate live API is currently not possible. Data is available only for the historical period."); } if (isPrecipitation && json.availabilityComplete === false && !json.apiUnavailable) { setErrorMsg("Some precipitation sources could not be loaded. Availability is incomplete."); } } catch (error: unknown) { if (getErrorName(error) === "AbortError") return; clearFallbackTimer(); console.error("[Map] Fetch observations failed:", error); setObservations({}); setActiveObservationKey(""); setErrorMsg(isPrecipitation ? "Could not load precipitation for the selected period. Try another time or period." : "Connection to the MeteoGate live API is currently not possible. Data is available only for the historical period."); setIsLoading(false); } }; const timer = window.setTimeout(fetchObservations, OBSERVATION_FETCH_DEBOUNCE_MS); return () => { abortController.abort(); window.clearTimeout(timer); isPendingIdleSyncRef.current = false; clearIdleSync(); clearFallbackTimer(); }; }, [stations, parameter, endDate, selectedHour, observationRequestKey, isPrecipitation, precipitationHours, setObservations, clearIdleSync, clearFallbackTimer]); // ── Build GeoJSON from current refs (always reads latest values) ── const buildGeoJSON = useCallback((): GeoJSON.FeatureCollection => { const features: GeoJSON.Feature[] = []; if (activeObservationKey !== observationRequestKey) { return { type: "FeatureCollection", features }; } for (const st of stations) { const hourlyVals = observations[st.id] || []; const hourVal = hourlyVals[selectedHour] ?? NaN; if (!Number.isFinite(hourVal)) continue; const value = Math.round(hourVal * 10) / 10; const isSelected = st.id === selectedStation; const isZeroPrecipitation = parameter.includes("precipitation") && hourVal === 0; features.push({ type: "Feature" as const, geometry: { type: "Point" as const, coordinates: [st.longitude, st.latitude] }, properties: { id: st.id, name: st.name, country: st.country, elevation: st.elevation, color: getColorFromPalette(hourVal, parameter), opacity: isZeroPrecipitation ? PRECIPITATION_ZERO_STYLE.opacity : 0.92, isZeroPrecipitation, renderOrder: isSelected ? 2 : parameter.includes("precipitation") && hourVal > 0 ? 1 : 0, label: formatMapValue(hourVal, parameter), value, precipitationHours: parameter.includes("precipitation") ? precipitationHours : null, sourceParameter: rainfallStationIds.has(st.id) ? "rainfall_amount" : parameter, selected: isSelected ? 1 : 0 } }); } // Draw positive precipitation above zero reports, with the selected station on top. features.sort((a, b) => (a.properties?.renderOrder || 0) - (b.properties?.renderOrder || 0)); return { type: "FeatureCollection", features }; }, [ activeObservationKey, observationRequestKey, stations, observations, selectedHour, selectedStation, parameter, precipitationHours, rainfallStationIds ]); // ── Calculate statistics for stations currently visible on screen ── const visibleStats = useMemo(() => { if (!visibleBounds || activeObservationKey !== observationRequestKey) { return null; } let minVal = Infinity; let maxVal = -Infinity; let minStation: Station | null = null; let maxStation: Station | null = null; let sum = 0; let count = 0; for (const st of stations) { if ( st.longitude >= visibleBounds.getWest() && st.longitude <= visibleBounds.getEast() && st.latitude >= visibleBounds.getSouth() && st.latitude <= visibleBounds.getNorth() ) { const val = observations[st.id]?.[selectedHour]; if (val !== undefined && val !== null && !isNaN(val)) { sum += val; count++; if (val < minVal) { minVal = val; minStation = st; } if (val > maxVal) { maxVal = val; maxStation = st; } } } } if (count === 0) { return null; } return { count, avg: sum / count, min: minVal, max: maxVal, minStation, maxStation }; }, [visibleBounds, activeObservationKey, observationRequestKey, stations, observations, selectedHour]); // ── Add source and layers to the map ── const addSourceAndLayers = useCallback(() => { const m = map.current; if (!m) return; // Remove existing layers/source if present try { if (m.getLayer(TEXT_LAYER)) m.removeLayer(TEXT_LAYER); } catch {} try { if (m.getLayer(SELECTED_LAYER)) m.removeLayer(SELECTED_LAYER); } catch {} try { if (m.getLayer(CIRCLE_LAYER)) m.removeLayer(CIRCLE_LAYER); } catch {} try { if (m.getSource(SOURCE_ID)) m.removeSource(SOURCE_ID); } catch {} const geojson = buildGeoJSON(); m.addSource(SOURCE_ID, { type: "geojson", data: geojson }); // Find the first symbol/label layer to insert our stations beneath let firstLabelId: string | undefined; const layers = m.getStyle()?.layers || []; for (const layer of layers) { if (layer.type === "symbol" && layer.id.includes("label")) { firstLabelId = layer.id; break; } } // Main circle layer — colored by the data-driven `color` property m.addLayer({ id: CIRCLE_LAYER, type: "circle", source: SOURCE_ID, layout: { "circle-sort-key": ["get", "renderOrder"] }, paint: { "circle-radius": [ "interpolate", ["linear"], ["zoom"], 2, 4, 5, 7, 8, 10, 12, 14 ], "circle-color": ["get", "color"], "circle-stroke-width": [ "case", ["==", ["get", "selected"], 1], 3, ["get", "isZeroPrecipitation"], PRECIPITATION_ZERO_STYLE.strokeWidth, 0 ], "circle-stroke-color": [ "case", ["==", ["get", "selected"], 1], "#1e293b", ["get", "isZeroPrecipitation"], PRECIPITATION_ZERO_STYLE.strokeColor, "#1e293b" ], "circle-opacity": ["get", "opacity"], "circle-stroke-opacity": [ "case", ["==", ["get", "selected"], 1], 1, ["get", "isZeroPrecipitation"], PRECIPITATION_ZERO_STYLE.strokeOpacity, 1 ] } }, firstLabelId); // Selected ring highlight layer m.addLayer({ id: SELECTED_LAYER, type: "circle", source: SOURCE_ID, filter: ["==", ["get", "selected"], 1], paint: { "circle-radius": [ "interpolate", ["linear"], ["zoom"], 2, 8, 5, 12, 8, 16, 12, 20 ], "circle-radius-transition": { duration: 300 }, "circle-color": "transparent", "circle-stroke-width": 4, "circle-stroke-color": ["get", "color"], "circle-stroke-opacity": 0.45, "circle-stroke-opacity-transition": { duration: 300 } } }, firstLabelId); // Text label layer — value inside the circle at higher zoom m.addLayer({ id: TEXT_LAYER, type: "symbol", source: SOURCE_ID, minzoom: 5, layout: { "text-field": ["get", "label"], "symbol-sort-key": ["get", "renderOrder"], "text-size": [ "interpolate", ["linear"], ["zoom"], 5, 8, 8, 10, 12, 12 ], "text-font": ["Open Sans Bold"], "text-allow-overlap": true, "text-ignore-placement": true, "text-anchor": "bottom", "text-offset": [0, -1] }, paint: { "text-color": "#1e293b", "text-halo-color": "rgba(255,255,255,0.85)", "text-halo-width": 1.2 } }, firstLabelId); sourceReadyRef.current = true; }, [buildGeoJSON]); // Ref so the style.load handler always calls the latest version const addSourceAndLayersRef = useRef(addSourceAndLayers); useEffect(() => { addSourceAndLayersRef.current = addSourceAndLayers; }, [addSourceAndLayers]); // ── 2. Initialize MapLibre GL (runs once) ── useEffect(() => { if (!mapContainer.current) return; let isMounted = true; const mapOptions: maplibregl.MapOptions & { projection: { type: "globe" } } = { container: mapContainer.current, style: "https://tiles.openfreemap.org/styles/positron", center: [10, 50], zoom: 3, attributionControl: false, projection: { type: "globe" }, pitchWithRotate: false, dragRotate: false, touchPitch: false, maxPitch: 0 }; map.current = new maplibregl.Map(mapOptions); // Capture map rendering or loading errors map.current.on('error', (e) => { console.error("[Map] MapLibre error:", e); if (isMounted) { setErrorMsg(`Map rendering error: ${e.error?.message || 'Unknown map error'}`); setIsLoading(false); } }); map.current.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-left"); map.current.addControl(new maplibregl.AttributionControl({ compact: true }), "bottom-left"); // Intercept zoom out button click for progressive deselection const zoomOutInterceptor = (e: MouseEvent) => { const target = e.target as HTMLElement; if (target.closest('.maplibregl-ctrl-zoom-out')) { const hasSelectedStation = !!selectedStationValueRef.current; const hasSelectedCountry = !!selectedCountryValueRef.current; if (hasSelectedStation) { e.stopPropagation(); e.preventDefault(); setSelectedStationRef.current(""); } else if (hasSelectedCountry) { e.stopPropagation(); e.preventDefault(); setSelectedCountryRef.current(""); } } }; const currentContainer = mapContainer.current; if (currentContainer) { currentContainer.addEventListener('click', zoomOutInterceptor, true); } let resizeObserver: ResizeObserver | null = null; if (typeof ResizeObserver !== "undefined" && currentContainer) { resizeObserver = new ResizeObserver(() => { if (map.current) { map.current.resize(); if (pendingFitBoundsRef.current) { const container = map.current.getContainer(); if (container && container.clientWidth > 0 && container.clientHeight > 0) { const pending = pendingFitBoundsRef.current; pendingFitBoundsRef.current = null; const compact = container.clientWidth < 640; map.current.fitBounds(pending.bounds, { padding: compact ? { top: 72, right: 24, bottom: 48, left: 24 } : 50, duration: pending.duration, maxZoom: 9 }); } } } }); resizeObserver.observe(currentContainer); } // Collapse the compact attribution on load — only expand on user click map.current.once('load', () => { const attrib = mapContainer.current?.querySelector('.maplibregl-ctrl-attrib'); if (attrib) attrib.classList.remove('maplibregl-compact-show'); }); const updateBounds = () => { if (map.current) { setVisibleBounds(map.current.getBounds()); } }; map.current.on('moveend', updateBounds); map.current.on('zoomend', updateBounds); map.current.once('load', () => { updateBounds(); }); // Create a reusable popup popupRef.current = new maplibregl.Popup({ closeButton: true, closeOnClick: false, offset: 12, maxWidth: "260px" }); // When style loads (initial + basemap change), re-add our data layers map.current.on("style.load", () => { sourceReadyRef.current = false; if (map.current) { map.current.setProjection({ type: "globe" }); } // Add satellite raster if needed (Hybrid mode) const m = map.current; if (m && basemapRef.current === "satellite") { if (!m.getSource("sentinel")) { m.addSource("sentinel", { type: "raster", tiles: ["https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2023_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg"], tileSize: 256, attribution: "Sentinel-2 cloudless by EOX" }); m.addLayer({ id: "sentinel-satellite", type: "raster", source: "sentinel", minzoom: 0, maxzoom: 18 }, m.getStyle().layers[0]?.id); // Hide all opaque background/land/water layers so satellite shows through, // but explicitly keep borders (boundary) and labels (label) const layers = m.getStyle().layers; layers.forEach(layer => { const id = layer.id; // Identify if the layer is a label or a boundary const isLabel = id.includes("label"); const isBoundary = id.includes("boundary"); const isCustom = id === "sentinel-satellite" || id === CIRCLE_LAYER || id === SELECTED_LAYER || id === TEXT_LAYER; if (!isLabel && !isBoundary && !isCustom) { m.setLayoutProperty(id, 'visibility', 'none'); } else if (isBoundary) { // Ensure boundaries are visible over the satellite imagery m.setLayoutProperty(id, 'visibility', 'visible'); // Lighten boundaries slightly so they are visible over dark satellite areas if (m.getLayer(id)?.type === "line") { m.setPaintProperty(id, 'line-color', 'rgba(255, 255, 255, 0.4)'); } } }); } } // Re-apply label visibility based on toggle if (m) { const labelLayers = ["place_label_city", "place_label_town", "place_label_village", "poi_label", "road_label", "water_label"]; labelLayers.forEach(layer => { if (m.getLayer(layer)) { m.setLayoutProperty(layer, 'visibility', showLabelsRef.current ? 'visible' : 'none'); } }); } // Re-add station layers (always uses latest data via ref) addSourceAndLayersRef.current(); // Trigger idle sync if there are pending observations waiting to render if (m) { triggerIdleSyncRef.current(m); } }); // ── Hover: change cursor + show popup ── map.current.on("mouseenter", CIRCLE_LAYER, (e) => { const m = map.current; if (!m) return; m.getCanvas().style.cursor = "pointer"; const feature = e.features?.[0]; if (!feature || !feature.properties) return; const coords = getPointCoordinates(feature.geometry as GeoJSON.Geometry); if (!coords) return; const props = feature.properties; const param = parameterRef.current; // always fresh popupRef.current ?.setLngLat(coords) .setDOMContent(buildStationHoverPopupContent(props, param)) .addTo(m); }); map.current.on("mouseleave", CIRCLE_LAYER, () => { const m = map.current; if (!m) return; m.getCanvas().style.cursor = ""; popupRef.current?.remove(); }); let isDragging = false; let lastDragEndTime = 0; let lastStationClickedTime = 0; let lastDeselectionTime = 0; map.current.on("dragstart", () => { isDragging = true; }); map.current.on("dragend", () => { isDragging = false; lastDragEndTime = Date.now(); }); // ── Click: select station (camera flyTo handled reactively by useEffect) ── const handleStationFeatureClick = (e: maplibregl.MapLayerMouseEvent) => { const feature = e.features?.[0]; if (!feature || !feature.properties) return; const stationId = feature.properties.id; if (!stationId) return; lastStationClickedTime = Date.now(); if (e.originalEvent) { (e.originalEvent as unknown as { _stationClicked?: boolean })._stationClicked = true; } setSelectedStationRef.current(stationId); if (onStationClickRef.current) { onStationClickRef.current(stationId); } }; map.current.on("click", CIRCLE_LAYER, handleStationFeatureClick); map.current.on("click", TEXT_LAYER, handleStationFeatureClick); map.current.on("click", SELECTED_LAYER, handleStationFeatureClick); // ── Hover on SELECTED_LAYER: show pointer cursor ── map.current.on("mouseenter", SELECTED_LAYER, () => { const m = map.current; if (!m) return; m.getCanvas().style.cursor = "pointer"; }); map.current.on("mouseleave", SELECTED_LAYER, () => { const m = map.current; if (!m) return; m.getCanvas().style.cursor = ""; }); // ── Prevent double-click zoom from fighting camera reset on deselection ── map.current.on("dblclick", (e) => { if (Date.now() - lastDeselectionTime < 600) { e.preventDefault(); } }); // ── Click on map canvas: if clicking empty space (outside station circles/markers), deselect station ── map.current.on("click", (e) => { if (!map.current) return; // Do not deselect while or immediately after dragging/panning the map if (isDragging || Date.now() - lastDragEndTime < 200) { return; } // Do not deselect if a station marker was clicked in this event or within 200ms const origEvent = e.originalEvent as unknown as { _stationClicked?: boolean } | undefined; if (origEvent?._stationClicked || Date.now() - lastStationClickedTime < 200) { return; } const target = e.originalEvent?.target as HTMLElement | null; if (target && target.tagName !== "CANVAS") { return; } // Check with a 4px bounding box to avoid deselecting when clicking near a station circle const activeLayers = [CIRCLE_LAYER, TEXT_LAYER, SELECTED_LAYER].filter((id) => map.current?.getLayer(id)); const bbox: [maplibregl.PointLike, maplibregl.PointLike] = [ [e.point.x - 4, e.point.y - 4], [e.point.x + 4, e.point.y + 4], ]; const features = map.current.queryRenderedFeatures(bbox, { layers: activeLayers }); if (features && features.length > 0) { return; // Click was on or adjacent to a station marker } if (selectedStationValueRef.current) { lastDeselectionTime = Date.now(); setSelectedStationRef.current(""); } }); return () => { isMounted = false; clearIdleSync(); clearFallbackTimer(); resizeObserver?.disconnect(); popupRef.current?.remove(); popupRef.current = null; if (currentContainer) { currentContainer.removeEventListener('click', zoomOutInterceptor, true); } map.current?.remove(); map.current = null; sourceReadyRef.current = false; }; }, [clearIdleSync, clearFallbackTimer]); // Runs once // ── 3. Handle basemap changes ── const initialBasemapRef = useRef(true); useEffect(() => { if (!map.current) return; // On initial mount, the map constructor already sets the style. // Calling setStyle again would destroy our source/layers and cause a race condition. if (initialBasemapRef.current) { initialBasemapRef.current = false; return; } // For satellite, we use 'positron' as the base to get all the vector boundaries/labels const styleUrl = basemap === "satellite" || basemap === "positron" ? "https://tiles.openfreemap.org/styles/positron" : "https://tiles.openfreemap.org/styles/bright"; map.current.setStyle(styleUrl); }, [basemap]); // ── 3b. Sync Label Visibility without full style reload ── useEffect(() => { if (!map.current) return; const applyLabelVisibility = () => { if (!map.current || !map.current.isStyleLoaded()) return; const style = map.current.getStyle(); if (style && style.layers) { style.layers.forEach(layer => { if (layer.id.includes('label') && layer.id !== TEXT_LAYER) { map.current?.setLayoutProperty(layer.id, 'visibility', showLabels ? 'visible' : 'none'); } }); } }; if (map.current.isStyleLoaded()) { applyLabelVisibility(); } map.current.on('style.load', applyLabelVisibility); return () => { map.current?.off('style.load', applyLabelVisibility); }; }, [showLabels]); // ── 4. Update GeoJSON source data reactively ── useEffect(() => { const m = map.current; if (!m) return; const tryUpdate = () => { if (!sourceReadyRef.current) { return false; } const source = m.getSource(SOURCE_ID) as maplibregl.GeoJSONSource; if (!source) { return false; } const geojson = buildGeoJSON(); source.setData(geojson); return true; }; const updated = tryUpdate(); if (updated) { triggerIdleSync(m); } }, [stations, observations, selectedHour, parameter, selectedStation, buildGeoJSON, triggerIdleSync]); // ── 5. Zoom to Selected Country or Station Centroid ── const prevResetMapViewRef = useRef(resetMapView); const hasInitialFitRef = useRef(false); const prevStationRef = useRef(selectedStation); const prevCountryRef = useRef(selectedCountry); useEffect(() => { if (!map.current || stations.length === 0) return; const isResetTriggered = resetMapView !== prevResetMapViewRef.current; prevResetMapViewRef.current = resetMapView; const prevStation = prevStationRef.current; const prevCountry = prevCountryRef.current; prevStationRef.current = selectedStation; prevCountryRef.current = selectedCountry; const isStationCleared = prevStation && !selectedStation; const isCountryCleared = prevCountry && !selectedCountry; const countryChanged = prevCountry !== selectedCountry; const fitStationsBounds = (stList: typeof stations, duration: number = 1500) => { if (!map.current || stList.length === 0) return; map.current.stop(); map.current.resize(); const bounds = computeStationBounds(stList); if (!bounds) return; const container = map.current.getContainer(); if (!container || container.clientWidth === 0 || container.clientHeight === 0) { pendingFitBoundsRef.current = { bounds, duration }; let frames = 0; const checkFrame = () => { if (!map.current || !pendingFitBoundsRef.current) return; map.current.resize(); const validContainer = map.current.getContainer(); if (validContainer && validContainer.clientWidth > 0 && validContainer.clientHeight > 0) { const pending = pendingFitBoundsRef.current; pendingFitBoundsRef.current = null; const compact = validContainer.clientWidth < 640; map.current.stop(); map.current.fitBounds(pending.bounds, { padding: compact ? { top: 72, right: 24, bottom: 48, left: 24 } : 50, duration: pending.duration, maxZoom: 9 }); return; } if (++frames < 10) { requestAnimationFrame(checkFrame); } }; requestAnimationFrame(checkFrame); return; } pendingFitBoundsRef.current = null; const compact = container.clientWidth < 640; map.current.fitBounds( bounds, { padding: compact ? { top: 72, right: 24, bottom: 48, left: 24 } : 50, duration, maxZoom: 9 } ); }; const euroStations = stations.filter(isEuropeanStation); if (isResetTriggered) { fitStationsBounds(euroStations.length > 0 ? euroStations : stations, 1200); hasInitialFitRef.current = true; } else if (isStationCleared) { if (selectedCountry) { const countryStations = stations.filter((st) => countryMatches(st.country, selectedCountry)); const euroCountryStations = countryStations.filter(isEuropeanStation); const targetStations = euroCountryStations.length > 0 ? euroCountryStations : countryStations; if (targetStations.length > 0) { fitStationsBounds(targetStations, 1200); } } else { fitStationsBounds(euroStations.length > 0 ? euroStations : stations, 1200); } popupRef.current?.remove(); hasInitialFitRef.current = true; } else if (selectedStation) { const activeSt = stations.find((st) => st.id === selectedStation); if (activeSt) { map.current.stop(); map.current.flyTo({ center: [activeSt.longitude, activeSt.latitude], zoom: 7.5, duration: 800, essential: true }); } hasInitialFitRef.current = true; } else if (isCountryCleared) { fitStationsBounds(euroStations.length > 0 ? euroStations : stations, 1200); hasInitialFitRef.current = true; } else if (selectedCountry) { if (countryChanged || !hasInitialFitRef.current) { const countryStations = stations.filter((st) => countryMatches(st.country, selectedCountry)); const euroCountryStations = countryStations.filter(isEuropeanStation); const targetStations = euroCountryStations.length > 0 ? euroCountryStations : countryStations; if (targetStations.length > 0) { fitStationsBounds(targetStations, 1200); } hasInitialFitRef.current = true; } } else { if (!hasInitialFitRef.current) { map.current.flyTo({ center: [10, 50], zoom: 3, duration: 0, essential: true }); hasInitialFitRef.current = true; } } }, [selectedCountry, selectedStation, stations, resetMapView]); const handleHomeClick = () => { if (selectedStationValueRef.current) { setSelectedStationRef.current(""); } else if (selectedCountryValueRef.current) { setSelectedCountryRef.current(""); } else { if (onResetMap) onResetMap(); } }; const selectedStationMeta = useMemo(() => { if (!selectedStation) return null; const found = stations.find((st) => st.id === selectedStation); if (found) return found; return { id: selectedStation, name: selectedStation, country: "", latitude: 0, longitude: 0, elevation: null, }; }, [stations, selectedStation]); return ( <div className="relative w-full h-full flex flex-col min-h-0"> {/* Interactive Map Canvas Container */} <div ref={mapContainer} className="flex-1 w-full h-full min-h-0 bg-slate-50" /> {/* Floating Station Selection Chip */} {selectedStationMeta && ( <div className="absolute top-[130px] lg:top-[76px] left-1/2 -translate-x-1/2 md:left-[calc(50%-87px)] xl:left-1/2 z-20 pointer-events-auto max-w-[calc(100%-1.5rem)]"> <div className="station-floating-chip bg-slate-800/90 text-white border-slate-700/60 md:bg-white/95 md:text-slate-800 md:border-slate-200 border"> <span className="chip-dot" /> <Tooltip content={`${selectedStationMeta.name} (${selectedStationMeta.id})${selectedStationMeta.elevation != null && !isNaN(selectedStationMeta.elevation) ? ` • ${Math.round(selectedStationMeta.elevation)} m` : ""}${selectedStationMeta.country ? ` • ${selectedStationMeta.country}` : ""}`} position="bottom" > <span className="chip-text text-slate-100 md:text-slate-800"> {selectedStationMeta.name} - {selectedStationMeta.id} {selectedStationMeta.elevation != null && !isNaN(selectedStationMeta.elevation) ? ` (${Math.round(selectedStationMeta.elevation)} m)` : ""} </span> </Tooltip> <button type="button" onClick={(e) => { e.stopPropagation(); setSelectedStation(""); }} onTouchStart={(e) => e.stopPropagation()} onPointerDown={(e) => e.stopPropagation()} className="btn-chip-clear" aria-label="Deselect station" > <X size={12} className="shrink-0" /> <span>Deselect</span> </button> </div> </div> )} {/* Home Button */} <div className="absolute top-[80px] left-2.5 z-10 hidden sm:block"> <Tooltip content="Zoom to All Stations" position="right"> <button onClick={handleHomeClick} className="p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center bg-white shadow-sm border border-slate-200 rounded-md text-slate-600 hover:bg-slate-50 transition-colors" > <Home size={20} /> </button> </Tooltip> </div> {/* Map Legend */} <MapLegend parameter={parameter} values={visibleStats ? [visibleStats.min, visibleStats.max] : currentValues} precipitationHours={precipitationHours} setPrecipitationHours={setPrecipitationHours} noReports={isPrecipitation && activeObservationKey === observationRequestKey && !errorMsg && (periodCounts ? periodCounts[precipitationHours] === 0 : currentValues.length === 0)} periodCounts={periodCounts} availabilityScope={selectedCountry || "All countries"} rainfallReportCount={rainfallReportCount} /> {/* Visible Extent Summary Cards */} {visibleStats && ( <div className="absolute top-3 right-2.5 z-10 hidden md:flex flex-col gap-2 max-w-[200px]"> <details className="group bg-white/95 backdrop-blur-md border border-slate-200 rounded-xl shadow-lg flex flex-col transition-all duration-200 marker:content-['']" open={isStatsExpanded} onToggle={(e) => setIsStatsExpanded(e.currentTarget.open)} > <summary className="p-3 text-[11px] font-bold text-slate-700 uppercase tracking-wider flex items-start justify-between gap-2 cursor-pointer border-slate-100 group-open:border-b group-open:pb-1.5 list-none [&::-webkit-details-marker]:hidden"> <div className="flex flex-col leading-tight gap-0.5"> <span className="break-words leading-tight"> {({ air_temperature: "Air Temperature", precipitation_amount: "Precipitation", air_pressure_at_mean_sea_level: "Sea Level Pressure", wind_speed: "Wind Speed", }[parameter] || parameter.replace(/_/g, ' ').replace(/([A-Z])/g, ' $1').trim())}{isPrecipitation ? ` · ${precipitationHours} h` : ""} </span> <span tabIndex={0} className="text-[9px] text-slate-400 tracking-normal normal-case font-medium flex items-center gap-1 cursor-help relative hover-tooltip focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-blue-500 rounded px-0.5" aria-label="Information about Screen Extent statistics" > {isPrecipitation ? "Reporting stations in view" : "Screen Extent"} <Info size={10} className="text-slate-400" /> <span className="tooltip-content pointer-events-none opacity-0 transition-opacity duration-200 absolute right-0 top-full mt-1 z-50 w-52 rounded-lg border border-slate-200 bg-white px-3 py-2 text-[10px] font-medium leading-relaxed text-slate-600 shadow-lg normal-case tracking-normal"> These aggregated statistics dynamically update to only include the stations currently visible within the map boundaries. </span> </span> </div> <div className="flex items-center gap-1.5 mt-0.5"> <span className="bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded text-[9px] shrink-0">{visibleStats.count} stn</span> <div className="text-slate-400 bg-slate-50 rounded-md p-0.5 hover:bg-slate-100 hover:text-slate-600 transition-colors"> <ChevronDown size={14} className="group-open:rotate-180 transition-transform" /> </div> </div> </summary> <div className="p-3 pt-1.5 flex flex-col animate-in fade-in duration-200"> <div className="flex justify-between items-center gap-2"> <span className="text-[10px] font-semibold text-slate-500 uppercase"> {isPrecipitation ? "Station mean" : "Average"} </span> <span className="shrink-0 text-sm font-bold text-slate-800"> {isPrecipitation ? formatMapValue(visibleStats.avg, parameter) : visibleStats.avg.toFixed(1)} {getUnitForParam(parameter)} </span> </div> <div className="flex flex-col gap-0.5 mt-1 pt-1.5 border-t border-slate-50"> <div className="flex justify-between items-start gap-3"> <span className="text-[10px] font-semibold text-red-500/80 uppercase">{isPrecipitation ? "Station max" : "Max"}</span> <div className="flex flex-col items-end"> <span className="text-sm font-bold text-slate-800"> {isPrecipitation ? formatMapValue(visibleStats.max, parameter) : visibleStats.max.toFixed(1)} {getUnitForParam(parameter)} </span> {visibleStats.maxStation && ( <span className="text-[9px] font-medium text-slate-500 text-right break-words leading-tight"> {visibleStats.maxStation.name}, {visibleStats.maxStation.country} </span> )} </div> </div> </div> <div className="flex flex-col gap-0.5 mt-1 pt-1.5 border-t border-slate-50"> <div className="flex justify-between items-start gap-3"> <span className="text-[10px] font-semibold text-blue-500/80 uppercase">{isPrecipitation ? "Station min" : "Min"}</span> <div className="flex flex-col items-end"> <span className="text-sm font-bold text-slate-800"> {isPrecipitation ? formatMapValue(visibleStats.min, parameter) : visibleStats.min.toFixed(1)} {getUnitForParam(parameter)} </span> {visibleStats.minStation && ( <span className="text-[9px] font-medium text-slate-500 text-right break-words leading-tight"> {visibleStats.minStation.name}, {visibleStats.minStation.country} </span> )} </div> </div> </div> </div> </details> </div> )} {/* Map Styles Layer selector */} <div className="absolute top-[130px] left-2.5 z-10 hidden sm:flex flex-col gap-1"> <Tooltip content="Map Styles" position="right"> <button popoverTarget="map-styles-menu" className="p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center bg-white shadow-sm border border-slate-200 rounded-md text-slate-600 hover:bg-slate-50 transition-colors cursor-pointer" > <Layers size={20} /> </button> </Tooltip> <div id="map-styles-menu" popover="auto" className="bg-white/95 backdrop-blur-md border border-slate-200 rounded-xl p-3.5 shadow-lg flex-col gap-2.5 w-[200px] m-0 fixed top-[130px] left-[64px]"> <h4 className="text-xs font-bold text-slate-700 uppercase tracking-wider flex items-center gap-1.5 border-b border-slate-100 pb-1.5"> <Layers size={14} className="text-slate-500" /> Map Styles </h4> <div className="flex flex-col gap-2"> {[ { id: "positron", label: "OpenFreeMap Positron" }, { id: "bright", label: "OpenFreeMap Bright" }, { id: "satellite", label: "Satellite Imagery" } ].map((item) => ( <label key={item.id} className="flex items-center gap-2 text-xs font-semibold text-slate-600 hover:text-slate-800 cursor-pointer"> <input type="radio" name="basemap" checked={basemap === item.id} onChange={() => { setBasemap(item.id); // Automatically close the popover when a new base style is chosen document.getElementById("map-styles-menu")?.hidePopover(); }} className="text-blue-500 focus:ring-blue-400" /> {item.label} </label> ))} <div className="border-t border-slate-100 mt-1 pt-2"> <label className="flex items-center gap-2 text-xs font-semibold text-slate-600 cursor-pointer"> <input type="checkbox" checked={showLabels} onChange={(e) => setShowLabels(e.target.checked)} className="text-blue-500 rounded focus:ring-blue-400" /> Show Labels </label> </div> </div> </div> </div> {/* Error/Bypass Alert Banner */} {errorMsg && ( <div className="absolute top-[132px] lg:top-20 left-2 right-2 z-20 flex items-center gap-3 rounded-xl border border-amber-200 bg-amber-50/95 p-3 shadow-md backdrop-blur-md md:left-4 md:right-4"> <ShieldAlert className="text-amber-500 shrink-0" size={20} /> <p className="text-xs font-semibold text-amber-700 leading-normal">{errorMsg}</p> </div> )} {/* Loading Overlay Spinner — unified for stations loading and data fetching */} {(isLoadingStations || isLoading) && ( <div className="absolute inset-0 z-40 bg-slate-50/40 backdrop-blur-[2px] flex items-center justify-center pointer-events-none transition-all duration-300"> <div className="flex flex-col items-center gap-3 bg-white/95 p-5 rounded-2xl shadow-xl border border-slate-200 pointer-events-auto"> <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin" /> <p className="text-xs font-bold text-slate-600 uppercase tracking-wider animate-pulse"> {isLoadingStations ? "Loading Stations..." : "Fetching Data..."} </p> </div> </div> )} {/* Timeline slider control panel at bottom of map (unified pill design) */} <div className="absolute bottom-3 md:bottom-6 left-1/2 -translate-x-1/2 w-max rounded-full z-10 bg-slate-800/80 md:bg-white/95 backdrop-blur-md border border-slate-700/50 md:border-slate-200 p-1 md:p-0 shadow-xl flex items-center md:overflow-hidden"> <div className="flex justify-between items-center text-sm font-bold w-full"> <button onClick={() => setSelectedHour(prev => Math.max(0, prev - 1))} disabled={selectedHour <= 0} aria-label="Step backwards" className="w-12 h-12 md:w-10 md:h-10 flex items-center justify-center text-slate-300 md:text-slate-600 disabled:opacity-50 flex-shrink-0 hover:text-white md:hover:text-slate-900 hover:bg-white/10 md:hover:bg-slate-100 rounded-full md:rounded-none active:scale-95 transition-all" > <StepBack size={18} /> </button> <div className="text-white md:text-slate-700 border-x border-white/20 md:border-slate-200 px-4 md:px-5 py-2 md:h-10 flex items-center justify-center gap-1.5 truncate text-xs sm:text-sm"> <Clock size={14} className="opacity-70 mt-[-1px]" /> <span className={isPrecipitation ? "flex flex-col items-center leading-tight" : undefined}> {isPrecipitation && <span className="text-[10px] font-semibold">{precipitationHours}-hour reported total</span>} {new Date(`${endDate}T00:00:00Z`).toLocaleDateString("en-GB", { day: "2-digit", month: "short", timeZone: "UTC" })}, {selectedHour.toString().padStart(2, "0")}:00 UTC </span> </div> <button onClick={() => setSelectedHour(prev => Math.min(maxAllowedHour, prev + 1))} disabled={selectedHour >= maxAllowedHour} aria-label="Step forwards" className="w-12 h-12 md:w-10 md:h-10 flex items-center justify-center text-slate-300 md:text-slate-600 disabled:opacity-50 flex-shrink-0 hover:text-white md:hover:text-slate-900 hover:bg-white/10 md:hover:bg-slate-100 rounded-full md:rounded-none active:scale-95 transition-all" > <StepForward size={18} /> </button> </div> </div> </div> ); }; export const WeatherMap = React.memo(WeatherMapComponent);
import React, { useEffect, useRef, useState, useCallback, useMemo } from "react";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import { Layers, ShieldAlert, Home, Info, ChevronDown, StepBack, StepForward, Clock, X } from "lucide-react";
import { formatMapValue, getColorFromPalette, getUnitForParam, PRECIPITATION_ZERO_STYLE } from "@/utils/colors";
import { countryMatches, isEuropeanStation, computeStationBounds } from "@/utils/country";
import { filterMapObservations } from "@/utils/qc";
import { countPrecipitationPeriods, extractPrecipitationObservation, precipitationNumber } from "@/utils/precipitation";
import type { PrecipitationAvailability, PrecipitationHours, PrecipitationParameter } from "@/utils/precipitation";
import { MapLegend } from "./MapLegend";
import { Tooltip } from "./Tooltip";
interface Station {
id: string;
name: string;
country: string;
longitude: number;
latitude: number;
elevation: number | null;
available_params: string;
}
interface MapProps {
stations: Station[];
selectedCountry: string;
selectedStation: string;
setSelectedStation: (stationId: string) => void;
setSelectedCountry: (country: string) => void;
parameter: string;
precipitationHours: PrecipitationHours;
setPrecipitationHours: (hours: PrecipitationHours) => void;
startDate: string;
endDate: string;
observations: Record<string, number[]>;
setObservations: (obs: Record<string, number[]>) => void;
selectedHour: number;
setSelectedHour: (hour: number | ((prev: number) => number)) => void;
isLoadingStations?: boolean;
onStationClick?: (stationId: string) => void;
resetMapView?: number;
onResetMap?: () => void;
}
interface AreaObservation {
stationId: string;
value: number;
sourceParameter?: "rainfall_amount";
}
function buildStationHoverPopupContent(
props: Record<string, unknown>,
param: string
): HTMLDivElement {
const valueDisplay =
props.value !== null && props.value !== undefined
? `${param.includes("precipitation") ? String(props.label ?? props.value) : String(props.value)} ${getUnitForParam(param)}`
: "No data";
const paramLabel = param.includes("precipitation")
? `${props.sourceParameter === "rainfall_amount" ? "Rainfall" : "Precipitation"} (${String(props.precipitationHours ?? "")} h):`
: `${param.replace(/_/g, " ")}:`;
const elevationDisplay =
props.elevation !== null && props.elevation !== undefined && props.elevation !== "null"
? `${String(props.elevation)}m`
: "Unknown";
const container = document.createElement("div");
container.style.cssText = "padding:10px;font-family:system-ui,sans-serif;min-width:170px";
const title = document.createElement("h4");
title.style.cssText = "font-weight:700;color:#1e293b;font-size:13px;margin:0 0 3px 0";
title.textContent = String(props.name ?? "");
container.appendChild(title);
const idEl = document.createElement("p");
idEl.style.cssText = "font-size:10px;color:#64748b;font-weight:500;margin:0 0 8px 0";
idEl.textContent = String(props.id ?? "");
container.appendChild(idEl);
const valueRow = document.createElement("div");
valueRow.style.cssText =
"display:flex;justify-content:space-between;align-items:center;font-size:11px;border-top:1px solid #f1f5f9;padding-top:6px";
const valueLabelSpan = document.createElement("span");
valueLabelSpan.style.cssText = "font-weight:500;color:#94a3b8";
valueLabelSpan.textContent = paramLabel;
const valueValSpan = document.createElement("span");
valueValSpan.style.cssText = "font-weight:700;color:#1e293b";
valueValSpan.textContent = valueDisplay;
valueRow.append(valueLabelSpan, valueValSpan);
container.appendChild(valueRow);
const elevRow = document.createElement("div");
elevRow.style.cssText =
"display:flex;justify-content:space-between;align-items:center;font-size:11px;padding-top:4px";
const elevLabelSpan = document.createElement("span");
elevLabelSpan.style.cssText = "font-weight:500;color:#94a3b8";
elevLabelSpan.textContent = "Elevation:";
const elevValSpan = document.createElement("span");
elevValSpan.style.cssText = "font-weight:500;color:#475569";