390 lines
17 KiB
TypeScript
390 lines
17 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';
|
|
import type { GeoJsonFeatureCollection } from '../lib/airports';
|
|
import type { StateSnapshot } from '../lib/game/state';
|
|
import type { HoverTarget } from './hoverTypes';
|
|
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';
|
|
// ISS-002 (v0.15.0): top-most hover-highlight layers, added after the base layers so they
|
|
// render above them. Each starts filtered to match nothing; applyHoverRef drives the filters.
|
|
const PLANES_HIGHLIGHT_LAYER_ID = 'planes-highlight';
|
|
const ROUTES_HIGHLIGHT_LAYER_ID = 'routes-highlight';
|
|
const AIRPORTS_HIGHLIGHT_LAYER_ID = 'airports-highlight';
|
|
|
|
function escapeHtml(s: string): string {
|
|
return s.replace(/&/g, '&').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;
|
|
// ISS-002 (v0.15.0): the side panels' hover target — highlights the matching plane
|
|
// (+ its route leg if flying) or a package's endpoint airports. Null = nothing hovered.
|
|
hovered?: HoverTarget | 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, hovered }: MapProps) {
|
|
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<GeoJsonFeatureCollection> | 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<StateSnapshot | null>(null);
|
|
const airportsIndexRef = useRef<Map<string, AirportCoord> | null>(null);
|
|
const [airportCount, setAirportCount] = useState<number | null>(null);
|
|
const [styleId, setStyleId] = useState<string>(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]);
|
|
|
|
// ISS-002 (v0.15.0): hover highlight — same ref + effect pattern as the snapshot above.
|
|
// No-op until the layers exist; ensureLayers re-applies the current filter after every
|
|
// styledata re-establish, so a hover that outlives a style switch stays highlighted.
|
|
const hoveredRef = useRef<HoverTarget | null>(null);
|
|
const applyHoverRef = useRef<() => void>(() => {});
|
|
applyHoverRef.current = () => {
|
|
const map = mapRef.current;
|
|
if (!map) return;
|
|
const h = hoveredRef.current;
|
|
// The empty-string sentinel matches nothing: no feature has id/icao ''.
|
|
const planeId = h && h.kind === 'plane' ? h.id : '';
|
|
if (map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
|
map.setFilter(PLANES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'id'], planeId]);
|
|
}
|
|
if (map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
|
map.setFilter(ROUTES_HIGHLIGHT_LAYER_ID, ['==', ['get', 'planeId'], planeId]);
|
|
}
|
|
const originIcao = h && h.kind === 'package' ? h.originIcao : '';
|
|
const destIcao = h && h.kind === 'package' ? h.destIcao : '';
|
|
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
|
map.setFilter(
|
|
AIRPORTS_HIGHLIGHT_LAYER_ID,
|
|
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
|
|
);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
hoveredRef.current = hovered ?? null;
|
|
applyHoverRef.current();
|
|
}, [hovered]);
|
|
|
|
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; 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(
|
|
`<div data-testid="airport-popup">` +
|
|
`<strong>${escapeHtml(p.name)}</strong><br/>${escapeHtml(p.icao)}<br/>` +
|
|
`<span data-testid="airport-local-time">${localTime} local (approx)</span><br/>` +
|
|
`<span data-testid="airport-weather">${w.condition}, wind ${w.windDirDeg}\u00B0 / ${w.windKt} kt, vis ${w.visibilityM} m</span>` +
|
|
`</div>`,
|
|
)
|
|
.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 ? `<br/><span data-testid="plane-route">${escapeHtml(p.routeText)}</span>` : '';
|
|
new maplibregl.Popup({ offset: 12 })
|
|
.setLngLat(f.geometry.coordinates as [number, number])
|
|
.setHTML(
|
|
`<div data-testid="plane-popup">` +
|
|
`<strong>${escapeHtml(p.modelLabel)}</strong><br/>` +
|
|
`<span data-testid="plane-status">${p.status}</span><br/>` +
|
|
`fuel <span data-testid="plane-fuel">${p.fuelText}</span>` +
|
|
routeLine +
|
|
`</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<GeoJsonFeatureCollection>;
|
|
})
|
|
.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',
|
|
},
|
|
});
|
|
}
|
|
// ISS-002 (v0.15.0): hover-highlight layers — added last so they sit top-most over
|
|
// both plane layers / the route line / the airport circles. Each starts filtered to
|
|
// match nothing; applyHoverRef sets the real filter on hover and re-applies it here.
|
|
if (!map.getLayer(PLANES_HIGHLIGHT_LAYER_ID)) {
|
|
map.addLayer({
|
|
id: PLANES_HIGHLIGHT_LAYER_ID,
|
|
type: 'circle',
|
|
source: PLANES_SOURCE_ID,
|
|
filter: ['==', ['get', 'id'], ''],
|
|
paint: {
|
|
'circle-radius': 10, // halo well above the base circles (3 grounded / 6 flying)
|
|
'circle-color': '#38bdf8',
|
|
'circle-stroke-width': 2.5,
|
|
'circle-stroke-color': '#ffffff',
|
|
},
|
|
});
|
|
}
|
|
if (!map.getLayer(ROUTES_HIGHLIGHT_LAYER_ID)) {
|
|
map.addLayer({
|
|
id: ROUTES_HIGHLIGHT_LAYER_ID,
|
|
type: 'line',
|
|
source: ROUTES_SOURCE_ID,
|
|
filter: ['==', ['get', 'planeId'], ''],
|
|
paint: {
|
|
'line-color': '#ef4444', // red — distinct from the amber routes-legs line
|
|
'line-width': 6,
|
|
},
|
|
});
|
|
}
|
|
if (!map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
|
|
map.addLayer({
|
|
id: AIRPORTS_HIGHLIGHT_LAYER_ID,
|
|
type: 'circle',
|
|
source: AIRPORTS_SOURCE_ID,
|
|
filter: ['any', ['==', ['get', 'icao'], ''], ['==', ['get', 'icao'], '']],
|
|
paint: {
|
|
'circle-radius': 8, // ring around the base airport circles (r=3)
|
|
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
|
|
'circle-stroke-width': 2.5,
|
|
'circle-stroke-color': '#facc15',
|
|
},
|
|
});
|
|
}
|
|
// 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, and re-apply
|
|
// the current hover filter to the (re-created) highlight layers.
|
|
applyDynamicRef.current();
|
|
applyHoverRef.current();
|
|
};
|
|
|
|
if (map.isStyleLoaded()) void ensureLayers();
|
|
else map.on('styledata', () => void ensureLayers());
|
|
});
|
|
|
|
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: 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>
|
|
);
|
|
}
|