mirror of
https://github.com/AmanTahiliani/box-box.git
synced 2026-08-07 11:54:59 -04:00
Compare commits
11 Commits
feat/issue
...
480e6ca860
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
480e6ca860 | ||
|
|
81deed4c75 | ||
|
|
d6d0558c72 | ||
|
|
b884ba8885 | ||
|
|
56ea860101 | ||
|
|
7c7886e6c6 | ||
|
|
71f81924ee | ||
|
|
7b86698b22 | ||
|
|
e88e0885ec | ||
|
|
255b296ecc | ||
|
|
888378e210 |
@@ -15,6 +15,7 @@ import type {
|
||||
Session,
|
||||
TrackOutline,
|
||||
Weekend,
|
||||
WeekendContext,
|
||||
} from './types'
|
||||
|
||||
export async function fetchRaceHub(sessionKey: number): Promise<RaceHub> {
|
||||
@@ -114,6 +115,14 @@ export async function fetchWeekend(meetingKey: number): Promise<Weekend> {
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchWeekendContext(): Promise<WeekendContext> {
|
||||
const res = await fetch('/api/v1/weekend-context')
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchChampionshipHub(year?: number): Promise<ChampionshipHub> {
|
||||
const params = new URLSearchParams({ source: 'auto' })
|
||||
if (year) params.set('year', year.toString())
|
||||
|
||||
@@ -47,7 +47,7 @@ export function WeekendSwitcher({ currentMeetingKey, currentSessionKey, onClose
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rh-switcher" data-testid="rh-switcher">
|
||||
<div id="rh-weekend-switcher" className="rh-switcher" data-testid="rh-switcher">
|
||||
<div className="rh-switcher-head">
|
||||
<span className="sec-title">Switch Weekend</span>
|
||||
<div className="rh-switcher-years">
|
||||
|
||||
@@ -53,9 +53,8 @@ function StintSparkline({ seconds }: { seconds: number[] }) {
|
||||
|
||||
export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
const isRace = isRaceSession(sessionType)
|
||||
// In practice/qualifying deg trends are secondary — collapse by default so
|
||||
// the Timing Tower stays above the fold. Races keep it open.
|
||||
const [collapsed, setCollapsed] = useState(!isRace)
|
||||
const [collapsed, setCollapsed] = useState(true)
|
||||
const [readerChose, setReaderChose] = useState(false)
|
||||
const [stints, setStints] = useState<StintHistoryMap>({})
|
||||
|
||||
// One lap-history update per received snapshot (rows is rebuilt per snapshot).
|
||||
@@ -75,6 +74,30 @@ export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
[rows, pinned],
|
||||
)
|
||||
|
||||
// One linear fit per driver per snapshot, shared by the readiness check and
|
||||
// the rows below. degradationModel is O(laps) and this runs at feed rate.
|
||||
const models = useMemo(() => {
|
||||
const out: Record<string, ReturnType<typeof degradationModel>> = {}
|
||||
for (const row of visible) {
|
||||
out[row.RacingNumber] = degradationModel(stints[row.RacingNumber]?.samples ?? [])
|
||||
}
|
||||
return out
|
||||
}, [visible, stints])
|
||||
|
||||
// Before any stint has enough clean laps to fit, every row reads "warming
|
||||
// up" — a full-height panel of placeholders that pushed the Timing Tower off
|
||||
// the fold for the first third of a race. Stay collapsed until there is
|
||||
// something to say, then open. A reader who has toggled it keeps their choice.
|
||||
const hasSignal = useMemo(
|
||||
() => visible.some((row) => models[row.RacingNumber] != null),
|
||||
[visible, models],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (readerChose) return
|
||||
setCollapsed(!(isRace && hasSignal))
|
||||
}, [isRace, hasSignal, readerChose])
|
||||
|
||||
if (visible.length === 0) return null
|
||||
|
||||
return (
|
||||
@@ -82,18 +105,25 @@ export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
<button
|
||||
type="button"
|
||||
className="sec-header tyredeg-toggle"
|
||||
onClick={() => setCollapsed((prev) => !prev)}
|
||||
onClick={() => {
|
||||
setReaderChose(true)
|
||||
setCollapsed((prev) => !prev)
|
||||
}}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
<span className="sec-title">Tyre Deg & Pit Window</span>
|
||||
{isRace && <span className="sec-meta">rejoin assumes ~{PIT_LOSS_SECONDS}s pit loss</span>}
|
||||
{!hasSignal ? (
|
||||
<span className="sec-meta">collecting clean laps</span>
|
||||
) : (
|
||||
isRace && <span className="sec-meta">rejoin assumes ~{PIT_LOSS_SECONDS}s pit loss</span>
|
||||
)}
|
||||
<span className="tyredeg-chevron" aria-hidden="true">{collapsed ? '▸' : '▾'}</span>
|
||||
</button>
|
||||
|
||||
{!collapsed && (
|
||||
<div className="tyredeg-rows">
|
||||
{visible.map((row) => {
|
||||
const model = degradationModel(stints[row.RacingNumber]?.samples ?? [])
|
||||
const model = models[row.RacingNumber]
|
||||
const rejoin = isRace ? estimatePitRejoin(rows, row.RacingNumber) : null
|
||||
const ageAnnotation = tyreAgeMeaning(row.Tyre?.Compound, row.Tyre?.Age)
|
||||
return (
|
||||
|
||||
@@ -145,6 +145,15 @@ export function formatSessionScheduleTime(value: string): string {
|
||||
})
|
||||
}
|
||||
|
||||
export const MAX_BROWSER_TIMEOUT = 2_147_483_647
|
||||
|
||||
export function refreshDeadlineDelay(refreshAt: string | undefined, now = Date.now()): number | null {
|
||||
if (!refreshAt) return null
|
||||
const deadline = Date.parse(refreshAt)
|
||||
if (Number.isNaN(deadline)) return null
|
||||
return Math.min(Math.max(0, deadline - now), MAX_BROWSER_TIMEOUT)
|
||||
}
|
||||
|
||||
export type FocusMeetingKind = 'current' | 'next' | 'recent' | 'fallback'
|
||||
|
||||
export function focusMeetingKind(meeting: Meeting, now: Date): FocusMeetingKind {
|
||||
|
||||
@@ -289,14 +289,16 @@ export function LiveTimingPage() {
|
||||
session={snapshot.Session}
|
||||
/>
|
||||
</div>
|
||||
{/* Rail runs most-synthesized to most-raw: a reader arriving
|
||||
mid-session wants "what did I miss" before the regulatory log. */}
|
||||
<div className="live-rc-col">
|
||||
<EventRail events={events} driverInfo={snapshot.DriverInfo} />
|
||||
<TeamRadioTicker
|
||||
captures={snapshot.TeamRadio ?? []}
|
||||
driverInfo={snapshot.DriverInfo}
|
||||
session={snapshot.Session}
|
||||
/>
|
||||
<RaceControlFeed messages={snapshot.RCMessages ?? []} driverInfo={snapshot.DriverInfo} />
|
||||
<EventRail events={events} driverInfo={snapshot.DriverInfo} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import {
|
||||
fetchLocalMeetings,
|
||||
fetchRaceHub,
|
||||
fetchSeasons,
|
||||
fetchWeekend,
|
||||
} from '../api'
|
||||
import { fetchRaceHub, fetchWeekend, fetchWeekendContext } from '../api'
|
||||
import { DatasetStrip } from '../components/DatasetStrip'
|
||||
import { RaceStoryCanvas } from '../components/RaceStoryCanvas'
|
||||
import { TabBar, type Tab } from '../components/TabBar'
|
||||
@@ -22,76 +17,72 @@ import { SourceBadge } from '../components/SourceBadge'
|
||||
import { countryAccent, countryDecal, formatGpDateRange } from '../lib/gpIdentity'
|
||||
import { formatCoverageHint, sessionTypeAbbrev } from '../lib/coverage'
|
||||
import {
|
||||
MAX_BROWSER_TIMEOUT,
|
||||
formatCountdown,
|
||||
formatSessionScheduleTime,
|
||||
pickFocusMeeting,
|
||||
refreshDeadlineDelay,
|
||||
sortSessionsByStart,
|
||||
} from '../lib/schedule'
|
||||
import type { Weekend, WeekendSession } from '../types'
|
||||
import type { ContextSession, Weekend } from '../types'
|
||||
|
||||
interface Props {
|
||||
sessionKey: number
|
||||
}
|
||||
|
||||
function pickAnalysisSession(weekend: Weekend | undefined): WeekendSession | undefined {
|
||||
if (!weekend) return undefined
|
||||
const local = weekend.sessions.filter((s) => s.source === 'local')
|
||||
const partial = weekend.sessions.filter((s) => s.source === 'partial')
|
||||
const pool = local.length > 0 ? local : partial.length > 0 ? partial : weekend.sessions
|
||||
const race = pool.find((s) => s.session.session_type?.toLowerCase().includes('race'))
|
||||
if (race) return race
|
||||
const qual = pool.find((s) => s.session.session_type?.toLowerCase().includes('qualifying'))
|
||||
if (qual) return qual
|
||||
return pool[0]
|
||||
}
|
||||
|
||||
export function RaceHubPage({ sessionKey }: Props) {
|
||||
const navigate = useNavigate()
|
||||
const [activeTab, setActiveTab] = useState<Tab>('overview')
|
||||
const [switcherOpen, setSwitcherOpen] = useState(false)
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
const [refreshGeneration, setRefreshGeneration] = useState(0)
|
||||
|
||||
// ─── Auto-redirect when no session_key is supplied ───
|
||||
const seasonsQuery = useQuery({
|
||||
queryKey: ['seasons'],
|
||||
queryFn: fetchSeasons,
|
||||
// The server owns bare Race Hub selection so every open tab crosses the
|
||||
// one-hour handoff at the same instant.
|
||||
const contextQuery = useQuery({
|
||||
queryKey: ['weekend-context'],
|
||||
queryFn: fetchWeekendContext,
|
||||
enabled: sessionKey === 0,
|
||||
})
|
||||
const { refetch: refetchContext } = contextQuery
|
||||
|
||||
const latestSeason = seasonsQuery.data?.[0] ?? null
|
||||
|
||||
const meetingsQuery = useQuery({
|
||||
queryKey: ['meetings', latestSeason],
|
||||
queryFn: () => fetchLocalMeetings(latestSeason!),
|
||||
enabled: sessionKey === 0 && latestSeason != null,
|
||||
})
|
||||
|
||||
const focusMeeting = useMemo(() => {
|
||||
if (sessionKey !== 0 || !meetingsQuery.data) return null
|
||||
return pickFocusMeeting(meetingsQuery.data, new Date())
|
||||
}, [sessionKey, meetingsQuery.data])
|
||||
|
||||
const fallbackWeekendQuery = useQuery({
|
||||
queryKey: ['weekend', focusMeeting?.meeting_key],
|
||||
queryFn: () => fetchWeekend(focusMeeting!.meeting_key),
|
||||
enabled: sessionKey === 0 && focusMeeting != null,
|
||||
const context = contextQuery.data
|
||||
const preSession = sessionKey === 0 && context?.race_hub_pre_session === true
|
||||
const preSessionRef = context?.race_hub_default_session
|
||||
const preSessionMeetingKey = preSessionRef?.meeting?.meeting_key
|
||||
const preSessionWeekendQuery = useQuery({
|
||||
queryKey: ['weekend', preSessionMeetingKey],
|
||||
queryFn: () => fetchWeekend(preSessionMeetingKey!),
|
||||
enabled: preSession && preSessionMeetingKey != null && preSessionMeetingKey > 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (sessionKey !== 0) return
|
||||
const weekend = fallbackWeekendQuery.data
|
||||
if (!weekend) return
|
||||
const target = pickAnalysisSession(weekend)?.session.session_key
|
||||
?? weekend.default_session_key
|
||||
?? weekend.sessions[0]?.session.session_key
|
||||
if (target) {
|
||||
navigate({ to: '/race-hub', search: { session_key: target }, replace: true })
|
||||
}
|
||||
}, [sessionKey, fallbackWeekendQuery.data, navigate])
|
||||
const delay = refreshDeadlineDelay(context?.race_hub_refresh_at)
|
||||
if (delay == null) return
|
||||
const rearmAfterRefetch = delay === MAX_BROWSER_TIMEOUT
|
||||
const timer = window.setTimeout(() => {
|
||||
void refetchContext().finally(() => {
|
||||
if (rearmAfterRefetch) setRefreshGeneration((generation) => generation + 1)
|
||||
})
|
||||
}, delay)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [sessionKey, context?.race_hub_refresh_at, refetchContext, refreshGeneration])
|
||||
|
||||
useEffect(() => {
|
||||
if (!preSession) return
|
||||
const timer = window.setInterval(() => setNow(Date.now()), 1_000)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [preSession])
|
||||
|
||||
// A bare route retains canonical context ownership while rendering its
|
||||
// completed analysis selection. Explicit URLs remain user-owned.
|
||||
const selectedSessionKey = sessionKey || context?.race_hub_default_session?.session.session_key || 0
|
||||
|
||||
// ─── Active session payload ───
|
||||
const raceHubQuery = useQuery({
|
||||
queryKey: ['race-hub', sessionKey],
|
||||
queryFn: () => fetchRaceHub(sessionKey),
|
||||
enabled: sessionKey > 0,
|
||||
queryKey: ['race-hub', selectedSessionKey],
|
||||
queryFn: () => fetchRaceHub(selectedSessionKey),
|
||||
enabled: selectedSessionKey > 0 && (sessionKey > 0 || !preSession),
|
||||
staleTime: 30_000,
|
||||
})
|
||||
|
||||
@@ -108,25 +99,36 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
const accent = countryAccent(data?.meeting ?? null)
|
||||
const accentStyle = { '--gp-accent': accent } as React.CSSProperties
|
||||
|
||||
// ─── No session_key: show resolving state, fall back to switcher if no local data ───
|
||||
// ─── No session_key: resolve exclusively through canonical Weekend Context ───
|
||||
if (sessionKey === 0) {
|
||||
if (seasonsQuery.isLoading || meetingsQuery.isLoading || fallbackWeekendQuery.isLoading) {
|
||||
if (contextQuery.isLoading || (preSession && preSessionWeekendQuery.isLoading)) {
|
||||
return (
|
||||
<div className="rh-page" style={accentStyle}>
|
||||
<div className="loading-state">resolving latest local weekend…</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const seasons = seasonsQuery.data ?? []
|
||||
if (seasons.length === 0) {
|
||||
if (preSession && preSessionRef) {
|
||||
return (
|
||||
<RaceHubPreSession
|
||||
session={preSessionRef}
|
||||
weekend={preSessionWeekendQuery.data}
|
||||
now={now}
|
||||
switcherOpen={switcherOpen}
|
||||
onToggleSwitcher={() => setSwitcherOpen((open) => !open)}
|
||||
onCloseSwitcher={() => setSwitcherOpen(false)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
if (!selectedSessionKey) {
|
||||
return (
|
||||
<div className="rh-page rh-empty" data-testid="race-hub-empty" style={accentStyle}>
|
||||
<div className="rh-empty-band">
|
||||
<span className="rh-empty-eyebrow mono">box-box · race hub</span>
|
||||
<h1 className="rh-empty-title">No local sessions yet</h1>
|
||||
<h1 className="rh-empty-title">No completed local analysis yet</h1>
|
||||
<p className="rh-empty-sub">
|
||||
The Race Hub reads from local ingest only. Once a weekend is ingested
|
||||
it will open here automatically.
|
||||
Race Hub opens completed local analysis between weekends. Check Data Health
|
||||
to ingest a completed session.
|
||||
</p>
|
||||
<div className="rh-empty-actions">
|
||||
<a href="/admin" className="rh-empty-action">Open Admin · Data Health</a>
|
||||
@@ -136,18 +138,13 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="rh-page" style={accentStyle}>
|
||||
<div className="loading-state">resolving latest local weekend…</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Loading / error for the requested session_key ───
|
||||
// ─── Loading / error for the selected session ───
|
||||
if (raceHubQuery.isLoading) {
|
||||
return (
|
||||
<div className="rh-page" style={accentStyle}>
|
||||
<div className="loading-state">loading session {sessionKey}…</div>
|
||||
<div className="loading-state">loading session {selectedSessionKey}…</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -157,7 +154,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
<div className="error-box">
|
||||
{raceHubQuery.error instanceof Error
|
||||
? raceHubQuery.error.message
|
||||
: `Failed to load session ${sessionKey}.`}
|
||||
: `Failed to load session ${selectedSessionKey}.`}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -168,7 +165,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
const sessionMeta = weekend
|
||||
? Object.fromEntries(weekend.sessions.map((w) => [w.session.session_key, w]))
|
||||
: {}
|
||||
const activeSessionMeta = sessionMeta[sessionKey]
|
||||
const activeSessionMeta = sessionMeta[selectedSessionKey]
|
||||
|
||||
return (
|
||||
<div className="rh-page" data-testid="race-hub" style={accentStyle}>
|
||||
@@ -194,7 +191,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
{switcherOpen && (
|
||||
<WeekendSwitcher
|
||||
currentMeetingKey={meetingKey}
|
||||
currentSessionKey={sessionKey}
|
||||
currentSessionKey={selectedSessionKey}
|
||||
onClose={() => setSwitcherOpen(false)}
|
||||
/>
|
||||
)}
|
||||
@@ -225,7 +222,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
<nav className="rh-session-rail" aria-label="Weekend sessions" data-testid="rh-session-rail">
|
||||
{sessions.map((session) => {
|
||||
const meta = sessionMeta[session.session_key]
|
||||
const active = session.session_key === sessionKey
|
||||
const active = session.session_key === selectedSessionKey
|
||||
return (
|
||||
<button
|
||||
key={session.session_key}
|
||||
@@ -278,7 +275,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
{formatCoverageHint(activeSessionMeta.datasets)} datasets local
|
||||
</span>
|
||||
)}
|
||||
<span className="rh-active-key mono">key {sessionKey}</span>
|
||||
<span className="rh-active-key mono">key {selectedSessionKey}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -314,7 +311,7 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
<span className="sec-title">Driver Compare</span>
|
||||
</div>
|
||||
<CompareView
|
||||
sessionKey={sessionKey}
|
||||
sessionKey={selectedSessionKey}
|
||||
results={data.results}
|
||||
drivers={data.drivers}
|
||||
/>
|
||||
@@ -368,3 +365,72 @@ export function RaceHubPage({ sessionKey }: Props) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RaceHubPreSession({
|
||||
session,
|
||||
weekend,
|
||||
now,
|
||||
switcherOpen,
|
||||
onToggleSwitcher,
|
||||
onCloseSwitcher,
|
||||
}: {
|
||||
session: ContextSession
|
||||
weekend?: Weekend
|
||||
now: number
|
||||
switcherOpen: boolean
|
||||
onToggleSwitcher: () => void
|
||||
onCloseSwitcher: () => void
|
||||
}) {
|
||||
const meeting = session.meeting
|
||||
const sessions = sortSessionsByStart((weekend?.sessions ?? []).map((entry) => entry.session))
|
||||
const target = new Date(session.session.date_start)
|
||||
const accent = countryAccent(meeting ?? null)
|
||||
const pendingLiveEvidence = target.getTime() <= now
|
||||
|
||||
return (
|
||||
<div className="rh-page rh-empty" data-testid="race-hub-pre-session" style={{ '--gp-accent': accent } as React.CSSProperties}>
|
||||
<div className="rh-topbar">
|
||||
<span className="rh-topbar-label mono">box-box · race hub</span>
|
||||
<span className="rh-topbar-spacer" />
|
||||
<button
|
||||
type="button"
|
||||
className={`rh-switcher-toggle${switcherOpen ? ' active' : ''}`}
|
||||
onClick={onToggleSwitcher}
|
||||
aria-expanded={switcherOpen}
|
||||
aria-controls="rh-weekend-switcher"
|
||||
data-testid="rh-switch-weekend"
|
||||
>
|
||||
{switcherOpen ? 'Close' : 'Switch Weekend'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{switcherOpen && (
|
||||
<WeekendSwitcher
|
||||
currentMeetingKey={meeting?.meeting_key}
|
||||
currentSessionKey={session.session.session_key}
|
||||
onClose={onCloseSwitcher}
|
||||
/>
|
||||
)}
|
||||
|
||||
<section className="rh-empty-band">
|
||||
<span className="rh-empty-eyebrow mono">box-box · race hub</span>
|
||||
<h1 className="rh-empty-title">{meeting?.meeting_name ?? 'Next race weekend'}</h1>
|
||||
<p className="rh-empty-sub">
|
||||
{pendingLiveEvidence
|
||||
? `${session.session.session_name} is scheduled; awaiting live timing.`
|
||||
: <>{session.session.session_name} begins in <span className="mono">{formatCountdown(target, new Date(now))}</span></>}
|
||||
</p>
|
||||
{sessions.length > 0 && (
|
||||
<div className="preview-schedule" data-testid="rh-pre-session-schedule">
|
||||
{sessions.map((scheduled) => (
|
||||
<div key={scheduled.session_key} className="preview-schedule-item">
|
||||
<span className="preview-schedule-name">{scheduled.session_name}</span>
|
||||
<span className="preview-schedule-time">{formatSessionScheduleTime(scheduled.date_start)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,16 @@ a { color: inherit; text-decoration: none; }
|
||||
}
|
||||
.app-nav::-webkit-scrollbar { display: none; }
|
||||
|
||||
/* The nav scrolls horizontally with its scrollbar hidden. Below the width
|
||||
where the links stop fitting, fade the trailing edge so the cut-off item
|
||||
reads as "scroll for more" instead of as a clipping bug. */
|
||||
@media (max-width: 560px) {
|
||||
.app-nav {
|
||||
-webkit-mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent 100%);
|
||||
mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent 100%);
|
||||
}
|
||||
}
|
||||
|
||||
.nav-logo {
|
||||
font-family: var(--f-mono);
|
||||
font-size: 15px;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import {
|
||||
Outlet,
|
||||
@@ -9,21 +9,24 @@ import {
|
||||
createRoute,
|
||||
} from '@tanstack/react-router'
|
||||
import { RaceHubPage } from '../pages/RaceHubPage'
|
||||
import type { DatasetInfo, Meeting, RaceHub, Session, Weekend } from '../types'
|
||||
import { MAX_BROWSER_TIMEOUT } from '../lib/schedule'
|
||||
import type { ContextAvailability, DatasetInfo, Meeting, RaceHub, Session, Weekend, WeekendContext } from '../types'
|
||||
|
||||
vi.mock('../api', () => ({
|
||||
fetchRaceHub: vi.fn(),
|
||||
fetchSeasons: vi.fn(),
|
||||
fetchLocalMeetings: vi.fn(),
|
||||
fetchWeekend: vi.fn(),
|
||||
fetchWeekendContext: vi.fn(),
|
||||
}))
|
||||
|
||||
import { fetchRaceHub, fetchSeasons, fetchLocalMeetings, fetchWeekend } from '../api'
|
||||
import { fetchLocalMeetings, fetchRaceHub, fetchSeasons, fetchWeekend, fetchWeekendContext } from '../api'
|
||||
|
||||
const mockFetchRaceHub = vi.mocked(fetchRaceHub)
|
||||
const mockFetchSeasons = vi.mocked(fetchSeasons)
|
||||
const mockFetchLocalMeetings = vi.mocked(fetchLocalMeetings)
|
||||
const mockFetchWeekend = vi.mocked(fetchWeekend)
|
||||
const mockFetchWeekendContext = vi.mocked(fetchWeekendContext)
|
||||
|
||||
const meeting: Meeting = {
|
||||
meeting_key: 1229,
|
||||
@@ -169,6 +172,26 @@ const weekend: Weekend = {
|
||||
],
|
||||
}
|
||||
|
||||
const availability: ContextAvailability = {
|
||||
source: 'local',
|
||||
schedule: 'available',
|
||||
live_transport: 'unknown',
|
||||
live_session: 'inactive',
|
||||
archive: 'unavailable',
|
||||
local_analysis: 'complete',
|
||||
freshness: 'local',
|
||||
limitations: [],
|
||||
}
|
||||
|
||||
const analysisContext: WeekendContext = {
|
||||
temporal_state: 'between_weekends',
|
||||
default_analysis_session: { session: raceSession, meeting, availability },
|
||||
race_hub_default_session: { session: raceSession, meeting, availability },
|
||||
race_hub_pre_session: false,
|
||||
championship_round: 1,
|
||||
total_championship_rounds: 24,
|
||||
}
|
||||
|
||||
function renderRaceHub(sessionKey: number) {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
@@ -193,23 +216,28 @@ function renderRaceHub(sessionKey: number) {
|
||||
return <RaceHubPage sessionKey={session_key ?? 0} />
|
||||
},
|
||||
})
|
||||
window.history.pushState({}, '', sessionKey ? `/race-hub?session_key=${sessionKey}` : '/race-hub')
|
||||
const router = createRouter({
|
||||
routeTree: rootRoute.addChildren([raceHubRoute]),
|
||||
history: undefined,
|
||||
})
|
||||
|
||||
// Navigate to the URL before mounting
|
||||
router.navigate({ to: '/race-hub', search: sessionKey ? { session_key: sessionKey } : {} })
|
||||
return render(<RouterProvider router={router} />)
|
||||
return { queryClient, ...render(<RouterProvider router={router} />) }
|
||||
}
|
||||
|
||||
describe('RaceHubPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.clearAllMocks()
|
||||
mockFetchSeasons.mockResolvedValue([2025])
|
||||
mockFetchLocalMeetings.mockResolvedValue([meeting])
|
||||
mockFetchWeekend.mockResolvedValue(weekend)
|
||||
mockFetchRaceHub.mockResolvedValue(raceHub)
|
||||
mockFetchWeekendContext.mockResolvedValue(analysisContext)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('renders the workspace identity band, session rail, and overview for a known session', async () => {
|
||||
@@ -256,4 +284,122 @@ describe('RaceHubPage', () => {
|
||||
fireEvent.click(screen.getByTestId('rh-switch-weekend'))
|
||||
expect(await screen.findByTestId('rh-switcher')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the server-selected completed analysis session for bare Race Hub without changing the URL', async () => {
|
||||
renderRaceHub(0)
|
||||
|
||||
await waitFor(() => expect(mockFetchRaceHub).toHaveBeenCalledWith(9472))
|
||||
expect(mockFetchWeekendContext).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('renders the intentional pre-session state without analysis cards', async () => {
|
||||
mockFetchWeekendContext.mockResolvedValue({
|
||||
...analysisContext,
|
||||
race_hub_default_session: {
|
||||
session: { ...raceSession, session_key: 9473, session_name: 'Practice 1', session_type: 'Practice', date_start: '2099-05-23T13:00:00Z' },
|
||||
meeting,
|
||||
availability,
|
||||
},
|
||||
race_hub_pre_session: true,
|
||||
race_hub_refresh_at: '2099-05-23T13:00:00Z',
|
||||
})
|
||||
|
||||
renderRaceHub(0)
|
||||
|
||||
expect(await screen.findByTestId('race-hub-pre-session')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('rh-pre-session-schedule')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Winner')).not.toBeInTheDocument()
|
||||
expect(mockFetchRaceHub).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the weekend switcher from pre-session and navigates to the selected explicit session', async () => {
|
||||
mockFetchWeekendContext.mockResolvedValue({
|
||||
...analysisContext,
|
||||
race_hub_default_session: {
|
||||
session: { ...raceSession, session_key: 9473, session_name: 'Practice 1', session_type: 'Practice', date_start: '2099-05-23T13:00:00Z' },
|
||||
meeting,
|
||||
availability,
|
||||
},
|
||||
race_hub_pre_session: true,
|
||||
race_hub_refresh_at: '2099-05-23T13:00:00Z',
|
||||
})
|
||||
|
||||
renderRaceHub(0)
|
||||
|
||||
const switchWeekend = await screen.findByTestId('rh-switch-weekend')
|
||||
expect(switchWeekend).toHaveAttribute('aria-expanded', 'false')
|
||||
fireEvent.click(switchWeekend)
|
||||
expect(await screen.findByTestId('rh-switcher')).toBeInTheDocument()
|
||||
expect(switchWeekend).toHaveAttribute('aria-expanded', 'true')
|
||||
|
||||
fireEvent.click(await screen.findByTestId('rh-switcher-session-9471'))
|
||||
await waitFor(() => expect(window.location.search).toBe('?session_key=9471'))
|
||||
})
|
||||
|
||||
it('shows recovery instead of selecting an empty future session', async () => {
|
||||
mockFetchWeekendContext.mockResolvedValue({
|
||||
...analysisContext,
|
||||
race_hub_default_session: undefined,
|
||||
race_hub_pre_session: false,
|
||||
})
|
||||
|
||||
renderRaceHub(0)
|
||||
|
||||
expect(await screen.findByTestId('race-hub-empty')).toHaveTextContent('No completed local analysis yet')
|
||||
expect(mockFetchRaceHub).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hands a bare route from completed analysis to pre-session at the supplied refresh boundary', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const handoff = new Date(Date.now() + 10_000).toISOString()
|
||||
const pendingContext: WeekendContext = {
|
||||
...analysisContext,
|
||||
race_hub_default_session: {
|
||||
session: { ...raceSession, session_key: 9473, session_name: 'Practice 1', session_type: 'Practice', date_start: handoff },
|
||||
meeting,
|
||||
availability,
|
||||
},
|
||||
race_hub_pre_session: true,
|
||||
race_hub_refresh_at: new Date(Date.now() + 16_000).toISOString(),
|
||||
}
|
||||
mockFetchWeekendContext
|
||||
.mockResolvedValueOnce({ ...analysisContext, race_hub_refresh_at: handoff })
|
||||
.mockResolvedValueOnce(pendingContext)
|
||||
|
||||
renderRaceHub(0)
|
||||
await screen.findByTestId('race-hub')
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
|
||||
|
||||
expect(await screen.findByTestId('race-hub-pre-session')).toBeInTheDocument()
|
||||
expect(mockFetchWeekendContext).toHaveBeenCalledTimes(2)
|
||||
expect(mockFetchRaceHub).toHaveBeenCalledWith(9472)
|
||||
expect(mockFetchRaceHub).not.toHaveBeenCalledWith(9473)
|
||||
})
|
||||
|
||||
it('re-arms a bare route refresh after a capped browser timer', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
mockFetchWeekendContext.mockResolvedValue({
|
||||
...analysisContext,
|
||||
race_hub_refresh_at: new Date(Date.now() + MAX_BROWSER_TIMEOUT + 1_000).toISOString(),
|
||||
})
|
||||
|
||||
renderRaceHub(0)
|
||||
await screen.findByTestId('race-hub')
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(MAX_BROWSER_TIMEOUT) })
|
||||
|
||||
await waitFor(() => expect(mockFetchWeekendContext).toHaveBeenCalledTimes(2))
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(1_000) })
|
||||
await waitFor(() => expect(mockFetchWeekendContext).toHaveBeenCalledTimes(3))
|
||||
})
|
||||
|
||||
it('keeps an explicit session URL stable across the canonical refresh boundary', async () => {
|
||||
vi.useFakeTimers()
|
||||
renderRaceHub(9472)
|
||||
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(60_000) })
|
||||
|
||||
expect(mockFetchWeekendContext).not.toHaveBeenCalled()
|
||||
expect(mockFetchRaceHub).toHaveBeenCalledWith(9472)
|
||||
expect(mockFetchRaceHub).not.toHaveBeenCalledWith(9473)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -47,9 +47,20 @@ function snapshotRows(lap: number, lastLapTime: string): LiveTimingRow[] {
|
||||
}
|
||||
|
||||
describe('TyreDegPanel', () => {
|
||||
it('shows a warming-up placeholder until enough clean laps accumulate', () => {
|
||||
it('stays collapsed while every stint is still warming up', () => {
|
||||
render(<TyreDegPanel rows={snapshotRows(3, '1:30.000')} sessionType="Race" pinned={[]} />)
|
||||
const panel = screen.getByTestId('tyredeg-panel')
|
||||
|
||||
// A panel of "warming up" placeholders carries no information and used to
|
||||
// push the Timing Tower off the fold for the first third of a race.
|
||||
expect(screen.queryAllByTestId('tyredeg-row')).toHaveLength(0)
|
||||
expect(panel).toHaveTextContent('collecting clean laps')
|
||||
})
|
||||
|
||||
it('shows a warming-up placeholder on each row once expanded', () => {
|
||||
render(<TyreDegPanel rows={snapshotRows(3, '1:30.000')} sessionType="Race" pinned={[]} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /tyre deg/i }))
|
||||
const panel = screen.getByTestId('tyredeg-panel')
|
||||
expect(panel).toHaveTextContent('VER')
|
||||
expect(panel).toHaveTextContent('M +5')
|
||||
expect(panel).toHaveTextContent('fresh')
|
||||
@@ -61,6 +72,7 @@ describe('TyreDegPanel', () => {
|
||||
makeRow('1', 1, 'VER', { NumberOfLaps: 10, LastLapTime: '1:30.000' }, { Compound: 'MEDIUM', Age: 12 }),
|
||||
]
|
||||
render(<TyreDegPanel rows={rows} sessionType="Race" pinned={[]} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /tyre deg/i }))
|
||||
expect(screen.getByText('mid-life')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -92,16 +104,44 @@ describe('TyreDegPanel', () => {
|
||||
expect(panel).not.toHaveTextContent('~P')
|
||||
})
|
||||
|
||||
it('starts expanded during a race', () => {
|
||||
render(<TyreDegPanel rows={snapshotRows(3, '1:30.000')} sessionType="Race" pinned={[]} />)
|
||||
it('opens itself during a race as soon as a stint has signal', () => {
|
||||
const { rerender } = render(
|
||||
<TyreDegPanel rows={snapshotRows(1, '1:30.000')} sessionType="Race" pinned={[]} />,
|
||||
)
|
||||
expect(screen.queryAllByTestId('tyredeg-row')).toHaveLength(0)
|
||||
|
||||
for (let lap = 2; lap <= 6; lap++) {
|
||||
const time = `1:30.${String((lap - 1) * 100).padStart(3, '0')}`
|
||||
rerender(<TyreDegPanel rows={snapshotRows(lap, time)} sessionType="Race" pinned={[]} />)
|
||||
}
|
||||
|
||||
expect(screen.getAllByTestId('tyredeg-row')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps the reader\'s own collapse choice when signal arrives', () => {
|
||||
const { rerender } = render(
|
||||
<TyreDegPanel rows={snapshotRows(1, '1:30.000')} sessionType="Race" pinned={[]} />,
|
||||
)
|
||||
// Reader opens it early, then closes it again — that decision must stick
|
||||
// even once the panel would otherwise auto-open.
|
||||
const toggle = screen.getByRole('button', { name: /tyre deg/i })
|
||||
fireEvent.click(toggle)
|
||||
fireEvent.click(toggle)
|
||||
|
||||
for (let lap = 2; lap <= 6; lap++) {
|
||||
const time = `1:30.${String((lap - 1) * 100).padStart(3, '0')}`
|
||||
rerender(<TyreDegPanel rows={snapshotRows(lap, time)} sessionType="Race" pinned={[]} />)
|
||||
}
|
||||
|
||||
expect(screen.queryAllByTestId('tyredeg-row')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('limits rows to the top ten plus pinned drivers', () => {
|
||||
const rows = Array.from({ length: 15 }, (_, index) =>
|
||||
makeRow(String(index + 1), index + 1, `D${index + 1}`),
|
||||
)
|
||||
render(<TyreDegPanel rows={rows} sessionType="Race" pinned={['14']} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /tyre deg/i }))
|
||||
expect(screen.getAllByTestId('tyredeg-row')).toHaveLength(11)
|
||||
expect(screen.getByText('D14')).toBeInTheDocument()
|
||||
expect(screen.queryByText('D12')).not.toBeInTheDocument()
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
focusMeetingKind,
|
||||
focusMeetingLabel,
|
||||
formatCountdown,
|
||||
MAX_BROWSER_TIMEOUT,
|
||||
nextUpcomingMeeting,
|
||||
pickFocusMeeting,
|
||||
refreshDeadlineDelay,
|
||||
} from '../lib/schedule'
|
||||
import type { Meeting, Session } from '../types'
|
||||
|
||||
@@ -78,4 +80,15 @@ describe('schedule helpers', () => {
|
||||
const target = new Date('2025-05-25T13:00:00+00:00')
|
||||
expect(formatCountdown(target, now)).toBe('0d 01h 00m 00s')
|
||||
})
|
||||
|
||||
it('uses the server refresh deadline without local timezone conversion', () => {
|
||||
expect(refreshDeadlineDelay('2025-05-25T13:00:00Z', Date.parse('2025-05-25T12:59:30Z'))).toBe(30_000)
|
||||
expect(refreshDeadlineDelay(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('caps a refresh deadline beyond the browser timer maximum', () => {
|
||||
const now = Date.parse('2025-05-25T12:00:00Z')
|
||||
const deadline = new Date(now + MAX_BROWSER_TIMEOUT + 1_000).toISOString()
|
||||
expect(refreshDeadlineDelay(deadline, now)).toBe(MAX_BROWSER_TIMEOUT)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -217,6 +217,41 @@ export interface Weekend {
|
||||
default_session_key?: number
|
||||
}
|
||||
|
||||
export interface ContextAvailability {
|
||||
source: string
|
||||
schedule: string
|
||||
live_transport: string
|
||||
live_session: string
|
||||
archive: string
|
||||
local_analysis: string
|
||||
freshness: string
|
||||
observed_at?: string
|
||||
limitations: string[]
|
||||
}
|
||||
|
||||
export interface ContextSession {
|
||||
session: Session
|
||||
meeting?: Meeting
|
||||
availability: ContextAvailability
|
||||
}
|
||||
|
||||
export interface WeekendContext {
|
||||
season?: number
|
||||
temporal_state: string
|
||||
previous_meeting?: Meeting
|
||||
focus_meeting?: Meeting
|
||||
next_meeting?: Meeting
|
||||
previous_completed_session?: ContextSession
|
||||
active_session?: ContextSession
|
||||
next_session?: ContextSession
|
||||
default_analysis_session?: ContextSession
|
||||
race_hub_default_session?: ContextSession
|
||||
race_hub_pre_session: boolean
|
||||
race_hub_refresh_at?: string
|
||||
championship_round: number
|
||||
total_championship_rounds: number
|
||||
}
|
||||
|
||||
export interface LiveStateResponse {
|
||||
is_live: boolean
|
||||
data: LiveStreamData | null
|
||||
|
||||
@@ -472,6 +472,62 @@ func TestProcessTopicTimingAppData(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The feed sends stints as sparse deltas keyed by stint index. Replacing the
|
||||
// slice on each delta collapsed pit history to one entry and pinned tyre age
|
||||
// near zero — observed live at lap 49 of a 70-lap race, where every driver
|
||||
// reported a single stint of age 0 despite having pitted.
|
||||
func TestProcessTopicTimingAppDataMergesSparseStintDeltas(t *testing.T) {
|
||||
state := live.NewState()
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"0": {"Compound": "MEDIUM", "New": "true", "TotalLaps": 0}}}}
|
||||
}`))
|
||||
// Stint 0 runs to 18 laps, then the driver pits onto a new hard.
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"0": {"TotalLaps": 18}}}}
|
||||
}`))
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"1": {"Compound": "HARD", "New": "true", "TotalLaps": 0}}}}
|
||||
}`))
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"1": {"TotalLaps": 12}}}}
|
||||
}`))
|
||||
|
||||
snap := state.Snapshot()
|
||||
stints := snap.Stints["4"]
|
||||
if len(stints) != 2 {
|
||||
t.Fatalf("expected 2 stints after a pit stop, got %d: %+v", len(stints), stints)
|
||||
}
|
||||
if stints[0].Compound != "MEDIUM" || stints[0].Laps != 18 {
|
||||
t.Errorf("first stint lost across deltas: %+v", stints[0])
|
||||
}
|
||||
if stints[1].Compound != "HARD" || stints[1].Laps != 12 {
|
||||
t.Errorf("second stint = %+v", stints[1])
|
||||
}
|
||||
if tyre := snap.Tyres["4"]; tyre.Compound != "HARD" || tyre.Age != 12 {
|
||||
t.Errorf("current tyre should track the latest stint, got %+v", tyre)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessTopicTimingAppDataIgnoresNonNumericStintKeys(t *testing.T) {
|
||||
state := live.NewState()
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"0": {"Compound": "SOFT", "New": "true", "TotalLaps": 9}}}}
|
||||
}`))
|
||||
// "_kf" is a feed key-frame marker, not a stint index. Parsing it as 0
|
||||
// would overwrite the real first stint.
|
||||
state.ProcessTopic("TimingAppData", json.RawMessage(`{
|
||||
"Lines": {"4": {"Stints": {"_kf": {"Compound": "HARD", "TotalLaps": 99}}}}
|
||||
}`))
|
||||
|
||||
stints := state.Snapshot().Stints["4"]
|
||||
if len(stints) != 1 {
|
||||
t.Fatalf("expected 1 stint, got %d: %+v", len(stints), stints)
|
||||
}
|
||||
if stints[0].Compound != "SOFT" || stints[0].Laps != 9 {
|
||||
t.Errorf("key-frame marker corrupted stint 0: %+v", stints[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessTopicTimingStats(t *testing.T) {
|
||||
state := live.NewState()
|
||||
state.Drivers["55"] = live.LiveDriverData{RacingNumber: "55"}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -404,22 +405,42 @@ func (s *State) ProcessTopic(topic string, data json.RawMessage) bool {
|
||||
Stints json.RawMessage `json:"Stints"`
|
||||
}
|
||||
if json.Unmarshal(lineRaw, &line) == nil && line.Stints != nil {
|
||||
var driverStints []LiveStintData
|
||||
// The feed sends stints as sparse deltas keyed by stint index:
|
||||
// a mid-stint update is just {"1": {"TotalLaps": 14}}. Merge
|
||||
// each entry into the stint it addresses. Replacing the slice
|
||||
// wholesale discarded every earlier stint, so pit history
|
||||
// collapsed to one entry and tyre age stuck near zero for the
|
||||
// whole race.
|
||||
driverStints := append([]LiveStintData(nil), s.Stints[num]...)
|
||||
changed := false
|
||||
for _, sRaw := range indexedRawValues(line.Stints) {
|
||||
var st struct {
|
||||
Compound string `json:"Compound"`
|
||||
New string `json:"New"`
|
||||
TotalLaps int `json:"TotalLaps"`
|
||||
Compound *string `json:"Compound"`
|
||||
New *string `json:"New"`
|
||||
TotalLaps *int `json:"TotalLaps"`
|
||||
}
|
||||
if json.Unmarshal(sRaw.Raw, &st) == nil && st.Compound != "" {
|
||||
driverStints = append(driverStints, LiveStintData{
|
||||
Compound: st.Compound,
|
||||
New: st.New == "true" || st.New == "True",
|
||||
Laps: st.TotalLaps,
|
||||
})
|
||||
if json.Unmarshal(sRaw.Raw, &st) != nil {
|
||||
continue
|
||||
}
|
||||
if st.Compound == nil && st.New == nil && st.TotalLaps == nil {
|
||||
continue
|
||||
}
|
||||
for len(driverStints) <= sRaw.Index {
|
||||
driverStints = append(driverStints, LiveStintData{})
|
||||
}
|
||||
entry := &driverStints[sRaw.Index]
|
||||
if st.Compound != nil && *st.Compound != "" {
|
||||
entry.Compound = *st.Compound
|
||||
}
|
||||
if st.New != nil {
|
||||
entry.New = *st.New == "true" || *st.New == "True"
|
||||
}
|
||||
if st.TotalLaps != nil {
|
||||
entry.Laps = *st.TotalLaps
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if len(driverStints) > 0 {
|
||||
if changed {
|
||||
s.Stints[num] = driverStints
|
||||
lastStint := driverStints[len(driverStints)-1]
|
||||
t := s.Tyres[num]
|
||||
@@ -874,8 +895,13 @@ func indexedRawValues(raw json.RawMessage) []indexedRaw {
|
||||
if err := json.Unmarshal(raw, &obj); err == nil {
|
||||
values := make([]indexedRaw, 0, len(obj))
|
||||
for k, v := range obj {
|
||||
i := 0
|
||||
fmt.Sscanf(k, "%d", &i)
|
||||
// Keys are array indices in the feed's delta form. Non-numeric keys
|
||||
// are feed metadata — "_kf" (key frame) is the common one — and must
|
||||
// not be folded in as index 0, which would clobber the first entry.
|
||||
i, err := strconv.Atoi(k)
|
||||
if err != nil || i < 0 {
|
||||
continue
|
||||
}
|
||||
values = append(values, indexedRaw{Index: i, Raw: v})
|
||||
}
|
||||
sort.Slice(values, func(i, j int) bool {
|
||||
|
||||
@@ -24,6 +24,7 @@ const (
|
||||
|
||||
preSessionWindow = 48 * time.Hour
|
||||
postWeekendWindow = 48 * time.Hour
|
||||
raceHubPendingPollInterval = 15 * time.Second
|
||||
)
|
||||
|
||||
// LiveEvidence is the small, transport-independent subset of FIA state needed
|
||||
@@ -69,6 +70,9 @@ type WeekendContext struct {
|
||||
ActiveSession *ContextSession `json:"active_session,omitempty"`
|
||||
NextSession *ContextSession `json:"next_session,omitempty"`
|
||||
DefaultAnalysisSession *ContextSession `json:"default_analysis_session,omitempty"`
|
||||
RaceHubDefaultSession *ContextSession `json:"race_hub_default_session,omitempty"`
|
||||
RaceHubPreSession bool `json:"race_hub_pre_session"`
|
||||
RaceHubRefreshAt string `json:"race_hub_refresh_at,omitempty"`
|
||||
ChampionshipRound int `json:"championship_round"`
|
||||
TotalChampionshipRounds int `json:"total_championship_rounds"`
|
||||
}
|
||||
@@ -150,7 +154,7 @@ func (s *Service) ResolveWeekendContext(evidence LiveEvidence) (WeekendContext,
|
||||
}
|
||||
}
|
||||
|
||||
var previous, next, defaultAnalysis *contextCandidate
|
||||
var previous, next, defaultAnalysis, pending *contextCandidate
|
||||
for i := range candidates {
|
||||
c := &candidates[i]
|
||||
isActive := active != nil && active.session.SessionKey != 0 && c.session.SessionKey == active.session.SessionKey
|
||||
@@ -164,6 +168,10 @@ func (s *Service) ResolveWeekendContext(evidence LiveEvidence) (WeekendContext,
|
||||
if !isActive && !c.start.IsZero() && !c.start.Before(now) && (next == nil || c.start.Before(next.start)) {
|
||||
next = c
|
||||
}
|
||||
if !isActive && !c.complete && !c.start.IsZero() && !c.start.After(now) &&
|
||||
(c.end.IsZero() || now.Before(c.end)) && (pending == nil || c.start.After(pending.start)) {
|
||||
pending = c
|
||||
}
|
||||
}
|
||||
|
||||
if previous != nil {
|
||||
@@ -188,9 +196,40 @@ func (s *Service) ResolveWeekendContext(evidence LiveEvidence) (WeekendContext,
|
||||
if out.FocusMeeting != nil {
|
||||
out.ChampionshipRound = championshipRound(champMeetings, int(out.FocusMeeting.MeetingKey))
|
||||
}
|
||||
applyRaceHubDefault(&out, active, defaultAnalysis, next, pending, now)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// applyRaceHubDefault is deliberately distinct from TemporalPreSession. Other
|
||||
// weekend surfaces begin preparation 48 hours ahead; Race Hub remains an
|
||||
// analysis destination until the one-hour handoff before the next session.
|
||||
func applyRaceHubDefault(out *WeekendContext, active, analysis, next, pending *contextCandidate, now time.Time) {
|
||||
if active != nil {
|
||||
out.RaceHubDefaultSession = out.ActiveSession
|
||||
return
|
||||
}
|
||||
if next != nil {
|
||||
handoff := next.start.Add(-time.Hour)
|
||||
if now.Before(handoff) {
|
||||
out.RaceHubRefreshAt = handoff.Format(time.RFC3339)
|
||||
} else if now.Before(next.start) {
|
||||
out.RaceHubDefaultSession = out.NextSession
|
||||
out.RaceHubPreSession = true
|
||||
out.RaceHubRefreshAt = next.start.Format(time.RFC3339)
|
||||
return
|
||||
}
|
||||
}
|
||||
if pending != nil {
|
||||
out.RaceHubDefaultSession = sessionRef(*pending, LiveEvidence{}, now)
|
||||
out.RaceHubPreSession = true
|
||||
out.RaceHubRefreshAt = now.Add(raceHubPendingPollInterval).Format(time.RFC3339)
|
||||
return
|
||||
}
|
||||
if analysis != nil {
|
||||
out.RaceHubDefaultSession = out.DefaultAnalysisSession
|
||||
}
|
||||
}
|
||||
|
||||
func currentLocalSeason(years []int, current int) int {
|
||||
for _, year := range years {
|
||||
if year == current {
|
||||
|
||||
@@ -399,3 +399,88 @@ func TestResolveWeekendContextMissingScheduleDoesNotClaimSeasonComplete(t *testi
|
||||
t.Fatalf("total rounds = %d, want scheduled round retained", got.TotalChampionshipRounds)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWeekendContextRaceHubDefault(t *testing.T) {
|
||||
seed := func(t *testing.T, svc *Service) {
|
||||
addContextMeeting(t, svc, 1, "British Grand Prix", "2026-07-03T09:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
addContextSession(t, svc, 11, 1, "Race", "2026-07-05T14:00:00Z", "2026-07-05T16:00:00Z", false)
|
||||
completeContextSession(t, svc, 11, 1)
|
||||
addContextMeeting(t, svc, 2, "Belgian Grand Prix", "2026-07-17T09:00:00Z", "2026-07-19T16:00:00Z", false)
|
||||
addContextSession(t, svc, 21, 2, "Practice 1", "2026-07-17T09:00:00Z", "2026-07-17T10:00:00Z", false)
|
||||
}
|
||||
|
||||
t.Run("keeps completed analysis before handoff", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-16T07:59:59Z")
|
||||
svc := contextService(t, now)
|
||||
seed(t, svc)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RaceHubDefaultSession == nil || got.RaceHubDefaultSession.Session.SessionKey != 11 || got.RaceHubPreSession {
|
||||
t.Fatalf("race hub default = %+v, pre-session = %t", got.RaceHubDefaultSession, got.RaceHubPreSession)
|
||||
}
|
||||
if got.RaceHubRefreshAt != "2026-07-17T08:00:00Z" {
|
||||
t.Fatalf("refresh = %q", got.RaceHubRefreshAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("hands off exactly one hour before first session", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-17T08:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
seed(t, svc)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RaceHubDefaultSession == nil || got.RaceHubDefaultSession.Session.SessionKey != 21 || !got.RaceHubPreSession {
|
||||
t.Fatalf("race hub handoff = %+v, pre-session = %t", got.RaceHubDefaultSession, got.RaceHubPreSession)
|
||||
}
|
||||
if got.RaceHubRefreshAt != "2026-07-17T09:00:00Z" {
|
||||
t.Fatalf("refresh = %q", got.RaceHubRefreshAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keeps the scheduled session pending after its start without live evidence", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-17T09:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
seed(t, svc)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RaceHubDefaultSession == nil || got.RaceHubDefaultSession.Session.SessionKey != 21 || !got.RaceHubPreSession {
|
||||
t.Fatalf("scheduled race hub default = %+v, pre-session = %t", got.RaceHubDefaultSession, got.RaceHubPreSession)
|
||||
}
|
||||
if got.RaceHubRefreshAt != "2026-07-17T09:00:15Z" {
|
||||
t.Fatalf("refresh = %q", got.RaceHubRefreshAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("active live session wins", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-17T08:30:00Z")
|
||||
svc := contextService(t, now)
|
||||
seed(t, svc)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{Active: true, MeetingName: "Belgian Grand Prix", SessionName: "Practice 1", SessionType: "Practice 1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RaceHubDefaultSession == nil || got.RaceHubDefaultSession.Session.SessionKey != 21 || got.RaceHubPreSession {
|
||||
t.Fatalf("live default = %+v, pre-session = %t", got.RaceHubDefaultSession, got.RaceHubPreSession)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("does not select an empty future session before handoff", func(t *testing.T) {
|
||||
now, _ := time.Parse(time.RFC3339, "2026-07-16T12:00:00Z")
|
||||
svc := contextService(t, now)
|
||||
addContextMeeting(t, svc, 2, "Belgian Grand Prix", "2026-07-17T09:00:00Z", "2026-07-19T16:00:00Z", false)
|
||||
addContextSession(t, svc, 21, 2, "Practice 1", "2026-07-17T09:00:00Z", "2026-07-17T10:00:00Z", false)
|
||||
got, err := svc.ResolveWeekendContext(LiveEvidence{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RaceHubDefaultSession != nil || got.RaceHubPreSession {
|
||||
t.Fatalf("unexpected empty future default: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -167,3 +167,30 @@ func TestTerminalSessionStatus(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeekendContextHandlerSerializesRaceHubRefreshDeadline(t *testing.T) {
|
||||
st := openContextStore(t)
|
||||
seedContextHandler(t, st)
|
||||
if err := st.UpsertSessionResult(store.SessionResult{SessionKey: 11, MeetingKey: 1, DriverNumber: 1, Position: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.UpsertMeeting(store.Meeting{MeetingKey: 2, MeetingName: "Belgian Grand Prix", CircuitShortName: "Spa", Year: 2026, DateStart: "2026-07-17T09:00:00Z", DateEnd: "2026-07-19T16:00:00Z"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := st.UpsertSession(store.Session{SessionKey: 21, MeetingKey: 2, SessionName: "Practice 1", SessionType: "Practice", DateStart: "2026-07-17T09:00:00Z", DateEnd: "2026-07-17T10:00:00Z"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := NewServer(nil, 0, st)
|
||||
s.query = query.NewServiceWithClock(st, func() time.Time {
|
||||
return time.Date(2026, 7, 17, 8, 0, 0, 0, time.UTC)
|
||||
})
|
||||
rr := httptest.NewRecorder()
|
||||
s.handleWeekendContext(rr, httptest.NewRequest(http.MethodGet, "/api/v1/weekend-context", nil))
|
||||
var got query.WeekendContext
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !got.RaceHubPreSession || got.RaceHubRefreshAt != "2026-07-17T09:00:00Z" || got.RaceHubDefaultSession == nil || got.RaceHubDefaultSession.Session.SessionKey != 21 {
|
||||
t.Fatalf("race hub context = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,42 @@ import { test, expect } from '@playwright/test'
|
||||
|
||||
const FULL_SESSION = 9472
|
||||
const CORE_ONLY_SESSION = 9000
|
||||
const CONTEXT_MEETING = {
|
||||
meeting_key: 1229,
|
||||
meeting_name: 'Monaco',
|
||||
country_code: 'MON',
|
||||
}
|
||||
const CONTEXT_AVAILABILITY = {
|
||||
source: 'local', schedule: 'available', live_transport: 'unknown', live_session: 'inactive',
|
||||
archive: 'unavailable', local_analysis: 'complete', freshness: 'local', limitations: [],
|
||||
}
|
||||
|
||||
function completedContext(refreshAt?: string) {
|
||||
return {
|
||||
temporal_state: 'between_weekends',
|
||||
race_hub_default_session: {
|
||||
session: { session_key: FULL_SESSION }, meeting: CONTEXT_MEETING, availability: CONTEXT_AVAILABILITY,
|
||||
},
|
||||
race_hub_pre_session: false,
|
||||
race_hub_refresh_at: refreshAt,
|
||||
}
|
||||
}
|
||||
|
||||
function pendingContext(refreshAt: string) {
|
||||
return {
|
||||
temporal_state: 'pre_session',
|
||||
race_hub_default_session: {
|
||||
session: {
|
||||
session_key: 9473, meeting_key: 1229, session_name: 'Practice 1', session_type: 'Practice',
|
||||
date_start: '2030-01-01T00:00:01Z', date_end: '2030-01-01T01:00:01Z', gmt_offset: '00:00:00',
|
||||
},
|
||||
meeting: CONTEXT_MEETING,
|
||||
availability: { ...CONTEXT_AVAILABILITY, local_analysis: 'not_applicable' },
|
||||
},
|
||||
race_hub_pre_session: true,
|
||||
race_hub_refresh_at: refreshAt,
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('Race Hub Weekend Workspace', () => {
|
||||
test('lands on the Overview tab with workspace identity', async ({ page }) => {
|
||||
@@ -102,9 +138,87 @@ test.describe('Race Hub Weekend Workspace', () => {
|
||||
)
|
||||
})
|
||||
|
||||
test('bare /race-hub redirects to the focus session', async ({ page }) => {
|
||||
test('bare /race-hub shows server-selected completed analysis without changing the URL', async ({ page }) => {
|
||||
await page.route('**/api/v1/weekend-context', (route) =>
|
||||
route.fulfill({ contentType: 'application/json', body: JSON.stringify(completedContext()) }),
|
||||
)
|
||||
await page.goto('/race-hub')
|
||||
await expect(page).toHaveURL(/session_key=\d+/)
|
||||
await expect(page).toHaveURL(/\/race-hub$/)
|
||||
await expect(page.getByTestId('race-hub')).toBeVisible()
|
||||
})
|
||||
|
||||
test('bare /race-hub hands off to pending pre-session state at the refresh deadline', async ({ page }) => {
|
||||
await page.clock.install({ time: new Date('2030-01-01T00:00:00Z') })
|
||||
let requests = 0
|
||||
const raceHubRequests: number[] = []
|
||||
page.on('request', (request) => {
|
||||
const url = new URL(request.url())
|
||||
if (url.pathname === '/api/v1/race-hub') {
|
||||
raceHubRequests.push(Number(url.searchParams.get('session_key')))
|
||||
}
|
||||
})
|
||||
await page.route('**/api/v1/weekend-context', (route) => {
|
||||
requests += 1
|
||||
const body = requests === 1
|
||||
? completedContext('2030-01-01T00:00:01Z')
|
||||
: pendingContext('2030-01-01T00:00:16Z')
|
||||
return route.fulfill({ contentType: 'application/json', body: JSON.stringify(body) })
|
||||
})
|
||||
|
||||
await page.goto('/race-hub')
|
||||
await expect(page.getByTestId('race-hub')).toBeVisible()
|
||||
await page.clock.fastForward(1_000)
|
||||
|
||||
await expect(page.getByTestId('race-hub-pre-session')).toBeVisible()
|
||||
await expect(page).toHaveURL(/\/race-hub$/)
|
||||
expect(raceHubRequests).toContain(FULL_SESSION)
|
||||
expect(raceHubRequests).not.toContain(9473)
|
||||
})
|
||||
|
||||
test('pre-session state opens the weekend switcher and navigates to an explicit session', async ({ page }) => {
|
||||
await page.route('**/api/v1/weekend-context', (route) =>
|
||||
route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(pendingContext('2030-01-01T00:00:16Z')),
|
||||
}),
|
||||
)
|
||||
|
||||
await page.goto('/race-hub')
|
||||
await expect(page.getByTestId('race-hub-pre-session')).toBeVisible()
|
||||
|
||||
const switchWeekend = page.getByTestId('rh-switch-weekend')
|
||||
await expect(switchWeekend).toHaveAttribute('aria-expanded', 'false')
|
||||
await switchWeekend.click()
|
||||
await expect(page.getByTestId('rh-switcher')).toBeVisible()
|
||||
await expect(switchWeekend).toHaveAttribute('aria-expanded', 'true')
|
||||
|
||||
await page.getByTestId(`rh-switcher-session-${FULL_SESSION}`).click()
|
||||
await expect(page).toHaveURL(new RegExp(`/race-hub\\?session_key=${FULL_SESSION}`))
|
||||
await expect(page.getByTestId('race-hub')).toBeVisible()
|
||||
})
|
||||
|
||||
test('bare /race-hub recovers when no completed local analysis exists', async ({ page }) => {
|
||||
await page.route('**/api/v1/weekend-context', (route) =>
|
||||
route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ temporal_state: 'between_weekends', race_hub_pre_session: false }),
|
||||
}),
|
||||
)
|
||||
|
||||
await page.goto('/race-hub')
|
||||
await expect(page.getByTestId('race-hub-empty')).toContainText('No completed local analysis yet')
|
||||
})
|
||||
|
||||
test('an explicit session URL remains stable when canonical context would refresh', async ({ page }) => {
|
||||
let contextRequested = false
|
||||
await page.route('**/api/v1/weekend-context', (route) => {
|
||||
contextRequested = true
|
||||
return route.fulfill({ contentType: 'application/json', body: JSON.stringify(pendingContext('2030-01-01T00:00:01Z')) })
|
||||
})
|
||||
|
||||
await page.goto(`/race-hub?session_key=${FULL_SESSION}`)
|
||||
await expect(page.getByTestId('race-hub')).toBeVisible()
|
||||
await expect(page).toHaveURL(new RegExp(`session_key=${FULL_SESSION}`))
|
||||
expect(contextRequested).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user