import { sortValuesAttribute } from "./list_sorting.js"; import { escapeHtml as escapeHtmlLocal } from "./html_escape.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}
`; } export function renderOverlayLeaderboard(rows, { t, escapeHtml, formatTeamActiveMemberLabel, formatLap, formatPredictedLapDelta }, { sortable = true } = {}) { 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([t("table.pos"), t("table.driver"), t("table.laps"), t("table.result"), t("table.gap"), t("table.ahead_gap"), t("table.own_delta"), t("table.best_lap")])}"` : ""; 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([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])}"` : ""; return `
${idx + 1}
${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? ` 🏁 ${t("timing.personal_time_up")}` : ""}${row.suspectPending ? ` ⚠` : ""} ${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)}
${row.laps ?? 0}
${escapeHtml(row.resultDisplay)}
${escapeHtml(row.gapDisplay || row.gapAhead || "-")}
${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; } // In practice the ranking value *is* the best lap, so "result" and "best" would print the // same time twice - show it once. function obsShowsResult(session, obsConfig) { return obsConfig.showResult && !(obsConfig.showBest && ["open_practice", "free_practice"].includes(String(session?.type || ""))); } 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 ? 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 === "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 })}
`; } 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} ${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? " 🏁" : ""}${row.suspectPending ? ` ⚠` : ""} ${obsConfig.showLaps ? `${t("table.laps")}: ${row.laps ?? 0}` : ""} ${obsShowsResult(active, obsConfig) ? `${t("table.result")}: ${escapeHtml(row.resultDisplay)}` : ""} ${obsConfig.showGap ? `${t("table.gap")}: ${escapeHtml(row.gapDisplay || row.gapAhead || "-")}` : ""}
`; }).join("")}
`; } 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)} ${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` : "", obsShowsResult(active, obsConfig) ? `${escapeHtml(row.resultDisplay)}` : "", obsConfig.showBest ? `${formatLap(row.bestLapMs)}` : "", obsConfig.showGap ? `${escapeHtml(row.gapDisplay || row.gapAhead || "-")}` : "", ] .filter(Boolean) .join(""); return `
${idx + 1}
${escapeHtml(row.displayName || row.driverName)}${row.personalTimeUp ? " 🏁" : ""}${row.suspectPending ? ` ⚠` : ""} ${escapeHtml(row.teamId ? formatTeamActiveMemberLabel(row) : row.subLabel || row.transponder || "-")}
${trail ? `
${trail}
` : ""}
`; }) .join(""); return `
${branding.logoDataUrl ? `` : ""}

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

${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")}`; }