From f5b77d5589a0972fa18cdd0db6255a604fcd7810 Mon Sep 17 00:00:00 2001 From: larssand Date: Tue, 10 Nov 2026 07:42:47 +0100 Subject: [PATCH] feat(overlay): flash the row on a new time, ticking pit clock and split badges (1.88.0) --- CHANGELOG.md | 9 +++ package-lock.json | 4 +- package.json | 2 +- src/app.js | 2 + src/overlay_live_marks.js | 109 ++++++++++++++++++++++++++++ src/overlays.js | 18 ++++- src/styles.css | 37 ++++++++++ tests/browser_overlay_live_marks.js | 62 ++++++++++++++++ tests/browser_smoke.js | 2 + tests/overlay_live_marks.test.js | 64 ++++++++++++++++ tests/run.js | 1 + 11 files changed, 304 insertions(+), 6 deletions(-) create mode 100644 src/overlay_live_marks.js create mode 100644 tests/browser_overlay_live_marks.js create mode 100644 tests/overlay_live_marks.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index aac5a18..2f05d83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ The application version is maintained in `package.json` and displayed in the adm No changes recorded yet. +## 1.88.0 + +### Added + +- **Overlay: see who just got a new time.** The driver's row flashes for a moment on every new lap - on the overlay leaderboard and the OBS tower. Nothing flashes when the overlay is first opened. +- **Overlay: pit clock.** While a car is in the pits, a yellow badge with a fuel pump and a ticking clock sits by the driver; after the pit exit it shows the stop time for 5 seconds. On the OBS tower it hangs just outside the tower, so it never covers a name. +- **Overlay: splits.** A new split shows for 4 seconds with its gain against the previous lap in green or red. +- The flash, pit clock and split run on the overlay computer's own clock, so they are right even if the decoder's clock differs. + ## 1.87.1 ### Fixed diff --git a/package-lock.json b/package-lock.json index 9800628..976e94e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rc-racecore", - "version": "1.87.1", + "version": "1.88.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rc-racecore", - "version": "1.87.1", + "version": "1.88.0", "hasInstallScript": true, "dependencies": { "better-sqlite3": "^12.11.1", diff --git a/package.json b/package.json index b411a7d..a56fd04 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rc-racecore", - "version": "1.87.1", + "version": "1.88.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 76dcacf..dc1fc18 100644 --- a/src/app.js +++ b/src/app.js @@ -3,6 +3,7 @@ import { getSyncStatus } from "./sync_status.js"; import { installListSorting } from "./list_sorting.js"; import { escapeHtml } from "./html_escape.js"; import { getOverlayModeLabel, buildOverlayPanels, renderOverlaySidePanel, renderOverlayLeaderboard, renderTeamOverlay, renderObsOverlay } from "./overlays.js"; +import { refreshLiveMarkNodes } from "./overlay_live_marks.js"; import { renderSettings, openSettingsTab } from "./settings.js"; import { buildRaceDayQueue, buildRaceDayPreflight, getRaceDriverIds, shouldOfferFinals } from "./race_day_logic.js"; @@ -811,6 +812,7 @@ const refreshOverlayDynamics = () => { node.textContent = clock; }); + refreshLiveMarkNodes(document); const rowsByKey = new Map(buildLeaderboard(active).map((row) => [String(row.key), row])); document.querySelectorAll("[data-overlay-competitor]").forEach((node) => { const row = rowsByKey.get(String(node.dataset.overlayCompetitor || "")); diff --git a/src/overlay_live_marks.js b/src/overlay_live_marks.js new file mode 100644 index 0000000..0b15d65 --- /dev/null +++ b/src/overlay_live_marks.js @@ -0,0 +1,109 @@ +// Live marks on overlay rows: a short flash when a driver gets a new time, a ticking pit +// clock while in the pits (then the stop time for a few seconds), and a new split for a few +// seconds. Everything runs on this computer's clock from the moment the overlay saw the +// change - the decoder's clock may differ, and a page just opened must not flash every row. + +export const PASSING_FLASH_MS = 700; +export const PIT_DONE_SHOW_MS = 5000; +export const SPLIT_SHOW_MS = 4000; +const MAX_PIT_FALLBACK_MS = 15 * 60 * 1000; + +export function createOverlayLiveMarks({ now = () => Date.now() } = {}) { + const seen = new Map(); + + // Call with the rows about to be drawn; returns the marks for each row key. + function observe(rows) { + const at = now(); + const marks = new Map(); + (Array.isArray(rows) ? rows : []).forEach((row) => { + const key = String(row?.key ?? ""); + if (!key) return; + const lastTimestamp = Number(row.lastTimestamp || 0); + const splitTimestamp = Number(row.lastSplitTimestamp || 0); + const pitActive = Boolean(row.pitActive); + const pitStops = Number(row.pitStops || 0); + const previous = seen.get(key); + const entry = previous || { passingAt: 0, splitAt: 0, pitStartAt: 0, pitDoneAt: 0 }; + if (!previous) { + // First sight: no flash, but a car already in the pits gets a clock from its entry time. + if (pitActive) { + const sinceEntry = at - Number(row.pitEnteredAt || 0); + entry.pitStartAt = sinceEntry > 0 && sinceEntry < MAX_PIT_FALLBACK_MS ? at - sinceEntry : at; + } + } else { + if (lastTimestamp && lastTimestamp !== previous.lastTimestamp) entry.passingAt = at; + if (splitTimestamp && splitTimestamp !== previous.splitTimestamp) entry.splitAt = at; + if (pitActive && !previous.pitActive) entry.pitStartAt = at; + if (!pitActive && previous.pitActive && pitStops > previous.pitStops) entry.pitDoneAt = at; + if (!pitActive) entry.pitStartAt = 0; + } + Object.assign(entry, { lastTimestamp, splitTimestamp, pitActive, pitStops }); + seen.set(key, entry); + + const passingAgeMs = entry.passingAt ? at - entry.passingAt : Infinity; + const splitAgeMs = entry.splitAt ? at - entry.splitAt : Infinity; + const pitDoneAgeMs = entry.pitDoneAt ? at - entry.pitDoneAt : Infinity; + marks.set(key, { + passingAgeMs: passingAgeMs < PASSING_FLASH_MS ? passingAgeMs : null, + pit: pitActive + ? { active: true, startAt: entry.pitStartAt } + : pitDoneAgeMs < PIT_DONE_SHOW_MS && Number(row.lastPitStopMs) > 0 + ? { active: false, stopMs: Number(row.lastPitStopMs), hideAt: entry.pitDoneAt + PIT_DONE_SHOW_MS } + : null, + split: splitAgeMs < SPLIT_SHOW_MS && Number(row.lastSplitMs) > 0 + ? { ms: Number(row.lastSplitMs), deltaMs: Number.isFinite(row.lastSplitDeltaMs) ? row.lastSplitDeltaMs : null, hideAt: entry.splitAt + SPLIT_SHOW_MS } + : null, + }); + }); + return marks; + } + + return { observe, reset: () => seen.clear() }; +} + +// "0:12.4" - the running pit clock. +export function formatPitClock(ms) { + const tenths = Math.max(0, Math.floor(Number(ms || 0) / 100)); + const seconds = Math.floor(tenths / 10); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}.${tenths % 10}`; +} + +const FUEL_ICON = ''; + +// Row class + style for the passing flash. A negative delay lets a re-render pick the +// animation up where it was instead of starting it over. +export function passingFlashAttrs(mark) { + if (!mark || mark.passingAgeMs == null) return { className: "", style: "" }; + return { className: " is-passing", style: ` style="--pass-delay:-${Math.round(mark.passingAgeMs)}ms"` }; +} + +// Pit badge and split chip shown next to the driver's time. +export function renderLiveMarkBadges(mark, { formatLap, escapeHtml, nowMs = Date.now(), labels = {} }) { + if (!mark) return ""; + const parts = []; + if (mark.pit?.active) { + parts.push(`${FUEL_ICON}${formatPitClock(nowMs - mark.pit.startAt)}`); + } else if (mark.pit) { + parts.push(`${FUEL_ICON}${escapeHtml(formatLap(mark.pit.stopMs))}`); + } + if (mark.split) { + const delta = mark.split.deltaMs == null ? "" : ` ${mark.split.deltaMs <= 0 ? "−" : "+"}${(Math.abs(mark.split.deltaMs) / 1000).toFixed(3)}`; + parts.push(`S ${escapeHtml(formatLap(mark.split.ms))}${delta}`); + } + return parts.length ? `${parts.join("")}` : ""; +} + +// Called by the overlay's 250 ms tick: run the pit clocks and drop marks whose time is up, +// without redrawing the rows. +export function refreshLiveMarkNodes(root, nowMs = Date.now()) { + root.querySelectorAll("[data-pit-clock]").forEach((node) => { + const label = node.querySelector("b"); + if (label) label.textContent = formatPitClock(nowMs - Number(node.dataset.pitClock || nowMs)); + }); + root.querySelectorAll("[data-live-hide-at]").forEach((node) => { + if (nowMs >= Number(node.dataset.liveHideAt || 0)) node.remove(); + }); +} + +// The overlay page's shared instance. +export const overlayLiveMarks = createOverlayLiveMarks(); diff --git a/src/overlays.js b/src/overlays.js index b916a82..0c85056 100644 --- a/src/overlays.js +++ b/src/overlays.js @@ -1,5 +1,6 @@ import { sortValuesAttribute } from "./list_sorting.js"; import { escapeHtml as escapeHtmlLocal } from "./html_escape.js"; +import { overlayLiveMarks, passingFlashAttrs, renderLiveMarkBadges } from "./overlay_live_marks.js"; export function getOverlayModeLabel(mode, { t }) { return t(`overlay.mode_${String(mode || "leaderboard").toLowerCase()}`); } @@ -69,6 +70,8 @@ export function renderOverlayLeaderboard(rows, { t, escapeHtml, formatTeamActive // More than 12 cars (a busy Open Practice): compact rows so all of them fit on a TV that // can't scroll - no per-cell labels (the header names the columns), sub-line or prediction bar. const compact = rows.length > 12; + const liveMarks = overlayLiveMarks.observe(rows); + const markLabels = { pit: t("table.pit"), split: t("table.split") }; return `
${rows @@ -76,13 +79,15 @@ export function renderOverlayLeaderboard(rows, { t, escapeHtml, formatTeamActive const posClass = idx === 0 ? "pos-1" : idx === 1 ? "pos-2" : idx === 2 ? "pos-3" : ""; const rowSortAttr = sortable ? ` data-sort-values="${sortValuesAttribute([idx + 1, row.displayName || row.driverName, row.laps ?? 0, row.resultDisplay, row.gapDisplay || row.gapAhead || null, row.gapAhead || null, row.lapDelta || null, row.bestLapMs || null])}"` : ""; const linkAttrs = driverLinks && row.driverId && !row.teamId ? ` data-training-driver="${escapeHtml(row.driverId)}" title="${escapeHtml(t("overlay.open_training_stats"))}"` : ""; + const mark = liveMarks.get(String(row.key ?? "")); + const flash = passingFlashAttrs(mark); return ` -
+
${idx + 1}
- ${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? ` 🏁 ${t("timing.personal_time_up")}` : ""}${row.suspectPending ? ` ⚠` : ""} + ${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? ` 🏁 ${t("timing.personal_time_up")}` : ""}${row.suspectPending ? ` ⚠` : ""}${renderLiveMarkBadges(mark, { formatLap, escapeHtml, labels: markLabels })} ${row.heatCarName ? `🚗 ${escapeHtml(row.heatCarName)}` : `${escapeHtml(row.teamId ? `${t("overlay.active_member")}: ${formatTeamActiveMemberLabel(row)}` : row.subLabel || row.transponder || "-")}`} ${row.lastSplitMs || row.pitActive || row.pitStops ? `${row.lastSplitMs ? `${t("table.split")}: ${formatLap(row.lastSplitMs)}` : ""}${row.lastSplitMs && (row.pitActive || row.pitStops) ? " • " : ""}${row.pitActive ? t("timing.pit_active") : row.pitStops ? `${t("table.pit")}: ${row.pitStops} / ${formatLap(row.totalPitMs)}` : ""}` : ""} ${row.invalidPending ? `${escapeHtml(row.invalidLabel)}${row.invalidLapMs ? ` • ${formatLap(row.invalidLapMs)}` : ""}` : ""} @@ -219,11 +224,14 @@ function renderObsBroadcast({ active, compactRows, startOrder, showStartGrid, fa // With laps in their own column the result's "14/" prefix only repeats them. const timeOnly = (value) => (obsConfig.showLaps ? String(value || "").replace(/^\d+\//, "") : String(value || "")); const podium = (place) => (place <= 3 ? ` is-p${place}` : ""); + const liveMarks = showStartGrid ? null : overlayLiveMarks.observe(compactRows); const rows = showStartGrid ? getSessionGridEntries(active).slice(0, obsConfig.rows).map((entry, idx) => `
${cell("pos", entry.slot)}${cell("name", escapeHtml(entry.name))}
`) : compactRows.map((row, idx) => { const start = startOrder.indexOf(row.driverId) + 1; + const mark = liveMarks?.get(String(row.key ?? "")); + const badges = renderLiveMarkBadges(mark, { formatLap, escapeHtml, labels: { pit: t("table.pit"), split: t("table.split") } }); const values = { pos: idx + 1, start: start ? `/${start}` : "", @@ -234,7 +242,11 @@ function renderObsBroadcast({ active, compactRows, startOrder, showStartGrid, fa best: Number.isFinite(row.bestLapMs) ? escapeHtml(formatLap(row.bestLapMs)) : "-", gap: escapeHtml(idx === 0 ? "" : row.gapDisplay || row.gapAhead || ""), }; - return `
${columns.map(([key]) => cell(key, values[key])).join("")}
`; + // Pit clock and split at the end of the name column, the one flexible column - in + // the time columns they would push every other column out of line. + if (badges) values.name = `${values.name}${badges}`; + const flash = passingFlashAttrs(mark); + return `
${columns.map(([key]) => cell(key, values[key])).join("")}
`; }); const eventName = String(getEventName(active.eventId) || "").trim(); return ` diff --git a/src/styles.css b/src/styles.css index 366904d..b9ce443 100644 --- a/src/styles.css +++ b/src/styles.css @@ -4992,3 +4992,40 @@ tr:has(> td > .medal-3) { background: linear-gradient(90deg, rgba(205, 127, 60, .stint-lap.is-excluded { opacity: 0.55; } .stint-laps-empty { color: var(--muted); } .stint-laps-title { margin: 12px 0 2px; } + +/* Overlay live marks (src/overlay_live_marks.js): flash on a new time, pit clock, split. */ +.overlay-race-row.is-passing, .obs-tv-row.is-passing { animation: overlay-pass 700ms ease-out var(--pass-delay, 0ms) both; } +@keyframes overlay-pass { + 0% { box-shadow: inset 4px 0 0 #ffe066, inset 0 0 0 999px rgb(255 224 102 / 34%); } + 100% { box-shadow: inset 4px 0 0 transparent, inset 0 0 0 999px transparent; } +} +@media (prefers-reduced-motion: reduce) { + .overlay-race-row.is-passing, .obs-tv-row.is-passing { animation: none; box-shadow: inset 4px 0 0 #ffe066; } +} +.overlay-live-marks { display: inline-flex; flex-wrap: wrap; gap: 4px; margin-left: 6px; vertical-align: middle; } +.overlay-race-driver .overlay-live-marks { margin-left: 8px; } +/* The driver cell styles its spans as tiny grey labels; the marks keep their own look. */ +.overlay-race-driver .overlay-live-marks span { font-size: 0.72rem; letter-spacing: 0; text-transform: none; } +.overlay-race-driver .overlay-pit-badge { color: #2a1a00; } +.overlay-race-driver .overlay-pit-badge.is-done { color: #ffd28a; } +.overlay-race-driver .overlay-split-chip { color: #bfe8ff; } +body[data-theme="light"] .overlay-race-driver .overlay-split-chip { color: #075985; } +body[data-theme="light"] .overlay-race-driver .overlay-pit-badge.is-done { color: #7a4a00; } +.overlay-pit-badge, .overlay-split-chip { display: inline-flex; align-items: center; gap: 3px; padding: 1px 6px; border-radius: 999px; font-size: 0.78em; font-weight: 800; line-height: 1.4; font-variant-numeric: tabular-nums; white-space: nowrap; } +.overlay-pit-badge { background: #f5a623; color: #2a1a00; } +.overlay-pit-badge.is-active { animation: overlay-pit-pulse 1s ease-in-out infinite; } +.overlay-pit-badge.is-done { background: color-mix(in srgb, #f5a623 30%, transparent); color: #ffd28a; } +.overlay-fuel-icon { width: 1.05em; height: 1.05em; flex: none; } +@keyframes overlay-pit-pulse { 50% { background: #ffc65c; } } +.overlay-split-chip { background: rgb(14 165 233 / 22%); color: #bfe8ff; } +.overlay-split-chip i { font-style: normal; } +.overlay-split-chip .is-faster { color: #4ade80; } +.overlay-split-chip .is-slower { color: #f87171; } +/* Hung outside the tower's left edge, over the video: it covers no name and the tower + (sized to its content) never changes width. */ +.obs-tv-row:has(.overlay-live-marks) { position: relative; overflow: visible; } +.obs-tv-name:has(.overlay-live-marks) { overflow: visible; } +.obs-tv-cell .overlay-live-marks { position: absolute; top: 50%; right: calc(100% + 0.35em); transform: translateY(-50%); flex-wrap: nowrap; margin: 0; font-size: 0.85em; text-transform: none; filter: drop-shadow(0 0.1em 0.3em rgb(0 0 0 / 60%)); } +.obs-tv-cell .overlay-split-chip { background: #0b4a6b; } +body[data-theme="light"] .overlay-split-chip { color: #075985; } +body[data-theme="light"] .overlay-pit-badge.is-done { color: #7a4a00; } diff --git a/tests/browser_overlay_live_marks.js b/tests/browser_overlay_live_marks.js new file mode 100644 index 0000000..bbbc95e --- /dev/null +++ b/tests/browser_overlay_live_marks.js @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; + +// Overlay live marks in a real browser: a new time flashes the row, a car in the pits gets a +// ticking clock with a fuel pump next to its time, and a new split shows - on the regular +// leaderboard and the OBS tower. +export async function runOverlayLiveMarksSmoke({ evaluate }) { + const result = await evaluate(`(async () => { + const { renderOverlayLeaderboard, renderObsOverlay } = await import('/src/overlays.js'); + const { refreshLiveMarkNodes } = await import('/src/overlay_live_marks.js'); + const { escapeHtml } = await import('/src/html_escape.js'); + const frame = document.createElement('iframe'); + frame.style.cssText = 'position:fixed;left:0;top:0;width:1200px;height:700px;border:0;z-index:99999'; + document.body.append(frame); + const doc = frame.contentDocument; + const style = doc.createElement('link'); style.rel = 'stylesheet'; style.href = '/src/styles.css'; + const loaded = new Promise((resolve, reject) => { style.onload = resolve; style.onerror = reject; }); + doc.head.append(style); await loaded; + const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + const deps = { t: (key) => key, escapeHtml, formatLap: (ms) => (ms / 1000).toFixed(3), formatTeamActiveMemberLabel: () => '', formatPredictedLapDelta: () => '-', getVisiblePassings: () => [], getEventName: () => 'Club', getSessionTypeLabel: () => 'Practice', getStartModeLabel: () => '', getStatusLabel: () => '', getObsOverlayConfig: () => ({ layout: 'broadcast', rows: 10, showClock: true, showLaps: true, showResult: true, showBest: true, showGap: true }), normalizeStartMode: (v) => v, renderPositionGrid: () => '', getSessionGridEntries: () => [], getSessionGridOrder: () => [] }; + const now = Date.now(); + let rows = [{ key: 'lm_a', displayName: 'Anna', laps: 3, resultDisplay: '3/0:41.000', bestLapMs: 13500, lastTimestamp: now - 5000 }, { key: 'lm_b', displayName: 'Bo', laps: 3, resultDisplay: '3/0:42.000', bestLapMs: 13700, lastTimestamp: now - 4000 }]; + const out = {}; + try { + doc.body.innerHTML = '
'; + const board = doc.querySelector('.overlay-board'); + const draw = () => { board.innerHTML = renderOverlayLeaderboard(rows, deps, { sortable: false }); }; + draw(); + out.flashOnOpen = board.querySelectorAll('.is-passing').length; + rows = rows.map((row) => row.key === 'lm_a' ? { ...row, laps: 4, lastTimestamp: now + 1 } : row); + draw(); + const flashed = board.querySelector('.overlay-race-row.is-passing'); + out.flashed = flashed?.dataset.overlayCompetitor || ''; + out.animation = flashed ? getComputedStyle(flashed).animationName : ''; + rows = rows.map((row) => row.key === 'lm_b' ? { ...row, pitActive: true, pitEnteredAt: now } : row); + draw(); + const clock = () => board.querySelector('[data-overlay-competitor="lm_b"] [data-pit-clock] b')?.textContent || ''; + out.pitIcon = Boolean(board.querySelector('[data-overlay-competitor="lm_b"] .overlay-pit-badge svg')); + const before = clock(); + await wait(450); + refreshLiveMarkNodes(doc); + out.pitTicks = before !== clock() && /^0:00\\.[0-9]$/.test(clock()); + rows = rows.map((row) => row.key === 'lm_a' ? { ...row, lastSplitTimestamp: now + 2, lastSplitMs: 5123, lastSplitDeltaMs: -120 } : row); + draw(); + out.split = board.querySelector('[data-overlay-competitor="lm_a"] .overlay-split-chip')?.textContent.trim() || ''; + doc.body.innerHTML = '
'; + rows = rows.map((row) => row.key === 'lm_a' ? { ...row, laps: 5, lastTimestamp: now + 3 } : row); + doc.body.firstElementChild.innerHTML = renderObsOverlay({ name: 'Practice', eventId: 'e', status: 'running', type: 'open_practice' }, rows, {}, { remainingMs: 300000 }, {}, deps); + out.obsFlash = doc.querySelectorAll('.obs-tv-row.is-passing').length; + out.obsPit = Boolean(doc.querySelector('.obs-tv-row [data-pit-clock]')); + } finally { frame.remove(); } + return out; + })()`); + assert.equal(result.flashOnOpen, 0, "nothing flashes when the overlay opens"); + assert.equal(result.flashed, "lm_a", "the driver with the new time flashes"); + assert.equal(result.animation, "overlay-pass"); + assert.equal(result.pitIcon, true, "fuel pump next to the time"); + assert.equal(result.pitTicks, true, "the pit clock ticks without a redraw"); + assert.match(result.split, /^S 5\.123 −0\.120$/); + assert.equal(result.obsFlash, 1, "the OBS tower flashes too"); + assert.equal(result.obsPit, true, "and shows the pit clock"); + console.log("PASS overlay live marks: a new time flashes the row, the pit clock ticks with a fuel pump, a new split shows - leaderboard and OBS tower"); +} diff --git a/tests/browser_smoke.js b/tests/browser_smoke.js index bfc60e0..7b87e7d 100644 --- a/tests/browser_smoke.js +++ b/tests/browser_smoke.js @@ -1,4 +1,5 @@ import { runOverlaySmoke } from "./browser_overlays.js"; +import { runOverlayLiveMarksSmoke } from "./browser_overlay_live_marks.js"; import { runRaceSetupSmoke } from "./browser_race_setup.js"; import { runRaceDaySmoke } from "./browser_race_day.js"; import { runRaceDayFinalsSmoke } from "./browser_race_day_finals.js"; @@ -222,6 +223,7 @@ try { })()`); console.log("PASS decoder diagnostics update without resetting settings draft"); await runOverlaySmoke({ evaluate }); + await runOverlayLiveMarksSmoke({ evaluate }); const mobileState = await savedState(); const mobileToken = "browser-mobile-profile-token-1234567890"; mobileState.training ||= {}; diff --git a/tests/overlay_live_marks.test.js b/tests/overlay_live_marks.test.js new file mode 100644 index 0000000..0a55e34 --- /dev/null +++ b/tests/overlay_live_marks.test.js @@ -0,0 +1,64 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createOverlayLiveMarks, formatPitClock, passingFlashAttrs, renderLiveMarkBadges, PASSING_FLASH_MS } from "../src/overlay_live_marks.js"; + +const escapeHtml = (value) => String(value); +const formatLap = (ms) => `${Math.floor(ms / 60000)}:${String(Math.floor(ms % 60000 / 1000)).padStart(2, "0")}.${String(ms % 1000).padStart(3, "0")}`; + +test("a new time flashes the row for a moment, but nothing flashes when the overlay first opens", () => { + let clock = 1_000_000; + const marks = createOverlayLiveMarks({ now: () => clock }); + const row = { key: "d1", lastTimestamp: 500 }; + assert.equal(marks.observe([row]).get("d1").passingAgeMs, null, "first sight: no flash"); + clock += 100; + assert.equal(marks.observe([row]).get("d1").passingAgeMs, null, "same time again: no flash"); + clock += 100; + assert.equal(marks.observe([{ ...row, lastTimestamp: 14_000 }]).get("d1").passingAgeMs, 0); + clock += 250; + const mark = marks.observe([{ ...row, lastTimestamp: 14_000 }]).get("d1"); + assert.equal(mark.passingAgeMs, 250, "a re-render keeps the flash going"); + assert.deepEqual(passingFlashAttrs(mark), { className: " is-passing", style: ' style="--pass-delay:-250ms"' }); + clock += PASSING_FLASH_MS; + assert.equal(marks.observe([{ ...row, lastTimestamp: 14_000 }]).get("d1").passingAgeMs, null); +}); + +test("pit: a running clock from this computer's time, then the stop time for a few seconds", () => { + let clock = 2_000_000; + const marks = createOverlayLiveMarks({ now: () => clock }); + marks.observe([{ key: "d1", lastTimestamp: 1, pitStops: 0 }]); + clock += 1000; + const inPit = marks.observe([{ key: "d1", lastTimestamp: 1, pitActive: true, pitEnteredAt: 42, pitStops: 0 }]).get("d1"); + assert.deepEqual(inPit.pit, { active: true, startAt: clock }, "the decoder's entry time is not used once the overlay saw the entry"); + assert.match(renderLiveMarkBadges(inPit, { formatLap, escapeHtml, nowMs: clock + 12_400 }), /data-pit-clock="\d+".*0:12\.4/s); + clock += 24_000; + const out = marks.observe([{ key: "d1", lastTimestamp: 1, pitActive: false, pitStops: 1, lastPitStopMs: 24_512 }]).get("d1"); + assert.equal(out.pit.stopMs, 24_512); + assert.match(renderLiveMarkBadges(out, { formatLap, escapeHtml }), /is-done.*0:24\.512/s); + clock += 5000; + assert.equal(marks.observe([{ key: "d1", lastTimestamp: 1, pitStops: 1, lastPitStopMs: 24_512 }]).get("d1").pit, null); +}); + +test("a car already in the pits when the overlay opens gets its clock from the entry time", () => { + const clock = 3_000_000; + const marks = createOverlayLiveMarks({ now: () => clock }); + assert.equal(marks.observe([{ key: "d1", pitActive: true, pitEnteredAt: clock - 8000 }]).get("d1").pit.startAt, clock - 8000); + const odd = createOverlayLiveMarks({ now: () => clock }); + assert.equal(odd.observe([{ key: "d1", pitActive: true, pitEnteredAt: clock + 60_000 }]).get("d1").pit.startAt, clock, "a decoder clock ahead of ours starts at 0"); +}); + +test("a new split shows for a few seconds with its gain against the previous lap", () => { + let clock = 4_000_000; + const marks = createOverlayLiveMarks({ now: () => clock }); + marks.observe([{ key: "d1", lastSplitTimestamp: 10 }]); + clock += 50; + const mark = marks.observe([{ key: "d1", lastSplitTimestamp: 20, lastSplitMs: 5123, lastSplitDeltaMs: -120 }]).get("d1"); + assert.match(renderLiveMarkBadges(mark, { formatLap, escapeHtml }), /S 0:05\.123 −0\.120/); + clock += 4000; + assert.equal(marks.observe([{ key: "d1", lastSplitTimestamp: 20, lastSplitMs: 5123 }]).get("d1").split, null); +}); + +test("formatPitClock", () => { + assert.equal(formatPitClock(12_480), "0:12.4"); + assert.equal(formatPitClock(75_000), "1:15.0"); + assert.equal(formatPitClock(-5), "0:00.0"); +}); diff --git a/tests/run.js b/tests/run.js index 757d67b..f49574d 100644 --- a/tests/run.js +++ b/tests/run.js @@ -2,6 +2,7 @@ import "./auth.test.js"; import "./backend_url.test.js"; import "./houseofrc_logic.test.js"; import "./stint_laps_view.test.js"; +import "./overlay_live_marks.test.js"; import "./judging_penalties.test.js"; import "./practice_rank.test.js"; import "./team_race_logic.test.js";