feat: v0.4.1 — untrack map-asset pack (~100 MB): compose volume mount + runtime fallback to remote OFM styles

This commit is contained in:
2026-09-17 09:14:34 +00:00
parent 501c452377
commit 1c50cfeab2
791 changed files with 257 additions and 5171 deletions
+92 -84
View File
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState, type ChangeEvent } from 'react';
import * as maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import pkg from '../package.json';
import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, styleUrl } from '../lib/mapStyles';
import { DEFAULT_STYLE_ID, STYLES, STYLE_STORAGE_KEY, isStyleId, localAssetsAvailable, styleUrlFor } from '../lib/mapStyles';
const EUROPE_CENTER: [number, number] = [10, 52];
const INITIAL_ZOOM = 4;
@@ -36,105 +36,113 @@ export default function Map() {
// route that serves the worker script (and its relative imports) from node_modules.
maplibregl.setWorkerUrl('/api/mlworker/maplibre-gl-worker.mjs');
const map = new maplibregl.Map({
container: containerRef.current,
style: styleUrl(DEFAULT_STYLE_ID), // self-hosted style (public/styles/)
center: EUROPE_CENTER,
zoom: INITIAL_ZOOM,
minZoom: MIN_ZOOM,
maxZoom: MAX_ZOOM,
});
mapRef.current = map;
// Dev/e2e hook so tests can project coordinates to screen space.
(window as unknown as Record<string, unknown>).__flightMap = map;
let cancelled = false;
const onAirportClick = (e: maplibregl.MapLayerMouseEvent) => {
const f = e.features?.[0];
if (!f) return;
const p = f.properties as { name: string; icao: string };
new maplibregl.Popup({ offset: 10 })
.setLngLat(f.geometry.coordinates as [number, number])
.setHTML(
`<div data-testid="airport-popup"><strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}</div>`,
)
.addTo(map);
};
// Defer map creation until the asset-pack probe resolves — one cheap local
// request decides between self-hosted styles (volume-mounted public/) and the
// remote openfreemap.org fallback. The persisted style choice is read here,
// post-mount: SSR hydration stays safe (server + first paint use the default),
// and applying it at creation time avoids a fiord→saved-style flash.
void localAssetsAvailable().then((available) => {
if (cancelled || !containerRef.current) return;
const loadAirports = () => {
if (!airportsPromiseRef.current) {
airportsPromiseRef.current = fetch('/api/airports')
.then((res) => {
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
return res.json() as Promise<{ features: unknown[] }>;
})
.then((data) => {
setAirportCount(data.features.length); // exactly once per page life
return data;
const saved = window.localStorage.getItem(STYLE_STORAGE_KEY);
const initialId = saved && isStyleId(saved) ? saved : DEFAULT_STYLE_ID;
setStyleId(initialId);
const map = new maplibregl.Map({
container: containerRef.current,
style: styleUrlFor(initialId, available), // local pack or remote OFM fallback
center: EUROPE_CENTER,
zoom: INITIAL_ZOOM,
minZoom: MIN_ZOOM,
maxZoom: MAX_ZOOM,
});
mapRef.current = map;
// Dev/e2e hook so tests can project coordinates to screen space.
(window as unknown as Record<string, unknown>).__flightMap = map;
const onAirportClick = (e: maplibregl.MapLayerMouseEvent) => {
const f = e.features?.[0];
if (!f) return;
const p = f.properties as { name: string; icao: string };
new maplibregl.Popup({ offset: 10 })
.setLngLat(f.geometry.coordinates as [number, number])
.setHTML(
`<div data-testid="airport-popup"><strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}</div>`,
)
.addTo(map);
};
const loadAirports = () => {
if (!airportsPromiseRef.current) {
airportsPromiseRef.current = fetch('/api/airports')
.then((res) => {
if (!res.ok) throw new Error(`GET /api/airports → HTTP ${res.status}`);
return res.json() as Promise<{ features: unknown[] }>;
})
.then((data) => {
setAirportCount(data.features.length); // exactly once per page life
return data;
});
}
return airportsPromiseRef.current;
};
// Idempotent, so it can run on EVERY styledata event: map.setStyle() removes all
// sources/layers not in the new style, which wipes our GeoJSON layer after each
// switch — this re-establishes it (and the initial load goes through here too).
const ensureAirportsLayer = async () => {
let data: { features: unknown[] };
try {
data = await loadAirports();
} catch (err) {
console.error('failed to load airports', err);
return;
}
if (!map.getSource(AIRPORTS_SOURCE_ID)) {
map.addSource(AIRPORTS_SOURCE_ID, { type: 'geojson', data });
}
if (!map.getLayer(AIRPORTS_LAYER_ID)) {
map.addLayer({
id: AIRPORTS_LAYER_ID,
type: 'circle',
source: AIRPORTS_SOURCE_ID,
paint: {
'circle-radius': 3,
'circle-color': '#e11d48',
'circle-stroke-width': 1,
'circle-stroke-color': '#ffffff',
},
});
}
return airportsPromiseRef.current;
};
}
// Layer-scoped listeners survive setStyle (they filter by layer id at event
// time), so off+on with the same reference re-wires without duplicating.
map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
map.on('click', AIRPORTS_LAYER_ID, onAirportClick);
};
// Idempotent, so it can run on EVERY styledata event: map.setStyle() removes all
// sources/layers not in the new style, which wipes our GeoJSON layer after each
// switch — this re-establishes it (and the initial load goes through here too).
const ensureAirportsLayer = async () => {
let data: { features: unknown[] };
try {
data = await loadAirports();
} catch (err) {
console.error('failed to load airports', err);
return;
}
if (!map.getSource(AIRPORTS_SOURCE_ID)) {
map.addSource(AIRPORTS_SOURCE_ID, { type: 'geojson', data });
}
if (!map.getLayer(AIRPORTS_LAYER_ID)) {
map.addLayer({
id: AIRPORTS_LAYER_ID,
type: 'circle',
source: AIRPORTS_SOURCE_ID,
paint: {
'circle-radius': 3,
'circle-color': '#e11d48',
'circle-stroke-width': 1,
'circle-stroke-color': '#ffffff',
},
});
}
// Layer-scoped listeners survive setStyle (they filter by layer id at event
// time), so off+on with the same reference re-wires without duplicating.
map.off('click', AIRPORTS_LAYER_ID, onAirportClick);
map.on('click', AIRPORTS_LAYER_ID, onAirportClick);
};
if (map.isStyleLoaded()) void ensureAirportsLayer();
else map.on('styledata', () => void ensureAirportsLayer());
if (map.isStyleLoaded()) void ensureAirportsLayer();
else map.on('styledata', () => void ensureAirportsLayer());
});
return () => {
cancelled = true;
delete (window as unknown as Record<string, unknown>).__flightMap;
const map = mapRef.current; // may be null if the probe hasn't resolved yet
mapRef.current = null;
map.remove();
if (map) map.remove();
};
}, []);
// Restore the persisted style choice once after mount. Reading localStorage here —
// not during render or in a useState initializer — keeps SSR hydration safe: server
// and first client paint both use DEFAULT_STYLE_ID, then we switch if needed.
useEffect(() => {
const saved = window.localStorage.getItem(STYLE_STORAGE_KEY);
if (saved && isStyleId(saved) && saved !== DEFAULT_STYLE_ID) {
setStyleId(saved);
mapRef.current?.setStyle(styleUrl(saved));
}
}, []);
const onStyleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const id = e.target.value;
if (!isStyleId(id)) return;
setStyleId(id);
window.localStorage.setItem(STYLE_STORAGE_KEY, id);
mapRef.current?.setStyle(styleUrl(id));
// The probe promise is cached module-wide and has resolved by the time a user
// interacts — this just picks local vs remote for the new style.
void localAssetsAvailable().then((available) => mapRef.current?.setStyle(styleUrlFor(id, available)));
};
return (