fix(training): keep the driver's page self-contained so it loads through the club router (1.87.1)

This commit is contained in:
larssand committed 2026-11-09 23:06:26 +01:00
1 parent 0caf50254a
commit ee290a4ab8
6 files changed
+122 -7

No files matched your search

+6
View File
@@ -8,6 +8,12 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.87.1
### Fixed
- **The driver's page only spun when opened from the internet** (through the club router) since 1.86.0: it loaded an extra file that the router does not publish. The page is one self-contained file again, and a test now stops it from loading other files.
## 1.87.0
### Added
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.87.0",
"version": "1.87.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.87.0",
"version": "1.87.1",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.87.0",
"version": "1.87.1",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+91 -2
View File
@@ -1,5 +1,3 @@
import { renderStintLapCards, openStintLapCardIds } from "./stint_laps_view.js";
const root = document.getElementById("publicTrainingRoot");
const shareToken = decodeURIComponent(window.location.pathname.split("/").filter(Boolean).at(-1) || "");
const requestedLanguage = new URLSearchParams(window.location.search).get("lang");
@@ -1492,9 +1490,100 @@ async function loadProfile(background = false) {
}
}
// ---- Stint cards: a copy of src/stint_laps_view.js (keep the two in step). ----
// This page must stay one self-contained file: the club router's nginx publishes only
// public_training.js/.css to the internet (scripts/teltonika/), so an import is a 404 and
// the page never loads. tests/stint_laps_view.test.js checks the copy matches.
const STINT_MAX_LAPS_SHOWN = 300;
// laps: [{ lapMs, excluded }] in driving order. excluded = the lap that opened the stint
// after a break (it counts as a lap but not for pace). Slow = over 15% above the median,
// the same "mistake" line the stint analysis uses.
// dayBestMs: the fastest lap that day over every stint - shown purple, as in timing apps.
function buildStintLapRows(laps, { dayBestMs = 0 } = {}) {
const list = (Array.isArray(laps) ? laps : [])
.map((lap) => ({ lapMs: Math.round(Number(lap?.lapMs || 0)), excluded: Boolean(lap?.excluded) }))
.filter((lap) => lap.lapMs > 0)
.slice(0, STINT_MAX_LAPS_SHOWN);
const values = list.filter((lap) => !lap.excluded).map((lap) => lap.lapMs).sort((a, b) => a - b);
const bestMs = values[0] || 0;
const medianMs = values.length ? values[Math.floor((values.length - 1) / 2)] : 0;
return list.map((lap, index) => ({
number: index + 1,
lapMs: lap.lapMs,
excluded: lap.excluded,
best: Boolean(bestMs && !lap.excluded && lap.lapMs === bestMs),
dayBest: Boolean(dayBestMs && !lap.excluded && lap.lapMs === dayBestMs),
slow: Boolean(medianMs && !lap.excluded && lap.lapMs > medianMs * 1.15),
deltaMs: bestMs && !lap.excluded ? lap.lapMs - bestMs : null,
// 1% slower = 5% shorter bar, so a few tenths show; 18% or more bottoms out.
barPct: bestMs && !lap.excluded ? Math.max(8, Math.round(100 - ((lap.lapMs - bestMs) / bestMs) * 500)) : 0,
}));
}
// stints: [{ id, number, startedAt, lapCount, bestLapMs, averageLapMs, durationMs, laps }]
// labels: { stint, laps, best, average, duration, consistency, lap, excluded, empty }
// consistency = spread between the 10% and 90% laps as % of the average (lower = steadier).
// openIds: cards to keep open - both pages re-render as laps come in, which would
// otherwise fold every card shut (collect them with openStintLapCardIds first).
// allStints: every stint known (not just the ones shown), for the day's fastest lap.
function renderStintLapCards(stints, { formatLap, formatDuration, escapeHtml, labels, locale, openIds = new Set(), allStints = stints } = {}) {
const items = Array.isArray(stints) ? stints.filter((stint) => Array.isArray(stint?.laps) && stint.laps.length) : [];
if (!items.length) return `<p class="stint-laps-empty">${escapeHtml(labels.empty)}</p>`;
const dayBests = buildDayBests(allStints);
return `<div class="stint-laps">${items.map((stint) => {
const dayBestMs = dayBests.get(dayKey(stint.startedAt)) || 0;
const rows = buildStintLapRows(stint.laps, { dayBestMs });
const started = new Date(Number(stint.startedAt || 0)).toLocaleString(locale, { dateStyle: "short", timeStyle: "short" });
const lapItems = rows.map((row) => `
<li class="stint-lap${row.dayBest ? " is-day-best" : row.best ? " is-best" : ""}${row.slow ? " is-slow" : ""}${row.excluded ? " is-excluded" : ""}">
<span class="stint-lap-no">${row.number}</span>
<span class="stint-lap-time">${escapeHtml(formatLap(row.lapMs))}</span>
<span class="stint-lap-bar"><i style="width:${row.barPct}%"></i></span>
<span class="stint-lap-delta">${row.excluded ? escapeHtml(labels.excluded) : row.best || row.dayBest ? "★" : `+${(row.deltaMs / 1000).toFixed(3)}`}</span>
</li>`).join("");
const id = String(stint.id ?? stint.startedAt ?? stint.number);
return `
<details class="stint-laps-card" data-stint-id="${escapeHtml(id)}"${openIds.has(id) ? " open" : ""}>
<summary>
<span class="stint-laps-head"><strong>${escapeHtml(labels.stint)} ${Number(stint.number || 0)}</strong><small>${escapeHtml(started)}</small></span>
<span class="stint-laps-stats"><span><small>${escapeHtml(labels.laps)}</small>${Number(stint.lapCount || rows.length)}</span>
<span class="${dayBestMs && Number(stint.bestLapMs) === dayBestMs ? "is-day-best" : "is-best"}"><small>${escapeHtml(labels.best)}</small>${escapeHtml(formatLap(stint.bestLapMs))}</span>
<span><small>${escapeHtml(labels.average)}</small>${escapeHtml(formatLap(stint.averageLapMs))}</span>
<span><small>${escapeHtml(labels.duration)}</small>${escapeHtml(formatDuration(stint.durationMs))}</span>
<span><small>${escapeHtml(labels.consistency)}</small>${stint.consistencyPct == null ? "-" : `${Number(stint.consistencyPct).toFixed(1)}%`}</span></span>
</summary>
<ol class="stint-lap-list" aria-label="${escapeHtml(labels.lap)}">${lapItems}</ol>
</details>`;
}).join("")}</div>`;
}
function openStintLapCardIds(container) {
return new Set([...(container?.querySelectorAll?.(".stint-laps-card[open]") || [])].map((card) => card.dataset.stintId));
}
function dayKey(timestamp) {
const date = new Date(Number(timestamp || 0));
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
function buildDayBests(stints) {
const bests = new Map();
(Array.isArray(stints) ? stints : []).forEach((stint) => {
const key = dayKey(stint?.startedAt);
(stint?.laps || []).forEach((lap) => {
const lapMs = Math.round(Number(lap?.lapMs || 0));
if (lapMs > 0 && !lap.excluded && (!bests.has(key) || lapMs < bests.get(key))) bests.set(key, lapMs);
});
});
return bests;
}
// ---- end of copy ----
loadProfile();
document.getElementById("publicTrainingRetry")?.addEventListener("click", () => loadProfile(true));
setInterval(updateProfileConnectionStatus, 1000);
setInterval(() => {
if (!document.hidden) loadProfile(true);
}, 10000);
+1 -2
View File
@@ -3,8 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import vm from "node:vm";
// The page is an ES module; drop its imports to run it as a plain script (rendering is stubbed below).
const source = fs.readFileSync(new URL("../src/public_training.js", import.meta.url), "utf8").replace(/^import .*$/gm, "");
const source = fs.readFileSync(new URL("../src/public_training.js", import.meta.url), "utf8");
function profileHarness() {
const ui = { editing: false, saving: false, requests: 0, renders: 0, html: "existing profile" };
+21
View File
@@ -1,5 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import vm from "node:vm";
import { buildStintLapRows, renderStintLapCards } from "../src/stint_laps_view.js";
import { buildTrainingStintAnalysis } from "../src/training_logic.js";
@@ -48,3 +50,22 @@ test("the day's fastest lap is purple, over every stint that day", () => {
assert.equal((both.match(/class="stint-lap is-day-best"/g) || []).length, 1);
assert.equal(buildStintLapRows([{ lapMs: 13100 }], { dayBestMs: 13100 })[0].dayBest, true);
});
// The driver's page goes to the internet through the club router, whose nginx publishes only
// public_training.js/.css - an import from it is a 404 and the page spins forever. So it
// carries its own copy of the stint cards, which must render exactly like the module.
test("the driver's page imports nothing and its stint-card copy matches the module", () => {
const source = fs.readFileSync(new URL("../src/public_training.js", import.meta.url), "utf8");
assert.doesNotMatch(source, /^\s*import\b|\bimport\(/m, "public_training.js must stay one self-contained file");
const copy = source.slice(source.indexOf("// ---- Stint cards: a copy"), source.indexOf("// ---- end of copy ----"));
const context = vm.createContext({});
vm.runInContext(`${copy}\nthis.render = renderStintLapCards; this.rows = buildStintLapRows;`, context);
const day = new Date(2026, 10, 9, 18).getTime();
const stints = [
{ id: "a", number: 1, startedAt: day, lapCount: 3, bestLapMs: 13300, averageLapMs: 13500, durationMs: 40000, consistencyPct: 2.5, laps: [{ lapMs: 150000, excluded: true }, { lapMs: 13500 }, { lapMs: 13300 }, { lapMs: 16000 }] },
{ id: "b", number: 2, startedAt: day + 3600000, lapCount: 2, bestLapMs: 13100, averageLapMs: 13250, durationMs: 26500, consistencyPct: null, laps: [{ lapMs: 13100 }, { lapMs: 13400 }] },
];
const options = { formatLap: fmt, formatDuration: fmt, escapeHtml, labels: { ...labels, consistency: "Jämnhet" }, openIds: new Set(["b"]) };
assert.equal(context.render(stints, options), renderStintLapCards(stints, options));
assert.equal(JSON.stringify(context.rows(stints[0].laps, { dayBestMs: 13100 })), JSON.stringify(buildStintLapRows(stints[0].laps, { dayBestMs: 13100 })));
});