CI / build + unit + e2e (pull_request) Failing after 7m29s
Every leg gains a 10-min takeoff phase at the origin and a 10-min landing phase at the destination, each weather-scaled up to 2x via a monotone condition rule (Clear < Cloudy < Rain < Fog). Single composition in lib/sim/movement.ts: BASE_PHASE_MS, phaseFactor, MAX_PHASE_FACTOR, legPhases; arrivalTimeFor and progressAt route through it (progress is now piecewise — hold at origin / linear cruise / hold at destination), so engine arrival gate, client position/fuel recompute and the job expiry floor all agree. Phases burn no fuel. Marker shows the current phase next to the status in the popup (mapData derives it from departureSimTime + clockMs; new data-testid=plane-phase sibling). plane-status keeps the raw status. Tests: movement.test.ts (phaseFactor bounds/monotonicity, origin-vs-dest composition, piecewise progressAt), engine.test.ts (deleted local travelMs mirror — all ~18 fixture clocks use the real composition), seed.test.ts (phase-inclusive expiry floor mirrors). New e2e/phases.spec.ts asserts 'taking off' at the origin gate and 'landing' at the destination gate on EDDF→LEMD using the same legPhases boundaries as the engine.
635 lines
32 KiB
TypeScript
635 lines
32 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, hoverTraceGeoJson, planesGeoJson, queuedRoutesGeoJson, routesGeoJson, type AirportCoord, type PlaneFeatureProps } from '../lib/mapData';
|
||
import { weatherFor } from '../lib/weather';
|
||
import { approxLocalTime } from '../lib/localTime';
|
||
import Modal from './Modal';
|
||
import AdminPanel from './AdminPanel';
|
||
import Leaderboard from './Leaderboard';
|
||
import { clearStoredSession, sessionHeaders } from '../lib/authClient';
|
||
|
||
// v0.70.0 default view: null island [0,0] at zoom 2 — the world is 2048 px wide there and the
|
||
// Africa+Europe bounding box (lat −35..+71, lon −18..+52) spans ~800 px vertically in Web Mercator,
|
||
// so both continents are fully visible on a typical desktop map pane.
|
||
const WORLD_CENTER: [number, number] = [0, 0];
|
||
const INITIAL_ZOOM = 2;
|
||
// 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 = 0; // v0.70.0: fully zoomed out the whole earth (512 px world) fits any viewport
|
||
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-043 (v0.26.0): the dotted queue line — a flying plane's NOT-yet-started legs
|
||
// (dest → queue[0] → …) as their own source + layer, drawn under everything else dynamic.
|
||
const QUEUE_ROUTES_SOURCE_ID = 'queue-routes';
|
||
const QUEUE_ROUTES_LAYER_ID = 'queue-routes';
|
||
// ISS-098 (v0.50.0): amber/gold — planned legs read as "queued", visible on light and dark tiles alike.
|
||
export const QUEUE_ROUTE_LINE_COLOR = '#d4a017';
|
||
// 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, '&').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, 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;
|
||
// v1.1.0 (ISS-107): the admin panel's Log out cleared the session — tell the shell to drop back
|
||
// to the sign-in screen instead of leaving a signed-out user staring at a live dashboard.
|
||
onLogout?: () => void;
|
||
// v1.10.0 (ISS-158): /api/me says this session is an admin → show the top-bar Admin button.
|
||
isAdmin?: boolean;
|
||
}
|
||
|
||
// 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, onLogout, isAdmin = false }: 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);
|
||
// v0.71.0: the Admin modal (top-bar button) — unmounted while closed so it re-checks the
|
||
// stored session on every open.
|
||
const [adminOpen, setAdminOpen] = useState(false);
|
||
// v1.6.0 (ISS-115): the leaderboard panel (top-bar button) — rows come from the polled snapshot.
|
||
const [leaderboardOpen, setLeaderboardOpen] = useState(false);
|
||
|
||
// 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;
|
||
// ISS-124 (v0.58.0): the airport index unwraps crossing markers — empty until it loads, so
|
||
// planes draw at their wrapped position in the meantime (same as pre-v0.58.0).
|
||
if (planesSource) void planesSource.setData(planesGeoJson(st, airportsIndexRef.current ?? new Map())); // 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));
|
||
}
|
||
// ISS-043 (v0.26.0): the dotted queue line — same airport-index guard as the solid legs above.
|
||
const queueRoutesSource = map.getSource(QUEUE_ROUTES_SOURCE_ID) as maplibregl.GeoJSONSource | undefined;
|
||
if (queueRoutesSource && airportsIndexRef.current) {
|
||
void queueRoutesSource.setData(queuedRoutesGeoJson(st.planes, airportsIndexRef.current));
|
||
}
|
||
};
|
||
|
||
useEffect(() => {
|
||
stateRef.current = state ?? null;
|
||
applyDynamicRef.current();
|
||
// ISS-040 (v0.23.2): re-apply the hover too, so an on-board package's trace follows a moving
|
||
// carrier between polls while hovered — idempotent and cheap (one small setData + ring filters).
|
||
applyHoverRef.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) {
|
||
// ISS-040 (v0.23.2): an on-board package's trace starts from the carrier plane's LIVE position,
|
||
// not its origin airport — identical to before while grounded at the pickup, different once it
|
||
// has departed with cargo still loaded. No carrier in state yet → fall back to the ICAO trace.
|
||
// ISS-077 (v0.41.0): a FLYING carrier's trace starts at its LANDING airport (destIcao), not the
|
||
// live mid-flight position — the hover previews what happens AFTER this leg lands, and the solid
|
||
// active-leg + dotted queue layers already show where it is now. Grounded / no active leg keeps
|
||
// today's behavior exactly (live position = the plane's airport). destIcao missing from the
|
||
// index → fall back to the live position rather than guessing.
|
||
const idx = airportsIndexRef.current ?? new Map();
|
||
const carrier = h?.kind === 'package' && h.planeId ? stateRef.current?.planes.find((p) => p.id === h.planeId) : undefined;
|
||
const landing = carrier?.status === 'flying' && carrier.destIcao ? idx.get(carrier.destIcao) : undefined;
|
||
void hoverSource.setData(
|
||
landing
|
||
? hoverTraceGeoJson(landing, toIcao, idx)
|
||
: carrier
|
||
? hoverTraceGeoJson({ lat: carrier.lat, lon: carrier.lon }, toIcao, idx)
|
||
: hoverRouteGeoJson(fromIcao, toIcao, idx),
|
||
);
|
||
}
|
||
// 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: WORLD_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 — every plane from the latest snapshot can be sent to
|
||
// this airport: grounded ones fly immediately (POST /api/planes/{id}/fly), flying/repairing
|
||
// ones get the leg appended to their queue (POST /api/planes/{id}/queue, ISS-096 v0.49.0).
|
||
const st = stateRef.current;
|
||
const planes = st ? st.planes : [];
|
||
const planeLabel = (model: string) => st?.catalog.find((c) => c.model === model)?.label ?? model;
|
||
const relocateHtml =
|
||
planes.length > 0
|
||
? `<select data-testid="airport-popup-plane" aria-label="Plane to relocate here">` +
|
||
`<option value="">Select a plane\u2026</option>` +
|
||
planes.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 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 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 {
|
||
// ISS-096 (v0.49.0): endpoint follows the SELECTED plane's current status — grounded
|
||
// planes fly now, flying/repairing ones get the leg queued for after landing.
|
||
const planeStatus = stateRef.current?.planes.find((pl) => pl.id === planeId)?.status ?? 'available';
|
||
const action = planeStatus === 'available' ? 'fly' : 'queue';
|
||
const res = await fetch(`/api/planes/${planeId}/${action}`, {
|
||
method: 'POST',
|
||
// v1.1.0 (ISS-107): fly/queue are session-guarded — echo the stored id.
|
||
headers: { 'Content-Type': 'application/json', ...sessionHeaders() },
|
||
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 = action === 'fly' ? 'Relocation started.' : 'Added to queue.';
|
||
} 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>` : '';
|
||
// v1.12.0: phase label next to the status — "flying · taking off" etc. plane-status keeps
|
||
// the raw status so existing assertions on it stay exact.
|
||
const phaseLine = p.phaseLabel ? `<span data-testid="plane-phase"> · ${p.phaseLabel}</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>${phaseLine}<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': '#f43f5e', // ISS-118 (v0.60.0): rose-500 — old #e11d48 (rose-600) was tuned for light tiles; 1.7:1 on Fiord's dark slate land
|
||
'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,
|
||
},
|
||
});
|
||
}
|
||
// ISS-043 (v0.26.0): dotted queue line — added after routes-legs but BEFORE the hover
|
||
// layers so a hovered trace still draws on top of it. Amber/gold + fine dots reads as
|
||
// "planned/future", distinct from the solid bright-amber active leg and the [2,2] yellow hover dash.
|
||
if (!map.getSource(QUEUE_ROUTES_SOURCE_ID)) {
|
||
map.addSource(QUEUE_ROUTES_SOURCE_ID, {
|
||
type: 'geojson',
|
||
data: queuedRoutesGeoJson(stateRef.current?.planes ?? [], airportsIndexRef.current ?? new Map()),
|
||
});
|
||
}
|
||
if (!map.getLayer(QUEUE_ROUTES_LAYER_ID)) {
|
||
map.addLayer({
|
||
id: QUEUE_ROUTES_LAYER_ID,
|
||
type: 'line',
|
||
source: QUEUE_ROUTES_SOURCE_ID,
|
||
paint: {
|
||
'line-color': QUEUE_ROUTE_LINE_COLOR, // amber/gold — planned legs, not actively flying (ISS-098)
|
||
'line-width': 3,
|
||
'line-dasharray': [0.1, 1.5], // dotted — distinct from solid legs and the [2,2] hover dash
|
||
},
|
||
});
|
||
}
|
||
if (!map.getSource(PLANES_SOURCE_ID)) {
|
||
// ISS-124 (v0.58.0): same airport-index unwrap as applyDynamic above.
|
||
map.addSource(PLANES_SOURCE_ID, { type: 'geojson', data: planesGeoJson(stateRef.current, airportsIndexRef.current ?? new Map()) });
|
||
}
|
||
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': '#f87171', // ISS-118 (v0.60.0): red-400 — old #ef4444 sat at 2.1:1 on Fiord's dark slate; brighter so the hover emphasis reads, still 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)));
|
||
};
|
||
|
||
// v1.10.0 (ISS-157): top-bar Log out — same three steps as the admin panel's button: best-effort
|
||
// server-side session kill, drop the stored id, tell the shell to show sign-in again.
|
||
const onTopBarLogout = async () => {
|
||
await fetch('/api/logout', { method: 'POST', headers: sessionHeaders() }).catch(() => undefined);
|
||
clearStoredSession();
|
||
onLogout?.();
|
||
};
|
||
|
||
return (
|
||
<div className="map-wrap">
|
||
<header data-testid="app-header" className="app-header">
|
||
<h1>Flight Ops</h1>
|
||
<a data-testid="app-version" href="https://git.kkhost.pl/OpenCode/Flight-Ops/src/branch/master/CHANGELOG.md" target="_blank" rel="noreferrer">
|
||
<small>v{pkg.version}</small>
|
||
</a>
|
||
<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} world airports`}
|
||
</span>
|
||
{/* v1.6.0 (ISS-115): leaderboard panel entry point — right side of the top bar, opens a modal. */}
|
||
<button type="button" data-testid="leaderboard-btn" className="pane-btn" onClick={() => setLeaderboardOpen(true)}>
|
||
Leaderboard
|
||
</button>
|
||
{/* v0.71.0: admin panel entry point — right side of the top bar, opens a modal (no URL).
|
||
v1.10.0 (ISS-158): only for admins (/api/me `admin` flag) — hidden entirely otherwise. */}
|
||
{isAdmin && (
|
||
<button type="button" data-testid="admin-btn" className="pane-btn" onClick={() => setAdminOpen(true)}>
|
||
Admin
|
||
</button>
|
||
)}
|
||
{/* v1.10.0 (ISS-157): Log out — last child, so the flex row puts it top-right of the bar. */}
|
||
<button type="button" data-testid="logout-btn" className="pane-btn" onClick={() => void onTopBarLogout()}>
|
||
Log out
|
||
</button>
|
||
</header>
|
||
<div ref={containerRef} data-testid="map" className="map-container" />
|
||
<Modal open={adminOpen} onClose={() => setAdminOpen(false)} title="Admin">
|
||
<AdminPanel onLogout={onLogout} />
|
||
</Modal>
|
||
{/* v1.6.0 (ISS-115): leaderboard — players from the shared snapshot, no extra endpoint. */}
|
||
<Modal open={leaderboardOpen} onClose={() => setLeaderboardOpen(false)} title="Leaderboard">
|
||
<Leaderboard players={state?.players ?? []} />
|
||
</Modal>
|
||
</div>
|
||
);
|
||
}
|