mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 03:46:29 -05:00
534 lines
25 KiB
JavaScript
534 lines
25 KiB
JavaScript
|
|
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>;
|
||
|
|
}
|