feat: v0.9.1 — left-pane time controls refined: log-scale slider (t→round(60^t), 250 ms debounced commit with release flush + in-flight queue) replaces the scale select; game clock now shows seconds (HH:MM:SS UTC)
This commit is contained in:
@@ -1,5 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## v0.9.1 — 2026-09-17 16:03
|
||||
- **Log-scale time slider** (left-pane UI refinement): the 1x–60x `<select>` in `components/LeftPane.tsx` is replaced by a single `<input type="range" data-testid="time-scale-slider">` — position t ∈ [0,1] maps to `scale = round(60^t)` (t=0→1×, mid≈8×, t=1→60×) so equal slider distances are equal multiplicative steps; 60 discrete positions (`step = 1/59`) keep keyboard arrows usable (~7% per step). The current value is shown beside the slider as "N×" (`data-testid="time-scale-value"`); pause/resume toggle unchanged
|
||||
- **Debounced commit**: dragging updates the displayed value optimistically; `POST /api/sim {timeScale}` fires after a 250 ms debounce and flushes immediately on release (native `change` event); a commit landing while another POST is in flight is held in a single slot and flushed right after, so rapid slider moves never drop the last intent — server's [1,60] clamp kept as backstop, no new dependencies
|
||||
- **Pure mapping helpers** in new `lib/timeScale.ts`: `sliderToScale(t)` / `scaleToSlider(scale)`, both clamped; exact at endpoints and round-tripping every integer 1..60
|
||||
- **Game clock shows seconds**: `formatSimClock` (in `lib/format.ts`) now renders the sim clock as `YYYY-MM-DD HH:MM:SS UTC` — same deterministic UTC wall-clock, seconds added
|
||||
- No backend changes: `POST /api/sim` signature and clamp unchanged; no OpenAPI change
|
||||
- Tests: unit — new `lib/timeScale.test.ts` (endpoint exactness 0→1/1→60, mid-slider ≈8×, monotonic non-decreasing over a 2000-step grid, full 1..60 coverage, clamping of out-of-range/non-finite input, round-trip for all integers 1..60) and `lib/format.test.ts` clock expectations updated to include seconds; e2e — `e2e/panes.spec.ts` time-controls test re-driven through the slider (keyboard End → max asserts label "60×" + `/api/state` timeScale=60, Home → min asserts "1×" + timeScale=1) and now also asserts the clock text matches `HH:MM:SS`; live instance restored to scale 1 + unpaused in-test and in `afterEach` as before
|
||||
- Verified: unit suite 150 → 159 green; `tsc --noEmit` clean; e2e re-run against the rebuilt compose instance
|
||||
|
||||
## v0.9.0 — 2026-09-17 14:24
|
||||
- **Single-screen 3-pane shell** (PLAN.md "Layout" increment): `app/page.tsx` is now a CSS grid (`grid-template-columns: 300px minmax(0, 1fr) 320px`) — left Assets pane, center = the existing `<Map/>` **untouched** (its `.map-wrap` fills the middle column, header included), right placeholder `data-testid="right-pane"` with a subtle "Jobs & Market" heading so the next increment has a home
|
||||
- **Single polling source**: new hook `lib/useGameState.ts` polls `GET /api/state` every 1000 ms (configurable arg) and returns `{state, loading, error, refresh}` — overlap guard skips a tick while the previous request is still in flight, interval cleaned up on unmount. Called ONCE in `app/page.tsx`; the snapshot flows down as props so later panes share one poll loop instead of running their own
|
||||
|
||||
+11
-6
@@ -218,20 +218,25 @@ body {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.time-controls button,
|
||||
.time-controls select {
|
||||
.time-controls button {
|
||||
font-size: 12px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.4);
|
||||
background: rgba(30, 41, 59, 0.9);
|
||||
color: #e2e8f0;
|
||||
}
|
||||
|
||||
.time-controls button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.time-controls select {
|
||||
.time-controls input[type='range'] {
|
||||
flex: 1;
|
||||
accent-color: #38bdf8;
|
||||
}
|
||||
|
||||
.time-scale-value {
|
||||
font-size: 12px;
|
||||
color: #e2e8f0;
|
||||
min-width: 34px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
+102
-33
@@ -1,9 +1,10 @@
|
||||
'use client';
|
||||
|
||||
import { useState, type ChangeEvent } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import type { ContractState, PlaneState, StateSnapshot } from '@/lib/game/state';
|
||||
import { PLANE_TYPES } from '@/lib/game/catalog';
|
||||
import { formatCash, formatFuel, formatSimClock } from '@/lib/format';
|
||||
import { scaleToSlider, sliderToScale } from '@/lib/timeScale';
|
||||
|
||||
interface LeftPaneProps {
|
||||
state: StateSnapshot | null;
|
||||
@@ -13,7 +14,10 @@ interface LeftPaneProps {
|
||||
onRefresh: () => void;
|
||||
}
|
||||
|
||||
const SCALE_OPTIONS = Array.from({ length: 60 }, (_, i) => i + 1); // 1x–60x, matching POST /api/sim's clamp range
|
||||
// Log-scale slider (v0.9.1): position t ∈ [0,1] → scale = round(60^t), so equal distances
|
||||
// are equal multiplicative steps. 60 discrete positions keep keyboard arrows usable (~7% per step).
|
||||
const SCALE_SLIDER_STEP = 1 / 59;
|
||||
const SCALE_COMMIT_DEBOUNCE_MS = 250;
|
||||
|
||||
function planeLocation(p: PlaneState, contracts: ContractState[]): string {
|
||||
if (p.status === 'flying' && p.contractId) {
|
||||
@@ -28,29 +32,95 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
||||
|
||||
// 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.
|
||||
const applySimControls = async (body: { timeScale?: number; paused?: boolean }) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch('/api/sim', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
|
||||
onRefresh();
|
||||
} catch (err) {
|
||||
console.error('failed to apply sim controls', err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
// 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 and flushed right after, so the last
|
||||
// user intent always reaches the server (the server's [1,60] clamp stays as backstop).
|
||||
const queuedRef = useRef<{ timeScale?: number; paused?: boolean } | null>(null);
|
||||
|
||||
const applySimControls = useCallback(
|
||||
async (body: { timeScale?: number; paused?: boolean }) => {
|
||||
if (busy) {
|
||||
queuedRef.current = body;
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch('/api/sim', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!res.ok) throw new Error(`POST /api/sim → HTTP ${res.status}`);
|
||||
onRefresh();
|
||||
} catch (err) {
|
||||
console.error('failed to apply sim controls', err);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
const queued = queuedRef.current;
|
||||
if (queued !== null) {
|
||||
queuedRef.current = null;
|
||||
void applySimControls(queued);
|
||||
}
|
||||
}
|
||||
},
|
||||
[busy, onRefresh],
|
||||
);
|
||||
|
||||
const paused = state?.simState.paused ?? false;
|
||||
const timeScale = state?.simState.timeScale ?? 1;
|
||||
|
||||
// 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,60] 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);
|
||||
|
||||
const setPending = useCallback((s: number | null) => {
|
||||
pendingRef.current = s;
|
||||
setPendingScaleState(s);
|
||||
}, []);
|
||||
|
||||
const commitNow = useCallback(() => {
|
||||
if (commitTimerRef.current !== null) {
|
||||
clearTimeout(commitTimerRef.current);
|
||||
commitTimerRef.current = null;
|
||||
}
|
||||
const s = pendingRef.current;
|
||||
if (s === null) return;
|
||||
setPending(null);
|
||||
void applySimControls({ timeScale: s });
|
||||
}, [applySimControls, setPending]);
|
||||
|
||||
const onSliderInput = useCallback(
|
||||
(e: ChangeEvent<HTMLInputElement>) => {
|
||||
setPending(sliderToScale(Number(e.target.value)));
|
||||
if (commitTimerRef.current !== null) clearTimeout(commitTimerRef.current);
|
||||
commitTimerRef.current = setTimeout(commitNow, SCALE_COMMIT_DEBOUNCE_MS);
|
||||
},
|
||||
[commitNow, setPending],
|
||||
);
|
||||
|
||||
const sliderRef = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
const el = sliderRef.current;
|
||||
if (!el) return;
|
||||
el.addEventListener('change', commitNow); // flush on pointer-up / keyboard release
|
||||
return () => el.removeEventListener('change', commitNow);
|
||||
}, [commitNow]);
|
||||
|
||||
// Drop any pending debounce timer on unmount.
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (commitTimerRef.current !== null) clearTimeout(commitTimerRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const displayedScale = pendingScale ?? timeScale;
|
||||
|
||||
return (
|
||||
<aside data-testid="left-pane" className="pane left-pane">
|
||||
<h2 className="pane-title">Assets</h2>
|
||||
@@ -109,19 +179,18 @@ export default function LeftPane({ state, loading, error, onRefresh }: LeftPaneP
|
||||
>
|
||||
{paused ? 'Resume' : 'Pause'}
|
||||
</button>
|
||||
<select
|
||||
data-testid="time-scale-select"
|
||||
<input
|
||||
ref={sliderRef}
|
||||
type="range"
|
||||
data-testid="time-scale-slider"
|
||||
aria-label="Time scale"
|
||||
value={String(timeScale)}
|
||||
disabled={busy}
|
||||
onChange={(e: ChangeEvent<HTMLSelectElement>) => void applySimControls({ timeScale: Number(e.target.value) })}
|
||||
>
|
||||
{SCALE_OPTIONS.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}x
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
min={0}
|
||||
max={1}
|
||||
step={SCALE_SLIDER_STEP}
|
||||
value={scaleToSlider(displayedScale)}
|
||||
onChange={onSliderInput}
|
||||
/>
|
||||
<span data-testid="time-scale-value">{displayedScale}×</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
+15
-5
@@ -54,7 +54,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 scale selector sets timeScale=60', async ({ page }) => {
|
||||
test('time controls: pause freezes the sim and the log-scale slider sets timeScale', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
const pauseBtn = page.getByTestId('pause-toggle');
|
||||
await expect(pauseBtn).toBeVisible({ timeout: 15_000 });
|
||||
@@ -65,11 +65,21 @@ test('time controls: pause freezes the sim and the scale selector sets timeScale
|
||||
// …and in the pane itself (the refetch after POST flips the button to Resume).
|
||||
await expect(pauseBtn).toHaveText('Resume');
|
||||
|
||||
// Scale via the UI select.
|
||||
const scaleSelect = page.getByTestId('time-scale-select');
|
||||
await scaleSelect.selectOption('60');
|
||||
// Scale via the log-scale slider. End jumps to max (t=1 → 60×): 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('60×', { timeout: 10_000 });
|
||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(60);
|
||||
await expect(scaleSelect).toHaveValue('60');
|
||||
|
||||
// Home jumps to min (t=0 → 1×).
|
||||
await page.keyboard.press('Home');
|
||||
await expect(page.getByTestId('time-scale-value')).toHaveText('1×', { timeout: 10_000 });
|
||||
await expect.poll(async () => (await getState(page)).simState.timeScale, { timeout: 10_000 }).toBe(1);
|
||||
|
||||
// Game clock shows seconds: YYYY-MM-DD HH:MM:SS UTC.
|
||||
await expect(page.getByTestId('sim-clock')).toContainText(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC/);
|
||||
|
||||
// Restore the live instance to scale 1 + unpaused (afterEach enforces this too).
|
||||
const restore = await page.request.post('/api/sim', { data: { timeScale: 1, paused: false } });
|
||||
|
||||
+4
-3
@@ -22,8 +22,9 @@ describe('formatFuel', () => {
|
||||
});
|
||||
|
||||
describe('formatSimClock', () => {
|
||||
it('formats epoch ms as a UTC wall-clock string (deterministic across timezones)', () => {
|
||||
expect(formatSimClock(Date.UTC(2026, 8, 17, 14, 5))).toBe('2026-09-17 14:05 UTC');
|
||||
expect(formatSimClock(Date.UTC(2026, 0, 1, 0, 0))).toBe('2026-01-01 00:00 UTC');
|
||||
it('formats epoch ms as a UTC wall-clock string with seconds (deterministic across timezones)', () => {
|
||||
expect(formatSimClock(Date.UTC(2026, 8, 17, 14, 5))).toBe('2026-09-17 14:05:00 UTC');
|
||||
expect(formatSimClock(Date.UTC(2026, 0, 1, 0, 0))).toBe('2026-01-01 00:00:00 UTC');
|
||||
expect(formatSimClock(Date.UTC(2026, 8, 17, 14, 5, 9))).toBe('2026-09-17 14:05:09 UTC');
|
||||
});
|
||||
});
|
||||
|
||||
+3
-3
@@ -11,10 +11,10 @@ export function formatFuel(fuel: number, maxFuel: number): string {
|
||||
return `${Math.round(fuel)} / ${maxFuel} L`;
|
||||
}
|
||||
|
||||
// The sim clock is epoch ms (seeded from real time) — shown as a UTC wall-clock so the
|
||||
// display is deterministic regardless of the viewer's timezone.
|
||||
// The sim clock is epoch ms (seeded from real time) — shown as a UTC wall-clock with
|
||||
// seconds so the display is deterministic regardless of the viewer's timezone.
|
||||
export function formatSimClock(clockMs: number): string {
|
||||
const d = new Date(clockMs);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`;
|
||||
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { MAX_SCALE, MIN_SCALE, scaleToSlider, sliderToScale } from './timeScale';
|
||||
|
||||
describe('sliderToScale', () => {
|
||||
it('is exact at the endpoints (0 → 1×, 1 → 60×)', () => {
|
||||
expect(sliderToScale(0)).toBe(MIN_SCALE);
|
||||
expect(sliderToScale(1)).toBe(MAX_SCALE);
|
||||
});
|
||||
|
||||
it('maps mid-slider to ~8× (√60 rounds to 8)', () => {
|
||||
expect(sliderToScale(0.5)).toBe(8);
|
||||
});
|
||||
|
||||
it('is monotonic non-decreasing across the whole range', () => {
|
||||
let prev = sliderToScale(0);
|
||||
for (let i = 1; i <= 2000; i++) {
|
||||
const t = i / 2000;
|
||||
const s = sliderToScale(t);
|
||||
expect(s).toBeGreaterThanOrEqual(prev);
|
||||
prev = s;
|
||||
}
|
||||
});
|
||||
|
||||
it('covers every integer scale 1..60 somewhere on the slider', () => {
|
||||
const seen = new Set<number>();
|
||||
for (let i = 0; i <= 2000; i++) seen.add(sliderToScale(i / 2000));
|
||||
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) expect(seen.has(s)).toBe(true);
|
||||
});
|
||||
|
||||
it('clamps out-of-range and non-finite input', () => {
|
||||
expect(sliderToScale(-0.5)).toBe(MIN_SCALE);
|
||||
expect(sliderToScale(1.5)).toBe(MAX_SCALE);
|
||||
expect(sliderToScale(NaN)).toBe(MIN_SCALE);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scaleToSlider', () => {
|
||||
it('is exact at the endpoints (1× → 0, 60× → 1)', () => {
|
||||
expect(scaleToSlider(1)).toBe(0);
|
||||
expect(scaleToSlider(60)).toBe(1);
|
||||
});
|
||||
|
||||
it('stays within [0, 1] for in-range scales', () => {
|
||||
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) {
|
||||
const t = scaleToSlider(s);
|
||||
expect(t).toBeGreaterThanOrEqual(0);
|
||||
expect(t).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('clamps out-of-range and non-finite input', () => {
|
||||
expect(scaleToSlider(0)).toBe(0);
|
||||
expect(scaleToSlider(-3)).toBe(0);
|
||||
expect(scaleToSlider(61)).toBe(1);
|
||||
expect(scaleToSlider(NaN)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('round-trip', () => {
|
||||
it('sliderToScale(scaleToSlider(s)) === s for every integer scale 1..60', () => {
|
||||
for (let s = MIN_SCALE; s <= MAX_SCALE; s++) {
|
||||
expect(sliderToScale(scaleToSlider(s))).toBe(s);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
// Pure log-scale mapping helpers for the time-scale slider (v0.9.1) — no game logic,
|
||||
// unit-testable in node. Slider position t ∈ [0,1] ↔ scale = round(60^t), so equal
|
||||
// distances on the slider correspond to equal multiplicative steps: 1× at t=0, ~8×
|
||||
// mid-slider, 60× at t=1 (matching POST /api/sim's clamp range).
|
||||
|
||||
export const MIN_SCALE = 1;
|
||||
export const MAX_SCALE = 60;
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
// t → scale. Exact at the endpoints: sliderToScale(0) === 1, sliderToScale(1) === 60.
|
||||
export function sliderToScale(t: number): number {
|
||||
const tt = clamp(Number.isFinite(t) ? t : 0, 0, 1);
|
||||
return Math.round(clamp(Math.pow(MAX_SCALE, tt), MIN_SCALE, MAX_SCALE));
|
||||
}
|
||||
|
||||
// scale → t (inverse of the pre-rounding mapping). Exact at the endpoints:
|
||||
// scaleToSlider(1) === 0, scaleToSlider(60) === 1. Round-trips every integer 1..60.
|
||||
export function scaleToSlider(scale: number): number {
|
||||
const s = clamp(Number.isFinite(scale) ? scale : MIN_SCALE, MIN_SCALE, MAX_SCALE);
|
||||
return Math.log(s) / Math.log(MAX_SCALE);
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "flight-ops",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3000",
|
||||
|
||||
Reference in New Issue
Block a user