feat: v0.11.0 — map interactions per PLAN.md: expanded airport popup (approx local time + deterministic generated weather), animated plane markers from /api/state polls with status popups, active contract route lines (pending dashed vs in-flight solid); pure libs lib/weather.ts, lib/localTime.ts, lib/mapData.ts
This commit is contained in:
+156
-12
@@ -5,6 +5,11 @@ 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;
|
||||
@@ -15,20 +20,60 @@ export const MAX_ZOOM = 11;
|
||||
|
||||
const AIRPORTS_SOURCE_ID = 'airports';
|
||||
const AIRPORTS_LAYER_ID = 'airports-circles';
|
||||
// Dynamic game-state layers (v0.11.0): planes as circles, active contract routes as lines.
|
||||
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_PENDING_LAYER_ID = 'routes-pending';
|
||||
const ROUTES_INFLIGHT_LAYER_ID = 'routes-inflight';
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
export default function Map() {
|
||||
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<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 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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
@@ -65,11 +110,37 @@ export default function Map() {
|
||||
const onAirportClick = (e: maplibregl.MapLayerMouseEvent) => {
|
||||
const f = e.features?.[0];
|
||||
if (!f) return;
|
||||
const p = f.properties as { name: string; icao: string };
|
||||
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)}</div>`,
|
||||
`<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);
|
||||
};
|
||||
@@ -79,10 +150,13 @@ export default function Map() {
|
||||
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[] }>;
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -90,10 +164,10 @@ export default function Map() {
|
||||
};
|
||||
|
||||
// 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[] };
|
||||
// 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) {
|
||||
@@ -116,14 +190,84 @@ export default function Map() {
|
||||
},
|
||||
});
|
||||
}
|
||||
// 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_PENDING_LAYER_ID)) {
|
||||
map.addLayer({
|
||||
id: ROUTES_PENDING_LAYER_ID,
|
||||
type: 'line',
|
||||
source: ROUTES_SOURCE_ID,
|
||||
filter: ['==', ['get', 'kind'], 'pending'],
|
||||
paint: {
|
||||
'line-color': '#94a3b8', // muted slate — accepted but not yet dispatched
|
||||
'line-width': 2,
|
||||
'line-dasharray': [2, 2],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!map.getLayer(ROUTES_INFLIGHT_LAYER_ID)) {
|
||||
map.addLayer({
|
||||
id: ROUTES_INFLIGHT_LAYER_ID,
|
||||
type: 'line',
|
||||
source: ROUTES_SOURCE_ID,
|
||||
filter: ['==', ['get', 'kind'], 'inflight'],
|
||||
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 ensureAirportsLayer();
|
||||
else map.on('styledata', () => void ensureAirportsLayer());
|
||||
if (map.isStyleLoaded()) void ensureLayers();
|
||||
else map.on('styledata', () => void ensureLayers());
|
||||
});
|
||||
|
||||
return () => {
|
||||
@@ -135,7 +279,7 @@ export default function Map() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onStyleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const onStyleChange = (e: ChangeEvent<HTMLSelectElement>) => {
|
||||
const id = e.target.value;
|
||||
if (!isStyleId(id)) return;
|
||||
setStyleId(id);
|
||||
|
||||
Reference in New Issue
Block a user