mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 03:46:29 -05:00
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:
parent
8478fc7229
commit
a429db441e
25 changed files with 4312 additions and 8 deletions
|
|
@ -840,6 +840,11 @@ tr.drag-deselecting td {
|
|||
}
|
||||
|
||||
/* Map popups (POI details and pins) follow the active theme's tokens. */
|
||||
/* A species dot's popup is drawn over the Species panel (z-index 1002) it was opened from. */
|
||||
.maplibregl-popup.wrolpi-species-popup {
|
||||
z-index: 1003;
|
||||
}
|
||||
|
||||
/* Scoped under .maplibregl-popup to outrank maplibre-gl.css, which loads after this file. */
|
||||
.maplibregl-popup .maplibregl-popup-content {
|
||||
background: var(--panel);
|
||||
|
|
|
|||
|
|
@ -1712,6 +1712,91 @@ export async function mapUnsubscribe(region) {
|
|||
}
|
||||
}
|
||||
|
||||
// The species pack catalog, subscriptions, and downloaded packs: {catalog, subscriptions, files}, or undefined.
|
||||
export async function fetchSpeciesSubscriptions() {
|
||||
const response = await apiGet(`${API_URI}/map/species/subscribe`);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
const message = await getErrorMessage(response, 'Could not get species subscriptions');
|
||||
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
||||
}
|
||||
}
|
||||
|
||||
export async function speciesSubscribe(region) {
|
||||
const response = await apiPost(`${API_URI}/map/species/subscribe`, {region});
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Could not subscribe to species');
|
||||
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
||||
}
|
||||
}
|
||||
|
||||
export async function speciesUnsubscribe(region) {
|
||||
const response = await apiDelete(`${API_URI}/map/species/subscribe/${encodeURIComponent(region)}`);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Could not unsubscribe from species');
|
||||
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
||||
}
|
||||
}
|
||||
|
||||
// GET a species endpoint: its JSON, or undefined when it failed (a response that was not OK, or no response at
|
||||
// all), after an error was shown.
|
||||
async function getSpeciesJson(url, failure) {
|
||||
try {
|
||||
const response = await apiGet(url);
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
const message = await getErrorMessage(response, failure);
|
||||
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
toast({type: 'error', title: 'Species Error', description: failure, time: 5000});
|
||||
}
|
||||
}
|
||||
|
||||
// Search the downloaded species: {q, lat, lon, radius_km, group, limit} (any may be omitted).
|
||||
// Returns {species, packs, groups}, or undefined (an error was shown).
|
||||
export async function searchSpecies(params) {
|
||||
const query = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined && value !== '') query.set(key, value);
|
||||
});
|
||||
return await getSpeciesJson(`${API_URI}/map/species?${query}`, 'Could not search species');
|
||||
}
|
||||
|
||||
// A species' details and its Wikipedia article: {taxon_id, name, ..., wikipedia}, or undefined.
|
||||
export async function getSpecies(taxonId) {
|
||||
return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}`,
|
||||
'Could not get the species');
|
||||
}
|
||||
|
||||
// What was seen in the ~11 km square of a point: {bbox, species_count, species: [{..., here_count, here_months}]}.
|
||||
// `taxonId`: the species clicked, returned as `taxon` however few times it was seen there.
|
||||
export async function getSpeciesHere(lat, lon, limit, taxonId) {
|
||||
const query = new URLSearchParams({lat, lon});
|
||||
if (limit) query.set('limit', limit);
|
||||
if (taxonId) query.set('taxon_id', taxonId);
|
||||
return await getSpeciesJson(`${API_URI}/map/species/here?${query}`, 'Could not get the species seen here');
|
||||
}
|
||||
|
||||
// A species' range: {grid, count, deltas} of grid 'low' (0.1°, every observation) or 'high' (0.02°, precise); see
|
||||
// rangeGeoJSON.
|
||||
export async function getSpeciesRange(taxonId, grid) {
|
||||
return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}/range?grid=${grid}`,
|
||||
"Could not get the species' range");
|
||||
}
|
||||
|
||||
// Throws (after showing why) when the pack was not deleted, so the button that asked shows it failed.
|
||||
export async function deleteSpeciesFiles(region) {
|
||||
const response = await apiDelete(`${API_URI}/map/species/files/${encodeURIComponent(region)}`);
|
||||
if (!response.ok) {
|
||||
const message = await getErrorMessage(response, 'Could not delete species pack');
|
||||
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
||||
throw new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Which months of the fallout climatology are kept: {version, months, missing, published}, or null.
|
||||
export async function getFalloutClimatology() {
|
||||
const response = await apiGet(`${API_URI}/map/fallout/climatology`);
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import {Media, StatusContext} from "../contexts/contexts";
|
|||
import {MAP_VIEWER_URI} from "./Vars";
|
||||
import MapViewer from "./MapViewer";
|
||||
import {WeatherSection} from "./MapWeather";
|
||||
import {SpeciesSection} from "./MapSpecies";
|
||||
import {AddToPlaylistButton} from "./AddToPlaylist";
|
||||
import {solarCalculatorPath} from "./calculators/solar";
|
||||
import maplibregl from "maplibre-gl";
|
||||
|
|
@ -268,9 +269,9 @@ function MapCatalogRow({item, subscribedRegions, fetchData}) {
|
|||
aria-label={`Preview ${name}`}
|
||||
onClick={() => setPreviewOpen(true)}
|
||||
/>}
|
||||
{/* A `color` would replace the danger role's red, so only Subscribe has one. */}
|
||||
<Button
|
||||
role={isSubscribed ? 'danger' : undefined}
|
||||
color={isSubscribed ? undefined : 'violet'}
|
||||
{...(isSubscribed ? {role: 'danger'} : {color: 'violet'})}
|
||||
size='xs'
|
||||
onClick={handleButton}
|
||||
>
|
||||
|
|
@ -507,6 +508,10 @@ function ManageMap() {
|
|||
|
||||
<Divider/>
|
||||
|
||||
<SpeciesSection/>
|
||||
|
||||
<Divider/>
|
||||
|
||||
<WeatherSection/>
|
||||
|
||||
<HandPointMessage>
|
||||
|
|
|
|||
|
|
@ -105,6 +105,7 @@ jest.mock('../api', () => ({
|
|||
getWeather: async () => ({enabled: false, download: null, targets: 0, field: null}),
|
||||
getMapFiles: jest.fn(),
|
||||
fetchMapSubscriptions: jest.fn(),
|
||||
fetchSpeciesSubscriptions: jest.fn(),
|
||||
getMapPins: jest.fn(),
|
||||
deleteMapFile: jest.fn(),
|
||||
deleteMapPin: jest.fn(),
|
||||
|
|
@ -120,6 +121,7 @@ const api = require('../api');
|
|||
const renderManage = async ({files = []} = {}) => {
|
||||
api.getMapFiles.mockResolvedValue({files});
|
||||
api.fetchMapSubscriptions.mockResolvedValue({catalog: CATALOG, subscriptions: []});
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({catalog: [], subscriptions: [], files: []});
|
||||
api.getMapPins.mockResolvedValue({pins: []});
|
||||
/*
|
||||
* Mounted under `/map/*` as App.js does, not bare. MapRoute's own `<Route path='manage'>`
|
||||
|
|
|
|||
144
app/src/components/MapSpecies.js
Normal file
144
app/src/components/MapSpecies.js
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import React, {useEffect, useRef, useState} from "react";
|
||||
import {deleteSpeciesFiles, fetchSpeciesSubscriptions, speciesSubscribe, speciesUnsubscribe} from "../api";
|
||||
import {APIButton, ErrorMessage, humanFileSize, InfoMessage} from "./Common";
|
||||
import {Button, Group, Header, Table} from "./ui";
|
||||
import {SortableTable} from "./SortableTable";
|
||||
|
||||
// The Manage tab's section for the iNaturalist species packs: one per map region, built monthly from
|
||||
// iNaturalist's research-grade observations. A subscription downloads a region's pack and keeps it up to date.
|
||||
|
||||
// How often (ms) the table is asked again while a subscribed region has no pack yet.
|
||||
export const REFRESH_MS = 10000;
|
||||
// The region name of the pack of every region (modules/map/species.py PLANET).
|
||||
const PLANET = 'planet';
|
||||
|
||||
// A pack's version is the date of iNaturalist's export: 20261123 -> 2026-11-23.
|
||||
export const packDate = (version) => version && version.length === 8
|
||||
? `${version.slice(0, 4)}-${version.slice(4, 6)}-${version.slice(6)}`
|
||||
: version;
|
||||
|
||||
function SpeciesRow({item, subscribed, file, fetchData}) {
|
||||
const {name, region, size_estimate} = item;
|
||||
|
||||
const toggleSubscription = async () => {
|
||||
if (subscribed) {
|
||||
await speciesUnsubscribe(region);
|
||||
} else {
|
||||
await speciesSubscribe(region);
|
||||
}
|
||||
await fetchData();
|
||||
};
|
||||
|
||||
// A refused delete throws, so the button shows it failed; the table is refreshed either way.
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await deleteSpeciesFiles(region);
|
||||
} finally {
|
||||
await fetchData();
|
||||
}
|
||||
};
|
||||
|
||||
return <Table.Row>
|
||||
<Table.Cell>{name}</Table.Cell>
|
||||
{/* A downloaded pack's size, else the estimate. */}
|
||||
<Table.Cell>{file ? humanFileSize(file.size) : `~${humanFileSize(size_estimate)}`}</Table.Cell>
|
||||
<Table.Cell>{file ? packDate(file.version) : ''}</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Group gap='xs' wrap='nowrap'>
|
||||
{/* The same button as a map region's subscription. */}
|
||||
{/* A `color` would replace the danger role's red, so only Subscribe has one. */}
|
||||
<Button
|
||||
size='xs'
|
||||
{...(subscribed ? {role: 'danger'} : {color: 'violet'})}
|
||||
onClick={toggleSubscription}
|
||||
>
|
||||
{subscribed ? 'Unsubscribe' : 'Subscribe'}
|
||||
</Button>
|
||||
{file && <APIButton
|
||||
size='xs'
|
||||
role='danger'
|
||||
confirmContent={`Delete the species of ${name}?`}
|
||||
confirmButton='Delete'
|
||||
onClick={handleDelete}
|
||||
>
|
||||
Delete
|
||||
</APIButton>}
|
||||
</Group>
|
||||
</Table.Cell>
|
||||
</Table.Row>;
|
||||
}
|
||||
|
||||
export function SpeciesSection() {
|
||||
// null = pending, undefined = fetch failed.
|
||||
const [data, setData] = useState(null);
|
||||
// Only the newest request may write state: a subscribe refetches while the mount request may be in flight.
|
||||
const generation = useRef(0);
|
||||
|
||||
const fetchData = async () => {
|
||||
const gen = ++generation.current;
|
||||
let fetched;
|
||||
try {
|
||||
fetched = await fetchSpeciesSubscriptions();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
if (gen === generation.current) {
|
||||
setData(fetched || undefined);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
// A subscribed region's pack arrives later (see Downloads): asked again until every one is here.
|
||||
const waiting = !!data && (data.subscriptions || []).some(
|
||||
(subscription) => !(data.files || []).some((file) => file.region === subscription.region));
|
||||
useEffect(() => {
|
||||
if (!waiting) return;
|
||||
const timer = setInterval(fetchData, REFRESH_MS);
|
||||
return () => clearInterval(timer);
|
||||
}, [waiting]);
|
||||
|
||||
const headers = [
|
||||
// The planet is every region in one download; it sorts ahead of the regions.
|
||||
{key: 'name', text: 'Region', sortBy: i => i.region === PLANET ? '' : i.name.toLowerCase()},
|
||||
{key: 'size', text: 'Size', sortBy: i => i.size_estimate || 0},
|
||||
{key: 'version', text: 'Downloaded', sortBy: null},
|
||||
{key: 'actions', text: '', sortBy: null},
|
||||
];
|
||||
|
||||
let body;
|
||||
if (data === undefined) {
|
||||
body = <ErrorMessage>Could not fetch species subscriptions</ErrorMessage>;
|
||||
} else {
|
||||
const subscribed = new Set((data?.subscriptions || []).map(i => i.region));
|
||||
const files = Object.fromEntries((data?.files || []).map(i => [i.region, i]));
|
||||
// A null catalog shows the table's placeholder while it loads.
|
||||
body = <SortableTable
|
||||
tableHeaders={headers}
|
||||
data={data ? data.catalog || [] : null}
|
||||
rowFunc={(item) => <SpeciesRow
|
||||
key={item.region}
|
||||
item={item}
|
||||
subscribed={subscribed.has(item.region)}
|
||||
file={files[item.region]}
|
||||
fetchData={fetchData}
|
||||
/>}
|
||||
rowKey='region'
|
||||
defaultSortColumn='name'
|
||||
/>;
|
||||
}
|
||||
|
||||
return <>
|
||||
<Header as='h3'>Species</Header>
|
||||
{body}
|
||||
<InfoMessage storageName='hint_map_species'>
|
||||
<p>Subscribe to a region to download where its plants and animals have been seen, and to keep it
|
||||
up to date each month. Each species links to its Wikipedia article when you have a Wikipedia Zim.</p>
|
||||
<p>Observations: iNaturalist contributors, iNaturalist Research-grade Observations (<a
|
||||
href='https://doi.org/10.15468/ab3s5x' rel='noopener noreferrer' target='_blank'>doi:10.15468/ab3s5x</a>),
|
||||
CC BY-NC 4.0. Common names: iNaturalist. Articles: Wikidata.</p>
|
||||
</InfoMessage>
|
||||
</>;
|
||||
}
|
||||
149
app/src/components/MapSpecies.test.js
Normal file
149
app/src/components/MapSpecies.test.js
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import React from 'react';
|
||||
import {act, screen, waitFor, within} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {renderWithProviders as render} from '../test-utils';
|
||||
import {packDate, REFRESH_MS, SpeciesSection} from './MapSpecies';
|
||||
|
||||
jest.mock('../api', () => ({
|
||||
...jest.requireActual('../api'),
|
||||
fetchSpeciesSubscriptions: jest.fn(),
|
||||
speciesSubscribe: jest.fn(),
|
||||
speciesUnsubscribe: jest.fn(),
|
||||
deleteSpeciesFiles: jest.fn(),
|
||||
}));
|
||||
|
||||
const api = require('../api');
|
||||
|
||||
const CATALOG = [
|
||||
{name: 'United States (West)', region: 'us-west', bbox: '-125.0,24.4,-104.0,49.4', size_estimate: 78000000},
|
||||
{name: 'Alaska', region: 'us-alaska', bbox: '-180.0,51.0,-129.0,71.5', size_estimate: 5000000},
|
||||
];
|
||||
|
||||
const rowOf = async (name) => (await screen.findByText(name)).closest('tr');
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({
|
||||
catalog: CATALOG,
|
||||
subscriptions: [{region: 'us-west'}],
|
||||
files: [{name: 'inat-us-west-20261123.species.db', region: 'us-west', version: '20261123', size: 77893632}],
|
||||
});
|
||||
api.speciesSubscribe.mockResolvedValue(undefined);
|
||||
api.speciesUnsubscribe.mockResolvedValue(undefined);
|
||||
api.deleteSpeciesFiles.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
test('packDate', () => {
|
||||
expect(packDate('20261123')).toBe('2026-11-23');
|
||||
expect(packDate(undefined)).toBe(undefined);
|
||||
});
|
||||
|
||||
test('a downloaded pack shows its size and date; others show an estimate', async () => {
|
||||
render(<SpeciesSection/>);
|
||||
|
||||
const west = await rowOf('United States (West)');
|
||||
expect(within(west).getByText('2026-11-23')).toBeInTheDocument();
|
||||
expect(within(west).getByText('Unsubscribe')).toBeInTheDocument();
|
||||
expect(within(west).getByText('Delete')).toBeInTheDocument();
|
||||
expect(within(west).queryByText(/^~/)).not.toBeInTheDocument();
|
||||
|
||||
const alaska = await rowOf('Alaska');
|
||||
expect(within(alaska).getByText(/^~/)).toBeInTheDocument();
|
||||
expect(within(alaska).getByText('Subscribe')).toBeInTheDocument();
|
||||
expect(within(alaska).queryByText('Delete')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('subscribing and unsubscribing refetch the subscriptions', async () => {
|
||||
render(<SpeciesSection/>);
|
||||
|
||||
await userEvent.click(within(await rowOf('Alaska')).getByText('Subscribe'));
|
||||
await waitFor(() => expect(api.speciesSubscribe).toHaveBeenCalledWith('us-alaska'));
|
||||
await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(2));
|
||||
|
||||
await userEvent.click(within(await rowOf('United States (West)')).getByText('Unsubscribe'));
|
||||
await waitFor(() => expect(api.speciesUnsubscribe).toHaveBeenCalledWith('us-west'));
|
||||
await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(3));
|
||||
});
|
||||
|
||||
test('deleting a pack asks first', async () => {
|
||||
render(<SpeciesSection/>);
|
||||
|
||||
await userEvent.click(within(await rowOf('United States (West)')).getByText('Delete'));
|
||||
expect(api.deleteSpeciesFiles).not.toHaveBeenCalled();
|
||||
expect(await screen.findByText('Delete the species of United States (West)?')).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', {name: 'Delete'}));
|
||||
await waitFor(() => expect(api.deleteSpeciesFiles).toHaveBeenCalledWith('us-west'));
|
||||
});
|
||||
|
||||
test('pending: shows a placeholder', () => {
|
||||
api.fetchSpeciesSubscriptions.mockReturnValue(new Promise(() => {
|
||||
}));
|
||||
const {container} = render(<SpeciesSection/>);
|
||||
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('a failed fetch is an error, not an empty table', async () => {
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue(undefined);
|
||||
render(<SpeciesSection/>);
|
||||
expect(await screen.findByText('Could not fetch species subscriptions')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Unsubscribe is a danger button; Subscribe is not', async () => {
|
||||
render(<SpeciesSection/>);
|
||||
const unsubscribe = within(await rowOf('United States (West)')).getByRole('button', {name: 'Unsubscribe'});
|
||||
const subscribe = within(await rowOf('Alaska')).getByRole('button', {name: 'Subscribe'});
|
||||
expect(unsubscribe.className).toContain('wrolpi-button-danger');
|
||||
// The danger role's red is not replaced by a color.
|
||||
expect(unsubscribe.getAttribute('style') || '').not.toContain('violet');
|
||||
expect(subscribe.className).not.toContain('wrolpi-button-danger');
|
||||
});
|
||||
|
||||
test('asked again while a subscribed region has no pack yet', async () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({
|
||||
catalog: CATALOG, subscriptions: [{region: 'us-alaska'}], files: [],
|
||||
});
|
||||
render(<SpeciesSection/>);
|
||||
await rowOf('Alaska');
|
||||
const calls = api.fetchSpeciesSubscriptions.mock.calls.length;
|
||||
await act(async () => jest.advanceTimersByTime(REFRESH_MS));
|
||||
expect(api.fetchSpeciesSubscriptions.mock.calls.length).toBe(calls + 1);
|
||||
|
||||
// Once the pack is here, it stops.
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({
|
||||
catalog: CATALOG, subscriptions: [{region: 'us-alaska'}],
|
||||
files: [{name: 'inat-us-alaska-20261123.species.db', region: 'us-alaska', version: '20261123', size: 1}],
|
||||
});
|
||||
await act(async () => jest.advanceTimersByTime(REFRESH_MS));
|
||||
const settled = api.fetchSpeciesSubscriptions.mock.calls.length;
|
||||
await act(async () => jest.advanceTimersByTime(REFRESH_MS * 3));
|
||||
expect(api.fetchSpeciesSubscriptions.mock.calls.length).toBe(settled);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('a refused delete still refreshes the table', async () => {
|
||||
api.deleteSpeciesFiles.mockRejectedValue(new Error('WROL Mode is enabled'));
|
||||
render(<SpeciesSection/>);
|
||||
await userEvent.click(within(await rowOf('United States (West)')).getByText('Delete'));
|
||||
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', {name: 'Delete'}));
|
||||
await waitFor(() => expect(api.deleteSpeciesFiles).toHaveBeenCalled());
|
||||
await waitFor(() => expect(api.fetchSpeciesSubscriptions).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
test('the planet is listed first, before the regions by name', async () => {
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({
|
||||
catalog: [...CATALOG, {name: 'Planet (every region)', region: 'planet', bbox: '-180.0,-90.0,180.0,90.0',
|
||||
size_estimate: 993000000}],
|
||||
subscriptions: [],
|
||||
files: [],
|
||||
});
|
||||
render(<SpeciesSection/>);
|
||||
|
||||
await screen.findByText('Planet (every region)');
|
||||
const names = screen.getAllByRole('row').slice(1).map(row => within(row).getAllByRole('cell')[0].textContent);
|
||||
expect(names).toEqual(['Planet (every region)', 'Alaska', 'United States (West)']);
|
||||
});
|
||||
533
app/src/components/MapSpeciesPanel.js
Normal file
533
app/src/components/MapSpeciesPanel.js
Normal 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>;
|
||||
}
|
||||
424
app/src/components/MapSpeciesPanel.test.js
Normal file
424
app/src/components/MapSpeciesPanel.test.js
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
import React from 'react';
|
||||
import {act, screen, waitFor, within} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {renderWithProviders as render} from '../test-utils';
|
||||
import MapSpeciesPanel, {
|
||||
HIGH_ZOOM, MonthsBar, MonthsSeen, RANGE_LAYERS, RANGE_SOURCES, rangeBounds, rangeClusters, rangeGeoJSON,
|
||||
rangeLayers, regionNames,
|
||||
SPECIES_LAYER_PREFIX,
|
||||
SpeciesHerePopup, WikipediaLink,
|
||||
} from './MapSpeciesPanel';
|
||||
import {exportStyle} from './mapExport';
|
||||
|
||||
// The popups opened: their content, where they are, and whether they were closed.
|
||||
const popups = [];
|
||||
jest.mock('maplibre-gl', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
Popup: class {
|
||||
constructor() {
|
||||
this.removed = false;
|
||||
popups.push(this);
|
||||
}
|
||||
|
||||
setLngLat(lngLat) {
|
||||
this.lngLat = lngLat;
|
||||
return this;
|
||||
}
|
||||
|
||||
setDOMContent(node) {
|
||||
this.node = node;
|
||||
return this;
|
||||
}
|
||||
|
||||
addTo() {
|
||||
return this;
|
||||
}
|
||||
|
||||
on() {
|
||||
return this;
|
||||
}
|
||||
|
||||
remove() {
|
||||
this.removed = true;
|
||||
}
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('../api', () => ({
|
||||
...jest.requireActual('../api'),
|
||||
searchSpecies: jest.fn(),
|
||||
getSpecies: jest.fn(),
|
||||
getSpeciesRange: jest.fn(),
|
||||
getSpeciesHere: jest.fn(),
|
||||
}));
|
||||
|
||||
const api = require('../api');
|
||||
|
||||
const GROUPS = [{code: 0, name: 'Other'}, {code: 1, name: 'Plants'}, {code: 3, name: 'Mammals'}];
|
||||
const ASPEN = {
|
||||
taxon_id: 54840, name: 'Populus tremuloides', common_name: 'quaking aspen', wiki_title: 'Populus_tremuloides',
|
||||
group: 'Plants', group_code: 1, obs_count: 22310, near_count: 585, bbox: [-124.9, 25.9, -104.0, 49.4],
|
||||
regions: ['us-west'],
|
||||
};
|
||||
const DEER = {...ASPEN, taxon_id: 42220, name: 'Odocoileus hemionus', common_name: 'Mule Deer', group: 'Mammals',
|
||||
group_code: 3, near_count: 0};
|
||||
// A range of `n` neighboring cells of the 0.1° grid, as the API sends it: the first cell, then 1 apart. The first is
|
||||
// the cell whose south-west corner is 40°N 111°W.
|
||||
const FIRST_CELL = 1300 * 3600 + 690;
|
||||
const dots = (n) => ({grid: 0.1, count: n, deltas: n ? [FIRST_CELL, ...Array(n - 1).fill(1)] : []});
|
||||
|
||||
// The parts of a MapLibre map the panel uses: sources and layers are kept, so drawing can be checked.
|
||||
function fakeMap() {
|
||||
const handlers = {};
|
||||
const sources = {}, layers = {};
|
||||
return {
|
||||
sources, layers, handlers,
|
||||
getCenter: () => ({lat: 44.06, lng: -121.31, wrap: () => ({lng: -121.31})}),
|
||||
// A handler of one layer's events is kept as "event:layer".
|
||||
on: jest.fn((event, layer, fn) => {
|
||||
const key = fn ? `${event}:${layer}` : event;
|
||||
(handlers[key] = handlers[key] || []).push(fn || layer);
|
||||
}),
|
||||
off: jest.fn((event, layer, fn) => {
|
||||
const key = fn ? `${event}:${layer}` : event;
|
||||
handlers[key] = (handlers[key] || []).filter((i) => i !== (fn || layer));
|
||||
}),
|
||||
getCanvas: () => ({style: {}}),
|
||||
addSource: jest.fn((id, source) => {
|
||||
sources[id] = source;
|
||||
}),
|
||||
addLayer: jest.fn((layer) => {
|
||||
layers[layer.id] = layer;
|
||||
}),
|
||||
getSource: (id) => sources[id],
|
||||
getLayer: (id) => layers[id],
|
||||
removeSource: jest.fn((id) => delete sources[id]),
|
||||
removeLayer: jest.fn((id) => delete layers[id]),
|
||||
fitBounds: jest.fn(),
|
||||
fire: (event, arg) => (handlers[event] || []).forEach((fn) => fn(arg)),
|
||||
};
|
||||
}
|
||||
|
||||
const HERE = {
|
||||
bbox: [-121.4, 44.0, -121.3, 44.1], species_count: 12,
|
||||
species: [
|
||||
{...DEER, here_count: 40, here_months: [6, 7, 8]},
|
||||
{...ASPEN, here_count: 25, here_months: [5, 9, 10]},
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
popups.length = 0;
|
||||
api.getSpeciesHere.mockResolvedValue(HERE);
|
||||
api.searchSpecies.mockResolvedValue({species: [ASPEN, DEER], packs: 1, groups: GROUPS});
|
||||
api.getSpecies.mockResolvedValue({...ASPEN, other_names: 'trembling aspen; popple', wikipedia: {zim_id: 3, path: 'Populus_tremuloides',
|
||||
title: 'Populus tremuloides', url: '/api/zim/3/entry/Populus_tremuloides'}});
|
||||
api.getSpeciesRange.mockImplementation(async (id, grid) => dots(grid === 'low' ? 3 : 5));
|
||||
});
|
||||
|
||||
describe('rangeLayers', () => {
|
||||
test('the low grid below HIGH_ZOOM, the high grid from it', () => {
|
||||
const [low, high] = rangeLayers(true);
|
||||
expect(low).toMatchObject({id: RANGE_LAYERS.low, source: RANGE_SOURCES.low, maxzoom: HIGH_ZOOM});
|
||||
expect(high).toMatchObject({id: RANGE_LAYERS.high, source: RANGE_SOURCES.high, minzoom: HIGH_ZOOM});
|
||||
});
|
||||
|
||||
test('without precise observations, the low grid at every zoom', () => {
|
||||
const layers = rangeLayers(false);
|
||||
expect(layers).toHaveLength(1);
|
||||
expect(layers[0].maxzoom).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('regionNames: the planet pack is not named', () => {
|
||||
expect(regionNames(['us-west', 'us-central'])).toBe('us-west, us-central');
|
||||
expect(regionNames(['planet'])).toBe('');
|
||||
expect(regionNames(undefined)).toBe('');
|
||||
});
|
||||
|
||||
describe('rangeGeoJSON', () => {
|
||||
test('the middle of each cell, from the differences', () => {
|
||||
const geojson = rangeGeoJSON(dots(3));
|
||||
expect(geojson.features.map((f) => f.geometry.coordinates)).toEqual(
|
||||
[[-110.95, 40.05], [-110.85, 40.05], [-110.75, 40.05]]);
|
||||
});
|
||||
|
||||
test('the corners of the world', () => {
|
||||
const last = 1800 * 3600 - 1;
|
||||
expect(rangeGeoJSON({grid: 0.1, deltas: [0, last]}).features.map((f) => f.geometry.coordinates))
|
||||
.toEqual([[-179.95, -89.95], [179.95, 89.95]]);
|
||||
// The high grid has 18,000 columns.
|
||||
expect(rangeGeoJSON({grid: 0.02, deltas: [18000]}).features[0].geometry.coordinates).toEqual([-179.99, -89.97]);
|
||||
});
|
||||
|
||||
test('nothing: no dots', () => {
|
||||
expect(rangeGeoJSON(undefined).features).toEqual([]);
|
||||
expect(rangeGeoJSON({grid: 0.1, deltas: []}).features).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rangeBounds', () => {
|
||||
const at = (points) => points.map(([lon, lat]) => ({geometry: {coordinates: [lon, lat]}}));
|
||||
// Giant sequoia: its groves in the Sierra Nevada, and trees planted in Britain and New Zealand.
|
||||
const SIERRA = Array.from({length: 40}, (_, i) => [-120.5 + i * 0.05, 36 + i * 0.07]);
|
||||
const BRITAIN = [[-3.2, 55.9], [-1.5, 53.8], [-0.1, 51.5], [-2.6, 51.4]];
|
||||
const NEW_ZEALAND = [[175.3, -37.8], [176.2, -38.1]];
|
||||
const SEQUOIA = at([...SIERRA, ...BRITAIN, ...NEW_ZEALAND]);
|
||||
const YOSEMITE = [-119.59, 37.745];
|
||||
const LONDON = [-0.12, 51.5];
|
||||
|
||||
test('one cluster: all of its dots', () => {
|
||||
expect(rangeBounds(at([[-120, 37], [-118, 36], [-119, 38]]), YOSEMITE)).toEqual([[-120, 36], [-118, 38]]);
|
||||
});
|
||||
|
||||
test('the cluster nearest the middle of the map', () => {
|
||||
const [[west, south], [east, north]] = rangeBounds(SEQUOIA, YOSEMITE);
|
||||
expect([west, south]).toEqual([-120.5, 36]);
|
||||
expect(east).toBeCloseTo(-120.5 + 39 * 0.05);
|
||||
expect(north).toBeCloseTo(36 + 39 * 0.07);
|
||||
// From London, the trees planted in Britain, though there are far fewer of them.
|
||||
expect(rangeBounds(SEQUOIA, LONDON)).toEqual([[-3.2, 51.4], [-0.1, 55.9]]);
|
||||
// From Auckland, New Zealand's.
|
||||
expect(rangeBounds(SEQUOIA, [174.76, -36.85])).toEqual([[175.3, -38.1], [176.2, -37.8]]);
|
||||
});
|
||||
|
||||
test('dots in touching 2° squares are one cluster; a wider gap is two', () => {
|
||||
// A chain of dots 1.5° apart across 9°: one cluster.
|
||||
const chain = Array.from({length: 7}, (_, i) => [-110 + i * 1.5, 40]);
|
||||
expect(rangeClusters(chain)).toHaveLength(1);
|
||||
// Two dots 5° apart: two clusters.
|
||||
expect(rangeClusters([[-110, 40], [-105, 40]])).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('across the antimeridian: one cluster, the short way, with its east past 180', () => {
|
||||
const fiji = [[178.5, -18], [179.5, -17], [-179.5, -16], [-178.5, -17]];
|
||||
expect(rangeClusters(fiji)).toHaveLength(1);
|
||||
expect(rangeBounds(at(fiji), [178, -17])).toEqual([[178.5, -18], [181.5, -16]]);
|
||||
});
|
||||
|
||||
test('no dots: none', () => {
|
||||
expect(rangeBounds([], YOSEMITE)).toBeNull();
|
||||
expect(rangeBounds(undefined, YOSEMITE)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('months', () => {
|
||||
test('a bar per month, or nothing without any', () => {
|
||||
const {rerender} = render(<MonthsBar counts={[0, 0, 3, 10, 0, 0, 0, 0, 0, 0, 1, 0]}/>);
|
||||
expect(screen.getByRole('img', {name: 'Seen by month'})).toBeInTheDocument();
|
||||
expect(screen.getByTitle('April: 10')).toBeInTheDocument();
|
||||
rerender(<MonthsBar counts={Array(12).fill(0)}/>);
|
||||
expect(screen.queryByRole('img', {name: 'Seen by month'})).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('the months seen, named', () => {
|
||||
render(<MonthsSeen months={[5, 10]}/>);
|
||||
expect(screen.getByLabelText('Seen in May, October')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SpeciesHerePopup', () => {
|
||||
test('the species clicked, even when it is not among the most seen there', () => {
|
||||
const here = {...HERE, species: [HERE.species[0]], taxon: {...ASPEN, here_count: 2, here_months: [6]}};
|
||||
render(<SpeciesHerePopup species={ASPEN} here={here} onSelect={jest.fn()}/>);
|
||||
expect(screen.getByText('Seen 2 times in this square (about 11 km).')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Seen in June')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("the species' count in the square, and the others seen there", async () => {
|
||||
const onSelect = jest.fn();
|
||||
render(<SpeciesHerePopup species={ASPEN} here={HERE} onSelect={onSelect}/>);
|
||||
expect(screen.getByText('Seen 25 times in this square (about 11 km).')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Seen in May, September, October')).toBeInTheDocument();
|
||||
expect(screen.getByText('and 10 more species')).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', {name: /Mule Deer/}));
|
||||
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({taxon_id: DEER.taxon_id}));
|
||||
});
|
||||
});
|
||||
|
||||
describe('WikipediaLink', () => {
|
||||
test('an article opens in a new tab', () => {
|
||||
render(<WikipediaLink name='Populus tremuloides'
|
||||
wikipedia={{zim_id: 3, url: '/api/zim/3/entry/Populus_tremuloides'}}/>);
|
||||
const link = screen.getByRole('link', {name: 'Read in Wikipedia'});
|
||||
expect(link).toHaveAttribute('href', '/api/zim/3/entry/Populus_tremuloides');
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
|
||||
test('no article: a search for the name', () => {
|
||||
render(<WikipediaLink name='Populus tremuloides'
|
||||
wikipedia={{zim_id: null, url: '/search?q=Populus%20tremuloides'}}/>);
|
||||
expect(screen.getByRole('link', {name: 'Search for Populus tremuloides'}))
|
||||
.toHaveAttribute('href', '/search?q=Populus%20tremuloides');
|
||||
});
|
||||
|
||||
test('no Wikipedia: where to download it', () => {
|
||||
render(<WikipediaLink name='Populus tremuloides' wikipedia={null}/>);
|
||||
expect(screen.getByRole('link', {name: 'Download Wikipedia'})).toHaveAttribute('href', '/zim/manage');
|
||||
});
|
||||
});
|
||||
|
||||
describe('MapSpeciesPanel', () => {
|
||||
test('lists the species near the middle of the map', async () => {
|
||||
render(<MapSpeciesPanel map={fakeMap()}/>);
|
||||
expect(await screen.findByText('quaking aspen')).toBeInTheDocument();
|
||||
expect(screen.getByText('585 nearby')).toBeInTheDocument();
|
||||
expect(screen.getByText('Not nearby')).toBeInTheDocument();
|
||||
expect(api.searchSpecies).toHaveBeenCalledWith(
|
||||
{q: '', group: null, radius_km: 30, lat: '44.0600', lon: '-121.3100'});
|
||||
});
|
||||
|
||||
test('nothing downloaded: says where to subscribe', async () => {
|
||||
api.searchSpecies.mockResolvedValue({species: [], packs: 0, groups: GROUPS});
|
||||
render(<MapSpeciesPanel map={fakeMap()}/>);
|
||||
expect(await screen.findByText(/No species have been downloaded/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', {name: 'Manage'})).toHaveAttribute('href', '/map/manage');
|
||||
});
|
||||
|
||||
test('searching by name asks again', async () => {
|
||||
render(<MapSpeciesPanel map={fakeMap()}/>);
|
||||
await screen.findByText('quaking aspen');
|
||||
await userEvent.type(screen.getByLabelText('Search species'), 'aspen');
|
||||
await waitFor(() => expect(api.searchSpecies).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({q: 'aspen'})));
|
||||
});
|
||||
|
||||
test('the list follows the map', async () => {
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await screen.findByText('quaking aspen');
|
||||
const calls = api.searchSpecies.mock.calls.length;
|
||||
act(() => map.fire('moveend'));
|
||||
await waitFor(() => expect(api.searchSpecies.mock.calls.length).toBe(calls + 1));
|
||||
});
|
||||
|
||||
test('a species: its range is drawn, put back after a style change, and erased on Back', async () => {
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
|
||||
expect(await screen.findByText(/3 places on the map/)).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', {name: 'Read in Wikipedia'})).toBeInTheDocument();
|
||||
expect(screen.getByText('Also called trembling aspen, popple.')).toBeInTheDocument();
|
||||
expect(Object.keys(map.layers).sort()).toEqual([RANGE_LAYERS.high, RANGE_LAYERS.low].sort());
|
||||
expect(map.sources[RANGE_SOURCES.low].data.features).toHaveLength(3);
|
||||
expect(map.sources[RANGE_SOURCES.high].data.features).toHaveLength(5);
|
||||
|
||||
// A new style drops the map's layers; the range comes back.
|
||||
Object.keys(map.layers).forEach((id) => delete map.layers[id]);
|
||||
Object.keys(map.sources).forEach((id) => delete map.sources[id]);
|
||||
act(() => map.fire('style.load'));
|
||||
expect(Object.keys(map.layers)).toHaveLength(2);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', {name: 'Zoom to range'}));
|
||||
// The bounds of the dots drawn: the middles of the first and last cells.
|
||||
expect(map.fitBounds).toHaveBeenCalledWith([[-110.95, 40.05], [-110.75, 40.05]],
|
||||
expect.objectContaining({maxZoom: 12}));
|
||||
|
||||
await userEvent.click(screen.getByRole('button', {name: 'Back'}));
|
||||
expect(Object.keys(map.layers)).toHaveLength(0);
|
||||
expect(Object.keys(map.sources)).toHaveLength(0);
|
||||
expect(await screen.findByText('Mule Deer')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('closing the panel erases the range', async () => {
|
||||
const map = fakeMap();
|
||||
const {unmount} = render(<MapSpeciesPanel map={map}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
await screen.findByText(/3 places on the map/);
|
||||
unmount();
|
||||
expect(Object.keys(map.layers)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when requests fail', () => {
|
||||
test('a failed search keeps the last list and says so', async () => {
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await screen.findByText('quaking aspen');
|
||||
api.searchSpecies.mockResolvedValue(undefined);
|
||||
act(() => map.fire('moveend'));
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Could not search the species. This is the last list');
|
||||
expect(screen.getByText('quaking aspen')).toBeInTheDocument();
|
||||
expect(screen.queryByText(/No species have been seen here/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('a failed first search can be tried again', async () => {
|
||||
api.searchSpecies.mockResolvedValue(undefined);
|
||||
render(<MapSpeciesPanel map={fakeMap()}/>);
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Could not search the species.');
|
||||
expect(screen.queryByText('Searching…')).not.toBeInTheDocument();
|
||||
api.searchSpecies.mockResolvedValue({species: [ASPEN], packs: 1, groups: GROUPS});
|
||||
await userEvent.type(screen.getByLabelText('Search species'), 'a');
|
||||
expect(await screen.findByText('quaking aspen')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('failed details: no Wikipedia suggestion, and the range is still drawn', async () => {
|
||||
api.getSpecies.mockResolvedValue(undefined);
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
expect(await screen.findByText(/3 places on the map/)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Download Wikipedia')).not.toBeInTheDocument();
|
||||
expect(Object.keys(map.layers)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('Zoom to range waits for the dots', async () => {
|
||||
// Both grids are asked for; neither answers until the test says.
|
||||
const answers = [];
|
||||
api.getSpeciesRange.mockImplementation(() => new Promise((resolve) => answers.push(resolve)));
|
||||
render(<MapSpeciesPanel map={fakeMap()}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
expect(screen.getByRole('button', {name: 'Zoom to range'})).toBeDisabled();
|
||||
await act(async () => answers.forEach((resolve) => resolve(dots(3))));
|
||||
await waitFor(() => expect(screen.getByRole('button', {name: 'Zoom to range'})).toBeEnabled());
|
||||
});
|
||||
});
|
||||
|
||||
describe('clicking a dot', () => {
|
||||
test("opens a popup of what was seen in its square; choosing one shows that species", async () => {
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
await screen.findByText(/3 places on the map/);
|
||||
|
||||
const dot = {features: [{geometry: {coordinates: [-121.35, 44.05]}}]};
|
||||
await act(async () => map.fire(`click:${RANGE_LAYERS.low}`, dot));
|
||||
expect(api.getSpeciesHere).toHaveBeenCalledWith(44.05, -121.35, 9, ASPEN.taxon_id);
|
||||
expect(popups).toHaveLength(1);
|
||||
expect(popups[0].lngLat).toEqual([-121.35, 44.05]);
|
||||
const popup = within(popups[0].node);
|
||||
// The stand-in Popup never puts its content in the page, so it is read where it was rendered.
|
||||
await waitFor(() => expect(popups[0].node.textContent).toContain('Seen 25 times in this square (about 11 km).'));
|
||||
|
||||
// Choosing the deer closes the popup and shows the deer.
|
||||
await act(async () => popup.getByRole('button', {name: /Mule Deer/}).click());
|
||||
expect(popups[0].removed).toBe(true);
|
||||
await waitFor(() => expect(api.getSpecies).toHaveBeenLastCalledWith(DEER.taxon_id));
|
||||
});
|
||||
|
||||
test('Back closes the popup and stops listening', async () => {
|
||||
const map = fakeMap();
|
||||
render(<MapSpeciesPanel map={map}/>);
|
||||
await userEvent.click(await screen.findByRole('button', {name: 'quaking aspen'}));
|
||||
await screen.findByText(/3 places on the map/);
|
||||
await act(async () => map.fire(`click:${RANGE_LAYERS.high}`, {features: [{geometry: {coordinates: [-121.3, 44]}}]}));
|
||||
await userEvent.click(screen.getByRole('button', {name: 'Back'}));
|
||||
expect(popups[0].removed).toBe(true);
|
||||
expect(map.handlers[`click:${RANGE_LAYERS.low}`]).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
test('an exported map leaves out the range', () => {
|
||||
const style = {
|
||||
version: 8, sources: {basemap: {type: 'vector'}, [RANGE_SOURCES.low]: {type: 'geojson', data: rangeGeoJSON(dots(1))}},
|
||||
layers: [{id: 'water', type: 'fill', source: 'basemap'}, ...rangeLayers(false)],
|
||||
};
|
||||
const exported = exportStyle(style, [SPECIES_LAYER_PREFIX]);
|
||||
expect(exported.layers.map((layer) => layer.id)).toEqual(['water']);
|
||||
expect(Object.keys(exported.sources)).toEqual(['basemap']);
|
||||
});
|
||||
|
|
@ -27,6 +27,7 @@ jest.mock('../api', () => ({
|
|||
...jest.requireActual('../api'),
|
||||
getMapFiles: jest.fn(),
|
||||
fetchMapSubscriptions: jest.fn(),
|
||||
fetchSpeciesSubscriptions: jest.fn(),
|
||||
getMapPins: jest.fn(),
|
||||
getMapTargets: jest.fn(),
|
||||
getWeather: jest.fn(),
|
||||
|
|
@ -64,6 +65,10 @@ beforeEach(() => {
|
|||
}));
|
||||
api.getMapFiles.mockResolvedValue({files: []});
|
||||
api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []});
|
||||
// A species catalog with a region, so "No results" can only come from the map's table.
|
||||
api.fetchSpeciesSubscriptions.mockResolvedValue({
|
||||
catalog: [{name: 'Alaska', region: 'us-alaska', size_estimate: 5000000}], subscriptions: [], files: [],
|
||||
});
|
||||
api.getMapPins.mockResolvedValue({pins: []});
|
||||
api.getMapTargets.mockResolvedValue([]);
|
||||
api.deleteMapTarget.mockResolvedValue(true);
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ import {
|
|||
import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle";
|
||||
import MapQuadPicker, {QUAD_LAYER_PREFIX} from "./MapQuadPicker";
|
||||
import FalloutPanel, {targetsUnsaved, WeaponPicker, withSavedTargets, withWeapon} from "./FalloutPanel";
|
||||
import MapSpeciesPanel, {RANGE_LAYERS, SPECIES_LAYER_PREFIX} from "./MapSpeciesPanel";
|
||||
import {DEFAULT_WEAPON} from "../map-shared/fallout/targets.js";
|
||||
import {contourInterval, contourThresholds, DEFAULT_TERRAIN_MAX_ZOOM, terrainMaxZoom} from "../map-shared/terrain.js";
|
||||
import {quadAt} from "./mapQuads";
|
||||
|
|
@ -100,6 +101,8 @@ maplibregl.addProtocol("pmtiles", protocol.tile);
|
|||
|
||||
// Planet overview blob — provides global basemap at zoom 0-6.
|
||||
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
|
||||
// Layers the app draws over the map (a quadrangle being chosen, a species' range), which an exported map leaves out.
|
||||
const APP_LAYER_PREFIXES = [QUAD_LAYER_PREFIX, SPECIES_LAYER_PREFIX];
|
||||
|
||||
// Layers to skip from non-primary sources (they would paint over the primary source's content).
|
||||
const SKIP_SECONDARY = new Set(["background", "earth"]);
|
||||
|
|
@ -748,6 +751,9 @@ export default function MapViewer() {
|
|||
const nuclearButtonRef = useRef(null);
|
||||
// The fallout view (nuclear mode): open or not.
|
||||
const [falloutOpen, setFalloutOpen] = useState(false);
|
||||
// The species view: open or not. It and nuclear mode share the panel's place: one at a time.
|
||||
const [speciesOpen, setSpeciesOpen] = useState(false);
|
||||
const speciesButtonRef = useRef(null);
|
||||
// The saved nuclear targets (map_nuclear.yaml).
|
||||
const [savedTargets, setSavedTargets] = useState([]);
|
||||
const markersRef = useRef([]);
|
||||
|
|
@ -957,6 +963,29 @@ export default function MapViewer() {
|
|||
onRemove: () => {},
|
||||
}, "top-right");
|
||||
|
||||
// The species seen around here, and their ranges.
|
||||
const speciesButton = document.createElement("button");
|
||||
speciesButton.type = "button";
|
||||
speciesButton.title = "Species: plants and animals seen here";
|
||||
speciesButton.setAttribute("aria-label", "Species");
|
||||
speciesButton.setAttribute("aria-pressed", "false");
|
||||
speciesButton.textContent = "🌿";
|
||||
speciesButton.style.cssText = pinToggle.style.cssText;
|
||||
speciesButton.addEventListener("click", () => {
|
||||
if (destroyed) return;
|
||||
setSpeciesOpen(open => !open);
|
||||
});
|
||||
speciesButtonRef.current = speciesButton;
|
||||
map.addControl({
|
||||
onAdd: () => {
|
||||
const container = document.createElement("div");
|
||||
container.className = "maplibregl-ctrl maplibregl-ctrl-group";
|
||||
container.appendChild(speciesButton);
|
||||
return container;
|
||||
},
|
||||
onRemove: () => {},
|
||||
}, "top-right");
|
||||
|
||||
// Right-click context menu (desktop).
|
||||
map.on("contextmenu", (e) => {
|
||||
if (destroyed) return;
|
||||
|
|
@ -986,6 +1015,9 @@ export default function MapViewer() {
|
|||
layers.length ? map.queryRenderedFeatures(point, {layers}) : [];
|
||||
map.on("click", (e) => {
|
||||
if (destroyed || pickingQuadRef.current || placingTargetRef.current) return;
|
||||
// A species' range dot has its own popup (the Species panel's).
|
||||
const speciesLayers = Object.values(RANGE_LAYERS).filter(id => map.getLayer(id));
|
||||
if (featuresAt(e.point, speciesLayers).length) return;
|
||||
const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds()))
|
||||
|| poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat);
|
||||
if (!html) return;
|
||||
|
|
@ -1203,8 +1235,10 @@ export default function MapViewer() {
|
|||
// A map file which is of somewhere else is not drawn.
|
||||
const outside = await sourcesOutside(
|
||||
style, [quad.west, quad.south, quad.east, quad.north], readTileBounds);
|
||||
// The quadrangle's outline and a species' range are of the app: they are not exported.
|
||||
const appLayer = id => APP_LAYER_PREFIXES.some(prefix => id.startsWith(prefix));
|
||||
const groups = exportGroups(
|
||||
style.layers.filter(layer => !layer.id.startsWith(QUAD_LAYER_PREFIX) && !outside.has(layer.source)),
|
||||
style.layers.filter(layer => !appLayer(layer.id) && !outside.has(layer.source)),
|
||||
{layerGroups: LAYER_GROUPS, overlayLabels});
|
||||
if (!groups.length) throw new Error("No layer of the map is turned on");
|
||||
// How sharp the map may be depends on how many images it is, which is not known until
|
||||
|
|
@ -1218,7 +1252,7 @@ export default function MapViewer() {
|
|||
style,
|
||||
frameFor,
|
||||
groups,
|
||||
ignoredPrefixes: [QUAD_LAYER_PREFIX],
|
||||
ignoredPrefixes: APP_LAYER_PREFIXES,
|
||||
readTile: readVectorTile,
|
||||
setup: exportMap => exportMap.on("styleimagemissing", e => addMissingOverlayIcon(exportMap, e.id)),
|
||||
// Stopped between two layers, as soon as the person exporting asks.
|
||||
|
|
@ -1409,8 +1443,19 @@ export default function MapViewer() {
|
|||
// Nuclear mode opens the fallout panel on its targets step; leaving it closes the panel.
|
||||
setFalloutOpen(nuclear);
|
||||
if (!nuclear) setPlacingTarget(false);
|
||||
if (nuclear) setSpeciesOpen(false);
|
||||
}, [nuclear, showPins]);
|
||||
|
||||
// The species view open or not: the button says so, and it leaves nuclear mode (they share the panel's place).
|
||||
useEffect(() => {
|
||||
const button = speciesButtonRef.current;
|
||||
if (button) {
|
||||
button.style.background = speciesOpen ? "#b2f2bb" : "white";
|
||||
button.setAttribute("aria-pressed", String(speciesOpen));
|
||||
}
|
||||
if (speciesOpen) setNuclear(false);
|
||||
}, [speciesOpen]);
|
||||
|
||||
// Global callback for popup delete buttons.
|
||||
useEffect(() => {
|
||||
window.__deleteMapPin = async (pinId) => {
|
||||
|
|
@ -1604,6 +1649,10 @@ export default function MapViewer() {
|
|||
setFalloutOpen(false);
|
||||
}}
|
||||
/>}
|
||||
{mapReady && speciesOpen && <MapSpeciesPanel
|
||||
map={mapRef.current}
|
||||
onClose={() => setSpeciesOpen(false)}
|
||||
/>}
|
||||
{addingPin && <AddPinDialog
|
||||
lat={addingPin.lat}
|
||||
lon={addingPin.lon}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue