import { useEffect, useMemo, 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, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js' import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js' import { beep, vibrate } from './lib/sound.js' import { t, dateLocale, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js' import { nav } from './lib/nav.js' import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js' import Media, { Thumb } from './components/Media.jsx' import LineChart from './components/LineChart.jsx' import Stepper from './components/Stepper.jsx' import Icon from './components/Icon.jsx' import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, NumberField, MultiSelectRow } from './components/ui.jsx' import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js' import BodyMap from './components/BodyMap.jsx' import MuscleExplorer from './components/MuscleExplorer.jsx' import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata, inMuscleOrder } from './lib/muscles.js' import { parseImport, mergeImport } from './lib/import-csv.js' import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js' import { buildPlanBundle, parsePlan, mergePlan, printPlan, planPrintHTML } from './lib/plan-share.js' import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js' import { exerciseHistory } from './lib/exercise-history.js' import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js' import { normalizeRepRange } from './lib/rep-range.js' import { MOBILE, shareExport, printHtml } from './lib/mobile.js' import { buildCompletedWorkout } from './lib/finish-workout.js' import { isWarmupRow, hasCompletedWork } from './lib/workout-model.js' import { nextUnfinishedUnit } from './lib/supersetFlow.js' import { swapActiveExercise } from './lib/active-exercise-swap.js' import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js' import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js' import { buildSessionEntries } from './lib/session-start.js' import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js' import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.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, onCancel, close }) { return
{title &&

{title}

}
{message}
} // Sign-in found workouts on this device that the profile does not have (logged while signed // out). The profile is the truth — settings and plan come from the server either way — the // question is only whether these entries are added to it or dropped. Resolves true to add. export function askAddDeviceData(extras) { return new Promise(resolve => confirmSheet({ title: t('Add this device\'s workouts to your profile?'), message: t('{0} workouts and {1} weigh-ins were logged on this device while signed out. Add them to your profile, or keep the profile exactly as it is on the server.', extras.workouts, extras.bodyweight), confirmText: t('Add them'), cancelText: t('Keep profile as is'), onConfirm: () => resolve(true), onCancel: () => resolve(false), locked: true })) } /* ============================ menu sheet ============================ */ // A list of actions, one per row, closing on tap. This is where the workout screen parks // everything that is not a set you are about to log: the point of a single "more" button is // that the ten things you do once a session stop competing with the two you do every set. // items: [{ icon, label, sub, onClick, danger, disabled, on }] — `on` draws a check for toggles. function MenuSheet({ title, subtitle, items, close }) { return <> {title &&

{title}

} {subtitle &&
{subtitle}
}
{items.filter(Boolean).map((it, i) =>
{ close(); it.onClick && it.onClick() })}> {it.icon && }
{it.label}
{it.sub &&
{it.sub}
}
{it.on != null && }
)}
} export function menuSheet(opts) { ui().openSheet(close => ) } // Themed replacement for window.confirm — callback-based (no blocking). export function confirmSheet(opts) { ui().openSheet(close => , { kind: 'center', ...(opts.locked ? { locked: true } : {}) }) } /* ============================ starter plan ============================ */ // Plan names and blurbs live here, not in lib/starter.js: check-source-strings.mjs only finds // string literals written inside a t() call, so copy parked in the catalog and passed in as a // variable is invisible to it — it would quietly stay English in every language. const PLAN_COPY = { ppl: () => ({ name: t('Push / Pull / Legs'), about: t('Push, pull and legs each get their own day.') }), 'upper-lower': () => ({ name: t('Upper / Lower'), about: t('Upper body twice, lower body twice.') }), 'full-body': () => ({ name: t('Full Body'), about: t('Three sessions, the whole body each time.') }), '5x5': () => ({ name: t('5×5'), about: t('Five sets of five on the main barbell lifts.') }) } // Adds the plan's routines and puts them on its weekdays. Existing routines are never touched // and only the weekdays the plan asks for are reassigned; an id with no plan behind it changes // nothing at all. planId is deliberately required — a default invites `onClick={loadStarterPlan}`, // which hands the click event in as the plan and silently loads nothing. export function loadStarterPlan(planId) { const plan = buildStarterPlan(planId) if (!plan) return false update(st => { st.routines.push(...plan.routines) plan.schedule.forEach(({ day, routineId }) => { st.week[day] = [routineId] }) }) toast(t('{0} loaded', PLAN_COPY[planId]().name)) return true } // Intl joins the days the way each language does it — "and" vs "und", "、" in Chinese. const dayList = days => new Intl.ListFormat(dateLocale()).format(days.map(d => t(DAYN[d]))) function StarterPlanChooser({ close }) { const week = useStore(s => s.S.week) const routines = useStore(s => s.S.routines) const choose = (id, name) => { const days = starterPlanDays(id) close() // A confirmation is only worth showing when one of those days is actually occupied — by a // routine that still exists, not by a stale id the Plan already shows as "Rest". const taken = day => [].concat(week[day] || []).some(id => routines.some(r => r.id === id)) if (!days.some(taken)) { loadStarterPlan(id); return } confirmSheet({ title: t('Load {0}?', name), message: t('The new plan will be scheduled on {0}. Existing routines are kept — only those days of the weekly plan change.', dayList(days)), confirmText: t('Load plan'), onConfirm: () => loadStarterPlan(id) }) } return <>

{t('Choose starter plan')}

{starterPlanOptions().map(({ id, days }) => { const { name, about } = PLAN_COPY[id]() return
choose(id, name))}>
{name}
{t('{0} days per week', days)} · {about}
})}
} export const starterPlanSheet = () => ui().openSheet(close => ) /* ============================ 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 <>
{fmtNum(value)} {unit}
} /* ============================ 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 ?

{t('Quick check-in')}

:

{t('Log body weight')}

}
{required ? t('Slide or tap to set your weight — tracked before every workout so your curve stays honest.') : t('Today') + ', ' + fmtDate(todayISO(), true)}
{required && <>
} {!required && recent.length > 0 && <>

{t('Recent weigh-ins')}

{recent.map(b =>
{fmtDate(b.d, true)} {fmtNum(b.w)} {unit}
)}
} } export function bwSheet(opts = {}) { const h = ui().openSheet(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 <>

{parsed.source ? t('Import from {0}', parsed.source) : t('Import history')}

{parsed.from === parsed.to ? fmtDate(parsed.from, true) : fmtDate(parsed.from, true) + ' – ' + fmtDate(parsed.to, true)}
{isBW ? <>
{t('Weigh-ins')}
{parsed.bodyweight.length}
{t('New')}
{fresh}
: <>
{t('Workouts')}
{parsed.workouts.length}
{t('Sets')}
{parsed.sets}
{t('Exercises matched')}
{parsed.matched}
{t('Added as your own')}
{parsed.created}
}
{parsed.mixedUnits ?
{t('The file mixes kg and lb — each set is converted to {0}.', st.unit)}
: parsed.converted ?
{t('The file is in {0} and your profile is in {1} — weights will be converted.', parsed.fileUnit, st.unit)}
: null} {!isBW && !parsed.fileUnit && !parsed.mixedUnits &&
{t('The file does not say which unit it uses — numbers are imported as they are.')}
} {have > 0 &&
{t('{0} days already have data here and will be left alone.', have)}
} {/* 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 &&
{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')}
} {!isBW && parsed.unmatchedNames.length > 0 && <>

{t('Not in the library — added as your own exercises')}

{parsed.unmatchedNames.slice(0, 12).map(n => {n})} {parsed.unmatchedNames.length > 12 && +{parsed.unmatchedNames.length - 12}}
}
} /** 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 => ) onDone && onDone() } rd.onerror = () => toast(t('Could not read that file')) rd.readAsText(file) } /* ============================ import from Hevy API ============================ */ // The key lives in React state for this sheet only — dismissed with the sheet, never // written to the store / localStorage / the server. After a successful fetch the user // picks workouts and/or weigh-ins before anything is merged. export function importFromHevy() { ui().openSheet(close => ) } function hevyProgressLabel(p) { if (!p) return t('Fetching from Hevy…') if (p.stage === 'templates') return t('Fetching exercises… ({0}/{1})', p.page, p.pageCount) if (p.stage === 'workouts') return t('Fetching workouts… ({0}/{1})', p.page, p.pageCount) if (p.stage === 'routines') return t('Fetching routines… ({0}/{1})', p.page, p.pageCount) if (p.stage === 'body') return t('Fetching weigh-ins… ({0}/{1})', p.page, p.pageCount) if (p.stage === 'parse') return t('Matching exercises…') return t('Fetching from Hevy…') } function HevyImportSheet({ close }) { const st = useStore(s => s.S) const [apiKey, setApiKey] = useState('') const [busy, setBusy] = useState(false) const [progress, setProgress] = useState(null) const [payload, setPayload] = useState(null) // { workouts, routines, bodyweight } const [wantWorkouts, setWantWorkouts] = useState(true) const [wantRoutines, setWantRoutines] = useState(true) const [wantBody, setWantBody] = useState(true) const keyRef = useRef(null) // Drop the key from memory when the sheet goes away (unmount or successful import). useEffect(() => () => { setApiKey('') }, []) const wipeKey = () => { setApiKey(''); if (keyRef.current) keyRef.current.value = '' } const fetchAccount = async () => { const key = apiKey.trim() if (!key) { toast(t('Paste your Hevy API key first')); return } setBusy(true) setProgress({ stage: 'templates', page: 1, pageCount: 1 }) setPayload(null) try { const data = await importHevyData(key, { unit: st.unit, onProgress: setProgress }) wipeKey() const empty = !data.workouts.workouts.length && !data.routines.routines.length && !data.bodyweight.bodyweight.length if (empty) { toast(t('Nothing to import from Hevy')) return } setWantWorkouts(!!data.workouts.workouts.length) setWantRoutines(!!data.routines.routines.length) setWantBody(!!data.bodyweight.bodyweight.length) setPayload(data) } catch (e) { if (e instanceof HevyApiError && e.message === 'auth') toast(t('That Hevy API key was refused')) else if (e instanceof HevyApiError && e.message === 'rate-limit') toast(t('Hevy is rate-limiting requests — wait a minute and try again')) else if (e instanceof HevyApiError && e.message === 'empty') toast(t('Paste your Hevy API key first')) else toast(t('Could not reach Hevy — check the key and try again')) } finally { setBusy(false) setProgress(null) } } const doImport = () => { if (!payload) return const parts = [] let addedW = 0, addedR = 0, addedB = 0 update(s => { if (wantWorkouts && payload.workouts.workouts.length) { const res = mergeImport(s, payload.workouts) addedW = res.added parts.push(t('{0} workouts imported', res.added)) } if (wantRoutines && payload.routines.routines.length) { const res = mergeHevyRoutines(s, payload.routines) addedR = res.added parts.push(t('{0} routines imported', res.added)) } if (wantBody && payload.bodyweight.bodyweight.length) { const res = mergeImport(s, payload.bodyweight) addedB = res.added parts.push(t('{0} weigh-ins imported', res.added)) } }) close() if (!addedW && !addedR && !addedB) toast(t('Nothing new to import')) else toast(parts.join(' · ')) } if (!payload) { return <>

{t('Import from Hevy')}

{t('Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.')}
setApiKey(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !busy) fetchAccount() }} />
{t('Get your API key')} — {t('Hevy → Settings → Developer')}
{busy &&
{hevyProgressLabel(progress)}
}
} const w = payload.workouts const r = payload.routines const b = payload.bodyweight const haveW = w.workouts.filter(x => st.workouts.some(y => y.d === x.d)).length const freshW = w.workouts.length - haveW const haveB = b.bodyweight.filter(x => st.bodyweight.some(y => y.d === x.d)).length const freshB = b.bodyweight.length - haveB // Routines are always added as new copies (same as plan import). const freshR = r.routines.length const canImport = (wantWorkouts && freshW > 0) || (wantRoutines && freshR > 0) || (wantBody && freshB > 0) const unmatched = [...new Set([ ...(wantWorkouts ? w.unmatchedNames : []), ...(wantRoutines ? r.unmatchedNames : []), ])].sort() return <>

{t('Import from Hevy')}

{w.from && (w.from === w.to ? fmtDate(w.from, true) : fmtDate(w.from, true) + ' – ' + fmtDate(w.to, true))} {!w.from && b.from && (b.from === b.to ? fmtDate(b.from, true) : fmtDate(b.from, true) + ' – ' + fmtDate(b.to, true))}
{t('Workouts')}
{w.workouts.length}
{t('Routines')}
{r.routines.length}
{t('Exercises matched')}
{w.matched + r.matched}
{t('Added as your own')}
{w.created + r.created}
{w.workouts.length > 0 &&
{t('Import workouts')}
{t('{0} new · {1} days already here', freshW, haveW)}
} {r.routines.length > 0 &&
{t('Import routines')}
{t('{0} routines · {1} exercises — added as new plans', freshR, r.exerciseCount)}
} {b.bodyweight.length > 0 &&
{t('Import weigh-ins')}
{t('{0} new · {1} days already here', freshB, haveB)}
} {!b.bodyweight.length &&
} {(w.converted || r.converted) &&
{t('Hevy stores weights in kg — they will be converted to {0}.', st.unit)}
} {wantWorkouts && (w.rirSets + w.rpeSets) > 0 &&
{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.', w.rirSets || w.rpeSets, w.rirSets ? 'RIR' : 'RPE')}
} {unmatched.length > 0 && <>

{t('Not in the library — added as your own exercises')}

{unmatched.slice(0, 12).map(n => {n})} {unmatched.length > 12 && +{unmatched.length - 12}}
}
} /* ============================ 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 <>

{t('Target weight')}

{t('Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.')}
{st.targetW && <>
} } export const goalSheet = () => ui().openSheet(close => ) /* ============================ bar weight ============================ */ // One editor for every place the bar weight shows up (exercise detail, exercise config, // mid-workout sheet): a stepper over the effective value. What it saves is per exercise // and lives in S.barWeights, in the profile unit (see lib/bar.js) — stepping or typing // down to 0 clears the override and the field falls back to the default for the bar // type, the same "0 drops the key" shape a nullable set field has. function BarWeightEditor({ ex, extra }) { const st = useStore(s => s.S) const explicit = hasBarOverride(st, ex.id) const def = defaultBarWeight(ex.eq, st.unit) const setBar = v => update(s => { s.barWeights = s.barWeights || {} const n = Math.max(0, Math.round((v || 0) * 100) / 100) if (n > 0) s.barWeights[ex.id] = n; else delete s.barWeights[ex.id] }) return <>
{explicit ? t('Set to 0 to go back to the default ({0}).', fmtNum(def) + ' ' + st.unit) : t('Default for this bar type.')} {extra ? ' ' + extra : ''}
} // Tiny mid-workout sheet behind the "Bar … · … per side" chip — same value, same editor. function BarWeightSheet({ exId, close }) { const ex = exOr(exId) return <>

{t('Bar weight')}

{exerciseNameFor(ex)}
} export const barWeightSheet = exId => ui().openSheet(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 <>

{t('Estimated 1RM')}

{best &&
{t('From your log:')} {fmtNum(best.est)} {st.unit} · {t('{0} × {1} on {2}', fmtNum(best.w) + ' ' + st.unit, best.r, fmtDate(best.d, true))}
}
{t('Estimate')} {est === null ? '—' : fmtNum(est) + ' ' + st.unit}
{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.')}
} function ExerciseDetail({ ex, close }) { const st = useStore(s => s.S) const last = lastEntryFor(st, ex.id) const best = bestWeightFor(st, ex.id) const fav = isFav(st, ex.id) const flipFav = () => { let on = false update(s => { on = toggleFav(s, ex.id) }) toast(on ? t('Added to favourites') : t('Removed from favourites')) } return <>

{exerciseNameFor(ex)}

{t(ex.bp)} {ex.bp === 'cardio' ? {t(MUSCLE_NAME['cardiovascular system'])} : (ex.primaries?.length ? ex.primaries : (ex.tg ? [ex.tg] : [])).map((s, i) => {t(MUSCLE_NAME[s] || s)})} {t(ex.eq)} {(ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3).map((s, i) => {t(MUSCLE_NAME[s] || s)})}
{ex.desc &&
{ex.desc}
} {best > 0 &&
{t('Best:')} {fmtNum(best)} {st.unit}{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}
} {last && } {ex.custom &&
} {usesBar(ex) && <>

{t('Bar weight')}

} {!isCardio(ex) && } {instrFor(ex).length > 0 &&<>

{t('How to')}{!INSTR_LANGS.includes(getLang()) && · {t('instructions in English')}}

    {instrFor(ex).map((s, i) =>
  1. {s}
  2. )}
} } export const exerciseDetailSheet = ex => ui().openSheet(close => ) /* ============================ exercise history ============================ */ // What you did on this exercise before, reachable mid-workout (issue #43): the curve first, // then the last sessions set by set, so the question "what did I do last month" is answered // without leaving the workout for Stats. Derived once per log change — the sheet re-renders on // every store tick while a session runs, and LineChart drops its hover whenever `points` // changes identity, so a series rebuilt per render would lose the tooltip under your finger. function ExerciseHistory({ exId }) { const st = useStore(s => s.S) const ex = exOr(exId) const h = useMemo(() => exerciseHistory(st, exId), [st.workouts, exId]) const [curve, setCurve] = useState('top') const onE1 = curve === 'e1rm' && h.e1rmPoints.length > 0 const unit = h.metric === 'weight' ? st.unit : h.metric === 'reps' ? t('reps') : h.metric === 'sec' ? 's' : t('min') const e1Best = useMemo(() => Math.max(0, ...h.e1rmPoints.map(p => p.y)), [h]) if (!h.total) return <>

{exerciseNameFor(ex)}

{t('No sessions logged yet')}
const tail = s => [ s.volume > 0 && t('Volume') + ' ' + fmtVol(s.volume, st.unit), s.e1rm != null && t('Est. 1RM') + ' ' + fmtNum(s.e1rm) + ' ' + st.unit, ].filter(Boolean).join(' · ') return <>

{exerciseNameFor(ex)}

{t('Exercise history')} · {t(h.total === 1 ? '{0} session' : '{0} sessions', h.total)}
{/* Only reps work with a load produces an estimate, so the toggle is absent for the rest. */} {h.e1rmPoints.length > 0 && h.metric === 'weight' && }
{t('Best:')} {fmtNum(onE1 ? e1Best : h.best)} {onE1 ? st.unit : unit}

{h.sessions.length < h.total ? t('Last {0} sessions', h.sessions.length) : t('Sessions')}

{h.sessions.map(s =>
{fmtDate(s.d, true)} {s.pr && PR}
{s.sets.map(x => setLabel(exId, x, s.target)).join(' · ')}
{tail(s) &&
{tail(s)}
}
{s.value != null && s.value > 0 && {fmtNum(s.value)} {unit}}
)}
} export const exerciseHistorySheet = exId => ui().openSheet(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}', capWords(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 <>

{t('Add “{0}”', exerciseNameFor(ex))}

{t('Pick a routine — sets, reps & weight come next.')}
{st.routines.map(r =>
pick(r.id))}>
{r.name}
{exCount(r.ex.length)}
{r.ex.some(e => e.id === ex.id) && {t('already in')}}
)}
pick('_new'))}>
{t('New routine')}
{t('Create one and start with this exercise')}
} export const addToRoutineSheet = ex => ui().openSheet(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 nameRef = useRef(null) const onNameFocus = useSheetKeyboard(nameRef) const [n, setN] = useState(existing ? existing.n : (prefill || '')) const [bp, setBp] = useState(existing ? existing.bp : '') const [eq, setEq] = useState(existing ? (existing.eq || '') : '') const [desc, setDesc] = useState(existing ? (existing.desc || '') : '') const [primaries, setPrimaries] = useState(() => { if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...existing.primaries] if (existing?.bp === 'cardio') return ['cardiovascular system'] 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 } if (!eq) { toast(t('Pick equipment')); 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) // Stored in the map's order, not the order the chips were tapped in — the tags on the exercise // used to shuffle with every edit. const prim = bp === 'cardio' ? ['cardiovascular system'] : inMuscleOrder(primaries) const sm = inMuscleOrder(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; c.eq = eq } }) 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: true }) }) } close() toast(existing ? t('Saved') : t('“{0}” created', name)) onDone && onDone(EXIDX[id]) } return <>

{existing ? t('Edit custom exercise') : t('Create your own exercise')}

{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}
setN(e.target.value)} />
{BODYPARTS.map(b => )}
{ALL_EQUIPMENT.map(k => ())}
{bp && <> {bp !== 'cardio' && ({ value: m, label: t(MUSCLE_NAME[m]) }))} onToggle={togglePrimary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} /> } !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' &&
{t('Cardio exercises log time + speed instead of weight × reps.')}
}