diff --git a/CHANGELOG.md b/CHANGELOG.md index 15c97b7..732ebcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 6c74fa0..1f8a05c 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/README.sv.md b/README.sv.md index badf69e..dfd084e 100644 --- a/README.sv.md +++ b/README.sv.md @@ -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. diff --git a/docs/javascript-architecture.md b/docs/javascript-architecture.md index 6bd091b..fc29fb6 100644 --- a/docs/javascript-architecture.md +++ b/docs/javascript-architecture.md @@ -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 `
`, `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. diff --git a/package-lock.json b/package-lock.json index 963d5bf..5dcacc5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 2516e53..7a1d408 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/server.js b/server.js index f5abab2..159b526 100644 --- a/server.js +++ b/server.js @@ -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), })) : []; diff --git a/server/pdf_render.js b/server/pdf_render.js index 0ed0f8a..87025e3 100644 --- a/server/pdf_render.js +++ b/server/pdf_render.js @@ -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); diff --git a/src/app.js b/src/app.js index f087d32..3c914c8 100644 --- a/src/app.js +++ b/src/app.js @@ -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 }) => ` `).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}`, diff --git a/src/lap_chart_logic.js b/src/lap_chart_logic.js new file mode 100644 index 0000000..a73aaff --- /dev/null +++ b/src/lap_chart_logic.js @@ -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) => `${index + 1}`).join(""); + const ticks = lapChartTicks(chart.laps).map((lap) => `${lap}`).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 `${escapeHtml(serie.name)} + + ${dots ? points.map(([px, py]) => ``).join("") : ""} + + ${index + 1}. ${escapeHtml(serie.name.length > 18 ? `${serie.name.slice(0, 17)}
` : serie.name)}`; + }).join(""); + return ` + ${grid}${ticks}${escapeHtml(lapLabel)}${lines}`; +} diff --git a/src/race_overview_logic.js b/src/race_overview_logic.js index fda16f5..7ae13d0 100644 --- a/src/race_overview_logic.js +++ b/src/race_overview_logic.js @@ -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 }; diff --git a/src/race_overview_view.js b/src/race_overview_view.js index dafe848..0de51dd 100644 --- a/src/race_overview_view.js +++ b/src/race_overview_view.js @@ -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 ? `

${t("race_overview.standings")}

${renderRaceStandingsTableView(phase.standings, t("race_overview.no_results"))} - ${phase.heats.map(({ session, rows }) => ` + ${phase.heats.map(({ session, rows, lapChart }) => `

${escapeHtml(session.name)} ${escapeHtml(getStatusLabel(session.status))}${session.status === "finished" && rows.length ? ` ` : ""}

- ${rows.length ? heatTable(rows) : `

${t("race_overview.no_results")}

`}`).join("")}` + ${rows.length ? heatTable(rows) : `

${t("race_overview.no_results")}

`} + ${lapChart ? `
📈 ${escapeHtml(t("lap_chart.title"))}${renderLapChartSvg(lapChart, { escapeHtml, title: `${t("lap_chart.title")} - ${session.name}`, lapLabel: t("table.lap") })}

${escapeHtml(t("lap_chart.hint"))}

` : ""}`).join("")}` : `

${t("race_overview.not_run")}

`}
`).join("")} diff --git a/src/styles.css b/src/styles.css index 02330a2..88acecd 100644 --- a/src/styles.css +++ b/src/styles.css @@ -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; } diff --git a/tests/lap_chart.test.js b/tests/lap_chart.test.js new file mode 100644 index 0000000..1c95363 --- /dev/null +++ b/tests/lap_chart.test.js @@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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", timestamps: [1, 3] }, { name: "B", timestamps: [2, 4] }]), { escapeHtml, title: "Lap chart", lapLabel: "Lap" }); + assert.equal((svg.match(/")); +}); + +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"); +}); diff --git a/tests/run.js b/tests/run.js index 406b335..6e9f45d 100644 --- a/tests/run.js +++ b/tests/run.js @@ -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";