import { rowFlag } from "./country_flags.js"; 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()}`); } export function buildOverlayPanels(active, recent, { t, overlayEvents, normalizeStartMode, renderPositionGrid }) { return [ { title: t("overlay.last_passings"), content: recent.length ? `
${recent .map( (passing) => `
${escapeHtmlLocal(passing.displayName || passing.teamName || passing.driverName || passing.transponder || t("common.unknown_driver"))} ${passing.lapMs == null ? "-" : formatLapLocal(passing.lapMs)}
` ) .join("")}
` : `

${t("timing.no_passings")}

`, }, { title: t("overlay.event_markers"), content: overlayEvents.length ? overlayEvents .map( (item) => `
${escapeHtmlLocal(item.label)} ${new Date(item.ts).toLocaleTimeString()}
` ) .join("") : `

${t("timing.no_passings")}

`, }, { title: t("events.position_grid"), content: active && normalizeStartMode(active.startMode) === "position" ? renderPositionGrid(active) : `

${t("events.na")}

`, }, ]; } export function renderOverlaySidePanel(panel, { t, escapeHtml }) { return `

${escapeHtml(panel.title)}

${t("overlay.rotating_panel")}
${panel.content}
`; } // driverLinks: a click on a driver opens their training stats (RaceCore's own overlay only - never // the public overlay, see openDriverTrainingStats in app.js). export function renderOverlayLeaderboard(rows, { t, escapeHtml, formatTeamActiveMemberLabel, formatLap, formatPredictedLapDelta }, { sortable = true, driverLinks = false, lastLap = false, practiceRank = false } = {}) { if (!rows.length) { return `

${t("timing.no_laps")}

`; } const sortAttrs = sortable ? ` data-sort-id="overlay-leaderboard" data-sort-text-columns="1" data-sort-labels="${sortValuesAttribute(practiceRank ? [t("table.pos"), t("table.driver"), t("table.result"), t("table.gap"), t("table.best_lap")] : [t("table.pos"), t("table.driver"), t("table.laps"), t(lastLap ? "table.last_lap" : "table.result"), t("table.gap"), t("table.ahead_gap"), t("table.own_delta"), t("table.best_lap")])}"` : ""; // 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 .map((row, idx) => { const posClass = idx === 0 ? "pos-1" : idx === 1 ? "pos-2" : idx === 2 ? "pos-3" : ""; const rowSortAttr = sortable ? ` data-sort-values="${sortValuesAttribute(practiceRank ? [idx + 1, row.displayName || row.driverName, row.practiceMetric?.comparableMs ?? null, row.gapDisplay || null, row.bestLapMs || null] : [idx + 1, row.displayName || row.driverName, row.laps ?? 0, lastLap ? row.lastLapMs || null : 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}
${rowFlag(row)}${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)}` : ""}` : ""}
${formatPredictedLapDelta(row.predictedRemainingMs)}
${practiceRank ? "" : `
${row.laps ?? 0}
`}
${lastLap ? (row.lastLapMs > 0 ? escapeHtml(formatLap(row.lastLapMs)) : "-") : escapeHtml(row.resultDisplay)}
${escapeHtml(row.gapDisplay || row.gapAhead || "-")}
${practiceRank ? "" : `
${escapeHtml(row.gapAhead || "-")}
${escapeHtml(row.lapDelta || "-")}
`}
${formatLap(row.bestLapMs)}
`; }) .join("")}
`; } export function renderTeamOverlay(rows, result, sessionTiming, deps) { const { t, escapeHtml, formatLap, formatTeamActiveMemberLabel, getVisiblePassings } = deps; const topThree = rows.slice(0, 3); return `

${t("overlay.top_three")}

${t("overlay.team_battle")}
${topThree .map( (row, index) => `
${index + 1} ${escapeHtml(row.displayName || row.driverName)}

${escapeHtml(row.resultDisplay || "-")}

${t("overlay.active_member")}: ${escapeHtml(formatTeamActiveMemberLabel(row))}
` ) .join("")}
${t("table.laps")} ${rows[0]?.laps || 0} ${escapeHtml(rows[0]?.displayName || rows[0]?.driverName || "-")}
${t("timing.total_passings")} ${getVisiblePassings(result).length || 0} ${sessionTiming?.untimed ? t("timing.elapsed") : t("timing.remaining")}
${t("overlay.fastest_lap")} ${formatLap([...rows].filter((row) => Number.isFinite(row.bestLapMs)).sort((a, b) => a.bestLapMs - b.bestLapMs)[0]?.bestLapMs)} ${escapeHtml( [...rows].filter((row) => Number.isFinite(row.bestLapMs)).sort((a, b) => a.bestLapMs - b.bestLapMs)[0]?.displayName || "-" )}

${t("events.team_standings")}

${renderOverlayLeaderboard(rows, deps)}
`; } const PRACTICE_TYPES = new Set(["open_practice", "free_practice", "practice"]); // Places gained (positive) or lost (negative) since the start, for heats and finals started // together from a start order (mass/position). null when it doesn't apply: practice and // qualifying rank on best laps or individual clocks, and a staggered or flying start has no // common start order to compare with. export function getPositionChange(session, startOrder, driverId, currentPosition) { if (!session || PRACTICE_TYPES.has(String(session.type || "")) || session.type === "qualification") return null; if (!["mass", "position"].includes(String(session.startMode || "mass"))) return null; if (session.status === "ready") return null; const startPosition = (startOrder || []).indexOf(driverId) + 1; return startPosition > 0 ? startPosition - currentPosition : null; } // TV graphics: a title plate top left and a timing tower top right with real columns - // place / start position, driver, laps, time, best lap and gap - large enough to read on a phone. function renderObsBroadcast({ active, compactRows, startOrder, showStartGrid, fastestRow, elapsedOrRemaining, branding, obsConfig, positionChangeMarkup, deps }) { const { t, escapeHtml, formatLap, getEventName, getSessionGridEntries } = deps; const practice = PRACTICE_TYPES.has(String(active.type || "")); const showStart = obsConfig.showStart && !practice && !showStartGrid && compactRows.some((row) => startOrder.includes(row.driverId)); const showResult = obsShowsResult(active, obsConfig); const columns = showStartGrid ? [["pos", "2.4em"], ["name", "minmax(0, 1fr)"]] : [ ["pos", "2.4em"], showStart && ["start", "2.4em"], ["name", "minmax(6em, 1fr)"], obsConfig.showPositionChange && !practice && ["change", "2.6em"], obsConfig.showLaps && ["laps", "max-content"], obsConfig.showLast && ["last", "max-content"], showResult && ["result", "max-content"], obsConfig.showBest && ["best", "max-content"], obsConfig.showGap && ["gap", "max-content"], ].filter(Boolean); const label = { pos: "#", start: t("overlay.col_start"), name: t("table.driver"), change: "", laps: t("table.laps"), last: t("overlay.col_last"), result: t("table.result"), best: t("table.best_lap"), gap: t("table.gap") }; const cell = (key, html) => `${html}`; // 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}` : "", name: `${obsConfig.showFlags !== false ? rowFlag(row) : ""}${escapeHtml(row.displayName || row.driverName)}${row.heatCarName ? ` ๐Ÿš— ${escapeHtml(row.heatCarName)}` : ""}${row.suspectPending ? ' โš ' : ""}`, change: positionChangeMarkup(row, idx + 1), laps: row.laps ?? 0, last: row.lastLapMs > 0 ? escapeHtml(formatLap(row.lastLapMs)) : "-", result: escapeHtml(timeOnly(row.resultDisplay)), best: Number.isFinite(row.bestLapMs) ? escapeHtml(formatLap(row.bestLapMs)) : "-", gap: escapeHtml(idx === 0 ? "" : row.gapDisplay || row.gapAhead || ""), }; // 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 `
${branding.logoDataUrl ? `` : "RC"}
${eventName && eventName !== active.name ? `

${escapeHtml(eventName)}

` : ""}

${escapeHtml(active.name)}

${branding.logoDataUrl ? `` : `${escapeHtml(branding.brandName || "RC RaceCore")}`} ${obsConfig.showClock ? `${elapsedOrRemaining}` : ""}
${columns.map(([key]) => cell(key, escapeHtml(label[key]))).join("")}
${rows.join("") || `

${t("timing.no_laps")}

`} ${!showStartGrid && obsConfig.showFastest && fastestRow ? `` : ""}
`; } // In practice the ranking value *is* the best lap, so "result" and "best" would print the // same time twice - show it once. // Ranked on the best N laps (or X minutes) rather than laps and time: an Open Practice set to // N laps in a row / X minutes, or a practice or qualifier seeded on the best N laps. The overlay // then shows only what the rule ranks on (result, gap, best lap), the same in every session type; // laps-and-time heats (most qualifiers and every final) keep the full columns. export function isPracticeRankedSession(session) { const type = String(session?.type || ""); if (["open_practice", "free_practice"].includes(type)) return ["consecutive", "window"].includes(String(session?.practiceRanking || "")); return ["practice", "qualification"].includes(type) && Number(session?.seedBestLapCount || 0) > 0; } // An Open Practice ranked on the best lap: its result only repeats the best-lap column, and the // last lap is what changes at each passing. Ranked on N laps in a row or X minutes, the result // ("2 laps 35.104") says something of its own and stays. export function isOpenPracticeSession(session) { return ["open_practice", "free_practice"].includes(String(session?.type || "")) && !["consecutive", "window"].includes(String(session?.practiceRanking || "")); } function obsShowsResult(session, obsConfig) { return obsConfig.showResult && !(obsConfig.showBest && isOpenPracticeSession(session)); } export function renderObsOverlay(active, leaderboard, result, sessionTiming, branding, deps) { const { t, escapeHtml, formatLap, getVisiblePassings, getSessionTypeLabel, getStartModeLabel, getStatusLabel, getEventName, getObsOverlayConfig, normalizeStartMode, renderPositionGrid, getSessionGridEntries, getSessionGridOrder = () => [], formatTeamActiveMemberLabel, } = deps; const obsConfig = getObsOverlayConfig(); const startOrder = active && (obsConfig.showPositionChange || obsConfig.showStart) ? getSessionGridOrder(active) : []; const positionChangeMarkup = (row, position) => { const change = obsConfig.showPositionChange ? getPositionChange(active, startOrder, row.driverId, position) : null; if (!change) return ""; return `${change > 0 ? "โ–ฒ" : "โ–ผ"}${Math.abs(change)}`; }; const compactRows = leaderboard.slice(0, obsConfig.rows); const readyPositionGrid = active && active.status === "ready" && normalizeStartMode(active.startMode) === "position"; const showStartGrid = obsConfig.showGrid && readyPositionGrid; const leadRow = compactRows[0] || null; const fastestRow = [...compactRows].filter((row) => Number.isFinite(row.bestLapMs)).sort((left, right) => left.bestLapMs - right.bestLapMs)[0] || null; const visiblePassings = getVisiblePassings(result); const elapsedOrRemaining = sessionTiming?.untimed ? formatElapsedClockLocal(sessionTiming?.elapsedMs ?? 0) : sessionTiming?.followUpActive ? formatCountdownLocal(sessionTiming?.followUpRemainingMs ?? 0) : formatCountdownLocal(sessionTiming?.remainingMs ?? 0); if (obsConfig.layout === "broadcast") { return renderObsBroadcast({ active, compactRows, startOrder, showStartGrid, fastestRow, elapsedOrRemaining, branding, obsConfig, positionChangeMarkup, deps }); } if (obsConfig.layout === "grid") { return `
${branding.logoDataUrl ? `` : ""}

${escapeHtml(getEventName(active.eventId))}

${escapeHtml(active.name)}

${escapeHtml(getSessionTypeLabel(active.type))} ${escapeHtml(getStartModeLabel(active.startMode))} ${t("table.laps")}: ${leadRow?.laps || 0} ${t("timing.total_passings")}: ${visiblePassings.length || 0}
${obsConfig.showClock ? `
${elapsedOrRemaining} ${escapeHtml(sessionTiming?.followUpActive ? t("timing.follow_up_active") : getStatusLabel(active.status))}
` : ""}

${showStartGrid ? t("events.start_grid") : t("overlay.leaderboard_live")}

${t("overlay.mode_obs")}
${showStartGrid ? renderPositionGrid(active) : renderOverlayLeaderboard(compactRows, deps, { sortable: false, lastLap: isOpenPracticeSession(active), practiceRank: isPracticeRankedSession(active) })}
`; } if (obsConfig.layout === "lowerthird") { return `

${escapeHtml(getEventName(active.eventId))}

${escapeHtml(active.name)}

${obsConfig.showClock ? `${elapsedOrRemaining}` : ""}
${compactRows.slice(0, 6).map((row, idx) => { const posClass = idx === 0 ? "pos-1" : idx === 1 ? "pos-2" : idx === 2 ? "pos-3" : ""; return `
${idx + 1} ${obsConfig.showFlags !== false ? rowFlag(row) : ""}${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? " ๐Ÿ" : ""}${row.suspectPending ? ` โš ` : ""} ${row.heatCarName ? `๐Ÿš— ${escapeHtml(row.heatCarName)}` : ""} ${obsConfig.showLaps ? `${t("table.laps")}: ${row.laps ?? 0}` : ""} ${obsConfig.showLast && row.lastLapMs > 0 ? `${t("overlay.col_last")}: ${escapeHtml(formatLap(row.lastLapMs))}` : ""} ${obsShowsResult(active, obsConfig) ? `${t("table.result")}: ${escapeHtml(row.resultDisplay)}` : ""} ${obsConfig.showGap ? `${t("table.gap")}: ${escapeHtml(row.gapDisplay || row.gapAhead || "-")}` : ""}
`; }).join("")}
`; } // The event name above the session name, unless it says the same thing (an Open Practice is // often named after its event). const eventName = String(getEventName(active.eventId) || "").trim(); const eventKicker = eventName.toLocaleLowerCase() === String(active.name || "").trim().toLocaleLowerCase() ? "" : eventName; const towerRowsHtml = showStartGrid ? getSessionGridEntries(active) .slice(0, obsConfig.rows) .map((entry, idx) => { const posClass = idx === 0 ? "pos-1" : idx === 1 ? "pos-2" : idx === 2 ? "pos-3" : ""; return `
${entry.slot}
${escapeHtml(entry.name)} ${entry.meta ? `${escapeHtml(entry.meta)}` : ""}
`; }) .join("") : compactRows .map((row, idx) => { const posClass = idx === 0 ? "pos-1" : idx === 1 ? "pos-2" : idx === 2 ? "pos-3" : ""; const trail = [ positionChangeMarkup(row, idx + 1), obsConfig.showLaps ? `${row.laps ?? 0}L` : "", obsConfig.showLast ? `${row.lastLapMs > 0 ? escapeHtml(formatLap(row.lastLapMs)) : "-"}` : "", obsShowsResult(active, obsConfig) ? `${escapeHtml(row.resultDisplay)}` : "", obsConfig.showBest ? `${formatLap(row.bestLapMs)}` : "", obsConfig.showGap ? `${escapeHtml(row.gapDisplay || row.gapAhead || "-")}` : "", ] .filter(Boolean) .join(""); return `
${idx + 1}
${obsConfig.showFlags !== false ? rowFlag(row) : ""}${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? " ๐Ÿ" : ""}${row.suspectPending ? ` โš ` : ""} ${row.teamId ? `${escapeHtml(formatTeamActiveMemberLabel(row))}` : row.heatCarName ? `๐Ÿš— ${escapeHtml(row.heatCarName)}` : ""}
${trail ? `
${trail}
` : ""}
`; }) .join(""); return `
${branding.logoDataUrl ? `` : ""}
${eventKicker ? `

${escapeHtml(eventKicker)}

` : ""}

${escapeHtml(active.name)}

${obsConfig.showClock ? `
${elapsedOrRemaining}
` : ""}
${escapeHtml(getSessionTypeLabel(active.type))} ${escapeHtml(getStartModeLabel(active.startMode))} ${showStartGrid ? `${t("events.start_grid")}` : ""} ${!showStartGrid && obsConfig.showFastest ? `${t("overlay.fastest_lap")}: ${formatLap(fastestRow?.bestLapMs)}` : ""}
${towerRowsHtml || `

${t("timing.no_laps")}

`}
`; } function padClock(value) { return String(value).padStart(2, "0"); } function formatCountdownLocal(ms) { const totalMs = Math.max(0, Number(ms) || 0); const totalSeconds = Math.floor(totalMs / 1000); const minutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; return `${padClock(minutes)}:${padClock(seconds)}`; } function formatElapsedClockLocal(ms) { const totalMs = Math.max(0, Number(ms) || 0); const totalSeconds = Math.floor(totalMs / 1000); const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = totalSeconds % 60; return `${hours}:${padClock(minutes)}:${padClock(seconds)}`; } function formatLapLocal(ms) { if (!Number.isFinite(ms)) { return "-"; } const totalMs = Math.max(0, Math.round(ms)); const minutes = Math.floor(totalMs / 60000); const seconds = Math.floor((totalMs % 60000) / 1000); const millis = totalMs % 1000; return `${minutes}:${String(seconds).padStart(2, "0")}.${String(millis).padStart(3, "0")}`; }