iNaturalist species map (#1033)

* Add iNaturalist species pack build script

Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.

modules/map/species.py holds the pack format shared with WROLPi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Download iNaturalist species packs by subscription

A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.

The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Search the downloaded species packs, with their range and Wikipedia article

- GET /api/map/species: search by name (every word a prefix), and/or what
  was seen within radius_km of lat/lon. Nearby species come first, most
  seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
  the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
  libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.

Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Use iNaturalist's common names in the species packs

Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed).  The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback.  In us-west this names 30,642
of 52,015 species, up from 17,805.

--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species panel on the map: what lives here, and a species' range as dots

A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other).  It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group.  Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close.  "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).

The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species tests: neutral Oregon fixtures

Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: zoom to a range without its outliers, beside the panel

"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range.  It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Help: the Species page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: months seen, a popup on each dot, and review fixes

Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month).  The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here).  Packs without months still work.

Review fixes:
- Common names: the archive's first listed English name, not the first
  without a place (which was an alias: "Robin Redbreast", "Wanderer",
  "Duck Hawk"); every other English name is kept in `other_names` and
  is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
  a newer one is not counted twice; a finished download also removes
  older versions.  A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
  antimeridian; Zoom to range takes the short way across it, drops at
  least one outlier on each side from 20 dots, waits for the dots, and
  measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
  before a selection of it.
- A failed search keeps the last list and says so; failed details no
  longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
  refreshes until a subscribed pack arrives; a refused Delete fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: less work for the WROLPi per search and range

Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.

- Search ranks the matching species from bare (taxon, names, counts)
  tuples and reads only the species it returns in full: 30 km 87 ms,
  100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
  browser makes the dots: the red-tailed hawk's fine range 34 ms and
  95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.

A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there.  The popup is drawn over the Species panel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: a planet pack, every region in one file

`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build.  An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.

On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: sizes of the 20261129 packs; no hang re-signing a manifest

The packs grew about 15% with months and other names; the planet pack
is 993 MB.  Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first.  Help: a dot's popup, months,
other names, and the planet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: the planet from each observation once; overlaps counted once

Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more.  Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB).  `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions.  The
merge and its flags are gone.

On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts.  Species totals still add up across
overlapping packs; the planet pack is exact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Help: Species screenshots from the planet pack

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: Zoom to range fits the cluster of dots nearest the view

On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves.  Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London.  A range
spread across a continent is one cluster.  Help updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Species: Planet is listed first on the Manage tab

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-29 19:24:01 -07:00 • committed by Roland
parent 8478fc7229
commit a429db441e
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
25 changed files with 4312 additions and 8 deletions

View file

@ -0,0 +1,533 @@
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 <div role="img" aria-label="Seen by month" style={{display: "flex", gap: "2px", alignItems: "flex-end"}}>
{counts.map((count, i) => <div key={i} title={`${MONTHS[i]}: ${number(count)}`}
style={{flex: 1, textAlign: "center"}}>
<div style={{height: "1.5rem", display: "flex", alignItems: "flex-end"}}>
<div style={{width: "100%", height: `${Math.max(count ? 8 : 0, (count / most) * 100)}%`,
background: "var(--primary)", borderRadius: "1px"}}/>
</div>
<div style={{fontSize: "0.625rem", color: "var(--muted)"}}>{MONTHS[i][0]}</div>
</div>)}
</div>;
}
// 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 <div aria-label={`Seen in ${months.map((m) => MONTHS[m - 1]).join(", ")}`}
style={{display: "flex", gap: "2px"}}>
{MONTHS.map((name, i) => <span key={name} title={name} style={{
flex: 1, textAlign: "center", fontSize: "0.6875rem", borderRadius: "2px", padding: "1px 0",
background: seen.has(i + 1) ? "var(--primary)" : "transparent",
color: seen.has(i + 1) ? "var(--btn-text)" : "var(--muted)",
}}>{name[0]}</span>)}
</div>;
}
// 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 <div style={{fontSize: "0.8125rem", minWidth: "13rem"}}>
<div style={{fontWeight: 600}}>{species.common_name || species.name}</div>
<div style={{color: "var(--muted)", fontSize: "0.75rem", marginBottom: "0.25rem"}}>
{self ? `Seen ${number(self.here_count)} times in this square (about 11 km).`
: "Seen in this square (about 11 km)."}
</div>
{self && <MonthsSeen months={self.here_months}/>}
{others.length > 0 && <>
<div style={{marginTop: "0.5rem", fontWeight: 600}}>Also seen here</div>
{others.map((i) => <button key={i.taxon_id} type="button" onClick={() => onSelect(i)} style={{
display: "flex", width: "100%", justifyContent: "space-between", gap: "0.5rem", padding: "0.125rem 0",
border: "none", background: "transparent", color: "inherit", font: "inherit", cursor: "pointer",
textAlign: "left",
}}>
<span style={{textDecoration: "underline"}}>{i.common_name || i.name}</span>
<span style={{color: "var(--muted)"}}>{number(i.here_count)}</span>
</button>)}
{more > 0 && <div style={{color: "var(--muted)", fontSize: "0.75rem"}}>
and {number(more)} more species
</div>}
</>}
</div>;
}
// 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 <span style={{
fontSize: "0.6875rem", padding: "0 0.375rem", borderRadius: "0.25rem", whiteSpace: "nowrap",
background: near ? "var(--primary)" : "transparent", color: near ? "var(--btn-text)" : "var(--muted)",
border: near ? "none" : "1px solid var(--border)",
}}>{near ? `${number(species.near_count)} nearby` : "Not nearby"}</span>;
}
function SpeciesName({species}) {
return <>
<div style={{fontWeight: 600}}>{species.common_name || species.name}</div>
{species.common_name && <div style={{fontStyle: "italic", color: "var(--muted)", fontSize: "0.75rem"}}>
{species.name}
</div>}
</>;
}
function SpeciesRow({species, onSelect}) {
const near = species.near_count === null || species.near_count === undefined || species.near_count > 0;
return <button
type="button"
onClick={() => onSelect(species)}
aria-label={species.common_name || species.name}
style={{
display: "flex", width: "100%", justifyContent: "space-between", alignItems: "center", gap: "0.5rem",
padding: "0.375rem 0.25rem", border: "none", borderBottom: "1px solid var(--table-line)",
background: "transparent", color: "inherit", textAlign: "left", cursor: "pointer", font: "inherit",
opacity: near ? 1 : 0.6,
}}
>
<div style={{minWidth: 0}}><SpeciesName species={species}/></div>
<div style={{textAlign: "right", flexShrink: 0}}>
<NearBadge species={species}/>
<div style={{color: "var(--muted)", fontSize: "0.6875rem"}}>{species.group}</div>
</div>
</button>;
}
// 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 <div style={{color: "var(--muted)", fontSize: "0.75rem"}}>
<Link to="/zim/manage">Download Wikipedia</Link> to read about {name}.
</div>;
}
if (wikipedia.zim_id) {
return <a href={wikipedia.url} target="_blank" rel="noopener noreferrer">Read in Wikipedia</a>;
}
return <Link to={wikipedia.url}>Search for {name}</Link>;
}
// 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(<SpeciesHerePopup species={species} here={here} onSelect={(other) => {
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 <div style={{display: "flex", flexDirection: "column", gap: "0.5rem"}}>
<div><Button size="xs" icon="arrow left" onClick={onBack}>Back</Button></div>
<SpeciesName species={species}/>
{details?.other_names && <div style={{color: "var(--muted)", fontSize: "0.75rem"}}>
Also called {details.other_names.split("; ").join(", ")}.
</div>}
<div style={{display: "flex", gap: "0.5rem", alignItems: "center", flexWrap: "wrap"}}>
<span>{species.group}</span>
<NearBadge species={species}/>
</div>
<MonthsBar counts={details?.months}/>
<div style={{color: "var(--muted)", fontSize: "0.75rem"}}>
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.`}
</div>
<div style={{display: "flex", gap: "0.5rem", alignItems: "center", flexWrap: "wrap"}}>
<Button size="xs" icon="expand arrows alternate" disabled={!canZoom} onClick={zoomToRange}>
Zoom to range
</Button>
{/* Nothing while loading or when the details failed; null `wikipedia` is "no Wikipedia Zim". */}
{details && <WikipediaLink wikipedia={details.wikipedia ?? null} name={species.name}/>}
</div>
<div style={{color: "var(--muted)", fontSize: "0.6875rem"}}>
Dots are approximate; iNaturalist blurs some locations on purpose. Click a dot to see what else was seen
there.
</div>
</div>;
}
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 = <SpeciesDetails key={selected.taxon_id} map={map} species={selected} onBack={() => setSelected(null)}
onSelect={setSelected} panelRef={panelRef}/>;
} else if (result === null && !failed) {
body = <div style={{color: "var(--muted)"}}>Searching…</div>;
} else if (result?.packs === 0) {
body = <div>
No species have been downloaded. Subscribe to a region's species on the{" "}
<Link to="/map/manage">Manage</Link> page.
</div>;
} else {
body = <>
<div style={{display: "flex", flexDirection: "column", gap: "0.375rem"}}>
<TextInput size="xs" placeholder="Search by name" aria-label="Search species" value={q}
onChange={(e) => setQ(e.currentTarget.value)}/>
<div style={{display: "flex", gap: "0.375rem"}}>
<Select size="xs" data={groups} value={group === null ? "" : String(group)}
onChange={(value) => setGroup(value ? Number(value) : null)} allowDeselect={false}
comboboxProps={DROPDOWN} aria-label="Group" style={{flex: 1}}/>
<Select size="xs" data={RADII.map((r) => ({value: String(r), label: `Within ${r} km`}))}
value={String(radius)} onChange={(value) => setRadius(Number(value))}
allowDeselect={false} comboboxProps={DROPDOWN} aria-label="Radius" style={{flex: 1}}/>
</div>
</div>
<div style={{marginTop: "0.5rem"}}>
{failed && <div role="alert" style={{color: "var(--danger)", marginBottom: "0.25rem"}}>
Could not search the species.{result ? " This is the last list found." : ""}
</div>}
{!result ? null : species.length === 0
? <div style={{color: "var(--muted)"}}>
{q.trim() ? "No species have that name" : "No species have been seen here"} in the regions
downloaded on the <Link to="/map/manage">Manage</Link> page.
</div>
: species.map((s) => <SpeciesRow key={s.taxon_id} species={s} onSelect={setSelected}/>)}
</div>
</>;
}
return <div ref={panelRef} role="dialog" aria-label="Species" style={{
position: "absolute", left: "0.75rem", bottom: "2.5rem", zIndex: 1002,
// Half the screen at most, so the range stays in sight above it; never under the map's buttons on the right.
width: "20rem", maxWidth: "calc(100% - 4.5rem)", maxHeight: "min(calc(100% - 7rem), 50vh)", overflowY: "auto",
background: "var(--panel)", border: "1px solid var(--border)", color: "var(--text)", padding: "0.75rem",
fontSize: "0.8125rem",
}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.5rem"}}>
<strong>Species near the middle of the map</strong>
<Button size="xs" icon="close" aria-label="Close species" onClick={onClose}/>
</div>
{body}
<div style={{color: "var(--muted)", fontSize: "0.6875rem", marginTop: "0.75rem"}}>
Observations: iNaturalist contributors, research grade.
</div>
</div>;
}