fix(race): finish the lap you are on, one clock owner, edits survive refresh, participants editable (1.59.0)
This commit is contained in:
1 parent
afb8829b16
commit
db6a9f19e4
16 files changed
+313
-39
No files matched your search
+17
-4
@@ -19,7 +19,7 @@ import { renderRaceFormatField, renderRaceFormatContextCard, getRaceSummaryItems
|
||||
|
||||
import { normalizeRaceTeam as normalizeRaceTeamLogic, normalizeStoredRacePreset as normalizeStoredRacePresetLogic, getRaceFormatPresets as getRaceFormatPresetsLogic, applyRaceFormatPreset as applyRaceFormatPresetLogic, buildRaceFormatConfigFromForm as buildRaceFormatConfigFromFormLogic, normalizeEvent as normalizeEventLogic, normalizeBrandingConfig as normalizeBrandingConfigLogic, resolveEventBranding as resolveEventBrandingLogic, getRaceManageStatuses as getRaceManageStatusesLogic, buildDefaultRaceWizardDraft as buildDefaultRaceWizardDraftLogic, getRaceWizardPreset as getRaceWizardPresetLogic, applyRaceWizardPresetDefaults as applyRaceWizardPresetDefaultsLogic, ensureRaceParticipantsConfigured as ensureRaceParticipantsConfiguredLogic, buildRaceSession as buildRaceSessionLogic, buildOpenPracticeBundle as buildOpenPracticeBundleLogic, buildTrackSession as buildTrackSessionLogic, createSponsorRounds as createSponsorRoundsLogic, buildRaceSessionsFromWizard as buildRaceSessionsFromWizardLogic, getRaceWizardSessionPlan as getRaceWizardSessionPlanLogic, getEventDrivers as getEventDriversLogic, getEventTeams as getEventTeamsLogic, getTeamDriverPool as getTeamDriverPoolLogic, reassignTeamMembers as reassignTeamMembersLogic, findEventTeamForPassing as findEventTeamForPassingLogic, generateQualifyingForRace as generateQualifyingForRaceLogic, reseedUpcomingQualifying as reseedUpcomingQualifyingLogic, moveDriversIntoQualifyingHeat as moveDriversIntoQualifyingHeatLogic, parseQualifyingHeatName as parseQualifyingHeatNameLogic, generateFinalsForRace as generateFinalsForRaceLogic, applyBumpsForRace as applyBumpsForRaceLogic, buildEventSchedule as buildEventScheduleLogic, normalizeHeatOrder, planSeedingGroups } from "./event_race_logic.js";
|
||||
|
||||
import { getSessionTypeLabel as getSessionTypeLabelLogic, getStatusLabel as getStatusLabelLogic, isUntimedSession as isUntimedSessionLogic, getActiveSession as getActiveSessionLogic, getLiveSession as getLiveSessionLogic, getSessionTargetMs as getSessionTargetMsLogic, getSessionLapWindow as getSessionLapWindowLogic, isCountedPassing as isCountedPassingLogic, getVisiblePassings as getVisiblePassingsLogic, getPassingValidationLabel as getPassingValidationLabelLogic, getSessionTiming as getSessionTimingLogic, ensureSessionResult as ensureSessionResultLogic, buildLeaderboard as buildLeaderboardLogic, formatLapDelta as formatLapDeltaLogic, formatLeaderboardGap as formatLeaderboardGapLogic, getCompetitorElapsedMs as getCompetitorElapsedMsLogic, getCompetitorPassings as getCompetitorPassingsLogic, getCompetitorSeedMetric as getCompetitorSeedMetricLogic, getSessionEntrants as getSessionEntrantsLogic, buildPracticeStandings as buildPracticeStandingsLogic, getQualifyingPointsValue as getQualifyingPointsValueLogic, isHighPointsTable as isHighPointsTableLogic, compareNumberSet as compareNumberSetLogic, buildQualifyingTieBreakNote as buildQualifyingTieBreakNoteLogic, hasQualifyingPrimaryTie as hasQualifyingPrimaryTieLogic, buildQualifyingStandings as buildQualifyingStandingsLogic, formatTeamActiveMemberLabel as formatTeamActiveMemberLabelLogic, buildTeamRaceStandings as buildTeamRaceStandingsLogic, buildSessionChannelStats as buildSessionChannelStatsLogic, buildTeamStintLog as buildTeamStintLogLogic, getSessionGridEntries as getSessionGridEntriesLogic, getSessionGridOrder as getSessionGridOrderLogic, ensureSessionDriverOrder as ensureSessionDriverOrderLogic, buildFinalStandings as buildFinalStandingsLogic, getTrackRecordMs as getTrackRecordMsLogic } from "./timing_logic.js";
|
||||
import { getFinishWait as getFinishWaitLogic, getSessionTypeLabel as getSessionTypeLabelLogic, getStatusLabel as getStatusLabelLogic, isUntimedSession as isUntimedSessionLogic, getActiveSession as getActiveSessionLogic, getLiveSession as getLiveSessionLogic, getSessionTargetMs as getSessionTargetMsLogic, getSessionLapWindow as getSessionLapWindowLogic, isCountedPassing as isCountedPassingLogic, getVisiblePassings as getVisiblePassingsLogic, getPassingValidationLabel as getPassingValidationLabelLogic, getSessionTiming as getSessionTimingLogic, ensureSessionResult as ensureSessionResultLogic, buildLeaderboard as buildLeaderboardLogic, formatLapDelta as formatLapDeltaLogic, formatLeaderboardGap as formatLeaderboardGapLogic, getCompetitorElapsedMs as getCompetitorElapsedMsLogic, getCompetitorPassings as getCompetitorPassingsLogic, getCompetitorSeedMetric as getCompetitorSeedMetricLogic, getSessionEntrants as getSessionEntrantsLogic, buildPracticeStandings as buildPracticeStandingsLogic, getQualifyingPointsValue as getQualifyingPointsValueLogic, isHighPointsTable as isHighPointsTableLogic, compareNumberSet as compareNumberSetLogic, buildQualifyingTieBreakNote as buildQualifyingTieBreakNoteLogic, hasQualifyingPrimaryTie as hasQualifyingPrimaryTieLogic, buildQualifyingStandings as buildQualifyingStandingsLogic, formatTeamActiveMemberLabel as formatTeamActiveMemberLabelLogic, buildTeamRaceStandings as buildTeamRaceStandingsLogic, buildSessionChannelStats as buildSessionChannelStatsLogic, buildTeamStintLog as buildTeamStintLogLogic, getSessionGridEntries as getSessionGridEntriesLogic, getSessionGridOrder as getSessionGridOrderLogic, ensureSessionDriverOrder as ensureSessionDriverOrderLogic, buildFinalStandings as buildFinalStandingsLogic, getTrackRecordMs as getTrackRecordMsLogic } from "./timing_logic.js";
|
||||
import { normalizeTrackLayouts, getTrackLayoutIdAt, getTrackLayoutLabel, nextTrackLayoutLabel, findRaceSessionBlockingLayoutChange, isPracticeSessionType, isTrackLayoutInUse } from "./track_layouts_logic.js";
|
||||
|
||||
import { renderDashboardView, renderClassesView, renderDriversView, renderCarsView } from "./core_views.js";
|
||||
@@ -219,7 +219,13 @@ const announceRaceFinished = (finished = null) => {
|
||||
if (podium.length > 1) triggerRaceAudio("podium", { variables: { podium: podium.map((row) => row.displayName || row.driverName).join(", ") } });
|
||||
};
|
||||
const announceRaceClockEvent = (eventKey, session) => triggerRaceAudio(eventKey, { logData: { raceId: session.eventId, sessionId: session.id } });
|
||||
const handleSessionTimerTick = () => handleSessionTimerTickHelper({ getActiveSession: getLiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, announceRaceFinished, announceRaceClockEvent });
|
||||
const handleSessionTimerTick = () => handleSessionTimerTickHelper({ getActiveSession: getLiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId: () => lastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId: (value) => { lastFinishAnnouncementSessionId = value; }, announceRaceFinished, announceRaceClockEvent,
|
||||
// The race browser: the one on the decoder, or with no decoder anywhere, the one that started the heat.
|
||||
isClockOwner: (session) => !overlayMode && (Boolean(state.decoder?.connected) || readClockOwner() === session.id),
|
||||
getFinishWait: (session) => getFinishWaitLogic(session, state.resultsBySession[session.id]?.competitors, { maxLapMs: getSessionLapWindow(session).maxLapMs }) });
|
||||
const CLOCK_OWNER_KEY = "rc_clock_owner";
|
||||
const readClockOwner = () => { try { return sessionStorage.getItem(CLOCK_OWNER_KEY) || ""; } catch { return ""; } };
|
||||
const writeClockOwner = (sessionId) => { try { sessionStorage.setItem(CLOCK_OWNER_KEY, sessionId); } catch { /* private mode */ } };
|
||||
const cancelRaceStart = () => raceAudioEngine.cancelStartSequence();
|
||||
const startSessionWithAudio = (session, callbacks) => {
|
||||
// Only the casual, come-and-go practice modes (open_practice - the standalone "Quick
|
||||
@@ -554,6 +560,7 @@ function resetSessionData(session) {
|
||||
session.resultsResetAt = Date.now();
|
||||
delete state.resultsBySession[session.id];
|
||||
session.followUpStartedAt = null;
|
||||
session.finishWaitUntil = null;
|
||||
session.calledAt = null;
|
||||
// A heat (anything but an Open/Free Practice that runs all evening) goes back to "ready":
|
||||
// the clock is back at zero and it can be started again.
|
||||
@@ -1794,6 +1801,8 @@ const TRANSLATIONS = {
|
||||
"events.edit": "Redigera",
|
||||
"events.sessions": "Sessioner",
|
||||
"events.participants": "Deltagare",
|
||||
"events.other_class_participants": "Förare från andra klasser ({count})",
|
||||
"events.participants_sync_hint": "Ändringar här följer med till practice och kvalheat som inte körts än. En ny förare hamnar i kvalheatet med minst förare.",
|
||||
"events.select_participants": "Välj racedeltagare",
|
||||
"events.select_all_participants": "Markera alla",
|
||||
"events.clear_participants": "Rensa deltagare",
|
||||
@@ -2796,7 +2805,7 @@ const TRANSLATIONS = {
|
||||
"guide.race_format_5": "Finaltid och Final-start styr varje finalleg, ofta med positionsstart.",
|
||||
"guide.race_format_6": "Bump-up per final och Reservera bump-platser används om förare ska kunna flyttas från lägre final till nästa main.",
|
||||
"guide.race_format_7": "Källa för finaler avgör om finalerna seedas från practice eller kvalrankingen.",
|
||||
"guide.race_format_8": "Follow-up tid ger en extra uppsamlingsperiod efter ordinarie racetid innan heatet verkligen stängs.",
|
||||
"guide.race_format_8": "När tiden är slut säger speakern \"Tiden är slut, slutför pågående varv\". Varje förare är i mål vid sin första passering efter sin egen tid, och passeringar efter det räknas inte. Heatet stängs så fort alla gått i mål, eller senast när den som är kvar ute fått cirka 1,5 av sin egen varvtid på sig (aldrig mer än Max varvtid). Follow-up tid är den kortaste väntetiden.",
|
||||
"guide.race_format_9": "Min varvtid filtrerar bort shortcuts och felträffar. Exempel: på en 16-sekundersbana kan du sätta 11 sekunder som min-gräns.",
|
||||
"guide.race_format_10": "Max varvtid är en statistikgräns. En längre passering avslutar stinten och utesluts ur pace-snittet, men varvet räknas fortfarande i race. Exempel: 120 sekunder ger en ny stint efter två minuters uppehåll.",
|
||||
"guide.race_format_11": "Preset låter dig snabbt fylla raceformat med vettiga grundvärden för kort teknisk bana, klubbrace, IFMAR-liknande upplägg eller endurance.",
|
||||
@@ -3773,6 +3782,8 @@ const TRANSLATIONS = {
|
||||
"events.edit": "Edit",
|
||||
"events.sessions": "Sessions",
|
||||
"events.participants": "Participants",
|
||||
"events.other_class_participants": "Drivers from other classes ({count})",
|
||||
"events.participants_sync_hint": "Changes here carry over to practice and qualifying heats not run yet. A new driver joins the qualifying heat with the fewest drivers.",
|
||||
"events.select_participants": "Select race participants",
|
||||
"events.select_all_participants": "Select all",
|
||||
"events.clear_participants": "Clear participants",
|
||||
@@ -4775,7 +4786,7 @@ const TRANSLATIONS = {
|
||||
"guide.race_format_5": "Final duration and Final start control each final leg, often with position start.",
|
||||
"guide.race_format_6": "Bump-up per main and Reserve bump slots are used if drivers should move from a lower final into the next main.",
|
||||
"guide.race_format_7": "Source for finals decides whether finals are seeded from practice or qualifying standings.",
|
||||
"guide.race_format_8": "Follow-up time adds an extra collection period after the scheduled race time before the heat is actually closed.",
|
||||
"guide.race_format_8": "When time is up the announcer says \"Time has expired, finish the lap you are on\". Each driver finishes at their first crossing after their own time, and crossings after that do not count. The heat closes as soon as everyone has finished, or at the latest when a car still out has had about 1.5 of its own lap time (never more than Max lap time). Follow-up time is the shortest wait.",
|
||||
"guide.race_format_9": "Min lap time filters out shortcuts and false hits. Example: on a 16-second track you can set 11 seconds as the minimum.",
|
||||
"guide.race_format_10": "Max lap time is a statistics boundary. A longer passing ends the stint and is excluded from pace averages, but the lap still counts in the race. Example: 120 seconds starts a new stint after a two-minute break.",
|
||||
"guide.race_format_11": "Preset lets you quickly fill the race format with sensible defaults for a short technical track, club race, IFMAR-like setup or endurance.",
|
||||
@@ -5179,6 +5190,7 @@ function normalizeSession(session = {}) {
|
||||
pausedAt: Number.isFinite(Number(session?.pausedAt)) ? Number(session.pausedAt) : null,
|
||||
totalPausedMs: Math.max(0, Number(session?.totalPausedMs || 0) || 0),
|
||||
followUpPausedMs: Math.max(0, Number(session?.followUpPausedMs || 0) || 0),
|
||||
finishWaitUntil: Number(session?.finishWaitUntil || 0) || null,
|
||||
audioAnnouncements: Array.isArray(session?.audioAnnouncements) ? session.audioAnnouncements.map(String).filter(Boolean) : [],
|
||||
assignments,
|
||||
driverIds: Array.isArray(session?.driverIds) ? session.driverIds.map(String).filter(Boolean) : [],
|
||||
@@ -5725,6 +5737,7 @@ async function runOperationalStart(session, sequenceCallbacks, onTone) {
|
||||
session = state.sessions.find((item) => item.id === session.id) || session;
|
||||
state.activeSessionId = session.id;
|
||||
beginSessionControl(session);
|
||||
writeClockOwner(session.id);
|
||||
session.trackLayoutId = getTrackLayoutIdAt(state.trackLayouts);
|
||||
lastFinishAnnouncementSessionId = null;
|
||||
lastOverlayLeaderKeyBySession[session.id] = null;
|
||||
|
||||
@@ -5,6 +5,7 @@ import { isSuspectLap, getSuspectReferenceLaps, releaseSettledSuspectLaps } from
|
||||
import { shouldCallPracticePersonalBest } from "./practice_callouts_logic.js";
|
||||
import { normalizeRaceAudioSettings } from "./race_audio.js";
|
||||
import { decoderClockCheck, describeDecoderClockSkew } from "./decoder_clock_check.js";
|
||||
import { getCompetitorEndTs } from "./timing_logic.js";
|
||||
|
||||
const PRACTICE_SESSION_TYPES = new Set(["open_practice", "free_practice", "practice"]);
|
||||
// Last personal best *called* per driver, per practice day and layout (practice_callouts_logic.js).
|
||||
@@ -482,6 +483,12 @@ export function processDecoderMessageHelper(msg, deps, decoderRole = "main") {
|
||||
entry.startTimestamp = session.startedAt || timestamp;
|
||||
}
|
||||
|
||||
// Finished (crossed after its time was up): later crossings are not laps.
|
||||
if (entry.finishedAt) {
|
||||
report("after_finish", "ignored");
|
||||
return true;
|
||||
}
|
||||
|
||||
const baseTs = entry.lastTimestamp || entry.startTimestamp || session.startedAt || timestamp;
|
||||
const lapMs = Math.max(0, timestamp - baseTs);
|
||||
const { minLapMs, maxLapMs } = getSessionLapWindow(session);
|
||||
@@ -551,6 +558,8 @@ export function processDecoderMessageHelper(msg, deps, decoderRole = "main") {
|
||||
entry.laps += 1;
|
||||
entry.lastLapMs = lapMs;
|
||||
entry.lastTimestamp = timestamp;
|
||||
const endTs = getCompetitorEndTs(session, entry);
|
||||
if (endTs && timestamp >= endTs) entry.finishedAt = timestamp;
|
||||
|
||||
// A suspect lap counts like any other lap until someone removes it; it is only not called
|
||||
// out as a personal best or record below.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { orderSessionsForRunning, moveSessionInRunningOrder } from "./event_race_logic.js";
|
||||
import { orderSessionsForRunning, moveSessionInRunningOrder, applyFormatToPendingSessions, syncParticipantsToSessions } from "./event_race_logic.js";
|
||||
import { setSessionGroupOpen } from "./event_manager_view.js";
|
||||
let activeManageTab = "setup";
|
||||
// Maps a data-target anchor id (used by the step-card overview and the race-summary
|
||||
@@ -130,6 +130,15 @@ export function renderEventManagerView(context) {
|
||||
.map((d) => `<option value="${d.id}">${escapeHtml(d.name)}</option>`)
|
||||
.join("");
|
||||
const raceDrivers = event.mode === "race" ? getEventDrivers(event) : [];
|
||||
// The checklist offers every driver of the class (a driver left out can be ticked again),
|
||||
// the chosen ones from other classes, and the rest of the club folded away.
|
||||
const chosenIds = event.raceConfig?.participantsConfigured ? (event.raceConfig.driverIds || []) : null;
|
||||
const participantChoices = event.mode === "race"
|
||||
? state.drivers.filter((driver) => !event.classId || driver.classId === event.classId || (chosenIds || []).includes(driver.id))
|
||||
: [];
|
||||
const otherClassChoices = event.mode === "race" && event.classId
|
||||
? state.drivers.filter((driver) => !participantChoices.includes(driver)).sort((a, b) => String(a.name || "").localeCompare(String(b.name || "")))
|
||||
: [];
|
||||
const teamDriverPool = event.mode === "race" ? getTeamDriverPool(event) : { drivers: [], fallback: false };
|
||||
const raceTeams = event.mode === "race" ? getEventTeams(event) : [];
|
||||
if (selectedTeamEditId && !raceTeams.some((team) => team.id === selectedTeamEditId)) {
|
||||
@@ -187,6 +196,8 @@ export function renderEventManagerView(context) {
|
||||
renderManageStatusBadgeView,
|
||||
selectedParticipantCount,
|
||||
raceDrivers,
|
||||
participantChoices,
|
||||
otherClassChoices,
|
||||
teamDriverPool,
|
||||
showTeamsSection,
|
||||
parseQualifyingHeatName,
|
||||
@@ -564,10 +575,15 @@ export function renderEventManagerView(context) {
|
||||
|
||||
if (event.mode === "race") {
|
||||
const persistRaceParticipants = () => {
|
||||
const selectedIds = Array.from(document.querySelectorAll(".race-participant:checked")).map((node) => node.value);
|
||||
const beforeIds = getEventDrivers(event).map((driver) => driver.id);
|
||||
const checked = new Set(Array.from(document.querySelectorAll(".race-participant:checked")).map((node) => node.value));
|
||||
// Keep the entry order: the ones already in stay where they were, new ones go last.
|
||||
const selectedIds = [...beforeIds.filter((id) => checked.has(id)), ...[...checked].filter((id) => !beforeIds.includes(id))];
|
||||
event.raceConfig.driverIds = selectedIds;
|
||||
event.raceConfig.participantsConfigured = true;
|
||||
syncParticipantsToSessions(state.sessions.filter((session) => session.eventId === event.id), beforeIds, selectedIds);
|
||||
saveState();
|
||||
refreshManager();
|
||||
};
|
||||
|
||||
document.querySelectorAll(".race-participant").forEach((node) => {
|
||||
@@ -727,6 +743,7 @@ export function renderEventManagerView(context) {
|
||||
e.preventDefault();
|
||||
const form = new FormData(e.currentTarget);
|
||||
const config = buildRaceFormatConfigFromForm(form, event);
|
||||
const before = { ...(event.raceConfig || {}) };
|
||||
updateEvent((item) => ({
|
||||
...item,
|
||||
raceConfig: {
|
||||
@@ -734,6 +751,7 @@ export function renderEventManagerView(context) {
|
||||
teams: getEventTeams(item),
|
||||
},
|
||||
}));
|
||||
applyFormatToPendingSessions(state.sessions.filter((session) => session.eventId === event.id), before, config);
|
||||
saveState();
|
||||
refreshManager();
|
||||
});
|
||||
|
||||
+13
-10
@@ -47,6 +47,8 @@ export function renderEventManagerMarkup(context) {
|
||||
renderManageStatusBadgeView,
|
||||
selectedParticipantCount,
|
||||
raceDrivers,
|
||||
participantChoices = raceDrivers,
|
||||
otherClassChoices = [],
|
||||
teamDriverPool,
|
||||
showTeamsSection,
|
||||
parseQualifyingHeatName,
|
||||
@@ -358,21 +360,22 @@ export function renderEventManagerMarkup(context) {
|
||||
<button id="selectAllParticipants" class="btn" type="button">${t("events.select_all_participants")}</button>
|
||||
<button id="clearParticipants" class="btn btn-danger" type="button">${t("events.clear_participants")}</button>
|
||||
</div>
|
||||
<div class="check-grid mt-16">
|
||||
${raceDrivers
|
||||
.map((driver) => {
|
||||
const checked = event.raceConfig.participantsConfigured
|
||||
? (event.raceConfig.driverIds || []).includes(driver.id)
|
||||
: true;
|
||||
return `
|
||||
${(() => {
|
||||
const card = (driver) => {
|
||||
const checked = event.raceConfig.participantsConfigured
|
||||
? (event.raceConfig.driverIds || []).includes(driver.id)
|
||||
: driver.classId === event.classId;
|
||||
return `
|
||||
<label class="check-card">
|
||||
<input type="checkbox" class="race-participant" value="${driver.id}" ${checked ? "checked" : ""} />
|
||||
<span>${escapeHtml(driver.name)}${driver.transponder ? ` (${escapeHtml(driver.transponder)})` : ""}</span>
|
||||
</label>
|
||||
`;
|
||||
})
|
||||
.join("")}
|
||||
</div>
|
||||
};
|
||||
return `<div class="check-grid mt-16">${participantChoices.map(card).join("")}</div>
|
||||
${otherClassChoices.length ? `<details class="mt-16" id="otherClassParticipants"><summary>${t("events.other_class_participants", { count: otherClassChoices.length })}</summary><div class="check-grid mt-16">${otherClassChoices.map(card).join("")}</div></details>` : ""}
|
||||
<p class="muted mt-16">${t("events.participants_sync_hint")}</p>`;
|
||||
})()}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
+56
-3
@@ -584,13 +584,43 @@ export function getEventDrivers(event, { state }) {
|
||||
// from this list (a fallback qualifying/finals grid with no practice data yet, a
|
||||
// staggered heat's start-order announcement) should follow the order a club admin
|
||||
// actually built the entry list in, not an unrelated internal array order.
|
||||
const classDriverIds = new Set(classDrivers.map((driver) => driver.id));
|
||||
const byId = new Map(classDrivers.map((driver) => [driver.id, driver]));
|
||||
// A chosen entry may come from another class (one driver, two classes).
|
||||
const byId = new Map(state.drivers.map((driver) => [driver.id, driver]));
|
||||
return (event.raceConfig.driverIds || [])
|
||||
.filter((id) => classDriverIds.has(id))
|
||||
.filter((id) => byId.has(id))
|
||||
.map((id) => byId.get(id));
|
||||
}
|
||||
|
||||
// The entry list changed: sessions not run yet follow it. A removed driver leaves them; an
|
||||
// added one joins each practice that holds the whole entry list, and the qualifying heat with
|
||||
// the fewest drivers (the same heat number in every round still to run). Run sessions and
|
||||
// finals are left alone.
|
||||
export function syncParticipantsToSessions(sessions, beforeIds = [], afterIds = []) {
|
||||
const removed = new Set(beforeIds.filter((id) => !afterIds.includes(id)));
|
||||
const added = afterIds.filter((id) => !beforeIds.includes(id));
|
||||
const pending = sessions.filter((session) => session.status === "ready" && !session.startedAt && ["practice", "qualification"].includes(session.type));
|
||||
const without = (list) => (list || []).filter((id) => !removed.has(id));
|
||||
pending.forEach((session) => {
|
||||
session.driverIds = without(session.driverIds);
|
||||
session.manualGridIds = without(session.manualGridIds);
|
||||
});
|
||||
if (!added.length) return;
|
||||
const join = (session, id) => {
|
||||
if (!(session.driverIds || []).includes(id)) session.driverIds = [...(session.driverIds || []), id];
|
||||
if (Array.isArray(session.manualGridIds) && !session.manualGridIds.includes(id)) session.manualGridIds = [...session.manualGridIds, id];
|
||||
};
|
||||
const keep = new Set(beforeIds.filter((id) => !removed.has(id)));
|
||||
pending.filter((session) => session.type === "practice" && [...keep].every((id) => (session.driverIds || []).includes(id)))
|
||||
.forEach((session) => added.forEach((id) => join(session, id)));
|
||||
const heats = pending.map((session) => ({ session, parsed: parseQualifyingHeatName(session.name) })).filter((item) => item.parsed);
|
||||
added.forEach((id) => {
|
||||
if (!heats.length) return;
|
||||
const size = (heat) => heats.filter((item) => item.parsed.heat === heat).reduce((max, item) => Math.max(max, (item.session.driverIds || []).length), 0);
|
||||
const heatNumbers = [...new Set(heats.map((item) => item.parsed.heat))].sort((a, b) => size(a) - size(b) || a - b);
|
||||
heats.filter((item) => item.parsed.heat === heatNumbers[0]).forEach((item) => join(item.session, id));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function getEventTeams(event, { normalizeRaceTeam }) {
|
||||
@@ -1114,3 +1144,26 @@ export function buildEventSchedule(event, sessions) {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// A changed race format reaches the sessions not run yet: when e.g. "qualifying time" goes
|
||||
// 5 -> 3 min, every ready practice/qualifying session gets 3 min. Only fields whose format
|
||||
// value changed are applied, so a heat edited by hand keeps its own other values.
|
||||
export function applyFormatToPendingSessions(sessions, before = {}, after = {}) {
|
||||
const fields = {
|
||||
practice: [["qualDurationMin", "durationMin"]],
|
||||
qualification: [["qualDurationMin", "durationMin"], ["qualStartMode", "startMode"], ["followUpSec", "followUpSec"], ["qualSeedLapCount", "seedBestLapCount"], ["qualSeedMethod", "seedMethod"]],
|
||||
final: [["finalDurationMin", "durationMin"], ["finalStartMode", "startMode"], ["followUpSec", "followUpSec"]],
|
||||
};
|
||||
let changed = 0;
|
||||
sessions.forEach((session) => {
|
||||
if (session.status !== "ready" || session.startedAt) return;
|
||||
let touched = false;
|
||||
(fields[session.type] || []).forEach(([configKey, sessionKey]) => {
|
||||
if (after[configKey] === undefined || after[configKey] === before[configKey]) return;
|
||||
session[sessionKey] = after[configKey];
|
||||
touched = true;
|
||||
});
|
||||
if (touched) changed += 1;
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
+44
-11
@@ -103,19 +103,32 @@ export async function stopManagedAmmcHelper({ ammc, t, getBackendUrl }) {
|
||||
}
|
||||
}
|
||||
|
||||
// The background refresh updates items with the same id in place instead of replacing them,
|
||||
// so a form or button that already holds a session/event/driver (an open edit dialog, Run
|
||||
// again) still changes the live one - not a copy that is thrown away on the next save.
|
||||
export function keepIdentityById(previous, next) {
|
||||
const byId = new Map((Array.isArray(previous) ? previous : []).filter((item) => item && item.id).map((item) => [item.id, item]));
|
||||
return next.map((item) => {
|
||||
const existing = item && item.id ? byId.get(item.id) : null;
|
||||
if (!existing || existing === item) return item;
|
||||
Object.keys(existing).forEach((key) => { if (!(key in item)) delete existing[key]; });
|
||||
return Object.assign(existing, item);
|
||||
});
|
||||
}
|
||||
|
||||
export function applyPersistedStateHelper(persisted, deps) {
|
||||
const { state, getDefaultBackendUrl, DEFAULT_LANGUAGE, DEFAULT_THEME, AVAILABLE_THEMES, normalizeDriver, normalizeCar, normalizeEvent, normalizeSession, normalizeStoredRacePreset, normalizeObsOverlaySettings, normalizeTrainingState, normalizeRaceAudioSettings = (value = {}) => value || {}, normalizeTrackLayouts = (value) => (Array.isArray(value) ? value : []), applyTheme } = deps;
|
||||
state.classes = persisted.classes || [];
|
||||
state.drivers = (persisted.drivers || []).map((driver) => normalizeDriver(driver)).filter((driver) => driver.name);
|
||||
state.cars = (persisted.cars || []).map((car) => normalizeCar(car)).filter((car) => car.name);
|
||||
state.events = (persisted.events || []).map((event) => normalizeEvent(event));
|
||||
state.sessions = (persisted.sessions || []).map((session) => normalizeSession(session));
|
||||
state.drivers = keepIdentityById(state.drivers, (persisted.drivers || []).map((driver) => normalizeDriver(driver)).filter((driver) => driver.name));
|
||||
state.cars = keepIdentityById(state.cars, (persisted.cars || []).map((car) => normalizeCar(car)).filter((car) => car.name));
|
||||
state.events = keepIdentityById(state.events, (persisted.events || []).map((event) => normalizeEvent(event)));
|
||||
state.sessions = keepIdentityById(state.sessions, (persisted.sessions || []).map((session) => normalizeSession(session)));
|
||||
state.resultsBySession = persisted.resultsBySession || {};
|
||||
state.audioEventLog = Array.isArray(persisted.audioEventLog) ? persisted.audioEventLog.slice(0, 500) : [];
|
||||
state.training = normalizeTrainingState(persisted.training);
|
||||
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.series = keepIdentityById(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",
|
||||
@@ -420,11 +433,26 @@ export function announceRaceFinishedHelper({ t, getActiveSession, pushOverlayEve
|
||||
if (session) pushOverlayEvent("finish", `${session.name} • ${t("timing.race_finished")}`, { silentCue: true });
|
||||
}
|
||||
|
||||
export function handleSessionTimerTickHelper({ getActiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId, announceRaceFinished, announceRaceClockEvent = () => {} }) {
|
||||
// isClockOwner: only the browser that runs the race (connected to the decoder) calls the
|
||||
// clock and closes the heat - every other open window (Timing on a second PC, the drivers'
|
||||
// board) would otherwise call "time has expired" too. Those only close a heat left running
|
||||
// a minute past its limit, in case the race browser was closed.
|
||||
export function handleSessionTimerTickHelper({ getActiveSession, isUntimedSession, getSessionTiming, saveState, getLastFinishAnnouncementSessionId, setLastFinishAnnouncementSessionId, announceRaceFinished, announceRaceClockEvent = () => {}, isClockOwner = () => true, getFinishWait = () => ({ allFinished: true, closeAt: null }), now = () => Date.now() }) {
|
||||
const active = getActiveSession();
|
||||
if (!active || active.status !== "running") return { changed: false };
|
||||
if (isUntimedSession(active)) return { changed: false };
|
||||
const timing = getSessionTiming(active);
|
||||
if (!isClockOwner(active)) {
|
||||
const limit = Number(active.finishWaitUntil || 0) || (Number(active.startedAt || 0) + Number(timing.targetMs || 0) + Math.max(0, Number(active.totalPausedMs || 0)) + 120000);
|
||||
if (timing.remainingMs > 0 || now() < limit + 60000) return { changed: false };
|
||||
active.status = "finished";
|
||||
active.endedAt = now();
|
||||
active.finishedByTimer = true;
|
||||
active.followUpStartedAt = null;
|
||||
active.finishWaitUntil = null;
|
||||
saveState();
|
||||
return { changed: true };
|
||||
}
|
||||
if (!Array.isArray(active.audioAnnouncements)) active.audioAnnouncements = [];
|
||||
let changed = false;
|
||||
const announceOnce = (marker, eventKey) => {
|
||||
@@ -440,16 +468,21 @@ export function handleSessionTimerTickHelper({ getActiveSession, isUntimedSessio
|
||||
if (changed) saveState();
|
||||
return { changed };
|
||||
}
|
||||
// "Time has expired. Finish the lap you are on." - then each car finishes at its next
|
||||
// crossing, and the heat closes when all have (or the wait runs out).
|
||||
announceOnce("time_expired", "time_expired");
|
||||
if (!["open_practice", "free_practice", "practice"].includes(String(active.type || ""))) announceOnce("final_lap", "final_lap");
|
||||
if (Number(active.followUpSec || 0) > 0) {
|
||||
if (!active.followUpStartedAt) { active.followUpStartedAt = Date.now(); saveState(); return { changed: true }; }
|
||||
if (timing.followUpRemainingMs > 0) { if (changed) saveState(); return { changed }; }
|
||||
const wait = getFinishWait(active);
|
||||
if (!active.followUpStartedAt) { active.followUpStartedAt = now(); changed = true; }
|
||||
if (!wait.allFinished && wait.closeAt && now() < wait.closeAt) {
|
||||
if (active.finishWaitUntil !== wait.closeAt) { active.finishWaitUntil = wait.closeAt; changed = true; }
|
||||
if (changed) saveState();
|
||||
return { changed };
|
||||
}
|
||||
active.status = "finished";
|
||||
active.endedAt = Date.now();
|
||||
active.endedAt = now();
|
||||
active.finishedByTimer = true;
|
||||
active.followUpStartedAt = null;
|
||||
active.finishWaitUntil = null;
|
||||
if (getLastFinishAnnouncementSessionId() !== active.id) { announceRaceFinished(active); setLastFinishAnnouncementSessionId(active.id); }
|
||||
saveState();
|
||||
return { changed: true };
|
||||
|
||||
@@ -4,6 +4,7 @@ export function beginSession(session, nowTs = Date.now()) {
|
||||
session.endedAt = null;
|
||||
session.finishedByTimer = false;
|
||||
session.followUpStartedAt = null;
|
||||
session.finishWaitUntil = null;
|
||||
session.pausedAt = null;
|
||||
session.totalPausedMs = 0;
|
||||
session.followUpPausedMs = 0;
|
||||
@@ -24,6 +25,7 @@ export function finishSession(session, nowTs = Date.now()) {
|
||||
session.endedAt = nowTs;
|
||||
session.finishedByTimer = false;
|
||||
session.followUpStartedAt = null;
|
||||
session.finishWaitUntil = null;
|
||||
session.pausedAt = null;
|
||||
return session;
|
||||
}
|
||||
|
||||
+33
-2
@@ -39,6 +39,34 @@ export function getLiveSession({ state }) {
|
||||
|
||||
|
||||
|
||||
// "Finish the lap you are on" (EFRA/IFMAR): when a car's time is up, its next crossing is its
|
||||
// finish and later ones don't count. Staggered/flying starts have a clock per car.
|
||||
const ROLLING_SESSION_TYPES = new Set(["open_practice", "free_practice"]);
|
||||
export function getCompetitorEndTs(session, row) {
|
||||
if (ROLLING_SESSION_TYPES.has(String(session?.type || "")) || !(Number(session?.durationMin) > 0)) return null;
|
||||
const personal = session.startMode === "staggered" || session.startMode === "flying";
|
||||
const startTs = Number(personal ? row?.startTimestamp : session.startedAt || row?.startTimestamp) || 0;
|
||||
if (!startTs) return null;
|
||||
return startTs + Number(session.durationMin) * 60000 + Math.max(0, Number(session.totalPausedMs || 0) || 0);
|
||||
}
|
||||
|
||||
// When a heat whose time is up may close: as soon as every car on track has crossed after its
|
||||
// own time, else at the latest when the slowest still-out car has had ~1.5 of its own lap
|
||||
// time to come round (never sooner than the follow-up time, never longer than max lap time).
|
||||
export function getFinishWait(session, competitors = {}, { maxLapMs = Infinity } = {}) {
|
||||
const followMs = Math.max(0, Number(session?.followUpSec || 0) || 0) * 1000;
|
||||
const rows = Object.values(competitors || {}).filter((row) => getCompetitorEndTs(session, row) !== null && (Number(row.laps || 0) > 0 || row.finishedAt));
|
||||
const unfinished = rows.filter((row) => !row.finishedAt);
|
||||
const closeAt = unfinished.length
|
||||
? Math.max(...unfinished.map((row) => {
|
||||
const lapMs = Number(row.lastLapMs || row.bestLapMs || 0) || 0;
|
||||
const graceMs = Math.max(followMs, Math.min(lapMs * 1.5, Number.isFinite(maxLapMs) && maxLapMs > 0 ? maxLapMs : Infinity));
|
||||
return getCompetitorEndTs(session, row) + graceMs;
|
||||
}))
|
||||
: null;
|
||||
return { allFinished: rows.length > 0 && unfinished.length === 0, closeAt, cars: rows.length, finished: rows.length - unfinished.length };
|
||||
}
|
||||
|
||||
export function getSessionTargetMs(session, { isUntimedSession }) {
|
||||
if (isUntimedSession(session)) {
|
||||
return null;
|
||||
@@ -124,8 +152,11 @@ export function getSessionTiming(session, nowTs = Date.now(), { getSessionTarget
|
||||
const followUpMs = Math.max(0, Number(session?.followUpSec || 0) || 0) * 1000;
|
||||
const followUpStartedAt = Number(session?.followUpStartedAt || 0) || 0;
|
||||
const followUpPausedMs = Math.max(0, Number(session?.followUpPausedMs || 0) || 0);
|
||||
const followUpActive = Boolean(followUpStartedAt && followUpMs > 0);
|
||||
const followUpRemainingMs = followUpActive ? Math.max(0, followUpMs - Math.max(0, clockNow - followUpStartedAt - followUpPausedMs)) : 0;
|
||||
const finishWaitUntil = session?.status === "running" ? Number(session?.finishWaitUntil || 0) || 0 : 0;
|
||||
const followUpActive = Boolean(followUpStartedAt && (followUpMs > 0 || finishWaitUntil));
|
||||
const followUpRemainingMs = !followUpActive ? 0
|
||||
: finishWaitUntil ? Math.max(0, finishWaitUntil - clockNow)
|
||||
: Math.max(0, followUpMs - Math.max(0, clockNow - followUpStartedAt - followUpPausedMs));
|
||||
return {
|
||||
targetMs,
|
||||
elapsedMs,
|
||||
|
||||
Reference in new issue
Block a user