Merge merge request !20 (intensifiers, pairing, theme, security hardening)

Takes the nine commits as submitted, with three adjustments:

- remote.test.js ran in the node environment while remote.js pulls in
  api.js, which reads navigator.userAgent at module scope — the file failed
  to import. Same @vitest-environment happy-dom pragma the api tests use.
- Drops skills-lock.json. It pins a personal Claude Code skill chain to
  third-party GitHub repos by hash; that is contributor tooling, not a
  project artefact, and this project's GitHub access is gone. CLAUDE.md
  itself is kept — it is an accurate description of the repo.
- Corrects two stale claims in that CLAUDE.md: the website deploys from
  .gitlab-ci.yml, not GitHub Pages, and the CI gate is GitLab, not Gitea
  Actions with a dormant GitHub copy.

pt-BR: 23 of the 44 new pt strings are European (ficheiro, telemóvel,
Definições, «guillemets», tu-forms), so they get Brazilian overrides
rather than being inherited; fingerprint re-baselined.
This commit is contained in:
Duarte Santos committed 2026-08-25 14:28:10 +02:00
commit 7d2460c2c2
47 files changed
+2296 -109

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
// Mobile build only, first launch: the choice useStore.boot() couldn't make on its own — keep
// everything on this device, or connect to a self-hosted openGym server instead. See
// lib/remote.js for the pairing flow this hands off to.
import { useState, useRef, useEffect } from 'react'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
export function ConnectSheet({ close }) {
const { connectToServer } = useStore()
const [url, setUrl] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const ref = useRef(null)
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
const go = async () => {
if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }
setBusy(true)
try { await connectToServer(url.trim(), code.trim()); close(); useUI.getState().toast(t('Connected')) }
catch (e) { useUI.getState().toast(e.message || t('Could not connect')) }
finally { setBusy(false) }
}
return <>
<h3>{t('Connect to my server')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
</div>
<input ref={ref} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={url}
onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
<div style={{ height: 10 }} />
<input className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
<div style={{ height: 12 }} />
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>
</>
}
export default function MobileOnboarding() {
const { chooseLocalMode } = useStore()
const head = <>
<div style={{ fontSize: 54, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="dumbbell" /></div>
<h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-.028em', margin: '10px 0 4px' }}>openGym</h1>
</>
const wrap = { display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: '78vh', textAlign: 'center' }
return (
<div className="narrow" style={wrap}>
{head}
<div className="muted" style={{ marginBottom: 34 }}>{t('How do you want to use openGym?')}</div>
<Button variant="primary" icon="lock" onClick={() => chooseLocalMode()}>{t('Use on this device')}</Button>
<div style={{ height: 10 }} />
<Button icon="rocket" onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)}>{t('Connect to my server')}</Button>
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>
{t('Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.')}
</div>
</div>
)
}
+4
View File
@@ -22,6 +22,10 @@ export default function RoutineEdit() {
const update = useStore(s => s.update)
const r = S.routines.find(x => x.id === id)
useEffect(() => { if (!r) nav('/plan') }, [!!r])
// Editing here has no explicit "save" — every field change persists immediately. A single
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
// included: this still unmounts after the delete button navigates away.
useEffect(() => () => useStore.getState().autoBackupNow(), [])
if (!r) return null
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
+56 -8
View File
@@ -10,6 +10,7 @@ import { wakeLockSupported } from '../lib/wakelock.js'
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -18,7 +19,7 @@ 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, signOutAll, resetDemo } = useStore()
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -73,12 +74,21 @@ export default function Settings() {
</div>
{/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
<Section title={MOBILE ? t('Your data') : DEMO ? t('Demo') : t('Account')}>
{MOBILE ? <>
<Section title={MOBILE ? (user ? t('Your server') : t('Your data')) : DEMO ? t('Demo') : t('Account')}>
{MOBILE ? (user ? <>
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Synced with your openGym server.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="signOut" iconTint="var(--red)" title={t('Disconnect')} danger onClick={() => confirmSheet({
title: t('Disconnect from your server?'),
message: t('Your data is synced to your server first, then this device switches back to local-only.'),
confirmText: t('Disconnect'), danger: true,
onConfirm: async () => { await disconnectServer(); nav('/home'); toast(t('Disconnected — back to local-only')) },
})} />
</> : <>
<Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />
<Row icon="rocket" iconTint="var(--indigo)" title={t('Self-host openGym')} subtitle={t('Passkey sign-in, sync across your devices, your own data.')} accessory="chevron"
onClick={() => window.open(REPO, '_blank', 'noopener')} />
</> : DEMO ? <>
<Row icon="link" iconTint="var(--indigo)" title={t('Connect to my server')} subtitle={t('Sync this device to your own self-hosted openGym instead.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)} />
</>) : DEMO ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('You’re in the demo')} subtitle={t('Example data, stored only in this browser — change anything you like.')} />
<Row icon="reset" iconTint="var(--blue)" title={t('Reset demo data')} accessory="chevron"
onClick={() => confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} />
@@ -87,6 +97,8 @@ export default function Settings() {
</> : user ? <>
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
@@ -120,6 +132,12 @@ export default function Settings() {
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))} />
{/* Default for a rest-pause burst added live on a plain set — a planned exercise's own
"Rest (s)" (in its Intensifier config) overrides this, same as the main rest timer
is the fallback whenever an exercise has no progression rule of its own. */}
<SelectRow icon="bolt" iconTint="var(--acc)" title={t('Rest-pause rest')}
value={S.restPauseSec} onChange={v => update(s => { s.restPauseSec = v })}
options={[10, 15, 20, 30].map(v => ({ value: v, label: v + 's' }))} />
{(wakeOK || !MOBILE) && (
<Row icon="sun" iconTint="var(--yellow)" title={t('Keep screen awake')}
subtitle={wakeOK ? null : t('Not supported in this browser.')}>
@@ -150,8 +168,12 @@ export default function Settings() {
<Row icon="moon" iconTint="var(--indigo)" title={t('Theme')}>
<Segmented
className="seg-inline"
options={[{ value: 'dark', icon: 'moon', label: t('Dark') }, { value: 'light', icon: 'sun', label: t('Light') }]}
value={S.theme === 'light' ? 'light' : 'dark'}
options={[
{ value: 'dark', icon: 'moon', label: t('Dark') },
{ value: 'light', icon: 'sun', label: t('Light') },
{ value: 'system', icon: 'gear', label: t('System') },
]}
value={S.theme || 'dark'}
onChange={v => update(s => { s.theme = v })}
/>
</Row>
@@ -183,6 +205,10 @@ export default function Settings() {
accessory="chevron" onClick={() => importRef.current.click()} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
subtitle={t('Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.')}>
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
</Row>}
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
</Section>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
@@ -362,6 +388,28 @@ function EquipmentCard({ S, update }) {
</Section>
}
// Lets the mobile app's "connect to my server" mode (lib/remote.js) authenticate without a
// WebAuthn ceremony of its own — the code is minted here, from an already signed-in session,
// and redeemed by the app for a bearer token. See /api/pair/create in api/server.js.
function PairSheet({ close }) {
const [code, setCode] = useState(null)
const [err, setErr] = useState(null)
useEffect(() => { api('/api/pair/create', { method: 'POST', body: '{}' }).then(r => setCode(r.code)).catch(e => setErr(e.message || t('Could not generate a code'))) }, [])
return <>
<h3>{t('Pair the mobile app')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')}
</div>
{err ? <div className="dim small">{err}</div> : (
<div className="card" style={{ textAlign: 'center', fontSize: 30, fontWeight: 700, letterSpacing: '.16em', padding: '18px 0' }}>
{code || '········'}
</div>
)}
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Done')}</Button>
</>
}
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
// the invite code on the same terms: an invite-only instance rejects a registration without
// one, so a form that cannot collect it is a form that cannot succeed.
+69 -3
View File
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
@@ -15,7 +15,7 @@ import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription } from '../lib/progression.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow } from '../lib/workout-model.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
@@ -58,8 +58,39 @@ function Elapsed({ start }) {
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
const entry = S.active.entries[entryIdx]
// Drops/bursts mutate the row in place — same card, not a new set with its own long rest.
// A planned exercise (see the exercise's "Intensifier" config) arrives with these already
// filled in by applyIntensifierPlan; these only add/edit/remove entries live from here on.
const mutSet = (i, fn) => update(s => { const row = s.active.entries[entryIdx].sets[i]; s.active.entries[entryIdx].sets[i] = fn(row) }, true)
const addDropRow = i => mutSet(i, row => {
const drops = dropsOf(row)
const base = drops.length ? drops[drops.length - 1].w : (row.w || 0)
const pct = entry.target?.intensifier?.type === 'dropset' ? entry.target.intensifier.pct : undefined
return addDrop(row, { w: nextDropWeight(base, pct), r: row.r })
})
// A rest-pause row's own reps are always the total across every burst (see
// applyIntensifierPlan/history.js) — clusters are the breakdown of that total, not extra on
// top of it — so adding, removing or editing one keeps `r` in step by the same delta.
const addBurstRow = i => mutSet(i, row => {
const clusters = clustersOf(row)
const base = clusters.length ? clusters[clusters.length - 1].r : (row.r || 0)
const restSec = entry.target?.intensifier?.type === 'restpause' ? entry.target.intensifier.restSec : (S.restPauseSec || 15)
const added = nextBurstReps(base)
return { ...addCluster(row, { r: added, restSec }), r: (row.r || 0) + added }
})
const removeDrop = (i, di) => mutSet(i, row => removeDropAt(row, di))
const removeCluster = (i, ci) => mutSet(i, row => {
const removed = clustersOf(row)[ci]?.r || 0
return { ...removeClusterAt(row, ci), r: Math.max(0, (row.r || 0) - removed) }
})
const setDropField = (i, di, field, v) => mutSet(i, row => setDropAt(row, di, { [field]: v }))
const setClusterField = (i, ci, v) => mutSet(i, row => {
const delta = (Number(v) || 0) - (clustersOf(row)[ci]?.r || 0)
return { ...setClusterAt(row, ci, { r: v }), r: Math.max(0, (row.r || 0) + delta) }
})
const ex = exOr(entry.id)
const mode = modeOf({ ...(entry.target || {}), id: entry.id })
const cardio = mode === 'cardio'
@@ -110,6 +141,15 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
<button aria-label="Increase" onClick={() => bump(s, i, col, 1)}><Icon name="plus" /></button>
</div>
)
// A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a
// live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field.
const miniStepper = (value, step, dec, onChange) => (
<div className="stp mini">
<button aria-label="Decrease" onClick={() => onChange(Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
<span className="val"><NumberField decimal={dec} value={value ?? ''} onChange={onChange} /></span>
<button aria-label="Increase" onClick={() => onChange(Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
</div>
)
return <>
<Media ex={ex} key={entry.id} compact={compact} minimizable />
<div className="row between" style={{ marginBottom: 6 }}>
@@ -160,6 +200,31 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
disabled={entry.sets.length <= 1} onClick={() => onRemoveSetAt(i)}><Icon name="xmark" /></button>}
<Check checked={s.done} onChange={() => onToggle(i)} />
</div>
{/* Drop-sets and rest-pause bursts extend this same row — no long rest, no new set.
A planned exercise arrives with these already filled in (applyIntensifierPlan);
every value here is just as editable as the main row's own weight/reps. */}
{!warm && mode === 'reps' && <>
{dropsOf(s).map((d, di) => (
<div className="subrow" key={'d' + di}>
<span className="subn">{t('Drop {0}', di + 1)}</span>
{miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))}
{miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
<button className="iconbtn" aria-label={t('Remove drop')} onClick={() => removeDrop(i, di)}><Icon name="xmark" /></button>
</div>
))}
{clustersOf(s).map((c, ci) => (
<div className="subrow" key={'c' + ci}>
<span className="subn">{t('Burst {0}', ci + 1)}</span>
{miniStepper(c.r, 1, false, v => setClusterField(i, ci, v))}
<span className="dim small">{c.restSec}s</span>
<button className="iconbtn" aria-label={t('Remove burst')} onClick={() => removeCluster(i, ci)}><Icon name="xmark" /></button>
</div>
))}
<div className="setextra">
{!isRestPauseSet(s) && <button className="chip add" onClick={() => addDropRow(i)}><Icon name="arrowDown" />{t('+ Drop')}</button>}
{!isDropSet(s) && <button className="chip add" onClick={() => addBurstRow(i)}><Icon name="bolt" />{t('+ Burst')}</button>}
</div>
</>}
</div>
})}
<div style={{ height: 8 }} />
@@ -429,7 +494,8 @@ function ActiveWorkout() {
const full = { ...cfg, id: ex.id }
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: freestyle ? sets : applyPrescription(sets, plan) })
const progressed = freestyle ? sets : applyPrescription(sets, plan)
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = s.active.entries.length - 1
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>