'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'; import type { GeoJsonFeatureCollection } from '../lib/airports'; import type { StateSnapshot } from '../lib/game/state'; import { planesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData'; import { weatherFor } from '../lib/weather'; import { approxLocalTime } from '../lib/localTime'; 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'; // Dynamic game-state layers (v0.11.0, package model v0.12.0): planes as circles, // each FLYING plane's current leg (origin → dest_icao) as a line. const PLANES_SOURCE_ID = 'planes'; const PLANES_GROUNDED_LAYER_ID = 'planes-grounded'; const PLANES_FLYING_LAYER_ID = 'planes-flying'; const ROUTES_SOURCE_ID = 'routes'; const ROUTES_LEGS_LAYER_ID = 'routes-legs'; function escapeHtml(s: string): string { return s.replace(/&/g, '&').replace(//g, '>'); } interface MapProps { // The shell's polled /api/state snapshot (v0.11.0) — drives the plane markers and // route lines. Null until the first successful poll. state?: StateSnapshot | null; } // Named FlightMap (not Map): a component called `Map` would shadow the global // Map constructor inside its own body, breaking `new Map(...)` for the airport index. export default function FlightMap({ state }: MapProps) { const containerRef = useRef(null); const mapRef = useRef(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 | null>(null); // Latest snapshot + airport coordinate index, so the mount effect's styledata wiring // and the state-change effect can both push data without prop-drilling into closures. const stateRef = useRef(null); const airportsIndexRef = useRef | null>(null); const [airportCount, setAirportCount] = useState(null); const [styleId, setStyleId] = useState(DEFAULT_STYLE_ID); // Push the latest planes/routes GeoJSON into whatever sources currently exist. // No-op until the map (and for routes: the airport index) is ready — the mount // effect calls this again after every styledata re-establish and airports load. const applyDynamicRef = useRef<() => void>(() => {}); applyDynamicRef.current = () => { const map = mapRef.current; const st = stateRef.current; if (!map || !st) return; const planesSource = map.getSource(PLANES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined; if (planesSource) void planesSource.setData(planesGeoJson(st)); // v6 API (setGeoData was removed) const routesSource = map.getSource(ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined; if (routesSource && airportsIndexRef.current) { void routesSource.setData(routesGeoJson(st, airportsIndexRef.current)); } }; useEffect(() => { stateRef.current = state ?? null; applyDynamicRef.current(); }, [state]); 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).__flightMap = map; const onAirportClick = (e: maplibregl.MapLayerMouseEvent) => { const f = e.features?.[0]; if (!f) return; const p = f.properties as { name: string; icao: string; lat: number; lon: number }; // Display-only extras (v0.11.0): approximate local time from longitude and a // deterministic generated weather — no gameplay effects per PLAN.md. const w = weatherFor(p.icao); const localTime = approxLocalTime(p.lon, Date.now()); new maplibregl.Popup({ offset: 10 }) .setLngLat(f.geometry.coordinates as [number, number]) .setHTML( `
` + `${escapeHtml(p.name)}
${escapeHtml(p.icao)}
` + `${localTime} local (approx)
` + `${w.condition}, wind ${w.windDirDeg}\u00B0 / ${w.windKt} kt, vis ${w.visibilityM} m` + `
`, ) .addTo(map); }; const onPlaneClick = (e: maplibregl.MapLayerMouseEvent) => { const f = e.features?.[0]; if (!f) return; const p = f.properties as PlaneFeatureProps; const routeLine = p.routeText ? `
${escapeHtml(p.routeText)}` : ''; new maplibregl.Popup({ offset: 12 }) .setLngLat(f.geometry.coordinates as [number, number]) .setHTML( `
` + `${escapeHtml(p.modelLabel)}
` + `${p.status}
` + `fuel ${p.fuelText}` + routeLine + `
`, ) .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; }) .then((data) => { setAirportCount(data.features.length); // exactly once per page life airportsIndexRef.current = new Map( data.features.map((f) => [f.properties.icao, { lat: f.properties.lat, lon: f.properties.lon }]), ); 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 layers after each // switch — this re-establishes them (and the initial load goes through here too). const ensureLayers = async () => { let data: GeoJsonFeatureCollection; 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', }, }); } // Routes first so the lines render under the plane circles. Empty collections // until the shell's first snapshot lands — applyDynamicRef fills them in. if (!map.getSource(ROUTES_SOURCE_ID)) { map.addSource(ROUTES_SOURCE_ID, { type: 'geojson', data: routesGeoJson(stateRef.current, airportsIndexRef.current ?? new Map()), }); } if (!map.getLayer(ROUTES_LEGS_LAYER_ID)) { map.addLayer({ id: ROUTES_LEGS_LAYER_ID, type: 'line', source: ROUTES_SOURCE_ID, paint: { 'line-color': '#f59e0b', // bright amber — actively flying the leg 'line-width': 3, }, }); } if (!map.getSource(PLANES_SOURCE_ID)) { map.addSource(PLANES_SOURCE_ID, { type: 'geojson', data: planesGeoJson(stateRef.current) }); } if (!map.getLayer(PLANES_GROUNDED_LAYER_ID)) { map.addLayer({ id: PLANES_GROUNDED_LAYER_ID, type: 'circle', source: PLANES_SOURCE_ID, filter: ['==', ['get', 'flying'], false], paint: { 'circle-radius': 3, 'circle-color': '#38bdf8', // sky blue at the home airport 'circle-stroke-width': 1, 'circle-stroke-color': '#ffffff', }, }); } if (!map.getLayer(PLANES_FLYING_LAYER_ID)) { map.addLayer({ id: PLANES_FLYING_LAYER_ID, type: 'circle', source: PLANES_SOURCE_ID, filter: ['==', ['get', 'flying'], true], paint: { 'circle-radius': 6, // bigger + distinct so a moving plane stands out 'circle-color': '#22c55e', 'circle-stroke-width': 1.5, '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); map.off('click', PLANES_GROUNDED_LAYER_ID, onPlaneClick); map.on('click', PLANES_GROUNDED_LAYER_ID, onPlaneClick); map.off('click', PLANES_FLYING_LAYER_ID, onPlaneClick); map.on('click', PLANES_FLYING_LAYER_ID, onPlaneClick); // Sources were (re)created above — push the latest game state into them. applyDynamicRef.current(); }; if (map.isStyleLoaded()) void ensureLayers(); else map.on('styledata', () => void ensureLayers()); }); return () => { cancelled = true; delete (window as unknown as Record).__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: ChangeEvent) => { 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 (

Flight Ops

v{pkg.version} {airportCount === null ? 'loading airports…' : `${airportCount} EU airports`}
); }