'use strict'; /* ============================================================ openGym — personal gym & body-weight tracker Static SPA, localStorage, exercise data from data.js (EXDB) ============================================================ */ /* ---------- data index ---------- */ const EXIDX = {}; EXDB.forEach(e => EXIDX[e.id] = e); const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort(); /* ---------- state ---------- */ const KEY = 'gym_state_v1'; const DEF = { unit: 'kg', restSec: 90, sound: true, theme: 'dark', accent: 'lime', // appearance — synced with the profile targetW: null, // goal body weight (drawn through the charts) bodyweight: [], // {d:'YYYY-MM-DD', w:Number, t:ms} routines: [], // {id, name, emoji, ex:[{id, sets, reps, weight}]} week: {}, // weekday(0-6, JS getDay) -> routineId dayPlan: {}, // 'YYYY-MM-DD' -> routineId | 'rest' (overrides week plan) exWeights: {}, // exId -> {w, d}: confirmed working weight, default next time workouts: [], // finished sessions, chronological active: null // in-progress session }; let S = loadState(); function loadState() { try { const raw = localStorage.getItem(KEY); if (raw) return Object.assign(JSON.parse(JSON.stringify(DEF)), JSON.parse(raw)); } catch (e) { console.warn('state load failed', e); } return JSON.parse(JSON.stringify(DEF)); } function save(push) { S._ts = Date.now(); localStorage.setItem(KEY, JSON.stringify(S)); if (push !== false) schedulePush(); } /* ---------- utils ---------- */ const $ = sel => document.querySelector(sel); const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7); const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const todayISO = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0'); }; const DAYN = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; const DAYS = ['Su','Mo','Tu','We','Th','Fr','Sa']; function fmtDate(iso, long) { const d = new Date(iso + 'T12:00:00'); return d.toLocaleDateString('en-GB', long ? {weekday:'short', day:'numeric', month:'short'} : {day:'numeric', month:'short'}); } function fmtDur(ms) { const m = Math.floor(ms / 60000); return m >= 60 ? Math.floor(m/60) + 'h ' + (m%60) + 'm' : m + ' min'; } function fmtNum(n) { return (Math.round(n*10)/10).toLocaleString('en-CH'); } function fmtVol(v) { return v >= 10000 ? fmtNum(v/1000) + 't' : fmtNum(v) + ' ' + S.unit; } function toast(msg) { const t = $('#toast'); t.textContent = msg; t.classList.add('show'); clearTimeout(t._tm); t._tm = setTimeout(() => t.classList.remove('show'), 2200); } function vibrate(p) { try { navigator.vibrate && navigator.vibrate(p); } catch(e){} } let audioCtx = null; function beep(freq, dur, when) { if (!S.sound) return; try { audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)(); const o = audioCtx.createOscillator(), g = audioCtx.createGain(); o.connect(g); g.connect(audioCtx.destination); o.frequency.value = freq || 880; o.type = 'sine'; const t0 = audioCtx.currentTime + (when || 0); g.gain.setValueAtTime(0.001, t0); g.gain.exponentialRampToValueAtTime(0.35, t0 + 0.02); g.gain.exponentialRampToValueAtTime(0.001, t0 + (dur || 0.18)); o.start(t0); o.stop(t0 + (dur || 0.18) + 0.05); } catch(e){} } /* ============================================================ AUTH (Apple passkeys / WebAuthn) + PER-USER SYNC ============================================================ */ let USER = null; const isGuest = () => localStorage.getItem('gym_guest') === '1'; const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials); /* platform-aware wording — same WebAuthn underneath, different branding on top */ const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent); const IS_ANDROID = /Android/.test(navigator.userAgent); const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint or face unlock' : 'your fingerprint, face or PIN'; const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager'; async function api(path, opts) { const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts)); const data = await r.json().catch(() => ({})); if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e; } return data; } const bufToB64u = buf => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); const b64uToBuf = s => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)).buffer; function toCreationOptions(o) { o.challenge = b64uToBuf(o.challenge); o.user.id = b64uToBuf(o.user.id); (o.excludeCredentials || []).forEach(c => c.id = b64uToBuf(c.id)); return o; } function toRequestOptions(o) { o.challenge = b64uToBuf(o.challenge); (o.allowCredentials || []).forEach(c => c.id = b64uToBuf(c.id)); return o; } function credToJSON(cred) { const r = cred.response; const out = { id: cred.id, rawId: bufToB64u(cred.rawId), type: cred.type, clientExtensionResults: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}, authenticatorAttachment: cred.authenticatorAttachment || null, response: { clientDataJSON: bufToB64u(r.clientDataJSON) } }; if (r.attestationObject) { out.response.attestationObject = bufToB64u(r.attestationObject); out.response.transports = r.getTransports ? r.getTransports() : ['internal']; } if (r.authenticatorData) { out.response.authenticatorData = bufToB64u(r.authenticatorData); out.response.signature = bufToB64u(r.signature); out.response.userHandle = r.userHandle ? bufToB64u(r.userHandle) : null; } return out; } async function passkeyRegister(name) { const { cid, options } = await api('/api/register/options', { method: 'POST', body: JSON.stringify({ name }) }); const cred = await navigator.credentials.create({ publicKey: toCreationOptions(options) }); const res = await api('/api/register/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) }); return res.user; } async function passkeyLogin() { const { cid, options } = await api('/api/login/options', { method: 'POST', body: '{}' }); const cred = await navigator.credentials.get({ publicKey: toRequestOptions(options) }); const res = await api('/api/login/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) }); return res.user; } function setUser(u) { USER = u; if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest'); } else localStorage.removeItem('gym_user'); } /* --- state sync (server is source of truth per user) --- */ let pushTm = null; function schedulePush() { if (!USER) return; clearTimeout(pushTm); pushTm = setTimeout(pushState, 1500); } async function pushState() { if (!USER) return; clearTimeout(pushTm); try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: S }) }); localStorage.removeItem('gym_dirty'); } catch (e) { localStorage.setItem('gym_dirty', '1'); } } function hasData(st) { return !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length); } async function pullState() { try { const { state } = await api('/api/data'); const dirty = localStorage.getItem('gym_dirty') === '1'; if (state && (!hasData(S) || ((state._ts || 0) >= (S._ts || 0) && !dirty))) { const active = S.active; // in-progress workout stays device-local S = Object.assign(JSON.parse(JSON.stringify(DEF)), state); if (active) S.active = active; save(false); } else if (hasData(S)) await pushState(); // adopt this device's data into the account } catch (e) { /* offline — keep local cache */ } } window.addEventListener('online', () => { if (localStorage.getItem('gym_dirty') === '1') pushState(); }); /* ---------- workout history helpers ---------- */ function lastEntryFor(exId) { for (let i = S.workouts.length - 1; i >= 0; i--) { const en = S.workouts[i].entries.find(e => e.id === exId); if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done) }; } return null; } function bestWeightFor(exId) { let best = 0; S.workouts.forEach(w => w.entries.forEach(e => { if (e.id === exId) { e.sets.forEach(s => { if (s.done && s.w > best) best = s.w; }); if (e.topW && e.topW > best) best = e.topW; } })); return best; } /* effective routine for a date: per-date override beats the weekly plan */ function effectiveRoutineId(iso) { const ov = S.dayPlan[iso]; if (ov === 'rest') return null; if (ov && S.routines.some(r => r.id === ov)) return ov; const wd = new Date(iso + 'T12:00:00').getDay(); return S.week[wd] || null; } function effectiveRoutine(iso) { const id = effectiveRoutineId(iso); return id ? S.routines.find(r => r.id === id) || null : null; } /* prefill sets: confirmed working weight > last time's sets > plan target */ function buildSets(cfg) { const last = lastEntryFor(cfg.id); const conf = S.exWeights[cfg.id]; const sets = []; for (let i = 0; i < cfg.sets; i++) { const prevSet = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null; const w = conf && conf.w > 0 ? conf.w : (prevSet ? prevSet.w : cfg.weight); sets.push({ w, r: prevSet ? prevSet.r : cfg.reps, done: false }); } return sets; } function workoutVolume(w) { let v = 0; w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0); })); return v; } function setsDone(w) { let n = 0; w.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++; })); return n; } function lastBW() { return S.bodyweight.length ? S.bodyweight[S.bodyweight.length-1] : null; } function weekKey(d) { // ISO week key const dt = new Date(d + 'T12:00:00'); const day = (dt.getDay() + 6) % 7; dt.setDate(dt.getDate() - day + 3); const jan4 = new Date(dt.getFullYear(), 0, 4); const week = 1 + Math.round(((dt - jan4) / 86400000 - 3 + ((jan4.getDay() + 6) % 7)) / 7); return dt.getFullYear() + '-' + week; } function streakWeeks() { if (!S.workouts.length) return 0; const weeks = new Set(S.workouts.map(w => weekKey(w.d))); let streak = 0; const cur = new Date(); for (let i = 0; i < 520; i++) { const iso = cur.getFullYear() + '-' + String(cur.getMonth()+1).padStart(2,'0') + '-' + String(cur.getDate()).padStart(2,'0'); const wk = weekKey(iso); if (weeks.has(wk)) streak++; else if (i > 0) break; // current week may still be empty cur.setDate(cur.getDate() - 7); } return streak; } /* ---------- media ---------- */ const imgEl = (ex, cls) => ``; /* big autoplay animation for single-exercise views; tap pauses (swaps to still) */ const mediaEl = (ex, id) => `
${esc(ex.n)}⏸ tap to pause
`; function bindMediaToggle(media, ex) { if (!media) return; media.onclick = () => { const img = media.querySelector('img'); const hint = media.querySelector('.gifhint'); if (img.src.includes('/gif/')) { img.src = 'img/' + ex.img; hint.textContent = '▶ tap to play'; } else { img.src = 'gif/' + ex.gif; hint.textContent = '⏸ tap to pause'; } }; } /* ---------- body scroll lock (iOS-safe) while a modal is open ---------- */ function currentScrollY() { return 'slock' in document.body.dataset ? +document.body.dataset.slock : (window.scrollY || 0); } function lockBodyScroll() { if ('slock' in document.body.dataset) return; const y = window.scrollY || 0; document.body.dataset.slock = y; const st = document.body.style; st.position = 'fixed'; st.top = -y + 'px'; st.left = '0'; st.right = '0'; st.width = '100%'; } function unlockBodyScroll() { if (!('slock' in document.body.dataset)) return; const y = +document.body.dataset.slock; delete document.body.dataset.slock; const st = document.body.style; st.position = st.top = st.left = st.right = st.width = ''; window.scrollTo(0, y); } /* ---------- modal system ---------- */ const modalRoot = $('#modal-root'); let modalStack = []; function openModal(html, kind) { const wrap = document.createElement('div'); wrap.innerHTML = `
${kind === 'center' ? '' : '
'}${html}
`; modalRoot.appendChild(wrap); modalRoot.classList.add('open'); lockBodyScroll(); const close = () => { wrap.remove(); modalStack = modalStack.filter(m => m !== api); if (!modalRoot.children.length) { modalRoot.classList.remove('open'); unlockBodyScroll(); } }; wrap.querySelector('.mback').addEventListener('click', () => { if (!wrap.dataset.lock) close(); }); const api = { el: wrap, close, lock: v => { wrap.dataset.lock = v ? '1' : ''; } }; // swipe-down to dismiss (bottom sheets only, when scrolled to top) const sh = wrap.querySelector('.sheet'); if (sh) { let startY = null, delta = 0; sh.addEventListener('touchstart', e => { startY = sh.scrollTop <= 0 ? e.touches[0].clientY : null; delta = 0; }, { passive: true }); sh.addEventListener('touchmove', e => { if (startY === null) return; delta = e.touches[0].clientY - startY; if (delta > 0 && sh.scrollTop <= 0) { e.preventDefault(); // only the sheet moves, never the page behind sh.style.transition = 'none'; sh.style.transform = `translateY(${delta}px)`; } else delta = 0; }, { passive: false }); sh.addEventListener('touchend', () => { if (startY === null) return; sh.style.transition = 'transform .2s'; if (delta > 90 && !wrap.dataset.lock) { sh.style.transform = 'translateY(110%)'; setTimeout(close, 180); } else sh.style.transform = ''; startY = null; }); } modalStack.push(api); return api; } function closeAllModals() { [...modalStack].forEach(m => m.close()); } /* ============================================================ REST TIMER ============================================================ */ const timerRoot = $('#timer-root'); let timer = null; function startRest(sec) { stopRest(); timer = { total: sec, left: sec, int: setInterval(tickRest, 1000) }; renderTimer(); } function tickRest() { if (!timer) return; timer.left--; if (timer.left <= 0) { beep(880, .15); beep(880, .15, .25); beep(1320, .4, .5); vibrate([200, 100, 200]); toast('Rest over — next set! 💪'); stopRest(); return; } if (timer.left <= 3) beep(660, .1); renderTimer(); } function stopRest() { if (timer) clearInterval(timer.int); timer = null; timerRoot.innerHTML = ''; } function renderTimer() { if (!timer) { timerRoot.innerHTML = ''; return; } const pct = (timer.left / timer.total) * 100; const m = Math.floor(timer.left / 60), s = String(timer.left % 60).padStart(2, '0'); timerRoot.innerHTML = `
${m}:${s}
`; $('#tm-add').onclick = () => { timer.left += 15; timer.total += 15; renderTimer(); }; $('#tm-skip').onclick = () => stopRest(); } /* ============================================================ CHARTS (hand-rolled SVG) ============================================================ */ const tsToISO = t => { const d = new Date(t); return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0'); }; let CHART_SEQ = 0; const CHARTS = {}; // cid -> {pts:[{x,y,iso,v}], W, H, unit} function lineChart(points, opts) { // points: [{t: ms, y: num, d?: iso}] sorted by t const o = Object.assign({ h: 150, unit: '', color: 'var(--acc)', axes: true }, opts); const W = 340, H = o.h; const P = { l: o.axes ? 34 : 8, r: 12, t: 10, b: o.axes ? 22 : 8 }; if (points.length === 0) return `
No data yet
`; const single = points.length === 1; if (single) points = [points[0], points[0]]; const ys = points.map(p => p.y); let ymin = Math.min(...ys), ymax = Math.max(...ys); if (o.goal != null && isFinite(o.goal)) { ymin = Math.min(ymin, o.goal); ymax = Math.max(ymax, o.goal); } if (ymin === ymax) { ymin -= 1; ymax += 1; } const pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += pad; const t0 = points[0].t, t1 = points[points.length-1].t || t0 + 1; const X = t => t1 === t0 ? (P.l + W - P.r) / 2 : P.l + (t - t0) / (t1 - t0) * (W - P.l - P.r); const Y = y => P.t + (1 - (y - ymin) / (ymax - ymin)) * (H - P.t - P.b); // y-axis: nice tick steps + gridlines + kg labels let axes = ''; if (o.axes) { const range = ymax - ymin, raw = range / 3; const pow = Math.pow(10, Math.floor(Math.log10(raw))); let step = 10 * pow; for (const m of [1, 2, 2.5, 5, 10]) if (raw <= m * pow) { step = m * pow; break; } for (let v = Math.ceil(ymin / step) * step; v <= ymax + 1e-9; v += step) { const y = Y(v).toFixed(1); axes += ` ${fmtNum(v)}`; } // x-axis: month boundaries in between (or 3 date labels inside one month) const d0 = new Date(t0), d1 = new Date(t1); const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; const ticks = []; let m = new Date(d0.getFullYear(), d0.getMonth() + 1, 1); while (m <= d1) { ticks.push({ t: +m, txt: MONTHS[m.getMonth()] }); m = new Date(m.getFullYear(), m.getMonth() + 1, 1); } if (ticks.length === 0 && !single) { for (let i = 0; i <= 2; i++) { const t = t0 + (t1 - t0) * i / 2; const dd = new Date(t); ticks.push({ t, txt: dd.getDate() + ' ' + MONTHS[dd.getMonth()], anchor: i === 0 ? 'start' : i === 2 ? 'end' : 'middle' }); } } const every = Math.max(1, Math.ceil(ticks.length / 7)); ticks.forEach((tk, i) => { if (i % every) return; const x = X(tk.t).toFixed(1); axes += ` ${tk.txt}`; }); } const pts = points.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' '); const last = points[points.length-1]; const gid = 'g' + Math.random().toString(36).slice(2, 7); const cid = 'ch' + (++CHART_SEQ); CHARTS[cid] = { W, H, unit: o.unit, pts: (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || tsToISO(p.t), v: p.y })), top: P.t, bot: H - P.b, left: P.l, right: W - P.r }; return `
${axes} ${o.goal != null && isFinite(o.goal) ? ` 🎯 ${fmtNum(o.goal)}` : ''}
`; } /* finger/mouse hover: snap to nearest point, crosshair + date/value tooltip */ function bindCharts(root) { root.querySelectorAll('.chart-i').forEach(box => { const d = CHARTS[box.dataset.cid]; if (!d || !d.pts.length) return; const svg = box.querySelector('svg'), tip = box.querySelector('.ctip'); const cross = svg.querySelector('.cross'); const vl = svg.querySelector('.cvl'), hl = svg.querySelector('.chl'), dot = svg.querySelector('.cdot'); function show(clientX) { const r = svg.getBoundingClientRect(); const w = r.width || d.W; const vx = (clientX - r.left) / w * d.W; let best = d.pts[0]; d.pts.forEach(p => { if (Math.abs(p.x - vx) < Math.abs(best.x - vx)) best = p; }); vl.setAttribute('x1', best.x); vl.setAttribute('x2', best.x); hl.setAttribute('y1', best.y); hl.setAttribute('y2', best.y); dot.setAttribute('cx', best.x); dot.setAttribute('cy', best.y); cross.setAttribute('visibility', 'visible'); tip.style.display = 'block'; tip.textContent = fmtDate(best.iso, true) + ' · ' + fmtNum(best.v) + (d.unit ? ' ' + d.unit : ''); const px = best.x / d.W * w; const tw = tip.offsetWidth || 110; tip.style.left = Math.max(2, Math.min(w - tw - 2, px - tw / 2)) + 'px'; } const onMove = e => { const p = e.touches ? e.touches[0] : e; if (p && p.clientX !== undefined) show(p.clientX); }; box.addEventListener('mousemove', onMove); box.addEventListener('mousedown', onMove); box.addEventListener('touchstart', onMove, { passive: true }); box.addEventListener('touchmove', onMove, { passive: true }); }); } /* ============================================================ ROUTER ============================================================ */ let elapsedInt = null; function nav(hash) { location.hash = hash; } const ACCENTS = { lime: '#a3e635', sky: '#38bdf8', orange: '#fb923c', violet: '#a78bfa', pink: '#f472b6', red: '#f87171', teal: '#2dd4bf', gold: '#fbbf24' }; function applyPrefs() { const de = document.documentElement; de.dataset.theme = S.theme === 'light' ? 'light' : 'dark'; de.dataset.accent = ACCENTS[S.accent] ? S.accent : 'lime'; const meta = document.querySelector('meta[name="theme-color"]'); if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f4f7' : '#0c0e12'; } function route() { applyPrefs(); renderView(); updateTabbar(); } function renderView() { const h = (location.hash || '#home').slice(1); // re-rendering the same view (range chips, toggles, …) keeps the scroll position; // only an actual view change jumps to the top const sameView = renderView._last === h; renderView._last = h; const keepY = sameView ? currentScrollY() : 0; const [view, ...rest] = h.split('/'); clearInterval(elapsedInt); closeAllModals(); const app = $('#app'); if (!sameView) { app.classList.remove('vfade'); void app.offsetWidth; app.classList.add('vfade'); } if (!USER && !isGuest()) viewLogin(app); else if (view === 'plan' && rest[0] === 'r') viewRoutineEdit(app, rest[1]); else switch (view) { case 'plan': viewPlan(app); break; case 'workout': viewWorkout(app); break; case 'stats': viewStats(app); break; case 'library': viewLibrary(app); break; case 'settings': viewSettings(app); break; case 'history': viewHistory(app); break; default: viewHome(app); } window.scrollTo(0, keepY); } window.addEventListener('hashchange', route); document.querySelectorAll('#tabbar button').forEach(b => b.addEventListener('click', () => { // Start tab: jump straight into today's session (it knows what day it is) if (b.dataset.tab === 'workout' && (USER || isGuest()) && !S.active) { const r = effectiveRoutine(todayISO()); if (r && r.ex.length) { startFlow(r.id); return; } } nav('#' + b.dataset.tab); })); function updateTabbar() { $('#tabbar').style.display = (!USER && !isGuest()) ? 'none' : ''; const cur = (location.hash || '#home').slice(1).split('/')[0]; document.querySelectorAll('#tabbar button').forEach(b => { b.classList.toggle('on', b.dataset.tab === cur || (cur === 'history' && b.dataset.tab === 'stats') || (cur === 'settings' && b.dataset.tab === 'home')); }); const st = document.querySelector('#tabbar .start'); st.classList.toggle('rec', !!S.active); st.querySelector('span:last-child').textContent = S.active ? 'Resume' : 'Start'; } /* ============================================================ VIEW: LOGIN ============================================================ */ function viewLogin(app) { app.innerHTML = `
🏋️

openGym

Your workouts. Your weights. Your profile.
${webauthnOK() ? `
` : `
This browser doesn't support passkeys — you can still use openGym locally on this device.
`}
Passkeys use ${BIO} — no passwords.
Each profile keeps its own plan, workouts & body weight.
`; const bi = $('#lg-in'); if (bi) bi.onclick = async () => { try { const u = await passkeyLogin(); setUser(u); await pullState(); toast('Welcome back, ' + u.name + ' 💪'); route(); } catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || 'Sign-in failed'); } }; const bn = $('#lg-new'); if (bn) bn.onclick = () => registerSheet(); $('#lg-guest').onclick = () => { localStorage.setItem('gym_guest', '1'); route(); }; } function registerSheet(fromSettings) { const m = openModal(`

Create your profile ✨

Pick a name, then confirm with ${BIO}. The passkey is saved in ${VAULT} — no password needed.
`); const inp = m.el.querySelector('#rg-name'); setTimeout(() => inp.focus(), 250); m.el.querySelector('#rg-go').onclick = async () => { const name = inp.value.trim(); if (!name) { toast('Enter a name'); return; } try { const u = await passkeyRegister(name); setUser(u); m.close(); if (hasData(S)) { await pushState(); toast('Profile created — data from this device moved into it ✓'); } else { await pullState(); toast('Welcome, ' + u.name + ' 💪'); } route(); } catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || 'Registration failed'); } }; } async function signOut() { try { await pushState(); await api('/api/logout', { method: 'POST', body: '{}' }); } catch (e) {} setUser(null); localStorage.removeItem('gym_guest'); localStorage.removeItem('gym_dirty'); S = JSON.parse(JSON.stringify(DEF)); // local copy cleared — data lives in the profile localStorage.removeItem(KEY); stopRest(); nav('#home'); route(); toast('Signed out — see you 👋'); } /* ============================================================ VIEW: HOME ============================================================ */ let weekOffset = 0; function viewHome(app) { const today = new Date(); const routine = effectiveRoutine(todayISO()); const todayOverridden = S.dayPlan[todayISO()] !== undefined; const bw = lastBW(); const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length-2] : null; const delta = bw && prevBW ? bw.w - prevBW.w : null; // week strip (Mon-start, pageable, days tappable to reschedule) const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + weekOffset * 7); const doneDays = new Set(S.workouts.map(w => w.d)); let strip = ''; for (let i = 0; i < 7; i++) { const d = new Date(monday); d.setDate(monday.getDate() + i); const iso = d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0'); const eff = effectiveRoutineId(iso); const ovr = S.dayPlan[iso] !== undefined; const done = doneDays.has(iso); strip += `
${DAYS[d.getDay()]}
${d.getDate()}
`; } const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6); const wkLabel = weekOffset === 0 ? 'This week' : `${monday.getDate()} ${monday.toLocaleDateString('en-GB',{month:'short'})} – ${sunday.getDate()} ${sunday.toLocaleDateString('en-GB',{month:'short'})}`; const wThisWeek = S.workouts.filter(w => weekKey(w.d) === weekKey(todayISO())).length; const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length; const lastW = S.workouts[S.workouts.length-1]; const bwSpark = lineChart(S.bodyweight.slice(-30).map(b => ({t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d})), {h: 130, unit: S.unit, goal: S.targetW}); app.innerHTML = `

${USER ? 'Hi ' + esc(USER.name) + ' 💪' : 'openGym 🏋️'}

${today.toLocaleDateString('en-GB', {weekday:'long', day:'numeric', month:'long'})}
${wkLabel}
${strip}
Tap a day to plan or move a session
${S.active ? `

Workout in progress

${esc(S.active.name)}
${setsDoneActive()} sets logged
` : `

Today

${routine ? `
${esc(routine.name)}
${routine.ex.length} exercises · ~${routine.ex.length * 8} min${todayOverridden ? ' · rescheduled' : ''}
${routine.emoji || '💪'}
` : S.routines.length ? `
Rest day 😌
Nothing planned for ${DAYN[today.getDay()]} — recovery counts too. Feeling strong anyway?
` : `
Welcome! 👋
Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.
`}
`}

Body weight

${bw ? `
${fmtNum(bw.w)} ${S.unit}
${delta !== null ? `${delta > 0 ? '▲' : delta < 0 ? '▼' : '•'} ${fmtNum(Math.abs(delta))}` : ''} ${fmtDate(bw.d, true)}
${S.targetW ? `
🎯 Goal ${fmtNum(S.targetW)} ${S.unit} · ${Math.abs(S.targetW - bw.w) < 0.05 ? 'reached! 🎉' : fmtNum(Math.abs(S.targetW - bw.w)) + ' ' + S.unit + ' to ' + (S.targetW > bw.w ? 'gain' : 'lose')}
` : ''}
${bwSpark}
` : `
No entries yet — log your weight to start the curve. It's also asked automatically before every workout.
`}
This week 📅
${wThisWeek}${plannedPerWeek ? ' / ' + plannedPerWeek : ''}
Week streak 📅
${streakWeeks()} 🔥
Total workouts
${S.workouts.length}
Last volume
${lastW ? fmtVol(lastW.vol) : '—'}
${S.workouts.length ? `

Recent workouts

${[...S.workouts].reverse().slice(0, 3).map(workoutItem).join('')}
` : ''}
`; $('#btn-settings').onclick = () => nav('#settings'); $('#btn-logbw').onclick = () => bwSheet(); const bg = $('#btn-goal'); if (bg) bg.onclick = () => goalSheet(); $('#wk-prev').onclick = () => { weekOffset--; route(); }; $('#wk-next').onclick = () => { weekOffset++; route(); }; app.querySelectorAll('[data-date]').forEach(el => el.addEventListener('click', () => dayOverrideSheet(el.dataset.date))); app.querySelectorAll('[data-open-cal]').forEach(el => el.addEventListener('click', () => calendarSheet())); const bs = $('#btn-start-today'); if (bs) bs.onclick = () => startFlow(routine.id); const ba = $('#btn-start-any'); if (ba) ba.onclick = () => nav('#workout'); const br = $('#btn-resume'); if (br) br.onclick = () => nav('#workout'); const bst = $('#btn-starter'); if (bst) bst.onclick = () => { loadStarterPlan(); route(); }; const bp = $('#btn-goplan'); if (bp) bp.onclick = () => nav('#plan'); const bh = $('#btn-history'); if (bh) bh.onclick = () => nav('#history'); bindWorkoutItems(app); bindCharts(app); } function setsDoneActive() { let n = 0; if (S.active) S.active.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++; })); return n; } function workoutItem(w) { return `
${(S.routines.find(r => r.id === w.routineId) || {}).emoji || '💪'}
${esc(w.name)}
${fmtDate(w.d, true)} · ${fmtDur(w.end - w.start)} · ${setsDone(w)} sets · ${fmtVol(w.vol)}
${w.prs && w.prs.length ? `🏆 ${w.prs.length} PR` : ''} ›
`; } function bindWorkoutItems(root) { root.querySelectorAll('[data-wid]').forEach(el => el.addEventListener('click', () => { const w = S.workouts.find(x => x.id === el.dataset.wid); if (w) workoutDetailSheet(w); })); } /* ---------- full month calendar (from streak/week tiles) ---------- */ const MONTHS_LONG = ['January','February','March','April','May','June','July','August','September','October','November','December']; function calendarSheet(startDate) { const cur = startDate ? new Date(startDate) : new Date(); cur.setDate(1); const m = openModal('
'); const wrap = m.el.querySelector('#cal-wrap'); const draw = () => { const y = cur.getFullYear(), mo = cur.getMonth(); const byDay = {}; S.workouts.forEach(w => (byDay[w.d] = byDay[w.d] || []).push(w)); const startOffset = (new Date(y, mo, 1).getDay() + 6) % 7; // Mon-start const daysIn = new Date(y, mo + 1, 0).getDate(); let cells = ''; for (let i = 0; i < startOffset; i++) cells += '
'; for (let d = 1; d <= daysIn; d++) { const iso = y + '-' + String(mo + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0'); const ws = byDay[iso]; const eff = effectiveRoutineId(iso); const ovr = S.dayPlan[iso] !== undefined; cells += ``; } const monthWs = S.workouts.filter(w => w.d.startsWith(y + '-' + String(mo + 1).padStart(2, '0'))); const monthVol = monthWs.reduce((a, w) => a + (w.vol || 0), 0); const monthMs = monthWs.reduce((a, w) => a + Math.max(0, (w.end || w.start) - w.start), 0); wrap.innerHTML = `

${MONTHS_LONG[mo]} ${y}

${monthWs.length ? monthWs.length + ' workout' + (monthWs.length > 1 ? 's' : '') + ' · ' + fmtDur(monthMs) + ' · ' + fmtVol(monthVol) : 'No workouts this month'}
${['Mo','Tu','We','Th','Fr','Sa','Su'].map(l => `
${l}
`).join('')}${cells}
Trained Planned Rescheduled
Tap a trained day for details · tap any other day to plan a session
`; wrap.querySelector('#cal-prev').onclick = () => { cur.setMonth(cur.getMonth() - 1); draw(); }; wrap.querySelector('#cal-next').onclick = () => { cur.setMonth(cur.getMonth() + 1); draw(); }; wrap.querySelectorAll('[data-cal]').forEach(b => b.addEventListener('click', () => { const iso = b.dataset.cal; const ws = byDay[iso]; if (!ws) { m.close(); dayOverrideSheet(iso); return; } if (ws.length === 1) { m.close(); workoutDetailSheet(ws[0]); return; } m.close(); const lm = openModal(`

${fmtDate(iso, true)}

${ws.map(workoutItem).join('')}
`); lm.el.querySelectorAll('[data-wid]').forEach(el => el.addEventListener('click', () => { const w = S.workouts.find(x => x.id === el.dataset.wid); if (w) { lm.close(); workoutDetailSheet(w); } })); })); }; draw(); } /* ---------- per-date session override ---------- */ function dayOverrideSheet(iso) { const wd = new Date(iso + 'T12:00:00').getDay(); const weeklyR = S.routines.find(r => r.id === S.week[wd]); const hasOvr = S.dayPlan[iso] !== undefined; const effId = effectiveRoutineId(iso); const m = openModal(`

${fmtDate(iso, true)}

Weekly plan: ${weeklyR ? esc(weeklyR.name) : 'Rest'}${hasOvr ? ' · changed for this day' : ''}
Sick, missed a day or want a different session? Pick what to train instead.
${S.routines.map(r => `
${r.emoji || '💪'}
${esc(r.name)}
${r.ex.length} exercises
${effId === r.id ? '✓' : ''}
`).join('')}
😌 Rest / skip this day
${effId === null ? '✓' : ''}
${hasOvr ? '
↺ Back to weekly plan
' : ''}
`); m.el.querySelectorAll('[data-pick]').forEach(el => el.addEventListener('click', () => { const v = el.dataset.pick; if (!v) delete S.dayPlan[iso]; else S.dayPlan[iso] = v; save(); m.close(); route(); toast(v === '' ? 'Back to weekly plan' : v === 'rest' ? fmtDate(iso) + ' set to rest' : (S.routines.find(r => r.id === v) || {}).name + ' planned for ' + fmtDate(iso) + ' ✓'); })); } /* ---------- target weight ---------- */ /* delta is "good" (accent) when it moves toward the goal, red when away; neutral without a goal */ function bwDeltaColor(delta, currentW) { if (!delta) return 'var(--mut)'; if (!S.targetW) return 'var(--txt)'; const wantUp = S.targetW > currentW; return (delta > 0) === wantUp ? 'var(--acc)' : 'var(--red)'; } function goalSheet() { const bw = lastBW(); const m = openModal(`

Target weight 🎯

Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.
${S.unit}
${S.targetW ? '
' : ''} `); const inp = m.el.querySelector('#gw-in'); setTimeout(() => { inp.focus(); inp.select(); }, 250); m.el.querySelector('#gw-save').onclick = () => { const v = parseFloat(inp.value); if (!v || v <= 0 || v > 400) { toast('Enter a valid weight'); return; } S.targetW = v; save(); m.close(); route(); const bw2 = lastBW(); toast('Goal set: ' + fmtNum(v) + ' ' + S.unit + (bw2 ? ' (' + fmtNum(Math.abs(v - bw2.w)) + ' to go)' : '')); }; const del = m.el.querySelector('#gw-del'); if (del) del.onclick = () => { S.targetW = null; save(); m.close(); route(); toast('Goal removed'); }; } /* ============================================================ BODY WEIGHT SHEET ============================================================ */ function bwSheet(onDone, required) { const bw = lastBW(); const m = openModal(`

${required ? 'Quick check-in ⚖️' : 'Log body weight'}

${required ? 'Step on the scale — tracked before every workout so your curve stays honest.' : 'Today, ' + fmtDate(todayISO(), true)}
${S.unit}
${required ? `
` : ''} `); if (required) m.lock(true); const inp = m.el.querySelector('#bw-in'); setTimeout(() => { inp.focus(); inp.select(); }, 250); m.el.querySelector('#bw-save').onclick = () => { const v = parseFloat(inp.value); if (!v || v <= 0 || v > 400) { toast('Enter a valid weight'); return; } const iso = todayISO(); const ex = S.bodyweight.find(b => b.d === iso); if (ex) { ex.w = v; ex.t = Date.now(); } else S.bodyweight.push({ d: iso, w: v, t: Date.now() }); S.bodyweight.sort((a, b) => a.d < b.d ? -1 : 1); save(); m.close(); if (onDone) onDone(v); else { toast('Weight saved ✓'); route(); } }; const sk = m.el.querySelector('#bw-skip'); if (sk) sk.onclick = () => { m.close(); if (onDone) onDone(null); }; const sw = m.el.querySelector('#bw-switch'); if (sw) sw.onclick = () => { m.close(); if (location.hash === '#workout') route(); else nav('#workout'); }; } /* ============================================================ VIEW: PLAN ============================================================ */ function viewPlan(app) { const dayRows = [1, 2, 3, 4, 5, 6, 0].map(d => { const r = S.routines.find(x => x.id === S.week[d]); return `
${DAYN[d]}
${r ? `${(r.emoji || '') + ' ' + esc(r.name)}` : 'Rest'} ›
`; }).join(''); app.innerHTML = `

Plan

Your weekly routine

Week schedule

${dayRows}

Routines

${S.routines.length ? `
${S.routines.map(r => `
${r.emoji || '💪'}
${esc(r.name)}
${r.ex.length} exercises
›
`).join('')}
` : `
📋
No routines yet.
Create one or load the starter plan.
`}
`; app.querySelectorAll('[data-day]').forEach(el => el.addEventListener('click', () => dayAssignSheet(+el.dataset.day))); app.querySelectorAll('[data-rid]').forEach(el => el.addEventListener('click', () => nav('#plan/r/' + el.dataset.rid))); $('#btn-add-routine').onclick = () => { const r = { id: uid(), name: 'New routine', emoji: '💪', ex: [] }; S.routines.push(r); save(); nav('#plan/r/' + r.id); }; const bst = $('#btn-starter2'); if (bst) bst.onclick = () => { loadStarterPlan(); route(); }; } function dayAssignSheet(day) { const m = openModal(`

${DAYN[day]}

😌 Rest day
${!S.week[day] ? '✓' : ''}
${S.routines.map(r => `
${r.emoji || '💪'}
${esc(r.name)}
${r.ex.length} exercises
${S.week[day] === r.id ? '✓' : ''}
`).join('')}
`); m.el.querySelectorAll('[data-pick]').forEach(el => el.addEventListener('click', () => { if (el.dataset.pick) S.week[day] = el.dataset.pick; else delete S.week[day]; save(); m.close(); route(); })); } /* ---------- routine editor ---------- */ function viewRoutineEdit(app, rid) { const r = S.routines.find(x => x.id === rid); if (!r) { nav('#plan'); return; } app.innerHTML = `
${r.ex.length ? `
${r.ex.map((e, i) => { const ex = EXIDX[e.id]; if (!ex) return ''; return `
${imgEl(ex)}
${esc(ex.n)}
${e.sets} × ${e.reps}${e.weight ? ' · ' + fmtNum(e.weight) + ' ' + S.unit : ''}
`; }).join('')}
` : '
🏋️
No exercises yet — add your first one.
'}
`; $('#btn-back').onclick = () => nav('#plan'); $('#r-name').addEventListener('change', ev => { r.name = ev.target.value.trim() || 'Routine'; save(); }); $('#btn-emoji').onclick = () => emojiPickerSheet(r.emoji, emo => { r.emoji = emo; save(); route(); }); $('#btn-add-ex').onclick = () => exercisePicker(ex => exConfigSheet(ex, null, cfg => { r.ex.push({ id: ex.id, ...cfg }); save(); route(); })); $('#btn-del-r').onclick = () => { if (!confirm('Delete "' + r.name + '"?')) return; S.routines = S.routines.filter(x => x.id !== rid); Object.keys(S.week).forEach(k => { if (S.week[k] === rid) delete S.week[k]; }); Object.keys(S.dayPlan).forEach(k => { if (S.dayPlan[k] === rid) delete S.dayPlan[k]; }); save(); nav('#plan'); }; app.querySelectorAll('[data-up]').forEach(b => b.addEventListener('click', ev => { ev.stopPropagation(); const i = +b.dataset.up; if (i > 0) { [r.ex[i-1], r.ex[i]] = [r.ex[i], r.ex[i-1]]; save(); route(); } })); app.querySelectorAll('[data-dn]').forEach(b => b.addEventListener('click', ev => { ev.stopPropagation(); const i = +b.dataset.dn; if (i < r.ex.length - 1) { [r.ex[i+1], r.ex[i]] = [r.ex[i], r.ex[i+1]]; save(); route(); } })); app.querySelectorAll('.item[data-idx]').forEach(el => el.addEventListener('click', () => { const i = +el.dataset.idx; const e = r.ex[i]; const ex = EXIDX[e.id]; exConfigSheet(ex, e, cfg => { Object.assign(e, cfg); save(); route(); }, () => { r.ex.splice(i, 1); save(); route(); }); })); } /* ---------- emoji picker (big grid instead of click-cycling) ---------- */ const ROUTINE_EMOJIS = [ '💪','🏋️','🏋️‍♀️','🦵','🦾','🫸','🫷','🔥','⚡','💥', '🏃','🏃‍♀️','🚴','🏊','🤸','🥊','🧗','⛰️','🏔️','🚀', '🧘','🧘‍♀️','🎯','🏆','🥇','⭐','🌟','👑','🛡️','⚔️', '🦍','🐂','🐻','🦁','🐺','🦈','😤','🤖','🧨','❤️‍🔥' ]; function emojiPickerSheet(current, onPick) { const m = openModal(`

Pick an emoji

${ROUTINE_EMOJIS.map(e => ``).join('')}
`); m.el.querySelectorAll('[data-emo]').forEach(b => b.addEventListener('click', () => { m.close(); onPick(b.dataset.emo); })); } /* ---------- exercise picker ---------- */ function exercisePicker(onPick) { let q = '', bp = '', shown = 50; const m = openModal(`

Add exercise

`); const listEl = m.el.querySelector('#pk-list'); const chipsEl = m.el.querySelector('#pk-chips'); const moreBtn = m.el.querySelector('#pk-more'); function filtered() { return EXDB.filter(e => (!bp || e.bp === bp) && (!q || e.n.includes(q) || e.tg.includes(q) || e.eq.includes(q))); } function draw() { chipsEl.innerHTML = `` + BODYPARTS.map(b => ``).join(''); chipsEl.querySelectorAll('.chip').forEach(c => c.onclick = () => { bp = c.dataset.bp; shown = 50; draw(); }); const f = filtered(); listEl.innerHTML = f.slice(0, shown).map(e => `
${imgEl(e)}
${esc(e.n)}
${e.tg || e.bp} · ${e.eq}
+
`).join('') || '
No match 🤷
'; moreBtn.style.display = f.length > shown ? '' : 'none'; listEl.querySelectorAll('[data-ex]').forEach(el => el.addEventListener('click', () => { m.close(); onPick(EXIDX[el.dataset.ex]); })); } moreBtn.onclick = () => { shown += 50; draw(); }; m.el.querySelector('#pk-q').addEventListener('input', ev => { q = ev.target.value.toLowerCase().trim(); shown = 50; draw(); }); draw(); } /* ---------- add exercise straight to a routine (from library browsing) ---------- */ function addToRoutineSheet(ex) { const m = openModal(`

Add “${esc(ex.n)}”

Pick a routine — sets, reps & weight come next.
${S.routines.map(r => `
${r.emoji || '💪'}
${esc(r.name)}
${r.ex.length} exercises
${r.ex.some(e => e.id === ex.id) ? 'already in' : ''}+
`).join('')}
✨
New routine
Create one and start with this exercise
+
`); m.el.querySelectorAll('[data-r]').forEach(el => el.addEventListener('click', () => { m.close(); const isNew = el.dataset.r === '_new'; let r = isNew ? null : S.routines.find(x => x.id === el.dataset.r); exConfigSheet(ex, null, cfg => { if (isNew) { r = { id: uid(), name: 'New routine', emoji: '💪', ex: [] }; S.routines.push(r); } if (!r) return; r.ex.push({ id: ex.id, ...cfg }); save(); toast('“' + ex.n + '” added to ' + r.name + ' ✓'); if (isNew) nav('#plan/r/' + r.id); }); })); } /* ---------- exercise config (sets/reps/weight) ---------- */ function stepperHTML(id, val, step, label) { return `
${label}
`; } function bindSteppers(root) { root.querySelectorAll('.step input').forEach(inp => inp.addEventListener('focus', () => setTimeout(() => inp.select(), 0))); root.querySelectorAll('[data-st]').forEach(b => b.addEventListener('click', () => { const inp = root.querySelector('#' + b.dataset.for); const v = (parseFloat(inp.value) || 0) + parseFloat(b.dataset.st); inp.value = Math.max(0, Math.round(v * 100) / 100); inp.dispatchEvent(new Event('change')); })); } function exConfigSheet(ex, existing, onSave, onDelete) { const e = existing || { sets: 3, reps: 10, weight: 0 }; const m = openModal(`

${esc(ex.n)}

${mediaEl(ex)}
${ex.tg || ex.bp}${ex.eq}
${stepperHTML('cf-sets', e.sets, 1, 'Sets')} ${stepperHTML('cf-reps', e.reps, 1, 'Reps')} ${stepperHTML('cf-w', e.weight, 2.5, 'Weight (' + S.unit + ')')}
${onDelete ? '
' : ''} `); bindSteppers(m.el); bindMediaToggle(m.el.querySelector('.exmedia'), ex); m.el.querySelector('#cf-save').onclick = () => { const cfg = { sets: Math.max(1, Math.round(parseFloat(m.el.querySelector('#cf-sets').value) || 3)), reps: Math.max(1, Math.round(parseFloat(m.el.querySelector('#cf-reps').value) || 10)), weight: Math.max(0, parseFloat(m.el.querySelector('#cf-w').value) || 0) }; m.close(); onSave(cfg); }; const del = m.el.querySelector('#cf-del'); if (del) del.onclick = () => { m.close(); onDelete(); }; } /* ============================================================ STARTER PLAN ============================================================ */ function loadStarterPlan() { const mk = (name, emoji, list) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) }); const push = mk('Push Day', '🫸', [['0025',4,8],['0047',3,10],['0426',3,10],['0334',3,12],['0241',3,12],['0251',3,10]]); const pull = mk('Pull Day', '🫷', [['2330',4,10],['0027',4,8],['1323',3,10],['0031',3,10],['0313',3,12]]); const legs = mk('Leg Day', '🦵', [['0043',4,8],['0085',3,10],['0739',3,12],['0585',3,12],['0586',3,12],['0605',4,15]]); S.routines.push(push, pull, legs); S.week[1] = push.id; S.week[3] = pull.id; S.week[5] = legs.id; // Mon / Wed / Fri save(); toast('Starter plan loaded — Mon Push · Wed Pull · Fri Legs'); } /* ============================================================ VIEW: WORKOUT ============================================================ */ function viewWorkout(app) { if (S.active) return renderActive(app); const today = new Date().getDay(); const todayR = effectiveRoutine(todayISO()); const todayOvr = S.dayPlan[todayISO()] !== undefined; app.innerHTML = `

Start workout

${DAYN[today]} — ${todayR ? 'today is ' + esc(todayR.name) : 'rest day, but no one’s stopping you'}
${todayR ? `

Today's plan${todayOvr ? ' · rescheduled' : ''}

${esc(todayR.name)}
${todayR.ex.length} exercises
${todayR.emoji || '💪'}
` : ''} ${S.routines.filter(r => r !== todayR).length ? `

Other routines

${S.routines.filter(r => r !== todayR).map(r => `
${r.emoji || '💪'}
${esc(r.name)}
${r.ex.length} exercises
Start ▶
`).join('')}
` : ''}
${!S.routines.length ? `
` : ''}
`; app.querySelectorAll('[data-start]').forEach(el => el.addEventListener('click', () => startFlow(el.dataset.start))); $('#btn-free').onclick = () => startFlow(null); const bst = $('#btn-starter3'); if (bst) bst.onclick = () => { loadStarterPlan(); route(); }; } function startFlow(routineId) { // Always ask for body weight first (core requirement) bwSheet(bw => beginWorkout(routineId, bw), true); } function beginWorkout(routineId, bw) { const r = routineId ? S.routines.find(x => x.id === routineId) : null; const entries = (r ? r.ex : []).map(cfg => ({ id: cfg.id, target: { ...cfg }, sets: buildSets(cfg) })); S.active = { id: uid(), d: todayISO(), start: Date.now(), routineId: routineId, name: r ? r.name : 'Freestyle', bw: bw || null, cur: 0, entries }; save(); stopRest(); nav('#workout'); route(); } function renderActive(app) { const A = S.active; const totalSets = A.entries.reduce((n, e) => n + e.sets.length, 0); const doneSets = setsDoneActive(); const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1)); A.cur = cur; const entry = A.entries[cur]; app.innerHTML = `
${esc(A.name)}
0:00 · ${doneSets}/${totalSets} sets
${entry ? renderExerciseCard(entry, cur, A.entries.length) : `
🎯
Freestyle workout — add your first exercise.
`}
`; // elapsed ticker const tick = () => { const el = $('#wo-elapsed'); if (!el) return; const s = Math.floor((Date.now() - A.start) / 1000); el.textContent = Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); }; tick(); elapsedInt = setInterval(tick, 1000); $('#wo-cancel').onclick = () => { if (confirm('Discard this workout? Logged sets will be lost.')) { S.active = null; save(); stopRest(); nav('#home'); } }; $('#wo-finish').onclick = $('#wo-finish2').onclick = finishWorkout; $('#wo-prev').onclick = () => { A.cur = Math.max(0, cur - 1); save(); route(); }; $('#wo-next').onclick = () => { A.cur = Math.min(A.entries.length - 1, cur + 1); save(); route(); }; $('#wo-add').onclick = () => exercisePicker(ex => exConfigSheet(ex, null, cfg => { A.entries.push({ id: ex.id, target: { ...cfg }, sets: buildSets({ ...cfg, id: ex.id }) }); A.cur = A.entries.length - 1; save(); route(); })); if (entry) bindExerciseCard(app, entry); } function renderExerciseCard(entry, idx, total) { const ex = EXIDX[entry.id]; if (!ex) return ''; const last = lastEntryFor(entry.id); const best = bestWeightFor(entry.id); // progression hint: all sets hit target reps last time → suggest +2.5 let hint = ''; if (last && last.sets.length >= (entry.target.sets || 1) && last.sets.every(s => s.r >= entry.target.reps) && last.sets[0].w > 0) { hint = ``; } return `
Exercise ${idx + 1} / ${total}
${mediaEl(ex, 'wo-media')}
${esc(ex.n)}
${ex.tg || ex.bp}${ex.eq} ${best ? `Best: ${fmtNum(best)} ${S.unit}` : ''}
${last ? `
Last time (${fmtDate(last.d)}): ${last.sets.map(s => fmtNum(s.w) + '×' + s.r).join(', ')}
` : ''} ${hint}
Weight (${S.unit})Reps
${entry.sets.map((s, i) => `
${i + 1}
`).join('')}
`; } function updateWorkoutHeader() { const A = S.active; if (!A) return; const total = A.entries.reduce((n, e) => n + e.sets.length, 0); const done = setsDoneActive(); const c = $('#wo-count'); if (c) c.textContent = done + '/' + total; const p = $('#wo-prog'); if (p) p.style.width = (total ? done / total * 100 : 0) + '%'; } function bindExerciseCard(app, entry) { const A = S.active; // tapping a number field selects its content so typing replaces instead of appending ("060") app.querySelectorAll('.setrow input').forEach(inp => { inp.addEventListener('focus', () => setTimeout(() => inp.select(), 0)); }); bindMediaToggle($('#wo-media'), EXIDX[entry.id]); const info = $('#wo-info'); if (info) info.onclick = () => exerciseDetailSheet(EXIDX[entry.id]); const hint = $('#wo-hint'); if (hint) hint.onclick = () => { const last = lastEntryFor(entry.id); const w = Math.max(...last.sets.map(s => s.w)) + 2.5; entry.sets.forEach(s => { if (!s.done) s.w = w; }); save(); route(); toast('Weights bumped to ' + fmtNum(w) + ' ' + S.unit + ' 💪'); }; app.querySelectorAll('[data-win]').forEach(inp => inp.addEventListener('change', () => { const v = Math.max(0, parseFloat(inp.value) || 0); entry.sets[+inp.dataset.win].w = v; inp.value = v; save(); // normalize display ("060" -> "60") })); app.querySelectorAll('[data-rin]').forEach(inp => inp.addEventListener('change', () => { const v = Math.max(0, Math.round(parseFloat(inp.value) || 0)); entry.sets[+inp.dataset.rin].r = v; inp.value = v; save(); })); app.querySelectorAll('[data-sw]').forEach(b => b.addEventListener('click', () => { const s = entry.sets[+b.dataset.si]; const inp = app.querySelector(`[data-win="${b.dataset.si}"]`); s.w = Math.max(0, Math.round(((parseFloat(inp.value) || 0) + parseFloat(b.dataset.sw)) * 100) / 100); save(); inp.value = s.w; })); app.querySelectorAll('[data-sr]').forEach(b => b.addEventListener('click', () => { const s = entry.sets[+b.dataset.si]; const inp = app.querySelector(`[data-rin="${b.dataset.si}"]`); s.r = Math.max(0, Math.round(parseFloat(inp.value) || 0) + parseInt(b.dataset.sr)); save(); inp.value = s.r; })); app.querySelectorAll('[data-ck]').forEach(b => b.addEventListener('click', () => { const i = +b.dataset.ck; const s = entry.sets[i]; s.done = !s.done; let askTop = false; if (s.done) { beep(1040, .12); vibrate(30); const allDoneHere = entry.sets.every(x => x.done); const isLastEx = A.cur >= A.entries.length - 1; // rest timer only BETWEEN sets of an exercise — not once it's finished (the recap sheet takes over) if (!allDoneHere) startRest(S.restSec); else { stopRest(); toast(isLastEx ? 'All sets done — Finish 🏁' : 'Exercise done ✓'); } if (allDoneHere && !entry.asked) { entry.asked = true; askTop = true; } } save(); // in-place update — no full re-render, so the GIF keeps playing and nothing flickers b.classList.toggle('on', s.done); b.closest('.setrow').classList.toggle('done', s.done); updateWorkoutHeader(); if (askTop) { const maxW = Math.max(0, ...entry.sets.map(x => x.w || 0), entry.target.weight || 0, (S.exWeights[entry.id] || {}).w || 0); if (maxW > 0) topWeightSheet(entry); } })); const as = $('#wo-addset'); if (as) as.onclick = () => { const lastSet = entry.sets[entry.sets.length - 1]; entry.sets.push({ w: lastSet ? lastSet.w : 0, r: lastSet ? lastSet.r : entry.target.reps, done: false }); save(); route(); }; } /* end-of-exercise weight confirmation: tracks the working weight, highest ever entered becomes next time's default */ function topWeightSheet(entry) { const A = S.active; const ex = EXIDX[entry.id]; if (!ex) return; const maxSet = Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)); const prevBest = Math.max((S.exWeights[entry.id] || {}).w || 0, bestWeightFor(entry.id)); const def = Math.max(maxSet, prevBest) || entry.target.weight || 0; const isLastEx = A && A.cur >= A.entries.length - 1; const m = openModal(`

✅ ${esc(ex.n)} done

Confirm the weight you worked with — your highest becomes the default next time.
${S.unit}
${prevBest > 0 ? `
Previous best: ${fmtNum(prevBest)} ${S.unit}${maxSet > prevBest ? ' — new record! 🏆' : ''}
` : '
'}
`); const save2 = advance => { const v = parseFloat(inp.value); if (!isFinite(v) || v < 0) { toast('Enter a valid weight'); return; } entry.topW = v; const cur = S.exWeights[entry.id]; S.exWeights[entry.id] = { w: Math.max(v, cur ? cur.w : 0), d: todayISO() }; save(); m.close(); if (advance && A) { if (isLastEx) finishWorkout(); else { A.cur = Math.min(A.entries.length - 1, A.cur + 1); save(); route(); } } else { toast('Tracked — next time starts at ' + fmtNum(S.exWeights[entry.id].w) + ' ' + S.unit + ' 📈'); } }; const inp = m.el.querySelector('#tw-in'); setTimeout(() => { inp.focus(); inp.select(); }, 250); m.el.querySelector('#tw-save').onclick = () => save2(true); m.el.querySelector('#tw-skip').onclick = () => save2(false); } function finishWorkout() { const A = S.active; const done = setsDoneActive(); if (!done && !confirm('No sets logged — finish anyway?')) return; if (done < A.entries.reduce((n, e) => n + e.sets.length, 0) && done > 0) { if (!confirm('Some sets are unchecked. Finish workout?')) return; } // PRs: compare vs history BEFORE saving const prs = []; A.entries.forEach(e => { const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w)); if (mx > 0 && mx > bestWeightFor(e.id)) prs.push(e.id); }); const w = { id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw, entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null })).filter(e => e.sets.some(s => s.done)), prs }; w.vol = workoutVolume(w); // remember highest weight per exercise → default next time w.entries.forEach(e => { const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w || 0), e.topW || 0); if (mx > 0) { const cur = S.exWeights[e.id]; if (!cur || mx > cur.w) S.exWeights[e.id] = { w: mx, d: w.d }; } }); S.workouts.push(w); S.active = null; save(); stopRest(); beep(880, .15); beep(1100, .15, .18); beep(1320, .3, .36); const m = openModal(`
🎉

Workout complete!

Duration
${fmtDur(w.end - w.start)}
Volume
${fmtVol(w.vol)}
Sets
${setsDone(w)}
PRs
${prs.length ? '🏆 ' + prs.length : '—'}
${prs.length ? `
${prs.map(id => `
🏆 New PR: ${esc((EXIDX[id] || {}).n || id)}
`).join('')}
` : ''}
`, 'center'); m.lock(true); m.el.querySelector('#sum-ok').onclick = () => { m.close(); nav('#home'); }; } /* ---------- activity heatmap (GitHub-style) ---------- */ function heatmapHTML() { // intensity = time spent training that day (minutes) — more intuitive than volume const agg = {}; // iso -> {n, vol, min} S.workouts.forEach(w => { const a = agg[w.d] = agg[w.d] || { n: 0, vol: 0, min: 0 }; a.n++; a.vol += w.vol || 0; a.min += Math.max(0, Math.round(((w.end || w.start) - w.start) / 60000)); }); const mins = Object.values(agg).map(a => a.min).filter(v => v > 0).sort((a, b) => a - b); const q = p => mins.length ? mins[Math.min(mins.length - 1, Math.floor(p * mins.length))] : 0; const t1 = q(0.25), t2 = q(0.5), t3 = q(0.75); const level = a => !a ? 0 : !a.min ? 1 : a.min >= t3 ? 4 : a.min >= t2 ? 3 : a.min >= t1 ? 2 : 1; const today = new Date(); today.setHours(12, 0, 0, 0); const iso = d => d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0'); // current week's Monday, then back 52 weeks const end = new Date(today); end.setDate(today.getDate() - ((today.getDay() + 6) % 7)); const start = new Date(end); start.setDate(end.getDate() - 52 * 7); const MON = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; let cols = '', months = '', lastMonth = -1; for (let wk = 0; wk <= 52; wk++) { const colStart = new Date(start); colStart.setDate(start.getDate() + wk * 7); const m = colStart.getMonth(); months += `${m !== lastMonth && colStart.getDate() <= 7 && wk < 51 ? MON[m] : ''}`; if (colStart.getDate() <= 7) lastMonth = m; let cells = ''; for (let d = 0; d < 7; d++) { const day = new Date(colStart); day.setDate(colStart.getDate() + d); const key = iso(day); const a = agg[key]; const isToday = key === todayISO(); const future = day > today; cells += `
`; } cols += `
${cells}
`; } return `
${months}
MonWedFri
${cols}
Less time
More time
`; } function bindHeatmap(root) { const wrap = root.querySelector('#hm-wrap'); if (wrap) wrap.scrollLeft = wrap.scrollWidth; // land on "now" root.querySelectorAll('[data-hm]').forEach(c => c.addEventListener('click', () => { const day = c.dataset.hm; const list = S.workouts.filter(w => w.d === day); if (list.length === 1) return workoutDetailSheet(list[0]); const m = openModal(`

${fmtDate(day, true)}

${list.map(workoutItem).join('')}
`); m.el.querySelectorAll('[data-wid]').forEach(el => el.addEventListener('click', () => { const w = S.workouts.find(x => x.id === el.dataset.wid); if (w) { m.close(); workoutDetailSheet(w); } })); })); } /* ============================================================ VIEW: STATS + HISTORY ============================================================ */ let statsRange = 90, statsEx = null; function viewStats(app) { const now = Date.now(); const bwPts = S.bodyweight .filter(b => statsRange === 0 || (b.t || new Date(b.d).getTime()) > now - statsRange * 86400000) .map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d })); const bw30 = S.bodyweight.filter(b => (b.t || new Date(b.d).getTime()) > now - 30 * 86400000); const bwDelta30 = bw30.length > 1 ? bw30[bw30.length-1].w - bw30[0].w : null; const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length; // exercises with history const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))] .filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1); if (!statsEx || !exHist.includes(statsEx)) statsEx = exHist[0] || null; let exChart = '', exList = ''; if (statsEx) { const pts = []; S.workouts.forEach(w => { const en = w.entries.find(e => e.id === statsEx); if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(s => s.w), en.topW || 0); if (mx > 0) pts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done) }); } }); exChart = lineChart(pts.map(p => ({ t: p.t, y: p.y, d: p.d })), { h: 150, unit: S.unit, color: 'var(--blue)' }); exList = pts.slice(-5).reverse().map(p => `
${fmtDate(p.d, true)} ${p.sets.map(s => fmtNum(s.w) + '×' + s.r).join(' ')}
`).join(''); } app.innerHTML = `

Stats

Progress & history
Workouts
${S.workouts.length}
This month
${monthW}
Week streak
${streakWeeks()} 🔥
Weight 30d
${bwDelta30 === null ? '—' : (bwDelta30 > 0 ? '+' : '') + fmtNum(bwDelta30) + ' ' + S.unit}

Activity — last 12 months · by time trained

${heatmapHTML()}

Body weight

${[[30,'1M'],[90,'3M'],[365,'1Y'],[0,'All']].map(([d, l]) => ``).join('')}
${lineChart(bwPts, { h: 160, unit: S.unit, goal: S.targetW })}

Exercise progress

${exHist.length ? `
${exChart}
${exList}
Best set weight per workout · Best ever: ${fmtNum(bestWeightFor(statsEx))} ${S.unit}
` : '
Finish your first workout to see strength curves here. 📈
'}
${S.workouts.length ? `

History

${[...S.workouts].reverse().slice(0, 5).map(workoutItem).join('')}
` : ''} `; $('#btn-hist').onclick = () => nav('#history'); $('#st-logbw').onclick = () => bwSheet(); $('#st-goal').onclick = () => goalSheet(); app.querySelectorAll('[data-range]').forEach(c => c.addEventListener('click', () => { statsRange = +c.dataset.range; route(); })); const sel = $('#st-ex'); if (sel) sel.addEventListener('change', () => { statsEx = sel.value; route(); }); const ha = $('#st-histall'); if (ha) ha.onclick = () => nav('#history'); bindWorkoutItems(app); bindHeatmap(app); bindCharts(app); } function viewHistory(app) { app.innerHTML = `

History

${S.workouts.length} workouts
${S.workouts.length ? `
${[...S.workouts].reverse().map(workoutItem).join('')}
` : '
🗂
No workouts yet.
'}`; $('#btn-back').onclick = () => nav('#stats'); bindWorkoutItems(app); } function workoutDetailSheet(w) { const m = openModal(`

${esc(w.name)}

${fmtDate(w.d, true)} · ${fmtDur(w.end - w.start)} · ${fmtVol(w.vol)}${w.bw ? ' · ⚖️ ' + fmtNum(w.bw) + ' ' + S.unit : ''}
${w.entries.map(e => { const ex = EXIDX[e.id]; return `
${ex ? imgEl(ex) : ''}
${esc(ex ? ex.n : e.id)} ${w.prs && w.prs.includes(e.id) ? '🏆 PR' : ''}
${e.sets.filter(s => s.done).map(s => fmtNum(s.w) + '×' + s.r).join(' · ') || 'no sets'}
`; }).join('')} `); m.el.querySelector('#wd-del').onclick = () => { if (!confirm('Delete this workout from history?')) return; S.workouts = S.workouts.filter(x => x.id !== w.id); save(); m.close(); route(); toast('Workout deleted'); }; } /* ============================================================ VIEW: LIBRARY ============================================================ */ let libQ = '', libBP = '', libShown = 40; function viewLibrary(app) { app.innerHTML = `

Exercises

${EXDB.length} exercises with animations
`; const chipsEl = $('#lib-chips'), listEl = $('#lib-list'), moreBtn = $('#lib-more'); function filtered() { return EXDB.filter(e => (!libBP || e.bp === libBP) && (!libQ || e.n.includes(libQ) || e.tg.includes(libQ) || e.eq.includes(libQ))); } function draw() { chipsEl.innerHTML = `` + BODYPARTS.map(b => ``).join(''); chipsEl.querySelectorAll('.chip').forEach(c => c.onclick = () => { libBP = c.dataset.bp; libShown = 40; draw(); }); const f = filtered(); listEl.innerHTML = f.slice(0, libShown).map(e => `
${imgEl(e)}
${esc(e.n)}
${e.tg || e.bp} · ${e.eq}
${bestWeightFor(e.id) ? `${fmtNum(bestWeightFor(e.id))}` : ''}
`).join('') || '
No match 🤷
'; moreBtn.style.display = f.length > libShown ? '' : 'none'; listEl.querySelectorAll('[data-ex]').forEach(el => el.addEventListener('click', () => exerciseDetailSheet(EXIDX[el.dataset.ex]))); listEl.querySelectorAll('[data-addex]').forEach(b => b.addEventListener('click', ev => { ev.stopPropagation(); addToRoutineSheet(EXIDX[b.dataset.addex]); })); } moreBtn.onclick = () => { libShown += 40; draw(); }; $('#lib-q').addEventListener('input', ev => { libQ = ev.target.value.toLowerCase().trim(); libShown = 40; draw(); }); draw(); } function exerciseDetailSheet(ex) { const last = lastEntryFor(ex.id); const best = bestWeightFor(ex.id); const m = openModal(`

${esc(ex.n)}

${mediaEl(ex)}
${ex.bp} ${ex.tg ? `🎯 ${ex.tg}` : ''} 🛠 ${ex.eq} ${(ex.sm || []).slice(0, 3).map(s => `${s}`).join('')}
${best ? `
🏆 Best: ${fmtNum(best)} ${S.unit}${last ? ` · last ${fmtDate(last.d)}: ${last.sets.map(s => fmtNum(s.w) + '×' + s.r).join(', ')}` : ''}
` : ''} ${ex.st && ex.st.length ? `

How to

    ${ex.st.map(s => `
  1. ${esc(s)}
  2. `).join('')}
` : ''} `); bindMediaToggle(m.el.querySelector('.exmedia'), ex); m.el.querySelector('#dt-add').onclick = () => { m.close(); addToRoutineSheet(ex); }; } /* ============================================================ VIEW: SETTINGS ============================================================ */ function viewSettings(app) { app.innerHTML = `

Settings

Account

${USER ? `
${esc(USER.name)}
Signed in with passkey — data syncs to this profile.
` : `
Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.
${webauthnOK() ? `
` : '
Passkeys not supported in this browser.
'}`}

Appearance · synced with your profile

Theme
Accent color
${Object.entries(ACCENTS).map(([k, c]) => ``).join('')}

Units & timer

Weight unit
Rest timer
Sounds
Note: switching units only changes the label — logged numbers are not converted.

Data

Tip

📱 ${IS_ANDROID ? 'In Chrome: ⋮ menu → Add to Home screen' : 'In Safari: Share → Add to Home Screen'} to install openGym as a full-screen app. ${USER ? 'Your data syncs with your profile — sign in anywhere to see it.' : 'Guest data stays on this device — export a backup now and then!'}
openGym · exercise data: hasaneyldrm/exercises-dataset (CC)
`; $('#btn-back').onclick = () => nav('#home'); const ao = $('#acc-out'); if (ao) ao.onclick = () => { if (confirm('Sign out? Local data is synced to your profile first, then cleared from this device.')) signOut(); }; const an = $('#acc-new'); if (an) an.onclick = () => registerSheet(true); const ai = $('#acc-in'); if (ai) ai.onclick = async () => { try { const u = await passkeyLogin(); setUser(u); await pullState(); route(); toast('Welcome back, ' + u.name + ' 💪'); } catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || 'Sign-in failed'); } }; app.querySelectorAll('[data-theme-set]').forEach(c => c.addEventListener('click', () => { S.theme = c.dataset.themeSet; save(); route(); })); app.querySelectorAll('[data-accent-set]').forEach(c => c.addEventListener('click', () => { S.accent = c.dataset.accentSet; save(); route(); })); app.querySelectorAll('[data-unit]').forEach(c => c.addEventListener('click', () => { S.unit = c.dataset.unit; save(); route(); })); $('#set-rest').addEventListener('change', ev => { S.restSec = +ev.target.value; save(); }); $('#set-sound').onclick = () => { S.sound = !S.sound; save(); route(); }; $('#set-export').onclick = () => { const blob = new Blob([JSON.stringify(S, null, 2)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'gymlog-backup-' + todayISO() + '.json'; a.click(); URL.revokeObjectURL(a.href); toast('Backup exported ✓'); }; $('#set-import').onclick = () => $('#set-file').click(); $('#set-file').addEventListener('change', ev => { const f = ev.target.files[0]; if (!f) return; const rd = new FileReader(); rd.onload = () => { try { const data = JSON.parse(rd.result); if (!data.workouts || !data.routines) throw new Error('not a openGym backup'); if (!confirm('Replace all current data with this backup?')) return; S = Object.assign(JSON.parse(JSON.stringify(DEF)), data); save(); toast('Backup imported ✓'); route(); } catch (e) { toast('Import failed: ' + e.message); } }; rd.readAsText(f); }); $('#set-starter').onclick = () => { loadStarterPlan(); route(); }; $('#set-reset').onclick = () => { if (!confirm('Delete ALL data (plan, workouts, body weight)?')) return; if (!confirm('Really sure? This cannot be undone.')) return; S = JSON.parse(JSON.stringify(DEF)); save(); stopRest(); nav('#home'); route(); toast('All data reset'); }; } /* ============================================================ BOOT ============================================================ */ (async function boot() { try { const me = await api('/api/me'); setUser(me.user); await pullState(); } catch (e) { if (e.status === 401) setUser(null); else { // network error (offline / API down): fall back to cached login try { USER = JSON.parse(localStorage.getItem('gym_user')) || null; } catch (x) { USER = null; } } } route(); })(); if ('serviceWorker' in navigator && location.protocol === 'https:') { navigator.serviceWorker.register('sw.js').catch(() => {}); }