mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-10-26 19:01:39 -04:00
* ui: a preview map that waited for a container it could never see
Both map preview modals -- the per-region eye button and "View All Regions"
-- opened to an empty box. Each renders a div into a Modal and hands it to
MapLibre from an effect gated on `open`, reading the node out of a `useRef`:
if (!open || !mapContainer.current) return;
Mantine's Modal mounts its body one commit after `opened` flips true, so on
the render that opens the modal the ref is still null. The effect returns,
nothing it depends on changes again, and it never runs a second time. No
console error, no rejected promise, no canvas -- just an empty div.
Semantic UI's Portal mounted the body in the same commit that opened it, so
the ref was attached by the time effects ran. The effect bodies are
byte-identical across that migration; the modal library is the only variable,
confirmed against a device still running the older build where both previews
render.
A callback ref instead, so the effect re-runs when the node arrives and this
stops depending on any modal's mounting schedule. The async source lookup
also gets a cancelled flag: it could resolve after the cleanup ran, building
a map nothing would ever remove and leaking a WebGL context per open.
The tests drive the real page and assert a map was built against a node that
is in the document -- the outcome, rather than the mechanism that quietly
changed underneath it. Seven of the eight fail on the code before this.
* build: docker had no world underneath its map regions
Caddy serves /blobs/map-overview.pmtiles out of /opt/wrolpi-blobs, and that
blob is the world at zoom 0-6 -- what a regional extract sits on top of.
Without it a user who subscribes to a few regions gets those regions floating
on an empty background everywhere their data does not reach. Only a full
planet file, at 134GB, makes it unnecessary.
Raspberry Pi and Debian installs get the blob from pi-gen, the live-build
config, and upgrade.sh. Docker got nothing: the compose file bind-mounted a
git-ignored host directory over /opt/wrolpi-blobs, and a bind mount replaces
the image's directory rather than merging with it, so the path existed and was
empty on every Docker WROLPi. Verified against a running deployment, where
that URL returned 404 while the same URL on hardware returned 206.
So the web image fetches the blob at build time, as the other three builders
do, and the mount that would hide it is gone. `curl -f` so an HTTP error
fails the layer -- an image that builds without the blob is this same bug,
except silent at build time too.
The tests read the deployment files rather than a built container: building
to check costs a CDN download and several minutes, and both things that broke
-- nothing fetches it, a mount hides it -- are visible in the source.
* ui: cancel the load handler too, and make the cancel test falsifiable
Review follow-ups on the preview modals.
The `cancelled` flag was checked before constructing the map but not inside
the `load` handler it installs, so cleanup landing between the two left that
body drawing into a map `remove()` had already torn down. Guarded, mirroring
the `destroyed` pattern in MapViewer.js. The source promise also gets a
`.catch`: the helper cannot reject today, but nothing says it never will, and
an unhandled rejection here would be as quiet as the bug this all started as.
Two test corrections, both cases of an assertion claiming more than it read:
The region-drawing test spied on `addSource` AFTER construction and then
re-fired `load` by hand, so its count came entirely from that manual call and
said nothing about the production path. FakeMap now records the sources it is
given, and the assertion reads what the component's own `load` drew -- each
region once, in order, and none for the entry with no bbox.
The new cancel test passed with the guard deleted, which is worse than not
having it: Mantine had not mounted the modal body when it closed, so the
effect had never run and there was nothing to cancel. It now waits for the
effect to reach the source lookup before closing, and ships beside a control
that releases the same held promise WITHOUT closing and requires a map. The
control is what makes the zero meaningful; verified that removing the guard
fails the cancel test while the control still passes.
694 lines
26 KiB
JavaScript
694 lines
26 KiB
JavaScript
import React, {useEffect, useState} from "react";
|
|
import {
|
|
APIButton,
|
|
ErrorMessage,
|
|
HandPointMessage,
|
|
humanFileSize,
|
|
InfoMessage,
|
|
TabLinks,
|
|
useTitle,
|
|
WROLModeMessage
|
|
} from "./Common";
|
|
import {Route, Routes, useNavigate} from "react-router";
|
|
import {
|
|
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
|
|
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, updateMapPin
|
|
} from "../api";
|
|
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput} from "./ui";
|
|
import {SortableTable} from "./SortableTable";
|
|
import {Media, StatusContext} from "../contexts/contexts";
|
|
import {MAP_VIEWER_URI} from "./Vars";
|
|
import MapViewer from "./MapViewer";
|
|
import {AddToPlaylistButton} from "./AddToPlaylist";
|
|
import maplibregl from "maplibre-gl";
|
|
import {Protocol} from "pmtiles";
|
|
import layers from "protomaps-themes-base";
|
|
|
|
// 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";
|
|
|
|
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
|
|
function isPlanetFile(name) {
|
|
if (name.startsWith("planet-")) return true;
|
|
return /^\d{8}\.pmtiles$/.test(name);
|
|
}
|
|
|
|
// 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();
|
|
if (data?.files) {
|
|
for (const f of data.files) {
|
|
if (isPlanetFile(f.name)) {
|
|
return {type: 'vector', url: `pmtiles:///media/map/${f.name}`};
|
|
}
|
|
}
|
|
}
|
|
} 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)}
|
|
/>}
|
|
<Button
|
|
role={isSubscribed ? 'danger' : undefined}
|
|
color={isSubscribed ? undefined : '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);
|
|
const [catalog, setCatalog] = useState([]);
|
|
const [subscriptions, setSubscriptions] = useState([]);
|
|
const [allRegionsOpen, setAllRegionsOpen] = useState(false);
|
|
const {status} = React.useContext(StatusContext);
|
|
const searchBuilding = status?.flags?.map_search_building;
|
|
|
|
const fetchFiles = async () => {
|
|
try {
|
|
const data = await getMapFiles();
|
|
if (data) {
|
|
setFiles(data.files || []);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
setFiles(undefined);
|
|
}
|
|
};
|
|
|
|
const fetchSubscriptionData = async () => {
|
|
try {
|
|
const data = await fetchMapSubscriptions();
|
|
if (data) {
|
|
setCatalog(data.catalog || []);
|
|
setSubscriptions(data.subscriptions || []);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
};
|
|
|
|
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.name.toLowerCase()},
|
|
{key: 'size', text: 'Size', sortBy: i => i.size || 0},
|
|
{key: 'search', text: 'Search', sortBy: null},
|
|
{key: 'actions', text: '', sortBy: null},
|
|
];
|
|
|
|
const handleBuildSearch = async (filename) => {
|
|
await rebuildMapSearchIndex(filename);
|
|
await fetchFiles();
|
|
};
|
|
|
|
const fileRowFunc = (file) => {
|
|
return <Table.Row key={file.name}>
|
|
<Table.Cell>{file.name}</Table.Cell>
|
|
<Table.Cell>{humanFileSize(file.size)}</Table.Cell>
|
|
<Table.Cell>
|
|
{file.name.startsWith('terrain')
|
|
? 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.name)}>
|
|
{searchBuilding ? 'Building...' : 'Build'}
|
|
</APIButton>
|
|
}
|
|
</Table.Cell>
|
|
<Table.Cell>
|
|
<APIButton
|
|
role='danger'
|
|
size='xs'
|
|
confirmContent='Delete this map file?'
|
|
confirmButton='Delete'
|
|
onClick={() => handleDelete(file.name)}
|
|
>
|
|
Delete
|
|
</APIButton>
|
|
</Table.Cell>
|
|
</Table.Row>;
|
|
};
|
|
|
|
const emptyRow = <Table.Row>
|
|
<Table.Cell colSpan={4}>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>
|
|
</>;
|
|
}
|
|
|
|
/*
|
|
* 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='name'
|
|
defaultSortColumn='name'
|
|
emptyRow={emptyRow}
|
|
/>
|
|
|
|
<Divider/>
|
|
|
|
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
|
|
<Header as='h3'>Map Subscriptions</Header>
|
|
<Button size='xs' icon='globe' onClick={() => setAllRegionsOpen(true)}>View All Regions</Button>
|
|
</div>
|
|
|
|
<AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen} onClose={() => setAllRegionsOpen(false)}/>
|
|
|
|
<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
|
|
<a href='https://maps.protomaps.com/builds/' rel='noopener noreferrer'
|
|
target='_blank'>maps.protomaps.com/builds</a>
|
|
</p>
|
|
</InfoMessage>
|
|
|
|
<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() {
|
|
const [pins, setPins] = useState([]);
|
|
const [filter, setFilter] = useState('');
|
|
const [editingId, setEditingId] = useState(null);
|
|
const navigate = useNavigate();
|
|
|
|
const fetchPins = async () => {
|
|
try {
|
|
const data = await getMapPins();
|
|
if (data) setPins(data.pins || []);
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
};
|
|
|
|
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`);
|
|
};
|
|
|
|
// --- 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 three 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)}/>
|
|
<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>
|
|
<APIButton
|
|
size='xs'
|
|
role='danger'
|
|
icon='trash'
|
|
aria-label={`Delete ${pin.label}`}
|
|
confirmContent='Delete this pin?'
|
|
confirmButton='Delete'
|
|
onClick={() => handleDelete(pin.id)}
|
|
/>
|
|
</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>;
|
|
|
|
const lowerFilter = filter.toLowerCase();
|
|
const filteredPins = lowerFilter
|
|
? 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>
|
|
</>;
|
|
}
|
|
|
|
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'},
|
|
{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='manage' exact element={<ManageMap/>}/>
|
|
</Routes>
|
|
</div>
|
|
}
|