feat: v0.4.0 — self-host OFM styles/fonts/sprites (tiles stay remote) + top-bar style switcher defaulting to Fiord

This commit is contained in:
2026-09-17 08:24:58 +00:00
parent b011953087
commit 501c452377
789 changed files with 5513 additions and 42 deletions
+94 -34
View File
@@ -1,9 +1,10 @@
'use client';
import { useEffect, useRef, useState } from 'react';
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';
const EUROPE_CENTER: [number, number] = [10, 52];
const INITIAL_ZOOM = 4;
@@ -11,7 +12,9 @@ const INITIAL_ZOOM = 4;
// European latitudes (~47 m/px at z11, 52°N); street-level zoom has no gameplay value.
export const MIN_ZOOM = 3;
export const MAX_ZOOM = 11;
const OPENFREEMAP_STYLE = 'https://tiles.openfreemap.org/styles/liberty';
const AIRPORTS_SOURCE_ID = 'airports';
const AIRPORTS_LAYER_ID = 'airports-circles';
function escapeHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -19,7 +22,12 @@ function escapeHtml(s: string): string {
export default function Map() {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<maplibregl.Map | null>(null);
// /api/airports is fetched at most once per page life: every styledata event
// (initial load AND after each setStyle) reuses this promise.
const airportsPromiseRef = useRef<Promise<{ features: unknown[] }> | null>(null);
const [airportCount, setAirportCount] = useState<number | null>(null);
const [styleId, setStyleId] = useState<string>(DEFAULT_STYLE_ID);
useEffect(() => {
if (!containerRef.current) return;
@@ -30,33 +38,62 @@ export default function Map() {
const map = new maplibregl.Map({
container: containerRef.current,
style: OPENFREEMAP_STYLE,
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;
// Airports are GeoJSON, so they don't depend on basemap tiles: initialize as soon
// as the style is applied ('styledata') rather than waiting for 'load', which also
// requires all tile sources to finish.
let initialized = false;
const init = async () => {
if (initialized) return;
initialized = true;
try {
const res = await fetch('/api/airports');
if (!res.ok) return;
const data = (await res.json()) as { features: unknown[] };
setAirportCount(data.features.length);
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);
};
map.addSource('airports', { type: 'geojson', data });
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-circles',
id: AIRPORTS_LAYER_ID,
type: 'circle',
source: 'airports',
source: AIRPORTS_SOURCE_ID,
paint: {
'circle-radius': 3,
'circle-color': '#e11d48',
@@ -64,37 +101,60 @@ export default function Map() {
'circle-stroke-color': '#ffffff',
},
});
map.on('click', 'airports-circles', (e) => {
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);
});
} catch (err) {
console.error('failed to initialize map layers', err);
}
// 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 init();
else map.on('styledata', () => void init());
if (map.isStyleLoaded()) void ensureAirportsLayer();
else map.on('styledata', () => void ensureAirportsLayer());
return () => {
delete (window as unknown as Record<string, unknown>).__flightMap;
mapRef.current = null;
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));
};
return (
<div className="map-wrap">
<header data-testid="app-header" className="app-header">
<h1>Flight Ops</h1>
<small>v{pkg.version}</small>
<select
data-testid="style-switch"
className="style-switch"
aria-label="Map style"
value={styleId}
onChange={onStyleChange}
>
{STYLES.map((s) => (
<option key={s.id} value={s.id}>
{s.label}
</option>
))}
</select>
<span data-testid="airport-count">
{airportCount === null ? 'loading airports…' : `${airportCount} EU airports`}
</span>