From fdc6c179dc05fa1df65f31d6bf0d539a541bef35 Mon Sep 17 00:00:00 2001 From: larssand Date: Sun, 1 Nov 2026 22:06:59 +0100 Subject: [PATCH] feat(race-day): day schedule for all classes, autopilot, pause the day, printed running order and drivers' board (1.50.0) --- CHANGELOG.md | 13 +++ README.md | 4 + README.sv.md | 4 + ROADMAP.md | 11 ++ package-lock.json | 4 +- package.json | 2 +- src/app.js | 203 +++++++++++++++++++++++++++++++++- src/day_schedule_logic.js | 144 ++++++++++++++++++++++++ src/day_schedule_view.js | 142 ++++++++++++++++++++++++ src/event_race_logic.js | 20 ++-- src/misc_views.js | 4 +- src/race_day_view.js | 5 +- src/runtime_services.js | 2 + src/styles.css | 39 +++++++ tests/browser_day_schedule.js | 85 ++++++++++++++ tests/browser_smoke.js | 2 + tests/day_schedule.test.js | 70 ++++++++++++ tests/run.js | 1 + 18 files changed, 735 insertions(+), 20 deletions(-) create mode 100644 src/day_schedule_logic.js create mode 100644 src/day_schedule_view.js create mode 100644 tests/browser_day_schedule.js create mode 100644 tests/day_schedule.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c43f702..27c7de6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.50.0 - 2026-11-01 + +### Added + +- Today's schedule on Race Day: every class raced that day in one running order with planned times (first start and break between heats), ▲▼ to change the order. A heat that starts late, runs long or is paused moves the rest of the day. +- Print running order: times, classes, heats and drivers on one sheet for the board in the pits. +- Drivers' board (`/public-overlay/schedule`, also under Overlay): what is on track, the next three heats with their drivers and a "get ready" heads-up 10 minutes before, and the rest of the day. +- Run the day automatically: each heat's count-down starts on its own when the schedule says so; it waits and says why while a heat runs, the decoder is offline or a heat is not ready. Pause the day pauses the heat on track and the autopilot. + +### Fixed + +- The schedule in Race Setup now follows the running order set with ▲▼. + ## 1.49.0 - 2026-11-01 ### Added diff --git a/README.md b/README.md index d4cf263..14c5b51 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,10 @@ The menu follows how a race day works: **Start** (Dashboard, Race Day), **Create - **A session picker** and the buttons that apply right now: Start, Pause, Resume, Finish, **↻ Run again** for a stopped or finished heat, qualifier or final (laps, results and clock reset), and for practice **Reset – new practice day**. Practice uses plain words and has no start lights. The picker lists today's races grouped per race (plus anything running); older races and other days' rounds are under **Show all sessions**. - **Live race** for the race controller, right under the clock while a heat, qualifier or final runs: the running order with laps, last lap, best lap, gap to the car ahead and to the leader, and the estimated finish (laps and time when the time is up). The heat's fastest lap is purple, a personal best on the last lap green, and a bar shows how far into the lap each car is (red = late). After the heat it shows the result. - The **heat queue** shows the current, next and after-next heat in running order: practice, qualifying round by round (Q1 H1, Q1 H2, Q2 H1 …), then finals from the lowest (C, B, A). When a heat is done, **▶ Next** selects the next one in one click. The session lists in Race Setup and on Race Day follow the same order, so a heat deleted and made again lands in its right place; **▲▼** on a session in Race Setup moves it earlier or later. +- **Today's schedule** (at the bottom) puts every class raced that day in one running order with times: practice, then each qualifying round with the classes taking turns, then the finals. Set the first start and the break between heats; **▲▼** change the order. A heat that starts late, runs long or is paused moves the rest of the day. + - **🖨 Print running order** gives times, classes, heats and drivers for the board in the pits. + - **📺 Drivers' board** (`/public-overlay/schedule`, also under Overlay) shows what is on track, the next three heats with their drivers and a "get ready" heads-up 10 minutes before, then the rest of the day. It works on a phone or a TV in the pits. + - **▶ 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. It runs only in the browser where it was turned on. **⏸ Pause the day** pauses the heat on track (or holds the count-down) and the autopilot until **Resume the day**. - **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 2abd643..5c43cdb 100644 --- a/README.sv.md +++ b/README.sv.md @@ -119,6 +119,10 @@ Gränssnittet finns på svenska och engelska. - **Snabbval** överst: **Starta träning** (fortsätt eller starta en Open Practice), **Ny banlayout** (under träning) och **Skapa race**. Översikten har samma tre vanliga uppgifter. - **En sessionsväljare** och de knappar som gäller just nu: Start, Pausa, Fortsätt, Avsluta, **↻ Kör om** för ett avbrutet eller klart heat, kval eller final (varv, resultat och klocka nollställs), och för träning **Nollställ – ny träningsdag**. Träning använder vanliga ord och har inga startljus. Väljaren visar dagens race grupperade per race (plus det som pågår); äldre race och andra dagars deltävlingar finns under **Visa alla sessioner**. - **Live-race** för race controllern, direkt under klockan medan ett heat, kval eller final pågår: ordningen med varv, senaste varv, bästa varv, avstånd till bilen före och till ledaren, och beräknat slut (varv och tid när tiden går ut). Heatets snabbaste varv är lila, personbästa på senaste varvet grönt, och en stapel visar hur långt in på varvet varje bil är (röd = sen). Efter heatet visas resultatet. +- **Dagens schema** (längst ned) lägger alla klasser som körs den dagen i en körordning med tider: träning, sedan varje kvalomgång där klasserna turas om, sist finalerna. Ange första start och paus mellan heaten; **▲▼** ändrar ordningen. Ett heat som startar sent, drar ut på tiden eller pausas flyttar resten av dagen. + - **🖨 Skriv ut körordning** ger tider, klasser, heat och förare att sätta upp på tavlan i depån. + - **📺 Förarvy** (`/public-overlay/schedule`, finns även under Overlay) visar vad som körs, de tre nästa heaten med förare och en påminnelse "gör dig redo" 10 minuter innan, sedan resten av dagen. Den fungerar på mobilen eller en TV i depån. + - **▶ 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. Den körs bara i webbläsaren där den slogs på. **⏸ 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. - **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/ROADMAP.md b/ROADMAP.md index 303f4be..aacb6bc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -984,6 +984,17 @@ Asked for after the first ÖRC Winter round, where a qualifying went wrong and t - [ ] **Readable day PDF per class (optional, after the CSV).** The day result used for series points (manual ✎ Result if set), then every session in running order with its full result. Lap-by-lap times stay in the CSV. - [ ] **Publish to an external results site (e.g. House of RC).** Create the race / series there over its API and push the results (and optionally laps) after each session or at the end of the day, so the club's racing gets more exposure. Open questions before building: is there a public API and how is it authenticated (club account / API key stored in Settings), what format it expects (class, heats, qualifying, finals, points), whether it can be updated afterwards when a result is corrected by hand, and what happens when the club PC is offline (queue and retry). Start by investigating the API; keep the integration as a separate server module so a different site can be added later. +## Race day schedule, autopilot and drivers' board (2026-11-01) + +Asked for after the first ÖRC Winter round: a schedule for the whole day, one button that runs it, a pause button, a printed running order for the board, and a heads-up for drivers 10 minutes before their heat. + +- [x] One schedule per date across every class (`src/day_schedule_logic.js`): practice, each qualifying round with the classes taking turns, finals leg by leg from the lowest; ▲▼ stored as `state.raceDays[].sessionOrder`. Late, long or paused heats push the rest of the day. +- [x] Race Day panel with first start, gap, ▲▼, print and the drivers' board link (`src/day_schedule_view.js`). +- [x] Autopilot in the tab where it is turned on (sessionStorage): starts the next heat's count-down at planned start minus the count-down length; waits while anything runs, the decoder is offline or preflight fails. Pause the day pauses the heat on track or holds the count-down. +- [x] Drivers' board at `/public-overlay/schedule` with the next three heats, drivers in grid order and a heads-up within 10 minutes. +- [x] Race Setup's schedule follows the ▲▼ running order. +- [ ] Spoken heads-up ("Q2 H1 2WD starts in 10 minutes") - not asked for yet. + ## Documentation maintenance - [x] Update the architecture's module/dependency inventory as modules change. diff --git a/package-lock.json b/package-lock.json index 3ccc564..f1a4f1f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.49.0", + "version": "1.50.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.49.0", + "version": "1.50.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index d801859..a50dc4e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.49.0", + "version": "1.50.0", "private": true, "description": "RC RaceCore live timing and race control with AMMC ingest and SQLite persistence", "engines": { diff --git a/src/app.js b/src/app.js index a4585e5..205f293 100644 --- a/src/app.js +++ b/src/app.js @@ -8,6 +8,8 @@ import { buildRaceDayQueue, buildRaceDayPreflight, getRaceDriverIds } from "./ra import { recordTransponderSighting, buildWarmupCheck, createPrologue, getPrologueRemainingMs, holdPrologue, resumePrologue, setPrologueRemaining, takeDuePrologueCall, formatPrologueTime, getPrologueHandoverMs, normalizePrologueSec } from "./prologue_logic.js"; import { findTransponderConflict, getDriverProfileId } from "./driver_profile_logic.js"; import { renderRaceDayView, refreshRaceDayWarmup, refreshRaceDayPrologueClock, updateRaceDayStartDisplay, refreshRaceDayLive } from "./race_day_view.js"; +import { normalizeRaceDays, getRaceDay, upsertRaceDay, orderDaySessions, buildDaySchedule, getAutopilotAction, moveInDayOrder, pickBoardDate } from "./day_schedule_logic.js"; +import { renderDaySchedulePanel, bindDaySchedulePanel, buildDaySchedulePrintHtml, renderDriverBoard, formatClockTime } from "./day_schedule_view.js"; import { beginSession as beginSessionControl, finishSession as finishSessionControl, pauseSession as pauseSessionControl, resumeSession as resumeSessionControl } from "./session_control.js"; import { normalizeSeries, buildSeriesStandings, getSeriesRoundStatus, getSeriesRoundNextStep, getSeriesDayResult } from "./series_logic.js"; import { renderSeriesView } from "./series_view.js"; @@ -129,7 +131,7 @@ const getManualCorrectionSummary = (row) => getManualCorrectionSummaryLogic(row, const renderTeamStintLog = (session, rows) => renderTeamStintLogHelper(session, rows, { t, escapeHtml, buildTeamStintLog, formatTeamActiveMemberLabel, renderTable, formatRaceClock }); const renderTeamRaceStandings = (event) => renderTeamRaceStandingsHelper(event, { t, escapeHtml, buildTeamRaceStandings, getSessionTypeLabel, renderTable, formatTeamActiveMemberLabel, formatLap, formatRaceClock, renderTeamStintLog, buildSessionChannelStats }); const getSessionSortWeight = (session) => getSessionSortWeightHelper(session); -const buildEventSchedule = (event) => buildEventScheduleLogic(event, getSessionsForEvent(event.id), { getSessionSortWeight }); +const buildEventSchedule = (event) => buildEventScheduleLogic(event, getSessionsForEvent(event.id)); const getDriverDisplayById = (driverId) => getDriverDisplayByIdHelper(driverId, { state, t }); const renderPositionGrid = (session) => renderPositionGridHelper(session, { t, escapeHtml, getSessionGridEntries }); const renderGridEditor = (session) => renderGridEditorHelper(session, { t, escapeHtml, ensureSessionDriverOrder, state }); @@ -232,7 +234,12 @@ const startSessionWithAudio = (session, callbacks) => { .filter(Boolean); return raceAudioEngine.runStartSequence(session, { ...callbacks, skipAudio: skipCeremony, staggerOrder }); }; -const tickClock = () => tickClockHelper({ dom, currentLanguage, handleSessionTimerTick, getActiveSession, getCurrentView: () => currentView, getOverlayMode: () => overlayMode, renderView, refreshTimingDynamics, updateHeaderState }); +const tickClock = () => { + tickClockHelper({ dom, currentLanguage, handleSessionTimerTick, getActiveSession, getCurrentView: () => currentView, getOverlayMode: () => overlayMode, renderView, refreshTimingDynamics, updateHeaderState }); + tickAutopilot(); + // The drivers' board counts down to each heat. + if (overlayMode && overlayViewMode === "schedule") renderView(); +}; const buildTeamRaceResultsHtml = (event) => buildTeamRaceResultsHtmlHelper(event, { t, escapeHtml, resolveEventBranding, getClassName, buildPrintBrandBlock, buildTeamRaceStandings, renderTable, formatLap, renderTeamStintLog, renderSessionChannelAnalysis }); const connectDecoder = () => connectDecoderHelper({ state, @@ -359,6 +366,118 @@ function setRacePrologueRemaining(remainingMs) { setRacePrologue(setPrologueRemaining(racePrologue, remainingMs)); renderView(); } +// --- The race day schedule and its autopilot ------------------------------------------ +// The plan (start time, gap, order, paused) is shared in state.raceDays; the autopilot runs +// only in the tab where it was switched on (sessionStorage), like the count-down, so two +// browsers never start the same heat. +const AUTOPILOT_STORAGE_KEY = "rc_day_autopilot"; +let autopilotDate = (() => { try { return sessionStorage.getItem(AUTOPILOT_STORAGE_KEY) || ""; } catch { return ""; } })(); +let autopilotStatus = ""; +let autopilotLaunchingId = null; +const todayKey = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; }; +const getDayPlan = (date) => getRaceDay(state.raceDays, date); +const saveDayPlan = (day) => { state.raceDays = upsertRaceDay(state.raceDays, day); saveState(); }; +const getDayClassLabel = (session) => { const event = state.events.find((item) => item.id === session.eventId); return event?.classId ? getClassName(event.classId) : event?.name || ""; }; +function buildDayRows(date, now = Date.now()) { + const day = getDayPlan(date); + const ordered = orderDaySessions({ events: state.events, sessions: state.sessions, date, manualOrder: day.sessionOrder }); + return buildDaySchedule(ordered, day, now).map((row) => ({ ...row, driverCount: getSessionGridEntries(row.session).length })); +} +// Race Day works on the date of the session in focus, else today. +const getRaceDayDate = () => { + const session = buildRaceDayQueue(state).current; + const event = session ? state.events.find((item) => item.id === session.eventId) : null; + return event?.mode === "race" && event.date ? event.date : todayKey(); +}; +const usesCountDown = (session) => Boolean(session && session.mode !== "track" && session.type !== "team_race" && !isPracticeSessionType(session.type)); +function setAutopilot(date, on) { + autopilotDate = on ? date : ""; + try { if (on) sessionStorage.setItem(AUTOPILOT_STORAGE_KEY, date); else sessionStorage.removeItem(AUTOPILOT_STORAGE_KEY); } catch { /* per tab only */ } + autopilotStatus = ""; + saveDayPlan({ ...getDayPlan(date), autopilot: on }); + tickAutopilot(); + renderView(); +} +function describeAutopilot(action) { + const name = action.row ? `${getDayClassLabel(action.row.session)} ${action.row.session.name}`.trim() : ""; + if (action.reason === "until") return t("day.auto_until", { name, time: formatDayClock(action.row.start), min: Math.max(0, Math.ceil((action.launchAt - Date.now()) / 60000)) }); + return t(`day.auto_${action.reason}`, { name }); +} +function tickAutopilot() { + if (!autopilotDate || overlayMode) return; + const day = getDayPlan(autopilotDate); + const rows = buildDayRows(autopilotDate); + const busy = Boolean(getPrologueSession() || pendingStartSessionId || startsInProgress > 0 || autopilotLaunchingId + || state.sessions.some((session) => ["running", "paused"].includes(session.status))); + let action = getAutopilotAction(rows, { day, busy, prologueMs: (session) => (usesCountDown(session) ? getDefaultPrologueSec(session) * 1000 : 0) }); + if (action.type === "start") { + const session = action.row.session; + if (!state.decoder?.connected) action = { type: "wait", reason: "decoder", row: action.row }; + else if (!buildRaceDayPreflight(state, session, { backendAvailable: backend.available }).ready) action = { type: "wait", reason: "preflight", row: action.row }; + } + autopilotStatus = describeAutopilot(action); + document.querySelectorAll("[data-autopilot-status]").forEach((node) => { node.textContent = autopilotStatus; }); + if (action.type !== "start") return; + const session = action.row.session; + autopilotLaunchingId = session.id; + selectOperationalSession(session.id, { render: false }); + if (usesCountDown(session)) { + startRacePrologue(session, getDefaultPrologueSec(session)); + autopilotLaunchingId = null; + return; + } + void startOperationalSession(session, { requirePreflight: true }).finally(() => { autopilotLaunchingId = null; renderView(); }); +} +// Pausing the day stops the autopilot and pauses whatever is on track (or holds the count-down). +function pauseRaceDay(date) { + saveDayPlan({ ...getDayPlan(date), pausedAt: Date.now() }); + const live = state.sessions.find((session) => session.status === "running"); + if (live) pauseOperationalSession(live); + if (getPrologueSession() && racePrologue.heldRemainingMs === null) holdRacePrologue(); + renderView(); +} +function resumeRaceDay(date) { + saveDayPlan({ ...getDayPlan(date), pausedAt: null }); + const paused = state.sessions.find((session) => session.status === "paused" && session.mode === "race" && !isPracticeSessionType(session.type)); + if (paused) resumeOperationalSession(paused); + if (getPrologueSession() && racePrologue.heldRemainingMs !== null) resumeRacePrologue(); + renderView(); +} +function moveDaySession(date, sessionId, step) { + const day = getDayPlan(date); + const ordered = orderDaySessions({ events: state.events, sessions: state.sessions, date, manualOrder: day.sessionOrder }); + saveDayPlan({ ...day, sessionOrder: moveInDayOrder(ordered, sessionId, step) }); + renderView(); +} +const formatDayClock = (ts) => formatClockTime(ts); +const renderDaySchedule = () => { + const date = getRaceDayDate(); + return renderDaySchedulePanel({ t, escapeHtml, date, day: getDayPlan(date), rows: buildDayRows(date), autopilotHere: autopilotDate === date, autopilotStatus: autopilotDate === date ? autopilotStatus : "", getClassLabel: getDayClassLabel }); +}; +const bindDaySchedule = (root) => { + const date = getRaceDayDate(); + bindDaySchedulePanel(root, { + date, + onSavePlan: ({ startAt, gapMin }) => { saveDayPlan({ ...getDayPlan(date), startAt, gapMin }); renderView(); }, + onMove: (sessionId, step) => moveDaySession(date, sessionId, step), + onPrint: () => openPrintWindow(t("day.print_title", { date }), buildDaySchedulePrintHtml({ t, escapeHtml, date, rows: buildDayRows(date), getClassLabel: getDayClassLabel, getSessionGridEntries })), + onBoard: () => window.open(buildOverlayUrl("schedule", { public: true }), "_blank"), + onAutopilot: (on) => { + if (on && !window.confirm(t("day.autopilot_confirm"))) return; + setAutopilot(date, on); + }, + onPause: () => pauseRaceDay(date), + onResume: () => resumeRaceDay(date), + }); +}; +const renderBoard = () => { + const date = pickBoardDate({ events: state.events, sessions: state.sessions, today: todayKey() }); + dom.view.innerHTML = renderDriverBoard({ + t, escapeHtml, date, rows: buildDayRows(date), getClassLabel: getDayClassLabel, getSessionGridEntries, + getRemainingLabel: (session) => { const timing = getSessionTiming(session); return timing.untimed ? formatElapsedClock(timing.elapsedMs) : formatCountdown(timing.remainingMs); }, + }); +}; + // --- Race Day as the place where things are run -------------------------------------- // "New practice day": clears the session's laps on Timing for a new day; every lap so far // is first put in the training stats, where resultsResetAt keeps it (see syncTrainingLedger). @@ -500,6 +619,7 @@ const renderRaceDay = () => renderRaceDayView({ getLiveSession, renderSuspectLapsPanel: (session) => renderSuspectLapsPanelWithRelease(session), buildLeaderboard, getSessionTargetMs, formatRaceClock, + renderDaySchedule, bindDaySchedule, setCompetitorLapStatus, addTrackLayout, renderView, state, dom, t, escapeHtml, formatLap, formatCountdown, formatElapsedClock, getEventName, getSessionTypeLabel, getStatusLabel, getStartModeLabel, @@ -2623,6 +2743,7 @@ const TRANSLATIONS = { "guide.race_day_8": "8. Redan när du registrerar eller ändrar en förare under Förare varnar systemet om transpondern redan används av en annan förare (t.ex. i fel klass) och namnger vem - ett komplement till förkontrollens kontroll av dubbla transpondrar inom samma heat. Samma person som kör flera klasser med sin egen transponder flaggas aldrig.", "guide.race_day_9": "9. Kör ni på ett nät där fler har åtkomst (t.ex. arenans WiFi)? Slå på Admin-PIN under Inställningar -> System & backup. Då kräver alla ändringar PIN - resultat, inställningar och uppdatering - medan visning och publika overlay-/träningslänkar fungerar som vanligt. Varje webbläsare loggar in en gång och kommer ihåg det i 30 dagar.", "guide.race_day_10": "10. Start med nedräkning (som EFRA/IFMAR): välj längd (Go, 30 s, 1, 1:30, 2, 3 eller 5 min - standard per tävling under Race Setup) och tryck Starta. Banan är öppen, speakern ropar ut tiden (varje minut, 30 s, 10 s; vid gridstart även \"bilarna till startplatsen\" vid 30 s och 9..3). Pausa medan bilarna ställs upp, +1 min, Till 30 s (omstart av gridet), Till 10 s, Go nu eller Avbryt. När tiden går ut startar heatet av sig själv: gridstart får startljus och slumpad signal, flygande start ger signalen och \"Klockan går\". Transponderkontrollen visar grön bock för alla som passerat sedan nedräkningen började - saknas någon, byt transponder direkt i panelen eller välj en okänd transponder som passerat. Go nu varnar om någon inte setts.", + "guide.race_day_11": "11. Dagens schema (längst ned på Race Day) visar alla klasser den dagen i en körordning med tider. Ange första start och paus mellan heaten; ▲▼ ändrar ordningen. Ett heat som startar sent eller pausas flyttar resten av dagen. 🖨 Skriv ut körordning ger en lista med tider och förare att sätta upp på tavlan, och 📺 Förarvy (/public-overlay/schedule) visar förarna nästa heat med vilka som kör och en påminnelse när det är 10 minuter kvar. ▶ Kör dagen automatiskt startar varje heats nedräkning själv när det är dags (den här webbläsaren måste vara öppen); ⏸ Pausa dagen pausar heatet på banan och automatiken tills du fortsätter.", "guide.dashboard_title": "Schemaavvikelse på Översikt", "guide.dashboard_1": "Översikt visar nu skillnaden mellan planerad tid och faktisk körtid för alla startade sessioner.", "guide.dashboard_2": "Planerad tid räknar sessionstid plus follow-up. Faktisk tid räknar verklig tid från start till stopp eller nuvarande tid om heatet fortfarande kör.", @@ -2678,6 +2799,40 @@ const TRANSLATIONS = { "overlay.mode_results": "Resultat", "overlay.mode_tv": "TV", "overlay.mode_team": "Team", + "overlay.mode_schedule": "Förarvy: dagens schema", + "day.title": "Dagens schema · {date}", + "day.hint": "Alla klasser i körordning med planerade tider. Ett heat som startar sent eller pausas flyttar resten av dagen. ▲▼ ändrar ordningen.", + "day.print": "Skriv ut körordning", + "day.board": "Förarvy", + "day.start_time": "Första start", + "day.gap": "Paus mellan heat (min)", + "day.autopilot_on": "Kör dagen automatiskt", + "day.autopilot_off": "Stoppa automatiken", + "day.autopilot_confirm": "Kör dagen automatiskt? Varje heat startar sin nedräkning själv när det är dags enligt schemat. Du kan pausa dagen eller ta över när som helst. Låt den här webbläsaren vara öppen.", + "day.autopilot_elsewhere": "Automatiken körs på en annan dator.", + "day.pause": "Pausa dagen", + "day.resume": "Fortsätt dagen", + "day.col_time": "Tid", + "day.col_session": "Klass · heat", + "day.col_drivers": "Förare", + "day.state_done": "Klar", + "day.state_live": "Pågår", + "day.state_paused": "Pausad", + "day.in_min": "om {min} min", + "day.auto_until": "Nästa: {name} kl {time} – nedräkningen börjar om {min} min", + "day.auto_running": "Väntar tills heatet på banan är klart", + "day.auto_paused": "Dagen är pausad", + "day.auto_done": "Alla heat i schemat är körda", + "day.auto_decoder": "Väntar: decodern är inte ansluten ({name} står på tur)", + "day.auto_preflight": "Väntar: {name} är inte redo – se kontrollerna", + "day.print_title": "Körordning {date}", + "day.print_hint": "Tiderna är planerade och kan flyttas om något drar ut på tiden. Följ förarvyn för aktuella tider.", + "day.board_title": "Dagens schema {date}", + "day.board_now": "startar nu", + "day.board_heads_up": "Gör dig redo – snart dags!", + "day.board_on_track": "På banan", + "day.board_all_done": "Alla heat är körda för idag.", + "day.board_none": "Inget schema för idag.", "overlay.mode_obs": "OBS", "overlay.fastest_lap": "Snabbaste varv", "overlay.fullscreen": "Fullscreen", @@ -4520,6 +4675,7 @@ const TRANSLATIONS = { "guide.race_day_8": "8. Already when you register or edit a driver under Drivers, the system warns if the transponder is already used by a different driver (e.g. in the wrong class) and names who - a complement to the preflight's duplicate-transponder check within a single heat. The same person racing multiple classes on their own transponder is never flagged.", "guide.race_day_9": "9. Running on a network others can reach (e.g. the venue WiFi)? Turn on the Admin PIN under Settings -> System & backup. Every change then needs the PIN - results, settings and updates - while viewing and public overlay/training links work as usual. Each browser logs in once and is remembered for 30 days.", "guide.race_day_10": "10. Start with a count-down (as EFRA/IFMAR): pick a length (Go, 30 s, 1, 1:30, 2, 3 or 5 min - the default per event is set in Race Setup) and press Start. The track is open and the announcer calls the time (every minute, 30 s, 10 s; for a grid start also \"cars to the grid\" at 30 s and 9..3). Hold while cars are placed on the grid, +1 min, To 30 s (grid restart), To 10 s, Go now or Cancel. When the time runs out the heat starts by itself: a grid start gets the start lights and a random signal, a flying start gets the signal and \"Clock is running\". The transponder check shows a green tick for everyone who has crossed since the count-down began - if someone is missing, change their transponder right in the panel or pick an unknown transponder that crossed. Go now warns if someone wasn't seen.", + "guide.race_day_11": "11. Today's schedule (at the bottom of Race Day) shows every class that day in one running order with times. Set the first start and the break between heats; ▲▼ change the order. A heat that starts late or is paused moves the rest of the day. 🖨 Print running order gives a list with times and drivers for the board in the pits, and 📺 Drivers' board (/public-overlay/schedule) shows drivers the next heats, who drives them and a heads-up 10 minutes before. ▶ Run the day automatically starts each heat's count-down on its own when it is due (keep this browser open); ⏸ Pause the day pauses the heat on track and the autopilot until you resume.", "guide.dashboard_title": "Schedule drift on overview", "guide.dashboard_1": "Overview now shows the difference between planned time and actual elapsed time for all started sessions.", "guide.dashboard_2": "Planned time includes session duration plus follow-up. Actual time uses real time from start to stop, or the current time if the heat is still running.", @@ -4575,6 +4731,40 @@ const TRANSLATIONS = { "overlay.mode_results": "Results", "overlay.mode_tv": "TV", "overlay.mode_team": "Team", + "overlay.mode_schedule": "Drivers' board: today's schedule", + "day.title": "Today's schedule · {date}", + "day.hint": "Every class in running order with planned times. A heat that starts late or is paused moves the rest of the day. ▲▼ change the order.", + "day.print": "Print running order", + "day.board": "Drivers' board", + "day.start_time": "First start", + "day.gap": "Break between heats (min)", + "day.autopilot_on": "Run the day automatically", + "day.autopilot_off": "Stop autopilot", + "day.autopilot_confirm": "Run the day automatically? Each heat starts its own count-down when the schedule says so. You can pause the day or take over at any time. Keep this browser open.", + "day.autopilot_elsewhere": "The autopilot runs on another computer.", + "day.pause": "Pause the day", + "day.resume": "Resume the day", + "day.col_time": "Time", + "day.col_session": "Class · heat", + "day.col_drivers": "Drivers", + "day.state_done": "Done", + "day.state_live": "Running", + "day.state_paused": "Paused", + "day.in_min": "in {min} min", + "day.auto_until": "Next: {name} at {time} – count-down starts in {min} min", + "day.auto_running": "Waiting for the heat on track to finish", + "day.auto_paused": "The day is paused", + "day.auto_done": "Every heat in the schedule has been run", + "day.auto_decoder": "Waiting: the decoder is not connected ({name} is next)", + "day.auto_preflight": "Waiting: {name} is not ready – see the checks", + "day.print_title": "Running order {date}", + "day.print_hint": "Times are planned and can move if something runs long. Follow the drivers' board for current times.", + "day.board_title": "Today's schedule {date}", + "day.board_now": "starting now", + "day.board_heads_up": "Get ready – almost time!", + "day.board_on_track": "On track", + "day.board_all_done": "Every heat has been run today.", + "day.board_none": "No schedule for today.", "overlay.mode_obs": "OBS", "overlay.fastest_lap": "Fastest Lap", "overlay.fullscreen": "Fullscreen", @@ -4666,7 +4856,7 @@ const TRANSLATIONS = { }; const urlParams = new URLSearchParams(window.location.search); -const allowedOverlayModes = ["leaderboard", "speaker", "results", "tv", "team", "obs"]; +const allowedOverlayModes = ["leaderboard", "speaker", "results", "tv", "team", "obs", "schedule"]; const publicOverlayMatch = window.location.pathname.match(/^\/public-overlay(?:\/([a-z0-9_-]+))?\/?$/i); const routeOverlayMode = String(publicOverlayMatch?.[1] || "").toLowerCase(); const queryOverlayMode = String(urlParams.get("overlayMode") || "").toLowerCase(); @@ -5168,6 +5358,7 @@ function seedDefaultData() { state.training = normalizeTrainingState(state.training); state.trackLayouts = normalizeTrackLayouts(state.trackLayouts, { uid }); state.series = normalizeSeriesList(state.series); + state.raceDays = normalizeRaceDays(state.raceDays); saveState({ skipBackend: true }); } @@ -5189,6 +5380,7 @@ function loadState() { activeSessionId: parsed.activeSessionId || null, trackLayouts: normalizeTrackLayouts(parsed.trackLayouts, { uid }), series: normalizeSeriesList(parsed.series), + raceDays: normalizeRaceDays(parsed.raceDays), settings: { wsUrl: parsed.settings?.wsUrl || "ws://127.0.0.1:9000", splitDecoderEnabled: parsed.settings?.splitDecoderEnabled === true, @@ -5261,6 +5453,7 @@ function loadState() { activeSessionId: null, trackLayouts: [], series: [], + raceDays: [], settings: { wsUrl: "ws://127.0.0.1:9000", splitDecoderEnabled: false, @@ -5539,6 +5732,7 @@ function buildPersistableState() { settings: state.settings, trackLayouts: normalizeTrackLayouts(state.trackLayouts, { uid }), series: normalizeSeriesList(state.series), + raceDays: normalizeRaceDays(state.raceDays), }; } @@ -6181,7 +6375,8 @@ function renderView() { renderJudging(); break; case "overlay": - renderOverlay(); + if (overlayViewMode === "schedule") renderBoard(); + else renderOverlay(); break; case "settings": renderSettings({ diff --git a/src/day_schedule_logic.js b/src/day_schedule_logic.js new file mode 100644 index 0000000..89c2ec0 --- /dev/null +++ b/src/day_schedule_logic.js @@ -0,0 +1,144 @@ +// The race day as one schedule: every race session of every class on one date, in one running +// order with planned times, plus what the autopilot should do next. Pure logic - the panel is +// in day_schedule_view.js and the runner in app.js. +import { applyManualOrder, orderSessionsForRunning, parseQualifyingHeatName } from "./event_race_logic.js"; + +export const DEFAULT_DAY_GAP_MIN = 3; +export const HEADS_UP_MS = 10 * 60000; + +// One plan per date: { date, startAt, gapMin, sessionOrder, autopilot, pausedAt }. +export function normalizeRaceDay(day = {}) { + return { + date: String(day.date || ""), + startAt: Number(day.startAt) > 0 ? Number(day.startAt) : null, + gapMin: Number.isFinite(Number(day.gapMin)) && day.gapMin !== null && day.gapMin !== "" ? Math.max(0, Number(day.gapMin)) : DEFAULT_DAY_GAP_MIN, + sessionOrder: [...new Set((Array.isArray(day.sessionOrder) ? day.sessionOrder : []).map(String).filter(Boolean))], + autopilot: day.autopilot === true, + pausedAt: Number(day.pausedAt) > 0 ? Number(day.pausedAt) : null, + }; +} + +export function normalizeRaceDays(list) { + const byDate = new Map(); + (Array.isArray(list) ? list : []).map(normalizeRaceDay).filter((day) => /^\d{4}-\d{2}-\d{2}$/.test(day.date)).forEach((day) => byDate.set(day.date, day)); + return [...byDate.values()]; +} + +export function getRaceDay(raceDays, date) { + return (raceDays || []).find((day) => day.date === date) || normalizeRaceDay({ date }); +} + +// Stores a changed plan for its date; returns the new list. +export function upsertRaceDay(raceDays, day) { + const next = normalizeRaceDay(day); + return [...(raceDays || []).filter((item) => item.date !== next.date), next]; +} + +const sessionDurationMs = (session) => Math.max(1, Number(session.durationMin || 0)) * 60000 + Math.max(0, Number(session.followUpSec || 0)) * 1000; +const isDone = (session) => ["finished", "stopped"].includes(session.status); +const isLive = (session) => ["running", "paused"].includes(session.status); + +// Where a session sits in the day: practice, then qualifying round by round, then finals leg +// by leg (lowest final first). Classes take turns within each step. +function dayStepKey(session) { + if (["practice", "free_practice", "open_practice"].includes(session.type)) return [0, 0, 0]; + if (session.type === "final") { + const match = String(session.name || "").match(/^([A-Z])\b.*?(\d+)\s*$/); + return match ? [2, Number(match[2]), -match[1].charCodeAt(0)] : [2, 0, 0]; + } + return [1, parseQualifyingHeatName(session.name)?.round || 0, 0]; +} +const compareKeys = (a, b) => a.reduce((diff, value, i) => diff || value - b[i], 0); + +// The race events of a date (one per class) and their race sessions, in the day's running order. +export function orderDaySessions({ events = [], sessions = [], date, manualOrder = [] }) { + const dayEvents = events.filter((event) => event.mode === "race" && event.date === date) + .sort((a, b) => String(a.name || "").localeCompare(String(b.name || ""), undefined, { numeric: true })); + const items = dayEvents.flatMap((event, eventIndex) => { + const own = orderSessionsForRunning(sessions.filter((session) => session.eventId === event.id && session.mode === "race"), event.sessionOrder); + // A step never goes back within a class, so a class's own ▲▼ order is kept. + let step = [0, 0, 0]; + return own.map((session, position) => { + const key = dayStepKey(session); + if (compareKeys(key, step) > 0) step = key; + return { session, event, key: [...step, eventIndex, position] }; + }); + }); + const auto = items.sort((a, b) => compareKeys(a.key, b.key)).map((item) => item.session); + return applyManualOrder(auto, manualOrder); +} + +export function moveInDayOrder(ordered, sessionId, step) { + const ids = ordered.map((session) => session.id); + const index = ids.indexOf(sessionId); + const other = index + step; + if (index < 0 || other < 0 || other >= ids.length) return ids; + [ids[index], ids[other]] = [ids[other], ids[index]]; + return ids; +} + +// Planned time for each session. A session that started or finished re-anchors everything +// after it; one that should have started but hasn't is expected now, so a paused day or a +// late heat pushes the rest of the day on its own. Without a start time the day runs from +// its first real start, else from now. +export function buildDaySchedule(ordered, day, now = Date.now()) { + const gapMs = Math.max(0, Number(day?.gapMin ?? DEFAULT_DAY_GAP_MIN)) * 60000; + const firstStart = ordered.map((session) => Number(session.startedAt || 0)).filter(Boolean).sort((a, b) => a - b)[0]; + let cursor = Number(day?.startAt || 0) || firstStart || now; + let upcomingIndex = 0; + return ordered.map((session) => { + const durationMs = sessionDurationMs(session); + const actualStart = Number(session.startedAt || 0) || null; + const actualEnd = isDone(session) ? Number(session.endedAt || 0) || null : null; + const planned = cursor; + let state = "upcoming"; + let start = planned; + let end; + if (isDone(session)) { + state = "done"; + start = actualStart || planned; + end = actualEnd || start + durationMs; + } else if (isLive(session) && actualStart) { + state = "live"; + start = actualStart; + const pausedMs = Number(session.totalPausedMs || 0) + (session.status === "paused" && session.pausedAt ? Math.max(0, now - Number(session.pausedAt)) : 0); + end = Math.max(now, actualStart + durationMs + pausedMs); + } else { + start = Math.max(planned, now); + end = start + durationMs; + } + cursor = end + gapMs; + return { + session, + state, + plannedStart: planned, + start, + end, + upcomingIndex: state === "upcoming" ? upcomingIndex++ : null, + delayed: Boolean((actualStart || (state === "upcoming" ? start : 0)) > planned + 60000), + }; + }); +} + +// What the autopilot does now: { type: "start", row, launchAt } or { type: "wait", reason, row?, launchAt? }. +// prologueMs(session) = how long before the planned start its count-down begins. +export function getAutopilotAction(rows, { day, now = Date.now(), busy = false, prologueMs = () => 0 }) { + if (day?.pausedAt) return { type: "wait", reason: "paused" }; + if (busy || rows.some((row) => row.state === "live")) return { type: "wait", reason: "running" }; + const row = rows.find((item) => item.state === "upcoming"); + if (!row) return { type: "wait", reason: "done" }; + const launchAt = row.start - Math.max(0, Number(prologueMs(row.session) || 0)); + return now >= launchAt ? { type: "start", row, launchAt } : { type: "wait", reason: "until", row, launchAt }; +} + +// The date the drivers' board shows: today if anything is raced today, else the next date with +// a session still to run, else today. +export function pickBoardDate({ events = [], sessions = [], today }) { + const raceDates = new Set(events.filter((event) => event.mode === "race" && event.date).map((event) => event.date)); + if (raceDates.has(today)) return today; + const pending = events + .filter((event) => event.mode === "race" && event.date >= today && sessions.some((session) => session.eventId === event.id && !isDone(session))) + .map((event) => event.date) + .sort(); + return pending[0] || today; +} diff --git a/src/day_schedule_view.js b/src/day_schedule_view.js new file mode 100644 index 0000000..65a81ac --- /dev/null +++ b/src/day_schedule_view.js @@ -0,0 +1,142 @@ +// The race day schedule on screen: the panel on Race Day (plan, order, autopilot, pause), the +// printable running order for the board in the pits, and the drivers' board +// (/public-overlay/schedule). Logic in day_schedule_logic.js, the autopilot runner in app.js. +import { HEADS_UP_MS } from "./day_schedule_logic.js"; + +export const formatClockTime = (ts) => (ts ? new Date(ts).toLocaleTimeString("sv-SE", { hour: "2-digit", minute: "2-digit" }) : "-"); +const toTimeInput = (ts) => (ts ? formatClockTime(ts) : ""); +const minutesUntil = (ts, now) => Math.max(0, Math.ceil((ts - now) / 60000)); + +function rowLabel(row, getClassLabel) { + return [getClassLabel(row.session), row.session.name].filter(Boolean).join(" · "); +} + +function stateLabel(row, t, now) { + if (row.state === "done") return t("day.state_done"); + if (row.state === "live") return t(row.session.status === "paused" ? "day.state_paused" : "day.state_live"); + if (row.start - now <= HEADS_UP_MS) return t("day.in_min", { min: minutesUntil(row.start, now) }); + return ""; +} + +export function renderDaySchedulePanel({ t, escapeHtml, date, day, rows, autopilotHere, autopilotStatus, getClassLabel, now = Date.now() }) { + if (!rows.length) return ""; + return ` +
+
+

${escapeHtml(t("day.title", { date }))}

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

+
+ + +
+
+
+
+ + + +
+
+ ${autopilotHere + ? `` + : ``} + ${day.pausedAt + ? `` + : ``} + ${escapeHtml(autopilotStatus || (day.autopilot && !autopilotHere ? t("day.autopilot_elsewhere") : ""))} +
+ + + + ${rows.map((row, index) => ` + + + + + + + `).join("")} + +
${escapeHtml(t("day.col_time"))}${escapeHtml(t("day.col_session"))}${escapeHtml(t("day.col_drivers"))}
${formatClockTime(row.start)}${row.delayed && row.state !== "done" ? ` (${formatClockTime(row.plannedStart)})` : ""}${escapeHtml(rowLabel(row, getClassLabel))}${row.driverCount ?? ""}${escapeHtml(stateLabel(row, t, now))} + + +
+
+
`; +} + +export function bindDaySchedulePanel(root, { date, onSavePlan, onMove, onPrint, onBoard, onAutopilot, onPause, onResume }) { + root.querySelector("#dayPlanForm")?.addEventListener("submit", (event) => { + event.preventDefault(); + const form = new FormData(event.currentTarget); + const time = String(form.get("startTime") || "").trim(); + const startAt = time ? new Date(`${date}T${time}`).getTime() : null; + onSavePlan({ startAt: Number.isFinite(startAt) ? startAt : null, gapMin: Math.max(0, Number(form.get("gapMin")) || 0) }); + }); + root.querySelectorAll("[data-day-move]").forEach((button) => button.addEventListener("click", () => onMove(button.dataset.dayMove, Number(button.dataset.step)))); + root.querySelector("#dayPrint")?.addEventListener("click", onPrint); + root.querySelector("#dayBoard")?.addEventListener("click", onBoard); + root.querySelector("#dayAutopilotOn")?.addEventListener("click", () => onAutopilot(true)); + root.querySelector("#dayAutopilotOff")?.addEventListener("click", () => onAutopilot(false)); + root.querySelector("#dayPause")?.addEventListener("click", onPause); + root.querySelector("#dayResume")?.addEventListener("click", onResume); +} + +// For the board in the pits: time, class, session and the drivers in grid order. +export function buildDaySchedulePrintHtml({ t, escapeHtml, date, rows, getClassLabel, getSessionGridEntries }) { + return ` + +
+

${escapeHtml(t("day.print_title", { date }))}

+

${escapeHtml(t("day.print_hint"))}

+ + + + ${rows.map((row) => ` + + + + `).join("")} + +
${escapeHtml(t("day.col_time"))}${escapeHtml(t("day.col_session"))}${escapeHtml(t("day.col_drivers"))}
${formatClockTime(row.start)}${escapeHtml(rowLabel(row, getClassLabel))}
    ${getSessionGridEntries(row.session).map((entry) => `
  1. ${escapeHtml(entry.name)}
  2. `).join("")}
+
`; +} + +// The drivers' board: what is on track, the next heats with a heads-up and who drives them, +// then the rest of the day. +export function renderDriverBoard({ t, escapeHtml, date, rows, getClassLabel, getSessionGridEntries, getRemainingLabel, now = Date.now() }) { + const live = rows.find((row) => row.state === "live"); + const next = rows.filter((row) => row.state === "upcoming").slice(0, 3); + const later = rows.filter((row) => row.state === "upcoming").slice(3); + const card = (row) => { + const soon = row.start - now <= HEADS_UP_MS; + const minutes = minutesUntil(row.start, now); + return ` +
+
+ ${formatClockTime(row.start)} + ${escapeHtml(minutes <= 0 ? t("day.board_now") : t("day.in_min", { min: minutes }))} +
+

${escapeHtml(rowLabel(row, getClassLabel))}

+ ${soon ? `

${escapeHtml(t("day.board_heads_up"))}

` : ""} +
    ${getSessionGridEntries(row.session).map((entry) => `
  1. ${escapeHtml(entry.name)}
  2. `).join("") || `
  3. ${escapeHtml(t("race_day.no_start_list"))}
  4. `}
+
`; + }; + return ` +
+
+

${escapeHtml(t("day.board_title", { date }))}

+ ${formatClockTime(now)} +
+ ${live ? `
${escapeHtml(t("day.board_on_track"))}: ${escapeHtml(rowLabel(live, getClassLabel))} ${escapeHtml(getRemainingLabel(live.session))}
` : ""} + ${next.length ? `
${next.map(card).join("")}
` : `

${escapeHtml(t(rows.length ? "day.board_all_done" : "day.board_none"))}

`} + ${later.length ? `${later.map((row) => ``).join("")}
${formatClockTime(row.start)}${escapeHtml(rowLabel(row, getClassLabel))}
` : ""} +
`; +} diff --git a/src/event_race_logic.js b/src/event_race_logic.js index 963e0c8..eb8f5b6 100644 --- a/src/event_race_logic.js +++ b/src/event_race_logic.js @@ -771,7 +771,12 @@ export function generateQualifyingForRace(event, { buildPracticeStandings, getEv // manualOrder (event.sessionOrder, set with ▲▼ in Race Setup) overrides it for the sessions it // lists; a session made later keeps its own place, e.g. a recreated Q1 H2 after Q1 H1. export function orderSessionsForRunning(sessions = [], manualOrder = []) { - const auto = orderSessionsAutomatically(sessions); + return applyManualOrder(orderSessionsAutomatically(sessions), manualOrder); +} + +// The ids in manualOrder take the slots those sessions have in the automatic order, in the +// listed order; every other session keeps its automatic slot. +export function applyManualOrder(auto = [], manualOrder = []) { const byId = new Map(auto.map((session) => [session.id, session])); const listed = [...new Set(manualOrder || [])].filter((id) => byId.has(id)).map((id) => byId.get(id)); if (!listed.length) return auto; @@ -1090,21 +1095,14 @@ export function applyBumpsForRace(event, { buildFinalStandings, getSessionsForEv // of the original plan - a heat that started late or ran long (including any pause; a // paused session's real endedAt already reflects the full wall-clock time it took) // automatically pushes the rest of the day forward, with no separate "reschedule" step. -export function buildEventSchedule(event, sessions, { getSessionSortWeight }) { +export function buildEventSchedule(event, sessions) { const scheduleStartAt = Number(event?.raceConfig?.scheduleStartAt || 0) || null; if (!scheduleStartAt) { return []; } const gapMs = Math.max(0, Number(event?.raceConfig?.scheduleGapMin ?? 3) || 0) * 60000; - const ordered = [...sessions] - .filter((session) => session.mode === "race") - .sort((left, right) => { - const weightDiff = getSessionSortWeight(left) - getSessionSortWeight(right); - if (weightDiff !== 0) { - return weightDiff; - } - return String(left.name || "").localeCompare(String(right.name || "")); - }); + // The same running order as Race Setup and Race Day (▲▼ included). + const ordered = orderSessionsForRunning(sessions.filter((session) => session.mode === "race"), event?.sessionOrder); let cursor = scheduleStartAt; return ordered.map((session) => { diff --git a/src/misc_views.js b/src/misc_views.js index a885ab6..68c57d9 100644 --- a/src/misc_views.js +++ b/src/misc_views.js @@ -99,7 +99,7 @@ export function renderGuideView({ dom, t }) {
- ${renderGuidePanel("guide.race_day_title", ["guide.race_day_1", "guide.race_day_2", "guide.race_day_3", "guide.race_day_4", "guide.race_day_5", "guide.race_day_6", "guide.race_day_7", "guide.race_day_8", "guide.race_day_9", "guide.race_day_10"], "", { t })} + ${renderGuidePanel("guide.race_day_title", ["guide.race_day_1", "guide.race_day_2", "guide.race_day_3", "guide.race_day_4", "guide.race_day_5", "guide.race_day_6", "guide.race_day_7", "guide.race_day_8", "guide.race_day_9", "guide.race_day_10", "guide.race_day_11"], "", { t })} ${renderGuidePanel("guide.manage_steps_title", ["guide.manage_steps_1", "guide.manage_steps_2", "guide.manage_steps_3", "guide.manage_steps_4", "guide.manage_steps_5", "guide.manage_steps_6", "guide.manage_steps_7", "guide.manage_steps_8", "guide.manage_steps_9"], "", { t })}
@@ -213,6 +213,7 @@ export function renderOverlayPageView(deps) { +
@@ -348,6 +349,7 @@ export function renderOverlayPageView(deps) { document.getElementById("overlayLaunchTv")?.addEventListener("click", () => openOverlayWindow("tv")); document.getElementById("overlayLaunchTeam")?.addEventListener("click", () => openOverlayWindow("team")); document.getElementById("overlayLaunchObs")?.addEventListener("click", () => openOverlayWindow("obs", { public: true })); + document.getElementById("overlayLaunchSchedule")?.addEventListener("click", () => openOverlayWindow("schedule", { public: true })); document.getElementById("overlayCopyObsUrl")?.addEventListener("click", async () => { const url = buildOverlayUrl("obs", { public: true }); if (navigator.clipboard?.writeText) { diff --git a/src/race_day_view.js b/src/race_day_view.js index 00c5470..4f17c1e 100644 --- a/src/race_day_view.js +++ b/src/race_day_view.js @@ -263,6 +263,7 @@ export function renderRaceDayView(deps) { isStartPending, renderSuspectLapsPanel = () => "", setCompetitorLapStatus = () => false, getLiveSession = () => null, resetSessionData = () => false, startPracticeNow = async () => false, findOpenPracticeToContinue = () => null, buildLeaderboard = () => [], getSessionTargetMs = () => null, formatRaceClock = (ms) => String(ms), + renderDaySchedule = () => "", bindDaySchedule = () => {}, } = deps; const queue = buildRaceDayQueue(state); const session = queue.current; @@ -407,7 +408,8 @@ export function renderRaceDayView(deps) { ${renderQueueSession(queue.next, "race_day.next", deps)} ${renderQueueSession(queue.afterNext, "race_day.after_next", deps)} - `; + + ${renderDaySchedule()}`; dom.view.querySelectorAll("[data-race-day-fix-view]").forEach((button) => { button.addEventListener("click", () => navigateTo(button.dataset.raceDayFixView, { settingsTab: button.dataset.raceDayFixTab || "" })); @@ -439,6 +441,7 @@ export function renderRaceDayView(deps) { saveLapWindow(session, minLapSec, maxLapSec); }); bindTrackLayoutBar(dom.view, { state, t, addTrackLayout, renderView }); + bindDaySchedule(dom.view); lastWarmupDeps = { t, escapeHtml, renderView, getRaceDayWarmupCheck, setDriverTransponder, getSession: () => buildRaceDayQueue(state).current }; paintWarmupPanel(); lastLiveDeps = { t, escapeHtml, formatLap, formatRaceClock, buildLeaderboard, getSessionTargetMs, getSession: () => buildRaceDayQueue(state).current }; diff --git a/src/runtime_services.js b/src/runtime_services.js index 8e0e1bd..0dca592 100644 --- a/src/runtime_services.js +++ b/src/runtime_services.js @@ -1,4 +1,5 @@ import { normalizeSeries } from "./series_logic.js"; +import { normalizeRaceDays } from "./day_schedule_logic.js"; import { speakWithPiper, isPiperSpeaking } from "./piper_speech.js"; export function createDefaultAmmcConfigHelper() { return { @@ -115,6 +116,7 @@ export function applyPersistedStateHelper(persisted, deps) { state.activeSessionId = persisted.activeSessionId || null; state.trackLayouts = normalizeTrackLayouts(persisted.trackLayouts); state.series = (Array.isArray(persisted.series) ? persisted.series : []).map((series) => normalizeSeries(series)).filter((series) => series.id); + state.raceDays = normalizeRaceDays(persisted.raceDays); state.settings = { wsUrl: persisted.settings?.wsUrl || state.settings.wsUrl || "ws://127.0.0.1:9000", splitDecoderEnabled: persisted.settings?.splitDecoderEnabled === true, diff --git a/src/styles.css b/src/styles.css index a175fee..c80e73b 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4763,3 +4763,42 @@ tr.is-removed td.lap-actions { .series-result-list li { display: grid; grid-template-columns: 2em 1fr auto; align-items: center; gap: 8px; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; } .series-result-place { font-weight: 800; } .series-result-add { display: flex; gap: 8px; align-items: center; max-width: 520px; } + +/* Race day schedule (Race Day panel) and the drivers' board (/public-overlay/schedule) */ +.day-schedule-actions { display: flex; gap: 8px; flex-wrap: wrap; } +.day-plan-form { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 12px; } +.day-plan-form label { display: grid; gap: 4px; font-size: 0.85rem; color: var(--muted); } +.day-autopilot { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; margin-bottom: 12px; } +.day-autopilot.is-on { border-color: var(--ok); } +.day-autopilot.is-paused { border-color: var(--warn); } +.day-autopilot-status { font-weight: 600; } +.day-schedule-table { width: 100%; border-collapse: collapse; } +.day-schedule-table th { text-align: left; font-size: 0.8rem; color: var(--muted); padding: 6px 8px; } +.day-schedule-table td { padding: 6px 8px; border-top: 1px solid var(--line); vertical-align: middle; } +.day-schedule-table tr.is-done { opacity: 0.55; } +.day-schedule-table tr.is-live td { background: rgba(38, 194, 129, 0.12); } +.day-schedule-table .day-planned, .day-schedule-table tr.is-delayed td:first-child strong { color: var(--warn); } +.day-schedule-table .day-move { white-space: nowrap; text-align: right; } +.driver-board { padding: 16px; display: grid; gap: 16px; color: var(--text); } +.driver-board-header { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; flex-wrap: wrap; } +.driver-board-header h1 { margin: 0; font-size: 1.6rem; } +.driver-board-clock { font-size: 2rem; font-variant-numeric: tabular-nums; } +.board-live { font-size: 1.2rem; padding: 10px 14px; border-radius: 10px; background: rgba(38, 194, 129, 0.12); } +.board-next-list { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); } +.board-next { border: 1px solid var(--line); border-radius: 12px; padding: 14px; background: var(--panel); } +.board-next header { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; } +.board-next h3 { margin: 6px 0; font-size: 1.3rem; } +.board-time { font-size: 2rem; font-variant-numeric: tabular-nums; } +.board-when { font-size: 1.1rem; color: var(--muted); } +.board-next.is-soon { border: 2px solid var(--warn); } +.board-next.is-soon .board-when { color: var(--warn); font-weight: 700; } +.board-heads-up { margin: 0 0 8px; font-weight: 700; color: var(--warn); } +.board-next ol { margin: 0; padding-left: 24px; font-size: 1.15rem; line-height: 1.5; } +.board-later { width: 100%; border-collapse: collapse; font-size: 1.05rem; } +.board-later td { padding: 6px 8px; border-top: 1px solid var(--line); } +.board-later td:first-child { width: 5em; font-variant-numeric: tabular-nums; } +.board-empty { font-size: 1.3rem; color: var(--muted); } +@media (max-width: 600px) { + .day-schedule-table th:nth-child(3), .day-schedule-table td:nth-child(3) { display: none; } + .board-time { font-size: 1.6rem; } +} diff --git a/tests/browser_day_schedule.js b/tests/browser_day_schedule.js new file mode 100644 index 0000000..df3874b --- /dev/null +++ b/tests/browser_day_schedule.js @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; + +// The race day schedule: every class on one date in one running order with times, ▲▼, a +// start time and gap, pause/resume of the day, the autopilot telling what it waits for, and +// the drivers' board with the next heats and a heads-up. +export async function runDayScheduleSmoke({ evaluate, navigate, savedState, waitFor, base, send, dialogs }) { + const dialogsAtStart = dialogs.length; + 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 d = new Date(); + const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; + const seeded = await savedState(); + const heat = (id, eventId, name) => ({ id, eventId, name, type: "qualification", mode: "race", status: "ready", durationMin: 5, startMode: "staggered" }); + await patchState({ + sessions: [ + ...seeded.sessions.map((session) => (["running", "paused"].includes(session.status) ? { ...session, status: "finished", endedAt: Date.now() } : session)), + heat("ds_2wd_q1", "ds_2wd", "Q1 H1"), heat("ds_4wd_q1", "ds_4wd", "Q1 H1"), heat("ds_2wd_q2", "ds_2wd", "Q2 H1"), + ], + events: [...seeded.events, { id: "ds_2wd", name: "DS Cup 2WD", date: today, mode: "race", raceConfig: {} }, { id: "ds_4wd", name: "DS Cup 4WD", date: today, mode: "race", raceConfig: {} }], + activeSessionId: "ds_2wd_q1", + raceDays: [], + }); + const rowIds = () => evaluate(`[...document.querySelectorAll("[data-day-row]")].map((row) => row.dataset.dayRow)`); + try { + await navigate("race_day", "daySchedule"); + await waitFor(async () => (await rowIds()).join() === "ds_2wd_q1,ds_4wd_q1,ds_2wd_q2", "both classes in one running order, round by round"); + await evaluate(`document.querySelector('[data-day-move="ds_4wd_q1"][data-step="-1"]').click()`); + await waitFor(async () => (await rowIds()).join() === "ds_4wd_q1,ds_2wd_q1,ds_2wd_q2", "▲ moves the 4WD heat first"); + await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.sessionOrder?.[0] === "ds_4wd_q1", "the day order is saved"); + console.log("PASS Race Day shows today's schedule for every class in running order and ▲▼ change it"); + + // First start in an hour, 2 min between heats: the second heat is 5 + 2 min later. + const inAnHour = new Date(Date.now() + 3600000); + const hhmm = (date) => `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; + await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.elements.startTime.value = ${JSON.stringify(hhmm(inAnHour))}; form.elements.gapMin.value = "2"; form.requestSubmit(); })()`); + await waitFor(async () => Boolean(((await savedState()).raceDays || []).find((day) => day.date === today)?.startAt), "start time saved"); + const times = await evaluate(`[...document.querySelectorAll("[data-day-row] td:first-child strong")].map((cell) => cell.textContent)`); + assert.equal(times[0], hhmm(inAnHour)); + assert.equal(times[1], hhmm(new Date(inAnHour.getTime() + 7 * 60000))); + console.log("PASS the day gets a first start time and gap, and every heat its planned time"); + + await evaluate(`document.getElementById("dayAutopilotOn").click()`); + await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.autopilot === true, "autopilot on"); + await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).startsWith("Next: 4WD") || (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).includes("DS"), "the autopilot says what is next"); + assert.match(await evaluate(`document.querySelector("[data-autopilot-status]").textContent`), /^Next: .*Q1 H1 at /); + // Time is up but no decoder: it waits and says why instead of starting. + await evaluate(`(() => { const form = document.getElementById("dayPlanForm"); form.elements.startTime.value = ${JSON.stringify(hhmm(new Date(Date.now() - 60000)))}; form.requestSubmit(); })()`); + await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)).includes("decoder is not connected"), "waits for the decoder"); + assert.equal((await savedState()).sessions.find((session) => session.id === "ds_4wd_q1").status, "ready", "nothing started without a decoder"); + await evaluate(`document.getElementById("dayPause").click()`); + await waitFor(async () => Boolean(((await savedState()).raceDays || []).find((day) => day.date === today)?.pausedAt), "the day is paused"); + await waitFor(async () => (await evaluate(`document.querySelector("[data-autopilot-status]").textContent`)) === "The day is paused", "the autopilot says the day is paused"); + await evaluate(`document.getElementById("dayResume").click()`); + await waitFor(async () => !((await savedState()).raceDays || []).find((day) => day.date === today)?.pausedAt, "the day is resumed"); + await evaluate(`document.getElementById("dayAutopilotOff").click()`); + await waitFor(async () => ((await savedState()).raceDays || []).find((day) => day.date === today)?.autopilot === false, "autopilot off"); + console.log("PASS the autopilot says what comes next, waits for the decoder, and the day can be paused and resumed"); + + const printHtml = await evaluate(`(async () => { + const { buildDaySchedulePrintHtml } = await import("/src/day_schedule_view.js"); + return buildDaySchedulePrintHtml({ t: (key, vars = {}) => key + JSON.stringify(vars), escapeHtml: (value) => String(value), date: "D", rows: [{ start: Date.now(), session: { name: "Q1 H1" } }], getClassLabel: () => "2WD", getSessionGridEntries: () => [{ name: "Roy" }, { name: "Eddie" }] }); + })()`); + assert.ok(printHtml.includes("2WD · Q1 H1") && printHtml.includes("
  • Roy
  • Eddie
  • "), "the printed running order lists each heat's drivers"); + + // The drivers' board: the next heats with a heads-up (the first is due now) and the rest. + await send("Page.navigate", { url: base + "/public-overlay/schedule" }); + await waitFor(async () => (await evaluate(`document.querySelectorAll(".board-next").length`)) === 3, "the board shows the next three heats"); + const board = await evaluate(`document.querySelector(".driver-board").innerText`); + assert.ok(board.includes("Get ready"), "a heat due within 10 minutes gets a heads-up"); + assert.equal(await evaluate(`document.querySelector(".board-next").dataset.boardSession`), "ds_4wd_q1", "in the day's order"); + console.log("PASS the drivers' board shows the next heats with their drivers and a heads-up"); + } finally { + const current = await savedState(); + await patchState({ + sessions: current.sessions.filter((session) => !session.id.startsWith("ds_")), + events: current.events.filter((event) => !event.id.startsWith("ds_")), + raceDays: [], + }); + dialogs.splice(dialogsAtStart); + } +} diff --git a/tests/browser_smoke.js b/tests/browser_smoke.js index 8371491..28b7a7a 100644 --- a/tests/browser_smoke.js +++ b/tests/browser_smoke.js @@ -23,6 +23,7 @@ import { runTrainingSourceSmoke } from "./browser_training_source.js"; import { runDecoderUrlSmoke } from "./browser_decoder_url.js"; import { runLiveSessionSmoke } from "./browser_live_session.js"; import { runRaceDayQuickSmoke } from "./browser_race_day_quick.js"; +import { runDayScheduleSmoke } from "./browser_day_schedule.js"; import { runObsPopupSmoke } from "./browser_obs_popup.js"; import { runDecoderReconnectSmoke } from "./browser_decoder_reconnect.js"; import assert from "node:assert/strict"; @@ -175,6 +176,7 @@ try { await runDecoderUrlSmoke({ evaluate, navigate, savedState, waitFor, base }); await runLiveSessionSmoke({ evaluate, navigate, savedState, waitFor, base }); await runRaceDayQuickSmoke({ evaluate, navigate, savedState, waitFor, base, dialogs }); + await runDayScheduleSmoke({ evaluate, navigate, savedState, waitFor, base, send, dialogs }); await runRaceDaySmoke({ evaluate, navigate, fill, savedState, waitFor, pause, base, dialogs }); await runRaceDayStartSequencesSmoke({ evaluate, navigate, waitFor, pause, base, dialogs }); await runObsPopupSmoke({ evaluate, navigate, fill, savedState, waitFor, pause, base, debugPort, dialogs, realClick }); diff --git a/tests/day_schedule.test.js b/tests/day_schedule.test.js new file mode 100644 index 0000000..b625cb0 --- /dev/null +++ b/tests/day_schedule.test.js @@ -0,0 +1,70 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { orderDaySessions, buildDaySchedule, getAutopilotAction, normalizeRaceDays, moveInDayOrder, pickBoardDate } from "../src/day_schedule_logic.js"; + +const events = [ + { id: "e4", name: "Cup #1 4WD", date: "2026-11-08", mode: "race" }, + { id: "e2", name: "Cup #1 2WD", date: "2026-11-08", mode: "race" }, + { id: "other", name: "Other day", date: "2026-11-09", mode: "race" }, +]; +const s = (id, eventId, type, name, extra = {}) => ({ id, eventId, type, name, mode: "race", status: "ready", durationMin: 5, ...extra }); +const sessions = [ + s("a4", "e4", "final", "A Final 1"), s("q4", "e4", "qualification", "Q1 H1"), s("q4b", "e4", "qualification", "Q2 H1"), + s("b2", "e2", "final", "B Final 1"), s("a2", "e2", "final", "A Final 1"), s("q2b", "e2", "qualification", "Q2 H1"), + s("q2", "e2", "qualification", "Q1 H1"), s("q2h2", "e2", "qualification", "Q1 H2"), s("p2", "e2", "practice", "Seeding"), + s("x", "other", "qualification", "Q1 H1"), +]; + +test("the day runs every class step by step: practice, each qualifying round, finals lowest first", () => { + const ids = orderDaySessions({ events, sessions, date: "2026-11-08" }).map((item) => item.id); + assert.deepEqual(ids, ["p2", "q2", "q2h2", "q4", "q2b", "q4b", "b2", "a2", "a4"]); +}); + +test("a manual day order and a class's own order are kept", () => { + const ordered = orderDaySessions({ events, sessions, date: "2026-11-08" }); + const manual = moveInDayOrder(ordered, "q4", -1); + assert.deepEqual(orderDaySessions({ events, sessions, date: "2026-11-08", manualOrder: manual }).slice(0, 4).map((item) => item.id), ["p2", "q2", "q4", "q2h2"]); + const swapped = events.map((event) => (event.id === "e2" ? { ...event, sessionOrder: ["q2h2", "q2"] } : event)); + assert.deepEqual(orderDaySessions({ events: swapped, sessions, date: "2026-11-08" }).slice(1, 3).map((item) => item.id), ["q2h2", "q2"]); +}); + +test("the schedule cascades from the start time and a late or paused day pushes the rest", () => { + const start = Date.UTC(2026, 10, 8, 10, 0); + const list = [s("one", "e2", "qualification", "Q1 H1"), s("two", "e2", "qualification", "Q1 H2")]; + const day = { startAt: start, gapMin: 3 }; + const plan = buildDaySchedule(list, day, start - 3600000); + assert.deepEqual(plan.map((row) => row.start), [start, start + 8 * 60000]); + assert.equal(plan[1].upcomingIndex, 1); + // Nothing started 4 minutes after the planned time: expected now, everything after moves. + const late = buildDaySchedule(list, day, start + 4 * 60000); + assert.equal(late[0].start, start + 4 * 60000); + assert.equal(late[0].delayed, true); + assert.equal(late[1].start, start + 12 * 60000); + // A heat running with a 2 minute pause ends 2 minutes later. + const running = [{ ...list[0], status: "running", startedAt: start + 60000, totalPausedMs: 120000 }, list[1]]; + const live = buildDaySchedule(running, day, start + 2 * 60000); + assert.equal(live[0].state, "live"); + assert.equal(live[0].end, start + 8 * 60000); + assert.equal(live[1].start, start + 11 * 60000); +}); + +test("the autopilot waits for the planned time minus the count-down, never while something runs or the day is paused", () => { + const start = Date.UTC(2026, 10, 8, 10, 0); + const rows = buildDaySchedule([s("one", "e2", "qualification", "Q1 H1")], { startAt: start }, start - 600000); + const prologueMs = () => 120000; + assert.deepEqual(getAutopilotAction(rows, { day: {}, now: start - 300000, prologueMs }).reason, "until"); + assert.equal(getAutopilotAction(rows, { day: {}, now: start - 120000, prologueMs }).type, "start"); + assert.equal(getAutopilotAction(rows, { day: {}, now: start, busy: true, prologueMs }).reason, "running"); + assert.equal(getAutopilotAction(rows, { day: { pausedAt: start }, now: start, prologueMs }).reason, "paused"); + assert.equal(getAutopilotAction([], { day: {}, now: start }).reason, "done"); +}); + +test("race days are stored one per date, and the board shows today or the next day still to race", () => { + const days = normalizeRaceDays([{ date: "2026-11-08", gapMin: 0 }, { date: "bad" }, { date: "2026-11-08", gapMin: 5, autopilot: true }]); + assert.equal(days.length, 1); + assert.equal(days[0].gapMin, 5); + assert.equal(normalizeRaceDays([{ date: "2026-11-08", gapMin: 0 }])[0].gapMin, 0); + assert.equal(pickBoardDate({ events, sessions, today: "2026-11-08" }), "2026-11-08"); + assert.equal(pickBoardDate({ events, sessions, today: "2026-11-01" }), "2026-11-08"); + assert.equal(pickBoardDate({ events, sessions, today: "2026-12-01" }), "2026-12-01"); +}); diff --git a/tests/run.js b/tests/run.js index 8c5d7b9..671bff4 100644 --- a/tests/run.js +++ b/tests/run.js @@ -1,4 +1,5 @@ import "./auth.test.js"; +import "./day_schedule.test.js"; import "./race_day_live.test.js"; import "./series_next_step.test.js"; import "./race_day_sessions.test.js";