1293 lines
79 KiB
React
1293 lines
79 KiB
React
import { useEffect, useRef, useState } from 'react'
|
||
import { useStore } from './store/useStore.js'
|
||
import { useUI } from './store/useUI.js'
|
||
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
|
||
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
|
||
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
|
||
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
|
||
import { beep, vibrate } from './lib/sound.js'
|
||
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
|
||
import { nav } from './lib/nav.js'
|
||
import { starterRoutines } from './lib/starter.js'
|
||
import Media, { Thumb } from './components/Media.jsx'
|
||
import Stepper from './components/Stepper.jsx'
|
||
import Icon from './components/Icon.jsx'
|
||
import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, MultiSelectRow } from './components/ui.jsx'
|
||
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
|
||
import BodyMap from './components/BodyMap.jsx'
|
||
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
|
||
import { parseImport, mergeImport } from './lib/import-csv.js'
|
||
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
|
||
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
|
||
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
|
||
import { MOBILE, shareExport } from './lib/mobile.js'
|
||
import { buildCompletedWorkout } from './lib/finish-workout.js'
|
||
import { isWarmupRow } from './lib/workout-model.js'
|
||
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
|
||
|
||
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
|
||
|
||
/* ============================ custom confirm dialog ============================ */
|
||
function ConfirmDialog({ title, message, confirmText, cancelText, danger, onConfirm, close }) {
|
||
return <div style={{ textAlign: 'center', padding: '4px 0' }}>
|
||
{title && <h3 style={{ marginBottom: 8 }}>{title}</h3>}
|
||
<div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>{message}</div>
|
||
<button className={'btn ' + (danger ? 'danger' : 'primary')} onClick={() => { close(); onConfirm && onConfirm() }}>{confirmText || t('Confirm')}</button>
|
||
<div style={{ height: 8 }} />
|
||
<Button variant="ghost" className="dim" onClick={close}>{cancelText || t('Cancel')}</Button>
|
||
</div>
|
||
}
|
||
// Themed replacement for window.confirm — callback-based (no blocking).
|
||
export function confirmSheet(opts) {
|
||
ui().openSheet(close => <ConfirmDialog {...opts} close={close} />, { kind: 'center' })
|
||
}
|
||
|
||
/* ============================ starter plan ============================ */
|
||
export function loadStarterPlan() {
|
||
const [push, pull, legs] = starterRoutines()
|
||
update(st => {
|
||
st.routines.push(push, pull, legs)
|
||
st.week[1] = push.id; st.week[3] = pull.id; st.week[5] = legs.id
|
||
})
|
||
toast(t('Starter plan loaded — Mon Push · Wed Pull · Fri Legs'))
|
||
}
|
||
|
||
/* ============================ weight picker (shared: body weight + goal) ============================ */
|
||
// Fixed range, not a moving window — a window that resizes itself mid-drag (the previous
|
||
// attempt) makes the thumb's position unpredictable: every time it grows, everything already
|
||
// placed on it shifts toward one side. A static range never has that problem, at the cost of
|
||
// coarser precision per pixel — the +/- buttons cover exact values.
|
||
// The ceiling follows the profile's unit: 300 covers a body weight or a working weight in
|
||
// kg, but as pounds it cut off at 136 kg — below plenty of people's body weight, and well
|
||
// below an everyday squat.
|
||
const W_LO = 1
|
||
const wHi = unit => (unit === 'lb' ? 660 : 300)
|
||
function WeightInput({ value, setValue, unit }) {
|
||
const W_HI = wHi(unit)
|
||
const clamp = x => Math.max(W_LO, Math.min(W_HI, Math.round((x || 0) * 10) / 10))
|
||
const sv = Math.max(W_LO, Math.min(W_HI, value))
|
||
const onSlide = v => setValue(clamp(v))
|
||
return <>
|
||
<div className="bwstep">
|
||
<button className="bw-pm" onClick={() => onSlide(value - 0.1)} aria-label="minus 0.1"><Icon name="minus" /></button>
|
||
<div className="bw-read">{fmtNum(value)}<span className="u"> {unit}</span></div>
|
||
<button className="bw-pm" onClick={() => onSlide(value + 0.1)} aria-label="plus 0.1"><Icon name="plus" /></button>
|
||
</div>
|
||
<div className="chips" style={{ justifyContent: 'center', margin: '8px 0' }}>
|
||
<button className="chip" onClick={() => onSlide(value - 1)}>−1</button>
|
||
<button className="chip" onClick={() => onSlide(value - 0.5)}>−0.5</button>
|
||
<button className="chip" onClick={() => onSlide(value + 0.5)}>+0.5</button>
|
||
<button className="chip" onClick={() => onSlide(value + 1)}>+1</button>
|
||
</div>
|
||
<Slider value={sv} min={W_LO} max={W_HI} step={0.5} onChange={onSlide} />
|
||
</>
|
||
}
|
||
|
||
/* ============================ body weight ============================ */
|
||
function BwSheet({ required, onDone, close }) {
|
||
const st = useStore(s => s.S)
|
||
const unit = st.unit
|
||
const bw = lastBW(st)
|
||
const [v, setV] = useState(bw ? bw.w : 70)
|
||
const save = () => {
|
||
const n = Math.round((v || 0) * 10) / 10
|
||
if (!n || n <= 0) { toast(t('Enter a valid weight')); return }
|
||
update(s => {
|
||
const iso = todayISO()
|
||
const ex = s.bodyweight.find(b => b.d === iso)
|
||
if (ex) { ex.w = n; ex.t = Date.now() } else s.bodyweight.push({ d: iso, w: n, t: Date.now() })
|
||
s.bodyweight.sort((a, b) => (a.d < b.d ? -1 : 1))
|
||
})
|
||
close()
|
||
if (onDone) onDone(n); else toast(t('Weight saved'))
|
||
}
|
||
const recent = [...st.bodyweight].reverse().slice(0, 3)
|
||
const delEntry = d => update(s => { s.bodyweight = s.bodyweight.filter(b => b.d !== d) })
|
||
return <>
|
||
{/* This sheet opens `locked` — swipe/backdrop/Escape/Android-back all no-op on it (see
|
||
Modals.jsx) so an accidental tap on "Start" can't be walked back by reflex the way
|
||
every other sheet in the app can. The two buttons below already cover leaving it
|
||
deliberately; this is the same close a normal sheet gets everywhere else, just
|
||
opted back in explicitly instead of by omission. Plain close() — no onDone, no
|
||
nav — so it's a true no-op: the screen underneath is exactly where you left it. */}
|
||
{required
|
||
? <div className="row between" style={{ marginBottom: 14 }}>
|
||
<h3 style={{ marginBottom: 0 }}>{t('Quick check-in')}</h3>
|
||
<button className="iconbtn" aria-label={t('Cancel')} onClick={() => close()}><Icon name="xmark" /></button>
|
||
</div>
|
||
: <h3>{t('Log body weight')}</h3>}
|
||
<div className="muted small">{required ? t('Slide or tap to set your weight — tracked before every workout so your curve stays honest.') : t('Today') + ', ' + fmtDate(todayISO(), true)}</div>
|
||
<WeightInput value={v} setValue={setV} unit={unit} />
|
||
<div style={{ height: 14 }} />
|
||
<Button variant="primary" onClick={save}>{required ? t('Save & start workout') : t('Save')}</Button>
|
||
{required && <>
|
||
<div style={{ height: 8 }} /><Button variant="ghost" className="dim" onClick={() => { close(); onDone && onDone(null) }}>{t('Start without weighing in')}</Button>
|
||
<div style={{ height: 2 }} /><Button variant="ghost" className="dim" icon="reset" onClick={() => { close(); nav('/workout') }}>{t('Choose a different workout')}</Button>
|
||
</>}
|
||
{!required && recent.length > 0 && <>
|
||
<h4 className="sec">{t('Recent weigh-ins')}</h4>
|
||
<div className="list" style={{ gap: 0 }}>
|
||
{recent.map(b => <div key={b.d} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||
<span className="small muted">{fmtDate(b.d, true)}</span>
|
||
<span className="row" style={{ gap: 12 }}><b>{fmtNum(b.w)} {unit}</b>
|
||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }} onClick={() => delEntry(b.d)} aria-label="delete"><Icon name="trash" /></button></span>
|
||
</div>)}
|
||
</div>
|
||
</>}
|
||
</>
|
||
}
|
||
export function bwSheet(opts = {}) {
|
||
const h = ui().openSheet(close => <BwSheet {...opts} close={close} />, { locked: !!opts.required })
|
||
return h
|
||
}
|
||
|
||
/* ============================ import from another app ============================ */
|
||
// Shows what a parsed export would actually do before anything is written. An import is
|
||
// the one action where "just try it" is expensive — it's someone's entire training
|
||
// history — so the numbers, the unit conversion and the exercises we couldn't recognise
|
||
// are all on screen before the confirm button.
|
||
function ImportSummary({ parsed, close }) {
|
||
const st = useStore(s => s.S)
|
||
const isBW = parsed.kind === 'bodyweight'
|
||
const have = isBW
|
||
? parsed.bodyweight.filter(b => st.bodyweight.some(x => x.d === b.d)).length
|
||
: parsed.workouts.filter(w => st.workouts.some(x => x.d === w.d)).length
|
||
const fresh = (isBW ? parsed.bodyweight.length : parsed.workouts.length) - have
|
||
|
||
const doImport = () => {
|
||
let res
|
||
update(s => { res = mergeImport(s, parsed) })
|
||
close()
|
||
toast(isBW
|
||
? t('{0} weigh-ins imported', res.added)
|
||
: t('{0} workouts imported', res.added))
|
||
}
|
||
|
||
return <>
|
||
<h3>{parsed.source ? t('Import from {0}', parsed.source) : t('Import history')}</h3>
|
||
<div className="muted small" style={{ marginBottom: 12 }}>
|
||
{parsed.from === parsed.to ? fmtDate(parsed.from, true) : fmtDate(parsed.from, true) + ' – ' + fmtDate(parsed.to, true)}
|
||
</div>
|
||
|
||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||
{isBW ? <>
|
||
<div className="tile"><div className="l">{t('Weigh-ins')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.bodyweight.length}</div></div>
|
||
<div className="tile"><div className="l">{t('New')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fresh}</div></div>
|
||
</> : <>
|
||
<div className="tile"><div className="l">{t('Workouts')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.workouts.length}</div></div>
|
||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.sets}</div></div>
|
||
<div className="tile"><div className="l">{t('Exercises matched')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.matched}</div></div>
|
||
<div className="tile"><div className="l">{t('Added as your own')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{parsed.created}</div></div>
|
||
</>}
|
||
</div>
|
||
|
||
{parsed.mixedUnits ? <div className="small" style={{ color: 'var(--yellow)', marginBottom: 10 }}>
|
||
{t('The file mixes kg and lb — each set is converted to {0}.', st.unit)}
|
||
</div> : parsed.converted ? <div className="small" style={{ color: 'var(--yellow)', marginBottom: 10 }}>
|
||
{t('The file is in {0} and your profile is in {1} — weights will be converted.', parsed.fileUnit, st.unit)}
|
||
</div> : null}
|
||
{!isBW && !parsed.fileUnit && !parsed.mixedUnits && <div className="small dim" style={{ marginBottom: 10 }}>
|
||
{t('The file does not say which unit it uses — numbers are imported as they are.')}
|
||
</div>}
|
||
{have > 0 && <div className="small dim" style={{ marginBottom: 10 }}>
|
||
{t('{0} days already have data here and will be left alone.', have)}
|
||
</div>}
|
||
{/* The file rated its sets. Say so: the column is off by default, so the ratings would
|
||
otherwise arrive invisibly and look like they had been dropped. */}
|
||
{!isBW && (parsed.rirSets + parsed.rpeSets) > 0 && <div className="small dim" style={{ marginBottom: 10 }}>
|
||
{t(effortOf(st) === 'none'
|
||
? '{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.'
|
||
: '{0} sets bring an {1} with them.',
|
||
parsed.rirSets || parsed.rpeSets, parsed.rirSets ? 'RIR' : 'RPE')}
|
||
</div>}
|
||
{!isBW && parsed.unmatchedNames.length > 0 && <>
|
||
<h4 className="sec">{t('Not in the library — added as your own exercises')}</h4>
|
||
<div className="mchips" style={{ marginBottom: 12 }}>
|
||
{parsed.unmatchedNames.slice(0, 12).map(n => <span key={n} className="mchip capitalize">{n}</span>)}
|
||
{parsed.unmatchedNames.length > 12 && <span className="mchip">+{parsed.unmatchedNames.length - 12}</span>}
|
||
</div>
|
||
</>}
|
||
|
||
<Button variant="primary" onClick={doImport} disabled={!fresh}>
|
||
{fresh ? t('Import') : t('Nothing new to import')}
|
||
</Button>
|
||
<div style={{ height: 8 }} />
|
||
<Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>
|
||
</>
|
||
}
|
||
|
||
/** Read a CSV/XML export, then show what it would do. */
|
||
export function importFromApp(file, onDone) {
|
||
const rd = new FileReader()
|
||
rd.onload = () => {
|
||
let parsed
|
||
try { parsed = parseImport(String(rd.result), { unit: S().unit }) }
|
||
catch (e) { toast(t('Could not read that file')); return }
|
||
if (parsed.error === 'empty') { toast(t('That file is empty')); return }
|
||
if (parsed.error) { toast(t("That file's columns aren't recognised — see the docs for supported apps.")); return }
|
||
if (parsed.kind === 'bodyweight' ? !parsed.bodyweight.length : !parsed.workouts.length) {
|
||
toast(t('Nothing to import from that file')); return
|
||
}
|
||
ui().openSheet(close => <ImportSummary parsed={parsed} close={close} />)
|
||
onDone && onDone()
|
||
}
|
||
rd.onerror = () => toast(t('Could not read that file'))
|
||
rd.readAsText(file)
|
||
}
|
||
|
||
/* ============================ target weight ============================ */
|
||
export function bwDeltaColor(delta, currentW) {
|
||
if (!delta) return 'var(--label-2)'
|
||
if (!S().targetW) return 'var(--label)'
|
||
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 ? bw.w : 70))
|
||
return <>
|
||
<h3>{t('Target weight')}</h3>
|
||
<div className="muted small">{t('Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.')}</div>
|
||
<WeightInput value={v} setValue={setV} unit={st.unit} />
|
||
<div style={{ height: 14 }} />
|
||
<Button variant="primary" onClick={() => {
|
||
const n = Math.round((v || 0) * 10) / 10
|
||
if (!n || n <= 0) { toast(t('Enter a valid weight')); return }
|
||
update(s => { s.targetW = n }); close()
|
||
const b = lastBW(S()); toast(t('Goal set: {0}', fmtNum(n) + ' ' + st.unit) + (b ? ' (' + t('{0} to go', fmtNum(Math.abs(n - b.w))) + ')' : ''))
|
||
}}>{t('Save goal')}</Button>
|
||
{st.targetW && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { update(s => { s.targetW = null }); close(); toast(t('Goal removed')) }}>{t('Remove goal')}</Button></>}
|
||
</>
|
||
}
|
||
export const goalSheet = () => ui().openSheet(close => <GoalSheet close={close} />)
|
||
|
||
/* ============================ exercise detail ============================ */
|
||
// Estimated 1RM for one exercise (issue #18): what the log already implies, plus a calculator
|
||
// for a set you have not done — so the number is reachable before there is any history.
|
||
function OneRM({ ex }) {
|
||
const st = useStore(s => s.S)
|
||
const best = best1RM(st, ex.id)
|
||
const [w, setW] = useState(best ? best.w : (st.exWeights[ex.id] || {}).w || 20)
|
||
const [r, setR] = useState(best ? best.r : 5)
|
||
const est = estimate1RM(w, r)
|
||
return <>
|
||
<h4 className="sec">{t('Estimated 1RM')}</h4>
|
||
{best && <div className="small" style={{ marginBottom: 8 }}>
|
||
{t('From your log:')} <b className="accent">{fmtNum(best.est)} {st.unit}</b>
|
||
<span className="dim"> · {t('{0} × {1} on {2}', fmtNum(best.w) + ' ' + st.unit, best.r, fmtDate(best.d, true))}</span>
|
||
</div>}
|
||
<div className="row cfgrow" style={{ marginBottom: 10 }}>
|
||
<Stepper label={t('Weight ({0})', st.unit)} value={w} step={2.5} onChange={setW} />
|
||
<Stepper label={t('Reps')} value={r} step={1} decimal={false} onChange={setR} />
|
||
</div>
|
||
<div className="row between" style={{ marginBottom: 4 }}>
|
||
<span className="muted small">{t('Estimate')}</span>
|
||
<b className="accent" style={{ fontSize: 20 }}>{est === null ? '—' : fmtNum(est) + ' ' + st.unit}</b>
|
||
</div>
|
||
<div className="small dim">{est === null
|
||
? t('Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.', REP_CAP)
|
||
: t('Epley formula — a calculation from one set, not a tested max.')}</div>
|
||
</>
|
||
}
|
||
|
||
function ExerciseDetail({ ex, close }) {
|
||
const st = useStore(s => s.S)
|
||
const last = lastEntryFor(st, ex.id)
|
||
const best = bestWeightFor(st, ex.id)
|
||
return <>
|
||
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
|
||
<Media ex={ex} />
|
||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
|
||
<span className="tag acc">{t(ex.bp)}</span>
|
||
{(ex.primaries?.length ? ex.primaries : (ex.tg ? [ex.tg] : [])).map((s, i) => <span key={i} className="tag"><Icon name="target" />{t(s)}</span>)}
|
||
<span className="tag"><Icon name="dumbbell" />{t(ex.eq)}</span>
|
||
{(ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
|
||
</div>
|
||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
|
||
<Button variant="primary" icon="plus" style={{ margin: '10px 0 4px' }} onClick={() => addToRoutineSheet(ex)}>{t('Add to my plan')}</Button>
|
||
{ex.custom && <div className="row" style={{ gap: 8, marginTop: 8 }}>
|
||
<Button icon="pencil" style={{ flex: 1 }} onClick={() => { close(); customExSheet(ex) }}>{t('Edit')}</Button>
|
||
<Button variant="danger" icon="trash" style={{ flex: 1 }} onClick={() => deleteCustomEx(ex, close)}>{t('Delete')}</Button>
|
||
</div>}
|
||
{!isCardio(ex) && <OneRM ex={ex} />}
|
||
{instrFor(ex).length > 0 &&<><h4 className="sec">{t('How to')}{!INSTR_LANGS.includes(getLang()) && <span className="dim" style={{ textTransform: 'none', letterSpacing: 0 }}> · {t('instructions in English')}</span>}</h4><ol className="steps-list">{instrFor(ex).map((s, i) => <li key={i}>{s}</li>)}</ol></>}
|
||
</>
|
||
}
|
||
export const exerciseDetailSheet = ex => ui().openSheet(close => <ExerciseDetail ex={ex} close={close} />)
|
||
|
||
/* ============================ 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: t('New routine'), emoji: DEFAULT_GLYPH, 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(t('“{0}” added to {1}', exerciseNameFor(ex), r ? r.name : t('routine')))
|
||
if (isNew && r) nav('/plan/r/' + r.id)
|
||
}, null, isNew ? null : st.routines.find(x => x.id === rid))
|
||
}
|
||
return <>
|
||
<h3 className="capitalize">{t('Add “{0}”', exerciseNameFor(ex))}</h3>
|
||
<div className="muted small" style={{ marginBottom: 12 }}>{t('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)}>
|
||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||
{r.ex.some(e => e.id === ex.id) && <span className="tag">{t('already in')}</span>}<Icon name="plus" className="chev" />
|
||
</div>)}
|
||
<div className="item" onClick={() => pick('_new')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
|
||
<div className="grow"><div className="tt">{t('New routine')}</div><div className="ss">{t('Create one and start with this exercise')}</div></div><Icon name="plus" className="chev" /></div>
|
||
</div>
|
||
</>
|
||
}
|
||
export const addToRoutineSheet = ex => ui().openSheet(close => <AddToRoutine ex={ex} close={close} />)
|
||
|
||
/* ============================ custom exercises (issue #11) ============================ */
|
||
// Name + body part is all it takes — the exercise then behaves like any built-in one
|
||
// (planning, logging, PRs, stats), just without an animation.
|
||
function CustomExForm({ existing, prefill, onDone, close }) {
|
||
const [n, setN] = useState(existing ? existing.n : (prefill || ''))
|
||
const [bp, setBp] = useState(existing ? existing.bp : '')
|
||
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
|
||
const [primaries, setPrimaries] = useState(() => {
|
||
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...existing.primaries]
|
||
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
|
||
return norm.length ? [norm[0]] : []
|
||
})
|
||
const [secondaries, setSecondaries] = useState(() => {
|
||
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...(existing.secondaries || [])]
|
||
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
|
||
return norm.slice(1)
|
||
})
|
||
const togglePrimary = value => setPrimaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||
const toggleSecondary = value => setSecondaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
|
||
const save = () => {
|
||
const name = n.trim()
|
||
if (!name) { toast(t('Give it a name')); return }
|
||
if (!bp) { toast(t('Pick a body part')); return }
|
||
const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id)
|
||
if (dup) { toast(t('“{0}” already exists', dup.n)); return }
|
||
const d = desc.trim().slice(0, 1000)
|
||
const prim = [...primaries]
|
||
const sm = secondaries.filter(m => !prim.includes(m))
|
||
const groups = [...prim, ...sm]
|
||
let id = existing && existing.id
|
||
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) {
|
||
c.n = name; c.bp = bp; c.desc = d; c.tg = prim[0] || ''; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm
|
||
} })
|
||
else {
|
||
id = 'c' + uid()
|
||
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: prim[0] || '', sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq: 'custom', custom: true }) })
|
||
}
|
||
close()
|
||
toast(existing ? t('Saved') : t('“{0}” created', name))
|
||
onDone && onDone(EXIDX[id])
|
||
}
|
||
return <>
|
||
<h3>{existing ? t('Edit custom exercise') : t('Create your own exercise')}</h3>
|
||
<div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}</div>
|
||
<input className="input" placeholder={t('Exercise name')} value={n} onChange={e => setN(e.target.value)} />
|
||
<div className="chips" style={{ margin: '12px 0' }}>
|
||
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => setBp(b)}>{t(b)}</button>)}
|
||
</div>
|
||
{bp && bp !== 'cardio' && <>
|
||
<MultiSelectRow title={t('Primary muscle groups')} sheetTitle={t('Primary muscle groups')}
|
||
values={primaries}
|
||
options={MUSCLES.map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
|
||
onToggle={togglePrimary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
|
||
<MultiSelectRow title={t('Additional muscle groups')} sheetTitle={t('Additional muscle groups')}
|
||
values={secondaries}
|
||
options={MUSCLES.filter(m => !primaries.includes(m)).map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
|
||
onToggle={toggleSecondary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
|
||
</>}
|
||
{bp === 'cardio' && <div className="small dim row" style={{ marginBottom: 10, gap: 5 }}><Icon name="figureRun" style={{ fontSize: 13 }} />{t('Cardio exercises log time + speed instead of weight × reps.')}</div>}
|
||
<textarea className="input" rows={4} maxLength={1000} placeholder={t('Description (optional) — setup, cues, anything you want to remember')}
|
||
value={desc} onChange={e => setDesc(e.target.value)} />
|
||
<div style={{ height: 14 }} />
|
||
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Create exercise')}</Button>
|
||
{existing && <><div style={{ height: 8 }} /><Button variant="danger" icon="trash" onClick={() => { close(); deleteCustomEx(existing) }}>{t('Delete exercise')}</Button></>}
|
||
</>
|
||
}
|
||
export const customExSheet = (existing, onDone, prefill) => ui().openSheet(close => <CustomExForm existing={existing} prefill={prefill} onDone={onDone} close={close} />)
|
||
|
||
export function deleteCustomEx(ex, afterDelete) {
|
||
if (S().active?.entries.some(e => e.id === ex.id)) { toast(t('Finish your current workout first')); return }
|
||
confirmSheet({
|
||
title: t('Delete “{0}”?', ex.n),
|
||
message: t('It will be removed from your routines. Already-logged workouts keep their sets.'),
|
||
confirmText: t('Delete'), danger: true,
|
||
onConfirm: () => {
|
||
update(s => {
|
||
// Keep display and muscle metadata in history before the custom catalogue row disappears.
|
||
const snapshot = exerciseMuscleSnapshot(ex)
|
||
s.workouts.forEach(w => w.entries.forEach(e => {
|
||
if (e.id !== ex.id) return
|
||
e.n = ex.n
|
||
if (!e.muscleSnapshot || !Object.keys(e.muscleSnapshot).length) e.muscleSnapshot = snapshot
|
||
}))
|
||
s.customEx = (s.customEx || []).filter(x => x.id !== ex.id)
|
||
s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) })
|
||
delete s.exWeights[ex.id]
|
||
})
|
||
toast(t('Exercise deleted'))
|
||
afterDelete && afterDelete()
|
||
}
|
||
})
|
||
}
|
||
|
||
/* ============================ exercise picker ============================ */
|
||
// Exercises already used in your routines or past workouts (for the "Chosen" filter + a marker).
|
||
function usageMap(st) {
|
||
const u = {}
|
||
st.routines.forEach(r => r.ex.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 }))
|
||
st.workouts.forEach(w => w.entries.forEach(e => { u[e.id] = (u[e.id] || 0) + 1 }))
|
||
return u
|
||
}
|
||
function ExercisePicker({ onPick, close }) {
|
||
const st = useStore(s => s.S)
|
||
const usage = usageMap(st)
|
||
const [q, setQ] = useState('')
|
||
const [bp, setBp] = useState('') // '' = all, '★' = chosen, else a body part
|
||
const [eq, setEq] = useState('') // '' = any equipment
|
||
const [showAll, setShowAll] = useState(false)
|
||
const [shown, setShown] = useState(50)
|
||
const all = allExercises(st)
|
||
const profile = activeProfile(st)
|
||
let base = all.filter(e =>
|
||
(bp === '★' ? usage[e.id] : (!bp || e.bp === bp)) &&
|
||
matchExercise(e, q))
|
||
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
|
||
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
|
||
const eqOpts = equipmentOf(eqFiltered)
|
||
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
|
||
const eqOn = eqOpts.includes(eq) ? eq : ''
|
||
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
|
||
const chosenCount = Object.keys(usage).length
|
||
return <>
|
||
<h3>{t('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={t('Search {0} exercises…', all.length)} value={q} onChange={e => { setQ(e.target.value); setShown(50) }} /></div>
|
||
{profile && <div className="small dim row" style={{ margin: '8px 0 2px', gap: 6, alignItems: 'center' }}>
|
||
<Icon name="dumbbell" style={{ fontSize: 13 }} />
|
||
{showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)}
|
||
<button className="chip nocap" style={{ marginLeft: 'auto', padding: '3px 10px', fontSize: 12 }} onClick={() => setShowAll(v => !v)}>
|
||
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
|
||
</button>
|
||
</div>}
|
||
<div className="chips" style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
|
||
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}><Icon name="starFill" style={{ fontSize: 12, display: 'inline-block', marginRight: 4, verticalAlign: '-1px' }} />{t('Chosen')} ({chosenCount})</button>}
|
||
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(50) }}>{t('All')}</button>
|
||
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(50) }}>{t(b)}</button>)}
|
||
</div>
|
||
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 10 }}>
|
||
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(50) }}>{t('Any equipment')}</button>
|
||
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
|
||
</div>}
|
||
<div className="list">
|
||
{bp !== '★' && <div className="item" onClick={() => customExSheet(null, ex => onPick(ex), q.trim())}>
|
||
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
|
||
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
|
||
</div>}
|
||
{f.slice(0, shown).map(e => <div key={e.id} className="item" onClick={() => onPick(e)}>
|
||
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
|
||
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}<Icon name="plus" className="chev" />
|
||
</div>)}
|
||
{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}
|
||
</div>
|
||
{f.length > shown && <><div style={{ height: 8 }} /><Button onClick={() => setShown(s => s + 50)}>{t('Show more')}</Button></>}
|
||
</>
|
||
}
|
||
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
|
||
|
||
/* ============================ equipment profiles ============================ */
|
||
// Create or edit one profile ("Home", "Gym", ...): a name plus a checklist of what you have.
|
||
function EquipmentProfileSheet({ profile, close }) {
|
||
const update = useStore(s => s.update)
|
||
const nameRef = useRef(null)
|
||
const [checked, setChecked] = useState(new Set(profile?.equipment || []))
|
||
const toggle = k => setChecked(s => { const n = new Set(s); n.has(k) ? n.delete(k) : n.add(k); return n })
|
||
const save = () => {
|
||
const name = (nameRef.current.value || '').trim()
|
||
if (!name) { return }
|
||
update(s => {
|
||
s.equipProfiles = s.equipProfiles || []
|
||
const equipment = [...checked]
|
||
if (profile) {
|
||
const p = s.equipProfiles.find(x => x.id === profile.id)
|
||
if (p) { p.name = name; p.equipment = equipment }
|
||
} else {
|
||
const p = newProfile(name); p.equipment = equipment
|
||
s.equipProfiles.push(p)
|
||
if (!s.activeEquipId) s.activeEquipId = p.id
|
||
}
|
||
})
|
||
close()
|
||
}
|
||
return <>
|
||
<h3>{profile ? t('Edit profile') : t('New equipment profile')}</h3>
|
||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||
{t('Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.')}
|
||
</div>
|
||
<TextField ref={nameRef} defaultValue={profile?.name || ''} placeholder={t('Profile name')} maxLength={40} />
|
||
<div style={{ height: 12 }} />
|
||
<div className="chips">
|
||
{ALL_EQUIPMENT.map(k => (
|
||
<button key={k} className={'chip' + (checked.has(k) ? ' on' : '')} onClick={() => toggle(k)}>{t(k)}</button>
|
||
))}
|
||
</div>
|
||
<div className="dim small" style={{ marginTop: 10 }}>
|
||
{t('Body-weight exercises are always available, in every profile.')}
|
||
</div>
|
||
<div style={{ height: 14 }} /><Button variant="primary" onClick={save}>{t('Save')}</Button>
|
||
</>
|
||
}
|
||
export const equipmentProfileSheet = profile => ui().openSheet(close => <EquipmentProfileSheet profile={profile} close={close} />)
|
||
|
||
/* ============================ exercise config ============================ */
|
||
// Progression settings for one exercise (issue #17). Shown inside the config sheet because
|
||
// "how does this lift go up" belongs next to sets and reps, not in a separate screen. Left
|
||
// on "follow the routine" it inherits, so most people never touch it.
|
||
const progressionStepOf = (c, mode, ex, unit) =>
|
||
c.inc >= 0 ? c.inc : (mode === 'time' ? 5 : defaultIncrement(ex.id, unit))
|
||
const progressionStepIsValid = (step, policy) =>
|
||
policy === 'off' || (Number.isFinite(step) && step > 0)
|
||
|
||
function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
|
||
const options = POLICIES_FOR[mode] || ['off']
|
||
if (options.length < 2) return null
|
||
const inherited = policyFor({ id: ex.id }, routine, mode)
|
||
const active = policyFor({ ...c, id: ex.id }, routine, mode)
|
||
const inc = progressionStepOf(c, mode, ex, unit)
|
||
const invalid = !progressionStepIsValid(inc, active)
|
||
return <>
|
||
<h4 className="sec">{t('Progression')}</h4>
|
||
<div className="sect-b" style={{ marginBottom: 8 }}>
|
||
<SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={v => setC(x => ({ ...x, prog: v || undefined }))}
|
||
options={[{ value: '', label: t('Follow the routine ({0})', t(POLICY_NAME[inherited])) },
|
||
...options.map(p => ({ value: p, label: t(POLICY_NAME[p]) }))]} />
|
||
</div>
|
||
<div className="small dim" style={{ marginBottom: active === 'off' ? 18 : 10 }}>{t(POLICY_DESC[active])}</div>
|
||
{active !== 'off' && <div className="row cfgrow" style={{ marginBottom: 18 }}>
|
||
<Stepper label={mode === 'time' ? t('Step (seconds)') : t('Step ({0})', unit)} value={inc}
|
||
step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} invalid={invalid} className={invalid ? 'invalid' : ''}
|
||
onChange={v => setC(x => ({ ...x, inc: v }))} />
|
||
{active === 'double' && <Stepper label={t('Reps from')} value={c.repsMin || Math.max(1, (c.reps || 10) - 2)}
|
||
step={1} decimal={false} onChange={v => setC(x => ({ ...x, repsMin: v }))} />}
|
||
</div>}
|
||
{invalid && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: -10, marginBottom: 18 }}>
|
||
{t('Enter a positive step to use this progression rule.')}
|
||
</div>}
|
||
</>
|
||
}
|
||
|
||
function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
|
||
const st = useStore(s => s.S)
|
||
const cardio = isCardio(ex.id)
|
||
const [c, setC] = useState(existing || initial || defaultConfig(ex.id))
|
||
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
|
||
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
|
||
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
|
||
// Both default from the dataset and are then whatever the config says — see isBw.
|
||
const bw = !cardio && isBw({ ...c, id: ex.id })
|
||
const perSide = isPerSide(c)
|
||
const progressionPolicy = policyFor({ ...c, id: ex.id }, routine, mode)
|
||
const progressionStepInvalid = !progressionStepIsValid(progressionStepOf(c, mode, ex, st.unit), progressionPolicy)
|
||
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
|
||
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
|
||
const save = () => {
|
||
if (progressionStepInvalid) return
|
||
close()
|
||
const sets = Math.max(1, Math.round(c.sets) || (cardio ? 1 : 3))
|
||
// Only carry progression settings that differ from the inherited default, so a plan file
|
||
// stays readable and "follow the routine" keeps meaning exactly that.
|
||
const prog = {}
|
||
if (c.prog) prog.prog = c.prog
|
||
if (c.inc > 0) prog.inc = c.inc
|
||
// Written only when it differs from what the dataset already says, so a barbell config
|
||
// stays exactly the shape it was before these flags existed.
|
||
// `bodyweight` is true of a hold as much as of a set of reps; `side` is not — it counts
|
||
// reps, and a timed hold has none. Switching an exercise to Time therefore drops it
|
||
// rather than carrying a flag nothing downstream can read.
|
||
const flags = {}
|
||
if (bw !== isBodyweightEq(ex.id)) flags.bodyweight = bw
|
||
// Free text, e.g. a pyramid's per-set loading ("bar only, +1 plate/side each set") — the
|
||
// sets/reps/weight fields are one flat target and have no room for that on their own.
|
||
// Mode-independent, so it is spread in below rather than folded into `flags`.
|
||
const note = (c.note || '').trim().slice(0, 500)
|
||
const withNote = note ? { note } : {}
|
||
// Only written when there are any, so a plan that never asked for warm-ups keeps the exact
|
||
// shape it had — and reads back as 0 either way (buildSets).
|
||
const warmupSets = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(c.warmupSets) || 0))
|
||
const withWarmups = warmupSets ? { warmupSets } : {}
|
||
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote })
|
||
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups })
|
||
else {
|
||
// A unilateral target is stored even: the split has to divide, and a typed 15 would
|
||
// otherwise plan seven reps on one side and eight on the other, every session.
|
||
const typed = Math.max(1, Math.round(c.reps) || 10)
|
||
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
|
||
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups }
|
||
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
|
||
// A ceiling below the working reps would tell you to add a set on day one.
|
||
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
|
||
// Every set in this exercise becomes a drop-set/rest-pause (buildSets stamps the rows) —
|
||
// decided here, in the plan, not re-decided live each time you train it.
|
||
if (c.intensifier && c.intensifier.type) out.intensifier = c.intensifier
|
||
onSave(out)
|
||
}
|
||
}
|
||
return <>
|
||
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
|
||
<Media ex={ex} />
|
||
{/* The same tags the exercise detail sheet shows, secondaries included: choosing what goes
|
||
into a plan is exactly when "what else does this hit" matters, and until now that was
|
||
only visible from the Exercises tab, after the fact. */}
|
||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0 14px' }}>
|
||
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
|
||
<span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>
|
||
{!cardio && (ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3)
|
||
.map((s, i) => <span key={i} className="tag dim">{t(s)}</span>)}
|
||
</div>
|
||
{ex.desc && <div className="exnote">{ex.desc}</div>}
|
||
{!cardio && <div style={{ marginBottom: 14 }}>
|
||
<Segmented className="seg-range" value={mode} onChange={setMode}
|
||
options={[{ value: 'reps', label: t('Reps') }, { value: 'time', label: t('Time') }]} />
|
||
</div>}
|
||
<div className="row cfgrow" style={{ marginBottom: mode === 'time' ? 8 : 18 }}>
|
||
{cardio ? <>
|
||
<Stepper label={t('Intervals')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
|
||
<Stepper label={t('Minutes')} value={c.min} step={1} decimal={false} onChange={v => setC(x => ({ ...x, min: v }))} />
|
||
<Stepper label={t('Speed (km/h)')} value={c.speed} step={0.5} onChange={v => setC(x => ({ ...x, speed: v }))} />
|
||
</> : mode === 'time' ? <>
|
||
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
|
||
<Stepper label={t('Seconds')} value={c.sec} step={5} decimal={false} onChange={v => setC(x => ({ ...x, sec: v }))} />
|
||
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||
</> : <>
|
||
{/* Rest-pause always trains as exactly two rows — a warm-up at this rep count, then one
|
||
rest-pause work set — so "Sets" has nothing left to mean and only invites a mismatch. */}
|
||
{c.intensifier?.type !== 'restpause' &&
|
||
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />}
|
||
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
|
||
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
|
||
until there is a belt to describe — see the added-weight row below. */}
|
||
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
|
||
</>}
|
||
</div>
|
||
{c.intensifier?.type === 'restpause' && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
|
||
{t('Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.')}
|
||
</div>}
|
||
{/* Planned warm-ups: the session used to start at the work weight and you added every
|
||
warm-up by hand, every time. Rest-pause is excluded because it builds its own warm-up
|
||
row, and cardio because an interval plan has no load to ramp. */}
|
||
{!cardio && c.intensifier?.type !== 'restpause' && <>
|
||
<div className="row cfgrow" style={{ marginBottom: 6 }}>
|
||
<Stepper label={t('Warm-up sets')} value={c.warmupSets || 0} step={1} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, warmupSets: Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(v) || 0)) }))} />
|
||
</div>
|
||
<div className="small dim" style={{ marginBottom: 18 }}>
|
||
{(c.warmupSets || 0) > 0
|
||
? t('Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.')
|
||
: t('Ramp-up sets added before the work sets, so you do not have to add them by hand each session.')}
|
||
</div>
|
||
</>}
|
||
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
|
||
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
|
||
</div>}
|
||
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
|
||
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
|
||
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
|
||
subtitle={bw ? t('No weight to enter — just log the reps.') : t('Ask for a weight on every set.')}>
|
||
<Switch checked={bw} onChange={v => setC(x => ({ ...x, bodyweight: v, weight: v ? 0 : x.weight }))} />
|
||
</Row>
|
||
{mode === 'reps' && <Row icon="shuffle" iconTint="var(--blue)" title={t('Reps per side')}
|
||
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
|
||
{/* Turning it on rounds the target up to an even number, since half of an odd
|
||
total is a rep one side does not get. */}
|
||
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
|
||
</Row>}
|
||
</div>}
|
||
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
|
||
one word per line — so added weight gets the same full-width treatment as sets and
|
||
reps, with its explanation underneath. */}
|
||
{bw && <>
|
||
<div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||
<Stepper label={t('Added ({0})', st.unit)} value={c.weight || 0} step={2.5}
|
||
onChange={v => setC(x => ({ ...x, weight: v }))} />
|
||
</div>
|
||
<div className="small dim" style={{ marginBottom: 18 }}>
|
||
{t('For dips or pull-ups with a belt. Progression then follows the weight.')}
|
||
</div>
|
||
</>}
|
||
{/* The rep ceiling only means something when there is no load to add instead. */}
|
||
{mode === 'reps' && bw && !(c.weight > 0) && <div className="row cfgrow" style={{ marginBottom: 18 }}>
|
||
<Stepper label={t('Top of the range')} value={c.repsMax || 0} step={1} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, repsMax: v }))} />
|
||
</div>}
|
||
{mode === 'reps' && bw && !(c.weight > 0) && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
|
||
{c.repsMax > 0
|
||
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
|
||
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
|
||
</div>}
|
||
{mode === 'reps' && <>
|
||
<h4 className="sec">{t('Drop-set / rest-pause')}</h4>
|
||
<div className="sect-b" style={{ marginBottom: 8 }}>
|
||
<SelectRow title={t('Intensifier')} sheetTitle={t('Intensifier')} value={c.intensifier?.type || ''}
|
||
onChange={v => setC(x => ({
|
||
...x,
|
||
intensifier: !v ? undefined : v === 'dropset'
|
||
? { type: 'dropset', count: x.intensifier?.count || 1, pct: x.intensifier?.pct || 20 }
|
||
// The activation set's own reps are whatever "Reps" above already says — a
|
||
// rest-pause plan only adds two new numbers: the total extra reps wanted past
|
||
// it, and the rest between the bursts that total gets split into.
|
||
: { type: 'restpause', totalReps: x.intensifier?.totalReps || x.reps || 8, restSec: x.intensifier?.restSec || st.restPauseSec || 15 },
|
||
}))}
|
||
options={[
|
||
{ value: '', label: t('None') },
|
||
{ value: 'dropset', label: t('Drop-set') },
|
||
{ value: 'restpause', label: t('Rest-pause') },
|
||
]} />
|
||
</div>
|
||
{c.intensifier?.type === 'dropset' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||
<Stepper label={t('Drops')} value={c.intensifier.count} step={1} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, count: Math.max(1, v) } }))} />
|
||
<Stepper label={t('Weight drop (%)')} value={c.intensifier.pct} step={5} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, pct: Math.max(5, v) } }))} />
|
||
</div>}
|
||
{c.intensifier?.type === 'restpause' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
|
||
<Stepper label={t('Rest-pause reps')} value={c.intensifier.totalReps} step={1} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, totalReps: Math.max(1, v) } }))} />
|
||
<Stepper label={t('Rest (s)')} value={c.intensifier.restSec} step={5} decimal={false}
|
||
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, restSec: Math.max(5, v) } }))} />
|
||
</div>}
|
||
{c.intensifier?.type && <div className="small dim" style={{ marginTop: -2, marginBottom: 18 }}>
|
||
{c.intensifier.type === 'dropset'
|
||
? t('Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.', c.intensifier.count, c.intensifier.pct)
|
||
: t('Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.', c.reps || 0, c.intensifier.totalReps, c.intensifier.restSec)}
|
||
</div>}
|
||
</>}
|
||
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
|
||
<textarea className="input" rows={3} maxLength={500} style={{ marginBottom: 18 }}
|
||
placeholder={t('Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here')}
|
||
value={c.note || ''} onChange={e => setC(x => ({ ...x, note: e.target.value }))} />
|
||
<Button variant="primary" disabled={progressionStepInvalid} onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
|
||
{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}
|
||
{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}
|
||
</>
|
||
}
|
||
export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial) => ui().openSheet(close => <ExConfig ex={ex} existing={existing} initial={initial} onSave={onSave} onDelete={onDelete} routine={routine} close={close} />)
|
||
|
||
/* ============================ glyph picker ============================ */
|
||
// Grouped by what the glyph means for a training day, so picking one is a scan
|
||
// of four short rows rather than a hunt through twenty loose icons.
|
||
export const glyphPicker = (current, onPick) => {
|
||
const cur = glyphOf(current)
|
||
return ui().openSheet(close => <>
|
||
<h3>{t('Pick an icon')}</h3>
|
||
{GLYPH_GROUPS.map(g => (
|
||
<div key={g.key} style={{ marginBottom: 14 }}>
|
||
<div className="sect-t" style={{ padding: '0 2px 7px' }}>{t(g.key)}</div>
|
||
<div className="glyph-grid">
|
||
{g.items.map(n => (
|
||
<button key={n} className={'glyph-cell' + (n === cur ? ' on' : '')}
|
||
onClick={() => { close(); onPick(n) }} aria-label={n}>
|
||
<Icon name={n} />
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
))}
|
||
<div style={{ height: 4 }} />
|
||
</>)
|
||
}
|
||
|
||
/* ============================ share / print / import a plan ============================ */
|
||
export const planToolsSheet = () => ui().openSheet(close => <PlanTools close={close} />)
|
||
|
||
function PlanTools({ close }) {
|
||
const st = useStore(s => s.S)
|
||
const user = useStore(s => s.user)
|
||
const fileRef = useRef(null)
|
||
const hasRoutines = (st.routines || []).some(r => r.ex && r.ex.length)
|
||
|
||
const exportFile = async () => {
|
||
const bundle = buildPlanBundle(st, user?.name ? t('{0}’s plan', user.name) : '')
|
||
const json = JSON.stringify(bundle, null, 2)
|
||
const name = 'opengym-plan-' + todayISO() + '.json'
|
||
if (MOBILE) { try { await shareExport(json, name) } catch (e) { /* dismissed */ } close(); return }
|
||
const blob = new Blob([json], { type: 'application/json' })
|
||
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)
|
||
close(); toast(t('Plan file saved — send it to a friend'))
|
||
}
|
||
const pickFile = ev => {
|
||
const f = ev.target.files[0]; ev.target.value = ''; if (!f) return
|
||
const rd = new FileReader()
|
||
rd.onload = () => {
|
||
try { const bundle = parsePlan(rd.result); close(); planImportSheet(bundle) }
|
||
catch (e) { toast(t('Import failed: {0}', e.message)) }
|
||
}
|
||
rd.readAsText(f)
|
||
}
|
||
|
||
return <>
|
||
<h3>{t('Share your plan')}</h3>
|
||
<div className="muted small" style={{ marginBottom: 16 }}>{t('Send your routines to a friend, or put your week on paper.')}</div>
|
||
<Button variant="primary" icon="upload" onClick={exportFile} disabled={!hasRoutines}>{t('Export plan file')}</Button>
|
||
<div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.')}</div>
|
||
{!MOBILE && <>
|
||
<div style={{ height: 12 }} />
|
||
<Button variant="tinted" icon="download" onClick={() => { close(); printPlan(st, user?.name || '') }} disabled={!hasRoutines}>{t('Print / Save as PDF')}</Button>
|
||
<div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A clean one-page-per-plan printout — no exercise ever splits across a page.')}</div>
|
||
</>}
|
||
{!hasRoutines && <div className="dim small" style={{ margin: '12px 2px 0' }}>{t('Add an exercise to a routine first — an empty plan has nothing to share.')}</div>}
|
||
<h4 className="sec">{t('Got a plan from a friend?')}</h4>
|
||
<Button variant="ghost" icon="folder" onClick={() => fileRef.current?.click()}>{t('Import a plan file')}</Button>
|
||
<input ref={fileRef} type="file" accept="application/json,.json" onChange={pickFile} hidden />
|
||
</>
|
||
}
|
||
|
||
export const planImportSheet = bundle => ui().openSheet(close => <PlanImport bundle={bundle} close={close} />)
|
||
|
||
function PlanImport({ bundle, close }) {
|
||
const [schedule, setSchedule] = useState(false)
|
||
const apply = () => {
|
||
update(s => mergePlan(s, bundle, { schedule }))
|
||
close()
|
||
toast(t('Added {0} routines to your plan', bundle.routineCount))
|
||
nav('/plan')
|
||
}
|
||
return <>
|
||
<h3>{bundle.name ? t('Import “{0}”', bundle.name) : t('Import this plan')}</h3>
|
||
<div className="muted small" style={{ marginBottom: 14 }}>
|
||
{t(bundle.routineCount === 1 ? '{0} routine' : '{0} routines', bundle.routineCount)}
|
||
{' · ' + exCount(bundle.exerciseCount)}
|
||
{bundle.scheduledDays > 0
|
||
? ' · ' + t(bundle.scheduledDays === 1 ? 'scheduled on {0} day' : 'scheduled on {0} days', bundle.scheduledDays)
|
||
: ''}
|
||
</div>
|
||
<div className="dim small" style={{ marginBottom: 14, lineHeight: 1.4 }}>{t('These are added as new routines — nothing you already have is changed.')}</div>
|
||
{bundle.dropped > 0 && <div className="small" style={{ color: 'var(--yellow)', marginBottom: 14, lineHeight: 1.4 }}>
|
||
{t(bundle.dropped === 1
|
||
? '{0} exercise in the file isn’t in your library and was left out.'
|
||
: '{0} exercises in the file aren’t in your library and were left out.', bundle.dropped)}
|
||
</div>}
|
||
{bundle.scheduledDays > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', borderBottom: '1px solid var(--sep)', marginBottom: 16, gap: 12 }}>
|
||
<div><div className="tt" style={{ fontSize: 15 }}>{t('Use this weekly schedule')}</div><div className="small dim">{t('Replaces your current Mon–Sun assignments.')}</div></div>
|
||
<Switch checked={schedule} onChange={setSchedule} />
|
||
</div>}
|
||
<Button variant="primary" onClick={apply}>{t('Add to my plan')}</Button>
|
||
<div style={{ height: 8 }} />
|
||
<Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>
|
||
</>
|
||
}
|
||
|
||
/* ============================ 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 === '' ? t('Back to weekly plan') : v === 'rest' ? t('{0} set to rest', fmtDate(iso)) : t('{0} planned for {1}', (st.routines.find(r => r.id === v) || {}).name, fmtDate(iso)))
|
||
}
|
||
return <>
|
||
<h3>{fmtDate(iso, true)}</h3>
|
||
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyR ? weeklyR.name : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('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)}>
|
||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||
{effId === r.id && <Icon name="check" className="accent" />}</div>)}
|
||
<div className="item" onClick={() => set('rest')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
|
||
{hasOvr && <div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('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>{t(DAYN[day])}</h3>
|
||
<div className="list">
|
||
<div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
|
||
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
|
||
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
|
||
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>
|
||
{st.week[day] === r.id && <Icon name="check" className="accent" />}</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)
|
||
const update = useStore(s => s.update)
|
||
// The session note is editable here rather than only at the finish sheet: what you want to
|
||
// record about a session is often clearer once you have looked at what you actually did.
|
||
const [note, setNote] = useState(w.note || '')
|
||
const saveNote = () => update(s => {
|
||
const rec = s.workouts.find(x => x.id === w.id)
|
||
if (!rec) return
|
||
const text = note.trim().slice(0, NOTE_MAX)
|
||
if (text) rec.note = text; else delete rec.note
|
||
})
|
||
// onBlur alone loses the note: Escape, the Android back gesture and swipe-to-dismiss all
|
||
// close the sheet without ever moving focus out of the textarea. Flush on unmount too. The
|
||
// ref is what makes that work — a cleanup closes over the note from its own render, which
|
||
// is the empty string this started with.
|
||
const latest = useRef(note)
|
||
latest.current = note
|
||
const initial = useRef(w.note || '')
|
||
useEffect(() => () => {
|
||
const text = latest.current.trim().slice(0, NOTE_MAX)
|
||
if (text === initial.current) return
|
||
update(s => {
|
||
const rec = s.workouts.find(x => x.id === w.id)
|
||
if (!rec) return // deleted from this very sheet
|
||
if (text) rec.note = text; else delete rec.note
|
||
})
|
||
}, [])
|
||
return <>
|
||
<h3>{w.name}</h3>
|
||
<div className="muted small" style={{ marginBottom: 12 }}>{[fmtDate(w.d, true), ...durPart(w.end - w.start), fmtVol(w.vol, st.unit), ...(w.bw ? [fmtNum(w.bw) + ' ' + st.unit] : [])].join(' · ')}</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: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
|
||
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
|
||
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
|
||
{e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
|
||
</div>}</div>
|
||
</div>
|
||
})}
|
||
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
|
||
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={note}
|
||
placeholder={t('How the session went as a whole.')}
|
||
onChange={e => setNote(e.target.value)} onBlur={saveNote} />
|
||
<div style={{ height: 14 }} />
|
||
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('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))} aria-label="Previous month"><Icon name="chevronLeft" /></button>
|
||
<h3 style={{ margin: 0 }}>{t(MONTHS_LONG[mo])} {y}</h3>
|
||
<button className="iconbtn" onClick={() => setCur(new Date(y, mo + 1, 1))} aria-label="Next month"><Icon name="chevronRight" /></button>
|
||
</div>
|
||
<div className="small muted" style={{ textAlign: 'center' }}>{monthWs.length ? `${t(monthWs.length === 1 ? '{0} workout' : '{0} workouts', monthWs.length)} · ${fmtDur(monthMs)} · ${fmtVol(monthVol, st.unit)}` : t('No workouts this month')}</div>
|
||
<div className="cal-grid">{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(l => <div key={l} className="cal-h">{t(l)}</div>)}{cells}</div>
|
||
<div className="cal-legend">
|
||
<span><i style={{ background: 'var(--acc)' }} />{t('Trained')}</span>
|
||
<span><i style={{ background: 'var(--label-3)' }} />{t('Planned')}</span>
|
||
<span><i style={{ background: 'var(--orange)' }} />{t('Rescheduled')}</span>
|
||
</div>
|
||
<div className="small dim" style={{ textAlign: 'center', marginTop: 10 }}>{t('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 glyph = glyphOf((st.routines.find(r => r.id === w.routineId) || {}).emoji)
|
||
return <div className="item" onClick={onClick}>
|
||
<span className="lrow-i" style={{ width: 34, height: 34, borderRadius: 8, fontSize: 19 }}><Icon name={glyph} /></span>
|
||
<div className="grow"><div className="tt">{w.name}</div>
|
||
<div className="ss">{[fmtDate(w.d, true), ...durPart(w.end - w.start), t('{0} sets', setsDone(w)), fmtVol(w.vol, st.unit)].join(' · ')}</div></div>
|
||
{w.prs && w.prs.length > 0 && <span className="pr"><Icon name="trophy" />{w.prs.length} PR</span>}
|
||
<Icon name="chevronRight" className="chev" />
|
||
</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
|
||
// The prescription is applied as the session is built, so you walk up to the bar with the
|
||
// right weight already on the screen instead of being told about it afterwards. `plan` is
|
||
// kept on the entry purely so the workout can explain the number it chose.
|
||
const entries = (r ? r.ex : []).map(cfg => {
|
||
const plan = nextPrescription(st, cfg, r)
|
||
const step = defaultIncrement(cfg.id, st.unit)
|
||
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step }), plan, step), cfg)
|
||
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
|
||
})
|
||
update(s => {
|
||
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }
|
||
})
|
||
useUI.getState().stopRest()
|
||
nav('/workout')
|
||
}
|
||
function TopWeight({ entryIdx, close }) {
|
||
const st = useStore(s => s.S)
|
||
const A = st.active
|
||
// The workout can end underneath this sheet: finishing from the last exercise clears
|
||
// `active`, and this re-renders before the sheet is torn down. Everything below is
|
||
// read defensively and the sheet dismisses itself — reading A.entries straight took
|
||
// the whole app down with it. Hooks still run unconditionally, so the bail-out has
|
||
// to sit after every one of them.
|
||
const entry = A ? A.entries[entryIdx] : null
|
||
const ex = entry && EXIDX[entry.id]
|
||
const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0
|
||
const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0
|
||
const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0)
|
||
useEffect(() => { if (!entry) close() }, [!entry])
|
||
|
||
const units = supersetUnits(A ? A.entries : [])
|
||
const unit = entry ? unitOf(units, entryIdx) : []
|
||
const unitDone = !!entry && unit.every(i => A.entries[i].sets.every(s => s.done))
|
||
const nextUnit = unitDone ? nextUnfinishedUnit(A.entries, units, entryIdx) : null
|
||
const workoutDone = unitDone && !nextUnit
|
||
if (!entry || !ex) return null
|
||
|
||
const commit = advance => {
|
||
const n = Math.round((v || 0) * 10) / 10
|
||
if (!isFinite(n) || n < 0) { toast(t('Enter a valid weight')); return }
|
||
update(s => {
|
||
s.active.entries[entryIdx].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 && unitDone) {
|
||
if (workoutDone) workoutCompleteSheet() // no unfinished unit → finish/continue prompt
|
||
else update(s => { s.active.cur = nextUnit[0] })
|
||
} else toast(t('Tracked — next time starts at {0}', fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit))
|
||
}
|
||
return <>
|
||
<h3 className="capitalize row" style={{ gap: 8 }}><Icon name="checkCircle" style={{ color: 'var(--acc)' }} />{t('{0} done', exerciseNameFor(ex))}</h3>
|
||
<div className="muted small">{t('Confirm the weight you worked with — your highest becomes the default next time.')}{!unitDone && unit.length > 1 ? ' ' + t('Then finish the superset partner.') : ''}</div>
|
||
<WeightInput value={v} setValue={setV} unit={st.unit} />
|
||
<div style={{ height: 10 }} />
|
||
{prevBest > 0 ? <div className="small dim" style={{ textAlign: 'center', marginBottom: 12 }}>{t('Previous best:')} {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && <span style={{ color: 'var(--yellow)' }}> — {t('new record!')}</span>}</div> : <div style={{ height: 4 }} />}
|
||
{unitDone ? <>
|
||
<Button variant="primary" trailingIcon={workoutDone ? null : 'chevronRight'} onClick={() => commit(true)}>{workoutDone ? t('Save') : t('Save & next exercise')}</Button>
|
||
<div style={{ height: 8 }} /><Button variant="ghost" className="dim" onClick={() => commit(false)}>{t('Just close')}</Button>
|
||
</> : <Button variant="primary" onClick={() => commit(false)}>{t('Save weight')}</Button>}
|
||
</>
|
||
}
|
||
export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight entryIdx={entryIdx} close={close} />)
|
||
|
||
/* ============================ exercise notes ============================
|
||
Two notes, one sheet, because from the user's side it is one question — "what do I want to
|
||
remember about this exercise?" — with two different lifetimes:
|
||
|
||
· today's note belongs to this session and is stored on the workout entry. It is history:
|
||
what happened, how it felt. The PIN is the user saying "this one is for next time", which
|
||
only they can know at the moment of writing — see pinnedNoteFor.
|
||
· the standing note belongs to the exercise itself and lives in S.exNotes. Seat height, pin
|
||
position, a form cue. True every session, so it is shown every session and never expires.
|
||
|
||
A routine's own `note` (a plan's instruction for this exercise) is edited in the config sheet
|
||
and is deliberately not here: it belongs to the plan, not to the day or to the movement. */
|
||
function ExerciseNote({ entryIdx, close }) {
|
||
const st = useStore(s => s.S)
|
||
const update = useStore(s => s.update)
|
||
const A = st.active
|
||
const entry = A ? A.entries[entryIdx] : null
|
||
const ex = entry ? exOr(entry.id) : null
|
||
const [note, setNote] = useState(entry?.note || '')
|
||
const [pin, setPin] = useState(!!entry?.notePin)
|
||
const [standing, setStanding] = useState(entry ? (st.exNotes?.[entry.id] || '') : '')
|
||
useEffect(() => { if (!entry) close() }, [!entry])
|
||
if (!entry) return null
|
||
|
||
const save = () => {
|
||
const today = note.trim().slice(0, NOTE_MAX)
|
||
const always = standing.trim().slice(0, NOTE_MAX)
|
||
update(s => {
|
||
const e = s.active?.entries?.[entryIdx]
|
||
if (e) {
|
||
if (today) { e.note = today; if (pin) e.notePin = true; else delete e.notePin }
|
||
else { delete e.note; delete e.notePin }
|
||
}
|
||
s.exNotes = s.exNotes || {}
|
||
if (always) s.exNotes[entry.id] = always
|
||
else delete s.exNotes[entry.id]
|
||
})
|
||
close()
|
||
}
|
||
|
||
return <>
|
||
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
|
||
<div className="small muted" style={{ marginBottom: 6 }}>{t('This session')}</div>
|
||
<textarea className="input" rows={3} maxLength={NOTE_MAX} value={note}
|
||
placeholder={t('How it went, what to change — kept with today’s workout.')}
|
||
onChange={e => setNote(e.target.value)} />
|
||
<div style={{ height: 10 }} />
|
||
<div className="sect-b">
|
||
<Row icon="flag" iconTint="var(--yellow)" title={t('Show this next time')}
|
||
subtitle={t('Brings it up again the next time you train this exercise.')}>
|
||
<Switch checked={pin} onChange={setPin} disabled={!note.trim()} />
|
||
</Row>
|
||
</div>
|
||
<div style={{ height: 18 }} />
|
||
<div className="small muted" style={{ marginBottom: 6 }}>{t('Always for this exercise')}</div>
|
||
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={standing}
|
||
placeholder={t('Seat height, pin position, a form cue — shown every session.')}
|
||
onChange={e => setStanding(e.target.value)} />
|
||
<div style={{ height: 18 }} />
|
||
<Button variant="primary" onClick={save}>{t('Save')}</Button>
|
||
</>
|
||
}
|
||
export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNote entryIdx={entryIdx} close={close} />)
|
||
|
||
/* The session note: how the whole workout went, as opposed to how one exercise went. It lives
|
||
on the active session, so buildCompletedWorkout carries it onto the finished workout and it
|
||
shows up again in history — where it stays editable. Written here rather than only after the
|
||
fact because "notes you can write during a workout" is the point; a note you can only add
|
||
once the session is filed is a different, smaller feature. */
|
||
function SessionNote({ close }) {
|
||
const st = useStore(s => s.S)
|
||
const update = useStore(s => s.update)
|
||
const A = st.active
|
||
const [note, setNote] = useState(A?.note || '')
|
||
useEffect(() => { if (!A) close() }, [!A])
|
||
if (!A) return null
|
||
|
||
const save = () => {
|
||
const text = note.trim().slice(0, NOTE_MAX)
|
||
update(s => { if (!s.active) return; if (text) s.active.note = text; else delete s.active.note })
|
||
close()
|
||
}
|
||
|
||
return <>
|
||
<h3>{t('Session note')}</h3>
|
||
<textarea className="input" rows={4} maxLength={NOTE_MAX} value={note}
|
||
placeholder={t('How the session went as a whole.')}
|
||
onChange={e => setNote(e.target.value)} />
|
||
<div style={{ height: 18 }} />
|
||
<Button variant="primary" onClick={save}>{t('Save')}</Button>
|
||
</>
|
||
}
|
||
export const sessionNoteSheet = () => ui().openSheet(close => <SessionNote close={close} />)
|
||
|
||
/* Drop-set drops and rest-pause bursts are edited inline on the set row itself (Workout.jsx) —
|
||
no sheet, no timer. A planned exercise (see the "Intensifier" config below) arrives with them
|
||
already computed via applyIntensifierPlan; an unplanned straight set can still grow one live
|
||
by tapping "+ Drop"/"+ Burst", which appends with the same suggested-next-value math. */
|
||
|
||
// Shown when the last exercise's last set is checked — finish, or keep going.
|
||
function WorkoutComplete({ close }) {
|
||
return <div style={{ textAlign: 'center', padding: '8px 0' }}>
|
||
<div style={{ fontSize: 44, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="checkCircle" /></div>
|
||
<h3 style={{ margin: '8px 0' }}>{t("That's the whole workout!")}</h3>
|
||
<div className="muted small" style={{ marginBottom: 16 }}>{t('Every exercise done — great work. Finish up, or keep going and add another exercise.')}</div>
|
||
<Button variant="primary" icon="flag" onClick={() => { close(); finishWorkout() }}>{t('Finish workout')}</Button>
|
||
<div style={{ height: 8 }} />
|
||
<Button onClick={() => { close(); useUI.getState().toast(t('Keep going — tap “+ Add exercise” below')) }}>{t('Continue workout')}</Button>
|
||
</div>
|
||
}
|
||
export const workoutCompleteSheet = () => ui().openSheet(close => <WorkoutComplete close={close} />, { kind: 'center' })
|
||
|
||
function FinishSummary({ w, prs, e1prs = [], close }) {
|
||
const st = useStore(s => s.S)
|
||
return <div style={{ textAlign: 'center', padding: '8px 0' }}>
|
||
<div style={{ fontSize: 44, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="trophy" /></div>
|
||
<h3 style={{ margin: '8px 0' }}>{t('Workout complete!')}</h3>
|
||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||
<div className="tile"><div className="l">{t('Duration')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtDur(w.end - w.start)}</div></div>
|
||
<div className="tile"><div className="l">{t('Volume')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{fmtVol(w.vol, st.unit)}</div></div>
|
||
<div className="tile"><div className="l">{t('Sets')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{t('{0} sets · {1} work', setsDone(w), workSetsDone(w))}</div></div>
|
||
<div className="tile"><div className="l">{t('PRs')}</div><div className="v" style={{ fontSize: 20 }}>{prs.length || '—'}</div></div>
|
||
</div>
|
||
{(prs.length > 0 || e1prs.length > 0) && <div style={{ textAlign: 'left', marginBottom: 12 }}>
|
||
{prs.map(id => <div key={id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="trophy" style={{ fontSize: 13 }} />{t('New PR:')} {EXIDX[id] ? exerciseNameFor(EXIDX[id]) : id}</div>)}
|
||
{e1prs.map(p => <div key={p.id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="chartLine" style={{ fontSize: 13 }} />{t('Best estimated 1RM:')} {EXIDX[p.id] ? exerciseNameFor(EXIDX[p.id]) : p.id} · {fmtNum(p.est)} {st.unit}</div>)}
|
||
</div>}
|
||
<h4 className="sec" style={{ textAlign: 'left' }}>{t('What you just trained')}</h4>
|
||
<BodyMap load={loadOfWorkouts([w])} body={st.body} />
|
||
<div style={{ height: 14 }} />
|
||
<Button variant="primary" onClick={() => { close(); nav('/home') }}>{t('Nice!')}</Button>
|
||
</div>
|
||
}
|
||
export function finishWorkout() {
|
||
const A = S().active
|
||
if (!A) return
|
||
const done = setsDoneActive(A)
|
||
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
|
||
if (!done) { confirmSheet({ title: t('Nothing logged yet'), message: t('You haven’t checked off any sets. Finish the workout anyway?'), confirmText: t('Finish anyway'), onConfirm: doFinishWorkout }); return }
|
||
if (done < total) { confirmSheet({ title: t('Finish early?'), message: t(total - done === 1 ? '{0} set still unchecked. Finish the workout now?' : '{0} sets still unchecked. Finish the workout now?', total - done), confirmText: t('Finish workout'), onConfirm: doFinishWorkout }); return }
|
||
doFinishWorkout()
|
||
}
|
||
function doFinishWorkout() {
|
||
const st = S()
|
||
const A = st.active
|
||
if (!A) return
|
||
const prs = []
|
||
const e1prs = []
|
||
A.entries.forEach(e => {
|
||
const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))
|
||
if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)
|
||
// A heavier estimate without a heavier top set is its own kind of progress —
|
||
// same weight for more reps. Reported separately so it can't be read as a load PR.
|
||
const rec = is1RMRecord(st, e.id, e)
|
||
if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })
|
||
})
|
||
const w = buildCompletedWorkout(A, {
|
||
end: Date.now(),
|
||
prs,
|
||
snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,
|
||
})
|
||
w.vol = workoutVolume(w)
|
||
update(s => {
|
||
w.entries.forEach(e => {
|
||
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).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
|
||
})
|
||
useStore.getState().autoBackupNow()
|
||
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} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
|
||
}
|