wrolpi/app/src/components/Map.js
lrnselfreliance a429db441e
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>
2026-11-29 19:24:19 -07:00

885 lines
34 KiB
JavaScript

import React, {useEffect, useRef, useState} from "react";
import {
APIButton,
ErrorMessage,
HandPointMessage,
humanFileSize,
InfoMessage,
TabLinks,
useTitle,
WROLModeMessage
} from "./Common";
import {Route, Routes, useNavigate} from "react-router";
import {
deleteMapFile, deleteMapPin, deleteMapTarget, fetchMapSubscriptions, getMapFiles, getMapPins, getMapTargets,
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin
} from "../api";
import {targetWeapon} from "../map-shared/fallout/targets.js";
import {formatYieldAndFission} from "../map-shared/fallout/weapons.js";
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui";
import {SortableTable} from "./SortableTable";
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";
import {Protocol} from "pmtiles";
import layers from "protomaps-themes-base";
import {planMapFiles, pmtilesUrl} from "./mapOverlays";
import {MapAtak} from "./MapAtak";
// Ensure PMTiles protocol is registered (may already be registered by MapViewer).
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
// How the map draws a file (the API's `kind`).
const MAP_FILE_KINDS = {
basemap: 'Basemap',
overlay: 'Overlay',
terrain: 'Terrain',
unknown: 'Unreadable',
};
// Resolve the best available base map source for preview maps.
// Checks for a user's planet file first, falls back to the overview blob.
async function getPreviewMapSource() {
try {
const data = await getMapFiles();
const {planet} = planMapFiles(data?.files);
if (planet) {
return {type: 'vector', url: pmtilesUrl(planet.path)};
}
} catch (e) { /* ignore */ }
return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`};
}
/*
* The container is a piece of state set by a callback ref, not a `useRef` read in the effect.
*
* A modal body is not in the DOM on the render that opens the modal -- Mantine mounts it a
* commit later -- so an effect gated on `open` that reads `ref.current` finds null, returns,
* and never runs again, because nothing it depends on changes after that. Both previews were
* silently blank for exactly this reason. A callback ref re-runs the effect when the node
* arrives, whenever that is, so this does not depend on any modal's mounting schedule.
*/
function RegionPreviewModal({bbox, name, open, onClose}) {
const [mapContainer, setMapContainer] = useState(null);
React.useEffect(() => {
if (!open || !mapContainer || !bbox) return;
const [minLon, minLat, maxLon, maxLat] = bbox.split(',').map(Number);
const centerLon = (minLon + maxLon) / 2;
const centerLat = (minLat + maxLat) / 2;
let map;
// The source lookup is async, so the modal can close before it resolves. Without this
// the cleanup below runs while `map` is still undefined and the map built afterwards
// is never removed -- a leaked WebGL context on every quick open-and-close.
let cancelled = false;
getPreviewMapSource().then(source => {
if (cancelled) return;
map = new maplibregl.Map({
container: mapContainer,
style: {
version: 8,
sources: {'basemap': source},
layers: layers('basemap', 'light'),
glyphs: '/map-assets/fonts/{fontstack}/{range}.pbf',
sprite: `${window.location.origin}/map-assets/sprites/light`,
},
center: [centerLon, centerLat],
zoom: 1,
attributionControl: false,
});
map.on('load', () => {
// The flag again: cleanup can land between construction and `load`, and this
// body draws into a map `remove()` has already torn down.
if (cancelled) return;
map.addSource('bbox', {
type: 'geojson',
data: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[
[minLon, minLat],
[maxLon, minLat],
[maxLon, maxLat],
[minLon, maxLat],
[minLon, minLat],
]],
},
},
});
map.addLayer({
id: 'bbox-fill',
type: 'fill',
source: 'bbox',
paint: {'fill-color': '#6435c9', 'fill-opacity': 0.2},
});
map.addLayer({
id: 'bbox-outline',
type: 'line',
source: 'bbox',
paint: {'line-color': '#6435c9', 'line-width': 2},
});
map.fitBounds([[minLon, minLat], [maxLon, maxLat]], {padding: 40});
});
}).catch(e => console.error('Could not build the region preview map:', e));
return () => {
cancelled = true;
if (map) map.remove();
};
}, [open, bbox, mapContainer]);
return <Modal open={open} onClose={onClose} size='fullscreen' closeIcon title={name}>
{/* No `.media` here: the bbox highlight is drawn as a map layer on the canvas itself
(see the `bbox` source/layers above), so the automatic `canvas` element-type filter
already covers it. There is no separate DOM overlay to wrap. */}
<div ref={setMapContainer} style={{width: '100%', height: '50vh'}}/>
</Modal>;
}
// Random-ish distinct colors for region boxes. These are map-data paint colors (drawn
// on the WebGL canvas itself), not UI chrome, so they are not theme tokens.
const REGION_COLORS = [
'#6435c9', '#e03997', '#00b5ad', '#2185d0', '#f2711c', '#b5cc18',
'#a333c8', '#21ba45', '#db2828', '#fbbd08', '#a5673f', '#767676',
];
// See RegionPreviewModal for why the container is state set by a callback ref.
function AllRegionsPreviewModal({catalog, open, onClose}) {
const [mapContainer, setMapContainer] = useState(null);
React.useEffect(() => {
if (!open || !mapContainer) return;
let map;
let cancelled = false;
getPreviewMapSource().then(source => {
if (cancelled) return;
map = new maplibregl.Map({
container: mapContainer,
style: {
version: 8,
sources: {'basemap': source},
layers: layers('basemap', 'light'),
glyphs: '/map-assets/fonts/{fontstack}/{range}.pbf',
sprite: `${window.location.origin}/map-assets/sprites/light`,
},
center: [0, 20],
zoom: 1,
attributionControl: false,
});
map.on('load', () => {
// See RegionPreviewModal: cleanup can land between construction and `load`.
if (cancelled) return;
const regions = catalog.filter(r => r.bbox);
regions.forEach((region, i) => {
const [minLon, minLat, maxLon, maxLat] = region.bbox.split(',').map(Number);
const color = REGION_COLORS[i % REGION_COLORS.length];
const id = `region-${i}`;
map.addSource(id, {
type: 'geojson',
data: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[
[minLon, minLat], [maxLon, minLat],
[maxLon, maxLat], [minLon, maxLat],
[minLon, minLat],
]],
},
properties: {name: region.name},
},
});
map.addLayer({
id: `${id}-fill`, type: 'fill', source: id,
paint: {'fill-color': color, 'fill-opacity': 0.15},
});
map.addLayer({
id: `${id}-outline`, type: 'line', source: id,
paint: {'line-color': color, 'line-width': 1.5},
});
map.addLayer({
id: `${id}-label`, type: 'symbol', source: id,
layout: {
'text-field': ['get', 'name'],
'text-size': 11,
'text-allow-overlap': true,
},
paint: {
'text-color': color,
'text-halo-color': 'white',
'text-halo-width': 1,
},
});
});
});
}).catch(e => console.error('Could not build the all-regions preview map:', e));
return () => {
cancelled = true;
if (map) map.remove();
};
}, [open, catalog, mapContainer]);
return <Modal open={open} onClose={onClose} size='fullscreen' closeIcon title='All Map Regions'>
{/* No `.media` here either — same reasoning as RegionPreviewModal. */}
<div ref={setMapContainer} style={{width: '100%', height: '75vh'}}/>
</Modal>;
}
function MapCatalogRow({item, subscribedRegions, fetchData}) {
const {name, region, size_estimate, bbox} = item;
const isSubscribed = subscribedRegions.has(region);
const [previewOpen, setPreviewOpen] = useState(false);
const handleButton = async () => {
if (isSubscribed) {
await mapUnsubscribe(region);
} else {
await mapSubscribe(name, region);
}
if (fetchData) {
await fetchData();
}
};
return <Table.Row>
<Table.Cell>{name}</Table.Cell>
<Table.Cell>{humanFileSize(size_estimate)}</Table.Cell>
<Table.Cell>
{/* See PinEditRow: a Group so the preview and subscribe controls line up and are
spaced, rather than sitting on baselines they do not share. */}
<Group gap='xs' wrap='nowrap'>
{bbox && <Button
size='xs'
icon='eye'
aria-label={`Preview ${name}`}
onClick={() => setPreviewOpen(true)}
/>}
{/* A `color` would replace the danger role's red, so only Subscribe has one. */}
<Button
{...(isSubscribed ? {role: 'danger'} : {color: 'violet'})}
size='xs'
onClick={handleButton}
>
{isSubscribed ? 'Unsubscribe' : 'Subscribe'}
</Button>
</Group>
</Table.Cell>
{previewOpen && <RegionPreviewModal
bbox={bbox}
name={name}
open={previewOpen}
onClose={() => setPreviewOpen(false)}
/>}
</Table.Row>;
}
function ManageMap() {
const [files, setFiles] = useState(null);
// null = pending, undefined = fetch failed, [] = no regions in the catalog.
const [catalog, setCatalog] = useState(null);
const [subscriptions, setSubscriptions] = useState([]);
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
const {status} = React.useContext(StatusContext);
const searchBuilding = status?.flags?.map_search_building;
// Only the newest subscriptions request may write state: a subscribe or unsubscribe refetches
// while the mount request may still be in flight.
const subscriptionsGen = useRef(0);
const fetchFiles = async () => {
try {
const data = await getMapFiles();
if (data) {
setFiles(data.files || []);
}
} catch (e) {
console.error(e);
setFiles(undefined);
}
};
const fetchSubscriptionData = async () => {
const gen = ++subscriptionsGen.current;
try {
const data = await fetchMapSubscriptions();
if (gen !== subscriptionsGen.current) {
return;
}
if (data) {
setCatalog(data.catalog || []);
setSubscriptions(data.subscriptions || []);
} else {
// The api helper already toasted the non-OK response.
setCatalog(undefined);
}
} catch (e) {
console.error(e);
if (gen === subscriptionsGen.current) {
setCatalog(undefined);
}
}
};
useEffect(() => {
fetchFiles();
fetchSubscriptionData();
const interval = setInterval(fetchFiles, 30000);
return () => clearInterval(interval);
}, []);
const handleDelete = async (filename) => {
await deleteMapFile(filename);
await fetchFiles();
};
// --- Files table ---
const fileHeaders = [
{key: 'name', text: 'File', sortBy: i => i.map_path.toLowerCase()},
{key: 'kind', text: 'Type', sortBy: i => i.kind || ''},
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
{key: 'search', text: 'Search', sortBy: null},
{key: 'actions', text: '', sortBy: null},
{key: 'visible', text: 'Visible', sortBy: i => (i.visible === false ? 0 : 1)},
];
const handleBuildSearch = async (mapPath) => {
await rebuildMapSearchIndex(mapPath);
await fetchFiles();
};
const handleVisible = async (file, visible) => {
try {
await setMapFileVisible(file.map_path, visible);
} finally {
await fetchFiles();
}
};
const fileRowFunc = (file) => {
return <Table.Row key={file.map_path}>
<Table.Cell>
{/* A file in a sub-directory is shown with its directory. */}
{file.map_path}
{file.title && file.title !== file.name.replace(/\.pmtiles$/, '') && <div style={{fontSize: '0.75rem', color: 'var(--muted)'}}
title={file.description || undefined}>{file.title}</div>}
</Table.Cell>
<Table.Cell>
{MAP_FILE_KINDS[file.kind] || ''}
{/* A style beside the file says how it is drawn. */}
{file.kind === 'overlay' && file.style_path ? ' (styled)' : ''}
</Table.Cell>
<Table.Cell>{humanFileSize(file.size)}</Table.Cell>
<Table.Cell>
{/* A search index is built from a basemap's places; other files have none. */}
{file.kind !== 'basemap'
? null
: file.has_search_index
? <Button size='xs' icon='check' disabled role='save'>Built</Button>
: <APIButton size='xs' icon='search'
disabled={searchBuilding}
loading={searchBuilding}
onClick={() => handleBuildSearch(file.map_path)}>
{searchBuilding ? 'Building...' : 'Build'}
</APIButton>
}
</Table.Cell>
<Table.Cell>
<APIButton
role='danger'
size='xs'
confirmContent='Delete this map file?'
confirmButton='Delete'
onClick={() => handleDelete(file.map_path)}
>
Delete
</APIButton>
</Table.Cell>
<Table.Cell>
<Toggle
aria-label={`Show ${file.map_path} on the map`}
title='Show this file on the map, or ignore it.'
checked={file.visible !== false}
onChange={(e) => handleVisible(file, e.currentTarget.checked)}
/>
</Table.Cell>
</Table.Row>;
};
const emptyRow = <Table.Row>
<Table.Cell colSpan={6}>No PMTiles map files were found in <b>map/</b></Table.Cell>
</Table.Row>;
// --- Catalog table ---
const catalogHeaders = [
{key: 'name', text: 'Region', sortBy: i => i.name.toLowerCase()},
{key: 'size', text: 'Estimated Size', sortBy: i => i.size_estimate || 0},
{key: 'actions', text: '', sortBy: null},
];
const catalogRowFunc = (item) => {
return <MapCatalogRow
key={item.region}
item={item}
subscribedRegions={new Set(subscriptions.map(s => s.region))}
fetchData={fetchSubscriptionData}
/>;
};
if (files === undefined) {
return <>
<WROLModeMessage content='Cannot modify Map'/>
<ErrorMessage>Could not fetch map files</ErrorMessage>
</>;
}
const catalogLoaded = Array.isArray(catalog);
/*
* A fragment, not a `PageContainer`. `MapRoute` already provides the page chrome -- a
* `wrolpi-stack` wrapper with its own top margin -- so a second one put this page a further
* 1em down and 1em in from the tab bar than the viewer beside it.
*/
return <>
<WROLModeMessage content='Cannot modify Map'/>
<Header as='h3'>Map Files</Header>
<SortableTable
tableHeaders={fileHeaders}
data={files}
rowFunc={fileRowFunc}
rowKey='map_path'
defaultSortColumn='name'
emptyRow={emptyRow}
/>
<Divider/>
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
<Header as='h3'>Map Subscriptions</Header>
{/* A pending or failed catalog is not "zero regions": the preview waits for one. The
modal is mounted only then, so it receives the state array itself and its map is
not rebuilt by a fresh `[]` on every status tick. */}
<Button size='xs' icon='globe' disabled={!catalogLoaded} onClick={() => setAllRegionsOpen(true)}>
View All Regions
</Button>
</div>
{catalogLoaded && <AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen}
onClose={() => setAllRegionsOpen(false)}/>}
{catalog === undefined
? <ErrorMessage>Could not fetch map subscriptions</ErrorMessage>
: <SortableTable
tableHeaders={catalogHeaders}
data={catalog}
rowFunc={catalogRowFunc}
rowKey='region'
defaultSortColumn='name'
/>}
<InfoMessage storageName='hint_map_subscribe'>
<div style={{fontWeight: 600, marginBottom: 4}}>How to get map files</div>
<p>Subscribe to a map region to automatically download it. Subscriptions will
periodically check for updated maps. Downloads may take a long time depending on
the region size and your internet speed. You can monitor progress on
the <b>Downloads</b> page.</p>
<p>You can also manually extract a region using the <b>pmtiles</b> command-line tool
and place the resulting file into the <b>map/</b> directory:</p>
<pre> pmtiles extract https://build.protomaps.com/YYYYMMDD.pmtiles region.pmtiles \{'\n'} --bbox="-125.0,24.4,-66.9,49.4"</pre>
<p>Find the latest build date at&nbsp;
<a href='https://maps.protomaps.com/builds/' rel='noopener noreferrer'
target='_blank'>maps.protomaps.com/builds</a>
</p>
</InfoMessage>
<Divider/>
<SpeciesSection/>
<Divider/>
<WeatherSection/>
<HandPointMessage>
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
</>
}
const PIN_COLORS = ["red", "blue", "green", "yellow", "orange", "purple"];
function PinEditRow({pin, onSave, onCancel}) {
const [label, setLabel] = useState(pin.label);
const [color, setColor] = useState(pin.color);
return <Table.Row>
<Table.Cell>
<div style={{display: "flex", gap: 4}}>
{PIN_COLORS.map(c =>
<div
key={c}
onClick={() => setColor(c)}
style={{
width: 20, height: 20, borderRadius: "50%", background: c, cursor: "pointer",
border: color === c ? "3px solid var(--text)" : "2px solid var(--border)",
}}
/>
)}
</div>
</Table.Cell>
<Table.Cell>
<TextInput
size='sm'
value={label}
onChange={(e) => setLabel(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && label.trim() && onSave(pin.id, label.trim(), color)}
/>
</Table.Cell>
<Table.Cell>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</Table.Cell>
<Media greaterThan='mobile'><Table.Cell>{pin.created}</Table.Cell></Media>
<Table.Cell>
{/* A Group, not bare siblings: inline-block controls align on text baselines they
do not share, and JSX leaves no whitespace between them to space them out. */}
<Group gap='xs' wrap='nowrap'>
<Button size='xs' role='save'
onClick={() => label.trim() && onSave(pin.id, label.trim(), color)}>Save</Button>
<Button size='xs' role='cancel' onClick={onCancel}>Cancel</Button>
</Group>
</Table.Cell>
</Table.Row>;
}
function MapPins() {
// null = pending, undefined = fetch failed, [] = no pins. The empty row invites the user to
// add one, so it may only appear for a confirmed empty list.
const [pins, setPins] = useState(null);
const [filter, setFilter] = useState('');
const [editingId, setEditingId] = useState(null);
const navigate = useNavigate();
// Only the newest pins request may write state: an edit or delete refetches while the mount
// request may still be in flight.
const pinsGen = useRef(0);
const fetchPins = async () => {
const gen = ++pinsGen.current;
try {
const data = await getMapPins();
if (gen === pinsGen.current) {
// The api helper returns undefined on a non-OK response.
setPins(data ? data.pins || [] : undefined);
}
} catch (e) {
console.error(e);
if (gen === pinsGen.current) {
setPins(undefined);
}
}
};
useEffect(() => {
fetchPins();
}, []);
const handleDelete = async (pinId) => {
await deleteMapPin(pinId);
setEditingId(null);
await fetchPins();
};
const handleSave = async (pinId, label, color) => {
await updateMapPin(pinId, label, color);
setEditingId(null);
await fetchPins();
};
const handleNavigate = (pin) => {
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
};
const solarButton = (pin) => <Button size='xs' icon='sun' aria-label={`Solar estimate for ${pin.label}`}
onClick={() => navigate(solarCalculatorPath(pin.lat, pin.lon))}/>;
// --- Desktop headers and row ---
const fullHeaders = [
{key: 'color', text: '', sortBy: i => i.color},
{key: 'label', text: 'Label', sortBy: i => i.label.toLowerCase()},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (pin) => {
if (editingId === pin.id) {
return <PinEditRow
key={pin.id}
pin={pin}
onSave={handleSave}
onCancel={() => setEditingId(null)}
/>;
}
return <Table.Row key={pin.id}>
<Table.Cell>
<div style={{
width: 16, height: 16, borderRadius: "50%",
background: pin.color || "red", border: "1px solid var(--border)",
}}/>
</Table.Cell>
<Table.Cell>{pin.label}</Table.Cell>
<Table.Cell>
<a href="#" onClick={(e) => {e.preventDefault(); handleNavigate(pin);}}>
{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}
</a>
</Table.Cell>
<Table.Cell>{pin.created}</Table.Cell>
<Table.Cell>
{/* See PinEditRow: a Group so the controls line up and are spaced. */}
<Group gap='xs' wrap='nowrap'>
<Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`}
onClick={() => setEditingId(pin.id)}/>
{solarButton(pin)}
<AddToPlaylistButton
size='xs'
icon='list'
content=''
url={{url: `/map?lat=${pin.lat}&lon=${pin.lon}&z=14`, title: pin.label}}
/>
<APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${pin.label}`}
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
</Group>
</Table.Cell>
</Table.Row>;
};
// --- Mobile headers and row ---
const mobileHeaders = [
{key: 'color', text: '', sortBy: i => i.color},
{key: 'label', text: 'Label', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (pin) => {
return <Table.Row key={pin.id}>
<Table.Cell>
<div style={{
width: 16, height: 16, borderRadius: "50%",
background: pin.color || "red", border: "1px solid var(--border)",
}}/>
</Table.Cell>
<Table.Cell>
<a href="#" onClick={(e) => {e.preventDefault(); handleNavigate(pin);}}>
{pin.label}
</a>
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
</Table.Cell>
<Table.Cell>
<Group gap='xs' wrap='nowrap'>
{solarButton(pin)}
<APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${pin.label}`}
confirmContent='Delete this pin?'
confirmButton='Delete'
onClick={() => handleDelete(pin.id)}
/>
</Group>
</Table.Cell>
</Table.Row>;
};
const emptyRow = <Table.Row>
<Table.Cell colSpan={5}>No pins. Right-click on the map to add one.</Table.Cell>
</Table.Row>;
if (pins === undefined) {
return <ErrorMessage>Could not fetch map pins</ErrorMessage>;
}
const lowerFilter = filter.toLowerCase();
// Pending (null) passes through so SortableTable shows its placeholder.
const filteredPins = lowerFilter && pins
? pins.filter(p =>
(p.label || '').toLowerCase().includes(lowerFilter) ||
`${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter)
)
: pins;
// A fragment for the same reason as ManageMap above. The filter carries no `marginBottom`
// either: it is a top-level block of the page, and the route's stack spaces it.
return <>
<TextInput
leftSection={<Icon name='search'/>}
placeholder='Filter by label or coordinates...'
value={filter}
onChange={(e) => setFilter(e.target.value)}
style={{width: '100%'}}
/>
<Media at='mobile'>
<SortableTable
tableHeaders={mobileHeaders}
data={filteredPins}
rowFunc={mobileRowFunc}
rowKey='label'
defaultSortColumn='label'
emptyRow={emptyRow}
/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable
tableHeaders={fullHeaders}
data={filteredPins}
rowFunc={fullRowFunc}
rowKey='label'
defaultSortColumn='label'
emptyRow={emptyRow}
/>
</Media>
<MapTargets filter={lowerFilter}/>
</>;
}
// The saved nuclear targets (map_nuclear.yaml), apart from the pins: what each is and where, and
// deleting one. `filter` (lower case) matches a name or coordinates.
export function MapTargets({filter = ''}) {
// null = pending, undefined = fetch failed, [] = no targets.
const [targets, setTargets] = useState(null);
const navigate = useNavigate();
const gen = useRef(0);
const fetchTargets = async () => {
const mine = ++gen.current;
const saved = await getMapTargets();
if (mine === gen.current) setTargets(saved);
};
useEffect(() => {
fetchTargets();
}, []);
const handleDelete = async (targetId) => {
await deleteMapTarget(targetId);
await fetchTargets();
};
const weaponOf = (target) => {
const chosen = targetWeapon(target);
return `${chosen.weapon ? chosen.weapon.name : 'A yield of my own'}, `
+ formatYieldAndFission(chosen.yieldKt, chosen.fissionFraction);
};
const place = (target) => {
const to = `/map?lat=${target.lat}&lon=${target.lon}&z=10`;
return <a href={to} onClick={(e) => {
e.preventDefault();
navigate(to);
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)}</a>;
};
const deleteButton = (target) => <APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${target.label}`}
confirmContent='Delete this target?'
confirmButton='Delete'
onClick={() => handleDelete(target.id)}
/>;
const fullHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'weapon', text: 'Weapon', sortBy: i => targetWeapon(i).yieldKt},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell><span aria-hidden>☢ </span>{target.label}</Table.Cell>
<Table.Cell>{weaponOf(target)}</Table.Cell>
<Table.Cell>{place(target)}</Table.Cell>
<Table.Cell>{target.created}</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const mobileHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell>
<span aria-hidden>☢ </span>{target.label}
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{weaponOf(target)}</div>
<div style={{fontSize: '0.6875rem'}}>{place(target)}</div>
</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const emptyRow = <Table.Row>
<Table.Cell colSpan={5}>No targets. Turn on nuclear mode (☢) on the map to add and save some.</Table.Cell>
</Table.Row>;
const shown = filter && targets
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
: targets;
return <>
<Header as='h3'>Nuclear Targets</Header>
{targets === undefined ? <ErrorMessage>Could not fetch the nuclear targets</ErrorMessage> : <>
<Media at='mobile'>
<SortableTable tableHeaders={mobileHeaders} data={shown} rowFunc={mobileRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable tableHeaders={fullHeaders} data={shown} rowFunc={fullRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
</>}
</>;
}
function MapPage() {
return <MapViewer/>;
}
export function MapRoute() {
useTitle('Map');
const links = [
{text: 'Map', to: '/map', key: 'map', end: true},
{text: 'Pins', to: '/map/pins', key: 'pins'},
// Manage (and Statistics, on pages which have one) are the last tabs.
{text: 'ATAK', to: '/map/atak', key: 'atak'},
{text: 'Manage', to: '/map/manage', key: 'manage'},
];
// `wrolpi-stack`: as in ZimRoute, this route wraps its own content instead of using
// PageContainer, so the spacing below the tab bar is this element's to provide.
return <div className='wrolpi-stack' style={{marginTop: '2em'}}>
<TabLinks links={links}/>
<Routes>
<Route path='/' exact element={<MapPage/>}/>
<Route path='pins' exact element={<MapPins/>}/>
<Route path='atak' exact element={<MapAtak/>}/>
<Route path='manage' exact element={<ManageMap/>}/>
</Routes>
</div>
}