Add secure public driver training profiles
This commit is contained in:
1 parent
c2ed00861a
commit
4a74785791
12 files changed
+1360
-12
No files matched your search
@@ -0,0 +1,348 @@
|
||||
const root = document.getElementById("publicTrainingRoot");
|
||||
const shareToken = decodeURIComponent(window.location.pathname.split("/").filter(Boolean).at(-1) || "");
|
||||
const requestedLanguage = new URLSearchParams(window.location.search).get("lang");
|
||||
const language = requestedLanguage === "en" || requestedLanguage === "sv"
|
||||
? requestedLanguage
|
||||
: String(navigator.language || "sv").toLowerCase().startsWith("sv") ? "sv" : "en";
|
||||
const TIMER_DURATION_MS = 20 * 60 * 1000;
|
||||
const TIMER_PHASE_MS = 10 * 60 * 1000;
|
||||
const TIMER_STORAGE_KEY = `rc-training-timer:${shareToken}`;
|
||||
|
||||
const messages = {
|
||||
sv: {
|
||||
loading: "Laddar träningsprofil...",
|
||||
loadError: "Kunde inte läsa träningsprofilen. Länken kan vara avstängd eller ersatt.",
|
||||
development: "Förarutveckling",
|
||||
rank: "Klubbrank {rank} av {count}",
|
||||
laps: "Totala varv",
|
||||
days: "Träningsdagar",
|
||||
best: "Bästa varv",
|
||||
consistency: "Jämnhet senaste 30",
|
||||
nextLevel: "Nästa nivå",
|
||||
reachLaps: "Nå {laps} varv",
|
||||
lapsRemaining: "{laps} varv kvar",
|
||||
plan: "Dagens 20-minuterspass",
|
||||
baselineTitle: "Bygg en baslinje",
|
||||
baselineBody: "Kör lugnt och jämnt tills du har minst 10 rena varv. Upprepa samma linje och bromspunkt.",
|
||||
consistencyTitle: "Höj din lägstanivå",
|
||||
consistencyBody: "Kör 10 minuter nära max, sedan 10 minuter på 80-90 procent med fokus på rena, repeterbara varv.",
|
||||
progressionTitle: "Balansera fart och kontroll",
|
||||
progressionBody: "Kör 10 minuter med maxfokus och avsluta med 10 kontrollerade minuter utan misstag.",
|
||||
target: "Kontrollmål {lap}",
|
||||
ready: "Redo att börja",
|
||||
push: "Maxfokus: hitta gränsen",
|
||||
control: "80-90%: höj lägstanivån",
|
||||
finished: "Passet är klart",
|
||||
start: "Starta pass",
|
||||
pause: "Pausa",
|
||||
resume: "Fortsätt",
|
||||
running: "Pågår",
|
||||
reset: "Nollställ",
|
||||
goals: "Mål och belöningar",
|
||||
noGoals: "Inga personliga mål har lagts till ännu.",
|
||||
goalReached: "Målet är nått",
|
||||
rewardDelivered: "Belöning utdelad",
|
||||
reward: "Belöning",
|
||||
history: "Senaste träningsdagar",
|
||||
date: "Datum",
|
||||
dayLaps: "Varv",
|
||||
average: "Snitt",
|
||||
updated: "Uppdaterad {time}",
|
||||
switchCue: "Byt till kontrollerad körning",
|
||||
finishCue: "Träningspasset är klart",
|
||||
},
|
||||
en: {
|
||||
loading: "Loading training profile...",
|
||||
loadError: "The training profile could not be loaded. The link may be disabled or replaced.",
|
||||
development: "Driver development",
|
||||
rank: "Club rank {rank} of {count}",
|
||||
laps: "Total laps",
|
||||
days: "Practice days",
|
||||
best: "Best lap",
|
||||
consistency: "Latest 30 consistency",
|
||||
nextLevel: "Next level",
|
||||
reachLaps: "Reach {laps} laps",
|
||||
lapsRemaining: "{laps} laps remaining",
|
||||
plan: "Today's 20-minute session",
|
||||
baselineTitle: "Build a baseline",
|
||||
baselineBody: "Drive calmly and consistently until at least 10 clean laps are recorded. Repeat the same line and braking point.",
|
||||
consistencyTitle: "Raise your minimum level",
|
||||
consistencyBody: "Run 10 minutes near maximum pace, then 10 minutes at 80-90 percent with clean, repeatable laps.",
|
||||
progressionTitle: "Balance pace and control",
|
||||
progressionBody: "Run 10 minutes at maximum focus and finish with 10 controlled minutes without mistakes.",
|
||||
target: "Control target {lap}",
|
||||
ready: "Ready to start",
|
||||
push: "Maximum focus: find the limit",
|
||||
control: "80-90%: raise the floor",
|
||||
finished: "Session completed",
|
||||
start: "Start session",
|
||||
pause: "Pause",
|
||||
resume: "Resume",
|
||||
running: "Running",
|
||||
reset: "Reset",
|
||||
goals: "Goals and rewards",
|
||||
noGoals: "No personal goals have been added yet.",
|
||||
goalReached: "Goal reached",
|
||||
rewardDelivered: "Reward delivered",
|
||||
reward: "Reward",
|
||||
history: "Latest practice days",
|
||||
date: "Date",
|
||||
dayLaps: "Laps",
|
||||
average: "Average",
|
||||
updated: "Updated {time}",
|
||||
switchCue: "Switch to controlled driving",
|
||||
finishCue: "The training session is complete",
|
||||
},
|
||||
};
|
||||
|
||||
let profileData = null;
|
||||
let timerHandle = null;
|
||||
let lastTimerPhase = "";
|
||||
|
||||
function t(key, vars = {}) {
|
||||
const template = messages[language]?.[key] || messages.en[key] || key;
|
||||
return String(template).replace(/\{(\w+)\}/g, (_, name) => String(vars[name] ?? ""));
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? "")
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function formatLap(ms) {
|
||||
const value = Math.max(0, Number(ms || 0));
|
||||
if (!value) return "-";
|
||||
const minutes = Math.floor(value / 60000);
|
||||
const seconds = Math.floor((value % 60000) / 1000);
|
||||
const millis = Math.floor(value % 1000);
|
||||
return `${minutes}:${String(seconds).padStart(2, "0")}.${String(millis).padStart(3, "0")}`;
|
||||
}
|
||||
|
||||
function formatTimer(ms) {
|
||||
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
||||
return `${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function recommendationCopy(recommendation) {
|
||||
const level = ["baseline", "consistency", "progression"].includes(recommendation?.level) ? recommendation.level : "baseline";
|
||||
return {
|
||||
title: t(`${level}Title`),
|
||||
body: t(`${level}Body`),
|
||||
};
|
||||
}
|
||||
|
||||
function renderProfile(data) {
|
||||
profileData = data;
|
||||
const { profile, branding, stats, nextMilestone, recommendation, goals } = data;
|
||||
const recommendationText = recommendationCopy(recommendation);
|
||||
const rank = profile.clubRank && profile.rankedDrivers ? t("rank", { rank: profile.clubRank, count: profile.rankedDrivers }) : "";
|
||||
const logo = /^data:image\/(?:png|jpeg|webp);base64,/i.test(branding.logoDataUrl || "")
|
||||
? `<img src="${escapeHtml(branding.logoDataUrl)}" alt="" />`
|
||||
: `<div class="profile-brand-mark">RC</div>`;
|
||||
const goalMarkup = goals.length
|
||||
? goals.map((goal) => `
|
||||
<article class="profile-goal ${goal.reached ? "reached" : ""}">
|
||||
<div class="profile-goal-row">
|
||||
<strong>${escapeHtml(goal.title || t("reachLaps", { laps: goal.targetLaps }))}</strong>
|
||||
<span>${goal.currentLaps} / ${goal.targetLaps}</span>
|
||||
</div>
|
||||
<div class="profile-progress"><span style="width:${Number(goal.percent || 0).toFixed(2)}%"></span></div>
|
||||
${goal.reward ? `<p><span class="profile-mini-label">${escapeHtml(t("reward"))}</span><br />${escapeHtml(goal.reward)}</p>` : ""}
|
||||
${goal.claimed ? `<span class="profile-mini-label">${escapeHtml(t("rewardDelivered"))}</span>` : goal.reached ? `<span class="profile-mini-label">${escapeHtml(t("goalReached"))}</span>` : ""}
|
||||
</article>
|
||||
`).join("")
|
||||
: `<p class="profile-empty">${escapeHtml(t("noGoals"))}</p>`;
|
||||
const historyRows = stats.dailySummaries.length
|
||||
? stats.dailySummaries.slice(0, 12).map((day) => `
|
||||
<tr>
|
||||
<td>${escapeHtml(new Date(day.latestTimestamp).toLocaleDateString(language))}</td>
|
||||
<td>${day.laps}</td>
|
||||
<td>${formatLap(day.bestLapMs)}</td>
|
||||
<td>${formatLap(day.averageLapMs)}</td>
|
||||
</tr>
|
||||
`).join("")
|
||||
: `<tr><td colspan="4">-</td></tr>`;
|
||||
|
||||
document.documentElement.lang = language;
|
||||
document.title = `${profile.name} - ${branding.clubName}`;
|
||||
root.innerHTML = `
|
||||
<header class="profile-header">
|
||||
<div class="profile-brand">
|
||||
${logo}
|
||||
<div><strong>${escapeHtml(branding.clubName)}</strong><span>${escapeHtml(branding.clubTagline)}</span></div>
|
||||
</div>
|
||||
<div class="profile-updated">${escapeHtml(t("updated", { time: new Date(data.updatedAt || Date.now()).toLocaleString(language) }))}</div>
|
||||
</header>
|
||||
|
||||
<section class="profile-hero">
|
||||
<span class="profile-eyebrow">${escapeHtml(t("development"))}</span>
|
||||
<h1>${escapeHtml(profile.name)}</h1>
|
||||
<div class="profile-meta">
|
||||
${profile.className ? `<span class="profile-pill">${escapeHtml(profile.className)}</span>` : ""}
|
||||
${profile.brand ? `<span class="profile-pill">${escapeHtml(profile.brand)}</span>` : ""}
|
||||
${rank ? `<span class="profile-pill">${escapeHtml(rank)}</span>` : ""}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="profile-stat-grid">
|
||||
${renderStat(t("laps"), stats.totalLaps)}
|
||||
${renderStat(t("days"), stats.trainingDays)}
|
||||
${renderStat(t("best"), formatLap(stats.bestLapMs))}
|
||||
${renderStat(t("consistency"), stats.recentLapCount ? `${Number(stats.consistencySpreadPct).toFixed(1)}%` : "-")}
|
||||
</section>
|
||||
|
||||
<div class="profile-grid">
|
||||
<section class="profile-card">
|
||||
<div class="profile-card-head"><h2>${escapeHtml(t("nextLevel"))}</h2></div>
|
||||
<div class="profile-card-body">
|
||||
<div class="profile-level-row">
|
||||
<div><span class="profile-mini-label">${escapeHtml(t("lapsRemaining", { laps: nextMilestone.remainingLaps }))}</span><h3>${escapeHtml(t("reachLaps", { laps: nextMilestone.targetLaps }))}</h3></div>
|
||||
<strong>${nextMilestone.currentLaps} / ${nextMilestone.targetLaps}</strong>
|
||||
</div>
|
||||
<div class="profile-progress"><span style="width:${Number(nextMilestone.percent || 0).toFixed(2)}%"></span></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="profile-card">
|
||||
<div class="profile-card-head"><h2>${escapeHtml(t("plan"))}</h2></div>
|
||||
<div class="profile-card-body">
|
||||
<span class="profile-mini-label">${recommendation.targetLapMs ? escapeHtml(t("target", { lap: formatLap(recommendation.targetLapMs) })) : ""}</span>
|
||||
<h3>${escapeHtml(recommendationText.title)}</h3>
|
||||
<p class="profile-plan-copy">${escapeHtml(recommendationText.body)}</p>
|
||||
<div id="profileTimer" class="profile-timer">20:00</div>
|
||||
<div id="profileTimerPhase" class="profile-timer-phase">${escapeHtml(t("ready"))}</div>
|
||||
<div class="profile-actions">
|
||||
<button id="profileTimerStart" class="profile-button profile-button-primary" type="button">${escapeHtml(t("start"))}</button>
|
||||
<button id="profileTimerPause" class="profile-button" type="button">${escapeHtml(t("pause"))}</button>
|
||||
<button id="profileTimerReset" class="profile-button" type="button">${escapeHtml(t("reset"))}</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="profile-card" style="margin-top:14px">
|
||||
<div class="profile-card-head"><h2>${escapeHtml(t("goals"))}</h2></div>
|
||||
<div class="profile-card-body profile-goals">${goalMarkup}</div>
|
||||
</section>
|
||||
|
||||
<section class="profile-card" style="margin-top:14px">
|
||||
<div class="profile-card-head"><h2>${escapeHtml(t("history"))}</h2></div>
|
||||
<div class="profile-history-wrap">
|
||||
<table class="profile-history">
|
||||
<thead><tr><th>${escapeHtml(t("date"))}</th><th>${escapeHtml(t("dayLaps"))}</th><th>${escapeHtml(t("best"))}</th><th>${escapeHtml(t("average"))}</th></tr></thead>
|
||||
<tbody>${historyRows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
bindTimerControls();
|
||||
updateTimerDisplay();
|
||||
}
|
||||
|
||||
function renderStat(label, value) {
|
||||
return `<article class="profile-card profile-stat"><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong></article>`;
|
||||
}
|
||||
|
||||
function readTimerState() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(TIMER_STORAGE_KEY) || "null");
|
||||
return parsed && typeof parsed === "object" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeTimerState(value) {
|
||||
if (value) localStorage.setItem(TIMER_STORAGE_KEY, JSON.stringify(value));
|
||||
else localStorage.removeItem(TIMER_STORAGE_KEY);
|
||||
}
|
||||
|
||||
function getTimerElapsed(state, now = Date.now()) {
|
||||
if (!state?.startedAt) return 0;
|
||||
const endpoint = state.pausedAt || now;
|
||||
return Math.max(0, endpoint - state.startedAt - Number(state.pausedTotalMs || 0));
|
||||
}
|
||||
|
||||
function bindTimerControls() {
|
||||
document.getElementById("profileTimerStart")?.addEventListener("click", () => {
|
||||
const current = readTimerState();
|
||||
if (current?.pausedAt) {
|
||||
current.pausedTotalMs = Number(current.pausedTotalMs || 0) + Date.now() - current.pausedAt;
|
||||
current.pausedAt = 0;
|
||||
writeTimerState(current);
|
||||
} else if (!current || getTimerElapsed(current) >= TIMER_DURATION_MS) {
|
||||
writeTimerState({ startedAt: Date.now(), pausedAt: 0, pausedTotalMs: 0 });
|
||||
lastTimerPhase = "push";
|
||||
}
|
||||
startTimerLoop();
|
||||
updateTimerDisplay();
|
||||
});
|
||||
document.getElementById("profileTimerPause")?.addEventListener("click", () => {
|
||||
const current = readTimerState();
|
||||
if (current?.startedAt && !current.pausedAt && getTimerElapsed(current) < TIMER_DURATION_MS) {
|
||||
current.pausedAt = Date.now();
|
||||
writeTimerState(current);
|
||||
}
|
||||
updateTimerDisplay();
|
||||
});
|
||||
document.getElementById("profileTimerReset")?.addEventListener("click", () => {
|
||||
writeTimerState(null);
|
||||
lastTimerPhase = "";
|
||||
updateTimerDisplay();
|
||||
});
|
||||
startTimerLoop();
|
||||
}
|
||||
|
||||
function startTimerLoop() {
|
||||
if (timerHandle) clearInterval(timerHandle);
|
||||
timerHandle = setInterval(updateTimerDisplay, 250);
|
||||
}
|
||||
|
||||
function updateTimerDisplay() {
|
||||
const timer = document.getElementById("profileTimer");
|
||||
const phase = document.getElementById("profileTimerPhase");
|
||||
const startButton = document.getElementById("profileTimerStart");
|
||||
const pauseButton = document.getElementById("profileTimerPause");
|
||||
if (!timer || !phase || !startButton || !pauseButton) return;
|
||||
const state = readTimerState();
|
||||
const elapsed = getTimerElapsed(state);
|
||||
const remaining = Math.max(0, TIMER_DURATION_MS - elapsed);
|
||||
const phaseName = !state?.startedAt ? "ready" : remaining <= 0 ? "finished" : elapsed < TIMER_PHASE_MS ? "push" : "control";
|
||||
timer.textContent = formatTimer(remaining || (phaseName === "ready" ? TIMER_DURATION_MS : 0));
|
||||
phase.textContent = t(phaseName);
|
||||
startButton.textContent = state?.pausedAt ? t("resume") : !state?.startedAt || remaining <= 0 ? t("start") : t("running");
|
||||
startButton.disabled = Boolean(state?.startedAt && !state.pausedAt && remaining > 0);
|
||||
pauseButton.disabled = !state?.startedAt || Boolean(state.pausedAt) || remaining <= 0;
|
||||
if (state?.startedAt && !state.pausedAt && phaseName !== lastTimerPhase) {
|
||||
if (lastTimerPhase === "push" && phaseName === "control") speak(t("switchCue"));
|
||||
if (phaseName === "finished") speak(t("finishCue"));
|
||||
lastTimerPhase = phaseName;
|
||||
}
|
||||
}
|
||||
|
||||
function speak(text) {
|
||||
if (!("speechSynthesis" in window)) return;
|
||||
window.speechSynthesis.cancel();
|
||||
const utterance = new SpeechSynthesisUtterance(text);
|
||||
utterance.lang = language === "sv" ? "sv-SE" : "en-GB";
|
||||
window.speechSynthesis.speak(utterance);
|
||||
}
|
||||
|
||||
async function loadProfile() {
|
||||
try {
|
||||
const response = await fetch(`/public-training/api/${encodeURIComponent(shareToken)}`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
renderProfile(await response.json());
|
||||
} catch {
|
||||
root.innerHTML = `<section class="public-training-error"><div class="profile-brand-mark">RC</div><h1>${escapeHtml(t("loadError"))}</h1></section>`;
|
||||
}
|
||||
}
|
||||
|
||||
loadProfile();
|
||||
setInterval(() => {
|
||||
if (!document.hidden) loadProfile();
|
||||
}, 30000);
|
||||
Reference in new issue
Block a user