lägg till jämna varv-övning + v1.2.0

Ny guidad träningsövning i Open Practice: sätt måltid, tolerans
och antal varv, se aktuell serie och dagens bästa live på
Training-sidan. Ett missat varv startar en ny serie utan att
radera bästa resultatet.

Hittade och fixade två buggar under vägen:
- syncTrainingLedger byggde om training-state vid varje sparning
  utan att föra vidare det nya evenLaps-fältet, så sparade
  konfigurationer försvann direkt
- Training-sidan kraschade för alla förare med färre än 3 varv i
  varje stint (t.ex. de första varven i ett pass) eftersom en
  dedupe-funktion läste en egenskap på ett null-värde

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
larssandandClaude Sonnet 5 committed 2026-09-09 08:51:50 +02:00
1 parent d18cd7fb5e
commit 9122e91f2e
9 files changed
+341 -18

No files matched your search

+95 -2
View File
@@ -111,7 +111,27 @@ export function normalizeTrainingState(training, { uid }) {
.sort((left, right) => left.timestamp - right.timestamp)
: [];
return { goals, ledger, shares, markers, clubGoal };
const seenEvenLapsConfigs = new Set();
const evenLaps = Array.isArray(source.evenLaps)
? source.evenLaps
.map((entry) => ({
id: String(entry?.id || uid("even_laps")),
driverId: String(entry?.driverId || ""),
classId: String(entry?.classId || ""),
targetMs: Math.max(0, Math.round(Number(entry?.targetMs || 0) || 0)),
toleranceMs: Math.max(0, Math.round(Number(entry?.toleranceMs || 0) || 0)),
lapCount: Math.max(1, Math.round(Number(entry?.lapCount || 0) || 5)),
updatedAt: String(entry?.updatedAt || new Date().toISOString()),
}))
.filter((entry) => {
const key = `${entry.driverId}:${entry.classId}`;
if (!entry.driverId || !entry.classId || entry.targetMs <= 0 || seenEvenLapsConfigs.has(key)) return false;
seenEvenLapsConfigs.add(key);
return true;
})
: [];
return { goals, ledger, shares, markers, clubGoal, evenLaps };
}
function getPassingSourceKey(sessionId, passing, index) {
@@ -161,6 +181,7 @@ export function syncTrainingLedger(training, state, { uid }) {
shares: normalized.shares,
markers: normalized.markers,
clubGoal: normalized.clubGoal,
evenLaps: normalized.evenLaps,
}, { uid });
}
@@ -694,7 +715,7 @@ export function buildDriverTimingChannelStats(state, driverId, classId = "") {
};
}
export function buildDriverActivePracticeStats(state, driverId, nowTs = Date.now(), classId = "") {
function getActivePracticeLaps(state, driverId, classId) {
const session = (Array.isArray(state?.sessions) ? state.sessions : [])
.find((item) => String(item?.id || "") === String(state?.activeSessionId || ""));
const practiceTypes = new Set(["open_practice", "free_practice", "practice"]);
@@ -719,6 +740,13 @@ export function buildDriverActivePracticeStats(state, driverId, nowTs = Date.now
stintBoundary: Boolean(passing.stintBoundary || passing.validationWarning === "above_max_stint"),
}))
.sort((left, right) => left.timestamp - right.timestamp);
return { session, startedAt, laps };
}
export function buildDriverActivePracticeStats(state, driverId, nowTs = Date.now(), classId = "") {
const active = getActivePracticeLaps(state, driverId, classId);
if (!active) return null;
const { session, startedAt, laps } = active;
const paceLapTimes = laps.filter((lap) => !lap.excludedFromPace).map((lap) => lap.lapMs);
const bestLapMs = paceLapTimes.length ? Math.min(...paceLapTimes) : 0;
const controlZoneMaxMs = bestLapMs ? Math.round(bestLapMs * 1.08) : 0;
@@ -739,6 +767,71 @@ export function buildDriverActivePracticeStats(state, driverId, nowTs = Date.now
};
}
// "Jämna varv" (even laps): a driver-configured target lap time and tolerance, run live
// inside an already-active Open Practice session. Tolerance is +/- around the target lap
// time (not the spread between the streak's fastest and slowest lap) - decided because
// it's simpler to understand and to show live, and matches how a beginner already thinks
// about "hit the target". A lap outside tolerance, or one excluded from pace (pit/reset),
// ends the current streak but never erases the best streak already reached today.
export function buildEvenLapsProgress(state, driverId, classId, config, nowTs = Date.now()) {
const targetMs = Math.round(Number(config?.targetMs || 0));
const toleranceMs = Math.round(Number(config?.toleranceMs || 0));
const lapCount = Math.max(1, Math.round(Number(config?.lapCount || 0) || 0));
if (!(targetMs > 0) || !(toleranceMs >= 0)) return null;
const withinTolerance = (lapMs) => Math.abs(lapMs - targetMs) <= toleranceMs;
const longestStreak = (lapTimes) => {
let longest = 0;
let current = 0;
for (const lap of lapTimes) {
if (!lap.excludedFromPace && withinTolerance(lap.lapMs)) {
current += 1;
longest = Math.max(longest, current);
} else {
current = 0;
}
}
return longest;
};
const active = getActivePracticeLaps(state, driverId, classId);
const liveLaps = active?.laps || [];
let currentStreak = 0;
for (let index = liveLaps.length - 1; index >= 0; index -= 1) {
if (!liveLaps[index].excludedFromPace && withinTolerance(liveLaps[index].lapMs)) currentStreak += 1;
else break;
}
const dayStart = new Date(nowTs);
dayStart.setHours(0, 0, 0, 0);
const profileReferences = getTrainingDriverIds(state, driverId, classId);
const ledgerToday = (Array.isArray(state?.training?.ledger) ? state.training.ledger : [])
.filter((entry) => profileReferences.has(String(entry?.driverId || "")) && Number(entry?.timestamp || 0) >= dayStart.getTime())
.map((entry) => ({ timestamp: Number(entry.timestamp || 0), lapMs: Number(entry.lapMs || 0), excludedFromPace: Boolean(entry.excludedFromPace) }));
const seen = new Set();
const todayLaps = [...ledgerToday, ...liveLaps]
.sort((left, right) => left.timestamp - right.timestamp)
.filter((lap) => {
const key = `${lap.timestamp}:${lap.lapMs}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
const bestStreakToday = Math.max(longestStreak(todayLaps), currentStreak);
const lastLap = liveLaps.at(-1) || null;
return {
active: Boolean(active),
targetMs,
toleranceMs,
lapCount,
currentStreak,
bestStreakToday,
lastLapMs: lastLap?.lapMs ?? null,
lastLapWithinTolerance: lastLap ? !lastLap.excludedFromPace && withinTolerance(lastLap.lapMs) : null,
};
}
export function buildTrainingRecommendation(stats) {
if (!stats || stats.totalLaps < 10) {
return {