feat(practice): open practice settings with ranking by best N in a row or best X minutes (1.68.0)

This commit is contained in:
larssand committed 2026-11-05 22:38:33 +01:00
1 parent 8a8b2417fd
commit a7d2d0b9ae
11 files changed
+243 -7

No files matched your search

+4
View File
@@ -8,6 +8,10 @@ The application version is maintained in `package.json` and displayed in the adm
No changes recorded yet.
## 1.68.0
- Open Practice settings: the Open Practice row in Events has "Settings" (it was "Edit", with only name and date) with the lap window (shortest and longest lap) and the ranking: best lap (as before), best N laps in a row (e.g. 3), or best X minutes (most laps inside X minutes, then the shorter time - e.g. 5 min). The timing list, the overlay, Race Day and the results show the chosen result ("3 laps 52.341", "17 laps / 5:00.3"), the best lap stays in its own column. Laps only count as "in a row" within one run: a stop in the pits starts a new one.
## 1.67.2
- Events → Manage: the easy setup comes first (sponsor setup, or the race steps and tabs), then the list of heats. Adding a heat by hand (type, start, seeding method ...) is folded away under "Add a heat by hand (advanced)", and branding is folded at the bottom.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.67.2",
"version": "1.68.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.67.2",
"version": "1.68.0",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.67.2",
"version": "1.68.0",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+26
View File
@@ -2848,6 +2848,17 @@ const TRANSLATIONS = {
"race_overview.phase_practice": "Träning",
"race_overview.phase_qualification": "Kval",
"race_overview.phase_final": "Finaler",
"practice_rank.settings": "Inställningar",
"practice_rank.min_lap": "Kortaste varv (s)",
"practice_rank.max_lap": "Längsta varv (s)",
"practice_rank.ranking": "Rankning",
"practice_rank.ranking_hint": "Hur listan sorteras – i tidtagningen, overlayn och resultaten.",
"practice_rank.mode_best_lap": "Bästa varv",
"practice_rank.mode_consecutive": "Bästa N varv i följd",
"practice_rank.mode_window": "Bästa X minuter (flest varv)",
"practice_rank.laps": "N varv i följd",
"practice_rank.minutes": "X minuter",
"practice_rank.laps_n": "{n} varv",
"team_setup.title": "Lagrace",
"team_setup.intro": "Dela in förarna i lag, välj lagets bil (eller förarnas egna transpondrar) och racets längd. Start, paus och stopp sköts från Race Day.",
"team_setup.step_teams": "1. Lag och förare",
@@ -4923,6 +4934,17 @@ const TRANSLATIONS = {
"race_overview.phase_practice": "Practice",
"race_overview.phase_qualification": "Qualifying",
"race_overview.phase_final": "Finals",
"practice_rank.settings": "Settings",
"practice_rank.min_lap": "Shortest lap (s)",
"practice_rank.max_lap": "Longest lap (s)",
"practice_rank.ranking": "Ranking",
"practice_rank.ranking_hint": "How the list is sorted – in timing, the overlay and the results.",
"practice_rank.mode_best_lap": "Best lap",
"practice_rank.mode_consecutive": "Best N laps in a row",
"practice_rank.mode_window": "Best X minutes (most laps)",
"practice_rank.laps": "N laps in a row",
"practice_rank.minutes": "X minutes",
"practice_rank.laps_n": "{n} laps",
"team_setup.title": "Team race",
"team_setup.intro": "Split the drivers into teams, pick each team's car (or the drivers' own transponders) and the race length. Start, pause and stop from Race Day.",
"team_setup.step_teams": "1. Teams and drivers",
@@ -5413,6 +5435,10 @@ function normalizeSession(session = {}) {
startMode: normalizeStartMode(session?.startMode || "mass"),
seedBestLapCount: Math.max(0, Number(session?.seedBestLapCount || 0) || 0),
seedMethod,
// Open / free practice ranking (timing_logic getPracticeRankMetric): best lap, N in a row, best X min.
practiceRanking: ["consecutive", "window"].includes(String(session?.practiceRanking || "")) ? String(session.practiceRanking) : "best_lap",
practiceRankLaps: Math.max(2, Math.min(50, Math.round(Number(session?.practiceRankLaps) || 3))),
practiceRankMin: Math.max(1, Math.min(120, Math.round(Number(session?.practiceRankMin) || 5))),
staggerGapSec: Math.max(0, Number(session?.staggerGapSec || 0) || 0),
maxCars: session?.maxCars ? Math.max(1, Number(session.maxCars) || 1) : null,
mode: session?.mode === "track" ? "track" : "race",
+19 -2
View File
@@ -41,6 +41,23 @@ export function renderEventWorkspaceMarkup(mode, deps) {
: `<span class="event-progress">${escapeHtml(t("events.progress_next", { name: next }))}</span>`;
return `${status} <small class="hint">${escapeHtml(t("events.progress_count", { done, total }))}</small>`;
};
// Open practice settings (in the edit window): lap window and how the list is ranked.
const renderPracticeSettingsFields = (practiceEvent) => {
const session = state.sessions.find((item) => item.eventId === practiceEvent.id && ["open_practice", "free_practice"].includes(item.type)) || {};
const ranking = session.practiceRanking || "best_lap";
const sec = (ms) => (Number(ms) > 0 ? String(Math.round(Number(ms) / 100) / 10) : "");
return `
<label>${t("practice_rank.min_lap")}<input type="number" name="minLapSec" min="0" step="0.1" value="${sec(practiceEvent.raceConfig?.minLapMs)}" /></label>
<label>${t("practice_rank.max_lap")}<input type="number" name="maxLapSec" min="0" step="0.1" value="${sec(practiceEvent.raceConfig?.maxLapMs)}" /></label>
<label>${t("practice_rank.ranking")}
<select name="practiceRanking">
${["best_lap", "consecutive", "window"].map((mode) => `<option value="${mode}" ${mode === ranking ? "selected" : ""}>${t(`practice_rank.mode_${mode}`)}</option>`).join("")}
</select>
<small>${t("practice_rank.ranking_hint")}</small>
</label>
<label>${t("practice_rank.laps")}<input type="number" name="practiceRankLaps" min="2" max="50" step="1" value="${Number(session.practiceRankLaps) || 3}" /></label>
<label>${t("practice_rank.minutes")}<input type="number" name="practiceRankMin" min="1" max="120" step="1" value="${Number(session.practiceRankMin) || 5}" /></label>`;
};
const renderEventRow = ({ event: e, progress }) => `
<div class="event-row" data-event-row="${escapeHtml(e.id)}" data-search="${escapeHtml(`${e.name} ${e.date || ""} ${getClassName(e.classId) || ""}`.toLowerCase())}">
<div class="event-row-main">
@@ -52,7 +69,7 @@ export function renderEventWorkspaceMarkup(mode, deps) {
${e.raceConfig?.practiceOnly
? `<button id="event-timing-${e.id}" class="btn btn-primary">${t("events.open_timing")}</button>`
: `<button id="event-manage-${e.id}" class="btn btn-primary">${t("events.manage")}</button>`}
<button id="event-edit-${e.id}" class="btn">${t("events.edit")}</button>
<button id="event-edit-${e.id}" class="btn">${t(e.raceConfig?.practiceOnly ? "practice_rank.settings" : "events.edit")}</button>
<button id="event-delete-${e.id}" class="btn btn-danger" title="${escapeHtml(t("common.delete"))}">✕</button>
</div>
</div>`;
@@ -187,7 +204,7 @@ export function renderEventWorkspaceMarkup(mode, deps) {
</label>
${
editingEvent.raceConfig?.practiceOnly
? `<input type="hidden" name="classId" value="" />`
? `<input type="hidden" name="classId" value="" />${renderPracticeSettingsFields(editingEvent)}`
: `<label>
${t("events.field_class")}
<select name="classId">
+18
View File
@@ -377,6 +377,23 @@ export function renderEventWorkspaceView(context) {
setFormError("eventEditError", t("validation.invalid_selection"));
return;
}
// Open practice: lap window on the event, ranking on its practice session(s).
let practiceConfig = {};
if (editingEvent.raceConfig?.practiceOnly) {
const minLapMs = Math.round(Number(form.get("minLapSec") || 0) * 1000);
const maxLapMs = Math.round(Number(form.get("maxLapSec") || 0) * 1000);
if (minLapMs > 0 && maxLapMs > 0 && maxLapMs <= minLapMs) {
setFormError("eventEditError", t("race_day.lap_window_invalid"));
return;
}
practiceConfig = { minLapMs: Math.max(0, minLapMs), maxLapMs: Math.max(0, maxLapMs) };
state.sessions.forEach((session) => {
if (session.eventId !== editingEvent.id || !["open_practice", "free_practice"].includes(session.type)) return;
session.practiceRanking = String(form.get("practiceRanking") || "best_lap");
session.practiceRankLaps = Math.max(2, Math.min(50, Math.round(Number(form.get("practiceRankLaps")) || 3)));
session.practiceRankMin = Math.max(1, Math.min(120, Math.round(Number(form.get("practiceRankMin")) || 5)));
});
}
setFormError("eventEditError", "");
state.events = state.events.map((item) =>
item.id === editingEvent.id
@@ -385,6 +402,7 @@ export function renderEventWorkspaceView(context) {
name: cleanedName,
date: cleanedDate,
classId: cleanedClassId || item.classId,
...(item.raceConfig?.practiceOnly ? { raceConfig: { ...item.raceConfig, ...practiceConfig } } : {}),
})
: item
);
+81 -2
View File
@@ -232,6 +232,7 @@ export function buildLeaderboard(session, { ensureSessionResult, getSessionTarge
const isFreePractice = sessionType === "free_practice";
const isOpenPractice = sessionType === "open_practice";
const isRollingPractice = isFreePractice || isOpenPractice;
const usesPracticeRank = isRollingPractice && ["consecutive", "window"].includes(String(session.practiceRanking || ""));
const { maxLapMs } = getSessionLapWindow(session);
const nowTs = Date.now();
const rows = Object.values(result.competitors).map((row) => {
@@ -255,6 +256,7 @@ export function buildLeaderboard(session, { ensureSessionResult, getSessionTarge
const totalElapsedMs = Math.max(0, rawElapsedMs + manualTimeAdjustmentMs);
const distanceToTargetMs = Math.abs(targetMs - totalElapsedMs);
const seedMetric = getCompetitorSeedMetric(session, row);
const practiceMetric = isRollingPractice ? getPracticeRankMetric(session, passings) : null;
const previousLapMs = passings.length >= 2 ? Number(passings[passings.length - 2].lapMs || 0) : null;
const lastLapMs = latestPassing ? Number(latestPassing.lapMs || 0) : Number(row.lastLapMs || 0) || 0;
const bestLapMs = Number(row.bestLapMs || 0) || 0;
@@ -316,14 +318,24 @@ export function buildLeaderboard(session, { ensureSessionResult, getSessionTarge
invalidPending,
invalidLabel: invalidPending ? getPassingValidationLabel(latestAnyPassing) : "",
invalidLapMs: invalidPending ? Number(latestAnyPassing?.lapMs || 0) || 0 : 0,
practiceMetric,
comparisonMs:
isRollingPractice
isRollingPractice && usesPracticeRank
// Not enough laps in a row yet: after everyone who has, by best lap.
? practiceMetric ? practiceMetric.comparableMs : 1e15 + (bestLapMs || lastLapMs || 1e12)
: isRollingPractice
? bestLapMs || lastLapMs || Number.MAX_SAFE_INTEGER
: useSeedRanking && seedMetric
? seedMetric.comparableMs
: totalElapsedMs,
resultDisplay:
isRollingPractice
isRollingPractice && usesPracticeRank
? practiceMetric
? practiceMetric.mode === "window"
? `${t("practice_rank.laps_n", { n: practiceMetric.lapCount })} / ${formatRaceClock(practiceMetric.totalMs)}`
: `${t("practice_rank.laps_n", { n: practiceMetric.lapCount })} ${formatLap(practiceMetric.totalMs)}`
: "-"
: isRollingPractice
? formatLap(bestLapMs || lastLapMs)
: useSeedRanking && seedMetric
? formatSeedMetric(seedMetric)
@@ -369,6 +381,16 @@ export function buildLeaderboard(session, { ensureSessionResult, getSessionTarge
if (!leader) {
return { ...row, gap: "-", leaderGap: "-", gapAhead: "-", lapDelta: "-" };
}
if (usesPracticeRank) {
const self = row.key === leader.key;
return {
...row,
gap: self ? t("status.free_practice") : formatPracticeRankGap(row, leader),
leaderGap: self ? t("status.free_practice") : formatPracticeRankGap(row, leader),
gapAhead: index === 0 ? t("status.leader") : formatPracticeRankGap(row, rows[index - 1]),
lapDelta: formatLapDelta(row.lapDeltaMs),
};
}
return {
...row,
gap: formatLeaderboardGap(row, leader, { useSeedRanking, isFreePractice: isRollingPractice }),
@@ -460,6 +482,63 @@ export function getCompetitorPassings(session, row, options = {}, { ensureSessio
// Open / free practice ranking other than the best lap (session.practiceRanking):
// "consecutive" - the best N laps in a row (practiceRankLaps), as in a qualifying run;
// "window" - the best X minutes (practiceRankMin): most laps started and finished
// inside X minutes, then the shorter time.
// Practice runs all evening with breaks: laps only count as "in a row" within one run, so a
// lap after a stop in the pits (an uncounted passing between) starts a new run.
export function getPracticeRankMetric(session, passings) {
const mode = String(session?.practiceRanking || "");
if (!["consecutive", "window"].includes(mode)) return null;
const runs = [];
let run = [];
let previousTs = null;
(passings || []).forEach((passing) => {
const lapMs = Number(passing?.lapMs || 0);
const ts = Number(passing?.timestamp || 0);
const joined = previousTs !== null && lapMs > 500 && Math.abs(ts - previousTs - lapMs) <= 1500;
if (!joined && run.length) { runs.push(run); run = []; }
if (joined) run.push(lapMs);
previousTs = ts;
});
if (run.length) runs.push(run);
if (mode === "consecutive") {
const lapCount = Math.max(2, Math.min(50, Math.round(Number(session.practiceRankLaps) || 3)));
let best = null;
runs.forEach((laps) => {
for (let index = 0; index + lapCount <= laps.length; index += 1) {
const totalMs = laps.slice(index, index + lapCount).reduce((sum, lapMs) => sum + lapMs, 0);
if (!best || totalMs < best.totalMs) best = { totalMs };
}
});
return best ? { mode, lapCount, totalMs: best.totalMs, comparableMs: best.totalMs } : null;
}
const minutes = Math.max(1, Math.min(120, Math.round(Number(session.practiceRankMin) || 5)));
const windowMs = minutes * 60000;
let best = null;
runs.forEach((laps) => {
for (let start = 0; start < laps.length; start += 1) {
let totalMs = 0;
let end = start;
while (end < laps.length && totalMs + laps[end] <= windowMs) { totalMs += laps[end]; end += 1; }
const lapCount = end - start;
if (lapCount && (!best || lapCount > best.lapCount || (lapCount === best.lapCount && totalMs < best.totalMs))) best = { lapCount, totalMs };
}
});
// One number to sort on: more laps first, then less time (time < 1e8 ms).
return best ? { mode, minutes, lapCount: best.lapCount, totalMs: best.totalMs, comparableMs: (100000 - best.lapCount) * 1e8 + best.totalMs } : null;
}
// The gap to the row above / the leader for a practice ranked as above.
export function formatPracticeRankGap(row, reference) {
const own = row?.practiceMetric;
const ref = reference?.practiceMetric;
if (!own || !ref) return "-";
if (own.mode === "window" && ref.lapCount !== own.lapCount) return `+${Math.max(0, ref.lapCount - own.lapCount)}L`;
return `+${(Math.max(0, own.totalMs - ref.totalMs) / 1000).toFixed(3)}s`;
}
export function getCompetitorSeedMetric(session, row, { getCompetitorPassings }) {
const lapCount = Math.max(0, Number(session?.seedBestLapCount || 0) || 0);
if (lapCount <= 0) {
+54
View File
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
// Open practice settings (Events → Settings on an Open Practice row): the ranking chosen there
// re-sorts the list everywhere - here the overlay - and the setting is saved on the session.
export async function runPracticeRankingSmoke({ evaluate, navigate, savedState, waitFor, base }) {
const patchState = async (patch) => {
const current = await savedState();
Object.assign(current, patch);
const response = await fetch(base + "/api/state", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(current) });
assert.equal(response.ok, true);
};
const seeded = await savedState();
const event = { id: "rk_event", name: "RK Practice", classId: "", mode: "race", raceConfig: { practiceOnly: true } };
const startedAt = Date.now() - 600000;
const practice = { id: "rk_practice", eventId: event.id, name: "RK Open Practice", type: "open_practice", durationMin: 600, status: "running", startedAt };
// Fast: one quick lap, then slow. Steady: three even laps - better over 2 laps in a row.
const laps = (id, tp, lapTimes) => {
let ts = startedAt + 5000;
return [{ driverId: id, driverName: id, competitorKey: id, transponder: tp, lapMs: 0, timestamp: ts, validLap: true },
...lapTimes.map((lapMs) => { ts += lapMs; return { driverId: id, driverName: id, competitorKey: id, transponder: tp, lapMs, timestamp: ts, validLap: true }; })];
};
const competitor = (id, tp, lapTimes) => ({ key: id, driverId: id, driverName: id, transponder: tp, laps: lapTimes.length, bestLapMs: Math.min(...lapTimes), lastLapMs: lapTimes.at(-1), startTimestamp: startedAt });
await patchState({
drivers: [...seeded.drivers, { id: "RK Fast", name: "RK Fast", classId: "", transponder: "8440001" }, { id: "RK Steady", name: "RK Steady", classId: "", transponder: "8440002" }],
events: [...seeded.events, event],
sessions: [...seeded.sessions.map((session) => (["running", "paused"].includes(session.status) ? { ...session, status: "finished", endedAt: Date.now() } : session)), practice],
resultsBySession: {
...seeded.resultsBySession,
[practice.id]: {
passings: [...laps("RK Fast", "8440001", [17000, 25000, 25000]), ...laps("RK Steady", "8440002", [18000, 18000, 18000])].sort((a, b) => a.timestamp - b.timestamp),
competitors: { "RK Fast": competitor("RK Fast", "8440001", [17000, 25000, 25000]), "RK Steady": competitor("RK Steady", "8440002", [18000, 18000, 18000]) },
},
},
activeSessionId: practice.id,
});
const firstOnOverlay = () => evaluate(`document.querySelector("[data-overlay-competitor]")?.textContent || ""`);
await navigate("overlay", "overlayFullscreen");
await waitFor(async () => /RK Fast/.test(await firstOnOverlay()), "best lap ranks the one quick lap first");
await navigate("race_setup", "raceWizardStepForm");
await evaluate(`document.getElementById("event-edit-rk_event").click()`);
await waitFor(async () => evaluate(`Boolean(document.querySelector('#eventEditForm [name="practiceRanking"]'))`), "settings window with ranking");
await evaluate(`(() => { const form = document.getElementById("eventEditForm"); form.elements.date.value = "2026-01-01"; form.elements.practiceRanking.value = "consecutive"; form.elements.practiceRankLaps.value = "2"; form.elements.minLapSec.value = "10"; form.elements.maxLapSec.value = "40"; form.requestSubmit(); })()`);
await waitFor(async () => (await savedState()).sessions.some((session) => session.id === practice.id && session.practiceRanking === "consecutive" && session.practiceRankLaps === 2), "ranking saved on the practice");
const saved = (await savedState()).events.find((item) => item.id === event.id);
assert.equal(saved.raceConfig.minLapMs, 10000);
assert.equal(saved.raceConfig.maxLapMs, 40000);
await navigate("overlay", "overlayFullscreen");
await waitFor(async () => /RK Steady/.test(await firstOnOverlay()), "best 2 in a row ranks the steady driver first");
assert.match(await firstOnOverlay(), /2 (laps|varv)/);
console.log("PASS open practice settings: ranking by best N laps in a row re-sorts the overlay");
}
+2
View File
@@ -12,6 +12,7 @@ import { runTtsSettingsSmoke } from "./browser_tts_settings.js";
import { runTrackLayoutsSmoke } from "./browser_track_layouts.js";
import { runPrologueSmoke } from "./browser_prologue.js";
import { runPracticeResetSmoke } from "./browser_practice_reset.js";
import { runPracticeRankingSmoke } from "./browser_practice_ranking.js";
import { runSuspectLapsSmoke } from "./browser_suspect_laps.js";
import { runOverlayDriverLinkSmoke } from "./browser_overlay_driver_link.js";
import { runProfileClassSmoke } from "./browser_profile_class.js";
@@ -166,6 +167,7 @@ try {
await runTrackLayoutsSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs });
await runPrologueSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs });
await runPracticeResetSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs });
await runPracticeRankingSmoke({ evaluate, navigate, savedState, waitFor, base });
await runSuspectLapsSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs });
await runOverlayDriverLinkSmoke({ evaluate, navigate, savedState, waitFor, base, send });
await runDecoderClockSmoke({ evaluate, navigate, savedState, waitFor, base });
+35
View File
@@ -0,0 +1,35 @@
import test from "node:test";
import assert from "node:assert/strict";
import { getPracticeRankMetric, formatPracticeRankGap } from "../src/timing_logic.js";
// Passings 1 s apart start; each lap's timestamp follows the previous by its lapMs.
function run(startTs, laps) {
const passings = [{ timestamp: startTs, lapMs: 0 }];
let ts = startTs;
laps.forEach((lapMs) => { ts += lapMs; passings.push({ timestamp: ts, lapMs }); });
return passings;
}
test("best lap ranking gives no metric", () => {
assert.equal(getPracticeRankMetric({ practiceRanking: "best_lap" }, run(0, [18000, 17000])), null);
});
test("best N in a row stays inside one run (a stop in the pits splits)", () => {
const passings = [...run(0, [18000, 17000, 30000]), ...run(10_000_000, [16000, 16000])];
const metric = getPracticeRankMetric({ practiceRanking: "consecutive", practiceRankLaps: 3 }, passings);
assert.equal(metric.totalMs, 65000);
assert.equal(metric.lapCount, 3);
assert.equal(getPracticeRankMetric({ practiceRanking: "consecutive", practiceRankLaps: 2 }, passings).totalMs, 32000);
assert.equal(getPracticeRankMetric({ practiceRanking: "consecutive", practiceRankLaps: 4 }, passings), null);
});
test("best X minutes: most laps inside the window, then the shorter time", () => {
const fast = getPracticeRankMetric({ practiceRanking: "window", practiceRankMin: 1 }, run(0, [20000, 20000, 19000, 25000]));
assert.deepEqual([fast.lapCount, fast.totalMs], [3, 59000]);
const slow = getPracticeRankMetric({ practiceRanking: "window", practiceRankMin: 1 }, run(0, [21000, 21000, 21000]));
assert.deepEqual([slow.lapCount, slow.totalMs], [2, 42000]);
assert.ok(fast.comparableMs < slow.comparableMs, "more laps ranks first");
assert.equal(formatPracticeRankGap({ practiceMetric: slow }, { practiceMetric: fast }), "+1L");
const tie = getPracticeRankMetric({ practiceRanking: "window", practiceRankMin: 1 }, run(0, [20000, 20000, 19500]));
assert.equal(formatPracticeRankGap({ practiceMetric: tie }, { practiceMetric: fast }), "+0.500s");
});
+1
View File
@@ -1,4 +1,5 @@
import "./auth.test.js";
import "./practice_rank.test.js";
import "./team_race_logic.test.js";
import "./race_overview.test.js";
import "./leader_call_logic.test.js";