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

+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>
}