Rewrite frontend in React + Vite (organised component tree)

Ersetzt die 1900-Zeilen-Vanilla-SPA durch eine strukturierte React-App:
- frontend/src: views/ (9 Views), components/ (Modals, LineChart, Heatmap,
  TabBar, Media, Stepper, RestTimer, Toast), store/ (Zustand: State+Sync,
  UI), lib/ (format, history, exercises, api/WebAuthn, sound, nav)
- React Router (Hash), Zustand-Store mit localStorage + Server-Sync
- Reaktives DOM-Diffing löst das manuelle Re-Render-Ruckeln (GIF läuft beim
  Set-Abhaken flüssig weiter)

Self-Hosting bleibt ein Befehl: web/ ist jetzt ein Multi-Stage-Dockerfile,
das das Frontend IM Container baut und mit nginx ausliefert — keine lokale
Node/Build-Kette nötig. Übungsmedien nach ./media ausgelagert.

Voller Ablauf im Headless-Browser getestet (Login→Plan→Workout→Stats→
Library→Settings, Feature-Parität) und Standalone-Compose Ende-zu-Ende
(React-Build im Docker, /api-Proxy, geforgter Passkey-Login) verifiziert.
This commit is contained in:
Duarte Santos committed 2026-07-20 15:12:05 +02:00
1 parent 0c237f96dc
commit 7e1d27b218
49 files changed
+3014 -2014

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
import { useEffect } from 'react'
import { HashRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import { useStore } from './store/useStore.js'
import { ACCENTS } from './lib/format.js'
import { setNav } from './lib/nav.js'
import { startFlow } from './sheets.jsx'
import TabBar from './components/TabBar.jsx'
import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import RestTimer from './components/RestTimer.jsx'
import Login from './views/Login.jsx'
import Home from './views/Home.jsx'
import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
import Workout from './views/Workout.jsx'
import Stats from './views/Stats.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Settings from './views/Settings.jsx'
function applyPrefs(theme, accent) {
const de = document.documentElement
de.dataset.theme = theme === 'light' ? 'light' : 'dark'
de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f4f7' : '#0c0e12'
}
function Shell() {
const navigate = useNavigate()
const { S, user, ready } = useStore()
const isGuest = useStore(s => s.isGuest())
useEffect(() => { setNav(navigate) }, [navigate])
useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])
const authed = user || isGuest
if (!ready && !authed) return <div id="app"><div style={{ paddingTop: '42vh', textAlign: 'center', fontSize: '2.2rem' }}>🏋️</div></div>
return (
<>
<div id="app" className="vfade" key={location.hash}>
{!authed ? <Login /> : (
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/plan" element={<Plan />} />
<Route path="/plan/r/:id" element={<RoutineEdit />} />
<Route path="/workout" element={<Workout />} />
<Route path="/stats" element={<Stats />} />
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>
)}
</div>
<TabBar onStart={startFlow} />
<RestTimer />
<Modals />
<Toast />
</>
)
}
export default function App() {
const boot = useStore(s => s.boot)
useEffect(() => { boot() }, [boot])
return <HashRouter><Shell /></HashRouter>
}
+55
View File
@@ -0,0 +1,55 @@
import { useEffect, useRef } from 'react'
import { fmtVol, isoOf, todayISO } from '../lib/format.js'
// GitHub-style activity heatmap, shaded by time trained per day.
export default function Heatmap({ S, onDay }) {
const wrapRef = useRef(null)
useEffect(() => { if (wrapRef.current) wrapRef.current.scrollLeft = wrapRef.current.scrollWidth }, [])
const agg = {}
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 end = new Date(today); end.setDate(today.getDate() - ((today.getDay() + 6) % 7))
const start = new Date(end); start.setDate(end.getDate() - 52 * 7)
const months = [], cols = []
let lastMonth = -1
for (let wk = 0; wk <= 52; wk++) {
const colStart = new Date(start); colStart.setDate(start.getDate() + wk * 7)
const mo = colStart.getMonth()
const showM = mo !== lastMonth && colStart.getDate() <= 7 && wk < 51
months.push(<span key={wk}>{showM ? ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][mo] : ''}</span>)
if (colStart.getDate() <= 7) lastMonth = mo
const cells = []
for (let d = 0; d < 7; d++) {
const day = new Date(colStart); day.setDate(colStart.getDate() + d)
const key = isoOf(day)
const a = agg[key]
const cls = 'hm-c l' + level(a) + (key === todayISO() ? ' today' : '') + (day > today ? ' future' : '')
cells.push(<div key={d} className={cls}
title={key + (a ? ` · ${a.n} workout${a.n > 1 ? 's' : ''} · ${a.min} min · ${fmtVol(a.vol, S.unit)}` : '')}
onClick={a ? () => onDay(key) : undefined} />)
}
cols.push(<div key={wk} className="hm-col">{cells}</div>)
}
return <>
<div className="hm-wrap" ref={wrapRef}>
<div className="hm-months" style={{ marginLeft: 30 }}>{months}</div>
<div className="hm-body">
<div className="hm-days"><span>Mon</span><span /><span>Wed</span><span /><span>Fri</span><span /><span /></div>
<div className="hm-grid">{cols}</div>
</div>
</div>
<div className="hm-legend">Less time <div className="hm-c l0" /><div className="hm-c l1" /><div className="hm-c l2" /><div className="hm-c l3" /><div className="hm-c l4" /> More time</div>
</>
}
+101
View File
@@ -0,0 +1,101 @@
import { useRef, useState } from 'react'
import { fmtNum, fmtDate, MONTHS, isoOf } from '../lib/format.js'
// points: [{ t: ms, y: num, d?: iso }] sorted by t. opts: { h, unit, color, axes, goal }
export default function LineChart({ points, h = 150, unit = '', color = 'var(--acc)', axes = true, goal = null }) {
const svgRef = useRef(null)
const [hover, setHover] = useState(null) // { x, y, iso, v }
if (!points || points.length === 0) return <div className="empty small">No data yet</div>
const W = 340, H = h
const P = { l: axes ? 34 : 8, r: 12, t: 10, b: axes ? 22 : 8 }
const single = points.length === 1
const pts = single ? [points[0], points[0]] : points
const ys = pts.map(p => p.y)
let ymin = Math.min(...ys), ymax = Math.max(...ys)
if (goal != null && isFinite(goal)) { ymin = Math.min(ymin, goal); ymax = Math.max(ymax, goal) }
if (ymin === ymax) { ymin -= 1; ymax += 1 }
const pad = (ymax - ymin) * 0.12; ymin -= pad; ymax += pad
const t0 = pts[0].t, t1 = pts[pts.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)
const gridlines = []
if (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)
gridlines.push(<g key={'y' + v}>
<line x1={P.l} y1={y} x2={W - P.r} y2={y} stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" />
<text x={P.l - 5} y={y + 3.5} textAnchor="end" fontSize="9.5" fill="var(--dim)">{fmtNum(v)}</text>
</g>)
}
const d0 = new Date(t0), d1 = new Date(t1)
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, 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)
gridlines.push(<g key={'x' + i}>
<line x1={x} y1={P.t} x2={x} y2={H - P.b} stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" />
<text x={x} y={H - 7} textAnchor={tk.anchor || 'middle'} fontSize="9.5" fill="var(--dim)">{tk.txt}</text>
</g>)
})
}
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
const last = pts[pts.length - 1]
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y }))
const onMove = e => {
const c = e.touches ? e.touches[0] : e
if (!c || c.clientX === undefined) return
const r = svgRef.current.getBoundingClientRect()
const w = r.width || W
const vx = (c.clientX - r.left) / w * W
let best = hoverPts[0]
hoverPts.forEach(p => { if (Math.abs(p.x - vx) < Math.abs(best.x - vx)) best = p })
setHover(best)
}
return (
<div className="chart-i"
onMouseMove={onMove} onMouseDown={onMove}
onTouchStart={onMove} onTouchMove={onMove}>
<svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ aspectRatio: `${W}/${H}` }}>
<defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={color} stopOpacity=".28" />
<stop offset="1" stopColor={color} stopOpacity="0" />
</linearGradient></defs>
{gridlines}
{goal != null && isFinite(goal) && <>
<line x1={P.l} y1={Y(goal)} x2={W - P.r} y2={Y(goal)} stroke="var(--gold)" strokeWidth="1.6" strokeDasharray="7 4" />
<text x={W - P.r - 2} y={Y(goal) - 5} textAnchor="end" fontSize="9.5" fontWeight="700" fill="var(--gold)">🎯 {fmtNum(goal)}</text>
</>}
<polygon points={`${P.l},${H - P.b} ${poly} ${X(last.t).toFixed(1)},${H - P.b}`} fill={`url(#${gid})`} />
<polyline points={poly} fill="none" stroke={color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
<circle cx={X(last.t)} cy={Y(last.y)} r="4" fill={color} />
{hover && <g>
<line className="cvl" x1={hover.x} y1={P.t} x2={hover.x} y2={H - P.b} stroke="var(--mut)" strokeWidth="1" strokeDasharray="3 3" />
<line className="chl" x1={P.l} y1={hover.y} x2={W - P.r} y2={hover.y} stroke="var(--mut)" strokeWidth="1" strokeDasharray="3 3" />
<circle cx={hover.x} cy={hover.y} r="5" fill={color} stroke="var(--bg)" strokeWidth="2" />
</g>}
</svg>
{hover && <div className="ctip" style={{ left: `calc(${hover.x / W * 100}% - 55px)` }}>
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}
</div>}
</div>
)
}
+17
View File
@@ -0,0 +1,17 @@
import { useState } from 'react'
import { imgSrc, gifSrc } from '../lib/exercises.js'
// Big autoplaying animation; tap toggles to the still frame.
export default function Media({ ex, id }) {
const [playing, setPlaying] = useState(true)
return (
<div className="exmedia" id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={ex.n} />
<span className="gifhint">{playing ? '⏸ tap to pause' : '▶ tap to play'}</span>
</div>
)
}
export function Thumb({ ex }) {
return <img className="thumb" loading="lazy" decoding="async" src={imgSrc(ex)} alt="" />
}
+82
View File
@@ -0,0 +1,82 @@
import { useEffect, useRef } from 'react'
import { useUI } from '../store/useUI.js'
// One bottom sheet (or centered dialog) with swipe-to-dismiss.
function Sheet({ sheet }) {
const { closeSheet } = useUI()
const ref = useRef(null)
const drag = useRef({ startY: null, delta: 0 })
const onTouchStart = e => {
const el = ref.current
drag.current = { startY: el.scrollTop <= 0 ? e.touches[0].clientY : null, delta: 0 }
}
const onTouchMove = e => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.touches[0].clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
e.preventDefault()
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
}
const onTouchEnd = () => {
const el = ref.current, d = drag.current
if (d.startY === null) return
el.style.transition = 'transform .2s'
if (d.delta > 90 && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
else el.style.transform = ''
d.startY = null
}
// non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref)
useEffect(() => {
const el = ref.current
if (!el) return
el.addEventListener('touchmove', onTouchMove, { passive: false })
return () => el.removeEventListener('touchmove', onTouchMove)
}, [])
const close = () => closeSheet(sheet.id)
if (sheet.kind === 'center') {
return (
<div>
<div className="mback" onClick={() => { if (!sheet.locked) close() }} />
<div className="center">{sheet.render(close)}</div>
</div>
)
}
return (
<div>
<div className="mback" onClick={() => { if (!sheet.locked) close() }} />
<div className="sheet" ref={ref} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
<div className="grab" />
{sheet.render(close)}
</div>
</div>
)
}
export default function Modals() {
const sheets = useUI(s => s.sheets)
// lock the page behind any open sheet (iOS-safe)
useEffect(() => {
if (!sheets.length) return
const y = window.scrollY || 0
const b = document.body.style
b.position = 'fixed'; b.top = -y + 'px'; b.left = '0'; b.right = '0'; b.width = '100%'
return () => {
b.position = b.top = b.left = b.right = b.width = ''
window.scrollTo(0, y)
}
}, [sheets.length > 0])
if (!sheets.length) return null
return (
<div id="modal-root" className="open">
{sheets.map(s => <Sheet key={s.id} sheet={s} />)}
</div>
)
}
+16
View File
@@ -0,0 +1,16 @@
import { useUI } from '../store/useUI.js'
export default function RestTimer() {
const timer = useUI(s => s.timer)
const { addRest, stopRest } = useUI()
if (!timer) return null
const pct = (timer.left / timer.total) * 100
const m = Math.floor(timer.left / 60), s = String(timer.left % 60).padStart(2, '0')
return (
<div id="timer">
<div className="t">{m}:{s}</div>
<div className="bar"><i style={{ width: pct + '%' }} /></div>
<button className="btn sm" onClick={() => addRest(15)}>+15s</button>
<button className="btn sm primary" onClick={stopRest}>Skip</button>
</div>
)
}
+24
View File
@@ -0,0 +1,24 @@
// Number field with −/+ buttons; tapping the field selects its content so typing replaces.
export default function Stepper({ value, step = 1, onChange, decimal = true, className = '', label }) {
const set = v => onChange(Math.max(0, Math.round((v || 0) * 100) / 100))
const inner = (
<div className={'step ' + className}>
<button onClick={() => set((+value || 0) - step)}>−</button>
<input
type="number"
inputMode={decimal ? 'decimal' : 'numeric'}
value={value}
onFocus={e => e.target.select()}
onChange={e => onChange(e.target.value === '' ? 0 : Math.max(0, parseFloat(e.target.value) || 0))}
/>
<button onClick={() => set((+value || 0) + step)}>+</button>
</div>
)
if (!label) return inner
return (
<div>
<div className="small muted" style={{ marginBottom: 5, textAlign: 'center' }}>{label}</div>
{inner}
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import { useLocation, useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine } from '../lib/history.js'
import { todayISO } from '../lib/format.js'
const ICONS = {
home: <path d="M3 10.5 12 3l9 7.5M5 9.5V21h14V9.5" />,
plan: <><rect x="3" y="5" width="18" height="16" rx="2" /><path d="M8 3v4M16 3v4M3 11h18" /></>,
stats: <path d="M4 20V10M10 20V4M16 20v-8M22 20H2" />,
library: <><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></>
}
export default function TabBar({ onStart }) {
const nav = useNavigate()
const loc = useLocation()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const isGuest = useStore(s => s.isGuest())
if (!user && !isGuest) return null
const cur = loc.pathname.split('/')[1] || 'home'
const on = k => cur === k || (cur === 'history' && k === 'stats') || (cur === 'settings' && k === 'home')
const startWorkout = () => {
if (!S.active) {
const r = effectiveRoutine(S, todayISO())
if (r && r.ex.length) { onStart(r.id); return }
}
nav('/workout')
}
const Icon = ({ k }) => <svg viewBox="0 0 24 24">{ICONS[k]}</svg>
return (
<nav id="tabbar">
<button className={on('home') ? 'on' : ''} onClick={() => nav('/home')}><Icon k="home" /><span>Home</span></button>
<button className={on('plan') ? 'on' : ''} onClick={() => nav('/plan')}><Icon k="plan" /><span>Plan</span></button>
<button className={'start' + (S.active ? ' rec' : '')} onClick={startWorkout}>
<span className="cir"><svg viewBox="0 0 24 24"><path d="M6.5 6.5v11M17.5 6.5v11M2.5 9.5v5M21.5 9.5v5M6.5 12h11" /></svg></span>
<span>{S.active ? 'Resume' : 'Start'}</span>
</button>
<button className={on('stats') ? 'on' : ''} onClick={() => nav('/stats')}><Icon k="stats" /><span>Stats</span></button>
<button className={on('library') ? 'on' : ''} onClick={() => nav('/library')}><Icon k="library" /><span>Exercises</span></button>
</nav>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { useUI } from '../store/useUI.js'
export default function Toast() {
const msg = useUI(s => s.toastMsg)
return <div id="toast" className={msg ? 'show' : ''}>{msg}</div>
}
+308
View File
@@ -0,0 +1,308 @@
/* openGym — mobile-first dark theme */
:root{
--bg:#0c0e12; --bg2:#14171d; --card:#1a1e26; --card2:#222733;
--line:#2b3140; --txt:#eef1f6; --mut:#8b94a7; --dim:#5c6475;
--acc:#a3e635; --acc2:#84cc16; --accT:rgba(163,230,53,.14);
--blue:#60a5fa; --orange:#fb923c; --red:#f87171; --gold:#fbbf24;
--r:16px; --pad:16px;
--sab:env(safe-area-inset-bottom,0px); --sat:env(safe-area-inset-top,0px);
}
/* light theme (per-account setting, synced) */
:root[data-theme="light"]{
--bg:#f2f4f7; --bg2:#e7eaef; --card:#ffffff; --card2:#eef0f4;
--line:#d9dee6; --txt:#171b22; --mut:#5b6474; --dim:#98a0af;
}
/* accent palettes (per-account setting) */
:root[data-accent="sky"]{--acc:#38bdf8;--acc2:#0ea5e9}
:root[data-accent="orange"]{--acc:#fb923c;--acc2:#f97316}
:root[data-accent="violet"]{--acc:#a78bfa;--acc2:#8b5cf6}
:root[data-accent="pink"]{--acc:#f472b6;--acc2:#ec4899}
:root[data-accent="red"]{--acc:#f87171;--acc2:#ef4444}
:root[data-accent="teal"]{--acc:#2dd4bf;--acc2:#14b8a6}
:root[data-accent="gold"]{--acc:#fbbf24;--acc2:#f59e0b}
:root{--accT:color-mix(in srgb, var(--acc) 16%, transparent)}
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
button,.chip,.tile,.item,.wday,.cal-d,.ck,.swatch,.emoji-cell,.hm-c,#tabbar,.step{-webkit-user-select:none;user-select:none}
@keyframes viewfade{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
#app.vfade{animation:viewfade .18s ease}
@media (prefers-reduced-motion: reduce){*{animation:none!important;transition:none!important}}
html{font-size:16px}
body{
background:var(--bg); color:var(--txt);
font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,sans-serif;
min-height:100vh; overscroll-behavior-y:none;
-webkit-font-smoothing:antialiased; touch-action:manipulation;
}
button{font:inherit;color:inherit;background:none;border:none;cursor:pointer}
input,select,textarea{font:inherit;color:var(--txt)}
img{max-width:100%}
a{color:var(--acc)}
/* bottom padding clears the tab bar AND its raised center button */
#app{padding:calc(var(--sat) + 10px) var(--pad) calc(124px + var(--sab)); max-width:560px; margin:0 auto}
/* ---------- header ---------- */
.hdr{display:flex;align-items:center;justify-content:space-between;margin:6px 0 16px}
.hdr h1{font-size:1.7rem;font-weight:800;letter-spacing:-.02em}
.hdr .sub{color:var(--mut);font-size:.86rem;margin-top:2px}
.iconbtn{width:42px;height:42px;border-radius:12px;background:var(--card);border:1px solid var(--line);
display:flex;align-items:center;justify-content:center;font-size:1.15rem;flex:none}
.iconbtn:active{background:var(--card2)}
/* ---------- cards ---------- */
.card{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:16px;margin-bottom:14px}
.card h2{font-size:.8rem;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);font-weight:700;margin-bottom:10px}
.card .big{font-size:1.9rem;font-weight:800;letter-spacing:-.02em}
.row{display:flex;align-items:center;gap:12px}
.row.between{justify-content:space-between}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.muted{color:var(--mut)} .dim{color:var(--dim)} .small{font-size:.82rem}
.accent{color:var(--acc)}
/* ---------- buttons ---------- */
.btn{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
padding:15px;border-radius:14px;font-weight:700;font-size:1rem;
background:var(--card2);border:1px solid var(--line);transition:transform .08s}
.btn:active{transform:scale(.97)}
.btn.primary{background:var(--acc);color:#111;border:none}
.btn.danger{background:rgba(248,113,113,.12);color:var(--red);border-color:rgba(248,113,113,.3)}
.btn.ghost{background:none}
.btn.sm{padding:9px 14px;width:auto;font-size:.86rem;border-radius:11px}
.btn:disabled{opacity:.4}
/* ---------- tab bar ---------- */
#tabbar{position:fixed;left:0;right:0;bottom:0;z-index:50;
background:rgba(16,18,24,.88);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);
border-top:1px solid var(--line);
}
:root[data-theme="light"] #tabbar{background:rgba(255,255,255,.86)}
#tabbar{
display:flex;justify-content:space-around;align-items:flex-end;
padding:8px 6px calc(8px + var(--sab))}
#tabbar button{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
color:var(--dim);font-size:.62rem;font-weight:600;padding-top:4px}
#tabbar button svg{width:23px;height:23px;fill:none;stroke:currentColor;stroke-width:1.9;stroke-linecap:round;stroke-linejoin:round}
#tabbar button.on{color:var(--txt)}
#tabbar button.start{margin-top:-26px}
#tabbar button.start .cir{width:58px;height:58px;border-radius:50%;background:var(--acc);
display:flex;align-items:center;justify-content:center;box-shadow:0 6px 20px rgba(163,230,53,.35);
box-shadow:0 6px 20px color-mix(in srgb, var(--acc) 45%, transparent)}
#tabbar button.start .cir svg{width:26px;height:26px;stroke:#111;stroke-width:2.2}
#tabbar button.start span{color:var(--acc)}
#tabbar button.start.rec .cir{background:var(--orange);box-shadow:0 6px 20px rgba(251,146,60,.4);animation:pulse 1.6s infinite}
#tabbar button.start.rec span{color:var(--orange)}
@keyframes pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.06)}}
/* ---------- week strip ---------- */
.week{display:flex;justify-content:space-between;gap:6px}
.wday{flex:1;text-align:center;padding:9px 2px 10px;border-radius:12px;background:var(--bg2);border:1px solid transparent}
.wday .lbl{font-size:.62rem;color:var(--dim);font-weight:700;text-transform:uppercase}
.wday .num{font-size:.95rem;font-weight:700;margin:3px 0}
.wday .dot{width:7px;height:7px;border-radius:50%;background:var(--line);margin:0 auto}
.wday .dot.plan{background:var(--blue)}
.wday .dot.ovr{background:var(--orange)}
.wday .dot.done{background:var(--acc)}
.wday:active{background:var(--card2)}
.wday.today{border-color:var(--acc);background:var(--accT)}
/* ---------- lists ---------- */
.list{display:flex;flex-direction:column;gap:10px}
.item{display:flex;align-items:center;gap:12px;background:var(--card);border:1px solid var(--line);
border-radius:14px;padding:12px;min-height:60px}
.item:active{background:var(--card2)}
.thumb{width:52px;height:52px;border-radius:10px;object-fit:cover;background:#fff;flex:none}
.item .tt{font-weight:600;font-size:.93rem;line-height:1.25;text-transform:capitalize}
.item .ss{color:var(--mut);font-size:.78rem;margin-top:2px;text-transform:capitalize}
.item .grow{flex:1;min-width:0}
.chev{color:var(--dim);flex:none}
.tag{display:inline-block;background:var(--bg2);border:1px solid var(--line);color:var(--mut);
border-radius:99px;padding:2px 9px;font-size:.7rem;font-weight:600;text-transform:capitalize}
.tag.acc{background:var(--accT);border-color:transparent;color:var(--acc)}
/* ---------- chips ---------- */
.chips{display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;scrollbar-width:none;-webkit-overflow-scrolling:touch}
.chips::-webkit-scrollbar{display:none}
.chip{flex:none;padding:8px 14px;border-radius:99px;background:var(--card);border:1px solid var(--line);
font-size:.82rem;font-weight:600;color:var(--mut);text-transform:capitalize}
.chip.on{background:var(--acc);color:#111;border-color:var(--acc)}
/* ---------- inputs ---------- */
.input{width:100%;background:var(--bg2);border:1px solid var(--line);border-radius:12px;
padding:13px 14px;font-size:1rem;outline:none}
.input:focus{border-color:var(--acc)}
.search{position:relative}
.search .input{padding-left:40px}
.search svg{position:absolute;left:13px;top:50%;transform:translateY(-50%);width:17px;height:17px;
stroke:var(--dim);fill:none;stroke-width:2;stroke-linecap:round}
/* stepper */
.step{display:flex;align-items:center;gap:2px;background:var(--bg2);border:1px solid var(--line);border-radius:12px}
.step button{width:38px;height:44px;font-size:1.25rem;color:var(--mut);flex:none}
.step input{width:58px;text-align:center;background:none;border:none;font-size:1.05rem;font-weight:700;outline:none;
-moz-appearance:textfield;appearance:textfield}
.step input::-webkit-inner-spin-button{display:none}
/* ---------- workout ---------- */
.wprog{height:5px;background:var(--bg2);border-radius:99px;overflow:hidden;margin-bottom:14px}
.wprog i{display:block;height:100%;background:var(--acc);border-radius:99px;transition:width .3s}
.exmedia{position:relative;border-radius:var(--r);overflow:hidden;background:#fff;margin-bottom:12px}
.exmedia img{width:100%;height:340px;object-fit:contain;display:block}
.exmedia .gifhint{position:absolute;right:10px;bottom:10px;background:rgba(0,0,0,.62);color:#fff;
border-radius:99px;padding:4px 11px;font-size:.72rem;font-weight:600}
.sethead{display:flex;align-items:center;gap:9px;padding-bottom:2px;
font-size:.66rem;color:var(--dim);font-weight:700;text-transform:uppercase;letter-spacing:.05em}
.sethead .n-sp{width:26px;flex:none}
.sethead .w-sp{flex:1.4;text-align:center}
.sethead .r-sp{flex:1;text-align:center}
.sethead .ck-sp{width:44px;flex:none}
.setrow{display:flex;align-items:center;gap:9px;padding:9px 0;border-bottom:1px solid var(--bg2)}
.setrow:last-child{border-bottom:none}
.setrow .n{width:26px;height:26px;border-radius:50%;background:var(--bg2);color:var(--mut);
display:flex;align-items:center;justify-content:center;font-size:.78rem;font-weight:700;flex:none}
.setrow .step.w{flex:1.4;min-width:0}
.setrow .step.r{flex:1;min-width:0}
.setrow .step button{width:32px;flex:none}
.setrow .step input{width:100%;min-width:0}
.setrow.done .n{background:var(--acc);color:#111}
.setrow.done{opacity:.55}
.ck{width:44px;height:44px;border-radius:12px;background:var(--bg2);border:1px solid var(--line);
display:flex;align-items:center;justify-content:center;flex:none}
.ck svg{width:20px;height:20px;stroke:var(--dim);fill:none;stroke-width:2.5;stroke-linecap:round;stroke-linejoin:round}
.ck.on{background:var(--acc);border-color:var(--acc)}
.ck.on svg{stroke:#111}
/* rest timer */
#timer{position:fixed;left:14px;right:14px;bottom:calc(92px + var(--sab));z-index:60;
background:var(--card2);border:1px solid var(--acc);border-radius:16px;padding:13px 16px;
display:flex;align-items:center;gap:14px;box-shadow:0 10px 30px rgba(0,0,0,.5);
animation:slideup .25s}
@keyframes slideup{from{transform:translateY(20px);opacity:0}to{transform:none;opacity:1}}
#timer .t{font-size:1.5rem;font-weight:800;font-variant-numeric:tabular-nums;min-width:74px}
#timer .bar{flex:1;height:5px;background:var(--bg);border-radius:99px;overflow:hidden}
#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}
/* ---------- modal ---------- */
#modal-root{position:fixed;inset:0;z-index:100;display:none}
#modal-root.open{display:block}
.mback{position:absolute;inset:0;background:rgba(0,0,0,.6);backdrop-filter:blur(3px);
touch-action:none;overscroll-behavior:none}
.sheet{position:absolute;left:0;right:0;bottom:0;background:var(--bg2);
border-radius:22px 22px 0 0;padding:10px 18px calc(22px + var(--sab));
max-height:88vh;overflow-y:auto;-webkit-overflow-scrolling:touch;animation:slideup .28s;
overscroll-behavior:contain;touch-action:pan-y;will-change:transform}
.sheet .grab{width:40px;height:4px;border-radius:99px;background:var(--line);margin:4px auto 14px}
.sheet h3{font-size:1.15rem;font-weight:800;margin-bottom:12px}
.center{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(88vw,360px);
background:var(--bg2);border:1px solid var(--line);border-radius:20px;padding:22px}
/* emoji grid picker */
.emoji-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:8px}
.emoji-cell{font-size:1.9rem;padding:10px 0;border-radius:14px;background:var(--card);
border:1px solid var(--line);line-height:1}
.emoji-cell:active{background:var(--card2)}
.emoji-cell.on{background:var(--accT);border-color:var(--acc)}
/* big weight input */
.bwin{display:flex;align-items:baseline;justify-content:center;gap:8px;margin:18px 0}
.bwin input{width:150px;background:none;border:none;outline:none;text-align:right;
font-size:3.2rem;font-weight:800;letter-spacing:-.03em;color:var(--txt)}
.bwin span{color:var(--mut);font-size:1.2rem;font-weight:600}
/* ---------- charts ---------- */
.chart{width:100%;overflow:hidden}
.chart svg{display:block;width:100%;height:auto}
.chart-i{position:relative;touch-action:pan-y}
.ctip{position:absolute;top:-4px;background:var(--card2);border:1px solid var(--line);
border-radius:99px;padding:4px 12px;font-size:.76rem;font-weight:700;white-space:nowrap;
pointer-events:none;box-shadow:0 4px 14px rgba(0,0,0,.4)}
/* activity heatmap (GitHub-style) */
.hm-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;padding-bottom:2px}
.hm-wrap::-webkit-scrollbar{display:none}
.hm-months{display:flex;margin-left:30px;margin-bottom:4px}
.hm-months span{flex:none;width:14px;font-size:.62rem;color:var(--dim);white-space:nowrap;overflow:visible}
.hm-body{display:flex}
.hm-days{display:flex;flex-direction:column;gap:3px;flex:none;width:30px}
.hm-days span{height:11px;font-size:.6rem;color:var(--dim);line-height:11px}
.hm-grid{display:flex;gap:3px}
.hm-col{display:flex;flex-direction:column;gap:3px}
.hm-c{width:11px;height:11px;border-radius:3px;background:var(--bg2);flex:none}
.hm-c.l1{background:#33451b;background:color-mix(in srgb, var(--acc) 28%, var(--bg2))}
.hm-c.l2{background:#527221;background:color-mix(in srgb, var(--acc) 52%, var(--bg2))}
.hm-c.l3{background:#7aa629;background:color-mix(in srgb, var(--acc) 76%, var(--bg2))}
.hm-c.l4{background:var(--acc)}
.hm-c.today{outline:1.5px solid var(--txt);outline-offset:-1.5px}
.hm-c.future{opacity:.28}
.hm-legend{display:flex;align-items:center;gap:4px;justify-content:flex-end;margin-top:8px;
font-size:.65rem;color:var(--dim)}
.hm-legend .hm-c{width:10px;height:10px}
/* stat tiles */
.tiles{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px}
.tile{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:14px}
.tile .v{font-size:1.45rem;font-weight:800;letter-spacing:-.02em;margin-top:2px}
.tile .l{color:var(--mut);font-size:.72rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em}
/* PR badge */
.pr{display:inline-flex;align-items:center;gap:4px;background:rgba(251,191,36,.15);color:var(--gold);
border-radius:99px;padding:3px 10px;font-size:.72rem;font-weight:700}
/* toast */
#toast{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(100px + var(--sab));z-index:200;
background:var(--card2);border:1px solid var(--line);border-radius:99px;padding:10px 20px;
font-size:.88rem;font-weight:600;box-shadow:0 8px 24px rgba(0,0,0,.5);
opacity:0;pointer-events:none;transition:opacity .25s}
#toast.show{opacity:1}
/* misc */
.empty{text-align:center;color:var(--mut);padding:34px 16px;font-size:.9rem;line-height:1.5}
.empty .ico{font-size:2.4rem;margin-bottom:10px}
.divider{height:1px;background:var(--line);margin:12px 0}
.capitalize{text-transform:capitalize}
h4.sec{font-size:.8rem;text-transform:uppercase;letter-spacing:.08em;color:var(--mut);margin:20px 0 10px;font-weight:700}
.steps-list{padding-left:20px;color:var(--mut);font-size:.9rem;line-height:1.55;display:flex;flex-direction:column;gap:8px}
/* month calendar sheet */
.cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;margin-top:12px}
.cal-h{text-align:center;font-size:.64rem;color:var(--dim);font-weight:700;text-transform:uppercase;padding:2px 0}
.cal-d{aspect-ratio:1;border-radius:12px;background:var(--card);border:1px solid var(--line);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;
font-weight:600;font-size:.88rem;color:var(--txt)}
.cal-d:active{background:var(--card2)}
.cal-d.has{background:var(--accT);border-color:var(--acc)}
.cal-d.today{border-color:var(--txt);border-width:2px}
.cal-d i{width:6px;height:6px;border-radius:50%;background:transparent}
.cal-d i.done{background:var(--acc)}
.cal-d i.plan{background:var(--blue)}
.cal-d i.ovr{background:var(--orange)}
.cal-legend{display:flex;gap:14px;justify-content:center;margin-top:12px;font-size:.7rem;color:var(--dim)}
.cal-legend i{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px}
.tile.tappable:active{background:var(--card2)}
/* accent swatches (settings) */
.swatches{display:flex;gap:10px;flex-wrap:wrap}
.swatch{width:36px;height:36px;border-radius:50%;border:3px solid transparent;flex:none}
.swatch.on{border-color:var(--txt)}
/* ---------- desktop (≥1000px): wide dashboard layout ---------- */
.cols{display:block}
@media (min-width:1000px){
#app{max-width:1080px;padding-top:28px}
.cols{display:grid;grid-template-columns:1fr 1fr;gap:14px;align-items:start}
.cols>*{min-width:0}
#app .list{display:grid;grid-template-columns:1fr 1fr;gap:10px}
#modal-root .list,.narrow .list{display:flex;flex-direction:column}
.narrow{max-width:640px;margin:0 auto}
.tiles{grid-template-columns:repeat(4,1fr)}
.cols .tiles{grid-template-columns:1fr 1fr}
#tabbar{left:50%;right:auto;bottom:14px;transform:translateX(-50%);width:560px;
border:1px solid var(--line);border-radius:22px;padding:8px 10px 10px}
#tabbar button.start{margin-top:-30px}
/* margin centering (not transform) — JS drag animates transform:translateY */
.sheet{left:50%;right:auto;margin-left:-320px;width:640px;border-radius:22px 22px 0 0}
.center{width:360px}
#timer{left:50%;right:auto;margin-left:-260px;width:520px;bottom:110px}
.exmedia img{height:400px}
.hm-wrap{display:flex;flex-direction:column;align-items:center}
}
+59
View File
@@ -0,0 +1,59 @@
// Backend + WebAuthn helpers (ported from the vanilla app).
export const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)
export const IS_ANDROID = /Android/.test(navigator.userAgent)
export const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint or face unlock' : 'your fingerprint, face or PIN'
export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager'
export const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials)
export 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
}
export 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
}
export 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
}
+1
View File
@@ -0,0 +1 @@
export const EXDB=[{"id":"0001","n":"3/4 sit-up","bp":"waist","eq":"body weight","tg":"abs","mg":"hip flexors","sm":["hip flexors","lower back"],"st":["Lie flat on your back with your knees bent and feet flat on the ground.","Place your hands behind your head with your elbows pointing outwards.","Engaging your abs, slowly lift your upper body off the ground, curling forward until your torso is at a 45-degree angle.","Pause for a moment at the top, then slowly lower your upper body back down to the starting position.","Repeat for the desired number of repetitions."],"img":"0001-2gPfomN.jpg","gif":"0001-2gPfomN.gif"},{"id":"0002","n":"45° side bend","bp":"waist","eq":"body weight","tg":"abs","mg":"obliques","sm":["obliques"],"st":["Stand with your feet shoulder-width apart and your arms extended straight down by your sides.","Keeping your back straight and your core engaged, slowly bend your torso to one side, lowering your hand towards your knee.","Pause for a moment at the bottom, then slowly return to the starting position.","Repeat on the other side.","Continue alternating sides for the desired number of repetitions."],"img":"0002-Hy9D21L.jpg","gif":"0002-Hy9D21L.gif"},{"id":"0003","n":"air bike","bp":"waist","eq":"body weight","tg":"abs","mg":"hip flexors","sm":["hip flexors"],"st":["Lie flat on your back with your hands placed behind your head.","Lift your legs off the ground and bend your knees at a 90-degree angle.","Bring your right elbow towards your left knee while simultaneously straightening your right leg.","Return to the starting position and repeat the movement on the opposite side, bringing your left elbow towards your right knee while straightening your left leg.","Continue alternating sides in a pedaling motion for the desired number of repetitions."],"img":"0003-1ZFqTDN.jpg","gif":"0003-1ZFqTDN.gif"},{"id":"1512","n":"all fours squad stretch","bp":"upper legs","eq":"body weight","tg":"quads","mg":"hamstrings","sm":["hamstrings","glutes"],"st":["Start on all fours with your hands directly under your shoulders and your knees directly under your hips.","Extend one leg straight back, keeping your knee bent and your foot flexed.","Slowly lower your hips towards the ground, feeling a stretch in your quads.","Hold this position for 20-30 seconds.","Switch legs and repeat the stretch on the other side."],"img":"1512-qBcKorM.jpg","gif":"1512-qBcKorM.gif"},{"id":"0006","n":"alternate heel touchers","bp":"waist","eq":"body weight","tg":"abs","mg":"obliques","sm":["obliques"],"st":["Lie flat on your back with your knees bent and feet flat on the ground.","Extend your arms straight out to the sides, parallel to the ground.","Engaging your abs, lift your shoulders off the ground and reach your right hand towards your right heel.","Return to the starting position and repeat on the left side, reaching your left hand towards your left heel.","Continue alternating sides for the desired number of repetitions."],"img":"0006-qaZVsGk.jpg","gif":"0006-qaZVsGk.gif"},{"id":"0007","n":"alternate lateral pulldown","bp":"back","eq":"cable","tg":"lats","mg":"biceps","sm":["biceps","rhomboids"],"st":["Sit on the cable machine with your back straight and feet flat on the ground.","Grasp the handles with an overhand grip, slightly wider than shoulder-width apart.","Lean back slightly and pull the handles towards your chest, squeezing your shoulder blades together.","Pause for a moment at the peak of the movement, then slowly release the handles back to the starting position.","Repeat for the desired number of repetitions."],"img":"0007-4IKbhHV.jpg","gif":"0007-4IKbhHV.gif"},{"id":"1368","n":"ankle circles","bp":"lower legs","eq":"body weight","tg":"calves","mg":"ankle stabilizers","sm":["ankle stabilizers"],"st":["Sit on the ground with your legs extended in front of you.","Lift one leg off the ground and rotate your ankle in a circular motion.","Perform the desired number of circles in one direction, then switch to the other direction.","Repeat with the other leg."],"img":"1368-uL9CsKm.jpg","gif":"1368-uL9CsKm.gif"},{"id":"3293","n":"archer pull up","bp":"back","eq":"body weight","tg":"lats","mg":"biceps","sm":["biceps","forearms"],"st":["Start by hanging from a pull-up bar with an overhand grip, slightly wider than shoulder-width apart.","Engage your core and pull your shoulder blades down and back.","As you pull yourself up, bend one arm and bring your elbow towards your side, while keeping the other arm straight.","Continue pulling until your chin is above the bar and your bent arm is fully flexed.","Lower yourself back down with control, straightening the bent arm and repeating the movement on the other side.","Alternate sides with each repetition."],"img":"3293-72BC5Za.jpg","gif":"3293-72BC5Za.gif"},{"id":"3294","n":"archer push up","bp":"chest","eq":"body weight","tg":"pectorals","mg":"triceps","sm":["triceps","shoulders","core"],"st":["Start in a push-up position with your hands slightly wider than shoulder-widLine truncated
+9
View File
@@ -0,0 +1,9 @@
import { EXDB } from './exercises-data.js'
export { EXDB }
export const EXIDX = {}
EXDB.forEach(e => { EXIDX[e.id] = e })
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
export const imgSrc = ex => 'img/' + ex.img
export const gifSrc = ex => 'gif/' + ex.gif
+35
View File
@@ -0,0 +1,35 @@
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
export const todayISO = () => {
const d = new Date()
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
}
export const isoOf = d =>
d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
export const DAYN = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
export const DAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
export const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
export const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
export 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' })
}
export function fmtDur(ms) {
const m = Math.floor(ms / 60000)
return m >= 60 ? Math.floor(m / 60) + 'h ' + (m % 60) + 'm' : m + ' min'
}
export const fmtNum = n => (Math.round(n * 10) / 10).toLocaleString('en-CH')
export const fmtVol = (v, unit) => (v >= 10000 ? fmtNum(v / 1000) + 't' : fmtNum(v) + ' ' + unit)
export function weekKey(d) {
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
}
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
export const ACCENTS = { lime: '#a3e635', sky: '#38bdf8', orange: '#fb923c', violet: '#a78bfa', pink: '#f472b6', red: '#f87171', teal: '#2dd4bf', gold: '#fbbf24' }
+72
View File
@@ -0,0 +1,72 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey } from './format.js'
export function lastEntryFor(S, 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
}
export function bestWeightFor(S, 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
}
export function effectiveRoutineId(S, 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
}
export function effectiveRoutine(S, iso) {
const id = effectiveRoutineId(S, iso)
return id ? S.routines.find(r => r.id === id) || null : null
}
export function buildSets(S, cfg) {
const last = lastEntryFor(S, cfg.id)
const conf = S.exWeights[cfg.id]
const sets = []
for (let i = 0; i < cfg.sets; i++) {
const prev = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null
const w = conf && conf.w > 0 ? conf.w : (prev ? prev.w : cfg.weight)
sets.push({ w, r: prev ? prev.r : cfg.reps, done: false })
}
return sets
}
export 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
}
export function setsDone(w) {
let n = 0
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++ }))
return n
}
export function setsDoneActive(A) {
let n = 0
if (A) A.entries.forEach(e => e.sets.forEach(s => { if (s.done) n++ }))
return n
}
export const lastBW = S => (S.bodyweight.length ? S.bodyweight[S.bodyweight.length - 1] : null)
export function streakWeeks(S) {
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 wk = weekKey(isoOf(cur))
if (weeks.has(wk)) streak++
else if (i > 0) break
cur.setDate(cur.getDate() - 7)
}
return streak
}
+4
View File
@@ -0,0 +1,4 @@
// Lets non-component modules (sheet flows) navigate. App registers the router's navigate.
let _nav = () => {}
export const setNav = fn => { _nav = fn }
export const nav = to => _nav(to)
+17
View File
@@ -0,0 +1,17 @@
// WebAudio beeps + haptics (ported from the vanilla app). `enabled` gates sound.
let audioCtx = null
export function beep(enabled, freq, dur, when) {
if (!enabled) 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) { /* */ }
}
export function vibrate(p) { try { navigator.vibrate && navigator.vibrate(p) } catch (e) { /* */ } }
+12
View File
@@ -0,0 +1,12 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
import './index.css'
createRoot(document.getElementById('root')).render(
<StrictMode><App /></StrictMode>
)
if ('serviceWorker' in navigator && location.protocol === 'https:') {
navigator.serviceWorker.register('sw.js').catch(() => {})
}
+413
View File
@@ -0,0 +1,413 @@
import { useEffect, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS } from './lib/exercises.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, todayISO, uid, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW } from './lib/history.js'
import { beep, vibrate } from './lib/sound.js'
import { nav } from './lib/nav.js'
import Media, { Thumb } from './components/Media.jsx'
import Stepper from './components/Stepper.jsx'
const S = () => useStore.getState().S
const update = (...a) => useStore.getState().update(...a)
const ui = () => useUI.getState()
const toast = m => ui().toast(m)
const snd = () => S().sound
/* ============================ starter plan ============================ */
export function loadStarterPlan() {
const mk = (name, emoji, list) => ({ id: uid(), name, emoji, ex: list.map(([id, sets, reps]) => ({ id, sets, reps, weight: 0 })) })
update(st => {
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]])
st.routines.push(push, pull, legs)
st.week[1] = push.id; st.week[3] = pull.id; st.week[5] = legs.id
})
toast('Starter plan loaded — Mon Push · Wed Pull · Fri Legs')
}
/* ============================ body weight ============================ */
function BwSheet({ required, onDone, close }) {
const bw = lastBW(S())
const [v, setV] = useState(bw ? String(bw.w) : '')
const ref = useRef(null)
useEffect(() => { setTimeout(() => { ref.current?.focus(); ref.current?.select() }, 250) }, [])
const save = () => {
const n = parseFloat(v)
if (!n || n <= 0 || n > 400) { toast('Enter a valid weight'); return }
update(st => {
const iso = todayISO()
const ex = st.bodyweight.find(b => b.d === iso)
if (ex) { ex.w = n; ex.t = Date.now() } else st.bodyweight.push({ d: iso, w: n, t: Date.now() })
st.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
})
close()
if (onDone) onDone(n); else toast('Weight saved ✓')
}
return <>
<h3>{required ? 'Quick check-in ⚖️' : 'Log body weight'}</h3>
<div className="muted small">{required ? 'Step on the scale — tracked before every workout so your curve stays honest.' : 'Today, ' + fmtDate(todayISO(), true)}</div>
<div className="bwin"><input ref={ref} type="number" inputMode="decimal" step="0.1" value={v} onChange={e => setV(e.target.value)} placeholder="0.0" /><span>{S().unit}</span></div>
<button className="btn primary" onClick={save}>{required ? 'Save & start workout' : 'Save'}</button>
{required && <>
<div style={{ height: 8 }} /><button className="btn ghost dim" onClick={() => { close(); onDone && onDone(null) }}>Skip today</button>
<div style={{ height: 2 }} /><button className="btn ghost dim" onClick={() => { close(); nav('/workout') }}>↺ Choose a different workout</button>
</>}
</>
}
export function bwSheet(opts = {}) {
const h = ui().openSheet(close => <BwSheet {...opts} close={close} />, { locked: !!opts.required })
return h
}
/* ============================ target weight ============================ */
export function bwDeltaColor(delta, currentW) {
if (!delta) return 'var(--mut)'
if (!S().targetW) return 'var(--txt)'
const up = S().targetW > currentW
return (delta > 0) === up ? 'var(--acc)' : 'var(--red)'
}
function GoalSheet({ close }) {
const st = S()
const bw = lastBW(st)
const [v, setV] = useState(st.targetW || (bw ? String(bw.w) : ''))
const ref = useRef(null)
useEffect(() => { setTimeout(() => { ref.current?.focus(); ref.current?.select() }, 250) }, [])
return <>
<h3>Target weight 🎯</h3>
<div className="muted small">Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.</div>
<div className="bwin"><input ref={ref} type="number" inputMode="decimal" step="0.5" value={v} onChange={e => setV(e.target.value)} placeholder="0.0" /><span>{st.unit}</span></div>
<button className="btn primary" onClick={() => {
const n = parseFloat(v)
if (!n || n <= 0 || n > 400) { toast('Enter a valid weight'); return }
update(s => { s.targetW = n }); close()
const b = lastBW(S()); toast('Goal set: ' + fmtNum(n) + ' ' + st.unit + (b ? ' (' + fmtNum(Math.abs(n - b.w)) + ' to go)' : ''))
}}>Save goal</button>
{st.targetW && <><div style={{ height: 8 }} /><button className="btn danger" onClick={() => { update(s => { s.targetW = null }); close(); toast('Goal removed') }}>Remove goal</button></>}
</>
}
export const goalSheet = () => ui().openSheet(close => <GoalSheet close={close} />)
/* ============================ exercise detail ============================ */
function ExerciseDetail({ ex }) {
const st = useStore(s => s.S)
const last = lastEntryFor(st, ex.id)
const best = bestWeightFor(st, ex.id)
return <>
<h3 className="capitalize">{ex.n}</h3>
<Media ex={ex} />
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
<span className="tag acc">{ex.bp}</span>
{ex.tg && <span className="tag">🎯 {ex.tg}</span>}
<span className="tag">🛠 {ex.eq}</span>
{(ex.sm || []).slice(0, 3).map((s, i) => <span key={i} className="tag">{s}</span>)}
</div>
{best > 0 && <div className="small" style={{ marginBottom: 6 }}>🏆 Best: <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · last ${fmtDate(last.d)}: ${last.sets.map(s => fmtNum(s.w) + '×' + s.r).join(', ')}` : ''}</div>}
<button className="btn primary" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>+ Add to my plan</button>
{ex.st && ex.st.length > 0 && <><h4 className="sec">How to</h4><ol className="steps-list">{ex.st.map((s, i) => <li key={i}>{s}</li>)}</ol></>}
</>
}
export const exerciseDetailSheet = ex => ui().openSheet(() => <ExerciseDetail ex={ex} />)
/* ============================ add to routine ============================ */
function AddToRoutine({ ex, close }) {
const st = useStore(s => s.S)
const pick = rid => {
close()
const isNew = rid === '_new'
exConfigSheet(ex, null, cfg => {
update(s => {
let r = isNew ? { id: uid(), name: 'New routine', emoji: '💪', ex: [] } : s.routines.find(x => x.id === rid)
if (isNew) s.routines.push(r)
if (r) r.ex.push({ id: ex.id, ...cfg })
})
const r = isNew ? S().routines[S().routines.length - 1] : st.routines.find(x => x.id === rid)
toast('“' + ex.n + '” added to ' + (r ? r.name : 'routine') + ' ✓')
if (isNew && r) nav('/plan/r/' + r.id)
})
}
return <>
<h3 className="capitalize">Add “{ex.n}”</h3>
<div className="muted small" style={{ marginBottom: 12 }}>Pick a routine — sets, reps & weight come next.</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => pick(r.id)}>
<div style={{ fontSize: '1.3rem', flex: 'none' }}>{r.emoji || '💪'}</div>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{r.ex.length} exercises</div></div>
{r.ex.some(e => e.id === ex.id) && <span className="tag">already in</span>}<span className="chev">+</span>
</div>)}
<div className="item" onClick={() => pick('_new')}><div style={{ fontSize: '1.3rem', flex: 'none' }}>✨</div>
<div className="grow"><div className="tt">New routine</div><div className="ss">Create one and start with this exercise</div></div><span className="chev">+</span></div>
</div>
</>
}
export const addToRoutineSheet = ex => ui().openSheet(close => <AddToRoutine ex={ex} close={close} />)
/* ============================ exercise picker ============================ */
function ExercisePicker({ onPick, close }) {
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [shown, setShown] = useState(50)
const ql = q.toLowerCase().trim()
const f = EXDB.filter(e => (!bp || e.bp === bp) && (!ql || e.n.includes(ql) || e.tg.includes(ql) || e.eq.includes(ql)))
return <>
<h3>Add exercise</h3>
<div className="search"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={`Search ${EXDB.length} exercises…`} value={q} onChange={e => { setQ(e.target.value); setShown(50) }} /></div>
<div className="chips" style={{ margin: '10px 0' }}>
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setShown(50) }}>All</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(50) }}>{b}</button>)}
</div>
<div className="list">
{f.slice(0, shown).map(e => <div key={e.id} className="item" onClick={() => { close(); onPick(e) }}>
<Thumb ex={e} /><div className="grow"><div className="tt">{e.n}</div><div className="ss">{(e.tg || e.bp)} · {e.eq}</div></div><span className="chev">+</span>
</div>)}
{f.length === 0 && <div className="empty">No match 🤷</div>}
</div>
{f.length > shown && <><div style={{ height: 8 }} /><button className="btn" onClick={() => setShown(s => s + 50)}>Show more</button></>}
</>
}
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
/* ============================ exercise config ============================ */
function ExConfig({ ex, existing, onSave, onDelete, close }) {
const st = useStore(s => s.S)
const [c, setC] = useState(existing || { sets: 3, reps: 10, weight: 0 })
return <>
<h3 className="capitalize">{ex.n}</h3>
<Media ex={ex} />
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0 14px' }}>
<span className="tag">{ex.tg || ex.bp}</span><span className="tag">{ex.eq}</span>
</div>
<div className="row" style={{ justifyContent: 'space-around', marginBottom: 18 }}>
<Stepper label="Sets" value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
<Stepper label="Reps" value={c.reps} step={1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
<Stepper label={'Weight (' + st.unit + ')'} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
</div>
<button className="btn primary" onClick={() => { close(); onSave({ sets: Math.max(1, Math.round(c.sets) || 3), reps: Math.max(1, Math.round(c.reps) || 10), weight: Math.max(0, c.weight || 0) }) }}>{existing ? 'Save' : 'Add to routine'}</button>
{onDelete && <><div style={{ height: 8 }} /><button className="btn danger" onClick={() => { close(); onDelete() }}>Remove exercise</button></>}
</>
}
export const exConfigSheet = (ex, existing, onSave, onDelete) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} onSave={onSave} onDelete={onDelete} close={close} />)
/* ============================ emoji picker ============================ */
const ROUTINE_EMOJIS = ['💪', '🏋️', '🏋️‍♀️', '🦵', '🦾', '🫸', '🫷', '🔥', '⚡', '💥', '🏃', '🏃‍♀️', '🚴', '🏊', '🤸', '🥊', '🧗', '⛰️', '🏔️', '🚀', '🧘', '🧘‍♀️', '🎯', '🏆', '🥇', '⭐', '🌟', '👑', '🛡️', '⚔️', '🦍', '🐂', '🐻', '🦁', '🐺', '🦈', '😤', '🤖', '🧨', '❤️‍🔥']
export const emojiPicker = (current, onPick) => ui().openSheet(close => <>
<h3>Pick an emoji</h3>
<div className="emoji-grid">{ROUTINE_EMOJIS.map(e => <button key={e} className={'emoji-cell' + (e === current ? ' on' : '')} onClick={() => { close(); onPick(e) }}>{e}</button>)}</div>
</>)
/* ============================ day override / assign ============================ */
function DayOverride({ iso, close }) {
const st = useStore(s => s.S)
const wd = new Date(iso + 'T12:00:00').getDay()
const weeklyR = st.routines.find(r => r.id === st.week[wd])
const hasOvr = st.dayPlan[iso] !== undefined
const effId = effectiveRoutineId(st, iso)
const set = v => {
update(s => { if (!v) delete s.dayPlan[iso]; else s.dayPlan[iso] = v })
close()
toast(v === '' ? 'Back to weekly plan' : v === 'rest' ? fmtDate(iso) + ' set to rest' : (st.routines.find(r => r.id === v) || {}).name + ' planned for ' + fmtDate(iso) + ' ✓')
}
return <>
<h3>{fmtDate(iso, true)}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>Weekly plan: {weeklyR ? weeklyR.name : 'Rest'}{hasOvr && <span style={{ color: 'var(--orange)' }}> · changed for this day</span>}<br />Sick, missed a day or want a different session? Pick what to train instead.</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
<div style={{ fontSize: '1.3rem', flex: 'none' }}>{r.emoji || '💪'}</div>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{r.ex.length} exercises</div></div>
{effId === r.id && <span className="accent">✓</span>}</div>)}
<div className="item" onClick={() => set('rest')}><div className="grow"><div className="tt">😌 Rest / skip this day</div></div>{effId === null && <span className="accent">✓</span>}</div>
{hasOvr && <div className="item" onClick={() => set('')}><div className="grow"><div className="tt">↺ Back to weekly plan</div></div></div>}
</div>
</>
}
export const dayOverrideSheet = iso => ui().openSheet(close => <DayOverride iso={iso} close={close} />)
function DayAssign({ day, close }) {
const st = useStore(s => s.S)
const set = v => { update(s => { if (v) s.week[day] = v; else delete s.week[day] }); close() }
return <>
<h3>{DAYN[day]}</h3>
<div className="list">
<div className="item" onClick={() => set('')}><div className="grow"><div className="tt">😌 Rest day</div></div>{!st.week[day] && <span className="accent">✓</span>}</div>
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
<div style={{ fontSize: '1.3rem', flex: 'none' }}>{r.emoji || '💪'}</div>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{r.ex.length} exercises</div></div>
{st.week[day] === r.id && <span className="accent">✓</span>}</div>)}
</div>
</>
}
export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day} close={close} />)
/* ============================ workout detail ============================ */
function WorkoutDetail({ w, close }) {
const st = useStore(s => s.S)
return <>
<h3>{w.name}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{fmtDate(w.d, true)} · {fmtDur(w.end - w.start)} · {fmtVol(w.vol, st.unit)}{w.bw ? ' · ⚖️ ' + fmtNum(w.bw) + ' ' + st.unit : ''}</div>
{w.entries.map((e, i) => {
const ex = EXIDX[e.id]
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
{ex && <Thumb ex={ex} />}
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 700 }}>{ex ? ex.n : e.id} {w.prs && w.prs.includes(e.id) && <span className="pr">🏆 PR</span>}</div>
<div className="ss">{e.sets.filter(s => s.done).map(s => fmtNum(s.w) + '×' + s.r).join(' · ') || 'no sets'}</div></div>
</div>
})}
<button className="btn danger" onClick={() => { if (confirm('Delete this workout from history?')) { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast('Workout deleted') } }}>Delete workout</button>
</>
}
export const workoutDetailSheet = w => ui().openSheet(close => <WorkoutDetail w={w} close={close} />)
/* ============================ calendar ============================ */
function Calendar({ start, close }) {
const st = useStore(s => s.S)
const [cur, setCur] = useState(() => { const d = start ? new Date(start) : new Date(); d.setDate(1); return d })
const y = cur.getFullYear(), mo = cur.getMonth()
const byDay = {}
st.workouts.forEach(w => (byDay[w.d] = byDay[w.d] || []).push(w))
const startOffset = (new Date(y, mo, 1).getDay() + 6) % 7
const daysIn = new Date(y, mo + 1, 0).getDate()
const monthWs = st.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)
const cells = []
for (let i = 0; i < startOffset; i++) cells.push(<div key={'e' + i} />)
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], effId = effectiveRoutineId(st, iso), ovr = st.dayPlan[iso] !== undefined
const dotCls = ws ? 'done' : ovr && effId ? 'ovr' : effId ? 'plan' : ''
cells.push(<button key={d} className={'cal-d' + (ws ? ' has' : '') + (iso === todayISO() ? ' today' : '')} onClick={() => {
if (!ws) { close(); dayOverrideSheet(iso); return }
if (ws.length === 1) { close(); workoutDetailSheet(ws[0]); return }
close(); ui().openSheet(c2 => <><h3>{fmtDate(iso, true)}</h3><div className="list">{ws.map(w => <WorkoutRow key={w.id} w={w} onClick={() => { c2(); workoutDetailSheet(w) }} />)}</div></>)
}}><span>{d}</span><i className={dotCls} /></button>)
}
return <>
<div className="row between" style={{ marginBottom: 2 }}>
<button className="iconbtn" onClick={() => setCur(new Date(y, mo - 1, 1))}>‹</button>
<h3 style={{ margin: 0 }}>{MONTHS_LONG[mo]} {y}</h3>
<button className="iconbtn" onClick={() => setCur(new Date(y, mo + 1, 1))}>›</button>
</div>
<div className="small muted" style={{ textAlign: 'center' }}>{monthWs.length ? `${monthWs.length} workout${monthWs.length > 1 ? 's' : ''} · ${fmtDur(monthMs)} · ${fmtVol(monthVol, st.unit)}` : 'No workouts this month'}</div>
<div className="cal-grid">{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(l => <div key={l} className="cal-h">{l}</div>)}{cells}</div>
<div className="cal-legend">
<span><i style={{ background: 'var(--acc)' }} />Trained</span>
<span><i style={{ background: 'var(--blue)' }} />Planned</span>
<span><i style={{ background: 'var(--orange)' }} />Rescheduled</span>
</div>
<div className="small dim" style={{ textAlign: 'center', marginTop: 10 }}>Tap a trained day for details · tap any other day to plan a session</div>
</>
}
export const calendarSheet = start => ui().openSheet(close => <Calendar start={start} close={close} />)
/* shared small workout row (used in lists) */
export function WorkoutRow({ w, onClick }) {
const st = useStore(s => s.S)
const emoji = (st.routines.find(r => r.id === w.routineId) || {}).emoji || '💪'
return <div className="item" onClick={onClick}>
<div style={{ fontSize: '1.5rem', flex: 'none' }}>{emoji}</div>
<div className="grow"><div className="tt">{w.name}</div>
<div className="ss">{fmtDate(w.d, true)} · {fmtDur(w.end - w.start)} · {setsDone(w)} sets · {fmtVol(w.vol, st.unit)}</div></div>
{w.prs && w.prs.length > 0 && <span className="pr">🏆 {w.prs.length} PR</span>}
<span className="chev">›</span>
</div>
}
/* ============================ workout lifecycle ============================ */
export function startFlow(routineId) {
bwSheet({ required: true, onDone: bw => beginWorkout(routineId, bw) })
}
export function beginWorkout(routineId, bw) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
const entries = (r ? r.ex : []).map(cfg => ({ id: cfg.id, target: { ...cfg }, sets: buildSets(st, cfg) }))
update(s => {
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : 'Freestyle', bw: bw || null, cur: 0, entries }
})
useUI.getState().stopRest()
nav('/workout')
}
function TopWeight({ entry, close }) {
const st = useStore(s => s.S)
const A = st.active
const ex = EXIDX[entry.id]
const maxSet = Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0))
const prevBest = Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id))
const [v, setV] = useState(String(Math.max(maxSet, prevBest) || entry.target.weight || 0))
const isLastEx = A && A.cur >= A.entries.length - 1
const ref = useRef(null)
useEffect(() => { setTimeout(() => { ref.current?.focus(); ref.current?.select() }, 250) }, [])
const commit = advance => {
const n = parseFloat(v)
if (!isFinite(n) || n < 0) { toast('Enter a valid weight'); return }
update(s => {
const e = s.active.entries.find(x => x === s.active.entries[A.cur]) || s.active.entries[A.cur]
s.active.entries[A.cur].topW = n
const cur = s.exWeights[entry.id]
s.exWeights[entry.id] = { w: Math.max(n, cur ? cur.w : 0), d: todayISO() }
})
close()
if (advance && A) {
if (isLastEx) finishWorkout()
else update(s => { s.active.cur = Math.min(s.active.entries.length - 1, s.active.cur + 1) })
} else toast('Tracked — next time starts at ' + fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit + ' 📈')
}
return <>
<h3 className="capitalize">✅ {ex.n} done</h3>
<div className="muted small">Confirm the weight you worked with — your highest becomes the default next time.</div>
<div className="bwin"><input ref={ref} type="number" inputMode="decimal" step="0.5" value={v} onChange={e => setV(e.target.value)} /><span>{st.unit}</span></div>
{prevBest > 0 ? <div className="small dim" style={{ textAlign: 'center', marginBottom: 12 }}>Previous best: {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && <span style={{ color: 'var(--gold)' }}> — new record! 🏆</span>}</div> : <div style={{ height: 4 }} />}
<button className="btn primary" onClick={() => commit(true)}>{isLastEx ? 'Save & finish 🏁' : 'Save & next exercise ›'}</button>
<div style={{ height: 8 }} /><button className="btn ghost dim" onClick={() => commit(false)}>Just close</button>
</>
}
export const topWeightSheet = entry => ui().openSheet(close => <TopWeight entry={entry} close={close} />)
function FinishSummary({ w, prs, close }) {
const st = useStore(s => s.S)
return <div style={{ textAlign: 'center', padding: '8px 0' }}>
<div style={{ fontSize: '3rem' }}>🎉</div>
<h3 style={{ margin: '8px 0' }}>Workout complete!</h3>
<div className="tiles" style={{ textAlign: 'left' }}>
<div className="tile"><div className="l">Duration</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtDur(w.end - w.start)}</div></div>
<div className="tile"><div className="l">Volume</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtVol(w.vol, st.unit)}</div></div>
<div className="tile"><div className="l">Sets</div><div className="v" style={{ fontSize: '1.1rem' }}>{setsDone(w)}</div></div>
<div className="tile"><div className="l">PRs</div><div className="v" style={{ fontSize: '1.1rem' }}>{prs.length ? '🏆 ' + prs.length : '—'}</div></div>
</div>
{prs.length > 0 && <div style={{ textAlign: 'left', marginBottom: 12 }}>{prs.map(id => <div key={id} className="small accent capitalize">🏆 New PR: {(EXIDX[id] || {}).n || id}</div>)}</div>}
<button className="btn primary" onClick={() => { close(); nav('/home') }}>Nice! 💪</button>
</div>
}
export function finishWorkout() {
const st = S()
const A = st.active
if (!A) return
const done = setsDoneActive(A)
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
if (!done && !confirm('No sets logged — finish anyway?')) return
if (done < total && done > 0 && !confirm('Some sets are unchecked. Finish workout?')) return
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(st, 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)
update(s => {
w.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(x => x.done).map(x => x.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
})
useUI.getState().stopRest()
beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36)
ui().openSheet(close => <FinishSummary w={w} prs={prs} close={close} />, { kind: 'center', locked: true })
}
+101
View File
@@ -0,0 +1,101 @@
import { create } from 'zustand'
import { api } from '../lib/api.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, sound: true,
theme: 'dark', accent: 'lime', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null
}
const clone = o => JSON.parse(JSON.stringify(o))
function loadState() {
try {
const raw = localStorage.getItem(KEY)
if (raw) return Object.assign(clone(DEF), JSON.parse(raw))
} catch (e) { /* ignore */ }
return clone(DEF)
}
const hasData = st => !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length)
export const useStore = create((set, get) => {
let pushTm = null
const persist = (S, push = true) => {
S._ts = Date.now()
localStorage.setItem(KEY, JSON.stringify(S))
set({ S })
if (push && get().user) {
clearTimeout(pushTm)
pushTm = setTimeout(() => get().pushState(), 1500)
}
}
return {
S: loadState(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
ready: false,
// Mutate a draft of S via producer fn, then persist + schedule sync.
update(mut, push = true) {
const S = clone(get().S)
mut(S)
persist(S, push)
},
replaceState(S, push = false) { persist(clone(S), push) },
isGuest: () => localStorage.getItem('gym_guest') === '1',
setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },
setUser(u) {
if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') }
else localStorage.removeItem('gym_user')
set({ user: u })
},
async pushState() {
if (!get().user) return
clearTimeout(pushTm)
try { await api('/api/data', { method: 'PUT', body: JSON.stringify({ state: get().S }) }); localStorage.removeItem('gym_dirty') }
catch (e) { localStorage.setItem('gym_dirty', '1') }
},
async pullState() {
try {
const { state } = await api('/api/data')
const S = get().S
const dirty = localStorage.getItem('gym_dirty') === '1'
if (state && (!hasData(S) || ((state._ts || 0) >= (S._ts || 0) && !dirty))) {
const active = S.active
const next = Object.assign(clone(DEF), state)
if (active) next.active = active
persist(next, false)
} else if (hasData(S)) { await get().pushState() }
} catch (e) { /* offline — keep local */ }
},
async signOut() {
try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
},
// Boot: ask the server who we are, then pull.
async boot() {
try {
const me = await api('/api/me')
get().setUser(me.user)
await get().pullState()
} catch (e) {
if (e.status === 401) get().setUser(null)
}
set({ ready: true })
}
}
})
export { hasData }
+47
View File
@@ -0,0 +1,47 @@
import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { useStore } from './useStore.js'
let toastTm = null
let timerInt = null
export const useUI = create((set, get) => ({
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
toastMsg: '',
timer: null, // { left, total }
openSheet(render, { kind = 'sheet', locked = false } = {}) {
const id = uid()
set(s => ({ sheets: [...s.sheets, { id, render, kind, locked }] }))
const close = () => get().closeSheet(id)
return { id, close, lock: v => set(s => ({ sheets: s.sheets.map(x => x.id === id ? { ...x, locked: v } : x) })) }
},
closeSheet(id) { set(s => ({ sheets: s.sheets.filter(x => x.id !== id) })) },
closeAll() { set({ sheets: [] }) },
toast(msg) {
set({ toastMsg: msg })
clearTimeout(toastTm)
toastTm = setTimeout(() => set({ toastMsg: '' }), 2200)
},
startRest(sec) {
get().stopRest()
set({ timer: { left: sec, total: sec } })
timerInt = setInterval(() => {
const t = get().timer
if (!t) return
const left = t.left - 1
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().toast('Rest over — next set! 💪'); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...t, left } })
}, 1000)
},
addRest(sec) { const t = get().timer; if (t) set({ timer: { left: t.left + sec, total: t.total + sec } }) },
stopRest() { if (timerInt) clearInterval(timerInt); timerInt = null; set({ timer: null }) }
}))
+14
View File
@@ -0,0 +1,14 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { WorkoutRow, workoutDetailSheet } from '../sheets.jsx'
export default function History() {
const nav = useNavigate()
const S = useStore(s => s.S)
return <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/stats')}>‹</button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>History</h1><div className="sub">{S.workouts.length} workouts</div></div></div>
{S.workouts.length ? <div className="list">{[...S.workouts].reverse().map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
: <div className="empty"><div className="ico">🗂</div>No workouts yet.</div>}
</>
}
+124
View File
@@ -0,0 +1,124 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtVol, fmtDate, todayISO, isoOf, weekKey, DAYS, DAYN } from '../lib/format.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, WorkoutRow, loadStarterPlan, bwDeltaColor, workoutDetailSheet } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
export default function Home() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const [weekOffset, setWeekOffset] = useState(0)
const today = new Date()
const routine = effectiveRoutine(S, todayISO())
const todayOvr = S.dayPlan[todayISO()] !== undefined
const bw = lastBW(S)
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
const delta = bw && prevBW ? bw.w - prevBW.w : null
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))
const strip = []
for (let i = 0; i < 7; i++) {
const d = new Date(monday); d.setDate(monday.getDate() + i)
const iso = isoOf(d)
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} onClick={() => dayOverrideSheet(iso)}>
<div className="lbl">{DAYS[d.getDay()]}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
}
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 bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
return <>
<div className="hdr">
<div><h1>{user ? 'Hi ' + user.name + ' 💪' : 'openGym 🏋️'}</h1><div className="sub">{today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })}</div></div>
<button className="iconbtn" onClick={() => nav('/settings')}>⚙️</button>
</div>
<div className="card">
<div className="row between" style={{ marginBottom: 8 }}>
<button className="iconbtn" style={{ width: 32, height: 32 }} onClick={() => setWeekOffset(w => w - 1)}>‹</button>
<div className="small muted" style={{ fontWeight: 600 }}>{wkLabel}</div>
<button className="iconbtn" style={{ width: 32, height: 32 }} onClick={() => setWeekOffset(w => w + 1)}>›</button>
</div>
<div className="week">{strip}</div>
<div className="small dim" style={{ marginTop: 8, textAlign: 'center' }}>Tap a day to plan or move a session</div>
</div>
<div className="cols"><div>
{S.active ? (
<div className="card" style={{ borderColor: 'var(--orange)' }}>
<h2 style={{ color: 'var(--orange)' }}>Workout in progress</h2>
<div className="row between">
<div><div className="big">{S.active.name}</div><div className="muted small">{setsDoneActive(S.active)} sets logged</div></div>
<button className="btn sm primary" onClick={() => nav('/workout')}>Resume ▶</button>
</div>
</div>
) : (
<div className="card">
<h2>Today</h2>
{routine ? <>
<div className="row between" style={{ marginBottom: 12 }}>
<div><div className="big">{routine.name}</div><div className="muted small">{routine.ex.length} exercises · ~{routine.ex.length * 8} min{todayOvr && <span style={{ color: 'var(--orange)' }}> · rescheduled</span>}</div></div>
<div style={{ fontSize: '2rem' }}>{routine.emoji || '💪'}</div>
</div>
<button className="btn primary" onClick={() => startFlow(routine.id)}>Start workout</button>
</> : S.routines.length ? <>
<div className="big" style={{ marginBottom: 4 }}>Rest day 😌</div>
<div className="muted small" style={{ marginBottom: 12 }}>Nothing planned for {DAYN[today.getDay()]} — recovery counts too. Feeling strong anyway?</div>
<button className="btn" onClick={() => nav('/workout')}>Start a workout anyway</button>
</> : <>
<div className="big" style={{ marginBottom: 4 }}>Welcome! 👋</div>
<div className="muted small" style={{ marginBottom: 12 }}>Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.</div>
<button className="btn primary" onClick={loadStarterPlan}>Load starter plan (PPL)</button>
<div style={{ height: 8 }} /><button className="btn" onClick={() => nav('/plan')}>Build my own plan</button>
</>}
</div>
)}
<div className="card">
<div className="row between" style={{ marginBottom: 6 }}>
<h2 style={{ margin: 0 }}>Body weight</h2>
<div className="row" style={{ gap: 8 }}>
<button className="btn sm" style={S.targetW ? { color: 'var(--gold)' } : undefined} onClick={goalSheet}>🎯 {S.targetW ? fmtNum(S.targetW) : 'Goal'}</button>
<button className="btn sm" onClick={() => bwSheet()}>+ Log</button>
</div>
</div>
{bw ? <>
<div className="row" style={{ gap: 8, alignItems: 'baseline' }}>
<div className="big">{fmtNum(bw.w)} <span className="muted" style={{ fontSize: '1rem' }}>{S.unit}</span></div>
{delta !== null && <span className="small" style={{ fontWeight: 700, color: bwDeltaColor(delta, bw.w) }}>{delta > 0 ? '▲' : delta < 0 ? '▼' : '•'} {fmtNum(Math.abs(delta))}</span>}
<span className="dim small" style={{ marginLeft: 'auto' }}>{fmtDate(bw.d, true)}</span>
</div>
{S.targetW && <div className="small" style={{ color: 'var(--gold)', marginTop: 2 }}>🎯 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')}</div>}
<div className="chart" style={{ marginTop: 8 }}><LineChart points={bwPoints} h={130} unit={S.unit} goal={S.targetW} /></div>
</> : <div className="muted small">No entries yet — log your weight to start the curve. It's also asked automatically before every workout.</div>}
</div>
</div><div>
<div className="tiles">
<div className="tile tappable" onClick={() => calendarSheet()}><div className="l">This week 📅</div><div className="v">{wThisWeek}<span className="muted" style={{ fontSize: '1rem' }}>{plannedPerWeek ? ' / ' + plannedPerWeek : ''}</span></div></div>
<div className="tile tappable" onClick={() => calendarSheet()}><div className="l">Week streak 📅</div><div className="v">{streakWeeks(S)} 🔥</div></div>
<div className="tile tappable" onClick={() => calendarSheet()}><div className="l">Total workouts</div><div className="v">{S.workouts.length}</div></div>
<div className="tile"><div className="l">Last volume</div><div className="v" style={{ fontSize: '1.15rem' }}>{lastW ? fmtVol(lastW.vol, S.unit) : '—'}</div></div>
</div>
{S.workouts.length > 0 && <>
<div className="row between" style={{ marginBottom: 10 }}>
<h4 className="sec" style={{ margin: 0 }}>Recent workouts</h4>
<button className="btn sm ghost accent" onClick={() => nav('/history')}>See all ›</button>
</div>
<div className="list">{[...S.workouts].reverse().slice(0, 3).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
</>}
</div></div>
</>
}
+39
View File
@@ -0,0 +1,39 @@
import { useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS } from '../lib/exercises.js'
import { bestWeightFor } from '../lib/history.js'
import { fmtNum } from '../lib/format.js'
import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet } from '../sheets.jsx'
export default function Library() {
const S = useStore(s => s.S)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [shown, setShown] = useState(40)
const ql = q.toLowerCase().trim()
const f = EXDB.filter(e => (!bp || e.bp === bp) && (!ql || e.n.includes(ql) || e.tg.includes(ql) || e.eq.includes(ql)))
return <>
<div className="hdr"><div><h1>Exercises</h1><div className="sub">{EXDB.length} exercises with animations</div></div></div>
<div className="search" style={{ marginBottom: 10 }}><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder="Search…" value={q} onChange={e => { setQ(e.target.value); setShown(40) }} /></div>
<div className="chips" style={{ marginBottom: 12 }}>
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setShown(40) }}>All</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(40) }}>{b}</button>)}
</div>
<div className="list">
{f.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" onClick={() => exerciseDetailSheet(e)}>
<Thumb ex={e} />
<div className="grow"><div className="tt">{e.n}</div><div className="ss">{(e.tg || e.bp)} · {e.eq}</div></div>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
<button className="btn sm primary" onClick={ev => { ev.stopPropagation(); addToRoutineSheet(e) }}>+ Plan</button>
</div>
})}
{f.length === 0 && <div className="empty">No match 🤷</div>}
</div>
{f.length > shown && <><div style={{ height: 10 }} /><button className="btn" onClick={() => setShown(s => s + 40)}>Show more</button></>}
</>
}
+52
View File
@@ -0,0 +1,52 @@
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js'
import { hasData } from '../store/useStore.js'
import { useState, useRef, useEffect } from 'react'
function RegisterSheet({ close }) {
const { setUser, pushState, pullState } = useStore()
const [name, setName] = useState('')
const ref = useRef(null)
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
const go = async () => {
const n = name.trim()
if (!n) { useUI.getState().toast('Enter a name'); return }
try {
const u = await passkeyRegister(n)
setUser(u); close()
if (hasData(useStore.getState().S)) { await pushState(); useUI.getState().toast('Profile created — data from this device moved into it ✓') }
else { await pullState(); useUI.getState().toast('Welcome, ' + u.name + ' 💪') }
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || 'Registration failed') }
}
return <>
<h3>Create your profile ✨</h3>
<div className="muted small" style={{ marginBottom: 14 }}>Pick a name, then confirm with {BIO}. The passkey is saved in your device — no password needed.</div>
<input ref={ref} className="input" placeholder="Your name" maxLength={40} value={name} onChange={e => setName(e.target.value)} />
<div style={{ height: 12 }} />
<button className="btn primary" onClick={go}>Create passkey</button>
</>
}
export default function Login() {
const { setUser, pullState, setGuest } = useStore()
const signIn = async () => {
try { const u = await passkeyLogin(); setUser(u); await pullState(); useUI.getState().toast('Welcome back, ' + u.name + ' 💪') }
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || 'Sign-in failed') }
}
return (
<div className="narrow" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: '78vh', textAlign: 'center' }}>
<div style={{ fontSize: '4rem' }}>🏋️</div>
<h1 style={{ fontSize: '2.2rem', fontWeight: 800, letterSpacing: '-.02em', margin: '8px 0 4px' }}>openGym</h1>
<div className="muted" style={{ marginBottom: 34 }}>Your workouts. Your weights. Your profile.</div>
{webauthnOK() ? <>
<button className="btn primary" onClick={signIn}>👤 Sign in with passkey</button>
<div style={{ height: 10 }} />
<button className="btn" onClick={() => useUI.getState().openSheet(close => <RegisterSheet close={close} />)}>✨ Create new profile</button>
<div style={{ height: 10 }} />
</> : <div className="card small muted" style={{ textAlign: 'left' }}>This browser doesn't support passkeys — you can still use openGym locally on this device.</div>}
<button className="btn ghost dim" onClick={() => setGuest(true)}>Continue without account</button>
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>Passkeys use {BIO} — no passwords.<br />Each profile keeps its own plan, workouts & body weight.</div>
</div>
)
}
+44
View File
@@ -0,0 +1,44 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, uid } from '../lib/format.js'
import { dayAssignSheet, loadStarterPlan } from '../sheets.jsx'
export default function Plan() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const addRoutine = () => {
const r = { id: uid(), name: 'New routine', emoji: '💪', ex: [] }
update(s => { s.routines.push(r) })
nav('/plan/r/' + r.id)
}
return <>
<div className="hdr"><div><h1>Plan</h1><div className="sub">Your weekly routine</div></div></div>
<div className="cols"><div>
<h4 className="sec">Week schedule</h4>
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
{[1, 2, 3, 4, 5, 6, 0].map(d => {
const r = S.routines.find(x => x.id === S.week[d])
return <div key={d} className="item" onClick={() => dayAssignSheet(d)}>
<div className="grow"><div className="tt">{DAYN[d]}</div></div>
{r ? <span className="tag acc">{(r.emoji || '') + ' ' + r.name}</span> : <span className="tag">Rest</span>}
<span className="chev">›</span></div>
})}
</div>
</div><div>
<div className="row between" style={{ marginTop: 22, marginBottom: 10 }}>
<h4 className="sec" style={{ margin: 0 }}>Routines</h4>
<button className="btn sm primary" onClick={addRoutine}>+ New</button>
</div>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" onClick={() => nav('/plan/r/' + r.id)}>
<div style={{ fontSize: '1.5rem', flex: 'none' }}>{r.emoji || '💪'}</div>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{r.ex.length} exercises</div></div>
<span className="chev">›</span></div>)}</div> : <>
<div className="empty"><div className="ico">📋</div>No routines yet.<br />Create one or load the starter plan.</div>
<button className="btn" onClick={loadStarterPlan}>Load starter plan (Push / Pull / Legs)</button>
</>}
</div></div>
</>
}
+63
View File
@@ -0,0 +1,63 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { fmtNum } from '../lib/format.js'
import { Thumb } from '../components/Media.jsx'
import { emojiPicker, exercisePicker, exConfigSheet } from '../sheets.jsx'
export default function RoutineEdit() {
const nav = useNavigate()
const { id } = useParams()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const r = S.routines.find(x => x.id === id)
useEffect(() => { if (!r) nav('/plan') }, [!!r])
if (!r) return null
const move = (i, dir) => update(s => {
const ex = s.routines.find(x => x.id === id).ex
const j = i + dir
if (j < 0 || j >= ex.length) return
;[ex[i], ex[j]] = [ex[j], ex[i]]
})
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => nav('/plan')}>‹</button>
<div style={{ flex: 1, margin: '0 12px' }}>
<input className="input" defaultValue={r.name} style={{ fontWeight: 800, fontSize: '1.1rem' }}
onChange={e => update(s => { s.routines.find(x => x.id === id).name = e.target.value.trim() || 'Routine' })} />
</div>
<button className="iconbtn" onClick={() => emojiPicker(r.emoji, emo => update(s => { s.routines.find(x => x.id === id).emoji = emo }))}>{r.emoji || '💪'}</button>
</div>
{r.ex.length ? <div className="list">{r.ex.map((e, i) => {
const ex = EXIDX[e.id]; if (!ex) return null
return <div key={i} className="item" onClick={() => {
exConfigSheet(ex, e, cfg => update(s => { Object.assign(s.routines.find(x => x.id === id).ex[i], cfg) }),
() => update(s => { s.routines.find(x => x.id === id).ex.splice(i, 1) }))
}}>
<Thumb ex={ex} />
<div className="grow"><div className="tt">{ex.n}</div><div className="ss">{e.sets} × {e.reps}{e.weight ? ' · ' + fmtNum(e.weight) + ' ' + S.unit : ''}</div></div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none' }}>
<button className="iconbtn" style={{ width: 34, height: 30, fontSize: '.8rem' }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}>▲</button>
<button className="iconbtn" style={{ width: 34, height: 30, fontSize: '.8rem' }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}>▼</button>
</div>
</div>
})}</div> : <div className="empty"><div className="ico">🏋️</div>No exercises yet — add your first one.</div>}
<div style={{ height: 10 }} />
<button className="btn primary" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => update(s => { s.routines.find(x => x.id === id).ex.push({ id: ex.id, ...cfg }) })))}>+ Add exercise</button>
<div style={{ height: 10 }} />
<button className="btn danger" onClick={() => {
if (!confirm('Delete "' + r.name + '"?')) return
update(s => {
s.routines = s.routines.filter(x => x.id !== id)
Object.keys(s.week).forEach(k => { if (s.week[k] === id) delete s.week[k] })
Object.keys(s.dayPlan).forEach(k => { if (s.dayPlan[k] === id) delete s.dayPlan[k] })
})
nav('/plan')
}}>Delete routine</button>
</div>
}
+118
View File
@@ -0,0 +1,118 @@
import { useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO } from '../lib/format.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { loadStarterPlan } from '../sheets.jsx'
export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const { update, replaceState, setUser, pullState, pushState, signOut } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const doExport = () => {
const blob = new Blob([JSON.stringify(S, null, 2)], { type: 'application/json' })
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'opengym-backup-' + todayISO() + '.json'; a.click(); URL.revokeObjectURL(a.href)
toast('Backup exported ✓')
}
const doImport = 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 an openGym backup')
if (!confirm('Replace all current data with this backup?')) return
replaceState(Object.assign(JSON.parse(JSON.stringify(DEF)), data), true); toast('Backup imported ✓')
} catch (e) { toast('Import failed: ' + e.message) }
}
rd.readAsText(f)
}
const signInHere = async () => {
try { const u = await passkeyLogin(); setUser(u); await pullState(); toast('Welcome back, ' + u.name + ' 💪') }
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || 'Sign-in failed') }
}
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
return <div className="narrow">
<div className="hdr"><button className="iconbtn" onClick={() => nav('/home')}>‹</button><div style={{ flex: 1, marginLeft: 12 }}><h1>Settings</h1></div></div>
<div className="card">
<h2>Account</h2>
{user ? <div className="row between">
<div><b>{user.name}</b><div className="small muted">Signed in with passkey — data syncs to this profile.</div></div>
<button className="btn sm danger" onClick={() => { if (confirm('Sign out? Local data is synced to your profile first, then cleared from this device.')) { signOut(); nav('/home') } }}>Sign out</button>
</div> : <>
<div className="small muted" style={{ marginBottom: 10 }}>Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.</div>
{webauthnOK() ? <>
<button className="btn primary" onClick={registerHere}>✨ Create passkey profile</button>
<div style={{ height: 8 }} /><button className="btn" onClick={signInHere}>👤 Sign in with passkey</button>
</> : <div className="small dim">Passkeys not supported in this browser.</div>}
</>}
</div>
<div className="card">
<h2>Appearance <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· synced with your profile</span></h2>
<div className="row between" style={{ padding: '8px 0' }}>
<span>Theme</span>
<div className="chips">
<button className={'chip' + (S.theme !== 'light' ? ' on' : '')} onClick={() => update(s => { s.theme = 'dark' })}>🌙 Dark</button>
<button className={'chip' + (S.theme === 'light' ? ' on' : '')} onClick={() => update(s => { s.theme = 'light' })}>☀️ Light</button>
</div>
</div>
<div style={{ padding: '8px 0' }}>
<div style={{ marginBottom: 10 }}>Accent color</div>
<div className="swatches">{Object.entries(ACCENTS).map(([k, c]) => <button key={k} className={'swatch' + ((S.accent || 'lime') === k ? ' on' : '')} style={{ background: c }} onClick={() => update(s => { s.accent = k })} />)}</div>
</div>
</div>
<div className="card">
<h2>Units & timer</h2>
<div className="row between" style={{ padding: '8px 0' }}><span>Weight unit</span>
<div className="chips"><button className={'chip' + (S.unit === 'kg' ? ' on' : '')} onClick={() => update(s => { s.unit = 'kg' })}>kg</button>
<button className={'chip' + (S.unit === 'lb' ? ' on' : '')} onClick={() => update(s => { s.unit = 'lb' })}>lb</button></div></div>
<div className="row between" style={{ padding: '8px 0' }}><span>Rest timer</span>
<select className="input" style={{ width: 120 }} value={S.restSec} onChange={e => update(s => { s.restSec = +e.target.value })}>
{[60, 90, 120, 150, 180].map(v => <option key={v} value={v}>{v}s</option>)}</select></div>
<div className="row between" style={{ padding: '8px 0' }}><span>Sounds</span>
<button className={'chip' + (S.sound ? ' on' : '')} onClick={() => update(s => { s.sound = !s.sound })}>{S.sound ? 'On 🔔' : 'Off 🔕'}</button></div>
<div className="small dim" style={{ marginTop: 6 }}>Note: switching units only changes the label — logged numbers are not converted.</div>
</div>
<div className="card">
<h2>Data</h2>
<button className="btn" onClick={doExport}>⬇️ Export backup (JSON)</button>
<div style={{ height: 8 }} /><button className="btn" onClick={() => fileRef.current.click()}>⬆️ Import backup</button>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
<div style={{ height: 8 }} /><button className="btn" onClick={loadStarterPlan}>Load starter plan (PPL)</button>
<div style={{ height: 8 }} /><button className="btn danger" onClick={() => { if (confirm('Delete ALL data (plan, workouts, body weight)?') && confirm('Really sure? This cannot be undone.')) { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast('All data reset') } }}>Reset everything</button>
</div>
<div className="card"><h2>Tip</h2>
<div className="small muted" style={{ lineHeight: 1.5 }}>📱 {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!'}</div></div>
<div className="dim small" style={{ textAlign: 'center', marginTop: 8 }}>openGym · exercise data: hasaneyldrm/exercises-dataset (CC)</div>
</div>
}
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const nameRef = useRef(null)
const go = async () => {
const n = (nameRef.current.value || '').trim()
if (!n) { toast('Enter a name'); return }
try {
const u = await passkeyRegister(n); setUser(u); close()
if (hasData(useStore.getState().S)) { await pushState(); toast('Profile created — data moved into it ✓') }
else { await pullState(); toast('Welcome, ' + u.name + ' 💪') }
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || 'Registration failed') }
}
return <>
<h3>Create your profile ✨</h3>
<div className="muted small" style={{ marginBottom: 14 }}>Pick a name, then confirm with your device.</div>
<input ref={nameRef} className="input" placeholder="Your name" maxLength={40} />
<div style={{ height: 12 }} /><button className="btn primary" onClick={go}>Create passkey</button>
</>
}
+88
View File
@@ -0,0 +1,88 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { bestWeightFor, lastBW, streakWeeks } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO } from '../lib/format.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
export default function Stats() {
const nav = useNavigate()
const S = useStore(s => s.S)
const [range, setRange] = useState(90)
const [exId, setExId] = useState(null)
const now = Date.now()
const bwPts = S.bodyweight.filter(b => range === 0 || (b.t || new Date(b.d).getTime()) > now - range * 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
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)
const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null
let exPts = [], exList = []
if (curEx) {
S.workouts.forEach(w => {
const en = w.entries.find(e => e.id === curEx)
if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(s => s.w), en.topW || 0); if (mx > 0) exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done) }) }
})
exList = exPts.slice(-5).reverse()
}
return <>
<div className="hdr"><div><h1>Stats</h1><div className="sub">Progress & history</div></div>
<button className="iconbtn" onClick={() => nav('/history')}>🗂</button></div>
<div className="tiles">
<div className="tile"><div className="l">Workouts</div><div className="v">{S.workouts.length}</div></div>
<div className="tile"><div className="l">This month</div><div className="v">{monthW}</div></div>
<div className="tile"><div className="l">Week streak</div><div className="v">{streakWeeks(S)} 🔥</div></div>
<div className="tile"><div className="l">Weight 30d</div><div className="v" style={{ fontSize: '1.15rem', color: bwDelta30 === null ? 'inherit' : bwDeltaColor(bwDelta30, (lastBW(S) || {}).w || 0) }}>{bwDelta30 === null ? '—' : (bwDelta30 > 0 ? '+' : '') + fmtNum(bwDelta30) + ' ' + S.unit}</div></div>
</div>
<div className="card">
<h2>Activity — last 12 months <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}>· by time trained</span></h2>
<Heatmap S={S} onDay={iso => { const ws = S.workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} />
</div>
<div className="cols">
<div className="card">
<div className="row between" style={{ marginBottom: 8 }}>
<h2 style={{ margin: 0 }}>Body weight</h2>
<div className="row" style={{ gap: 8 }}>
<button className="btn sm" style={S.targetW ? { color: 'var(--gold)' } : undefined} onClick={goalSheet}>🎯 {S.targetW ? fmtNum(S.targetW) : 'Goal'}</button>
<button className="btn sm" onClick={() => bwSheet()}>+ Log</button>
</div>
</div>
<div className="chips" style={{ marginBottom: 8 }}>
{[[30, '1M'], [90, '3M'], [365, '1Y'], [0, 'All']].map(([d, l]) => <button key={l} className={'chip' + (range === d ? ' on' : '')} onClick={() => setRange(d)}>{l}</button>)}
</div>
<div className="chart"><LineChart points={bwPts} h={160} unit={S.unit} goal={S.targetW} /></div>
</div>
<div className="card">
<h2>Exercise progress</h2>
{exHist.length ? <>
<select className="input capitalize" style={{ marginBottom: 10 }} value={curEx} onChange={e => setExId(e.target.value)}>
{exHist.map(id => <option key={id} value={id}>{EXIDX[id].n}</option>)}
</select>
<div className="chart"><LineChart points={exPts.map(p => ({ t: p.t, y: p.y, d: p.d }))} h={150} unit={S.unit} color="var(--blue)" /></div>
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: '1px solid var(--bg2)' }}>
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => fmtNum(s.w) + '×' + s.r).join(' ')}</span></div>)}</div>
<div className="small dim" style={{ marginTop: 8 }}>Best set weight per workout · Best ever: <b className="accent">{fmtNum(bestWeightFor(S, curEx))} {S.unit}</b></div>
</> : <div className="muted small">Finish your first workout to see strength curves here. 📈</div>}
</div>
</div>
{S.workouts.length > 0 && <>
<div className="row between" style={{ marginBottom: 10 }}>
<h4 className="sec" style={{ margin: 0 }}>History</h4>
<button className="btn sm ghost accent" onClick={() => nav('/history')}>All {S.workouts.length} ›</button>
</div>
<div className="list">{[...S.workouts].reverse().slice(0, 5).map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
</>}
</>
}
+161
View File
@@ -0,0 +1,161 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { EXIDX } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout } from '../sheets.jsx'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
const nav = useNavigate()
const S = useStore(s => s.S)
const todayR = effectiveRoutine(S, todayISO())
const todayOvr = S.dayPlan[todayISO()] !== undefined
const others = S.routines.filter(r => r !== todayR)
return <div className="narrow">
<div className="hdr"><div><h1>Start workout</h1><div className="sub">{DAYN[new Date().getDay()]} — {todayR ? 'today is ' + todayR.name : 'rest day, but no one’s stopping you'}</div></div></div>
{todayR && <div className="card" style={{ borderColor: 'var(--acc)' }}>
<h2 className="accent">Today's plan{todayOvr ? ' · rescheduled' : ''}</h2>
<div className="row between" style={{ marginBottom: 12 }}>
<div><div className="big">{todayR.name}</div><div className="muted small">{todayR.ex.length} exercises</div></div>
<div style={{ fontSize: '2rem' }}>{todayR.emoji || '💪'}</div>
</div>
<button className="btn primary" onClick={() => startFlow(todayR.id)}>Start {todayR.name} ▶</button>
</div>}
{others.length > 0 && <><h4 className="sec">Other routines</h4>
<div className="list">{others.map(r => <div key={r.id} className="item" onClick={() => startFlow(r.id)}>
<div style={{ fontSize: '1.5rem', flex: 'none' }}>{r.emoji || '💪'}</div>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{r.ex.length} exercises</div></div>
<span className="tag acc">Start ▶</span></div>)}</div></>}
<div style={{ height: 14 }} />
<button className="btn" onClick={() => startFlow(null)}>🎯 Freestyle workout (pick as you go)</button>
{!S.routines.length && <><div style={{ height: 10 }} /><button className="btn primary" onClick={() => nav('/plan')}>Build a plan first</button></>}
</div>
}
/* ---------- one set row ---------- */
function SetRow({ entry, i, unit, last, onToggle, onWeight, onReps }) {
const s = entry.sets[i]
return <div className={'setrow' + (s.done ? ' done' : '')}>
<div className="n">{i + 1}</div>
<div className="step w">
<button onClick={() => onWeight(Math.max(0, (s.w || 0) - 2.5))}>−</button>
<input type="number" inputMode="decimal" value={s.w} onFocus={e => e.target.select()} onChange={e => onWeight(e.target.value === '' ? 0 : Math.max(0, parseFloat(e.target.value) || 0))} />
<button onClick={() => onWeight(Math.max(0, (s.w || 0) + 2.5))}>+</button>
</div>
<div className="step r">
<button onClick={() => onReps(Math.max(0, (s.r || 0) - 1))}>−</button>
<input type="number" inputMode="numeric" value={s.r} onFocus={e => e.target.select()} onChange={e => onReps(e.target.value === '' ? 0 : Math.max(0, Math.round(parseFloat(e.target.value) || 0)))} />
<button onClick={() => onReps(Math.max(0, (s.r || 0) + 1))}>+</button>
</div>
<button className={'ck' + (s.done ? ' on' : '')} onClick={onToggle}><svg viewBox="0 0 24 24"><path d="m4.5 12.5 5 5 10-11" /></svg></button>
</div>
}
/* ---------- active workout ---------- */
function ActiveWorkout() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const { startRest, stopRest } = useUI()
const A = S.active
const [elapsed, setElapsed] = useState('0:00')
const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1))
const entry = A.entries[cur]
useEffect(() => {
const tick = () => {
const sec = Math.floor((Date.now() - A.start) / 1000)
setElapsed(Math.floor(sec / 60) + ':' + String(sec % 60).padStart(2, '0'))
}
tick(); const iv = setInterval(tick, 1000); return () => clearInterval(iv)
}, [A.start])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
const done = setsDoneActive(A)
const ex = entry ? EXIDX[entry.id] : null
const last = entry ? lastEntryFor(S, entry.id) : null
const best = entry ? bestWeightFor(S, entry.id) : 0
const hint = last && entry && last.sets.length >= (entry.target.sets || 1) && last.sets.every(s => s.r >= entry.target.reps) && last.sets[0].w > 0
? Math.max(...last.sets.map(s => s.w)) + 2.5 : null
const mutEntry = fn => update(s => { fn(s.active.entries[cur]) }, true)
const toggle = i => {
let askTop = false
mutEntry(e => {
e.sets[i].done = !e.sets[i].done
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const allDone = e.sets.every(x => x.done)
const isLastEx = cur >= A.entries.length - 1
if (!allDone) startRest(S.restSec)
else { stopRest(); useUI.getState().toast(isLastEx ? 'All sets done — Finish 🏁' : 'Exercise done ✓') }
if (allDone && !e.asked) { e.asked = true; askTop = true }
}
})
if (askTop) {
const e2 = S.active.entries[cur]
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)
}
}
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => { if (confirm('Discard this workout? Logged sets will be lost.')) { update(s => { s.active = null }); stopRest(); nav('/home') } }}>✕</button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 800 }}>{A.name}</div><div className="sub">{elapsed} · {done}/{total} sets</div></div>
<button className="iconbtn" style={{ color: 'var(--acc)' }} onClick={finishWorkout}>✓</button>
</div>
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{entry ? <>
<div className="muted small" style={{ marginBottom: 6 }}>Exercise {cur + 1} / {A.entries.length}</div>
<Media ex={ex} key={entry.id} />
<div className="row between" style={{ marginBottom: 6 }}>
<div style={{ fontSize: '1.2rem', fontWeight: 800, textTransform: 'capitalize', lineHeight: 1.2 }}>{ex.n}</div>
<button className="iconbtn" onClick={() => exerciseDetailSheet(ex)}>ℹ️</button>
</div>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
<span className="tag">{ex.tg || ex.bp}</span><span className="tag">{ex.eq}</span>
{best > 0 && <span className="tag">Best: {fmtNum(best)} {S.unit}</span>}
</div>
{last && <div className="small dim" style={{ marginBottom: 4 }}>Last time ({fmtDate(last.d)}): {last.sets.map(s => fmtNum(s.w) + '×' + s.r).join(', ')}</div>}
{hint && <button className="tag acc" style={{ border: 'none' }} onClick={() => { mutEntry(e => e.sets.forEach(s => { if (!s.done) s.w = hint })); useUI.getState().toast('Weights bumped to ' + fmtNum(hint) + ' ' + S.unit + ' 💪') }}>💡 Last time you hit all reps — try {fmtNum(hint)} {S.unit}</button>}
<div className="card" style={{ marginTop: 10 }}>
<div className="sethead"><span className="n-sp" /><span className="w-sp">Weight ({S.unit})</span><span className="r-sp">Reps</span><span className="ck-sp" /></div>
{entry.sets.map((s, i) => <SetRow key={i} entry={entry} i={i} unit={S.unit} last={last}
onToggle={() => toggle(i)}
onWeight={v => mutEntry(e => { e.sets[i].w = v })}
onReps={v => mutEntry(e => { e.sets[i].r = v })} />)}
<div style={{ height: 8 }} />
<button className="btn sm" onClick={() => mutEntry(e => { const l = e.sets[e.sets.length - 1]; e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false }) })}>+ Add set</button>
</div>
</> : <div className="empty"><div className="ico">🎯</div>Freestyle workout — add your first exercise.</div>}
<div style={{ height: 12 }} />
<div className="row">
<button className="btn" disabled={cur === 0 || !entry} onClick={() => update(s => { s.active.cur = Math.max(0, cur - 1) })}>‹ Prev</button>
<button className="btn" disabled={cur >= A.entries.length - 1} onClick={() => update(s => { s.active.cur = Math.min(s.active.entries.length - 1, cur + 1) })}>Next ›</button>
</div>
<div style={{ height: 10 }} />
<button className="btn" onClick={() => exercisePicker(ex => exConfigSheet(ex, null, cfg => update(s => {
s.active.entries.push({ id: ex.id, target: { ...cfg }, sets: buildSets(s, { ...cfg, id: ex.id }) })
s.active.cur = s.active.entries.length - 1
})))}>+ Add exercise</button>
<div style={{ height: 10 }} />
<button className="btn primary" onClick={finishWorkout}>Finish workout 🏁</button>
<div style={{ height: 40 }} />
</div>
}
export default function Workout() {
const active = useStore(s => s.S.active)
return active ? <ActiveWorkout /> : <StartChooser />
}