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 {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
{/* 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. */}
;
}
// 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
{/* No `.media` here either — same reasoning as RegionPreviewModal. */}
;
}
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
{name}{humanFileSize(size_estimate)}
{/* See PinEditRow: a Group so the preview and subscribe controls line up and are
spaced, rather than sitting on baselines they do not share. */}
{bbox &&
{previewOpen && setPreviewOpen(false)}
/>}
;
}
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
{/* A file in a sub-directory is shown with its directory. */}
{file.map_path}
{file.title && file.title !== file.name.replace(/\.pmtiles$/, '') &&
{file.title}
}
{MAP_FILE_KINDS[file.kind] || ''}
{/* A style beside the file says how it is drawn. */}
{file.kind === 'overlay' && file.style_path ? ' (styled)' : ''}
{humanFileSize(file.size)}
{/* A search index is built from a basemap's places; other files have none. */}
{file.kind !== 'basemap'
? null
: file.has_search_index
? Built
: handleBuildSearch(file.map_path)}>
{searchBuilding ? 'Building...' : 'Build'}
}
handleDelete(file.map_path)}
>
Delete
handleVisible(file, e.currentTarget.checked)}
/>
;
};
const emptyRow = No PMTiles map files were found in map/;
// --- 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 s.region))}
fetchData={fetchSubscriptionData}
/>;
};
if (files === undefined) {
return <>
Could not fetch map files
>;
}
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 <>
Map Files
Map Subscriptions
{/* 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. */}
setAllRegionsOpen(true)}>
View All Regions
{catalogLoaded && setAllRegionsOpen(false)}/>}
{catalog === undefined
? Could not fetch map subscriptions
: }
How to get map files
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 Downloads page.
You can also manually extract a region using the pmtiles command-line tool
and place the resulting file into the map/ directory:
setLabel(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && label.trim() && onSave(pin.id, label.trim(), color)}
/>
{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}{pin.created}
{/* 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. */}
label.trim() && onSave(pin.id, label.trim(), color)}>SaveCancel
;
}
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) => 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 setEditingId(null)}
/>;
}
return {pin.label} {e.preventDefault(); handleNavigate(pin);}}>
{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}
{pin.created}
{/* See PinEditRow: a Group so the controls line up and are spaced. */}
setEditingId(pin.id)}/>
{solarButton(pin)}
handleDelete(pin.id)}
/>
;
};
// --- 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 {e.preventDefault(); handleNavigate(pin);}}>
{pin.label}
{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}
{solarButton(pin)}
handleDelete(pin.id)}
/>
;
};
const emptyRow = No pins. Right-click on the map to add one.;
if (pins === undefined) {
return Could not fetch map pins;
}
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 <>
}
placeholder='Filter by label or coordinates...'
value={filter}
onChange={(e) => setFilter(e.target.value)}
style={{width: '100%'}}
/>
>;
}
// 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 {
e.preventDefault();
navigate(to);
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)};
};
const deleteButton = (target) => 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) => ☢ {target.label}{weaponOf(target)}{place(target)}{target.created}{deleteButton(target)};
const mobileHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (target) => ☢ {target.label}
{weaponOf(target)}
{place(target)}
{deleteButton(target)};
const emptyRow = No targets. Turn on nuclear mode (☢) on the map to add and save some.;
const shown = filter && targets
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
: targets;
return <>
Nuclear Targets
{targets === undefined ? Could not fetch the nuclear targets : <>
>}
>;
}
function MapPage() {
return ;
}
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