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

+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) {