eurometeo / src /components /MapLegend.tsx
alexdum's picture
Improve mobile embedded UX with quick parameter switcher and drawer contrast
c9b0d0b
Raw History Blame Contribute Delete
8.66 kB
import React, { useId, useMemo } from "react";
import { getLegendStops, getUnitForParam, PRECIPITATION_ZERO_STYLE } from "@/utils/colors";
import { normalizePrecipitationHours, PRECIPITATION_HOURS } from "@/utils/precipitation";
import type { PrecipitationHours } from "@/utils/precipitation";
interface MapLegendProps {
parameter: string;
values?: number[];
precipitationHours: PrecipitationHours;
setPrecipitationHours: (hours: PrecipitationHours) => void;
noReports?: boolean;
periodCounts?: Record<PrecipitationHours, number> | null;
availabilityScope?: string;
rainfallReportCount?: number;
}
interface LegendStop {
val: number;
color: string;
showLabel: boolean;
}
export const MapLegend: React.FC<MapLegendProps> = ({ parameter, values, precipitationHours, setPrecipitationHours, noReports, periodCounts, availabilityScope = "All countries", rainfallReportCount = 0 }) => {
const allStops = useMemo(() => getLegendStops(parameter), [parameter]);
const unit = getUnitForParam(parameter);
const gradientId = useId();
const periodId = useId();
// Clip legend stops to the value range visible on screen
const stops = useMemo<LegendStop[]>(() => {
if (!values || values.length === 0) {
return allStops;
}
const minVal = Math.min(...values);
const maxVal = Math.max(...values);
// stops are sorted HIGH → LOW (reversed palette)
// Find the range of stops that covers [minVal, maxVal],
// plus one extra stop on each end for the boundary color blocks.
let startIndex = -1;
let endIndex = -1;
for (let i = 0; i < allStops.length; i++) {
// First stop whose value is <= maxVal (upper boundary of visible range)
if (startIndex === -1 && allStops[i].val <= maxVal) {
startIndex = i;
}
// First stop whose value <= minVal (lower boundary of visible range)
if (endIndex === -1 && allStops[i].val <= minVal) {
endIndex = i;
}
}
if (startIndex === -1) startIndex = 0;
if (endIndex === -1) endIndex = allStops.length - 1;
// Add one extra stop above (lower index = higher value) and below
startIndex = Math.max(0, startIndex - 1);
endIndex = Math.min(allStops.length - 1, endIndex + 1);
if (startIndex <= endIndex) {
return allStops.slice(startIndex, endIndex + 1);
}
return allStops;
}, [allStops, values]);
const isTemperature = parameter.includes("temperature");
if (parameter.includes("precipitation")) {
// Keep the full scale fixed as the map changes. Each palette interval is
// equally tall, with sRGB interpolation matching getColorFromPalette.
const ascendingStops = [...allStops].reverse();
return (
<section
aria-label="Precipitation legend"
className="absolute bottom-20 right-2 md:bottom-6 md:right-2.5 z-10 w-36 md:w-40 max-h-[calc(100%_-_212px)] md:max-h-[calc(100%_-_280px)] overflow-y-auto rounded-xl border border-white/20 md:border-slate-200 bg-slate-800/95 md:bg-white/95 p-2 md:p-3 font-sans text-slate-100 md:text-slate-700 shadow-lg backdrop-blur-md"
tabIndex={0}
>
<h3 className="border-b border-white/20 md:border-slate-200 pb-1.5 text-[11px] font-bold">
Precipitation (mm)
</h3>
<label htmlFor={periodId} className="mt-2 block text-[10px] font-semibold">Accumulation period</label>
<select
id={periodId}
name="precipitationHours"
aria-describedby={`${periodId}-help`}
value={precipitationHours}
onChange={event => setPrecipitationHours(normalizePrecipitationHours(event.target.value))}
className="mt-1 min-h-11 w-full rounded-md border border-slate-500 bg-slate-800 px-2 text-xs font-semibold text-white md:border-slate-300 md:bg-white md:text-slate-700 focus-visible:outline-2 focus-visible:outline-blue-500"
>
{PRECIPITATION_HOURS.map(hours => <option key={hours} value={hours}>{hours} {hours === 1 ? "hour" : "hours"}{periodCounts ? ` — ${periodCounts[hours]} reports` : ""}</option>)}
</select>
<p id={`${periodId}-help`} className="mt-1 text-[10px] leading-relaxed text-slate-200 md:text-slate-600">Reported total at selected UTC time.</p>
{periodCounts && <p className="mt-1 text-[10px] font-semibold leading-relaxed">{availabilityScope}: {periodCounts[precipitationHours]} reporting stations</p>}
{noReports && (
<p role="status" className="mt-2 text-[11px] font-semibold leading-relaxed">
No {precipitationHours}-hour reports{availabilityScope !== "All countries" ? ` for ${availabilityScope}` : ""} at this time.
{periodCounts && PRECIPITATION_HOURS.some(hours => periodCounts[hours] > 0)
? ` Available: ${PRECIPITATION_HOURS.filter(hours => periodCounts[hours] > 0).join(", ")} h.` : " Try another UTC time."}
</p>
)}
{rainfallReportCount > 0 && <p className="mt-1 text-[10px] leading-relaxed text-slate-200 md:text-slate-600">Includes {rainfallReportCount} rainfall-only reports.</p>}
<div aria-hidden="true" className="relative my-3 h-32 md:h-36">
<svg className="h-full w-4 md:w-5" preserveAspectRatio="none" viewBox="0 0 20 144">
<defs>
<linearGradient id={gradientId} x1="0" y1="1" x2="0" y2="0" colorInterpolation="sRGB">
{ascendingStops.map((stop, index) => (
<stop key={stop.val} offset={index / (ascendingStops.length - 1)} stopColor={stop.color} />
))}
</linearGradient>
</defs>
<rect width="20" height="144" fill={`url(#${gradientId})`} fillOpacity="0.92" />
</svg>
{allStops.map((stop, index) => (
<span
key={stop.val}
className="absolute left-5 md:left-6 text-[10px] font-semibold leading-none"
style={{ top: `${index / (allStops.length - 1) * 100}%`, transform: "translateY(-50%)" }}
>
{index === 0 ? `≥${stop.val}` : stop.val}
</span>
))}
</div>
<table className="sr-only">
<caption>Continuous precipitation colour scale with uneven value intervals</caption>
<thead><tr><th scope="col">Amount (mm)</th><th scope="col">Colour</th></tr></thead>
<tbody>
{allStops.map((stop, index) => (
<tr key={stop.val}><th scope="row">{index === 0 ? `≥${stop.val}` : stop.val}</th><td>{stop.color}</td></tr>
))}
</tbody>
</table>
<div className="mt-2 flex items-center gap-1.5 border-t border-white/20 md:border-slate-200 pt-2 text-[10px] font-semibold">
<svg aria-hidden="true" className="h-4 w-4 shrink-0" viewBox="0 0 16 16">
<circle cx="8" cy="8" r="5" fill={PRECIPITATION_ZERO_STYLE.color} fillOpacity={PRECIPITATION_ZERO_STYLE.opacity} stroke={PRECIPITATION_ZERO_STYLE.strokeColor} strokeOpacity={PRECIPITATION_ZERO_STYLE.strokeOpacity} strokeWidth={PRECIPITATION_ZERO_STYLE.strokeWidth} />
</svg>
<span>0 mm</span>
</div>
</section>
);
}
return (
<div className="flex absolute bottom-20 right-2 md:bottom-6 md:right-2.5 bg-slate-800/80 md:bg-white/90 backdrop-blur-md p-2 md:p-3 rounded-xl shadow-lg border border-white/20 md:border-slate-200 z-10 font-sans text-xs flex-col text-white md:text-inherit overflow-hidden" style={{ maxHeight: 'calc(100% - 240px)' }}>
<div className="font-bold text-slate-300 md:text-slate-700 text-center text-xs md:text-sm border-b border-white/20 md:border-slate-200 pb-1.5 md:pb-2 mb-1.5 md:mb-2 shrink-0">
{unit}
</div>
<div className="flex flex-col overflow-y-auto overflow-x-hidden min-h-0 pr-6 md:pr-7 pb-2">
{stops.map((stop: LegendStop) => (
<div key={`${stop.val}`} className={`relative ${isTemperature ? 'h-[9px] md:h-[11px]' : 'h-[14px] md:h-[16px]'} shrink-0`}>
<div
className="w-4 md:w-5 h-full"
style={{
backgroundColor: stop.color,
opacity: 0.9,
}}
/>
{stop.showLabel && (
<span
className="absolute left-[18px] md:left-[22px] text-slate-300 md:text-slate-600 font-semibold text-[10px] md:text-[11px] leading-none whitespace-nowrap"
style={{ bottom: 0, transform: 'translateY(50%)' }}
>
{stop.val}
</span>
)}
</div>
))}
</div>
</div>
);
};
MapLegend.displayName = "MapLegend";