174 lines
6.7 KiB
TypeScript
174 lines
6.7 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, localAssetsAvailable, styleUrlFor } 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, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
}
|
|
|
|
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');
|
|
|
|
let cancelled = false;
|
|
|
|
// 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 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',
|
|
},
|
|
});
|
|
}
|
|
// 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 () => {
|
|
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;
|
|
if (map) map.remove();
|
|
};
|
|
}, []);
|
|
|
|
const onStyleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
|
const id = e.target.value;
|
|
if (!isStyleId(id)) return;
|
|
setStyleId(id);
|
|
window.localStorage.setItem(STYLE_STORAGE_KEY, 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 (
|
|
<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>
|
|
);
|
|
}
|