import React, {useCallback, useEffect, useRef, useState} from "react";
import {createRoot} from "react-dom/client";
import {Link} from "react-router";
import maplibregl from "maplibre-gl";
import {getSpecies, getSpeciesHere, getSpeciesRange, searchSpecies} from "../api";
import {Button, Select, TextInput} from "./ui";
// The map's species view: what plants and animals have been seen around the middle of the map (or are named
// what was searched), from the downloaded iNaturalist packs; and a species' range, drawn as dots.
// The range is of the app, not of the map: an exported map (PDF) leaves out what starts with this.
export const SPECIES_LAYER_PREFIX = "species-range-";
export const RANGE_SOURCES = {low: `${SPECIES_LAYER_PREFIX}low`, high: `${SPECIES_LAYER_PREFIX}high`};
export const RANGE_LAYERS = {low: `${SPECIES_LAYER_PREFIX}low`, high: `${SPECIES_LAYER_PREFIX}high`};
// Below this zoom the range is the 0.1° grid of every observation; from it, the 0.02° grid of the precise ones.
export const HIGH_ZOOM = 7;
// Map data, not app chrome: one strong color that reads on every basemap.
const DOT_COLOR = "#d9480f";
export const RADII = [10, 30, 100];
const DEFAULT_RADIUS = 30;
// The list follows the map: it is asked again this long after the map stops moving.
const MOVE_DELAY_MS = 400;
// The panel floats over the map (z-index 1002); its dropdowns open above it.
const DROPDOWN = {zIndex: 1100};
const number = (n) => (n || 0).toLocaleString();
export const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"];
// How many other species a dot's popup lists.
const HERE_LIMIT = 8;
// How often a species was seen in each month of the year: a bar per month, January first.
export function MonthsBar({counts}) {
const most = Math.max(...(counts || []));
if (!counts || most <= 0) return null;
return
{counts.map((count, i) =>
{MONTHS[i][0]}
)}
;
}
// The months (1-12) a species was seen in, as the year's letters with those months marked.
export function MonthsSeen({months}) {
if (!months || months.length === 0) return null;
const seen = new Set(months);
return
;
}
// A dot's popup: the species seen in its square (about 11 km), and the others seen there; one of those can be chosen.
export function SpeciesHerePopup({species, here, onSelect}) {
const self = here.taxon || here.species.find((i) => i.taxon_id === species.taxon_id);
const others = here.species.filter((i) => i.taxon_id !== species.taxon_id);
const more = here.species_count - here.species.length;
return
{species.common_name || species.name}
{self ? `Seen ${number(self.here_count)} times in this square (about 11 km).`
: "Seen in this square (about 11 km)."}
{self && }
{others.length > 0 && <>
Also seen here
{others.map((i) => )}
{more > 0 &&
and {number(more)} more species
}
>}
;
}
// A range as the API sends it ({grid, deltas}: the sorted cells of a grid as differences, cells numbered row by row
// from the south-west corner of the world) as GeoJSON points, one at the middle of each cell. The browser does this
// so the WROLPi does not have to.
export function rangeGeoJSON(range) {
const features = [];
if (range?.deltas) {
const grid = range.grid;
const columns = Math.round(360 / grid);
let cell = 0;
for (const delta of range.deltas) {
cell += delta;
const row = Math.floor(cell / columns);
const lat = row * grid - 90 + grid / 2;
const lon = (cell - row * columns) * grid - 180 + grid / 2;
features.push({type: "Feature", properties: {},
geometry: {type: "Point", coordinates: [Math.round(lon * 1e4) / 1e4, Math.round(lat * 1e4) / 1e4]}});
}
}
return {type: "FeatureCollection", features};
}
// The circle layers of a range. A species with no precise observation has no high grid: its low grid is drawn at
// every zoom.
export function rangeLayers(hasHigh) {
const paint = {
"circle-color": DOT_COLOR,
"circle-opacity": 0.8,
"circle-stroke-color": "#ffffff",
"circle-stroke-width": 0.5,
"circle-radius": ["interpolate", ["linear"], ["zoom"], 0, 1.5, 4, 2.5, 7, 4, 12, 6],
};
const low = {id: RANGE_LAYERS.low, type: "circle", source: RANGE_SOURCES.low, paint};
if (!hasHigh) return [low];
return [
{...low, maxzoom: HIGH_ZOOM},
{id: RANGE_LAYERS.high, type: "circle", source: RANGE_SOURCES.high, minzoom: HIGH_ZOOM, paint},
];
}
// "Zoom to range" fits the cluster of dots nearest the middle of the map: dots in touching squares this many degrees
// across (about 220 km) are one cluster. A species planted far from its home (giant sequoias in Britain) is drawn
// everywhere, but zooms to the place being looked at; one spread across a continent is one cluster.
const CLUSTER_DEGREES = 2;
const CLUSTER_COLUMNS = 360 / CLUSTER_DEGREES;
// The least room (pixels) "Zoom to range" leaves for the range beside or above the panel.
const MIN_FIT = 80;
// The dots' clusters: groups of [lon, lat] whose CLUSTER_DEGREES squares touch, also across the antimeridian.
export function rangeClusters(points) {
const squares = new Map();
for (const point of points) {
const column = Math.floor((point[0] + 180) / CLUSTER_DEGREES) % CLUSTER_COLUMNS;
const row = Math.floor((point[1] + 90) / CLUSTER_DEGREES);
const key = `${row},${column}`;
if (!squares.has(key)) squares.set(key, {row, column, points: []});
squares.get(key).points.push(point);
}
const clusters = [];
const seen = new Set();
for (const [key, first] of squares) {
if (seen.has(key)) continue;
seen.add(key);
const cluster = [];
const stack = [first];
while (stack.length) {
const square = stack.pop();
cluster.push(...square.points);
for (let dRow = -1; dRow <= 1; dRow++) {
for (let dColumn = -1; dColumn <= 1; dColumn++) {
const column = (square.column + dColumn + CLUSTER_COLUMNS) % CLUSTER_COLUMNS;
const next = `${square.row + dRow},${column}`;
if (squares.has(next) && !seen.has(next)) {
seen.add(next);
stack.push(squares.get(next));
}
}
}
}
clusters.push(cluster);
}
return clusters;
}
// About how far apart two [lon, lat] are, in degrees of latitude; enough to say which is nearer.
function distance([lon1, lat1], [lon2, lat2]) {
const dLon = Math.abs(lon1 - lon2) % 360;
const across = Math.min(dLon, 360 - dLon) * Math.cos(((lat1 + lat2) / 2) * Math.PI / 180);
return Math.hypot(across, lat1 - lat2);
}
// [[west, south], [east, north]] of points, the short way around: a span across the antimeridian has its east past
// 180 (west 170, east 190), which MapLibre fits as one span.
function pointsBounds(points) {
const lats = points.map((p) => p[1]).sort((a, b) => a - b);
const lons = points.map((p) => p[0]).sort((a, b) => a - b);
// The span is the circle of longitudes less its largest empty gap; the gap across ±180 is the usual one.
let start = 0;
let largest = lons[0] + 360 - lons[lons.length - 1];
for (let i = 1; i < lons.length; i++) {
if (lons[i] - lons[i - 1] > largest) {
largest = lons[i] - lons[i - 1];
start = i;
}
}
const arc = [...lons.slice(start), ...lons.slice(0, start).map((lon) => lon + 360)];
return [[arc[0], lats[0]], [arc[arc.length - 1], lats[lats.length - 1]]];
}
// The bounds of the cluster of a range's dots nearest `center` ([lon, lat]); null when it has no dots.
export function rangeBounds(features, center) {
const points = (features || []).map((f) => f.geometry.coordinates);
if (points.length === 0) return null;
let nearest = null;
let nearestDistance = Infinity;
for (const cluster of rangeClusters(points)) {
const away = center ? Math.min(...cluster.map((point) => distance(point, center))) : 0;
if (away < nearestDistance) {
nearest = cluster;
nearestDistance = away;
}
}
return pointsBounds(nearest);
}
function eraseRange(map) {
try {
Object.values(RANGE_LAYERS).forEach((id) => map.getLayer(id) && map.removeLayer(id));
Object.values(RANGE_SOURCES).forEach((id) => map.getSource(id) && map.removeSource(id));
} catch (e) {
// The map is gone.
}
}
function drawRange(map, range) {
eraseRange(map);
if (!range) return;
const hasHigh = range.high?.features?.length > 0;
map.addSource(RANGE_SOURCES.low, {type: "geojson", data: range.low});
if (hasHigh) map.addSource(RANGE_SOURCES.high, {type: "geojson", data: range.high});
rangeLayers(hasHigh).forEach((layer) => map.addLayer(layer));
}
// How many times a species was seen near the middle of the map.
export function NearBadge({species}) {
if (species.near_count === null || species.near_count === undefined) return null;
const near = species.near_count > 0;
return {near ? `${number(species.near_count)} nearby` : "Not nearby"};
}
function SpeciesName({species}) {
return <>
{species.common_name || species.name}
{species.common_name &&
{species.name}
}
>;
}
function SpeciesRow({species, onSelect}) {
const near = species.near_count === null || species.near_count === undefined || species.near_count > 0;
return ;
}
// Where to read about a species: its Wikipedia article, a search, or a suggestion to download Wikipedia.
export function WikipediaLink({wikipedia, name}) {
if (wikipedia === undefined) return null;
if (wikipedia === null) {
return
Download Wikipedia to read about {name}.
;
}
if (wikipedia.zim_id) {
return Read in Wikipedia;
}
return Search for {name};
}
// The regions a species was counted in, to say so; the planet pack is every region and is not named.
export const regionNames = (regions) => (regions || []).filter((i) => i !== "planet").join(", ");
function SpeciesDetails({map, species, onBack, onSelect, panelRef}) {
// undefined while loading, null when it could not be had (the request said why).
const [details, setDetails] = useState(undefined);
const [range, setRange] = useState(undefined);
const rangeRef = useRef(null);
useEffect(() => {
let current = true;
// Each is used as it comes: a range is drawn even if the details failed.
getSpecies(species.taxon_id).then((found) => current && setDetails(found || null));
Promise.all([getSpeciesRange(species.taxon_id, "low"), getSpeciesRange(species.taxon_id, "high")])
.then(([low, high]) => current
&& setRange(low ? {low: rangeGeoJSON(low), high: rangeGeoJSON(high)} : null));
return () => {
current = false;
};
}, [species.taxon_id]);
// The range is a layer of the map's style, which a change of style removes: it is put back when the style has
// loaded, and erased when the species is put away.
useEffect(() => {
rangeRef.current = range;
if (map && range) drawRange(map, range);
}, [map, range]);
useEffect(() => {
if (!map) return;
const restore = () => drawRange(map, rangeRef.current);
map.on("style.load", restore);
return () => {
map.off("style.load", restore);
eraseRange(map);
};
}, [map]);
// Clicking a dot opens a popup of what was seen in its square.
useEffect(() => {
if (!map) return;
let popup = null;
let root = null;
let clicked = 0;
const close = () => {
if (popup) popup.remove();
popup = null;
};
const onClick = async (e) => {
const feature = e.features?.[0];
if (!feature) return;
const [lon, lat] = feature.geometry.coordinates;
const click = ++clicked;
const here = await getSpeciesHere(lat, lon, HERE_LIMIT + 1, species.taxon_id);
if (!here || click !== clicked) return;
close();
const node = document.createElement("div");
root = createRoot(node);
const current = root;
root.render( {
close();
onSelect(other);
}}/>);
popup = new maplibregl.Popup({offset: 6, maxWidth: "18rem", className: "wrolpi-species-popup"})
.setLngLat([lon, lat]).setDOMContent(node).addTo(map);
// Unmounted after the popup's own event, not during it.
popup.on("close", () => setTimeout(() => current.unmount()));
};
const pointer = () => map.getCanvas().style.cursor = "pointer";
const plain = () => map.getCanvas().style.cursor = "";
const layers = Object.values(RANGE_LAYERS);
layers.forEach((layer) => {
map.on("click", layer, onClick);
map.on("mouseenter", layer, pointer);
map.on("mouseleave", layer, plain);
});
return () => {
clicked++;
layers.forEach((layer) => {
map.off("click", layer, onClick);
map.off("mouseenter", layer, pointer);
map.off("mouseleave", layer, plain);
});
close();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [map, species.taxon_id]);
// The range's dots once they are here (the cluster nearest the view); the species' bbox only when it has no dots.
const bbox = details?.bbox || species.bbox;
const canZoom = range !== undefined && (range?.low?.features?.length > 0 || !!bbox);
const zoomToRange = () => {
const center = map.getCenter();
const bounds = rangeBounds(range?.low?.features, [center.lng, center.lat])
|| (bbox && [[bbox[0], bbox[1]], [bbox[2], bbox[3]]]);
if (!bounds) return;
// Not behind the panel: beside it on a wide map, above it on a narrow one. What is left to fit the range
// in is never less than MIN_FIT pixels across, or MapLibre would not move at all.
const padding = {top: 40, right: 60, bottom: 40, left: 40};
const panel = panelRef?.current?.getBoundingClientRect();
const canvas = map.getContainer?.()?.getBoundingClientRect();
if (panel && canvas) {
if (canvas.width > panel.width * 2) {
padding.left = Math.min(panel.right - canvas.left + 20, canvas.width - padding.right - MIN_FIT);
} else {
padding.bottom = Math.min(canvas.bottom - panel.top + 20, canvas.height - padding.top - MIN_FIT);
}
}
map.fitBounds(bounds, {padding, maxZoom: 12});
};
const dots = range ? (range.low?.features?.length || 0) : null;
return
{details?.other_names &&
Also called {details.other_names.split("; ").join(", ")}.
}
{species.group}
Seen {number(details?.obs_count ?? species.obs_count)} times
{/* The planet pack is every region: it names none. */}
{regionNames(details?.regions) ? ` in ${regionNames(details.regions)}` : ""}.
{dots !== null && ` ${number(dots)} places on the map.`}
{/* Nothing while loading or when the details failed; null `wikipedia` is "no Wikipedia Zim". */}
{details && }
Dots are approximate; iNaturalist blurs some locations on purpose. Click a dot to see what else was seen
there.
;
}
export default function MapSpeciesPanel({map, onClose}) {
const [q, setQ] = useState("");
const [group, setGroup] = useState(null);
const [radius, setRadius] = useState(DEFAULT_RADIUS);
// null while the first search is pending. A failed search keeps the last result, and says it failed.
const [result, setResult] = useState(null);
const [failed, setFailed] = useState(false);
const [selected, setSelected] = useState(null);
const generation = useRef(0);
const panelRef = useRef(null);
const search = useCallback(async () => {
if (!map) return;
const gen = ++generation.current;
const center = map.getCenter();
const found = await searchSpecies({
q: q.trim(), group, radius_km: radius,
lat: center.lat.toFixed(4), lon: center.wrap().lng.toFixed(4),
});
if (gen !== generation.current) return;
setFailed(!found);
if (found) setResult(found);
}, [map, q, group, radius]);
// Asked again when the search changes (typing waits a moment), and when the map stops moving.
useEffect(() => {
const timer = setTimeout(search, MOVE_DELAY_MS);
return () => clearTimeout(timer);
}, [search]);
useEffect(() => {
if (!map) return;
let timer;
const moved = () => {
clearTimeout(timer);
timer = setTimeout(search, MOVE_DELAY_MS);
};
map.on("moveend", moved);
return () => {
clearTimeout(timer);
map.off("moveend", moved);
};
}, [map, search]);
const groups = [{value: "", label: "All groups"},
...(result?.groups || []).map((g) => ({value: String(g.code), label: g.name}))];
const species = result?.species || [];
let body;
if (selected) {
body = setSelected(null)}
onSelect={setSelected} panelRef={panelRef}/>;
} else if (result === null && !failed) {
body =
Searching…
;
} else if (result?.packs === 0) {
body =
No species have been downloaded. Subscribe to a region's species on the{" "}
Manage page.
;
} else {
body = <>
setQ(e.currentTarget.value)}/>
{failed &&
Could not search the species.{result ? " This is the last list found." : ""}
}
{!result ? null : species.length === 0
?
{q.trim() ? "No species have that name" : "No species have been seen here"} in the regions
downloaded on the Manage page.
: species.map((s) => )}
>;
}
return
Species near the middle of the map
{body}
Observations: iNaturalist contributors, research grade.