Files
Flight-Ops/components/Map.tsx
T
2026-09-19 22:01:02 +00:00

522 lines
24 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 { hoverRouteGeoJson, 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';
// ISS-022/025/027 (v0.22.0): the hover route trace — its OWN source + top-most dashed line,
// because the shared `routes` source only holds FLYING legs: an open package's or a grounded
// relocation's planned route is never in it. applyHoverRef pushes data into it on every hover.
const HOVER_ROUTES_SOURCE_ID = 'hover-routes';
const HOVER_ROUTE_LAYER_ID = 'hover-route';
// ISS-022 (v0.22.0): the DESTINATION airport's ring — a second, differently-colored circle over
// the same `airports` source so the target stands out from the origin's plain yellow ring.
// applyHoverRef filters it to the hovered target's destination icao only.
const AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID = 'airports-target-highlight';
function escapeHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
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, and (ISS-022/025/027 v0.22.0)
// draws the full great-circle trace between any hovered target's two endpoints. Null = nothing hovered.
hovered?: HoverTarget | null;
// ISS-010 (v0.18.0): push an action endpoint's full response snapshot into the shared
// shell state — same callback RightPane receives, used by the airport popup's Relocate row.
applySnapshot: (snapshot: StateSnapshot) => void;
}
// 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, applySnapshot }: 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);
// ISS-010 (v0.18.0): the shell's applySnapshot is stable (useCallback with no deps), but the
// mount effect captures it once — keep a ref so the popup wiring always calls the latest one.
const applySnapshotRef = useRef(applySnapshot);
useEffect(() => {
applySnapshotRef.current = applySnapshot;
}, [applySnapshot]);
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 ''. A package hover may
// name its plane (ISS-025 on-board cargo rows), so that plane's halo stays lit too.
let planeId = '';
let fromIcao = '';
let toIcao = '';
if (h) {
if (h.kind === 'plane') planeId = h.id;
else if (h.kind === 'package') {
planeId = h.planeId ?? '';
fromIcao = h.originIcao;
toIcao = h.destIcao;
} else {
// 'route' — the Relocate panel's planned flight: trace + target airport only.
fromIcao = h.fromIcao;
toIcao = h.toIcao;
}
}
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]);
}
// ISS-022/025/027: the hover route trace — one great-circle line for any target carrying two
// ICAOs (package origin→dest / relocate fromIcao→toIcao); empty when either endpoint is unknown.
const hoverSource = map.getSource(HOVER_ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined;
if (hoverSource) {
void hoverSource.setData(hoverRouteGeoJson(fromIcao, toIcao, airportsIndexRef.current ?? new Map()));
}
// Package hovers ring BOTH endpoints (v0.15.0 behavior); 'route' hovers ring the TARGET only —
// the relocation's destination is what ISS-027 asks to see. Plane hovers ring nothing.
const originIcao = h?.kind === 'package' ? fromIcao : '';
const destIcao = h?.kind === 'package' || h?.kind === 'route' ? toIcao : '';
if (map.getLayer(AIRPORTS_HIGHLIGHT_LAYER_ID)) {
map.setFilter(
AIRPORTS_HIGHLIGHT_LAYER_ID,
['any', ['==', ['get', 'icao'], originIcao], ['==', ['get', 'icao'], destIcao]],
);
}
// ISS-022: the destination gets its own distinct-colored ring on top (package AND route hovers).
if (map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
map.setFilter(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID, ['==', ['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());
// ISS-010 (v0.18.0): Relocate row — grounded planes from the latest snapshot can be
// repositioned to this airport via POST /api/planes/{id}/fly (pure repositioning).
const st = stateRef.current;
const groundedPlanes = st ? st.planes.filter((pl) => pl.status === 'available') : [];
const planeLabel = (model: string) => st?.catalog.find((c) => c.model === model)?.label ?? model;
const relocateHtml =
groundedPlanes.length > 0
? `<select data-testid="airport-popup-plane" aria-label="Plane to relocate here">` +
`<option value="">Select a plane\u2026</option>` +
groundedPlanes.map(
(pl) =>
`<option value="${escapeHtml(pl.id)}">${escapeHtml(planeLabel(pl.model))} \u2014 ${escapeHtml(pl.locationIcao)}</option>`,
).join('') +
`</select><button type="button" data-testid="airport-popup-relocate" disabled>Relocate here</button>`
: `<span data-testid="airport-popup-no-planes">No grounded planes to relocate.</span>`;
const popup = 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 class="popup-relocate">` + relocateHtml + `<span data-testid="airport-popup-relocate-status"></span></div>` +
`</div>`,
)
.addTo(map);
// Popups are plain HTML, not React — the element only exists after addTo, so wire the
// controls via querySelector (the select enables the button once a plane is picked).
const el = popup.getElement();
const select = el?.querySelector<HTMLSelectElement>('[data-testid="airport-popup-plane"]');
const button = el?.querySelector<HTMLButtonElement>('[data-testid="airport-popup-relocate"]');
// The status span is always in the popup HTML (even with no grounded planes), so it
// exists whenever the select/button do.
const statusEl = el?.querySelector<HTMLElement>('[data-testid="airport-popup-relocate-status"]');
if (select && button && statusEl) {
select.addEventListener('change', () => {
button.disabled = select.value === '';
});
button.addEventListener('click', async () => {
const planeId = select.value;
if (!planeId || button.disabled) return;
button.disabled = true;
statusEl.textContent = 'Relocating\u2026';
try {
const res = await fetch(`/api/planes/${planeId}/fly`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ destIcao: p.icao }),
cache: 'no-store',
});
const data = (await res.json()) as StateSnapshot & { error?: string };
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
applySnapshotRef.current(data); // shared shell state updates immediately, like the panes' runAction
statusEl.textContent = 'Relocation started.';
} catch (err) {
statusEl.textContent = err instanceof Error ? err.message : String(err);
button.disabled = false; // allow retry / picking another plane
}
});
}
};
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': 5, // ISS-010 (v0.18.0): bigger — the r=3 dots were hard to click
'circle-color': '#e11d48',
'circle-stroke-width': 1.5,
'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': 9, // ring around the base airport circles (r=5)
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
'circle-stroke-width': 2.5,
'circle-stroke-color': '#facc15',
},
});
}
// ISS-022/025/027 (v0.22.0): the hover route trace — added LAST so it sits above every
// other layer, including the highlight rings at its endpoints. Own source: the shared
// `routes` source only holds flying legs, never a planned one. Empty until a hover sets data.
if (!map.getSource(HOVER_ROUTES_SOURCE_ID)) {
map.addSource(HOVER_ROUTES_SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
}
if (!map.getLayer(HOVER_ROUTE_LAYER_ID)) {
map.addLayer({
id: HOVER_ROUTE_LAYER_ID,
type: 'line',
source: HOVER_ROUTES_SOURCE_ID,
paint: {
'line-color': '#facc15', // matches the airports-highlight ring — one "trace" color
'line-width': 4,
'line-dasharray': [2, 2], // dashed = planned route, distinct from solid flying legs
},
});
}
// ISS-022 (v0.22.0): the destination's ring — same geometry as airports-highlight but a
// DIFFERENT color so the target stands out over the origin's yellow ring; added last so it
// also sits above the hover-route line at its endpoint. Starts filtered to match nothing.
if (!map.getLayer(AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID)) {
map.addLayer({
id: AIRPORTS_TARGET_HIGHLIGHT_LAYER_ID,
type: 'circle',
source: AIRPORTS_SOURCE_ID,
filter: ['==', ['get', 'icao'], ''],
paint: {
'circle-radius': 9, // same ring size as airports-highlight (r=5 base circles)
'circle-color': 'rgba(0, 0, 0, 0)', // transparent fill — stroke-only ring
'circle-stroke-width': 3,
'circle-stroke-color': '#4ade80', // green — distinct from the yellow endpoint rings
},
});
}
// 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>
);
}