Compare commits

..
12 Commits
Author SHA1 Message Date
kamilkrzywda 1dc5beb0dd Merge pull request 'v0.15.1 — ISS-004 right pane widened, On-board wrapping fixed' (#16) from fix/right-pane-width into master
CI / build + unit + e2e (push) Successful in 5m4s
2026-09-19 13:38:52 +02:00
kamilkrzywda b6bfcedaf6 test: click the rendered marker position while paused — closes render-lag race (CI run #37)
CI / build + unit + e2e (pull_request) Successful in 5m0s
2026-09-19 11:32:19 +00:00
kamilkrzywda 4c99dbe550 fix: v0.15.1 — ISS-004 right pane widened to 360px, on-board wrap fixes
CI / build + unit + e2e (pull_request) Failing after 6m15s
2026-09-19 11:05:02 +00:00
kamilkrzywda e6d7e03934 Merge pull request 'v0.15.0 — ISS-002 hovering a plane or package in the side panels highlights it on the map' (#15) from feat/map-hover-highlight into master
CI / build + unit + e2e (push) Failing after 4m21s
2026-09-19 12:57:45 +02:00
kamilkrzywda 08094a00e2 test: hover spec — fleet row testid is plane-${p.id} (double prefix), derive from state
CI / build + unit + e2e (pull_request) Successful in 5m42s
2026-09-19 10:51:18 +00:00
kamilkrzywda eff934a1cc test: decisive hover diagnostics — browser snapshot vs node state + fleet HTML; CI fresh DB per run
CI / build + unit + e2e (pull_request) Failing after 6m3s
2026-09-19 10:35:36 +00:00
kamilkrzywda 3209dea425 test: hover spec — robust fleet-row wait + fit map to both endpoints before asserting
CI / build + unit + e2e (pull_request) Failing after 6m15s
2026-09-19 10:06:48 +00:00
kamilkrzywda 3b6506832f feat: v0.15.0 — ISS-002 hovering a plane or package in the side panels highlights it on the map
CI / build + unit + e2e (pull_request) Failing after 6m8s
2026-09-19 09:37:42 +00:00
kamilkrzywda 7db8fcc549 Merge pull request 'v0.14.0 — ISS-006 time-scale slider values up to 1000x; tests use fastest time' (#14) from feat/time-scale-slider-1000x into master
CI / build + unit + e2e (push) Successful in 4m27s
2026-09-19 11:16:55 +02:00
kamilkrzywda d65d4e45b9 test: pause sim around plane-popup marker click at 1000× (rendered marker lags fresh state by one poll)
CI / build + unit + e2e (pull_request) Successful in 4m43s
2026-09-19 09:11:10 +00:00
kamilkrzywda bd00b2b4c4 feat: v0.14.0 — ISS-006 time-scale slider values up to 1000x; tests use fastest time
CI / build + unit + e2e (pull_request) Failing after 4m52s
2026-09-19 08:49:30 +00:00
kamilkrzywda 0c9279818a ci: e2e list reporter — per-test progress in job log
CI / build + unit + e2e (pull_request) Successful in 19m58s
CI / build + unit + e2e (push) Successful in 18m20s
2026-09-19 08:09:32 +00:00
26 changed files with 668 additions and 101 deletions
+6 -1
View File
@@ -24,6 +24,9 @@ jobs:
- name: Prepare e2e network
run: |
set -u
# Interrupted runs skip the end-of-run cleanup, leaking a USED DB volume into later
# runs (tests assume seeded state) — drop it so every run starts fresh.
docker volume rm flight-ci_flight-db 2>/dev/null || true
SUBNET=172.39.0.0/24
if docker network inspect flight-ci-e2e >/dev/null 2>&1; then
cur=$(docker network inspect flight-ci-e2e --format '{{(index .IPAM.Config 0).Subnet}}')
@@ -187,7 +190,9 @@ jobs:
NO_PROXY: app,localhost,127.0.0.1,.kkhost.pl
no_proxy: app,localhost,127.0.0.1,.kkhost.pl
# Connectivity diagnostics now run post-deploy in e2e/ci-diagnostics.ts (globalSetup).
run: npx playwright test
# --reporter=list prints each test as it completes (name + ✓/× + duration) for progress
# visibility in the job log; failure error context/snapshots are unchanged.
run: npx playwright test --reporter=list
# The daemon is shared with production — never leave our stack or network behind.
# -v drops the named DB volume so every run seeds fresh (no schema drift between PRs).
+28
View File
@@ -1,5 +1,33 @@
# Changelog
## v0.15.1 — 2026-09-19 11:04
- **Right pane widened, "On board" wrapping fixed (ISS-004).** The 3-pane shell grid (`app/globals.css` `.app-shell`) moves from `300px / 1fr / 320px` to `280px / 1fr / 360px` — the map column absorbs the delta (MapLibre sizes itself from its container, no JS change). Three wrap offenders in the right pane's "On board" blocks are fixed:
- In-flight leg header (`components/RightPane.tsx`, `.contract-route` span): the class already had `white-space: nowrap; overflow: hidden; text-overflow: ellipsis`, but as a flex item with default `min-width: auto` it could not shrink below its full text width, so long routes (e.g. "Frankfurt → Madrid–Barajas") overflowed instead of ellipsizing — `.contract-route` now has `min-width: 0`
- Cargo-row buttons ("Fly to {dest}" / "Abandon −€X" in `.contract-main`): labels wrapped mid-text at the old width — `.pane-btn` now has `white-space: nowrap`
- Cargo sub-line route span had no white-space rule and wrapped mid-route — it now carries the existing `contract-route` class (nowrap + ellipsis)
- **Left pane sanity-checked at its new 280px**: fleet-row location span (`.plane-loc`) already had nowrap+ellipsis but lacked `min-width: 0`, so a long in-flight leg would have overflowed instead of truncating — same one-line guard added. Fuel/loadout spans are short fixed strings and need no guard
- Verified: `tsc --noEmit` clean; unit suite **238/238** green locally (no lib changes); e2e not run locally by design — CI verifies against an isolated stack
- **Unrelated test-stability fix included on this branch to unblock the pipeline** (`e2e/map-interactions.spec.ts`, no app changes): the mid-flight marker click now targets the plane's RENDERED position — it polls up to ~5 s for the rendered feature via `window.__flightMap.queryRenderedFeatures` on layers `planes-flying`/`planes-grounded` and projects that feature's coordinates, instead of fetching a fresh `/api/state`. With the sim paused the server position is static, but the map renders from its own ~1 s poll — right after the freeze confirmation the last rendered frame can still be up to one poll interval stale (tens of px at scale 1000 on EDDF→LEMD), so a click projected from a fresh fetch misses the small circle layer: the render-lag race that flaked CI run #37. Pause + freeze confirmation, popup assertions and resume are unchanged
## v0.15.0 — 2026-09-19 09:35
- **Hover visualization from the side panels (ISS-002).** Hovering a fleet row in the left pane, an "On board" block (including its cargo rows) or an open-package row in the right pane now highlights the matching object on the map. The shared `HoverTarget` type (`components/hoverTypes.ts`: `{kind:'plane', id}` | `{kind:'package', originIcao, destIcao}`) is owned by the shell as a single `useState` and prop-drilled down — panes report via an `onHover` callback, `<Map>` consumes it. No React contexts introduced; the established prop-drilling pattern is kept
- **Three top-most highlight layers** (`components/Map.tsx`, added inside idempotent `ensureLayers()` so they survive every `setStyle`): `planes-highlight` (circle over both plane layers, filter `['==',['get','id'],<planeId>]`, r=10, #38bdf8 fill + white stroke), `routes-highlight` (line over `routes-legs`, filter on the leg's `planeId`, width 6, #ef4444) and `airports-highlight` (circle ring over `airports-circles`, filter matching the hovered package's two ICAOs via `['any', …]`, r=8 stroke-only). All start filtered to match nothing — an empty-string sentinel no feature can have. Consumption follows the existing ref + effect pattern: a `[hovered]` effect calls `map.setFilter(...)` on the three layers (guarded by `getLayer`), and `ensureLayers` re-applies the current filter at its end so a hover outliving a style switch stays highlighted
- e2e — new `e2e/hover.spec.ts` (3 tests, same SCALE/self-heal/`window.__flightMap` conventions as the other specs): fleet-row hover → `planes-highlight` renders exactly plane-starter, clears on mouseleave; open-package hover → `airports-highlight` shows both endpoint ICAOs (hook-created EDDF→LEMD package), clears on mouseleave; on-board block of a flying plane → `routes-highlight` shows the leg's planeId (sim paused mid-flight so the ~10 s leg can't land under the assertions, then resumed + fly-home cleanup)
- Verified: `tsc --noEmit` clean; unit suite **238/238** green locally (no lib changes); e2e not run locally by design — CI verifies against an isolated stack
- **E2e hover spec mechanics fixed after CI run #32** (`e2e/hover.spec.ts`, no app changes): the fleet-row wait now polls up to 30 s with a diagnostic that distinguishes "server has no plane-starter" from "DOM didn't render" (the browser's /api/state poll can lag node-side requests right after page load, leaving the pane in its loading state); the open-package test fits the map to both endpoint airports before asserting — `queryRenderedFeatures` only returns features inside the current viewport and the default Frankfurt-centered view leaves LEMD off-screen
- **Decisive hover test-1 diagnostics (run #33 transient)**: the fleet-row poll now reports on every failed attempt what the NODE side sees (`/api/state` plane ids + cash via `page.request`) vs what the BROWSER last polled — new dev hook `window.__flightLastSnapshot` set in `lib/useGameState.ts` after each successful fetch (planeIds/cash/timeScale/timestamp, client-only) — plus the fleet section's HTML (`fleet-list` outerHTML or left-pane text), so a future failure can distinguish server divergence from a render bug
- **CI removes the stale e2e DB volume at run start** (`.gitea/workflows/ci.yml`, "Prepare e2e network"): `docker volume rm flight-ci_flight-db 2>/dev/null || true` — an interrupted run skips the end-of-run cleanup and leaks its used game state into later runs (run #33's instance showed spent cash from a pre-#26 seed), while tests assume seeded state
- **Hover e2e test 1 used the wrong fleet-row testid** (`e2e/hover.spec.ts`): it waited for `data-testid="plane-starter"`, but rows are rendered as `plane-${p.id}` and the server id already carries the `plane-` prefix — so the real testid is **`plane-plane-starter`** and the "missing row" failures in runs #32–#34 were deterministic selector misses, not transient state (run #34's diagnostics proved it: the fleet-list HTML contained `<li data-testid="plane-plane-starter">`). The selector is now derived from `/api/state` (starter plane id, or the single plane) and used for both the visibility poll and the hover
## v0.14.0 — 2026-09-19 08:45
- **Time-scale slider reworked to a 10-step ladder up to 1000× (ISS-006).** The old power-of-two ladder `1/2/4/8/16/32/64` is replaced by the discrete values `1, 2, 5, 10, 25, 50, 100, 250, 500, 1000` (each step roughly doubles the speed). The server clamp range widens from `[1, 64]` to `[1, 1000]` (`MAX_TIME_SCALE` in `lib/sim/engine.ts`, enforced by `clampTimeScale`; out-of-range values are still clamped, never rejected), and the OpenAPI spec's `timeScale` bounds + description follow. The slider mapping helpers in `lib/timeScale.ts` now place off-ladder scales at the nearest ladder step **by log distance** (the old `log2` formula assumed a pure power-of-two ladder); round-trip, monotonicity and endpoint-exactness are preserved
- **E2e suite runs at the fastest time.** Every spec's fast-forward scale moves from 60× to the new top of 1000× (`sim`, `actions`, `right-pane`, `map-interactions`), so flights/expiries resolve in seconds instead of minutes. The map mid-flight test (`map-interactions.spec.ts`) needed a longer leg to keep its click assertions inside the flight window at 1000×: destination moves EDDV (Hannover, ~2 s real) → LEMD (Madrid–Barajas, ~10 s real), with a full-tank refuel before departure so the ~4970 L round trip always fits the 6300 L tank. The slider e2e (`panes.spec.ts`) now asserts End→`1000×` / Home→`1×`, and the clamp tests post `2000` → expect `1000` (500 is a valid ladder value, so it passes through unclamped)
- Tests: unit — `lib/timeScale.test.ts` covers the 10-position ladder + log-distance nearest-step mapping; new `clampTimeScale` boundary suite in `lib/sim/engine.test.ts` (`[1, 1000]`, full ladder pass-through); `app/api/sim/route.test.ts` and `lib/openapi.test.ts` updated to the new bounds. Verified: unit suite **238/238** green locally (was 234 before this change)
- e2e `map-interactions.spec.ts`: the plane-popup test now pauses the sim around the marker click — at 1000× the rendered marker lags a fresh `/api/state` fetch by up to one map poll (~1 s), tens of px of drift on the EDDF→LEMD leg, so `page.mouse.click` missed the small circle layer (CI run #29); the sim is paused until the popup assertions pass, then resumed
## v0.13.1 — 2026-09-19 08:09
- CI e2e step now uses Playwright's list reporter so every test prints as it runs in the job log (progress visibility); failures still get full error context
## v0.12.3 — 2026-09-19 07:36
- **e2e: removed the unreliable curved-route assertion from `map-interactions.spec.ts`.** The "route line has >2 coordinates in the routes source" check (added with v0.12.2) failed in CI and against the live instance even though the arc renders correctly — MapLibre's `querySourceFeatures` returns tile-simplified geometry at low zoom, so coordinate counts from it are not a reliable signal for what was pushed into the source. The curved arc remains fully covered by unit tests (`lib/mapData.test.ts`: 25 sampled coordinates, exact endpoints, curvature on long routes); the spec keeps all other steps (grounded plane draws no line, marker moves across polls, plane popup with status + route)
+1 -1
View File
@@ -19,7 +19,7 @@ Accept job → dispatch a plane → watch it fly the route on the map → earn m
## Simulation engine
- Server-authoritative state: sim ticks on the server, client polls and renders
- Time scale 1x–60x + pause; sim clock persisted across sessions
- Time scale 1x–1000x (discrete ladder 1/2/5/10/25/50/100/250/500/1000) + pause; sim clock persisted across sessions
- SQLite via Drizzle ORM — schema designed to switch to Postgres later
- Demand/revenue/cost formulas per contract leg; fuel burn by distance/plane type
+11 -6
View File
@@ -31,19 +31,24 @@ describe('POST /api/sim', () => {
expect(body.paused).toBe(false);
});
it('sets and clamps timeScale into [1, 64]', async () => {
const hi = await post({ timeScale: 500 });
it('sets and clamps timeScale into [1, 1000]', async () => {
const hi = await post({ timeScale: 2000 });
expect(hi.status).toBe(200);
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(64);
expect(((await hi.json()) as { timeScale: number }).timeScale).toBe(1000);
const lo = await post({ timeScale: 0.1 });
expect(lo.status).toBe(200);
expect(((await lo.json()) as { timeScale: number }).timeScale).toBe(1);
// The top of the power-of-two ladder passes through unclamped (v0.9.2).
const max = await post({ timeScale: 64 });
// The top of the ladder passes through unclamped (v0.14.0).
const max = await post({ timeScale: 1000 });
expect(max.status).toBe(200);
expect(((await max.json()) as { timeScale: number }).timeScale).toBe(64);
expect(((await max.json()) as { timeScale: number }).timeScale).toBe(1000);
// In-range values pass through unclamped — ladder and off-ladder alike.
const ladder = await post({ timeScale: 500 });
expect(ladder.status).toBe(200);
expect(((await ladder.json()) as { timeScale: number }).timeScale).toBe(500);
const mid = await post({ timeScale: 37 });
expect(mid.status).toBe(200);
+2 -2
View File
@@ -1,6 +1,6 @@
import { applyTimeControls } from '@/lib/sim/engine';
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–64, paused?: boolean }.
// POST /api/sim — set sim time controls (v0.7.0). Body: { timeScale?: 1–1000, paused?: boolean }.
// Ticks the clock first (so the response reflects current game time), then applies
// and persists the new controls. Returns the updated simState.
@@ -23,7 +23,7 @@ export async function POST(req: Request) {
}
}
if (input.timeScale !== undefined && (typeof input.timeScale !== 'number' || !Number.isFinite(input.timeScale))) {
return Response.json({ error: 'timeScale must be a finite number (1–64)' }, { status: 400 });
return Response.json({ error: 'timeScale must be a finite number (1–1000)' }, { status: 400 });
}
if (input.paused !== undefined && typeof input.paused !== 'boolean') {
return Response.json({ error: 'paused must be a boolean' }, { status: 400 });
+1 -1
View File
@@ -17,7 +17,7 @@ import { tickNow } from '@/lib/sim/engine';
// (game time) so the next fast tick expires it; 404 if unknown/not open.
// - without: creates a fresh open package with the same short deadline.
const HOOK_DEADLINE_MS = 10_000; // game ms past the current clock (~0.2 s real at 60×)
const HOOK_DEADLINE_MS = 10_000; // game ms past the current clock (≈ 0.01 s real at the fastest 1000×)
export async function POST(req: Request) {
if (process.env.FLIGHT_TEST_HOOKS !== '1') {
+4 -1
View File
@@ -71,7 +71,7 @@ body {
/* v0.9.0 — single-screen 3-pane shell: left Assets / center map / right Jobs & Market */
.app-shell {
display: grid;
grid-template-columns: 300px minmax(0, 1fr) 320px;
grid-template-columns: 280px minmax(0, 1fr) 360px;
height: 100%;
}
@@ -201,6 +201,7 @@ body {
}
.plane-loc {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -265,6 +266,7 @@ body {
}
.contract-route {
min-width: 0;
font-weight: 600;
color: #f1f5f9;
overflow: hidden;
@@ -284,6 +286,7 @@ body {
.pane-btn {
flex-shrink: 0;
white-space: nowrap;
font-size: 12px;
padding: 3px 10px;
border-radius: 4px;
+9 -3
View File
@@ -1,8 +1,10 @@
'use client';
import dynamic from 'next/dynamic';
import { useState } from 'react';
import LeftPane from '@/components/LeftPane';
import RightPane from '@/components/RightPane';
import type { HoverTarget } from '@/components/hoverTypes';
import { useGameState } from '@/lib/useGameState';
const Map = dynamic(() => import('@/components/Map'), { ssr: false });
@@ -13,12 +15,16 @@ export default function Home() {
// lets a pane push an action endpoint's full response snapshot in immediately.
const { state, loading, error, refresh, applySnapshot } = useGameState(1000);
// ISS-002 (v0.15.0): the side panels' hover target — shared here so hovering a row in
// either pane highlights the matching plane/route/airports on the map.
const [hovered, setHovered] = useState<HoverTarget | null>(null);
return (
<div className="app-shell">
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} />
<LeftPane state={state} loading={loading} error={error} onRefresh={refresh} onHover={setHovered} />
{/* v0.11.0 — the same polled snapshot drives the map's plane markers + route lines */}
<Map state={state} />
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} />
<Map state={state} hovered={hovered} />
<RightPane state={state} loading={loading} applySnapshot={applySnapshot} onHover={setHovered} />
</div>
);
}
+18 -7
View File
@@ -5,6 +5,7 @@ import type { PlaneState, StateSnapshot } from '@/lib/game/state';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
import { TIME_SCALES, scaleToSlider, sliderToScale } from '@/lib/timeScale';
import type { HoverTarget } from './hoverTypes';
interface LeftPaneProps {
state: StateSnapshot | null;
@@ -12,11 +13,14 @@ interface LeftPaneProps {
error: string | null;
// The shell's single-poll refresh — called after a sim-control POST so the pane updates immediately.
onRefresh: () => void;
// ISS-002 (v0.15.0): report fleet-row hovers to the shell so the map can highlight the plane.
onHover: (target: HoverTarget | null) => void;
}
// Power-of-two slider (v0.9.2): position t ∈ [0,1] → nearest step of the ladder
// 1×/2×/4×/8×/16×/32×/64× — each of the 7 positions doubles the speed.
const SCALE_SLIDER_STEP = 1 / (TIME_SCALES.length - 1); // one doubling per keyboard-arrow step
// Discrete ladder slider (v0.9.2, values reworked in v0.14.0): position t ∈ [0,1] → nearest
// step of the ladder 1×/2×/5×/10×/25×/50×/100×/250×/500×/1000× — each of the 10 positions
// roughly doubles the speed.
const SCALE_SLIDER_STEP = 1 / (TIME_SCALES.length - 1); // one ladder step per keyboard-arrow step
const SCALE_COMMIT_DEBOUNCE_MS = 250;
// Flying planes show their current leg from the snapshot's dest fields (v0.12.0).
@@ -41,14 +45,14 @@ export function pendingScaleConfirmed(pendingScale: number | null, serverTimeSca
return pendingScale !== null && serverTimeScale === pendingScale;
}
export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneProps) {
export default function LeftPane({ state, loading, error, onRefresh, onHover }: LeftPaneProps) {
const [busy, setBusy] = useState(false);
// POST /api/sim, then refetch the full snapshot immediately so the pane reflects the new
// controls without waiting for the next poll tick. On failure keep the stale UI — the
// running poll retries on its own and surfaces the error state. A commit that lands while
// another POST is in flight is held in a single slot (last intent wins) and flushed by the
// in-flight call, so every user intent reaches the server (the [1,64] clamp stays as backstop).
// in-flight call, so every user intent reaches the server (the [1,1000] clamp stays as backstop).
// The gate is a REF, not React state: closures never see a stale "busy" value, which used to
// let a flush re-queue instead of send and silently drop a commit.
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
@@ -101,7 +105,7 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
// Slider commit (v0.9.1): the displayed value follows the drag optimistically via
// pendingScale; POST /api/sim fires after a 250 ms debounce, or immediately when the
// user releases the slider (browsers fire a native 'change' on release). The server's
// [1,64] clamp stays as the backstop.
// [1,1000] clamp stays as the backstop.
const [pendingScale, setPendingScaleState] = useState<number | null>(null);
const pendingRef = useRef<number | null>(null);
const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -188,7 +192,14 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
) : (
<ul data-testid="fleet-list" className="fleet-list">
{state.planes.map((p) => (
<li key={p.id} data-testid={`plane-${p.id}`} className="plane-row">
// ISS-002: hovering a fleet row highlights the plane on the map.
<li
key={p.id}
data-testid={`plane-${p.id}`}
className="plane-row"
onMouseEnter={() => onHover({ kind: 'plane', id: p.id })}
onMouseLeave={() => onHover(null)}
>
<div className="plane-main">
<span className="plane-model">{PLANE_TYPES[p.model]?.name ?? p.model}</span>
<span className={`plane-status status-${p.status}`}>{p.status}</span>
+88 -2
View File
@@ -7,6 +7,7 @@ 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';
@@ -27,6 +28,11 @@ 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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -36,11 +42,14 @@ 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 }: MapProps) {
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
@@ -74,6 +83,38 @@ export default function FlightMap({ state }: MapProps) {
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;
@@ -240,6 +281,49 @@ export default function FlightMap({ state }: MapProps) {
},
});
}
// 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);
@@ -248,8 +332,10 @@ export default function FlightMap({ state }: MapProps) {
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.
// 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();
+24 -4
View File
@@ -5,6 +5,7 @@ import type { PackageState, PlaneState, StateSnapshot } from '@/lib/game/state';
import { PLANE_TYPES } from '@/lib/game/catalog';
import { abandonPenalty } from '@/lib/game/penalty';
import { formatCash, formatDeadlineRelative } from '@/lib/format';
import type { HoverTarget } from './hoverTypes';
interface RightPaneProps {
state: StateSnapshot | null;
@@ -12,6 +13,9 @@ interface RightPaneProps {
// Push the full snapshot returned by an action endpoint into the shared shell state (v0.10.0),
// so the pane updates on click without waiting for the next poll tick.
applySnapshot: (snapshot: StateSnapshot) => void;
// ISS-002 (v0.15.0): report row hovers to the shell so the map can highlight the plane or
// the package's endpoint airports.
onHover: (target: HoverTarget | null) => void;
}
const planeName = (p: PlaneState): string => PLANE_TYPES[p.model]?.name ?? p.model;
@@ -100,7 +104,7 @@ function LoadControls({
);
}
export default function RightPane({ state, loading, applySnapshot }: RightPaneProps) {
export default function RightPane({ state, loading, applySnapshot, onHover }: RightPaneProps) {
const [busy, setBusy] = useState(false);
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
// snapshot prop changes every tick) or the next successful action.
@@ -192,7 +196,14 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
{open.map((pkg) => {
const eligible = loadEligiblePlanes(state, pkg);
return (
<li key={pkg.id} data-testid={`open-package-${pkg.id}`} className="contract-row">
// ISS-002: hovering an open package highlights its two endpoint airports on the map.
<li
key={pkg.id}
data-testid={`open-package-${pkg.id}`}
className="contract-row"
onMouseEnter={() => onHover({ kind: 'package', originIcao: pkg.originIcao, destIcao: pkg.destIcao })}
onMouseLeave={() => onHover(null)}
>
<div className="contract-main">
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
{eligible.length > 0 ? (
@@ -232,7 +243,16 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
(pkg) => pkg.planeId === plane.id && (pkg.status === 'loaded' || pkg.status === 'expired'),
);
return (
<div key={plane.id} data-testid={`onboard-${plane.id}`} className="onboard-block">
// ISS-002: hovering the on-board block (including its cargo rows) highlights the plane.
// Handlers live only on the outer div — React's enter/leave don't fire when moving to a
// child, so this covers the whole block without flicker between sub-elements.
<div
key={plane.id}
data-testid={`onboard-${plane.id}`}
className="onboard-block"
onMouseEnter={() => onHover({ kind: 'plane', id: plane.id })}
onMouseLeave={() => onHover(null)}
>
<div className="contract-main">
<span className="plane-model">{planeName(plane)}</span>
{plane.status === 'flying' ? (
@@ -274,7 +294,7 @@ export default function RightPane({ state, loading, applySnapshot }: RightPanePr
</button>
</div>
<div className="contract-sub">
<span>{pkg.originName} → {pkg.destName}</span>
<span className="contract-route">{pkg.originName} → {pkg.destName}</span>
<span>{formatCash(pkg.reward)}</span>
{pkg.status === 'expired' ? (
<span data-testid={`onboard-expired-${pkg.id}`}>expired</span>
+7
View File
@@ -0,0 +1,7 @@
// ISS-002 — what a side-panel hover highlights on the map (v0.15.0): a plane marker
// (+ its route leg if flying) or both endpoint airports of an open package. The shell
// owns this state and passes it to <Map>; panes report it via their onHover callback.
export type HoverTarget =
| { kind: 'plane'; id: string }
| { kind: 'package'; originIcao: string; destIcao: string };
+7 -7
View File
@@ -3,12 +3,12 @@ import { expect, test } from '@playwright/test';
// v0.12.0 package model against the live origin (https://flight.dev.kkhost.pl):
// the full core loop through the UI — hook creates a short package at EDDF → Load
// via the right pane → click its destination in the on-board list → fly at 60× →
// via the right pane → click its destination in the on-board list → fly at 1000× →
// arrival delivers EXACTLY the reward + rep; abandon deducts exactly the formula
// penalty while grounded; expired packages deliver/abandon with no reward and no
// penalty. Mirrors lib/game/penalty.ts for exact-value assertions.
const SCALE = 60; // fastest sim speed — keeps flights to seconds of real time
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
const HUB = 'EDDF'; // Frankfurt Main — the seeded starter plane's home base (lib/game/seed.ts)
const FAR = 'LEZL'; // Seville — one-way burn 3174 L > half tank, so the return leg is unfuelable
@@ -93,7 +93,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
const s0 = await getState(page);
const plane = s0.planes.find((p) => p.id === 'plane-starter')!;
if (plane.status === 'flying' || plane.locationIcao !== HUB) {
// Fast-forward any leftover leg / repositioning flight (~3 min real time worst case at 60×).
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
await setScale(page, SCALE);
}
if (plane.status === 'flying') {
@@ -119,7 +119,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
test('full core loop via UI: load → fly to destination → exact reward + rep on arrival', async ({ page }) => {
test.setTimeout(300_000); // self-heal (worst case ~3 min at 60×) + two short flights + refuel
test.setTimeout(300_000); // self-heal (worst case ~20 s at 1000×) + two short flights + refuel
// Self-heal: the starter plane may be anywhere from a previous run/spec.
await flyHomeViaApi(page);
const before = await getState(page);
@@ -154,7 +154,7 @@ test('full core loop via UI: load → fly to destination → exact reward + rep
expect(s.planes.find((p) => p.id === planeId)!.status).toBe('flying');
expect(s.planes.find((p) => p.id === planeId)!.destIcao).toBe(nearest.icao);
// Fast-forward to arrival (≤ ~10 min game time at 60× → seconds of real time).
// Fast-forward to arrival (a few seconds of real time at 1000×).
await setScale(page, SCALE);
await expect.poll(async () => ((await getState(page)).planes.find((p) => p.id === planeId)!.status), { timeout: 120_000 }).toBe('available');
@@ -230,7 +230,7 @@ test('abandon while grounded deducts exactly the formula penalty', async ({ page
});
test('expired packages deliver and abandon with no reward and no penalty', async ({ page }) => {
test.setTimeout(480_000); // two ~3 min real-time legs at 60× (HUB↔LEMD) plus expiry wait
test.setTimeout(480_000); // two ~10 s real-time legs at 1000× (HUB↔LEMD) plus expiry wait
await flyHomeViaApi(page);
const before = await getState(page);
@@ -281,7 +281,7 @@ test('expired packages deliver and abandon with no reward and no penalty', async
});
test('load and fly validation paths (404 / 409 / 400)', async ({ page }) => {
test.setTimeout(600_000); // the FAR round trip alone is ~7.5 min real time at 60×
test.setTimeout(600_000); // the FAR round trip alone is ~30 s real time at 1000×
await flyHomeViaApi(page);
// Load a package whose origin the plane is not at → 409.
+302
View File
@@ -0,0 +1,302 @@
import { test, expect, type Page } from '@playwright/test';
// v0.15.0 — ISS-002: hovering a plane or package in either side panel highlights it on the map.
// Fleet rows + on-board blocks highlight the plane marker (and its route leg while flying);
// open-package rows highlight both endpoint airports. The map exposes three top-most
// highlight layers (planes-highlight / routes-highlight / airports-highlight), each filtered
// to match nothing until a hover sets the filter — asserted here via window.__flightMap's
// queryRenderedFeatures, same pattern as e2e/map.spec.ts and e2e/map-interactions.spec.ts.
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
// Madrid–Barajas — same long leg as e2e/map-interactions.spec.ts: ~1420 km → ~10 s at scale 1000.
const DEST = 'LEMD';
interface PlaneState {
id: string;
model: string;
status: 'available' | 'flying';
fuel: number;
maxFuel: number;
locationIcao: string;
destIcao: string | null;
}
interface PackageState {
id: string;
originName: string;
destName: string;
reward: number;
status: 'open' | 'loaded' | 'delivered' | 'expired' | 'abandoned';
planeId: string | null;
}
interface StateBody {
account: { cash: number; reputation: number };
simState: { clockMs: number; timeScale: number; paused: boolean };
planes: PlaneState[];
packages: PackageState[];
}
async function getState(page: Page): Promise<StateBody> {
const res = await page.request.get('/api/state');
expect(res.status()).toBe(200);
return (await res.json()) as StateBody;
}
async function postSim(page: Page, body: unknown) {
return page.request.post('/api/sim', { data: body });
}
// Set the time scale and VERIFY from the response that it stuck — a silent reset would
// otherwise surface as an unexplained landing-wait timeout.
async function setScale(page: Page, scale: number): Promise<void> {
const res = await page.request.post('/api/sim', { data: { timeScale: scale } });
expect(res.status()).toBe(200);
const body = (await res.json()) as { timeScale: number };
expect(body.timeScale, `timeScale should be ${scale} after POST /api/sim`).toBe(scale);
}
// Leave the live instance in a sane state for the other specs (scale 1, running).
test.afterEach(async ({ page }) => {
const res = await postSim(page, { timeScale: 1, paused: false });
expect(res.status()).toBe(200);
});
// Test hook (FLIGHT_TEST_HOOKS=1): create an open package on a known route.
async function createPackage(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
const created = await page.request.post('/api/test/create-package', {
data: { originIcao: fromIcao, destIcao: toIcao, deadlineOffsetMs: 24 * 3_600_000 },
});
expect(created.status()).toBe(201);
return (await created.json()) as PackageState;
}
// Self-heal: let any in-flight leg finish, then reposition plane-starter home via the API.
async function flyHomeViaApi(page: Page): Promise<void> {
const s0 = await getState(page);
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
await setScale(page, SCALE);
}
if (starter.status === 'flying') {
await expect
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.status === 'available', {
timeout: 240_000,
message: 'waiting for an in-flight plane-starter to land',
})
.toBe(true);
}
if (starter.locationIcao !== HUB) {
const res = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
expect(res.status()).toBe(200); // repositioning needs no package (v0.12.0 manual flight)
await expect
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
timeout: 240_000,
message: 'waiting for plane-starter to land back at the hub',
})
.toBe(true);
}
}
async function waitForAirportCount(page: Page): Promise<void> {
const countEl = page.getByTestId('airport-count');
await expect.poll(async () => {
const text = (await countEl.textContent()) ?? '';
const m = text.match(/(\d+)/);
return m ? parseInt(m[1], 10) : -1;
}).toBeGreaterThan(0);
}
// Rendered features of the given layers in the current viewport, [] until the map exists.
function renderedFeatures(page: Page, layers: string[]) {
return page.evaluate((ls: string[]) => {
const m = (window as any).__flightMap;
if (!m) return [];
try {
return m.queryRenderedFeatures(undefined, { layers: ls });
} catch {
return [];
}
}, layers);
}
// Move the pointer to a neutral element with no hover handler — leaves any hovered row/block.
async function unhover(page: Page): Promise<void> {
await page.getByTestId('wallet-cash').hover();
}
// Fit the map so all given airports are in-viewport — queryRenderedFeatures only returns
// features rendered inside the CURRENT viewport, and the default Frankfurt-centered view leaves
// far endpoints (LEMD) off-screen even when they match a layer filter.
async function fitToAirports(page: Page, icaos: string[]): Promise<void> {
const fc = (await (await page.request.get('/api/airports')).json()) as {
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
};
const points = icaos.map((icao) => {
const f = fc.features.find((x) => x.properties.icao === icao);
if (!f) throw new Error(`airport ${icao} not found in /api/airports`);
return [f.properties.lon, f.properties.lat] as [number, number];
});
await page.evaluate((pts: [number, number][]) => {
const m = (window as any).__flightMap;
if (!m) throw new Error('map not ready');
const lons = pts.map((p) => p[0]);
const lats = pts.map((p) => p[1]);
// duration 0 → instant camera jump, no animation to wait out.
m.fitBounds(
[
[Math.min(...lons), Math.min(...lats)],
[Math.max(...lons), Math.max(...lats)],
],
{ padding: 40, duration: 0 },
);
}, points);
// Give the renderer a beat after the camera jump before asserting on rendered features.
await page.waitForTimeout(300);
}
test('hovering a fleet row highlights the plane on the map', async ({ page }) => {
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
await flyHomeViaApi(page); // deterministic: the starter sits at EDDF, inside the initial view
await page.goto('/');
await waitForAirportCount(page);
// Fleet rows are <li data-testid={`plane-${p.id}`}> and the server id already carries the "plane-"
// prefix (run #34: the real testid is plane-plane-starter) — derive it from /api/state, never hardcode.
const planes = (await getState(page)).planes;
const starterId = planes.find((p) => p.id.endsWith('starter'))?.id ?? (planes.length === 1 ? planes[0].id : undefined);
expect(starterId).toBeDefined();
const row = page.locator(`li[data-testid="plane-${starterId}"]`);
// The browser's /api/state polls can lag node-side requests right after a fresh page load
// (useGameState keeps loading=true until the first success → no fleet rows yet), so poll with
// diagnostics: on timeout the message compares what the NODE side sees vs what the BROWSER
// last polled, plus the fleet section's HTML — distinguishing server divergence from a render
// bug. (The value is returned, not thrown — expect.poll fails immediately on a callback throw
// instead of retrying.)
await expect
.poll(async () => {
if ((await row.count()) > 0 && (await row.isVisible())) return 'visible';
const body = await getState(page);
const browserSnap = await page.evaluate(() => (window as any).__flightLastSnapshot ?? null);
const fleetHtml = await page.evaluate(() => {
const el = document.querySelector('[data-testid="fleet-list"]');
if (el) return `fleet-list HTML: ${(el.outerHTML ?? '').slice(0, 300)}`;
const pane = document.querySelector<HTMLElement>('[data-testid="left-pane"]');
return `no fleet-list — left-pane text: ${(pane?.innerText ?? '').slice(0, 200)}`;
});
return (
`not visible — node /api/state planes=[${body.planes.map((p) => p.id).join(', ')}] cash=${body.account.cash}; ` +
`browser __flightLastSnapshot=${JSON.stringify(browserSnap)}; ${fleetHtml}`
);
}, { timeout: 30_000 })
.toBe('visible');
// No highlight before hovering (the layers start filtered to match nothing).
expect(await renderedFeatures(page, ['planes-highlight'])).toHaveLength(0);
await row.hover();
await expect.poll(async () => {
const feats = (await renderedFeatures(page, ['planes-highlight'])) as Array<{ properties: Record<string, unknown> }>;
return feats.length > 0 && feats[0].properties.id === starterId;
}, { timeout: 15_000, message: `waiting for the planes-highlight layer to show ${starterId}` }).toBe(true);
await unhover(page);
await expect.poll(async () => (await renderedFeatures(page, ['planes-highlight'])).length, {
timeout: 15_000,
message: 'waiting for the highlight to clear after mouseleave',
}).toBe(0);
});
test('hovering an open package highlights its endpoint airports', async ({ page }) => {
test.setTimeout(300_000); // self-heal can take minutes after an interrupted run
await flyHomeViaApi(page);
const pkg = await createPackage(page, HUB, DEST);
await page.goto('/');
await waitForAirportCount(page);
const row = page.locator(`li[data-testid="open-package-${pkg.id}"]`);
await expect(row, 'the hook-created package appears in the list').toBeVisible({ timeout: 15_000 });
// Both endpoints must be in-viewport for queryRenderedFeatures to see them (LEMD is off-screen
// at the default Frankfurt-centered view).
await fitToAirports(page, [HUB, DEST]);
expect(await renderedFeatures(page, ['airports-highlight'])).toHaveLength(0);
await row.hover();
await expect.poll(async () => {
const feats = (await renderedFeatures(page, ['airports-highlight'])) as Array<{ properties: Record<string, unknown> }>;
return JSON.stringify(feats.map((f) => f.properties.icao).sort());
}, { timeout: 15_000, message: 'waiting for the airports-highlight layer to show both endpoints' })
.toBe(JSON.stringify([HUB, DEST].sort()));
await unhover(page);
await expect.poll(async () => (await renderedFeatures(page, ['airports-highlight'])).length, {
timeout: 15_000,
message: 'waiting for the highlight to clear after mouseleave',
}).toBe(0);
});
test('hovering an on-board block of a flying plane highlights its route', async ({ page }) => {
test.setTimeout(600_000); // self-heal + one flight at scale 1000 + fly-home cleanup
await flyHomeViaApi(page);
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank.
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
expect(refuel.status()).toBe(200);
await page.goto('/');
await waitForAirportCount(page);
// Load + fly via the API (same pattern as e2e/map-interactions.spec.ts), then speed up.
const pkg = await createPackage(page, HUB, DEST);
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
expect(load.status()).toBe(200);
const fly = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: DEST } });
expect(fly.status()).toBe(200);
await setScale(page, SCALE);
// The on-board block shows the plane in flight once a snapshot with status 'flying' lands.
const block = page.getByTestId('onboard-plane-starter');
await expect(block).toContainText(/in flight/i, { timeout: 15_000 });
// Freeze mid-flight so the ~10 s leg can't land under us while we assert (same pattern as
// e2e/map-interactions.spec.ts' marker click): the route line stays drawn while paused.
await postSim(page, { paused: true });
await block.hover();
await expect.poll(async () => {
const feats = (await renderedFeatures(page, ['routes-highlight'])) as Array<{ properties: Record<string, unknown> }>;
return feats.length > 0 && feats[0].properties.planeId === 'plane-starter';
}, { timeout: 15_000, message: 'waiting for the routes-highlight layer to show the plane-starter leg' }).toBe(true);
await unhover(page);
await expect.poll(async () => (await renderedFeatures(page, ['routes-highlight'])).length, {
timeout: 15_000,
message: 'waiting for the highlight to clear after mouseleave',
}).toBe(0);
// Resume and fast-forward to arrival, then fly home so the live instance stays in its
// onboarding state (starter grounded at EDDF) for the other specs.
await postSim(page, { timeScale: SCALE, paused: false });
await expect
.poll(async () => {
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
return !!p && p.status === 'available' && p.locationIcao === DEST;
}, { timeout: 120_000, message: `waiting for plane-starter to land at ${DEST}` })
.toBe(true);
const home = await page.request.post('/api/planes/plane-starter/fly', { data: { destIcao: HUB } });
expect(home.status()).toBe(200);
await expect
.poll(async () => (await getState(page)).planes.find((p) => p.id === 'plane-starter')?.locationIcao === HUB, {
timeout: 120_000,
message: 'waiting for plane-starter to land back at the hub',
})
.toBe(true);
});
+55 -15
View File
@@ -5,14 +5,16 @@ import { test, expect, type Page } from '@playwright/test';
// deterministic generated weather), plane markers whose positions come from the
// /api/state polls, each FLYING plane's current leg as a route line (origin →
// dest_icao; grounded planes draw nothing), and the plane status popup. Packages
// are created on a known EDDF→EDDV route via POST /api/test/create-package
// are created on a known EDDF→LEMD route via POST /api/test/create-package
// (FLIGHT_TEST_HOOKS=1).
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
// Hannover — ~282 km from EDDF → ~33 min game time ≈ 33 s at scale 60, a comfortable
// window for the click assertions below (the nearest airport would land too fast).
const DEST = 'EDDV';
const SCALE = 60;
// Madrid–Barajas — ~1420 km from EDDF → ~2.8 h game time ≈ 10 s at scale 1000, a comfortable
// window for the mid-flight click assertions below (at 1000× even Hannover's 33-min leg would
// land in ~2 s — shorter than the map poll + click pipeline). Round-trip burn (~4970 L) fits
// the 6300 L tank, so a full-tank departure always makes it home.
const DEST = 'LEMD';
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top)
interface PlaneState {
id: string;
@@ -91,7 +93,7 @@ async function createPackage(page: Page, fromIcao: string, toIcao: string): Prom
}
// Load a package onto plane-starter and fly it from → to via the API, then poll at
// scale 60 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
// scale 1000 until the plane lands at `to`. Same pattern as e2e/actions.spec.ts.
async function loadAndFly(page: Page, fromIcao: string, toIcao: string): Promise<PackageState> {
const pkg = await createPackage(page, fromIcao, toIcao);
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
@@ -171,7 +173,7 @@ test('airport popup shows name, ICAO, local time and generated weather', async (
});
test('plane markers move while flying and the plane popup shows status + route', async ({ page }) => {
test.setTimeout(600_000); // self-heal from a far airport (~4 min worst case at 60×) + main flight + cleanup
test.setTimeout(600_000); // self-heal from a far airport (~20 s worst case at 1000×) + main flight + cleanup
await page.goto('/');
await waitForAirportCount(page);
@@ -195,6 +197,11 @@ test('plane markers move while flying and the plane popup shows status + route',
await loadAndFly(page, starterLoc, HUB);
}
// Full tank before departure — the EDDF↔LEMD round trip burns ~4970 L of the 6300 L tank,
// so a partially drained plane left by an earlier spec could not make it home.
const refuel = await page.request.post('/api/planes/plane-starter/refuel');
expect(refuel.status()).toBe(200);
// 1) Load the hook-created package — a GROUNDED plane draws no route line yet.
const pkg = await createPackage(page, HUB, DEST);
const load = await page.request.post(`/api/packages/${pkg.id}/load`, { data: { planeId: 'plane-starter' } });
@@ -244,20 +251,50 @@ test('plane markers move while flying and the plane popup shows status + route',
// The arc itself stays covered by unit tests: lib/mapData.test.ts.)
// 4) Click the flying plane → status popup with model, status, fuel and the leg.
// Fetch + project in one evaluate so the click lands on a fresh position (the
// marker drifts only ~1 px/s of screen space at scale 60).
// Freeze the sim so the click can't miss a fast-moving marker: at scale 1000 the rendered
// marker lags our fresh /api/state fetch by up to one map poll (~1 s) — tens of px of drift
// on this leg. Pausing makes the position static; we resume right after the popup checks.
await postSim(page, { paused: true });
let prevPos: { lat: number; lon: number } | null = null;
await expect
.poll(async () => {
const p = (await getState(page)).planes.find((x) => x.id === 'plane-starter');
if (!p || p.status !== 'flying') return false;
if (prevPos && prevPos.lat === p.lat && prevPos.lon === p.lon) return true;
prevPos = { lat: p.lat, lon: p.lon };
return false;
}, { timeout: 15_000, message: 'waiting for the paused clock to freeze the plane position' })
.toBe(true);
// Click the RENDERED marker position, not a fresh /api/state fetch. With the sim paused
// above the server's analytic position is static — but the map renders from its own ~1 s
// poll, so right after the freeze confirmation the last rendered frame can still be up to
// one poll interval stale (tens of px at scale 1000 on this leg) and a click projected
// from a fresh fetch misses the small circle layer (CI run #37). Poll for the plane's
// rendered feature instead and project ITS coordinates — exactly what the map draws.
// Find + project in one evaluate so nothing can change between the two steps.
const pt = await page.evaluate(async () => {
const m = (window as any).__flightMap;
if (!m) return null;
const res = await fetch('/api/state', { cache: 'no-store' });
const body = (await res.json()) as StateBody;
const p = body.planes.find((x) => x.id === 'plane-starter');
if (!p || p.status !== 'flying') return null;
const projected = m.project([p.lon, p.lat]);
const deadline = Date.now() + 5_000;
for (;;) {
let feats: Array<{ properties?: Record<string, unknown>; geometry?: { coordinates: number[] } }> = [];
try {
feats = m.queryRenderedFeatures(undefined, { layers: ['planes-flying', 'planes-grounded'] });
} catch {
// map not ready yet — keep polling
}
const f = feats.find((x) => x.properties?.id === 'plane-starter');
if (f && f.geometry) {
const projected = m.project(f.geometry.coordinates);
const rect = m.getContainer().getBoundingClientRect();
return { x: rect.left + projected.x, y: rect.top + projected.y };
}
if (Date.now() >= deadline) return null;
await new Promise((r) => setTimeout(r, 100));
}
});
expect(pt).not.toBeNull(); // the flight (~33 s at scale 60) is still in progress here
expect(pt, 'plane marker not rendered after pause').not.toBeNull();
await page.mouse.click(pt!.x, pt!.y);
const popup = page.getByTestId('plane-popup');
@@ -270,6 +307,9 @@ test('plane markers move while flying and the plane popup shows status + route',
// The popup's route line is the plane's own leg: origin name → destination name.
await expect(page.getByTestId('plane-route')).toContainText(`${live.locationName} → ${live.destName}`);
// Resume before step 5 — the landing wait needs a running clock.
await postSim(page, { timeScale: SCALE, paused: false });
// 5) Let the flight finish, then fly home so the live instance stays in its
// onboarding state (starter grounded at EDDF) for the other specs. The loaded
// package is delivered on arrival (in-deadline).
+8 -8
View File
@@ -69,7 +69,7 @@ test('left pane renders wallet, reputation and the starter fleet at Frankfurt',
await expect(page.getByTestId('sim-clock')).toContainText(/UTC/);
});
test('time controls: pause freezes the sim and the power-of-two slider sets timeScale', async ({ page }) => {
test('time controls: pause freezes the sim and the ladder slider sets timeScale', async ({ page }) => {
await page.goto('/');
const pauseBtn = page.getByTestId('pause-toggle');
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
@@ -80,13 +80,13 @@ test('time controls: pause freezes the sim and the power-of-two slider sets time
// …and in the pane itself (the refetch after POST flips the button to Resume).
await expect(pauseBtn).toHaveText('Resume');
// Scale via the power-of-two slider. End jumps to max (t=1 → 64×): the label updates
// Scale via the ladder slider. End jumps to max (t=1 → 1000×): the label updates
// optimistically on input, and release flushes the debounced POST immediately.
const slider = page.getByTestId('time-scale-slider');
await slider.focus();
await page.keyboard.press('End');
await expect(page.getByTestId('time-scale-value')).toHaveText('64×', { timeout: 10_000 });
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(64);
await expect(page.getByTestId('time-scale-value')).toHaveText('1000×', { timeout: 10_000 });
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1000);
// Home jumps to min (t=0 → 1×).
await page.keyboard.press('Home');
@@ -116,19 +116,19 @@ test('slider commit keeps the chosen scale on screen until confirmed — no snap
// …and sample the displayed value rapidly across the whole commit→confirm window. With the
// ISS-001 fix the optimistic value stays until a snapshot confirms it, so EVERY sample must
// be '64×' — never snapping back to the previous scale for one poll cycle (the old bug).
// be '1000×' — never snapping back to the previous scale for one poll cycle (the old bug).
const seen: string[] = [];
for (let i = 0; i < 30; i++) {
seen.push(((await page.getByTestId('time-scale-value').textContent()) ?? '').trim());
await new Promise((r) => setTimeout(r, 25));
}
expect(
seen.every((v) => v === '64×'),
`displayed scale must stay 64× during the commit window (saw: ${[...new Set(seen)].join(', ')})`,
seen.every((v) => v === '1000×'),
`displayed scale must stay 1000× during the commit window (saw: ${[...new Set(seen)].join(', ')})`,
).toBe(true);
// …and the server confirms it.
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(64);
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1000);
// Restore to min for later tests (afterEach restores scale anyway).
await page.keyboard.press('Home');
+5 -5
View File
@@ -8,7 +8,7 @@ import { expect, test } from '@playwright/test';
// match the catalog + economy constants exposed in /api/state. Packages are created via
// POST /api/test/create-package (FLIGHT_TEST_HOOKS=1), same pattern as e2e/actions.spec.ts.
const SCALE = 60;
const SCALE = 1000; // fastest sim speed (v0.14.0 ladder top) — keeps flights to seconds of real time
const HUB = 'EDDF'; // must match HUB_ICAO in lib/game/seed.ts
interface PlaneState {
@@ -98,7 +98,7 @@ function penaltyFor(reward: number, createdSimTime: number, deadlineSimTime: num
return Math.round(reward * (0.15 + 0.45 * frac) * 100) / 100;
}
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 60.
// Closest airport to EDDF from /api/airports → shortest possible arrival time at scale 1000.
async function nearestToHub(page: Page): Promise<{ icao: string; lat: number; lon: number }> {
const fc = (await (await page.request.get('/api/airports')).json()) as {
features: Array<{ properties: { icao: string; lat: number; lon: number } }>;
@@ -128,7 +128,7 @@ async function flyHomeViaApi(page: Page): Promise<void> {
const s0 = await getState(page);
const starter = s0.planes.find((p) => p.id === 'plane-starter')!;
if (starter.status === 'flying' || starter.locationIcao !== HUB) {
// Fast-forward any leftover leg / repositioning flight (~3 min real time worst case at 60×).
// Fast-forward any leftover leg / repositioning flight (~20 s real time worst case at 1000×).
await setScale(page, SCALE);
}
if (starter.status === 'flying') {
@@ -197,7 +197,7 @@ test('Load is disabled when no plane sits at the package origin', async ({ page
});
test('on-board list: fly-to-destination + abandon with penalty preview; flying planes show their leg', async ({ page }) => {
test.setTimeout(240_000); // one short flight at scale 60 plus UI steps — typical run well under three minutes
test.setTimeout(240_000); // one short flight at scale 1000 (seconds of real time) plus UI steps
await flyHomeViaApi(page);
const nearest = await nearestToHub(page);
@@ -241,7 +241,7 @@ test('on-board list: fly-to-destination + abandon with penalty preview; flying p
const b = await getState(page);
const p = b.planes.find((x) => x.id === 'plane-starter');
return !!p && p.status === 'available' && p.locationIcao === nearest.icao;
}, { timeout: 120_000, message: `waiting for arrival at ${nearest.icao} (scale 60)` })
}, { timeout: 120_000, message: `waiting for arrival at ${nearest.icao} (scale 1000)` })
.toBe(true);
// The in-deadline package was delivered on arrival — it leaves the on-board list…
+12 -8
View File
@@ -6,8 +6,8 @@ import { test, expect, type Page } from '@playwright/test';
// Must match lib/sim/engine.ts — kept in sync manually (same pattern as MIN_ZOOM/MAX_ZOOM in map.spec.ts).
const MAX_TICK_ELAPSED_MS = 2_000;
const SCALE = 60;
const MAX_DELTA_PER_TICK = MAX_TICK_ELAPSED_MS * SCALE; // 120_000 game ms per tick at scale 60
const SCALE = 1000; // fastest sim speed — top of the v0.14.0 ladder
const MAX_DELTA_PER_TICK = MAX_TICK_ELAPSED_MS * SCALE; // 2_000_000 game ms per tick at scale 1000
// Must match MARKET_TARGET_OPEN_PACKAGES in lib/game/seed.ts.
const MARKET_TARGET = 10;
@@ -42,7 +42,7 @@ test.afterEach(async ({ page }) => {
expect(res.status()).toBe(200);
});
test('timeScale 60 advances the clock by roughly real-time × 60 between polls', async ({ page }) => {
test('timeScale 1000 advances the clock by roughly real-time × 1000 between polls', async ({ page }) => {
const post = await postSim(page, { timeScale: SCALE });
expect(post.status()).toBe(200);
const s1 = (await post.json()) as SimState;
@@ -51,11 +51,11 @@ test('timeScale 60 advances the clock by roughly real-time × 60 between polls',
let prev = s1.clockMs;
for (let i = 0; i < 3; i++) {
await sleep(1_000); // one real second ≈ 60 game seconds at scale 60 — well under the clamp
await sleep(1_000); // one real second ≈ 1000 game seconds at scale 1000 — well under the clamp
const body = await getState(page);
const now = body.simState.clockMs;
expect(now).toBeGreaterThan(prev); // strictly advances while actively polled
expect(now - prev).toBeGreaterThanOrEqual(30_000); // ≥ ~500 ms real × 60
expect(now - prev).toBeGreaterThanOrEqual(500_000); // ≥ ~500 ms real × 1000
expect(now - prev).toBeLessThanOrEqual(MAX_DELTA_PER_TICK + 60); // clamp bounds each tick
prev = now;
}
@@ -82,7 +82,7 @@ test('an open package past its short deadline expires and the market stays toppe
expect(victim).toBeDefined(); // steady state always has open packages
// Test-only hook (FLIGHT_TEST_HOOKS=1 in docker-compose): move an existing open
// package's deadline ~10 game-seconds out so expiry is observable at scale 60.
// package's deadline ~10 game-seconds out so expiry is observable at scale 1000.
const hook = await page.request.post('/api/test/expire-package', { data: { packageId: victim!.id } });
expect(hook.status()).toBe(200);
const moved = (await hook.json()) as { id: string; deadlineSimTime: number };
@@ -132,9 +132,13 @@ test('the hook can also create a fresh short-deadline package, which then expire
});
test('POST /api/sim validates and clamps its input', async ({ page }) => {
const clampHigh = await postSim(page, { timeScale: 500 });
const clampHigh = await postSim(page, { timeScale: 2000 });
expect(clampHigh.status()).toBe(200);
expect(((await clampHigh.json()) as SimState).timeScale).toBe(64); // top of the power-of-two ladder (v0.9.2)
expect(((await clampHigh.json()) as SimState).timeScale).toBe(1000); // top of the ladder (v0.14.0)
const inRange = await postSim(page, { timeScale: 500 });
expect(inRange.status()).toBe(200);
expect(((await inRange.json()) as SimState).timeScale).toBe(500); // ladder value passes through unclamped
const clampLow = await postSim(page, { timeScale: 0.1 });
expect(clampLow.status()).toBe(200);
+1 -1
View File
@@ -153,7 +153,7 @@ describe('OpenAPI spec', () => {
expect(Object.keys(controls).sort()).toEqual(['paused', 'timeScale']);
expect(controls.timeScale.type).toBe('number');
expect(controls.timeScale.minimum).toBe(1);
expect(controls.timeScale.maximum).toBe(64);
expect(controls.timeScale.maximum).toBe(1000);
expect(controls.paused.type).toBe('boolean');
const error = openApiSpec.components.schemas.Error.properties;
+3 -3
View File
@@ -394,7 +394,7 @@ export const openApiSpec = {
type: 'object',
properties: {
clockMs: { type: 'integer', description: 'Sim-clock epoch ms (game time)' },
timeScale: { type: 'number', minimum: 1, maximum: 64 },
timeScale: { type: 'number', minimum: 1, maximum: 1000 },
paused: { type: 'boolean' },
},
required: ['clockMs', 'timeScale', 'paused'],
@@ -406,8 +406,8 @@ export const openApiSpec = {
timeScale: {
type: 'number',
minimum: 1,
maximum: 64,
description: 'Game-time multiplier; values outside [1, 64] are clamped. The UI offers the power-of-two ladder 1/2/4/8/16/32/64.',
maximum: 1000,
description: 'Game-time multiplier; values outside [1, 1000] are clamped. The UI offers the ladder 1/2/5/10/25/50/100/250/500/1000.',
},
paused: { type: 'boolean' },
},
+29
View File
@@ -11,9 +11,12 @@ import { PLANE_TYPES } from '@/lib/game/catalog';
import { MARKET_TARGET_OPEN_PACKAGES, mulberry32 } from '@/lib/game/seed';
import { arrivalTimeFor } from './movement';
import {
clampTimeScale,
deliverPackages,
expirePackages,
MAX_TICK_ELAPSED_MS,
MAX_TIME_SCALE,
MIN_TIME_SCALE,
reputationGainFor,
spawnCoveragePackages,
spawnOpenPackages,
@@ -374,6 +377,32 @@ describe('spawnCoveragePackages (v0.8.0 spawn coverage rule)', () => {
});
});
describe('clampTimeScale — v0.14.0 ladder bounds [1, 1000]', () => {
it('clamps below-minimum values to MIN_TIME_SCALE', () => {
expect(clampTimeScale(0)).toBe(MIN_TIME_SCALE);
expect(clampTimeScale(-5)).toBe(MIN_TIME_SCALE);
expect(clampTimeScale(0.1)).toBe(MIN_TIME_SCALE);
});
it('clamps above-maximum values to MAX_TIME_SCALE', () => {
expect(clampTimeScale(1001)).toBe(MAX_TIME_SCALE);
expect(clampTimeScale(2000)).toBe(MAX_TIME_SCALE);
expect(clampTimeScale(Number.MAX_SAFE_INTEGER)).toBe(MAX_TIME_SCALE);
});
it('passes in-range values through unclamped — ladder and off-ladder alike', () => {
for (const s of [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000]) {
expect(clampTimeScale(s)).toBe(s); // the full v0.14.0 slider ladder
}
expect(clampTimeScale(37)).toBe(37); // off-ladder but in range (e.g. a legacy value)
});
it('keeps the endpoints exact', () => {
expect(clampTimeScale(MIN_TIME_SCALE)).toBe(MIN_TIME_SCALE);
expect(clampTimeScale(MAX_TIME_SCALE)).toBe(MAX_TIME_SCALE);
});
});
// Local helper mirroring lib/sim/movement.ts (kept private there on purpose — the
// engine composes arrivalTimeFor; tests just need the duration for fixtures).
function travelMs(km: number, speedKmh: number): number {
+3 -3
View File
@@ -22,12 +22,12 @@ import { arrivalTimeFor, fuelAt } from './movement';
// Clamp constant: max real-time gap counted by a single tick. Chosen at 2000 ms —
// comfortably above a normal client poll interval (~1 s), so active play advances
// ~real time × scale; small enough that one stale read after an absence moves game
// time by at most 2 s × scale (≈ 2 min even at max scale 64). The sim therefore
// time by at most 2 s × scale (≈ 33 min even at max scale 1000). The sim therefore
// only meaningfully progresses while actively polled.
export const MAX_TICK_ELAPSED_MS = 2_000;
export const MIN_TIME_SCALE = 1;
export const MAX_TIME_SCALE = 64; // top of the power-of-two ladder (v0.9.2)
export const MAX_TIME_SCALE = 1000; // top of the slider ladder (v0.14.0)
// Reputation gain per delivered package: BASE + PER_KM × great-circle km, rounded
// to 2 decimals (reputation is REAL). A short hop (~300 km) earns ~1.15 rep, a
@@ -264,7 +264,7 @@ export function runAction<T>(fn: (inst: GameDb) => Promise<T>): Promise<T> {
}
// Tick first so the returned state reflects current time, then apply the new
// controls. timeScale is clamped to [1, 64]; validation of raw input happens in
// controls. timeScale is clamped to [1, 1000]; validation of raw input happens in
// the route handler (400 on non-number / non-boolean).
export function applyTimeControls(input: SimControlsInput): Promise<schema.SimStateRow> {
return withLock(async () => {
+11 -10
View File
@@ -1,16 +1,16 @@
import { describe, expect, it } from 'vitest';
import { MAX_SCALE, MIN_SCALE, TIME_SCALES, scaleToSlider, sliderToScale } from './timeScale';
const STEPS = TIME_SCALES.length - 1; // 6 intervals across the 7 ladder positions
const STEPS = TIME_SCALES.length - 1; // 9 intervals across the 10 ladder positions (v0.14.0)
describe('sliderToScale', () => {
it('is exact at the endpoints (0 → 1×, 1 → 64×)', () => {
it('is exact at the endpoints (0 → 1×, 1 → 1000×)', () => {
expect(sliderToScale(0)).toBe(MIN_SCALE);
expect(sliderToScale(1)).toBe(MAX_SCALE);
});
it('maps each of the 7 positions to the power-of-two ladder', () => {
const expected = [1, 2, 4, 8, 16, 32, 64];
it('maps each of the 10 positions to the ladder', () => {
const expected = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000];
for (let i = 0; i < TIME_SCALES.length; i++) {
expect(sliderToScale(i / STEPS)).toBe(expected[i]);
}
@@ -39,9 +39,9 @@ describe('sliderToScale', () => {
});
describe('scaleToSlider', () => {
it('is exact at the endpoints (1× → 0, 64× → 1)', () => {
it('is exact at the endpoints (1× → 0, 1000× → 1)', () => {
expect(scaleToSlider(1)).toBe(0);
expect(scaleToSlider(64)).toBe(1);
expect(scaleToSlider(1000)).toBe(1);
});
it('places each ladder value on its own position', () => {
@@ -61,7 +61,7 @@ describe('scaleToSlider', () => {
it('clamps out-of-range and non-finite input', () => {
expect(scaleToSlider(0)).toBe(0);
expect(scaleToSlider(-3)).toBe(0);
expect(scaleToSlider(65)).toBe(1);
expect(scaleToSlider(1001)).toBe(1); // above the ladder top → clamped to 1000× → t=1
expect(scaleToSlider(NaN)).toBe(0);
});
});
@@ -73,8 +73,9 @@ describe('round-trip', () => {
}
});
it('maps off-ladder scales to the nearest power of two', () => {
expect(sliderToScale(scaleToSlider(3))).toBe(4); // log2(3) ≈ 1.58 → step 2 (4×)
expect(sliderToScale(scaleToSlider(60))).toBe(64); // legacy max from the v0.9.x era
it('maps off-ladder scales to the nearest ladder step by log distance', () => {
expect(sliderToScale(scaleToSlider(3))).toBe(2); // ln 3 ≈ 1.10 → closer to 2 (ln ≈ 0.69) than 5 (ln ≈ 1.61)
expect(sliderToScale(scaleToSlider(60))).toBe(50); // legacy max from the v0.9.x era sits between 50 and 100, nearer 50
expect(sliderToScale(scaleToSlider(200))).toBe(250); // ln 200 ≈ 5.30 → closer to 250 (ln ≈ 5.52) than 100 (ln ≈ 4.61)
});
});
+18 -9
View File
@@ -1,24 +1,33 @@
// Pure mapping helpers for the time-scale slider (v0.9.2) — no game logic, unit-testable
// in node. The slider has 7 discrete positions on a power-of-two ladder:
// 1× → 2× → 4× → 8× → 16× → 32× → 64×, so each step doubles the speed (matching
// POST /api/sim's clamp range [1, 64]).
// Pure mapping helpers for the time-scale slider (v0.9.2, values reworked in v0.14.0) — no
// game logic, unit-testable in node. The slider has 10 discrete positions on a mixed
// ×2/×2.5 ladder: 1× → 2× → 5× → 10× → 25× → 50× → 100× → 250× → 500× → 1000×, so each
// step roughly doubles the speed (matching POST /api/sim's clamp range [1, 1000]).
export const TIME_SCALES = [1, 2, 4, 8, 16, 32, 64] as const;
export const TIME_SCALES = [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000] as const;
export const MIN_SCALE: number = TIME_SCALES[0];
export const MAX_SCALE: number = TIME_SCALES[TIME_SCALES.length - 1];
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
// t → scale: the position maps to the nearest ladder step. Exact at the endpoints:
// sliderToScale(0) === 1, sliderToScale(1) === 64.
// sliderToScale(0) === 1, sliderToScale(1) === 1000.
export function sliderToScale(t: number): number {
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
return TIME_SCALES[clamp(Math.round(tt * (TIME_SCALES.length - 1)), 0, TIME_SCALES.length - 1)];
}
// scale → t: the nearest ladder position by log2 distance. Exact at the endpoints:
// scaleToSlider(1) === 0, scaleToSlider(64) === 1; round-trips every value in TIME_SCALES.
// scale → t: the nearest ladder position by log distance. Exact at the endpoints:
// scaleToSlider(1) === 0, scaleToSlider(1000) === 1; round-trips every value in TIME_SCALES.
export function scaleToSlider(scale: number): number {
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
return Math.log2(s) / Math.log2(MAX_SCALE);
let best = 0;
let bestDist = Infinity;
for (let i = 0; i < TIME_SCALES.length; i++) {
const d = Math.abs(Math.log(s) - Math.log(TIME_SCALES[i]));
if (d < bestDist) {
bestDist = d;
best = i;
}
}
return best / (TIME_SCALES.length - 1);
}
+12 -1
View File
@@ -21,7 +21,18 @@ export interface GameStateResult {
export async function fetchState(): Promise<StateSnapshot> {
const res = await fetch('/api/state', { cache: 'no-store' });
if (!res.ok) throw new Error(`GET /api/state → HTTP ${res.status}`);
return (await res.json()) as StateSnapshot;
const snapshot = (await res.json()) as StateSnapshot;
// Dev/e2e hook (v0.15.0): the last successfully polled snapshot, so tests can compare what
// the BROWSER received against a fresh node-side fetch. Client-only, harmless in prod.
if (typeof window !== 'undefined') {
(window as unknown as Record<string, unknown>).__flightLastSnapshot = {
planeIds: snapshot.planes.map((p) => p.id),
cash: snapshot.account.cash,
timeScale: snapshot.simState.timeScale,
at: Date.now(),
};
}
return snapshot;
}
// The shell's single polling source (v0.9.0): one GET /api/state loop for the whole page,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "flight-ops",
"version": "0.13.0",
"version": "0.15.1",
"private": true,
"scripts": {
"dev": "next dev -p 3000",