Compare commits
98 Commits
024accfb3d
...
feat/front
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
888378e210 | ||
|
|
c475011c49 | ||
|
|
5a6323d3b4 | ||
|
|
ed3b8cf628 | ||
|
|
0a42c05487 | ||
|
|
08ff75b469 | ||
|
|
16c035b037 | ||
|
|
1dac73cdc5 | ||
|
|
02a84f67b4 | ||
|
|
f0a8e4e631 | ||
|
|
519053d340 | ||
|
|
e0d7b9981e | ||
|
|
79acf0579a | ||
|
|
82abbd6b35 | ||
|
|
faa173578c | ||
|
|
39f1560282 | ||
|
|
d3f7bab6dc | ||
|
|
5b112fb012 | ||
|
|
96d741424c | ||
|
|
c2617d39bb | ||
|
|
beacda278d | ||
|
|
f24ec4be94 | ||
|
|
09104451d0 | ||
|
|
f8bd183c26 | ||
|
|
01ec1f24e7 | ||
|
|
3f022a0cf9 | ||
|
|
5970649a9c | ||
|
|
7212eb9b44 | ||
|
|
785dccdca2 | ||
|
|
e8de2068c1 | ||
|
|
3cc6157337 | ||
|
|
1782fd313c | ||
|
|
be7eb3c034 | ||
|
|
71523641ad | ||
|
|
e51cabba62 | ||
|
|
fc6fc36d8f | ||
|
|
16d82afad5 | ||
|
|
91199ff5c0 | ||
|
|
144e93ee44 | ||
|
|
f4f5071e26 | ||
|
|
a1d71900d1 | ||
|
|
34b060238a | ||
|
|
a9920f0dd4 | ||
|
|
7c8a75f7ca | ||
|
|
e0174f7bf1 | ||
|
|
2d6fa531f2 | ||
|
|
8fd358748d | ||
|
|
b0fd252096 | ||
|
|
ad379e0f07 | ||
|
|
9ee14e5c89 | ||
|
|
cc4337be88 | ||
|
|
addfd6d24d | ||
|
|
b5d070e116 | ||
|
|
233eefaf12 | ||
|
|
51b0238b09 | ||
|
|
24bcac8038 | ||
|
|
93ac0ccebb | ||
|
|
66bf649729 | ||
|
|
2ddc930efe | ||
|
|
7d0b25b66e | ||
|
|
bc18a20829 | ||
|
|
2795ccf11b | ||
|
|
4813b958a0 | ||
|
|
a97e3caa4f | ||
|
|
655df9845b | ||
|
|
2d49a8bd00 | ||
|
|
4e62e93ea2 | ||
|
|
eacd5f26e9 | ||
|
|
ba7f653e3c | ||
|
|
f2bf1fd0fc | ||
|
|
6c72c12821 | ||
|
|
98126a06f9 | ||
|
|
47f0cd6d12 | ||
|
|
26642e3ff6 | ||
|
|
0977861806 | ||
|
|
c5a7ad51eb | ||
|
|
75ca5f4deb | ||
|
|
094620fa08 | ||
|
|
7263949260 | ||
|
|
5408a45bbd | ||
|
|
b7696c11de | ||
|
|
8e3d4cea3f | ||
|
|
c973c03689 | ||
|
|
85a8b6ad44 | ||
|
|
cc5184c4b6 | ||
|
|
8d5ab4d7a7 | ||
|
|
c3ad7743e6 | ||
|
|
127628e4dd | ||
|
|
c989aace10 | ||
|
|
3c6115e815 | ||
|
|
7f0c338a57 | ||
|
|
5cfaed30ba | ||
|
|
e5cb4e4ed2 | ||
|
|
c708b6697d | ||
|
|
7a5e0a323d | ||
|
|
282b5a8c24 | ||
|
|
2220d5d30a | ||
|
|
91e2d13ab7 |
58
.agents/README.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# `.agents/` — harness-agnostic agentic dev toolkit
|
||||
|
||||
Portable skills, prompts, and scripts that drive the box-box development lifecycle.
|
||||
Any harness (Claude, Codex, opencode, …) can read these — the canonical workflows
|
||||
live here, not in a tool-specific folder. The shared project context every harness
|
||||
reads is `AGENTS.md` (→ `CLAUDE.md`).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
skills/ Codex/open agent skills: groom, write-spec, implement, review, lenses
|
||||
personas/ grill.md (base) + lens overlays (architect, …) — the interrogation voices
|
||||
prompts/ ready-spec.md (groomed spec), implement.md/review.md dispatch prompts
|
||||
lib/gh.sh GitHub issue + Project (#2) state helpers: issue_*, set_stage/effort/priority
|
||||
lib/dispatch.sh dispatch(): Ready issue → worktree → harness → gate → PR
|
||||
harnesses.sh headless adapters (one fn per harness) + run_gate — the ONLY tool-specific code
|
||||
bin/dev CLI: `dev implement <issue#> --harness <name> [--dry-run]`
|
||||
```
|
||||
|
||||
## The lifecycle
|
||||
|
||||
`Icebox → Research → Ready → In Progress → In Review → Done` (the Project `Stage` field).
|
||||
|
||||
- **Groom** (interactive, Claude): `/groom <issue#>` runs a seeded grill-me → writes a
|
||||
Ready spec into the issue body → sets Effort/Priority → leaves Stage at `Research`.
|
||||
You review and flip to `Ready`.
|
||||
- **Implement** (recommended harnesses: `codex` or `cursor`): `.agents/bin/dev implement <issue#> --harness <name>`
|
||||
(or `/implement …` in Claude to supervise) → isolated worktree → runs the harness
|
||||
headless on the spec → build gate → opens a PR → sets Stage `In Review`.
|
||||
- **Review + merge**: use the `review` skill from a harness different from the
|
||||
implementer to create a local review packet and PR comment, then you merge.
|
||||
|
||||
## Skills and harnesses
|
||||
|
||||
`.agents/skills` is the canonical home for reusable workflows. Codex discovers
|
||||
repo skills from that path directly, and Claude can use the same files through
|
||||
`.claude/skills -> ../.agents/skills`. Other harnesses can read the same
|
||||
`SKILL.md` files explicitly or enter the workflow through `.agents/bin/dev`.
|
||||
Do not put canonical workflow instructions under `.claude/`; that directory is
|
||||
local adapter state.
|
||||
|
||||
## Adding / fixing a harness
|
||||
|
||||
Edit one function in `harnesses.sh`: `harness_<name> <workdir> <promptfile>`, running the
|
||||
tool non-interactively in `<workdir>` on the prompt. For current implementation
|
||||
dispatch, prefer `codex` or `cursor`; `claude` and `opencode` remain available, and
|
||||
`pi` still needs flag verification before trusting.
|
||||
|
||||
`agy` / Antigravity is deliberately disabled for non-dry-run dispatch as of
|
||||
2026-07-04. Phase 1 testing found the headless path unreliable: with
|
||||
`--new-project` it ignored the prompt and tried to scaffold, while without it the CLI
|
||||
could resume a stale conversation and hang past the print timeout. Keep using
|
||||
`.agents/bin/dev implement <issue#> --harness agy --dry-run` for prompt inspection
|
||||
only; real dispatch should use `codex` or `cursor` until a fresh Antigravity
|
||||
headless invocation is verified and documented.
|
||||
|
||||
Always `--dry-run` a new harness first: it renders the exact prompt and plan, touching
|
||||
nothing (no worktree, PR, or state change).
|
||||
45
.agents/bin/dev
Executable file
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# .agents/bin/dev — box-box agentic dev CLI. Works from any harness's shell.
|
||||
#
|
||||
# dev implement <issue#> --harness <codex|cursor|claude|opencode|pi|agy> [--dry-run] [--base <branch>]
|
||||
#
|
||||
# Grooming is driven interactively via the Claude Code /groom skill; this CLI covers
|
||||
# the implement lane (dispatch a Ready issue to a harness → worktree → gate → PR).
|
||||
|
||||
set -o pipefail
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")/../.." && pwd)"
|
||||
|
||||
usage() {
|
||||
cat >&2 <<EOF
|
||||
box-box dev CLI
|
||||
|
||||
dev implement <issue#> --harness <name> [--dry-run] [--base <branch>]
|
||||
|
||||
harnesses: codex, cursor (recommended) · claude, opencode (available) · agy (dry-run only, disabled for dispatch) · pi (verify flags)
|
||||
--dry-run render the prompt + plan, touch nothing (no worktree/PR/state change)
|
||||
--base base branch for the worktree/PR (default: main)
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
cmd="${1:-}"; shift 2>/dev/null || true
|
||||
case "$cmd" in
|
||||
implement)
|
||||
issue="${1:-}"; shift 2>/dev/null || true
|
||||
harness=""; passthru=()
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--harness) harness="${2:-}"; shift 2 ;;
|
||||
--dry-run) passthru+=(--dry-run); shift ;;
|
||||
--base) passthru+=(--base "${2:-}"); shift 2 ;;
|
||||
*) echo "unknown arg: $1" >&2; usage ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$issue" ] && [ -n "$harness" ] || usage
|
||||
# shellcheck source=/dev/null
|
||||
source "$ROOT/.agents/lib/dispatch.sh"
|
||||
dispatch "$issue" "$harness" ${passthru[@]+"${passthru[@]}"}
|
||||
;;
|
||||
""|-h|--help|help) usage ;;
|
||||
*) echo "unknown command: $cmd" >&2; usage ;;
|
||||
esac
|
||||
71
.agents/harnesses.sh
Normal file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env bash
|
||||
# .agents/harnesses.sh — headless harness adapters.
|
||||
#
|
||||
# ONE function per harness: harness_<name> <workdir> <promptfile>
|
||||
# Each runs the harness NON-INTERACTIVELY inside <workdir>, feeding it the rendered
|
||||
# prompt, expected to edit files (and ideally commit). This is the ONLY harness-specific
|
||||
# code in the toolkit — tune the exact flags here per tool/version.
|
||||
#
|
||||
# Autonomy note: these run unattended, so each uses the tool's "just do it" mode
|
||||
# (accept edits / full-auto). Only run harnesses you trust on code you can review via PR.
|
||||
|
||||
# ---- MUST-HAVE ----
|
||||
|
||||
harness_disabled_reason() { # <name> -> reason on stdout; 0 means disabled
|
||||
case "$1" in
|
||||
agy)
|
||||
cat <<'EOF'
|
||||
agy is disabled for implementation dispatch as of 2026-07-04: Antigravity headless mode was observed to ignore prompts with --new-project, resume stale conversations without it, and hang past print timeouts. Use codex or cursor until a fresh headless invocation is verified.
|
||||
EOF
|
||||
return 0
|
||||
;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
harness_claude() { # Claude Code — print mode, auto-accept edits
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && claude -p "$(cat "$prompt")" --permission-mode acceptEdits )
|
||||
}
|
||||
|
||||
harness_codex() { # OpenAI Codex CLI — non-interactive exec, full auto
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && codex exec --full-auto "$(cat "$prompt")" )
|
||||
}
|
||||
|
||||
harness_opencode() { # opencode — non-interactive run
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && opencode run "$(cat "$prompt")" )
|
||||
}
|
||||
|
||||
harness_cursor() { # Cursor CLI agent — composer-2.5, headless full-auto
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && cursor-agent -p "$(cat "$prompt")" --model composer-2.5 --force --trust )
|
||||
}
|
||||
|
||||
harness_agy() { # Antigravity CLI — disabled until headless is verified
|
||||
local reason
|
||||
reason="$(harness_disabled_reason agy)"
|
||||
echo "harness_agy: $reason" >&2
|
||||
return 2
|
||||
}
|
||||
|
||||
# ---- NICE-TO-HAVE (verify the exact invocation for your version before trusting) ----
|
||||
|
||||
harness_pi() { # pi — CONFIRM headless CLI + flags
|
||||
local dir="$1" prompt="$2"
|
||||
( cd "$dir" && pi run "$(cat "$prompt")" ) # placeholder — verify
|
||||
}
|
||||
|
||||
# ---- build/typecheck gate (fast, local) ----
|
||||
# Returns non-zero on failure. This is a smoke gate — CI runs the full suite. Tune freely.
|
||||
run_gate() {
|
||||
local dir="$1"
|
||||
( cd "$dir" && go build ./... ) || return 1
|
||||
if [ -d "$dir/frontend/node_modules" ]; then
|
||||
( cd "$dir/frontend" && npx tsc --noEmit ) || return 1
|
||||
else
|
||||
echo " (gate: frontend deps absent in worktree — tsc/vitest deferred to CI)" >&2
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
130
.agents/lib/dispatch.sh
Normal file
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env bash
|
||||
# .agents/lib/dispatch.sh — implement a Ready issue with a chosen harness in an
|
||||
# isolated git worktree, run the build gate, and open a PR.
|
||||
#
|
||||
# Source it, then: dispatch <issue#> <harness> [--dry-run] [--base <branch>]
|
||||
# (or use the CLI: .agents/bin/dev implement <issue#> --harness <name> [--dry-run])
|
||||
|
||||
_AGENTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
# shellcheck source=/dev/null
|
||||
source "$_AGENTS_DIR/lib/gh.sh"
|
||||
# shellcheck source=/dev/null
|
||||
source "$_AGENTS_DIR/harnesses.sh"
|
||||
|
||||
_slug() { echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//' | cut -c1-40; }
|
||||
|
||||
_render_prompt() { # <issue#> <title> <body>
|
||||
echo "# Implement: $2"
|
||||
echo
|
||||
cat "$_AGENTS_DIR/prompts/implement.md"
|
||||
echo; echo "---"; echo
|
||||
echo "## Spec — issue #$1"
|
||||
echo
|
||||
echo "$3"
|
||||
}
|
||||
|
||||
_pr_body() { # <issue#> <harness> <gate>
|
||||
cat <<EOF
|
||||
Implements #$1.
|
||||
|
||||
- **Harness:** $2 (dispatched via \`.agents/bin/dev\`)
|
||||
- **Local gate** (\`go build\` + \`tsc --noEmit\`): **$3**
|
||||
- Full test suite + independent review run in CI / by a reviewer harness.
|
||||
|
||||
See #$1 for the groomed spec, Test Plan, and Definition of Done.
|
||||
|
||||
Closes #$1
|
||||
EOF
|
||||
}
|
||||
|
||||
dispatch() { # <issue#> <harness> [--dry-run] [--base <branch>]
|
||||
local issue="$1" harness="$2"; shift 2 || { echo "usage: dispatch <issue#> <harness> [--dry-run] [--base <branch>]"; return 2; }
|
||||
local dry=0 base="main"
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--dry-run) dry=1 ;;
|
||||
--base) base="$2"; shift ;;
|
||||
*) echo "dispatch: unknown flag '$1'" >&2; return 2 ;;
|
||||
esac; shift
|
||||
done
|
||||
|
||||
# adapter must exist
|
||||
if ! declare -f "harness_$harness" >/dev/null 2>&1; then
|
||||
echo "no adapter for harness '$harness' — add harness_$harness() to .agents/harnesses.sh" >&2; return 2
|
||||
fi
|
||||
if [ "$dry" != 1 ] && declare -f harness_disabled_reason >/dev/null 2>&1; then
|
||||
local disabled_reason
|
||||
if disabled_reason="$(harness_disabled_reason "$harness")"; then
|
||||
echo "harness '$harness' is disabled for non-dry-run dispatch." >&2
|
||||
echo " $disabled_reason" >&2
|
||||
echo " Use --dry-run for prompt inspection, or dispatch with --harness codex/cursor." >&2
|
||||
return 2
|
||||
fi
|
||||
fi
|
||||
|
||||
local repo_root title body slug branch wt prompt
|
||||
repo_root="$(git rev-parse --show-toplevel)" || return 1
|
||||
title="$(issue_title "$issue")" || { echo "issue #$issue not found on $REPO" >&2; return 1; }
|
||||
body="$(issue_body "$issue")"
|
||||
slug="$(_slug "$title")"
|
||||
branch="feat/issue-${issue}-${slug}"
|
||||
wt="$repo_root/.worktrees/issue-${issue}"
|
||||
prompt="$(mktemp "${TMPDIR:-/tmp}/boxbox-prompt-${issue}.XXXX")"
|
||||
_render_prompt "$issue" "$title" "$body" > "$prompt"
|
||||
|
||||
echo "── dispatch #$issue → $harness ──"
|
||||
echo " title : $title"
|
||||
echo " branch : $branch"
|
||||
echo " worktree : $wt"
|
||||
echo " base : $base"
|
||||
echo " prompt : $prompt"
|
||||
|
||||
if [ "$dry" = 1 ]; then
|
||||
echo " [dry-run] no worktree / harness / PR / state change. Prompt preview:"
|
||||
sed 's/^/ | /' "$prompt"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# preflight: warn (don't block) if not Ready
|
||||
local stage; stage="$(get_field "$issue" Stage)"
|
||||
[ "$stage" = "Ready" ] || echo " ⚠ Stage is '$stage' (not Ready) — dispatching anyway"
|
||||
|
||||
# isolated worktree
|
||||
if [ -d "$wt" ]; then
|
||||
echo " worktree exists — reusing"
|
||||
else
|
||||
git -C "$repo_root" worktree add -b "$branch" "$wt" "$base" || return 1
|
||||
fi
|
||||
|
||||
set_stage "$issue" "In Progress"
|
||||
|
||||
echo " running $harness (headless)…"
|
||||
( harness_"$harness" "$wt" "$prompt" ); local hrc=$?
|
||||
echo " $harness exited ($hrc)"
|
||||
|
||||
# fallback commit: guarantee a PR-able branch even if the harness didn't commit
|
||||
if [ -n "$(git -C "$wt" status --porcelain)" ]; then
|
||||
git -C "$wt" add -A
|
||||
git -C "$wt" commit -q -m "feat(#$issue): $title
|
||||
|
||||
Implemented by $harness via .agents/dev dispatch." && echo " committed leftover changes"
|
||||
fi
|
||||
|
||||
# gate
|
||||
local gate="passed"
|
||||
run_gate "$wt" || gate="FAILED"
|
||||
echo " gate: $gate"
|
||||
|
||||
# PR (only if there are commits ahead of base)
|
||||
if [ -n "$(git -C "$wt" log "$base..$branch" --oneline 2>/dev/null)" ]; then
|
||||
git -C "$wt" push -u origin "$branch" || { echo " push failed — inspect $wt" >&2; return 1; }
|
||||
local draft=""; [ "$gate" = "FAILED" ] && draft="--draft"
|
||||
local pr
|
||||
pr="$(gh pr create -R "$REPO" --head "$branch" --base "$base" $draft \
|
||||
--title "$title (#$issue)" --body "$(_pr_body "$issue" "$harness" "$gate")")" || { echo " gh pr create failed" >&2; return 1; }
|
||||
echo " PR: $pr${draft:+ (draft — gate failed)}"
|
||||
set_stage "$issue" "In Review"
|
||||
else
|
||||
echo " no commits on $branch — leaving Stage 'In Progress'. Inspect the worktree: $wt" >&2
|
||||
fi
|
||||
}
|
||||
68
.agents/lib/gh.sh
Normal file
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# .agents/lib/gh.sh — harness-agnostic helpers for the box-box agentic dev lifecycle.
|
||||
#
|
||||
# Source it, then call the functions:
|
||||
# source .agents/lib/gh.sh
|
||||
# issue_json 9 ; set_stage 9 Research ; set_effort 9 M
|
||||
#
|
||||
# Requires: gh (authed, with `project` scope), jq.
|
||||
# Config is overridable via env vars.
|
||||
|
||||
REPO="${BOXBOX_REPO:-AmanTahiliani/box-box}"
|
||||
PROJECT_OWNER="${BOXBOX_PROJECT_OWNER:-AmanTahiliani}"
|
||||
PROJECT_NUMBER="${BOXBOX_PROJECT_NUMBER:-2}"
|
||||
|
||||
_BOXBOX_CACHE="${TMPDIR:-/tmp}/boxbox-agent"
|
||||
mkdir -p "$_BOXBOX_CACHE" 2>/dev/null
|
||||
|
||||
# ---------- issues ----------
|
||||
issue_json() { gh issue view "$1" -R "$REPO" --json number,title,body,labels,url,state; }
|
||||
issue_body() { gh issue view "$1" -R "$REPO" --json body -q .body; }
|
||||
issue_title() { gh issue view "$1" -R "$REPO" --json title -q .title; }
|
||||
issue_url() { gh issue view "$1" -R "$REPO" --json url -q .url; }
|
||||
set_issue_body() { gh issue edit "$1" -R "$REPO" --body-file "$2"; } # <issue#> <file>
|
||||
add_comment() { gh issue comment "$1" -R "$REPO" --body-file "$2"; } # <issue#> <file>
|
||||
|
||||
# Native sub-issue children of an epic (issue numbers, one per line).
|
||||
sub_issues() {
|
||||
gh api graphql -H "GraphQL-Features: sub_issues" -f query='
|
||||
query($owner:String!,$repo:String!,$num:Int!){
|
||||
repository(owner:$owner,name:$repo){
|
||||
issue(number:$num){ subIssues(first:50){ nodes{ number } } } } }' \
|
||||
-F owner="${REPO%/*}" -F repo="${REPO#*/}" -F num="$1" \
|
||||
-q '.data.repository.issue.subIssues.nodes[].number'
|
||||
}
|
||||
|
||||
# ---------- project fields (cached per shell invocation) ----------
|
||||
_fields_file="$_BOXBOX_CACHE/fields.json"
|
||||
_items_file="$_BOXBOX_CACHE/items.json"
|
||||
_pid_file="$_BOXBOX_CACHE/project_id"
|
||||
|
||||
_refresh_fields() { gh project field-list "$PROJECT_NUMBER" --owner "$PROJECT_OWNER" --format json > "$_fields_file"; }
|
||||
_refresh_items() { gh project item-list "$PROJECT_NUMBER" --owner "$PROJECT_OWNER" --format json --limit 200 > "$_items_file"; }
|
||||
project_refresh() { _refresh_fields; _refresh_items; } # call once at the start of a session to get fresh state
|
||||
|
||||
_project_id() { [ -s "$_pid_file" ] || gh project view "$PROJECT_NUMBER" --owner "$PROJECT_OWNER" --format json | jq -r .id > "$_pid_file"; cat "$_pid_file"; }
|
||||
_field_id() { [ -s "$_fields_file" ] || _refresh_fields; jq -r --arg n "$1" '.fields[]|select(.name==$n)|.id' "$_fields_file"; }
|
||||
_option_id() { [ -s "$_fields_file" ] || _refresh_fields; jq -r --arg f "$1" --arg o "$2" '.fields[]|select(.name==$f)|.options[]?|select(.name==$o)|.id' "$_fields_file"; }
|
||||
_item_id() { [ -s "$_items_file" ] || _refresh_items; jq -r --arg n "$1" '.items[]|select(.content.number==($n|tonumber))|.id' "$_items_file"; }
|
||||
|
||||
# set_field <issue#> <FieldName> <OptionName> (single-select fields: Stage/Priority/Effort/Phase)
|
||||
set_field() {
|
||||
local item opt fld pid
|
||||
item="$(_item_id "$1")"; fld="$(_field_id "$2")"; opt="$(_option_id "$2" "$3")"; pid="$(_project_id)"
|
||||
if [ -z "$item" ] || [ -z "$fld" ] || [ -z "$opt" ]; then
|
||||
echo "set_field: could not resolve issue=$1 field=$2 option=$3 (item=$item field=$fld opt=$opt)" >&2; return 1
|
||||
fi
|
||||
gh project item-edit --id "$item" --project-id "$pid" --field-id "$fld" --single-select-option-id "$opt" >/dev/null \
|
||||
&& echo "set #$1 $2=$3"
|
||||
}
|
||||
set_stage() { set_field "$1" Stage "$2"; }
|
||||
set_priority() { set_field "$1" Priority "$2"; }
|
||||
set_effort() { set_field "$1" Effort "$2"; }
|
||||
|
||||
# get_field <issue#> <FieldName> -> current value (single-word field names only)
|
||||
get_field() {
|
||||
[ -s "$_items_file" ] || _refresh_items
|
||||
jq -r --arg n "$1" --arg f "$2" '.items[]|select(.content.number==($n|tonumber))|.[($f|ascii_downcase)] // "-"' "$_items_file"
|
||||
}
|
||||
35
.agents/personas/architect.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Lens overlay: Architect
|
||||
|
||||
Apply this **on top of** the base grill (`grill.md`). Bias every question toward
|
||||
technical soundness and fit with the existing box-box architecture.
|
||||
|
||||
## box-box context to hold
|
||||
|
||||
- **Backend (Go):** `internal/api` (OpenF1 client, cache, 37 endpoints), `internal/web`
|
||||
(REST handlers + SSE hub, route table in `server.go`), `internal/store` (domain
|
||||
SQLite), `internal/query` (read models over the domain DB), `internal/ingest`,
|
||||
`internal/live` (SignalR).
|
||||
- **Frontend (React+Vite+TS):** TanStack Router/Query, `src/api.ts` (typed fetchers),
|
||||
`src/types.ts` (payload mirrors), `src/lib` (client helpers), `src/pages`,
|
||||
`src/components` (incl. `components/live`).
|
||||
- **Patterns to respect** (see CLAUDE.md "How To Extend"): ServeMux longest-prefix
|
||||
route ordering in `server.go`, cache TTL tiers, `?source=openf1|local|auto`
|
||||
resolution, two-phase standings load, lazy tab loads, stale-data fallback banner.
|
||||
|
||||
## Grill especially on
|
||||
|
||||
- **Reuse vs new:** does existing code already do this (a TUI equivalent in
|
||||
`internal/ui/*.go`, a query model, an `api.ts` fetcher)? Port vs rebuild.
|
||||
- **Data flow & source:** OpenF1 live vs domain DB vs cache; payload size; rate
|
||||
limits; how `?source` is handled.
|
||||
- **Seams:** which files/modules change; new endpoint (mind registration order!) vs
|
||||
extend an existing one; new component vs extend; where shared logic lives
|
||||
(`frontend/src/lib/*`).
|
||||
- **Testability:** how does this land in `go test` / `vitest` / hermetic Playwright?
|
||||
What seam makes it testable without live OpenF1?
|
||||
- **Risk:** domain-DB migrations, perf on large sessions, backward compat, and
|
||||
failure / stale-data behavior.
|
||||
|
||||
Keep questions concrete and decision-shaped — e.g. *"port the GPS normalization from
|
||||
`internal/ui/trackmap.go`, or recompute in a shared `frontend/src/lib/trackmap.ts` so
|
||||
it's unit-testable?"* — each with your recommendation.
|
||||
51
.agents/personas/grill.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Persona: The Grill
|
||||
|
||||
You run a **grill-me** session. Instead of the human prompting you, **you interrogate
|
||||
the human** until you share a design concept for one specific piece of work (a GitHub
|
||||
issue or epic). The shared understanding — not the document — is the real output.
|
||||
|
||||
## Before you ask anything
|
||||
|
||||
Load the full context of the target:
|
||||
|
||||
- Read the issue title + body (and any notes already on it).
|
||||
- Read `CLAUDE.md`.
|
||||
- Explore the code paths the work implicates.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **One question at a time.** Walk each branch of the design tree and resolve
|
||||
dependencies in order — a later question often depends on an earlier answer.
|
||||
2. **Recommend, consequence-first.** Every question carries your recommended answer
|
||||
and a short "why". **Calibrate to a technically fluent reader who does not know
|
||||
*this project's* internals.** Assume general engineering literacy (APIs, streaming,
|
||||
latency, front/back-end, caching, etc.) and don't explain those. **Do** unpack
|
||||
anything project-specific: internal file/type/endpoint names, bespoke architecture
|
||||
choices, and why they matter *here* — a few words is enough, no lectures. Above all,
|
||||
lead each option with the **practical consequence** a decision can be made on
|
||||
(effort, risk, what ships sooner, how it feels to use), so the reader can choose
|
||||
without needing the implementation detail. Recommendation first, with why it's the
|
||||
better call **for them**.
|
||||
- *Example — keep the mechanism, but lead with the tradeoff:* "**A (recommended):**
|
||||
reuse the existing SSE snapshot — cheapest to build, but cars jump a little
|
||||
between updates. **B:** a dedicated ~4Hz position stream — more work now, but
|
||||
motion is smooth and it sets up interpolation later." (Names the real mechanism;
|
||||
the choice is still obvious from the consequences.)
|
||||
3. **Hybrid asking.**
|
||||
- Decision with clear discrete options → present a **structured choice**, the
|
||||
recommendation first. *(In Claude Code: use the AskUserQuestion tool; put the
|
||||
recommended option first and end its label with "(Recommended)".)* Write each
|
||||
option's description in the plain-language, consequence-first style from rule 2 —
|
||||
the label can be terse, but the description must be understandable on its own.
|
||||
- Genuinely open-ended → ask in **prose**.
|
||||
4. **Explore before you ask.** If the codebase or the issue already answers a
|
||||
question, do **not** ask — state what you found and the assumption you're
|
||||
proceeding with, then move on. Only ask about real forks the human must decide.
|
||||
5. **Stay in scope.** Grill the design of *this* work, not the whole app. Note
|
||||
out-of-scope temptations instead of chasing them.
|
||||
|
||||
## Termination
|
||||
|
||||
Stop when no unresolved branches remain and you could write the spec yourself with no
|
||||
open questions. Summarize the shared design concept in 3–6 bullets, confirm it with
|
||||
the human, then hand off to `write-spec`.
|
||||
21
.agents/prompts/implement.md
Normal file
@@ -0,0 +1,21 @@
|
||||
You are an autonomous coding agent working in an **isolated git worktree** on the
|
||||
**box-box** repo. Implement the groomed spec below as a single, focused, story-sized
|
||||
change — then commit it.
|
||||
|
||||
## Ground rules
|
||||
- Read `AGENTS.md` / `CLAUDE.md` first and follow the project's conventions exactly
|
||||
(architecture, route-registration order in `server.go`, cache TTL tiers,
|
||||
`api.ts`/`types.ts` mirrors, test layout).
|
||||
- Implement ONLY this story's scope. Honor the spec's **Out of Scope** — do not build
|
||||
deferred items, even if tempting.
|
||||
- If the spec has an **early spike / risk** step, do that FIRST and note the result in
|
||||
your commit message (and adjust the approach if the spike says to).
|
||||
- Add or extend tests per the **Test Plan**. Make the relevant suites pass:
|
||||
`go build ./...`, `go test ./...`, and in `frontend/`: `npm run test`, `tsc --noEmit`.
|
||||
- Keep the change reviewable and story-sized. **Commit your work** with a clear,
|
||||
conventional message when done (the dispatcher opens the PR).
|
||||
- Satisfy every item in the spec's **Definition of Done**.
|
||||
|
||||
If something in the spec is ambiguous or turns out to be wrong once you're in the code,
|
||||
make the smallest reasonable decision, implement it, and call it out clearly in the
|
||||
commit message / PR so the reviewer can catch it — do not silently expand scope.
|
||||
27
.agents/prompts/ready-spec.md
Normal file
@@ -0,0 +1,27 @@
|
||||
## Context
|
||||
{one paragraph: the problem and why it matters, grounded in the grooming}
|
||||
|
||||
## Acceptance Criteria
|
||||
- [ ] {observable behaviour 1}
|
||||
- [ ] {observable behaviour 2}
|
||||
|
||||
## Technical Approach
|
||||
- **Files to touch:** {real paths}
|
||||
- **Data source:** {OpenF1 live | domain DB | cache | ...}
|
||||
- **Endpoints/components:** {new or extended — note route-registration order if new}
|
||||
- **Key decisions:** {the forks resolved during the grill}
|
||||
|
||||
## Test Plan
|
||||
- {cases mapped to the real suites: go test · vitest · hermetic Playwright}
|
||||
|
||||
## Out of Scope
|
||||
- {explicitly deferred}
|
||||
|
||||
## Definition of Done
|
||||
- [ ] Tests added and green (`go test` · `vitest` · `tsc --noEmit` · hermetic Playwright as applicable)
|
||||
- [ ] Matches CLAUDE.md conventions (route order, cache TTLs, `api.ts`/`types.ts` mirrors)
|
||||
- [ ] No console / preview errors (UI verified in preview)
|
||||
- [ ] Story-sized PR, linked to this issue
|
||||
|
||||
---
|
||||
_Groomed {date} · Effort {S|M|L} · Priority {P0|P1|P2} · via /groom_
|
||||
20
.agents/prompts/review.md
Normal file
@@ -0,0 +1,20 @@
|
||||
You are an independent reviewer for a box-box pull request. Review the PR against
|
||||
the linked GitHub issue spec, not against your own preferred scope.
|
||||
|
||||
## Ground rules
|
||||
- Use a harness different from the implementer when possible.
|
||||
- Read `AGENTS.md` / `CLAUDE.md`, the PR body/diff, and the linked issue body.
|
||||
- Run the relevant local gates and capture logs under `.review/issue-<n>-pr-<pr>/logs`.
|
||||
- For UI changes, create a local visual packet under `.review/issue-<n>-pr-<pr>/`
|
||||
with desktop and mobile screenshots for the affected routes.
|
||||
- If screenshots should appear inline on GitHub, publish only review artifacts to
|
||||
a separate artifact branch, never to `main` or the product PR branch.
|
||||
- Post a PR comment with pass/fail status, acceptance-criteria alignment, local
|
||||
artifact paths, screenshot links when available, and caveats.
|
||||
- Do not merge. The human owns the merge gate.
|
||||
|
||||
## Output
|
||||
- A local packet with `summary.md`, optional `index.html`, screenshots, logs, and
|
||||
any visual diffs.
|
||||
- A GitHub PR comment that makes the review visually scannable.
|
||||
- A clear recommendation: pass, pass with caveats, or needs changes.
|
||||
42
.agents/skills/groom/SKILL.md
Normal file
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: groom
|
||||
description: 'Groom a box-box GitHub issue into a Ready spec via a seeded grill-me interrogation. Use when the user asks to groom an issue, for example "/groom <issue-number>" or "$groom <issue-number>" with optional "--lens architect". Single-issue path: asks targeted questions, writes a structured spec into the issue body, sets Effort/Priority, and leaves Stage at Research for approval.'
|
||||
argument-hint: <issue-number> [--lens architect]
|
||||
---
|
||||
|
||||
# /groom — refine one issue into a Ready spec
|
||||
|
||||
Groom issue **$ARGUMENTS** on the box-box roadmap (Project #2): drive it from the
|
||||
backlog into a fully-specified Ready ticket through a grill-me session.
|
||||
|
||||
## 0. Setup
|
||||
- Parse the first token of the arguments as the **issue number**. An optional
|
||||
`--lens <name>` pulls in a lens overlay (currently: `architect`).
|
||||
- Run: `source .agents/lib/gh.sh && project_refresh` (fresh field/item state).
|
||||
- Load context **before asking anything**: `issue_json <n>`, read `CLAUDE.md`, and
|
||||
explore the code paths the issue implicates.
|
||||
- Move it into grooming if it isn't already there: `set_stage <n> Research`.
|
||||
|
||||
## 1. Grill
|
||||
- Read `.agents/personas/grill.md`. If `--lens <name>` was given, also read
|
||||
`.agents/personas/<name>.md` and apply it on top.
|
||||
- Run the grill exactly per those rules: **one question at a time**, recommendation
|
||||
first, **hybrid** asking (AskUserQuestion for discrete decisions with the
|
||||
recommended option first and labelled "(Recommended)"; prose for open-ended), and
|
||||
**explore the code to self-answer** wherever possible — only ask about genuine forks.
|
||||
- Track the resolved decisions as you go.
|
||||
|
||||
## 2. Synthesize
|
||||
- When no open branches remain, summarize the shared design concept in 3–6 bullets and
|
||||
confirm it with the user.
|
||||
- Then invoke the **write-spec** skill for issue `<n>`, handing it the resolved
|
||||
decisions, so it renders `.agents/prompts/ready-spec.md` into the issue body and
|
||||
sets Effort + Priority.
|
||||
|
||||
## 3. Hand back (human gate)
|
||||
- Do **not** auto-advance to Ready — that's the user's call. Report that the spec is
|
||||
written, Stage is `Research`, and they should review the issue and flip Stage →
|
||||
`Ready` when satisfied (`set_stage <n> Ready`).
|
||||
- Print the issue URL (`issue_url <n>`).
|
||||
|
||||
Stay focused on THIS issue's design throughout. Note but don't chase out-of-scope ideas.
|
||||
32
.agents/skills/implement/SKILL.md
Normal file
@@ -0,0 +1,32 @@
|
||||
---
|
||||
name: implement
|
||||
description: 'Dispatch a Ready box-box issue to a coding harness (claude/codex/opencode/pi/cursor) in an isolated git worktree, run the build gate, and open a PR. Use when supervising implementation via "/implement <issue-number> --harness <name> [--dry-run]" or from any harness terminal with .agents/bin/dev.'
|
||||
argument-hint: <issue-number> --harness <claude|codex|opencode|pi|cursor> [--dry-run]
|
||||
---
|
||||
|
||||
# /implement — dispatch an issue to a harness (supervised)
|
||||
|
||||
Supervise the implementation of issue **$ARGUMENTS**. You are SUPERVISING, not coding —
|
||||
a fresh harness does the work in its own isolated worktree with clean context. Do not
|
||||
edit project files yourself.
|
||||
|
||||
## Steps
|
||||
1. Parse: `<issue-number> --harness <name> [--dry-run] [--base <branch>]`.
|
||||
2. **Preflight (report, don't hard-block):** `source .agents/lib/gh.sh` and check
|
||||
`get_field <n> Stage` is `Ready` and the issue body has an "## Acceptance Criteria"
|
||||
section (a groomed spec). If it's not Ready or has no spec, say so and recommend
|
||||
`/groom <n>` first — proceed only if the user confirms.
|
||||
3. **Dispatch:** run `.agents/bin/dev implement <n> --harness <name> [flags]`. For a
|
||||
first run against an unfamiliar harness, suggest `--dry-run` first so the user can
|
||||
eyeball the prompt.
|
||||
4. **Report the outcome:** branch, worktree path, gate result (pass/FAILED → draft PR),
|
||||
and the PR URL. On success, Stage will be `In Review`.
|
||||
5. If no PR was created (no changes, or push failed), surface exactly why and point at
|
||||
the worktree (`.worktrees/issue-<n>`) so the user can inspect. Diagnose from the
|
||||
dispatcher output; recommend a fix or re-run — don't silently take over the coding.
|
||||
|
||||
## Notes
|
||||
- The harness adapters and the gate live in `.agents/harnesses.sh` — the single place
|
||||
to tune per-tool flags.
|
||||
- From any harness shell, run the same thing directly:
|
||||
`.agents/bin/dev implement <n> --harness <name>`.
|
||||
22
.agents/skills/lens-architect/SKILL.md
Normal file
@@ -0,0 +1,22 @@
|
||||
---
|
||||
name: lens-architect
|
||||
description: 'Grill/analyze a box-box issue or epic from a software-architecture perspective and post the findings as a comment. Use standalone as "/lens-architect <issue-number>" for an on-the-fly architecture review, or let /groom compose it via "--lens architect". Reads the base grill + architect persona and focuses on reuse, data flow, seams, testability, and risk.'
|
||||
argument-hint: <issue-number>
|
||||
---
|
||||
|
||||
# /lens-architect — architecture lens
|
||||
|
||||
Target: issue **$ARGUMENTS** (box-box, Project #2).
|
||||
|
||||
1. `source .agents/lib/gh.sh`; load context (`issue_json <n>`, `CLAUDE.md`, and the
|
||||
relevant code paths).
|
||||
2. Read `.agents/personas/grill.md` + `.agents/personas/architect.md` and run a focused
|
||||
grill from the architecture lens: hybrid asking (AskUserQuestion for discrete
|
||||
decisions, recommendation first; prose otherwise), recommend every answer, and
|
||||
explore the code to self-answer before asking.
|
||||
3. When aligned, write an **"## Architecture review"** summary (decisions taken,
|
||||
files/seams affected, risks, the test seam) to a temp file and `add_comment <n> <file>`.
|
||||
4. Print the issue URL.
|
||||
|
||||
If invoked from **within /groom**, skip the comment — instead return the architecture
|
||||
decisions inline so groom can fold them into the spec.
|
||||
53
.agents/skills/review/SKILL.md
Normal file
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: review
|
||||
description: 'Locally review a box-box PR against its linked GitHub issue spec, run tests, capture visual screenshots when applicable, create a .review packet, and post a GitHub PR comment. Use when a ticket implementation is ready for independent local review before the human merge gate.'
|
||||
argument-hint: <pr-number> [--harness <name>] [--publish-screenshots]
|
||||
---
|
||||
|
||||
# /review — local independent PR review
|
||||
|
||||
Review PR **$ARGUMENTS** for box-box using the local-only lifecycle. You are
|
||||
reviewing, not implementing. Do not merge the PR.
|
||||
|
||||
## 0. Setup
|
||||
- Parse the PR number. Optional `--harness <name>` records which reviewer harness is
|
||||
acting; optional `--publish-screenshots` allows pushing visual artifacts to a
|
||||
dedicated artifact branch.
|
||||
- Read `.agents/prompts/review.md`, `AGENTS.md`, the PR metadata/diff, and the linked
|
||||
issue body.
|
||||
- Identify the implementer harness from the PR body when present. If it matches the
|
||||
reviewer harness, call that out as a reduced independence caveat.
|
||||
- Create `.review/issue-<issue>-pr-<pr>/logs`, `screenshots`, and `artifacts`.
|
||||
|
||||
## 1. Verify
|
||||
- Run the smallest meaningful gates first, then broaden based on risk:
|
||||
`go test` for touched Go packages, `npm run test` and `npm run build` for frontend
|
||||
changes, and hermetic Playwright when user-facing routes changed.
|
||||
- Save all command output to `.review/issue-<issue>-pr-<pr>/logs`.
|
||||
- Inspect the diff for spec conformance, scope leaks, missing tests, and known project
|
||||
conventions from `AGENTS.md`.
|
||||
|
||||
## 2. Visual Packet
|
||||
- If the PR changes UI, start a local seeded or mocked preview and capture desktop and
|
||||
mobile screenshots for affected routes.
|
||||
- Prefer hermetic mocks/seeded data over live external state.
|
||||
- Save screenshots under `.review/issue-<issue>-pr-<pr>/screenshots`.
|
||||
- Create a concise `summary.md`; create `index.html` when screenshots exist.
|
||||
|
||||
## 3. Publish
|
||||
- If `--publish-screenshots` is present, publish only review artifacts to a dedicated
|
||||
branch such as `review-artifacts/pr-<pr>/` and use raw GitHub URLs in the comment.
|
||||
- Post a PR comment with:
|
||||
- reviewer harness and implementer harness
|
||||
- result: pass, pass with caveats, or needs changes
|
||||
- local packet path
|
||||
- gates run and results
|
||||
- acceptance-criteria checklist
|
||||
- screenshots or artifact links when available
|
||||
- caveats that the human must inspect
|
||||
- If the result is pass/pass-with-caveats, set the linked issue's custom Project
|
||||
`Stage` to `In Review` using `.agents/lib/gh.sh`. Do not set `Done`.
|
||||
|
||||
## 4. Hand Back
|
||||
- Tell the human exactly what to open locally and what decision remains theirs.
|
||||
- Do not merge or delete worktrees.
|
||||
30
.agents/skills/write-spec/SKILL.md
Normal file
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: write-spec
|
||||
description: 'Render a groomed design into the box-box Ready-spec template and write it into a GitHub issue body, then set Effort and Priority. Called by /groom after a grill session, or run standalone as "/write-spec <issue-number>" to (re)write an issue''s spec from agreed decisions. Does not change Stage.'
|
||||
argument-hint: <issue-number>
|
||||
---
|
||||
|
||||
# /write-spec — write the Ready spec into an issue
|
||||
|
||||
Target issue: **$ARGUMENTS** (box-box, Project #2).
|
||||
|
||||
## Steps
|
||||
1. `source .agents/lib/gh.sh`
|
||||
2. Gather the agreed design decisions: from the current grooming conversation if one
|
||||
is in progress; otherwise ask the user for the key points, or read the issue and
|
||||
explore the code to draft them and confirm.
|
||||
3. Read `.agents/prompts/ready-spec.md` and fill every placeholder:
|
||||
- Concrete, **behavioural** acceptance criteria (checkboxes).
|
||||
- Technical approach grounded in **real files/paths** and the chosen data source.
|
||||
- Test plan mapped to the actual suites (`go test` · `vitest` · hermetic Playwright).
|
||||
- Explicit out-of-scope.
|
||||
- Keep the Definition of Done checklist verbatim.
|
||||
- Stamp the footer: date (from the current-date context), Effort (S/M/L),
|
||||
Priority (P0–P2).
|
||||
4. Write it into the issue body: save the filled template to a temp file under the
|
||||
scratchpad and `set_issue_body <n> <file>`. The spec is the single source of truth —
|
||||
only preserve prior body text that captures decisions the spec doesn't.
|
||||
5. Set fields: `set_effort <n> <S|M|L>` and `set_priority <n> <P0|P1|P2>`.
|
||||
6. Print the issue URL and a one-line summary of what was written.
|
||||
|
||||
Do **not** change Stage — `/groom` owns state transitions.
|
||||
59
.agents/test/dispatch_disabled_harness_test.sh
Executable file
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
source "$ROOT/.agents/lib/dispatch.sh"
|
||||
|
||||
issue_title() { echo "Disable agy harness smoke"; }
|
||||
issue_body() { echo "## Spec"; echo; echo "Smoke prompt body"; }
|
||||
get_field() { echo "Ready"; }
|
||||
set_stage() { echo "unexpected set_stage $*" >&2; return 99; }
|
||||
run_gate() { echo "unexpected run_gate $*" >&2; return 99; }
|
||||
|
||||
unexpected_git_file="$(mktemp "${TMPDIR:-/tmp}/boxbox-agy-git.XXXX")"
|
||||
rm -f "$unexpected_git_file"
|
||||
git() {
|
||||
if [ "${1:-}" = "rev-parse" ]; then
|
||||
command git "$@"
|
||||
return
|
||||
fi
|
||||
echo "unexpected git $*" >&2
|
||||
touch "$unexpected_git_file"
|
||||
return 99
|
||||
}
|
||||
|
||||
set +e
|
||||
non_dry_output="$(dispatch 47 agy 2>&1)"
|
||||
non_dry_status=$?
|
||||
set -e
|
||||
|
||||
[ "$non_dry_status" -eq 2 ] || {
|
||||
echo "expected agy non-dry-run to exit 2, got $non_dry_status" >&2
|
||||
echo "$non_dry_output" >&2
|
||||
exit 1
|
||||
}
|
||||
[[ "$non_dry_output" == *"harness 'agy' is disabled"* ]] || {
|
||||
echo "expected disabled-harness message" >&2
|
||||
echo "$non_dry_output" >&2
|
||||
exit 1
|
||||
}
|
||||
[ ! -e "$unexpected_git_file" ] || {
|
||||
echo "agy non-dry-run reached git before failing" >&2
|
||||
echo "$non_dry_output" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
dry_output="$(dispatch 47 agy --dry-run 2>&1)"
|
||||
[[ "$dry_output" == *"[dry-run] no worktree / harness / PR / state change"* ]] || {
|
||||
echo "expected agy dry-run to render dispatch preview" >&2
|
||||
echo "$dry_output" >&2
|
||||
exit 1
|
||||
}
|
||||
[[ "$dry_output" == *"Smoke prompt body"* ]] || {
|
||||
echo "expected agy dry-run prompt body" >&2
|
||||
echo "$dry_output" >&2
|
||||
exit 1
|
||||
}
|
||||
1
.claude/skills
Symbolic link
@@ -0,0 +1 @@
|
||||
../.agents/skills
|
||||
9
.gitignore
vendored
@@ -22,7 +22,8 @@ frontend/node_modules/
|
||||
frontend/dist/
|
||||
|
||||
# Local Claude workspace settings
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills
|
||||
|
||||
# Playwright
|
||||
node_modules/
|
||||
@@ -31,3 +32,9 @@ node_modules/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
/playwright/.auth/
|
||||
|
||||
# agentic dev: isolated implementation worktrees
|
||||
.worktrees/
|
||||
|
||||
# agentic dev: local review packets
|
||||
.review/
|
||||
|
||||
88
CLAUDE.md
@@ -3,18 +3,31 @@
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
go build -o box-box ./cmd/main.go # Build binary
|
||||
go run cmd/main.go # Run directly
|
||||
go test ./... # All tests
|
||||
go build -o box-box ./cmd/main.go # Build binary
|
||||
go run cmd/main.go # Run TUI
|
||||
go run cmd/main.go --web --port 8080 # Run web server (default port 8080)
|
||||
go run cmd/main.go --ingest-year 2025 # Ingest a season into the domain DB (also: --ingest-meeting, --ingest-session, --ingest-news, --coverage)
|
||||
go test ./... # All Go tests
|
||||
go test -v ./internal/api # API integration tests (requires internet, rate-limit aware)
|
||||
OPENF1_API_KEY=key go run cmd/main.go # Run with paid tier (enables live session access)
|
||||
|
||||
# Frontend (run inside frontend/)
|
||||
npm run dev # Vite dev server on :5173, proxies /api to :8080 (override with BOXBOX_API_PORT)
|
||||
npm run build # tsc --noEmit && vite build -> frontend/dist
|
||||
npm run test # Vitest unit tests (frontend/src/test/); npm run test:watch for watch mode
|
||||
|
||||
# E2E / visual (run at repo root; Playwright auto-starts a seeded Go server + Vite dev server)
|
||||
npm run test:e2e # Playwright e2e (tests/*.spec.ts, playwright.config.ts)
|
||||
npm run test:visual # Visual snapshots (tests/visual/, playwright.visual.config.ts)
|
||||
npm run test:visual:update # Regenerate visual snapshots
|
||||
# :prod variants (test:e2e:prod, test:visual:prod) run against the *.prod.config.ts configs
|
||||
```
|
||||
|
||||
## Project Overview
|
||||
|
||||
**box-box** is an F1 Terminal UI (TUI) dashboard built in Go with Bubble Tea. It shows live timing, standings, race calendar, driver telemetry, track maps, and race replay — all sourced from the OpenF1 API.
|
||||
**box-box** is an F1 dashboard in Go with two frontends sharing the same data layer: a Bubble Tea TUI and a web app (`--web` flag) — a Go HTTP server in `internal/web/` serving a React SPA plus a REST/SSE API. It shows live timing, standings, race calendar, driver telemetry, track maps, and race replay — sourced from the OpenF1 API and a local domain SQLite DB filled by the ingestion CLI.
|
||||
|
||||
**Status**: Pre-beta, actively developed. All layers (API, models, UI) are fully implemented.
|
||||
**Status**: Pre-beta, actively developed.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
@@ -23,12 +36,15 @@ OPENF1_API_KEY=key go run cmd/main.go # Run with paid tier (enables live sessio
|
||||
- **Bubbles** — TUI components (spinner, viewport, table)
|
||||
- **OpenF1 API** — F1 data at `https://api.openf1.org`
|
||||
- **gorilla/websocket** — Official F1 SignalR live feed
|
||||
- **modernc.org/sqlite** — HTTP response caching with TTL
|
||||
- **modernc.org/sqlite** — HTTP response cache + domain DB
|
||||
- **React 18 + Vite + TypeScript** — Web frontend (`frontend/`), TanStack Router + TanStack Query
|
||||
- **Vitest + Testing Library** — Frontend unit tests; **Playwright** — e2e and visual tests (repo root)
|
||||
|
||||
## File Map
|
||||
|
||||
```
|
||||
cmd/main.go Entry point (package main). Inits client, launches TUI.
|
||||
cmd/main.go Entry point. Flags: --web/--port (web server), --ingest-* /
|
||||
--backfill-season/--coverage (ingestion CLI), --db. Default: TUI.
|
||||
|
||||
internal/api/
|
||||
client.go OpenF1Client: HTTP client, 15s timeout, optional Bearer auth
|
||||
@@ -56,6 +72,40 @@ internal/ui/
|
||||
battles.go Sub-view: Auto-detected on-track battles with gap sparkline
|
||||
pitwindow.go Sub-view: Pit stop rejoin position calculator
|
||||
replay.go Sub-view: Lap-by-lap race replay scrubber
|
||||
|
||||
internal/store/ Domain SQLite DB (~/.local/share/box-box/boxbox.db), season/session data
|
||||
internal/ingest/ OpenF1 -> domain DB ingestion (driven by cmd/main.go --ingest-* flags)
|
||||
internal/query/ Read models over the domain DB, used by web handlers
|
||||
internal/news/ RSS/Atom paddock briefing feed ingestion (--ingest-news)
|
||||
internal/live/ Shared F1 SignalR live feed client + LiveStreamData types
|
||||
|
||||
internal/web/
|
||||
server.go HTTP server: route table, CORS/logging middleware, SPA file server.
|
||||
Serves frontend/dist if found (walks up from cwd), else embedded assets/
|
||||
api.go REST handlers under /api/v1/ (results, laps, telemetry, championship
|
||||
hub aggregation, news + readability article extraction, ...)
|
||||
live.go SSEHub + SignalR bridge: relays official F1 feed to SSE subscribers
|
||||
racehub.go /api/v1/race-hub: per-session payload assembled from the domain DB
|
||||
navigation.go Local-first navigation: /api/v1/seasons, meetings, sessions, weekend
|
||||
source.go ?source=openf1|local|auto data-source resolution
|
||||
assets/ Embedded fallback SPA (legacy vanilla JS; used when no frontend/dist)
|
||||
|
||||
frontend/ React + Vite + TypeScript SPA
|
||||
src/main.tsx Entry: QueryClientProvider + RouterProvider
|
||||
src/router.tsx TanStack Router: / (command center), /race-hub, /live, /championship,
|
||||
/briefing, /data-library (also /admin alias)
|
||||
src/api.ts Typed fetch wrappers for /api/v1/ endpoints
|
||||
src/types.ts TypeScript mirrors of API payloads
|
||||
src/pages/ CommandCenterPage, RaceHubPage, LiveTimingPage, ChampionshipPage,
|
||||
BriefingPage, DataLibraryPage
|
||||
src/components/ Shared components (Nav, TabBar, race hub views, live/ timing tower)
|
||||
src/lib/ Client helpers: live SSE parsing, schedule, coverage, GP identity
|
||||
src/test/ Vitest + Testing Library unit tests
|
||||
|
||||
tests/ Playwright e2e specs; tests/visual/ visual snapshot specs
|
||||
playwright*.config.ts Dev/prod e2e + visual configs (webServer blocks seed a temp domain DB
|
||||
and start Go API + Vite automatically)
|
||||
scripts/seed-e2e-db/ Seeds the throwaway domain DB used by Playwright runs
|
||||
```
|
||||
|
||||
## Architecture
|
||||
@@ -66,6 +116,17 @@ Each tab is a sub-model with `Init()`, `Update(msg)`, `View()`. The root `AppMod
|
||||
|
||||
Async work (API calls, WebSocket) returns `tea.Cmd` that emits typed messages back to Update. Use `tea.Batch()` for parallel fetches.
|
||||
|
||||
### Web Layer
|
||||
|
||||
`box-box --web` starts an HTTP server (default `:8080`) with three surfaces:
|
||||
|
||||
- **REST API at `/api/v1/...`** — Handlers in `internal/web/api.go` wrap `OpenF1Client`; navigation/race-hub endpoints read the domain DB via `internal/query` (empty responses if the DB is missing). `?source=openf1|local|auto` picks the data source where supported. Register routes in `routes()` in `server.go` — Go ServeMux longest-prefix matching means more specific paths (e.g. `/api/v1/laps/comparison`) must be registered before their prefixes.
|
||||
- **SSE live stream** — `internal/web/live.go` runs a background SignalR connection to the official F1 feed (exponential-backoff reconnect; disabled with `BOXBOX_DISABLE_LIVE=1`). An `SSEHub` broadcasts snapshots to browsers on `/api/v1/live/stream`, with `/api/v1/live/state` for the initial snapshot and a 20s heartbeat. `LiveTimingPage.tsx` consumes it; parsing helpers live in `frontend/src/lib/live.ts`.
|
||||
- **Embedded SPA** — Static file server with SPA fallback to `index.html`. Prefers a `frontend/dist` directory found by walking up from cwd (so `npm run build` output is served without rebuilding Go); otherwise serves the legacy assets embedded via `//go:embed assets`.
|
||||
- **Championship hub** — `/api/v1/championship/hub` aggregates official standings with derived stats (wins, podiums, poles, last-5 form, teammate head-to-head) and per-round cumulative points, computed from all season race results.
|
||||
|
||||
Frontend dev loop: run `go run cmd/main.go --web` and `npm run dev` in `frontend/` — Vite proxies `/api` to the Go server.
|
||||
|
||||
### Key Patterns
|
||||
|
||||
- **Two-phase standings load**: `GetLatestDriverChampionship()` -> extract SessionKey -> `GetDriversForSession(sessionKey)` -> join by DriverNumber for names/colors
|
||||
@@ -104,13 +165,20 @@ Replay: `h`/`l` or arrows scrub laps
|
||||
- **New message type**: Define in `messages.go`, handle in relevant model's `Update()`
|
||||
- **New keybinding**: Define in `keys.go`, handle in relevant model's `Update()`
|
||||
- **New styles**: Add to `styles.go`, reference F1 palette constants
|
||||
- **New web page/route**: Create page in `frontend/src/pages/`, register route in `frontend/src/router.tsx`, add nav link in `frontend/src/components/Nav.tsx`, add fetchers to `src/api.ts` and payload types to `src/types.ts`, add a test in `frontend/src/test/`
|
||||
- **New web API endpoint**: Add handler in `internal/web/api.go` (or a new file in `internal/web/`), register it in `routes()` in `server.go` (mind prefix ordering), add a handler test alongside (see `championship_hub_test.go`)
|
||||
|
||||
## Testing
|
||||
|
||||
Tests in `openf1_test.go` hit the real OpenF1 API. They use `skipOnRateLimit(t, err)` to gracefully skip on HTTP 429. Require internet.
|
||||
- Go: tests in `openf1_test.go` hit the real OpenF1 API and use `skipOnRateLimit(t, err)` to skip on HTTP 429 (require internet). `internal/web` handler tests run offline.
|
||||
- Frontend: Vitest + Testing Library in `frontend/src/test/` (`npm run test` inside `frontend/`).
|
||||
- E2E/visual: Playwright at repo root (`npm run test:e2e`, `npm run test:visual`). Configs seed a temp domain DB and start the Go server with `BOXBOX_DISABLE_LIVE=1` and `BOXBOX_OPENF1_BASE_URL` pointed at an unreachable address (hermetic: no live OpenF1 dependency, date-stable) plus a Vite dev server — no manual setup needed.
|
||||
|
||||
## Environment
|
||||
|
||||
- `OPENF1_API_KEY` — Optional Bearer token for paid tier (live session WebSocket access)
|
||||
- Logs go to `box-box.log` in project root (prevents TUI pollution)
|
||||
- Cache at `~/.cache/box-box/cache.db` (SQLite WAL mode, auto-created)
|
||||
- `BOXBOX_DISABLE_LIVE=1` — Skip the background SignalR live feed in web mode (used by e2e)
|
||||
- `BOXBOX_OPENF1_BASE_URL` — Override the OpenF1 API root (default `https://api.openf1.org`; e2e sets an unreachable address for hermetic runs)
|
||||
- `BOXBOX_API_PORT` — Go API port that the Vite dev proxy targets (default 8080)
|
||||
- Logs: TUI writes `box-box.log` in project root; web/ingest modes log to stderr
|
||||
- HTTP cache at `~/.cache/box-box/cache.db`; domain DB at `~/.local/share/box-box/boxbox.db` (override with `--db`)
|
||||
|
||||
230
README.md
@@ -1,228 +1,66 @@
|
||||
# box-box
|
||||
|
||||
> "Box, box. Box, box." — Every F1 race engineer, ever.
|
||||
> "Box, box. Box, box." Every F1 race engineer, ever.
|
||||
|
||||
**box-box** is a Formula 1 dashboard in Go with two surfaces:
|
||||
**box-box** is an unofficial F1 race-weekend command center: live timing, Race Hub analytics, championship context, paddock briefing feeds, and local historical data in one Go + React app, with a preserved Bubble Tea TUI.
|
||||
|
||||
- **Web UI (primary)** — React + TypeScript SPA for Race Hub analytics, local data coverage, and live timing.
|
||||
- **TUI (preserved)** — Bubble Tea terminal app with standings, calendar, driver profiles, official live timing, track map, battles, pit window, and replay.
|
||||
Live demo: [box-box.amantahiliani.com](https://box-box.amantahiliani.com/)
|
||||
|
||||
Historical Web data is **local-first** in a SQLite domain database (ingested from OpenF1). **Live timing** uses the official F1 SignalR feed via the Go server; the React app reads `/api/v1/live/*`, not OpenF1 directly.
|
||||

|
||||
|
||||
For architecture, phase history, and design rationale, see [documentations/refactor/README.md](documentations/refactor/README.md).
|
||||
## What It Does
|
||||
|
||||
## How it fits together
|
||||
- **Command Center**: current race-weekend home with GP identity, live status, schedule, championship leaders, and direct analysis links.
|
||||
- **Race Hub**: session workspace for overview, race story, strategy, laps, weather, race control, and dataset coverage.
|
||||
- **Live Timing**: official F1 SignalR feed bridged through the Go server to the browser via SSE.
|
||||
- **Championship View**: standings, form, teammate context, cumulative points, and a simulator.
|
||||
- **Paddock Briefing**: RSS/Atom news ingestion for a local race-weekend briefing surface.
|
||||
- **Local-first history**: OpenF1 data ingested into a SQLite domain database for fast historical browsing.
|
||||
- **Terminal Mode**: Bubble Tea TUI with standings, calendar, driver profiles, live timing, track map, battles, pit window, and replay.
|
||||
|
||||
| Layer | Role |
|
||||
| --- | --- |
|
||||
| **OpenF1 REST** | Backfill and ingestion source; optional paid tier via `OPENF1_API_KEY`. Also powers the TUI’s on-demand reads and HTTP cache. |
|
||||
| **Domain SQLite** (`boxbox.db`) | Local store for meetings, sessions, Race Hub datasets, and navigation APIs used by the Web UI. |
|
||||
| **HTTP cache SQLite** (`cache.db`) | TTL cache for OpenF1 responses (TUI and legacy paths). Separate from the domain DB. |
|
||||
| **Official F1 SignalR** | Live timing bridge in `internal/live`, exposed to Web (SSE) and TUI. |
|
||||
| **Go server** | `cmd/main.go` — TUI, `--web` API + static SPA, or CLI ingestion. |
|
||||
| **React frontend** | `frontend/` — production build served from `frontend/dist` when present. |
|
||||
|
||||
The Web UI should call **local-first Go APIs** (`/api/v1/...`). Do not add direct OpenF1 reads in the frontend.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [Go](https://go.dev/doc/install) (see `go.mod` for the module version)
|
||||
- [Node.js](https://nodejs.org/) 18+ and npm (Web UI dev, unit tests, Playwright)
|
||||
- Internet for ingestion and TUI OpenF1 calls
|
||||
- For E2E / visual tests: `npx playwright install` (Chromium) after `npm install` at the repo root
|
||||
|
||||
## Install
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
git clone https://github.com/AmanTahiliani/box-box.git
|
||||
cd box-box
|
||||
|
||||
npm install # Playwright and repo-level test scripts
|
||||
npm install --prefix frontend # Vite + React app
|
||||
```
|
||||
npm install
|
||||
npm install --prefix frontend
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
go build -o box-box ./cmd/main.go
|
||||
npm run build --prefix frontend # writes frontend/dist (gitignored)
|
||||
```
|
||||
|
||||
## Run — TUI (default)
|
||||
|
||||
```bash
|
||||
go run ./cmd/main.go
|
||||
# or: ./box-box
|
||||
```
|
||||
|
||||
Logs go to `box-box.log` in the project directory so the terminal stays clean.
|
||||
|
||||
### TUI keybindings
|
||||
|
||||
| Key | Action |
|
||||
| --- | --- |
|
||||
| `1`–`7` | Home, Standings, Calendar, Race Detail, Drivers, Live, Track Map |
|
||||
| `tab` / `shift+tab` | Next / previous tab |
|
||||
| `j`/`k`, `enter`, `b`/`esc` | Navigate, select, back |
|
||||
| `s`, `b`, `p` | Live: sectors, battles, pit window |
|
||||
| `r` | Race replay (Race Detail, race sessions) |
|
||||
| `y` | Cycle season year |
|
||||
| `q` / `ctrl+c` | Quit |
|
||||
|
||||
## Run — Web (Go serves API + built React)
|
||||
|
||||
Build the frontend first, then start web mode. Go walks up from the cwd to find `frontend/dist/index.html`; if missing, it serves embedded legacy assets.
|
||||
|
||||
```bash
|
||||
npm run build --prefix frontend
|
||||
go run ./cmd/main.go --web
|
||||
# → http://localhost:8080
|
||||
# http://localhost:8080
|
||||
```
|
||||
|
||||
Use a specific domain database or port:
|
||||
For a local frontend development loop with seeded data, see [docs/getting-started.md](docs/getting-started.md).
|
||||
|
||||
```bash
|
||||
go run ./cmd/main.go --web --db ~/.local/share/box-box/boxbox.db --port 8080
|
||||
```
|
||||
## Project Shape
|
||||
|
||||
## Run — Web dev (Vite + Go API)
|
||||
|
||||
Vite proxies `/api` to the Go server. Set `BOXBOX_API_PORT` to match the Go `--port`.
|
||||
|
||||
**Terminal 1 — API (seeded DB is enough for UI work without ingesting):**
|
||||
|
||||
```bash
|
||||
go run ./scripts/seed-e2e-db/main.go --db /tmp/boxbox-dev.db
|
||||
BOXBOX_DISABLE_LIVE=1 go run ./cmd/main.go --web --db /tmp/boxbox-dev.db --port 18080
|
||||
```
|
||||
|
||||
**Terminal 2 — frontend:**
|
||||
|
||||
```bash
|
||||
BOXBOX_API_PORT=18080 npm run dev --prefix frontend
|
||||
# default Vite port 5173 → http://localhost:5173
|
||||
```
|
||||
|
||||
`BOXBOX_DISABLE_LIVE=1` skips starting the SignalR bridge (used in CI and local UI work).
|
||||
|
||||
## Web routes
|
||||
|
||||
| Route | Purpose |
|
||||
| Area | What lives there |
|
||||
| --- | --- |
|
||||
| `/` | **Command Center** — fan-facing race-weekend home with GP identity, live status, session schedule, and analysis links |
|
||||
| `/race-hub?session_key=<key>` | **Race Hub** — weekend workspace with session rail and Overview / Race Story / Strategy / Lap Data / Conditions / Race Control / Data Status tabs. Bare `/race-hub` auto-resolves to the focus session. |
|
||||
| `/admin` | **Admin / Data Health** — ingestion coverage, local data status, and suggested CLI commands |
|
||||
| `/data-library` | Legacy alias for Admin / Data Health |
|
||||
| `/live` | **Live Timing** — timing tower and race control via SSE when a session is live |
|
||||
| `cmd/main.go` | Entry point for TUI, web server, and ingestion CLI |
|
||||
| `internal/web/` | Go REST API, SSE live bridge, SPA serving |
|
||||
| `internal/live/` | Official F1 SignalR client shared by Web and TUI |
|
||||
| `internal/store/`, `internal/ingest/`, `internal/query/` | Local SQLite domain database, ingestion, and read models |
|
||||
| `internal/ui/` | Bubble Tea TUI |
|
||||
| `frontend/` | React + Vite + TypeScript web app |
|
||||
| `tests/` | Playwright e2e and visual coverage |
|
||||
|
||||
Example after seeding: `http://localhost:5173/race-hub?session_key=9472`
|
||||
The Web UI is local-first and should call the Go APIs under `/api/v1/...`; it should not read OpenF1 directly.
|
||||
|
||||
## Ingest historical data and briefing feeds
|
||||
## Documentation
|
||||
|
||||
Ingestion is a **CLI mode** on the same binary. Only one of `--ingest-year`, `--ingest-meeting`, `--ingest-session`, or `--ingest-news` may be set per run.
|
||||
- [Getting Started](docs/getting-started.md): install, build, run modes, TUI keybindings, and web routes.
|
||||
- [Data and Operations](docs/data-and-operations.md): ingestion, environment variables, local files, and live timing notes.
|
||||
- [Testing](docs/testing.md): Go, frontend, e2e, and visual regression commands.
|
||||
- [Architecture Notes](documentations/refactor/README.md): deeper design rationale, data-source decisions, and phase history.
|
||||
|
||||
```bash
|
||||
# Season: discover and store meeting metadata (2023+)
|
||||
go run ./cmd/main.go --ingest-year 2025
|
||||
## Status
|
||||
|
||||
# Full race weekend: all sessions + Race Hub datasets
|
||||
go run ./cmd/main.go --ingest-meeting 1229
|
||||
|
||||
# Single session only
|
||||
go run ./cmd/main.go --ingest-session 9472
|
||||
|
||||
# Preview without writing
|
||||
go run ./cmd/main.go --dry-run --ingest-meeting 1229
|
||||
|
||||
# Refresh Paddock Briefing RSS/Atom feeds
|
||||
go run ./cmd/main.go --ingest-news
|
||||
|
||||
# Custom DB path (default: ~/.local/share/box-box/boxbox.db)
|
||||
go run ./cmd/main.go --ingest-meeting 1229 --db /tmp/boxbox.db
|
||||
```
|
||||
|
||||
Use **`--ingest-meeting`** for a complete weekend. **`--ingest-year`** lists meetings for the season; ingest meetings individually or by weekend as needed. Optional analytics fetches may partially fail without aborting the whole run.
|
||||
|
||||
## `OPENF1_API_KEY`
|
||||
|
||||
```bash
|
||||
export OPENF1_API_KEY=your_key_here
|
||||
go run ./cmd/main.go --web
|
||||
```
|
||||
|
||||
Without a key, the free OpenF1 tier is used. A key may be required for paid-tier behavior (e.g. live session access during API lockouts). Ingestion and TUI calls use the same client.
|
||||
|
||||
## Local files
|
||||
|
||||
| Path | Purpose |
|
||||
| --- | --- |
|
||||
| `~/.local/share/box-box/boxbox.db` | Domain database (default `--db`) |
|
||||
| `~/.cache/box-box/cache.db` | OpenF1 HTTP response cache (TUI / client) |
|
||||
| `box-box.log` | TUI application log (project root) |
|
||||
| `frontend/dist/` | Production React build (**gitignored** — build locally, do not commit) |
|
||||
| `.playwright/*.db` | Seeded DBs for automated tests |
|
||||
|
||||
Web mode logs to **stderr**.
|
||||
|
||||
## Tests and QA
|
||||
|
||||
### Go (targeted packages)
|
||||
|
||||
```bash
|
||||
go test ./internal/live ./internal/models ./internal/store ./internal/ingest ./internal/query ./internal/web
|
||||
```
|
||||
|
||||
All packages: `go test ./...`
|
||||
|
||||
OpenF1 integration tests (network, rate-limit aware): `go test -v ./internal/api`
|
||||
|
||||
### Frontend unit tests and build
|
||||
|
||||
```bash
|
||||
npm --prefix frontend test -- --run
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
### E2E (Vite dev proxy + seeded API)
|
||||
|
||||
Starts seeded Go on port `18080` and Vite on `15173` (see `playwright.config.ts`).
|
||||
|
||||
```bash
|
||||
npx playwright install # first time only
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
### E2E production (Go serves `frontend/dist`)
|
||||
|
||||
```bash
|
||||
npm run test:e2e:prod
|
||||
```
|
||||
|
||||
### Visual regression (screenshots)
|
||||
|
||||
```bash
|
||||
npm run test:visual # dev proxy stack
|
||||
npm run test:visual:prod # production serving (canonical baselines)
|
||||
|
||||
# after intentional UI changes
|
||||
npm run test:visual:update
|
||||
npm run test:visual:prod:update
|
||||
```
|
||||
|
||||
Snapshots live under `tests/visual/__snapshots__/`.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **Live timing** only works when F1 is broadcasting timing data; there is no guaranteed live session for local dev.
|
||||
- **E2E / visual tests** use `BOXBOX_DISABLE_LIVE=1` and seeded SQLite — they do not exercise full SignalR live behavior.
|
||||
- **`frontend/dist`** is generated output; build before production web mode or `test:e2e:prod`.
|
||||
- **TUI historical views** still use OpenF1 on demand with the HTTP cache; the Web UI’s local-first model does not fully replace the TUI yet.
|
||||
- **`--ingest-year`** stores season meetings, not full session datasets — use `--ingest-meeting` or `--ingest-session` for Race Hub data.
|
||||
Pre-beta and actively developed. The Web UI is the primary surface; the TUI is preserved and still useful for terminal workflows. Live timing depends on F1 broadcasting timing data, so it is only fully active during live sessions.
|
||||
|
||||
## License
|
||||
|
||||
MIT © [Aman Tahiliani](https://github.com/AmanTahiliani)
|
||||
|
||||
---
|
||||
|
||||
*Unofficial project; not associated with Formula 1 or the FIA.*
|
||||
|
||||
58
cmd/main.go
@@ -27,6 +27,7 @@ func main() {
|
||||
ingestMeeting := flag.Int("ingest-meeting", 0, "Ingest meeting metadata and Race Hub datasets for all sessions")
|
||||
ingestSession := flag.Int("ingest-session", 0, "Ingest Race Hub datasets for a session key")
|
||||
ingestNews := flag.Bool("ingest-news", false, "Refresh RSS/Atom paddock briefing feeds")
|
||||
prefetchTrackOutlines := flag.Int("prefetch-track-outlines", 0, "Warm the web track-outline cache for a season year (for web-only hosts, run before --web so /api/v1/track-outline can serve live maps)")
|
||||
dryRun := flag.Bool("dry-run", false, "Preview ingestion without writing domain rows")
|
||||
force := flag.Bool("force", false, "Re-ingest datasets even if already tracked in the session_coverage table as completed")
|
||||
coverageYear := flag.Int("coverage", 0, "Show season coverage report for the given year")
|
||||
@@ -41,11 +42,19 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
// BOXBOX_OPENF1_BASE_URL overrides the upstream OpenF1 API root. E2E runs
|
||||
// point it at an unreachable address so tests stay hermetic and
|
||||
// deterministic regardless of wall-clock date or network state.
|
||||
baseURL := os.Getenv("BOXBOX_OPENF1_BASE_URL")
|
||||
if baseURL == "" {
|
||||
baseURL = "https://api.openf1.org"
|
||||
}
|
||||
|
||||
var client *api.OpenF1Client
|
||||
if apiKey := os.Getenv("OPENF1_API_KEY"); apiKey != "" {
|
||||
client = api.NewOpenF1ClientWithKey("https://api.openf1.org", 15*time.Second, apiKey)
|
||||
client = api.NewOpenF1ClientWithKey(baseURL, 15*time.Second, apiKey)
|
||||
} else {
|
||||
client = api.NewOpenF1Client("https://api.openf1.org", 15*time.Second)
|
||||
client = api.NewOpenF1Client(baseURL, 15*time.Second)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
@@ -68,11 +77,21 @@ func main() {
|
||||
if *ingestNews {
|
||||
ingestFlags++
|
||||
}
|
||||
if *prefetchTrackOutlines != 0 {
|
||||
ingestFlags++
|
||||
}
|
||||
if ingestFlags > 0 {
|
||||
if ingestFlags > 1 {
|
||||
fmt.Fprintln(os.Stderr, "box-box: only one of --ingest-year, --backfill-season, --ingest-meeting, --ingest-session, or --ingest-news may be set")
|
||||
fmt.Fprintln(os.Stderr, "box-box: only one of --ingest-year, --backfill-season, --ingest-meeting, --ingest-session, --ingest-news, or --prefetch-track-outlines may be set")
|
||||
os.Exit(1)
|
||||
}
|
||||
if *prefetchTrackOutlines != 0 {
|
||||
if err := runTrackOutlinePrefetch(client, *prefetchTrackOutlines); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "box-box track outline prefetch error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if *ingestNews {
|
||||
if err := runNewsIngestion(*dryRun, *dbPath); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "box-box ingest error: %v\n", err)
|
||||
@@ -80,7 +99,7 @@ func main() {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
yearVal := *ingestYear
|
||||
if *backfillSeason != 0 {
|
||||
yearVal = *backfillSeason
|
||||
@@ -166,6 +185,35 @@ func runIngestion(client *api.OpenF1Client, year, meetingKey, sessionKey int, fo
|
||||
return err
|
||||
}
|
||||
|
||||
func runTrackOutlinePrefetch(client *api.OpenF1Client, year int) error {
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
fmt.Fprintf(os.Stderr, "track outlines: warming HTTP cache %s for %d\n", api.DefaultCacheDBPath(), year)
|
||||
|
||||
meetings, err := client.GetMeetingsForYear(year)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch meetings for %d: %w", year, err)
|
||||
}
|
||||
|
||||
result := client.PrefetchTrackOutlinesForYear(year, meetings)
|
||||
fmt.Printf(
|
||||
"track outlines %d: cached %d/%d unique circuit(s) before, %d/%d after; %d skipped, %d fetched, %d failed\n",
|
||||
result.Year,
|
||||
result.CachedBefore,
|
||||
result.UniqueCircuits,
|
||||
result.CachedAfter,
|
||||
result.UniqueCircuits,
|
||||
result.Skipped,
|
||||
result.Fetched,
|
||||
result.Failed,
|
||||
)
|
||||
|
||||
if result.CachedAfter == 0 {
|
||||
return fmt.Errorf("cached zero track outlines for %d", year)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runNewsIngestion(dryRun bool, dbPath string) error {
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
@@ -267,7 +315,7 @@ func runCoverageReport(year int, dbPath string) error {
|
||||
}
|
||||
|
||||
fmt.Printf("\n--- Season %d Coverage Report ---\n\n", year)
|
||||
fmt.Printf("%-35s | %-5s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s\n",
|
||||
fmt.Printf("%-35s | %-5s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s\n",
|
||||
"Meeting / Session (Key)", "ID", "DR", "SR", "SG", "ST", "PS", "PO", "RC", "WE", "LA")
|
||||
fmt.Println(strings.Repeat("-", 82))
|
||||
|
||||
|
||||
198
docs/PRODUCT_ROADMAP.md
Normal file
@@ -0,0 +1,198 @@
|
||||
# box-box — Product & UX Roadmap
|
||||
|
||||
> An F1-geek + product/UX analysis of box-box as an F1 companion, and a
|
||||
> prioritized plan to make it richer than "data in tables" — for both live race
|
||||
> weekends and the quiet stretch between rounds.
|
||||
|
||||
## Where the app is today (honest read)
|
||||
|
||||
box-box has a strong data layer with two front doors (TUI + web) and six web
|
||||
surfaces:
|
||||
|
||||
| Surface | What it does today | Where it's thin |
|
||||
|---|---|---|
|
||||
| **Command Center** (`/`) | Hero weekend + countdown, season calendar, championship snapshot, weekend schedule, news | Strong launcher, but tells you *when*, rarely *what to care about*. It's a menu, not a companion |
|
||||
| **Race Hub** (`/race-hub`) | Per-session tabs: Overview, Race Story (position-evolution scrubber), Strategy (stints), Laps, Conditions, Race Control | `RaceStoryCanvas` is the best "beyond tables" work in the app. Everything else is still tables |
|
||||
| **Live Timing** (`/live`) | SSE timing tower, battle chips, gap sparklines, pinned drivers, RC feed | Solid tower, but it's "a spreadsheet that updates" — no track map, no telemetry, no "what just happened" |
|
||||
| **Championship** (`/championship`) | Standings + hub stats (wins/poles/form) + points simulator | Good; the simulator is a genuine differentiator |
|
||||
| **Briefing** (`/briefing`) | 7 RSS feeds (FIA, BBC, Autosport, RaceFans, Guardian, RACER, F1 YouTube) + readability extraction | Passive reading list, not tied to the season narrative |
|
||||
| **Data Library** (`/admin`) | Ingestion / coverage admin | Fine as-is |
|
||||
|
||||
**Biggest finding:** the app already *pulls* the richest data in F1 — GPS
|
||||
`Location`, full car telemetry (throttle / brake / DRS / gear / rpm / speed),
|
||||
team-radio audio, mini-sector `Segments`, speed traps, overtakes — and the web
|
||||
app visualizes almost none of it. The **track map exists only in the TUI**
|
||||
(`internal/ui/trackmap.go`); telemetry is fetched and shown to nobody. This is a
|
||||
large latent asset.
|
||||
|
||||
## Core product thesis
|
||||
|
||||
An F1 companion serves two different jobs; the app currently treats them the same
|
||||
(data, in tables, per session):
|
||||
|
||||
1. **On a race weekend — the "second screen."** The user is watching the
|
||||
broadcast (or can't, and wants to *feel* it). They want: what's happening now,
|
||||
why it matters, what to watch next. The broadcast supplies emotion; box-box
|
||||
should supply **the data the broadcast doesn't show** — the delta the director
|
||||
cut away from, the undercut developing, the tyre cliff approaching.
|
||||
|
||||
2. **Between races — "understand the season."** No live action. The user wants to
|
||||
make sense of what happened and anticipate what's next: rewatch the story of
|
||||
the last race, argue strategy, track the title fight, get smart before the next
|
||||
round.
|
||||
|
||||
Everything below makes each job *feel* like a companion instead of a database.
|
||||
|
||||
---
|
||||
|
||||
## Race-weekend experience ("second screen")
|
||||
|
||||
### 1. Live Track Map — highest-leverage missing feature
|
||||
Port the TUI's GPS outline (`trackmap.go`, `GetLocation`) to a web SVG dot-map:
|
||||
cars as team-colored dots on the circuit outline, DRS zones highlighted, sectors
|
||||
tinted by status. Turn mini-sectors purple/green live using the `Segments` data
|
||||
already fetched. Tap a car → mini-telemetry readout. This is what turns "updating
|
||||
spreadsheet" into "I'm watching the race."
|
||||
|
||||
### 2. "What just happened" synthesized event rail — the companion voice
|
||||
Combine Race Control + overtakes + pit stops + position deltas into plain-English
|
||||
beats: *"LAP 34 — VER pits (2.4s), rejoins P4 behind NOR — undercut on RUS is
|
||||
live."* The inputs all exist; this is a synthesis layer, not new data. It's the
|
||||
difference between *data* and *commentary*.
|
||||
|
||||
### 3. Telemetry compare overlay
|
||||
On the tower / a driver panel, pick two drivers → overlaid speed/throttle/brake
|
||||
traces + delta-time graph for their last comparable lap. *The* tifosi feature —
|
||||
"where did Leclerc lose the lap." `/api/v1/laps/comparison` + car data already
|
||||
exist; this needs a chart, not a table.
|
||||
|
||||
### 4. Live strategy / tyre-degradation view
|
||||
Stints + tyre age + pit-lane times → live pit window and tyre-cliff panel, with
|
||||
**undercut/overcut threat** indicators from gap-to-car-behind vs. pit-loss time.
|
||||
The pit-window calculator exists in the TUI (`pitwindow.go`); bring it to the web
|
||||
and make it live.
|
||||
|
||||
### 5. Team radio, surfaced
|
||||
`GetTeamRadio` returns audio clips. Add a "Radio" ticker on the live page — play
|
||||
button + driver + timestamp. Peak emotional content, and no rival dashboard has it
|
||||
inline.
|
||||
|
||||
### 6. Session-aware Command Center
|
||||
When a session is live, the home hero should pull the top battles, leader gap, and
|
||||
last RC flag onto the front page instead of only saying "LIVE." Make the front
|
||||
page reactive to the moment.
|
||||
|
||||
---
|
||||
|
||||
## Between-races experience ("understand the season")
|
||||
|
||||
### 7. Race replay as a first-class story
|
||||
Grow `RaceStoryCanvas` from a scrubber into a narrative replay: auto-generated
|
||||
"chapters" (start, first pit phase, VSC, decisive overtake, finish) with a
|
||||
headline each (derived from RC + position swings), and scrub the position graph
|
||||
and track map together. The "watch the race in 90 seconds" mode that makes people
|
||||
open the app on a Tuesday.
|
||||
|
||||
### 8. Driver pages + rivalry view (a real gap)
|
||||
No driver profile exists in the web app. Add a **driver page** (season form,
|
||||
teammate H2H — already computed in the champ hub — quali vs. race pace, tyre
|
||||
management, track-by-track) and a **rivalry view** (two drivers → cumulative
|
||||
points, H2H, gap-over-season). Feeds the argument every fan has.
|
||||
|
||||
### 9. Next-race preview / "get smart" page
|
||||
Between races the app goes quiet. Fill it: circuit characteristics, last year's
|
||||
result (2023/24 is cached), typical strategy (1 vs 2 stop), DRS zones, weather
|
||||
outlook, and the storylines (title-fight math to watch). Turn dead air into
|
||||
anticipation.
|
||||
|
||||
### 10. Championship scenario narratives
|
||||
Extend the simulator from "drag points around" to narrative permutations:
|
||||
*"VER clinches if he outscores NOR by 9 this weekend"* / *"first race McLaren can
|
||||
seal constructors'."* The stuff fans actually search for.
|
||||
|
||||
### 11. Briefing → calendar-aware season digest
|
||||
Reframe the news reader into a paddock digest tied to the calendar: group by GP,
|
||||
tag by team/driver, surface a "since last race" summary. Optionally an
|
||||
LLM-generated weekly briefing (a `claude-haiku` summarization pass over ingested
|
||||
RSS — cheap and on-brand).
|
||||
|
||||
---
|
||||
|
||||
## New / better data sources
|
||||
|
||||
- **Jolpica (Ergast successor, `api.jolpi.ca`)** — free historical results back to
|
||||
1950: qualifying, pit stops, lap times, circuit metadata. Unlocks all-time
|
||||
records, "best-ever at this track," and career stats OpenF1 (2023+) can't give.
|
||||
High value for driver pages and the "get smart" preview.
|
||||
- **OpenF1 weather timeseries** — already fetched; plot it as a session-long strip
|
||||
(track temp / rain / wind) instead of a table. Weather narrates strategy.
|
||||
- **Circuit metadata / DRS zones / corner names** — enriches the track map and
|
||||
previews. Some is in OpenF1 circuit info; curate the rest once as static data.
|
||||
- **Static per-race context** — a tiny curated JSON per round (tyre allocation,
|
||||
notable stats) goes a long way for previews.
|
||||
|
||||
---
|
||||
|
||||
## Cross-cutting UX principles
|
||||
|
||||
1. **Replace tables with a shape wherever a shape carries the meaning.** Lap times
|
||||
→ a trace with fastest lap marked. Stints → a horizontal tyre timeline. Gaps →
|
||||
the sparkline already shipped. Keep tables only where data is genuinely tabular
|
||||
(standings) — but annotate them.
|
||||
2. **Always answer "so what?"** Every number sits next to its meaning (a gap next
|
||||
to "undercut live," a tyre age next to "5 laps from the cliff").
|
||||
3. **One primary "moment" per screen.** The Command Center should always have a
|
||||
single obvious "here's what to watch/do now."
|
||||
4. **Make between-races feel alive.** The app currently rewards you only on
|
||||
Sundays. Previews, digests, replays, and rivalries give a reason to open it
|
||||
midweek.
|
||||
|
||||
---
|
||||
|
||||
## Suggested sequencing (impact × effort)
|
||||
|
||||
**Phase 1 — turn live into a companion (highest impact; data already in hand)**
|
||||
1. Web track map (SVG + GPS + mini-sectors)
|
||||
2. Telemetry compare overlay (speed/throttle/brake + delta)
|
||||
3. "What just happened" synthesized event rail
|
||||
4. Team radio ticker
|
||||
|
||||
**Phase 2 — own the between-races window**
|
||||
5. Narrative race replay (grow `RaceStoryCanvas`)
|
||||
6. Driver pages + rivalry view
|
||||
7. Next-race preview page
|
||||
|
||||
**Phase 3 — depth & reach**
|
||||
8. Jolpica/Ergast historical integration + all-time records
|
||||
9. Championship scenario narratives
|
||||
10. Calendar-aware briefing digest (optional LLM summaries)
|
||||
|
||||
---
|
||||
|
||||
## Execution tracking (GitHub)
|
||||
|
||||
This roadmap is tracked on GitHub:
|
||||
|
||||
- **Project board:** https://github.com/users/AmanTahiliani/projects/2 ("box-box Roadmap")
|
||||
- **Epics:** issues #2–#8 (label `epic`), one per epic above, on Phase milestones
|
||||
- **Stories:** issues #9–#31, wired as native **sub-issues** under their epic (progress rolls up automatically)
|
||||
- **Labels:** `epic`, `enabler`, `research`, `area:{live,viz,between-races,championship,data,ux}`
|
||||
- **Milestones:** `Phase 1 — Live Companion`, `Phase 2 — Between-Races`, `Phase 3 — Depth & Reach`
|
||||
|
||||
**Board fields:** `Stage` (Icebox → Research → Ready → In Progress → In Review → Done),
|
||||
`Priority` (P0–P2), `Effort` (S/M/L), `Phase` (1–3).
|
||||
|
||||
**Working model — active vs. bank:**
|
||||
- Only **1–2 epics active** at a time (currently **E1 Live Race Companion** + **E2 Viz
|
||||
Primitives**); the other five epics are the theme-level idea bank.
|
||||
- `Stage = Icebox` is the story-level bank. The 10 E1/E2 stories are seeded to
|
||||
`Ready`; everything else is `Icebox`. Promote a handful to `Ready`/`In Progress`
|
||||
per cycle; use `Research` to scope a vague idea before it's `Ready`.
|
||||
**Board views** (built):
|
||||
- **Backlog** — Table, all epics with expandable sub-issues: the full bank.
|
||||
- **Board** — grouped by `Stage`, filtered `-stage:Icebox`: the active-WIP wall.
|
||||
- **Roadmap** — Table grouped by `Phase` (Phase 1/2/3). Note: this is a
|
||||
phase-grouped table, not a timeline. A true timeline roadmap needs a date or
|
||||
iteration field (GitHub won't draw/persist a roadmap layout without one); add a
|
||||
`Target date` field and populate it once phases have real target dates, then
|
||||
switch this view to the Roadmap layout.
|
||||
BIN
docs/assets/command-center.jpg
Normal file
|
After Width: | Height: | Size: 99 KiB |
75
docs/data-and-operations.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Data and Operations
|
||||
|
||||
## Data Flow
|
||||
|
||||
| Layer | Role |
|
||||
| --- | --- |
|
||||
| OpenF1 REST | Backfill and ingestion source; optional paid tier via `OPENF1_API_KEY`. Also powers the TUI's on-demand reads and HTTP cache. |
|
||||
| Domain SQLite (`boxbox.db`) | Local store for meetings, sessions, Race Hub datasets, and navigation APIs used by the Web UI. |
|
||||
| HTTP cache SQLite (`cache.db`) | TTL cache for OpenF1 responses used by the TUI and legacy paths. Separate from the domain DB. |
|
||||
| Official F1 SignalR | Live timing bridge in `internal/live`, exposed to Web via SSE and to the TUI. |
|
||||
| Go server | `cmd/main.go`: TUI, `--web` API + static SPA, or CLI ingestion. |
|
||||
| React frontend | `frontend/`: production build served from `frontend/dist` when present. |
|
||||
|
||||
The Web UI should call local-first Go APIs under `/api/v1/...`; do not add direct OpenF1 reads in the frontend.
|
||||
|
||||
## Ingest Historical Data and Briefing Feeds
|
||||
|
||||
Ingestion is a CLI mode on the same binary. Only one of `--ingest-year`, `--ingest-meeting`, `--ingest-session`, or `--ingest-news` may be set per run.
|
||||
|
||||
```bash
|
||||
# Season: discover and store meeting metadata for 2023+
|
||||
go run ./cmd/main.go --ingest-year 2025
|
||||
|
||||
# Full race weekend: all sessions + Race Hub datasets
|
||||
go run ./cmd/main.go --ingest-meeting 1229
|
||||
|
||||
# Single session only
|
||||
go run ./cmd/main.go --ingest-session 9472
|
||||
|
||||
# Preview without writing
|
||||
go run ./cmd/main.go --dry-run --ingest-meeting 1229
|
||||
|
||||
# Refresh Paddock Briefing RSS/Atom feeds
|
||||
go run ./cmd/main.go --ingest-news
|
||||
|
||||
# Custom DB path
|
||||
go run ./cmd/main.go --ingest-meeting 1229 --db /tmp/boxbox.db
|
||||
```
|
||||
|
||||
Use `--ingest-meeting` for a complete weekend. `--ingest-year` stores season meetings, not full session datasets. Optional analytics fetches may partially fail without aborting the whole run.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `OPENF1_API_KEY` | Optional Bearer token for paid OpenF1 behavior. |
|
||||
| `BOXBOX_DISABLE_LIVE=1` | Skip the background SignalR live feed in web mode. Used by CI and local seeded UI work. |
|
||||
| `BOXBOX_OPENF1_BASE_URL` | Override the OpenF1 API root. Defaults to `https://api.openf1.org`. |
|
||||
| `BOXBOX_API_PORT` | Go API port used by the Vite dev proxy. Defaults to `8080`. |
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
export OPENF1_API_KEY=your_key_here
|
||||
go run ./cmd/main.go --web
|
||||
```
|
||||
|
||||
## Local Files
|
||||
|
||||
| Path | Purpose |
|
||||
| --- | --- |
|
||||
| `~/.local/share/box-box/boxbox.db` | Domain database, default `--db`. |
|
||||
| `~/.cache/box-box/cache.db` | OpenF1 HTTP response cache for the TUI and client. |
|
||||
| `box-box.log` | TUI application log in the project root. |
|
||||
| `frontend/dist/` | Production React build. Generated output, do not commit. |
|
||||
| `.playwright/*.db` | Seeded databases for automated tests. |
|
||||
|
||||
Web mode logs to stderr.
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- Live timing only works when F1 is broadcasting timing data; there is no guaranteed live session for local development.
|
||||
- E2E and visual tests use `BOXBOX_DISABLE_LIVE=1` and seeded SQLite, so they do not exercise full SignalR live behavior.
|
||||
- `frontend/dist` is generated output; build before production web mode or `test:e2e:prod`.
|
||||
- TUI historical views still use OpenF1 on demand with the HTTP cache; the Web UI's local-first model does not fully replace the TUI yet.
|
||||
94
docs/getting-started.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Getting Started
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [Go](https://go.dev/doc/install), using the module version in `go.mod`.
|
||||
- [Node.js](https://nodejs.org/) 18+ and npm.
|
||||
- Internet access for ingestion and TUI OpenF1 calls.
|
||||
- For e2e and visual tests: `npx playwright install` after `npm install` at the repo root.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
git clone https://github.com/AmanTahiliani/box-box.git
|
||||
cd box-box
|
||||
|
||||
npm install # Playwright and repo-level test scripts
|
||||
npm install --prefix frontend # Vite + React app
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
go build -o box-box ./cmd/main.go
|
||||
npm run build --prefix frontend # writes frontend/dist
|
||||
```
|
||||
|
||||
## Run: Web
|
||||
|
||||
Build the frontend first, then start web mode. Go walks up from the current directory to find `frontend/dist/index.html`; if missing, it serves embedded legacy assets.
|
||||
|
||||
```bash
|
||||
npm run build --prefix frontend
|
||||
go run ./cmd/main.go --web
|
||||
# http://localhost:8080
|
||||
```
|
||||
|
||||
Use a specific domain database or port:
|
||||
|
||||
```bash
|
||||
go run ./cmd/main.go --web --db ~/.local/share/box-box/boxbox.db --port 8080
|
||||
```
|
||||
|
||||
## Run: Web Dev
|
||||
|
||||
Vite proxies `/api` to the Go server. Set `BOXBOX_API_PORT` to match the Go `--port`.
|
||||
|
||||
Terminal 1: API with a seeded database:
|
||||
|
||||
```bash
|
||||
go run ./scripts/seed-e2e-db/main.go --db /tmp/boxbox-dev.db
|
||||
BOXBOX_DISABLE_LIVE=1 go run ./cmd/main.go --web --db /tmp/boxbox-dev.db --port 18080
|
||||
```
|
||||
|
||||
Terminal 2: frontend:
|
||||
|
||||
```bash
|
||||
BOXBOX_API_PORT=18080 npm run dev --prefix frontend
|
||||
# http://localhost:5173
|
||||
```
|
||||
|
||||
`BOXBOX_DISABLE_LIVE=1` skips starting the SignalR bridge, which is useful for CI and local UI work.
|
||||
|
||||
## Run: TUI
|
||||
|
||||
```bash
|
||||
go run ./cmd/main.go
|
||||
# or: ./box-box
|
||||
```
|
||||
|
||||
Logs go to `box-box.log` in the project directory so the terminal stays clean.
|
||||
|
||||
## TUI Keybindings
|
||||
|
||||
| Key | Action |
|
||||
| --- | --- |
|
||||
| `1`-`7` | Home, Standings, Calendar, Race Detail, Drivers, Live, Track Map |
|
||||
| `tab` / `shift+tab` | Next / previous tab |
|
||||
| `j`/`k`, `enter`, `b`/`esc` | Navigate, select, back |
|
||||
| `s`, `b`, `p` | Live: sectors, battles, pit window |
|
||||
| `r` | Race replay in Race Detail race sessions |
|
||||
| `y` | Cycle season year |
|
||||
| `q` / `ctrl+c` | Quit |
|
||||
|
||||
## Web Routes
|
||||
|
||||
| Route | Purpose |
|
||||
| --- | --- |
|
||||
| `/` | Command Center: race-weekend home with GP identity, live status, schedule, and analysis links |
|
||||
| `/race-hub?session_key=<key>` | Race Hub: session workspace with Overview, Race Story, Strategy, Lap Data, Conditions, Race Control, and Data Status tabs |
|
||||
| `/admin` | Admin / Data Health: ingestion coverage, local data status, and suggested CLI commands |
|
||||
| `/data-library` | Legacy alias for Admin / Data Health |
|
||||
| `/live` | Live Timing: timing tower and race control via SSE when a session is live |
|
||||
|
||||
Example after seeding: `http://localhost:5173/race-hub?session_key=9472`.
|
||||
BIN
docs/phase-1/screenshots/command-center-hero-between.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
docs/phase-1/screenshots/live-event-tyre-radio-mocked.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
docs/phase-1/screenshots/race-hub-compare-telemetry-delta.png
Normal file
|
After Width: | Height: | Size: 93 KiB |
BIN
docs/phase-1/screenshots/race-hub-strategy-timeline.png
Normal file
|
After Width: | Height: | Size: 42 KiB |
BIN
docs/phase-2/19-21-20-race-story.png
Normal file
|
After Width: | Height: | Size: 213 KiB |
BIN
docs/phase-2/22-driver-profile.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
docs/phase-2/23-teammate-h2h.png
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
docs/phase-2/24-rivalry-compare.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
BIN
docs/phase-2/25-race-preview.png
Normal file
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/phase-2/26-briefing-digest.png
Normal file
|
After Width: | Height: | Size: 683 KiB |
59
docs/testing.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Testing
|
||||
|
||||
## Go
|
||||
|
||||
Targeted offline-ish packages:
|
||||
|
||||
```bash
|
||||
go test ./internal/live ./internal/models ./internal/store ./internal/ingest ./internal/query ./internal/web
|
||||
```
|
||||
|
||||
All packages:
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
```
|
||||
|
||||
OpenF1 integration tests require network access and are rate-limit aware:
|
||||
|
||||
```bash
|
||||
go test -v ./internal/api
|
||||
```
|
||||
|
||||
## Frontend Unit Tests and Build
|
||||
|
||||
```bash
|
||||
npm --prefix frontend test -- --run
|
||||
npm --prefix frontend run build
|
||||
```
|
||||
|
||||
## E2E
|
||||
|
||||
The default Playwright config starts a seeded Go server on port `18080` and Vite on `15173`.
|
||||
|
||||
```bash
|
||||
npx playwright install # first time only
|
||||
npm run test:e2e
|
||||
```
|
||||
|
||||
Production serving mode builds around Go serving `frontend/dist`:
|
||||
|
||||
```bash
|
||||
npm run test:e2e:prod
|
||||
```
|
||||
|
||||
## Visual Regression
|
||||
|
||||
```bash
|
||||
npm run test:visual
|
||||
npm run test:visual:prod
|
||||
```
|
||||
|
||||
After intentional UI changes:
|
||||
|
||||
```bash
|
||||
npm run test:visual:update
|
||||
npm run test:visual:prod:update
|
||||
```
|
||||
|
||||
Snapshots live under `tests/visual/__snapshots__/`.
|
||||
@@ -2,8 +2,28 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>box-box</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<meta name="theme-color" content="#0d0d0d" />
|
||||
<meta name="description" content="box-box: A premium Live F1 Dashboard and Timing Tower" />
|
||||
|
||||
<!-- Open Graph / Social -->
|
||||
<meta property="og:title" content="box-box | Live F1 Dashboard" />
|
||||
<meta property="og:description" content="Real-time F1 timing, telemetry, and race dashboard." />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://box-box.amantahiliani.com/" />
|
||||
<meta property="og:image" content="https://box-box.amantahiliani.com/favicon.jpg" />
|
||||
|
||||
<!-- Icons & PWA -->
|
||||
<link rel="icon" type="image/jpeg" href="/favicon.jpg" />
|
||||
<link rel="apple-touch-icon" href="/favicon.jpg" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
|
||||
<!-- Google Fonts -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700;800&display=swap" rel="stylesheet">
|
||||
|
||||
<title>box-box | Live F1 Dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
17
frontend/package-lock.json
generated
@@ -8,8 +8,10 @@
|
||||
"name": "box-box-web",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@tanstack/react-router": "^1.81.0",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
@@ -902,6 +904,12 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@formkit/auto-animate": {
|
||||
"version": "0.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@formkit/auto-animate/-/auto-animate-0.9.0.tgz",
|
||||
"integrity": "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
@@ -2556,6 +2564,15 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/lucide-react": {
|
||||
"version": "1.23.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.23.0.tgz",
|
||||
"integrity": "sha512-38BpJcD0JhFosxHApP/BYsBetLpQFRoTRzEzstM/XCc3jsAG7wqaY1lgVwxiUe3xqYE+lNxo2PkCmYwXWrwwIw==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lz-string": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@tanstack/react-query": "^5.62.0",
|
||||
"@tanstack/react-router": "^1.81.0",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
|
||||
BIN
frontend/public/favicon.jpg
Normal file
|
After Width: | Height: | Size: 392 KiB |
15
frontend/public/manifest.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "box-box",
|
||||
"name": "box-box | Live F1 Dashboard",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/favicon.jpg",
|
||||
"type": "image/jpeg",
|
||||
"sizes": "192x192 512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#0d0d0d",
|
||||
"background_color": "#0d0d0d"
|
||||
}
|
||||
@@ -1,4 +1,21 @@
|
||||
import type { ArticleContent, LiveStateResponse, Meeting, NewsItem, RaceHub, Weekend } from './types'
|
||||
import type {
|
||||
ArticleContent,
|
||||
CarDataSample,
|
||||
ChampionshipHub,
|
||||
DriverSummary,
|
||||
EnrichedGrid,
|
||||
EnrichedResult,
|
||||
LapsComparisonResponse,
|
||||
LiveStateResponse,
|
||||
LiveSessionMeta,
|
||||
Meeting,
|
||||
NewsItem,
|
||||
RaceHub,
|
||||
ReplayFramesResponse,
|
||||
Session,
|
||||
TrackOutline,
|
||||
Weekend,
|
||||
} from './types'
|
||||
|
||||
export async function fetchRaceHub(sessionKey: number): Promise<RaceHub> {
|
||||
const res = await fetch(`/api/v1/race-hub?session_key=${sessionKey}`)
|
||||
@@ -27,7 +44,11 @@ export async function fetchLocalMeetings(year: number): Promise<Meeting[]> {
|
||||
}
|
||||
|
||||
export async function fetchSeasonMeetings(year: number): Promise<Meeting[]> {
|
||||
const res = await fetch(`/api/v1/meetings?year=${year}&source=openf1`)
|
||||
return fetchMeetings(year, 'openf1')
|
||||
}
|
||||
|
||||
export async function fetchMeetings(year: number, source = 'auto'): Promise<Meeting[]> {
|
||||
const res = await fetch(`/api/v1/meetings?year=${year}&source=${source}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
@@ -35,6 +56,56 @@ export async function fetchSeasonMeetings(year: number): Promise<Meeting[]> {
|
||||
return Array.isArray(meetings) ? meetings : []
|
||||
}
|
||||
|
||||
export async function fetchResults(sessionKey: number, source = 'auto'): Promise<EnrichedResult[]> {
|
||||
const res = await fetch(`/api/v1/results?session_key=${sessionKey}&source=${source}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
const results = await res.json()
|
||||
return Array.isArray(results) ? results : []
|
||||
}
|
||||
|
||||
export async function fetchStartingGrid(sessionKey: number, source = 'auto'): Promise<EnrichedGrid[]> {
|
||||
const res = await fetch(`/api/v1/grid?session_key=${sessionKey}&source=${source}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
const grid = await res.json()
|
||||
return Array.isArray(grid) ? grid : []
|
||||
}
|
||||
|
||||
export async function fetchTrackOutline(circuitKey: number, year: number): Promise<TrackOutline | null> {
|
||||
const res = await fetch(`/api/v1/track-outline?circuit_key=${circuitKey}&year=${year}`)
|
||||
if (!res.ok) return null
|
||||
const data = await res.json()
|
||||
if (data?.error || !Array.isArray(data?.points) || data.points.length < 2) return null
|
||||
return data as TrackOutline
|
||||
}
|
||||
|
||||
export async function fetchReplayFrames(
|
||||
sessionKey: number,
|
||||
intervalMs = 5000,
|
||||
): Promise<ReplayFramesResponse> {
|
||||
const params = new URLSearchParams({
|
||||
session_key: String(sessionKey),
|
||||
interval_ms: String(intervalMs),
|
||||
})
|
||||
const res = await fetch(`/api/v1/replay/frames?${params}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchSessions(meetingKey: number, source = 'openf1'): Promise<Session[]> {
|
||||
const res = await fetch(`/api/v1/sessions?meeting_key=${meetingKey}&source=${source}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
const sessions = await res.json()
|
||||
return Array.isArray(sessions) ? sessions : []
|
||||
}
|
||||
|
||||
export async function fetchWeekend(meetingKey: number): Promise<Weekend> {
|
||||
const res = await fetch(`/api/v1/weekend?meeting_key=${meetingKey}`)
|
||||
if (!res.ok) {
|
||||
@@ -43,6 +114,30 @@ export async function fetchWeekend(meetingKey: number): Promise<Weekend> {
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchChampionshipHub(year?: number): Promise<ChampionshipHub> {
|
||||
const params = new URLSearchParams({ source: 'auto' })
|
||||
if (year) params.set('year', year.toString())
|
||||
const url = `/api/v1/championship/hub?${params.toString()}`
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchDriverSummary(
|
||||
driverNumber: number,
|
||||
year?: number,
|
||||
): Promise<DriverSummary> {
|
||||
const params = new URLSearchParams({ driver_number: String(driverNumber) })
|
||||
if (year) params.set('year', String(year))
|
||||
const res = await fetch(`/api/v1/driver/summary?${params.toString()}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchLiveState(): Promise<LiveStateResponse> {
|
||||
const res = await fetch('/api/v1/live/state')
|
||||
if (!res.ok) {
|
||||
@@ -51,6 +146,20 @@ export async function fetchLiveState(): Promise<LiveStateResponse> {
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchLiveTrackOutline(
|
||||
session: LiveSessionMeta,
|
||||
year = new Date().getFullYear(),
|
||||
): Promise<TrackOutline> {
|
||||
const params = new URLSearchParams({ year: year.toString() })
|
||||
if (session.MeetingName) params.set('meeting_name', session.MeetingName)
|
||||
if (session.CircuitName) params.set('circuit_name', session.CircuitName)
|
||||
const res = await fetch(`/api/v1/track-outline?${params.toString()}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchNews(limit?: number, source?: string): Promise<NewsItem[]> {
|
||||
const params = new URLSearchParams()
|
||||
if (limit) params.set('limit', limit.toString())
|
||||
@@ -81,3 +190,32 @@ export async function markNewsRead(articleUrl: string): Promise<void> {
|
||||
body: JSON.stringify({ url: articleUrl }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchTelemetry(
|
||||
sessionKey: number,
|
||||
driverNumber: number,
|
||||
): Promise<CarDataSample[]> {
|
||||
const res = await fetch(
|
||||
`/api/v1/telemetry?session_key=${sessionKey}&driver_number=${driverNumber}`,
|
||||
)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
return Array.isArray(data) ? data : []
|
||||
}
|
||||
|
||||
export async function fetchLapsComparison(
|
||||
sessionKey: number,
|
||||
drivers?: number[],
|
||||
): Promise<LapsComparisonResponse> {
|
||||
const params = new URLSearchParams({ session_key: String(sessionKey) })
|
||||
if (drivers?.length) {
|
||||
params.set('drivers', drivers.join(','))
|
||||
}
|
||||
const res = await fetch(`/api/v1/laps/comparison?${params}`)
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${res.status}: ${res.statusText}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
233
frontend/src/components/ChampionshipSimulator.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import type { ChampionshipHub } from '../types'
|
||||
import { teamColor } from '../utils'
|
||||
import {
|
||||
assignPosition,
|
||||
defaultRound,
|
||||
defaultScenario,
|
||||
normalizeScenario,
|
||||
pointsForPosition,
|
||||
projectStandings,
|
||||
} from '../lib/simulator'
|
||||
import type { Scenario } from '../lib/simulator'
|
||||
|
||||
const STORAGE_PREFIX = 'box-box.champ.sim'
|
||||
|
||||
function storageKey(season: number): string {
|
||||
return `${STORAGE_PREFIX}.${season}`
|
||||
}
|
||||
|
||||
function loadScenario(hub: ChampionshipHub): Scenario {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey(hub.season))
|
||||
if (!raw) return defaultScenario(hub.drivers, hub.rounds_left)
|
||||
return normalizeScenario(JSON.parse(raw), hub.drivers, hub.rounds_left)
|
||||
} catch {
|
||||
return defaultScenario(hub.drivers, hub.rounds_left)
|
||||
}
|
||||
}
|
||||
|
||||
function saveScenario(season: number, scenario: Scenario) {
|
||||
try {
|
||||
window.localStorage.setItem(storageKey(season), JSON.stringify(scenario))
|
||||
} catch {
|
||||
// storage unavailable (private mode, quota) — simulator still works in memory
|
||||
}
|
||||
}
|
||||
|
||||
/** Label for the i-th remaining round (0-based), e.g. "R7" or "Round 7". */
|
||||
function roundLabel(hub: ChampionshipHub, index: number): string {
|
||||
return hub.round_labels[hub.round + index] ?? `Round ${hub.round + index + 1}`
|
||||
}
|
||||
|
||||
function fmtPts(n: number): string {
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
export function ChampionshipSimulator({ hub }: { hub: ChampionshipHub }) {
|
||||
const [scenario, setScenario] = useState<Scenario>(() => loadScenario(hub))
|
||||
const [selected, setSelected] = useState(0)
|
||||
|
||||
// Reload when the season changes (new hub, new storage key).
|
||||
useEffect(() => {
|
||||
setScenario(loadScenario(hub))
|
||||
setSelected(0)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hub.season, hub.rounds_left])
|
||||
|
||||
useEffect(() => {
|
||||
if (scenario.length > 0) saveScenario(hub.season, scenario)
|
||||
}, [hub.season, scenario])
|
||||
|
||||
const projected = useMemo(
|
||||
() => projectStandings(hub.drivers, scenario, hub.rounds_left),
|
||||
[hub.drivers, scenario, hub.rounds_left],
|
||||
)
|
||||
|
||||
if (hub.rounds_left <= 0 || hub.drivers.length === 0 || scenario.length === 0) {
|
||||
return (
|
||||
<div className="champ-chart-empty" data-testid="champ-view-simulator">
|
||||
Season complete — nothing left to simulate.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const roundIdx = Math.min(selected, scenario.length - 1)
|
||||
const round = scenario[roundIdx]
|
||||
|
||||
const setRound = (nextRound: (number | null)[]) => {
|
||||
setScenario((prev) => prev.map((r, i) => (i === roundIdx ? nextRound : r)))
|
||||
}
|
||||
|
||||
const driverByNumber = new Map(hub.drivers.map((d) => [d.driver_number, d]))
|
||||
|
||||
return (
|
||||
<div className="champ-sim" data-testid="champ-view-simulator">
|
||||
<div className="champ-sim-head">
|
||||
<span className="champ-chart-title mono">What-if simulator — remaining rounds</span>
|
||||
<button
|
||||
type="button"
|
||||
className="champ-sim-btn"
|
||||
onClick={() => setScenario(defaultScenario(hub.drivers, hub.rounds_left))}
|
||||
data-testid="sim-reset-all"
|
||||
>
|
||||
Reset all
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="champ-sim-rounds" role="tablist" aria-label="Remaining rounds">
|
||||
{scenario.map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
className={`champ-sim-round${i === roundIdx ? ' is-active' : ''}`}
|
||||
onClick={() => setSelected(i)}
|
||||
data-testid={`sim-round-${i}`}
|
||||
>
|
||||
{roundLabel(hub, i)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="champ-sim-grid">
|
||||
<div className="champ-sim-editor" data-testid="sim-editor">
|
||||
<div className="champ-sim-editor-head">
|
||||
<span className="champ-sim-editor-title mono">{roundLabel(hub, roundIdx)} finishing order</span>
|
||||
<button
|
||||
type="button"
|
||||
className="champ-sim-btn"
|
||||
onClick={() => setRound(defaultRound(hub.drivers))}
|
||||
data-testid="sim-reset-round"
|
||||
>
|
||||
Reset round
|
||||
</button>
|
||||
</div>
|
||||
{round.map((driverNumber, p) => {
|
||||
const driver = driverNumber != null ? driverByNumber.get(driverNumber) : undefined
|
||||
return (
|
||||
<div className="champ-sim-slot" key={p}>
|
||||
<span className="champ-sim-slot-pos mono">P{p + 1}</span>
|
||||
<span
|
||||
className="champ-sim-slot-bar"
|
||||
style={{ background: driver ? teamColor(driver.team_colour) : 'var(--border)' }}
|
||||
/>
|
||||
<select
|
||||
className="champ-sim-select mono"
|
||||
value={driverNumber ?? ''}
|
||||
aria-label={`P${p + 1} driver`}
|
||||
data-testid={`sim-pos-${p + 1}`}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value
|
||||
setRound(assignPosition(round, p, value === '' ? null : Number(value)))
|
||||
}}
|
||||
>
|
||||
<option value="">—</option>
|
||||
{hub.drivers.map((d) => (
|
||||
<option key={d.driver_number} value={d.driver_number}>
|
||||
{d.name_acronym} · {d.full_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="champ-sim-slot-pts mono">+{pointsForPosition(p + 1)}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="champ-sim-table-wrap">
|
||||
<div className="champ-sim-editor-head">
|
||||
<span className="champ-sim-editor-title mono">Projected standings</span>
|
||||
</div>
|
||||
<div className="champ-scroll">
|
||||
<table className="champ-table champ-sim-table" data-testid="sim-projected">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="l">Pos</th>
|
||||
<th className="c">Δ</th>
|
||||
<th className="l">Driver</th>
|
||||
<th className="r">Now</th>
|
||||
<th className="r">+Sim</th>
|
||||
<th className="r">Proj</th>
|
||||
<th className="r">Title</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{projected.map((row) => {
|
||||
const d = row.driver
|
||||
const moved = row.delta !== 0
|
||||
return (
|
||||
<tr
|
||||
key={d.driver_number}
|
||||
className={moved ? 'champ-sim-row-moved' : undefined}
|
||||
data-testid={`sim-row-${d.driver_number}`}
|
||||
>
|
||||
<td className="mono" style={{ fontWeight: 700 }}>
|
||||
P{row.projectedPosition}
|
||||
</td>
|
||||
<td className="c mono">
|
||||
{row.delta > 0 && (
|
||||
<span className="champ-sim-delta up">▲{row.delta}</span>
|
||||
)}
|
||||
{row.delta < 0 && (
|
||||
<span className="champ-sim-delta down">▼{-row.delta}</span>
|
||||
)}
|
||||
{row.delta === 0 && <span className="champ-td-dim">—</span>}
|
||||
</td>
|
||||
<td>
|
||||
<div className="champ-drv">
|
||||
<span
|
||||
className="champ-drv-bar"
|
||||
style={{ background: teamColor(d.team_colour) }}
|
||||
/>
|
||||
<span className="champ-drv-code mono">{d.name_acronym}</span>
|
||||
<span className="champ-drv-name">{d.full_name}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="r mono champ-td-muted">{fmtPts(row.currentPoints)}</td>
|
||||
<td className="r mono champ-td-dim">+{fmtPts(row.simPoints)}</td>
|
||||
<td className="r mono champ-td-pts">{fmtPts(row.projectedPoints)}</td>
|
||||
<td className="r">
|
||||
<span
|
||||
className="champ-alive mono"
|
||||
style={{ color: row.titleAlive ? 'var(--green)' : 'var(--text-3)' }}
|
||||
>
|
||||
{row.titleAlive ? 'ALIVE' : 'OUT'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="champ-sim-caption">
|
||||
Simplified model: every remaining round is scored as a standard Grand Prix
|
||||
(25-18-15-12-10-8-6-4-2-1, no fastest-lap point). Sprint weekends are ignored. Title status
|
||||
uses the max-points-remaining bound against the leader's projected total.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
116
frontend/src/components/ChapterStrip.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { BookOpen } from 'lucide-react'
|
||||
import type { Chapter } from '../types'
|
||||
import {
|
||||
activeChapterIndex,
|
||||
chapterKindLabel,
|
||||
chapterLapRange,
|
||||
chapterStartScrub,
|
||||
} from '../lib/chapters'
|
||||
import { EmptyStateCard } from './EmptyStateCard'
|
||||
import '../styles/chapters.css'
|
||||
|
||||
interface Props {
|
||||
chapters: Chapter[]
|
||||
scrubTime: number | null
|
||||
tMin: number
|
||||
tRange: number
|
||||
tourActive: boolean
|
||||
tourChapterIndex: number | null
|
||||
/** Explicit selection from a chapter click; wins over scrub-derived active. */
|
||||
selectedChapterIndex?: number | null
|
||||
onChapterClick: (index: number, scrub: number) => void
|
||||
onTourToggle: () => void
|
||||
}
|
||||
|
||||
export function ChapterStrip({
|
||||
chapters,
|
||||
scrubTime,
|
||||
tMin,
|
||||
tRange,
|
||||
tourActive,
|
||||
tourChapterIndex,
|
||||
selectedChapterIndex = null,
|
||||
onChapterClick,
|
||||
onTourToggle,
|
||||
}: Props) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const activeIndex = activeChapterIndex(chapters, scrubTime, tMin, tRange)
|
||||
const highlightedIndex = tourActive
|
||||
? tourChapterIndex
|
||||
: (selectedChapterIndex ?? activeIndex)
|
||||
|
||||
useEffect(() => {
|
||||
if (highlightedIndex === null || !scrollRef.current) return
|
||||
const card = scrollRef.current.querySelector<HTMLElement>(
|
||||
`[data-testid="chapter-card-${highlightedIndex}"]`,
|
||||
)
|
||||
card?.scrollIntoView?.({ behavior: 'smooth', inline: 'center', block: 'nearest' })
|
||||
}, [highlightedIndex])
|
||||
|
||||
if (chapters.length === 0) {
|
||||
return (
|
||||
<div className="chapter-strip" data-testid="chapter-strip">
|
||||
<EmptyStateCard
|
||||
icon={BookOpen}
|
||||
title="No story chapters"
|
||||
hint="This session does not have enough race-control or position data to build narrative chapters."
|
||||
testId="chapter-strip-empty"
|
||||
className="chapter-strip-empty-card"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="chapter-strip" data-testid="chapter-strip">
|
||||
<div className="chapter-strip-header">
|
||||
<span className="chapter-strip-title">Race chapters</span>
|
||||
<div className="chapter-strip-actions">
|
||||
<button
|
||||
type="button"
|
||||
className={`chapter-tour-btn ${tourActive ? 'active' : ''}`}
|
||||
onClick={onTourToggle}
|
||||
aria-pressed={tourActive}
|
||||
>
|
||||
{tourActive ? 'Exit 90s' : '90s tour'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chapter-strip-scroll-wrap">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="chapter-strip-scroll"
|
||||
role="list"
|
||||
aria-label="Race story chapters"
|
||||
>
|
||||
{chapters.map((chapter, index) => {
|
||||
const scrub = chapterStartScrub(chapter, tMin, tRange) ?? index / Math.max(chapters.length - 1, 1)
|
||||
const isActive = highlightedIndex === index
|
||||
const headline = chapter.headline || chapter.title
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`${chapter.kind}-${chapter.start_lap}-${index}`}
|
||||
type="button"
|
||||
role="listitem"
|
||||
className={`chapter-card ${isActive ? (tourActive ? 'tour-active' : 'active') : ''}`}
|
||||
onClick={() => onChapterClick(index, scrub)}
|
||||
aria-current={isActive ? 'true' : undefined}
|
||||
data-testid={`chapter-card-${index}`}
|
||||
>
|
||||
<div className="chapter-card-top">
|
||||
<span className={`chapter-kind chapter-kind--${chapter.kind}`}>
|
||||
{chapterKindLabel(chapter.kind)}
|
||||
</span>
|
||||
<span className="chapter-lap-range">{chapterLapRange(chapter)}</span>
|
||||
</div>
|
||||
<span className="chapter-headline">{headline}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { Copy, Check } from 'lucide-react'
|
||||
|
||||
interface Command {
|
||||
comment?: string
|
||||
@@ -39,8 +40,9 @@ function CliCommandLine({ cmd }: { cmd: string }) {
|
||||
return (
|
||||
<div className="cli-cmd-row">
|
||||
<code className="cli-cmd">{cmd}</code>
|
||||
<button type="button" className="cli-copy-btn" onClick={handleCopy} aria-label={`Copy ${cmd}`}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
<button type="button" className="cli-copy-btn interactive" onClick={handleCopy} aria-label={`Copy ${cmd}`} style={{ display: 'flex', alignItems: 'center', gap: '4px', padding: '4px 8px', background: copied ? 'var(--green)' : 'rgba(255,255,255,0.05)', color: copied ? '#000' : 'var(--text)', border: 'none', borderRadius: '4px', cursor: 'pointer', transition: 'all 0.2s' }}>
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
<span>{copied ? 'Copied' : 'Copy'}</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
415
frontend/src/components/CommandCenterHero.tsx
Normal file
@@ -0,0 +1,415 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { Activity, ArrowRight, Play } from 'lucide-react'
|
||||
import { sessionTypeAbbrev } from '../lib/coverage'
|
||||
import { countryDecal, countryFlag, formatGpDateRange } from '../lib/gpIdentity'
|
||||
import { classifySessionStatus, type HeroStateKind } from '../lib/hero'
|
||||
import { sortLiveTimingRows, trackStatusInfo } from '../lib/live'
|
||||
import {
|
||||
formatCountdown,
|
||||
formatSessionScheduleTime,
|
||||
meetingStartTime,
|
||||
sessionStartTime,
|
||||
type FocusMeetingKind,
|
||||
} from '../lib/schedule'
|
||||
import type { EnrichedResult, LiveStreamData, Meeting, Session, WeekendSession } from '../types'
|
||||
import '../styles/hero.css'
|
||||
|
||||
export interface CommandCenterHeroProps {
|
||||
state: HeroStateKind
|
||||
now: Date
|
||||
accent: string
|
||||
liveActive: boolean
|
||||
liveData: LiveStreamData | null | undefined
|
||||
focusMeeting: Meeting
|
||||
focusKind: FocusMeetingKind
|
||||
sessions: WeekendSession[]
|
||||
currentSession: Session | null
|
||||
nextSession: Session | null
|
||||
analysisSessionKey?: number
|
||||
analysisSessionName?: string
|
||||
lastRaceName: string
|
||||
lastRacePodium: EnrichedResult[]
|
||||
lastRaceSessionKey?: number
|
||||
nextMeeting: Meeting | null
|
||||
}
|
||||
|
||||
export function CommandCenterHero({
|
||||
state,
|
||||
now,
|
||||
accent,
|
||||
liveActive,
|
||||
liveData,
|
||||
focusMeeting,
|
||||
focusKind,
|
||||
sessions,
|
||||
currentSession,
|
||||
nextSession,
|
||||
analysisSessionKey,
|
||||
analysisSessionName,
|
||||
lastRaceName,
|
||||
lastRacePodium,
|
||||
lastRaceSessionKey,
|
||||
nextMeeting,
|
||||
}: CommandCenterHeroProps) {
|
||||
const accentStyle = {
|
||||
'--gp-accent': accent,
|
||||
'--hero-accent': accent,
|
||||
} as React.CSSProperties
|
||||
|
||||
return (
|
||||
<div className="hero-panel cc-hero" data-testid="cc-focus">
|
||||
<section className="hero-card ui-card glass-panel" style={accentStyle}>
|
||||
<div
|
||||
className={`hero-accent${state === 'live' ? ' hero-accent--live' : ''}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div className="hero-body">
|
||||
<div className="hero-inner">
|
||||
{state === 'live' && (
|
||||
<LiveHero
|
||||
liveActive={liveActive}
|
||||
liveData={liveData}
|
||||
currentSession={currentSession}
|
||||
focusMeeting={focusMeeting}
|
||||
/>
|
||||
)}
|
||||
{state === 'upcoming' && (
|
||||
<UpcomingHero
|
||||
now={now}
|
||||
focusMeeting={focusMeeting}
|
||||
focusKind={focusKind}
|
||||
sessions={sessions}
|
||||
currentSession={currentSession}
|
||||
nextSession={nextSession}
|
||||
liveActive={liveActive}
|
||||
analysisSessionKey={analysisSessionKey}
|
||||
analysisSessionName={analysisSessionName}
|
||||
/>
|
||||
)}
|
||||
{state === 'between' && (
|
||||
<BetweenHero
|
||||
now={now}
|
||||
lastRaceName={lastRaceName}
|
||||
lastRacePodium={lastRacePodium}
|
||||
lastRaceSessionKey={lastRaceSessionKey}
|
||||
nextMeeting={nextMeeting}
|
||||
analysisSessionKey={analysisSessionKey}
|
||||
analysisSessionName={analysisSessionName}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LiveHero({
|
||||
liveActive,
|
||||
liveData,
|
||||
currentSession,
|
||||
focusMeeting,
|
||||
}: {
|
||||
liveActive: boolean
|
||||
liveData: LiveStreamData | null | undefined
|
||||
currentSession: Session | null
|
||||
focusMeeting: Meeting
|
||||
}) {
|
||||
const sessionName =
|
||||
liveData?.Session?.SessionName ?? currentSession?.session_name ?? 'Live session'
|
||||
const trackStatus = trackStatusInfo(liveData?.TrackStatus)
|
||||
const topThree = sortLiveTimingRows(liveData).filter((r) => r.Position > 0).slice(0, 3)
|
||||
const decal = countryDecal(focusMeeting)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="hero-row">
|
||||
<span className="hero-decal mono">{decal}</span>
|
||||
<div className="hero-identity">
|
||||
<div className="hero-eyebrow hero-eyebrow--live mono">● Live now</div>
|
||||
<h1 className="hero-title">{sessionName}</h1>
|
||||
<div className="hero-sub mono">
|
||||
{[focusMeeting.meeting_name, focusMeeting.circuit_short_name].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
<div className={`hero-track-status hero-track-status--${trackStatus.key}`}>
|
||||
{trackStatus.label}
|
||||
</div>
|
||||
</div>
|
||||
{topThree.length > 0 && (
|
||||
<div className="hero-timing" data-testid="hero-live-timing">
|
||||
{topThree.map((row) => (
|
||||
<div key={row.RacingNumber} className="hero-timing-row">
|
||||
<span className={`hero-timing-pos hero-timing-pos--p${row.Position}`}>
|
||||
P{row.Position}
|
||||
</span>
|
||||
<span className="hero-timing-driver">
|
||||
<span
|
||||
className="hero-timing-bar"
|
||||
style={{ background: `#${row.Info?.TeamColour ?? '9aa0a6'}` }}
|
||||
/>
|
||||
{row.Info?.Tla ?? row.RacingNumber}
|
||||
</span>
|
||||
<span className="hero-timing-gap">
|
||||
{row.Position === 1 ? 'LEAD' : row.Driver.Interval || row.Driver.GapToLeader || '—'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="hero-countdown">
|
||||
<div className="hero-cd-label mono">{liveActive ? 'SignalR' : 'On track'}</div>
|
||||
<div className="hero-cd-value hero-cd-value--live mono">LIVE</div>
|
||||
<div className="hero-cd-sub mono">{sessionName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hero-actions">
|
||||
<Link to="/live" className="hero-cta hero-cta--primary" data-testid="hero-live-link">
|
||||
Open Live Timing <ArrowRight size={16} />
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function UpcomingHero({
|
||||
now,
|
||||
focusMeeting,
|
||||
focusKind,
|
||||
sessions,
|
||||
currentSession,
|
||||
nextSession,
|
||||
liveActive,
|
||||
analysisSessionKey,
|
||||
analysisSessionName,
|
||||
}: {
|
||||
now: Date
|
||||
focusMeeting: Meeting
|
||||
focusKind: FocusMeetingKind
|
||||
sessions: WeekendSession[]
|
||||
currentSession: Session | null
|
||||
nextSession: Session | null
|
||||
liveActive: boolean
|
||||
analysisSessionKey?: number
|
||||
analysisSessionName?: string
|
||||
}) {
|
||||
const decal = countryDecal(focusMeeting)
|
||||
const countdownTarget =
|
||||
nextSession && sessionStartTime(nextSession)
|
||||
? sessionStartTime(nextSession)!
|
||||
: meetingStartTime(focusMeeting)
|
||||
|
||||
const kindLabel =
|
||||
focusKind === 'current'
|
||||
? 'Current weekend'
|
||||
: focusKind === 'next'
|
||||
? 'Next weekend'
|
||||
: 'Weekend'
|
||||
|
||||
const sortedSessions = [...sessions].sort((a, b) => {
|
||||
const left = sessionStartTime(a.session)?.getTime() ?? 0
|
||||
const right = sessionStartTime(b.session)?.getTime() ?? 0
|
||||
return left - right
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="hero-row">
|
||||
<span className="hero-decal mono">{decal}</span>
|
||||
<div className="hero-identity">
|
||||
<div className="hero-eyebrow mono">{kindLabel}</div>
|
||||
<h1 className="hero-title">{focusMeeting.meeting_name}</h1>
|
||||
<div className="hero-sub mono">
|
||||
{[focusMeeting.location, focusMeeting.circuit_short_name].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
<div className="hero-sub mono">{formatGpDateRange(focusMeeting)}</div>
|
||||
</div>
|
||||
<div className="hero-countdown" data-testid="hero-countdown">
|
||||
{nextSession ? (
|
||||
<>
|
||||
<div className="hero-cd-label mono">Next · {nextSession.session_name}</div>
|
||||
{countdownTarget && (
|
||||
<div className="hero-cd-value mono">{formatCountdown(countdownTarget, now)}</div>
|
||||
)}
|
||||
<div className="hero-cd-sub mono">{formatSessionScheduleTime(nextSession.date_start)}</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="hero-cd-label mono">Status</div>
|
||||
<div className="hero-cd-value mono">Complete</div>
|
||||
<div className="hero-cd-sub mono">Weekend finished</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{sortedSessions.length > 0 && (
|
||||
<div className="hero-schedule-strip" data-testid="hero-schedule-strip" role="list">
|
||||
{sortedSessions.map(({ session }) => {
|
||||
const status = classifySessionStatus(session, now)
|
||||
const isNext = nextSession?.session_key === session.session_key
|
||||
const isCurrent = currentSession?.session_key === session.session_key
|
||||
const isLive = isCurrent && liveActive
|
||||
return (
|
||||
<Link
|
||||
key={session.session_key}
|
||||
to="/race-hub"
|
||||
search={{ session_key: session.session_key }}
|
||||
className={`hero-schedule-card${isNext ? ' is-next' : ''}${
|
||||
status === 'done' ? ' is-done' : ''
|
||||
}${isLive ? ' is-live' : ''}`}
|
||||
role="listitem"
|
||||
>
|
||||
<div className="hero-schedule-abbrev mono">
|
||||
{sessionTypeAbbrev(session.session_type, session.session_name)}
|
||||
</div>
|
||||
<div className="hero-schedule-name">{session.session_name}</div>
|
||||
<div className="hero-schedule-time mono">
|
||||
{formatSessionScheduleTime(session.date_start)}
|
||||
</div>
|
||||
<div
|
||||
className={`hero-schedule-marker mono${
|
||||
isLive ? ' hero-schedule-marker--live' : isNext ? ' hero-schedule-marker--next' : ''
|
||||
}`}
|
||||
>
|
||||
{isCurrent ? 'On track' : status === 'done' ? 'Done' : isNext ? 'Next' : 'Upcoming'}
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="hero-actions">
|
||||
<Link
|
||||
to="/live"
|
||||
className="hero-secondary-link"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}
|
||||
>
|
||||
<Play size={14} /> Watch Live
|
||||
</Link>
|
||||
{analysisSessionKey != null && (
|
||||
<Link
|
||||
to="/race-hub"
|
||||
search={{ session_key: analysisSessionKey }}
|
||||
className="hero-secondary-link"
|
||||
data-testid="hero-analysis-link"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: '6px' }}
|
||||
>
|
||||
<Activity size={14} /> Open Analysis
|
||||
{analysisSessionName ? ` · ${analysisSessionName}` : ''}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BetweenHero({
|
||||
now,
|
||||
lastRaceName,
|
||||
lastRacePodium,
|
||||
lastRaceSessionKey,
|
||||
nextMeeting,
|
||||
analysisSessionKey,
|
||||
analysisSessionName,
|
||||
}: {
|
||||
now: Date
|
||||
lastRaceName: string
|
||||
lastRacePodium: EnrichedResult[]
|
||||
lastRaceSessionKey?: number
|
||||
nextMeeting: Meeting | null
|
||||
analysisSessionKey?: number
|
||||
analysisSessionName?: string
|
||||
}) {
|
||||
const nextStart = nextMeeting ? meetingStartTime(nextMeeting) : null
|
||||
const podium = lastRacePodium
|
||||
.filter((r) => r.position >= 1 && r.position <= 3)
|
||||
.sort((a, b) => a.position - b.position)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="hero-row">
|
||||
<div className="hero-identity">
|
||||
<div className="hero-eyebrow mono">Between race weekends</div>
|
||||
{lastRaceName && (
|
||||
<h1 className="hero-title" data-testid="hero-last-race">
|
||||
After {lastRaceName}
|
||||
</h1>
|
||||
)}
|
||||
{!lastRaceName && <h1 className="hero-title">Season pause</h1>}
|
||||
</div>
|
||||
|
||||
{podium.length > 0 && (
|
||||
<div className="hero-podium" data-testid="hero-podium">
|
||||
{podium.map((r) => (
|
||||
<div key={r.driver_number} className="hero-podium-row">
|
||||
<span className={`hero-podium-pos hero-podium-pos--p${r.position} mono`}>
|
||||
P{r.position}
|
||||
</span>
|
||||
<span className="hero-podium-driver">
|
||||
<span
|
||||
className="hero-timing-bar"
|
||||
style={{ background: `#${r.team_colour}` }}
|
||||
/>
|
||||
{r.name_acronym}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nextMeeting && (
|
||||
<div className="hero-countdown" data-testid="hero-next-gp-countdown">
|
||||
<div className="hero-between-next">
|
||||
{countryFlag(nextMeeting) && (
|
||||
<span className="hero-flag" aria-hidden="true">
|
||||
{countryFlag(nextMeeting)}
|
||||
</span>
|
||||
)}
|
||||
<div>
|
||||
<div className="hero-cd-label mono">Next GP</div>
|
||||
<div className="hero-title" style={{ fontSize: '20px' }}>
|
||||
{nextMeeting.meeting_name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{nextStart && (
|
||||
<>
|
||||
<div className="hero-cd-value mono" style={{ marginTop: 'var(--s3)' }}>
|
||||
{formatCountdown(nextStart, now)}
|
||||
</div>
|
||||
<div className="hero-cd-sub mono">{formatGpDateRange(nextMeeting)}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="hero-actions">
|
||||
{lastRaceSessionKey != null && (
|
||||
<Link
|
||||
to="/race-hub"
|
||||
search={{ session_key: lastRaceSessionKey }}
|
||||
className="hero-secondary-link"
|
||||
data-testid="hero-last-race-link"
|
||||
>
|
||||
View {lastRaceName || 'last race'} results →
|
||||
</Link>
|
||||
)}
|
||||
{analysisSessionKey != null && analysisSessionKey !== lastRaceSessionKey && (
|
||||
<Link
|
||||
to="/race-hub"
|
||||
search={{ session_key: analysisSessionKey }}
|
||||
className="hero-secondary-link"
|
||||
data-testid="hero-analysis-link"
|
||||
>
|
||||
Open Analysis{analysisSessionName ? ` · ${analysisSessionName}` : ''}
|
||||
</Link>
|
||||
)}
|
||||
<Link to="/live" className="hero-secondary-link">
|
||||
Live Timing →
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
253
frontend/src/components/CompareView.tsx
Normal file
@@ -0,0 +1,253 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { fetchLapsComparison, fetchTelemetry } from '../api'
|
||||
import {
|
||||
buildBestLapTraceSeries,
|
||||
compareDriverOptions,
|
||||
comparisonToDeltaSeries,
|
||||
defaultCompareDriverNumbers,
|
||||
formatPitLapsCaption,
|
||||
} from '../lib/compare'
|
||||
import type { Driver, EnrichedResult } from '../types'
|
||||
import { teamColor } from '../utils'
|
||||
import { DriverCell } from './DriverCell'
|
||||
import { TelemetryTraceChart } from './charts/TelemetryTraceChart'
|
||||
import { DeltaTimeGraph } from './charts/DeltaTimeGraph'
|
||||
import '../styles/compare-view.css'
|
||||
|
||||
interface Props {
|
||||
sessionKey: number
|
||||
results: EnrichedResult[]
|
||||
drivers: Driver[]
|
||||
}
|
||||
|
||||
function SectionState({
|
||||
loading,
|
||||
error,
|
||||
empty,
|
||||
emptyMessage,
|
||||
children,
|
||||
}: {
|
||||
loading: boolean
|
||||
error: Error | null
|
||||
empty: boolean
|
||||
emptyMessage: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
if (loading) {
|
||||
return <div className="loading-state">loading…</div>
|
||||
}
|
||||
if (error) {
|
||||
return <div className="error-box">{error.message}</div>
|
||||
}
|
||||
if (empty) {
|
||||
return <div className="missing-notice">{emptyMessage}</div>
|
||||
}
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export function CompareView({ sessionKey, results, drivers }: Props) {
|
||||
const driverOptions = useMemo(
|
||||
() => compareDriverOptions(drivers, results),
|
||||
[drivers, results],
|
||||
)
|
||||
|
||||
const initialPair = useMemo(
|
||||
() => defaultCompareDriverNumbers(results, drivers),
|
||||
[results, drivers],
|
||||
)
|
||||
|
||||
const previousSessionKey = useRef(sessionKey)
|
||||
const [driverA, setDriverA] = useState<number | null>(initialPair?.[0] ?? null)
|
||||
const [driverB, setDriverB] = useState<number | null>(initialPair?.[1] ?? null)
|
||||
|
||||
useEffect(() => {
|
||||
if (previousSessionKey.current !== sessionKey) {
|
||||
previousSessionKey.current = sessionKey
|
||||
setDriverA(initialPair?.[0] ?? null)
|
||||
setDriverB(initialPair?.[1] ?? null)
|
||||
return
|
||||
}
|
||||
|
||||
if (driverA != null && driverB != null) return
|
||||
if (!initialPair) return
|
||||
setDriverA(initialPair[0])
|
||||
setDriverB(initialPair[1])
|
||||
}, [sessionKey, initialPair, driverA, driverB])
|
||||
|
||||
const pair = useMemo((): [number, number] | null => {
|
||||
if (driverA == null || driverB == null || driverA === driverB) return null
|
||||
return [driverA, driverB]
|
||||
}, [driverA, driverB])
|
||||
|
||||
const comparisonQuery = useQuery({
|
||||
queryKey: ['laps-comparison', sessionKey, pair?.[0], pair?.[1]],
|
||||
queryFn: () => fetchLapsComparison(sessionKey, pair!),
|
||||
enabled: pair != null,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const telemetryAQuery = useQuery({
|
||||
queryKey: ['telemetry', sessionKey, pair?.[0]],
|
||||
queryFn: () => fetchTelemetry(sessionKey, pair![0]),
|
||||
enabled: pair != null,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const telemetryBQuery = useQuery({
|
||||
queryKey: ['telemetry', sessionKey, pair?.[1]],
|
||||
queryFn: () => fetchTelemetry(sessionKey, pair![1]),
|
||||
enabled: pair != null,
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const comparison = comparisonQuery.data
|
||||
const referenceLabel = useMemo(() => {
|
||||
if (!pair) return undefined
|
||||
const meta = comparison?.drivers.find((d) => d.driver_number === pair[0])
|
||||
const session = drivers.find((d) => d.driver_number === pair[0])
|
||||
return meta?.name_acronym || session?.name_acronym
|
||||
}, [pair, comparison, drivers])
|
||||
|
||||
const deltaSeries = useMemo(() => {
|
||||
if (!comparison || !pair) return []
|
||||
return comparisonToDeltaSeries(comparison, pair, drivers)
|
||||
}, [comparison, pair, drivers])
|
||||
|
||||
const pitCaption = useMemo(() => {
|
||||
if (!comparison || !pair) return null
|
||||
return formatPitLapsCaption(comparison.pit_laps, pair, comparison, drivers)
|
||||
}, [comparison, pair, drivers])
|
||||
|
||||
const traceSeries = useMemo(() => {
|
||||
if (!pair || !comparison) return []
|
||||
const out = []
|
||||
|
||||
for (const dn of pair) {
|
||||
const comp = comparison.drivers.find((d) => d.driver_number === dn)
|
||||
const session = drivers.find((d) => d.driver_number === dn)
|
||||
const label = comp?.name_acronym || session?.name_acronym || `#${dn}`
|
||||
const color = teamColor(comp?.team_colour || session?.team_colour)
|
||||
|
||||
const carData =
|
||||
dn === pair[0] ? (telemetryAQuery.data ?? []) : (telemetryBQuery.data ?? [])
|
||||
const series = buildBestLapTraceSeries(carData, comp?.laps ?? [], label, color)
|
||||
if (series) out.push(series)
|
||||
}
|
||||
|
||||
return out
|
||||
}, [pair, comparison, drivers, telemetryAQuery.data, telemetryBQuery.data])
|
||||
|
||||
const telemetryLoading = telemetryAQuery.isLoading || telemetryBQuery.isLoading
|
||||
const telemetryError = telemetryAQuery.error ?? telemetryBQuery.error
|
||||
|
||||
if (driverOptions.length < 2) {
|
||||
return (
|
||||
<div className="missing-notice" data-testid="compare-view-empty">
|
||||
Need at least two drivers in this session to compare.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const driverAInfo = driverOptions.find((d) => d.driver_number === driverA)
|
||||
const driverBInfo = driverOptions.find((d) => d.driver_number === driverB)
|
||||
|
||||
return (
|
||||
<div className="compare-view" data-testid="compare-view">
|
||||
<div className="compare-pickers">
|
||||
<div className="compare-picker">
|
||||
<span className="compare-picker-label">Reference</span>
|
||||
<select
|
||||
className="compare-picker-select"
|
||||
value={driverA ?? ''}
|
||||
onChange={(e) => setDriverA(Number(e.target.value))}
|
||||
data-testid="compare-picker-a"
|
||||
>
|
||||
{driverOptions.map((d) => (
|
||||
<option key={d.driver_number} value={d.driver_number}>
|
||||
{d.name_acronym} · #{d.driver_number}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{driverAInfo && (
|
||||
<DriverCell
|
||||
acronym={driverAInfo.name_acronym}
|
||||
number={driverAInfo.driver_number}
|
||||
colour={driverAInfo.team_colour}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="compare-picker">
|
||||
<span className="compare-picker-label">Challenger</span>
|
||||
<select
|
||||
className="compare-picker-select"
|
||||
value={driverB ?? ''}
|
||||
onChange={(e) => setDriverB(Number(e.target.value))}
|
||||
data-testid="compare-picker-b"
|
||||
>
|
||||
{driverOptions.map((d) => (
|
||||
<option key={d.driver_number} value={d.driver_number}>
|
||||
{d.name_acronym} · #{d.driver_number}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{driverBInfo && (
|
||||
<DriverCell
|
||||
acronym={driverBInfo.name_acronym}
|
||||
number={driverBInfo.driver_number}
|
||||
colour={driverBInfo.team_colour}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{driverA === driverB && (
|
||||
<div className="analysis-notice">
|
||||
<strong>Pick two different drivers</strong> to run a comparison.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="compare-section" data-testid="compare-telemetry-section">
|
||||
<div>
|
||||
<div className="compare-section-title">Best lap telemetry</div>
|
||||
<div className="compare-section-meta">
|
||||
Speed, throttle, and brake traces for each driver's fastest lap
|
||||
</div>
|
||||
</div>
|
||||
<SectionState
|
||||
loading={telemetryLoading}
|
||||
error={telemetryError instanceof Error ? telemetryError : null}
|
||||
empty={!telemetryLoading && !telemetryError && traceSeries.length === 0}
|
||||
emptyMessage="No telemetry samples for the best laps. Car data may not be available for this session."
|
||||
>
|
||||
<TelemetryTraceChart series={traceSeries} />
|
||||
</SectionState>
|
||||
</section>
|
||||
|
||||
<section className="compare-section" data-testid="compare-pace-section">
|
||||
<div>
|
||||
<div className="compare-section-title">Race pace</div>
|
||||
<div className="compare-section-meta">
|
||||
Cumulative lap-time delta vs {referenceLabel ?? 'reference'}. Deltas are plotted
|
||||
only where the reference lap is valid; gaps appear when the reference has no lap
|
||||
time.
|
||||
</div>
|
||||
</div>
|
||||
<SectionState
|
||||
loading={comparisonQuery.isLoading}
|
||||
error={comparisonQuery.error instanceof Error ? comparisonQuery.error : null}
|
||||
empty={!comparisonQuery.isLoading && !comparisonQuery.error && deltaSeries.length < 2}
|
||||
emptyMessage="No lap comparison data for the selected drivers."
|
||||
>
|
||||
<DeltaTimeGraph series={deltaSeries} referenceLabel={referenceLabel} />
|
||||
{pitCaption && (
|
||||
<p className="compare-pit-caption" data-testid="compare-pit-caption">
|
||||
{pitCaption}
|
||||
</p>
|
||||
)}
|
||||
</SectionState>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
20
frontend/src/components/EmptyStateCard.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface Props {
|
||||
icon: LucideIcon
|
||||
title: string
|
||||
hint: ReactNode
|
||||
testId?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function EmptyStateCard({ icon: Icon, title, hint, testId, className = '' }: Props) {
|
||||
return (
|
||||
<div className={`empty-state ui-card ${className}`.trim()} data-testid={testId}>
|
||||
<Icon size={32} className="empty-state-icon" aria-hidden />
|
||||
<div className="empty-state-title">{title}</div>
|
||||
<div className="empty-state-desc">{hint}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
26
frontend/src/components/Meaning.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import '../styles/meaning.css'
|
||||
|
||||
export interface MeaningProps {
|
||||
value: ReactNode
|
||||
meaning?: string | null
|
||||
/** Long-form explanation for the native tooltip; falls back to meaning. */
|
||||
title?: string | null
|
||||
tone?: 'good' | 'bad' | 'neutral' | 'warn'
|
||||
}
|
||||
|
||||
export function Meaning({ value, meaning, title, tone }: MeaningProps) {
|
||||
if (!meaning) {
|
||||
return <>{value}</>
|
||||
}
|
||||
|
||||
const tooltip = title ?? meaning
|
||||
const toneClass = tone ? `meaning-caption--${tone}` : ''
|
||||
|
||||
return (
|
||||
<span className="meaning" title={tooltip}>
|
||||
<span className="meaning-value">{value}</span>
|
||||
<span className={`meaning-caption ${toneClass}`.trim()}>{meaning}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,17 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { fetchLiveState } from '../api'
|
||||
import { isLiveSessionActive } from '../lib/live'
|
||||
|
||||
export function Nav() {
|
||||
const { data: liveState } = useQuery({
|
||||
queryKey: ['live-state'],
|
||||
queryFn: fetchLiveState,
|
||||
staleTime: 5_000,
|
||||
refetchInterval: 30_000,
|
||||
})
|
||||
const liveActive = isLiveSessionActive(liveState)
|
||||
|
||||
return (
|
||||
<nav className="app-nav">
|
||||
<Link to="/" className="nav-logo">
|
||||
@@ -10,12 +21,26 @@ export function Nav() {
|
||||
<Link to="/" activeProps={{ className: 'active' }} activeOptions={{ exact: true }}>
|
||||
Command
|
||||
</Link>
|
||||
<Link to="/live" activeProps={{ className: 'active' }}>
|
||||
<Link
|
||||
to="/live"
|
||||
className={liveActive ? 'nav-live nav-live-on' : 'nav-live'}
|
||||
activeProps={{ className: 'active' }}
|
||||
data-testid="nav-live"
|
||||
data-live-active={liveActive ? 'true' : 'false'}
|
||||
>
|
||||
{liveActive && <span className="nav-live-dot" aria-hidden="true" />}
|
||||
Live
|
||||
{liveActive && <span className="sr-only"> session active</span>}
|
||||
</Link>
|
||||
<Link to="/race-hub" search={{}} activeProps={{ className: 'active' }}>
|
||||
Race Hub
|
||||
</Link>
|
||||
<Link to="/preview" activeProps={{ className: 'active' }}>
|
||||
Preview
|
||||
</Link>
|
||||
<Link to="/championship" activeProps={{ className: 'active' }}>
|
||||
Championship
|
||||
</Link>
|
||||
<Link to="/briefing" activeProps={{ className: 'active' }}>
|
||||
Briefing
|
||||
</Link>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { RaceHub } from '../types'
|
||||
import { compareFinishPosition, formatDuration, formatGap, formatLapTime } from '../utils'
|
||||
import { countRaceHubDatasets } from '../lib/coverage'
|
||||
import { Thermometer, Map, Droplets, Wind, CloudRain } from 'lucide-react'
|
||||
|
||||
interface Props {
|
||||
data: RaceHub
|
||||
@@ -74,7 +75,7 @@ export function OverviewView({ data }: Props) {
|
||||
</div>
|
||||
|
||||
<div className="rh-overview-row">
|
||||
<section className="rh-panel">
|
||||
<section className="rh-panel ui-card">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Conditions</span>
|
||||
{latestWeather && (
|
||||
@@ -83,17 +84,20 @@ export function OverviewView({ data }: Props) {
|
||||
</div>
|
||||
{latestWeather ? (
|
||||
<div className="rh-condition-strip" data-testid="rh-conditions">
|
||||
<ConditionChip label="Air" value={`${latestWeather.air_temperature.toFixed(1)}°C`} />
|
||||
<ConditionChip icon={Thermometer} label="Air" value={`${latestWeather.air_temperature.toFixed(1)}°C`} />
|
||||
<ConditionChip
|
||||
icon={Map}
|
||||
label="Track"
|
||||
value={`${latestWeather.track_temperature.toFixed(1)}°C`}
|
||||
/>
|
||||
<ConditionChip label="Humidity" value={`${latestWeather.humidity.toFixed(0)}%`} />
|
||||
<ConditionChip icon={Droplets} label="Humidity" value={`${latestWeather.humidity.toFixed(0)}%`} />
|
||||
<ConditionChip
|
||||
icon={Wind}
|
||||
label="Wind"
|
||||
value={`${latestWeather.wind_speed.toFixed(1)} m/s`}
|
||||
/>
|
||||
<ConditionChip
|
||||
icon={CloudRain}
|
||||
label="Rain"
|
||||
value={latestWeather.rainfall > 0 ? 'Yes' : 'No'}
|
||||
accent={latestWeather.rainfall > 0 ? 'wet' : undefined}
|
||||
@@ -104,7 +108,7 @@ export function OverviewView({ data }: Props) {
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rh-panel">
|
||||
<section className="rh-panel ui-card">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Race Control · Latest</span>
|
||||
<span className="sec-meta mono">{data.race_control.length}</span>
|
||||
@@ -126,7 +130,7 @@ export function OverviewView({ data }: Props) {
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rh-panel">
|
||||
<section className="rh-panel ui-card">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Local Coverage</span>
|
||||
<span className="sec-meta mono">
|
||||
@@ -173,7 +177,7 @@ function StatCard({
|
||||
}: StatCardProps) {
|
||||
if (placeholder) {
|
||||
return (
|
||||
<div className="rh-stat-card rh-stat-empty">
|
||||
<div className="rh-stat-card ui-card rh-stat-empty">
|
||||
<div className="rh-stat-label mono">{label}</div>
|
||||
<div className="rh-stat-primary">—</div>
|
||||
<div className="rh-stat-secondary">No data ingested</div>
|
||||
@@ -181,7 +185,7 @@ function StatCard({
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="rh-stat-card">
|
||||
<div className="rh-stat-card ui-card interactive">
|
||||
<div className="rh-stat-label mono">{label}</div>
|
||||
<div className="rh-stat-primary" style={primaryColor ? { color: primaryColor } : undefined}>
|
||||
{primary}
|
||||
@@ -196,7 +200,7 @@ function StatCard({
|
||||
function PodiumCard({ podium }: { podium: Array<{ name_acronym: string; team_colour: string; position: number; full_name: string; gap_to_leader: number | string | number[] | null; duration: number | number[] | null; driver_number: number }> }) {
|
||||
if (podium.length === 0) {
|
||||
return (
|
||||
<div className="rh-stat-card rh-stat-empty">
|
||||
<div className="rh-stat-card ui-card rh-stat-empty">
|
||||
<div className="rh-stat-label mono">Podium</div>
|
||||
<div className="rh-stat-primary">—</div>
|
||||
<div className="rh-stat-secondary">No classified finishers</div>
|
||||
@@ -204,7 +208,7 @@ function PodiumCard({ podium }: { podium: Array<{ name_acronym: string; team_col
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="rh-stat-card">
|
||||
<div className="rh-stat-card ui-card interactive">
|
||||
<div className="rh-stat-label mono">Podium</div>
|
||||
<ol className="rh-podium-list">
|
||||
{podium.map((r) => (
|
||||
@@ -232,13 +236,16 @@ function ConditionChip({
|
||||
label,
|
||||
value,
|
||||
accent,
|
||||
icon: Icon,
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
accent?: 'wet'
|
||||
icon?: React.ElementType
|
||||
}) {
|
||||
return (
|
||||
<div className={`rh-condition-chip${accent === 'wet' ? ' rh-condition-wet' : ''}`}>
|
||||
<div className={`rh-condition-chip${accent === 'wet' ? ' rh-condition-wet' : ''}`} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
|
||||
{Icon && <Icon size={14} style={{ opacity: 0.7 }} />}
|
||||
<span className="rh-condition-label mono">{label}</span>
|
||||
<span className="rh-condition-value">{value}</span>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { fetchNews } from '../api'
|
||||
import {
|
||||
fetchChampionshipHub,
|
||||
fetchNews,
|
||||
fetchSeasonMeetings,
|
||||
fetchSeasons,
|
||||
} from '../api'
|
||||
import {
|
||||
activeDigestWindow,
|
||||
gpWindows,
|
||||
itemsForWindow,
|
||||
sinceLastLabel,
|
||||
tagColour,
|
||||
tagItems,
|
||||
topTags,
|
||||
} from '../lib/digest'
|
||||
import { timeAgo } from '../utils'
|
||||
import '../styles/digest.css'
|
||||
|
||||
const SOURCE_DISPLAY: Record<string, string> = {
|
||||
'fia': 'FIA',
|
||||
@@ -14,14 +30,53 @@ const SOURCE_DISPLAY: Record<string, string> = {
|
||||
}
|
||||
|
||||
export function PaddockBriefing() {
|
||||
const now = useMemo(() => new Date(), [])
|
||||
|
||||
const { data: news, isLoading, isError } = useQuery({
|
||||
queryKey: ['news'],
|
||||
queryFn: () => fetchNews(100),
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const seasonsQuery = useQuery({
|
||||
queryKey: ['seasons'],
|
||||
queryFn: fetchSeasons,
|
||||
})
|
||||
const latestSeason = seasonsQuery.data?.[0] ?? null
|
||||
|
||||
const meetingsQuery = useQuery({
|
||||
queryKey: ['season-meetings', latestSeason],
|
||||
queryFn: () => fetchSeasonMeetings(latestSeason!),
|
||||
enabled: latestSeason != null,
|
||||
})
|
||||
|
||||
const hubQuery = useQuery({
|
||||
queryKey: ['championship-hub', latestSeason],
|
||||
queryFn: () => fetchChampionshipHub(latestSeason!),
|
||||
enabled: latestSeason != null,
|
||||
})
|
||||
|
||||
const meetings = meetingsQuery.data ?? []
|
||||
const hub = hubQuery.data
|
||||
const tagged = useMemo(
|
||||
() => tagItems(news ?? [], hub?.drivers ?? [], hub?.teams ?? []),
|
||||
[news, hub],
|
||||
)
|
||||
|
||||
const windows = useMemo(() => gpWindows(meetings, now), [meetings, now])
|
||||
const activeWindow = useMemo(
|
||||
() => activeDigestWindow(windows, meetings, now),
|
||||
[windows, meetings, now],
|
||||
)
|
||||
const sinceItems = useMemo(
|
||||
() => itemsForWindow(tagged, activeWindow),
|
||||
[tagged, activeWindow],
|
||||
)
|
||||
const sinceTags = useMemo(() => topTags(sinceItems, 4), [sinceItems])
|
||||
const sinceLabel = sinceLastLabel(meetings, now)
|
||||
|
||||
const unreadCount = news?.filter((i) => !i.read_at).length ?? 0
|
||||
const preview = news?.slice(0, 5) ?? []
|
||||
const preview = sinceItems.length > 0 ? sinceItems.slice(0, 5) : (tagged.slice(0, 5))
|
||||
|
||||
return (
|
||||
<section className="cc-briefing" data-testid="paddock-briefing">
|
||||
@@ -37,6 +92,27 @@ export function PaddockBriefing() {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{meetings.length > 0 && (
|
||||
<div className="cc-brief-digest-meta" data-testid="cc-brief-digest-meta">
|
||||
<span>Since {sinceLabel}</span>
|
||||
<span>·</span>
|
||||
<span>{sinceItems.length} items</span>
|
||||
{sinceTags.length > 0 && (
|
||||
<div className="cc-brief-digest-tags">
|
||||
{sinceTags.map((tag) => (
|
||||
<span
|
||||
key={tag.key}
|
||||
className="cc-brief-tag"
|
||||
style={{ borderColor: tagColour(tag.colour) }}
|
||||
>
|
||||
{tag.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && <div className="briefing-state loading-state">loading…</div>}
|
||||
{isError && <div className="briefing-state error-box">Failed to load briefing</div>}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ interface Props {
|
||||
function SourceBadge({ source }: { source: RaceHub['source'] }) {
|
||||
if (source === 'local') return <span className="badge badge-local">Local</span>
|
||||
if (source === 'partial') return <span className="badge badge-partial">Partial</span>
|
||||
if (source === 'cancelled') return <span className="badge badge-cancelled">Cancelled</span>
|
||||
return <span className="badge badge-none">No data</span>
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
import { useState, useMemo, useRef, useCallback } from 'react'
|
||||
import type { EnrichedResult, EnrichedGrid, PositionSample, Lap, Session } from '../types'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { LineChart } from 'lucide-react'
|
||||
import type { Driver, EnrichedResult, EnrichedGrid, PositionSample, Lap, Meeting, Session, Chapter } from '../types'
|
||||
import { fetchReplayFrames, fetchTrackOutline } from '../api'
|
||||
import { ReplayTrackMap } from './ReplayTrackMap'
|
||||
import { ChapterStrip } from './ChapterStrip'
|
||||
import { EmptyStateCard } from './EmptyStateCard'
|
||||
import { gridDelta, gridDeltaClass, formatDuration, formatGap } from '../utils'
|
||||
import {
|
||||
chapterBandFill,
|
||||
chapterEndScrub,
|
||||
chapterStartScrub,
|
||||
chapterTourDurations,
|
||||
deCollideYPositions,
|
||||
decimatedPositionLabels,
|
||||
} from '../lib/chapters'
|
||||
import { isReplayMapAvailable } from '../lib/replayMap'
|
||||
import '../styles/race-story.css'
|
||||
|
||||
const CHAPTER_TOUR_MS = 90_000
|
||||
const CHART_W = 640
|
||||
const CHART_H = 180
|
||||
const CHART_PL = 40
|
||||
const CHART_PR = 48
|
||||
const CHART_PT = 8
|
||||
const CHART_PB = 20
|
||||
|
||||
interface ChartTiming {
|
||||
tMin: number
|
||||
tMax: number
|
||||
tRange: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
data: {
|
||||
@@ -12,38 +42,256 @@ interface Props {
|
||||
race_control?: any[]
|
||||
pit_stops?: any[]
|
||||
session?: Session
|
||||
meeting?: Meeting
|
||||
drivers?: Driver[]
|
||||
chapters?: Chapter[]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Position samples are recorded for the entire session, including the pre-race
|
||||
* grid period. Use the winning driver's laps to define the race window so
|
||||
* that the x-axis starts at lights-out rather than at the earliest sample.
|
||||
*/
|
||||
function raceChartTiming(
|
||||
positions: PositionSample[],
|
||||
laps: Lap[],
|
||||
results: EnrichedResult[],
|
||||
): ChartTiming | null {
|
||||
const positionTimes = positions
|
||||
.map((position) => new Date(position.date).getTime())
|
||||
.filter(Number.isFinite)
|
||||
if (positionTimes.length === 0) return null
|
||||
|
||||
const fallbackMin = Math.min(...positionTimes)
|
||||
const fallbackMax = Math.max(...positionTimes)
|
||||
const fallback = {
|
||||
tMin: fallbackMin,
|
||||
tMax: fallbackMax,
|
||||
tRange: Math.max(fallbackMax - fallbackMin, 1),
|
||||
}
|
||||
|
||||
const winner = results.find((result) => result.position === 1)
|
||||
if (!winner) return fallback
|
||||
|
||||
const winnerLaps = laps
|
||||
.filter((lap) => lap.driver_number === winner.driver_number && lap.lap_number > 0)
|
||||
.map((lap) => ({ ...lap, start: new Date(lap.date_start).getTime() }))
|
||||
.filter((lap) => Number.isFinite(lap.start))
|
||||
.sort((a, b) => a.lap_number - b.lap_number)
|
||||
if (winnerLaps.length === 0) return fallback
|
||||
|
||||
const firstLap = winnerLaps[0]
|
||||
const lastLap = winnerLaps[winnerLaps.length - 1]
|
||||
const finalLapDuration = lastLap.lap_duration ?? 0
|
||||
const tMax = lastLap.start + (finalLapDuration > 0 ? finalLapDuration * 1000 : 0)
|
||||
if (tMax <= firstLap.start) return fallback
|
||||
|
||||
return { tMin: firstLap.start, tMax, tRange: tMax - firstLap.start }
|
||||
}
|
||||
|
||||
export function RaceStoryCanvas({ data }: Props) {
|
||||
const { results, starting_grid: grid, positions, datasets, race_control = [], pit_stops = [], laps = [] } = data
|
||||
const {
|
||||
results,
|
||||
starting_grid: grid,
|
||||
positions,
|
||||
datasets,
|
||||
race_control = [],
|
||||
pit_stops = [],
|
||||
laps = [],
|
||||
session,
|
||||
meeting,
|
||||
drivers = [],
|
||||
chapters = [],
|
||||
} = data
|
||||
const hasPositions = datasets['positions']?.status === 'available'
|
||||
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
const [hoverDriver, setHoverDriver] = useState<number | null>(null)
|
||||
const [mapOpen, setMapOpen] = useState(false)
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [playbackSpeed, setPlaybackSpeed] = useState(10)
|
||||
const [chapterTourActive, setChapterTourActive] = useState(false)
|
||||
const [tourChapterIndex, setTourChapterIndex] = useState<number | null>(null)
|
||||
const [selectedChapterIndex, setSelectedChapterIndex] = useState<number | null>(null)
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
const tourRef = useRef({ chapterIndex: 0, startedAt: 0, durationMs: 0, startScrub: 0, endScrub: 0 })
|
||||
|
||||
// Position Evolution Chart Logic
|
||||
const allTimes = useMemo(() => [...new Set(positions.map((p) => p.date))].sort(), [positions])
|
||||
const hasChartData = hasPositions && allTimes.length > 0
|
||||
const chartTiming = useMemo(() => raceChartTiming(positions, laps, results), [laps, positions, results])
|
||||
const hasChartData = hasPositions && chartTiming !== null
|
||||
const circuitKey = session?.circuit_key ?? meeting?.circuit_key ?? 0
|
||||
const outlineYear = meeting?.year ?? (session?.date_start ? new Date(session.date_start).getFullYear() : 0)
|
||||
const canProbeMap = Boolean(session?.session_key) && circuitKey > 0 && outlineYear > 0
|
||||
|
||||
const replayQuery = useQuery({
|
||||
queryKey: ['replay-frames', session?.session_key, 5000],
|
||||
queryFn: () => fetchReplayFrames(session!.session_key, 5000),
|
||||
enabled: canProbeMap,
|
||||
})
|
||||
const outlineQuery = useQuery({
|
||||
queryKey: ['track-outline', circuitKey, outlineYear],
|
||||
queryFn: () => fetchTrackOutline(circuitKey, outlineYear),
|
||||
enabled: canProbeMap,
|
||||
})
|
||||
|
||||
const mapProbeSettled = !canProbeMap || (!replayQuery.isLoading && !outlineQuery.isLoading)
|
||||
const mapAvailable = useMemo(
|
||||
() =>
|
||||
canProbeMap &&
|
||||
isReplayMapAvailable(
|
||||
replayQuery.data,
|
||||
outlineQuery.data,
|
||||
replayQuery.isError || outlineQuery.isError,
|
||||
),
|
||||
[canProbeMap, outlineQuery.data, outlineQuery.isError, replayQuery.data, replayQuery.isError],
|
||||
)
|
||||
const showMapPanel = mapOpen && mapAvailable
|
||||
|
||||
useEffect(() => {
|
||||
if (!mapAvailable && mapOpen) {
|
||||
setMapOpen(false)
|
||||
}
|
||||
}, [mapAvailable, mapOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPlaying || !chartTiming) return
|
||||
|
||||
let frame = 0
|
||||
let last = performance.now()
|
||||
const tick = (now: number) => {
|
||||
const delta = now - last
|
||||
last = now
|
||||
setScrubTime((current) => {
|
||||
const next = Math.min(1, (current ?? 0) + (delta * playbackSpeed) / chartTiming.tRange)
|
||||
if (next >= 1) {
|
||||
setIsPlaying(false)
|
||||
}
|
||||
return next
|
||||
})
|
||||
frame = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
frame = requestAnimationFrame(tick)
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [chartTiming, isPlaying, playbackSpeed])
|
||||
|
||||
const stopChapterTour = () => {
|
||||
setChapterTourActive(false)
|
||||
setTourChapterIndex(null)
|
||||
}
|
||||
|
||||
const jumpToChapter = (index: number, scrub: number) => {
|
||||
setIsPlaying(false)
|
||||
stopChapterTour()
|
||||
setSelectedChapterIndex(index)
|
||||
setScrubTime(scrub)
|
||||
}
|
||||
|
||||
const clearChapterSelection = () => {
|
||||
setSelectedChapterIndex(null)
|
||||
}
|
||||
|
||||
const toggleChapterTour = () => {
|
||||
if (chapterTourActive) {
|
||||
stopChapterTour()
|
||||
return
|
||||
}
|
||||
if (!chartTiming || chapters.length === 0) return
|
||||
setIsPlaying(false)
|
||||
setSelectedChapterIndex(null)
|
||||
setChapterTourActive(true)
|
||||
setTourChapterIndex(0)
|
||||
const startScrub = chapterStartScrub(chapters[0], chartTiming.tMin, chartTiming.tRange) ?? 0
|
||||
setScrubTime(startScrub)
|
||||
const durations = chapterTourDurations(chapters, CHAPTER_TOUR_MS)
|
||||
tourRef.current = {
|
||||
chapterIndex: 0,
|
||||
startedAt: performance.now(),
|
||||
durationMs: durations[0] ?? CHAPTER_TOUR_MS / chapters.length,
|
||||
startScrub,
|
||||
endScrub: chapterEndScrub(chapters[0], chartTiming.tMin, chartTiming.tRange) ?? startScrub,
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!chapterTourActive || !chartTiming || chapters.length === 0) return
|
||||
|
||||
let frame = 0
|
||||
const tick = (now: number) => {
|
||||
const state = tourRef.current
|
||||
const elapsed = now - state.startedAt
|
||||
const progress = Math.min(1, elapsed / Math.max(state.durationMs, 1))
|
||||
const scrub = state.startScrub + (state.endScrub - state.startScrub) * progress
|
||||
setScrubTime(scrub)
|
||||
setTourChapterIndex(state.chapterIndex)
|
||||
|
||||
if (progress >= 1) {
|
||||
const nextIndex = state.chapterIndex + 1
|
||||
if (nextIndex >= chapters.length) {
|
||||
stopChapterTour()
|
||||
return
|
||||
}
|
||||
const durations = chapterTourDurations(chapters, CHAPTER_TOUR_MS)
|
||||
const startScrub = chapterStartScrub(chapters[nextIndex], chartTiming.tMin, chartTiming.tRange) ?? 0
|
||||
const endScrub = chapterEndScrub(chapters[nextIndex], chartTiming.tMin, chartTiming.tRange) ?? startScrub
|
||||
tourRef.current = {
|
||||
chapterIndex: nextIndex,
|
||||
startedAt: now,
|
||||
durationMs: durations[nextIndex] ?? CHAPTER_TOUR_MS / chapters.length,
|
||||
startScrub,
|
||||
endScrub,
|
||||
}
|
||||
}
|
||||
frame = requestAnimationFrame(tick)
|
||||
}
|
||||
|
||||
frame = requestAnimationFrame(tick)
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [chapterTourActive, chartTiming, chapters])
|
||||
|
||||
useEffect(() => {
|
||||
if (!chapterTourActive) return
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
stopChapterTour()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
}, [chapterTourActive])
|
||||
|
||||
const replayTMs = useMemo(() => {
|
||||
const replay = replayQuery.data
|
||||
const frames = replay?.frames ?? []
|
||||
if (frames.length === 0) return 0
|
||||
const lastFrameT = frames[frames.length - 1].t
|
||||
const progress = scrubTime ?? 0
|
||||
if (!chartTiming || !replay?.start_time) {
|
||||
return Math.max(0, Math.min(lastFrameT, Math.round(progress * lastFrameT)))
|
||||
}
|
||||
const replayStart = new Date(replay.start_time).getTime()
|
||||
const chartTime = chartTiming.tMin + progress * chartTiming.tRange
|
||||
return Math.max(0, Math.min(lastFrameT, Math.round(chartTime - replayStart)))
|
||||
}, [chartTiming, replayQuery.data, scrubTime])
|
||||
|
||||
let chartContent = null
|
||||
let displayResults = results
|
||||
|
||||
if (hasChartData) {
|
||||
const tMin = new Date(allTimes[0]).getTime()
|
||||
const tMax = new Date(allTimes[allTimes.length - 1]).getTime()
|
||||
const tRange = Math.max(tMax - tMin, 1)
|
||||
if (hasChartData && chartTiming) {
|
||||
const { tMin, tRange } = chartTiming
|
||||
const normaliseTime = (time: number) => Math.max(0, Math.min(1, (time - tMin) / tRange))
|
||||
|
||||
const byDriver = new Map<number, Array<{ t: number; pos: number }>>()
|
||||
for (const p of positions) {
|
||||
const time = new Date(p.date).getTime()
|
||||
if (!Number.isFinite(time)) continue
|
||||
if (!byDriver.has(p.driver_number)) byDriver.set(p.driver_number, [])
|
||||
byDriver.get(p.driver_number)!.push({
|
||||
t: (new Date(p.date).getTime() - tMin) / tRange,
|
||||
t: normaliseTime(time),
|
||||
pos: p.position,
|
||||
})
|
||||
}
|
||||
const dnfSet = new Set(results.filter(r => r.dnf || r.dns || r.dsq).map(r => r.driver_number))
|
||||
const dnfSet = new Set(results.filter((r) => r.dnf || r.dns || r.dsq).map((r) => r.driver_number))
|
||||
for (const [dNum, samples] of byDriver.entries()) {
|
||||
samples.sort((a, b) => a.t - b.t)
|
||||
if (samples.length > 0 && !dnfSet.has(dNum)) {
|
||||
@@ -51,16 +299,16 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const getInterpPos = (samples: {t: number, pos: number}[], t: number) => {
|
||||
const getInterpPos = (samples: { t: number; pos: number }[], t: number) => {
|
||||
if (!samples || samples.length === 0) return null
|
||||
if (t <= samples[0].t) return samples[0].pos
|
||||
if (t >= samples[samples.length - 1].t) return samples[samples.length - 1].pos
|
||||
for (let i = 0; i < samples.length - 1; i++) {
|
||||
if (samples[i].t <= t && samples[i+1].t >= t) {
|
||||
const dt = samples[i+1].t - samples[i].t
|
||||
if (samples[i].t <= t && samples[i + 1].t >= t) {
|
||||
const dt = samples[i + 1].t - samples[i].t
|
||||
if (dt === 0) return samples[i].pos
|
||||
const frac = (t - samples[i].t) / dt
|
||||
return samples[i].pos + (samples[i+1].pos - samples[i].pos) * frac
|
||||
return samples[i].pos + (samples[i + 1].pos - samples[i].pos) * frac
|
||||
}
|
||||
}
|
||||
return null
|
||||
@@ -84,43 +332,46 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
const maxPos = Math.max(...positions.map((p) => p.position), results.length, 2)
|
||||
const colorByDriver = new Map(results.map((r) => [r.driver_number, r.team_colour]))
|
||||
const acronymByDriver = new Map(results.map((r) => [r.driver_number, r.name_acronym]))
|
||||
const positionLabels = decimatedPositionLabels(maxPos)
|
||||
|
||||
const W = 640
|
||||
const H = 180
|
||||
const PL = 40
|
||||
const PR = 48
|
||||
const PT = 8
|
||||
const PB = 20
|
||||
const W = CHART_W
|
||||
const H = CHART_H
|
||||
const PL = CHART_PL
|
||||
const PR = CHART_PR
|
||||
const PT = CHART_PT
|
||||
const PB = CHART_PB
|
||||
const plotW = W - PL - PR
|
||||
const plotH = H - PT - PB
|
||||
|
||||
const toX = (t: number) => PL + t * plotW
|
||||
const toY = (pos: number) => PT + ((pos - 1) / Math.max(maxPos - 1, 1)) * plotH
|
||||
|
||||
const winner = results.find(r => r.position === 1)
|
||||
const winnerLaps = winner ? laps.filter(l => l.driver_number === winner.driver_number) : []
|
||||
const lapTicks: { lap: number, t: number }[] = []
|
||||
const winner = results.find((r) => r.position === 1)
|
||||
const winnerLaps = winner ? laps.filter((l) => l.driver_number === winner.driver_number) : []
|
||||
const lapTicks: { lap: number; t: number }[] = []
|
||||
const lapInterval = winnerLaps.length < 30 ? 5 : 10
|
||||
|
||||
for (const lap of winnerLaps) {
|
||||
|
||||
for (let i = 0; i < winnerLaps.length; i++) {
|
||||
const lap = winnerLaps[i]
|
||||
if (lap.lap_number > 0 && lap.lap_number % lapInterval === 0) {
|
||||
const t = (new Date(lap.date_start).getTime() - tMin) / tRange
|
||||
if (t >= 0 && t <= 1) {
|
||||
lapTicks.push({ lap: lap.lap_number, t })
|
||||
}
|
||||
const lapStart = new Date(lap.date_start).getTime()
|
||||
const nextLapStart = winnerLaps[i + 1] ? new Date(winnerLaps[i + 1].date_start).getTime() : NaN
|
||||
const lapEnd = lap.lap_duration && lap.lap_duration > 0
|
||||
? lapStart + lap.lap_duration * 1000
|
||||
: nextLapStart
|
||||
if (Number.isFinite(lapEnd)) lapTicks.push({ lap: lap.lap_number, t: normaliseTime(lapEnd) })
|
||||
}
|
||||
}
|
||||
|
||||
// Safety Car / VSC periods
|
||||
const scPeriods: { start: number; end: number | null; type: 'SC' | 'VSC' }[] = []
|
||||
let activeSC: { start: number; type: 'SC' | 'VSC' } | null = null
|
||||
const rc = [...race_control].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
|
||||
|
||||
|
||||
for (const msg of rc) {
|
||||
const t = new Date(msg.date).getTime()
|
||||
const m = msg.message?.toUpperCase() || ''
|
||||
const cat = msg.category?.toUpperCase() || ''
|
||||
|
||||
|
||||
if (m.includes('VIRTUAL SAFETY CAR DEPLOYED') || cat === 'VIRTUALSAFETYCAR') {
|
||||
if (!activeSC) activeSC = { start: t, type: 'VSC' }
|
||||
} else if (m.includes('SAFETY CAR DEPLOYED') || cat === 'SAFETYCAR') {
|
||||
@@ -136,23 +387,73 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
scPeriods.push({ start: activeSC.start, end: null, type: activeSC.type })
|
||||
}
|
||||
|
||||
const chapterBands = chapters
|
||||
.map((chapter, index) => {
|
||||
const startT = chapterStartScrub(chapter, tMin, tRange)
|
||||
const endT = chapterEndScrub(chapter, tMin, tRange)
|
||||
if (startT === null) return null
|
||||
const end = endT ?? startT
|
||||
return {
|
||||
key: `${chapter.kind}-${index}`,
|
||||
start: Math.min(startT, end),
|
||||
end: Math.max(startT, end),
|
||||
fill: chapterBandFill(chapter.kind),
|
||||
}
|
||||
})
|
||||
.filter((band): band is NonNullable<typeof band> => band !== null)
|
||||
|
||||
const labelCandidates = Array.from(byDriver.entries())
|
||||
.map(([dNum, samples]) => {
|
||||
const last = samples[samples.length - 1]
|
||||
if (!last) return null
|
||||
return { key: dNum, y: toY(last.pos) }
|
||||
})
|
||||
.filter((item): item is { key: number; y: number } => item !== null)
|
||||
const labelYByDriver = deCollideYPositions(labelCandidates, 12)
|
||||
|
||||
const handlePointerMove = (e: React.PointerEvent<SVGRectElement>) => {
|
||||
setIsPlaying(false)
|
||||
stopChapterTour()
|
||||
clearChapterSelection()
|
||||
if (!svgRef.current) return
|
||||
const rect = svgRef.current.getBoundingClientRect()
|
||||
const x = e.clientX - rect.left
|
||||
if (rect.width <= 0) return
|
||||
// Pointer coordinates are CSS pixels; convert them to the SVG viewBox
|
||||
// before comparing with the fixed chart margins and plot width.
|
||||
const x = ((e.clientX - rect.left) / rect.width) * W
|
||||
const t = Math.max(0, Math.min(1, (x - PL) / plotW))
|
||||
setScrubTime(t)
|
||||
}
|
||||
|
||||
chartContent = (
|
||||
<div className="rs-chart-container scroll-x" data-testid="position-chart">
|
||||
<div
|
||||
className={`rs-chart-container scroll-x${showMapPanel ? '' : ' rs-chart-container--full'}`}
|
||||
data-testid="position-chart"
|
||||
>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="rs-position-chart-svg"
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
style={{ width: '100%', minWidth: 280, maxWidth: W, display: 'block' }}
|
||||
role="img"
|
||||
aria-label="Position evolution chart"
|
||||
>
|
||||
{chapterBands.map((band) => {
|
||||
const x1 = toX(Math.max(0, band.start))
|
||||
const x2 = toX(Math.min(1, band.end))
|
||||
if (x2 <= PL || x1 >= W - PR) return null
|
||||
return (
|
||||
<rect
|
||||
key={band.key}
|
||||
x={x1}
|
||||
y={PT}
|
||||
width={Math.max(0, x2 - x1)}
|
||||
height={plotH}
|
||||
fill={band.fill}
|
||||
data-testid="chapter-band"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{scPeriods.map((sc, i) => {
|
||||
const startT = (sc.start - tMin) / tRange
|
||||
const endT = sc.end ? (sc.end - tMin) / tRange : 1
|
||||
@@ -171,33 +472,41 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
)
|
||||
})}
|
||||
|
||||
{Array.from({ length: maxPos }, (_, i) => i + 1).map((pos) => (
|
||||
{positionLabels.map((pos) => (
|
||||
<g key={pos}>
|
||||
<line
|
||||
x1={PL}
|
||||
x2={W - PR}
|
||||
y1={toY(pos)}
|
||||
y2={toY(pos)}
|
||||
stroke="var(--border)"
|
||||
strokeWidth={0.5}
|
||||
className="rs-chart-grid-line"
|
||||
/>
|
||||
<text
|
||||
x={PL - 4}
|
||||
y={toY(pos) + 4}
|
||||
textAnchor="end"
|
||||
fill="var(--text-3)"
|
||||
fontSize={8}
|
||||
fontFamily="var(--f-mono)"
|
||||
className="rs-chart-axis-label"
|
||||
>
|
||||
P{pos}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
|
||||
{lapTicks.map(tick => (
|
||||
{lapTicks.map((tick) => (
|
||||
<g key={`lap-${tick.lap}`}>
|
||||
<line x1={toX(tick.t)} x2={toX(tick.t)} y1={H - PB} y2={H - PB + 4} stroke="var(--border)" strokeWidth={1} />
|
||||
<text x={toX(tick.t)} y={H - PB + 14} textAnchor="middle" fill="var(--text-3)" fontSize={9} fontFamily="var(--f-mono)">
|
||||
<line
|
||||
x1={toX(tick.t)}
|
||||
x2={toX(tick.t)}
|
||||
y1={H - PB}
|
||||
y2={H - PB + 4}
|
||||
className="rs-chart-lap-tick"
|
||||
/>
|
||||
<text
|
||||
x={toX(tick.t)}
|
||||
y={H - PB + 14}
|
||||
textAnchor="middle"
|
||||
className="rs-chart-axis-label"
|
||||
>
|
||||
L{tick.lap}
|
||||
</text>
|
||||
</g>
|
||||
@@ -210,11 +519,12 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
const last = samples[samples.length - 1]
|
||||
const isHovered = hoverDriver === dNum
|
||||
const isFaded = hoverDriver !== null && !isHovered
|
||||
const labelY = last ? (labelYByDriver.get(dNum) ?? toY(last.pos)) : 0
|
||||
|
||||
const driverPits = pit_stops.filter(p => p.driver_number === dNum)
|
||||
const driverPits = pit_stops.filter((p) => p.driver_number === dNum)
|
||||
|
||||
return (
|
||||
<g
|
||||
<g
|
||||
key={dNum}
|
||||
style={{ opacity: isFaded ? 0.2 : 1, transition: 'opacity 0.2s' }}
|
||||
onMouseEnter={() => setHoverDriver(dNum)}
|
||||
@@ -230,30 +540,31 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
className="rs-driver-line"
|
||||
pathLength={1}
|
||||
/>
|
||||
|
||||
|
||||
{driverPits.map((p, i) => {
|
||||
const t = (new Date(p.date).getTime() - tMin) / tRange
|
||||
if (t < 0 || t > 1) return null
|
||||
const time = new Date(p.date).getTime()
|
||||
if (!Number.isFinite(time) || time < tMin || time > tMin + tRange) return null
|
||||
const t = normaliseTime(time)
|
||||
const pos = getInterpPos(samples, t)
|
||||
if (pos === null) return null
|
||||
return (
|
||||
<circle
|
||||
key={`pit-${i}`}
|
||||
cx={toX(t)}
|
||||
cy={toY(pos)}
|
||||
r={3}
|
||||
fill="var(--bg)"
|
||||
stroke={color}
|
||||
<circle
|
||||
key={`pit-${i}`}
|
||||
cx={toX(t)}
|
||||
cy={toY(pos)}
|
||||
r={3}
|
||||
fill="var(--bg)"
|
||||
stroke={color}
|
||||
strokeWidth={2}
|
||||
className="rs-pit-dot"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
|
||||
{last && (
|
||||
<text
|
||||
x={toX(last.t) + 6}
|
||||
y={toY(last.pos) + 4}
|
||||
y={labelY + 4}
|
||||
fill={color}
|
||||
fontSize={isHovered ? 11 : 9}
|
||||
fontFamily="var(--f-mono)"
|
||||
@@ -287,25 +598,110 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
width={plotW}
|
||||
height={plotH}
|
||||
fill="transparent"
|
||||
data-testid="position-chart-interaction"
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerLeave={() => setScrubTime(null)}
|
||||
onPointerLeave={() => {
|
||||
if (!isPlaying) {
|
||||
clearChapterSelection()
|
||||
setScrubTime(null)
|
||||
}
|
||||
}}
|
||||
style={{ cursor: 'crosshair', touchAction: 'none' }}
|
||||
/>
|
||||
</svg>
|
||||
<div className="rs-segmented-control" aria-label="Race replay controls" data-testid="replay-controls">
|
||||
<button
|
||||
type="button"
|
||||
className={`rs-segment ${isPlaying ? 'active' : ''}`}
|
||||
onClick={() => {
|
||||
setScrubTime((current) => current ?? 0)
|
||||
stopChapterTour()
|
||||
clearChapterSelection()
|
||||
setIsPlaying((current) => !current)
|
||||
}}
|
||||
aria-pressed={isPlaying}
|
||||
>
|
||||
{isPlaying ? 'Pause' : 'Play'}
|
||||
</button>
|
||||
<span className="rs-segment-divider" aria-hidden />
|
||||
{[1, 10, 30].map((speed) => (
|
||||
<button
|
||||
key={speed}
|
||||
type="button"
|
||||
className={`rs-segment ${playbackSpeed === speed ? 'active' : ''}`}
|
||||
onClick={() => setPlaybackSpeed(speed)}
|
||||
aria-pressed={playbackSpeed === speed}
|
||||
>
|
||||
{speed}x
|
||||
</button>
|
||||
))}
|
||||
{mapProbeSettled && mapAvailable && (
|
||||
<>
|
||||
<span className="rs-segment-divider" aria-hidden />
|
||||
<button
|
||||
type="button"
|
||||
className={`rs-segment ${mapOpen ? 'active' : ''}`}
|
||||
onClick={() => setMapOpen((current) => !current)}
|
||||
aria-pressed={mapOpen}
|
||||
data-testid="replay-map-toggle"
|
||||
>
|
||||
Map
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="race-story-canvas">
|
||||
{hasChartData ? (
|
||||
chartContent
|
||||
) : (
|
||||
<div className="analysis-notice">
|
||||
<strong>Lap-by-lap positions not available.</strong> This session does not
|
||||
have ingested position samples in <code>/api/v1/race-hub</code>.
|
||||
</div>
|
||||
{hasChartData && chartTiming && chapters.length > 0 && (
|
||||
<ChapterStrip
|
||||
chapters={chapters}
|
||||
scrubTime={scrubTime}
|
||||
tMin={chartTiming.tMin}
|
||||
tRange={chartTiming.tRange}
|
||||
tourActive={chapterTourActive}
|
||||
tourChapterIndex={tourChapterIndex}
|
||||
selectedChapterIndex={selectedChapterIndex}
|
||||
onChapterClick={jumpToChapter}
|
||||
onTourToggle={toggleChapterTour}
|
||||
/>
|
||||
)}
|
||||
<div className={`rs-replay-shell${showMapPanel ? ' rs-replay-shell--split' : ''}`}>
|
||||
<div className="rs-replay-main">
|
||||
{hasChartData ? (
|
||||
chartContent
|
||||
) : (
|
||||
<EmptyStateCard
|
||||
icon={LineChart}
|
||||
title="Lap-by-lap positions not available"
|
||||
hint={
|
||||
<>
|
||||
This session does not have ingested position samples in{' '}
|
||||
<code>/api/v1/race-hub</code>.
|
||||
</>
|
||||
}
|
||||
testId="race-story-no-positions"
|
||||
className="race-story-empty-card"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{showMapPanel && (
|
||||
<div className="rs-replay-map-slot" data-testid="replay-map-slot">
|
||||
<ReplayTrackMap
|
||||
outline={outlineQuery.data}
|
||||
replay={replayQuery.data}
|
||||
tMs={replayTMs}
|
||||
drivers={drivers}
|
||||
results={results}
|
||||
loading={outlineQuery.isLoading || replayQuery.isLoading}
|
||||
error={outlineQuery.isError || replayQuery.isError}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{displayResults.length > 0 && (
|
||||
<div className="rs-field-list">
|
||||
@@ -313,30 +709,29 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
const gridPos = grid.find((g) => g.driver_number === r.driver_number)?.position ?? 0
|
||||
const currentPos = scrubTime !== null ? i + 1 : r.position
|
||||
const isWinner = i === 0 && r.position === 1
|
||||
const pClass = currentPos === 1 ? 'rs-pos-p1' : currentPos === 2 ? 'rs-pos-p2' : currentPos === 3 ? 'rs-pos-p3' : ''
|
||||
|
||||
const pClass =
|
||||
currentPos === 1 ? 'rs-pos-p1' : currentPos === 2 ? 'rs-pos-p2' : currentPos === 3 ? 'rs-pos-p3' : ''
|
||||
|
||||
let currentPoints: number | string = r.points
|
||||
if (scrubTime !== null) {
|
||||
const isSprint = data.session?.session_type?.toLowerCase().includes('sprint')
|
||||
const ptsArray = isSprint ? [8, 7, 6, 5, 4, 3, 2, 1] : [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]
|
||||
currentPoints = currentPos <= ptsArray.length ? ptsArray[currentPos - 1] : 0
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<div
|
||||
key={r.driver_number}
|
||||
<div
|
||||
key={r.driver_number}
|
||||
className={`rs-driver-row ${hoverDriver === r.driver_number ? 'rs-driver-row-hover' : ''}`}
|
||||
onMouseEnter={() => setHoverDriver(r.driver_number)}
|
||||
onMouseLeave={() => setHoverDriver(null)}
|
||||
>
|
||||
<div className="rs-driver-left">
|
||||
<div className={`rs-pos-col ${pClass}`}>
|
||||
{currentPos}
|
||||
</div>
|
||||
<div className={`rs-pos-col ${pClass}`}>{currentPos}</div>
|
||||
<div className="rs-driver-cell">
|
||||
<div
|
||||
className="rs-driver-color"
|
||||
style={{ background: r.team_colour ? `#${r.team_colour}` : 'var(--border)' }}
|
||||
<div
|
||||
className="rs-driver-color"
|
||||
style={{ background: r.team_colour ? `#${r.team_colour}` : 'var(--border)' }}
|
||||
/>
|
||||
<div className="rs-driver-identity">
|
||||
<span className="rs-driver-name">{r.name_acronym || r.driver_number}</span>
|
||||
@@ -354,12 +749,12 @@ export function RaceStoryCanvas({ data }: Props) {
|
||||
</span>
|
||||
<span className="rs-metric-label">Grid</span>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="rs-metric" style={{ width: '80px', opacity: scrubTime !== null ? 0.3 : 1 }}>
|
||||
<span>{isWinner ? formatDuration(r.duration) : formatGap(r.gap_to_leader)}</span>
|
||||
<span className="rs-metric-label">{isWinner ? 'Time' : 'Gap'}</span>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="rs-metric" style={{ width: '40px' }}>
|
||||
<span style={{ color: Number(currentPoints) > 0 ? 'var(--text)' : 'var(--text-3)' }}>
|
||||
{currentPoints}
|
||||
|
||||
159
frontend/src/components/ReplayTrackMap.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Loader2, MapPin, Satellite } from 'lucide-react'
|
||||
import type { Driver, EnrichedResult, ReplayFramesResponse, TrackOutline } from '../types'
|
||||
import { buildOutlinePath } from '../lib/trackmap'
|
||||
import { interpolateReplayCars, replayCarToSvg } from '../lib/replay'
|
||||
import { EmptyStateCard } from './EmptyStateCard'
|
||||
import '../styles/replay-map.css'
|
||||
|
||||
interface Props {
|
||||
outline?: TrackOutline | null
|
||||
replay?: ReplayFramesResponse | null
|
||||
tMs: number
|
||||
drivers: Driver[]
|
||||
results: EnrichedResult[]
|
||||
loading?: boolean
|
||||
error?: boolean
|
||||
}
|
||||
|
||||
export function ReplayTrackMap({
|
||||
outline,
|
||||
replay,
|
||||
tMs,
|
||||
drivers,
|
||||
results,
|
||||
loading = false,
|
||||
error = false,
|
||||
}: Props) {
|
||||
const [pinned, setPinned] = useState<string | null>(null)
|
||||
const outlinePath = useMemo(() => buildOutlinePath(outline?.points ?? []), [outline])
|
||||
const driverInfo = useMemo(() => {
|
||||
const info = new Map<string, { label: string; color: string }>()
|
||||
for (const driver of drivers) {
|
||||
info.set(String(driver.driver_number), {
|
||||
label: driver.name_acronym || String(driver.driver_number),
|
||||
color: normalizeColor(driver.team_colour),
|
||||
})
|
||||
}
|
||||
for (const result of results) {
|
||||
const key = String(result.driver_number)
|
||||
if (!info.has(key)) {
|
||||
info.set(key, {
|
||||
label: result.name_acronym || key,
|
||||
color: normalizeColor(result.team_colour),
|
||||
})
|
||||
}
|
||||
}
|
||||
return info
|
||||
}, [drivers, results])
|
||||
|
||||
const cars = useMemo(() => {
|
||||
if (!outline?.bounds || !replay?.frames?.length) return []
|
||||
const positions = interpolateReplayCars(replay.frames, tMs)
|
||||
return Object.entries(positions)
|
||||
.map(([number, car]) => ({
|
||||
number,
|
||||
svg: replayCarToSvg(car, outline.bounds),
|
||||
info: driverInfo.get(number),
|
||||
}))
|
||||
.sort((a, b) => Number(a.number) - Number(b.number))
|
||||
}, [driverInfo, outline?.bounds, replay?.frames, tMs])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section className="replay-map-panel" data-testid="replay-track-map">
|
||||
<EmptyStateCard
|
||||
icon={Loader2}
|
||||
title="Loading replay map"
|
||||
hint="Fetching track outline and historical GPS frames."
|
||||
testId="replay-map-loading"
|
||||
className="replay-map-empty-card"
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<section className="replay-map-panel" data-testid="replay-track-map">
|
||||
<EmptyStateCard
|
||||
icon={Satellite}
|
||||
title="Replay GPS unavailable"
|
||||
hint="This session does not have ingested location samples for the replay map."
|
||||
testId="replay-map-error"
|
||||
className="replay-map-empty-card"
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
if (!outline || !outlinePath) {
|
||||
return (
|
||||
<section className="replay-map-panel" data-testid="replay-track-map">
|
||||
<EmptyStateCard
|
||||
icon={MapPin}
|
||||
title="Track outline unavailable"
|
||||
hint="Circuit GPS outline data is missing for this session."
|
||||
testId="replay-map-no-outline"
|
||||
className="replay-map-empty-card"
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
if (!replay?.frames?.length || cars.length === 0) {
|
||||
return (
|
||||
<section className="replay-map-panel" data-testid="replay-track-map">
|
||||
<EmptyStateCard
|
||||
icon={Satellite}
|
||||
title="Historical GPS unavailable"
|
||||
hint="Fewer than two replay frames were returned for this session."
|
||||
testId="replay-map-no-frames"
|
||||
className="replay-map-empty-card"
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="replay-map-panel" data-testid="replay-track-map">
|
||||
<div className="replay-map-stage">
|
||||
<svg className="replay-map-svg" viewBox="0 0 100 100" role="img" aria-label="Replay track map">
|
||||
<path className="replay-map-outline-shadow" d={outlinePath} />
|
||||
<path className="replay-map-outline" d={outlinePath} />
|
||||
{cars.map((car) => {
|
||||
const label = car.info?.label ?? car.number
|
||||
const selected = pinned === car.number
|
||||
return (
|
||||
<g
|
||||
key={car.number}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${label} replay position`}
|
||||
className={`replay-car ${selected ? 'replay-car-pinned' : ''}`}
|
||||
transform={`translate(${car.svg.x.toFixed(2)} ${car.svg.y.toFixed(2)})`}
|
||||
onClick={() => setPinned(selected ? null : car.number)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
setPinned(selected ? null : car.number)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<title>{label}</title>
|
||||
<circle r="2.7" fill={car.info?.color ?? '#777777'} />
|
||||
<text y="0.85">{label}</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeColor(color: string | undefined): string {
|
||||
const raw = color?.trim()
|
||||
if (!raw) return '#777777'
|
||||
return raw.startsWith('#') ? raw : `#${raw}`
|
||||
}
|
||||
271
frontend/src/components/RivalryCompare.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import type { ChampHubDriver, ChampionshipHub } from '../types'
|
||||
import { teamColor } from '../utils'
|
||||
import { gapSeries, h2hTally, lastRounds } from '../lib/rivalry'
|
||||
import '../styles/rivalry.css'
|
||||
|
||||
const PAD_L = 48
|
||||
const PAD_T = 16
|
||||
const PLOT_W = 882
|
||||
const PLOT_H = 316
|
||||
const GAP_PLOT_H = 200
|
||||
|
||||
function fmtPts(n: number): string {
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
/** Up to ~7 evenly spaced round labels, always including the last round. */
|
||||
function xTicks(n: number, labels: string[], x: (i: number) => number): { x: number; label: string }[] {
|
||||
const step = Math.max(1, Math.ceil(n / 7))
|
||||
const ticks: { x: number; label: string }[] = []
|
||||
for (let i = 0; i < n; i += step) {
|
||||
ticks.push({ x: x(i), label: labels[i] ?? `R${i + 1}` })
|
||||
}
|
||||
const last = labels[n - 1] ?? `R${n}`
|
||||
if (ticks[ticks.length - 1]?.label !== last) {
|
||||
ticks.push({ x: x(n - 1), label: last })
|
||||
}
|
||||
return ticks
|
||||
}
|
||||
|
||||
function polyline(values: number[], x: (i: number) => number, y: (v: number) => number): string {
|
||||
return values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ')
|
||||
}
|
||||
|
||||
interface PickerProps {
|
||||
id: 'a' | 'b'
|
||||
label: string
|
||||
drivers: ChampHubDriver[]
|
||||
value: number
|
||||
color: string
|
||||
onChange: (driverNumber: number) => void
|
||||
}
|
||||
|
||||
function DriverPicker({ id, label, drivers, value, color, onChange }: PickerProps) {
|
||||
return (
|
||||
<label className="rivalry-picker">
|
||||
<span className="rivalry-picker-label">{label}</span>
|
||||
<select
|
||||
className="rivalry-picker-select"
|
||||
style={{ borderLeft: `3px solid ${color}` }}
|
||||
value={value}
|
||||
data-testid={`rivalry-pick-${id}`}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
>
|
||||
{drivers.map((d) => (
|
||||
<option key={d.driver_number} value={d.driver_number}>
|
||||
{d.name_acronym} · {d.full_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export function RivalryCompare({ hub }: { hub: ChampionshipHub }) {
|
||||
const { drivers } = hub
|
||||
const [pickA, setPickA] = useState<number | null>(null)
|
||||
const [pickB, setPickB] = useState<number | null>(null)
|
||||
|
||||
// Default to the top two in the standings; fall back there if a picked
|
||||
// driver disappears (e.g. season switch re-fetches the hub).
|
||||
const a = drivers.find((d) => d.driver_number === pickA) ?? drivers[0]
|
||||
const b = drivers.find((d) => d.driver_number === pickB) ?? drivers[1]
|
||||
|
||||
const tally = useMemo(
|
||||
() => (a && b ? h2hTally(a.round_positions ?? [], b.round_positions ?? [], hub.round_labels) : null),
|
||||
[a, b, hub.round_labels],
|
||||
)
|
||||
|
||||
if (drivers.length < 2) {
|
||||
return (
|
||||
<div className="champ-chart-empty" data-testid="champ-view-rivalry">
|
||||
Need at least two drivers in the standings to compare a rivalry.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const colorA = teamColor(a.team_colour)
|
||||
const colorB = teamColor(b.team_colour)
|
||||
const sameTeam = a.team_name === b.team_name
|
||||
|
||||
const cumA = a.cumulative ?? []
|
||||
const cumB = b.cumulative ?? []
|
||||
const rounds = Math.min(cumA.length, cumB.length)
|
||||
const gaps = gapSeries(cumA, cumB)
|
||||
const lastGap = gaps[gaps.length - 1] ?? 0
|
||||
const strip = tally ? lastRounds(tally, 5) : []
|
||||
|
||||
const pickers = (
|
||||
<div className="rivalry-pickers">
|
||||
<DriverPicker id="a" label="Driver A" drivers={drivers} value={a.driver_number} color={colorA} onChange={setPickA} />
|
||||
<span className="rivalry-vs mono">vs</span>
|
||||
<DriverPicker id="b" label="Driver B" drivers={drivers} value={b.driver_number} color={colorB} onChange={setPickB} />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (rounds === 0) {
|
||||
return (
|
||||
<div className="rivalry" data-testid="champ-view-rivalry">
|
||||
{pickers}
|
||||
<div className="champ-chart-empty">
|
||||
No completed rounds yet — the rivalry will appear after the first race.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Points race scales.
|
||||
const peak = Math.max(...cumA.slice(0, rounds), ...cumB.slice(0, rounds), 1)
|
||||
const maxY = Math.max(50, Math.ceil(peak / 50) * 50)
|
||||
const px = (i: number) => (rounds <= 1 ? PAD_L : PAD_L + (i * PLOT_W) / (rounds - 1))
|
||||
const py = (v: number) => PAD_T + PLOT_H - (v / maxY) * PLOT_H
|
||||
const pyGrid = [0, 0.25, 0.5, 0.75, 1].map((f) => ({ y: py(maxY * f), label: Math.round(maxY * f) }))
|
||||
const pxGrid = xTicks(rounds, hub.round_labels, px)
|
||||
|
||||
// Gap scales: symmetric around zero.
|
||||
const maxAbs = Math.max(10, Math.ceil(Math.max(...gaps.map(Math.abs), 1) / 10) * 10)
|
||||
const gy = (v: number) => PAD_T + GAP_PLOT_H / 2 - (v / maxAbs) * (GAP_PLOT_H / 2)
|
||||
const gyGrid = [maxAbs, 0, -maxAbs].map((v) => ({ y: gy(v), label: v > 0 ? `+${v}` : String(v) }))
|
||||
const gxGrid = xTicks(rounds, hub.round_labels, px)
|
||||
|
||||
const gapLeader = lastGap === 0 ? null : lastGap > 0 ? a : b
|
||||
const gapCaption = gapLeader
|
||||
? `${gapLeader.name_acronym} leads by ${fmtPts(Math.abs(lastGap))} pts after ${hub.round_labels[rounds - 1] ?? `R${rounds}`}.`
|
||||
: 'Dead level on points.'
|
||||
|
||||
return (
|
||||
<div className="rivalry" data-testid="champ-view-rivalry">
|
||||
{pickers}
|
||||
|
||||
<div className="rivalry-h2h" data-testid="rivalry-h2h">
|
||||
<div className="rivalry-h2h-score">
|
||||
<span className="rivalry-h2h-code mono" style={{ color: colorA }}>
|
||||
{a.name_acronym}
|
||||
</span>
|
||||
<span className="rivalry-h2h-num mono" data-testid="rivalry-h2h-num">
|
||||
{tally ? `${tally.a}–${tally.b}` : '—'}
|
||||
</span>
|
||||
<span className="rivalry-h2h-code mono" style={{ color: colorB }}>
|
||||
{b.name_acronym}
|
||||
</span>
|
||||
</div>
|
||||
<span className="rivalry-h2h-meta">
|
||||
Race head-to-head · {tally?.rounds.length ?? 0} round{(tally?.rounds.length ?? 0) === 1 ? '' : 's'} counted
|
||||
{tally && tally.skipped > 0 ? ` · ${tally.skipped} skipped` : ''}
|
||||
</span>
|
||||
{strip.length > 0 && (
|
||||
<div className="rivalry-strip" data-testid="rivalry-strip">
|
||||
<span className="rivalry-strip-label">Last {strip.length}</span>
|
||||
{strip.map((r) => (
|
||||
<span className="rivalry-chip" key={r.round} title={`${r.label}: ${a.name_acronym} P${r.posA} · ${b.name_acronym} P${r.posB}`}>
|
||||
<span className="rivalry-chip-round mono">{r.label}</span>
|
||||
<span className="rivalry-chip-winner mono" style={{ color: r.winner === 'a' ? colorA : colorB }}>
|
||||
{r.winner === 'a' ? a.name_acronym : b.name_acronym}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<section className="rivalry-section" data-testid="rivalry-points-race">
|
||||
<div className="champ-chart-head">
|
||||
<span className="champ-chart-title mono">
|
||||
Points race — {a.name_acronym} vs {b.name_acronym}
|
||||
</span>
|
||||
<span className="champ-chart-meta">
|
||||
Rounds 1–{rounds} · {hub.season}
|
||||
</span>
|
||||
</div>
|
||||
<div className="champ-chart">
|
||||
<svg viewBox="0 0 1000 380" className="champ-chart-svg" preserveAspectRatio="none">
|
||||
{pyGrid.map((g) => (
|
||||
<g key={g.label}>
|
||||
<line x1={PAD_L} y1={g.y} x2={930} y2={g.y} stroke="var(--border)" strokeWidth="1" />
|
||||
<text x={40} y={g.y + 4} textAnchor="end" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{pxGrid.map((g, i) => (
|
||||
<text key={i} x={g.x} y={372} textAnchor="middle" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
))}
|
||||
{[
|
||||
{ slot: 'a', d: a, color: colorA, dash: '0', values: cumA.slice(0, rounds) },
|
||||
{ slot: 'b', d: b, color: colorB, dash: sameTeam ? '5 4' : '0', values: cumB.slice(0, rounds) },
|
||||
].map((s) => (
|
||||
<g key={s.slot}>
|
||||
<polyline
|
||||
points={polyline(s.values, px, py)}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
strokeWidth="2.4"
|
||||
strokeDasharray={s.dash}
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle cx={px(s.values.length - 1)} cy={py(s.values[s.values.length - 1])} r="3" fill={s.color} />
|
||||
<text
|
||||
x={px(s.values.length - 1) + 8}
|
||||
y={py(s.values[s.values.length - 1]) + 4}
|
||||
fill={s.color}
|
||||
className="champ-chart-label"
|
||||
>
|
||||
{s.d.name_acronym}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rivalry-section" data-testid="rivalry-gap">
|
||||
<div className="champ-chart-head">
|
||||
<span className="champ-chart-title mono">
|
||||
Gap over season — {a.name_acronym} − {b.name_acronym}
|
||||
</span>
|
||||
<span className="champ-chart-meta">{gapCaption}</span>
|
||||
</div>
|
||||
<div className="champ-chart">
|
||||
<svg viewBox="0 0 1000 250" className="champ-chart-svg" preserveAspectRatio="none">
|
||||
{gyGrid.map((g) => (
|
||||
<g key={g.label}>
|
||||
<line
|
||||
x1={PAD_L}
|
||||
y1={g.y}
|
||||
x2={930}
|
||||
y2={g.y}
|
||||
stroke={g.label === '0' ? 'var(--border-2)' : 'var(--border)'}
|
||||
strokeWidth={g.label === '0' ? 1.5 : 1}
|
||||
/>
|
||||
<text x={40} y={g.y + 4} textAnchor="end" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{gxGrid.map((g, i) => (
|
||||
<text key={i} x={g.x} y={242} textAnchor="middle" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
))}
|
||||
<polyline
|
||||
points={polyline(gaps, px, gy)}
|
||||
fill="none"
|
||||
stroke={colorA}
|
||||
strokeWidth="2.4"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle cx={px(gaps.length - 1)} cy={gy(lastGap)} r="3" fill={colorA} />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="rivalry-caption">
|
||||
Above the zero line: {a.name_acronym} ahead. Below: {b.name_acronym} ahead.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
type Source = 'local' | 'partial' | 'none'
|
||||
type Source = 'local' | 'partial' | 'none' | 'cancelled'
|
||||
|
||||
interface Props {
|
||||
source: Source
|
||||
@@ -11,6 +11,8 @@ export function SourceBadge({ source, label }: Props) {
|
||||
return <span className="badge badge-local">{label ?? 'Local'}</span>
|
||||
case 'partial':
|
||||
return <span className="badge badge-partial">{label ?? 'Partial'}</span>
|
||||
case 'cancelled':
|
||||
return <span className="badge badge-cancelled">{label ?? 'Cancelled'}</span>
|
||||
default:
|
||||
return <span className="badge badge-none">{label ?? 'None'}</span>
|
||||
}
|
||||
@@ -22,6 +24,8 @@ export function weekendStatusLabel(source: Source): string {
|
||||
return 'Full'
|
||||
case 'partial':
|
||||
return 'Partial'
|
||||
case 'cancelled':
|
||||
return 'Cancelled'
|
||||
default:
|
||||
return 'Missing'
|
||||
}
|
||||
|
||||
@@ -1,28 +1,9 @@
|
||||
import type { EnrichedResult, Stint, PitStop } from '../types'
|
||||
import { compareFinishPosition } from '../utils'
|
||||
|
||||
const COMPOUND_COLORS: Record<string, string> = {
|
||||
SOFT: '#e8002d',
|
||||
MEDIUM: '#ffd600',
|
||||
HARD: '#e8e8e4',
|
||||
INTERMEDIATE: '#39b54a',
|
||||
WET: '#0067ff',
|
||||
}
|
||||
|
||||
function compoundColor(c: string): string {
|
||||
return COMPOUND_COLORS[c.toUpperCase()] ?? '#666'
|
||||
}
|
||||
|
||||
function compoundInitial(c: string): string {
|
||||
const abbr: Record<string, string> = {
|
||||
SOFT: 'S',
|
||||
MEDIUM: 'M',
|
||||
HARD: 'H',
|
||||
INTERMEDIATE: 'I',
|
||||
WET: 'W',
|
||||
}
|
||||
return abbr[c.toUpperCase()] ?? c[0] ?? '?'
|
||||
}
|
||||
import {
|
||||
TyreStintTimeline,
|
||||
type StintTimelineRow,
|
||||
} from './charts/TyreStintTimeline'
|
||||
|
||||
interface Props {
|
||||
results: EnrichedResult[]
|
||||
@@ -89,147 +70,33 @@ export function StrategyView({ results, stints, pit_stops, hasStints }: Props) {
|
||||
const cmp = compareFinishPosition(a.position, b.position)
|
||||
return cmp !== 0 ? cmp : a.driver_number - b.driver_number
|
||||
})
|
||||
|
||||
const totalLaps = Math.max(
|
||||
...stints.map((s) => s.lap_end),
|
||||
...results.map((r) => r.number_of_laps),
|
||||
1
|
||||
1,
|
||||
)
|
||||
|
||||
const SVG_W = 640
|
||||
const LEFT = 48
|
||||
const RIGHT = 12
|
||||
const ROW_H = 28
|
||||
const BAR_H = 14
|
||||
const BAR_Y = 7
|
||||
const BAR_W = SVG_W - LEFT - RIGHT
|
||||
const SVG_H = sortedDrivers.length * ROW_H + 8
|
||||
|
||||
const lapX = (lap: number) => LEFT + ((lap - 1) / totalLaps) * BAR_W
|
||||
const stintW = (s: Stint) =>
|
||||
Math.max(2, ((s.lap_end - s.lap_start + 1) / totalLaps) * BAR_W)
|
||||
|
||||
const usedCompounds = [...new Set(stints.map((s) => s.compound.toUpperCase()))].filter(
|
||||
(c) => c in COMPOUND_COLORS
|
||||
)
|
||||
const timelineRows: StintTimelineRow[] = sortedDrivers.map((driver) => ({
|
||||
label: driver.name_acronym || String(driver.driver_number),
|
||||
color: driver.team_colour ? `#${driver.team_colour}` : '#888',
|
||||
stints: stints
|
||||
.filter((s) => s.driver_number === driver.driver_number)
|
||||
.map((s) => ({
|
||||
compound: s.compound,
|
||||
lapStart: s.lap_start,
|
||||
lapEnd: s.lap_end,
|
||||
isNew: s.tyre_age_at_start === 0,
|
||||
})),
|
||||
pitStops: pit_stops
|
||||
.filter((p) => p.driver_number === driver.driver_number)
|
||||
.map((p) => p.lap_number)
|
||||
.sort((a, b) => a - b),
|
||||
}))
|
||||
|
||||
return (
|
||||
<div data-testid="strategy-chart">
|
||||
<div className="scroll-x">
|
||||
<svg
|
||||
viewBox={`0 0 ${SVG_W} ${SVG_H}`}
|
||||
style={{ width: '100%', minWidth: 280, maxWidth: SVG_W, display: 'block' }}
|
||||
role="img"
|
||||
aria-label="Race strategy stint chart"
|
||||
>
|
||||
{sortedDrivers.map((driver, i) => {
|
||||
const rowY = i * ROW_H
|
||||
const color = driver.team_colour ? `#${driver.team_colour}` : '#888'
|
||||
const dStints = stints.filter((s) => s.driver_number === driver.driver_number)
|
||||
const dPits = pit_stops.filter((p) => p.driver_number === driver.driver_number)
|
||||
|
||||
return (
|
||||
<g key={driver.driver_number} transform={`translate(0,${rowY})`}>
|
||||
<text
|
||||
x={LEFT - 5}
|
||||
y={BAR_Y + BAR_H / 2 + 4}
|
||||
textAnchor="end"
|
||||
fill={color}
|
||||
fontFamily="var(--f-mono)"
|
||||
fontWeight={700}
|
||||
fontSize={10}
|
||||
>
|
||||
{driver.name_acronym}
|
||||
</text>
|
||||
|
||||
{dStints.map((stint, si) => {
|
||||
const x = lapX(stint.lap_start)
|
||||
const w = stintW(stint)
|
||||
const fill = compoundColor(stint.compound)
|
||||
return (
|
||||
<g key={si}>
|
||||
<rect x={x} y={BAR_Y} width={w} height={BAR_H} fill={fill} rx={1.5} />
|
||||
{w > 18 && (
|
||||
<text
|
||||
x={x + w / 2}
|
||||
y={BAR_Y + BAR_H / 2 + 4}
|
||||
textAnchor="middle"
|
||||
fill="#111"
|
||||
fontFamily="var(--f-mono)"
|
||||
fontWeight={700}
|
||||
fontSize={8}
|
||||
>
|
||||
{compoundInitial(stint.compound)}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
{dPits.map((pit, pi) => {
|
||||
const x = lapX(pit.lap_number)
|
||||
return (
|
||||
<line
|
||||
key={pi}
|
||||
x1={x}
|
||||
x2={x}
|
||||
y1={BAR_Y - 3}
|
||||
y2={BAR_Y + BAR_H + 3}
|
||||
stroke="var(--text)"
|
||||
strokeWidth={1.5}
|
||||
opacity={0.7}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: 'var(--s4)',
|
||||
flexWrap: 'wrap',
|
||||
marginTop: 'var(--s4)',
|
||||
fontSize: 11,
|
||||
color: 'var(--text-3)',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
{usedCompounds.map((c) => (
|
||||
<span key={c} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
|
||||
<span
|
||||
style={{
|
||||
width: 10,
|
||||
height: 10,
|
||||
background: COMPOUND_COLORS[c],
|
||||
borderRadius: 2,
|
||||
display: 'inline-block',
|
||||
border: c === 'HARD' ? '1px solid #555' : undefined,
|
||||
}}
|
||||
/>
|
||||
{c.charAt(0) + c.slice(1).toLowerCase()}
|
||||
</span>
|
||||
))}
|
||||
{pit_stops.length > 0 && (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginLeft: 4 }}>
|
||||
<span
|
||||
style={{
|
||||
width: 1,
|
||||
height: 12,
|
||||
background: 'var(--text)',
|
||||
display: 'inline-block',
|
||||
opacity: 0.7,
|
||||
}}
|
||||
/>
|
||||
Pit stop
|
||||
</span>
|
||||
)}
|
||||
<span style={{ marginLeft: 'auto', fontFamily: 'var(--f-mono)', fontSize: 10 }}>
|
||||
{totalLaps} laps
|
||||
</span>
|
||||
</div>
|
||||
<TyreStintTimeline rows={timelineRows} totalLaps={totalLaps} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export type Tab =
|
||||
| 'overview'
|
||||
| 'race_story'
|
||||
| 'strategy'
|
||||
| 'compare'
|
||||
| 'lap_data'
|
||||
| 'conditions'
|
||||
| 'race_control'
|
||||
@@ -11,6 +12,7 @@ const TABS: { id: Tab; label: string }[] = [
|
||||
{ id: 'overview', label: 'Overview' },
|
||||
{ id: 'race_story', label: 'Race Story' },
|
||||
{ id: 'strategy', label: 'Strategy' },
|
||||
{ id: 'compare', label: 'Compare' },
|
||||
{ id: 'lap_data', label: 'Lap Data' },
|
||||
{ id: 'conditions', label: 'Conditions' },
|
||||
{ id: 'race_control', label: 'Race Control' },
|
||||
|
||||
55
frontend/src/components/TeammateH2H.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import { teamColor } from '../utils'
|
||||
import '../styles/h2h.css'
|
||||
|
||||
export interface TeammateH2HProps {
|
||||
teamName: string
|
||||
teamColour: string
|
||||
driverATla: string
|
||||
driverBTla: string
|
||||
winsA: number
|
||||
winsB: number
|
||||
/** e.g. "+1" when more than two drivers share the team. */
|
||||
extraNote?: string
|
||||
}
|
||||
|
||||
export function TeammateH2H({
|
||||
teamName,
|
||||
teamColour,
|
||||
driverATla,
|
||||
driverBTla,
|
||||
winsA,
|
||||
winsB,
|
||||
extraNote,
|
||||
}: TeammateH2HProps) {
|
||||
const total = winsA + winsB || 1
|
||||
const pctA = (winsA / total) * 100
|
||||
const color = teamColor(teamColour)
|
||||
|
||||
return (
|
||||
<div className="h2h-row" data-testid="teammate-h2h">
|
||||
<div className="h2h-team">
|
||||
<span className="h2h-team-name">{teamName}</span>
|
||||
{extraNote ? <span className="h2h-extra mono">{extraNote}</span> : null}
|
||||
</div>
|
||||
<div className="h2h-bar-wrap">
|
||||
<span className="h2h-tla h2h-tla--left mono">{driverATla}</span>
|
||||
<div className="h2h-bar" data-testid="h2h-bar">
|
||||
<span
|
||||
className="h2h-bar-seg"
|
||||
data-testid="h2h-bar-a"
|
||||
style={{ width: `${pctA}%`, background: color }}
|
||||
/>
|
||||
<span
|
||||
className="h2h-bar-seg h2h-bar-seg--muted"
|
||||
data-testid="h2h-bar-b"
|
||||
style={{ width: `${100 - pctA}%`, background: color }}
|
||||
/>
|
||||
<span className="h2h-score mono" data-testid="h2h-score">
|
||||
{winsA}–{winsB}
|
||||
</span>
|
||||
</div>
|
||||
<span className="h2h-tla h2h-tla--right mono">{driverBTla}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
282
frontend/src/components/charts/DeltaTimeGraph.tsx
Normal file
@@ -0,0 +1,282 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
computeCumulativeDeltas,
|
||||
deltaPolylineSegments,
|
||||
formatDeltaSeconds,
|
||||
type DeltaSeries,
|
||||
type DriverDeltaResult,
|
||||
} from '../../lib/delta'
|
||||
import '../../styles/delta-graph.css'
|
||||
|
||||
export type { DeltaSeries }
|
||||
|
||||
export interface DeltaTimeGraphProps {
|
||||
series: DeltaSeries[]
|
||||
referenceLabel?: string
|
||||
}
|
||||
|
||||
const W = 640
|
||||
const H = 220
|
||||
const PL = 44
|
||||
const PR = 16
|
||||
const PT = 12
|
||||
const PB = 28
|
||||
|
||||
function lapCount(series: ReadonlyArray<DeltaSeries>): number {
|
||||
return series.reduce((max, s) => Math.max(max, s.lapTimes.length), 0)
|
||||
}
|
||||
|
||||
function yExtent(drivers: ReadonlyArray<DriverDeltaResult>): { min: number; max: number } {
|
||||
let min = 0
|
||||
let max = 0
|
||||
for (const driver of drivers) {
|
||||
for (const delta of driver.deltas) {
|
||||
if (delta === null) continue
|
||||
min = Math.min(min, delta)
|
||||
max = Math.max(max, delta)
|
||||
}
|
||||
}
|
||||
if (min === max) {
|
||||
const pad = 1
|
||||
return { min: min - pad, max: max + pad }
|
||||
}
|
||||
const span = max - min
|
||||
const pad = span * 0.08
|
||||
return { min: min - pad, max: max + pad }
|
||||
}
|
||||
|
||||
function niceYTicks(min: number, max: number): number[] {
|
||||
const span = max - min
|
||||
if (span <= 0) return [0]
|
||||
const rough = span / 4
|
||||
const magnitude = Math.pow(10, Math.floor(Math.log10(rough)))
|
||||
const step = Math.ceil(rough / magnitude) * magnitude
|
||||
const ticks: number[] = []
|
||||
const start = Math.ceil(min / step) * step
|
||||
for (let v = start; v <= max + step * 0.01; v += step) {
|
||||
ticks.push(Number(v.toFixed(6)))
|
||||
}
|
||||
if (!ticks.some((t) => Math.abs(t) < step * 0.01)) {
|
||||
ticks.push(0)
|
||||
ticks.sort((a, b) => a - b)
|
||||
}
|
||||
return ticks
|
||||
}
|
||||
|
||||
export function DeltaTimeGraph({ series, referenceLabel }: DeltaTimeGraphProps) {
|
||||
const svgRef = useRef<SVGSVGElement>(null)
|
||||
const [hoverLap, setHoverLap] = useState<number | null>(null)
|
||||
|
||||
const drivers = useMemo(
|
||||
() => computeCumulativeDeltas(series, referenceLabel),
|
||||
[series, referenceLabel],
|
||||
)
|
||||
|
||||
const laps = useMemo(() => lapCount(series), [series])
|
||||
const plotW = W - PL - PR
|
||||
const plotH = H - PT - PB
|
||||
const { min: yMin, max: yMax } = useMemo(() => yExtent(drivers), [drivers])
|
||||
const yTicks = useMemo(() => niceYTicks(yMin, yMax), [yMin, yMax])
|
||||
|
||||
const toX = useCallback(
|
||||
(lapIndex: number) => {
|
||||
if (laps <= 1) return PL + plotW / 2
|
||||
return PL + (lapIndex / (laps - 1)) * plotW
|
||||
},
|
||||
[laps, plotW],
|
||||
)
|
||||
|
||||
const toY = useCallback(
|
||||
(delta: number) => {
|
||||
const span = yMax - yMin || 1
|
||||
return PT + ((delta - yMin) / span) * plotH
|
||||
},
|
||||
[yMin, yMax, plotH],
|
||||
)
|
||||
|
||||
const lapTickNumbers = useMemo(() => {
|
||||
const ticks: number[] = []
|
||||
for (let lap = 5; lap <= laps; lap += 5) {
|
||||
ticks.push(lap)
|
||||
}
|
||||
return ticks
|
||||
}, [laps])
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent<SVGRectElement> | React.MouseEvent<SVGRectElement>) => {
|
||||
if (!svgRef.current || laps === 0) return
|
||||
const rect = svgRef.current.getBoundingClientRect()
|
||||
if (rect.width <= 0) return
|
||||
const x = ((e.clientX - rect.left) / rect.width) * W
|
||||
const frac = Math.max(0, Math.min(1, (x - PL) / plotW))
|
||||
const lapIndex = laps <= 1 ? 0 : Math.round(frac * (laps - 1))
|
||||
if (!Number.isFinite(lapIndex)) return
|
||||
setHoverLap(Math.max(0, Math.min(laps - 1, lapIndex)))
|
||||
},
|
||||
[laps, plotW],
|
||||
)
|
||||
|
||||
const handlePointerLeave = useCallback(() => setHoverLap(null), [])
|
||||
|
||||
if (series.length === 0 || laps === 0) {
|
||||
return (
|
||||
<div className="delta-graph" data-testid="delta-time-graph-empty">
|
||||
<p className="delta-graph-empty">No lap data to compare.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (drivers.length === 0) {
|
||||
return (
|
||||
<div className="delta-graph" data-testid="delta-time-graph-empty">
|
||||
<p className="delta-graph-empty">Select at least two drivers to compare.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const hoverX = hoverLap !== null ? toX(hoverLap) : null
|
||||
const tooltipRows = hoverLap !== null
|
||||
? drivers
|
||||
.map((d) => {
|
||||
const delta = d.deltas[hoverLap]
|
||||
if (delta == null) return null
|
||||
return { label: d.label, color: d.color, delta }
|
||||
})
|
||||
.filter((row): row is { label: string; color: string; delta: number } => row !== null)
|
||||
: []
|
||||
|
||||
const tooltipH = 18 + tooltipRows.length * 14
|
||||
const tooltipW = 120
|
||||
const tooltipX = hoverX !== null ? Math.min(Math.max(hoverX + 8, PL), W - PR - tooltipW) : 0
|
||||
const tooltipY = PT
|
||||
|
||||
return (
|
||||
<div className="delta-graph" data-testid="delta-time-graph">
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="delta-graph-svg"
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
role="img"
|
||||
aria-label="Cumulative delta time chart"
|
||||
>
|
||||
{yTicks.map((tick) => (
|
||||
<g key={`y-${tick}`}>
|
||||
<line
|
||||
x1={PL}
|
||||
x2={W - PR}
|
||||
y1={toY(tick)}
|
||||
y2={toY(tick)}
|
||||
className={Math.abs(tick) < 1e-9 ? 'delta-graph-zero-line' : 'delta-graph-grid-line'}
|
||||
data-testid={Math.abs(tick) < 1e-9 ? 'delta-zero-line' : undefined}
|
||||
/>
|
||||
<text
|
||||
x={PL - 6}
|
||||
y={toY(tick) + 3}
|
||||
textAnchor="end"
|
||||
className="delta-graph-axis-label"
|
||||
>
|
||||
{formatDeltaSeconds(tick)}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
|
||||
{lapTickNumbers.map((lap) => {
|
||||
const x = toX(lap - 1)
|
||||
return (
|
||||
<g key={`lap-${lap}`}>
|
||||
<line
|
||||
x1={x}
|
||||
x2={x}
|
||||
y1={H - PB}
|
||||
y2={H - PB + 4}
|
||||
className="delta-graph-grid-line"
|
||||
/>
|
||||
<text
|
||||
x={x}
|
||||
y={H - PB + 16}
|
||||
textAnchor="middle"
|
||||
className="delta-graph-axis-label"
|
||||
>
|
||||
{lap}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
{drivers.map((driver) => {
|
||||
const segments = deltaPolylineSegments(driver.deltas, (lapIndex, delta) =>
|
||||
`${toX(lapIndex).toFixed(1)},${toY(delta).toFixed(1)}`,
|
||||
)
|
||||
return (
|
||||
<g key={driver.label} data-testid={`delta-line-${driver.label}`}>
|
||||
{segments.map((points, i) => (
|
||||
<polyline
|
||||
key={`${driver.label}-${i}`}
|
||||
points={points}
|
||||
className="delta-graph-driver-line"
|
||||
stroke={driver.color}
|
||||
/>
|
||||
))}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
{hoverX !== null && (
|
||||
<>
|
||||
<line
|
||||
x1={hoverX}
|
||||
x2={hoverX}
|
||||
y1={PT}
|
||||
y2={H - PB}
|
||||
className="delta-graph-crosshair"
|
||||
data-testid="delta-crosshair"
|
||||
/>
|
||||
{tooltipRows.length > 0 && (
|
||||
<g className="delta-graph-tooltip" data-testid="delta-tooltip">
|
||||
<rect
|
||||
x={tooltipX}
|
||||
y={tooltipY}
|
||||
width={tooltipW}
|
||||
height={tooltipH}
|
||||
rx={4}
|
||||
className="delta-graph-tooltip-bg"
|
||||
/>
|
||||
<text
|
||||
x={tooltipX + 8}
|
||||
y={tooltipY + 14}
|
||||
className="delta-graph-tooltip-title"
|
||||
>
|
||||
Lap {hoverLap! + 1}
|
||||
</text>
|
||||
{tooltipRows.map((row, i) => (
|
||||
<text
|
||||
key={row.label}
|
||||
x={tooltipX + 8}
|
||||
y={tooltipY + 28 + i * 14}
|
||||
className="delta-graph-tooltip-row"
|
||||
fill={row.color}
|
||||
>
|
||||
{row.label} {formatDeltaSeconds(row.delta)}
|
||||
</text>
|
||||
))}
|
||||
</g>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<rect
|
||||
x={PL}
|
||||
y={PT}
|
||||
width={plotW}
|
||||
height={plotH}
|
||||
fill="transparent"
|
||||
className="delta-graph-hover-layer"
|
||||
onPointerMove={handlePointerMove}
|
||||
onMouseMove={handlePointerMove}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
onMouseLeave={handlePointerLeave}
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
194
frontend/src/components/charts/TelemetryTraceChart.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import '../../styles/telemetry-trace.css'
|
||||
|
||||
export interface TelemetryTraceSample {
|
||||
speed: number
|
||||
throttle: number
|
||||
brake: number
|
||||
}
|
||||
|
||||
export interface TelemetryTraceSeries {
|
||||
label: string
|
||||
color: string
|
||||
samples: TelemetryTraceSample[]
|
||||
}
|
||||
|
||||
export type TelemetryTraceChannel = 'speed' | 'throttle' | 'brake'
|
||||
|
||||
export interface TelemetryTraceChartProps {
|
||||
series: TelemetryTraceSeries[]
|
||||
channels?: TelemetryTraceChannel[]
|
||||
/** Height of each channel panel in SVG units (viewBox space). */
|
||||
height?: number
|
||||
}
|
||||
|
||||
const VIEW_WIDTH = 800
|
||||
const PANEL_GAP = 18
|
||||
const PAD_TOP = 6
|
||||
const PAD_BOTTOM = 6
|
||||
|
||||
const CHANNEL_LABELS: Record<TelemetryTraceChannel, string> = {
|
||||
speed: 'Speed',
|
||||
throttle: 'Throttle',
|
||||
brake: 'Brake',
|
||||
}
|
||||
|
||||
const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))
|
||||
|
||||
function channelValue(sample: TelemetryTraceSample, channel: TelemetryTraceChannel): number {
|
||||
const raw = sample[channel]
|
||||
// Throttle/brake are percentages; clamp so out-of-range API values can't
|
||||
// draw outside the panel. Speed is clamped to >= 0.
|
||||
if (channel === 'speed') return Math.max(0, raw)
|
||||
return clamp(raw, 0, 100)
|
||||
}
|
||||
|
||||
function formatValue(value: number, channel: TelemetryTraceChannel): string {
|
||||
if (channel === 'speed') return `${Math.round(value)} km/h`
|
||||
return `${Math.round(value)}%`
|
||||
}
|
||||
|
||||
export function TelemetryTraceChart({
|
||||
series,
|
||||
channels = ['speed', 'throttle', 'brake'],
|
||||
height = 110,
|
||||
}: TelemetryTraceChartProps) {
|
||||
const svgRef = useRef<SVGSVGElement | null>(null)
|
||||
const [hoverIndex, setHoverIndex] = useState<number | null>(null)
|
||||
|
||||
// Series are index-aligned; mismatched lengths are clamped to the shortest
|
||||
// series so every drawn x has a value for every driver.
|
||||
const sampleCount = useMemo(
|
||||
() => (series.length === 0 ? 0 : Math.min(...series.map((s) => s.samples.length))),
|
||||
[series],
|
||||
)
|
||||
|
||||
const speedMax = useMemo(() => {
|
||||
let max = 0
|
||||
for (const s of series) {
|
||||
for (let i = 0; i < sampleCount; i++) {
|
||||
max = Math.max(max, channelValue(s.samples[i], 'speed'))
|
||||
}
|
||||
}
|
||||
return max > 0 ? max : 1
|
||||
}, [series, sampleCount])
|
||||
|
||||
if (series.length === 0 || sampleCount === 0 || channels.length === 0) {
|
||||
return <div className="telemetry-trace-empty">No telemetry data</div>
|
||||
}
|
||||
|
||||
// Clamp a stale hover index in case the series prop shrank between renders.
|
||||
const hover = hoverIndex === null ? null : Math.min(hoverIndex, sampleCount - 1)
|
||||
|
||||
const panelHeight = height
|
||||
const totalHeight = channels.length * panelHeight + (channels.length - 1) * PANEL_GAP
|
||||
const xAt = (i: number) => (i / Math.max(1, sampleCount - 1)) * VIEW_WIDTH
|
||||
|
||||
const channelMax = (channel: TelemetryTraceChannel) => (channel === 'speed' ? speedMax : 100)
|
||||
|
||||
const yAt = (value: number, channel: TelemetryTraceChannel, panelTop: number) => {
|
||||
const usable = panelHeight - PAD_TOP - PAD_BOTTOM
|
||||
const frac = channelValue({ speed: value, throttle: value, brake: value }, channel) / channelMax(channel)
|
||||
return panelTop + PAD_TOP + (1 - frac) * usable
|
||||
}
|
||||
|
||||
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
|
||||
const rect = svgRef.current?.getBoundingClientRect()
|
||||
if (!rect || rect.width === 0) {
|
||||
setHoverIndex(0)
|
||||
return
|
||||
}
|
||||
const frac = clamp((e.clientX - rect.left) / rect.width, 0, 1)
|
||||
setHoverIndex(clamp(Math.round(frac * (sampleCount - 1)), 0, sampleCount - 1))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="telemetry-trace" data-testid="telemetry-trace">
|
||||
<div className="telemetry-trace-legend">
|
||||
{series.map((s) => (
|
||||
<span key={s.label} className="telemetry-trace-legend-item">
|
||||
<span className="telemetry-trace-swatch" style={{ background: s.color }} aria-hidden="true" />
|
||||
{s.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="telemetry-trace-svg"
|
||||
viewBox={`0 0 ${VIEW_WIDTH} ${totalHeight}`}
|
||||
role="img"
|
||||
aria-label="Telemetry trace chart"
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={() => setHoverIndex(null)}
|
||||
>
|
||||
{channels.map((channel, panelIdx) => {
|
||||
const panelTop = panelIdx * (panelHeight + PANEL_GAP)
|
||||
return (
|
||||
<g key={channel} className="telemetry-trace-panel" data-channel={channel}>
|
||||
<rect
|
||||
className="telemetry-trace-panel-bg"
|
||||
x={0}
|
||||
y={panelTop}
|
||||
width={VIEW_WIDTH}
|
||||
height={panelHeight}
|
||||
/>
|
||||
<text className="telemetry-trace-panel-title" x={6} y={panelTop + 13}>
|
||||
{CHANNEL_LABELS[channel]}
|
||||
</text>
|
||||
<text className="telemetry-trace-axis-max" x={VIEW_WIDTH - 6} y={panelTop + 13} textAnchor="end">
|
||||
{channel === 'speed' ? `${Math.round(speedMax)} km/h` : '100%'}
|
||||
</text>
|
||||
{series.map((s) => {
|
||||
const points = Array.from({ length: sampleCount }, (_, i) => {
|
||||
const x = xAt(i)
|
||||
const y = yAt(s.samples[i][channel], channel, panelTop)
|
||||
return `${x.toFixed(2)},${y.toFixed(2)}`
|
||||
}).join(' ')
|
||||
return (
|
||||
<polyline
|
||||
key={s.label}
|
||||
className="telemetry-trace-line"
|
||||
data-channel={channel}
|
||||
data-series={s.label}
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
strokeWidth={1.6}
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
{hover !== null && (
|
||||
<line
|
||||
className="telemetry-trace-crosshair"
|
||||
data-testid="telemetry-trace-crosshair"
|
||||
x1={xAt(hover)}
|
||||
y1={0}
|
||||
x2={xAt(hover)}
|
||||
y2={totalHeight}
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
{hover !== null && (
|
||||
<div className="telemetry-trace-readout" data-testid="telemetry-trace-readout">
|
||||
<span className="telemetry-trace-readout-index">Sample {hover}</span>
|
||||
{series.map((s) => (
|
||||
<span key={s.label} className="telemetry-trace-readout-driver">
|
||||
<span className="telemetry-trace-swatch" style={{ background: s.color }} aria-hidden="true" />
|
||||
<span className="telemetry-trace-readout-label">{s.label}</span>
|
||||
{channels.map((channel) => (
|
||||
<span key={channel} className="telemetry-trace-readout-value">
|
||||
{formatValue(channelValue(s.samples[hover], channel), channel)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
207
frontend/src/components/charts/TyreStintTimeline.tsx
Normal file
@@ -0,0 +1,207 @@
|
||||
import { compoundClass } from '../../lib/live'
|
||||
import '../../styles/stint-timeline.css'
|
||||
|
||||
export interface StintTimelineStint {
|
||||
compound: string
|
||||
lapStart: number
|
||||
lapEnd: number
|
||||
isNew?: boolean
|
||||
}
|
||||
|
||||
export interface StintTimelineRow {
|
||||
label: string
|
||||
color: string
|
||||
stints: StintTimelineStint[]
|
||||
/** Lap numbers where the driver pitted; optional — rows without stops render normally. */
|
||||
pitStops?: number[]
|
||||
}
|
||||
|
||||
interface TyreStintTimelineProps {
|
||||
rows: StintTimelineRow[]
|
||||
totalLaps: number
|
||||
}
|
||||
|
||||
const SVG_W = 640
|
||||
const LEFT = 48
|
||||
const RIGHT = 12
|
||||
const ROW_H = 28
|
||||
const BAR_H = 14
|
||||
const BAR_Y = 7
|
||||
const AXIS_H = 20
|
||||
const BAR_W = SVG_W - LEFT - RIGHT
|
||||
|
||||
const COMPOUND_ORDER = ['SOFT', 'MEDIUM', 'HARD', 'INTERMEDIATE', 'WET'] as const
|
||||
|
||||
function compoundLabel(compound: string): string {
|
||||
const upper = compound.toUpperCase()
|
||||
if (upper === 'INTERMEDIATE') return 'Intermediate'
|
||||
return upper.charAt(0) + upper.slice(1).toLowerCase()
|
||||
}
|
||||
|
||||
function stintLength(stint: StintTimelineStint): number {
|
||||
return stint.lapEnd - stint.lapStart + 1
|
||||
}
|
||||
|
||||
function stintTitle(stint: StintTimelineStint): string {
|
||||
const length = stintLength(stint)
|
||||
return `${compoundLabel(stint.compound)} · L${stint.lapStart}–${stint.lapEnd} · ${length} lap${length === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
function lapX(lap: number, totalLaps: number): number {
|
||||
return LEFT + (lap / totalLaps) * BAR_W
|
||||
}
|
||||
|
||||
function stintBarX(stint: StintTimelineStint, totalLaps: number): number {
|
||||
return LEFT + ((stint.lapStart - 1) / totalLaps) * BAR_W
|
||||
}
|
||||
|
||||
function stintBarW(stint: StintTimelineStint, totalLaps: number): number {
|
||||
return Math.max(2, (stintLength(stint) / totalLaps) * BAR_W)
|
||||
}
|
||||
|
||||
function pitMarkerX(lapNumber: number, totalLaps: number): number {
|
||||
return LEFT + ((lapNumber - 1) / totalLaps) * BAR_W
|
||||
}
|
||||
|
||||
function pitMarkerTitle(driverLabel: string, lapNumber: number): string {
|
||||
return `${driverLabel} pit stop · L${lapNumber}`
|
||||
}
|
||||
|
||||
function axisTicks(totalLaps: number): number[] {
|
||||
const ticks: number[] = []
|
||||
for (let lap = 0; lap <= totalLaps; lap += 10) {
|
||||
ticks.push(lap)
|
||||
}
|
||||
return ticks
|
||||
}
|
||||
|
||||
function collectUsedCompounds(rows: StintTimelineRow[]): string[] {
|
||||
const seen = new Set<string>()
|
||||
for (const row of rows) {
|
||||
for (const stint of row.stints) {
|
||||
seen.add(stint.compound.toUpperCase())
|
||||
}
|
||||
}
|
||||
const ordered = COMPOUND_ORDER.filter((c) => seen.has(c))
|
||||
const extras = [...seen]
|
||||
.filter((c) => !COMPOUND_ORDER.includes(c as (typeof COMPOUND_ORDER)[number]))
|
||||
.sort()
|
||||
return [...ordered, ...extras]
|
||||
}
|
||||
|
||||
export function TyreStintTimeline({ rows, totalLaps }: TyreStintTimelineProps) {
|
||||
const safeTotal = Math.max(totalLaps, 1)
|
||||
const usedCompounds = collectUsedCompounds(rows)
|
||||
const ticks = axisTicks(safeTotal)
|
||||
const chartH = rows.length * ROW_H
|
||||
const svgH = chartH + AXIS_H + 4
|
||||
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
<div className="stint-timeline" data-testid="stint-timeline-empty">
|
||||
<div className="stint-timeline__empty">No stint data to display.</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="stint-timeline" data-testid="stint-timeline">
|
||||
<div className="stint-timeline__scroll">
|
||||
<svg
|
||||
viewBox={`0 0 ${SVG_W} ${svgH}`}
|
||||
className="stint-timeline__svg"
|
||||
role="img"
|
||||
aria-label="Tyre stint timeline"
|
||||
>
|
||||
{rows.map((row, i) => {
|
||||
const rowY = i * ROW_H
|
||||
return (
|
||||
<g key={`${row.label}-${i}`} transform={`translate(0,${rowY})`}>
|
||||
<text
|
||||
x={LEFT - 5}
|
||||
y={BAR_Y + BAR_H / 2 + 4}
|
||||
textAnchor="end"
|
||||
fill={row.color}
|
||||
className="stint-timeline__label"
|
||||
>
|
||||
{row.label}
|
||||
</text>
|
||||
|
||||
{row.stints.map((stint, si) => (
|
||||
<rect
|
||||
key={si}
|
||||
x={stintBarX(stint, safeTotal)}
|
||||
y={BAR_Y}
|
||||
width={stintBarW(stint, safeTotal)}
|
||||
height={BAR_H}
|
||||
rx={3}
|
||||
className={`stint-timeline__bar ${compoundClass(stint.compound)}${stint.isNew ? ' stint-timeline__bar--new' : ''}`}
|
||||
>
|
||||
<title>{stintTitle(stint)}</title>
|
||||
</rect>
|
||||
))}
|
||||
|
||||
{(row.pitStops ?? []).map((lapNumber, pi) => (
|
||||
<line
|
||||
key={`pit-${pi}`}
|
||||
x1={pitMarkerX(lapNumber, safeTotal)}
|
||||
x2={pitMarkerX(lapNumber, safeTotal)}
|
||||
y1={BAR_Y - 3}
|
||||
y2={BAR_Y + BAR_H + 3}
|
||||
className="stint-timeline__pit-marker"
|
||||
data-testid="pit-marker"
|
||||
data-lap={lapNumber}
|
||||
>
|
||||
<title>{pitMarkerTitle(row.label, lapNumber)}</title>
|
||||
</line>
|
||||
))}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
|
||||
<g transform={`translate(0,${chartH})`}>
|
||||
<line
|
||||
x1={LEFT}
|
||||
x2={LEFT + BAR_W}
|
||||
y1={0}
|
||||
y2={0}
|
||||
className="stint-timeline__axis-line"
|
||||
/>
|
||||
{ticks.map((lap) => (
|
||||
<g key={lap}>
|
||||
<line
|
||||
x1={lapX(lap, safeTotal)}
|
||||
x2={lapX(lap, safeTotal)}
|
||||
y1={0}
|
||||
y2={4}
|
||||
className="stint-timeline__axis-line"
|
||||
/>
|
||||
<text
|
||||
x={lapX(lap, safeTotal)}
|
||||
y={14}
|
||||
textAnchor="middle"
|
||||
className="stint-timeline__axis-tick"
|
||||
>
|
||||
{lap}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div className="stint-timeline__legend">
|
||||
{usedCompounds.map((compound) => (
|
||||
<span key={compound} className="stint-timeline__legend-item">
|
||||
<span
|
||||
className={`stint-timeline__legend-swatch ${compoundClass(compound)}`}
|
||||
data-testid={`legend-${compound.toLowerCase()}`}
|
||||
/>
|
||||
{compoundLabel(compound)}
|
||||
</span>
|
||||
))}
|
||||
<span className="stint-timeline__meta">{safeTotal} laps</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
21
frontend/src/components/live/BattleChips.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { Battle } from '../../lib/battles'
|
||||
import { battleLabel } from '../../lib/battles'
|
||||
|
||||
interface Props {
|
||||
battles: Battle[]
|
||||
}
|
||||
|
||||
export function BattleChips({ battles }: Props) {
|
||||
if (battles.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="battle-chips" data-testid="battle-chips">
|
||||
<span className="battle-chips-label">Battles</span>
|
||||
{battles.map((battle) => (
|
||||
<span className="battle-chip mono" key={battle.drivers.map((d) => d.racingNumber).join('-')}>
|
||||
{battleLabel(battle)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
72
frontend/src/components/live/EventRail.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useAutoAnimate } from '@formkit/auto-animate/react'
|
||||
import {
|
||||
Flag,
|
||||
LogOut,
|
||||
Megaphone,
|
||||
OctagonX,
|
||||
Swords,
|
||||
Timer,
|
||||
TrendingDown,
|
||||
TrendingUp,
|
||||
Wrench,
|
||||
Zap,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import type { LiveDriverInfo } from '../../types'
|
||||
import type { LiveEvent, LiveEventKind } from '../../lib/events'
|
||||
import { teamColor } from '../../utils'
|
||||
import '../../styles/event-rail.css'
|
||||
|
||||
interface Props {
|
||||
events: LiveEvent[]
|
||||
driverInfo?: Record<string, LiveDriverInfo>
|
||||
}
|
||||
|
||||
const KIND_ICONS: Record<LiveEventKind, LucideIcon> = {
|
||||
overtake: Swords,
|
||||
'position-gain': TrendingUp,
|
||||
'position-loss': TrendingDown,
|
||||
'pit-in': Wrench,
|
||||
'pit-out': LogOut,
|
||||
'personal-best': Timer,
|
||||
'fastest-lap': Zap,
|
||||
retirement: OctagonX,
|
||||
'track-status': Flag,
|
||||
'race-control': Megaphone,
|
||||
}
|
||||
|
||||
export function EventRail({ events, driverInfo }: Props) {
|
||||
const [listRef] = useAutoAnimate<HTMLDivElement>()
|
||||
|
||||
return (
|
||||
<section className="event-rail panel-glass" data-testid="event-rail">
|
||||
<div className="sec-header sticky-header">
|
||||
<span className="sec-title">What Just Happened</span>
|
||||
{events.length > 0 && <span className="sec-meta">{events.length} events</span>}
|
||||
</div>
|
||||
{events.length === 0 ? (
|
||||
<div className="missing-notice">Events will appear here as the session unfolds.</div>
|
||||
) : (
|
||||
<div className="event-rail-list" ref={listRef}>
|
||||
{events.map((event) => {
|
||||
const Icon = KIND_ICONS[event.kind] ?? Megaphone
|
||||
const colour = driverInfo?.[event.racingNumbers[0]]?.TeamColour
|
||||
const accent = event.racingNumbers.length > 0 ? teamColor(colour) : 'var(--border-2)'
|
||||
return (
|
||||
<div className={`event-rail-row event-kind-${event.kind}`} key={event.id} style={{ borderLeftColor: accent }}>
|
||||
<span className="event-rail-icon" aria-hidden="true">
|
||||
<Icon size={14} />
|
||||
</span>
|
||||
<div className="event-rail-body">
|
||||
<span className="event-rail-headline">{event.headline}</span>
|
||||
{event.detail && <span className="event-rail-detail">{event.detail}</span>}
|
||||
</div>
|
||||
{event.lap > 0 && <span className="event-rail-lap">L{event.lap}</span>}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
44
frontend/src/components/live/GapSparkline.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { gapTrend, sparklinePoints } from '../../lib/gapHistory'
|
||||
|
||||
interface Props {
|
||||
samples: number[] | undefined
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
export function GapSparkline({ samples, width = 56, height = 14 }: Props) {
|
||||
if (!samples || samples.length < 2) {
|
||||
return <span className="gap-spark gap-spark-empty">·</span>
|
||||
}
|
||||
|
||||
const trend = gapTrend(samples)
|
||||
const points = sparklinePoints(samples, width, height)
|
||||
|
||||
return (
|
||||
<span className={`gap-spark trend-${trend ?? 'steady'}`} data-testid="gap-spark">
|
||||
<svg
|
||||
className="gap-spark-svg"
|
||||
width={width}
|
||||
height={height}
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
{trend === 'closing' && (
|
||||
<span className="trend-arrow trend-arrow-closing" title="Gap closing">▼</span>
|
||||
)}
|
||||
{trend === 'opening' && (
|
||||
<span className="trend-arrow trend-arrow-opening" title="Gap opening">▲</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
63
frontend/src/components/live/PinnedDrivers.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { teamColor } from '../../utils'
|
||||
import type { LiveTimingRow } from '../../lib/live'
|
||||
import { driverCode, tyreClass, tyreLabel } from '../../lib/live'
|
||||
import type { GapHistoryMap } from '../../lib/gapHistory'
|
||||
import { GapSparkline } from './GapSparkline'
|
||||
|
||||
interface Props {
|
||||
rows: LiveTimingRow[]
|
||||
history: GapHistoryMap
|
||||
pinned: string[]
|
||||
onToggle: (racingNumber: string) => void
|
||||
}
|
||||
|
||||
export function PinnedDrivers({ rows, history, pinned, onToggle }: Props) {
|
||||
if (pinned.length === 0) return null
|
||||
|
||||
const rowsByNumber = new Map(rows.map((row) => [row.RacingNumber, row]))
|
||||
|
||||
return (
|
||||
<div className="pinned-strip" data-testid="pinned-strip">
|
||||
{pinned.map((number) => {
|
||||
const row = rowsByNumber.get(number)
|
||||
if (!row) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="pinned-card pinned-card-missing"
|
||||
key={number}
|
||||
onClick={() => onToggle(number)}
|
||||
title="Unpin driver"
|
||||
>
|
||||
<span className="drv-code">#{number}</span>
|
||||
<span className="pinned-nodata">no data</span>
|
||||
<span className="pinned-unpin" aria-hidden="true">×</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
const driver = row.Driver
|
||||
const gap = driver.Interval || driver.GapToLeader || '-'
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="pinned-card"
|
||||
key={number}
|
||||
onClick={() => onToggle(number)}
|
||||
title="Unpin driver"
|
||||
>
|
||||
<span className="pinned-pos mono">P{row.Position}</span>
|
||||
<span className="drv-bar" style={{ background: teamColor(row.Info?.TeamColour) }} />
|
||||
<span className="drv-code">{driverCode(row)}</span>
|
||||
<span className={`tyre-badge ${tyreClass(row.Tyre)}`}>{tyreLabel(row.Tyre)}</span>
|
||||
<span className="pinned-gap mono">{gap}</span>
|
||||
<GapSparkline samples={history[number]} />
|
||||
{driver.InPit && <span className="badge badge-pit">PIT</span>}
|
||||
{driver.Retired && <span className="badge badge-out">RET</span>}
|
||||
<span className="pinned-unpin" aria-hidden="true">×</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,36 +1,121 @@
|
||||
import type { LiveRCMessage } from '../../types'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { LiveRCMessage, LiveDriverInfo } from '../../types'
|
||||
import { latestRaceControl, rcFlagClass } from '../../lib/live'
|
||||
import { teamColor } from '../../utils'
|
||||
import { useAutoAnimate } from '@formkit/auto-animate/react'
|
||||
|
||||
interface Props {
|
||||
messages: LiveRCMessage[]
|
||||
driverInfo?: Record<string, LiveDriverInfo>
|
||||
}
|
||||
|
||||
export function RaceControlFeed({ messages }: Props) {
|
||||
function FormattedMessage({ text, driverInfo }: { text: string, driverInfo?: Record<string, LiveDriverInfo> }) {
|
||||
if (!text) return null;
|
||||
const regex = /(CAR \d+(?: \([A-Z]{3}\))?|DELETED|TRACK LIMITS|INVESTIGATING|NO FURTHER INVESTIGATION|TIME PENALTY|DRIVE THROUGH PENALTY|STOP AND GO PENALTY|BLACK AND WHITE FLAG|DISQUALIFIED)/g;
|
||||
const parts = text.split(regex);
|
||||
|
||||
return (
|
||||
<span className="rc-message">
|
||||
{parts.map((part, i) => {
|
||||
if (!part) return null;
|
||||
if (part.startsWith('CAR ')) {
|
||||
let style = {}
|
||||
const match = part.match(/CAR (\d+)/)
|
||||
if (match && driverInfo && driverInfo[match[1]]) {
|
||||
const hex = teamColor(driverInfo[match[1]].TeamColour)
|
||||
style = {
|
||||
backgroundColor: hex,
|
||||
color: '#fff',
|
||||
textShadow: '0 1px 2px rgba(0,0,0,0.5)',
|
||||
border: 'none'
|
||||
}
|
||||
}
|
||||
return <span key={i} className="rc-hlt rc-hlt-car" style={style}>{part}</span>
|
||||
}
|
||||
if (part === 'DELETED' || part.includes('PENALTY') || part === 'DISQUALIFIED') return <span key={i} className="rc-hlt rc-hlt-bad">{part}</span>;
|
||||
if (part === 'TRACK LIMITS' || part === 'INVESTIGATING' || part === 'BLACK AND WHITE FLAG') return <span key={i} className="rc-hlt rc-hlt-warn">{part}</span>;
|
||||
if (part === 'NO FURTHER INVESTIGATION') return <span key={i} className="rc-hlt rc-hlt-ok">{part}</span>;
|
||||
return <span key={i}>{part}</span>;
|
||||
})}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function RaceControlFeed({ messages, driverInfo }: Props) {
|
||||
const latest = latestRaceControl(messages)
|
||||
const [listRef] = useAutoAnimate<HTMLDivElement>()
|
||||
const prevMessagesRef = useRef<LiveRCMessage[]>([])
|
||||
const [newKeys, setNewKeys] = useState<Set<string>>(new Set())
|
||||
|
||||
useEffect(() => {
|
||||
const prev = prevMessagesRef.current
|
||||
if (prev.length > 0 && messages.length > prev.length) {
|
||||
// Find new messages
|
||||
const newlyAdded = messages.filter(
|
||||
(m) => !prev.some((p) => p.Time === m.Time && p.Message === m.Message)
|
||||
)
|
||||
|
||||
if (newlyAdded.length > 0) {
|
||||
const keys = newlyAdded.map((m) => `${m.Time}-${m.Message}`)
|
||||
setNewKeys((current) => {
|
||||
const updated = new Set(current)
|
||||
keys.forEach(k => updated.add(k))
|
||||
return updated
|
||||
})
|
||||
|
||||
// Clear highlight after 3 seconds
|
||||
setTimeout(() => {
|
||||
setNewKeys((current) => {
|
||||
const updated = new Set(current)
|
||||
keys.forEach(k => updated.delete(k))
|
||||
return updated
|
||||
})
|
||||
}, 3000)
|
||||
}
|
||||
}
|
||||
prevMessagesRef.current = messages
|
||||
}, [messages])
|
||||
|
||||
return (
|
||||
<section className="live-rc">
|
||||
<div className="sec-header">
|
||||
<section className="live-rc panel-glass">
|
||||
<div className="sec-header sticky-header">
|
||||
<span className="sec-title">Race Control</span>
|
||||
{messages.length > 0 && <span className="sec-meta">{messages.length} messages</span>}
|
||||
<span className="sec-meta" data-testid="rc-timezone">
|
||||
{messages.length > 0 ? `${messages.length} messages · ` : ''}times UTC
|
||||
</span>
|
||||
</div>
|
||||
{latest.length === 0 ? (
|
||||
<div className="missing-notice">No race control messages in the current live snapshot.</div>
|
||||
) : (
|
||||
<div className="live-rc-list live-rc-scroll">
|
||||
{latest.map((message, index) => (
|
||||
<div className="live-rc-row" key={`${message.Time}-${message.Message}-${index}`}>
|
||||
<span className="rc-time">{message.Time || '--:--'}</span>
|
||||
{message.Lap > 0 && <span className="rc-lap">L{message.Lap}</span>}
|
||||
{message.Flag
|
||||
? <span className={`rc-flag ${rcFlagClass(message.Flag)}`}>{message.Flag}</span>
|
||||
: message.Category && message.Category !== 'Other'
|
||||
? <span className="rc-category">{message.Category}</span>
|
||||
: null
|
||||
<div className="live-rc-list live-rc-scroll" ref={listRef}>
|
||||
{latest.map((message, index) => {
|
||||
const key = `${message.Time}-${message.Message}`
|
||||
const isNew = newKeys.has(key)
|
||||
let flashClass = ''
|
||||
if (isNew) {
|
||||
if (message.Flag === 'YELLOW' || message.Flag === 'DOUBLE YELLOW') {
|
||||
flashClass = ' rc-item-yellow'
|
||||
} else if (message.Flag === 'RED') {
|
||||
flashClass = ' rc-item-red'
|
||||
} else {
|
||||
flashClass = ' rc-item-new'
|
||||
}
|
||||
<span className="rc-message">{message.Message}</span>
|
||||
</div>
|
||||
))}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`live-rc-row${flashClass}`} key={key}>
|
||||
<span className="rc-time" title="UTC">{message.Time || '--:--'}</span>
|
||||
{message.Lap > 0 && <span className="rc-lap">L{message.Lap}</span>}
|
||||
{message.Flag
|
||||
? <span className={`rc-flag ${rcFlagClass(message.Flag)}`}>{message.Flag}</span>
|
||||
: message.Category && message.Category !== 'Other'
|
||||
? <span className="rc-category">{message.Category}</span>
|
||||
: null
|
||||
}
|
||||
<FormattedMessage text={message.Message} driverInfo={driverInfo} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
import type { LiveStreamData } from '../../types'
|
||||
import { extrapolateClock, trackStatusClass, trackStatusLabel } from '../../lib/live'
|
||||
import type { LiveTimingRow } from '../../lib/live'
|
||||
import { extrapolateClock, liveSessionDisplay } from '../../lib/live'
|
||||
import { WeatherStrip } from './WeatherStrip'
|
||||
|
||||
interface Props {
|
||||
isLive: boolean
|
||||
isArchive?: boolean
|
||||
snapshot: LiveStreamData
|
||||
rows: LiveTimingRow[]
|
||||
connection: 'connected' | 'connecting' | 'disconnected' | 'error'
|
||||
now: number
|
||||
}
|
||||
|
||||
export function SessionBanner({ isLive, snapshot, connection, now }: Props) {
|
||||
export function SessionBanner({ isLive, isArchive = false, snapshot, rows, connection, now }: Props) {
|
||||
const session = snapshot.Session
|
||||
const clock = extrapolateClock(snapshot.Clock, snapshot.ClockRefTime, snapshot.ClockExtrapolating, now)
|
||||
const status = snapshot.TrackStatus ? trackStatusLabel(snapshot.TrackStatus) : ''
|
||||
const weather = snapshot.Weather
|
||||
const hasWeather = weather && (weather.AirTemp > 0 || weather.TrackTemp > 0)
|
||||
const display = liveSessionDisplay(session, rows)
|
||||
const atRiskLabel =
|
||||
display.atRiskStart && display.atRiskEnd ? `P${display.atRiskStart}-P${display.atRiskEnd} at risk` : ''
|
||||
const stateLabel = isLive ? 'live' : isArchive ? 'archive' : 'stale'
|
||||
|
||||
return (
|
||||
<section className="live-banner">
|
||||
@@ -27,24 +32,22 @@ export function SessionBanner({ isLive, snapshot, connection, now }: Props) {
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="live-banner-meta">
|
||||
{status && <span className={`track-status ${trackStatusClass(snapshot.TrackStatus)}`}>{status}</span>}
|
||||
<span className="mono">
|
||||
L<strong>{snapshot.CurrentLap || '-'}</strong>/<strong>{snapshot.TotalLaps || '-'}</strong>
|
||||
</span>
|
||||
{clock && <span className="mono">{clock}</span>}
|
||||
<span className={isLive ? 'live-state live-state-on' : 'live-state'}>{isLive ? 'live' : 'stale'}</span>
|
||||
<div className="live-session-board">
|
||||
{display.phaseLabel && <span className="live-phase-pill mono">{display.phaseLabel}</span>}
|
||||
<div className="live-clock mono" data-testid="live-clock">{clock || '--:--:--'}</div>
|
||||
<div className="live-banner-meta">
|
||||
{display.advanceCount && <span>{display.advanceCount} advance</span>}
|
||||
{atRiskLabel && <span>{atRiskLabel}</span>}
|
||||
{display.isRace && (
|
||||
<span data-testid="live-lap-counter">
|
||||
L<strong>{snapshot.CurrentLap || '-'}</strong>/<strong>{snapshot.TotalLaps || '-'}</strong>
|
||||
</span>
|
||||
)}
|
||||
<span className={isLive ? 'live-state live-state-on' : 'live-state'}>{stateLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{hasWeather && (
|
||||
<div className="live-weather-strip">
|
||||
<span>{weather.AirTemp.toFixed(0)}° air</span>
|
||||
<span>{weather.TrackTemp.toFixed(0)}° track</span>
|
||||
{weather.Humidity > 0 && <span>{weather.Humidity.toFixed(0)}% humidity</span>}
|
||||
{weather.WindSpeed > 0 && <span>{weather.WindSpeed.toFixed(1)} m/s</span>}
|
||||
{weather.Rainfall && <span className="badge badge-wet">WET</span>}
|
||||
</div>
|
||||
)}
|
||||
<WeatherStrip weather={snapshot.Weather} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
29
frontend/src/components/live/StintHistory.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { LiveStintData } from '../../types'
|
||||
import { compoundClass, compoundLetter } from '../../lib/live'
|
||||
|
||||
interface Props {
|
||||
stints: LiveStintData[] | undefined
|
||||
}
|
||||
|
||||
export function StintHistory({ stints }: Props) {
|
||||
if (!stints || stints.length === 0) {
|
||||
return <span className="stint-empty">-</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="stint-seq" data-testid="stint-seq">
|
||||
{stints.map((stint, index) => (
|
||||
<span className="stint-item" key={index}>
|
||||
{index > 0 && <span className="stint-arrow">›</span>}
|
||||
<span
|
||||
className={`stint-dot ${compoundClass(stint.Compound)}`}
|
||||
title={`${stint.Compound || 'Unknown'}${stint.New ? ' (new)' : ''} · ${stint.Laps} laps`}
|
||||
>
|
||||
{compoundLetter(stint.Compound)}
|
||||
</span>
|
||||
{stint.Laps > 0 && <span className="stint-laps">{stint.Laps}</span>}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
108
frontend/src/components/live/TeamRadioTicker.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { Pause, Play } from 'lucide-react'
|
||||
import type { LiveDriverInfo, LiveRadioCapture, LiveSessionMeta } from '../../types'
|
||||
import { radioCaptureKey, radioClipUrl } from '../../lib/radio'
|
||||
import { teamColor } from '../../utils'
|
||||
import '../../styles/team-radio.css'
|
||||
|
||||
interface Props {
|
||||
captures?: LiveRadioCapture[]
|
||||
driverInfo?: Record<string, LiveDriverInfo>
|
||||
session?: LiveSessionMeta
|
||||
}
|
||||
|
||||
function relativeTime(utc: string): string {
|
||||
const timestamp = new Date(utc).getTime()
|
||||
if (!utc || Number.isNaN(timestamp)) return '--'
|
||||
|
||||
const diffSeconds = Math.max(0, Math.floor((Date.now() - timestamp) / 1000))
|
||||
if (diffSeconds < 60) return `${diffSeconds}s ago`
|
||||
const minutes = Math.floor(diffSeconds / 60)
|
||||
if (minutes < 60) return `${minutes}m ago`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
if (hours < 24) return `${hours}h ago`
|
||||
return new Date(utc).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
}
|
||||
|
||||
function driverLabel(info: LiveDriverInfo | undefined, racingNumber: string): string {
|
||||
return info?.Tla || racingNumber
|
||||
}
|
||||
|
||||
export function TeamRadioTicker({ captures = [], driverInfo = {}, session }: Props) {
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const [playingKey, setPlayingKey] = useState<string | null>(null)
|
||||
|
||||
const newestFirst = useMemo(() => [...captures].reverse(), [captures])
|
||||
|
||||
const toggleCapture = (capture: LiveRadioCapture) => {
|
||||
const key = radioCaptureKey(capture)
|
||||
const audio = audioRef.current
|
||||
const url = radioClipUrl(session, capture)
|
||||
if (!audio || !url) return
|
||||
|
||||
if (playingKey === key) {
|
||||
audio.pause()
|
||||
setPlayingKey(null)
|
||||
return
|
||||
}
|
||||
|
||||
audio.pause()
|
||||
audio.src = url
|
||||
setPlayingKey(key)
|
||||
const play = audio.play()
|
||||
if (play) {
|
||||
play.catch(() => setPlayingKey(null))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="team-radio panel-glass" data-testid="team-radio-ticker">
|
||||
<div className="sec-header sticky-header">
|
||||
<span className="sec-title">Team Radio</span>
|
||||
{captures.length > 0 && <span className="sec-meta">{captures.length} clips</span>}
|
||||
</div>
|
||||
|
||||
<audio
|
||||
ref={audioRef}
|
||||
className="team-radio-audio"
|
||||
onEnded={() => setPlayingKey(null)}
|
||||
/>
|
||||
|
||||
{newestFirst.length === 0 ? (
|
||||
<div className="missing-notice">No team radio clips in the current live snapshot.</div>
|
||||
) : (
|
||||
<div className="team-radio-list">
|
||||
{newestFirst.map((capture) => {
|
||||
const key = radioCaptureKey(capture)
|
||||
const info = driverInfo[capture.RacingNumber]
|
||||
const label = driverLabel(info, capture.RacingNumber)
|
||||
const isPlaying = playingKey === key
|
||||
const url = radioClipUrl(session, capture)
|
||||
|
||||
return (
|
||||
<div className="team-radio-row" key={key}>
|
||||
<button
|
||||
className="team-radio-play"
|
||||
type="button"
|
||||
aria-label={`${isPlaying ? 'Pause' : 'Play'} ${label} radio`}
|
||||
disabled={!url}
|
||||
onClick={() => toggleCapture(capture)}
|
||||
>
|
||||
{isPlaying ? <Pause size={14} /> : <Play size={14} />}
|
||||
</button>
|
||||
<span
|
||||
className="team-radio-driver"
|
||||
style={{ borderColor: teamColor(info?.TeamColour) }}
|
||||
title={info?.TeamName || undefined}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<span className="team-radio-time">{relativeTime(capture.Utc)}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,16 +1,33 @@
|
||||
import { useState, useMemo, Fragment } from 'react'
|
||||
import { teamColor } from '../../utils'
|
||||
import type { LiveStreamData } from '../../types'
|
||||
import { useAutoAnimate } from '@formkit/auto-animate/react'
|
||||
import type { LiveSessionMeta, LiveStintData } from '../../types'
|
||||
import type { LiveTimingRow } from '../../lib/live'
|
||||
import {
|
||||
bestLapGaps,
|
||||
driverCode,
|
||||
liveSessionDisplay,
|
||||
positionDelta,
|
||||
positionDeltaClass,
|
||||
sortLiveTimingRows,
|
||||
tyreClass,
|
||||
tyreLabel,
|
||||
} from '../../lib/live'
|
||||
import type { GapHistoryMap } from '../../lib/gapHistory'
|
||||
import { parseIntervalSeconds } from '../../lib/gapHistory'
|
||||
import { intervalMeaning } from '../../lib/meaning'
|
||||
import { Meaning } from '../Meaning'
|
||||
import { GapSparkline } from './GapSparkline'
|
||||
import { StintHistory } from './StintHistory'
|
||||
import { Pin } from 'lucide-react'
|
||||
|
||||
interface Props {
|
||||
snapshot: LiveStreamData
|
||||
rows: LiveTimingRow[]
|
||||
stints?: Record<string, LiveStintData[]>
|
||||
history?: GapHistoryMap
|
||||
battleNumbers?: Set<string>
|
||||
pinned?: string[]
|
||||
onTogglePin?: (racingNumber: string) => void
|
||||
session?: LiveSessionMeta
|
||||
}
|
||||
|
||||
function posClass(pos: number): string {
|
||||
@@ -20,8 +37,18 @@ function posClass(pos: number): string {
|
||||
return 'pos-n'
|
||||
}
|
||||
|
||||
export function TimingTower({ snapshot }: Props) {
|
||||
const rows = sortLiveTimingRows(snapshot)
|
||||
export function TimingTower({
|
||||
rows,
|
||||
stints,
|
||||
history,
|
||||
battleNumbers,
|
||||
pinned,
|
||||
onTogglePin,
|
||||
session,
|
||||
}: Props) {
|
||||
const [expandedRow, setExpandedRow] = useState<string | null>(null)
|
||||
const [gapMode, setGapMode] = useState<'interval' | 'leader'>('interval')
|
||||
const [listRef] = useAutoAnimate<HTMLTableSectionElement>({ duration: 300, easing: 'ease-out' })
|
||||
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
@@ -31,62 +58,207 @@ export function TimingTower({ snapshot }: Props) {
|
||||
)
|
||||
}
|
||||
|
||||
const sessionDisplay = liveSessionDisplay(session, rows)
|
||||
const isRace = sessionDisplay.isRace
|
||||
const isQuali = sessionDisplay.isQualifying || !isRace
|
||||
const columnCount = 7 + (isRace ? 3 : 0) + (isQuali ? 3 : 0)
|
||||
|
||||
// Practice/qualifying: derive a display-only gap to P1 from valid best laps
|
||||
// when the upstream feed omits GapToLeader. Empty for races (feed is truth).
|
||||
const practiceGaps = useMemo(() => bestLapGaps(isRace ? [] : rows), [isRace, rows])
|
||||
|
||||
return (
|
||||
<div className="scroll-x">
|
||||
<table className="data-table live-tower" style={{ minWidth: 480 }}>
|
||||
<table className="data-table live-tower" style={{ minWidth: 760 }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Pos</th>
|
||||
<th>Δ</th>
|
||||
{isRace && <th>Δ</th>}
|
||||
<th>Driver</th>
|
||||
<th>Tyre</th>
|
||||
<th>Last Lap</th>
|
||||
<th>Gap</th>
|
||||
<th className="hide-mobile">Best</th>
|
||||
<th className="hide-mobile r">Laps</th>
|
||||
<th className={isRace ? undefined : 'hide-mobile'}>Last Lap</th>
|
||||
<th
|
||||
className="interactive"
|
||||
onClick={() => setGapMode(g => g === 'interval' ? 'leader' : 'interval')}
|
||||
title="Click to toggle Gap vs Interval"
|
||||
style={{ cursor: 'pointer', textDecoration: 'underline' }}
|
||||
>
|
||||
{gapMode === 'interval' && isRace ? 'Interval' : 'Gap to P1'}
|
||||
</th>
|
||||
{isRace && <th>Trend</th>}
|
||||
{isQuali && <th className="hide-mobile">S1</th>}
|
||||
{isQuali && <th className="hide-mobile">S2</th>}
|
||||
{isQuali && <th className="hide-mobile">S3</th>}
|
||||
<th className={isRace ? 'hide-mobile' : undefined}>Best</th>
|
||||
{isRace && <th className="hide-mobile r">Laps</th>}
|
||||
<th className="r"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tbody ref={listRef}>
|
||||
{rows.map((row) => {
|
||||
const driver = row.Driver
|
||||
const delta = positionDelta(driver)
|
||||
const deltaClass = positionDeltaClass(driver)
|
||||
const isPinned = pinned?.includes(row.RacingNumber) ?? false
|
||||
const inBattle = battleNumbers?.has(row.RacingNumber) ?? false
|
||||
const isExpanded = expandedRow === row.RacingNumber
|
||||
const isAtRisk =
|
||||
Boolean(sessionDisplay.cutoffPosition && row.Position > sessionDisplay.cutoffPosition) ||
|
||||
driver.Cutoff
|
||||
const showCutoffAfter = row.Position === sessionDisplay.cutoffPosition
|
||||
|
||||
let gapText: string
|
||||
if (isRace) {
|
||||
gapText = gapMode === 'interval' ? (driver.Interval || driver.GapToLeader) : driver.GapToLeader
|
||||
} else if (driver.GapToLeader) {
|
||||
gapText = driver.GapToLeader
|
||||
} else {
|
||||
const computed = practiceGaps[row.RacingNumber]
|
||||
gapText = computed ? (computed.isLeader ? '—' : computed.gap) : ''
|
||||
}
|
||||
const intervalAnnotation =
|
||||
gapMode === 'interval' && isRace && row.Position > 1
|
||||
? intervalMeaning(parseIntervalSeconds(gapText))
|
||||
: null
|
||||
|
||||
const renderSector = (idx: number) => {
|
||||
const sec = driver.Sectors?.[idx]
|
||||
if (!sec) return '-'
|
||||
let sClass = 'sector-time mono'
|
||||
if (sec.OverallFastest) sClass += ' sector-overall txt-purple'
|
||||
else if (sec.PersonalFastest) sClass += ' sector-personal txt-green'
|
||||
else if (sec.Value) sClass += ' sector-active txt-yellow'
|
||||
return <span className={sClass}>{sec.Value || '-'}</span>
|
||||
}
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={row.RacingNumber}
|
||||
className={[
|
||||
driver.InPit ? 'in-pit' : '',
|
||||
driver.PitOut ? 'pit-out' : '',
|
||||
driver.Retired ? 'retired' : '',
|
||||
].filter(Boolean).join(' ')}
|
||||
>
|
||||
<td className={`mono ${posClass(row.Position)}`}>{row.Position}</td>
|
||||
<td className={`pos-delta${deltaClass ? ` ${deltaClass}` : ''}`}>{delta}</td>
|
||||
<td>
|
||||
<div className="drv-cell">
|
||||
<div className="drv-bar" style={{ background: teamColor(row.Info?.TeamColour) }} />
|
||||
<span className="drv-code">{driverCode(row)}</span>
|
||||
<span className="drv-num">{row.RacingNumber}</span>
|
||||
{driver.InPit && <span className="badge badge-pit">PIT</span>}
|
||||
{driver.PitOut && !driver.InPit && <span className="badge badge-pit">OUT</span>}
|
||||
{driver.Retired && <span className="badge badge-out">RET</span>}
|
||||
{driver.KnockedOut && <span className="badge badge-knocked">KO</span>}
|
||||
{driver.Cutoff && !driver.KnockedOut && <span className="badge badge-cutoff">CUT</span>}
|
||||
{driver.OnFlyingLap && <span className="badge badge-flying">FL</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`tyre-badge ${tyreClass(row.Tyre)}`}>{tyreLabel(row.Tyre)}</span>
|
||||
</td>
|
||||
<td className={driver.LastLapOB ? 'mono lap-ob' : driver.LastLapPB ? 'mono lap-pb' : 'mono'}>
|
||||
{driver.LastLapTime || '-'}
|
||||
</td>
|
||||
<td className="mono">{driver.GapToLeader || driver.Interval || '-'}</td>
|
||||
<td className={`hide-mobile ${driver.BestLapOB ? 'mono lap-ob' : 'mono'}`}>
|
||||
{driver.BestLapTime || '-'}
|
||||
</td>
|
||||
<td className="hide-mobile mono r">{driver.NumberOfLaps || '-'}</td>
|
||||
</tr>
|
||||
<Fragment key={row.RacingNumber}>
|
||||
<tr
|
||||
className={[
|
||||
driver.InPit ? 'in-pit' : '',
|
||||
driver.PitOut ? 'pit-out' : '',
|
||||
driver.Retired ? 'retired' : '',
|
||||
inBattle ? 'battle-row' : '',
|
||||
isPinned ? 'pinned-row' : '',
|
||||
isAtRisk && !driver.KnockedOut ? 'danger-row' : '',
|
||||
driver.OnFlyingLap ? 'flying-row' : '',
|
||||
'interactive-row'
|
||||
].filter(Boolean).join(' ')}
|
||||
onClick={() => setExpandedRow(isExpanded ? null : row.RacingNumber)}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<td className={`mono ${posClass(row.Position)}`}>{row.Position}</td>
|
||||
{isRace && <td className={`pos-delta${deltaClass ? ` ${deltaClass}` : ''}`}>{delta}</td>}
|
||||
<td>
|
||||
<div className="drv-cell">
|
||||
<div className="drv-bar" style={{ background: teamColor(row.Info?.TeamColour) }} />
|
||||
<span className="drv-code">{driverCode(row)}</span>
|
||||
<span className="drv-num">{row.RacingNumber}</span>
|
||||
{driver.InPit && <span className="badge badge-pit">PIT</span>}
|
||||
{driver.PitOut && !driver.InPit && <span className="badge badge-pit">OUT</span>}
|
||||
{driver.Retired && <span className="badge badge-out">RET</span>}
|
||||
{driver.KnockedOut && <span className="badge badge-knocked">KO</span>}
|
||||
{driver.Cutoff && !driver.KnockedOut && <span className="badge badge-cutoff">CUT</span>}
|
||||
{!driver.Cutoff && isAtRisk && !driver.KnockedOut && <span className="badge badge-risk">RISK</span>}
|
||||
{driver.OnFlyingLap && <span className="badge badge-flying">FL</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`tyre-badge ${tyreClass(row.Tyre)}`}>{tyreLabel(row.Tyre)}</span>
|
||||
</td>
|
||||
<td className={[
|
||||
isRace ? '' : 'hide-mobile',
|
||||
driver.LastLapOB ? 'mono lap-ob' : driver.LastLapPB ? 'mono lap-pb' : 'mono',
|
||||
].filter(Boolean).join(' ')}>
|
||||
{driver.LastLapTime || '-'}
|
||||
</td>
|
||||
<td className="mono">
|
||||
<Meaning
|
||||
value={gapText || '-'}
|
||||
meaning={intervalAnnotation?.caption}
|
||||
title={intervalAnnotation?.title}
|
||||
tone={intervalAnnotation?.tone}
|
||||
/>
|
||||
</td>
|
||||
|
||||
{isRace && (
|
||||
<td className="spark-cell">
|
||||
<GapSparkline samples={history?.[row.RacingNumber]} />
|
||||
</td>
|
||||
)}
|
||||
|
||||
{isQuali && <td className="hide-mobile">{renderSector(0)}</td>}
|
||||
{isQuali && <td className="hide-mobile">{renderSector(1)}</td>}
|
||||
{isQuali && <td className="hide-mobile">{renderSector(2)}</td>}
|
||||
|
||||
<td className={[
|
||||
isRace ? 'hide-mobile' : '',
|
||||
driver.BestLapOB ? 'mono lap-ob' : 'mono',
|
||||
].filter(Boolean).join(' ')}>
|
||||
{driver.BestLapTime || '-'}
|
||||
</td>
|
||||
|
||||
{isRace && <td className="hide-mobile mono r">{driver.NumberOfLaps || '-'}</td>}
|
||||
|
||||
<td className="r">
|
||||
{onTogglePin && (
|
||||
<button
|
||||
className="pin-btn interactive"
|
||||
onClick={(e) => { e.stopPropagation(); onTogglePin(row.RacingNumber); }}
|
||||
style={{ opacity: isPinned ? 1 : 0.3, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text)' }}
|
||||
title={isPinned ? 'Unpin driver' : 'Pin driver'}
|
||||
>
|
||||
<Pin size={14} fill={isPinned ? 'currentColor' : 'none'} />
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
{isExpanded && (
|
||||
<tr className="expanded-row">
|
||||
<td colSpan={columnCount} style={{ padding: '16px', background: 'rgba(255,255,255,0.02)', borderBottom: '1px solid var(--border)' }}>
|
||||
<div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>
|
||||
<div>
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>STINTS</div>
|
||||
<StintHistory stints={stints?.[row.RacingNumber]} />
|
||||
</div>
|
||||
{!isRace && (
|
||||
<div>
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>LAPS</div>
|
||||
<div className="mono">{driver.NumberOfLaps || 0}</div>
|
||||
</div>
|
||||
)}
|
||||
{!isRace && driver.Sectors?.some((sec) => sec?.Value) && (
|
||||
<div data-testid="expanded-sectors">
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>SECTORS</div>
|
||||
<div className="mono" style={{ display: 'flex', gap: '10px' }}>
|
||||
{renderSector(0)}
|
||||
{renderSector(1)}
|
||||
{renderSector(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{driver.SpeedTrap && (
|
||||
<div>
|
||||
<div className="mono" style={{ color: 'var(--text-3)', fontSize: '10px', marginBottom: '4px' }}>SPEED TRAP</div>
|
||||
<div className="mono">{driver.SpeedTrap} km/h</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{showCutoffAfter && (
|
||||
<tr className="cutoff-separator" data-testid="qualifying-cutoff">
|
||||
<td colSpan={columnCount}>
|
||||
<span>{sessionDisplay.phaseLabel || 'Q'} cutoff</span>
|
||||
<strong>P{sessionDisplay.cutoffPosition} advance</strong>
|
||||
{sessionDisplay.atRiskStart && sessionDisplay.atRiskEnd && (
|
||||
<em>P{sessionDisplay.atRiskStart}-P{sessionDisplay.atRiskEnd} at risk</em>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
|
||||
145
frontend/src/components/live/TrackMap.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import type {
|
||||
LiveDriverData,
|
||||
LiveDriverInfo,
|
||||
LivePosition,
|
||||
LiveTelemetry,
|
||||
TrackOutline,
|
||||
} from '../../types'
|
||||
import {
|
||||
buildOutlinePath,
|
||||
canvasToSvg,
|
||||
isOnTrack,
|
||||
normalizeRawPoint,
|
||||
} from '../../lib/trackmap'
|
||||
|
||||
interface Props {
|
||||
outline?: TrackOutline | null
|
||||
positions: Record<string, LivePosition>
|
||||
telemetry?: Record<string, LiveTelemetry>
|
||||
drivers?: Record<string, LiveDriverData>
|
||||
driverInfo?: Record<string, LiveDriverInfo>
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
export function TrackMap({
|
||||
outline,
|
||||
positions,
|
||||
telemetry = {},
|
||||
drivers = {},
|
||||
driverInfo = {},
|
||||
loading = false,
|
||||
}: Props) {
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
const outlinePath = useMemo(() => buildOutlinePath(outline?.points ?? []), [outline])
|
||||
const cars = useMemo(() => {
|
||||
if (!outline?.bounds) return []
|
||||
return Object.entries(positions)
|
||||
.map(([number, position]) => {
|
||||
const canvas = normalizeRawPoint(position, outline.bounds)
|
||||
return {
|
||||
number,
|
||||
position,
|
||||
svg: canvasToSvg(canvas),
|
||||
info: driverInfo[number],
|
||||
driver: drivers[number],
|
||||
telemetry: telemetry[number],
|
||||
active: isOnTrack(position.status) && !drivers[number]?.Retired,
|
||||
}
|
||||
})
|
||||
.sort((a, b) => Number(a.number) - Number(b.number))
|
||||
}, [driverInfo, drivers, outline?.bounds, positions, telemetry])
|
||||
|
||||
const selectedCar = selected ? cars.find((car) => car.number === selected) : null
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<section className="live-track-panel" data-testid="track-map">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Track Map</span>
|
||||
</div>
|
||||
<div className="track-map-empty">loading cached circuit outline...</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
if (!outline || !outlinePath) {
|
||||
return (
|
||||
<section className="live-track-panel" data-testid="track-map">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Track Map</span>
|
||||
</div>
|
||||
<div className="track-map-empty">track outline unavailable for this live session</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="live-track-panel" data-testid="track-map">
|
||||
<div className="sec-header">
|
||||
<span className="sec-title">Track Map</span>
|
||||
<span className="sec-meta">{cars.length ? `${cars.length} cars` : 'waiting for GPS'}</span>
|
||||
</div>
|
||||
<div className="track-map-stage">
|
||||
<svg className="track-map-svg" viewBox="0 0 100 100" role="img" aria-label="Live track map">
|
||||
<path className="track-map-outline-shadow" d={outlinePath} />
|
||||
<path className="track-map-outline" d={outlinePath} />
|
||||
{cars.map((car) => {
|
||||
const label = car.info?.Tla || car.number
|
||||
return (
|
||||
<g
|
||||
key={car.number}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`${label} telemetry`}
|
||||
className={`track-car ${car.active ? 'track-car-active' : 'track-car-inactive'} ${selected === car.number ? 'track-car-selected' : ''}`}
|
||||
transform={`translate(${car.svg.x.toFixed(2)} ${car.svg.y.toFixed(2)})`}
|
||||
onClick={() => setSelected(car.number)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
setSelected(car.number)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<circle r="2.8" fill={teamColor(car.info)} />
|
||||
<text y="0.85">{label}</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
{cars.length === 0 && <div className="track-map-empty track-map-overlay">waiting for live GPS</div>}
|
||||
{selectedCar && (
|
||||
<div className="track-telemetry" data-testid="track-telemetry">
|
||||
<div className="track-telemetry-head">
|
||||
<span className="track-driver-code">{selectedCar.info?.Tla || selectedCar.number}</span>
|
||||
<span>{selectedCar.position.status || 'OnTrack'}</span>
|
||||
</div>
|
||||
<dl>
|
||||
<Metric label="SPD" value={selectedCar.telemetry?.Speed} suffix="km/h" />
|
||||
<Metric label="THR" value={selectedCar.telemetry?.Throttle} suffix="%" />
|
||||
<Metric label="BRK" value={selectedCar.telemetry?.Brake} suffix="%" />
|
||||
<Metric label="DRS" value={selectedCar.telemetry?.DRS} />
|
||||
<Metric label="GEAR" value={selectedCar.telemetry?.NGear} />
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Metric({ label, value, suffix = '' }: { label: string; value: number | undefined; suffix?: string }) {
|
||||
return (
|
||||
<>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value === undefined ? '-' : `${value}${suffix}`}</dd>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function teamColor(info: LiveDriverInfo | undefined): string {
|
||||
const raw = info?.TeamColour?.trim()
|
||||
if (!raw) return '#777777'
|
||||
return raw.startsWith('#') ? raw : `#${raw}`
|
||||
}
|
||||
17
frontend/src/components/live/TrackStatusBanner.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { trackStatusInfo } from '../../lib/live'
|
||||
|
||||
interface Props {
|
||||
status: string | null | undefined
|
||||
}
|
||||
|
||||
export function TrackStatusBanner({ status }: Props) {
|
||||
if (!status) return null
|
||||
const info = trackStatusInfo(status)
|
||||
|
||||
return (
|
||||
<div className={`track-banner track-banner-${info.key}`} role="status" data-testid="track-banner">
|
||||
<span className="track-banner-label">{info.label}</span>
|
||||
{info.detail && <span className="track-banner-detail">{info.detail}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
171
frontend/src/components/live/TyreDegPanel.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { teamColor } from '../../utils'
|
||||
import type { LiveTimingRow } from '../../lib/live'
|
||||
import { compoundClass, driverCode, tyreLabel } from '../../lib/live'
|
||||
import { sparklinePoints } from '../../lib/gapHistory'
|
||||
import { isRaceSession } from '../../lib/battles'
|
||||
import type { StintHistoryMap } from '../../lib/tyredeg'
|
||||
import {
|
||||
PIT_LOSS_SECONDS,
|
||||
degradationModel,
|
||||
estimatePitRejoin,
|
||||
formatSlope,
|
||||
recordStintSamples,
|
||||
stintInputFromRow,
|
||||
} from '../../lib/tyredeg'
|
||||
import { tyreAgeMeaning } from '../../lib/meaning'
|
||||
import { Meaning } from '../Meaning'
|
||||
import '../../styles/tyredeg.css'
|
||||
|
||||
const TOP_DRIVER_COUNT = 10
|
||||
const SPARK_WIDTH = 64
|
||||
const SPARK_HEIGHT = 16
|
||||
|
||||
interface Props {
|
||||
rows: LiveTimingRow[]
|
||||
sessionType: string | undefined
|
||||
pinned: string[]
|
||||
}
|
||||
|
||||
function StintSparkline({ seconds }: { seconds: number[] }) {
|
||||
if (seconds.length < 2) return <span className="tyredeg-spark-empty">·</span>
|
||||
const points = sparklinePoints(seconds, SPARK_WIDTH, SPARK_HEIGHT)
|
||||
return (
|
||||
<svg
|
||||
className="tyredeg-spark"
|
||||
width={SPARK_WIDTH}
|
||||
height={SPARK_HEIGHT}
|
||||
viewBox={`0 0 ${SPARK_WIDTH} ${SPARK_HEIGHT}`}
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function TyreDegPanel({ rows, sessionType, pinned }: Props) {
|
||||
const isRace = isRaceSession(sessionType)
|
||||
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).
|
||||
useEffect(() => {
|
||||
if (rows.length === 0) return
|
||||
setStints((prev) => recordStintSamples(prev, rows.map(stintInputFromRow)))
|
||||
}, [rows])
|
||||
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
rows.filter(
|
||||
(row) =>
|
||||
row.Position > 0 &&
|
||||
!row.Driver.Retired &&
|
||||
(row.Position <= TOP_DRIVER_COUNT || pinned.includes(row.RacingNumber)),
|
||||
),
|
||||
[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 (
|
||||
<section className="live-tyredeg-panel" data-testid="tyredeg-panel">
|
||||
<button
|
||||
type="button"
|
||||
className="sec-header tyredeg-toggle"
|
||||
onClick={() => {
|
||||
setReaderChose(true)
|
||||
setCollapsed((prev) => !prev)
|
||||
}}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
<span className="sec-title">Tyre Deg & Pit Window</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 = models[row.RacingNumber]
|
||||
const rejoin = isRace ? estimatePitRejoin(rows, row.RacingNumber) : null
|
||||
const ageAnnotation = tyreAgeMeaning(row.Tyre?.Compound, row.Tyre?.Age)
|
||||
return (
|
||||
<div className="tyredeg-row" key={row.RacingNumber} data-testid="tyredeg-row">
|
||||
<span className="tyredeg-pos mono">P{row.Position}</span>
|
||||
<span className="drv-bar" style={{ background: teamColor(row.Info?.TeamColour) }} />
|
||||
<span className="drv-code">{driverCode(row)}</span>
|
||||
<span className={`tyre-badge ${compoundClass(row.Tyre?.Compound)}`}>
|
||||
<Meaning
|
||||
value={tyreLabel(row.Tyre)}
|
||||
meaning={ageAnnotation?.caption}
|
||||
title={ageAnnotation?.title}
|
||||
tone={ageAnnotation?.tone}
|
||||
/>
|
||||
</span>
|
||||
{model ? (
|
||||
<>
|
||||
<span className={`tyredeg-trend tyredeg-trend-${model.trend}`}>
|
||||
<StintSparkline seconds={model.samples.map((sample) => sample.seconds)} />
|
||||
</span>
|
||||
<span className={`tyredeg-slope mono tyredeg-trend-${model.trend}`}>
|
||||
{formatSlope(model.slope)}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="tyredeg-warmup">warming up</span>
|
||||
)}
|
||||
{rejoin && (
|
||||
<span className="tyredeg-rejoin mono" title={`Pits now: rejoins ~P${rejoin.rejoinPosition}`}>
|
||||
→ ~P{rejoin.rejoinPosition}
|
||||
{rejoin.aheadCode && rejoin.behindCode && (
|
||||
<span className="tyredeg-rejoin-between">
|
||||
{rejoin.aheadCode} · {rejoin.behindCode}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
51
frontend/src/components/live/WeatherStrip.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import type { LiveWeatherData } from '../../types'
|
||||
import { windDirectionLabel } from '../../lib/live'
|
||||
|
||||
interface Props {
|
||||
weather: LiveWeatherData | null | undefined
|
||||
}
|
||||
|
||||
export function WeatherStrip({ weather }: Props) {
|
||||
if (!weather) return null
|
||||
const hasData =
|
||||
weather.AirTemp > 0 ||
|
||||
weather.TrackTemp > 0 ||
|
||||
weather.Humidity > 0 ||
|
||||
weather.WindSpeed > 0 ||
|
||||
weather.Rainfall
|
||||
if (!hasData) return null
|
||||
|
||||
const windDir = windDirectionLabel(weather.WindDir)
|
||||
|
||||
return (
|
||||
<div className="live-weather-strip" data-testid="weather-strip">
|
||||
{weather.AirTemp > 0 && (
|
||||
<span className="weather-item">
|
||||
<span className="weather-k">air</span>
|
||||
<span className="weather-v">{weather.AirTemp.toFixed(0)}°C</span>
|
||||
</span>
|
||||
)}
|
||||
{weather.TrackTemp > 0 && (
|
||||
<span className="weather-item">
|
||||
<span className="weather-k">track</span>
|
||||
<span className="weather-v">{weather.TrackTemp.toFixed(0)}°C</span>
|
||||
</span>
|
||||
)}
|
||||
{weather.Humidity > 0 && (
|
||||
<span className="weather-item">
|
||||
<span className="weather-k">hum</span>
|
||||
<span className="weather-v">{weather.Humidity.toFixed(0)}%</span>
|
||||
</span>
|
||||
)}
|
||||
{weather.WindSpeed > 0 && (
|
||||
<span className="weather-item">
|
||||
<span className="weather-k">wind</span>
|
||||
<span className="weather-v">
|
||||
{weather.WindSpeed.toFixed(1)} m/s{windDir ? ` ${windDir}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{weather.Rainfall && <span className="badge badge-wet">RAIN</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
108
frontend/src/lib/battles.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
// Battle detection for the live timing tower.
|
||||
// Pure functions only — no React, no side effects — so everything is unit-testable.
|
||||
|
||||
import type { LiveTimingRow } from './live'
|
||||
import { driverCode } from './live'
|
||||
import { parseIntervalSeconds } from './gapHistory'
|
||||
|
||||
export const BATTLE_THRESHOLD_SECONDS = 1.0
|
||||
|
||||
export interface BattleDriver {
|
||||
racingNumber: string
|
||||
code: string
|
||||
position: number
|
||||
/** Interval to the car ahead within the group; null for the group leader. */
|
||||
gapToAhead: number | null
|
||||
}
|
||||
|
||||
export interface Battle {
|
||||
drivers: BattleDriver[]
|
||||
/** Tightest car-to-car interval within the group. */
|
||||
minGap: number
|
||||
}
|
||||
|
||||
/** Battles are only meaningful in race-type sessions (GP race, sprint). */
|
||||
export function isRaceSession(sessionType: string | null | undefined): boolean {
|
||||
if (!sessionType) return false
|
||||
const type = sessionType.toLowerCase()
|
||||
const isQualifying = type.includes('qualifying') || type.includes('shootout') || /\bsq\s*[123]\b/.test(type)
|
||||
return !isQualifying && (type.includes('race') || /\bsprint\b/.test(type))
|
||||
}
|
||||
|
||||
function isEligible(row: LiveTimingRow): boolean {
|
||||
const driver = row.Driver
|
||||
return Boolean(driver) && !driver.InPit && !driver.Retired && row.Position > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan position-sorted tower rows and group consecutive cars racing within
|
||||
* `threshold` seconds of the car ahead. Cars in the pits or retired break
|
||||
* the chain, as do lapped/unparsable intervals.
|
||||
*/
|
||||
export function detectBattles(
|
||||
rows: ReadonlyArray<LiveTimingRow>,
|
||||
sessionType: string | null | undefined,
|
||||
threshold = BATTLE_THRESHOLD_SECONDS,
|
||||
): Battle[] {
|
||||
if (!isRaceSession(sessionType) || rows.length < 2) return []
|
||||
|
||||
const battles: Battle[] = []
|
||||
let current: BattleDriver[] | null = null
|
||||
let minGap = Number.POSITIVE_INFINITY
|
||||
|
||||
const flush = () => {
|
||||
if (current && current.length >= 2) {
|
||||
battles.push({ drivers: current, minGap })
|
||||
}
|
||||
current = null
|
||||
minGap = Number.POSITIVE_INFINITY
|
||||
}
|
||||
|
||||
for (let i = 1; i < rows.length; i++) {
|
||||
const ahead = rows[i - 1]
|
||||
const row = rows[i]
|
||||
const gap = parseIntervalSeconds(row.Driver?.Interval)
|
||||
|
||||
const inBattle =
|
||||
gap !== null && gap >= 0 && gap <= threshold && isEligible(ahead) && isEligible(row)
|
||||
|
||||
if (!inBattle) {
|
||||
flush()
|
||||
continue
|
||||
}
|
||||
|
||||
if (!current) {
|
||||
current = [toBattleDriver(ahead, null)]
|
||||
}
|
||||
current.push(toBattleDriver(row, gap))
|
||||
if (gap < minGap) minGap = gap
|
||||
}
|
||||
flush()
|
||||
|
||||
return battles
|
||||
}
|
||||
|
||||
function toBattleDriver(row: LiveTimingRow, gapToAhead: number | null): BattleDriver {
|
||||
return {
|
||||
racingNumber: row.RacingNumber,
|
||||
code: driverCode(row),
|
||||
position: row.Position,
|
||||
gapToAhead,
|
||||
}
|
||||
}
|
||||
|
||||
/** Chip label, e.g. "VER ⚔ NOR +0.4" or "VER ⚔ NOR ⚔ PIA +0.3". */
|
||||
export function battleLabel(battle: Battle): string {
|
||||
const codes = battle.drivers.map((driver) => driver.code).join(' ⚔ ')
|
||||
const gap = Number.isFinite(battle.minGap) ? ` +${battle.minGap.toFixed(1)}` : ''
|
||||
return `${codes}${gap}`
|
||||
}
|
||||
|
||||
/** Racing numbers involved in any battle, for tower row highlighting. */
|
||||
export function battleNumbers(battles: ReadonlyArray<Battle>): Set<string> {
|
||||
const numbers = new Set<string>()
|
||||
for (const battle of battles) {
|
||||
for (const driver of battle.drivers) numbers.add(driver.racingNumber)
|
||||
}
|
||||
return numbers
|
||||
}
|
||||
132
frontend/src/lib/chapters.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import type { Chapter } from '../types'
|
||||
|
||||
export function chapterKindLabel(kind: string): string {
|
||||
switch (kind) {
|
||||
case 'start':
|
||||
return 'GO'
|
||||
case 'safety_car':
|
||||
return 'SC'
|
||||
case 'virtual_safety_car':
|
||||
return 'VSC'
|
||||
case 'red_flag':
|
||||
return 'RF'
|
||||
case 'pit_phase':
|
||||
return 'PIT'
|
||||
case 'decisive_swing':
|
||||
return '▲'
|
||||
case 'finish':
|
||||
return 'FIN'
|
||||
default:
|
||||
return kind.slice(0, 3).toUpperCase()
|
||||
}
|
||||
}
|
||||
|
||||
export function chapterLapRange(chapter: Chapter): string {
|
||||
if (chapter.start_lap === chapter.end_lap) {
|
||||
return `L${chapter.start_lap}`
|
||||
}
|
||||
return `L${chapter.start_lap}–L${chapter.end_lap}`
|
||||
}
|
||||
|
||||
/** Normalized scrub position (0–1) for a chapter's start time on the chart axis. */
|
||||
export function chapterStartScrub(
|
||||
chapter: Chapter,
|
||||
tMin: number,
|
||||
tRange: number,
|
||||
): number | null {
|
||||
if (!chapter.start_time || tRange <= 0) return null
|
||||
const ms = new Date(chapter.start_time).getTime()
|
||||
if (Number.isNaN(ms)) return null
|
||||
return Math.max(0, Math.min(1, (ms - tMin) / tRange))
|
||||
}
|
||||
|
||||
/** Normalized scrub position (0–1) for a chapter's end time on the chart axis. */
|
||||
export function chapterEndScrub(
|
||||
chapter: Chapter,
|
||||
tMin: number,
|
||||
tRange: number,
|
||||
): number | null {
|
||||
const raw = chapter.end_time ?? chapter.start_time
|
||||
if (!raw || tRange <= 0) return null
|
||||
const ms = new Date(raw).getTime()
|
||||
if (Number.isNaN(ms)) return null
|
||||
return Math.max(0, Math.min(1, (ms - tMin) / tRange))
|
||||
}
|
||||
|
||||
/** Index of the chapter containing the current scrub position, if any.
|
||||
* Uses the same 0–1 clamped bounds as chapterStartScrub/chapterEndScrub so
|
||||
* chapters whose timestamps fall outside the position-sample window still
|
||||
* activate when the scrubber is parked at the clamped edge. */
|
||||
export function activeChapterIndex(
|
||||
chapters: Chapter[],
|
||||
scrubTime: number | null,
|
||||
tMin: number,
|
||||
tRange: number,
|
||||
): number | null {
|
||||
if (scrubTime === null || chapters.length === 0 || tRange <= 0) return null
|
||||
for (let i = 0; i < chapters.length; i++) {
|
||||
const start = chapterStartScrub(chapters[i], tMin, tRange)
|
||||
const end = chapterEndScrub(chapters[i], tMin, tRange)
|
||||
if (start === null || end === null) continue
|
||||
const lo = Math.min(start, end)
|
||||
const hi = Math.max(start, end)
|
||||
if (scrubTime >= lo && scrubTime <= hi) return i
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Duration in ms each chapter should play during a ~90s tour. */
|
||||
export function chapterTourDurations(chapters: Chapter[], totalMs = 90_000): number[] {
|
||||
if (chapters.length === 0) return []
|
||||
const perChapter = totalMs / chapters.length
|
||||
return chapters.map(() => perChapter)
|
||||
}
|
||||
|
||||
/** Decimated position axis labels, e.g. P1, P5, P10, P15, P20. */
|
||||
export function decimatedPositionLabels(maxPos: number): number[] {
|
||||
if (maxPos <= 1) return [1]
|
||||
const labels = new Set<number>([1])
|
||||
for (let pos = 5; pos < maxPos; pos += 5) {
|
||||
labels.add(pos)
|
||||
}
|
||||
labels.add(maxPos)
|
||||
return [...labels].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
/** Subtle background fill for chapter time-bands on the position graph. */
|
||||
export function chapterBandFill(kind: string): string {
|
||||
switch (kind) {
|
||||
case 'safety_car':
|
||||
return 'rgba(255, 153, 0, 0.14)'
|
||||
case 'virtual_safety_car':
|
||||
return 'rgba(255, 204, 0, 0.12)'
|
||||
case 'red_flag':
|
||||
return 'rgba(230, 36, 41, 0.12)'
|
||||
case 'pit_phase':
|
||||
return 'rgba(96, 165, 250, 0.08)'
|
||||
case 'decisive_swing':
|
||||
return 'rgba(34, 197, 94, 0.08)'
|
||||
case 'finish':
|
||||
return 'rgba(255, 204, 0, 0.06)'
|
||||
default:
|
||||
return 'rgba(255, 255, 255, 0.03)'
|
||||
}
|
||||
}
|
||||
|
||||
/** Minimum vertical spacing between colliding labels (SVG units). */
|
||||
export function deCollideYPositions(
|
||||
items: ReadonlyArray<{ key: string | number; y: number }>,
|
||||
minGap = 12,
|
||||
): Map<string | number, number> {
|
||||
if (items.length === 0) return new Map()
|
||||
const sorted = [...items].sort((a, b) => a.y - b.y)
|
||||
const adjusted = sorted.map((item) => ({ ...item }))
|
||||
for (let i = 1; i < adjusted.length; i++) {
|
||||
const prev = adjusted[i - 1]
|
||||
const curr = adjusted[i]
|
||||
if (curr.y - prev.y < minGap) {
|
||||
curr.y = prev.y + minGap
|
||||
}
|
||||
}
|
||||
return new Map(adjusted.map((item) => [item.key, item.y]))
|
||||
}
|
||||
202
frontend/src/lib/compare.ts
Normal file
@@ -0,0 +1,202 @@
|
||||
// Driver comparison mapping — pure functions for telemetry traces and lap deltas.
|
||||
|
||||
import type { TelemetryTraceSeries } from '../components/charts/TelemetryTraceChart'
|
||||
import type { DeltaSeries } from '../lib/delta'
|
||||
import type {
|
||||
CarDataSample,
|
||||
ComparisonLap,
|
||||
Driver,
|
||||
EnrichedResult,
|
||||
LapsComparisonResponse,
|
||||
} from '../types'
|
||||
import { compareFinishPosition, teamColor } from '../utils'
|
||||
|
||||
function sortDriversByResults(drivers: Driver[], results: EnrichedResult[]): Driver[] {
|
||||
const order = new Map(
|
||||
[...results]
|
||||
.filter((r) => r.position > 0)
|
||||
.sort((a, b) => compareFinishPosition(a.position, b.position))
|
||||
.map((r, i) => [r.driver_number, i]),
|
||||
)
|
||||
return [...drivers].sort((a, b) => {
|
||||
const ao = order.get(a.driver_number) ?? 999
|
||||
const bo = order.get(b.driver_number) ?? 999
|
||||
if (ao !== bo) return ao - bo
|
||||
return a.driver_number - b.driver_number
|
||||
})
|
||||
}
|
||||
|
||||
/** Default compare pair: top two classified finishers, else first two session drivers. */
|
||||
export function defaultCompareDriverNumbers(
|
||||
results: EnrichedResult[],
|
||||
drivers: Driver[],
|
||||
): [number, number] | null {
|
||||
const classified = [...results]
|
||||
.filter((r) => r.position > 0)
|
||||
.sort((a, b) => compareFinishPosition(a.position, b.position))
|
||||
|
||||
if (classified.length >= 2) {
|
||||
return [classified[0].driver_number, classified[1].driver_number]
|
||||
}
|
||||
|
||||
if (drivers.length >= 2) {
|
||||
const sorted = sortDriversByResults(drivers, results)
|
||||
return [sorted[0].driver_number, sorted[1].driver_number]
|
||||
}
|
||||
|
||||
if (classified.length === 1 && drivers.length >= 1) {
|
||||
const other = drivers.find((d) => d.driver_number !== classified[0].driver_number)
|
||||
if (other) return [classified[0].driver_number, other.driver_number]
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** Lap records → per-lap duration array (index 0 = lap 1); null for pit/out laps. */
|
||||
export function lapsToLapTimes(laps: ComparisonLap[]): (number | null)[] {
|
||||
if (laps.length === 0) return []
|
||||
|
||||
const maxLap = laps.reduce((max, lap) => Math.max(max, lap.lap_number), 0)
|
||||
const times: (number | null)[] = Array.from({ length: maxLap }, () => null)
|
||||
|
||||
for (const lap of laps) {
|
||||
const idx = lap.lap_number - 1
|
||||
if (idx < 0) continue
|
||||
if (lap.is_pit_out_lap || lap.lap_duration == null || lap.lap_duration <= 0) {
|
||||
times[idx] = null
|
||||
} else {
|
||||
times[idx] = lap.lap_duration
|
||||
}
|
||||
}
|
||||
|
||||
return times
|
||||
}
|
||||
|
||||
export function findBestLap(laps: ComparisonLap[]): ComparisonLap | null {
|
||||
let best: ComparisonLap | null = null
|
||||
for (const lap of laps) {
|
||||
if (lap.lap_duration == null || lap.lap_duration <= 0) continue
|
||||
if (!best || (best.lap_duration ?? Infinity) > lap.lap_duration) {
|
||||
best = lap
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/** Keep car-data samples whose timestamps fall within a lap window. */
|
||||
export function filterCarDataToLap(
|
||||
samples: CarDataSample[],
|
||||
lap: ComparisonLap,
|
||||
): CarDataSample[] {
|
||||
if (!lap.date_start || samples.length === 0) return samples
|
||||
|
||||
const start = new Date(lap.date_start).getTime()
|
||||
if (!Number.isFinite(start)) return samples
|
||||
|
||||
const end = start + (lap.lap_duration ?? 0) * 1000 + 500
|
||||
|
||||
return samples.filter((s) => {
|
||||
const t = new Date(s.date).getTime()
|
||||
return Number.isFinite(t) && t >= start && t <= end
|
||||
})
|
||||
}
|
||||
|
||||
export function carDataToTraceSeries(
|
||||
samples: CarDataSample[],
|
||||
label: string,
|
||||
color: string,
|
||||
): TelemetryTraceSeries {
|
||||
return {
|
||||
label,
|
||||
color,
|
||||
samples: samples.map((s) => ({
|
||||
speed: s.speed,
|
||||
throttle: s.throttle,
|
||||
brake: s.brake,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export function buildBestLapTraceSeries(
|
||||
carData: CarDataSample[],
|
||||
laps: ComparisonLap[],
|
||||
label: string,
|
||||
color: string,
|
||||
): TelemetryTraceSeries | null {
|
||||
const best = findBestLap(laps)
|
||||
if (!best) return null
|
||||
|
||||
const filtered = filterCarDataToLap(carData, best)
|
||||
if (filtered.length === 0) return null
|
||||
|
||||
return carDataToTraceSeries(filtered, label, color)
|
||||
}
|
||||
|
||||
function driverMeta(
|
||||
driverNumber: number,
|
||||
comparison: LapsComparisonResponse | undefined,
|
||||
drivers: Driver[],
|
||||
): { label: string; color: string; laps: ComparisonLap[] } {
|
||||
const comp = comparison?.drivers.find((d) => d.driver_number === driverNumber)
|
||||
const session = drivers.find((d) => d.driver_number === driverNumber)
|
||||
return {
|
||||
label: comp?.name_acronym || session?.name_acronym || `#${driverNumber}`,
|
||||
color: teamColor(comp?.team_colour || session?.team_colour),
|
||||
laps: comp?.laps ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
export function comparisonToDeltaSeries(
|
||||
comparison: LapsComparisonResponse,
|
||||
driverNumbers: [number, number],
|
||||
drivers: Driver[],
|
||||
): DeltaSeries[] {
|
||||
return driverNumbers.map((dn) => {
|
||||
const meta = driverMeta(dn, comparison, drivers)
|
||||
return {
|
||||
label: meta.label,
|
||||
color: meta.color,
|
||||
lapTimes: lapsToLapTimes(meta.laps),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function formatPitLapsCaption(
|
||||
pitLaps: Record<string, number[]>,
|
||||
driverNumbers: [number, number],
|
||||
comparison: LapsComparisonResponse | undefined,
|
||||
drivers: Driver[],
|
||||
): string | null {
|
||||
const parts: string[] = []
|
||||
|
||||
for (const dn of driverNumbers) {
|
||||
const laps = pitLaps[String(dn)]
|
||||
if (!laps?.length) continue
|
||||
const meta = driverMeta(dn, comparison, drivers)
|
||||
parts.push(`${meta.label}: L${laps.join(', L')}`)
|
||||
}
|
||||
|
||||
return parts.length > 0 ? `Pit stops — ${parts.join(' · ')}` : null
|
||||
}
|
||||
|
||||
export function compareDriverOptions(
|
||||
drivers: Driver[],
|
||||
results: EnrichedResult[],
|
||||
): Driver[] {
|
||||
if (drivers.length > 0) {
|
||||
return sortDriversByResults(drivers, results)
|
||||
}
|
||||
return results.map((r) => ({
|
||||
driver_number: r.driver_number,
|
||||
name_acronym: r.name_acronym,
|
||||
full_name: r.full_name,
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
team_name: r.team_name,
|
||||
team_colour: r.team_colour,
|
||||
headshot_url: '',
|
||||
broadcast_name: r.full_name,
|
||||
session_key: r.session_key,
|
||||
meeting_key: r.meeting_key,
|
||||
}))
|
||||
}
|
||||
@@ -51,6 +51,7 @@ export function countWeekendStats(weekends: (Weekend | undefined)[]) {
|
||||
let full = 0
|
||||
let partial = 0
|
||||
let missing = 0
|
||||
let cancelled = 0
|
||||
|
||||
for (const weekend of weekends) {
|
||||
if (!weekend || weekend.sessions.length === 0) {
|
||||
@@ -64,15 +65,19 @@ export function countWeekendStats(weekends: (Weekend | undefined)[]) {
|
||||
case 'partial':
|
||||
partial++
|
||||
break
|
||||
case 'cancelled':
|
||||
cancelled++
|
||||
break
|
||||
default:
|
||||
missing++
|
||||
}
|
||||
}
|
||||
|
||||
return { full, partial, missing, total: weekends.length }
|
||||
return { full, partial, cancelled, missing, total: weekends.length }
|
||||
}
|
||||
|
||||
export function sessionIconClass(session: WeekendSession): string {
|
||||
if (session.source === 'cancelled') return 'si-cancelled'
|
||||
if (session.source === 'none') return 'si-missing'
|
||||
if (isSessionComplete(session.datasets)) return 'si-full'
|
||||
return 'si-partial'
|
||||
|
||||
127
frontend/src/lib/delta.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
// Cumulative lap-time delta math for driver comparison charts.
|
||||
// Pure functions only — no React — so everything is unit-testable.
|
||||
|
||||
export interface DeltaSeries {
|
||||
label: string
|
||||
color: string
|
||||
/** Lap duration in seconds; null = no time (pit/out lap). */
|
||||
lapTimes: (number | null)[]
|
||||
}
|
||||
|
||||
export interface DriverDeltaResult {
|
||||
label: string
|
||||
color: string
|
||||
/** Cumulative delta vs reference (seconds); null when that lap has no time. */
|
||||
deltas: (number | null)[]
|
||||
}
|
||||
|
||||
/** Format a delta value for axis labels and tooltips (e.g. "+2.5s", "-1.2s"). */
|
||||
export function formatDeltaSeconds(delta: number): string {
|
||||
const sign = delta >= 0 ? '+' : ''
|
||||
return `${sign}${delta.toFixed(1)}s`
|
||||
}
|
||||
|
||||
/**
|
||||
* Cumulative lap time aligned to reference-valid laps only.
|
||||
* Laps where the reference is null are skipped for every series so later deltas
|
||||
* do not compare against a frozen baseline while challengers keep accumulating.
|
||||
*/
|
||||
function buildAlignedCumulative(
|
||||
lapTimes: ReadonlyArray<number | null>,
|
||||
referenceLapTimes: ReadonlyArray<number | null>,
|
||||
): number[] {
|
||||
const cumulative: number[] = []
|
||||
let running = 0
|
||||
const length = Math.max(lapTimes.length, referenceLapTimes.length)
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (referenceLapTimes[i] == null) {
|
||||
cumulative.push(running)
|
||||
continue
|
||||
}
|
||||
const lap = lapTimes[i]
|
||||
if (lap != null) {
|
||||
running += lap
|
||||
}
|
||||
cumulative.push(running)
|
||||
}
|
||||
|
||||
return cumulative
|
||||
}
|
||||
|
||||
function resolveReference(
|
||||
series: ReadonlyArray<DeltaSeries>,
|
||||
referenceLabel?: string,
|
||||
): DeltaSeries | null {
|
||||
if (series.length === 0) return null
|
||||
if (referenceLabel) {
|
||||
return series.find((s) => s.label === referenceLabel) ?? series[0]
|
||||
}
|
||||
return series[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute per-lap cumulative time delta for each non-reference driver.
|
||||
* Positive = behind reference; negative = ahead.
|
||||
* Deltas are only emitted where the reference lap is valid; reference-null laps
|
||||
* gap every series. Challenger-null laps gap only that driver's line.
|
||||
*/
|
||||
export function computeCumulativeDeltas(
|
||||
series: ReadonlyArray<DeltaSeries>,
|
||||
referenceLabel?: string,
|
||||
): DriverDeltaResult[] {
|
||||
const reference = resolveReference(series, referenceLabel)
|
||||
if (!reference) return []
|
||||
|
||||
const refLapTimes = reference.lapTimes
|
||||
const refCumulative = buildAlignedCumulative(refLapTimes, refLapTimes)
|
||||
|
||||
return series
|
||||
.filter((s) => s.label !== reference.label)
|
||||
.map((driver) => {
|
||||
const driverCumulative = buildAlignedCumulative(driver.lapTimes, refLapTimes)
|
||||
const lapCount = Math.max(driver.lapTimes.length, refCumulative.length)
|
||||
const deltas: (number | null)[] = []
|
||||
|
||||
for (let i = 0; i < lapCount; i++) {
|
||||
if (refLapTimes[i] == null || driver.lapTimes[i] == null) {
|
||||
deltas.push(null)
|
||||
continue
|
||||
}
|
||||
deltas.push(driverCumulative[i] - refCumulative[i])
|
||||
}
|
||||
|
||||
return {
|
||||
label: driver.label,
|
||||
color: driver.color,
|
||||
deltas,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Split delta samples into contiguous SVG polyline point strings (gaps at null laps). */
|
||||
export function deltaPolylineSegments(
|
||||
deltas: ReadonlyArray<number | null>,
|
||||
toPoint: (lapIndex: number, delta: number) => string,
|
||||
): string[] {
|
||||
const segments: string[] = []
|
||||
let current: string[] = []
|
||||
|
||||
for (let i = 0; i < deltas.length; i++) {
|
||||
const value = deltas[i]
|
||||
if (value === null) {
|
||||
if (current.length > 0) {
|
||||
segments.push(current.join(' '))
|
||||
current = []
|
||||
}
|
||||
continue
|
||||
}
|
||||
current.push(toPoint(i, value))
|
||||
}
|
||||
|
||||
if (current.length > 0) {
|
||||
segments.push(current.join(' '))
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
293
frontend/src/lib/digest.ts
Normal file
@@ -0,0 +1,293 @@
|
||||
import { meetingEndTime, meetingStartTime, mostRecentPastMeeting, nextUpcomingMeeting } from './schedule'
|
||||
import type { ChampHubDriver, ChampHubTeam, Meeting, NewsItem } from '../types'
|
||||
|
||||
export interface GPWindow {
|
||||
meeting_key: number
|
||||
meeting_name: string
|
||||
/** Inclusive lower bound: end of previous GP, or open for season opener. */
|
||||
start: Date | null
|
||||
/** Exclusive upper bound: start of next GP, or open after the final round. */
|
||||
end: Date | null
|
||||
}
|
||||
|
||||
export interface DigestTag {
|
||||
kind: 'driver' | 'team'
|
||||
key: string
|
||||
label: string
|
||||
colour: string
|
||||
}
|
||||
|
||||
export type TaggedNewsItem = NewsItem & { tags: DigestTag[] }
|
||||
|
||||
export const RECENT_BUCKET_KEY = '__recent__'
|
||||
|
||||
interface MatchCandidate {
|
||||
start: number
|
||||
end: number
|
||||
tag: DigestTag
|
||||
}
|
||||
|
||||
interface TagPattern {
|
||||
pattern: string
|
||||
tag: DigestTag
|
||||
}
|
||||
|
||||
function sortMeetings(meetings: Meeting[]): Meeting[] {
|
||||
return [...meetings].sort((a, b) => {
|
||||
const left = meetingStartTime(a)?.getTime() ?? 0
|
||||
const right = meetingStartTime(b)?.getTime() ?? 0
|
||||
if (left !== right) return left - right
|
||||
return a.meeting_name.localeCompare(b.meeting_name)
|
||||
})
|
||||
}
|
||||
|
||||
/** Derive inter-race windows [prev GP end → next GP start] for each round. */
|
||||
export function gpWindows(meetings: Meeting[], _now: Date): GPWindow[] {
|
||||
const sorted = sortMeetings(meetings)
|
||||
return sorted.map((meeting, index) => ({
|
||||
meeting_key: meeting.meeting_key,
|
||||
meeting_name: meeting.meeting_name,
|
||||
start: index > 0 ? meetingEndTime(sorted[index - 1]) : null,
|
||||
end: index < sorted.length - 1 ? meetingStartTime(sorted[index + 1]) : null,
|
||||
}))
|
||||
}
|
||||
|
||||
function itemPublishedAt(item: NewsItem): Date | null {
|
||||
if (!item.published_at) return null
|
||||
const parsed = Date.parse(item.published_at)
|
||||
return Number.isNaN(parsed) ? null : new Date(parsed)
|
||||
}
|
||||
|
||||
function itemInWindow(published: Date, window: GPWindow): boolean {
|
||||
if (window.start && published < window.start) return false
|
||||
if (window.end && published >= window.end) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export function windowForDate(windows: GPWindow[], published: Date): GPWindow | null {
|
||||
const matches = windows.filter((window) => itemInWindow(published, window))
|
||||
if (matches.length === 0) return null
|
||||
return matches.reduce((best, window) => {
|
||||
const bestStart = best.start?.getTime() ?? Number.NEGATIVE_INFINITY
|
||||
const windowStart = window.start?.getTime() ?? Number.NEGATIVE_INFINITY
|
||||
return windowStart >= bestStart ? window : best
|
||||
})
|
||||
}
|
||||
|
||||
export interface GroupedDigest {
|
||||
windows: Array<{ window: GPWindow; items: NewsItem[] }>
|
||||
recent: NewsItem[]
|
||||
}
|
||||
|
||||
/** Bucket news items into GP windows; undated items land in `recent`. */
|
||||
export function groupByWindow(items: NewsItem[], windows: GPWindow[]): GroupedDigest {
|
||||
const buckets = new Map<number, NewsItem[]>()
|
||||
const recent: NewsItem[] = []
|
||||
|
||||
for (const item of items) {
|
||||
const published = itemPublishedAt(item)
|
||||
if (!published) {
|
||||
recent.push(item)
|
||||
continue
|
||||
}
|
||||
const match = windowForDate(windows, published)
|
||||
if (!match) {
|
||||
recent.push(item)
|
||||
continue
|
||||
}
|
||||
const list = buckets.get(match.meeting_key) ?? []
|
||||
list.push(item)
|
||||
buckets.set(match.meeting_key, list)
|
||||
}
|
||||
|
||||
const grouped = windows
|
||||
.map((window) => ({
|
||||
window,
|
||||
items: buckets.get(window.meeting_key) ?? [],
|
||||
}))
|
||||
.filter((entry) => entry.items.length > 0)
|
||||
|
||||
return { windows: grouped, recent }
|
||||
}
|
||||
|
||||
function driverLastName(fullName: string): string | null {
|
||||
const parts = fullName.trim().split(/\s+/).filter(Boolean)
|
||||
if (parts.length < 2) return null
|
||||
return parts[parts.length - 1] ?? null
|
||||
}
|
||||
|
||||
function buildTagPatterns(drivers: ChampHubDriver[], teams: ChampHubTeam[]): TagPattern[] {
|
||||
const patterns: TagPattern[] = []
|
||||
|
||||
for (const team of teams) {
|
||||
if (!team.team_name.trim()) continue
|
||||
patterns.push({
|
||||
pattern: team.team_name.toLowerCase(),
|
||||
tag: {
|
||||
kind: 'team',
|
||||
key: `team:${team.team_name}`,
|
||||
label: team.team_name,
|
||||
colour: team.team_colour,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
for (const driver of drivers) {
|
||||
const colour = driver.team_colour
|
||||
const base = {
|
||||
kind: 'driver' as const,
|
||||
colour,
|
||||
}
|
||||
if (driver.full_name.trim()) {
|
||||
patterns.push({
|
||||
pattern: driver.full_name.toLowerCase(),
|
||||
tag: {
|
||||
...base,
|
||||
key: `driver:${driver.name_acronym}`,
|
||||
label: driver.name_acronym,
|
||||
},
|
||||
})
|
||||
const lastName = driverLastName(driver.full_name)
|
||||
if (lastName) {
|
||||
patterns.push({
|
||||
pattern: lastName.toLowerCase(),
|
||||
tag: {
|
||||
...base,
|
||||
key: `driver:${driver.name_acronym}`,
|
||||
label: driver.name_acronym,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
if (driver.name_acronym.trim()) {
|
||||
patterns.push({
|
||||
pattern: driver.name_acronym.toLowerCase(),
|
||||
tag: {
|
||||
...base,
|
||||
key: `driver:${driver.name_acronym}`,
|
||||
label: driver.name_acronym,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
patterns.sort((a, b) => b.pattern.length - a.pattern.length)
|
||||
return patterns
|
||||
}
|
||||
|
||||
function overlaps(a: MatchCandidate, b: MatchCandidate): boolean {
|
||||
return a.start < b.end && b.start < a.end
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag items via case-insensitive substring match on title + summary.
|
||||
* Longest pattern wins on overlapping spans (v1 string match — no NLP).
|
||||
*
|
||||
* Known limitations: common-word last names, team names inside other words,
|
||||
* and driver TLAs that appear in unrelated acronyms can false-positive.
|
||||
*/
|
||||
export function tagItems(
|
||||
items: NewsItem[],
|
||||
drivers: ChampHubDriver[],
|
||||
teams: ChampHubTeam[],
|
||||
): TaggedNewsItem[] {
|
||||
const patterns = buildTagPatterns(drivers, teams)
|
||||
|
||||
return items.map((item) => {
|
||||
const haystack = `${item.title} ${item.summary ?? ''}`.toLowerCase()
|
||||
const accepted: MatchCandidate[] = []
|
||||
|
||||
for (const { pattern, tag } of patterns) {
|
||||
if (!pattern) continue
|
||||
let from = 0
|
||||
while (from <= haystack.length - pattern.length) {
|
||||
const index = haystack.indexOf(pattern, from)
|
||||
if (index === -1) break
|
||||
const candidate: MatchCandidate = {
|
||||
start: index,
|
||||
end: index + pattern.length,
|
||||
tag,
|
||||
}
|
||||
if (!accepted.some((match) => overlaps(match, candidate))) {
|
||||
accepted.push(candidate)
|
||||
}
|
||||
from = index + 1
|
||||
}
|
||||
}
|
||||
|
||||
const tagsByKey = new Map<string, DigestTag>()
|
||||
for (const match of accepted) {
|
||||
tagsByKey.set(match.tag.key, match.tag)
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
tags: [...tagsByKey.values()].sort((a, b) => a.label.localeCompare(b.label)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function activeDigestWindow(
|
||||
windows: GPWindow[],
|
||||
meetings: Meeting[],
|
||||
now: Date,
|
||||
): GPWindow | null {
|
||||
const next = nextUpcomingMeeting(meetings, now)
|
||||
if (next) {
|
||||
return windows.find((window) => window.meeting_key === next.meeting_key) ?? null
|
||||
}
|
||||
const recent = mostRecentPastMeeting(meetings, now)
|
||||
if (recent) {
|
||||
return windows.find((window) => window.meeting_key === recent.meeting_key) ?? null
|
||||
}
|
||||
return windows[0] ?? null
|
||||
}
|
||||
|
||||
export function sinceLastLabel(meetings: Meeting[], now: Date): string {
|
||||
const last = mostRecentPastMeeting(meetings, now)
|
||||
if (last) return last.meeting_name
|
||||
const next = nextUpcomingMeeting(meetings, now)
|
||||
if (next) return `Before ${next.meeting_name}`
|
||||
return 'Pre-season'
|
||||
}
|
||||
|
||||
export function itemsForWindow(items: TaggedNewsItem[], window: GPWindow | null): TaggedNewsItem[] {
|
||||
if (!window) return []
|
||||
return items.filter((item) => {
|
||||
const published = itemPublishedAt(item)
|
||||
return published != null && itemInWindow(published, window)
|
||||
})
|
||||
}
|
||||
|
||||
export function topTags(items: TaggedNewsItem[], limit = 5): DigestTag[] {
|
||||
const counts = new Map<string, { tag: DigestTag; count: number }>()
|
||||
for (const item of items) {
|
||||
for (const tag of item.tags) {
|
||||
const current = counts.get(tag.key)
|
||||
if (current) current.count += 1
|
||||
else counts.set(tag.key, { tag, count: 1 })
|
||||
}
|
||||
}
|
||||
return [...counts.values()]
|
||||
.sort((a, b) => b.count - a.count || a.tag.label.localeCompare(b.tag.label))
|
||||
.slice(0, limit)
|
||||
.map((entry) => entry.tag)
|
||||
}
|
||||
|
||||
export function filterByTag(items: TaggedNewsItem[], tagKey: string | null): TaggedNewsItem[] {
|
||||
if (!tagKey) return items
|
||||
return items.filter((item) => item.tags.some((tag) => tag.key === tagKey))
|
||||
}
|
||||
|
||||
export function tagColour(colour: string): string {
|
||||
if (!colour) return 'var(--text-3)'
|
||||
return colour.startsWith('#') ? colour : `#${colour}`
|
||||
}
|
||||
|
||||
export function sortWindowBucketsNewestFirst<T extends { window: GPWindow }>(buckets: T[]): T[] {
|
||||
return [...buckets].sort((a, b) => {
|
||||
const left = a.window.start?.getTime() ?? 0
|
||||
const right = b.window.start?.getTime() ?? 0
|
||||
return right - left
|
||||
})
|
||||
}
|
||||
69
frontend/src/lib/driverProfile.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import type { DriverSummaryRound } from '../types'
|
||||
|
||||
/** One round mapped for the grid-vs-finish chart and results table. */
|
||||
export interface RoundDelta {
|
||||
round: number // 1-based round index within the completed season
|
||||
label: string // short GP label, e.g. "Bahrain"
|
||||
grid: number | null
|
||||
finish: number | null
|
||||
/** grid − finish: positive = places gained on Sunday, null when unknowable. */
|
||||
delta: number | null
|
||||
points: number
|
||||
status: 'classified' | 'dnf' | 'dns' | 'dsq' | 'absent'
|
||||
}
|
||||
|
||||
/** Strip the "Grand Prix" boilerplate so round labels fit chart axes. */
|
||||
export function shortGpLabel(meetingName: string): string {
|
||||
const short = meetingName
|
||||
.replace(/\s*grand prix\s*/i, ' ')
|
||||
.replace(/\s+gp\s*$/i, ' ')
|
||||
.trim()
|
||||
return short || meetingName
|
||||
}
|
||||
|
||||
function roundStatus(r: DriverSummaryRound): RoundDelta['status'] {
|
||||
if (r.dns) return 'dns'
|
||||
if (r.dsq) return 'dsq'
|
||||
if (r.dnf) return 'dnf'
|
||||
if (r.race_position <= 0 && r.grid_position <= 0) return 'absent'
|
||||
return 'classified'
|
||||
}
|
||||
|
||||
/**
|
||||
* Map summary rounds to grid-vs-finish deltas. Positions of 0 mean "no data"
|
||||
* (driver absent, pit-lane start, …) and become null; a delta is only computed
|
||||
* when both ends are known and the driver actually started the race.
|
||||
*/
|
||||
export function gridFinishDeltas(rounds: DriverSummaryRound[]): RoundDelta[] {
|
||||
return rounds.map((r, i) => {
|
||||
const status = roundStatus(r)
|
||||
const grid = r.grid_position > 0 ? r.grid_position : null
|
||||
const finish = r.race_position > 0 ? r.race_position : null
|
||||
const delta =
|
||||
grid != null && finish != null && status !== 'dns' && status !== 'absent'
|
||||
? grid - finish
|
||||
: null
|
||||
return {
|
||||
round: i + 1,
|
||||
label: shortGpLabel(r.meeting_name),
|
||||
grid,
|
||||
finish,
|
||||
delta,
|
||||
points: r.points,
|
||||
status,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 'P4' for known positions, '—' when unknown. */
|
||||
export function formatPosition(pos: number | null): string {
|
||||
return pos != null && pos > 0 ? `P${pos}` : '—'
|
||||
}
|
||||
|
||||
/** '+3' (gained), '−2' (lost), '=' (held), '—' (unknown). */
|
||||
export function formatDelta(delta: number | null): string {
|
||||
if (delta == null) return '—'
|
||||
if (delta > 0) return `+${delta}`
|
||||
if (delta < 0) return `−${Math.abs(delta)}`
|
||||
return '='
|
||||
}
|
||||
318
frontend/src/lib/events.ts
Normal file
@@ -0,0 +1,318 @@
|
||||
// "What just happened" event synthesis for the live page.
|
||||
// Pure functions only — no React, no side effects — so everything is unit-testable.
|
||||
// Mirrors the gapHistory/battles precedent: successive LiveStreamData snapshots
|
||||
// in, typed events out; the page owns the buffer, this module owns the diffing.
|
||||
|
||||
import type {
|
||||
LiveDriverData,
|
||||
LiveRCMessage,
|
||||
LiveSessionMeta,
|
||||
LiveStreamData,
|
||||
} from '../types'
|
||||
|
||||
export const MAX_EVENTS = 30
|
||||
|
||||
export type LiveEventKind =
|
||||
| 'overtake'
|
||||
| 'position-gain'
|
||||
| 'position-loss'
|
||||
| 'pit-in'
|
||||
| 'pit-out'
|
||||
| 'personal-best'
|
||||
| 'fastest-lap'
|
||||
| 'retirement'
|
||||
| 'track-status'
|
||||
| 'race-control'
|
||||
|
||||
export interface LiveEvent {
|
||||
id: string
|
||||
kind: LiveEventKind
|
||||
lap: number
|
||||
timestamp: string
|
||||
headline: string
|
||||
detail?: string
|
||||
racingNumbers: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity of the running session, used to reset the event buffer when a new
|
||||
* session starts. LiveSessionMeta carries no numeric session key, so the
|
||||
* meeting + session name/type triple stands in for one.
|
||||
*/
|
||||
export function sessionSignature(session: LiveSessionMeta | null | undefined): string {
|
||||
if (!session) return ''
|
||||
return [session.MeetingName, session.SessionName, session.SessionType].join('|')
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepend freshly diffed events onto the newest-first buffer, dropping any
|
||||
* whose id is already present (re-renders and replayed diffs must not
|
||||
* duplicate) and evicting the oldest events beyond `cap`.
|
||||
*/
|
||||
export function appendEvents(
|
||||
buffer: ReadonlyArray<LiveEvent>,
|
||||
incoming: ReadonlyArray<LiveEvent>,
|
||||
cap = MAX_EVENTS,
|
||||
): LiveEvent[] {
|
||||
const seen = new Set(buffer.map((event) => event.id))
|
||||
const fresh = incoming.filter((event) => {
|
||||
if (seen.has(event.id)) return false
|
||||
seen.add(event.id)
|
||||
return true
|
||||
})
|
||||
if (fresh.length === 0) return [...buffer]
|
||||
// Within one diff the array is oldest-first; reverse so the last-produced
|
||||
// event ends up at the top of the newest-first rail.
|
||||
return [...fresh.reverse(), ...buffer].slice(0, cap)
|
||||
}
|
||||
|
||||
const TRACK_STATUS_HEADLINES: Record<string, string> = {
|
||||
'1': 'Green flag — track clear',
|
||||
'2': 'Yellow flag',
|
||||
'4': 'Safety Car deployed',
|
||||
'5': 'Red flag — session stopped',
|
||||
'6': 'Virtual Safety Car deployed',
|
||||
'7': 'Virtual Safety Car ending',
|
||||
}
|
||||
|
||||
const RC_CATEGORIES = new Set(['flag', 'safetycar', 'drs'])
|
||||
|
||||
/**
|
||||
* Diff two successive live snapshots into a chronological list of synthesized
|
||||
* events. Callers are expected to feed genuinely consecutive snapshots of the
|
||||
* same session; diffing across a session boundary is the caller's job to
|
||||
* prevent (see sessionSignature).
|
||||
*/
|
||||
export function diffSnapshots(prev: LiveStreamData, next: LiveStreamData): LiveEvent[] {
|
||||
if (!prev || !next || prev === next) return []
|
||||
|
||||
const events: LiveEvent[] = []
|
||||
const lap = next.CurrentLap || 0
|
||||
const timestamp = next.Clock || ''
|
||||
const code = (racingNumber: string): string =>
|
||||
next.DriverInfo?.[racingNumber]?.Tla ||
|
||||
prev.DriverInfo?.[racingNumber]?.Tla ||
|
||||
`#${racingNumber}`
|
||||
|
||||
diffTrackStatus(prev, next, lap, timestamp, events)
|
||||
diffRaceControl(prev, next, events)
|
||||
|
||||
const prevDrivers = prev.Drivers ?? {}
|
||||
const nextDrivers = next.Drivers ?? {}
|
||||
const numbers = Object.keys(nextDrivers).filter((number) => prevDrivers[number])
|
||||
|
||||
// Racing numbers whose position loss is already explained by an overtake
|
||||
// event, so we don't also report a generic "drops to Pn".
|
||||
const overtakenNumbers = new Set<string>()
|
||||
|
||||
for (const number of numbers) {
|
||||
const before = prevDrivers[number]
|
||||
const after = nextDrivers[number]
|
||||
|
||||
if (!before.Retired && after.Retired) {
|
||||
events.push({
|
||||
id: `ret:${number}`,
|
||||
kind: 'retirement',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} retires`,
|
||||
detail: before.Position > 0 ? `Was running P${before.Position}` : undefined,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
|
||||
if (!before.InPit && after.InPit && !after.Retired) {
|
||||
const fromPosition = before.Position > 0 ? ` from P${before.Position}` : ''
|
||||
events.push({
|
||||
id: `pit-in:${number}:l${lap}`,
|
||||
kind: 'pit-in',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} pits${fromPosition}`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
|
||||
if (before.InPit && !after.InPit && !after.Retired) {
|
||||
const compound = next.Tyres?.[number]?.Compound || ''
|
||||
const stops = Math.max(0, (next.Stints?.[number]?.length ?? 0) - 1)
|
||||
const parts = [compound, stops > 0 ? `${ordinal(stops)} stop` : ''].filter(Boolean)
|
||||
const rejoined = after.Position > 0 ? ` P${after.Position}` : ''
|
||||
events.push({
|
||||
id: `pit-out:${number}:l${lap}`,
|
||||
kind: 'pit-out',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} rejoins${rejoined}${parts.length > 0 ? ` (${parts.join(', ')})` : ''}`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
|
||||
diffBestLap(number, before, after, code, lap, timestamp, events)
|
||||
}
|
||||
|
||||
// Position gains, with overtake attribution via position swaps.
|
||||
for (const number of numbers) {
|
||||
const before = prevDrivers[number]
|
||||
const after = nextDrivers[number]
|
||||
if (before.Position <= 0 || after.Position <= 0) continue
|
||||
if (after.Position >= before.Position) continue
|
||||
if (after.InPit || after.Retired) continue
|
||||
|
||||
const overtaken = numbers.find((other) => {
|
||||
if (other === number) return false
|
||||
const otherBefore = prevDrivers[other]
|
||||
const otherAfter = nextDrivers[other]
|
||||
return (
|
||||
otherBefore.Position === after.Position &&
|
||||
otherAfter.Position > otherBefore.Position &&
|
||||
!otherAfter.InPit &&
|
||||
!otherAfter.Retired
|
||||
)
|
||||
})
|
||||
|
||||
if (overtaken) {
|
||||
overtakenNumbers.add(overtaken)
|
||||
events.push({
|
||||
id: `overtake:${number}:${overtaken}:p${after.Position}:l${lap}`,
|
||||
kind: 'overtake',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} overtakes ${code(overtaken)} for P${after.Position}`,
|
||||
detail: before.Position - after.Position > 1 ? `Up from P${before.Position}` : undefined,
|
||||
racingNumbers: [number, overtaken],
|
||||
})
|
||||
} else {
|
||||
events.push({
|
||||
id: `pos:${number}:${before.Position}-${after.Position}:l${lap}`,
|
||||
kind: 'position-gain',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} moves up to P${after.Position} (from P${before.Position})`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Position losses not already explained by an overtake or a pit visit.
|
||||
for (const number of numbers) {
|
||||
const before = prevDrivers[number]
|
||||
const after = nextDrivers[number]
|
||||
if (before.Position <= 0 || after.Position <= 0) continue
|
||||
if (after.Position <= before.Position) continue
|
||||
if (overtakenNumbers.has(number)) continue
|
||||
if (after.InPit || after.PitOut || after.Retired || before.InPit) continue
|
||||
|
||||
events.push({
|
||||
id: `pos:${number}:${before.Position}-${after.Position}:l${lap}`,
|
||||
kind: 'position-loss',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} drops to P${after.Position} (from P${before.Position})`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
|
||||
return events
|
||||
}
|
||||
|
||||
function diffTrackStatus(
|
||||
prev: LiveStreamData,
|
||||
next: LiveStreamData,
|
||||
lap: number,
|
||||
timestamp: string,
|
||||
events: LiveEvent[],
|
||||
): void {
|
||||
if (!prev.TrackStatus || !next.TrackStatus) return
|
||||
if (prev.TrackStatus === next.TrackStatus) return
|
||||
events.push({
|
||||
id: `track:${next.TrackStatus}:l${lap}`,
|
||||
kind: 'track-status',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: TRACK_STATUS_HEADLINES[next.TrackStatus] ?? `Track status ${next.TrackStatus}`,
|
||||
racingNumbers: [],
|
||||
})
|
||||
}
|
||||
|
||||
function diffRaceControl(prev: LiveStreamData, next: LiveStreamData, events: LiveEvent[]): void {
|
||||
const prevMessages = prev.RCMessages ?? []
|
||||
const seen = new Set(prevMessages.map(rcMessageKey))
|
||||
for (const message of next.RCMessages ?? []) {
|
||||
if (!message.Message || seen.has(rcMessageKey(message))) continue
|
||||
if (!RC_CATEGORIES.has((message.Category || '').toLowerCase())) continue
|
||||
events.push({
|
||||
id: `rc:${rcMessageKey(message)}`,
|
||||
kind: 'race-control',
|
||||
lap: message.Lap || 0,
|
||||
timestamp: message.Time || '',
|
||||
headline: humanizeRaceControl(message.Message),
|
||||
racingNumbers: carNumbersIn(message.Message),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function diffBestLap(
|
||||
number: string,
|
||||
before: LiveDriverData,
|
||||
after: LiveDriverData,
|
||||
code: (racingNumber: string) => string,
|
||||
lap: number,
|
||||
timestamp: string,
|
||||
events: LiveEvent[],
|
||||
): void {
|
||||
if (!after.LastLapTime) return
|
||||
const isNewLap = after.LastLapTime !== before.LastLapTime
|
||||
|
||||
if (after.LastLapOB && (isNewLap || !before.LastLapOB)) {
|
||||
events.push({
|
||||
id: `ob:${number}:${after.LastLapTime}`,
|
||||
kind: 'fastest-lap',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} sets the fastest lap — ${after.LastLapTime}`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (after.LastLapPB && !after.LastLapOB && (isNewLap || !before.LastLapPB)) {
|
||||
events.push({
|
||||
id: `pb:${number}:${after.LastLapTime}`,
|
||||
kind: 'personal-best',
|
||||
lap,
|
||||
timestamp,
|
||||
headline: `${code(number)} sets a personal best — ${after.LastLapTime}`,
|
||||
racingNumbers: [number],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function rcMessageKey(message: LiveRCMessage): string {
|
||||
return `${message.Time}:${message.Message}`
|
||||
}
|
||||
|
||||
/** "SAFETY CAR DEPLOYED" -> "Safety car deployed", keeping known acronyms upper-cased. */
|
||||
export function humanizeRaceControl(message: string): string {
|
||||
const lower = message.trim().toLowerCase()
|
||||
if (!lower) return ''
|
||||
const sentence = lower.charAt(0).toUpperCase() + lower.slice(1)
|
||||
return sentence.replace(/\b(drs|vsc|sc|fia)\b/gi, (acronym) => acronym.toUpperCase())
|
||||
}
|
||||
|
||||
function carNumbersIn(message: string): string[] {
|
||||
const numbers: string[] = []
|
||||
for (const match of message.matchAll(/CAR (\d+)/gi)) {
|
||||
if (!numbers.includes(match[1])) numbers.push(match[1])
|
||||
}
|
||||
return numbers
|
||||
}
|
||||
|
||||
function ordinal(n: number): string {
|
||||
const rem10 = n % 10
|
||||
const rem100 = n % 100
|
||||
if (rem10 === 1 && rem100 !== 11) return `${n}st`
|
||||
if (rem10 === 2 && rem100 !== 12) return `${n}nd`
|
||||
if (rem10 === 3 && rem100 !== 13) return `${n}rd`
|
||||
return `${n}th`
|
||||
}
|
||||
108
frontend/src/lib/gapHistory.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
// Client-side gap/interval history tracking for the live timing tower.
|
||||
// Pure functions only — no React, no side effects — so everything is unit-testable.
|
||||
|
||||
export const MAX_GAP_SAMPLES = 40
|
||||
|
||||
/** Per-driver ring buffer of interval samples (seconds), keyed by racing number. */
|
||||
export type GapHistoryMap = Record<string, number[]>
|
||||
|
||||
export type GapTrend = 'closing' | 'opening' | 'steady'
|
||||
|
||||
/**
|
||||
* Parse an F1 live-timing interval/gap string into seconds.
|
||||
* Handles "+1.234", "1.234", "+1:05.678" (minute form) and rejects
|
||||
* lapped/leader markers: "", "LAP 12", "1L", "+1 LAP", "2 LAPS", etc.
|
||||
*/
|
||||
export function parseIntervalSeconds(raw: string | null | undefined): number | null {
|
||||
if (!raw) return null
|
||||
const text = raw.trim()
|
||||
if (!text) return null
|
||||
// Lapped / leader markers are never numeric gaps.
|
||||
if (/lap/i.test(text) || /^\+?\d+\s*L$/i.test(text)) return null
|
||||
|
||||
const match = text.match(/^([+-])?(?:(\d+):)?(\d+(?:\.\d+)?)$/)
|
||||
if (!match) return null
|
||||
|
||||
const sign = match[1] === '-' ? -1 : 1
|
||||
const minutes = match[2] ? Number(match[2]) : 0
|
||||
const seconds = Number(match[3])
|
||||
if (!Number.isFinite(minutes) || !Number.isFinite(seconds)) return null
|
||||
|
||||
return sign * (minutes * 60 + seconds)
|
||||
}
|
||||
|
||||
export interface GapSampleInput {
|
||||
racingNumber: string
|
||||
interval: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Record one snapshot's worth of interval samples.
|
||||
* Returns a new map (input is not mutated). Drivers missing from `rows`
|
||||
* are pruned; unparsable intervals keep the existing buffer untouched.
|
||||
*/
|
||||
export function recordGapSamples(
|
||||
history: GapHistoryMap,
|
||||
rows: ReadonlyArray<GapSampleInput>,
|
||||
maxSamples = MAX_GAP_SAMPLES,
|
||||
): GapHistoryMap {
|
||||
const next: GapHistoryMap = {}
|
||||
for (const row of rows) {
|
||||
if (!row.racingNumber) continue
|
||||
const existing = history[row.racingNumber] ?? []
|
||||
const value = parseIntervalSeconds(row.interval)
|
||||
if (value === null) {
|
||||
if (existing.length > 0) next[row.racingNumber] = existing
|
||||
continue
|
||||
}
|
||||
const samples = [...existing, value]
|
||||
next[row.racingNumber] = samples.length > maxSamples ? samples.slice(samples.length - maxSamples) : samples
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the recent trend of a gap buffer: is the driver closing on the
|
||||
* car ahead, dropping back, or holding steady? Compares the mean of the
|
||||
* older half vs the newer half of the most recent samples.
|
||||
*/
|
||||
export function gapTrend(samples: ReadonlyArray<number>, window = 10, threshold = 0.1): GapTrend | null {
|
||||
if (!samples || samples.length < 3) return null
|
||||
const recent = samples.slice(-window)
|
||||
const mid = Math.floor(recent.length / 2)
|
||||
const older = recent.slice(0, mid)
|
||||
const newer = recent.slice(mid)
|
||||
if (older.length === 0 || newer.length === 0) return null
|
||||
|
||||
const mean = (xs: ReadonlyArray<number>) => xs.reduce((a, b) => a + b, 0) / xs.length
|
||||
const delta = mean(newer) - mean(older)
|
||||
if (delta <= -threshold) return 'closing'
|
||||
if (delta >= threshold) return 'opening'
|
||||
return 'steady'
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute SVG polyline points for a sparkline of the samples, fitted to
|
||||
* width x height with a small vertical inset. Flat data draws a mid line.
|
||||
*/
|
||||
export function sparklinePoints(
|
||||
samples: ReadonlyArray<number>,
|
||||
width: number,
|
||||
height: number,
|
||||
inset = 1.5,
|
||||
): string {
|
||||
if (!samples || samples.length < 2) return ''
|
||||
const min = Math.min(...samples)
|
||||
const max = Math.max(...samples)
|
||||
const span = max - min
|
||||
const usable = height - inset * 2
|
||||
const step = width / (samples.length - 1)
|
||||
|
||||
return samples
|
||||
.map((value, index) => {
|
||||
const x = index * step
|
||||
const y = span === 0 ? height / 2 : inset + (1 - (value - min) / span) * usable
|
||||
return `${x.toFixed(1)},${y.toFixed(1)}`
|
||||
})
|
||||
.join(' ')
|
||||
}
|
||||
@@ -47,7 +47,9 @@ export function countryDecal(meeting: Meeting | undefined | null): string {
|
||||
return name.slice(0, 3).toUpperCase() || '—'
|
||||
}
|
||||
|
||||
export function countryFlag(meeting: Meeting | undefined | null): string {
|
||||
export function countryFlag(
|
||||
meeting: Pick<Meeting, 'country_code' | 'country_flag'> | undefined | null,
|
||||
): string {
|
||||
if (meeting?.country_flag && !/^https?:\/\//i.test(meeting.country_flag)) return meeting.country_flag
|
||||
const code = meeting?.country_code?.toUpperCase()
|
||||
const iso2 = code ? CODE3_TO_2[code] : ''
|
||||
|
||||
47
frontend/src/lib/h2h.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { ChampHubDriver } from '../types'
|
||||
|
||||
export interface TeammatePair {
|
||||
teamName: string
|
||||
teamColour: string
|
||||
driverA: ChampHubDriver
|
||||
driverB: ChampHubDriver
|
||||
/** Drivers on the team beyond the top two (shown as +N). */
|
||||
extraCount: number
|
||||
/** Absolute win gap — smaller means a closer battle. */
|
||||
closeness: number
|
||||
}
|
||||
|
||||
/** Pair teammates per team for H2H display; skip single-driver teams. */
|
||||
export function teammatePairs(drivers: ReadonlyArray<ChampHubDriver>): TeammatePair[] {
|
||||
const byTeam = new Map<string, ChampHubDriver[]>()
|
||||
for (const d of drivers) {
|
||||
const list = byTeam.get(d.team_name) ?? []
|
||||
list.push(d)
|
||||
byTeam.set(d.team_name, list)
|
||||
}
|
||||
|
||||
const pairs: TeammatePair[] = []
|
||||
for (const [teamName, members] of byTeam) {
|
||||
if (members.length < 2) continue
|
||||
|
||||
const sorted = [...members].sort((a, b) => b.points - a.points)
|
||||
const driverA = sorted[0]
|
||||
const driverB = sorted[1]
|
||||
const winsA = driverA.teammate_wins
|
||||
const winsB = driverB.teammate_wins
|
||||
|
||||
pairs.push({
|
||||
teamName,
|
||||
teamColour: driverA.team_colour,
|
||||
driverA,
|
||||
driverB,
|
||||
extraCount: members.length - 2,
|
||||
closeness: Math.abs(winsA - winsB),
|
||||
})
|
||||
}
|
||||
|
||||
return pairs.sort((a, b) => {
|
||||
if (a.closeness !== b.closeness) return a.closeness - b.closeness
|
||||
return a.teamName.localeCompare(b.teamName)
|
||||
})
|
||||
}
|
||||
27
frontend/src/lib/hero.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { Session } from '../types'
|
||||
import { sessionEndTime, sessionStartTime, type FocusMeetingKind } from './schedule'
|
||||
|
||||
export type HeroStateKind = 'live' | 'upcoming' | 'between'
|
||||
|
||||
export interface HeroStateInputs {
|
||||
now: Date
|
||||
liveActive: boolean
|
||||
currentSession: Session | null
|
||||
focusKind: FocusMeetingKind | null
|
||||
}
|
||||
|
||||
export function classifySessionStatus(session: Session, now: Date): 'live' | 'done' | 'upcoming' {
|
||||
const start = sessionStartTime(session)
|
||||
const end = sessionEndTime(session)
|
||||
if (start && end && now >= start && now < end) return 'live'
|
||||
if (start && now >= start) return 'done'
|
||||
return 'upcoming'
|
||||
}
|
||||
|
||||
export function heroState(inputs: HeroStateInputs): HeroStateKind {
|
||||
const { liveActive, currentSession, focusKind } = inputs
|
||||
|
||||
if (liveActive || currentSession) return 'live'
|
||||
if (focusKind === 'current') return 'upcoming'
|
||||
return 'between'
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
LiveDriverData,
|
||||
LiveDriverInfo,
|
||||
LiveRCMessage,
|
||||
LiveSectorData,
|
||||
LiveSessionMeta,
|
||||
LiveStateResponse,
|
||||
LiveStreamData,
|
||||
LiveTyreData,
|
||||
@@ -15,12 +17,62 @@ export interface LiveTimingRow {
|
||||
Tyre?: LiveTyreData
|
||||
}
|
||||
|
||||
export interface LiveSessionDisplay {
|
||||
isRace: boolean
|
||||
isQualifying: boolean
|
||||
isSprintQualifying: boolean
|
||||
phase: 1 | 2 | 3 | null
|
||||
phaseLabel: string
|
||||
cutoffPosition: number | null
|
||||
advanceCount: number | null
|
||||
atRiskStart: number | null
|
||||
atRiskEnd: number | null
|
||||
}
|
||||
|
||||
export interface VisibleSectorEntry {
|
||||
lap: number
|
||||
lastLapTime: string
|
||||
completed: boolean
|
||||
sectors: LiveSectorData[]
|
||||
}
|
||||
|
||||
export type VisibleSectorState = Record<string, VisibleSectorEntry>
|
||||
|
||||
const TRACK_STATUS_LABELS: Record<string, string> = {
|
||||
'1': 'GREEN',
|
||||
'2': 'YELLOW',
|
||||
'4': 'SC',
|
||||
'5': 'RED',
|
||||
'6': 'VSC',
|
||||
'7': 'VSC ENDING',
|
||||
}
|
||||
|
||||
export interface TrackStatusInfo {
|
||||
key: 'green' | 'yellow' | 'sc' | 'vsc' | 'red' | 'unknown'
|
||||
label: string
|
||||
detail: string
|
||||
}
|
||||
|
||||
// Raw F1 SignalR TrackStatus.Status values (see internal/live/types.go):
|
||||
// "1"=all clear, "2"=yellow, "4"=safety car, "5"=red, "6"=VSC, "7"=VSC ending.
|
||||
// "3" has not been observed in the feed; unknown values fall through to a
|
||||
// neutral display so a new encoding never breaks the banner.
|
||||
const TRACK_STATUS_INFO: Record<string, TrackStatusInfo> = {
|
||||
'1': { key: 'green', label: 'TRACK CLEAR', detail: 'Green flag — racing' },
|
||||
'2': { key: 'yellow', label: 'YELLOW FLAG', detail: 'Caution on track' },
|
||||
'4': { key: 'sc', label: 'SAFETY CAR', detail: 'Safety car deployed' },
|
||||
'5': { key: 'red', label: 'RED FLAG', detail: 'Session stopped' },
|
||||
'6': { key: 'vsc', label: 'VIRTUAL SAFETY CAR', detail: 'VSC deployed' },
|
||||
'7': { key: 'vsc', label: 'VSC ENDING', detail: 'Virtual safety car ending' },
|
||||
}
|
||||
|
||||
export function trackStatusInfo(status: string | null | undefined): TrackStatusInfo {
|
||||
if (status && TRACK_STATUS_INFO[status]) return TRACK_STATUS_INFO[status]
|
||||
return {
|
||||
key: 'unknown',
|
||||
label: status ? `TRACK STATUS ${status}` : 'TRACK STATUS UNKNOWN',
|
||||
detail: '',
|
||||
}
|
||||
}
|
||||
|
||||
export function parseLiveStateEvent(data: string): LiveStateResponse | null {
|
||||
@@ -82,16 +134,199 @@ export function sortLiveTimingRows(snapshot: LiveStreamData | null | undefined):
|
||||
}))
|
||||
}
|
||||
|
||||
export function liveSessionDisplay(
|
||||
session: LiveSessionMeta | null | undefined,
|
||||
rows: ReadonlyArray<LiveTimingRow>,
|
||||
): LiveSessionDisplay {
|
||||
const text = [session?.SessionName, session?.SessionType].filter(Boolean).join(' ').toLowerCase()
|
||||
const isQualifying =
|
||||
/\bs?q\s*[123]\b/i.test(text) ||
|
||||
text.includes('qualifying') ||
|
||||
text.includes('shootout')
|
||||
const isSprintQualifying =
|
||||
/\bsq\s*[123]\b/i.test(text) ||
|
||||
text.includes('sprint qualifying') ||
|
||||
text.includes('sprint shootout')
|
||||
const isRace = !isQualifying && (text.includes('race') || /\bsprint\b/i.test(text))
|
||||
const phase = isQualifying ? explicitQualifyingPhase(text) ?? inferredQualifyingPhase(rows) : null
|
||||
const prefix = isSprintQualifying ? 'SQ' : 'Q'
|
||||
const cutoffPosition = qualifyingCutoffPosition(rows.length, phase)
|
||||
const atRiskStart = cutoffPosition === null ? null : cutoffPosition + 1
|
||||
|
||||
return {
|
||||
isRace,
|
||||
isQualifying,
|
||||
isSprintQualifying,
|
||||
phase,
|
||||
phaseLabel: phase ? `${prefix}${phase}` : isQualifying ? prefix : '',
|
||||
cutoffPosition,
|
||||
advanceCount: cutoffPosition,
|
||||
atRiskStart,
|
||||
atRiskEnd: cutoffPosition === null ? null : rows.length,
|
||||
}
|
||||
}
|
||||
|
||||
function explicitQualifyingPhase(text: string): 1 | 2 | 3 | null {
|
||||
const match = text.match(/\b(?:s?q|qualifying)\s*([123])\b/i)
|
||||
if (!match) return null
|
||||
const phase = Number(match[1])
|
||||
return phase === 1 || phase === 2 || phase === 3 ? phase : null
|
||||
}
|
||||
|
||||
function inferredQualifyingPhase(rows: ReadonlyArray<LiveTimingRow>): 1 | 2 | 3 {
|
||||
if (rows.length === 0) return 1
|
||||
const knockedOut = rows.filter((row) => row.Driver.KnockedOut).length
|
||||
if (knockedOut >= Math.max(0, rows.length - 10)) return 3
|
||||
if (knockedOut >= 5) return 2
|
||||
if (rows.length <= 10) return 3
|
||||
if (rows.length <= 18) return 2
|
||||
return 1
|
||||
}
|
||||
|
||||
export function qualifyingCutoffPosition(totalRows: number, phase: 1 | 2 | 3 | null): number | null {
|
||||
if (phase === 1 && totalRows > 5) return totalRows - 5
|
||||
if (phase === 2 && totalRows > 10) return 10
|
||||
return null
|
||||
}
|
||||
|
||||
function emptySector(): LiveSectorData {
|
||||
return { Value: '', PersonalFastest: false, OverallFastest: false }
|
||||
}
|
||||
|
||||
function sectorHasValue(sector: LiveSectorData | undefined): boolean {
|
||||
return Boolean(sector?.Value)
|
||||
}
|
||||
|
||||
function normalizeSectors(sectors: ReadonlyArray<LiveSectorData> | undefined): LiveSectorData[] {
|
||||
return [0, 1, 2].map((index) => sectors?.[index] ?? emptySector())
|
||||
}
|
||||
|
||||
export function mergeVisibleSectors(
|
||||
previous: VisibleSectorState,
|
||||
rows: ReadonlyArray<LiveTimingRow>,
|
||||
): VisibleSectorState {
|
||||
const next: VisibleSectorState = {}
|
||||
|
||||
for (const row of rows) {
|
||||
const driver = row.Driver
|
||||
const prior = previous[row.RacingNumber]
|
||||
const incoming = normalizeSectors(driver.Sectors)
|
||||
const hasIncoming = incoming.some(sectorHasValue)
|
||||
const lap = driver.NumberOfLaps || prior?.lap || 0
|
||||
const lapAdvanced = Boolean(prior && driver.NumberOfLaps > prior.lap)
|
||||
const lastLapChanged = Boolean(
|
||||
prior &&
|
||||
driver.LastLapTime &&
|
||||
driver.LastLapTime !== prior.lastLapTime,
|
||||
)
|
||||
|
||||
if ((lapAdvanced || lastLapChanged || prior?.completed) && !hasIncoming) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (!prior && !hasIncoming) continue
|
||||
|
||||
const merged = lapAdvanced || lastLapChanged ? normalizeSectors(undefined) : normalizeSectors(prior?.sectors)
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
if (sectorHasValue(incoming[index])) {
|
||||
merged[index] = incoming[index]
|
||||
}
|
||||
}
|
||||
|
||||
const hasMerged = merged.some(sectorHasValue)
|
||||
if (!hasMerged) continue
|
||||
|
||||
next[row.RacingNumber] = {
|
||||
lap,
|
||||
lastLapTime: driver.LastLapTime || prior?.lastLapTime || '',
|
||||
completed: sectorHasValue(merged[2]) || (!driver.OnFlyingLap && lastLapChanged),
|
||||
sectors: merged,
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
export function rowsWithVisibleSectors(
|
||||
rows: ReadonlyArray<LiveTimingRow>,
|
||||
visibleSectors: VisibleSectorState,
|
||||
): LiveTimingRow[] {
|
||||
return rows.map((row) => {
|
||||
const sectors = visibleSectors[row.RacingNumber]?.sectors
|
||||
if (!sectors) return row
|
||||
return {
|
||||
...row,
|
||||
Driver: {
|
||||
...row.Driver,
|
||||
Sectors: sectors,
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function driverCode(row: LiveTimingRow): string {
|
||||
return row.Info?.Tla || row.RacingNumber
|
||||
}
|
||||
|
||||
export function trackStatusLabel(status: string): string {
|
||||
return TRACK_STATUS_LABELS[status] || status || 'UNKNOWN'
|
||||
/**
|
||||
* Parse an F1 lap-time string ("1:45.944", "45.944") into total seconds.
|
||||
* Returns null for empty/invalid values so callers never invent a gap.
|
||||
*/
|
||||
export function parseLapTimeSeconds(value: string | null | undefined): number | null {
|
||||
if (!value) return null
|
||||
const match = value.trim().match(/^(?:(\d+):)?([0-5]?\d(?:\.\d+)?)$/)
|
||||
if (!match) return null
|
||||
const minutes = match[1] ? Number(match[1]) : 0
|
||||
const seconds = Number(match[2])
|
||||
if (!Number.isFinite(minutes) || !Number.isFinite(seconds)) return null
|
||||
return minutes * 60 + seconds
|
||||
}
|
||||
|
||||
export function trackStatusClass(status: string): string {
|
||||
return `track-${trackStatusLabel(status).toLowerCase()}`
|
||||
export interface BestLapGap {
|
||||
isLeader: boolean
|
||||
gap: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Display-only gap-to-P1 for practice/qualifying, derived from each driver's
|
||||
* valid best lap. Only drivers with a parseable best lap get an entry, and the
|
||||
* fastest is flagged as the leader. Never fabricates a gap from a missing or
|
||||
* invalid lap — the upstream interval remains the source of truth for races.
|
||||
*/
|
||||
export function bestLapGaps(rows: ReadonlyArray<LiveTimingRow>): Record<string, BestLapGap> {
|
||||
let leaderNumber = ''
|
||||
let best = Infinity
|
||||
for (const row of rows) {
|
||||
const seconds = parseLapTimeSeconds(row.Driver.BestLapTime)
|
||||
if (seconds === null) continue
|
||||
if (seconds < best) {
|
||||
best = seconds
|
||||
leaderNumber = row.RacingNumber
|
||||
}
|
||||
}
|
||||
|
||||
const out: Record<string, BestLapGap> = {}
|
||||
if (!Number.isFinite(best)) return out
|
||||
for (const row of rows) {
|
||||
const seconds = parseLapTimeSeconds(row.Driver.BestLapTime)
|
||||
if (seconds === null) continue
|
||||
out[row.RacingNumber] =
|
||||
row.RacingNumber === leaderNumber
|
||||
? { isLeader: true, gap: '' }
|
||||
: { isLeader: false, gap: `+${(seconds - best).toFixed(3)}` }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** True when the live feed reports an in-progress session with timing data. */
|
||||
export function isLiveSessionActive(
|
||||
state: { is_live?: boolean; data?: unknown } | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(state?.is_live && state.data)
|
||||
}
|
||||
|
||||
export function trackStatusLabel(status: string): string {
|
||||
return TRACK_STATUS_LABELS[status] || status || 'UNKNOWN'
|
||||
}
|
||||
|
||||
export function positionDelta(driver: LiveDriverData): string {
|
||||
@@ -132,10 +367,68 @@ export function tyreLabel(tyre: LiveTyreData | undefined): string {
|
||||
return `${compound} +${tyre.Age || 0}`
|
||||
}
|
||||
|
||||
export function compoundClass(compound: string | null | undefined): string {
|
||||
if (!compound) return 'tyre-unknown'
|
||||
const normalized = compound.toLowerCase()
|
||||
return `tyre-${normalized === 'intermediate' ? 'inter' : normalized}`
|
||||
}
|
||||
|
||||
export function compoundLetter(compound: string | null | undefined): string {
|
||||
return compound?.charAt(0).toUpperCase() || '?'
|
||||
}
|
||||
|
||||
export function tyreClass(tyre: LiveTyreData | undefined): string {
|
||||
if (!tyre?.Compound) return 'tyre-unknown'
|
||||
const compound = tyre.Compound.toLowerCase()
|
||||
return `tyre-${compound === 'intermediate' ? 'inter' : compound}`
|
||||
return compoundClass(tyre?.Compound)
|
||||
}
|
||||
|
||||
export function windDirectionLabel(degrees: number | null | undefined): string {
|
||||
if (degrees == null || !Number.isFinite(degrees)) return ''
|
||||
const points = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
|
||||
const index = Math.round((((degrees % 360) + 360) % 360) / 45) % 8
|
||||
return points[index]
|
||||
}
|
||||
|
||||
export const MAX_PINNED_DRIVERS = 3
|
||||
|
||||
/**
|
||||
* Toggle a driver pin. Unpins if already pinned; otherwise appends,
|
||||
* dropping the oldest pin when at capacity so clicking always works.
|
||||
*/
|
||||
export function togglePin(pins: ReadonlyArray<string>, racingNumber: string, max = MAX_PINNED_DRIVERS): string[] {
|
||||
if (!racingNumber) return [...pins]
|
||||
if (pins.includes(racingNumber)) return pins.filter((pin) => pin !== racingNumber)
|
||||
const next = [...pins, racingNumber]
|
||||
return next.length > max ? next.slice(next.length - max) : next
|
||||
}
|
||||
|
||||
const PINS_STORAGE_KEY = 'box-box.live.pins'
|
||||
|
||||
export function loadPinnedDrivers(storage: Pick<Storage, 'getItem'> | null = safeStorage()): string[] {
|
||||
try {
|
||||
const raw = storage?.getItem(PINS_STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter((pin): pin is string => typeof pin === 'string').slice(0, MAX_PINNED_DRIVERS)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function savePinnedDrivers(pins: ReadonlyArray<string>, storage: Pick<Storage, 'setItem'> | null = safeStorage()): void {
|
||||
try {
|
||||
storage?.setItem(PINS_STORAGE_KEY, JSON.stringify(pins))
|
||||
} catch {
|
||||
// storage unavailable (private mode, SSR) — pins just won't persist
|
||||
}
|
||||
}
|
||||
|
||||
function safeStorage(): Storage | null {
|
||||
try {
|
||||
return typeof window !== 'undefined' ? window.localStorage : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function latestRaceControl(messages: LiveRCMessage[], limit = 10): LiveRCMessage[] {
|
||||
|
||||
146
frontend/src/lib/meaning.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
// Pure interpretation helpers for pairing numbers with their "so-what".
|
||||
// Thresholds are exported consts so they are cheap to tune in one place.
|
||||
|
||||
import { PIT_LOSS_SECONDS } from './tyredeg'
|
||||
|
||||
/** Gaps under this (seconds) are DRS attack range. */
|
||||
export const INTERVAL_DRS_MAX_SECONDS = 1.0
|
||||
|
||||
/** Lower bound of the undercut window (seconds); contiguous with DRS range. */
|
||||
export const INTERVAL_UNDERCUT_MIN_SECONDS = INTERVAL_DRS_MAX_SECONDS
|
||||
|
||||
/**
|
||||
* Upper bound of the undercut window (seconds). Kept well below typical pit
|
||||
* loss ({@link PIT_LOSS_SECONDS}s) — only a few seconds matter for strategy.
|
||||
*/
|
||||
export const INTERVAL_UNDERCUT_MAX_SECONDS = Math.min(3.0, PIT_LOSS_SECONDS / 7)
|
||||
|
||||
/**
|
||||
* Rough per-compound cliff lap estimates (dry compounds). Wet/intermediate
|
||||
* values are conservative — deg varies wildly with conditions.
|
||||
*/
|
||||
export const TYRE_CLIFF_LAPS: Readonly<Record<string, number>> = {
|
||||
SOFT: 18,
|
||||
MEDIUM: 28,
|
||||
HARD: 38,
|
||||
INTERMEDIATE: 20,
|
||||
WET: 15,
|
||||
}
|
||||
|
||||
/** Default cliff when compound is unknown. */
|
||||
export const TYRE_CLIFF_DEFAULT_LAPS = 25
|
||||
|
||||
/** Championship max points per race (winner). */
|
||||
export const MAX_POINTS_PER_ROUND = 25
|
||||
|
||||
export interface MeaningAnnotation {
|
||||
caption: string
|
||||
title: string
|
||||
tone?: 'good' | 'bad' | 'neutral' | 'warn'
|
||||
}
|
||||
|
||||
function cliffLaps(compound: string | null | undefined): number {
|
||||
if (!compound) return TYRE_CLIFF_DEFAULT_LAPS
|
||||
return TYRE_CLIFF_LAPS[compound.toUpperCase()] ?? TYRE_CLIFF_DEFAULT_LAPS
|
||||
}
|
||||
|
||||
/**
|
||||
* Interval / gap-to-ahead meaning for the live timing tower.
|
||||
* Returns null for leader gaps, out-of-range values, or unparsable input.
|
||||
*/
|
||||
export function intervalMeaning(seconds: number | null | undefined): MeaningAnnotation | null {
|
||||
if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return null
|
||||
|
||||
if (seconds < INTERVAL_DRS_MAX_SECONDS) {
|
||||
return {
|
||||
caption: 'DRS range',
|
||||
title: `Within ${INTERVAL_DRS_MAX_SECONDS}s — DRS enabled next straight`,
|
||||
tone: 'good',
|
||||
}
|
||||
}
|
||||
|
||||
if (seconds >= INTERVAL_UNDERCUT_MIN_SECONDS && seconds <= INTERVAL_UNDERCUT_MAX_SECONDS) {
|
||||
return {
|
||||
caption: 'undercut window',
|
||||
title: `${INTERVAL_UNDERCUT_MIN_SECONDS}–${INTERVAL_UNDERCUT_MAX_SECONDS}s — pit now could gain a position (vs ~${PIT_LOSS_SECONDS}s stop)`,
|
||||
tone: 'warn',
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Tyre-age meaning for deg / stint panels.
|
||||
*/
|
||||
export function tyreAgeMeaning(
|
||||
compound: string | null | undefined,
|
||||
age: number | null | undefined,
|
||||
): MeaningAnnotation | null {
|
||||
if (age == null || !Number.isFinite(age) || age < 0) return null
|
||||
|
||||
const cliff = cliffLaps(compound)
|
||||
const freshEnd = Math.ceil(cliff * 0.25)
|
||||
const midEnd = Math.ceil(cliff * 0.65)
|
||||
|
||||
if (age <= freshEnd) {
|
||||
return {
|
||||
caption: 'fresh',
|
||||
title: `${age} lap${age === 1 ? '' : 's'} on ${compound ?? 'tyre'} — early stint grip`,
|
||||
tone: 'good',
|
||||
}
|
||||
}
|
||||
|
||||
if (age <= midEnd) {
|
||||
return {
|
||||
caption: 'mid-life',
|
||||
title: `${age} laps — tyre in its working window before cliff (~${cliff} laps)`,
|
||||
tone: 'neutral',
|
||||
}
|
||||
}
|
||||
|
||||
const lapsToCliff = cliff - age
|
||||
if (lapsToCliff <= 0) {
|
||||
return {
|
||||
caption: 'past cliff',
|
||||
title: `${age} laps — beyond typical ${compound ?? 'tyre'} cliff (~${cliff} laps)`,
|
||||
tone: 'bad',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
caption: `~${lapsToCliff} laps to cliff`,
|
||||
title: `${age} of ~${cliff} laps before deg cliff on ${compound ?? 'tyre'}`,
|
||||
tone: 'warn',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Points gap to the driver directly ahead — catchable-or-not v1.
|
||||
*/
|
||||
export function pointsGapMeaning(
|
||||
gapToAhead: number | null | undefined,
|
||||
roundsLeft: number,
|
||||
driverAhead?: string | null,
|
||||
): MeaningAnnotation | null {
|
||||
if (gapToAhead == null || !Number.isFinite(gapToAhead) || gapToAhead <= 0) return null
|
||||
if (!Number.isFinite(roundsLeft) || roundsLeft <= 0) return null
|
||||
|
||||
const maxCatchable = roundsLeft * MAX_POINTS_PER_ROUND
|
||||
const ahead = driverAhead?.trim() || 'ahead'
|
||||
|
||||
if (gapToAhead > maxCatchable) {
|
||||
return {
|
||||
caption: 'out of reach',
|
||||
title: `+${gapToAhead} pts with ${roundsLeft} round${roundsLeft === 1 ? '' : 's'} left (max ${maxCatchable} available)`,
|
||||
tone: 'bad',
|
||||
}
|
||||
}
|
||||
|
||||
const perRound = Math.ceil(gapToAhead / roundsLeft)
|
||||
return {
|
||||
caption: `~${perRound} pts/round`,
|
||||
title: `Needs ~${perRound} pts per round on ${ahead} to catch (${gapToAhead} pts in ${roundsLeft} round${roundsLeft === 1 ? '' : 's'})`,
|
||||
tone: perRound <= 10 ? 'good' : 'warn',
|
||||
}
|
||||
}
|
||||
123
frontend/src/lib/preview.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import type { ChampionshipHub, EnrichedGrid, EnrichedResult, Meeting, Session } from '../types'
|
||||
import {
|
||||
currentAndNextSession,
|
||||
nextUpcomingMeeting,
|
||||
sessionStartTime,
|
||||
sortSessionsByStart,
|
||||
} from './schedule'
|
||||
|
||||
export const RACE_WIN_POINTS = 25
|
||||
export const SPRINT_WIN_POINTS = 8
|
||||
export const SPRINT_WEEKEND_MAX_POINTS = RACE_WIN_POINTS + SPRINT_WIN_POINTS
|
||||
|
||||
export function pickPreviewMeeting(meetings: Meeting[], now: Date): Meeting | null {
|
||||
const active = meetings.filter((m) => !m.is_cancelled)
|
||||
return nextUpcomingMeeting(active, now)
|
||||
}
|
||||
|
||||
export function findPriorYearMeetingByCircuit(
|
||||
priorYearMeetings: Meeting[],
|
||||
circuitKey: number | undefined,
|
||||
): Meeting | null {
|
||||
if (!circuitKey) return null
|
||||
return priorYearMeetings.find((m) => m.circuit_key === circuitKey && !m.is_cancelled) ?? null
|
||||
}
|
||||
|
||||
export function findRaceSession(sessions: Session[]): Session | null {
|
||||
const sorted = sortSessionsByStart(sessions)
|
||||
return (
|
||||
sorted.find((s) => {
|
||||
const type = s.session_type?.toLowerCase() ?? ''
|
||||
return type.includes('race') && !type.includes('sprint')
|
||||
}) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
export function isSprintWeekend(sessions: Session[]): boolean {
|
||||
return sessions.some((s) => {
|
||||
const label = `${s.session_type} ${s.session_name}`.toLowerCase()
|
||||
return /\bsprint\b/.test(label) && !label.includes('sprint qualifying') && !label.includes('sprint shootout')
|
||||
})
|
||||
}
|
||||
|
||||
export interface PodiumPlace {
|
||||
position: number
|
||||
name_acronym: string
|
||||
full_name: string
|
||||
team_name: string
|
||||
team_colour: string
|
||||
}
|
||||
|
||||
export interface PolePosition {
|
||||
name_acronym: string
|
||||
full_name: string
|
||||
team_name: string
|
||||
team_colour: string
|
||||
}
|
||||
|
||||
export function extractPodium(results: EnrichedResult[]): PodiumPlace[] {
|
||||
return results
|
||||
.filter((r) => r.position >= 1 && r.position <= 3 && !r.dns && !r.dsq)
|
||||
.sort((a, b) => a.position - b.position)
|
||||
.map((r) => ({
|
||||
position: r.position,
|
||||
name_acronym: r.name_acronym,
|
||||
full_name: r.full_name,
|
||||
team_name: r.team_name,
|
||||
team_colour: r.team_colour,
|
||||
}))
|
||||
}
|
||||
|
||||
export function extractPole(grid: EnrichedGrid[]): PolePosition | null {
|
||||
const pole = grid.find((g) => g.position === 1)
|
||||
if (!pole) return null
|
||||
return {
|
||||
name_acronym: pole.name_acronym,
|
||||
full_name: pole.full_name,
|
||||
team_name: pole.team_name,
|
||||
team_colour: pole.team_colour,
|
||||
}
|
||||
}
|
||||
|
||||
export interface TitleFightDriver {
|
||||
name_acronym: string
|
||||
full_name: string
|
||||
team_colour: string
|
||||
points: number
|
||||
position: number
|
||||
gapToLeader: number
|
||||
gapAfterRaceWin: number
|
||||
gapAfterSprintWeekendMax: number
|
||||
}
|
||||
|
||||
export function buildTitleFightContext(hub: ChampionshipHub): TitleFightDriver[] {
|
||||
if (hub.drivers.length === 0) return []
|
||||
const leader = hub.drivers[0]
|
||||
return hub.drivers.slice(0, 3).map((d) => ({
|
||||
name_acronym: d.name_acronym,
|
||||
full_name: d.full_name,
|
||||
team_colour: d.team_colour,
|
||||
points: d.points,
|
||||
position: d.position,
|
||||
gapToLeader: leader.points - d.points,
|
||||
gapAfterRaceWin: leader.points - (d.points + RACE_WIN_POINTS),
|
||||
gapAfterSprintWeekendMax: leader.points - (d.points + SPRINT_WEEKEND_MAX_POINTS),
|
||||
}))
|
||||
}
|
||||
|
||||
export function countdownTargetSession(sessions: Session[], now: Date): Session | null {
|
||||
const sorted = sortSessionsByStart(sessions)
|
||||
const { next } = currentAndNextSession(sorted, now)
|
||||
if (next) return next
|
||||
for (const session of sorted) {
|
||||
const start = sessionStartTime(session)
|
||||
if (start && start > now) return session
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function formatPointsGap(gap: number): string {
|
||||
if (gap === 0) return 'LEADER'
|
||||
const sign = gap > 0 ? '+' : ''
|
||||
return `${sign}${Number.isInteger(gap) ? gap : gap.toFixed(1)}`
|
||||
}
|
||||
22
frontend/src/lib/radio.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { LiveRadioCapture, LiveSessionMeta } from '../types'
|
||||
|
||||
export const LIVE_TIMING_STATIC_BASE = 'https://livetiming.formula1.com/static/'
|
||||
|
||||
export function radioClipUrl(
|
||||
session: Pick<LiveSessionMeta, 'Path'> | null | undefined,
|
||||
capture: Pick<LiveRadioCapture, 'Path'> | null | undefined,
|
||||
): string {
|
||||
const sessionPath = session?.Path?.trim()
|
||||
const capturePath = capture?.Path?.trim()
|
||||
if (!sessionPath || !capturePath) return ''
|
||||
if (/^https?:\/\//i.test(capturePath)) return capturePath
|
||||
|
||||
const base = LIVE_TIMING_STATIC_BASE.replace(/\/+$/, '')
|
||||
const normalizedSession = sessionPath.replace(/^\/+|\/+$/g, '')
|
||||
const normalizedCapture = capturePath.replace(/^\/+/g, '')
|
||||
return `${base}/${normalizedSession}/${normalizedCapture}`
|
||||
}
|
||||
|
||||
export function radioCaptureKey(capture: LiveRadioCapture): string {
|
||||
return `${capture.Utc}-${capture.RacingNumber}-${capture.Path}`
|
||||
}
|
||||
75
frontend/src/lib/replay.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type { ReplayCarPosition, ReplayFrame, TrackBounds } from '../types'
|
||||
import { canvasToSvg, normalizeRawPoint } from './trackmap'
|
||||
|
||||
export interface ReplayFramePair {
|
||||
previous: ReplayFrame | null
|
||||
next: ReplayFrame | null
|
||||
}
|
||||
|
||||
export function lookupReplayFramePair(
|
||||
frames: ReadonlyArray<ReplayFrame>,
|
||||
tMs: number,
|
||||
): ReplayFramePair {
|
||||
if (frames.length === 0) return { previous: null, next: null }
|
||||
if (tMs <= frames[0].t) return { previous: frames[0], next: frames[0] }
|
||||
const last = frames[frames.length - 1]
|
||||
if (tMs >= last.t) return { previous: last, next: last }
|
||||
|
||||
let lo = 0
|
||||
let hi = frames.length - 1
|
||||
while (lo <= hi) {
|
||||
const mid = Math.floor((lo + hi) / 2)
|
||||
const frame = frames[mid]
|
||||
if (frame.t === tMs) return { previous: frame, next: frame }
|
||||
if (frame.t < tMs) {
|
||||
lo = mid + 1
|
||||
} else {
|
||||
hi = mid - 1
|
||||
}
|
||||
}
|
||||
|
||||
return { previous: frames[Math.max(0, hi)], next: frames[Math.min(frames.length - 1, lo)] }
|
||||
}
|
||||
|
||||
export function interpolateReplayCars(
|
||||
frames: ReadonlyArray<ReplayFrame>,
|
||||
tMs: number,
|
||||
): Record<string, ReplayCarPosition> {
|
||||
const { previous, next } = lookupReplayFramePair(frames, tMs)
|
||||
if (!previous && !next) return {}
|
||||
if (!previous) return next?.cars ?? {}
|
||||
if (!next || previous.t === next.t) return previous.cars
|
||||
|
||||
const span = next.t - previous.t
|
||||
const fraction = span <= 0 ? 0 : clamp01((tMs - previous.t) / span)
|
||||
const cars: Record<string, ReplayCarPosition> = {}
|
||||
const numbers = new Set([...Object.keys(previous.cars), ...Object.keys(next.cars)])
|
||||
|
||||
for (const number of numbers) {
|
||||
const before = previous.cars[number]
|
||||
const after = next.cars[number]
|
||||
if (before && after) {
|
||||
cars[number] = {
|
||||
x: before.x + (after.x - before.x) * fraction,
|
||||
y: before.y + (after.y - before.y) * fraction,
|
||||
}
|
||||
} else if (before) {
|
||||
cars[number] = before
|
||||
} else if (after) {
|
||||
cars[number] = after
|
||||
}
|
||||
}
|
||||
return cars
|
||||
}
|
||||
|
||||
export function replayCarToSvg(
|
||||
car: ReplayCarPosition,
|
||||
bounds: TrackBounds,
|
||||
): ReplayCarPosition {
|
||||
return canvasToSvg(normalizeRawPoint({ x: car.x, y: car.y }, bounds))
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.min(1, Math.max(0, value))
|
||||
}
|
||||
14
frontend/src/lib/replayMap.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { ReplayFramesResponse, TrackOutline } from '../types'
|
||||
|
||||
/** Whether replay map can render (probe uses existing frames + outline queries). */
|
||||
export function isReplayMapAvailable(
|
||||
replay: ReplayFramesResponse | null | undefined,
|
||||
outline: TrackOutline | null | undefined,
|
||||
hasError: boolean,
|
||||
): boolean {
|
||||
if (hasError) return false
|
||||
const frames = replay?.frames ?? []
|
||||
if (frames.length < 2) return false
|
||||
if (!outline?.points?.length) return false
|
||||
return true
|
||||
}
|
||||
61
frontend/src/lib/rivalry.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Pure helpers for the championship rivalry compare view.
|
||||
|
||||
/** One round that counted toward the head-to-head tally. */
|
||||
export interface H2HRound {
|
||||
round: number // 1-based season round
|
||||
label: string
|
||||
posA: number
|
||||
posB: number
|
||||
winner: 'a' | 'b'
|
||||
}
|
||||
|
||||
export interface H2HTally {
|
||||
a: number
|
||||
b: number
|
||||
/** Rounds counted in the tally, in season order. */
|
||||
rounds: H2HRound[]
|
||||
/** Rounds skipped because either driver had no finishing position. */
|
||||
skipped: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-round points gap (a − b) across the rounds both cumulative series
|
||||
* cover. Positive values mean driver A is ahead.
|
||||
*/
|
||||
export function gapSeries(a: number[], b: number[]): number[] {
|
||||
const n = Math.min(a.length, b.length)
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < n; i++) out.push(a[i] - b[i])
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Race head-to-head: per round, the lower finishing position wins. Rounds
|
||||
* where either driver has no position (0 / missing) are skipped from the
|
||||
* tally, as are equal positions (defensive — races can't tie).
|
||||
*/
|
||||
export function h2hTally(posA: number[], posB: number[], labels: string[]): H2HTally {
|
||||
const n = Math.max(posA.length, posB.length)
|
||||
const rounds: H2HRound[] = []
|
||||
let a = 0
|
||||
let b = 0
|
||||
let skipped = 0
|
||||
for (let i = 0; i < n; i++) {
|
||||
const pa = posA[i] ?? 0
|
||||
const pb = posB[i] ?? 0
|
||||
if (pa <= 0 || pb <= 0 || pa === pb) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
const winner = pa < pb ? 'a' : 'b'
|
||||
if (winner === 'a') a++
|
||||
else b++
|
||||
rounds.push({ round: i + 1, label: labels[i] ?? `R${i + 1}`, posA: pa, posB: pb, winner })
|
||||
}
|
||||
return { a, b, rounds, skipped }
|
||||
}
|
||||
|
||||
/** Last n counted rounds of a tally, for the mini strip. */
|
||||
export function lastRounds(tally: H2HTally, n: number): H2HRound[] {
|
||||
return tally.rounds.slice(-n)
|
||||
}
|
||||
183
frontend/src/lib/simulator.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
// Championship simulator: project the drivers' championship over the
|
||||
// remaining rounds from per-round finishing assignments.
|
||||
// Pure functions only — no React, no side effects — so everything is unit-testable.
|
||||
|
||||
import type { ChampHubDriver } from '../types'
|
||||
|
||||
/** Current F1 points system for P1–P10. No fastest-lap point (dropped in 2025). */
|
||||
export const POINTS_BY_POSITION = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] as const
|
||||
|
||||
/** Number of points-scoring positions per round. */
|
||||
export const SCORING_POSITIONS = POINTS_BY_POSITION.length
|
||||
|
||||
/** Maximum points a single driver can take from one round. */
|
||||
export const MAX_POINTS_PER_ROUND = POINTS_BY_POSITION[0]
|
||||
|
||||
/**
|
||||
* One remaining round: driver numbers assigned to P1–P10 (index 0 = P1).
|
||||
* `null` means the position is unassigned (nobody scores those points).
|
||||
*/
|
||||
export type RoundAssignment = (number | null)[]
|
||||
|
||||
/** One assignment per remaining round, in chronological order. */
|
||||
export type Scenario = RoundAssignment[]
|
||||
|
||||
/** Points for a 1-based finishing position; 0 outside the top ten. */
|
||||
export function pointsForPosition(position: number): number {
|
||||
if (!Number.isInteger(position) || position < 1 || position > SCORING_POSITIONS) return 0
|
||||
return POINTS_BY_POSITION[position - 1]
|
||||
}
|
||||
|
||||
/** An empty round: all ten scoring positions unassigned. */
|
||||
export function emptyRound(): RoundAssignment {
|
||||
return Array.from({ length: SCORING_POSITIONS }, () => null)
|
||||
}
|
||||
|
||||
/** Drivers sorted by current championship order (points desc, position asc). */
|
||||
function championshipOrder(drivers: ReadonlyArray<ChampHubDriver>): ChampHubDriver[] {
|
||||
return [...drivers].sort((a, b) => b.points - a.points || a.position - b.position)
|
||||
}
|
||||
|
||||
/**
|
||||
* Default assignment for one round: the top ten drivers in current
|
||||
* championship order finish P1–P10.
|
||||
*/
|
||||
export function defaultRound(drivers: ReadonlyArray<ChampHubDriver>): RoundAssignment {
|
||||
const ordered = championshipOrder(drivers)
|
||||
const round = emptyRound()
|
||||
for (let i = 0; i < SCORING_POSITIONS; i++) {
|
||||
round[i] = ordered[i]?.driver_number ?? null
|
||||
}
|
||||
return round
|
||||
}
|
||||
|
||||
/** Default scenario: every remaining round finishes in current championship order. */
|
||||
export function defaultScenario(drivers: ReadonlyArray<ChampHubDriver>, roundsLeft: number): Scenario {
|
||||
const rounds = Math.max(0, Math.floor(roundsLeft) || 0)
|
||||
return Array.from({ length: rounds }, () => defaultRound(drivers))
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an untrusted (e.g. localStorage) scenario against the current hub.
|
||||
* Rounds with the wrong shape, unknown driver numbers, or duplicate drivers
|
||||
* fall back to the default round; the scenario is trimmed/padded to
|
||||
* `roundsLeft`. Never throws.
|
||||
*/
|
||||
export function normalizeScenario(
|
||||
raw: unknown,
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
roundsLeft: number,
|
||||
): Scenario {
|
||||
const fallback = defaultScenario(drivers, roundsLeft)
|
||||
if (!Array.isArray(raw)) return fallback
|
||||
|
||||
const known = new Set(drivers.map((d) => d.driver_number))
|
||||
return fallback.map((defRound, i) => {
|
||||
const candidate = raw[i]
|
||||
if (!Array.isArray(candidate) || candidate.length !== SCORING_POSITIONS) return defRound
|
||||
const seen = new Set<number>()
|
||||
const round = emptyRound()
|
||||
for (let p = 0; p < SCORING_POSITIONS; p++) {
|
||||
const v = candidate[p]
|
||||
if (v === null) continue
|
||||
if (typeof v !== 'number' || !known.has(v) || seen.has(v)) return defRound
|
||||
seen.add(v)
|
||||
round[p] = v
|
||||
}
|
||||
return round
|
||||
})
|
||||
}
|
||||
|
||||
/** Total simulated (extra) points per driver number across the scenario. */
|
||||
export function simulatedPoints(scenario: Scenario): Map<number, number> {
|
||||
const totals = new Map<number, number>()
|
||||
for (const round of scenario) {
|
||||
if (!Array.isArray(round)) continue
|
||||
for (let p = 0; p < Math.min(round.length, SCORING_POSITIONS); p++) {
|
||||
const driverNumber = round[p]
|
||||
if (driverNumber == null) continue
|
||||
totals.set(driverNumber, (totals.get(driverNumber) ?? 0) + POINTS_BY_POSITION[p])
|
||||
}
|
||||
}
|
||||
return totals
|
||||
}
|
||||
|
||||
export interface ProjectedDriver {
|
||||
driver: ChampHubDriver
|
||||
currentPoints: number
|
||||
simPoints: number
|
||||
projectedPoints: number
|
||||
currentPosition: number
|
||||
projectedPosition: number
|
||||
/** Positive = moved up the standings, negative = dropped. */
|
||||
delta: number
|
||||
/** Mathematically alive for the title under the max-points-remaining bound. */
|
||||
titleAlive: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Project final standings from current standings plus a scenario.
|
||||
* Ties on projected points keep the driver with the better current position ahead.
|
||||
*
|
||||
* Title math: a driver is mathematically alive if
|
||||
* current points + 25 × rounds left ≥ current leader's points under the scenario.
|
||||
* The current leader is always alive by this bound.
|
||||
*/
|
||||
export function projectStandings(
|
||||
drivers: ReadonlyArray<ChampHubDriver>,
|
||||
scenario: Scenario,
|
||||
roundsLeft: number,
|
||||
): ProjectedDriver[] {
|
||||
if (drivers.length === 0) return []
|
||||
|
||||
const extras = simulatedPoints(scenario)
|
||||
const ordered = championshipOrder(drivers)
|
||||
const leader = ordered[0]
|
||||
const leaderProjected = leader.points + (extras.get(leader.driver_number) ?? 0)
|
||||
const maxRemaining = MAX_POINTS_PER_ROUND * Math.max(0, roundsLeft)
|
||||
|
||||
const rows = ordered.map((driver, i) => {
|
||||
const simPoints = extras.get(driver.driver_number) ?? 0
|
||||
return {
|
||||
driver,
|
||||
currentPoints: driver.points,
|
||||
simPoints,
|
||||
projectedPoints: driver.points + simPoints,
|
||||
currentPosition: i + 1,
|
||||
projectedPosition: 0,
|
||||
delta: 0,
|
||||
titleAlive: driver.points + maxRemaining >= leaderProjected,
|
||||
}
|
||||
})
|
||||
|
||||
rows.sort(
|
||||
(a, b) => b.projectedPoints - a.projectedPoints || a.currentPosition - b.currentPosition,
|
||||
)
|
||||
rows.forEach((row, i) => {
|
||||
row.projectedPosition = i + 1
|
||||
row.delta = row.currentPosition - row.projectedPosition
|
||||
})
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign a driver to a position within one round, returning a new round.
|
||||
* The driver is removed from any other position it held; assigning `null`
|
||||
* clears the slot.
|
||||
*/
|
||||
export function assignPosition(
|
||||
round: RoundAssignment,
|
||||
positionIndex: number,
|
||||
driverNumber: number | null,
|
||||
): RoundAssignment {
|
||||
const next = round.slice(0, SCORING_POSITIONS)
|
||||
while (next.length < SCORING_POSITIONS) next.push(null)
|
||||
if (positionIndex < 0 || positionIndex >= SCORING_POSITIONS) return next
|
||||
if (driverNumber != null) {
|
||||
for (let p = 0; p < next.length; p++) {
|
||||
if (next[p] === driverNumber) next[p] = null
|
||||
}
|
||||
}
|
||||
next[positionIndex] = driverNumber
|
||||
return next
|
||||
}
|
||||
66
frontend/src/lib/trackmap.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import type { LivePosition, TrackBounds, TrackPoint } from '../types'
|
||||
|
||||
export interface CanvasPoint {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
const VIEWBOX_SIZE = 100
|
||||
|
||||
export function normalizeRawPoint(
|
||||
point: Pick<LivePosition, 'x' | 'y'>,
|
||||
bounds: TrackBounds,
|
||||
): CanvasPoint {
|
||||
return {
|
||||
x: normalizeAxis(point.x, bounds.minX, bounds.maxX),
|
||||
y: 1 - normalizeAxis(point.y, bounds.minY, bounds.maxY),
|
||||
}
|
||||
}
|
||||
|
||||
export function outlinePointToCanvas(point: TrackPoint): CanvasPoint {
|
||||
return {
|
||||
x: clamp01(point.x),
|
||||
y: 1 - clamp01(point.y),
|
||||
}
|
||||
}
|
||||
|
||||
export function buildOutlinePath(points: ReadonlyArray<TrackPoint>): string {
|
||||
if (points.length < 2) return ''
|
||||
|
||||
return points
|
||||
.map((point, index) => {
|
||||
const canvas = outlinePointToCanvas(point)
|
||||
const command = index === 0 ? 'M' : 'L'
|
||||
return `${command} ${formatSvgCoord(canvas.x)} ${formatSvgCoord(canvas.y)}`
|
||||
})
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
export function canvasToSvg(point: CanvasPoint): CanvasPoint {
|
||||
return {
|
||||
x: clamp01(point.x) * VIEWBOX_SIZE,
|
||||
y: clamp01(point.y) * VIEWBOX_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
export function isOnTrack(status: string | null | undefined): boolean {
|
||||
if (!status) return true
|
||||
const normalized = status.toLowerCase()
|
||||
return normalized === 'ontrack' || normalized === 'on-track' || normalized === 'on_track'
|
||||
}
|
||||
|
||||
function normalizeAxis(value: number, min: number, max: number): number {
|
||||
const range = max - min
|
||||
if (!Number.isFinite(value) || !Number.isFinite(min) || !Number.isFinite(max)) return 0.5
|
||||
if (range === 0) return 0.5
|
||||
return clamp01((value - min) / range)
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
if (!Number.isFinite(value)) return 0.5
|
||||
return Math.min(1, Math.max(0, value))
|
||||
}
|
||||
|
||||
function formatSvgCoord(value: number): string {
|
||||
return (value * VIEWBOX_SIZE).toFixed(2)
|
||||
}
|
||||
271
frontend/src/lib/tyredeg.ts
Normal file
@@ -0,0 +1,271 @@
|
||||
// Tyre degradation + pit-window estimation for the live timing page.
|
||||
// Pure functions only — no React, no side effects — so everything is unit-testable.
|
||||
//
|
||||
// Lap-time samples are accumulated client-side from successive SSE snapshots
|
||||
// (mirroring the gapHistory/battles precedent); nothing here talks to the server.
|
||||
|
||||
import type { LiveTimingRow } from './live'
|
||||
import { driverCode } from './live'
|
||||
import { parseIntervalSeconds } from './gapHistory'
|
||||
|
||||
/**
|
||||
* Rough typical pit-lane time loss (entry + stop + exit vs a flying lap), in
|
||||
* seconds. Per-track values are deliberately out of scope for v1.
|
||||
*/
|
||||
export const PIT_LOSS_SECONDS = 22
|
||||
|
||||
/** Minimum clean laps in the current stint before a slope is trustworthy. */
|
||||
export const MIN_CLEAN_LAPS = 4
|
||||
|
||||
/**
|
||||
* Laps more than this many seconds off the stint median are treated as
|
||||
* outliers (traffic, spins, safety car) and excluded from the fit.
|
||||
*/
|
||||
export const OUTLIER_DELTA_SECONDS = 5
|
||||
|
||||
/**
|
||||
* Slope classification thresholds (seconds per lap):
|
||||
* slope <= -DEG_SLOPE_THRESHOLD -> 'improving' (track evolution, fuel burn dominating)
|
||||
* slope >= +DEG_SLOPE_THRESHOLD -> 'degrading' (tyre wear dominating)
|
||||
* otherwise -> 'stable'
|
||||
*/
|
||||
export const DEG_SLOPE_THRESHOLD = 0.05
|
||||
|
||||
/** Safety cap so a very long stint cannot grow the buffer unbounded. */
|
||||
export const MAX_STINT_SAMPLES = 80
|
||||
|
||||
export type DegTrend = 'improving' | 'stable' | 'degrading'
|
||||
|
||||
export interface StintSample {
|
||||
lap: number
|
||||
seconds: number
|
||||
}
|
||||
|
||||
export interface DriverStintHistory {
|
||||
compound: string
|
||||
tyreAge: number
|
||||
lastLapNumber: number
|
||||
lastLapTime: string
|
||||
/** The next completed lap is an out-lap (fresh stint) and must be discarded. */
|
||||
skipNextLap: boolean
|
||||
samples: StintSample[]
|
||||
}
|
||||
|
||||
/** Per-driver current-stint lap history, keyed by racing number. */
|
||||
export type StintHistoryMap = Record<string, DriverStintHistory>
|
||||
|
||||
export interface StintLapInput {
|
||||
racingNumber: string
|
||||
lapNumber: number
|
||||
lastLapTime: string
|
||||
compound: string
|
||||
tyreAge: number
|
||||
inPit: boolean
|
||||
pitOut: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an F1 live-timing lap time string ("1:23.456", "83.456") into seconds.
|
||||
* Same conventions as parseIntervalSeconds, but a lap time is never signed and
|
||||
* never a lapped/leader marker; zero or negative values are rejected.
|
||||
*/
|
||||
export function parseLapTimeSeconds(raw: string | null | undefined): number | null {
|
||||
const value = parseIntervalSeconds(raw)
|
||||
if (value === null || value <= 0) return null
|
||||
return value
|
||||
}
|
||||
|
||||
export function stintInputFromRow(row: LiveTimingRow): StintLapInput {
|
||||
return {
|
||||
racingNumber: row.RacingNumber,
|
||||
lapNumber: row.Driver.NumberOfLaps || 0,
|
||||
lastLapTime: row.Driver.LastLapTime || '',
|
||||
compound: row.Tyre?.Compound || '',
|
||||
tyreAge: row.Tyre?.Age ?? 0,
|
||||
inPit: Boolean(row.Driver.InPit),
|
||||
pitOut: Boolean(row.Driver.PitOut),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record one snapshot's worth of lap samples for each driver's current stint.
|
||||
* Returns a new map (input is not mutated); drivers missing from `inputs` are
|
||||
* pruned.
|
||||
*
|
||||
* A lap counts as completed when LastLapTime changes to a new non-empty value
|
||||
* (NumberOfLaps can tick before the lap time arrives, so the time string is
|
||||
* the trigger; a sample for the same lap number is replaced, not duplicated).
|
||||
* The stint buffer resets when the compound changes or the tyre age drops
|
||||
* (new set fitted), and laps completed in the pit lane (in-lap), on pit exit
|
||||
* (out-lap), or immediately after a reset are excluded.
|
||||
*/
|
||||
export function recordStintSamples(
|
||||
history: StintHistoryMap,
|
||||
inputs: ReadonlyArray<StintLapInput>,
|
||||
): StintHistoryMap {
|
||||
const next: StintHistoryMap = {}
|
||||
|
||||
for (const input of inputs) {
|
||||
if (!input.racingNumber) continue
|
||||
|
||||
const prior = history[input.racingNumber]
|
||||
if (!prior) {
|
||||
next[input.racingNumber] = {
|
||||
compound: input.compound,
|
||||
tyreAge: input.tyreAge,
|
||||
lastLapNumber: input.lapNumber,
|
||||
lastLapTime: input.lastLapTime,
|
||||
skipNextLap: false,
|
||||
samples: [],
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
let samples = prior.samples
|
||||
let skipNextLap = prior.skipNextLap
|
||||
|
||||
const compoundChanged = Boolean(input.compound) && Boolean(prior.compound) && input.compound !== prior.compound
|
||||
const freshSet = input.tyreAge < prior.tyreAge
|
||||
if (compoundChanged || freshSet || input.inPit) {
|
||||
// Stint over (or a new one starting): drop the old laps and flag the
|
||||
// upcoming out-lap for exclusion.
|
||||
samples = []
|
||||
skipNextLap = true
|
||||
}
|
||||
|
||||
const lapCompleted = Boolean(input.lastLapTime) && input.lastLapTime !== prior.lastLapTime
|
||||
if (lapCompleted) {
|
||||
const seconds = parseLapTimeSeconds(input.lastLapTime)
|
||||
const dirty = input.inPit || input.pitOut || skipNextLap
|
||||
if (seconds !== null && !dirty) {
|
||||
const last = samples[samples.length - 1]
|
||||
if (last && last.lap === input.lapNumber) {
|
||||
samples = [...samples.slice(0, -1), { lap: input.lapNumber, seconds }]
|
||||
} else {
|
||||
samples = [...samples, { lap: input.lapNumber, seconds }]
|
||||
if (samples.length > MAX_STINT_SAMPLES) {
|
||||
samples = samples.slice(samples.length - MAX_STINT_SAMPLES)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!input.inPit) skipNextLap = false
|
||||
}
|
||||
|
||||
next[input.racingNumber] = {
|
||||
compound: input.compound || prior.compound,
|
||||
tyreAge: input.tyreAge,
|
||||
lastLapNumber: input.lapNumber,
|
||||
lastLapTime: input.lastLapTime || prior.lastLapTime,
|
||||
skipNextLap,
|
||||
samples,
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
export interface DegModel {
|
||||
/** Least-squares slope of lap time vs lap number, in seconds per lap. */
|
||||
slope: number
|
||||
trend: DegTrend
|
||||
/** Clean (outlier-filtered) samples the fit ran over, in lap order. */
|
||||
samples: StintSample[]
|
||||
}
|
||||
|
||||
/** Drop laps more than OUTLIER_DELTA_SECONDS off the stint median. */
|
||||
export function cleanStintSamples(
|
||||
samples: ReadonlyArray<StintSample>,
|
||||
maxDelta = OUTLIER_DELTA_SECONDS,
|
||||
): StintSample[] {
|
||||
if (samples.length === 0) return []
|
||||
const sorted = samples.map((sample) => sample.seconds).sort((a, b) => a - b)
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
const median = sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
|
||||
return samples.filter((sample) => Math.abs(sample.seconds - median) <= maxDelta)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fit a linear degradation model over the stint's clean laps.
|
||||
* Returns null with fewer than MIN_CLEAN_LAPS clean samples — the caller
|
||||
* should show a "warming up" placeholder rather than a junk slope.
|
||||
*/
|
||||
export function degradationModel(samples: ReadonlyArray<StintSample>): DegModel | null {
|
||||
const clean = cleanStintSamples(samples)
|
||||
if (clean.length < MIN_CLEAN_LAPS) return null
|
||||
|
||||
const n = clean.length
|
||||
const meanLap = clean.reduce((sum, s) => sum + s.lap, 0) / n
|
||||
const meanSec = clean.reduce((sum, s) => sum + s.seconds, 0) / n
|
||||
|
||||
let numerator = 0
|
||||
let denominator = 0
|
||||
for (const sample of clean) {
|
||||
numerator += (sample.lap - meanLap) * (sample.seconds - meanSec)
|
||||
denominator += (sample.lap - meanLap) ** 2
|
||||
}
|
||||
if (denominator === 0) return null
|
||||
|
||||
const slope = numerator / denominator
|
||||
const trend: DegTrend =
|
||||
slope <= -DEG_SLOPE_THRESHOLD ? 'improving' : slope >= DEG_SLOPE_THRESHOLD ? 'degrading' : 'stable'
|
||||
|
||||
return { slope, trend, samples: clean }
|
||||
}
|
||||
|
||||
/** "+0.08s/lap" / "-0.12s/lap" display form. */
|
||||
export function formatSlope(slope: number): string {
|
||||
const sign = slope >= 0 ? '+' : '−'
|
||||
return `${sign}${Math.abs(slope).toFixed(2)}s/lap`
|
||||
}
|
||||
|
||||
export interface PitRejoinEstimate {
|
||||
rejoinPosition: number
|
||||
/** Cars behind that would get past during the stop. */
|
||||
positionsLost: number
|
||||
/** Driver code directly ahead after rejoining, if any. */
|
||||
aheadCode: string | null
|
||||
/** Driver code directly behind after rejoining, if any. */
|
||||
behindCode: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate where a driver rejoins after a pit stop costing `pitLoss` seconds.
|
||||
*
|
||||
* Walks the cars behind the driver, accumulating their Interval (gap to car
|
||||
* ahead) values: every car whose cumulative gap to the driver is under the
|
||||
* pit loss gets past. An unparsable interval (lapped marker like "1L") ends
|
||||
* the walk — those cars are at least a lap down and stay behind. Cars in the
|
||||
* pits or retired are excluded from the ladder.
|
||||
*/
|
||||
export function estimatePitRejoin(
|
||||
rows: ReadonlyArray<LiveTimingRow>,
|
||||
racingNumber: string,
|
||||
pitLoss = PIT_LOSS_SECONDS,
|
||||
): PitRejoinEstimate | null {
|
||||
const ladder = rows
|
||||
.filter((row) => row.Position > 0 && !row.Driver.Retired && !row.Driver.InPit)
|
||||
.sort((a, b) => a.Position - b.Position)
|
||||
|
||||
const index = ladder.findIndex((row) => row.RacingNumber === racingNumber)
|
||||
if (index === -1) return null
|
||||
|
||||
let cumulative = 0
|
||||
let positionsLost = 0
|
||||
for (let i = index + 1; i < ladder.length; i++) {
|
||||
const gap = parseIntervalSeconds(ladder[i].Driver.Interval)
|
||||
if (gap === null) break
|
||||
cumulative += Math.max(0, gap)
|
||||
if (cumulative >= pitLoss) break
|
||||
positionsLost += 1
|
||||
}
|
||||
|
||||
const ahead = positionsLost > 0 ? ladder[index + positionsLost] : ladder[index - 1]
|
||||
const behind = ladder[index + positionsLost + 1]
|
||||
|
||||
return {
|
||||
rejoinPosition: ladder[index].Position + positionsLost,
|
||||
positionsLost,
|
||||
aheadCode: ahead ? driverCode(ahead) : null,
|
||||
behindCode: behind ? driverCode(behind) : null,
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,33 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { fetchNews, fetchNewsArticle, markNewsRead } from '../api'
|
||||
import {
|
||||
fetchChampionshipHub,
|
||||
fetchNews,
|
||||
fetchNewsArticle,
|
||||
fetchSeasonMeetings,
|
||||
fetchSeasons,
|
||||
markNewsRead,
|
||||
} from '../api'
|
||||
import {
|
||||
activeDigestWindow,
|
||||
filterByTag,
|
||||
groupByWindow,
|
||||
gpWindows,
|
||||
itemsForWindow,
|
||||
sinceLastLabel,
|
||||
sortWindowBucketsNewestFirst,
|
||||
tagColour,
|
||||
tagItems,
|
||||
topTags,
|
||||
type DigestTag,
|
||||
type TaggedNewsItem,
|
||||
} from '../lib/digest'
|
||||
import { stripHtml, timeAgo } from '../utils'
|
||||
import type { ArticleContent, NewsItem } from '../types'
|
||||
import '../styles/digest.css'
|
||||
|
||||
type Category = 'all' | 'official' | 'news' | 'video'
|
||||
|
||||
const PAGE_SIZE = 16
|
||||
|
||||
const CATEGORY_LABELS: Record<Category, string> = {
|
||||
all: 'All',
|
||||
official: 'Official',
|
||||
@@ -71,6 +91,31 @@ function CategoryTabs({
|
||||
)
|
||||
}
|
||||
|
||||
function TagChip({
|
||||
tag,
|
||||
active,
|
||||
onClick,
|
||||
className = 'digest-tag-chip',
|
||||
}: {
|
||||
tag: DigestTag
|
||||
active?: boolean
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`${className}${active ? ' active' : ''}`}
|
||||
style={{ '--tag-colour': tagColour(tag.colour) } as React.CSSProperties}
|
||||
onClick={onClick}
|
||||
aria-pressed={active}
|
||||
>
|
||||
<span className="digest-tag-dot" aria-hidden="true" />
|
||||
{tag.label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function OGImage({ url, title }: { url?: string; title: string }) {
|
||||
const [failed, setFailed] = useState(false)
|
||||
const initial = (title[0] ?? '?').toUpperCase()
|
||||
@@ -98,11 +143,15 @@ function OGImage({ url, title }: { url?: string; title: string }) {
|
||||
function BriefingCard({
|
||||
item,
|
||||
isActive,
|
||||
activeTag,
|
||||
onSelect,
|
||||
onTagClick,
|
||||
}: {
|
||||
item: NewsItem
|
||||
item: TaggedNewsItem
|
||||
isActive: boolean
|
||||
activeTag: string | null
|
||||
onSelect: (item: NewsItem) => void
|
||||
onTagClick: (tag: DigestTag) => void
|
||||
}) {
|
||||
const isRead = !!item.read_at
|
||||
const isVideo = categoryOf(item) === 'video'
|
||||
@@ -129,6 +178,25 @@ function BriefingCard({
|
||||
{stripHtml(item.og_description || item.summary || '')}
|
||||
</p>
|
||||
)}
|
||||
{item.tags.length > 0 && (
|
||||
<div className="bp-card-tags">
|
||||
{item.tags.map((tag) => (
|
||||
<button
|
||||
key={tag.key}
|
||||
type="button"
|
||||
className={`bp-card-tag${activeTag === tag.key ? ' active' : ''}`}
|
||||
style={{ '--tag-colour': tagColour(tag.colour) } as React.CSSProperties}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onTagClick(tag)
|
||||
}}
|
||||
>
|
||||
<span className="digest-tag-dot" aria-hidden="true" />
|
||||
{tag.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
@@ -146,7 +214,6 @@ function ReaderPanel({
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Close on Escape
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
@@ -155,7 +222,6 @@ function ReaderPanel({
|
||||
return () => document.removeEventListener('keydown', handler)
|
||||
}, [onClose])
|
||||
|
||||
// Fetch article when item changes
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
setArticle(null)
|
||||
@@ -175,9 +241,14 @@ function ReaderPanel({
|
||||
.catch((err) => { setError(String(err)); setLoading(false) })
|
||||
}, [item?.url, item ? categoryOf(item) : ''])
|
||||
|
||||
// Scroll panel to top when item changes
|
||||
useEffect(() => {
|
||||
panelRef.current?.scrollTo({ top: 0 })
|
||||
const panel = panelRef.current
|
||||
if (!panel) return
|
||||
if (typeof panel.scrollTo === 'function') {
|
||||
panel.scrollTo({ top: 0 })
|
||||
} else {
|
||||
panel.scrollTop = 0
|
||||
}
|
||||
}, [item?.url])
|
||||
|
||||
const isOpen = item !== null
|
||||
@@ -297,7 +368,6 @@ function ReaderPanel({
|
||||
{article && !loading && article.content && (
|
||||
<div
|
||||
className="bp-reader-body"
|
||||
// readability strips scripts/iframes; sources are all known news outlets
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{ __html: article.content }}
|
||||
/>
|
||||
@@ -332,8 +402,9 @@ function ReaderPanel({
|
||||
export function BriefingPage() {
|
||||
const [activeCategory, setActiveCategory] = useState<Category>('all')
|
||||
const [selectedItem, setSelectedItem] = useState<NewsItem | null>(null)
|
||||
const [page, setPage] = useState(1)
|
||||
const [activeTag, setActiveTag] = useState<string | null>(null)
|
||||
const queryClient = useQueryClient()
|
||||
const now = useMemo(() => new Date(), [])
|
||||
|
||||
const { data: allNews = [], isLoading, isError } = useQuery({
|
||||
queryKey: ['news'],
|
||||
@@ -341,13 +412,74 @@ export function BriefingPage() {
|
||||
staleTime: 60_000,
|
||||
})
|
||||
|
||||
const filtered = allNews.filter(
|
||||
(item) => activeCategory === 'all' || categoryOf(item) === activeCategory,
|
||||
const seasonsQuery = useQuery({
|
||||
queryKey: ['seasons'],
|
||||
queryFn: fetchSeasons,
|
||||
})
|
||||
const latestSeason = seasonsQuery.data?.[0] ?? null
|
||||
|
||||
const meetingsQuery = useQuery({
|
||||
queryKey: ['season-meetings', latestSeason],
|
||||
queryFn: () => fetchSeasonMeetings(latestSeason!),
|
||||
enabled: latestSeason != null,
|
||||
})
|
||||
|
||||
const hubQuery = useQuery({
|
||||
queryKey: ['championship-hub', latestSeason],
|
||||
queryFn: () => fetchChampionshipHub(latestSeason!),
|
||||
enabled: latestSeason != null,
|
||||
})
|
||||
|
||||
const meetings = meetingsQuery.data ?? []
|
||||
const hub = hubQuery.data
|
||||
|
||||
const taggedNews = useMemo(
|
||||
() => tagItems(allNews, hub?.drivers ?? [], hub?.teams ?? []),
|
||||
[allNews, hub],
|
||||
)
|
||||
const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
|
||||
const safePage = Math.min(page, pageCount)
|
||||
const pageStart = (safePage - 1) * PAGE_SIZE
|
||||
const pagedItems = filtered.slice(pageStart, pageStart + PAGE_SIZE)
|
||||
|
||||
const categoryFiltered = useMemo(
|
||||
() => taggedNews.filter(
|
||||
(item) => activeCategory === 'all' || categoryOf(item) === activeCategory,
|
||||
),
|
||||
[taggedNews, activeCategory],
|
||||
)
|
||||
|
||||
const tagFiltered = useMemo(
|
||||
() => filterByTag(categoryFiltered, activeTag),
|
||||
[categoryFiltered, activeTag],
|
||||
)
|
||||
|
||||
const windows = useMemo(() => gpWindows(meetings, now), [meetings, now])
|
||||
const grouped = useMemo(() => groupByWindow(tagFiltered, windows), [tagFiltered, windows])
|
||||
const windowSections = useMemo(
|
||||
() => sortWindowBucketsNewestFirst(grouped.windows),
|
||||
[grouped.windows],
|
||||
)
|
||||
|
||||
const activeWindow = useMemo(
|
||||
() => activeDigestWindow(windows, meetings, now),
|
||||
[windows, meetings, now],
|
||||
)
|
||||
|
||||
const sinceLastItems = useMemo(
|
||||
() => itemsForWindow(tagFiltered, activeWindow),
|
||||
[tagFiltered, activeWindow],
|
||||
)
|
||||
|
||||
const sinceLastTags = useMemo(() => topTags(sinceLastItems), [sinceLastItems])
|
||||
const sinceLabel = sinceLastLabel(meetings, now)
|
||||
|
||||
const taggedByUrl = useMemo(() => {
|
||||
const map = new Map<string, TaggedNewsItem>()
|
||||
for (const item of tagFiltered) map.set(item.url, item)
|
||||
return map
|
||||
}, [tagFiltered])
|
||||
|
||||
const recentTagged = useMemo(() => {
|
||||
const urls = new Set(grouped.recent.map((item) => item.url))
|
||||
return tagFiltered.filter((item) => urls.has(item.url))
|
||||
}, [grouped.recent, tagFiltered])
|
||||
|
||||
const counts: Record<Category, number> = {
|
||||
all: allNews.length,
|
||||
@@ -374,22 +506,14 @@ export function BriefingPage() {
|
||||
|
||||
const handleClose = useCallback(() => setSelectedItem(null), [])
|
||||
|
||||
useEffect(() => {
|
||||
setPage((current) => Math.min(current, pageCount))
|
||||
}, [pageCount])
|
||||
|
||||
const handlePageChange = useCallback(
|
||||
(nextPage: number) => {
|
||||
setPage(Math.min(Math.max(nextPage, 1), pageCount))
|
||||
setSelectedItem(null)
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
},
|
||||
[pageCount],
|
||||
)
|
||||
const handleTagClick = useCallback((tag: DigestTag) => {
|
||||
setActiveTag((current) => (current === tag.key ? null : tag.key))
|
||||
setSelectedItem(null)
|
||||
}, [])
|
||||
|
||||
const unreadCount = allNews.filter((i) => !i.read_at).length
|
||||
const pageEnd = Math.min(pageStart + pagedItems.length, filtered.length)
|
||||
const showPagination = filtered.length > PAGE_SIZE
|
||||
const hasDigest = meetings.length > 0
|
||||
const showEmpty = tagFiltered.length === 0 && grouped.recent.length === 0
|
||||
|
||||
return (
|
||||
<div className="bp-page" data-testid="briefing-page">
|
||||
@@ -408,74 +532,106 @@ export function BriefingPage() {
|
||||
<CategoryTabs
|
||||
active={activeCategory}
|
||||
counts={counts}
|
||||
onChange={(c) => { setActiveCategory(c); setSelectedItem(null); setPage(1) }}
|
||||
onChange={(c) => {
|
||||
setActiveCategory(c)
|
||||
setSelectedItem(null)
|
||||
setActiveTag(null)
|
||||
}}
|
||||
/>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
{hasDigest && (
|
||||
<div className="digest-sticky" data-testid="digest-sticky-header">
|
||||
<div className="digest-sticky-head">
|
||||
<h2 className="digest-sticky-title">Since {sinceLabel}</h2>
|
||||
<span className="digest-sticky-count">
|
||||
{sinceLastItems.length} item{sinceLastItems.length === 1 ? '' : 's'}
|
||||
</span>
|
||||
</div>
|
||||
{(sinceLastTags.length > 0 || activeTag) && (
|
||||
<div className="digest-sticky-tags">
|
||||
{sinceLastTags.map((tag) => (
|
||||
<TagChip
|
||||
key={tag.key}
|
||||
tag={tag}
|
||||
active={activeTag === tag.key}
|
||||
onClick={() => handleTagClick(tag)}
|
||||
/>
|
||||
))}
|
||||
{activeTag && (
|
||||
<button
|
||||
type="button"
|
||||
className="digest-filter-clear"
|
||||
onClick={() => setActiveTag(null)}
|
||||
data-testid="digest-filter-clear"
|
||||
>
|
||||
Clear filter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showEmpty ? (
|
||||
<div className="bp-empty">
|
||||
No {activeCategory !== 'all' ? activeCategory : ''} items available.
|
||||
Run <code>box-box --ingest-news</code> to refresh feeds.
|
||||
{activeTag ? ' Try clearing the tag filter.' : ''}
|
||||
{!activeTag && (
|
||||
<>
|
||||
{' '}
|
||||
Run <code>box-box --ingest-news</code> to refresh feeds.
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{showPagination && (
|
||||
<div className="bp-pagination bp-pagination-top">
|
||||
<span className="bp-pagination-meta mono">
|
||||
{pageStart + 1}-{pageEnd} of {filtered.length}
|
||||
</span>
|
||||
<div className="bp-pagination-actions">
|
||||
<button
|
||||
className="bp-page-btn"
|
||||
onClick={() => handlePageChange(safePage - 1)}
|
||||
disabled={safePage === 1}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span className="bp-page-current mono">
|
||||
Page {safePage} / {pageCount}
|
||||
</span>
|
||||
<button
|
||||
className="bp-page-btn"
|
||||
onClick={() => handlePageChange(safePage + 1)}
|
||||
disabled={safePage === pageCount}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
{windowSections.map(({ window, items }) => (
|
||||
<section
|
||||
key={window.meeting_key}
|
||||
className="digest-section"
|
||||
data-testid={`digest-window-${window.meeting_key}`}
|
||||
>
|
||||
<div className="digest-section-head">
|
||||
<h3 className="digest-section-title">{window.meeting_name}</h3>
|
||||
<span className="digest-section-count">{items.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className={`bp-grid${selectedItem ? ' bp-grid-narrow' : ''}`}>
|
||||
{items.map((item) => {
|
||||
const tagged = taggedByUrl.get(item.url) ?? { ...item, tags: [] }
|
||||
return (
|
||||
<BriefingCard
|
||||
key={item.url}
|
||||
item={tagged}
|
||||
isActive={selectedItem?.url === item.url}
|
||||
activeTag={activeTag}
|
||||
onSelect={handleSelect}
|
||||
onTagClick={handleTagClick}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
<div className={`bp-grid${selectedItem ? ' bp-grid-narrow' : ''}`}>
|
||||
{pagedItems.map((item) => (
|
||||
<BriefingCard
|
||||
key={item.url}
|
||||
item={item}
|
||||
isActive={selectedItem?.url === item.url}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{showPagination && (
|
||||
<div className="bp-pagination bp-pagination-bottom">
|
||||
<button
|
||||
className="bp-page-btn"
|
||||
onClick={() => handlePageChange(safePage - 1)}
|
||||
disabled={safePage === 1}
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<span className="bp-page-current mono">
|
||||
Page {safePage} / {pageCount}
|
||||
</span>
|
||||
<button
|
||||
className="bp-page-btn"
|
||||
onClick={() => handlePageChange(safePage + 1)}
|
||||
disabled={safePage === pageCount}
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
{recentTagged.length > 0 && (
|
||||
<section className="digest-section digest-recent-section" data-testid="digest-recent">
|
||||
<div className="digest-section-head">
|
||||
<h3 className="digest-section-title">Recent</h3>
|
||||
<span className="digest-section-count">{recentTagged.length}</span>
|
||||
</div>
|
||||
<div className={`bp-grid${selectedItem ? ' bp-grid-narrow' : ''}`}>
|
||||
{recentTagged.map((item) => (
|
||||
<BriefingCard
|
||||
key={item.url}
|
||||
item={item}
|
||||
isActive={selectedItem?.url === item.url}
|
||||
activeTag={activeTag}
|
||||
onSelect={handleSelect}
|
||||
onTagClick={handleTagClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
704
frontend/src/pages/ChampionshipPage.tsx
Normal file
@@ -0,0 +1,704 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { fetchChampionshipHub, fetchSeasons } from '../api'
|
||||
import { teamColor } from '../utils'
|
||||
import type { ChampHubDriver, ChampionshipHub } from '../types'
|
||||
import { ChampionshipSimulator } from '../components/ChampionshipSimulator'
|
||||
import { RivalryCompare } from '../components/RivalryCompare'
|
||||
import { Meaning } from '../components/Meaning'
|
||||
import { TeammateH2H } from '../components/TeammateH2H'
|
||||
import { teammatePairs } from '../lib/h2h'
|
||||
import { pointsGapMeaning } from '../lib/meaning'
|
||||
|
||||
type View = 'drivers' | 'constructors' | 'progression' | 'rivalry' | 'simulator'
|
||||
|
||||
const GOLD = '#ffd700'
|
||||
const SILVER = '#c0c0c0'
|
||||
const BRONZE = '#cd7f32'
|
||||
|
||||
function medalColor(pos: number): string {
|
||||
if (pos === 1) return GOLD
|
||||
if (pos === 2) return SILVER
|
||||
if (pos === 3) return BRONZE
|
||||
return 'var(--text-2)'
|
||||
}
|
||||
|
||||
function ghostColor(pos: number): string {
|
||||
if (pos === 1) return 'rgba(255,215,0,0.08)'
|
||||
if (pos === 2) return 'rgba(192,192,192,0.07)'
|
||||
if (pos === 3) return 'rgba(205,127,50,0.07)'
|
||||
return 'rgba(255,255,255,0.03)'
|
||||
}
|
||||
|
||||
function fmtPts(n: number): string {
|
||||
return Number.isInteger(n) ? String(n) : n.toFixed(1)
|
||||
}
|
||||
|
||||
/** Sparkline polyline points inside a 62×20 box. */
|
||||
function sparkPoints(form: number[]): string {
|
||||
if (!form.length) return ''
|
||||
const fmax = Math.max(25, ...form)
|
||||
const n = form.length
|
||||
return form
|
||||
.map((v, k) => {
|
||||
const x = n === 1 ? 0 : (k * 62) / (n - 1)
|
||||
const y = 18 - (fmax > 0 ? (v / fmax) * 16 : 0)
|
||||
return `${x.toFixed(1)},${y.toFixed(1)}`
|
||||
})
|
||||
.join(' ')
|
||||
}
|
||||
|
||||
interface TeamSplit {
|
||||
driverA: string
|
||||
ptsA: number
|
||||
driverB: string
|
||||
ptsB: number
|
||||
splitA: number
|
||||
splitB: number
|
||||
shareLabel: string
|
||||
}
|
||||
|
||||
function teamSplit(teamName: string, drivers: ChampHubDriver[]): TeamSplit {
|
||||
const ds = drivers.filter((d) => d.team_name === teamName).sort((a, b) => b.points - a.points)
|
||||
const a = ds[0]
|
||||
const b = ds[1]
|
||||
const ptsA = a?.points ?? 0
|
||||
const ptsB = b?.points ?? 0
|
||||
const total = ptsA + ptsB || 1
|
||||
const splitA = Math.round((ptsA / total) * 100)
|
||||
return {
|
||||
driverA: a?.name_acronym ?? '—',
|
||||
ptsA,
|
||||
driverB: b?.name_acronym ?? '—',
|
||||
ptsB,
|
||||
splitA,
|
||||
splitB: 100 - splitA,
|
||||
shareLabel: `${splitA}/${100 - splitA}`,
|
||||
}
|
||||
}
|
||||
|
||||
export function ChampionshipPage() {
|
||||
const [view, setView] = useState<View>('drivers')
|
||||
|
||||
const seasonsQuery = useQuery({ queryKey: ['seasons'], queryFn: fetchSeasons })
|
||||
const latestSeason = seasonsQuery.data?.[0] ?? null
|
||||
|
||||
const hubQuery = useQuery({
|
||||
queryKey: ['championship-hub', latestSeason],
|
||||
queryFn: () => fetchChampionshipHub(latestSeason ?? undefined),
|
||||
enabled: latestSeason != null,
|
||||
staleTime: 5 * 60_000,
|
||||
})
|
||||
|
||||
if (seasonsQuery.isLoading || hubQuery.isLoading) {
|
||||
return <div className="page loading-state">loading championship…</div>
|
||||
}
|
||||
if (hubQuery.isError) {
|
||||
return (
|
||||
<div className="page error-box">
|
||||
{hubQuery.error instanceof Error ? hubQuery.error.message : 'Failed to load championship'}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const hub = hubQuery.data
|
||||
if (!hub || hub.drivers.length === 0) {
|
||||
return (
|
||||
<div className="champ-page champ-empty" data-testid="championship-empty">
|
||||
<div className="champ-empty-band">
|
||||
<span className="champ-empty-eyebrow mono">box-box · championship</span>
|
||||
<h1 className="champ-empty-title">No championship data</h1>
|
||||
<p className="champ-empty-sub">
|
||||
Standings for {latestSeason ?? 'this season'} are not available yet. Once race results are
|
||||
ingested they will appear here.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <ChampionshipBody hub={hub} view={view} setView={setView} />
|
||||
}
|
||||
|
||||
interface BodyProps {
|
||||
hub: ChampionshipHub
|
||||
view: View
|
||||
setView: (v: View) => void
|
||||
}
|
||||
|
||||
function ChampionshipBody({ hub, view, setView }: BodyProps) {
|
||||
const { drivers, teams } = hub
|
||||
const leader = drivers[0]
|
||||
const remaining = hub.rounds_left * 25
|
||||
|
||||
const enriched = useMemo<EnrichedDriver[]>(
|
||||
() =>
|
||||
drivers.map((d, i) => {
|
||||
const gapLeaderNum = leader.points - d.points
|
||||
const gapAheadNum = i === 0 ? null : drivers[i - 1].points - d.points
|
||||
const alive = i === 0 || gapLeaderNum <= remaining
|
||||
return {
|
||||
d,
|
||||
pos: d.position,
|
||||
color: teamColor(d.team_colour),
|
||||
gapLeader: i === 0 ? 'LEADER' : `+${fmtPts(gapLeaderNum)}`,
|
||||
gapAhead: gapAheadNum == null ? '—' : `+${fmtPts(gapAheadNum)}`,
|
||||
gapAheadNum,
|
||||
driverAhead: i === 0 ? null : drivers[i - 1].name_acronym,
|
||||
spark: sparkPoints(d.form),
|
||||
h2h: `${d.teammate_wins}–${d.teammate_losses}`,
|
||||
h2hWin: d.teammate_wins >= d.teammate_losses,
|
||||
aliveLabel: i === 0 ? 'LEADS' : alive ? 'ALIVE' : 'OUT',
|
||||
aliveColor: i === 0 ? GOLD : alive ? 'var(--green)' : 'var(--text-3)',
|
||||
}
|
||||
}),
|
||||
[drivers, leader, remaining],
|
||||
)
|
||||
|
||||
const aliveCount = enriched.filter((e) => e.aliveLabel === 'ALIVE' || e.aliveLabel === 'LEADS').length
|
||||
|
||||
const titleMath =
|
||||
`${aliveCount} driver${aliveCount === 1 ? '' : 's'} can still mathematically win the title. ` +
|
||||
`With ${hub.rounds_left} round${hub.rounds_left === 1 ? '' : 's'} left (max ${remaining} pts), ` +
|
||||
`${leader.name_acronym} leads ` +
|
||||
(drivers[1] ? `${drivers[1].name_acronym} by ${fmtPts(leader.points - drivers[1].points)}` : 'the field') +
|
||||
(drivers[2] ? ` and ${drivers[2].name_acronym} by ${fmtPts(leader.points - drivers[2].points)}.` : '.')
|
||||
|
||||
const topTeam = teams[0]
|
||||
const teamGap = teams[1] ? topTeam.points - teams[1].points : 0
|
||||
const seasonPct = hub.total_rounds > 0 ? Math.round((hub.round / hub.total_rounds) * 100) : 0
|
||||
|
||||
const statRail = [
|
||||
{ label: 'Drivers Leader', value: leader.name_acronym, sub: `${fmtPts(leader.points)} pts · ${leader.wins} wins`, color: '#fff' },
|
||||
{
|
||||
label: 'Constructors Leader',
|
||||
value: topTeam?.team_name ?? '—',
|
||||
sub: teams[1] ? `+${fmtPts(teamGap)} ahead` : 'Sole entry',
|
||||
color: '#fff',
|
||||
},
|
||||
{ label: 'Title Fight', value: `${aliveCount} alive`, sub: `${hub.rounds_left} rounds remain`, color: 'var(--red)' },
|
||||
{ label: 'Season Progress', value: `${seasonPct}%`, sub: `Round ${hub.round}/${hub.total_rounds}`, color: '#fff' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="champ-page" data-testid="championship">
|
||||
<div className="champ-header">
|
||||
<div className="champ-title-row">
|
||||
<span className="champ-accent" aria-hidden="true" />
|
||||
<h1 className="champ-title">Championship</h1>
|
||||
<span className="champ-season mono">{hub.season}</span>
|
||||
</div>
|
||||
<div className="champ-sub">
|
||||
{hub.last_race ? `After ${hub.last_race} · ` : ''}Round {hub.round} of {hub.total_rounds}
|
||||
</div>
|
||||
<div className="champ-tabs" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
className={`champ-tab${view === 'drivers' ? ' is-active' : ''}`}
|
||||
onClick={() => setView('drivers')}
|
||||
data-testid="champ-tab-drivers"
|
||||
>
|
||||
Drivers
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`champ-tab${view === 'constructors' ? ' is-active' : ''}`}
|
||||
onClick={() => setView('constructors')}
|
||||
data-testid="champ-tab-constructors"
|
||||
>
|
||||
Constructors
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`champ-tab${view === 'progression' ? ' is-active' : ''}`}
|
||||
onClick={() => setView('progression')}
|
||||
data-testid="champ-tab-progression"
|
||||
>
|
||||
Progression
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`champ-tab${view === 'rivalry' ? ' is-active' : ''}`}
|
||||
onClick={() => setView('rivalry')}
|
||||
data-testid="champ-tab-rivalry"
|
||||
>
|
||||
Rivalry
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`champ-tab${view === 'simulator' ? ' is-active' : ''}`}
|
||||
onClick={() => setView('simulator')}
|
||||
data-testid="champ-tab-simulator"
|
||||
>
|
||||
Simulator
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="champ-stat-rail">
|
||||
{statRail.map((stat) => (
|
||||
<div className="champ-stat" key={stat.label}>
|
||||
<div className="champ-stat-label mono">{stat.label}</div>
|
||||
<div className="champ-stat-value mono" style={{ color: stat.color }}>
|
||||
{stat.value}
|
||||
</div>
|
||||
<div className="champ-stat-sub">{stat.sub}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{view === 'drivers' && (
|
||||
<DriversView
|
||||
enriched={enriched}
|
||||
leaderPoints={leader.points}
|
||||
titleMath={titleMath}
|
||||
roundsLeft={hub.rounds_left}
|
||||
drivers={drivers}
|
||||
season={hub.season}
|
||||
/>
|
||||
)}
|
||||
{view === 'constructors' && <ConstructorsView hub={hub} />}
|
||||
{view === 'progression' && <ProgressionView hub={hub} />}
|
||||
{view === 'rivalry' && <RivalryCompare hub={hub} />}
|
||||
{view === 'simulator' && <ChampionshipSimulator hub={hub} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface EnrichedDriver {
|
||||
d: ChampHubDriver
|
||||
pos: number
|
||||
color: string
|
||||
gapLeader: string
|
||||
gapAhead: string
|
||||
gapAheadNum: number | null
|
||||
driverAhead: string | null
|
||||
spark: string
|
||||
h2h: string
|
||||
h2hWin: boolean
|
||||
aliveLabel: string
|
||||
aliveColor: string
|
||||
}
|
||||
|
||||
function DriversView({
|
||||
enriched,
|
||||
leaderPoints,
|
||||
titleMath,
|
||||
roundsLeft,
|
||||
drivers,
|
||||
season,
|
||||
}: {
|
||||
enriched: EnrichedDriver[]
|
||||
leaderPoints: number
|
||||
titleMath: string
|
||||
roundsLeft: number
|
||||
drivers: ChampHubDriver[]
|
||||
season: number
|
||||
}) {
|
||||
const podium = enriched.slice(0, 3)
|
||||
const h2hPairs = useMemo(() => teammatePairs(drivers), [drivers])
|
||||
|
||||
return (
|
||||
<div data-testid="champ-view-drivers">
|
||||
<div className="champ-podium">
|
||||
{podium.map((e) => (
|
||||
<div
|
||||
className="champ-podium-card"
|
||||
key={e.d.driver_number}
|
||||
style={{ borderTopColor: e.color }}
|
||||
>
|
||||
<span className="champ-podium-ghost mono" style={{ color: ghostColor(e.pos) }}>
|
||||
P{e.pos}
|
||||
</span>
|
||||
<div className="champ-podium-inner">
|
||||
<div className="champ-podium-top">
|
||||
<span className="mono" style={{ color: medalColor(e.pos), fontWeight: 700 }}>
|
||||
P{e.pos}
|
||||
</span>
|
||||
<span className="champ-podium-team mono">{e.d.team_name}</span>
|
||||
</div>
|
||||
<div className="champ-podium-id">
|
||||
<span className="champ-podium-bar" style={{ background: e.color }} />
|
||||
<span className="champ-podium-code mono">{e.d.name_acronym}</span>
|
||||
</div>
|
||||
<div className="champ-podium-name">{e.d.full_name}</div>
|
||||
<div className="champ-podium-pts">
|
||||
<span className="champ-podium-pts-num mono">{fmtPts(e.d.points)}</span>
|
||||
<span className="champ-podium-pts-unit">PTS</span>
|
||||
<span
|
||||
className="champ-podium-gap mono"
|
||||
style={{ color: e.pos === 1 ? GOLD : 'var(--text-2)' }}
|
||||
>
|
||||
{e.pos === 1 ? 'P1' : `+${fmtPts(leaderPoints - e.d.points)}`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="champ-podium-stats">
|
||||
<div>
|
||||
<div className="champ-podium-stat-num mono">{e.d.wins}</div>
|
||||
<div className="champ-podium-stat-label">Wins</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="champ-podium-stat-num mono">{e.d.podiums}</div>
|
||||
<div className="champ-podium-stat-label">Podiums</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="champ-podium-stat-num mono">{e.d.poles}</div>
|
||||
<div className="champ-podium-stat-label">Poles</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="champ-titlemath" data-testid="champ-titlemath">
|
||||
<span className="champ-titlemath-tag mono">Title Math</span>
|
||||
<span className="champ-titlemath-text">{titleMath}</span>
|
||||
</div>
|
||||
|
||||
{h2hPairs.length > 0 && (
|
||||
<section className="h2h-section" data-testid="champ-teammate-battles">
|
||||
<div className="h2h-section-head">
|
||||
<h2 className="h2h-section-title">Teammate battles</h2>
|
||||
<span className="h2h-section-sub">race finishes · closest first</span>
|
||||
</div>
|
||||
<div className="h2h-list">
|
||||
{h2hPairs.map((pair) => (
|
||||
<TeammateH2H
|
||||
key={pair.teamName}
|
||||
teamName={pair.teamName}
|
||||
teamColour={pair.teamColour}
|
||||
driverATla={pair.driverA.name_acronym}
|
||||
driverBTla={pair.driverB.name_acronym}
|
||||
winsA={pair.driverA.teammate_wins}
|
||||
winsB={pair.driverB.teammate_wins}
|
||||
extraNote={pair.extraCount > 0 ? `+${pair.extraCount}` : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<div className="champ-scroll">
|
||||
<table className="champ-table champ-table-drivers">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="l">Pos</th>
|
||||
<th className="l">Driver</th>
|
||||
<th className="l">Team</th>
|
||||
<th className="r">Pts</th>
|
||||
<th className="r">Gap</th>
|
||||
<th className="r">Int</th>
|
||||
<th className="c">Wins</th>
|
||||
<th className="c">Pod</th>
|
||||
<th className="l">Form</th>
|
||||
<th className="c">vs Teammate</th>
|
||||
<th className="r">Title</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{enriched.map((e) => (
|
||||
<tr key={e.d.driver_number}>
|
||||
<td className="mono" style={{ color: medalColor(e.pos), fontWeight: 700 }}>
|
||||
P{e.pos}
|
||||
</td>
|
||||
<td>
|
||||
<Link
|
||||
to="/drivers/$driverNumber"
|
||||
params={{ driverNumber: String(e.d.driver_number) }}
|
||||
search={{ year: season }}
|
||||
className="champ-drv"
|
||||
style={{ color: 'inherit', textDecoration: 'none' }}
|
||||
data-testid={`champ-driver-link-${e.d.driver_number}`}
|
||||
>
|
||||
<span className="champ-drv-bar" style={{ background: e.color }} />
|
||||
<span className="champ-drv-code mono">{e.d.name_acronym}</span>
|
||||
<span className="champ-drv-name">{e.d.full_name}</span>
|
||||
<span className="champ-drv-num mono">#{e.d.driver_number}</span>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="champ-td-team">{e.d.team_name}</td>
|
||||
<td className="r mono champ-td-pts">{fmtPts(e.d.points)}</td>
|
||||
<td className="r mono champ-td-muted">{e.gapLeader}</td>
|
||||
<td className="r mono champ-td-dim">
|
||||
{(() => {
|
||||
const gapAnnotation = pointsGapMeaning(e.gapAheadNum, roundsLeft, e.driverAhead)
|
||||
return (
|
||||
<Meaning
|
||||
value={e.gapAhead}
|
||||
meaning={gapAnnotation?.caption}
|
||||
title={gapAnnotation?.title}
|
||||
tone={gapAnnotation?.tone}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
</td>
|
||||
<td className="c mono" style={{ color: e.d.wins > 0 ? 'var(--text)' : 'var(--text-3)' }}>
|
||||
{e.d.wins}
|
||||
</td>
|
||||
<td className="c mono champ-td-muted">{e.d.podiums}</td>
|
||||
<td>
|
||||
{e.spark ? (
|
||||
<svg width="62" height="20" viewBox="0 0 62 20" className="champ-spark">
|
||||
<polyline
|
||||
points={e.spark}
|
||||
fill="none"
|
||||
stroke={e.color}
|
||||
strokeWidth="1.5"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
opacity="0.9"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<span className="champ-td-dim mono">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="c mono" style={{ color: e.h2hWin ? 'var(--green)' : 'var(--text-2)' }}>
|
||||
{e.h2h}
|
||||
</td>
|
||||
<td className="r">
|
||||
<span className="champ-alive mono" style={{ color: e.aliveColor }}>
|
||||
{e.aliveLabel}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ConstructorsView({ hub }: { hub: ChampionshipHub }) {
|
||||
const { teams, drivers } = hub
|
||||
const leaderPts = teams[0]?.points ?? 0
|
||||
const podium = teams.slice(0, 3)
|
||||
|
||||
return (
|
||||
<div data-testid="champ-view-constructors">
|
||||
<div className="champ-podium">
|
||||
{podium.map((t) => {
|
||||
const color = teamColor(t.team_colour)
|
||||
const split = teamSplit(t.team_name, drivers)
|
||||
return (
|
||||
<div className="champ-podium-card" key={t.team_name} style={{ borderTopColor: color }}>
|
||||
<span className="champ-podium-ghost mono" style={{ color: ghostColor(t.position) }}>
|
||||
P{t.position}
|
||||
</span>
|
||||
<div className="champ-podium-inner">
|
||||
<div className="champ-podium-top">
|
||||
<span className="mono" style={{ color: medalColor(t.position), fontWeight: 700 }}>
|
||||
P{t.position}
|
||||
</span>
|
||||
</div>
|
||||
<div className="champ-podium-id">
|
||||
<span className="champ-podium-bar" style={{ background: color }} />
|
||||
<span className="champ-podium-team-name">{t.team_name}</span>
|
||||
</div>
|
||||
<div className="champ-podium-pts">
|
||||
<span className="champ-podium-pts-num mono">{fmtPts(t.points)}</span>
|
||||
<span className="champ-podium-pts-unit">PTS</span>
|
||||
<span
|
||||
className="champ-podium-gap mono"
|
||||
style={{ color: t.position === 1 ? GOLD : 'var(--text-2)' }}
|
||||
>
|
||||
{t.position === 1 ? 'P1' : `+${fmtPts(leaderPts - t.points)}`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="champ-contrib">
|
||||
<div className="champ-contrib-bar">
|
||||
<span style={{ width: `${split.splitA}%`, background: color }} />
|
||||
<span style={{ width: `${split.splitB}%`, background: color, opacity: 0.4 }} />
|
||||
</div>
|
||||
<div className="champ-contrib-legend mono">
|
||||
<span>
|
||||
{split.driverA} <em>{fmtPts(split.ptsA)}</em>
|
||||
</span>
|
||||
<span>
|
||||
{split.driverB} <em>{fmtPts(split.ptsB)}</em>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="champ-scroll">
|
||||
<table className="champ-table champ-table-teams">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="l">Pos</th>
|
||||
<th className="l">Constructor</th>
|
||||
<th className="r">Pts</th>
|
||||
<th className="r">Gap</th>
|
||||
<th className="c">Wins</th>
|
||||
<th className="l">Driver Contribution</th>
|
||||
<th className="r">Share</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{teams.map((t) => {
|
||||
const color = teamColor(t.team_colour)
|
||||
const split = teamSplit(t.team_name, drivers)
|
||||
return (
|
||||
<tr key={t.team_name}>
|
||||
<td className="mono" style={{ color: medalColor(t.position), fontWeight: 700 }}>
|
||||
P{t.position}
|
||||
</td>
|
||||
<td>
|
||||
<div className="champ-drv">
|
||||
<span className="champ-drv-bar" style={{ background: color }} />
|
||||
<span className="champ-team-name">{t.team_name}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="r mono champ-td-pts">{fmtPts(t.points)}</td>
|
||||
<td className="r mono champ-td-muted">
|
||||
{t.position === 1 ? 'LEADER' : `+${fmtPts(leaderPts - t.points)}`}
|
||||
</td>
|
||||
<td className="c mono" style={{ color: t.wins > 0 ? 'var(--text)' : 'var(--text-3)' }}>
|
||||
{t.wins}
|
||||
</td>
|
||||
<td>
|
||||
<div className="champ-contrib-row">
|
||||
<div className="champ-contrib-bar">
|
||||
<span style={{ width: `${split.splitA}%`, background: color }} />
|
||||
<span style={{ width: `${split.splitB}%`, background: color, opacity: 0.4 }} />
|
||||
</div>
|
||||
<span className="champ-contrib-names mono">
|
||||
{split.driverA}
|
||||
<em> · </em>
|
||||
{split.driverB}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="r mono champ-td-dim">{split.shareLabel}</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const CHART_PAD_L = 48
|
||||
const CHART_PAD_T = 16
|
||||
const CHART_PLOT_W = 882
|
||||
const CHART_PLOT_H = 316
|
||||
|
||||
function ProgressionView({ hub }: { hub: ChampionshipHub }) {
|
||||
const top = hub.drivers.slice(0, 6).filter((d) => d.cumulative.length > 0)
|
||||
|
||||
if (top.length === 0) {
|
||||
return (
|
||||
<div className="champ-chart-empty" data-testid="champ-view-progression">
|
||||
No completed rounds yet — progression will appear after the first race.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const N = Math.max(...top.map((d) => d.cumulative.length))
|
||||
const peak = Math.max(...top.flatMap((d) => d.cumulative))
|
||||
const maxY = Math.max(100, Math.ceil(peak / 100) * 100)
|
||||
|
||||
const x = (i: number) => (N <= 1 ? CHART_PAD_L : CHART_PAD_L + (i * CHART_PLOT_W) / (N - 1))
|
||||
const y = (v: number) => CHART_PAD_T + CHART_PLOT_H - (v / maxY) * CHART_PLOT_H
|
||||
|
||||
const yGrid = [0, 0.25, 0.5, 0.75, 1].map((f) => {
|
||||
const value = Math.round(maxY * f)
|
||||
const yy = y(value)
|
||||
return { y: yy, label: value }
|
||||
})
|
||||
|
||||
// x ticks: up to ~7 evenly spaced round labels.
|
||||
const tickStep = Math.max(1, Math.ceil(N / 7))
|
||||
const xGrid: { x: number; label: string }[] = []
|
||||
for (let i = 0; i < N; i += tickStep) {
|
||||
xGrid.push({ x: x(i), label: hub.round_labels[i] ?? `R${i + 1}` })
|
||||
}
|
||||
if (xGrid[xGrid.length - 1]?.label !== (hub.round_labels[N - 1] ?? `R${N}`)) {
|
||||
xGrid.push({ x: x(N - 1), label: hub.round_labels[N - 1] ?? `R${N}` })
|
||||
}
|
||||
|
||||
const seenTeams = new Set<string>()
|
||||
const series = top.map((d, idx) => {
|
||||
const dashed = seenTeams.has(d.team_name)
|
||||
seenTeams.add(d.team_name)
|
||||
const pts = d.cumulative.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ')
|
||||
const endVal = d.cumulative[d.cumulative.length - 1]
|
||||
const endX = x(d.cumulative.length - 1)
|
||||
const endY = y(endVal)
|
||||
return {
|
||||
code: d.name_acronym,
|
||||
name: d.full_name,
|
||||
total: d.points,
|
||||
color: teamColor(d.team_colour),
|
||||
width: idx < 3 ? 2.4 : 1.8,
|
||||
dash: dashed ? '5 4' : '0',
|
||||
points: pts,
|
||||
endX,
|
||||
endY,
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="champ-progression" data-testid="champ-view-progression">
|
||||
<div className="champ-chart-head">
|
||||
<span className="champ-chart-title mono">Cumulative points — top {top.length} drivers</span>
|
||||
<span className="champ-chart-meta">
|
||||
Rounds 1–{hub.round} · {hub.season}
|
||||
</span>
|
||||
</div>
|
||||
<div className="champ-chart">
|
||||
<svg viewBox="0 0 1000 380" className="champ-chart-svg" preserveAspectRatio="none">
|
||||
{yGrid.map((g) => (
|
||||
<g key={g.label}>
|
||||
<line x1={CHART_PAD_L} y1={g.y} x2={930} y2={g.y} stroke="var(--border)" strokeWidth="1" />
|
||||
<text x={40} y={g.y + 4} textAnchor="end" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{xGrid.map((g, i) => (
|
||||
<text key={i} x={g.x} y={372} textAnchor="middle" className="champ-chart-axis">
|
||||
{g.label}
|
||||
</text>
|
||||
))}
|
||||
{series.map((s) => (
|
||||
<g key={s.code}>
|
||||
<polyline
|
||||
points={s.points}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
strokeWidth={s.width}
|
||||
strokeDasharray={s.dash}
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<circle cx={s.endX} cy={s.endY} r="3" fill={s.color} />
|
||||
<text x={s.endX + 8} y={s.endY + 4} fill={s.color} className="champ-chart-label">
|
||||
{s.code}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
<div className="champ-legend">
|
||||
{series.map((s) => (
|
||||
<div className="champ-legend-item" key={s.code}>
|
||||
<span className="champ-legend-swatch" style={{ background: s.color }} />
|
||||
<span className="champ-legend-code mono">{s.code}</span>
|
||||
<span className="champ-legend-name">{s.name}</span>
|
||||
<span className="champ-legend-total mono">{fmtPts(s.total)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||