feat(results): lap chart per qualifying heat and final in the race overview, print and PDF (1.89.32)

This commit is contained in:
larssand committed 2026-11-14 20:55:44 +01:00
1 parent 01998952a7
commit 6a036899ab
15 files changed
+245 -14

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.89.32
- **Lap chart in the results:** every qualifying heat and final in the race overview (Race Day and the results archive) has a fold-out 📈 lap chart - each driver's place after every lap, from the passings. It is in the print and PDF of a single heat, and with the finals in the full results PDF and print.
## 1.89.31 - 2026-11-14
### Added
+1
View File
@@ -114,6 +114,7 @@ The menu follows how a race day works: **Start** (Dashboard, Race Day), **Create
- **Calling a heat:** when a heat is 10 minutes away (set under **Call**), Race Day asks the race controller: **📢 Call now** reads the heat and its drivers over the speakers and highlights it on the drivers' board; **Later** asks again in 2 minutes. With the autopilot on, heats are called on their own.
- **▶ Run the day automatically** starts each heat's count-down on its own when the schedule says so, and waits (saying why) while a heat runs, the decoder is offline or a heat is not ready. With several classes on one day, every class's heats run in the same order. Finals are never created automatically: when a class's qualifying is done it says "Waiting: check qualifying and press 🏁 Create finals for …" with the class names, so qualifying can be corrected first. Then the autopilot runs the finals. It runs only in the browser where it was turned on. **■ Stop autopilot** to run heats by hand; turning it on again carries on with the next heat not yet run. **⏸ Pause the day** pauses the heat on track (or holds the count-down) and the autopilot until **Resume the day**.
- **Race overview** (under the heat queue): the whole race of the current event in one place - the podium from the A final, then practice, qualifying and finals that open and close, each with the standings and every heat's result (laps, result, best lap, and the car in sponsor heats). **Print**, **PDF** and **CSV** export the whole race with every heat, finals on top (A final first), then qualifying, then practice. A finished heat or final has its own **🖨** and **PDF** buttons for just that heat, e.g. for the board in the pits.
- **📈 Lap chart:** every qualifying heat and final has a fold-out lap chart - each driver's place after every lap as a coloured line, place 1 on top, names at their official finish place. Counted from the passings, nothing extra to set up. It is printed and in the PDF of a single heat, and with the finals in the full results.
- **Speaker panel** (under the start buttons): track call, track clear, red flag, pause, resume, false start and marshal warning. Under **Sound and calls** are quick switches that save at once: mute all, lap time calls, race leader calls, practice hype and the speaker cues.
- **Preflight** checks the decoder, participants, transponders (missing or duplicated), the lap window, the grid and audio. Blockers come first, each with a shortcut to the right setting. The min/max lap time can be edited right there.
- **An automatic SQLite backup** is taken before every start.
+1
View File
@@ -127,6 +127,7 @@ Gränssnittet finns på svenska och engelska.
- **▶ Kör dagen automatiskt** startar varje heats nedräkning själv när schemat säger det, och väntar (och säger varför) medan ett heat körs, decodern är frånkopplad eller ett heat inte är redo. Med flera klasser samma dag körs alla klassernas heat i samma ordning. Finaler skapas aldrig automatiskt: när kvalet är klart i en klass står det "Väntar: kontrollera kvalet och tryck 🏁 Skapa finaler för …" med klassernas namn, så att kvalet kan korrigeras först. Sedan kör automatiken finalerna. Den körs bara i webbläsaren där den slogs på. **■ Stoppa automatiken** för att köra för hand; slår du på den igen fortsätter den med nästa heat som inte är kört. **⏸ Pausa dagen** pausar heatet på banan (eller håller nedräkningen) och automatiken tills **Fortsätt dagen**.
- **Heat-kön** visar aktuellt, nästa och därpå följande heat i körordning: träning, kval omgång för omgång (Q1 H1, Q1 H2, Q2 H1 …), sedan finaler från lägsta (C, B, A). När ett heat är klart väljer **▶ Nästa** nästa heat med ett klick. Sessionslistorna i Race Setup och på Race Day följer samma ordning, så ett heat som tagits bort och skapats om hamnar på rätt plats; **▲▼** på en session i Race Setup flyttar den tidigare eller senare.
- **Race-översikt** (under heatkön): hela racet för det aktuella eventet på ett ställe – pallen från A-finalen, sedan träning, kval och finaler som kan fällas ut, var och en med ställning och varje heats resultat (varv, resultat, bästa varv, och bilen i sponsorheat). **Skriv ut**, **PDF** och **CSV** exporterar hela racet med alla heat, finalerna överst (A-finalen först), sedan kval och sist träning. Ett avslutat heat eller en final har egna knappar **🖨** och **PDF** för bara det heatet, t.ex. till tavlan i depån.
- **📈 Varvdiagram:** varje kvalheat och final har ett utfällbart varvdiagram – varje förares placering efter varje varv som en färgad linje, 1:a överst, namnen vid den officiella placeringen. Räknas från passeringarna, inget att ställa in. Det kommer med i utskrift och PDF av ett enskilt heat, och med finalerna i hela resultatet.
- **Speakerpanel** (under startknapparna): stopp på banan, banan fri, röd flagg, paus, fortsätt, tjuvstart och banvaktsvarning. Under **Ljud och utrop** finns snabbval som sparas direkt: tysta allt, varvtidsutrop, ledarutrop, pepp under träning och speaker-utropen.
- **Förkontrollen** kontrollerar decoder, deltagare, transpondrar (saknade eller dubbletter), varvtidsgränser, grid och ljud. Blockerare visas först, var och en med en genväg till rätt inställning. Min/max-varvtid kan ändras direkt där.
- **En automatisk SQLite-backup** tas före varje start.
+3
View File
@@ -2978,3 +2978,6 @@ Tests: decoder_diagnostics.test.js covers bounds, isolation, snapshots and outco
`loadProfile` serializes requests, uses AbortController with a 15-second timer, and releases its lock in finally. Existing 10-second visible-page polling and before/after-response edit guards remain. Only a successfully applied profile updates lastSuccessAt; responses deferred due to active editing never falsely refresh it. Failed background requests preserve loaded DOM and data. A 30-second age marks data stale. Retry uses the same background-safe load path. Status is not a write acknowledgement or decoder health indicator. This change adds no persistence or server/API contract.
`tests/public_training_refresh.test.js` exercises stale/failure/recovery, non-overlap, deferred responses, independent status DOM and timeout recovery. Browser smoke coverage simulates network loss on a real personal profile and retries after network restoration using isolated state.
`lap_chart_logic.js` (pure) turns a heat's passings into a lap chart: `buildLapChart(entries)` gives each driver's place after every lap (order of crossing for that lap, among those who did it), `renderLapChartSvg()` draws it as a self-styled inline SVG (`currentColor` for axes, so it works in every theme and in print). `buildRaceOverview()` adds `heat.lapChart` for qualifying and finals when given `getCompetitorPassings`; the race overview panel shows it in a `<details>`, `renderRaceOverviewHeatsHtml()` prints it (single heat, or finals in the full results), and `buildHeatPdfSection()` sends it as `section.chart`, which `server.js` `normalizePdfLapChart()` checks and `server/pdf_render.js` `drawLapChart()` draws as vector lines.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rc-racecore",
"version": "1.89.31",
"version": "1.89.32",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rc-racecore",
"version": "1.89.31",
"version": "1.89.32",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^12.11.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "rc-racecore",
"version": "1.89.31",
"version": "1.89.32",
"private": true,
"description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence",
"engines": {
+17
View File
@@ -961,6 +961,22 @@ function attachmentDisposition(filename) {
return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
}
// A heat's lap chart (src/lap_chart_logic.js): places per lap per driver, drawn as lines.
function normalizePdfLapChart(chart) {
if (!chart || !Array.isArray(chart.series)) return null;
const laps = Math.min(400, Math.max(0, Math.floor(Number(chart.laps) || 0)));
const series = chart.series.slice(0, 24).map((serie) => ({
name: String(serie?.name || "-").slice(0, 60),
color: /^#[0-9a-f]{6}$/i.test(String(serie?.color || "")) ? String(serie.color) : "#555555",
positions: (Array.isArray(serie?.positions) ? serie.positions : []).slice(0, laps).map((place) => {
const value = Math.floor(Number(place));
return value >= 1 && value <= 24 ? value : null;
}),
}));
if (laps < 2 || series.length < 2) return null;
return { title: String(chart.title || "").slice(0, 80), lapLabel: String(chart.lapLabel || "").slice(0, 20), laps, series };
}
function normalizePdfExportPayload(input = {}) {
const title = String(input.title || "RC RaceCore").trim();
const subtitle = String(input.subtitle || "").trim();
@@ -982,6 +998,7 @@ function normalizePdfExportPayload(input = {}) {
: [],
// A country code per row for the flag before the driver's name ("SE", "GB-ENG"); anything else is dropped.
flags: Array.isArray(section?.flags) ? section.flags.map((code) => (/^[A-Z]{2}(-[A-Z]{3})?$/.test(String(code || "")) ? String(code) : "")) : [],
chart: normalizePdfLapChart(section?.chart),
}))
: [];
+41
View File
@@ -195,6 +195,12 @@ function createWriter(pageWidth, pageHeight, title) {
const size = label.length > 1 ? 6 : 7.5;
writer.text(cx - 6, cy - size / 3, label, size, { bold: true, color: ink, align: "center", width: 12 });
},
// An open line through points [[x, y], ...]; dashed draws it dotted.
polyline(points, color, width = 1, { dashed = false } = {}) {
if (points.length < 2) return;
const path = points.map(([px, py], index) => `${n(px)} ${n(py)} ${index ? "l" : "m"}`).join(" ");
writer.page.push(`q ${rgb(color)} RG ${width} w 1 J 1 j ${dashed ? "[1.5 2.5] 0 d " : ""}${path} S Q`);
},
image(x, y, w, h) {
writer.page.push(`q ${n(w)} 0 0 ${n(h)} ${n(x)} ${n(y)} cm /Im1 Do Q`);
},
@@ -309,6 +315,40 @@ function drawTable(writer, section, theme) {
writer.y -= 10;
}
// The lap chart under a heat: place 1 on top, a line per driver, names at their finish place.
function drawLapChart(writer, chart) {
const rows = chart.series.length;
const rowH = rows > 14 ? 11 : 14;
const height = 18 + rows * rowH + 22;
writer.ensure(height);
writer.text(MARGIN, writer.y - 10, fitText(chart.title, 10, true, writer.width), 10, { bold: true });
const top = writer.y - 18;
const left = MARGIN + 16;
const plotW = writer.width - 16 - 120;
const x = (lap) => left + ((lap - 1) / (chart.laps - 1)) * plotW;
const y = (place) => top - (place - 0.5) * rowH;
for (let place = 1; place <= rows; place += 1) {
writer.line(left, y(place), left + plotW, y(place), RULE, 0.4);
writer.text(MARGIN, y(place) - 2.5, String(place), 7, { color: MUTED, align: "right", width: 11 });
}
const step = chart.laps <= 12 ? 1 : chart.laps <= 30 ? 2 : chart.laps <= 60 ? 5 : chart.laps <= 150 ? 10 : 25;
for (let lap = 1; lap <= chart.laps; lap += 1) {
if (lap === 1 || lap === chart.laps || (lap % step === 0 && chart.laps - lap >= step / 2)) {
writer.text(x(lap) - 10, top - rows * rowH - 10, String(lap), 7, { color: MUTED, align: "center", width: 20 });
}
}
writer.text(left + plotW - 60, top - rows * rowH - 20, chart.lapLabel, 7, { color: MUTED, align: "right", width: 60 });
chart.series.forEach((serie, index) => {
const points = serie.positions.map((place, lap) => (place ? [x(lap + 1), y(place)] : null)).filter(Boolean);
if (!points.length) return;
writer.polyline(points, serie.color, 1.6);
const last = points[points.length - 1];
writer.polyline([last, [left + plotW + 6, y(index + 1)]], serie.color, 0.7, { dashed: true });
writer.text(left + plotW + 9, y(index + 1) - 2.5, fitText(`${index + 1}. ${serie.name}`, 7.5, true, 110), 7.5, { bold: true, color: serie.color });
});
writer.y -= height + 8;
}
function drawParagraphs(writer, section) {
section.rows.forEach((row) => row.forEach((value) => {
wrapText(value, 10, false, writer.width).forEach((line) => {
@@ -449,6 +489,7 @@ function buildStyledPdf(payload) {
if (section.title) drawSectionTitle(writer, section.title, theme);
if (section.headers.length) drawTable(writer, section, theme);
else drawParagraphs(writer, section);
if (section.chart) drawLapChart(writer, section.chart);
});
drawFooters(writer, pages, payload, theme, pageWidth);
+13 -5
View File
@@ -15,6 +15,7 @@ import { flagHtml, driverCountryCode, countryChoices, setDriverCountryResolver,
import { renderRaceDayView, refreshRaceDayWarmup, refreshRaceDayPrologueClock, updateRaceDayStartDisplay, refreshRaceDayLive } from "./race_day_view.js";
import { assignMarshals, normalizeRaceDays, getRaceDay, upsertRaceDay, orderDaySessions, buildDaySchedule, getAutopilotAction, moveInDayOrder, pickBoardDate, getDueCall, withRaceSetupStart, eventScheduleFromDayRows } from "./day_schedule_logic.js";
import { buildRaceOverview, buildRaceOverviewCsvRows, withQualifyingPlaces, qualifyingPlaces } from "./race_overview_logic.js";
import { renderLapChartSvg } from "./lap_chart_logic.js";
import { renderRaceOverviewPanel, bindRaceOverviewPanel } from "./race_overview_view.js";
import { renderSpeakerPanel, bindSpeakerPanel } from "./speaker_panel_view.js";
import { renderDaySchedulePanel, bindDaySchedulePanel, buildDaySchedulePrintHtml, renderDriverBoard, formatClockTime, renderDayCallBanner, bindDayCallBanner } from "./day_schedule_view.js";
@@ -167,7 +168,7 @@ const buildPrintBrandBlock = (branding) => buildPrintBrandBlockHelper(branding,
const buildRaceStartListsHtml = (event) => buildRaceStartListsHtmlHelper(event, { t, state, escapeHtml, resolveEventBranding, getSessionsForEvent, getSessionSortWeight, getClassName, buildPrintBrandBlock, getSessionGridEntries, getSessionTypeLabel, getStartModeLabel, renderTable, buildEventSchedule });
const buildRaceResultsHtml = (event) => buildRaceResultsHtmlHelper(event, { t, escapeHtml, resolveEventBranding, getClassName, buildPrintBrandBlock, renderRaceStandingsTableView, buildPracticeStandings, buildQualifyingStandings, buildFinalStandings, renderTeamRaceStandings, getSessionsForEvent, renderSessionChannelAnalysis, renderHeatResults: (event) => renderRaceOverviewHeatsHtml(event) });
// Race overview (Race Day and the results archive): the whole race, with print, PDF and CSV.
const getRaceOverview = (event) => buildRaceOverview(event, { sessions: getSessionsForEvent(event?.id), cars: state.cars, buildLeaderboard, buildPracticeStandings, buildQualifyingStandings, buildFinalStandings });
const getRaceOverview = (event) => buildRaceOverview(event, { sessions: getSessionsForEvent(event?.id), cars: state.cars, buildLeaderboard, buildPracticeStandings, buildQualifyingStandings, buildFinalStandings, getCompetitorPassings });
const raceOverviewPhaseLabel = (type) => t(`race_overview.phase_${type}`);
const renderRaceOverviewFor = (event) => (event ? renderRaceOverviewPanel(getRaceOverview(event), { t, escapeHtml, formatLap, renderTable, renderRaceStandingsTableView, phaseLabel: raceOverviewPhaseLabel, getStatusLabel }) : "");
const bindRaceOverviewFor = (root, event) => event && bindRaceOverviewPanel(root, getRaceOverview(event), {
@@ -190,21 +191,24 @@ const getOverviewHeats = (event, onlySessionId = "") => [...(getRaceOverview(eve
return heats.map((heat) => ({ ...heat, phase }));
})
.filter(({ session }) => !onlySessionId || session.id === onlySessionId);
const renderRaceOverviewHeatsHtml = (event, onlySessionId = "") => getOverviewHeats(event, onlySessionId).map(({ session, rows, phase }) => `
// The lap chart prints with a single heat, and with the finals in the full results.
const renderRaceOverviewHeatsHtml = (event, onlySessionId = "") => getOverviewHeats(event, onlySessionId).map(({ session, rows, phase, lapChart }) => `
<section class="print-block">
<h2>${escapeHtml(raceOverviewPhaseLabel(phase.type))} • ${escapeHtml(session.name)}</h2>
${renderTable([t("table.pos"), ...(rows.some((row) => row.qual) ? [t("table.qual")] : []), t("table.driver"), ...(rows.some((row) => row.car) ? [t("race_overview.car")] : []), t("table.laps"), t("table.result"), t("table.best_lap")],
rows.map((row) => `<tr><td>${medal(row.pos)}</td>${rows.some((item) => item.qual) ? qualCell(row.qual, escapeHtml) : ""}<td>${rowFlag(row)}${escapeHtml(row.name)}</td>${rows.some((item) => item.car) ? `<td>${escapeHtml(row.car || "-")}</td>` : ""}<td>${row.laps}</td><td>${escapeHtml(row.result)}</td><td>${row.bestLapMs ? escapeHtml(formatLap(row.bestLapMs)) : "-"}</td></tr>`))}
${lapChart && (onlySessionId || phase.type === "final") ? `<div class="print-lap-chart"><h3>${escapeHtml(t("lap_chart.title"))}</h3>${renderLapChartSvg(lapChart, { escapeHtml, title: t("lap_chart.title"), lapLabel: t("table.lap") })}</div>` : ""}
</section>`).join("");
const buildHeatPdfSection = ({ session, rows, phase }) => {
const buildHeatPdfSection = ({ session, rows, phase, lapChart }, { withChart = true } = {}) => {
const withCar = rows.some((row) => row.car);
const withQual = rows.some((row) => row.qual);
return buildPdfSection(
const section = buildPdfSection(
`${raceOverviewPhaseLabel(phase.type)} • ${session.name}`,
[t("table.pos"), ...(withQual ? [t("table.qual")] : []), t("table.driver"), ...(withCar ? [t("race_overview.car")] : []), t("table.laps"), t("table.result"), t("table.best_lap")],
rows.map((row) => [String(row.pos), ...(withQual ? [row.qual || "-"] : []), row.name, ...(withCar ? [row.car || "-"] : []), String(row.laps), row.result, row.bestLapMs ? formatLap(row.bestLapMs) : "-"]),
pdfFlags(rows)
);
return lapChart && withChart ? { ...section, chart: { title: t("lap_chart.title"), lapLabel: t("table.lap"), ...lapChart } } : section;
};
// One finished heat or final on its own page: for the board in the pits right after it.
const printHeatResult = (event, sessionId) => {
@@ -3268,6 +3272,8 @@ const TRANSLATIONS = {
"race_overview.standings": "Ställning",
"race_overview.heats_done": "{done} av {total} heat klara",
"race_overview.no_results": "Inga resultat än.",
"lap_chart.title": "Varvdiagram",
"lap_chart.hint": "Placering efter varje varv, räknat från passeringarna. Officiell placering står till höger.",
"race_overview.not_run": "Inte körd än.",
"race_overview.phase_practice": "Träning",
"race_overview.phase_qualification": "Kval",
@@ -5619,6 +5625,8 @@ const TRANSLATIONS = {
"race_overview.standings": "Standings",
"race_overview.heats_done": "{done} of {total} heats done",
"race_overview.no_results": "No results yet.",
"lap_chart.title": "Lap chart",
"lap_chart.hint": "Place after every lap, counted from the passings. Official finish place on the right.",
"race_overview.not_run": "Not run yet.",
"race_overview.phase_practice": "Practice",
"race_overview.phase_qualification": "Qualifying",
@@ -8549,7 +8557,7 @@ async function buildRaceResultsPdfPayload(event) {
buildPracticeStandings(event).map((row) => [String(row.rank), row.driverName || "-", row.score || "-"]),
pdfFlags(buildPracticeStandings(event))
),
...getOverviewHeats(event).map(buildHeatPdfSection),
...getOverviewHeats(event).map((heat) => buildHeatPdfSection(heat, { withChart: heat.phase.type === "final" })),
...buildTeamRaceStandings(event).map(({ session, rows }) =>
buildPdfSection(
`${t("events.team_standings")} • ${session.name}`,
+73
View File
@@ -0,0 +1,73 @@
// Lap chart: each driver's place after every lap of a heat, from the passings already stored.
// Place after lap n = order in which the drivers who did n laps crossed the line for the n-th time.
// Pure logic + an SVG string (screen and print); the PDF draws the same data in server/pdf_render.js.
export const LAP_CHART_COLORS = ["#e63946", "#1d7fd6", "#2a9d3f", "#f08c00", "#8e44ad", "#00a6a6", "#d6336c", "#6c7a89", "#b5651d", "#5c940d", "#3b5bdb", "#c2255c"];
export const LAP_CHART_MAX_DRIVERS = 24;
export const LAP_CHART_MAX_LAPS = 400;
// entries: [{ name, timestamps: [ms, ...] }] in official finish order (one per counted lap).
// Returns { laps, series: [{ name, color, positions: [place or null per lap] }] } or null when
// there is nothing to draw (fewer than 2 drivers with laps, or fewer than 2 laps).
export function buildLapChart(entries = []) {
const drivers = entries
.slice(0, LAP_CHART_MAX_DRIVERS)
.map((entry) => ({ name: String(entry?.name || "-"), times: (entry?.timestamps || []).map(Number).filter(Number.isFinite).sort((a, b) => a - b).slice(0, LAP_CHART_MAX_LAPS) }));
const laps = Math.max(0, ...drivers.map((driver) => driver.times.length));
if (laps < 2 || drivers.filter((driver) => driver.times.length).length < 2) return null;
const positions = drivers.map(() => []);
for (let lap = 0; lap < laps; lap += 1) {
drivers
.map((driver, index) => ({ index, at: driver.times[lap] }))
.filter((item) => item.at !== undefined)
.sort((a, b) => a.at - b.at || a.index - b.index)
.forEach((item, place) => { positions[item.index][lap] = place + 1; });
drivers.forEach((driver, index) => { if (positions[index][lap] === undefined) positions[index][lap] = null; });
}
return {
laps,
series: drivers.map((driver, index) => ({ name: driver.name, color: LAP_CHART_COLORS[index % LAP_CHART_COLORS.length], positions: positions[index] })),
};
}
// Which lap numbers get a tick: about 10 along the axis, always the last.
export function lapChartTicks(laps) {
const step = laps <= 12 ? 1 : laps <= 30 ? 2 : laps <= 60 ? 5 : laps <= 150 ? 10 : 25;
const ticks = [];
for (let lap = step; lap < laps; lap += step) ticks.push(lap);
if (laps - (ticks[ticks.length - 1] || 0) < step / 2 && ticks.length) ticks.pop();
ticks.push(laps);
return laps > 1 ? [1, ...ticks.filter((lap) => lap > 1)] : ticks;
}
// The chart as an inline SVG: place 1 on top, a line per driver, names on the right at their
// official finish place (with a dotted lead-in from where their last lap ended).
export function renderLapChartSvg(chart, { escapeHtml, title = "", lapLabel = "Lap" } = {}) {
if (!chart) return "";
const rows = chart.series.length;
const rowH = 22;
const left = 28;
const right = 150;
const top = 12;
const width = 720;
const plotW = width - left - right;
const height = top + rows * rowH + 30;
const x = (lap) => left + (chart.laps === 1 ? 0 : ((lap - 1) / (chart.laps - 1)) * plotW);
const y = (place) => top + (place - 0.5) * rowH;
const grid = Array.from({ length: rows }, (_, index) => `<line x1="${left}" x2="${left + plotW}" y1="${y(index + 1)}" y2="${y(index + 1)}" stroke="currentColor" stroke-opacity="0.14"/><text x="${left - 8}" y="${y(index + 1) + 4}" text-anchor="end" fill="currentColor" fill-opacity="0.7" font-size="11">${index + 1}</text>`).join("");
const ticks = lapChartTicks(chart.laps).map((lap) => `<text x="${x(lap)}" y="${height - 8}" text-anchor="middle" fill="currentColor" fill-opacity="0.7" font-size="11">${lap}</text>`).join("");
const dots = chart.laps <= 40;
const lines = chart.series.map((serie, index) => {
const points = serie.positions.map((place, lap) => (place ? [x(lap + 1), y(place)] : null)).filter(Boolean);
if (!points.length) return "";
const [lastX, lastY] = points[points.length - 1];
const labelY = y(index + 1);
return `<g class="lap-chart-serie"><title>${escapeHtml(serie.name)}</title>
<polyline points="${points.map(([px, py]) => `${px.toFixed(1)},${py.toFixed(1)}`).join(" ")}" fill="none" stroke="${serie.color}" stroke-width="2.4" stroke-linejoin="round" stroke-linecap="round"/>
${dots ? points.map(([px, py]) => `<circle cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" r="2.6" fill="${serie.color}"/>`).join("") : ""}
<line x1="${lastX.toFixed(1)}" y1="${lastY.toFixed(1)}" x2="${left + plotW + 10}" y2="${labelY}" stroke="${serie.color}" stroke-width="1.2" stroke-dasharray="2 3"/>
<text x="${left + plotW + 14}" y="${labelY + 4}" fill="${serie.color}" font-size="12" font-weight="700">${index + 1}. ${escapeHtml(serie.name.length > 18 ? `${serie.name.slice(0, 17)}…` : serie.name)}</text></g>`;
}).join("");
return `<svg class="lap-chart" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(title)}" xmlns="http://www.w3.org/2000/svg">
${grid}${ticks}<text x="${left + plotW}" y="${height - 20}" text-anchor="end" fill="currentColor" fill-opacity="0.6" font-size="10" font-style="italic">${escapeHtml(lapLabel)}</text>${lines}</svg>`;
}
+13 -4
View File
@@ -1,6 +1,7 @@
// Race overview (Race Day): the whole event in one place - podium, then practice, qualifying
// and finals, each with its standings and every heat's result. Also the rows for one CSV.
// Works for race events and sponsor events (their heats carry carAssignments).
import { buildLapChart } from "./lap_chart_logic.js";
const PHASES = ["practice", "qualification", "final"];
// Where each driver ended up in qualifying ("TQ" for the top qualifier), shown next to the
@@ -20,7 +21,7 @@ export function withQualifyingPlaces(rows = [], qualifyingRows = []) {
}
export function buildRaceOverview(event, deps) {
const { sessions = [], cars = [], buildLeaderboard, buildPracticeStandings, buildQualifyingStandings, buildFinalStandings } = deps;
const { sessions = [], cars = [], buildLeaderboard, buildPracticeStandings, buildQualifyingStandings, buildFinalStandings, getCompetitorPassings = null } = deps;
if (!event) return null;
const carName = (session, driverId) => {
const carId = session.carAssignments?.[driverId];
@@ -33,9 +34,16 @@ export function buildRaceOverview(event, deps) {
const phases = PHASES.map((type) => {
const heats = sessions
.filter((session) => session.type === type && session.status !== "ready")
.map((session) => ({
.map((session) => {
const leaderboard = buildLeaderboard(session);
// Practice is about best laps, not places: no lap chart there.
const lapChart = type !== "practice" && getCompetitorPassings
? buildLapChart(leaderboard.map((row) => ({ name: row.displayName || row.driverName || row.transponder || "-", timestamps: getCompetitorPassings(session, row).map((passing) => passing.timestamp) })))
: null;
return {
session,
rows: buildLeaderboard(session).map((row, index) => ({
lapChart,
rows: leaderboard.map((row, index) => ({
pos: index + 1,
driverId: row.driverId,
qual: type === "final" ? qualPlaces.get(row.driverId) || "" : "",
@@ -47,7 +55,8 @@ export function buildRaceOverview(event, deps) {
timeMs: Number(row.totalElapsedMs || 0) || null,
raceStatus: row.raceStatus || "",
})),
}));
};
});
const planned = sessions.filter((session) => session.type === type).length;
const standings = heats.length ? standingsOf[type](event) || [] : [];
return { type, planned, heats, standings: type === "final" && qualPlaces.size ? standings.map((row) => ({ ...row, qual: qualPlaces.get(row.driverId) || "" })) : standings };
+4 -2
View File
@@ -1,5 +1,6 @@
import { rowFlag } from "./country_flags.js";
import { medal, qualCell } from "./medal.js";
import { renderLapChartSvg } from "./lap_chart_logic.js";
// Race Day → Race overview panel: podium, then practice / qualifying / finals with standings
// and every heat. Logic in race_overview_logic.js; print, PDF and CSV come in as deps.
const openPhases = new Set();
@@ -29,9 +30,10 @@ export function renderRaceOverviewPanel(overview, { t, escapeHtml, formatLap, re
${phase.heats.length ? `
<h4>${t("race_overview.standings")}</h4>
${renderRaceStandingsTableView(phase.standings, t("race_overview.no_results"))}
${phase.heats.map(({ session, rows }) => `
${phase.heats.map(({ session, rows, lapChart }) => `
<h4>${escapeHtml(session.name)} <small>${escapeHtml(getStatusLabel(session.status))}</small>${session.status === "finished" && rows.length ? ` <span class="race-overview-heat-actions"><button class="btn btn-mini" type="button" data-heat-print="${escapeHtml(session.id)}" title="${escapeHtml(t("race_overview.print_heat"))}">🖨</button><button class="btn btn-mini" type="button" data-heat-pdf="${escapeHtml(session.id)}" title="${escapeHtml(t("race_overview.pdf_heat"))}">PDF</button></span>` : ""}</h4>
${rows.length ? heatTable(rows) : `<p class="hint">${t("race_overview.no_results")}</p>`}`).join("")}`
${rows.length ? heatTable(rows) : `<p class="hint">${t("race_overview.no_results")}</p>`}
${lapChart ? `<details class="lap-chart-box"><summary>📈 ${escapeHtml(t("lap_chart.title"))}</summary>${renderLapChartSvg(lapChart, { escapeHtml, title: `${t("lap_chart.title")} - ${session.name}`, lapLabel: t("table.lap") })}<p class="hint">${escapeHtml(t("lap_chart.hint"))}</p></details>` : ""}`).join("")}`
: `<p class="hint">${t("race_overview.not_run")}</p>`}
</details>`).join("")}
</div>
+7
View File
@@ -5095,3 +5095,10 @@ tr.is-selected td { background: color-mix(in srgb, var(--danger) 12%, transparen
.check-in-table td:nth-child(n+4), .check-in-table th:nth-child(n+4) { text-align: center; }
.check-in-table input[type="checkbox"] { width: 20px; height: 20px; }
.check-in-table tr.is-present td:first-child { box-shadow: inset 3px 0 0 #2fa84f; }
/* Lap chart under a heat in the race overview (lap_chart_logic.js draws the SVG). */
.lap-chart-box { margin: 6px 0 14px; }
.lap-chart-box > summary { cursor: pointer; font-weight: 600; padding: 4px 0; }
.lap-chart { display: block; width: 100%; max-width: 820px; height: auto; font-family: var(--overlay-font, inherit); }
.print-lap-chart { margin-top: 10px; break-inside: avoid; }
.print-lap-chart .lap-chart { max-width: 100%; color: #222; }
+64
View File
@@ -0,0 +1,64 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import { buildLapChart, lapChartTicks, renderLapChartSvg } from "../src/lap_chart_logic.js";
import { buildRaceOverview } from "../src/race_overview_logic.js";
const { buildStyledPdf } = createRequire(import.meta.url)("../server/pdf_render.js");
const escapeHtml = (value) => String(value).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
test("the place after each lap is the order the drivers crossed the line for that lap", () => {
const chart = buildLapChart([
{ name: "Anna", timestamps: [1200, 2100, 3000] }, // passes Bo on lap 2
{ name: "Bo", timestamps: [1000, 2200, 3300] },
{ name: "Cid", timestamps: [1500, 2900] }, // one lap down
]);
assert.equal(chart.laps, 3);
assert.deepEqual(chart.series.map((s) => s.positions), [[2, 1, 1], [1, 2, 2], [3, 3, null]]);
assert.equal(chart.series[0].name, "Anna");
assert.match(chart.series[0].color, /^#[0-9a-f]{6}$/);
});
test("no chart without at least two drivers and two laps", () => {
assert.equal(buildLapChart([{ name: "A", timestamps: [1, 2, 3] }]), null);
assert.equal(buildLapChart([{ name: "A", timestamps: [1] }, { name: "B", timestamps: [2] }]), null);
assert.equal(buildLapChart([{ name: "A", timestamps: [1, 2] }, { name: "B", timestamps: [] }]), null);
});
test("lap ticks start at 1, end on the last lap and stay about ten", () => {
assert.deepEqual(lapChartTicks(5), [1, 2, 3, 4, 5]);
assert.deepEqual(lapChartTicks(21), [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21]);
assert.ok(lapChartTicks(120).length <= 14);
});
test("the SVG has a line per driver and the names (escaped) in finish order", () => {
const svg = renderLapChartSvg(buildLapChart([{ name: "A<b>", timestamps: [1, 3] }, { name: "B", timestamps: [2, 4] }]), { escapeHtml, title: "Lap chart", lapLabel: "Lap" });
assert.equal((svg.match(/<polyline/g) || []).length, 2);
assert.ok(svg.includes("1. A&lt;b&gt;") && svg.includes("2. B"));
assert.ok(!svg.includes("<b>"));
});
test("the race overview gives qualifying and finals a lap chart, practice none", () => {
const sessions = [
{ id: "p", type: "practice", status: "finished" },
{ id: "q", type: "qualification", status: "finished" },
];
const passings = { A: [1, 3, 5], B: [2, 4, 6] };
const overview = buildRaceOverview({ id: "e" }, {
sessions,
buildLeaderboard: () => [{ key: "A", driverName: "A" }, { key: "B", driverName: "B" }],
buildPracticeStandings: () => [], buildQualifyingStandings: () => [], buildFinalStandings: () => [],
getCompetitorPassings: (session, row) => passings[row.key].map((timestamp) => ({ timestamp })),
});
const heat = (type) => overview.phases.find((phase) => phase.type === type).heats[0];
assert.equal(heat("practice").lapChart, null);
assert.equal(heat("qualification").lapChart.laps, 3);
});
test("the PDF draws the lap chart as coloured lines with the names", () => {
const chart = { title: "Varvdiagram", lapLabel: "Varv", ...buildLapChart([{ name: "Anna", timestamps: [1, 3, 5] }, { name: "Bo", timestamps: [2, 4, 6] }]) };
const pdf = buildStyledPdf({ title: "R", subtitle: "", brandName: "K", brandTagline: "", footer: "", theme: "classic", logoDataUrl: "", sections: [{ title: "A-final", headers: ["Pos", "Förare"], rows: [["1", "Anna"], ["2", "Bo"]], chart }] }).toString("latin1");
assert.ok(pdf.includes("(Varvdiagram) Tj"));
assert.ok(pdf.includes("(1. Anna) Tj") && pdf.includes("(2. Bo) Tj"));
assert.ok(pdf.includes("0.902 0.224 0.275 RG"), "the first driver's red line");
});
+1
View File
@@ -9,6 +9,7 @@ import "./judging_penalties.test.js";
import "./practice_rank.test.js";
import "./team_race_logic.test.js";
import "./race_overview.test.js";
import "./lap_chart.test.js";
import "./leader_call_logic.test.js";
import "./decoder_sim.test.js";
import "./sponsor_event.test.js";