Files
Flight-Ops/components/Map.tsx
T

166 lines
6.0 KiB
TypeScript

'use client';
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;
// Flat 2D view only. Max zoom ≈ ~100 km across a typical desktop viewport width at
// 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 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;');
}
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;
// Bundlers (Turbopack) break MapLibre's derived worker URL, so point it at a
// 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;
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',
},
});
}
// 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());
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>
</header>
<div ref={containerRef} data-testid="map" className="map-container" />
</div>
);
}