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:
1 parent
0c237f96dc
commit
7e1d27b218
49 files changed
+3014
-2014
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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' }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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) { /* */ } }
|
||||
Reference in new issue
Block a user