fix: keep a named place's own point in situation briefs

Brief sections received a named place as its bounding box, so they centered
on the box's middle: Tokyo's aircraft were sorted from a point in the
Pacific. Sections now receive the place name and resolve it like a direct
query, and place lookups are cached briefly so a brief resolves it once.
This commit is contained in:
Sameh Khamis committed 2026-10-02 15:21:36 -07:00
1 parent 1b3aa8de8b
commit 4af15aa6a9
5 files changed
+137 -21

No files matched your search

+42 -5
View File
@@ -20,18 +20,55 @@ const POINT_RADIUS_DEGREES = 0.25;
*/
export function createGeocodePlaceService({
fetchImpl = (...args) => globalThis.fetch(...args),
cacheSize = 200,
cacheMs = 10 * 60_000,
now = () => Date.now(),
} = {}) {
// Recent answers by name, so tools that combine others resolve a place to
// the same point once instead of once per section.
const cache = new Map();
async function lookup(name) {
const query = new URLSearchParams({ q: name });
const response = await fetchImpl(`/api/geocode?${query}`);
if (!response.ok) throw new Error(`Geocode HTTP ${response.status}`);
const payload = await response.json();
return placeFromGeocodeResult(payload?.results?.[0]);
}
return {
async resolve(name, { signal } = {}) {
const query = new URLSearchParams({ q: name });
const response = await fetchImpl(`/api/geocode?${query}`, { signal });
if (!response.ok) throw new Error(`Geocode HTTP ${response.status}`);
const payload = await response.json();
return placeFromGeocodeResult(payload?.results?.[0]);
signal?.throwIfAborted();
const key = name.trim().toLowerCase();
const hit = cache.get(key);
if (hit && now() - hit.at < cacheMs) {
cache.delete(key);
cache.set(key, hit);
return waitFor(hit.place, signal);
}
const place = lookup(name);
const entry = { at: now(), place };
cache.set(key, entry);
while (cache.size > cacheSize) cache.delete(cache.keys().next().value);
place.catch(() => {
if (cache.get(key) === entry) cache.delete(key);
});
return waitFor(place, signal);
},
};
}
/** Settle with `promise`, or reject when `signal` aborts first. */
function waitFor(promise, signal) {
if (!signal) return promise;
signal.throwIfAborted();
return new Promise((resolve, reject) => {
const abort = () => reject(signal.reason);
signal.addEventListener('abort', abort, { once: true });
promise
.then(resolve, reject)
.finally(() => signal.removeEventListener('abort', abort));
});
}
/** Convert one geocode result to a place with bounds, or null. */
export function placeFromGeocodeResult(result) {
const location = result?.geometry?.location;